Merge branch 'main' into develop
This commit is contained in:
@@ -17,7 +17,7 @@ import moment from "moment";
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
mutateUser: KeyedMutator<User>;
|
||||
mutateUser: (user: User) => void;
|
||||
}
|
||||
|
||||
export default function DemographicInformationInput({user, mutateUser}: Props) {
|
||||
@@ -42,7 +42,7 @@ export default function DemographicInformationInput({user, mutateUser}: Props) {
|
||||
setIsLoading(true);
|
||||
|
||||
axios
|
||||
.patch("/api/users/update", {
|
||||
.patch<{user: User}>("/api/users/update", {
|
||||
demographicInformation: {
|
||||
country,
|
||||
phone: `+${countryCodes.findOne("countryCode" as any, country!).countryCallingCode}${phone}`,
|
||||
@@ -54,7 +54,7 @@ export default function DemographicInformationInput({user, mutateUser}: Props) {
|
||||
},
|
||||
agentInformation: user.type === "agent" ? {companyName, commercialRegistration} : undefined,
|
||||
})
|
||||
.then((response) => mutateUser((response.data as {user: User}).user))
|
||||
.then((response) => mutateUser(response.data.user))
|
||||
.catch(() => {
|
||||
toast.error("Something went wrong, please try again later!", {toastId: "user-update-error"});
|
||||
})
|
||||
@@ -89,7 +89,15 @@ export default function DemographicInformationInput({user, mutateUser}: Props) {
|
||||
<label className="font-normal text-base text-mti-gray-dim">Country *</label>
|
||||
<CountrySelect value={country} onChange={setCountry} />
|
||||
</div>
|
||||
<Input type="tel" name="phone" label="Phone number" onChange={(e) => setPhone(e)} value={phone} placeholder="Enter phone number" required />
|
||||
<Input
|
||||
type="tel"
|
||||
name="phone"
|
||||
label="Phone number"
|
||||
onChange={(e) => setPhone(e)}
|
||||
value={phone}
|
||||
placeholder="Enter phone number"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{user.type === "student" && (
|
||||
<Input
|
||||
|
||||
@@ -65,28 +65,28 @@ export default function Navbar({user, path, navDisabled = false, focusMode = fal
|
||||
{
|
||||
module: "reading",
|
||||
icon: () => <BsBook className="h-4 w-4 text-white" />,
|
||||
achieved: user.levels.reading >= user.desiredLevels.reading,
|
||||
achieved: user.levels?.reading || 0 >= user.desiredLevels?.reading || 9,
|
||||
},
|
||||
|
||||
{
|
||||
module: "listening",
|
||||
icon: () => <BsHeadphones className="h-4 w-4 text-white" />,
|
||||
achieved: user.levels.listening >= user.desiredLevels.listening,
|
||||
achieved: user.levels?.listening || 0 >= user.desiredLevels?.listening || 9,
|
||||
},
|
||||
{
|
||||
module: "writing",
|
||||
icon: () => <BsPen className="h-4 w-4 text-white" />,
|
||||
achieved: user.levels.writing >= user.desiredLevels.writing,
|
||||
achieved: user.levels?.writing || 0 >= user.desiredLevels?.writing || 9,
|
||||
},
|
||||
{
|
||||
module: "speaking",
|
||||
icon: () => <BsMegaphone className="h-4 w-4 text-white" />,
|
||||
achieved: user.levels.speaking >= user.desiredLevels.speaking,
|
||||
achieved: user.levels?.speaking || 0 >= user.desiredLevels?.speaking || 9,
|
||||
},
|
||||
{
|
||||
module: "level",
|
||||
icon: () => <BsClipboard className="h-4 w-4 text-white" />,
|
||||
achieved: user.levels.level >= user.desiredLevels.level,
|
||||
achieved: user.levels?.level || 0 >= user.desiredLevels?.level || 9,
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@@ -31,12 +31,40 @@ interface Props {
|
||||
user: User;
|
||||
}
|
||||
|
||||
const studentHash = {
|
||||
type: "student",
|
||||
size: 25,
|
||||
orderBy: "registrationDate",
|
||||
};
|
||||
|
||||
const teacherHash = {
|
||||
type: "teacher",
|
||||
size: 25,
|
||||
orderBy: "registrationDate",
|
||||
};
|
||||
|
||||
const corporateHash = {
|
||||
type: "corporate",
|
||||
size: 25,
|
||||
orderBy: "registrationDate",
|
||||
};
|
||||
|
||||
const agentsHash = {
|
||||
type: "agent",
|
||||
size: 25,
|
||||
orderBy: "registrationDate",
|
||||
};
|
||||
|
||||
export default function AdminDashboard({user}: Props) {
|
||||
const [page, setPage] = useState("");
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
|
||||
const {users, reload, isLoading} = useUsers();
|
||||
const {users: students, total: totalStudents, reload: reloadStudents, isLoading: isStudentsLoading} = useUsers(studentHash);
|
||||
const {users: teachers, total: totalTeachers, reload: reloadTeachers, isLoading: isTeachersLoading} = useUsers(teacherHash);
|
||||
const {users: corporates, total: totalCorporate, reload: reloadCorporates, isLoading: isCorporatesLoading} = useUsers(corporateHash);
|
||||
const {users: agents, total: totalAgents, reload: reloadAgents, isLoading: isAgentsLoading} = useUsers(corporateHash);
|
||||
|
||||
const {groups} = useGroups({});
|
||||
const {pending, done} = usePaymentStatusUsers();
|
||||
|
||||
@@ -47,9 +75,6 @@ export default function AdminDashboard({user}: Props) {
|
||||
setShowModal(!!selectedUser && router.asPath === "/#");
|
||||
}, [selectedUser, router.asPath]);
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
useEffect(reload, [page]);
|
||||
|
||||
const inactiveCountryManagerFilter = (x: User) => x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate);
|
||||
|
||||
const UserDisplay = (displayUser: User) => (
|
||||
@@ -279,50 +304,50 @@ export default function AdminDashboard({user}: Props) {
|
||||
<section className="w-full grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 place-items-center items-center justify-between">
|
||||
<IconCard
|
||||
Icon={BsPersonFill}
|
||||
isLoading={isLoading}
|
||||
isLoading={isStudentsLoading}
|
||||
label="Students"
|
||||
value={users.filter((x) => x.type === "student").length}
|
||||
value={totalStudents}
|
||||
onClick={() => router.push("/#students")}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsPencilSquare}
|
||||
isLoading={isLoading}
|
||||
isLoading={isTeachersLoading}
|
||||
label="Teachers"
|
||||
value={users.filter((x) => x.type === "teacher").length}
|
||||
value={totalTeachers}
|
||||
onClick={() => router.push("/#teachers")}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsBank}
|
||||
isLoading={isLoading}
|
||||
isLoading={isCorporatesLoading}
|
||||
label="Corporate"
|
||||
value={users.filter((x) => x.type === "corporate").length}
|
||||
value={totalCorporate}
|
||||
onClick={() => router.push("/#corporate")}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsBriefcaseFill}
|
||||
isLoading={isLoading}
|
||||
isLoading={isAgentsLoading}
|
||||
label="Country Managers"
|
||||
value={users.filter((x) => x.type === "agent").length}
|
||||
value={totalAgents}
|
||||
onClick={() => router.push("/#agents")}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsGlobeCentralSouthAsia}
|
||||
isLoading={isLoading}
|
||||
isLoading={isAgentsLoading}
|
||||
label="Countries"
|
||||
value={[...new Set(users.filter((x) => x.demographicInformation).map((x) => x.demographicInformation?.country))].length}
|
||||
value={[...new Set(agents.filter((x) => x.demographicInformation).map((x) => x.demographicInformation?.country))].length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => router.push("/#inactiveStudents")}
|
||||
Icon={BsPersonFill}
|
||||
isLoading={isLoading}
|
||||
isLoading={isStudentsLoading}
|
||||
label="Inactive Students"
|
||||
value={
|
||||
users.filter((x) => x.type === "student" && (x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate)))
|
||||
students.filter((x) => x.type === "student" && (x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate)))
|
||||
.length
|
||||
}
|
||||
color="rose"
|
||||
@@ -330,26 +355,26 @@ export default function AdminDashboard({user}: Props) {
|
||||
<IconCard
|
||||
onClick={() => router.push("/#inactiveCountryManagers")}
|
||||
Icon={BsBriefcaseFill}
|
||||
isLoading={isLoading}
|
||||
isLoading={isAgentsLoading}
|
||||
label="Inactive Country Managers"
|
||||
value={users.filter(inactiveCountryManagerFilter).length}
|
||||
value={agents.filter(inactiveCountryManagerFilter).length}
|
||||
color="rose"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => router.push("/#inactiveCorporate")}
|
||||
Icon={BsBank}
|
||||
isLoading={isLoading}
|
||||
isLoading={isCorporatesLoading}
|
||||
label="Inactive Corporate"
|
||||
value={
|
||||
users.filter((x) => x.type === "corporate" && (x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate)))
|
||||
.length
|
||||
corporates.filter(
|
||||
(x) => x.type === "corporate" && (x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate)),
|
||||
).length
|
||||
}
|
||||
color="rose"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => router.push("/#paymentdone")}
|
||||
Icon={BsCurrencyDollar}
|
||||
isLoading={isLoading}
|
||||
label="Payment Done"
|
||||
value={done.length}
|
||||
color="purple"
|
||||
@@ -357,7 +382,6 @@ export default function AdminDashboard({user}: Props) {
|
||||
<IconCard
|
||||
onClick={() => router.push("/#paymentpending")}
|
||||
Icon={BsCurrencyDollar}
|
||||
isLoading={isLoading}
|
||||
label="Pending Payment"
|
||||
value={pending.length}
|
||||
color="rose"
|
||||
@@ -365,14 +389,13 @@ export default function AdminDashboard({user}: Props) {
|
||||
<IconCard
|
||||
onClick={() => router.push("https://cms.encoach.com/admin")}
|
||||
Icon={BsLayoutSidebar}
|
||||
isLoading={isLoading}
|
||||
label="Content Management System (CMS)"
|
||||
color="green"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => router.push("/#corporatestudentslevels")}
|
||||
Icon={BsPersonFill}
|
||||
isLoading={isLoading}
|
||||
isLoading={isStudentsLoading}
|
||||
label="Corporate Students Levels"
|
||||
color="purple"
|
||||
/>
|
||||
@@ -382,8 +405,7 @@ export default function AdminDashboard({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((x) => x.type === "student")
|
||||
{students
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
@@ -393,8 +415,7 @@ export default function AdminDashboard({user}: Props) {
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest teachers</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter((x) => x.type === "teacher")
|
||||
{teachers
|
||||
.sort((a, b) => {
|
||||
return dateSorter(a, b, "desc", "registrationDate");
|
||||
})
|
||||
@@ -406,8 +427,7 @@ export default function AdminDashboard({user}: Props) {
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest corporate</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter((x) => x.type === "corporate")
|
||||
{corporates
|
||||
.sort((a, b) => {
|
||||
return dateSorter(a, b, "desc", "registrationDate");
|
||||
})
|
||||
@@ -419,8 +439,8 @@ export default function AdminDashboard({user}: Props) {
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Unpaid Corporate</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter((x) => x.type === "corporate" && x.status === "paymentDue")
|
||||
{corporates
|
||||
.filter((x) => x.status === "paymentDue")
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
@@ -429,10 +449,9 @@ export default function AdminDashboard({user}: Props) {
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Students expiring in 1 month</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
{students
|
||||
.filter(
|
||||
(x) =>
|
||||
x.type === "student" &&
|
||||
x.subscriptionExpirationDate &&
|
||||
moment().isAfter(moment(x.subscriptionExpirationDate).subtract(30, "days")) &&
|
||||
moment().isBefore(moment(x.subscriptionExpirationDate)),
|
||||
@@ -445,10 +464,9 @@ export default function AdminDashboard({user}: Props) {
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Teachers expiring in 1 month</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
{teachers
|
||||
.filter(
|
||||
(x) =>
|
||||
x.type === "teacher" &&
|
||||
x.subscriptionExpirationDate &&
|
||||
moment().isAfter(moment(x.subscriptionExpirationDate).subtract(30, "days")) &&
|
||||
moment().isBefore(moment(x.subscriptionExpirationDate)),
|
||||
@@ -461,10 +479,9 @@ export default function AdminDashboard({user}: Props) {
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Country Manager expiring in 1 month</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
{agents
|
||||
.filter(
|
||||
(x) =>
|
||||
x.type === "agent" &&
|
||||
x.subscriptionExpirationDate &&
|
||||
moment().isAfter(moment(x.subscriptionExpirationDate).subtract(30, "days")) &&
|
||||
moment().isBefore(moment(x.subscriptionExpirationDate)),
|
||||
@@ -477,10 +494,9 @@ export default function AdminDashboard({user}: Props) {
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Corporate expiring in 1 month</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
{corporates
|
||||
.filter(
|
||||
(x) =>
|
||||
x.type === "corporate" &&
|
||||
x.subscriptionExpirationDate &&
|
||||
moment().isAfter(moment(x.subscriptionExpirationDate).subtract(30, "days")) &&
|
||||
moment().isBefore(moment(x.subscriptionExpirationDate)),
|
||||
@@ -493,10 +509,8 @@ export default function AdminDashboard({user}: Props) {
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Expired Students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(
|
||||
(x) => x.type === "student" && x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)),
|
||||
)
|
||||
{students
|
||||
.filter((x) => x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
@@ -505,10 +519,8 @@ export default function AdminDashboard({user}: Props) {
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Expired Teachers</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(
|
||||
(x) => x.type === "teacher" && x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)),
|
||||
)
|
||||
{teachers
|
||||
.filter((x) => x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
@@ -517,10 +529,8 @@ export default function AdminDashboard({user}: Props) {
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Expired Country Manager</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(
|
||||
(x) => x.type === "agent" && x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)),
|
||||
)
|
||||
{agents
|
||||
.filter((x) => x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
@@ -529,11 +539,8 @@ export default function AdminDashboard({user}: Props) {
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Expired Corporate</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(
|
||||
(x) =>
|
||||
x.type === "corporate" && x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)),
|
||||
)
|
||||
{corporates
|
||||
.filter((x) => x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
@@ -553,7 +560,10 @@ export default function AdminDashboard({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();
|
||||
if (shouldReload && selectedUser!.type === "agent") reloadAgents();
|
||||
}}
|
||||
onViewStudents={
|
||||
selectedUser.type === "corporate" || selectedUser.type === "teacher"
|
||||
|
||||
@@ -1,400 +1,546 @@
|
||||
/* 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 UserList from "@/pages/(admin)/Lists/UserList";
|
||||
import {dateSorter} from "@/utils";
|
||||
import moment from "moment";
|
||||
import {useEffect, useMemo, useState} from "react";
|
||||
import useUsers, {
|
||||
userHashStudent,
|
||||
userHashTeacher,
|
||||
userHashCorporate,
|
||||
} from "@/hooks/useUsers";
|
||||
import {
|
||||
BsArrowLeft,
|
||||
BsClipboard2Data,
|
||||
BsClipboard2DataFill,
|
||||
BsClock,
|
||||
BsGlobeCentralSouthAsia,
|
||||
BsPaperclip,
|
||||
BsPerson,
|
||||
BsPersonAdd,
|
||||
BsPersonFill,
|
||||
BsPersonFillGear,
|
||||
BsPersonGear,
|
||||
BsPencilSquare,
|
||||
BsPersonBadge,
|
||||
BsPersonCheck,
|
||||
BsPeople,
|
||||
BsArrowRepeat,
|
||||
BsPlus,
|
||||
BsEnvelopePaper,
|
||||
CorporateUser,
|
||||
Group,
|
||||
MasterCorporateUser,
|
||||
Stat,
|
||||
User,
|
||||
} from "@/interfaces/user";
|
||||
import UserList from "@/pages/(admin)/Lists/UserList";
|
||||
import { dateSorter } from "@/utils";
|
||||
import moment from "moment";
|
||||
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,
|
||||
} 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);
|
||||
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 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(
|
||||
() =>
|
||||
[...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 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]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setShowModal(!!selectedUser && router.asPath === "/#");
|
||||
}, [selectedUser, router.asPath]);
|
||||
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" />
|
||||
<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 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} />;
|
||||
|
||||
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 === "/#assignments")
|
||||
return (
|
||||
<AssignmentsPage
|
||||
assignments={assignments}
|
||||
user={user}
|
||||
groups={assignmentsGroups}
|
||||
reloadAssignments={reloadAssignments}
|
||||
isLoading={isAssignmentsLoading}
|
||||
onBack={() => router.push("/")}
|
||||
/>
|
||||
);
|
||||
|
||||
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),
|
||||
});
|
||||
if (router.asPath === "/#statistical") return <MasterStatisticalPage />;
|
||||
|
||||
router.push("/list/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
user={selectedUser}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</Modal>
|
||||
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),
|
||||
});
|
||||
|
||||
<>
|
||||
{!!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")}
|
||||
/>
|
||||
<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
|
||||
}
|
||||
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),
|
||||
});
|
||||
|
||||
<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>
|
||||
</>
|
||||
</>
|
||||
);
|
||||
router.push("/list/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
user={selectedUser}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</Modal>
|
||||
|
||||
<>
|
||||
{!!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>
|
||||
</>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,23 +7,14 @@ import {BsArrowLeft} from "react-icons/bs";
|
||||
import MasterStatistical from "./MasterStatistical";
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
groupedByNameCorporates: Record<string, CorporateUser[]>;
|
||||
}
|
||||
|
||||
const MasterStatisticalPage = () => {
|
||||
const MasterStatisticalPage = ({ groupedByNameCorporates }: Props) => {
|
||||
const {users} = useUsers();
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const groupedByNameCorporates = useMemo(
|
||||
() =>
|
||||
groupBy(
|
||||
users.filter((x) => x.type === "corporate"),
|
||||
(x: CorporateUser) => x.corporateInformation?.companyInformation?.name || "N/A",
|
||||
),
|
||||
[users],
|
||||
);
|
||||
|
||||
const groupedByNameCorporateIds = useMemo(
|
||||
() =>
|
||||
Object.keys(groupedByNameCorporates).reduce((accm, x) => {
|
||||
|
||||
@@ -129,6 +129,20 @@ export default function MasterCorporateDashboard({user}: Props) {
|
||||
</div>
|
||||
);
|
||||
|
||||
const {users} = useUsers();
|
||||
|
||||
|
||||
const groupedByNameCorporates = useMemo(
|
||||
() =>
|
||||
groupBy(
|
||||
users.filter((x) => x.type === "corporate"),
|
||||
(x: CorporateUser) => x.corporateInformation?.companyInformation?.name || "N/A",
|
||||
) as Record<string, CorporateUser[]>,
|
||||
[users],
|
||||
);
|
||||
|
||||
const groupedByNameCorporatesKeys = Object.keys(groupedByNameCorporates);
|
||||
|
||||
const GroupsList = () => {
|
||||
return (
|
||||
<>
|
||||
@@ -148,7 +162,7 @@ export default function MasterCorporateDashboard({user}: Props) {
|
||||
};
|
||||
|
||||
if (router.asPath === "/#studentsPerformance") return <StudentPerformancePage user={user} />;
|
||||
if (router.asPath === "/#statistical") return <MasterStatisticalPage />;
|
||||
if (router.asPath === "/#statistical") return <MasterStatisticalPage groupedByNameCorporates={groupedByNameCorporates} />;
|
||||
if (router.asPath === "/#groups") return <GroupsList />;
|
||||
|
||||
if (router.asPath === "/#students")
|
||||
@@ -360,7 +374,7 @@ export default function MasterCorporateDashboard({user}: Props) {
|
||||
color="purple"
|
||||
onClick={() => router.push("/#corporate")}
|
||||
/>
|
||||
<IconCard Icon={BsBank} label="Corporate" value={totalCorporate} isLoading={isCorporatesLoading} color="purple" />
|
||||
<IconCard Icon={BsBank} label="Corporate" value={groupedByNameCorporatesKeys.length} isLoading={isCorporatesLoading} color="purple" />
|
||||
<IconCard
|
||||
Icon={BsPersonFillGear}
|
||||
isLoading={isStudentsLoading}
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import {Exam} from "@/interfaces/exam";
|
||||
import {ExamState} from "@/stores/examStore";
|
||||
import Axios from "axios";
|
||||
import axios from "axios";
|
||||
import {setupCache} from "axios-cache-interceptor";
|
||||
import {useEffect, useState} from "react";
|
||||
|
||||
const instance = Axios.create();
|
||||
const axios = setupCache(instance);
|
||||
|
||||
export type Session = ExamState & {user: string; id: string; date: string};
|
||||
|
||||
export default function useSessions(user?: string) {
|
||||
|
||||
@@ -16,9 +16,9 @@ export default function useUser({redirectTo = "", redirectIfFound = false} = {})
|
||||
|
||||
if (
|
||||
// If redirectIfFound is also set, redirect if the user was found
|
||||
(redirectIfFound && user && user.isVerified) ||
|
||||
(redirectIfFound && user) ||
|
||||
// If redirectTo is set, redirect if the user was not found.
|
||||
(redirectTo && !redirectIfFound && (!user || (user && !user.isVerified)))
|
||||
(redirectTo && !redirectIfFound && !user)
|
||||
) {
|
||||
Router.push(redirectTo);
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ const USER_TYPE_PERMISSIONS: {
|
||||
},
|
||||
admin: {
|
||||
perm: "createCodeAdmin",
|
||||
list: ["student", "teacher", "agent", "corporate", "admin", "mastercorporate"],
|
||||
list: ["student", "teacher", "agent", "corporate", "mastercorporate"],
|
||||
},
|
||||
developer: {
|
||||
perm: undefined,
|
||||
@@ -161,7 +161,7 @@ export default function BatchCreateUser({user, users, permissions, onFinish}: Pr
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
await axios.post("/api/batch_users", { users: newUsers.map(user => ({...user, type, expiryDate})) });
|
||||
await axios.post("/api/batch_users", {users: newUsers.map((user) => ({...user, type, expiryDate}))});
|
||||
toast.success(`Successfully added ${newUsers.length} user(s)!`);
|
||||
onFinish();
|
||||
} catch {
|
||||
|
||||
@@ -31,6 +31,10 @@ import useUserBalance from "@/hooks/useUserBalance";
|
||||
const columnHelper = createColumnHelper<User>();
|
||||
const searchFields = [["name"], ["email"], ["corporateInformation", "companyInformation", "name"]];
|
||||
|
||||
const corporatesHash = {
|
||||
type: "corporate",
|
||||
};
|
||||
|
||||
const CompanyNameCell = ({users, user, groups}: {user: User; users: User[]; groups: Group[]}) => {
|
||||
const [companyName, setCompanyName] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
@@ -70,6 +74,10 @@ export default function UserList({
|
||||
);
|
||||
|
||||
const {users, total, isLoading, reload} = useUsers(userHash);
|
||||
const {users: corporates} = useUsers(corporatesHash);
|
||||
|
||||
const totalUsers = useMemo(() => [...users, ...corporates], [users, corporates]);
|
||||
|
||||
const {permissions} = usePermissions(user?.id || "");
|
||||
const {balance} = useUserBalance();
|
||||
const {groups} = useGroups({
|
||||
@@ -354,7 +362,7 @@ export default function UserList({
|
||||
<SorterArrow name="companyName" />
|
||||
</button>
|
||||
) as any,
|
||||
cell: (info) => <CompanyNameCell user={info.row.original} users={users} groups={groups} />,
|
||||
cell: (info) => <CompanyNameCell user={info.row.original} users={totalUsers} groups={groups} />,
|
||||
}),
|
||||
columnHelper.accessor("subscriptionExpirationDate", {
|
||||
header: (
|
||||
|
||||
@@ -141,7 +141,11 @@ export default function UserCreator({user, users, permissions, onFinish}: Props)
|
||||
setType("student");
|
||||
setPosition(undefined);
|
||||
})
|
||||
.catch(() => toast.error("Something went wrong! Please try again later!"))
|
||||
.catch((error) => {
|
||||
const data = error?.response?.data;
|
||||
if (!!data?.message) return toast.error(data.message);
|
||||
toast.error("Something went wrong! Please try again later!");
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
|
||||
@@ -218,6 +218,8 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
return res.status(200).json({ok: true});
|
||||
})
|
||||
.catch((error) => {
|
||||
if (error.code.includes("email-already-in-use")) return res.status(403).json({error, message: "E-mail is already in the platform."});
|
||||
|
||||
console.log(`Failing - ${email}`);
|
||||
console.log(error);
|
||||
return res.status(401).json({error});
|
||||
|
||||
@@ -24,7 +24,7 @@ async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||
const {user} = req.query as {user?: string};
|
||||
|
||||
const q = user ? {user: user} : {};
|
||||
const sessions = await db.collection("sessions").find<Session>(q).toArray();
|
||||
const sessions = await db.collection("sessions").find<Session>(q).limit(10).toArray();
|
||||
|
||||
res.status(200).json(
|
||||
sessions.filter((x) => {
|
||||
@@ -41,12 +41,8 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
return;
|
||||
}
|
||||
const session = req.body;
|
||||
|
||||
await db.collection("sessions").updateOne(
|
||||
{ id: session.id},
|
||||
{ $set: session },
|
||||
{ upsert: true }
|
||||
);
|
||||
|
||||
await db.collection("sessions").updateOne({id: session.id}, {$set: session}, {upsert: true});
|
||||
|
||||
res.status(200).json({ok: true});
|
||||
}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { app, storage } from "@/firebase";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { Group, User } from "@/interfaces/user";
|
||||
import { getDownloadURL, getStorage, ref, uploadBytes } from "firebase/storage";
|
||||
import { getAuth, signInWithEmailAndPassword, updateEmail, updatePassword } from "firebase/auth";
|
||||
import { errorMessages } from "@/constants/errors";
|
||||
import type {NextApiRequest, NextApiResponse} from "next";
|
||||
import {app, storage} from "@/firebase";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {Group, User} from "@/interfaces/user";
|
||||
import {getDownloadURL, getStorage, ref, uploadBytes} from "firebase/storage";
|
||||
import {getAuth, signInWithEmailAndPassword, updateEmail, updatePassword} from "firebase/auth";
|
||||
import {errorMessages} from "@/constants/errors";
|
||||
import moment from "moment";
|
||||
import ShortUniqueId from "short-unique-id";
|
||||
import { Payment } from "@/interfaces/paypal";
|
||||
import { toFixedNumber } from "@/utils/number";
|
||||
import { propagateExpiryDateChanges, propagateStatusChange } from "@/utils/propagate.user.changes";
|
||||
import {Payment} from "@/interfaces/paypal";
|
||||
import {toFixedNumber} from "@/utils/number";
|
||||
import {propagateExpiryDateChanges, propagateStatusChange} from "@/utils/propagate.user.changes";
|
||||
import client from "@/lib/mongodb";
|
||||
|
||||
const db = client.db(process.env.MONGODB_DB);
|
||||
@@ -41,7 +41,7 @@ const managePaymentRecords = async (user: User, userId: string | undefined): Pro
|
||||
date: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const corporatePayments = await db.collection("payments").find({ corporate: userId }).toArray();
|
||||
const corporatePayments = await db.collection("payments").find({corporate: userId}).toArray();
|
||||
if (corporatePayments.length === 0) {
|
||||
await addPaymentRecord(data);
|
||||
return true;
|
||||
@@ -71,21 +71,17 @@ const managePaymentRecords = async (user: User, userId: string | undefined): Pro
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ ok: false });
|
||||
res.status(401).json({ok: false});
|
||||
return;
|
||||
}
|
||||
|
||||
const queryId = req.query.id as string;
|
||||
|
||||
const userId = queryId ? (queryId as string) : req.session.user.id
|
||||
let user = await db.collection("users").findOne<User>({ id: userId });
|
||||
const updatedUser = req.body as User & { password?: string; newPassword?: string };
|
||||
let user = await db.collection("users").findOne<User>({id: queryId ? (queryId as string) : req.session.user.id});
|
||||
const updatedUser = req.body as User & {password?: string; newPassword?: string};
|
||||
|
||||
if (!!queryId) {
|
||||
await db.collection("users").updateOne(
|
||||
{ id: queryId },
|
||||
{ $set: updatedUser }
|
||||
);
|
||||
await db.collection("users").updateOne({id: queryId}, {$set: updatedUser});
|
||||
|
||||
await managePaymentRecords(updatedUser, updatedUser.id);
|
||||
if (updatedUser.status || updatedUser.type === "corporate") {
|
||||
@@ -94,7 +90,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
propagateExpiryDateChanges(queryId, user?.subscriptionExpirationDate, updatedUser.subscriptionExpirationDate || null);
|
||||
}
|
||||
|
||||
res.status(200).json({ ok: true });
|
||||
res.status(200).json({ok: true});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -114,17 +110,17 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const credential = await signInWithEmailAndPassword(auth, req.session.user.email, updatedUser.password);
|
||||
await updatePassword(credential.user, updatedUser.newPassword);
|
||||
} catch {
|
||||
res.status(400).json({ error: "E001", message: errorMessages.E001 });
|
||||
res.status(400).json({error: "E001", message: errorMessages.E001});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (updatedUser.email !== req.session.user.email && updatedUser.password) {
|
||||
try {
|
||||
const usersWithSameEmail = await db.collection("users").find({ email: updatedUser.email.toLowerCase() }).toArray();
|
||||
const usersWithSameEmail = await db.collection("users").find({email: updatedUser.email.toLowerCase()}).toArray();
|
||||
|
||||
if (usersWithSameEmail.length > 0) {
|
||||
res.status(400).json({ error: "E003", message: errorMessages.E003 });
|
||||
res.status(400).json({error: "E003", message: errorMessages.E003});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -132,22 +128,24 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
await updateEmail(credential.user, updatedUser.email);
|
||||
|
||||
if (req.session.user.type === "student") {
|
||||
const corporateAdmins = (await db.collection("users").find<User>({ type: "corporate" }).toArray()).map((x) => x.id);
|
||||
const corporateAdmins = (await db.collection("users").find<User>({type: "corporate"}).toArray()).map((x) => x.id);
|
||||
|
||||
const groups = await db.collection("groups").find<Group>({
|
||||
participants: req.session.user!.id,
|
||||
admin: { $in: corporateAdmins }
|
||||
}).toArray();
|
||||
const groups = await db
|
||||
.collection("groups")
|
||||
.find<Group>({
|
||||
participants: req.session.user!.id,
|
||||
admin: {$in: corporateAdmins},
|
||||
})
|
||||
.toArray();
|
||||
|
||||
groups.forEach(async (group) => {
|
||||
await db.collection("groups").updateOne(
|
||||
{ id: group.id },
|
||||
{ $set: { participants: group.participants.filter((x) => x !== req.session.user!.id) } }
|
||||
);
|
||||
await db
|
||||
.collection("groups")
|
||||
.updateOne({id: group.id}, {$set: {participants: group.participants.filter((x) => x !== req.session.user!.id)}});
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
res.status(400).json({ error: "E002", message: errorMessages.E002 });
|
||||
res.status(400).json({error: "E002", message: errorMessages.E002});
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -160,22 +158,18 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
delete updatedUser.password;
|
||||
delete updatedUser.newPassword;
|
||||
|
||||
await db.collection("users").updateOne(
|
||||
{ id: userId },
|
||||
{ $set: updatedUser }
|
||||
);
|
||||
|
||||
user = await db.collection("users").findOne<User>({ id: req.session.user.id });
|
||||
await db.collection("users").updateOne({id: queryId}, {$set: updatedUser});
|
||||
|
||||
if (!queryId) {
|
||||
req.session.user = user ? user : null;
|
||||
req.session.user = updatedUser ? {...updatedUser, id: req.session.user.id} : null;
|
||||
await req.session.save();
|
||||
}
|
||||
|
||||
if (user) {
|
||||
await managePaymentRecords(user, queryId);
|
||||
if ({...updatedUser, id: req.session.user!.id}) {
|
||||
await managePaymentRecords({...updatedUser, id: req.session.user!.id}, queryId);
|
||||
}
|
||||
res.status(200).json({ user });
|
||||
|
||||
res.status(200).json({user: {...updatedUser, id: req.session.user!.id}});
|
||||
}
|
||||
|
||||
export const config = {
|
||||
|
||||
@@ -10,7 +10,7 @@ import {User} from "@/interfaces/user";
|
||||
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
const user = req.session.user;
|
||||
|
||||
if (!user || !user.isVerified) {
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
|
||||
@@ -10,7 +10,7 @@ import {User} from "@/interfaces/user";
|
||||
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
const user = req.session.user;
|
||||
|
||||
if (!user || !user.isVerified) {
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
|
||||
@@ -27,7 +27,7 @@ import {User} from "@/interfaces/user";
|
||||
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
const user = req.session.user;
|
||||
|
||||
if (!user || !user.isVerified) {
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
|
||||
@@ -43,7 +43,7 @@ import {getUsers} from "@/utils/users.be";
|
||||
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||
const user = req.session.user;
|
||||
|
||||
if (!user || !user.isVerified) {
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
|
||||
@@ -46,7 +46,7 @@ export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||
envVariables[x] = process.env[x]!;
|
||||
});
|
||||
|
||||
if (!user || !user.isVerified) {
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
@@ -68,22 +68,18 @@ interface Props {
|
||||
linkedCorporate?: CorporateUser | MasterCorporateUser;
|
||||
}
|
||||
|
||||
export default function Home({linkedCorporate}: Props) {
|
||||
export default function Home({user: propsUser, linkedCorporate}: Props) {
|
||||
const [user, setUser] = useState(propsUser);
|
||||
const [showDiagnostics, setShowDiagnostics] = useState(false);
|
||||
const [showDemographicInput, setShowDemographicInput] = useState(false);
|
||||
const [selectedScreen, setSelectedScreen] = useState<Type>("admin");
|
||||
|
||||
const {user, mutateUser} = useUser({redirectTo: "/login"});
|
||||
const {mutateUser} = useUser({redirectTo: "/login"});
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
setShowDemographicInput(
|
||||
!user.demographicInformation ||
|
||||
!user.demographicInformation.country ||
|
||||
!user.demographicInformation.gender ||
|
||||
!user.demographicInformation.phone,
|
||||
);
|
||||
// setShowDemographicInput(!user.demographicInformation || !user.demographicInformation.country || !user.demographicInformation.phone);
|
||||
setShowDiagnostics(user.isFirstLogin && user.type === "student");
|
||||
}
|
||||
}, [user]);
|
||||
@@ -135,7 +131,13 @@ export default function Home({linkedCorporate}: Props) {
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<Layout user={user} navDisabled>
|
||||
<DemographicInformationInput mutateUser={mutateUser} user={user} />
|
||||
<DemographicInformationInput
|
||||
mutateUser={(user) => {
|
||||
setUser(user);
|
||||
mutateUser(user);
|
||||
}}
|
||||
user={user}
|
||||
/>
|
||||
</Layout>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -21,7 +21,7 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
envVariables[x] = process.env[x]!;
|
||||
});
|
||||
|
||||
if (!user || !user.isVerified) {
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
|
||||
@@ -28,7 +28,7 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
envVariables[x] = process.env[x]!;
|
||||
});
|
||||
|
||||
if (user && user.isVerified) {
|
||||
if (user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/",
|
||||
@@ -56,7 +56,7 @@ export default function Login() {
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (user && user.isVerified) router.push("/");
|
||||
if (user) router.push("/");
|
||||
}, [router, user]);
|
||||
|
||||
const forgotPassword = () => {
|
||||
@@ -173,7 +173,7 @@ export default function Login() {
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
{user && !user.isVerified && <EmailVerification user={user} isLoading={isLoading} setIsLoading={setIsLoading} />}
|
||||
{/* {user && !user.isVerified && <EmailVerification user={user} isLoading={isLoading} setIsLoading={setIsLoading} />} */}
|
||||
</section>
|
||||
</main>
|
||||
</>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -16,7 +16,7 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
envVariables[x] = process.env[x]!;
|
||||
});
|
||||
|
||||
if (!user || !user.isVerified) {
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
|
||||
@@ -32,7 +32,7 @@ export const getServerSideProps = withIronSessionSsr(async (context) => {
|
||||
const {req, params} = context;
|
||||
const user = req.session.user;
|
||||
|
||||
if (!user || !user.isVerified) {
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
|
||||
@@ -12,7 +12,7 @@ import PermissionList from "@/components/PermissionList";
|
||||
export const getServerSideProps = withIronSessionSsr(async ({req}) => {
|
||||
const user = req.session.user;
|
||||
|
||||
if (!user || !user.isVerified) {
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
|
||||
@@ -50,7 +50,7 @@ import {getUsers} from "@/utils/users.be";
|
||||
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||
const user = req.session.user;
|
||||
|
||||
if (!user || !user.isVerified) {
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
|
||||
@@ -29,7 +29,7 @@ import useGradingSystem from "@/hooks/useGrading";
|
||||
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||
const user = req.session.user;
|
||||
|
||||
if (!user || !user.isVerified) {
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
|
||||
@@ -121,7 +121,7 @@ export default function Register({code: queryCode}: {code: string}) {
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
{user && !user.isVerified && <EmailVerification user={user} isLoading={isLoading} setIsLoading={setIsLoading} />}
|
||||
{/* {user && !user.isVerified && <EmailVerification user={user} isLoading={isLoading} setIsLoading={setIsLoading} />} */}
|
||||
</section>
|
||||
</main>
|
||||
</>
|
||||
|
||||
@@ -31,7 +31,7 @@ import useUsers from "@/hooks/useUsers";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||
const user = req.session.user;
|
||||
if (!user || !user.isVerified) {
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
|
||||
@@ -34,7 +34,7 @@ const COLORS = ["#1EB3FF", "#FF790A", "#3D9F11", "#EF5DA8", "#414288"];
|
||||
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
const user = req.session.user;
|
||||
|
||||
if (!user || !user.isVerified) {
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
|
||||
@@ -22,7 +22,7 @@ const columnHelper = createColumnHelper<TicketWithCorporate>();
|
||||
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
const user = req.session.user;
|
||||
|
||||
if (!user || !user.isVerified) {
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
|
||||
@@ -35,7 +35,7 @@ import {sortByModule} from "@/utils/moduleUtils";
|
||||
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
const user = req.session.user;
|
||||
|
||||
if (!user || !user.isVerified) {
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
|
||||
@@ -1,30 +1,30 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import Head from "next/head";
|
||||
import { withIronSessionSsr } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { User } from "@/interfaces/user";
|
||||
import { ToastContainer } from "react-toastify";
|
||||
import {withIronSessionSsr} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {User} from "@/interfaces/user";
|
||||
import {ToastContainer} from "react-toastify";
|
||||
import Layout from "@/components/High/Layout";
|
||||
import { shouldRedirectHome } from "@/utils/navigation.disabled";
|
||||
import { useEffect, useState } from "react";
|
||||
import {shouldRedirectHome} from "@/utils/navigation.disabled";
|
||||
import {useEffect, useState} from "react";
|
||||
import clsx from "clsx";
|
||||
import { FaPlus } from "react-icons/fa";
|
||||
import {FaPlus} from "react-icons/fa";
|
||||
import useRecordStore from "@/stores/recordStore";
|
||||
import router from "next/router";
|
||||
import useTrainingContentStore from "@/stores/trainingContentStore";
|
||||
import axios from "axios";
|
||||
import { ITrainingContent } from "@/training/TrainingInterfaces";
|
||||
import {ITrainingContent} from "@/training/TrainingInterfaces";
|
||||
import moment from "moment";
|
||||
import { uuidv4 } from "@firebase/util";
|
||||
import {uuidv4} from "@firebase/util";
|
||||
import TrainingScore from "@/training/TrainingScore";
|
||||
import ModuleBadge from "@/components/ModuleBadge";
|
||||
import RecordFilter from "@/components/Medium/RecordFilter";
|
||||
import useFilterRecordsByUser from "@/hooks/useFilterRecordsByUser";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(({ req, res }) => {
|
||||
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
const user = req.session.user;
|
||||
|
||||
if (!user || !user.isVerified) {
|
||||
if (!user) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
@@ -43,22 +43,23 @@ export const getServerSideProps = withIronSessionSsr(({ req, res }) => {
|
||||
}
|
||||
|
||||
return {
|
||||
props: { user: req.session.user },
|
||||
props: {user: req.session.user},
|
||||
};
|
||||
}, sessionOptions);
|
||||
|
||||
const Training: React.FC<{ user: User }> = ({ user }) => {
|
||||
const [recordUserId, setRecordTraining] = useRecordStore((state) => [
|
||||
state.selectedUser,
|
||||
state.setTraining,
|
||||
]);
|
||||
const Training: React.FC<{user: User}> = ({user}) => {
|
||||
const [recordUserId, setRecordTraining] = useRecordStore((state) => [state.selectedUser, state.setTraining]);
|
||||
const [filter, setFilter] = useState<"months" | "weeks" | "days" | "assignments">();
|
||||
|
||||
const [stats, setTrainingStats] = useTrainingContentStore((state) => [state.stats, state.setStats]);
|
||||
const [isNewContentLoading, setIsNewContentLoading] = useState(stats.length != 0);
|
||||
const [groupedByTrainingContent, setGroupedByTrainingContent] = useState<{ [key: string]: ITrainingContent }>();
|
||||
const [groupedByTrainingContent, setGroupedByTrainingContent] = useState<{[key: string]: ITrainingContent}>();
|
||||
|
||||
const { data: trainingContent, isLoading: areRecordsLoading } = useFilterRecordsByUser<ITrainingContent[]>(recordUserId || user?.id, undefined, "training");
|
||||
const {data: trainingContent, isLoading: areRecordsLoading} = useFilterRecordsByUser<ITrainingContent[]>(
|
||||
recordUserId || user?.id,
|
||||
undefined,
|
||||
"training",
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const handleRouteChange = (url: string) => {
|
||||
@@ -74,7 +75,7 @@ const Training: React.FC<{ user: User }> = ({ user }) => {
|
||||
useEffect(() => {
|
||||
const postStats = async () => {
|
||||
try {
|
||||
const response = await axios.post<{ id: string }>(`/api/training`, { userID: user.id, stats: stats });
|
||||
const response = await axios.post<{id: string}>(`/api/training`, {userID: user.id, stats: stats});
|
||||
return response.data.id;
|
||||
} catch (error) {
|
||||
setIsNewContentLoading(false);
|
||||
@@ -97,12 +98,12 @@ const Training: React.FC<{ user: User }> = ({ user }) => {
|
||||
router.push("/record");
|
||||
};
|
||||
|
||||
const filterTrainingContentByDate = (trainingContent: { [key: string]: ITrainingContent }) => {
|
||||
const filterTrainingContentByDate = (trainingContent: {[key: string]: ITrainingContent}) => {
|
||||
if (filter) {
|
||||
const filterDate = moment()
|
||||
.subtract({ [filter as string]: 1 })
|
||||
.subtract({[filter as string]: 1})
|
||||
.format("x");
|
||||
const filteredTrainingContent: { [key: string]: ITrainingContent } = {};
|
||||
const filteredTrainingContent: {[key: string]: ITrainingContent} = {};
|
||||
|
||||
Object.keys(trainingContent).forEach((timestamp) => {
|
||||
if (timestamp >= filterDate) filteredTrainingContent[timestamp] = trainingContent[timestamp];
|
||||
@@ -117,10 +118,10 @@ const Training: React.FC<{ user: User }> = ({ user }) => {
|
||||
const grouped = trainingContent.reduce((acc, content) => {
|
||||
acc[content.created_at] = content;
|
||||
return acc;
|
||||
}, {} as { [key: number]: ITrainingContent });
|
||||
}, {} as {[key: number]: ITrainingContent});
|
||||
|
||||
setGroupedByTrainingContent(grouped);
|
||||
}else {
|
||||
} else {
|
||||
setGroupedByTrainingContent(undefined);
|
||||
}
|
||||
}, [trainingContent]);
|
||||
@@ -138,7 +139,7 @@ const Training: React.FC<{ user: User }> = ({ user }) => {
|
||||
|
||||
const trainingContentContainer = (timestamp: string) => {
|
||||
if (!groupedByTrainingContent) return <></>;
|
||||
|
||||
|
||||
const trainingContent: ITrainingContent = groupedByTrainingContent[timestamp];
|
||||
const uniqueModules = [...new Set(trainingContent.exams.map((exam) => exam.module))];
|
||||
|
||||
@@ -192,7 +193,7 @@ const Training: React.FC<{ user: User }> = ({ user }) => {
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<RecordFilter user={user} filterState={{ filter: filter, setFilter: setFilter }} assignments={false} >
|
||||
<RecordFilter user={user} filterState={{filter: filter, setFilter: setFilter}} assignments={false}>
|
||||
{user.type === "student" && (
|
||||
<>
|
||||
<div className="flex items-center">
|
||||
|
||||
@@ -5,7 +5,7 @@ import {DeveloperUser, Stat, StudentUser, User} from "@/interfaces/user";
|
||||
import {Module} from "@/interfaces";
|
||||
import {getCorporateUser} from "@/resources/user";
|
||||
import {getUserCorporate} from "./groups.be";
|
||||
import { Db, ObjectId } from "mongodb";
|
||||
import {Db, ObjectId} from "mongodb";
|
||||
|
||||
export const getExams = async (
|
||||
db: Db,
|
||||
@@ -18,18 +18,18 @@ export const getExams = async (
|
||||
variant?: Variant,
|
||||
instructorGender?: InstructorGender,
|
||||
): Promise<Exam[]> => {
|
||||
const allExams = await db
|
||||
.collection(module)
|
||||
.find<Exam>({
|
||||
isDiagnostic: false,
|
||||
})
|
||||
.toArray();
|
||||
|
||||
const allExams = await db.collection(module).find<Exam>({
|
||||
isDiagnostic: false
|
||||
}).toArray();
|
||||
|
||||
const shuffledPublicExams = (
|
||||
shuffle(
|
||||
allExams.map((doc) => ({
|
||||
...doc,
|
||||
module,
|
||||
})) as Exam[],
|
||||
)
|
||||
const shuffledPublicExams = shuffle(
|
||||
allExams.map((doc) => ({
|
||||
...doc,
|
||||
module,
|
||||
})) as Exam[],
|
||||
).filter((x) => !x.private);
|
||||
|
||||
let exams: Exam[] = await filterByOwners(shuffledPublicExams, userId);
|
||||
@@ -39,9 +39,12 @@ export const getExams = async (
|
||||
exams = await filterByPreference(db, exams, module, userId);
|
||||
|
||||
if (avoidRepeated === "true") {
|
||||
const stats = await db.collection("stats").find<Stat>({
|
||||
user: userId
|
||||
}).toArray();
|
||||
const stats = await db
|
||||
.collection("stats")
|
||||
.find<Stat>({
|
||||
user: userId,
|
||||
})
|
||||
.toArray();
|
||||
|
||||
const filteredExams = exams.filter((x) => !stats.map((s) => s.exam).includes(x.id));
|
||||
|
||||
@@ -78,7 +81,7 @@ const filterByOwners = async (exams: Exam[], userID?: string) => {
|
||||
|
||||
const filterByDifficulty = async (db: Db, exams: Exam[], module: Module, userID?: string) => {
|
||||
if (!userID) return exams;
|
||||
const user = await db.collection("users").findOne<User>({ _id: new ObjectId(userID) });
|
||||
const user = await db.collection("users").findOne<User>({id: userID});
|
||||
if (!user) return exams;
|
||||
|
||||
const difficulty = user.levels[module] <= 3 ? "easy" : user.levels[module] <= 6 ? "medium" : "hard";
|
||||
@@ -92,7 +95,7 @@ const filterByPreference = async (db: Db, exams: Exam[], module: Module, userID?
|
||||
|
||||
if (!userID) return exams;
|
||||
|
||||
const user = await db.collection("users").findOne<StudentUser | DeveloperUser>({ _id: new ObjectId(userID) });
|
||||
const user = await db.collection("users").findOne<StudentUser | DeveloperUser>({id: userID});
|
||||
if (!user) return exams;
|
||||
|
||||
if (!["developer", "student"].includes(user.type)) return exams;
|
||||
|
||||
@@ -56,7 +56,7 @@ export async function getLinkedUsers(
|
||||
|
||||
const participants = uniq([
|
||||
...adminGroups.flatMap((x) => x.participants),
|
||||
...groups.flat().flatMap((x) => x.participants),
|
||||
...(userType === "mastercorporate" ? groups.flat().flatMap((x) => x.participants) : []),
|
||||
...(userType === "teacher" ? belongingGroups.flatMap((x) => x.participants) : []),
|
||||
]);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user