Compare commits
3 Commits
bugfix/mon
...
22209ee1c1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22209ee1c1 | ||
|
|
0e2f53db0a | ||
|
|
9177a6b2ac |
@@ -1,12 +1,22 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import Modal from "@/components/Modal";
|
||||
import useFilterRecordsByUser from "@/hooks/useFilterRecordsByUser";
|
||||
import useUsers, {userHashStudent, userHashTeacher, userHashCorporate} from "@/hooks/useUsers";
|
||||
import {CorporateUser, Group, MasterCorporateUser, Stat, User} from "@/interfaces/user";
|
||||
import useUsers, {
|
||||
userHashStudent,
|
||||
userHashTeacher,
|
||||
userHashCorporate,
|
||||
} from "@/hooks/useUsers";
|
||||
import {
|
||||
CorporateUser,
|
||||
Group,
|
||||
MasterCorporateUser,
|
||||
Stat,
|
||||
User,
|
||||
} from "@/interfaces/user";
|
||||
import UserList from "@/pages/(admin)/Lists/UserList";
|
||||
import {dateSorter} from "@/utils";
|
||||
import { dateSorter } from "@/utils";
|
||||
import moment from "moment";
|
||||
import {useEffect, useMemo, useState} from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
BsArrowLeft,
|
||||
BsClipboard2Data,
|
||||
@@ -30,32 +40,40 @@ import {
|
||||
} from "react-icons/bs";
|
||||
import UserCard from "@/components/UserCard";
|
||||
import useGroups from "@/hooks/useGroups";
|
||||
import {averageLevelCalculator, calculateAverageLevel, calculateBandScore} from "@/utils/score";
|
||||
import {MODULE_ARRAY} from "@/utils/moduleUtils";
|
||||
import {Module} from "@/interfaces";
|
||||
import {groupByExam} from "@/utils/stats";
|
||||
import {
|
||||
averageLevelCalculator,
|
||||
calculateAverageLevel,
|
||||
calculateBandScore,
|
||||
} from "@/utils/score";
|
||||
import { MODULE_ARRAY } from "@/utils/moduleUtils";
|
||||
import { Module } from "@/interfaces";
|
||||
import { groupByExam } from "@/utils/stats";
|
||||
import IconCard from "../IconCard";
|
||||
import GroupList from "@/pages/(admin)/Lists/GroupList";
|
||||
import useFilterStore from "@/stores/listFilterStore";
|
||||
import {useRouter} from "next/router";
|
||||
import { useRouter } from "next/router";
|
||||
import useCodes from "@/hooks/useCodes";
|
||||
import {getUserCorporate} from "@/utils/groups";
|
||||
import { getUserCorporate } from "@/utils/groups";
|
||||
import useAssignments from "@/hooks/useAssignments";
|
||||
import {Assignment} from "@/interfaces/results";
|
||||
import { Assignment } from "@/interfaces/results";
|
||||
import AssignmentView from "../AssignmentView";
|
||||
import AssignmentCreator from "../AssignmentCreator";
|
||||
import clsx from "clsx";
|
||||
import AssignmentCard from "../AssignmentCard";
|
||||
import {createColumnHelper} from "@tanstack/react-table";
|
||||
import { createColumnHelper } from "@tanstack/react-table";
|
||||
import Checkbox from "@/components/Low/Checkbox";
|
||||
import List from "@/components/List";
|
||||
import {getUserCompanyName} from "@/resources/user";
|
||||
import {futureAssignmentFilter, pastAssignmentFilter, archivedAssignmentFilter, activeAssignmentFilter} from "@/utils/assignments";
|
||||
import { getUserCompanyName } from "@/resources/user";
|
||||
import {
|
||||
futureAssignmentFilter,
|
||||
pastAssignmentFilter,
|
||||
archivedAssignmentFilter,
|
||||
activeAssignmentFilter,
|
||||
} from "@/utils/assignments";
|
||||
import useUserBalance from "@/hooks/useUserBalance";
|
||||
import AssignmentsPage from "../views/AssignmentsPage";
|
||||
import StudentPerformancePage from "./StudentPerformancePage";
|
||||
import MasterStatistical from "../MasterCorporate/MasterStatistical";
|
||||
import MasterStatisticalPage from "./MasterStatisticalPage";
|
||||
|
||||
interface Props {
|
||||
user: CorporateUser;
|
||||
@@ -74,22 +92,42 @@ const teacherHash = {
|
||||
size: 25,
|
||||
};
|
||||
|
||||
export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||
export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
|
||||
const {data: stats} = useFilterRecordsByUser<Stat[]>();
|
||||
const {groups} = useGroups({admin: user.id});
|
||||
const {assignments, isLoading: isAssignmentsLoading, reload: reloadAssignments} = useAssignments({corporate: user.id});
|
||||
const {balance} = useUserBalance();
|
||||
const { data: stats } = useFilterRecordsByUser<Stat[]>();
|
||||
const { groups } = useGroups({ admin: user.id });
|
||||
const {
|
||||
assignments,
|
||||
isLoading: isAssignmentsLoading,
|
||||
reload: reloadAssignments,
|
||||
} = useAssignments({ corporate: user.id });
|
||||
const { balance } = useUserBalance();
|
||||
|
||||
const {users: students, total: totalStudents, reload: reloadStudents, isLoading: isStudentsLoading} = useUsers(studentHash);
|
||||
const {users: teachers, total: totalTeachers, reload: reloadTeachers, isLoading: isTeachersLoading} = useUsers(teacherHash);
|
||||
const {
|
||||
users: students,
|
||||
total: totalStudents,
|
||||
reload: reloadStudents,
|
||||
isLoading: isStudentsLoading,
|
||||
} = useUsers(studentHash);
|
||||
const {
|
||||
users: teachers,
|
||||
total: totalTeachers,
|
||||
reload: reloadTeachers,
|
||||
isLoading: isTeachersLoading,
|
||||
} = useUsers(teacherHash);
|
||||
|
||||
const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
|
||||
const router = useRouter();
|
||||
|
||||
const 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(
|
||||
() =>
|
||||
@@ -99,22 +137,28 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||
.filter((g) => g.admin === selectedUser.id)
|
||||
.flatMap((g) => g.participants)
|
||||
.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(() => {
|
||||
setShowModal(!!selectedUser && router.asPath === "/#");
|
||||
}, [selectedUser, router.asPath]);
|
||||
|
||||
const getStatsByStudent = (user: User) => stats.filter((s) => s.user === user.id);
|
||||
const getStatsByStudent = (user: User) =>
|
||||
stats.filter((s) => s.user === user.id);
|
||||
|
||||
const UserDisplay = (displayUser: User) => (
|
||||
<div
|
||||
onClick={() => setSelectedUser(displayUser)}
|
||||
className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300">
|
||||
<img src={displayUser.profilePicture} alt={displayUser.name} className="rounded-full w-10 h-10" />
|
||||
className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300"
|
||||
>
|
||||
<img
|
||||
src={displayUser.profilePicture}
|
||||
alt={displayUser.name}
|
||||
className="rounded-full w-10 h-10"
|
||||
/>
|
||||
<div className="flex flex-col gap-1 items-start">
|
||||
<span>{displayUser.name}</span>
|
||||
<span className="text-sm opacity-75">{displayUser.email}</span>
|
||||
@@ -122,19 +166,59 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||
</div>
|
||||
);
|
||||
|
||||
// this workaround will allow us toreuse the master statistical due to master corporate restraints
|
||||
// while still being able to use the corporate user
|
||||
const groupedByNameCorporateIds = useMemo(
|
||||
() => ({
|
||||
[user.corporateInformation?.companyInformation?.name || user.name]: [
|
||||
user.id,
|
||||
],
|
||||
}),
|
||||
[user]
|
||||
);
|
||||
const teachersAndStudents = useMemo(
|
||||
() => [...students, ...teachers],
|
||||
[students, teachers]
|
||||
);
|
||||
const MasterStatisticalPage = () => {
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => router.push("/")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
|
||||
>
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">Master Statistical</h2>
|
||||
</div>
|
||||
<MasterStatistical
|
||||
users={teachersAndStudents}
|
||||
corporateUsers={groupedByNameCorporateIds}
|
||||
displaySelection={false}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const GroupsList = () => {
|
||||
const filter = (x: Group) => x.admin === user.id || x.participants.includes(user.id);
|
||||
const filter = (x: Group) =>
|
||||
x.admin === user.id || x.participants.includes(user.id);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => router.push("/")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||
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>
|
||||
<h2 className="text-2xl font-semibold">
|
||||
Groups ({groups.filter(filter).length})
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<GroupList user={user} />
|
||||
@@ -152,10 +236,15 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||
.filter((f) => !!f.focus);
|
||||
const bandScores = formattedStats.map((s) => ({
|
||||
module: s.module,
|
||||
level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!),
|
||||
level: calculateBandScore(
|
||||
s.score.correct,
|
||||
s.score.total,
|
||||
s.module,
|
||||
s.focus!
|
||||
),
|
||||
}));
|
||||
|
||||
const levels: {[key in Module]: number} = {
|
||||
const levels: { [key in Module]: number } = {
|
||||
reading: 0,
|
||||
listening: 0,
|
||||
writing: 0,
|
||||
@@ -176,7 +265,8 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||
<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">
|
||||
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>
|
||||
@@ -195,7 +285,8 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||
<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">
|
||||
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>
|
||||
@@ -206,7 +297,8 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||
);
|
||||
|
||||
if (router.asPath === "/#groups") return <GroupsList />;
|
||||
if (router.asPath === "/#studentsPerformance") return <StudentPerformancePage user={user} />;
|
||||
if (router.asPath === "/#studentsPerformance")
|
||||
return <StudentPerformancePage user={user} />;
|
||||
|
||||
if (router.asPath === "/#assignments")
|
||||
return (
|
||||
@@ -220,7 +312,7 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||
/>
|
||||
);
|
||||
|
||||
if (router.asPath === "/#statistical") return <MasterStatisticalPage user={user} />;
|
||||
if (router.asPath === "/#statistical") return <MasterStatisticalPage />;
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -232,11 +324,14 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||
loggedInUser={user}
|
||||
onClose={(shouldReload) => {
|
||||
setSelectedUser(undefined);
|
||||
if (shouldReload && selectedUser!.type === "student") reloadStudents();
|
||||
if (shouldReload && selectedUser!.type === "teacher") reloadTeachers();
|
||||
if (shouldReload && selectedUser!.type === "student")
|
||||
reloadStudents();
|
||||
if (shouldReload && selectedUser!.type === "teacher")
|
||||
reloadTeachers();
|
||||
}}
|
||||
onViewStudents={
|
||||
selectedUser.type === "corporate" || selectedUser.type === "teacher"
|
||||
selectedUser.type === "corporate" ||
|
||||
selectedUser.type === "teacher"
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-students",
|
||||
@@ -246,7 +341,11 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||
id: "belongs-to-admin",
|
||||
filter: (x: User) =>
|
||||
groups
|
||||
.filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id))
|
||||
.filter(
|
||||
(g) =>
|
||||
g.admin === selectedUser.id ||
|
||||
g.participants.includes(selectedUser.id)
|
||||
)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id),
|
||||
});
|
||||
@@ -256,7 +355,8 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||
: undefined
|
||||
}
|
||||
onViewTeachers={
|
||||
selectedUser.type === "corporate" || selectedUser.type === "student"
|
||||
selectedUser.type === "corporate" ||
|
||||
selectedUser.type === "student"
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-teachers",
|
||||
@@ -266,7 +366,11 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||
id: "belongs-to-admin",
|
||||
filter: (x: User) =>
|
||||
groups
|
||||
.filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id))
|
||||
.filter(
|
||||
(g) =>
|
||||
g.admin === selectedUser.id ||
|
||||
g.participants.includes(selectedUser.id)
|
||||
)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id),
|
||||
});
|
||||
@@ -285,7 +389,11 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||
<>
|
||||
{!!linkedCorporate && (
|
||||
<div className="absolute top-4 right-4 bg-neutral-200 px-2 rounded-lg py-1">
|
||||
Linked to: <b>{linkedCorporate?.corporateInformation?.companyInformation.name || linkedCorporate.name}</b>
|
||||
Linked to:{" "}
|
||||
<b>
|
||||
{linkedCorporate?.corporateInformation?.companyInformation.name ||
|
||||
linkedCorporate.name}
|
||||
</b>
|
||||
</div>
|
||||
)}
|
||||
<section className="grid grid-cols-5 -md:grid-cols-2 gap-4 text-center">
|
||||
@@ -308,27 +416,47 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||
<IconCard
|
||||
Icon={BsClipboard2Data}
|
||||
label="Exams Performed"
|
||||
value={stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user)).length}
|
||||
value={
|
||||
stats.filter((s) =>
|
||||
groups.flatMap((g) => g.participants).includes(s.user)
|
||||
).length
|
||||
}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsPaperclip}
|
||||
isLoading={isStudentsLoading}
|
||||
label="Average Level"
|
||||
value={averageLevelCalculator(stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user))).toFixed(1)}
|
||||
value={averageLevelCalculator(
|
||||
stats.filter((s) =>
|
||||
groups.flatMap((g) => g.participants).includes(s.user)
|
||||
)
|
||||
).toFixed(1)}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => router.push("/#groups")}
|
||||
Icon={BsPeople}
|
||||
label="Groups"
|
||||
value={groups.length}
|
||||
color="purple"
|
||||
/>
|
||||
<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}`}
|
||||
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"}
|
||||
value={
|
||||
user.subscriptionExpirationDate
|
||||
? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy")
|
||||
: "Unlimited"
|
||||
}
|
||||
color="rose"
|
||||
/>
|
||||
<IconCard
|
||||
@@ -339,16 +467,24 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||
color="purple"
|
||||
onClick={() => router.push("/#studentsPerformance")}
|
||||
/>
|
||||
<IconCard Icon={BsDatabase} label="Master Statistical" color="purple" onClick={() => router.push("/#statistical")} />
|
||||
<IconCard
|
||||
Icon={BsDatabase}
|
||||
label="Master Statistical"
|
||||
color="purple"
|
||||
onClick={() => router.push("/#statistical")}
|
||||
/>
|
||||
<button
|
||||
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">
|
||||
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}
|
||||
{isAssignmentsLoading
|
||||
? "Loading..."
|
||||
: assignments.filter((a) => !a.archived).length}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
@@ -379,7 +515,11 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||
<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))
|
||||
.sort(
|
||||
(a, b) =>
|
||||
calculateAverageLevel(b.levels) -
|
||||
calculateAverageLevel(a.levels)
|
||||
)
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
@@ -391,7 +531,8 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||
{students
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Object.keys(groupByExam(getStatsByStudent(b))).length - Object.keys(groupByExam(getStatsByStudent(a))).length,
|
||||
Object.keys(groupByExam(getStatsByStudent(b))).length -
|
||||
Object.keys(groupByExam(getStatsByStudent(a))).length
|
||||
)
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, {useEffect, useMemo, useState} from "react";
|
||||
import {CorporateUser, StudentUser, User} from "@/interfaces/user";
|
||||
import {CorporateUser, User} from "@/interfaces/user";
|
||||
import {BsFileExcel, BsBank, BsPersonFill} from "react-icons/bs";
|
||||
import IconCard from "../IconCard";
|
||||
|
||||
@@ -28,7 +28,7 @@ interface Props {
|
||||
}
|
||||
|
||||
interface TableData {
|
||||
user: User | undefined;
|
||||
user: string;
|
||||
email: string;
|
||||
correct: number;
|
||||
corporate: string;
|
||||
@@ -62,7 +62,7 @@ const MasterStatistical = (props: Props) => {
|
||||
const [startDate, setStartDate] = React.useState<Date | null>(moment("01/01/2023").toDate());
|
||||
const [endDate, setEndDate] = React.useState<Date | null>(moment().endOf("year").toDate());
|
||||
|
||||
const {assignments, isLoading} = useAssignmentsCorporates({
|
||||
const {assignments} = useAssignmentsCorporates({
|
||||
corporates: selectedCorporates,
|
||||
startDate,
|
||||
endDate,
|
||||
@@ -74,11 +74,11 @@ const MasterStatistical = (props: Props) => {
|
||||
() =>
|
||||
assignments.reduce((accmA: TableData[], a: AssignmentWithCorporateId) => {
|
||||
const userResults = a.assignees.map((assignee) => {
|
||||
const userData = users.find((u) => u.id === assignee);
|
||||
const userStats = a.results.find((r) => r.user === assignee)?.stats || [];
|
||||
const userData = users.find((u) => u.id === assignee);
|
||||
const corporate = getUserName(users.find((u) => u.id === a.assigner));
|
||||
const commonData = {
|
||||
user: userData,
|
||||
user: userData?.name || "N/A",
|
||||
email: userData?.email || "N/A",
|
||||
userId: assignee,
|
||||
corporateId: a.corporateId,
|
||||
@@ -86,7 +86,6 @@ const MasterStatistical = (props: Props) => {
|
||||
corporate,
|
||||
assignment: a.name,
|
||||
};
|
||||
|
||||
if (userStats.length === 0) {
|
||||
return {
|
||||
...commonData,
|
||||
@@ -109,6 +108,8 @@ const MasterStatistical = (props: Props) => {
|
||||
[assignments, users],
|
||||
);
|
||||
|
||||
useEffect(() => console.log(assignments), [assignments]);
|
||||
|
||||
const getCorporateScores = (corporateId: string): UserCount => {
|
||||
const corporateAssignmentsUsers = assignments.filter((a) => a.corporateId === corporateId).reduce((acc, a) => acc + a.assignees.length, 0);
|
||||
|
||||
@@ -150,7 +151,7 @@ const MasterStatistical = (props: Props) => {
|
||||
header: "User",
|
||||
id: "user",
|
||||
cell: (info) => {
|
||||
return <span>{info.getValue()?.name || "N/A"}</span>;
|
||||
return <span>{info.getValue()}</span>;
|
||||
},
|
||||
}),
|
||||
columnHelper.accessor("email", {
|
||||
@@ -160,13 +161,6 @@ const MasterStatistical = (props: Props) => {
|
||||
return <span>{info.getValue()}</span>;
|
||||
},
|
||||
}),
|
||||
columnHelper.accessor("user", {
|
||||
header: "Student ID",
|
||||
id: "studentID",
|
||||
cell: (info) => {
|
||||
return <span>{(info.getValue() as StudentUser)?.studentID || "N/A"}</span>;
|
||||
},
|
||||
}),
|
||||
...(displaySelection
|
||||
? [
|
||||
columnHelper.accessor("corporate", {
|
||||
@@ -287,7 +281,6 @@ const MasterStatistical = (props: Props) => {
|
||||
<IconCard
|
||||
Icon={BsBank}
|
||||
label="Consolidate"
|
||||
isLoading={isLoading}
|
||||
value={getConsolidateScoreStr(consolidateScore)}
|
||||
color="purple"
|
||||
onClick={() => {
|
||||
@@ -309,7 +302,6 @@ const MasterStatistical = (props: Props) => {
|
||||
<IconCard
|
||||
key={corporateName}
|
||||
Icon={BsBank}
|
||||
isLoading={isLoading}
|
||||
label={corporateName}
|
||||
value={value}
|
||||
color="purple"
|
||||
@@ -351,7 +343,7 @@ const MasterStatistical = (props: Props) => {
|
||||
</div>
|
||||
{renderSearch()}
|
||||
<div className="flex flex-col gap-3 justify-end">
|
||||
<Button className="w-[200px] h-[70px]" variant="outline" isLoading={downloading} onClick={triggerDownload}>
|
||||
<Button className="max-w-[200px] h-[70px]" variant="outline" onClick={triggerDownload}>
|
||||
Download
|
||||
</Button>
|
||||
</div>
|
||||
@@ -367,7 +359,7 @@ const MasterStatistical = (props: Props) => {
|
||||
{page * SIZE + 1} - {(page + 1) * SIZE > filteredRows.length ? filteredRows.length : (page + 1) * SIZE} /{" "}
|
||||
{filteredRows.length}
|
||||
</span>
|
||||
<Button className="w-[200px]" disabled={(page + 1) * SIZE >= filteredRows.length} onClick={() => setPage((prev) => prev + 1)}>
|
||||
<Button className="w-[200px]" disabled={(page + 1) * SIZE >= rows.length} onClick={() => setPage((prev) => prev + 1)}>
|
||||
Next Page
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -55,7 +55,7 @@ export default function AssignmentsPage({assignments, corporateAssignments, user
|
||||
<AssignmentCreator
|
||||
assignment={selectedAssignment}
|
||||
groups={groups}
|
||||
users={[...users, user]}
|
||||
users={users}
|
||||
user={user}
|
||||
isCreating={isCreatingAssignment}
|
||||
cancelCreation={() => {
|
||||
|
||||
@@ -287,9 +287,7 @@ export default function Finish({user, scores, modules, information, solutions, i
|
||||
<div className="flex w-fit cursor-pointer flex-col items-center gap-1">
|
||||
<button
|
||||
onClick={() => window.location.reload()}
|
||||
// disabled={user.type === "admin"}
|
||||
// TODO: temporarily disabled
|
||||
disabled
|
||||
disabled={user.type === "admin"}
|
||||
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" />
|
||||
</button>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {useState, useMemo} from "react";
|
||||
import Input from "@/components/Low/Input";
|
||||
import {search} from "@/utils/search";
|
||||
import { search } from "@/utils/search";
|
||||
|
||||
export function useListSearch<T>(fields: string[][], rows: T[]) {
|
||||
const [text, setText] = useState("");
|
||||
@@ -8,8 +8,7 @@ export function useListSearch<T>(fields: string[][], rows: T[]) {
|
||||
const renderSearch = () => <Input label="Search" type="text" name="search" onChange={setText} placeholder="Enter search text" value={text} />;
|
||||
|
||||
const updatedRows = useMemo(() => {
|
||||
if (text.length > 0) return search(text, fields, rows);
|
||||
return rows;
|
||||
return search(text, fields, rows);
|
||||
}, [fields, rows, text]);
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import Button from "@/components/Low/Button";
|
||||
import {useMemo, useState} from "react";
|
||||
|
||||
export default function usePagination<T>(list: T[], size = 25) {
|
||||
const [page, setPage] = useState(0);
|
||||
|
||||
const items = useMemo(() => list.slice(page * size, (page + 1) * size), [page, size, list]);
|
||||
|
||||
const render = () => (
|
||||
<div className="w-full flex gap-2 justify-between items-center">
|
||||
<div className="flex items-center gap-4 w-fit">
|
||||
<Button className="w-[200px] h-fit" disabled={page === 0} onClick={() => setPage((prev) => prev - 1)}>
|
||||
Previous Page
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 w-fit">
|
||||
<span className="opacity-80">
|
||||
{page * size + 1} - {(page + 1) * size > list.length ? list.length : (page + 1) * size} / {list.length}
|
||||
</span>
|
||||
<Button className="w-[200px]" disabled={(page + 1) * size >= list.length} onClick={() => setPage((prev) => prev + 1)}>
|
||||
Next Page
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return {page, items, setPage, render};
|
||||
}
|
||||
@@ -9,7 +9,7 @@ export const userHashStudent = {type: "student"} as {type: Type};
|
||||
export const userHashTeacher = {type: "teacher"} as {type: Type};
|
||||
export const userHashCorporate = {type: "corporate"} as {type: Type};
|
||||
|
||||
export default function useUsers(props?: {type?: string; page?: number; size?: number; orderBy?: string; direction?: "asc" | "desc"}) {
|
||||
export default function useUsers(props?: {type?: string; page?: number; size?: number; orderBy?: string; direction?: "asc" | "desc", searchTerm?: string | undefined}) {
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
@@ -23,6 +23,8 @@ export default function useUsers(props?: {type?: string; page?: number; size?: n
|
||||
if (props[key as keyof typeof props] !== undefined) params.append(key, props[key as keyof typeof props]!.toString());
|
||||
});
|
||||
|
||||
console.log(params.toString());
|
||||
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.get<{users: User[]; total: number}>(`/api/users/list?${params.toString()}`, {headers: {page: "register"}})
|
||||
@@ -33,7 +35,7 @@ export default function useUsers(props?: {type?: string; page?: number; size?: n
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
useEffect(getData, [props?.page, props?.size, props?.type, props?.orderBy, props?.direction]);
|
||||
useEffect(getData, [props?.page, props?.size, props?.type, props?.orderBy, props?.direction, props?.searchTerm]);
|
||||
|
||||
return {users, total, isLoading, isError, reload: getData};
|
||||
}
|
||||
|
||||
@@ -1,34 +1,34 @@
|
||||
import Button from "@/components/Low/Button";
|
||||
import {PERMISSIONS} from "@/constants/userPermissions";
|
||||
import { PERMISSIONS } from "@/constants/userPermissions";
|
||||
import useGroups from "@/hooks/useGroups";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import {Type, User, userTypes, CorporateUser, Group} from "@/interfaces/user";
|
||||
import {Popover, Transition} from "@headlessui/react";
|
||||
import {createColumnHelper, flexRender, getCoreRowModel, useReactTable} from "@tanstack/react-table";
|
||||
import { Type, User, userTypes, CorporateUser, Group } from "@/interfaces/user";
|
||||
import { Popover, Transition } from "@headlessui/react";
|
||||
import { createColumnHelper, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table";
|
||||
import axios from "axios";
|
||||
import clsx from "clsx";
|
||||
import {capitalize, reverse} from "lodash";
|
||||
import { capitalize, reverse } from "lodash";
|
||||
import moment from "moment";
|
||||
import {Fragment, useEffect, useState, useMemo} from "react";
|
||||
import {BsArrowDown, BsArrowDownUp, BsArrowUp, BsCheck, BsCheckCircle, BsEye, BsFillExclamationOctagonFill, BsPerson, BsTrash} from "react-icons/bs";
|
||||
import {toast} from "react-toastify";
|
||||
import {countries, TCountries} from "countries-list";
|
||||
import { Fragment, useEffect, useState, useMemo } from "react";
|
||||
import { BsArrowDown, BsArrowDownUp, BsArrowUp, BsCheck, BsCheckCircle, BsEye, BsFillExclamationOctagonFill, BsPerson, BsTrash } from "react-icons/bs";
|
||||
import { toast } from "react-toastify";
|
||||
import { countries, TCountries } from "countries-list";
|
||||
import countryCodes from "country-codes-list";
|
||||
import Modal from "@/components/Modal";
|
||||
import UserCard from "@/components/UserCard";
|
||||
import {getUserCompanyName, isAgentUser, USER_TYPE_LABELS} from "@/resources/user";
|
||||
import { getUserCompanyName, isAgentUser, USER_TYPE_LABELS } from "@/resources/user";
|
||||
import useFilterStore from "@/stores/listFilterStore";
|
||||
import {useRouter} from "next/router";
|
||||
import {isCorporateUser} from "@/resources/user";
|
||||
import {useListSearch} from "@/hooks/useListSearch";
|
||||
import {getUserCorporate} from "@/utils/groups";
|
||||
import {asyncSorter} from "@/utils";
|
||||
import {exportListToExcel, UserListRow} from "@/utils/users";
|
||||
import {checkAccess} from "@/utils/permissions";
|
||||
import {PermissionType} from "@/interfaces/permissions";
|
||||
import { useRouter } from "next/router";
|
||||
import { isCorporateUser } from "@/resources/user";
|
||||
import { useListSearch } from "@/hooks/useListSearch";
|
||||
import { getUserCorporate } from "@/utils/groups";
|
||||
import { asyncSorter } from "@/utils";
|
||||
import { exportListToExcel, UserListRow } from "@/utils/users";
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
import { PermissionType } from "@/interfaces/permissions";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
import useUserBalance from "@/hooks/useUserBalance";
|
||||
import usePagination from "@/hooks/usePagination";
|
||||
import Input from "@/components/Low/Input";
|
||||
const columnHelper = createColumnHelper<User>();
|
||||
const searchFields = [["name"], ["email"], ["corporateInformation", "companyInformation", "name"]];
|
||||
|
||||
@@ -63,15 +63,11 @@ export default function UserList({
|
||||
const [sorter, setSorter] = useState<string>();
|
||||
const [displayUsers, setDisplayUsers] = useState<User[]>([]);
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
const [page, setPage] = useState(0);
|
||||
const [searchTerm, setSearchTerm] = useState<string | undefined>(undefined);
|
||||
|
||||
const userHash = useMemo(
|
||||
() => ({
|
||||
type,
|
||||
}),
|
||||
[type],
|
||||
);
|
||||
const { users, total, isLoading, reload } = useUsers({type: type, size: 16, page: page, searchTerm: searchTerm});
|
||||
|
||||
const {users, total, isLoading, reload} = useUsers(userHash);
|
||||
const {users: corporates} = useUsers(corporatesHash);
|
||||
|
||||
const totalUsers = useMemo(() => [...users, ...corporates], [users, corporates]);
|
||||
@@ -100,9 +96,9 @@ export default function UserList({
|
||||
(async () => {
|
||||
if (users && users.length > 0) {
|
||||
const filteredUsers = filters.reduce((d, f) => d.filter(f), users);
|
||||
// const sortedUsers = await asyncSorter<User>(filteredUsers, sortFunction);
|
||||
const sortedUsers = await asyncSorter<User>(filteredUsers, sortFunction);
|
||||
|
||||
setDisplayUsers([...filteredUsers]);
|
||||
setDisplayUsers([...sortedUsers]);
|
||||
}
|
||||
})();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
@@ -112,20 +108,20 @@ export default function UserList({
|
||||
if (!confirm(`Are you sure you want to delete ${user.name}'s account?`)) return;
|
||||
|
||||
axios
|
||||
.delete<{ok: boolean}>(`/api/user?id=${user.id}`)
|
||||
.delete<{ ok: boolean }>(`/api/user?id=${user.id}`)
|
||||
.then(() => {
|
||||
toast.success("User deleted successfully!");
|
||||
reload();
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error("Something went wrong!", {toastId: "delete-error"});
|
||||
toast.error("Something went wrong!", { toastId: "delete-error" });
|
||||
})
|
||||
.finally(reload);
|
||||
};
|
||||
|
||||
const verifyAccount = (user: User) => {
|
||||
axios
|
||||
.post<{user?: User; ok?: boolean}>(`/api/users/update?id=${user.id}`, {
|
||||
.post<{ user?: User; ok?: boolean }>(`/api/users/update?id=${user.id}`, {
|
||||
...user,
|
||||
isVerified: true,
|
||||
})
|
||||
@@ -134,22 +130,21 @@ export default function UserList({
|
||||
reload();
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error("Something went wrong!", {toastId: "update-error"});
|
||||
toast.error("Something went wrong!", { toastId: "update-error" });
|
||||
});
|
||||
};
|
||||
|
||||
const toggleDisableAccount = (user: User) => {
|
||||
if (
|
||||
!confirm(
|
||||
`Are you sure you want to ${user.status === "disabled" ? "enable" : "disable"} ${
|
||||
user.name
|
||||
`Are you sure you want to ${user.status === "disabled" ? "enable" : "disable"} ${user.name
|
||||
}'s account? This change is usually related to their payment state.`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
axios
|
||||
.post<{user?: User; ok?: boolean}>(`/api/users/update?id=${user.id}`, {
|
||||
.post<{ user?: User; ok?: boolean }>(`/api/users/update?id=${user.id}`, {
|
||||
...user,
|
||||
status: user.status === "disabled" ? "active" : "disabled",
|
||||
})
|
||||
@@ -158,18 +153,18 @@ export default function UserList({
|
||||
reload();
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error("Something went wrong!", {toastId: "update-error"});
|
||||
toast.error("Something went wrong!", { toastId: "update-error" });
|
||||
});
|
||||
};
|
||||
|
||||
const SorterArrow = ({name}: {name: string}) => {
|
||||
const SorterArrow = ({ name }: { name: string }) => {
|
||||
if (sorter === name) return <BsArrowUp />;
|
||||
if (sorter === reverseString(name)) return <BsArrowDown />;
|
||||
|
||||
return <BsArrowDownUp />;
|
||||
};
|
||||
|
||||
const actionColumn = ({row}: {row: {original: User}}) => {
|
||||
const actionColumn = ({ row }: { row: { original: User } }) => {
|
||||
const updateUserPermission = PERMISSIONS.updateUser[row.original.type] as {
|
||||
list: Type[];
|
||||
perm: PermissionType;
|
||||
@@ -214,7 +209,7 @@ export default function UserList({
|
||||
<SorterArrow name="name" />
|
||||
</button>
|
||||
) as any,
|
||||
cell: ({row, getValue}) => (
|
||||
cell: ({ row, getValue }) => (
|
||||
<div
|
||||
className={clsx(
|
||||
checkAccess(user, ["admin", "corporate", "developer", "mastercorporate"]) &&
|
||||
@@ -236,8 +231,7 @@ export default function UserList({
|
||||
) as any,
|
||||
cell: (info) =>
|
||||
info.getValue()
|
||||
? `${countryCodes.findOne("countryCode" as any, info.getValue())?.flag} ${
|
||||
countries[info.getValue() as unknown as keyof TCountries]?.name
|
||||
? `${countryCodes.findOne("countryCode" as any, info.getValue())?.flag} ${countries[info.getValue() as unknown as keyof TCountries]?.name
|
||||
} (+${countryCodes.findOne("countryCode" as any, info.getValue())?.countryCallingCode})`
|
||||
: "N/A",
|
||||
}),
|
||||
@@ -304,7 +298,7 @@ export default function UserList({
|
||||
<SorterArrow name="name" />
|
||||
</button>
|
||||
) as any,
|
||||
cell: ({row, getValue}) => (
|
||||
cell: ({ row, getValue }) => (
|
||||
<div
|
||||
className={clsx(
|
||||
checkAccess(user, ["admin", "corporate", "developer", "mastercorporate"]) &&
|
||||
@@ -324,7 +318,7 @@ export default function UserList({
|
||||
<SorterArrow name="email" />
|
||||
</button>
|
||||
) as any,
|
||||
cell: ({row, getValue}) => (
|
||||
cell: ({ row, getValue }) => (
|
||||
<div
|
||||
className={clsx(
|
||||
PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type) &&
|
||||
@@ -511,23 +505,17 @@ export default function UserList({
|
||||
return a.id.localeCompare(b.id);
|
||||
};
|
||||
|
||||
const {rows: filteredRows, renderSearch, text: searchText} = useListSearch<User>(searchFields, displayUsers);
|
||||
const {items, setPage, render: renderPagination} = usePagination<User>(filteredRows, 16);
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
useEffect(() => setPage(0), [searchText]);
|
||||
|
||||
const table = useReactTable({
|
||||
data: items,
|
||||
data: displayUsers,
|
||||
columns: (!showDemographicInformation ? defaultColumns : demographicColumns) as any,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
|
||||
const downloadExcel = () => {
|
||||
const csv = exportListToExcel(filteredRows, users, groups);
|
||||
const csv = exportListToExcel(displayUsers, users, groups);
|
||||
|
||||
const element = document.createElement("a");
|
||||
const file = new Blob([csv], {type: "text/csv"});
|
||||
const file = new Blob([csv], { type: "text/csv" });
|
||||
element.href = URL.createObjectURL(file);
|
||||
element.download = "users.csv";
|
||||
document.body.appendChild(element);
|
||||
@@ -629,12 +617,32 @@ export default function UserList({
|
||||
</Modal>
|
||||
<div className="w-full flex flex-col gap-2">
|
||||
<div className="w-full flex gap-2 items-end">
|
||||
{renderSearch()}
|
||||
<Input label="Search" type="text" name="search" onChange={setSearchTerm} placeholder="Enter search text" value={searchTerm} />
|
||||
<Button className="w-full max-w-[200px] mb-1" variant="outline" onClick={downloadExcel}>
|
||||
Download List
|
||||
</Button>
|
||||
</div>
|
||||
{renderPagination()}
|
||||
<div className="w-full flex gap-2 justify-between">
|
||||
<Button
|
||||
isLoading={isLoading}
|
||||
className="w-full max-w-[200px]"
|
||||
disabled={page === 0}
|
||||
onClick={() => setPage((prev) => prev - 1)}>
|
||||
Previous Page
|
||||
</Button>
|
||||
<div className="flex items-center gap-4 w-fit">
|
||||
<span className="opacity-80">
|
||||
{page * userHash.size + 1} - {(page + 1) * userHash.size > total ? total : (page + 1) * userHash.size} / {total}
|
||||
</span>
|
||||
<Button
|
||||
isLoading={isLoading}
|
||||
className="w-[200px]"
|
||||
disabled={(page + 1) * userHash.size >= total}
|
||||
onClick={() => setPage((prev) => prev + 1)}>
|
||||
Next Page
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<table className="rounded-xl bg-mti-purple-ultralight/40 w-full">
|
||||
<thead>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
|
||||
@@ -22,7 +22,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
async function GET(req: NextApiRequest, res: NextApiResponse) {
|
||||
const {id} = req.query as {id: string};
|
||||
|
||||
const assigners = await getAllAssignersByCorporate(id, req.session.user!.type);
|
||||
const assigners = await getAllAssignersByCorporate(id);
|
||||
const assignments = await getAssignmentsByAssigners([...assigners, id]);
|
||||
|
||||
res.status(200).json(uniqBy(assignments, "id"));
|
||||
|
||||
@@ -29,7 +29,7 @@ async function GET(req: NextApiRequest, res: NextApiResponse) {
|
||||
try {
|
||||
const idsList = ids.split(",");
|
||||
|
||||
const assignments = await getAssignmentsForCorporates(req.session.user!.type, idsList, startDateParsed, endDateParsed);
|
||||
const assignments = await getAssignmentsForCorporates(idsList, startDateParsed, endDateParsed);
|
||||
res.status(200).json(assignments);
|
||||
} catch (err: any) {
|
||||
res.status(500).json({error: err.message});
|
||||
|
||||
@@ -1,31 +1,24 @@
|
||||
import type {NextApiRequest, NextApiResponse} from "next";
|
||||
import {storage} from "@/firebase";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {ref, uploadBytes, getDownloadURL} from "firebase/storage";
|
||||
import {AssignmentWithCorporateId} from "@/interfaces/results";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { storage } from "@/firebase";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { ref, uploadBytes, getDownloadURL } from "firebase/storage";
|
||||
import { AssignmentWithCorporateId } from "@/interfaces/results";
|
||||
import moment from "moment-timezone";
|
||||
import ExcelJS from "exceljs";
|
||||
import {getSpecificUsers} from "@/utils/users.be";
|
||||
import {checkAccess} from "@/utils/permissions";
|
||||
import {getAssignmentsForCorporates} from "@/utils/assignments.be";
|
||||
import {search} from "@/utils/search";
|
||||
import {getGradingSystem} from "@/utils/grading.be";
|
||||
import {StudentUser, User} from "@/interfaces/user";
|
||||
import {calculateBandScore, getGradingLabel} from "@/utils/score";
|
||||
import {Module} from "@/interfaces";
|
||||
import {uniq} from "lodash";
|
||||
import {getUserName} from "@/utils/users";
|
||||
import {LevelExam} from "@/interfaces/exam";
|
||||
import {getSpecificExams} from "@/utils/exams.be";
|
||||
import { getSpecificUsers } from "@/utils/users.be";
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
import { getAssignmentsForCorporates } from "@/utils/assignments.be";
|
||||
import { search } from "@/utils/search";
|
||||
import { getGradingSystem } from "@/utils/grading.be";
|
||||
import { User } from "@/interfaces/user";
|
||||
import { calculateBandScore, getGradingLabel } from "@/utils/score";
|
||||
import { Module } from "@/interfaces";
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
interface TableData {
|
||||
user: string;
|
||||
studentID: string;
|
||||
passportID: string;
|
||||
exams: string;
|
||||
email: string;
|
||||
correct: number;
|
||||
corporate: string;
|
||||
@@ -47,13 +40,15 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "POST") return await post(req, res);
|
||||
}
|
||||
|
||||
const searchFilters = [["email"], ["user"], ["userId"], ["assignment"], ["exams"]];
|
||||
const searchFilters = [["email"], ["user"], ["userId"]];
|
||||
|
||||
async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
// verify if it's a logged user that is trying to export
|
||||
if (req.session.user) {
|
||||
if (!checkAccess(req.session.user, ["mastercorporate", "corporate", "developer", "admin"])) {
|
||||
return res.status(403).json({error: "Unauthorized"});
|
||||
if (
|
||||
!checkAccess(req.session.user, ["mastercorporate", "corporate", "developer", "admin"])
|
||||
) {
|
||||
return res.status(403).json({ error: "Unauthorized" });
|
||||
}
|
||||
const {
|
||||
ids,
|
||||
@@ -70,62 +65,79 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
};
|
||||
const startDateParsed = startDate ? new Date(startDate) : undefined;
|
||||
const endDateParsed = endDate ? new Date(endDate) : undefined;
|
||||
const assignments = await getAssignmentsForCorporates(req.session.user.type, ids, startDateParsed, endDateParsed);
|
||||
const assignments = await getAssignmentsForCorporates(
|
||||
ids,
|
||||
startDateParsed,
|
||||
endDateParsed
|
||||
);
|
||||
|
||||
const assignmentUsers = uniq([...assignments.flatMap((x) => x.assignees), ...assignments.flatMap((x) => x.assigner)]);
|
||||
const assignmentUsers = [
|
||||
...new Set(assignments.flatMap((a) => a.assignees)),
|
||||
];
|
||||
const assigners = [...new Set(assignments.map((a) => a.assigner))];
|
||||
const users = await getSpecificUsers(assignmentUsers);
|
||||
const assignerUsers = await getSpecificUsers(assigners);
|
||||
const exams = await getSpecificExams(uniq(assignments.flatMap((x) => x.exams.map((x) => x.id))));
|
||||
|
||||
const assignerUsersGradingSystems = await Promise.all(
|
||||
assignerUsers.map(async (user: User) => {
|
||||
const data = await getGradingSystem(user);
|
||||
// in this context I need to override as I'll have to match to the assigner
|
||||
return {...data, user: user.id};
|
||||
}),
|
||||
return { ...data, user: user.id };
|
||||
})
|
||||
);
|
||||
|
||||
const getGradingSystemHelper = (
|
||||
exams: {id: string; module: Module; assignee: string}[],
|
||||
exams: { id: string; module: Module; assignee: string }[],
|
||||
assigner: string,
|
||||
user: User,
|
||||
correct: number,
|
||||
total: number,
|
||||
total: number
|
||||
) => {
|
||||
if (exams.some((e) => e.module === "level")) {
|
||||
const gradingSystem = assignerUsersGradingSystems.find((gs) => gs.user === assigner);
|
||||
const gradingSystem = assignerUsersGradingSystems.find(
|
||||
(gs) => gs.user === assigner
|
||||
);
|
||||
if (gradingSystem) {
|
||||
const bandScore = calculateBandScore(correct, total, "level", user?.focus || "academic");
|
||||
const bandScore = calculateBandScore(
|
||||
correct,
|
||||
total,
|
||||
"level",
|
||||
user.focus
|
||||
);
|
||||
return {
|
||||
label: getGradingLabel(bandScore, gradingSystem.steps || []),
|
||||
label: getGradingLabel(bandScore, gradingSystem?.steps || []),
|
||||
score: bandScore,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {score: -1, label: "N/A"};
|
||||
return { score: -1, label: "N/A" };
|
||||
};
|
||||
|
||||
const tableResults = assignments
|
||||
.reduce((accmA: TableData[], a: AssignmentWithCorporateId) => {
|
||||
const userResults = a.assignees.map((assignee) => {
|
||||
const userStats = a.results.find((r) => r.user === assignee)?.stats || [];
|
||||
const userStats =
|
||||
a.results.find((r) => r.user === assignee)?.stats || [];
|
||||
const userData = users.find((u) => u.id === assignee);
|
||||
const corporateUser = users.find((u) => u.id === a.assigner);
|
||||
const correct = userStats.reduce((n, e) => n + e.score.correct, 0);
|
||||
const total = userStats.reduce((n, e) => n + e.score.total, 0);
|
||||
const {label: level, score} = getGradingSystemHelper(a.exams, a.assigner, userData!, correct, total);
|
||||
const { label: level, score } = getGradingSystemHelper(
|
||||
a.exams,
|
||||
a.assigner,
|
||||
userData!,
|
||||
correct,
|
||||
total
|
||||
);
|
||||
|
||||
console.log("Level", level);
|
||||
const commonData = {
|
||||
user: userData?.name || "",
|
||||
email: userData?.email || "",
|
||||
studentID: (userData as StudentUser)?.studentID || "",
|
||||
passportID: (userData as StudentUser)?.demographicInformation?.passport_id || "",
|
||||
userId: assignee,
|
||||
exams: a.exams.map((x) => x.id).join(", "),
|
||||
corporateId: a.corporateId,
|
||||
corporate: !corporateUser ? "" : getUserName(corporateUser),
|
||||
corporate: corporateUser?.name || "",
|
||||
assignment: a.name,
|
||||
level,
|
||||
score,
|
||||
@@ -139,22 +151,14 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
};
|
||||
}
|
||||
|
||||
let data: {total: number; correct: number}[] = [];
|
||||
if (a.exams.every((x) => x.module === "level")) {
|
||||
const exam = exams.find((x) => x.id === a.exams.find((x) => x.assignee === assignee)?.id) as LevelExam;
|
||||
data = exam.parts.map((x) => {
|
||||
const exerciseIDs = x.exercises.map((x) => x.id);
|
||||
const stats = userStats.filter((x) => exerciseIDs.includes(x.exercise));
|
||||
|
||||
const total = stats.reduce((acc, curr) => acc + curr.score.total, 0);
|
||||
const correct = stats.reduce((acc, curr) => acc + curr.score.correct, 0);
|
||||
|
||||
return {total, correct};
|
||||
});
|
||||
}
|
||||
|
||||
const partsData =
|
||||
data.length > 0 ? data.reduce((acc, e, index) => ({...acc, [`part${index}`]: `${e.correct}/${e.total}`}), {}) : {};
|
||||
const partsData = userStats.every((e) => e.module === "level")
|
||||
? userStats.reduce((acc, e, index) => {
|
||||
return {
|
||||
...acc,
|
||||
[`part${index}`]: `${e.score.correct}/${e.score.total}`,
|
||||
};
|
||||
}, {})
|
||||
: {};
|
||||
|
||||
return {
|
||||
...commonData,
|
||||
@@ -182,14 +186,6 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
label: "Email",
|
||||
value: (entry: TableData) => entry.email,
|
||||
},
|
||||
{
|
||||
label: "Student ID",
|
||||
value: (entry: TableData) => entry.studentID,
|
||||
},
|
||||
{
|
||||
label: "Passport ID",
|
||||
value: (entry: TableData) => entry.passportID,
|
||||
},
|
||||
...(displaySelection
|
||||
? [
|
||||
{
|
||||
@@ -207,7 +203,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
value: (entry: TableData) => (entry.submitted ? "Yes" : "No"),
|
||||
},
|
||||
{
|
||||
label: "Score",
|
||||
label: "Correct",
|
||||
value: (entry: TableData) => entry.correct,
|
||||
},
|
||||
{
|
||||
@@ -227,7 +223,9 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
})),
|
||||
];
|
||||
|
||||
const filteredSearch = !!searchText ? search(searchText, searchFilters, tableResults) : tableResults;
|
||||
const filteredSearch = searchText
|
||||
? search(searchText, searchFilters, tableResults)
|
||||
: tableResults;
|
||||
|
||||
worksheet.addRow(headers.map((h) => h.label));
|
||||
(filteredSearch as TableData[]).forEach((entry) => {
|
||||
@@ -243,7 +241,8 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
const fileRef = ref(storage, refName);
|
||||
// upload the pdf to storage
|
||||
await uploadBytes(fileRef, buffer, {
|
||||
contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
contentType:
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
});
|
||||
|
||||
const url = await getDownloadURL(fileRef);
|
||||
@@ -251,5 +250,5 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
return;
|
||||
}
|
||||
|
||||
return res.status(401).json({error: "Unauthorized"});
|
||||
return res.status(401).json({ error: "Unauthorized" });
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
// 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 { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import axios, { AxiosResponse } from "axios";
|
||||
import { Stat } from "@/interfaces/user";
|
||||
import { writingReverseMarking } from "@/utils/score";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import axios, {AxiosResponse} from "axios";
|
||||
import {Stat} from "@/interfaces/user";
|
||||
import {writingReverseMarking} from "@/utils/score";
|
||||
|
||||
interface Body {
|
||||
question: string;
|
||||
@@ -24,7 +24,7 @@ export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ ok: false });
|
||||
res.status(401).json({ok: false});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -36,11 +36,10 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
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(
|
||||
{ id: (req.body as Body).id },
|
||||
{ id: (req.body as Body).id},
|
||||
{
|
||||
$set: {
|
||||
id: (req.body as Body).id,
|
||||
solutions,
|
||||
score: {
|
||||
@@ -49,16 +48,15 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
missing: 0,
|
||||
},
|
||||
isDisabled: false,
|
||||
}
|
||||
},
|
||||
{ upsert: true },
|
||||
{upsert: true},
|
||||
);
|
||||
console.log("🌱 - Updated the DB");
|
||||
}
|
||||
|
||||
async function getCorrespondingStat(id: string, index: number): Promise<Stat> {
|
||||
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;
|
||||
|
||||
|
||||
@@ -72,9 +72,6 @@ async function registerIndividual(req: NextApiRequest, res: NextApiResponse) {
|
||||
...(passport_id ? {demographicInformation: {passport_id}} : {}),
|
||||
registrationDate: new Date().toISOString(),
|
||||
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);
|
||||
@@ -120,9 +117,6 @@ async function registerCorporate(req: NextApiRequest, res: NextApiResponse) {
|
||||
subscriptionExpirationDate: req.body.subscriptionExpirationDate || null,
|
||||
status: "paymentDue",
|
||||
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 = {
|
||||
|
||||
@@ -16,5 +16,5 @@ async function GET(req: NextApiRequest, res: NextApiResponse) {
|
||||
const snapshot = await db.collection("stats").findOne({ id: id as string});
|
||||
if (!snapshot) return res.status(404).json({id: id as string});
|
||||
|
||||
res.status(200).json({...snapshot, id: snapshot.id});
|
||||
res.status(200).json({...snapshot.data(), id: snapshot.id});
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {getLinkedUsers} from "@/utils/users.be";
|
||||
import {Type} from "@/interfaces/user";
|
||||
import {uniqBy} from "lodash";
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
@@ -20,7 +19,8 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
page,
|
||||
orderBy,
|
||||
direction = "desc",
|
||||
} = req.query as {size?: string; type?: Type; page?: string; orderBy?: string; direction?: "asc" | "desc"};
|
||||
searchTerm
|
||||
} = req.query as {size?: string; type?: Type; page?: string; orderBy?: string; direction?: "asc" | "desc"; searchTerm?: string | undefined};
|
||||
|
||||
const {users, total} = await getLinkedUsers(
|
||||
req.session.user?.id,
|
||||
@@ -30,7 +30,8 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
size !== undefined ? parseInt(size) : undefined,
|
||||
orderBy,
|
||||
direction,
|
||||
searchTerm
|
||||
);
|
||||
|
||||
res.status(200).json({users: uniqBy([...users], "id"), total});
|
||||
res.status(200).json({users, total});
|
||||
}
|
||||
|
||||
@@ -158,7 +158,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
delete updatedUser.password;
|
||||
delete updatedUser.newPassword;
|
||||
|
||||
await db.collection("users").updateOne({id: queryId ? (queryId as string) : req.session.user.id}, {$set: updatedUser});
|
||||
await db.collection("users").updateOne({id: queryId}, {$set: updatedUser});
|
||||
|
||||
if (!queryId) {
|
||||
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);
|
||||
}
|
||||
|
||||
res.status(200).json({user: {...updatedUser, ...user, id: req.session.user!.id}});
|
||||
res.status(200).json({user: {...updatedUser, id: req.session.user!.id}});
|
||||
}
|
||||
|
||||
export const config = {
|
||||
|
||||
@@ -79,7 +79,7 @@ export default function Home({user: propsUser, linkedCorporate}: Props) {
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
setShowDemographicInput(!user.demographicInformation || !user.demographicInformation.country || !user.demographicInformation.phone);
|
||||
// setShowDemographicInput(!user.demographicInformation || !user.demographicInformation.country || !user.demographicInformation.phone);
|
||||
setShowDiagnostics(user.isFirstLogin && user.type === "student");
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import client from "@/lib/mongodb";
|
||||
import {Assignment} from "@/interfaces/results";
|
||||
import {getAllAssignersByCorporate} from "@/utils/groups.be";
|
||||
import {Type} from "@/interfaces/user";
|
||||
|
||||
const db = client.db(process.env.MONGODB_DB);
|
||||
|
||||
@@ -37,10 +36,10 @@ export const getAssignmentsByAssigners = async (ids: string[], startDate?: Date,
|
||||
.toArray();
|
||||
};
|
||||
|
||||
export const getAssignmentsForCorporates = async (userType: Type, idsList: string[], startDate?: Date, endDate?: Date) => {
|
||||
export const getAssignmentsForCorporates = async (idsList: string[], startDate?: Date, endDate?: Date) => {
|
||||
const assigners = await Promise.all(
|
||||
idsList.map(async (id) => {
|
||||
const assigners = await getAllAssignersByCorporate(id, userType);
|
||||
const assigners = await getAllAssignersByCorporate(id);
|
||||
return {
|
||||
corporateId: id,
|
||||
assigners,
|
||||
|
||||
@@ -6,28 +6,6 @@ import {Module} from "@/interfaces";
|
||||
import {getCorporateUser} from "@/resources/user";
|
||||
import {getUserCorporate} from "./groups.be";
|
||||
import {Db, ObjectId} from "mongodb";
|
||||
import client from "@/lib/mongodb";
|
||||
import {MODULE_ARRAY} from "./moduleUtils";
|
||||
|
||||
const db = client.db(process.env.MONGODB_DB);
|
||||
|
||||
export async function getSpecificExams(ids: string[]) {
|
||||
if (ids.length === 0) return [];
|
||||
|
||||
const exams: Exam[] = (
|
||||
await Promise.all(
|
||||
MODULE_ARRAY.flatMap(
|
||||
async (module) =>
|
||||
await db
|
||||
.collection(module)
|
||||
.find<Exam>({id: {$in: ids}})
|
||||
.toArray(),
|
||||
),
|
||||
)
|
||||
).flat();
|
||||
|
||||
return exams;
|
||||
}
|
||||
|
||||
export const getExams = async (
|
||||
db: Db,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {app} from "@/firebase";
|
||||
import {Assignment} from "@/interfaces/results";
|
||||
import {CorporateUser, Group, MasterCorporateUser, StudentUser, TeacherUser, Type, User} from "@/interfaces/user";
|
||||
import {CorporateUser, Group, MasterCorporateUser, StudentUser, TeacherUser, User} from "@/interfaces/user";
|
||||
import client from "@/lib/mongodb";
|
||||
import moment from "moment";
|
||||
import {getLinkedUsers, getUser} from "./users.be";
|
||||
@@ -71,9 +71,9 @@ export const getUsersGroups = async (ids: string[]) => {
|
||||
.toArray();
|
||||
};
|
||||
|
||||
export const getAllAssignersByCorporate = async (corporateID: string, type: Type): Promise<string[]> => {
|
||||
const linkedTeachers = await getLinkedUsers(corporateID, type, "teacher");
|
||||
const linkedCorporates = await getLinkedUsers(corporateID, type, "corporate");
|
||||
export const getAllAssignersByCorporate = async (corporateID: string): Promise<string[]> => {
|
||||
const linkedTeachers = await getLinkedUsers(corporateID, "mastercorporate", "teacher");
|
||||
const linkedCorporates = await getLinkedUsers(corporateID, "mastercorporate", "corporate");
|
||||
|
||||
return [...linkedTeachers.users.map((x) => x.id), ...linkedCorporates.users.map((x) => x.id)];
|
||||
};
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
/*fields example = [
|
||||
['id'],
|
||||
['companyInformation', 'companyInformation', 'name']
|
||||
@@ -25,4 +26,4 @@ export const search = (text: string, fields: string[][], rows: any[]) => {
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -1,18 +1,18 @@
|
||||
import {CorporateUser, Group, Type, User} from "@/interfaces/user";
|
||||
import {getGroupsForUser, getParticipantGroups, getUserGroups, getUsersGroups} from "./groups.be";
|
||||
import {last, uniq, uniqBy} from "lodash";
|
||||
import {getUserCodes} from "./codes.be";
|
||||
import { CorporateUser, Group, Type, User } from "@/interfaces/user";
|
||||
import { getGroupsForUser, getParticipantGroups, getUserGroups, getUsersGroups } from "./groups.be";
|
||||
import { last, uniq, uniqBy } from "lodash";
|
||||
import { getUserCodes } from "./codes.be";
|
||||
import moment from "moment";
|
||||
import client from "@/lib/mongodb";
|
||||
|
||||
const db = client.db(process.env.MONGODB_DB);
|
||||
|
||||
export async function getUsers() {
|
||||
return await db.collection("users").find<User>({}, { projection: { _id: 0 } }).toArray();
|
||||
return await db.collection("users").find<User>({}).toArray();
|
||||
}
|
||||
|
||||
export async function getUser(id: string): Promise<User | undefined> {
|
||||
const user = await db.collection("users").findOne<User>({id: id}, { projection: { _id: 0 } });
|
||||
const user = await db.collection("users").findOne<User>({ id });
|
||||
return !!user ? user : undefined;
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ export async function getSpecificUsers(ids: string[]) {
|
||||
|
||||
return await db
|
||||
.collection("users")
|
||||
.find<User>({id: {$in: ids}}, { projection: { _id: 0 } })
|
||||
.find<User>({ id: { $in: ids } })
|
||||
.toArray();
|
||||
}
|
||||
|
||||
@@ -33,21 +33,32 @@ export async function getLinkedUsers(
|
||||
size?: number,
|
||||
sort?: string,
|
||||
direction?: "asc" | "desc",
|
||||
searchTerm?: string | undefined,
|
||||
) {
|
||||
const filters = {
|
||||
...(!!type ? {type} : {}),
|
||||
};
|
||||
const filters: any = {};
|
||||
|
||||
if (type) {
|
||||
filters.type = type;
|
||||
}
|
||||
|
||||
if (searchTerm) {
|
||||
filters.$or = [
|
||||
{ name: { $regex: searchTerm, $options: 'i' } },
|
||||
{ email: { $regex: searchTerm, $options: 'i' } },
|
||||
{ company: { $regex: searchTerm, $options: 'i' } },
|
||||
];
|
||||
}
|
||||
|
||||
if (!userID || userType === "admin" || userType === "developer") {
|
||||
const users = await db
|
||||
.collection("users")
|
||||
.find<User>(filters)
|
||||
.sort(sort ? {[sort]: direction === "desc" ? -1 : 1} : {})
|
||||
.sort(sort ? { [sort]: direction === "desc" ? -1 : 1 } : {})
|
||||
.skip(page && size ? page * size : 0)
|
||||
.limit(size || 0)
|
||||
.toArray();
|
||||
const total = await db.collection("users").countDocuments(filters);
|
||||
return {users, total};
|
||||
return { users, total };
|
||||
}
|
||||
|
||||
const adminGroups = await getUserGroups(userID);
|
||||
@@ -61,17 +72,17 @@ export async function getLinkedUsers(
|
||||
]);
|
||||
|
||||
// ⨯ [FirebaseError: Invalid Query. A non-empty array is required for 'in' filters.] {
|
||||
if (participants.length === 0) return {users: [], total: 0};
|
||||
if (participants.length === 0) return { users: [], total: 0 };
|
||||
|
||||
const users = await db
|
||||
.collection("users")
|
||||
.find<User>({...filters, id: {$in: participants}})
|
||||
.find<User>({ ...filters, id: { $in: participants } })
|
||||
.skip(page && size ? page * size : 0)
|
||||
.limit(size || 0)
|
||||
.toArray();
|
||||
const total = await db.collection("users").countDocuments({...filters, id: {$in: participants}});
|
||||
const total = await db.collection("users").countDocuments({ ...filters, id: { $in: participants } });
|
||||
|
||||
return {users, total};
|
||||
return { users, total };
|
||||
}
|
||||
|
||||
export async function getUserBalance(user: User) {
|
||||
|
||||
Reference in New Issue
Block a user