Updated the MasterCorporate with the improved queries

This commit is contained in:
Tiago Ribeiro
2024-09-06 14:57:23 +01:00
parent a6bf53e84c
commit de35e1a8b7
8 changed files with 153 additions and 146 deletions

View File

@@ -302,33 +302,30 @@ export default function MasterCorporateDashboard({user}: Props) {
const [corporateAssignments, setCorporateAssignments] = useState<(Assignment & {corporate?: CorporateUser})[]>([]);
const {data: stats} = useFilterRecordsByUser<Stat[]>();
const {users, reload} = useUsers();
const {users: students, reload: reloadStudents} = useUsers({type: "student"});
const {users: teachers, reload: reloadTeachers} = useUsers({type: "teacher"});
const {users: corporates, reload: reloadCorporates} = useUsers({type: "corporate"});
const {groups} = useGroups({admin: user.id, userType: user.type});
const {balance} = useUserBalance();
const masterCorporateUserGroups = useMemo(
() => [...new Set(groups.filter((u) => u.admin === user.id).flatMap((g) => g.participants))],
[groups, user.id],
);
const corporateUserGroups = useMemo(() => [...new Set(groups.flatMap((g) => g.participants))], [groups]);
const users = useMemo(() => [...students, ...teachers, ...corporates], [corporates, students, teachers]);
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 assignmentsUsers = useMemo(
() =>
users.filter(
(x) =>
(x.type === "student" || x.type === "teacher") &&
(!!selectedUser
? groups
.filter((g) => g.admin === selectedUser.id)
.flatMap((g) => g.participants)
.includes(x.id) || false
: groups.flatMap((g) => g.participants).includes(x.id)),
[...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, users, selectedUser],
[groups, selectedUser, teachers, students],
);
const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
@@ -340,17 +337,16 @@ export default function MasterCorporateDashboard({user}: Props) {
useEffect(() => {
setCorporateAssignments(
assignments.filter(activeAssignmentFilter).map((a) => ({
...a,
corporate: !!users.find((x) => x.id === a.assigner)
? getCorporateUser(users.find((x) => x.id === a.assigner)!, users, groups)
: undefined,
})),
);
}, [assignments, groups, users]);
assignments.filter(activeAssignmentFilter).map((a) => {
const assigner = [...teachers, ...corporates].find((x) => x.id === a.assigner);
const studentFilter = (user: User) => user.type === "student";
const teacherFilter = (user: User) => user.type === "teacher";
return {
...a,
corporate: assigner ? getCorporateUser(assigner, [...teachers, ...corporates], groups) : undefined,
};
}),
);
}, [assignments, groups, teachers, corporates]);
const getStatsByStudent = (user: User) => stats.filter((s) => s.user === user.id);
const UserDisplay = (displayUser: User) => (
@@ -386,14 +382,6 @@ export default function MasterCorporateDashboard({user}: Props) {
};
const StudentPerformancePage = () => {
const students = users
.filter((x) => x.type === "student" && groups.flatMap((g) => g.participants).includes(x.id))
.map((u) => ({
...u,
group: groups.find((x) => x.participants.includes(u.id)),
corporate: getCorporateUser(u, users, groups),
}));
return (
<>
<div className="w-full flex justify-between items-center">
@@ -410,21 +398,11 @@ export default function MasterCorporateDashboard({user}: Props) {
<BsArrowRepeat className={clsx("text-xl", isAssignmentsLoading && "animate-spin")} />
</div>
</div>
<StudentPerformanceList items={students} stats={stats} users={users} groups={groups} />
<StudentPerformanceList items={students} stats={stats} users={corporates} groups={groups} />
</>
);
};
const masterCorporateUsers = useMemo(
() =>
masterCorporateUserGroups.reduce((accm: CorporateUser[], id) => {
const user = users.find((u) => u.id === id) as CorporateUser;
if (user) return [...accm, user];
return accm;
}, []),
[masterCorporateUserGroups, users],
);
const MasterStatisticalPage = () => {
return (
<>
@@ -437,7 +415,7 @@ export default function MasterCorporateDashboard({user}: Props) {
</div>
<h2 className="text-2xl font-semibold">Master Statistical</h2>
</div>
<MasterStatistical users={users} corporateUsers={masterCorporateUsers} />
<MasterStatistical users={users} corporateUsers={corporates} />
</>
);
};
@@ -445,20 +423,8 @@ export default function MasterCorporateDashboard({user}: Props) {
const DefaultDashboard = () => (
<>
<section className="flex flex-wrap gap-2 items-center -lg:justify-center lg:justify-between text-center">
<IconCard
onClick={() => router.push("/#students")}
Icon={BsPersonFill}
label="Students"
value={users.filter(studentFilter).length}
color="purple"
/>
<IconCard
onClick={() => router.push("/#teachers")}
Icon={BsPencilSquare}
label="Teachers"
value={users.filter(teacherFilter).length}
color="purple"
/>
<IconCard onClick={() => router.push("/#students")} Icon={BsPersonFill} label="Students" value={students.length} color="purple" />
<IconCard onClick={() => router.push("/#teachers")} Icon={BsPencilSquare} label="Teachers" value={teachers.length} color="purple" />
<IconCard
Icon={BsClipboard2Data}
label="Exams Performed"
@@ -469,7 +435,7 @@ export default function MasterCorporateDashboard({user}: Props) {
Icon={BsPaperclip}
label="Average Level"
value={averageLevelCalculator(
users,
students,
stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user)),
).toFixed(1)}
color="purple"
@@ -487,17 +453,11 @@ export default function MasterCorporateDashboard({user}: Props) {
value={user.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy") : "Unlimited"}
color="rose"
/>
<IconCard
Icon={BsBank}
label="Corporate"
value={users.filter(corporateUserFilter).length}
color="purple"
onClick={() => router.push("/#corporate")}
/>
<IconCard Icon={BsBank} label="Corporate" value={corporates.length} color="purple" onClick={() => router.push("/#corporate")} />
<IconCard
Icon={BsPersonFillGear}
label="Student Performance"
value={users.filter(studentFilter).length}
value={students.length}
color="purple"
onClick={() => router.push("/#studentsPerformance")}
/>
@@ -526,8 +486,7 @@ export default function MasterCorporateDashboard({user}: Props) {
<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">
{users
.filter(studentFilter)
{students
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
.map((x) => (
<UserDisplay key={x.id} {...x} />
@@ -537,8 +496,7 @@ export default function MasterCorporateDashboard({user}: Props) {
<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">
{users
.filter(teacherFilter)
{teachers
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
.map((x) => (
<UserDisplay key={x.id} {...x} />
@@ -548,8 +506,7 @@ export default function MasterCorporateDashboard({user}: Props) {
<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">
{users
.filter(studentFilter)
{students
.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))
.map((x) => (
<UserDisplay key={x.id} {...x} />
@@ -559,8 +516,7 @@ export default function MasterCorporateDashboard({user}: Props) {
<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">
{users
.filter(studentFilter)
{students
.sort(
(a, b) =>
Object.keys(groupByExam(getStatsByStudent(b))).length - Object.keys(groupByExam(getStatsByStudent(a))).length,
@@ -589,7 +545,9 @@ export default function MasterCorporateDashboard({user}: Props) {
loggedInUser={user}
onClose={(shouldReload) => {
setSelectedUser(undefined);
if (shouldReload) reload();
if (shouldReload && selectedUser!.type === "student") reloadStudents();
if (shouldReload && selectedUser!.type === "teacher") reloadTeachers();
if (shouldReload && selectedUser!.type === "corporate") reloadCorporates();
}}
onViewStudents={
selectedUser.type === "corporate" || selectedUser.type === "teacher"

View File

@@ -1,21 +1,31 @@
import {User} from "@/interfaces/user";
import axios from "axios";
import {Type, User} from "@/interfaces/user";
import Axios from "axios";
import {useEffect, useState} from "react";
import {setupCache} from "axios-cache-interceptor";
export default function useUsers() {
const instance = Axios.create();
const axios = setupCache(instance);
export default function useUsers(props?: {type?: Type; page?: number; size?: number}) {
const [users, setUsers] = useState<User[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const getData = () => {
const params = new URLSearchParams();
if (!!props)
Object.keys(props).forEach((key) => {
if (!!props[key as keyof typeof props]) params.append(key, props[key as keyof typeof props]!.toString());
});
setIsLoading(true);
axios
.get<User[]>("/api/users/list", {headers: {page: "register"}})
.get<User[]>(`/api/users/list?${params.toString()}`, {headers: {page: "register"}})
.then((response) => setUsers(response.data))
.finally(() => setIsLoading(false));
};
useEffect(getData, []);
useEffect(getData, [props]);
return {users, isLoading, isError, reload: getData};
}

View File

@@ -80,7 +80,7 @@ export default function UserList({
useEffect(() => {
(async () => {
if (users) {
if (users && users.length > 0) {
const filteredUsers = filters.reduce((d, f) => d.filter(f), users);
const sortedUsers = await asyncSorter<User>(filteredUsers, sortFunction);

View File

@@ -3,6 +3,7 @@ import type {NextApiRequest, NextApiResponse} from "next";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {getLinkedUsers} from "@/utils/users.be";
import {Type} from "@/interfaces/user";
export default withIronSessionApiRoute(handler, sessionOptions);
@@ -12,6 +13,14 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
return;
}
const users = await getLinkedUsers(req.session.user?.id, req.session.user?.type);
const {page, size, type} = req.query as {page?: string; size?: string; type?: Type};
const users = await getLinkedUsers(
req.session.user?.id,
req.session.user?.type,
type,
page !== undefined ? parseInt(page) : undefined,
size !== undefined ? parseInt(size) : undefined,
);
res.status(200).json(users);
}

View File

@@ -2,7 +2,6 @@
import Head from "next/head";
import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import useUser from "@/hooks/useUser";
import {ToastContainer} from "react-toastify";
import Layout from "@/components/High/Layout";
import CodeGenerator from "./(admin)/CodeGenerator";
@@ -28,6 +27,7 @@ import {User} from "@/interfaces/user";
import {getUserPermissions} from "@/utils/permissions.be";
import {Permission, PermissionType} from "@/interfaces/permissions";
import {getUsers} from "@/utils/users.be";
import useUsers from "@/hooks/useUsers";
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
const user = req.session.user;
@@ -50,21 +50,20 @@ export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
}
const permissions = await getUserPermissions(user.id);
const users = await getUsers();
return {
props: {user, permissions, users},
props: {user, permissions},
};
}, sessionOptions);
interface Props {
user: User;
users: User[];
permissions: PermissionType[];
}
export default function Admin({user, users, permissions}: Props) {
export default function Admin({user, permissions}: Props) {
const {gradingSystem, mutate} = useGradingSystem();
const {users} = useUsers();
const [modalOpen, setModalOpen] = useState<string>();

View File

@@ -1,6 +1,20 @@
import {app} from "@/firebase";
import {collection, doc, getDoc, getDocs, getFirestore, query, where} from "firebase/firestore";
import {
collection,
doc,
documentId,
endAt,
getDoc,
getDocs,
getFirestore,
limit,
orderBy,
query,
startAfter,
startAt,
where,
} from "firebase/firestore";
import {CorporateUser, Group, Type, User} from "@/interfaces/user";
import {getGroupsForUser} from "./groups.be";
import {uniq, uniqBy} from "lodash";
@@ -38,15 +52,16 @@ export async function getSpecificUsers(ids: string[]) {
return groups;
}
export async function getLinkedUsers(userID?: string, type?: Type) {
const snapshot = await getDocs(collection(db, "users"));
const users = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
})) as User[];
export async function getLinkedUsers(userID?: string, userType?: Type, type?: Type, page?: number, size?: number) {
if (!userID || userType === "admin" || userType === "developer") {
const snapshot = await getDocs(collection(db, "users"));
const users = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
})) as User[];
if (!userID) return users;
if (type === "admin" || type === "developer") return users;
return users;
}
const adminGroups = await getGroupsForUser(userID);
const groups = await Promise.all(adminGroups.flatMap((x) => x.participants).map(async (x) => await getGroupsForUser(x)));
@@ -55,10 +70,24 @@ export async function getLinkedUsers(userID?: string, type?: Type) {
const participants = uniq([
...adminGroups.flatMap((x) => x.participants),
...groups.flat().flatMap((x) => x.participants),
...(type === "teacher" ? belongingGroups.flatMap((x) => x.participants) : []),
...(userType === "teacher" ? belongingGroups.flatMap((x) => x.participants) : []),
]);
return users.filter((x) => participants.includes(x.id) && x.id !== userID);
const q = [
where(documentId(), "in", participants),
...(!!type ? [where("type", "==", type)] : []),
orderBy(documentId()),
...(page !== undefined && !!size ? [startAt(page * size)] : []),
...(page !== undefined && !!size ? [limit(page + 1 * size)] : []),
];
const snapshot = await getDocs(query(collection(db, "users"), ...q));
const users = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
})) as User[];
return users;
}
export async function getUserBalance(user: User) {