Solved some problems with the excel of master statistical

This commit is contained in:
Tiago Ribeiro
2024-09-10 12:00:14 +01:00
parent 33a46c227b
commit 2a10933206
8 changed files with 448 additions and 522 deletions

View File

@@ -1,546 +1,432 @@
/* 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,
BsClipboard2DataFill,
BsClock,
BsGlobeCentralSouthAsia,
BsPaperclip,
BsPerson,
BsPersonAdd,
BsPersonFill,
BsPersonFillGear,
BsPersonGear,
BsPencilSquare,
BsPersonBadge,
BsPersonCheck,
BsPeople,
BsArrowRepeat,
BsPlus,
BsEnvelopePaper,
BsDatabase,
BsArrowLeft,
BsClipboard2Data,
BsClipboard2DataFill,
BsClock,
BsGlobeCentralSouthAsia,
BsPaperclip,
BsPerson,
BsPersonAdd,
BsPersonFill,
BsPersonFillGear,
BsPersonGear,
BsPencilSquare,
BsPersonBadge,
BsPersonCheck,
BsPeople,
BsArrowRepeat,
BsPlus,
BsEnvelopePaper,
BsDatabase,
} 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";
interface Props {
user: CorporateUser;
linkedCorporate?: CorporateUser | MasterCorporateUser;
user: CorporateUser;
linkedCorporate?: CorporateUser | MasterCorporateUser;
}
const studentHash = {
type: "student",
orderBy: "registrationDate",
size: 25,
type: "student",
orderBy: "registrationDate",
size: 25,
};
const teacherHash = {
type: "teacher",
orderBy: "registrationDate",
size: 25,
type: "teacher",
orderBy: "registrationDate",
size: 25,
};
export default function CorporateDashboard({ user, linkedCorporate }: Props) {
const [selectedUser, setSelectedUser] = useState<User>();
const [showModal, setShowModal] = useState(false);
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);
useEffect(() => console.log(assignments), [assignments]);
const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
const router = useRouter();
const {users: students, total: totalStudents, reload: reloadStudents, isLoading: isStudentsLoading} = useUsers(studentHash);
const {users: teachers, total: totalTeachers, reload: reloadTeachers, isLoading: isTeachersLoading} = useUsers(teacherHash);
const assignmentsGroups = useMemo(
() =>
groups.filter(
(x) => x.admin === user.id || x.participants.includes(user.id)
),
[groups, user.id]
);
const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
const router = useRouter();
const assignmentsUsers = useMemo(
() =>
[...teachers, ...students].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, teachers, students, selectedUser]
);
const assignmentsGroups = useMemo(() => groups.filter((x) => x.admin === user.id || x.participants.includes(user.id)), [groups, user.id]);
useEffect(() => {
setShowModal(!!selectedUser && router.asPath === "/#");
}, [selectedUser, router.asPath]);
const assignmentsUsers = useMemo(
() =>
[...teachers, ...students].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, teachers, students, selectedUser],
);
const getStatsByStudent = (user: User) =>
stats.filter((s) => s.user === user.id);
useEffect(() => {
setShowModal(!!selectedUser && router.asPath === "/#");
}, [selectedUser, router.asPath]);
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"
/>
<div className="flex flex-col gap-1 items-start">
<span>{displayUser.name}</span>
<span className="text-sm opacity-75">{displayUser.email}</span>
</div>
</div>
);
const getStatsByStudent = (user: User) => stats.filter((s) => s.user === user.id);
// 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 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" />
<div className="flex flex-col gap-1 items-start">
<span>{displayUser.name}</span>
<span className="text-sm opacity-75">{displayUser.email}</span>
</div>
</div>
);
const GroupsList = () => {
const filter = (x: Group) =>
x.admin === user.id || x.participants.includes(user.id);
// 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} />
</>
);
};
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">
Groups ({groups.filter(filter).length})
</h2>
</div>
const GroupsList = () => {
const filter = (x: Group) => x.admin === user.id || x.participants.includes(user.id);
<GroupList user={user} />
</>
);
};
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">Groups ({groups.filter(filter).length})</h2>
</div>
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!
),
}));
<GroupList user={user} />
</>
);
};
const levels: { [key in Module]: number } = {
reading: 0,
listening: 0,
writing: 0,
speaking: 0,
level: 0,
};
bandScores.forEach((b) => (levels[b.module] += b.level));
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!),
}));
return calculateAverageLevel(levels);
};
const levels: {[key in Module]: number} = {
reading: 0,
listening: 0,
writing: 0,
speaking: 0,
level: 0,
};
bandScores.forEach((b) => (levels[b.module] += b.level));
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>
)}
/>
);
return calculateAverageLevel(levels);
};
if (router.asPath === "/#teachers")
return (
<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 === "/#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 === "/#groups") return <GroupsList />;
if (router.asPath === "/#studentsPerformance")
return <StudentPerformancePage user={user} />;
if (router.asPath === "/#teachers")
return (
<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 === "/#assignments")
return (
<AssignmentsPage
assignments={assignments}
user={user}
groups={assignmentsGroups}
reloadAssignments={reloadAssignments}
isLoading={isAssignmentsLoading}
onBack={() => router.push("/")}
/>
);
if (router.asPath === "/#groups") return <GroupsList />;
if (router.asPath === "/#studentsPerformance") return <StudentPerformancePage user={user} />;
if (router.asPath === "/#statistical") return <MasterStatisticalPage />;
if (router.asPath === "/#assignments")
return (
<AssignmentsPage
assignments={assignments}
user={user}
groups={assignmentsGroups}
reloadAssignments={reloadAssignments}
isLoading={isAssignmentsLoading}
onBack={() => router.push("/")}
/>
);
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),
});
if (router.asPath === "/#statistical") return <MasterStatisticalPage />;
router.push("/list/users");
}
: undefined
}
onViewTeachers={
selectedUser.type === "corporate" ||
selectedUser.type === "student"
? () => {
appendUserFilters({
id: "view-teachers",
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),
});
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),
});
router.push("/list/users");
}
: undefined
}
user={selectedUser}
/>
</div>
)}
</>
</Modal>
router.push("/list/users");
}
: undefined
}
onViewTeachers={
selectedUser.type === "corporate" || selectedUser.type === "student"
? () => {
appendUserFilters({
id: "view-teachers",
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),
});
<>
{!!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>
</div>
)}
<section className="grid grid-cols-5 -md:grid-cols-2 gap-4 text-center">
<IconCard
onClick={() => router.push("/#students")}
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>
router.push("/list/users");
}
: undefined
}
user={selectedUser}
/>
</div>
)}
</>
</Modal>
<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>
</>
</>
);
<>
{!!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>
</div>
)}
<section className="grid grid-cols-5 -md:grid-cols-2 gap-4 text-center">
<IconCard
onClick={() => router.push("/#students")}
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">
<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

@@ -75,7 +75,7 @@ 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 = !!userData ? a.results.find((r) => r.user === assignee)?.stats || [] : [];
const userStats = a.results.find((r) => r.user === assignee)?.stats || [];
const corporate = getUserName(users.find((u) => u.id === a.assigner));
const commonData = {
user: userData,
@@ -109,8 +109,6 @@ 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);

View File

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

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());
});
console.log(params.toString());
setIsLoading(true);
axios
.get<{users: User[]; total: number}>(`/api/users/list?${params.toString()}`, {headers: {page: "register"}})

View File

@@ -14,12 +14,18 @@ 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";
export default withIronSessionApiRoute(handler, sessionOptions);
interface TableData {
user: string;
studentID: string;
passportID: string;
exams: string;
email: string;
correct: number;
corporate: string;
@@ -41,7 +47,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
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) {
// verify if it's a logged user that is trying to export
@@ -66,10 +72,11 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
const endDateParsed = endDate ? new Date(endDate) : undefined;
const assignments = await getAssignmentsForCorporates(req.session.user.type, ids, startDateParsed, endDateParsed);
const assignmentUsers = [...new Set(assignments.flatMap((a) => a.assignees))];
const assignmentUsers = uniq([...assignments.flatMap((x) => x.assignees), ...assignments.flatMap((x) => x.assigner)]);
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) => {
@@ -91,7 +98,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
if (gradingSystem) {
const bandScore = calculateBandScore(correct, total, "level", user?.focus || "academic");
return {
label: getGradingLabel(bandScore, gradingSystem?.steps || []),
label: getGradingLabel(bandScore, gradingSystem.steps || []),
score: bandScore,
};
}
@@ -113,10 +120,12 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
const commonData = {
user: userData?.name || "",
email: userData?.email || "",
studentID: (userData as StudentUser).studentID || "",
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?.name || "",
corporate: !corporateUser ? "" : getUserName(corporateUser),
assignment: a.name,
level,
score,
@@ -130,14 +139,22 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
};
}
const partsData = userStats.every((e) => e.module === "level")
? userStats.reduce((acc, e, index) => {
return {
...acc,
[`part${index}`]: `${e.score.correct}/${e.score.total}`,
};
}, {})
: {};
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}`}), {}) : {};
return {
...commonData,
@@ -169,6 +186,10 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
label: "Student ID",
value: (entry: TableData) => entry.studentID,
},
{
label: "Passport ID",
value: (entry: TableData) => entry.passportID,
},
...(displaySelection
? [
{
@@ -186,7 +207,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
value: (entry: TableData) => (entry.submitted ? "Yes" : "No"),
},
{
label: "Correct",
label: "Score",
value: (entry: TableData) => entry.correct,
},
{
@@ -206,7 +227,7 @@ 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) => {

View File

@@ -4,6 +4,7 @@ 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);
@@ -31,5 +32,5 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
direction,
);
res.status(200).json({users, total});
res.status(200).json({users: uniqBy([...users, req.session.user], "id"), total});
}

View File

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

View File

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