Did some fixes related to master corporates
This commit is contained in:
@@ -1,273 +1,272 @@
|
||||
import Button from "@/components/Low/Button";
|
||||
import Checkbox from "@/components/Low/Checkbox";
|
||||
import { PERMISSIONS } from "@/constants/userPermissions";
|
||||
import { CorporateUser, TeacherUser, Type, User } from "@/interfaces/user";
|
||||
import { USER_TYPE_LABELS } from "@/resources/user";
|
||||
import {PERMISSIONS} from "@/constants/userPermissions";
|
||||
import {CorporateUser, TeacherUser, Type, User} from "@/interfaces/user";
|
||||
import {USER_TYPE_LABELS} from "@/resources/user";
|
||||
import axios from "axios";
|
||||
import clsx from "clsx";
|
||||
import { capitalize, uniqBy } from "lodash";
|
||||
import {capitalize, uniqBy} from "lodash";
|
||||
import moment from "moment";
|
||||
import { useEffect, useState } from "react";
|
||||
import {useEffect, useState} from "react";
|
||||
import ReactDatePicker from "react-datepicker";
|
||||
import { toast } from "react-toastify";
|
||||
import {toast} from "react-toastify";
|
||||
import ShortUniqueId from "short-unique-id";
|
||||
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
|
||||
import { PermissionType } from "@/interfaces/permissions";
|
||||
import {checkAccess, getTypesOfUser} from "@/utils/permissions";
|
||||
import {PermissionType} from "@/interfaces/permissions";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
import Input from "@/components/Low/Input";
|
||||
import CountrySelect from "@/components/Low/CountrySelect";
|
||||
import useGroups from "@/hooks/useGroups";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import { getUserName } from "@/utils/users";
|
||||
import {getUserName} from "@/utils/users";
|
||||
import Select from "@/components/Low/Select";
|
||||
import { EntityWithRoles } from "@/interfaces/entity";
|
||||
import {EntityWithRoles} from "@/interfaces/entity";
|
||||
import useEntitiesGroups from "@/hooks/useEntitiesGroups";
|
||||
import {mapBy} from "@/utils";
|
||||
|
||||
const USER_TYPE_PERMISSIONS: {
|
||||
[key in Type]: { perm: PermissionType | undefined; list: Type[] };
|
||||
[key in Type]: {perm: PermissionType | undefined; list: Type[]};
|
||||
} = {
|
||||
student: {
|
||||
perm: "createCodeStudent",
|
||||
list: [],
|
||||
},
|
||||
teacher: {
|
||||
perm: "createCodeTeacher",
|
||||
list: [],
|
||||
},
|
||||
agent: {
|
||||
perm: "createCodeCountryManager",
|
||||
list: ["student", "teacher", "corporate", "mastercorporate"],
|
||||
},
|
||||
corporate: {
|
||||
perm: "createCodeCorporate",
|
||||
list: ["student", "teacher"],
|
||||
},
|
||||
mastercorporate: {
|
||||
perm: undefined,
|
||||
list: ["student", "teacher", "corporate"],
|
||||
},
|
||||
admin: {
|
||||
perm: "createCodeAdmin",
|
||||
list: ["student", "teacher", "agent", "corporate", "admin", "mastercorporate"],
|
||||
},
|
||||
developer: {
|
||||
perm: undefined,
|
||||
list: ["student", "teacher", "agent", "corporate", "admin", "developer", "mastercorporate"],
|
||||
},
|
||||
student: {
|
||||
perm: "createCodeStudent",
|
||||
list: [],
|
||||
},
|
||||
teacher: {
|
||||
perm: "createCodeTeacher",
|
||||
list: [],
|
||||
},
|
||||
agent: {
|
||||
perm: "createCodeCountryManager",
|
||||
list: ["student", "teacher", "corporate", "mastercorporate"],
|
||||
},
|
||||
corporate: {
|
||||
perm: "createCodeCorporate",
|
||||
list: ["student", "teacher"],
|
||||
},
|
||||
mastercorporate: {
|
||||
perm: undefined,
|
||||
list: ["student", "teacher", "corporate"],
|
||||
},
|
||||
admin: {
|
||||
perm: "createCodeAdmin",
|
||||
list: ["student", "teacher", "agent", "corporate", "admin", "mastercorporate"],
|
||||
},
|
||||
developer: {
|
||||
perm: undefined,
|
||||
list: ["student", "teacher", "agent", "corporate", "admin", "developer", "mastercorporate"],
|
||||
},
|
||||
};
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
users: User[];
|
||||
entities: EntityWithRoles[]
|
||||
permissions: PermissionType[];
|
||||
onFinish: () => void;
|
||||
user: User;
|
||||
users: User[];
|
||||
entities: EntityWithRoles[];
|
||||
permissions: PermissionType[];
|
||||
onFinish: () => void;
|
||||
}
|
||||
|
||||
export default function UserCreator({ user, users, entities = [], permissions, onFinish }: Props) {
|
||||
const [name, setName] = useState<string>();
|
||||
const [email, setEmail] = useState<string>();
|
||||
const [phone, setPhone] = useState<string>();
|
||||
const [passportID, setPassportID] = useState<string>();
|
||||
const [studentID, setStudentID] = useState<string>();
|
||||
const [country, setCountry] = useState(user?.demographicInformation?.country);
|
||||
const [group, setGroup] = useState<string | null>();
|
||||
const [password, setPassword] = useState<string>();
|
||||
const [confirmPassword, setConfirmPassword] = useState<string>();
|
||||
const [expiryDate, setExpiryDate] = useState<Date | null>(
|
||||
user?.subscriptionExpirationDate ? moment(user?.subscriptionExpirationDate).toDate() : null,
|
||||
);
|
||||
const [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [type, setType] = useState<Type>("student");
|
||||
const [position, setPosition] = useState<string>();
|
||||
const [entity, setEntity] = useState((entities || [])[0]?.id || undefined)
|
||||
export default function UserCreator({user, users, entities = [], permissions, onFinish}: Props) {
|
||||
const [name, setName] = useState<string>();
|
||||
const [email, setEmail] = useState<string>();
|
||||
const [phone, setPhone] = useState<string>();
|
||||
const [passportID, setPassportID] = useState<string>();
|
||||
const [studentID, setStudentID] = useState<string>();
|
||||
const [country, setCountry] = useState(user?.demographicInformation?.country);
|
||||
const [group, setGroup] = useState<string | null>();
|
||||
const [password, setPassword] = useState<string>();
|
||||
const [confirmPassword, setConfirmPassword] = useState<string>();
|
||||
const [expiryDate, setExpiryDate] = useState<Date | null>(
|
||||
user?.subscriptionExpirationDate ? moment(user?.subscriptionExpirationDate).toDate() : null,
|
||||
);
|
||||
const [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [type, setType] = useState<Type>("student");
|
||||
const [position, setPosition] = useState<string>();
|
||||
const [entity, setEntity] = useState((entities || [])[0]?.id || undefined);
|
||||
|
||||
const { groups } = useEntitiesGroups();
|
||||
const {groups} = useEntitiesGroups();
|
||||
|
||||
useEffect(() => {
|
||||
if (!isExpiryDateEnabled) setExpiryDate(null);
|
||||
}, [isExpiryDateEnabled]);
|
||||
useEffect(() => {
|
||||
if (!isExpiryDateEnabled) setExpiryDate(null);
|
||||
}, [isExpiryDateEnabled]);
|
||||
|
||||
const createUser = () => {
|
||||
if (!name || name.trim().length === 0) return toast.error("Please enter a valid name!");
|
||||
if (!email || email.trim().length === 0) return toast.error("Please enter a valid e-mail address!");
|
||||
if (users.map((x) => x.email).includes(email.trim())) return toast.error("That e-mail is already in use!");
|
||||
if (!password || password.trim().length < 6) return toast.error("Please enter a valid password!");
|
||||
if (password !== confirmPassword) return toast.error("The passwords do not match!");
|
||||
const createUser = () => {
|
||||
if (!name || name.trim().length === 0) return toast.error("Please enter a valid name!");
|
||||
if (!email || email.trim().length === 0) return toast.error("Please enter a valid e-mail address!");
|
||||
if (users.map((x) => x.email).includes(email.trim())) return toast.error("That e-mail is already in use!");
|
||||
if (!password || password.trim().length < 6) return toast.error("Please enter a valid password!");
|
||||
if (password !== confirmPassword) return toast.error("The passwords do not match!");
|
||||
|
||||
setIsLoading(true);
|
||||
setIsLoading(true);
|
||||
|
||||
const body = {
|
||||
name,
|
||||
email,
|
||||
password,
|
||||
groupID: group,
|
||||
entity,
|
||||
type,
|
||||
studentID: type === "student" ? studentID : undefined,
|
||||
expiryDate,
|
||||
demographicInformation: {
|
||||
passport_id: type === "student" ? passportID : undefined,
|
||||
phone,
|
||||
country,
|
||||
position,
|
||||
},
|
||||
};
|
||||
const body = {
|
||||
name,
|
||||
email,
|
||||
password,
|
||||
groupID: group,
|
||||
entity,
|
||||
type,
|
||||
studentID: type === "student" ? studentID : undefined,
|
||||
expiryDate,
|
||||
demographicInformation: {
|
||||
passport_id: type === "student" ? passportID : undefined,
|
||||
phone,
|
||||
country,
|
||||
position,
|
||||
},
|
||||
};
|
||||
|
||||
axios
|
||||
.post("/api/make_user", body)
|
||||
.then(() => {
|
||||
toast.success("That user has been created!");
|
||||
onFinish();
|
||||
axios
|
||||
.post("/api/make_user", body)
|
||||
.then(() => {
|
||||
toast.success("That user has been created!");
|
||||
onFinish();
|
||||
|
||||
setName("");
|
||||
setEmail("");
|
||||
setPhone("");
|
||||
setPassportID("");
|
||||
setStudentID("");
|
||||
setCountry(user?.demographicInformation?.country);
|
||||
setGroup(null);
|
||||
setEntity((entities || [])[0]?.id || undefined)
|
||||
setExpiryDate(user?.subscriptionExpirationDate ? moment(user?.subscriptionExpirationDate).toDate() : null);
|
||||
setIsExpiryDateEnabled(true);
|
||||
setType("student");
|
||||
setPosition(undefined);
|
||||
})
|
||||
.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));
|
||||
};
|
||||
setName("");
|
||||
setEmail("");
|
||||
setPhone("");
|
||||
setPassportID("");
|
||||
setStudentID("");
|
||||
setCountry(user?.demographicInformation?.country);
|
||||
setGroup(null);
|
||||
setEntity((entities || [])[0]?.id || undefined);
|
||||
setExpiryDate(user?.subscriptionExpirationDate ? moment(user?.subscriptionExpirationDate).toDate() : null);
|
||||
setIsExpiryDateEnabled(true);
|
||||
setType("student");
|
||||
setPosition(undefined);
|
||||
})
|
||||
.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));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 border p-4 border-mti-gray-platinum rounded-xl">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Input required label="Name" value={name} onChange={setName} type="text" name="name" placeholder="Name" />
|
||||
<Input label="E-mail" required value={email} onChange={setEmail} type="email" name="email" placeholder="E-mail" />
|
||||
return (
|
||||
<div className="flex flex-col gap-4 border p-4 border-mti-gray-platinum rounded-xl">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Input required label="Name" value={name} onChange={setName} type="text" name="name" placeholder="Name" />
|
||||
<Input label="E-mail" required value={email} onChange={setEmail} type="email" name="email" placeholder="E-mail" />
|
||||
|
||||
<Input type="password" name="password" label="Password" value={password} onChange={setPassword} placeholder="Password" required />
|
||||
<Input
|
||||
type="password"
|
||||
name="confirmPassword"
|
||||
label="Confirm Password"
|
||||
value={confirmPassword}
|
||||
onChange={setConfirmPassword}
|
||||
placeholder="ConfirmPassword"
|
||||
required
|
||||
/>
|
||||
<Input type="password" name="password" label="Password" value={password} onChange={setPassword} placeholder="Password" required />
|
||||
<Input
|
||||
type="password"
|
||||
name="confirmPassword"
|
||||
label="Confirm Password"
|
||||
value={confirmPassword}
|
||||
onChange={setConfirmPassword}
|
||||
placeholder="ConfirmPassword"
|
||||
required
|
||||
/>
|
||||
|
||||
<div className="flex flex-col gap-4">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Country *</label>
|
||||
<CountrySelect value={country} onChange={setCountry} />
|
||||
</div>
|
||||
<div className="flex flex-col gap-4">
|
||||
<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" value={phone} onChange={setPhone} placeholder="Phone number" required />
|
||||
<Input type="tel" name="phone" label="Phone number" value={phone} onChange={setPhone} placeholder="Phone number" required />
|
||||
|
||||
{type === "student" && (
|
||||
<>
|
||||
<Input
|
||||
type="text"
|
||||
name="passport_id"
|
||||
label="Passport/National ID"
|
||||
onChange={setPassportID}
|
||||
value={passportID}
|
||||
placeholder="National ID or Passport number"
|
||||
required
|
||||
/>
|
||||
<Input type="text" name="studentID" label="Student ID" onChange={setStudentID} value={studentID} placeholder="Student ID" />
|
||||
</>
|
||||
)}
|
||||
{type === "student" && (
|
||||
<>
|
||||
<Input
|
||||
type="text"
|
||||
name="passport_id"
|
||||
label="Passport/National ID"
|
||||
onChange={setPassportID}
|
||||
value={passportID}
|
||||
placeholder="National ID or Passport number"
|
||||
required
|
||||
/>
|
||||
<Input type="text" name="studentID" label="Student ID" onChange={setStudentID} value={studentID} placeholder="Student ID" />
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className={clsx("flex flex-col gap-4")}>
|
||||
<label className="font-normal text-base text-mti-gray-dim">Entity</label>
|
||||
<Select
|
||||
defaultValue={{ value: (entities || [])[0]?.id, label: (entities || [])[0]?.label }}
|
||||
options={entities.map((e) => ({ value: e.id, label: e.label }))}
|
||||
onChange={(e) => setEntity(e?.value || undefined)}
|
||||
isClearable={checkAccess(user, ["admin", "developer"])}
|
||||
/>
|
||||
</div>
|
||||
<div className={clsx("flex flex-col gap-4")}>
|
||||
<label className="font-normal text-base text-mti-gray-dim">Entity</label>
|
||||
<Select
|
||||
defaultValue={{value: (entities || [])[0]?.id, label: (entities || [])[0]?.label}}
|
||||
options={entities.map((e) => ({value: e.id, label: e.label}))}
|
||||
onChange={(e) => setEntity(e?.value || undefined)}
|
||||
isClearable={checkAccess(user, ["admin", "developer"])}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{["corporate", "mastercorporate"].includes(type) && (
|
||||
<Input type="text" name="department" label="Department" onChange={setPosition} value={position} placeholder="Department" />
|
||||
)}
|
||||
{["corporate", "mastercorporate"].includes(type) && (
|
||||
<Input type="text" name="department" label="Department" onChange={setPosition} value={position} placeholder="Department" />
|
||||
)}
|
||||
|
||||
<div className={clsx("flex flex-col gap-4")}>
|
||||
<label className="font-normal text-base text-mti-gray-dim">Classroom</label>
|
||||
<Select
|
||||
options={groups
|
||||
.filter((x) => x.entity?.id === entity)
|
||||
.map((g) => ({ value: g.id, label: g.name }))}
|
||||
onChange={(e) => setGroup(e?.value || undefined)}
|
||||
isClearable
|
||||
/>
|
||||
</div>
|
||||
<div className={clsx("flex flex-col gap-4")}>
|
||||
<label className="font-normal text-base text-mti-gray-dim">Classroom</label>
|
||||
<Select
|
||||
options={groups.filter((x) => x.entity?.id === entity).map((g) => ({value: g.id, label: g.name}))}
|
||||
onChange={(e) => setGroup(e?.value || undefined)}
|
||||
isClearable
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={clsx(
|
||||
"flex flex-col gap-4",
|
||||
!checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"]) && "col-span-2",
|
||||
)}>
|
||||
<label className="font-normal text-base text-mti-gray-dim">Type</label>
|
||||
{user && (
|
||||
<select
|
||||
defaultValue="student"
|
||||
value={type}
|
||||
onChange={(e) => setType(e.target.value as Type)}
|
||||
className="p-6 w-full min-w-[350px] min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer bg-white">
|
||||
{Object.keys(USER_TYPE_LABELS)
|
||||
.filter((x) => {
|
||||
const { list, perm } = USER_TYPE_PERMISSIONS[x as Type];
|
||||
return checkAccess(user, getTypesOfUser(list), permissions, perm);
|
||||
})
|
||||
.map((type) => (
|
||||
<option key={type} value={type}>
|
||||
{USER_TYPE_LABELS[type as keyof typeof USER_TYPE_LABELS]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={clsx(
|
||||
"flex flex-col gap-4",
|
||||
!checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"]) && "col-span-2",
|
||||
)}>
|
||||
<label className="font-normal text-base text-mti-gray-dim">Type</label>
|
||||
{user && (
|
||||
<select
|
||||
defaultValue="student"
|
||||
value={type}
|
||||
onChange={(e) => setType(e.target.value as Type)}
|
||||
className="p-6 w-full min-w-[350px] min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer bg-white">
|
||||
{Object.keys(USER_TYPE_LABELS)
|
||||
.filter((x) => {
|
||||
const {list, perm} = USER_TYPE_PERMISSIONS[x as Type];
|
||||
return checkAccess(user, getTypesOfUser(list), permissions, perm);
|
||||
})
|
||||
.map((type) => (
|
||||
<option key={type} value={type}>
|
||||
{USER_TYPE_LABELS[type as keyof typeof USER_TYPE_LABELS]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4">
|
||||
{user && checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"]) && (
|
||||
<>
|
||||
<div className="-md:flex-row -md:items-center flex justify-between gap-2 md:flex-col 2xl:flex-row 2xl:items-center">
|
||||
<label className="text-mti-gray-dim text-base font-normal">Expiry Date</label>
|
||||
<Checkbox
|
||||
isChecked={isExpiryDateEnabled}
|
||||
onChange={setIsExpiryDateEnabled}
|
||||
disabled={!!user?.subscriptionExpirationDate}>
|
||||
Enabled
|
||||
</Checkbox>
|
||||
</div>
|
||||
{isExpiryDateEnabled && (
|
||||
<ReactDatePicker
|
||||
className={clsx(
|
||||
"flex min-h-[70px] w-full cursor-pointer justify-center rounded-full border p-6 text-sm font-normal focus:outline-none",
|
||||
"hover:border-mti-purple tooltip",
|
||||
"transition duration-300 ease-in-out",
|
||||
)}
|
||||
filterDate={(date) =>
|
||||
moment(date).isAfter(new Date()) &&
|
||||
(user?.subscriptionExpirationDate ? moment(date).isBefore(user?.subscriptionExpirationDate) : true)
|
||||
}
|
||||
dateFormat="dd/MM/yyyy"
|
||||
selected={expiryDate}
|
||||
onChange={(date) => setExpiryDate(date)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-4">
|
||||
{user && checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"]) && (
|
||||
<>
|
||||
<div className="-md:flex-row -md:items-center flex justify-between gap-2 md:flex-col 2xl:flex-row 2xl:items-center">
|
||||
<label className="text-mti-gray-dim text-base font-normal">Expiry Date</label>
|
||||
<Checkbox
|
||||
isChecked={isExpiryDateEnabled}
|
||||
onChange={setIsExpiryDateEnabled}
|
||||
disabled={!!user?.subscriptionExpirationDate}>
|
||||
Enabled
|
||||
</Checkbox>
|
||||
</div>
|
||||
{isExpiryDateEnabled && (
|
||||
<ReactDatePicker
|
||||
className={clsx(
|
||||
"flex min-h-[70px] w-full cursor-pointer justify-center rounded-full border p-6 text-sm font-normal focus:outline-none",
|
||||
"hover:border-mti-purple tooltip",
|
||||
"transition duration-300 ease-in-out",
|
||||
)}
|
||||
filterDate={(date) =>
|
||||
moment(date).isAfter(new Date()) &&
|
||||
(user?.subscriptionExpirationDate ? moment(date).isBefore(user?.subscriptionExpirationDate) : true)
|
||||
}
|
||||
dateFormat="dd/MM/yyyy"
|
||||
selected={expiryDate}
|
||||
onChange={(date) => setExpiryDate(date)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button onClick={createUser} isLoading={isLoading} disabled={(isExpiryDateEnabled ? !expiryDate : false) || isLoading}>
|
||||
Create User
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
<Button onClick={createUser} isLoading={isLoading} disabled={(isExpiryDateEnabled ? !expiryDate : false) || isLoading}>
|
||||
Create User
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,269 +1,216 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import UserDisplayList from "@/components/UserDisplayList";
|
||||
import IconCard from "@/components/IconCard";
|
||||
import { useAllowedEntities } from "@/hooks/useEntityPermissions";
|
||||
import { EntityWithRoles } from "@/interfaces/entity";
|
||||
import { Stat, StudentUser, Type, User } from "@/interfaces/user";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { filterBy, mapBy, redirect, serialize } from "@/utils";
|
||||
import { requestUser } from "@/utils/api";
|
||||
import { countEntitiesAssignments } from "@/utils/assignments.be";
|
||||
import { getEntitiesWithRoles } from "@/utils/entities.be";
|
||||
import { countGroupsByEntities } from "@/utils/groups.be";
|
||||
import {
|
||||
checkAccess,
|
||||
groupAllowedEntitiesByPermissions,
|
||||
} from "@/utils/permissions";
|
||||
import { groupByExam } from "@/utils/stats";
|
||||
import { countAllowedUsers, getUsers } from "@/utils/users.be";
|
||||
import { clsx } from "clsx";
|
||||
import { withIronSessionSsr } from "iron-session/next";
|
||||
import {useAllowedEntities} from "@/hooks/useEntityPermissions";
|
||||
import {EntityWithRoles} from "@/interfaces/entity";
|
||||
import {Stat, StudentUser, Type, User} from "@/interfaces/user";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {filterBy, mapBy, redirect, serialize} from "@/utils";
|
||||
import {requestUser} from "@/utils/api";
|
||||
import {countEntitiesAssignments} from "@/utils/assignments.be";
|
||||
import {getEntitiesWithRoles} from "@/utils/entities.be";
|
||||
import {countGroupsByEntities} from "@/utils/groups.be";
|
||||
import {checkAccess, groupAllowedEntitiesByPermissions} from "@/utils/permissions";
|
||||
import {groupByExam} from "@/utils/stats";
|
||||
import {countAllowedUsers, getUsers} from "@/utils/users.be";
|
||||
import {clsx} from "clsx";
|
||||
import {withIronSessionSsr} from "iron-session/next";
|
||||
import moment from "moment";
|
||||
import Head from "next/head";
|
||||
import { useRouter } from "next/router";
|
||||
import { useMemo } from "react";
|
||||
import {
|
||||
BsBank,
|
||||
BsClock,
|
||||
BsEnvelopePaper,
|
||||
BsPencilSquare,
|
||||
BsPeople,
|
||||
BsPeopleFill,
|
||||
BsPersonFill,
|
||||
BsPersonFillGear,
|
||||
} from "react-icons/bs";
|
||||
import { ToastContainer } from "react-toastify";
|
||||
import { isAdmin } from "@/utils/users";
|
||||
import {useRouter} from "next/router";
|
||||
import {useMemo} from "react";
|
||||
import {BsBank, BsClock, BsEnvelopePaper, BsPencilSquare, BsPeople, BsPeopleFill, BsPersonFill, BsPersonFillGear} from "react-icons/bs";
|
||||
import {ToastContainer} from "react-toastify";
|
||||
import {isAdmin} from "@/utils/users";
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
students: StudentUser[];
|
||||
latestStudents: User[];
|
||||
latestTeachers: User[];
|
||||
userCounts: { [key in Type]: number };
|
||||
entities: EntityWithRoles[];
|
||||
assignmentsCount: number;
|
||||
stats: Stat[];
|
||||
groupsCount: number;
|
||||
user: User;
|
||||
students: StudentUser[];
|
||||
latestStudents: User[];
|
||||
latestTeachers: User[];
|
||||
userCounts: {[key in Type]: number};
|
||||
entities: EntityWithRoles[];
|
||||
assignmentsCount: number;
|
||||
stats: Stat[];
|
||||
groupsCount: number;
|
||||
}
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(async ({ req, res }) => {
|
||||
const user = await requestUser(req, res);
|
||||
if (!user || !user.isVerified) return redirect("/login");
|
||||
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||
const user = await requestUser(req, res);
|
||||
if (!user || !user.isVerified) return redirect("/login");
|
||||
|
||||
if (!checkAccess(user, ["admin", "developer", "mastercorporate"]))
|
||||
return redirect("/");
|
||||
if (!checkAccess(user, ["admin", "developer", "mastercorporate"])) return redirect("/");
|
||||
|
||||
const entityIDS = mapBy(user.entities, "id") || [];
|
||||
const entities = await getEntitiesWithRoles(
|
||||
isAdmin(user) ? undefined : entityIDS
|
||||
);
|
||||
const {
|
||||
["view_students"]: allowedStudentEntities,
|
||||
["view_teachers"]: allowedTeacherEntities,
|
||||
} = groupAllowedEntitiesByPermissions(user, entities, [
|
||||
"view_students",
|
||||
"view_teachers",
|
||||
]);
|
||||
const entityIDS = mapBy(user.entities, "id") || [];
|
||||
const entities = await getEntitiesWithRoles(isAdmin(user) ? undefined : entityIDS);
|
||||
const {["view_students"]: allowedStudentEntities, ["view_teachers"]: allowedTeacherEntities} = groupAllowedEntitiesByPermissions(user, entities, [
|
||||
"view_students",
|
||||
"view_teachers",
|
||||
]);
|
||||
|
||||
const allowedStudentEntitiesIDS = mapBy(allowedStudentEntities, "id");
|
||||
const allowedStudentEntitiesIDS = mapBy(allowedStudentEntities, "id");
|
||||
|
||||
const entitiesIDS = mapBy(entities, "id") || [];
|
||||
const entitiesIDS = mapBy(entities, "id") || [];
|
||||
|
||||
const [
|
||||
students,
|
||||
latestStudents,
|
||||
latestTeachers,
|
||||
userCounts,
|
||||
assignmentsCount,
|
||||
groupsCount,
|
||||
] = await Promise.all([
|
||||
getUsers(
|
||||
{ type: "student", "entities.id": { $in: allowedStudentEntitiesIDS } },
|
||||
10,
|
||||
{ averageLevel: -1 },
|
||||
{ _id: 0, id: 1, name: 1, email: 1, profilePicture: 1 }
|
||||
),
|
||||
getUsers(
|
||||
{ type: "student", "entities.id": { $in: allowedStudentEntitiesIDS } },
|
||||
10,
|
||||
{ registrationDate: -1 },
|
||||
{ _id: 0, id: 1, name: 1, email: 1, profilePicture: 1 }
|
||||
),
|
||||
getUsers(
|
||||
{
|
||||
type: "teacher",
|
||||
"entities.id": { $in: mapBy(allowedTeacherEntities, "id") },
|
||||
},
|
||||
10,
|
||||
{ registrationDate: -1 },
|
||||
{ _id: 0, id: 1, name: 1, email: 1, profilePicture: 1 }
|
||||
),
|
||||
countAllowedUsers(user, entities),
|
||||
countEntitiesAssignments(entitiesIDS, { archived: { $ne: true } }),
|
||||
countGroupsByEntities(entitiesIDS),
|
||||
]);
|
||||
const [students, latestStudents, latestTeachers, userCounts, assignmentsCount, groupsCount] = await Promise.all([
|
||||
getUsers(
|
||||
{type: "student", "entities.id": {$in: allowedStudentEntitiesIDS}},
|
||||
10,
|
||||
{averageLevel: -1},
|
||||
{_id: 0, id: 1, name: 1, email: 1, profilePicture: 1},
|
||||
),
|
||||
getUsers(
|
||||
{type: "student", "entities.id": {$in: allowedStudentEntitiesIDS}},
|
||||
10,
|
||||
{registrationDate: -1},
|
||||
{_id: 0, id: 1, name: 1, email: 1, profilePicture: 1},
|
||||
),
|
||||
getUsers(
|
||||
{
|
||||
type: "teacher",
|
||||
"entities.id": {$in: mapBy(allowedTeacherEntities, "id")},
|
||||
},
|
||||
10,
|
||||
{registrationDate: -1},
|
||||
{_id: 0, id: 1, name: 1, email: 1, profilePicture: 1},
|
||||
),
|
||||
countAllowedUsers(user, entities),
|
||||
countEntitiesAssignments(entitiesIDS, {archived: {$ne: true}}),
|
||||
countGroupsByEntities(entitiesIDS),
|
||||
]);
|
||||
|
||||
return {
|
||||
props: serialize({
|
||||
user,
|
||||
students,
|
||||
latestStudents,
|
||||
latestTeachers,
|
||||
userCounts,
|
||||
entities,
|
||||
assignmentsCount,
|
||||
groupsCount,
|
||||
}),
|
||||
};
|
||||
return {
|
||||
props: serialize({
|
||||
user,
|
||||
students,
|
||||
latestStudents,
|
||||
latestTeachers,
|
||||
userCounts,
|
||||
entities,
|
||||
assignmentsCount,
|
||||
groupsCount,
|
||||
}),
|
||||
};
|
||||
}, sessionOptions);
|
||||
|
||||
export default function Dashboard({
|
||||
user,
|
||||
students,
|
||||
latestStudents,
|
||||
latestTeachers,
|
||||
userCounts,
|
||||
entities,
|
||||
assignmentsCount,
|
||||
stats = [],
|
||||
groupsCount,
|
||||
user,
|
||||
students,
|
||||
latestStudents,
|
||||
latestTeachers,
|
||||
userCounts,
|
||||
entities,
|
||||
assignmentsCount,
|
||||
stats = [],
|
||||
groupsCount,
|
||||
}: Props) {
|
||||
|
||||
const totalCount = useMemo(
|
||||
() =>
|
||||
userCounts.corporate +
|
||||
userCounts.mastercorporate +
|
||||
userCounts.student +
|
||||
userCounts.teacher,
|
||||
[userCounts]
|
||||
);
|
||||
const totalCount = useMemo(() => userCounts.corporate + userCounts.mastercorporate + userCounts.student + userCounts.teacher, [userCounts]);
|
||||
|
||||
const totalLicenses = useMemo(
|
||||
() =>
|
||||
entities.reduce(
|
||||
(acc, curr) => acc + parseInt(curr.licenses.toString()),
|
||||
0
|
||||
),
|
||||
[entities]
|
||||
);
|
||||
const totalLicenses = useMemo(() => entities.reduce((acc, curr) => acc + parseInt(curr.licenses.toString()), 0), [entities]);
|
||||
|
||||
const router = useRouter();
|
||||
const router = useRouter();
|
||||
|
||||
const allowedEntityStatistics = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"view_entity_statistics"
|
||||
);
|
||||
const allowedStudentPerformance = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"view_student_performance"
|
||||
);
|
||||
const allowedEntityStatistics = useAllowedEntities(user, entities, "view_entity_statistics");
|
||||
const allowedStudentPerformance = useAllowedEntities(user, entities, "view_student_performance");
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>EnCoach</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<ToastContainer />
|
||||
<>
|
||||
<section className="grid grid-cols-5 place-items-center -md:grid-cols-2 gap-4 text-center">
|
||||
<IconCard
|
||||
onClick={() => router.push("/users?type=student")}
|
||||
Icon={BsPersonFill}
|
||||
label="Students"
|
||||
value={userCounts.student}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => router.push("/users?type=teacher")}
|
||||
Icon={BsPencilSquare}
|
||||
label="Teachers"
|
||||
value={userCounts.teacher}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => router.push("/users?type=corporate")}
|
||||
Icon={BsBank}
|
||||
label="Corporate Accounts"
|
||||
value={userCounts.corporate}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsPeople}
|
||||
onClick={() => router.push("/classrooms")}
|
||||
label="Classrooms"
|
||||
value={groupsCount}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsPeopleFill}
|
||||
onClick={() => router.push("/entities")}
|
||||
label="Entities"
|
||||
value={`${entities.length} - ${totalCount}/${totalLicenses}`}
|
||||
color="purple"
|
||||
/>
|
||||
{allowedStudentPerformance.length > 0 && (
|
||||
<IconCard
|
||||
Icon={BsPersonFillGear}
|
||||
onClick={() => router.push("/users/performance")}
|
||||
label="Student Performance"
|
||||
value={userCounts.student}
|
||||
color="purple"
|
||||
/>
|
||||
)}
|
||||
{allowedEntityStatistics.length > 0 && (
|
||||
<IconCard
|
||||
Icon={BsPersonFillGear}
|
||||
onClick={() => router.push("/statistical")}
|
||||
label="Entity Statistics"
|
||||
value={allowedEntityStatistics.length}
|
||||
color="purple"
|
||||
/>
|
||||
)}
|
||||
<IconCard
|
||||
Icon={BsEnvelopePaper}
|
||||
onClick={() => router.push("/assignments")}
|
||||
label="Assignments"
|
||||
value={assignmentsCount}
|
||||
className={clsx(
|
||||
allowedEntityStatistics.length === 0 && "col-span-2"
|
||||
)}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsClock}
|
||||
label="Expiration Date"
|
||||
value={
|
||||
user.subscriptionExpirationDate
|
||||
? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy")
|
||||
: "Unlimited"
|
||||
}
|
||||
color="rose"
|
||||
/>
|
||||
</section>
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>EnCoach</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<ToastContainer />
|
||||
<>
|
||||
<section className="grid grid-cols-5 place-items-center -md:grid-cols-2 gap-4 text-center">
|
||||
<IconCard
|
||||
onClick={() => router.push("/users?type=student")}
|
||||
Icon={BsPersonFill}
|
||||
label="Students"
|
||||
value={userCounts.student}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => router.push("/users?type=teacher")}
|
||||
Icon={BsPencilSquare}
|
||||
label="Teachers"
|
||||
value={userCounts.teacher}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => router.push("/users?type=corporate")}
|
||||
Icon={BsBank}
|
||||
label="Corporate Accounts"
|
||||
value={userCounts.corporate}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsBank}
|
||||
onClick={() => router.push("/users?type=mastercorporate")}
|
||||
label="Master Corporates"
|
||||
value={userCounts.mastercorporate}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard Icon={BsPeople} onClick={() => router.push("/classrooms")} label="Classrooms" value={groupsCount} color="purple" />
|
||||
<IconCard
|
||||
Icon={BsPeopleFill}
|
||||
onClick={() => router.push("/entities")}
|
||||
label="Entities"
|
||||
value={`${entities.length} - ${totalCount}/${totalLicenses}`}
|
||||
color="purple"
|
||||
/>
|
||||
{allowedStudentPerformance.length > 0 && (
|
||||
<IconCard
|
||||
Icon={BsPersonFillGear}
|
||||
onClick={() => router.push("/users/performance")}
|
||||
label="Student Performance"
|
||||
value={userCounts.student}
|
||||
color="purple"
|
||||
/>
|
||||
)}
|
||||
{allowedEntityStatistics.length > 0 && (
|
||||
<IconCard
|
||||
Icon={BsPersonFillGear}
|
||||
onClick={() => router.push("/statistical")}
|
||||
label="Entity Statistics"
|
||||
value={allowedEntityStatistics.length}
|
||||
color="purple"
|
||||
/>
|
||||
)}
|
||||
<IconCard
|
||||
Icon={BsEnvelopePaper}
|
||||
onClick={() => router.push("/assignments")}
|
||||
label="Assignments"
|
||||
value={assignmentsCount}
|
||||
className={clsx(allowedEntityStatistics.length === 0 && "col-span-2")}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsClock}
|
||||
label="Expiration Date"
|
||||
value={user.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy") : "Unlimited"}
|
||||
color="rose"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
|
||||
<UserDisplayList users={latestStudents} title="Latest Students" />
|
||||
<UserDisplayList users={latestTeachers} title="Latest Teachers" />
|
||||
<UserDisplayList users={students} title="Highest level students" />
|
||||
<UserDisplayList
|
||||
users={students.sort(
|
||||
(a, b) =>
|
||||
Object.keys(groupByExam(filterBy(stats, "user", b))).length -
|
||||
Object.keys(groupByExam(filterBy(stats, "user", a))).length
|
||||
)}
|
||||
title="Highest exam count students"
|
||||
/>
|
||||
</section>
|
||||
</>
|
||||
</>
|
||||
);
|
||||
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
|
||||
<UserDisplayList users={latestStudents} title="Latest Students" />
|
||||
<UserDisplayList users={latestTeachers} title="Latest Teachers" />
|
||||
<UserDisplayList users={students} title="Highest level students" />
|
||||
<UserDisplayList
|
||||
users={students.sort(
|
||||
(a, b) =>
|
||||
Object.keys(groupByExam(filterBy(stats, "user", b))).length -
|
||||
Object.keys(groupByExam(filterBy(stats, "user", a))).length,
|
||||
)}
|
||||
title="Highest exam count students"
|
||||
/>
|
||||
</section>
|
||||
</>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,268 +1,201 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import Head from "next/head";
|
||||
import { withIronSessionSsr } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { ToastContainer } from "react-toastify";
|
||||
import {withIronSessionSsr} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {ToastContainer} from "react-toastify";
|
||||
import CodeGenerator from "./(admin)/CodeGenerator";
|
||||
import ExamLoader from "./(admin)/ExamLoader";
|
||||
import Lists from "./(admin)/Lists";
|
||||
import BatchCodeGenerator from "./(admin)/BatchCodeGenerator";
|
||||
import { shouldRedirectHome } from "@/utils/navigation.disabled";
|
||||
import {shouldRedirectHome} from "@/utils/navigation.disabled";
|
||||
import BatchCreateUser from "./(admin)/Lists/BatchCreateUser";
|
||||
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
|
||||
import { useState } from "react";
|
||||
import {checkAccess, getTypesOfUser} from "@/utils/permissions";
|
||||
import {useEffect, useState} from "react";
|
||||
import Modal from "@/components/Modal";
|
||||
import IconCard from "@/components/IconCard";
|
||||
import {
|
||||
BsCode,
|
||||
BsCodeSquare,
|
||||
BsGearFill,
|
||||
BsPeopleFill,
|
||||
BsPersonFill,
|
||||
} from "react-icons/bs";
|
||||
import {BsCode, BsCodeSquare, BsGearFill, BsPeopleFill, BsPersonFill} from "react-icons/bs";
|
||||
import UserCreator from "./(admin)/UserCreator";
|
||||
import CorporateGradingSystem from "./(admin)/CorporateGradingSystem";
|
||||
import { CEFR_STEPS } from "@/resources/grading";
|
||||
import { User } from "@/interfaces/user";
|
||||
import { getUserPermissions } from "@/utils/permissions.be";
|
||||
import { PermissionType } from "@/interfaces/permissions";
|
||||
import { getUsers } from "@/utils/users.be";
|
||||
import { getEntitiesWithRoles } from "@/utils/entities.be";
|
||||
import { mapBy, serialize, redirect } from "@/utils";
|
||||
import { EntityWithRoles } from "@/interfaces/entity";
|
||||
import { requestUser } from "@/utils/api";
|
||||
import { isAdmin } from "@/utils/users";
|
||||
import {
|
||||
getGradingSystemByEntities,
|
||||
getGradingSystemByEntity,
|
||||
} from "@/utils/grading.be";
|
||||
import { Grading } from "@/interfaces";
|
||||
import { useRouter } from "next/router";
|
||||
import { useAllowedEntities } from "@/hooks/useEntityPermissions";
|
||||
import {CEFR_STEPS} from "@/resources/grading";
|
||||
import {User} from "@/interfaces/user";
|
||||
import {getUserPermissions} from "@/utils/permissions.be";
|
||||
import {PermissionType} from "@/interfaces/permissions";
|
||||
import {getUsers} from "@/utils/users.be";
|
||||
import {getEntitiesWithRoles} from "@/utils/entities.be";
|
||||
import {mapBy, serialize, redirect, filterBy} from "@/utils";
|
||||
import {EntityWithRoles} from "@/interfaces/entity";
|
||||
import {requestUser} from "@/utils/api";
|
||||
import {isAdmin} from "@/utils/users";
|
||||
import {getGradingSystemByEntities, getGradingSystemByEntity} from "@/utils/grading.be";
|
||||
import {Grading} from "@/interfaces";
|
||||
import {useRouter} from "next/router";
|
||||
import {useAllowedEntities} from "@/hooks/useEntityPermissions";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(async ({ req, res }) => {
|
||||
const user = await requestUser(req, res);
|
||||
if (!user) return redirect("/login");
|
||||
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||
const user = await requestUser(req, res);
|
||||
if (!user) return redirect("/login");
|
||||
|
||||
if (
|
||||
shouldRedirectHome(user) ||
|
||||
!checkAccess(user, [
|
||||
"admin",
|
||||
"developer",
|
||||
"corporate",
|
||||
"teacher",
|
||||
"mastercorporate",
|
||||
])
|
||||
)
|
||||
return redirect("/");
|
||||
const [permissions, entities, allUsers] = await Promise.all([
|
||||
getUserPermissions(user.id),
|
||||
isAdmin(user)
|
||||
? await getEntitiesWithRoles()
|
||||
: await getEntitiesWithRoles(mapBy(user.entities, "id")),
|
||||
getUsers(),
|
||||
]);
|
||||
const gradingSystems = await getGradingSystemByEntities(
|
||||
mapBy(entities, "id")
|
||||
);
|
||||
const entitiesGrading = entities.map(
|
||||
(e) =>
|
||||
gradingSystems.find((g) => g.entity === e.id) || {
|
||||
entity: e.id,
|
||||
steps: CEFR_STEPS,
|
||||
}
|
||||
);
|
||||
if (shouldRedirectHome(user) || !checkAccess(user, ["admin", "developer", "corporate", "teacher", "mastercorporate"])) return redirect("/");
|
||||
const [permissions, entities, allUsers] = await Promise.all([
|
||||
getUserPermissions(user.id),
|
||||
isAdmin(user) ? await getEntitiesWithRoles() : await getEntitiesWithRoles(mapBy(user.entities, "id")),
|
||||
getUsers(),
|
||||
]);
|
||||
const gradingSystems = await getGradingSystemByEntities(mapBy(entities, "id"));
|
||||
const entitiesGrading = entities.map(
|
||||
(e) =>
|
||||
gradingSystems.find((g) => g.entity === e.id) || {
|
||||
entity: e.id,
|
||||
steps: CEFR_STEPS,
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
props: serialize({
|
||||
user,
|
||||
permissions,
|
||||
entities,
|
||||
allUsers,
|
||||
entitiesGrading,
|
||||
}),
|
||||
};
|
||||
return {
|
||||
props: serialize({
|
||||
user,
|
||||
permissions,
|
||||
entities,
|
||||
allUsers,
|
||||
entitiesGrading,
|
||||
}),
|
||||
};
|
||||
}, sessionOptions);
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
permissions: PermissionType[];
|
||||
entities: EntityWithRoles[];
|
||||
allUsers: User[];
|
||||
entitiesGrading: Grading[];
|
||||
user: User;
|
||||
permissions: PermissionType[];
|
||||
entities: EntityWithRoles[];
|
||||
allUsers: User[];
|
||||
entitiesGrading: Grading[];
|
||||
}
|
||||
|
||||
export default function Admin({
|
||||
user,
|
||||
entities,
|
||||
permissions,
|
||||
allUsers,
|
||||
entitiesGrading,
|
||||
}: Props) {
|
||||
const [modalOpen, setModalOpen] = useState<string>();
|
||||
const router = useRouter();
|
||||
export default function Admin({user, entities, permissions, allUsers, entitiesGrading}: Props) {
|
||||
const [modalOpen, setModalOpen] = useState<string>();
|
||||
const router = useRouter();
|
||||
|
||||
const entitiesAllowCreateUser = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"create_user"
|
||||
);
|
||||
const entitiesAllowCreateUsers = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"create_user_batch"
|
||||
);
|
||||
const entitiesAllowCreateCode = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"create_code"
|
||||
);
|
||||
const entitiesAllowCreateCodes = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"create_code_batch"
|
||||
);
|
||||
const entitiesAllowEditGrading = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"edit_grading_system"
|
||||
);
|
||||
const entitiesAllowCreateUser = useAllowedEntities(user, entities, "create_user");
|
||||
const entitiesAllowCreateUsers = useAllowedEntities(user, entities, "create_user_batch");
|
||||
const entitiesAllowCreateCode = useAllowedEntities(user, entities, "create_code");
|
||||
const entitiesAllowCreateCodes = useAllowedEntities(user, entities, "create_code_batch");
|
||||
const entitiesAllowEditGrading = useAllowedEntities(user, entities, "edit_grading_system");
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Settings Panel | EnCoach</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<ToastContainer />
|
||||
<>
|
||||
<Modal
|
||||
isOpen={modalOpen === "batchCreateUser"}
|
||||
onClose={() => setModalOpen(undefined)}
|
||||
maxWidth="max-w-[85%]"
|
||||
>
|
||||
<BatchCreateUser
|
||||
user={user}
|
||||
entities={entitiesAllowCreateUser}
|
||||
permissions={permissions}
|
||||
onFinish={() => setModalOpen(undefined)}
|
||||
/>
|
||||
</Modal>
|
||||
<Modal
|
||||
isOpen={modalOpen === "batchCreateCode"}
|
||||
onClose={() => setModalOpen(undefined)}
|
||||
>
|
||||
<BatchCodeGenerator
|
||||
entities={entitiesAllowCreateCodes}
|
||||
user={user}
|
||||
users={allUsers}
|
||||
permissions={permissions}
|
||||
onFinish={() => setModalOpen(undefined)}
|
||||
/>
|
||||
</Modal>
|
||||
<Modal
|
||||
isOpen={modalOpen === "createCode"}
|
||||
onClose={() => setModalOpen(undefined)}
|
||||
>
|
||||
<CodeGenerator
|
||||
entities={entitiesAllowCreateCode}
|
||||
user={user}
|
||||
permissions={permissions}
|
||||
onFinish={() => setModalOpen(undefined)}
|
||||
/>
|
||||
</Modal>
|
||||
<Modal
|
||||
isOpen={modalOpen === "createUser"}
|
||||
onClose={() => setModalOpen(undefined)}
|
||||
>
|
||||
<UserCreator
|
||||
user={user}
|
||||
entities={entitiesAllowCreateUsers}
|
||||
users={allUsers}
|
||||
permissions={permissions}
|
||||
onFinish={() => setModalOpen(undefined)}
|
||||
/>
|
||||
</Modal>
|
||||
<Modal
|
||||
isOpen={modalOpen === "gradingSystem"}
|
||||
onClose={() => setModalOpen(undefined)}
|
||||
>
|
||||
<CorporateGradingSystem
|
||||
user={user}
|
||||
entitiesGrading={entitiesGrading}
|
||||
entities={entitiesAllowEditGrading}
|
||||
mutate={() => router.replace(router.asPath)}
|
||||
/>
|
||||
</Modal>
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Settings Panel | EnCoach</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<ToastContainer />
|
||||
<>
|
||||
<Modal isOpen={modalOpen === "batchCreateUser"} onClose={() => setModalOpen(undefined)} maxWidth="max-w-[85%]">
|
||||
<BatchCreateUser
|
||||
user={user}
|
||||
entities={entitiesAllowCreateUsers.filter(
|
||||
(e) =>
|
||||
e.licenses > 0 &&
|
||||
e.licenses > allUsers.filter((u) => !isAdmin(u) && (u.entities || []).some((ent) => ent.id === e.id)).length,
|
||||
)}
|
||||
permissions={permissions}
|
||||
onFinish={() => setModalOpen(undefined)}
|
||||
/>
|
||||
</Modal>
|
||||
<Modal isOpen={modalOpen === "batchCreateCode"} onClose={() => setModalOpen(undefined)}>
|
||||
<BatchCodeGenerator
|
||||
entities={entitiesAllowCreateCodes}
|
||||
user={user}
|
||||
users={allUsers}
|
||||
permissions={permissions}
|
||||
onFinish={() => setModalOpen(undefined)}
|
||||
/>
|
||||
</Modal>
|
||||
<Modal isOpen={modalOpen === "createCode"} onClose={() => setModalOpen(undefined)}>
|
||||
<CodeGenerator
|
||||
entities={entitiesAllowCreateCode}
|
||||
user={user}
|
||||
permissions={permissions}
|
||||
onFinish={() => setModalOpen(undefined)}
|
||||
/>
|
||||
</Modal>
|
||||
<Modal isOpen={modalOpen === "createUser"} onClose={() => setModalOpen(undefined)}>
|
||||
<UserCreator
|
||||
user={user}
|
||||
entities={entitiesAllowCreateUser.filter(
|
||||
(e) =>
|
||||
e.licenses > 0 &&
|
||||
e.licenses > allUsers.filter((u) => !isAdmin(u) && (u.entities || []).some((ent) => ent.id === e.id)).length,
|
||||
)}
|
||||
users={allUsers}
|
||||
permissions={permissions}
|
||||
onFinish={() => setModalOpen(undefined)}
|
||||
/>
|
||||
</Modal>
|
||||
<Modal isOpen={modalOpen === "gradingSystem"} onClose={() => setModalOpen(undefined)}>
|
||||
<CorporateGradingSystem
|
||||
user={user}
|
||||
entitiesGrading={entitiesGrading}
|
||||
entities={entitiesAllowEditGrading}
|
||||
mutate={() => router.replace(router.asPath)}
|
||||
/>
|
||||
</Modal>
|
||||
|
||||
<section className="w-full grid grid-cols-2 -md:grid-cols-1 gap-8">
|
||||
<ExamLoader />
|
||||
{checkAccess(
|
||||
user,
|
||||
getTypesOfUser(["teacher"]),
|
||||
permissions,
|
||||
"viewCodes"
|
||||
) && (
|
||||
<div className="w-full grid grid-cols-2 gap-4">
|
||||
<IconCard
|
||||
Icon={BsCode}
|
||||
label="Generate Single Code"
|
||||
color="purple"
|
||||
className="w-full h-full"
|
||||
onClick={() => setModalOpen("createCode")}
|
||||
disabled={entitiesAllowCreateCode.length === 0}
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsCodeSquare}
|
||||
label="Generate Codes in Batch"
|
||||
color="purple"
|
||||
className="w-full h-full"
|
||||
onClick={() => setModalOpen("batchCreateCode")}
|
||||
disabled={entitiesAllowCreateCodes.length === 0}
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsPersonFill}
|
||||
label="Create Single User"
|
||||
color="purple"
|
||||
className="w-full h-full"
|
||||
onClick={() => setModalOpen("createUser")}
|
||||
disabled={entitiesAllowCreateUser.length === 0}
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsPeopleFill}
|
||||
label="Create Users in Batch"
|
||||
color="purple"
|
||||
className="w-full h-full"
|
||||
onClick={() => setModalOpen("batchCreateUser")}
|
||||
disabled={entitiesAllowCreateUsers.length === 0}
|
||||
/>
|
||||
{checkAccess(user, [
|
||||
"admin",
|
||||
"corporate",
|
||||
"developer",
|
||||
"mastercorporate",
|
||||
]) && (
|
||||
<IconCard
|
||||
Icon={BsGearFill}
|
||||
label="Grading System"
|
||||
color="purple"
|
||||
className="w-full h-full col-span-2"
|
||||
onClick={() => setModalOpen("gradingSystem")}
|
||||
disabled={entitiesAllowEditGrading.length === 0}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
<section className="w-full">
|
||||
<Lists user={user} entities={entities} permissions={permissions} />
|
||||
</section>
|
||||
</>
|
||||
</>
|
||||
);
|
||||
<section className="w-full grid grid-cols-2 -md:grid-cols-1 gap-8">
|
||||
<ExamLoader />
|
||||
{checkAccess(user, getTypesOfUser(["teacher"]), permissions, "viewCodes") && (
|
||||
<div className="w-full grid grid-cols-2 gap-4">
|
||||
<IconCard
|
||||
Icon={BsCode}
|
||||
label="Generate Single Code"
|
||||
color="purple"
|
||||
className="w-full h-full"
|
||||
onClick={() => setModalOpen("createCode")}
|
||||
disabled={entitiesAllowCreateCode.length === 0}
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsCodeSquare}
|
||||
label="Generate Codes in Batch"
|
||||
color="purple"
|
||||
className="w-full h-full"
|
||||
onClick={() => setModalOpen("batchCreateCode")}
|
||||
disabled={entitiesAllowCreateCodes.length === 0}
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsPersonFill}
|
||||
label="Create Single User"
|
||||
color="purple"
|
||||
className="w-full h-full"
|
||||
onClick={() => setModalOpen("createUser")}
|
||||
disabled={entitiesAllowCreateUser.length === 0}
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsPeopleFill}
|
||||
label="Create Users in Batch"
|
||||
color="purple"
|
||||
className="w-full h-full"
|
||||
onClick={() => setModalOpen("batchCreateUser")}
|
||||
disabled={entitiesAllowCreateUsers.length === 0}
|
||||
/>
|
||||
{checkAccess(user, ["admin", "corporate", "developer", "mastercorporate"]) && (
|
||||
<IconCard
|
||||
Icon={BsGearFill}
|
||||
label="Grading System"
|
||||
color="purple"
|
||||
className="w-full h-full col-span-2"
|
||||
onClick={() => setModalOpen("gradingSystem")}
|
||||
disabled={entitiesAllowEditGrading.length === 0}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
<section className="w-full">
|
||||
<Lists user={user} entities={entities} permissions={permissions} />
|
||||
</section>
|
||||
</>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user