Compare commits

...

37 Commits

Author SHA1 Message Date
Carlos-Mesquita
3c1c4489f8 Updated user had only demographicInformation and was causing the diagnostic view to not show up after submitting the info 2024-10-01 17:11:04 +01:00
Carlos-Mesquita
044ec8d966 Added back the demographic view 2024-10-01 15:34:56 +01:00
Carlos Mesquita
07c9074d15 More bugs, some updates where not using set 2024-09-23 01:09:34 +01:00
Carlos Mesquita
71bac76c3a More mongodb migration bugs, remove _id from find, and a stat endpoint firebase leftover bug 2024-09-23 00:04:06 +01:00
carlos.mesquita
fb293dc98c Merged main into bugfix/mongo-migration-bugs 2024-09-22 22:47:23 +00:00
Tiago Ribeiro
3ce97b4dcd Removed sorting in exchange for filtering 2024-09-11 16:33:05 +01:00
Tiago Ribeiro
7bfd000213 Solved a problem where it was only getting the first 25 students 2024-09-11 11:29:48 +01:00
Tiago Ribeiro
2a10933206 Solved some problems with the excel of master statistical 2024-09-10 12:00:14 +01:00
Tiago Ribeiro
33a46c227b Solved a bug for the master statistical 2024-09-10 10:55:02 +01:00
Tiago Ribeiro
5153c3d5f1 Merge branch 'main' into develop 2024-09-09 17:52:04 +01:00
Tiago Ribeiro
85c8f622ee Added Student ID to the Master Statistical 2024-09-09 14:43:05 +01:00
Tiago Ribeiro
b9c097d42c Had a bug in pagination 2024-09-09 09:07:30 +01:00
Tiago Ribeiro
192132559b Solved a problem with the download of the excel 2024-09-09 08:19:32 +01:00
Tiago Ribeiro
6d1e8a9788 Had some errors on updating groups 2024-09-09 00:06:51 +01:00
Tiago Ribeiro
1c61d50a5c Improved some of the querying for the assignments 2024-09-09 00:02:34 +01:00
Tiago Ribeiro
9f0ba418e5 Added filtering and pagination for the assignment creator 2024-09-08 23:24:27 +01:00
Tiago Ribeiro
6fd2e64e04 Merge branch 'main' of bitbucket.org:ecropdev/ielts-ui 2024-09-08 23:09:25 +01:00
carlos.mesquita
2c01e6b460 Merged in feature/training-content (pull request #101)
Feature/training content

Approved-by: Tiago Ribeiro
2024-09-08 22:08:32 +00:00
Tiago Ribeiro
6e0c4d4361 Added search per exam 2024-09-08 23:07:47 +01:00
Tiago Ribeiro
745eef981f Added some more pagination 2024-09-08 23:02:48 +01:00
carlos.mesquita
7a33f42bcd Merged main into feature/training-content 2024-09-08 21:49:22 +00:00
Tiago Ribeiro
eab6ab03b7 Not shown when not completed 2024-09-08 22:46:09 +01:00
Tiago Ribeiro
fbc7abdabb Solved a bug 2024-09-08 22:35:14 +01:00
Tiago Ribeiro
392eac2ef9 Merge branch 'main' into develop 2024-09-08 19:57:57 +01:00
Tiago Ribeiro
b7349b5df8 Tried to solve some more issues with counts 2024-09-08 19:56:44 +01:00
Tiago Ribeiro
298901a642 Updated the UserList to show the corporates 2024-09-08 19:50:59 +01:00
Tiago Ribeiro
88eafafe12 Stopped sessions from being cached 2024-09-08 19:36:04 +01:00
Tiago Ribeiro
31a01a3157 Allow admins create other admins 2024-09-08 19:27:12 +01:00
Tiago Ribeiro
a5b3a7e94d Solved a problem with the _id 2024-09-08 19:25:14 +01:00
Tiago Ribeiro
49e8237e99 A bit of error handling I guess 2024-09-08 18:54:44 +01:00
Tiago Ribeiro
d5769c2cb9 Updated more of the page 2024-09-08 18:39:52 +01:00
Tiago Ribeiro
e49a325074 Had a small error on the groups 2024-09-08 18:00:47 +01:00
Tiago Ribeiro
e6528392a2 Changed the totals of the admin pretty much 2024-09-08 16:06:54 +01:00
Joao Ramos
a073ca1cce Temporarily disabled Play Again button 2024-09-08 13:56:08 +01:00
João Ramos
7e30ca5750 Merged in bug-fixing-8-sep-24_2 (pull request #100)
Bug fixing 8 sep 24 2

Approved-by: Tiago Ribeiro
2024-09-08 09:22:05 +00:00
Joao Ramos
2e065eddcb Added an workaround for the broken email system 2024-09-08 10:19:49 +01:00
Joao Ramos
4e91b2f1fb ENCOA-202: Fixed issue updating user 2024-09-08 10:08:24 +01:00
33 changed files with 1102 additions and 1066 deletions

View File

@@ -17,7 +17,7 @@ import moment from "moment";
interface Props { interface Props {
user: User; user: User;
mutateUser: KeyedMutator<User>; mutateUser: (user: User) => void;
} }
export default function DemographicInformationInput({user, mutateUser}: Props) { export default function DemographicInformationInput({user, mutateUser}: Props) {

View File

@@ -1,51 +1,77 @@
import {Column, flexRender, getCoreRowModel, getSortedRowModel, useReactTable} from "@tanstack/react-table"; import {Column, flexRender, getCoreRowModel, getSortedRowModel, useReactTable} from "@tanstack/react-table";
import {useMemo, useState} from "react";
import Button from "./Low/Button";
const SIZE = 25;
export default function List<T>({data, columns}: {data: T[]; columns: any[]}) { export default function List<T>({data, columns}: {data: T[]; columns: any[]}) {
const [page, setPage] = useState(0);
const items = useMemo(() => data.slice(page * SIZE, (page + 1) * SIZE > data.length ? data.length : (page + 1) * SIZE), [data, page]);
const table = useReactTable({ const table = useReactTable({
data, data: items,
columns: columns, columns: columns,
getCoreRowModel: getCoreRowModel(), getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(), getSortedRowModel: getSortedRowModel(),
}); });
return ( return (
<table className="rounded-xl bg-mti-purple-ultralight/40 w-full"> <div className="w-full h-full flex flex-col gap-2">
<thead> <div className="w-full flex gap-2 justify-between">
{table.getHeaderGroups().map((headerGroup) => ( <Button className="w-full max-w-[200px]" disabled={page === 0} onClick={() => setPage((prev) => prev - 1)}>
<tr key={headerGroup.id}> Previous Page
{headerGroup.headers.map((header) => ( </Button>
<th key={header.id} colSpan={header.colSpan}> <div className="flex items-center gap-4 w-fit">
{header.isPlaceholder ? null : ( <span className="opacity-80">
<> {page * SIZE + 1} - {(page + 1) * SIZE > data.length ? data.length : (page + 1) * SIZE} / {data.length}
<div </span>
{...{ <Button className="w-[200px]" disabled={(page + 1) * SIZE >= data.length} onClick={() => setPage((prev) => prev + 1)}>
className: header.column.getCanSort() ? "cursor-pointer select-none py-4 text-left first:pl-4" : "", Next Page
onClick: header.column.getToggleSortingHandler(), </Button>
}}> </div>
{flexRender(header.column.columnDef.header, header.getContext())} </div>
{{
asc: " 🔼", <table className="rounded-xl bg-mti-purple-ultralight/40 w-full">
desc: " 🔽", <thead>
}[header.column.getIsSorted() as string] ?? null} {table.getHeaderGroups().map((headerGroup) => (
</div> <tr key={headerGroup.id}>
</> {headerGroup.headers.map((header) => (
)} <th key={header.id} colSpan={header.colSpan}>
</th> {header.isPlaceholder ? null : (
))} <>
</tr> <div
))} {...{
</thead> className: header.column.getCanSort()
<tbody className="px-2"> ? "cursor-pointer select-none py-4 text-left first:pl-4"
{table.getRowModel().rows.map((row) => ( : "",
<tr className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2" key={row.id}> onClick: header.column.getToggleSortingHandler(),
{row.getVisibleCells().map((cell) => ( }}>
<td className="px-4 py-2" key={cell.id}> {flexRender(header.column.columnDef.header, header.getContext())}
{flexRender(cell.column.columnDef.cell, cell.getContext())} {{
</td> asc: " 🔼",
))} desc: " 🔽",
</tr> }[header.column.getIsSorted() as string] ?? null}
))} </div>
</tbody> </>
</table> )}
</th>
))}
</tr>
))}
</thead>
<tbody className="px-2">
{table.getRowModel().rows.map((row) => (
<tr className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2" key={row.id}>
{row.getVisibleCells().map((cell) => (
<td className="px-4 py-2" key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
); );
} }

View File

@@ -31,12 +31,40 @@ interface Props {
user: User; user: User;
} }
const studentHash = {
type: "student",
size: 25,
orderBy: "registrationDate",
};
const teacherHash = {
type: "teacher",
size: 25,
orderBy: "registrationDate",
};
const corporateHash = {
type: "corporate",
size: 25,
orderBy: "registrationDate",
};
const agentsHash = {
type: "agent",
size: 25,
orderBy: "registrationDate",
};
export default function AdminDashboard({user}: Props) { export default function AdminDashboard({user}: Props) {
const [page, setPage] = useState(""); const [page, setPage] = useState("");
const [selectedUser, setSelectedUser] = useState<User>(); const [selectedUser, setSelectedUser] = useState<User>();
const [showModal, setShowModal] = useState(false); const [showModal, setShowModal] = useState(false);
const {users, reload, isLoading} = useUsers(); const {users: students, total: totalStudents, reload: reloadStudents, isLoading: isStudentsLoading} = useUsers(studentHash);
const {users: teachers, total: totalTeachers, reload: reloadTeachers, isLoading: isTeachersLoading} = useUsers(teacherHash);
const {users: corporates, total: totalCorporate, reload: reloadCorporates, isLoading: isCorporatesLoading} = useUsers(corporateHash);
const {users: agents, total: totalAgents, reload: reloadAgents, isLoading: isAgentsLoading} = useUsers(agentsHash);
const {groups} = useGroups({}); const {groups} = useGroups({});
const {pending, done} = usePaymentStatusUsers(); const {pending, done} = usePaymentStatusUsers();
@@ -47,9 +75,6 @@ export default function AdminDashboard({user}: Props) {
setShowModal(!!selectedUser && router.asPath === "/#"); setShowModal(!!selectedUser && router.asPath === "/#");
}, [selectedUser, router.asPath]); }, [selectedUser, router.asPath]);
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(reload, [page]);
const inactiveCountryManagerFilter = (x: User) => x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate); const inactiveCountryManagerFilter = (x: User) => x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate);
const UserDisplay = (displayUser: User) => ( const UserDisplay = (displayUser: User) => (
@@ -279,50 +304,50 @@ export default function AdminDashboard({user}: Props) {
<section className="w-full grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 place-items-center items-center justify-between"> <section className="w-full grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 place-items-center items-center justify-between">
<IconCard <IconCard
Icon={BsPersonFill} Icon={BsPersonFill}
isLoading={isLoading} isLoading={isStudentsLoading}
label="Students" label="Students"
value={users.filter((x) => x.type === "student").length} value={totalStudents}
onClick={() => router.push("/#students")} onClick={() => router.push("/#students")}
color="purple" color="purple"
/> />
<IconCard <IconCard
Icon={BsPencilSquare} Icon={BsPencilSquare}
isLoading={isLoading} isLoading={isTeachersLoading}
label="Teachers" label="Teachers"
value={users.filter((x) => x.type === "teacher").length} value={totalTeachers}
onClick={() => router.push("/#teachers")} onClick={() => router.push("/#teachers")}
color="purple" color="purple"
/> />
<IconCard <IconCard
Icon={BsBank} Icon={BsBank}
isLoading={isLoading} isLoading={isCorporatesLoading}
label="Corporate" label="Corporate"
value={users.filter((x) => x.type === "corporate").length} value={totalCorporate}
onClick={() => router.push("/#corporate")} onClick={() => router.push("/#corporate")}
color="purple" color="purple"
/> />
<IconCard <IconCard
Icon={BsBriefcaseFill} Icon={BsBriefcaseFill}
isLoading={isLoading} isLoading={isAgentsLoading}
label="Country Managers" label="Country Managers"
value={users.filter((x) => x.type === "agent").length} value={totalAgents}
onClick={() => router.push("/#agents")} onClick={() => router.push("/#agents")}
color="purple" color="purple"
/> />
<IconCard <IconCard
Icon={BsGlobeCentralSouthAsia} Icon={BsGlobeCentralSouthAsia}
isLoading={isLoading} isLoading={isAgentsLoading}
label="Countries" label="Countries"
value={[...new Set(users.filter((x) => x.demographicInformation).map((x) => x.demographicInformation?.country))].length} value={[...new Set(agents.filter((x) => x.demographicInformation).map((x) => x.demographicInformation?.country))].length}
color="purple" color="purple"
/> />
<IconCard <IconCard
onClick={() => router.push("/#inactiveStudents")} onClick={() => router.push("/#inactiveStudents")}
Icon={BsPersonFill} Icon={BsPersonFill}
isLoading={isLoading} isLoading={isStudentsLoading}
label="Inactive Students" label="Inactive Students"
value={ value={
users.filter((x) => x.type === "student" && (x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate))) students.filter((x) => x.type === "student" && (x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate)))
.length .length
} }
color="rose" color="rose"
@@ -330,26 +355,26 @@ export default function AdminDashboard({user}: Props) {
<IconCard <IconCard
onClick={() => router.push("/#inactiveCountryManagers")} onClick={() => router.push("/#inactiveCountryManagers")}
Icon={BsBriefcaseFill} Icon={BsBriefcaseFill}
isLoading={isLoading} isLoading={isAgentsLoading}
label="Inactive Country Managers" label="Inactive Country Managers"
value={users.filter(inactiveCountryManagerFilter).length} value={agents.filter(inactiveCountryManagerFilter).length}
color="rose" color="rose"
/> />
<IconCard <IconCard
onClick={() => router.push("/#inactiveCorporate")} onClick={() => router.push("/#inactiveCorporate")}
Icon={BsBank} Icon={BsBank}
isLoading={isLoading} isLoading={isCorporatesLoading}
label="Inactive Corporate" label="Inactive Corporate"
value={ value={
users.filter((x) => x.type === "corporate" && (x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate))) corporates.filter(
.length (x) => x.type === "corporate" && (x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate)),
).length
} }
color="rose" color="rose"
/> />
<IconCard <IconCard
onClick={() => router.push("/#paymentdone")} onClick={() => router.push("/#paymentdone")}
Icon={BsCurrencyDollar} Icon={BsCurrencyDollar}
isLoading={isLoading}
label="Payment Done" label="Payment Done"
value={done.length} value={done.length}
color="purple" color="purple"
@@ -357,7 +382,6 @@ export default function AdminDashboard({user}: Props) {
<IconCard <IconCard
onClick={() => router.push("/#paymentpending")} onClick={() => router.push("/#paymentpending")}
Icon={BsCurrencyDollar} Icon={BsCurrencyDollar}
isLoading={isLoading}
label="Pending Payment" label="Pending Payment"
value={pending.length} value={pending.length}
color="rose" color="rose"
@@ -365,14 +389,13 @@ export default function AdminDashboard({user}: Props) {
<IconCard <IconCard
onClick={() => router.push("https://cms.encoach.com/admin")} onClick={() => router.push("https://cms.encoach.com/admin")}
Icon={BsLayoutSidebar} Icon={BsLayoutSidebar}
isLoading={isLoading}
label="Content Management System (CMS)" label="Content Management System (CMS)"
color="green" color="green"
/> />
<IconCard <IconCard
onClick={() => router.push("/#corporatestudentslevels")} onClick={() => router.push("/#corporatestudentslevels")}
Icon={BsPersonFill} Icon={BsPersonFill}
isLoading={isLoading} isLoading={isStudentsLoading}
label="Corporate Students Levels" label="Corporate Students Levels"
color="purple" color="purple"
/> />
@@ -382,8 +405,7 @@ export default function AdminDashboard({user}: Props) {
<div className="bg-white shadow flex flex-col rounded-xl w-full"> <div className="bg-white shadow flex flex-col rounded-xl w-full">
<span className="p-4">Latest students</span> <span className="p-4">Latest 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">
{users {students
.filter((x) => x.type === "student")
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate")) .sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
.map((x) => ( .map((x) => (
<UserDisplay key={x.id} {...x} /> <UserDisplay key={x.id} {...x} />
@@ -393,8 +415,7 @@ export default function AdminDashboard({user}: Props) {
<div className="bg-white shadow flex flex-col rounded-xl w-full"> <div className="bg-white shadow flex flex-col rounded-xl w-full">
<span className="p-4">Latest teachers</span> <span className="p-4">Latest teachers</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">
{users {teachers
.filter((x) => x.type === "teacher")
.sort((a, b) => { .sort((a, b) => {
return dateSorter(a, b, "desc", "registrationDate"); return dateSorter(a, b, "desc", "registrationDate");
}) })
@@ -406,8 +427,7 @@ export default function AdminDashboard({user}: Props) {
<div className="bg-white shadow flex flex-col rounded-xl w-full"> <div className="bg-white shadow flex flex-col rounded-xl w-full">
<span className="p-4">Latest corporate</span> <span className="p-4">Latest corporate</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">
{users {corporates
.filter((x) => x.type === "corporate")
.sort((a, b) => { .sort((a, b) => {
return dateSorter(a, b, "desc", "registrationDate"); return dateSorter(a, b, "desc", "registrationDate");
}) })
@@ -419,8 +439,8 @@ export default function AdminDashboard({user}: Props) {
<div className="bg-white shadow flex flex-col rounded-xl w-full"> <div className="bg-white shadow flex flex-col rounded-xl w-full">
<span className="p-4">Unpaid Corporate</span> <span className="p-4">Unpaid Corporate</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">
{users {corporates
.filter((x) => x.type === "corporate" && x.status === "paymentDue") .filter((x) => x.status === "paymentDue")
.map((x) => ( .map((x) => (
<UserDisplay key={x.id} {...x} /> <UserDisplay key={x.id} {...x} />
))} ))}
@@ -429,10 +449,9 @@ export default function AdminDashboard({user}: Props) {
<div className="bg-white shadow flex flex-col rounded-xl w-full"> <div className="bg-white shadow flex flex-col rounded-xl w-full">
<span className="p-4">Students expiring in 1 month</span> <span className="p-4">Students expiring in 1 month</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">
{users {students
.filter( .filter(
(x) => (x) =>
x.type === "student" &&
x.subscriptionExpirationDate && x.subscriptionExpirationDate &&
moment().isAfter(moment(x.subscriptionExpirationDate).subtract(30, "days")) && moment().isAfter(moment(x.subscriptionExpirationDate).subtract(30, "days")) &&
moment().isBefore(moment(x.subscriptionExpirationDate)), moment().isBefore(moment(x.subscriptionExpirationDate)),
@@ -445,10 +464,9 @@ export default function AdminDashboard({user}: Props) {
<div className="bg-white shadow flex flex-col rounded-xl w-full"> <div className="bg-white shadow flex flex-col rounded-xl w-full">
<span className="p-4">Teachers expiring in 1 month</span> <span className="p-4">Teachers expiring in 1 month</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">
{users {teachers
.filter( .filter(
(x) => (x) =>
x.type === "teacher" &&
x.subscriptionExpirationDate && x.subscriptionExpirationDate &&
moment().isAfter(moment(x.subscriptionExpirationDate).subtract(30, "days")) && moment().isAfter(moment(x.subscriptionExpirationDate).subtract(30, "days")) &&
moment().isBefore(moment(x.subscriptionExpirationDate)), moment().isBefore(moment(x.subscriptionExpirationDate)),
@@ -461,10 +479,9 @@ export default function AdminDashboard({user}: Props) {
<div className="bg-white shadow flex flex-col rounded-xl w-full"> <div className="bg-white shadow flex flex-col rounded-xl w-full">
<span className="p-4">Country Manager expiring in 1 month</span> <span className="p-4">Country Manager expiring in 1 month</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">
{users {agents
.filter( .filter(
(x) => (x) =>
x.type === "agent" &&
x.subscriptionExpirationDate && x.subscriptionExpirationDate &&
moment().isAfter(moment(x.subscriptionExpirationDate).subtract(30, "days")) && moment().isAfter(moment(x.subscriptionExpirationDate).subtract(30, "days")) &&
moment().isBefore(moment(x.subscriptionExpirationDate)), moment().isBefore(moment(x.subscriptionExpirationDate)),
@@ -477,10 +494,9 @@ export default function AdminDashboard({user}: Props) {
<div className="bg-white shadow flex flex-col rounded-xl w-full"> <div className="bg-white shadow flex flex-col rounded-xl w-full">
<span className="p-4">Corporate expiring in 1 month</span> <span className="p-4">Corporate expiring in 1 month</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">
{users {corporates
.filter( .filter(
(x) => (x) =>
x.type === "corporate" &&
x.subscriptionExpirationDate && x.subscriptionExpirationDate &&
moment().isAfter(moment(x.subscriptionExpirationDate).subtract(30, "days")) && moment().isAfter(moment(x.subscriptionExpirationDate).subtract(30, "days")) &&
moment().isBefore(moment(x.subscriptionExpirationDate)), moment().isBefore(moment(x.subscriptionExpirationDate)),
@@ -493,10 +509,8 @@ export default function AdminDashboard({user}: Props) {
<div className="bg-white shadow flex flex-col rounded-xl w-full"> <div className="bg-white shadow flex flex-col rounded-xl w-full">
<span className="p-4">Expired Students</span> <span className="p-4">Expired 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">
{users {students
.filter( .filter((x) => x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)))
(x) => x.type === "student" && x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)),
)
.map((x) => ( .map((x) => (
<UserDisplay key={x.id} {...x} /> <UserDisplay key={x.id} {...x} />
))} ))}
@@ -505,10 +519,8 @@ export default function AdminDashboard({user}: Props) {
<div className="bg-white shadow flex flex-col rounded-xl w-full"> <div className="bg-white shadow flex flex-col rounded-xl w-full">
<span className="p-4">Expired Teachers</span> <span className="p-4">Expired Teachers</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">
{users {teachers
.filter( .filter((x) => x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)))
(x) => x.type === "teacher" && x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)),
)
.map((x) => ( .map((x) => (
<UserDisplay key={x.id} {...x} /> <UserDisplay key={x.id} {...x} />
))} ))}
@@ -517,10 +529,8 @@ export default function AdminDashboard({user}: Props) {
<div className="bg-white shadow flex flex-col rounded-xl w-full"> <div className="bg-white shadow flex flex-col rounded-xl w-full">
<span className="p-4">Expired Country Manager</span> <span className="p-4">Expired Country Manager</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">
{users {agents
.filter( .filter((x) => x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)))
(x) => x.type === "agent" && x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)),
)
.map((x) => ( .map((x) => (
<UserDisplay key={x.id} {...x} /> <UserDisplay key={x.id} {...x} />
))} ))}
@@ -529,11 +539,8 @@ export default function AdminDashboard({user}: Props) {
<div className="bg-white shadow flex flex-col rounded-xl w-full"> <div className="bg-white shadow flex flex-col rounded-xl w-full">
<span className="p-4">Expired Corporate</span> <span className="p-4">Expired Corporate</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">
{users {corporates
.filter( .filter((x) => x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)))
(x) =>
x.type === "corporate" && x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)),
)
.map((x) => ( .map((x) => (
<UserDisplay key={x.id} {...x} /> <UserDisplay key={x.id} {...x} />
))} ))}
@@ -553,7 +560,10 @@ export default function AdminDashboard({user}: Props) {
loggedInUser={user} loggedInUser={user}
onClose={(shouldReload) => { onClose={(shouldReload) => {
setSelectedUser(undefined); setSelectedUser(undefined);
if (shouldReload) reload(); if (shouldReload && selectedUser!.type === "student") reloadStudents();
if (shouldReload && selectedUser!.type === "teacher") reloadTeachers();
if (shouldReload && selectedUser!.type === "corporate") reloadCorporates();
if (shouldReload && selectedUser!.type === "agent") reloadAgents();
}} }}
onViewStudents={ onViewStudents={
selectedUser.type === "corporate" || selectedUser.type === "teacher" selectedUser.type === "corporate" || selectedUser.type === "teacher"

View File

@@ -21,6 +21,7 @@ import Checkbox from "@/components/Low/Checkbox";
import {InstructorGender, Variant} from "@/interfaces/exam"; import {InstructorGender, Variant} from "@/interfaces/exam";
import Select from "@/components/Low/Select"; import Select from "@/components/Low/Select";
import useExams from "@/hooks/useExams"; import useExams from "@/hooks/useExams";
import {useListSearch} from "@/hooks/useListSearch";
interface Props { interface Props {
isCreating: boolean; isCreating: boolean;
@@ -31,7 +32,12 @@ interface Props {
cancelCreation: () => void; cancelCreation: () => void;
} }
const SIZE = 12;
export default function AssignmentCreator({isCreating, assignment, user, groups, users, cancelCreation}: Props) { export default function AssignmentCreator({isCreating, assignment, user, groups, users, cancelCreation}: Props) {
const [studentsPage, setStudentsPage] = useState(0);
const [teachersPage, setTeachersPage] = useState(0);
const [selectedModules, setSelectedModules] = useState<Module[]>(assignment?.exams.map((e) => e.module) || []); const [selectedModules, setSelectedModules] = useState<Module[]>(assignment?.exams.map((e) => e.module) || []);
const [assignees, setAssignees] = useState<string[]>(assignment?.assignees || []); const [assignees, setAssignees] = useState<string[]>(assignment?.assignees || []);
const [teachers, setTeachers] = useState<string[]>(!!assignment ? assignment.teachers || [] : [...(user.type === "teacher" ? [user.id] : [])]); const [teachers, setTeachers] = useState<string[]>(!!assignment ? assignment.teachers || [] : [...(user.type === "teacher" ? [user.id] : [])]);
@@ -69,6 +75,29 @@ export default function AssignmentCreator({isCreating, assignment, user, groups,
const userStudents = useMemo(() => users.filter((x) => x.type === "student"), [users]); const userStudents = useMemo(() => users.filter((x) => x.type === "student"), [users]);
const userTeachers = useMemo(() => users.filter((x) => x.type === "teacher"), [users]); const userTeachers = useMemo(() => users.filter((x) => x.type === "teacher"), [users]);
const {rows: filteredStudentsRows, renderSearch: renderStudentSearch, text: studentText} = useListSearch([["name"], ["email"]], userStudents);
const {rows: filteredTeachersRows, renderSearch: renderTeacherSearch, text: teacherText} = useListSearch([["name"], ["email"]], userTeachers);
useEffect(() => setStudentsPage(0), [studentText]);
const studentRows = useMemo(
() =>
filteredStudentsRows.slice(
studentsPage * SIZE,
(studentsPage + 1) * SIZE > filteredStudentsRows.length ? filteredStudentsRows.length : (studentsPage + 1) * SIZE,
),
[filteredStudentsRows, studentsPage],
);
useEffect(() => setTeachersPage(0), [teacherText]);
const teacherRows = useMemo(
() =>
filteredTeachersRows.slice(
teachersPage * SIZE,
(teachersPage + 1) * SIZE > filteredTeachersRows.length ? filteredTeachersRows.length : (teachersPage + 1) * SIZE,
),
[filteredTeachersRows, teachersPage],
);
useEffect(() => { useEffect(() => {
setExamIDs((prev) => prev.filter((x) => selectedModules.includes(x.module))); setExamIDs((prev) => prev.filter((x) => selectedModules.includes(x.module)));
}, [selectedModules]); }, [selectedModules]);
@@ -347,9 +376,9 @@ export default function AssignmentCreator({isCreating, assignment, user, groups,
</div> </div>
)} )}
<section className="w-full flex flex-col gap-3"> <section className="w-full flex flex-col gap-4">
<span className="font-semibold">Assignees ({assignees.length} selected)</span> <span className="font-semibold">Assignees ({assignees.length} selected)</span>
<div className="flex gap-4 overflow-x-scroll scrollbar-hide"> <div className="grid grid-cols-5 gap-4">
{groups.map((g) => ( {groups.map((g) => (
<button <button
key={g.id} key={g.id}
@@ -371,8 +400,11 @@ export default function AssignmentCreator({isCreating, assignment, user, groups,
</button> </button>
))} ))}
</div> </div>
{renderStudentSearch()}
<div className="flex flex-wrap -md:justify-center gap-4"> <div className="flex flex-wrap -md:justify-center gap-4">
{userStudents.map((user) => ( {studentRows.map((user) => (
<div <div
onClick={() => toggleAssignee(user)} onClick={() => toggleAssignee(user)}
className={clsx( className={clsx(
@@ -402,12 +434,32 @@ export default function AssignmentCreator({isCreating, assignment, user, groups,
</div> </div>
))} ))}
</div> </div>
<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={studentsPage === 0} onClick={() => setStudentsPage((prev) => prev - 1)}>
Previous Page
</Button>
</div>
<div className="flex items-center gap-4 w-fit">
<span className="opacity-80">
{studentsPage * SIZE + 1} -{" "}
{(studentsPage + 1) * SIZE > filteredStudentsRows.length ? filteredStudentsRows.length : (studentsPage + 1) * SIZE} /{" "}
{filteredStudentsRows.length}
</span>
<Button
className="w-[200px]"
disabled={(studentsPage + 1) * SIZE >= filteredStudentsRows.length}
onClick={() => setStudentsPage((prev) => prev + 1)}>
Next Page
</Button>
</div>
</div>
</section> </section>
{user.type !== "teacher" && ( {user.type !== "teacher" && (
<section className="w-full flex flex-col gap-3"> <section className="w-full flex flex-col gap-3">
<span className="font-semibold">Teachers ({teachers.length} selected)</span> <span className="font-semibold">Teachers ({teachers.length} selected)</span>
<div className="flex gap-4 overflow-x-scroll scrollbar-hide"> <div className="grid grid-cols-5 gap-4">
{groups.map((g) => ( {groups.map((g) => (
<button <button
key={g.id} key={g.id}
@@ -429,8 +481,11 @@ export default function AssignmentCreator({isCreating, assignment, user, groups,
</button> </button>
))} ))}
</div> </div>
{renderTeacherSearch()}
<div className="flex flex-wrap -md:justify-center gap-4"> <div className="flex flex-wrap -md:justify-center gap-4">
{userTeachers.map((user) => ( {teacherRows.map((user) => (
<div <div
onClick={() => toggleTeacher(user)} onClick={() => toggleTeacher(user)}
className={clsx( className={clsx(
@@ -453,6 +508,29 @@ export default function AssignmentCreator({isCreating, assignment, user, groups,
</div> </div>
))} ))}
</div> </div>
<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={teachersPage === 0} onClick={() => setTeachersPage((prev) => prev - 1)}>
Previous Page
</Button>
</div>
<div className="flex items-center gap-4 w-fit">
<span className="opacity-80">
{teachersPage * SIZE + 1} -{" "}
{(teachersPage + 1) * SIZE > filteredTeachersRows.length
? filteredTeachersRows.length
: (teachersPage + 1) * SIZE}{" "}
/ {filteredTeachersRows.length}
</span>
<Button
className="w-[200px]"
disabled={(teachersPage + 1) * SIZE >= filteredTeachersRows.length}
onClick={() => setTeachersPage((prev) => prev + 1)}>
Next Page
</Button>
</div>
</div>
</section> </section>
)} )}

View File

@@ -1,546 +1,405 @@
/* eslint-disable @next/next/no-img-element */ /* eslint-disable @next/next/no-img-element */
import Modal from "@/components/Modal"; import Modal from "@/components/Modal";
import useFilterRecordsByUser from "@/hooks/useFilterRecordsByUser"; import useFilterRecordsByUser from "@/hooks/useFilterRecordsByUser";
import useUsers, { import useUsers, {userHashStudent, userHashTeacher, userHashCorporate} from "@/hooks/useUsers";
userHashStudent, import {CorporateUser, Group, MasterCorporateUser, Stat, User} from "@/interfaces/user";
userHashTeacher,
userHashCorporate,
} from "@/hooks/useUsers";
import {
CorporateUser,
Group,
MasterCorporateUser,
Stat,
User,
} from "@/interfaces/user";
import UserList from "@/pages/(admin)/Lists/UserList"; import UserList from "@/pages/(admin)/Lists/UserList";
import { dateSorter } from "@/utils"; import {dateSorter} from "@/utils";
import moment from "moment"; import moment from "moment";
import { useEffect, useMemo, useState } from "react"; import {useEffect, useMemo, useState} from "react";
import { import {
BsArrowLeft, BsArrowLeft,
BsClipboard2Data, BsClipboard2Data,
BsClipboard2DataFill, BsClipboard2DataFill,
BsClock, BsClock,
BsGlobeCentralSouthAsia, BsGlobeCentralSouthAsia,
BsPaperclip, BsPaperclip,
BsPerson, BsPerson,
BsPersonAdd, BsPersonAdd,
BsPersonFill, BsPersonFill,
BsPersonFillGear, BsPersonFillGear,
BsPersonGear, BsPersonGear,
BsPencilSquare, BsPencilSquare,
BsPersonBadge, BsPersonBadge,
BsPersonCheck, BsPersonCheck,
BsPeople, BsPeople,
BsArrowRepeat, BsArrowRepeat,
BsPlus, BsPlus,
BsEnvelopePaper, BsEnvelopePaper,
BsDatabase, BsDatabase,
} from "react-icons/bs"; } from "react-icons/bs";
import UserCard from "@/components/UserCard"; import UserCard from "@/components/UserCard";
import useGroups from "@/hooks/useGroups"; import useGroups from "@/hooks/useGroups";
import { import {averageLevelCalculator, calculateAverageLevel, calculateBandScore} from "@/utils/score";
averageLevelCalculator, import {MODULE_ARRAY} from "@/utils/moduleUtils";
calculateAverageLevel, import {Module} from "@/interfaces";
calculateBandScore, import {groupByExam} from "@/utils/stats";
} from "@/utils/score";
import { MODULE_ARRAY } from "@/utils/moduleUtils";
import { Module } from "@/interfaces";
import { groupByExam } from "@/utils/stats";
import IconCard from "../IconCard"; import IconCard from "../IconCard";
import GroupList from "@/pages/(admin)/Lists/GroupList"; import GroupList from "@/pages/(admin)/Lists/GroupList";
import useFilterStore from "@/stores/listFilterStore"; import useFilterStore from "@/stores/listFilterStore";
import { useRouter } from "next/router"; import {useRouter} from "next/router";
import useCodes from "@/hooks/useCodes"; import useCodes from "@/hooks/useCodes";
import { getUserCorporate } from "@/utils/groups"; import {getUserCorporate} from "@/utils/groups";
import useAssignments from "@/hooks/useAssignments"; import useAssignments from "@/hooks/useAssignments";
import { Assignment } from "@/interfaces/results"; import {Assignment} from "@/interfaces/results";
import AssignmentView from "../AssignmentView"; import AssignmentView from "../AssignmentView";
import AssignmentCreator from "../AssignmentCreator"; import AssignmentCreator from "../AssignmentCreator";
import clsx from "clsx"; import clsx from "clsx";
import AssignmentCard from "../AssignmentCard"; import AssignmentCard from "../AssignmentCard";
import { createColumnHelper } from "@tanstack/react-table"; import {createColumnHelper} from "@tanstack/react-table";
import Checkbox from "@/components/Low/Checkbox"; import Checkbox from "@/components/Low/Checkbox";
import List from "@/components/List"; import List from "@/components/List";
import { getUserCompanyName } from "@/resources/user"; import {getUserCompanyName} from "@/resources/user";
import { import {futureAssignmentFilter, pastAssignmentFilter, archivedAssignmentFilter, activeAssignmentFilter} from "@/utils/assignments";
futureAssignmentFilter,
pastAssignmentFilter,
archivedAssignmentFilter,
activeAssignmentFilter,
} from "@/utils/assignments";
import useUserBalance from "@/hooks/useUserBalance"; import useUserBalance from "@/hooks/useUserBalance";
import AssignmentsPage from "../views/AssignmentsPage"; import AssignmentsPage from "../views/AssignmentsPage";
import StudentPerformancePage from "./StudentPerformancePage"; import StudentPerformancePage from "./StudentPerformancePage";
import MasterStatistical from "../MasterCorporate/MasterStatistical"; import MasterStatistical from "../MasterCorporate/MasterStatistical";
import MasterStatisticalPage from "./MasterStatisticalPage";
interface Props { interface Props {
user: CorporateUser; user: CorporateUser;
linkedCorporate?: CorporateUser | MasterCorporateUser; linkedCorporate?: CorporateUser | MasterCorporateUser;
} }
const studentHash = { const studentHash = {
type: "student", type: "student",
orderBy: "registrationDate", orderBy: "registrationDate",
size: 25, size: 25,
}; };
const teacherHash = { const teacherHash = {
type: "teacher", type: "teacher",
orderBy: "registrationDate", orderBy: "registrationDate",
size: 25, size: 25,
}; };
export default function CorporateDashboard({ user, linkedCorporate }: Props) { export default function CorporateDashboard({user, linkedCorporate}: Props) {
const [selectedUser, setSelectedUser] = useState<User>(); const [selectedUser, setSelectedUser] = useState<User>();
const [showModal, setShowModal] = useState(false); const [showModal, setShowModal] = useState(false);
const { data: stats } = useFilterRecordsByUser<Stat[]>(); const {data: stats} = useFilterRecordsByUser<Stat[]>();
const { groups } = useGroups({ admin: user.id }); const {groups} = useGroups({admin: user.id});
const { const {assignments, isLoading: isAssignmentsLoading, reload: reloadAssignments} = useAssignments({corporate: user.id});
assignments, const {balance} = useUserBalance();
isLoading: isAssignmentsLoading,
reload: reloadAssignments,
} = useAssignments({ corporate: user.id });
const { balance } = useUserBalance();
const { const {users: students, total: totalStudents, reload: reloadStudents, isLoading: isStudentsLoading} = useUsers(studentHash);
users: students, const {users: teachers, total: totalTeachers, reload: reloadTeachers, isLoading: isTeachersLoading} = useUsers(teacherHash);
total: totalStudents,
reload: reloadStudents,
isLoading: isStudentsLoading,
} = useUsers(studentHash);
const {
users: teachers,
total: totalTeachers,
reload: reloadTeachers,
isLoading: isTeachersLoading,
} = useUsers(teacherHash);
const appendUserFilters = useFilterStore((state) => state.appendUserFilter); const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
const router = useRouter(); const router = useRouter();
const assignmentsGroups = useMemo( const assignmentsGroups = useMemo(() => groups.filter((x) => x.admin === user.id || x.participants.includes(user.id)), [groups, user.id]);
() =>
groups.filter(
(x) => x.admin === user.id || x.participants.includes(user.id)
),
[groups, user.id]
);
const assignmentsUsers = useMemo( const assignmentsUsers = useMemo(
() => () =>
[...teachers, ...students].filter((x) => [...teachers, ...students].filter((x) =>
!!selectedUser !!selectedUser
? groups ? groups
.filter((g) => g.admin === selectedUser.id) .filter((g) => g.admin === selectedUser.id)
.flatMap((g) => g.participants) .flatMap((g) => g.participants)
.includes(x.id) || false .includes(x.id) || false
: groups.flatMap((g) => g.participants).includes(x.id) : groups.flatMap((g) => g.participants).includes(x.id),
), ),
[groups, teachers, students, selectedUser] [groups, teachers, students, selectedUser],
); );
useEffect(() => { useEffect(() => {
setShowModal(!!selectedUser && router.asPath === "/#"); setShowModal(!!selectedUser && router.asPath === "/#");
}, [selectedUser, router.asPath]); }, [selectedUser, router.asPath]);
const getStatsByStudent = (user: User) => const getStatsByStudent = (user: User) => stats.filter((s) => s.user === user.id);
stats.filter((s) => s.user === user.id);
const UserDisplay = (displayUser: User) => ( const UserDisplay = (displayUser: User) => (
<div <div
onClick={() => setSelectedUser(displayUser)} onClick={() => setSelectedUser(displayUser)}
className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300" className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300">
> <img src={displayUser.profilePicture} alt={displayUser.name} className="rounded-full w-10 h-10" />
<img <div className="flex flex-col gap-1 items-start">
src={displayUser.profilePicture} <span>{displayUser.name}</span>
alt={displayUser.name} <span className="text-sm opacity-75">{displayUser.email}</span>
className="rounded-full w-10 h-10" </div>
/> </div>
<div className="flex flex-col gap-1 items-start"> );
<span>{displayUser.name}</span>
<span className="text-sm opacity-75">{displayUser.email}</span>
</div>
</div>
);
// this workaround will allow us toreuse the master statistical due to master corporate restraints const GroupsList = () => {
// while still being able to use the corporate user const filter = (x: Group) => x.admin === user.id || x.participants.includes(user.id);
const groupedByNameCorporateIds = useMemo(
() => ({
[user.corporateInformation?.companyInformation?.name || user.name]: [
user.id,
],
}),
[user]
);
const teachersAndStudents = useMemo(
() => [...students, ...teachers],
[students, teachers]
);
const MasterStatisticalPage = () => {
return (
<>
<div className="flex flex-col gap-4">
<div
onClick={() => router.push("/")}
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
>
<BsArrowLeft className="text-xl" />
<span>Back</span>
</div>
<h2 className="text-2xl font-semibold">Master Statistical</h2>
</div>
<MasterStatistical
users={teachersAndStudents}
corporateUsers={groupedByNameCorporateIds}
displaySelection={false}
/>
</>
);
};
const GroupsList = () => { return (
const filter = (x: Group) => <>
x.admin === user.id || x.participants.includes(user.id); <div className="flex flex-col gap-4">
<div
onClick={() => router.push("/")}
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
<BsArrowLeft className="text-xl" />
<span>Back</span>
</div>
<h2 className="text-2xl font-semibold">Groups ({groups.filter(filter).length})</h2>
</div>
return ( <GroupList user={user} />
<> </>
<div className="flex flex-col gap-4"> );
<div };
onClick={() => router.push("/")}
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
>
<BsArrowLeft className="text-xl" />
<span>Back</span>
</div>
<h2 className="text-2xl font-semibold">
Groups ({groups.filter(filter).length})
</h2>
</div>
<GroupList user={user} /> const averageLevelCalculator = (studentStats: Stat[]) => {
</> const formattedStats = studentStats
); .map((s) => ({
}; focus: students.find((u) => u.id === s.user)?.focus,
score: s.score,
module: s.module,
}))
.filter((f) => !!f.focus);
const bandScores = formattedStats.map((s) => ({
module: s.module,
level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!),
}));
const averageLevelCalculator = (studentStats: Stat[]) => { const levels: {[key in Module]: number} = {
const formattedStats = studentStats reading: 0,
.map((s) => ({ listening: 0,
focus: students.find((u) => u.id === s.user)?.focus, writing: 0,
score: s.score, speaking: 0,
module: s.module, level: 0,
})) };
.filter((f) => !!f.focus); bandScores.forEach((b) => (levels[b.module] += b.level));
const bandScores = formattedStats.map((s) => ({
module: s.module,
level: calculateBandScore(
s.score.correct,
s.score.total,
s.module,
s.focus!
),
}));
const levels: { [key in Module]: number } = { return calculateAverageLevel(levels);
reading: 0, };
listening: 0,
writing: 0,
speaking: 0,
level: 0,
};
bandScores.forEach((b) => (levels[b.module] += b.level));
return calculateAverageLevel(levels); if (router.asPath === "/#students")
}; return (
<UserList
user={user}
type="student"
renderHeader={(total) => (
<div className="flex flex-col gap-4">
<div
onClick={() => router.push("/")}
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
<BsArrowLeft className="text-xl" />
<span>Back</span>
</div>
<h2 className="text-2xl font-semibold">Students ({total})</h2>
</div>
)}
/>
);
if (router.asPath === "/#students") if (router.asPath === "/#teachers")
return ( return (
<UserList <UserList
user={user} user={user}
type="student" type="teacher"
renderHeader={(total) => ( renderHeader={(total) => (
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<div <div
onClick={() => router.push("/")} onClick={() => router.push("/")}
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300" className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
> <BsArrowLeft className="text-xl" />
<BsArrowLeft className="text-xl" /> <span>Back</span>
<span>Back</span> </div>
</div> <h2 className="text-2xl font-semibold">Teachers ({total})</h2>
<h2 className="text-2xl font-semibold">Students ({total})</h2> </div>
</div> )}
)} />
/> );
);
if (router.asPath === "/#teachers") if (router.asPath === "/#groups") return <GroupsList />;
return ( if (router.asPath === "/#studentsPerformance") return <StudentPerformancePage user={user} />;
<UserList
user={user}
type="teacher"
renderHeader={(total) => (
<div className="flex flex-col gap-4">
<div
onClick={() => router.push("/")}
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
>
<BsArrowLeft className="text-xl" />
<span>Back</span>
</div>
<h2 className="text-2xl font-semibold">Teachers ({total})</h2>
</div>
)}
/>
);
if (router.asPath === "/#groups") return <GroupsList />; if (router.asPath === "/#assignments")
if (router.asPath === "/#studentsPerformance") return (
return <StudentPerformancePage user={user} />; <AssignmentsPage
assignments={assignments}
user={user}
groups={assignmentsGroups}
reloadAssignments={reloadAssignments}
isLoading={isAssignmentsLoading}
onBack={() => router.push("/")}
/>
);
if (router.asPath === "/#assignments") if (router.asPath === "/#statistical") return <MasterStatisticalPage user={user} />;
return (
<AssignmentsPage
assignments={assignments}
user={user}
groups={assignmentsGroups}
reloadAssignments={reloadAssignments}
isLoading={isAssignmentsLoading}
onBack={() => router.push("/")}
/>
);
if (router.asPath === "/#statistical") return <MasterStatisticalPage />; return (
<>
<Modal isOpen={showModal} onClose={() => setSelectedUser(undefined)}>
<>
{selectedUser && (
<div className="w-full flex flex-col gap-8">
<UserCard
loggedInUser={user}
onClose={(shouldReload) => {
setSelectedUser(undefined);
if (shouldReload && selectedUser!.type === "student") reloadStudents();
if (shouldReload && selectedUser!.type === "teacher") reloadTeachers();
}}
onViewStudents={
selectedUser.type === "corporate" || selectedUser.type === "teacher"
? () => {
appendUserFilters({
id: "view-students",
filter: (x: User) => x.type === "student",
});
appendUserFilters({
id: "belongs-to-admin",
filter: (x: User) =>
groups
.filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id))
.flatMap((g) => g.participants)
.includes(x.id),
});
return ( router.push("/list/users");
<> }
<Modal isOpen={showModal} onClose={() => setSelectedUser(undefined)}> : undefined
<> }
{selectedUser && ( onViewTeachers={
<div className="w-full flex flex-col gap-8"> selectedUser.type === "corporate" || selectedUser.type === "student"
<UserCard ? () => {
loggedInUser={user} appendUserFilters({
onClose={(shouldReload) => { id: "view-teachers",
setSelectedUser(undefined); filter: (x: User) => x.type === "teacher",
if (shouldReload && selectedUser!.type === "student") });
reloadStudents(); appendUserFilters({
if (shouldReload && selectedUser!.type === "teacher") id: "belongs-to-admin",
reloadTeachers(); filter: (x: User) =>
}} groups
onViewStudents={ .filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id))
selectedUser.type === "corporate" || .flatMap((g) => g.participants)
selectedUser.type === "teacher" .includes(x.id),
? () => { });
appendUserFilters({
id: "view-students",
filter: (x: User) => x.type === "student",
});
appendUserFilters({
id: "belongs-to-admin",
filter: (x: User) =>
groups
.filter(
(g) =>
g.admin === selectedUser.id ||
g.participants.includes(selectedUser.id)
)
.flatMap((g) => g.participants)
.includes(x.id),
});
router.push("/list/users"); router.push("/list/users");
} }
: undefined : undefined
} }
onViewTeachers={ user={selectedUser}
selectedUser.type === "corporate" || />
selectedUser.type === "student" </div>
? () => { )}
appendUserFilters({ </>
id: "view-teachers", </Modal>
filter: (x: User) => x.type === "teacher",
});
appendUserFilters({
id: "belongs-to-admin",
filter: (x: User) =>
groups
.filter(
(g) =>
g.admin === selectedUser.id ||
g.participants.includes(selectedUser.id)
)
.flatMap((g) => g.participants)
.includes(x.id),
});
router.push("/list/users"); <>
} {!!linkedCorporate && (
: undefined <div className="absolute top-4 right-4 bg-neutral-200 px-2 rounded-lg py-1">
} Linked to: <b>{linkedCorporate?.corporateInformation?.companyInformation.name || linkedCorporate.name}</b>
user={selectedUser} </div>
/> )}
</div> <section className="grid grid-cols-5 -md:grid-cols-2 gap-4 text-center">
)} <IconCard
</> onClick={() => router.push("/#students")}
</Modal> isLoading={isStudentsLoading}
Icon={BsPersonFill}
label="Students"
value={totalStudents}
color="purple"
/>
<IconCard
onClick={() => router.push("/#teachers")}
isLoading={isTeachersLoading}
Icon={BsPencilSquare}
label="Teachers"
value={totalTeachers}
color="purple"
/>
<IconCard
Icon={BsClipboard2Data}
label="Exams Performed"
value={stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user)).length}
color="purple"
/>
<IconCard
Icon={BsPaperclip}
isLoading={isStudentsLoading}
label="Average Level"
value={averageLevelCalculator(stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user))).toFixed(1)}
color="purple"
/>
<IconCard onClick={() => router.push("/#groups")} Icon={BsPeople} label="Groups" value={groups.length} color="purple" />
<IconCard
Icon={BsPersonCheck}
label="User Balance"
value={`${balance}/${user.corporateInformation?.companyInformation?.userAmount || 0}`}
color="purple"
/>
<IconCard
Icon={BsClock}
label="Expiration Date"
value={user.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy") : "Unlimited"}
color="rose"
/>
<IconCard
Icon={BsPersonFillGear}
isLoading={isStudentsLoading}
label="Student Performance"
value={totalStudents}
color="purple"
onClick={() => router.push("/#studentsPerformance")}
/>
<IconCard Icon={BsDatabase} label="Master Statistical" color="purple" onClick={() => router.push("/#statistical")} />
<button
disabled={isAssignmentsLoading}
onClick={() => router.push("/#assignments")}
className="bg-white col-span-2 rounded-xl shadow p-4 flex flex-col gap-4 items-center w-96 h-52 justify-center cursor-pointer hover:shadow-xl transition ease-in-out duration-300">
<BsEnvelopePaper className="text-6xl text-mti-purple-light" />
<span className="flex flex-col gap-1 items-center text-xl">
<span className="text-lg">Assignments</span>
<span className="font-semibold text-mti-purple-light">
{isAssignmentsLoading ? "Loading..." : assignments.filter((a) => !a.archived).length}
</span>
</span>
</button>
</section>
<> <section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
{!!linkedCorporate && ( <div className="bg-white shadow flex flex-col rounded-xl w-full">
<div className="absolute top-4 right-4 bg-neutral-200 px-2 rounded-lg py-1"> <span className="p-4">Latest students</span>
Linked to:{" "} <div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
<b> {students
{linkedCorporate?.corporateInformation?.companyInformation.name || .sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
linkedCorporate.name} .map((x) => (
</b> <UserDisplay key={x.id} {...x} />
</div> ))}
)} </div>
<section className="grid grid-cols-5 -md:grid-cols-2 gap-4 text-center"> </div>
<IconCard <div className="bg-white shadow flex flex-col rounded-xl w-full">
onClick={() => router.push("/#students")} <span className="p-4">Latest teachers</span>
isLoading={isStudentsLoading} <div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
Icon={BsPersonFill} {teachers
label="Students" .sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
value={totalStudents} .map((x) => (
color="purple" <UserDisplay key={x.id} {...x} />
/> ))}
<IconCard </div>
onClick={() => router.push("/#teachers")} </div>
isLoading={isTeachersLoading} <div className="bg-white shadow flex flex-col rounded-xl w-full">
Icon={BsPencilSquare} <span className="p-4">Highest level students</span>
label="Teachers" <div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
value={totalTeachers} {students
color="purple" .sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))
/> .map((x) => (
<IconCard <UserDisplay key={x.id} {...x} />
Icon={BsClipboard2Data} ))}
label="Exams Performed" </div>
value={ </div>
stats.filter((s) => <div className="bg-white shadow flex flex-col rounded-xl w-full">
groups.flatMap((g) => g.participants).includes(s.user) <span className="p-4">Highest exam count students</span>
).length <div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
} {students
color="purple" .sort(
/> (a, b) =>
<IconCard Object.keys(groupByExam(getStatsByStudent(b))).length - Object.keys(groupByExam(getStatsByStudent(a))).length,
Icon={BsPaperclip} )
isLoading={isStudentsLoading} .map((x) => (
label="Average Level" <UserDisplay key={x.id} {...x} />
value={averageLevelCalculator( ))}
stats.filter((s) => </div>
groups.flatMap((g) => g.participants).includes(s.user) </div>
) </section>
).toFixed(1)} </>
color="purple" </>
/> );
<IconCard
onClick={() => router.push("/#groups")}
Icon={BsPeople}
label="Groups"
value={groups.length}
color="purple"
/>
<IconCard
Icon={BsPersonCheck}
label="User Balance"
value={`${balance}/${
user.corporateInformation?.companyInformation?.userAmount || 0
}`}
color="purple"
/>
<IconCard
Icon={BsClock}
label="Expiration Date"
value={
user.subscriptionExpirationDate
? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy")
: "Unlimited"
}
color="rose"
/>
<IconCard
Icon={BsPersonFillGear}
isLoading={isStudentsLoading}
label="Student Performance"
value={totalStudents}
color="purple"
onClick={() => router.push("/#studentsPerformance")}
/>
<IconCard
Icon={BsDatabase}
label="Master Statistical"
color="purple"
onClick={() => router.push("/#statistical")}
/>
<button
disabled={isAssignmentsLoading}
onClick={() => router.push("/#assignments")}
className="bg-white col-span-2 rounded-xl shadow p-4 flex flex-col gap-4 items-center w-96 h-52 justify-center cursor-pointer hover:shadow-xl transition ease-in-out duration-300"
>
<BsEnvelopePaper className="text-6xl text-mti-purple-light" />
<span className="flex flex-col gap-1 items-center text-xl">
<span className="text-lg">Assignments</span>
<span className="font-semibold text-mti-purple-light">
{isAssignmentsLoading
? "Loading..."
: assignments.filter((a) => !a.archived).length}
</span>
</span>
</button>
</section>
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
<div className="bg-white shadow flex flex-col rounded-xl w-full">
<span className="p-4">Latest students</span>
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
{students
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
.map((x) => (
<UserDisplay key={x.id} {...x} />
))}
</div>
</div>
<div className="bg-white shadow flex flex-col rounded-xl w-full">
<span className="p-4">Latest teachers</span>
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
{teachers
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
.map((x) => (
<UserDisplay key={x.id} {...x} />
))}
</div>
</div>
<div className="bg-white shadow flex flex-col rounded-xl w-full">
<span className="p-4">Highest level students</span>
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
{students
.sort(
(a, b) =>
calculateAverageLevel(b.levels) -
calculateAverageLevel(a.levels)
)
.map((x) => (
<UserDisplay key={x.id} {...x} />
))}
</div>
</div>
<div className="bg-white shadow flex flex-col rounded-xl w-full">
<span className="p-4">Highest exam count students</span>
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
{students
.sort(
(a, b) =>
Object.keys(groupByExam(getStatsByStudent(b))).length -
Object.keys(groupByExam(getStatsByStudent(a))).length
)
.map((x) => (
<UserDisplay key={x.id} {...x} />
))}
</div>
</div>
</section>
</>
</>
);
} }

View File

@@ -1,5 +1,5 @@
import React 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";
@@ -14,6 +14,7 @@ import {useListSearch} from "@/hooks/useListSearch";
import axios from "axios"; import axios from "axios";
import {toast} from "react-toastify"; import {toast} from "react-toastify";
import Button from "@/components/Low/Button"; import Button from "@/components/Low/Button";
import {getUserName} from "@/utils/users";
interface GroupedCorporateUsers { interface GroupedCorporateUsers {
// list of user Ids // list of user Ids
@@ -27,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;
@@ -42,10 +43,13 @@ interface UserCount {
maxUserCount: number; maxUserCount: number;
} }
const searchFilters = [["email"], ["user"], ["userId"]]; const searchFilters = [["email"], ["user"], ["userId"], ["exams"], ["assignment"]];
const SIZE = 16;
const MasterStatistical = (props: Props) => { const MasterStatistical = (props: Props) => {
const {users, corporateUsers, displaySelection = true} = props; const {users, corporateUsers, displaySelection = true} = props;
const [page, setPage] = useState(0);
// const corporateRelevantUsers = React.useMemo( // const corporateRelevantUsers = React.useMemo(
// () => corporateUsers.filter((x) => x.type !== "student") as CorporateUser[], // () => corporateUsers.filter((x) => x.type !== "student") as CorporateUser[],
@@ -58,8 +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: [...corporates, "tYU0HTiJdjMsS8SB7XJsUdMMP892"],
corporates: selectedCorporates, corporates: selectedCorporates,
startDate, startDate,
endDate, endDate,
@@ -71,23 +74,25 @@ 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 corporate = users.find((u) => u.id === a.assigner)?.name || ""; const userStats = a.results.find((r) => r.user === assignee)?.stats || [];
const corporate = getUserName(users.find((u) => u.id === a.assigner));
const commonData = { const commonData = {
user: userData?.name || "", user: userData,
email: userData?.email || "", email: userData?.email || "N/A",
userId: assignee, userId: assignee,
corporateId: a.corporateId, corporateId: a.corporateId,
exams: a.exams.map((x) => x.id).join(", "),
corporate, corporate,
assignment: a.name, assignment: a.name,
}; };
if (userStats.length === 0) { if (userStats.length === 0) {
return { return {
...commonData, ...commonData,
correct: 0, correct: 0,
submitted: false, submitted: false,
// date: moment(), date: null,
}; };
} }
@@ -145,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", {
@@ -155,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", {
@@ -166,13 +178,6 @@ const MasterStatistical = (props: Props) => {
}), }),
] ]
: []), : []),
columnHelper.accessor("corporate", {
header: "Corporate",
id: "corporate",
cell: (info) => {
return <span>{info.getValue()}</span>;
},
}),
columnHelper.accessor("assignment", { columnHelper.accessor("assignment", {
header: "Assignment", header: "Assignment",
id: "assignment", id: "assignment",
@@ -192,7 +197,7 @@ const MasterStatistical = (props: Props) => {
}, },
}), }),
columnHelper.accessor("correct", { columnHelper.accessor("correct", {
header: "Correct", header: "Score",
id: "correct", id: "correct",
cell: (info) => { cell: (info) => {
return <span>{info.getValue()}</span>; return <span>{info.getValue()}</span>;
@@ -204,7 +209,7 @@ const MasterStatistical = (props: Props) => {
cell: (info) => { cell: (info) => {
const date = info.getValue(); const date = info.getValue();
if (date) { if (date) {
return <span>{date.format("DD/MM/YYYY")}</span>; return <span>{!!date ? date.format("DD/MM/YYYY") : "N/A"}</span>;
} }
return <span>{""}</span>; return <span>{""}</span>;
@@ -214,8 +219,14 @@ const MasterStatistical = (props: Props) => {
const {rows: filteredRows, renderSearch, text: searchText} = useListSearch(searchFilters, tableResults); const {rows: filteredRows, renderSearch, text: searchText} = useListSearch(searchFilters, tableResults);
useEffect(() => setPage(0), [searchText]);
const rows = useMemo(
() => filteredRows.slice(page * SIZE, (page + 1) * SIZE > filteredRows.length ? filteredRows.length : (page + 1) * SIZE),
[filteredRows, page],
);
const table = useReactTable({ const table = useReactTable({
data: filteredRows, data: rows,
columns: defaultColumns, columns: defaultColumns,
getCoreRowModel: getCoreRowModel(), getCoreRowModel: getCoreRowModel(),
}); });
@@ -276,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={() => {
@@ -297,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"
@@ -338,13 +351,28 @@ 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>
</div> </div>
<div> <div className="w-full h-full flex flex-col gap-4">
<div className="w-full flex gap-2 justify-between">
<Button 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 * SIZE + 1} - {(page + 1) * SIZE > filteredRows.length ? filteredRows.length : (page + 1) * SIZE} /{" "}
{filteredRows.length}
</span>
<Button className="w-[200px]" disabled={(page + 1) * SIZE >= filteredRows.length} onClick={() => setPage((prev) => prev + 1)}>
Next Page
</Button>
</div>
</div>
<table className="rounded-xl h-full bg-mti-purple-ultralight/40 w-full"> <table className="rounded-xl h-full bg-mti-purple-ultralight/40 w-full">
<thead> <thead>
{table.getHeaderGroups().map((headerGroup) => ( {table.getHeaderGroups().map((headerGroup) => (

View File

@@ -83,18 +83,6 @@ export default function MasterCorporateDashboard({user}: Props) {
const {assignments, isLoading: isAssignmentsLoading, reload: reloadAssignments} = useAssignments({corporate: user.id}); const {assignments, isLoading: isAssignmentsLoading, reload: reloadAssignments} = useAssignments({corporate: user.id});
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(
() =>
[...students, ...teachers].filter((x) =>
!!selectedUser
? groups
.filter((g) => g.admin === selectedUser.id)
.flatMap((g) => g.participants)
.includes(x.id) || false
: groups.flatMap((g) => g.participants).includes(x.id),
),
[groups, selectedUser, teachers, students],
);
const appendUserFilters = useFilterStore((state) => state.appendUserFilter); const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
const router = useRouter(); const router = useRouter();
@@ -131,7 +119,6 @@ export default function MasterCorporateDashboard({user}: Props) {
const {users} = useUsers(); const {users} = useUsers();
const groupedByNameCorporates = useMemo( const groupedByNameCorporates = useMemo(
() => () =>
groupBy( groupBy(
@@ -374,12 +361,18 @@ export default function MasterCorporateDashboard({user}: Props) {
color="purple" color="purple"
onClick={() => router.push("/#corporate")} onClick={() => router.push("/#corporate")}
/> />
<IconCard Icon={BsBank} label="Corporate" value={groupedByNameCorporatesKeys.length} isLoading={isCorporatesLoading} color="purple" /> <IconCard
Icon={BsBank}
label="Corporate"
value={groupedByNameCorporatesKeys.length}
isLoading={isCorporatesLoading}
color="purple"
/>
<IconCard <IconCard
Icon={BsPersonFillGear} Icon={BsPersonFillGear}
isLoading={isStudentsLoading} isLoading={isStudentsLoading}
label="Student Performance" label="Student Performance"
value={students.length} value={totalStudents}
color="purple" color="purple"
onClick={() => router.push("/#studentsPerformance")} onClick={() => router.push("/#studentsPerformance")}
/> />

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} users={[...users, user]}
user={user} user={user}
isCreating={isCreatingAssignment} isCreating={isCreatingAssignment}
cancelCreation={() => { cancelCreation={() => {

View File

@@ -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>

View File

@@ -1,6 +1,6 @@
import {useState, useMemo} from "react"; import {useState, useMemo} from "react";
import Input from "@/components/Low/Input"; import Input from "@/components/Low/Input";
import { search } from "@/utils/search"; import {search} from "@/utils/search";
export function useListSearch<T>(fields: string[][], rows: T[]) { export function useListSearch<T>(fields: string[][], rows: T[]) {
const [text, setText] = useState(""); const [text, setText] = useState("");
@@ -8,7 +8,8 @@ export function useListSearch<T>(fields: string[][], rows: T[]) {
const renderSearch = () => <Input label="Search" type="text" name="search" onChange={setText} placeholder="Enter search text" value={text} />; const renderSearch = () => <Input label="Search" type="text" name="search" onChange={setText} placeholder="Enter search text" value={text} />;
const updatedRows = useMemo(() => { const updatedRows = useMemo(() => {
return search(text, fields, rows); if (text.length > 0) return search(text, fields, rows);
return rows;
}, [fields, rows, text]); }, [fields, rows, text]);
return { return {

View 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};
}

View File

@@ -1,12 +1,9 @@
import {Exam} from "@/interfaces/exam"; import {Exam} from "@/interfaces/exam";
import {ExamState} from "@/stores/examStore"; import {ExamState} from "@/stores/examStore";
import Axios from "axios"; import axios from "axios";
import {setupCache} from "axios-cache-interceptor"; import {setupCache} from "axios-cache-interceptor";
import {useEffect, useState} from "react"; import {useEffect, useState} from "react";
const instance = Axios.create();
const axios = setupCache(instance);
export type Session = ExamState & {user: string; id: string; date: string}; export type Session = ExamState & {user: string; id: string; date: string};
export default function useSessions(user?: string) { export default function useSessions(user?: string) {

View File

@@ -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"}})

View File

@@ -53,7 +53,7 @@ const USER_TYPE_PERMISSIONS: {
}, },
admin: { admin: {
perm: "createCodeAdmin", perm: "createCodeAdmin",
list: ["student", "teacher", "agent", "corporate", "admin", "mastercorporate"], list: ["student", "teacher", "agent", "corporate", "mastercorporate"],
}, },
developer: { developer: {
perm: undefined, perm: undefined,
@@ -161,7 +161,7 @@ export default function BatchCreateUser({user, users, permissions, onFinish}: Pr
setIsLoading(true); setIsLoading(true);
try { try {
await axios.post("/api/batch_users", { users: newUsers.map(user => ({...user, type, expiryDate})) }); await axios.post("/api/batch_users", {users: newUsers.map((user) => ({...user, type, expiryDate}))});
toast.success(`Successfully added ${newUsers.length} user(s)!`); toast.success(`Successfully added ${newUsers.length} user(s)!`);
onFinish(); onFinish();
} catch { } catch {

View File

@@ -28,9 +28,14 @@ import {checkAccess} from "@/utils/permissions";
import {PermissionType} from "@/interfaces/permissions"; import {PermissionType} from "@/interfaces/permissions";
import usePermissions from "@/hooks/usePermissions"; import usePermissions from "@/hooks/usePermissions";
import useUserBalance from "@/hooks/useUserBalance"; import useUserBalance from "@/hooks/useUserBalance";
import usePagination from "@/hooks/usePagination";
const columnHelper = createColumnHelper<User>(); const columnHelper = createColumnHelper<User>();
const searchFields = [["name"], ["email"], ["corporateInformation", "companyInformation", "name"]]; const searchFields = [["name"], ["email"], ["corporateInformation", "companyInformation", "name"]];
const corporatesHash = {
type: "corporate",
};
const CompanyNameCell = ({users, user, groups}: {user: User; users: User[]; groups: Group[]}) => { const CompanyNameCell = ({users, user, groups}: {user: User; users: User[]; groups: Group[]}) => {
const [companyName, setCompanyName] = useState(""); const [companyName, setCompanyName] = useState("");
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
@@ -58,18 +63,19 @@ export default function UserList({
const [sorter, setSorter] = useState<string>(); const [sorter, setSorter] = useState<string>();
const [displayUsers, setDisplayUsers] = useState<User[]>([]); const [displayUsers, setDisplayUsers] = useState<User[]>([]);
const [selectedUser, setSelectedUser] = useState<User>(); const [selectedUser, setSelectedUser] = useState<User>();
const [page, setPage] = useState(0);
const userHash = useMemo( const userHash = useMemo(
() => ({ () => ({
type, type,
size: 16,
page,
}), }),
[type, page], [type],
); );
const {users, total, isLoading, reload} = useUsers(userHash); const {users, total, isLoading, reload} = useUsers(userHash);
const {users: corporates} = useUsers(corporatesHash);
const totalUsers = useMemo(() => [...users, ...corporates], [users, corporates]);
const {permissions} = usePermissions(user?.id || ""); const {permissions} = usePermissions(user?.id || "");
const {balance} = useUserBalance(); const {balance} = useUserBalance();
const {groups} = useGroups({ const {groups} = useGroups({
@@ -94,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
@@ -354,7 +360,7 @@ export default function UserList({
<SorterArrow name="companyName" /> <SorterArrow name="companyName" />
</button> </button>
) as any, ) as any,
cell: (info) => <CompanyNameCell user={info.row.original} users={users} groups={groups} />, cell: (info) => <CompanyNameCell user={info.row.original} users={totalUsers} groups={groups} />,
}), }),
columnHelper.accessor("subscriptionExpirationDate", { columnHelper.accessor("subscriptionExpirationDate", {
header: ( header: (
@@ -505,10 +511,14 @@ export default function UserList({
return a.id.localeCompare(b.id); return a.id.localeCompare(b.id);
}; };
const {rows: filteredRows, renderSearch} = useListSearch<User>(searchFields, displayUsers); const {rows: filteredRows, renderSearch, text: searchText} = useListSearch<User>(searchFields, displayUsers);
const {items, setPage, render: renderPagination} = usePagination<User>(filteredRows, 16);
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => setPage(0), [searchText]);
const table = useReactTable({ const table = useReactTable({
data: filteredRows, data: items,
columns: (!showDemographicInformation ? defaultColumns : demographicColumns) as any, columns: (!showDemographicInformation ? defaultColumns : demographicColumns) as any,
getCoreRowModel: getCoreRowModel(), getCoreRowModel: getCoreRowModel(),
}); });
@@ -624,27 +634,7 @@ export default function UserList({
Download List Download List
</Button> </Button>
</div> </div>
<div className="w-full flex gap-2 justify-between"> {renderPagination()}
<Button
isLoading={isLoading}
className="w-full max-w-[200px]"
disabled={page === 0}
onClick={() => setPage((prev) => prev - 1)}>
Previous Page
</Button>
<div className="flex items-center gap-4 w-fit">
<span className="opacity-80">
{page * 16 + 1} - {(page + 1) * 16 > total ? total : (page + 1) * 16} / {total}
</span>
<Button
isLoading={isLoading}
className="w-[200px]"
disabled={page * 16 >= 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

@@ -141,7 +141,11 @@ export default function UserCreator({user, users, permissions, onFinish}: Props)
setType("student"); setType("student");
setPosition(undefined); setPosition(undefined);
}) })
.catch(() => toast.error("Something went wrong! Please try again later!")) .catch((error) => {
const data = error?.response?.data;
if (!!data?.message) return toast.error(data.message);
toast.error("Something went wrong! Please try again later!");
})
.finally(() => setIsLoading(false)); .finally(() => setIsLoading(false));
}; };

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); 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"));

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(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});

View File

@@ -1,254 +1,255 @@
import type { NextApiRequest, NextApiResponse } from "next"; import type {NextApiRequest, NextApiResponse} from "next";
import { storage } from "@/firebase"; import {storage} from "@/firebase";
import { withIronSessionApiRoute } from "iron-session/next"; import {withIronSessionApiRoute} from "iron-session/next";
import { sessionOptions } from "@/lib/session"; import {sessionOptions} from "@/lib/session";
import { ref, uploadBytes, getDownloadURL } from "firebase/storage"; import {ref, uploadBytes, getDownloadURL} from "firebase/storage";
import { AssignmentWithCorporateId } from "@/interfaces/results"; import {AssignmentWithCorporateId} from "@/interfaces/results";
import moment from "moment-timezone"; import moment from "moment-timezone";
import ExcelJS from "exceljs"; import ExcelJS from "exceljs";
import { getSpecificUsers } from "@/utils/users.be"; import {getSpecificUsers} from "@/utils/users.be";
import { checkAccess } from "@/utils/permissions"; 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;
email: string; studentID: string;
correct: number; passportID: string;
corporate: string; exams: string;
submitted: boolean; email: string;
date: moment.Moment; correct: number;
assignment: string; corporate: string;
corporateId: string; submitted: boolean;
score: number; date: moment.Moment;
level: string; assignment: string;
part1?: string; corporateId: string;
part2?: string; score: number;
part3?: string; level: string;
part4?: string; part1?: string;
part5?: string; part2?: string;
part3?: string;
part4?: string;
part5?: string;
} }
async function handler(req: NextApiRequest, res: NextApiResponse) { async function handler(req: NextApiRequest, res: NextApiResponse) {
// if (req.method === "GET") return get(req, res); // if (req.method === "GET") return get(req, res);
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 {
} ids,
const { startDate,
ids, endDate,
startDate, searchText,
endDate, displaySelection = true,
searchText, } = req.body as {
displaySelection = true, ids: string[];
} = req.body as { startDate?: string;
ids: string[]; endDate?: string;
startDate?: string; searchText: string;
endDate?: string; displaySelection?: boolean;
searchText: string; };
displaySelection?: boolean; const startDateParsed = startDate ? new Date(startDate) : undefined;
}; const endDateParsed = endDate ? new Date(endDate) : undefined;
const startDateParsed = startDate ? new Date(startDate) : undefined; const assignments = await getAssignmentsForCorporates(req.session.user.type, ids, startDateParsed, endDateParsed);
const endDateParsed = endDate ? new Date(endDate) : undefined;
const assignments = await getAssignmentsForCorporates(
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 users = await getSpecificUsers(assignmentUsers);
const assigners = [...new Set(assignments.map((a) => a.assigner))]; const assignerUsers = await getSpecificUsers(assigners);
const users = await getSpecificUsers(assignmentUsers); const exams = await getSpecificExams(uniq(assignments.flatMap((x) => x.exams.map((x) => x.id))));
const assignerUsers = await getSpecificUsers(assigners);
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 = (
exams: { id: string; module: Module; assignee: string }[], exams: {id: string; module: Module; assignee: string}[],
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) {
); const bandScore = calculateBandScore(correct, total, "level", user?.focus || "academic");
if (gradingSystem) { return {
const bandScore = calculateBandScore( label: getGradingLabel(bandScore, gradingSystem.steps || []),
correct, score: bandScore,
total, };
"level", }
user.focus }
);
return {
label: getGradingLabel(bandScore, gradingSystem?.steps || []),
score: bandScore,
};
}
}
return { score: -1, label: "N/A" }; return {score: -1, label: "N/A"};
}; };
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(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 || "",
userId: assignee, passportID: (userData as StudentUser)?.demographicInformation?.passport_id || "",
corporateId: a.corporateId, userId: assignee,
corporate: corporateUser?.name || "", exams: a.exams.map((x) => x.id).join(", "),
assignment: a.name, corporateId: a.corporateId,
level, corporate: !corporateUser ? "" : getUserName(corporateUser),
score, assignment: a.name,
}; level,
if (userStats.length === 0) { score,
return { };
...commonData, if (userStats.length === 0) {
correct: 0, return {
submitted: false, ...commonData,
// date: moment(), correct: 0,
}; submitted: false,
} // date: moment(),
};
}
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));
}, {})
: {};
return { const total = stats.reduce((acc, curr) => acc + curr.score.total, 0);
...commonData, const correct = stats.reduce((acc, curr) => acc + curr.score.correct, 0);
correct,
submitted: true,
date: moment.max(userStats.map((e) => moment(e.date))),
...partsData,
};
}) as TableData[];
return [...accmA, ...userResults]; return {total, correct};
}, []) });
.sort((a, b) => b.score - a.score); }
// Create a new workbook and add a worksheet const partsData =
const workbook = new ExcelJS.Workbook(); data.length > 0 ? data.reduce((acc, e, index) => ({...acc, [`part${index}`]: `${e.correct}/${e.total}`}), {}) : {};
const worksheet = workbook.addWorksheet("Master Statistical");
const headers = [ return {
{ ...commonData,
label: "User", correct,
value: (entry: TableData) => entry.user, submitted: true,
}, date: moment.max(userStats.map((e) => moment(e.date))),
{ ...partsData,
label: "Email", };
value: (entry: TableData) => entry.email, }) as TableData[];
},
...(displaySelection
? [
{
label: "Corporate",
value: (entry: TableData) => entry.corporate,
},
]
: []),
{
label: "Assignment",
value: (entry: TableData) => entry.assignment,
},
{
label: "Submitted",
value: (entry: TableData) => (entry.submitted ? "Yes" : "No"),
},
{
label: "Correct",
value: (entry: TableData) => entry.correct,
},
{
label: "Date",
value: (entry: TableData) => entry.date?.format("YYYY/MM/DD") || "",
},
{
label: "Level",
value: (entry: TableData) => entry.level,
},
...new Array(5).fill(0).map((_, index) => ({
label: `Part ${index + 1}`,
value: (entry: TableData) => {
const key = `part${index}` as keyof TableData;
return entry[key] || "";
},
})),
];
const filteredSearch = searchText return [...accmA, ...userResults];
? search(searchText, searchFilters, tableResults) }, [])
: tableResults; .sort((a, b) => b.score - a.score);
worksheet.addRow(headers.map((h) => h.label)); // Create a new workbook and add a worksheet
(filteredSearch as TableData[]).forEach((entry) => { const workbook = new ExcelJS.Workbook();
worksheet.addRow(headers.map((h) => h.value(entry))); const worksheet = workbook.addWorksheet("Master Statistical");
});
// Convert workbook to Buffer (Node.js) or Blob (Browser) const headers = [
const buffer = await workbook.xlsx.writeBuffer(); {
label: "User",
value: (entry: TableData) => entry.user,
},
{
label: "Email",
value: (entry: TableData) => entry.email,
},
{
label: "Student ID",
value: (entry: TableData) => entry.studentID,
},
{
label: "Passport ID",
value: (entry: TableData) => entry.passportID,
},
...(displaySelection
? [
{
label: "Corporate",
value: (entry: TableData) => entry.corporate,
},
]
: []),
{
label: "Assignment",
value: (entry: TableData) => entry.assignment,
},
{
label: "Submitted",
value: (entry: TableData) => (entry.submitted ? "Yes" : "No"),
},
{
label: "Score",
value: (entry: TableData) => entry.correct,
},
{
label: "Date",
value: (entry: TableData) => entry.date?.format("YYYY/MM/DD") || "",
},
{
label: "Level",
value: (entry: TableData) => entry.level,
},
...new Array(5).fill(0).map((_, index) => ({
label: `Part ${index + 1}`,
value: (entry: TableData) => {
const key = `part${index}` as keyof TableData;
return entry[key] || "";
},
})),
];
// generate the file ref for storage const filteredSearch = !!searchText ? search(searchText, searchFilters, tableResults) : tableResults;
const fileName = `${Date.now().toString()}.xlsx`;
const refName = `statistical/${fileName}`;
const fileRef = ref(storage, refName);
// upload the pdf to storage
await uploadBytes(fileRef, buffer, {
contentType:
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
const url = await getDownloadURL(fileRef); worksheet.addRow(headers.map((h) => h.label));
res.status(200).end(url); (filteredSearch as TableData[]).forEach((entry) => {
return; worksheet.addRow(headers.map((h) => h.value(entry)));
} });
return res.status(401).json({ error: "Unauthorized" }); // Convert workbook to Buffer (Node.js) or Blob (Browser)
const buffer = await workbook.xlsx.writeBuffer();
// generate the file ref for storage
const fileName = `${Date.now().toString()}.xlsx`;
const refName = `statistical/${fileName}`;
const fileRef = ref(storage, refName);
// upload the pdf to storage
await uploadBytes(fileRef, buffer, {
contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
const url = await getDownloadURL(fileRef);
res.status(200).end(url);
return;
}
return res.status(401).json({error: "Unauthorized"});
} }

View File

@@ -1,11 +1,11 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction // Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next"; import type { NextApiRequest, NextApiResponse } from "next";
import client from "@/lib/mongodb"; import client from "@/lib/mongodb";
import {withIronSessionApiRoute} from "iron-session/next"; import { withIronSessionApiRoute } from "iron-session/next";
import {sessionOptions} from "@/lib/session"; import { sessionOptions } from "@/lib/session";
import axios, {AxiosResponse} from "axios"; import axios, { AxiosResponse } from "axios";
import {Stat} from "@/interfaces/user"; import { Stat } from "@/interfaces/user";
import {writingReverseMarking} from "@/utils/score"; import { writingReverseMarking } from "@/utils/score";
interface Body { interface Body {
question: string; question: string;
@@ -24,7 +24,7 @@ export default withIronSessionApiRoute(handler, sessionOptions);
async function handler(req: NextApiRequest, res: NextApiResponse) { async function handler(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) { if (!req.session.user) {
res.status(401).json({ok: false}); res.status(401).json({ ok: false });
return; return;
} }
@@ -36,27 +36,29 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
const correspondingStat = await getCorrespondingStat(req.body.id, 1); const correspondingStat = await getCorrespondingStat(req.body.id, 1);
const solutions = correspondingStat.solutions.map((x) => ({...x, evaluation: backendRequest.data})); const solutions = correspondingStat.solutions.map((x) => ({ ...x, evaluation: backendRequest.data }));
await db.collection("stats").updateOne( await db.collection("stats").updateOne(
{ id: (req.body as Body).id}, { id: (req.body as Body).id },
{ {
id: (req.body as Body).id, $set: {
solutions, id: (req.body as Body).id,
score: { solutions,
correct: writingReverseMarking[backendRequest.data.overall], score: {
total: 100, correct: writingReverseMarking[backendRequest.data.overall],
missing: 0, total: 100,
}, missing: 0,
isDisabled: false, },
isDisabled: false,
}
}, },
{upsert: true}, { upsert: true },
); );
console.log("🌱 - Updated the DB"); console.log("🌱 - Updated the DB");
} }
async function getCorrespondingStat(id: string, index: number): Promise<Stat> { async function getCorrespondingStat(id: string, index: number): Promise<Stat> {
console.log(`🌱 - Try number ${index} - ${id}`); console.log(`🌱 - Try number ${index} - ${id}`);
const correspondingStat = await db.collection("stats").findOne<Stat>({ id: id}); const correspondingStat = await db.collection("stats").findOne<Stat>({ id: id });
if (correspondingStat) return correspondingStat; if (correspondingStat) return correspondingStat;

View File

@@ -1,109 +1,91 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction // Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next"; import type {NextApiRequest, NextApiResponse} from "next";
import client from "@/lib/mongodb"; import client from "@/lib/mongodb";
import { withIronSessionApiRoute } from "iron-session/next"; import {withIronSessionApiRoute} from "iron-session/next";
import { sessionOptions } from "@/lib/session"; import {sessionOptions} from "@/lib/session";
import { Group } from "@/interfaces/user"; import {Group} from "@/interfaces/user";
import { updateExpiryDateOnGroup } from "@/utils/groups.be"; import {updateExpiryDateOnGroup} from "@/utils/groups.be";
const db = client.db(process.env.MONGODB_DB); const db = client.db(process.env.MONGODB_DB);
export default withIronSessionApiRoute(handler, sessionOptions); export default withIronSessionApiRoute(handler, sessionOptions);
async function handler(req: NextApiRequest, res: NextApiResponse) { async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "GET") return await get(req, res); if (req.method === "GET") return await get(req, res);
if (req.method === "DELETE") return await del(req, res); if (req.method === "DELETE") return await del(req, res);
if (req.method === "PATCH") return await patch(req, res); if (req.method === "PATCH") return await patch(req, res);
res.status(404).json(undefined); res.status(404).json(undefined);
} }
async function get(req: NextApiRequest, res: NextApiResponse) { async function get(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) { if (!req.session.user) {
res.status(401).json({ ok: false }); res.status(401).json({ok: false});
return; return;
} }
const { id } = req.query as { id: string }; const {id} = req.query as {id: string};
const snapshot = await db.collection("groups").findOne({ id: id}); const snapshot = await db.collection("groups").findOne({id: id});
if (snapshot) { if (snapshot) {
res.status(200).json({ ...snapshot }); res.status(200).json({...snapshot});
} else { } else {
res.status(404).json(undefined); res.status(404).json(undefined);
} }
} }
async function del(req: NextApiRequest, res: NextApiResponse) { async function del(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) { if (!req.session.user) {
res.status(401).json({ ok: false }); res.status(401).json({ok: false});
return; return;
} }
const { id } = req.query as { id: string }; const {id} = req.query as {id: string};
const group = await db.collection("groups").findOne<Group>({id: id}); const group = await db.collection("groups").findOne<Group>({id: id});
if (!group) { if (!group) {
res.status(404); res.status(404);
return; return;
} }
const user = req.session.user; const user = req.session.user;
if ( if (user.type === "admin" || user.type === "developer" || user.id === group.admin) {
user.type === "admin" || await db.collection("groups").deleteOne({id: id});
user.type === "developer" ||
user.id === group.admin
) {
await db.collection("groups").deleteOne({ id: id });
res.status(200).json({ ok: true }); res.status(200).json({ok: true});
return; return;
} }
res.status(403).json({ ok: false }); res.status(403).json({ok: false});
} }
async function patch(req: NextApiRequest, res: NextApiResponse) { async function patch(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) { if (!req.session.user) {
res.status(401).json({ ok: false }); res.status(401).json({ok: false});
return; return;
} }
const { id } = req.query as { id: string }; const {id} = req.query as {id: string};
const group = await db.collection("groups").findOne<Group>({id: id}); const group = await db.collection("groups").findOne<Group>({id: id});
if (!group) { if (!group) {
res.status(404); res.status(404);
return; return;
} }
const user = req.session.user; const user = req.session.user;
if ( if (user.type === "admin" || user.type === "developer" || user.id === group.admin) {
user.type === "admin" || if ("participants" in req.body) {
user.type === "developer" || const newParticipants = (req.body.participants as string[]).filter((x) => !group.participants.includes(x));
user.id === group.admin await Promise.all(newParticipants.map(async (p) => await updateExpiryDateOnGroup(p, group.admin)));
) { }
if ("participants" in req.body) {
const newParticipants = (req.body.participants as string[]).filter(
(x) => !group.participants.includes(x),
);
await Promise.all(
newParticipants.map(
async (p) => await updateExpiryDateOnGroup(p, group.admin),
),
);
}
await db.collection("grading").updateOne( await db.collection("groups").updateOne({id: req.session.user.id}, {$set: {id, ...req.body}}, {upsert: true});
{ id: req.session.user.id },
{ $set: {id: id, ...req.body} },
{ upsert: true }
);
res.status(200).json({ ok: true }); res.status(200).json({ok: true});
return; return;
} }
res.status(403).json({ ok: false }); res.status(403).json({ok: false});
} }

View File

@@ -218,6 +218,8 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
return res.status(200).json({ok: true}); return res.status(200).json({ok: true});
}) })
.catch((error) => { .catch((error) => {
if (error.code.includes("email-already-in-use")) return res.status(403).json({error, message: "E-mail is already in the platform."});
console.log(`Failing - ${email}`); console.log(`Failing - ${email}`);
console.log(error); console.log(error);
return res.status(401).json({error}); return res.status(401).json({error});

View File

@@ -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 = {

View File

@@ -24,7 +24,7 @@ async function get(req: NextApiRequest, res: NextApiResponse) {
const {user} = req.query as {user?: string}; const {user} = req.query as {user?: string};
const q = user ? {user: user} : {}; const q = user ? {user: user} : {};
const sessions = await db.collection("sessions").find<Session>(q).toArray(); const sessions = await db.collection("sessions").find<Session>(q).limit(10).toArray();
res.status(200).json( res.status(200).json(
sessions.filter((x) => { sessions.filter((x) => {
@@ -42,11 +42,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
} }
const session = req.body; const session = req.body;
await db.collection("sessions").updateOne( await db.collection("sessions").updateOne({id: session.id}, {$set: session}, {upsert: true});
{ id: session.id},
{ $set: session },
{ upsert: true }
);
res.status(200).json({ok: true}); res.status(200).json({ok: true});
} }

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

View File

@@ -4,6 +4,7 @@ import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session"; import {sessionOptions} from "@/lib/session";
import {getLinkedUsers} from "@/utils/users.be"; import {getLinkedUsers} from "@/utils/users.be";
import {Type} from "@/interfaces/user"; import {Type} from "@/interfaces/user";
import {uniqBy} from "lodash";
export default withIronSessionApiRoute(handler, sessionOptions); export default withIronSessionApiRoute(handler, sessionOptions);
@@ -31,5 +32,5 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
direction, direction,
); );
res.status(200).json({users, total}); res.status(200).json({users: uniqBy([...users], "id"), total});
} }

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}, {$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 = {

View File

@@ -68,17 +68,17 @@ interface Props {
linkedCorporate?: CorporateUser | MasterCorporateUser; linkedCorporate?: CorporateUser | MasterCorporateUser;
} }
export default function Home({linkedCorporate}: Props) { export default function Home({user: propsUser, linkedCorporate}: Props) {
const [user, setUser] = useState(propsUser);
const [showDiagnostics, setShowDiagnostics] = useState(false); const [showDiagnostics, setShowDiagnostics] = useState(false);
const [showDemographicInput, setShowDemographicInput] = useState(false); const [showDemographicInput, setShowDemographicInput] = useState(false);
const [selectedScreen, setSelectedScreen] = useState<Type>("admin"); const [selectedScreen, setSelectedScreen] = useState<Type>("admin");
const {user, mutateUser} = useUser({redirectTo: "/login"}); const {mutateUser} = useUser({redirectTo: "/login"});
const router = useRouter(); const router = useRouter();
useEffect(() => { useEffect(() => {
if (user) { if (user) {
console.log(user.demographicInformation);
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");
} }
@@ -131,7 +131,13 @@ export default function Home({linkedCorporate}: Props) {
<link rel="icon" href="/favicon.ico" /> <link rel="icon" href="/favicon.ico" />
</Head> </Head>
<Layout user={user} navDisabled> <Layout user={user} navDisabled>
<DemographicInformationInput mutateUser={mutateUser} user={user} /> <DemographicInformationInput
mutateUser={(user) => {
setUser(user);
mutateUser(user);
}}
user={user}
/>
</Layout> </Layout>
</> </>
); );

View File

@@ -1,18 +1,19 @@
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);
export const getAssignmentsByAssigner = async (id: string, startDate?: Date, endDate?: Date) => { export const getAssignmentsByAssigner = async (id: string, startDate?: Date, endDate?: Date) => {
let query: any = { assigner: id }; let query: any = {assigner: id};
if (startDate) { if (startDate) {
query.startDate = { $gte: startDate.toISOString() }; query.startDate = {$gte: startDate.toISOString()};
} }
if (endDate) { if (endDate) {
query.endDate = { $lte: endDate.toISOString() }; query.endDate = {$lte: endDate.toISOString()};
} }
return await db.collection("assignments").find<Assignment>(query).toArray(); return await db.collection("assignments").find<Assignment>(query).toArray();
@@ -26,13 +27,20 @@ export const getAssignmentsByAssignerBetweenDates = async (id: string, startDate
}; };
export const getAssignmentsByAssigners = async (ids: string[], startDate?: Date, endDate?: Date) => { export const getAssignmentsByAssigners = async (ids: string[], startDate?: Date, endDate?: Date) => {
return (await Promise.all(ids.map((id) => getAssignmentsByAssigner(id, startDate, endDate)))).flat(); return await db
.collection("assignments")
.find<Assignment>({
assigner: {$in: ids},
...(!!startDate ? {startDate: {$gte: startDate.toISOString()}} : {}),
...(!!endDate ? {endDate: {$lte: endDate.toISOString()}} : {}),
})
.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,
@@ -57,4 +65,4 @@ export const getAssignmentsForCorporates = async (idsList: string[], startDate?:
); );
return assignments.flat(); return assignments.flat();
} };

View File

@@ -5,7 +5,29 @@ import {DeveloperUser, Stat, StudentUser, User} from "@/interfaces/user";
import {Module} from "@/interfaces"; 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,
@@ -18,18 +40,18 @@ export const getExams = async (
variant?: Variant, variant?: Variant,
instructorGender?: InstructorGender, instructorGender?: InstructorGender,
): Promise<Exam[]> => { ): Promise<Exam[]> => {
const allExams = await db
.collection(module)
.find<Exam>({
isDiagnostic: false,
})
.toArray();
const allExams = await db.collection(module).find<Exam>({ const shuffledPublicExams = shuffle(
isDiagnostic: false allExams.map((doc) => ({
}).toArray(); ...doc,
module,
const shuffledPublicExams = ( })) as Exam[],
shuffle(
allExams.map((doc) => ({
...doc,
module,
})) as Exam[],
)
).filter((x) => !x.private); ).filter((x) => !x.private);
let exams: Exam[] = await filterByOwners(shuffledPublicExams, userId); let exams: Exam[] = await filterByOwners(shuffledPublicExams, userId);
@@ -39,9 +61,12 @@ export const getExams = async (
exams = await filterByPreference(db, exams, module, userId); exams = await filterByPreference(db, exams, module, userId);
if (avoidRepeated === "true") { if (avoidRepeated === "true") {
const stats = await db.collection("stats").find<Stat>({ const stats = await db
user: userId .collection("stats")
}).toArray(); .find<Stat>({
user: userId,
})
.toArray();
const filteredExams = exams.filter((x) => !stats.map((s) => s.exam).includes(x.id)); const filteredExams = exams.filter((x) => !stats.map((s) => s.exam).includes(x.id));
@@ -78,7 +103,7 @@ const filterByOwners = async (exams: Exam[], userID?: string) => {
const filterByDifficulty = async (db: Db, exams: Exam[], module: Module, userID?: string) => { const filterByDifficulty = async (db: Db, exams: Exam[], module: Module, userID?: string) => {
if (!userID) return exams; if (!userID) return exams;
const user = await db.collection("users").findOne<User>({ _id: new ObjectId(userID) }); const user = await db.collection("users").findOne<User>({id: userID});
if (!user) return exams; if (!user) return exams;
const difficulty = user.levels[module] <= 3 ? "easy" : user.levels[module] <= 6 ? "medium" : "hard"; const difficulty = user.levels[module] <= 3 ? "easy" : user.levels[module] <= 6 ? "medium" : "hard";
@@ -92,7 +117,7 @@ const filterByPreference = async (db: Db, exams: Exam[], module: Module, userID?
if (!userID) return exams; if (!userID) return exams;
const user = await db.collection("users").findOne<StudentUser | DeveloperUser>({ _id: new ObjectId(userID) }); const user = await db.collection("users").findOne<StudentUser | DeveloperUser>({id: userID});
if (!user) return exams; if (!user) return exams;
if (!["developer", "student"].includes(user.type)) return exams; if (!["developer", "student"].includes(user.type)) return exams;

View File

@@ -1,8 +1,9 @@
import {app} from "@/firebase"; import {app} from "@/firebase";
import {CorporateUser, Group, MasterCorporateUser, StudentUser, TeacherUser, User} from "@/interfaces/user"; import {Assignment} from "@/interfaces/results";
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 {getUser} from "./users.be"; import {getLinkedUsers, getUser} from "./users.be";
import {getSpecificUsers} from "./users.be"; import {getSpecificUsers} from "./users.be";
const db = client.db(process.env.MONGODB_DB); const db = client.db(process.env.MONGODB_DB);
@@ -70,18 +71,11 @@ 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 groups = await getUserGroups(corporateID); const linkedTeachers = await getLinkedUsers(corporateID, type, "teacher");
const groupUsers = (await Promise.all(groups.map(async (g) => await Promise.all(g.participants.map(getUser))))) const linkedCorporates = await getLinkedUsers(corporateID, type, "corporate");
.flat()
.filter((x) => !!x) as User[];
const teacherPromises = await Promise.all(
groupUsers.map(async (u) =>
u.type === "teacher" ? u.id : u.type === "corporate" ? [...(await getAllAssignersByCorporate(u.id)), u.id] : undefined,
),
);
return teacherPromises.filter((x) => !!x).flat() as string[]; return [...linkedTeachers.users.map((x) => x.id), ...linkedCorporates.users.map((x) => x.id)];
}; };
export const getGroupsForUser = async (admin?: string, participant?: string) => { export const getGroupsForUser = async (admin?: string, participant?: string) => {

View File

@@ -1,4 +1,3 @@
/*fields example = [ /*fields example = [
['id'], ['id'],
['companyInformation', 'companyInformation', 'name'] ['companyInformation', 'companyInformation', 'name']
@@ -13,17 +12,17 @@ const getFieldValue = (fields: string[], data: any): string => {
}; };
export const search = (text: string, fields: string[][], rows: any[]) => { export const search = (text: string, fields: string[][], rows: any[]) => {
const searchText = text.toLowerCase(); const searchText = text.toLowerCase();
return rows.filter((row) => { return rows.filter((row) => {
return fields.some((fieldsKeys) => { return fields.some((fieldsKeys) => {
const value = getFieldValue(fieldsKeys, row); const value = getFieldValue(fieldsKeys, row);
if (typeof value === "string") { if (typeof value === "string") {
return value.toLowerCase().includes(searchText); return value.toLowerCase().includes(searchText);
} }
if (typeof value === "number") { if (typeof value === "number") {
return (value as Number).toString().includes(searchText); return (value as Number).toString().includes(searchText);
} }
}); });
}); });
} };

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>({}).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();
} }
@@ -56,7 +56,7 @@ export async function getLinkedUsers(
const participants = uniq([ const participants = uniq([
...adminGroups.flatMap((x) => x.participants), ...adminGroups.flatMap((x) => x.participants),
...groups.flat().flatMap((x) => x.participants), ...(userType === "mastercorporate" ? groups.flat().flatMap((x) => x.participants) : []),
...(userType === "teacher" ? belongingGroups.flatMap((x) => x.participants) : []), ...(userType === "teacher" ? belongingGroups.flatMap((x) => x.participants) : []),
]); ]);