Merged develop into feature/ai-detection
This commit is contained in:
@@ -33,8 +33,7 @@ export default function Layout({user, children, className, navDisabled = false,
|
||||
focusMode={focusMode}
|
||||
onFocusLayerMouseEnter={onFocusLayerMouseEnter}
|
||||
className="-md:hidden"
|
||||
userType={user.type}
|
||||
userId={user.id}
|
||||
user={user}
|
||||
/>
|
||||
<div
|
||||
className={clsx(
|
||||
|
||||
@@ -16,6 +16,7 @@ import ShortUniqueId from "short-unique-id";
|
||||
import Button from "../Low/Button";
|
||||
import Input from "../Low/Input";
|
||||
import Select from "../Low/Select";
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
@@ -137,13 +138,13 @@ export default function TicketDisplay({ user, ticket, onClose }: Props) {
|
||||
options={[
|
||||
{ value: "me", label: "Assign to me" },
|
||||
...users
|
||||
.filter((x) => ["admin", "developer", "agent"].includes(x.type))
|
||||
.filter((x) => checkAccess(x, ["admin", "developer", "agent"]))
|
||||
.map((u) => ({
|
||||
value: u.id,
|
||||
label: `${u.name} - ${u.email}`,
|
||||
})),
|
||||
]}
|
||||
disabled={user.type === "agent"}
|
||||
disabled={checkAccess(user, ["agent"])}
|
||||
value={
|
||||
assignedTo
|
||||
? {
|
||||
|
||||
@@ -7,6 +7,7 @@ import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { Fragment } from "react";
|
||||
import { BsXLg } from "react-icons/bs";
|
||||
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
|
||||
|
||||
interface Props {
|
||||
isOpen: boolean;
|
||||
@@ -16,7 +17,13 @@ interface Props {
|
||||
disableNavigation?: boolean;
|
||||
}
|
||||
|
||||
export default function MobileMenu({isOpen, onClose, path, user, disableNavigation}: Props) {
|
||||
export default function MobileMenu({
|
||||
isOpen,
|
||||
onClose,
|
||||
path,
|
||||
user,
|
||||
disableNavigation,
|
||||
}: Props) {
|
||||
const router = useRouter();
|
||||
|
||||
const logout = async () => {
|
||||
@@ -35,7 +42,8 @@ export default function MobileMenu({isOpen, onClose, path, user, disableNavigati
|
||||
enterTo="opacity-100"
|
||||
leave="ease-in duration-200"
|
||||
leaveFrom="opacity-100"
|
||||
leaveTo="opacity-0">
|
||||
leaveTo="opacity-0"
|
||||
>
|
||||
<div className="fixed inset-0 bg-black bg-opacity-25" />
|
||||
</Transition.Child>
|
||||
|
||||
@@ -48,14 +56,30 @@ export default function MobileMenu({isOpen, onClose, path, user, disableNavigati
|
||||
enterTo="opacity-100 scale-100"
|
||||
leave="ease-in duration-200"
|
||||
leaveFrom="opacity-100 scale-100"
|
||||
leaveTo="opacity-0 scale-95">
|
||||
leaveTo="opacity-0 scale-95"
|
||||
>
|
||||
<Dialog.Panel className="flex h-screen w-full transform flex-col gap-8 overflow-hidden bg-white text-left align-middle text-black shadow-xl transition-all">
|
||||
<Dialog.Title as="header" className="-md:flex w-full items-center justify-between px-8 py-2 shadow-sm md:hidden">
|
||||
<Dialog.Title
|
||||
as="header"
|
||||
className="-md:flex w-full items-center justify-between px-8 py-2 shadow-sm md:hidden"
|
||||
>
|
||||
<Link href={disableNavigation ? "" : "/"}>
|
||||
<Image src="/logo_title.png" alt="EnCoach logo" width={69} height={69} />
|
||||
<Image
|
||||
src="/logo_title.png"
|
||||
alt="EnCoach logo"
|
||||
width={69}
|
||||
height={69}
|
||||
/>
|
||||
</Link>
|
||||
<div className="cursor-pointer" onClick={onClose} tabIndex={0}>
|
||||
<BsXLg className="text-mti-purple-light text-2xl" onClick={onClose} />
|
||||
<div
|
||||
className="cursor-pointer"
|
||||
onClick={onClose}
|
||||
tabIndex={0}
|
||||
>
|
||||
<BsXLg
|
||||
className="text-mti-purple-light text-2xl"
|
||||
onClick={onClose}
|
||||
/>
|
||||
</div>
|
||||
</Dialog.Title>
|
||||
<div className="flex h-full flex-col gap-6 px-8 text-lg">
|
||||
@@ -63,18 +87,22 @@ export default function MobileMenu({isOpen, onClose, path, user, disableNavigati
|
||||
href={disableNavigation ? "" : "/"}
|
||||
className={clsx(
|
||||
"w-fit transition duration-300 ease-in-out",
|
||||
path === "/" && "text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold ",
|
||||
)}>
|
||||
path === "/" &&
|
||||
"text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold "
|
||||
)}
|
||||
>
|
||||
Dashboard
|
||||
</Link>
|
||||
{(user.type === "student" || user.type === "teacher" || user.type === "developer") && (
|
||||
{checkAccess(user, ["student", "teacher", "developer"]) && (
|
||||
<>
|
||||
<Link
|
||||
href={disableNavigation ? "" : "/exam"}
|
||||
className={clsx(
|
||||
"w-fit transition duration-300 ease-in-out",
|
||||
path === "/exam" && "text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold ",
|
||||
)}>
|
||||
path === "/exam" &&
|
||||
"text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold "
|
||||
)}
|
||||
>
|
||||
Exams
|
||||
</Link>
|
||||
<Link
|
||||
@@ -82,8 +110,9 @@ export default function MobileMenu({isOpen, onClose, path, user, disableNavigati
|
||||
className={clsx(
|
||||
"w-fit transition duration-300 ease-in-out",
|
||||
path === "/exercises" &&
|
||||
"text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold ",
|
||||
)}>
|
||||
"text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold "
|
||||
)}
|
||||
>
|
||||
Exercises
|
||||
</Link>
|
||||
</>
|
||||
@@ -92,46 +121,67 @@ export default function MobileMenu({isOpen, onClose, path, user, disableNavigati
|
||||
href={disableNavigation ? "" : "/stats"}
|
||||
className={clsx(
|
||||
"w-fit transition duration-300 ease-in-out",
|
||||
path === "/stats" && "text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold ",
|
||||
)}>
|
||||
path === "/stats" &&
|
||||
"text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold "
|
||||
)}
|
||||
>
|
||||
Stats
|
||||
</Link>
|
||||
<Link
|
||||
href={disableNavigation ? "" : "/record"}
|
||||
className={clsx(
|
||||
"w-fit transition duration-300 ease-in-out",
|
||||
path === "/record" && "text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold ",
|
||||
)}>
|
||||
path === "/record" &&
|
||||
"text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold "
|
||||
)}
|
||||
>
|
||||
Record
|
||||
</Link>
|
||||
{["admin", "developer", "agent", "corporate"].includes(user.type) && (
|
||||
{checkAccess(user, [
|
||||
"admin",
|
||||
"developer",
|
||||
"agent",
|
||||
"corporate",
|
||||
"mastercorporate",
|
||||
]) && (
|
||||
<Link
|
||||
href={disableNavigation ? "" : "/payment-record"}
|
||||
className={clsx(
|
||||
"w-fit transition duration-300 ease-in-out",
|
||||
path === "/payment-record" &&
|
||||
"text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold ",
|
||||
)}>
|
||||
"text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold "
|
||||
)}
|
||||
>
|
||||
Payment Record
|
||||
</Link>
|
||||
)}
|
||||
{["admin", "developer", "corporate", "teacher"].includes(user.type) && (
|
||||
{checkAccess(user, [
|
||||
"admin",
|
||||
"developer",
|
||||
"corporate",
|
||||
"teacher",
|
||||
"mastercorporate",
|
||||
]) && (
|
||||
<Link
|
||||
href={disableNavigation ? "" : "/settings"}
|
||||
className={clsx(
|
||||
"w-fit transition duration-300 ease-in-out",
|
||||
path === "/settings" && "text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold ",
|
||||
)}>
|
||||
path === "/settings" &&
|
||||
"text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold "
|
||||
)}
|
||||
>
|
||||
Settings
|
||||
</Link>
|
||||
)}
|
||||
{["admin", "developer", "agent"].includes(user.type) && (
|
||||
{checkAccess(user, ["admin", "developer", "agent"]) && (
|
||||
<Link
|
||||
href={disableNavigation ? "" : "/tickets"}
|
||||
className={clsx(
|
||||
"w-fit transition duration-300 ease-in-out",
|
||||
path === "/tickets" && "text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold ",
|
||||
)}>
|
||||
path === "/tickets" &&
|
||||
"text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold "
|
||||
)}
|
||||
>
|
||||
Tickets
|
||||
</Link>
|
||||
)}
|
||||
@@ -139,14 +189,19 @@ export default function MobileMenu({isOpen, onClose, path, user, disableNavigati
|
||||
href={disableNavigation ? "" : "/profile"}
|
||||
className={clsx(
|
||||
"w-fit transition duration-300 ease-in-out",
|
||||
path === "/profile" && "text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold ",
|
||||
)}>
|
||||
path === "/profile" &&
|
||||
"text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold "
|
||||
)}
|
||||
>
|
||||
Profile
|
||||
</Link>
|
||||
|
||||
<span
|
||||
className={clsx("w-fit cursor-pointer justify-self-end transition duration-300 ease-in-out")}
|
||||
onClick={logout}>
|
||||
className={clsx(
|
||||
"w-fit cursor-pointer justify-self-end transition duration-300 ease-in-out"
|
||||
)}
|
||||
onClick={logout}
|
||||
>
|
||||
Logout
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
BsCloudFill,
|
||||
BsCurrencyDollar,
|
||||
BsClipboardData,
|
||||
BsFileLock,
|
||||
} from "react-icons/bs";
|
||||
import { RiLogoutBoxFill } from "react-icons/ri";
|
||||
import { SlPencil } from "react-icons/sl";
|
||||
@@ -23,16 +24,16 @@ import FocusLayer from "@/components/FocusLayer";
|
||||
import { preventNavigation } from "@/utils/navigation.disabled";
|
||||
import { useEffect, useState } from "react";
|
||||
import usePreferencesStore from "@/stores/preferencesStore";
|
||||
import {Type} from "@/interfaces/user";
|
||||
import { User } from "@/interfaces/user";
|
||||
import useTicketsListener from "@/hooks/useTicketsListener";
|
||||
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
|
||||
interface Props {
|
||||
path: string;
|
||||
navDisabled?: boolean;
|
||||
focusMode?: boolean;
|
||||
onFocusLayerMouseEnter?: () => void;
|
||||
className?: string;
|
||||
userType?: Type;
|
||||
userId?: string;
|
||||
user: User;
|
||||
}
|
||||
|
||||
interface NavProps {
|
||||
@@ -45,17 +46,28 @@ interface NavProps {
|
||||
badge?: number;
|
||||
}
|
||||
|
||||
const Nav = ({Icon, label, path, keyPath, disabled = false, isMinimized = false, badge}: NavProps) => {
|
||||
const Nav = ({
|
||||
Icon,
|
||||
label,
|
||||
path,
|
||||
keyPath,
|
||||
disabled = false,
|
||||
isMinimized = false,
|
||||
badge,
|
||||
}: NavProps) => {
|
||||
return (
|
||||
<Link
|
||||
href={!disabled ? keyPath : ""}
|
||||
className={clsx(
|
||||
"flex items-center gap-4 rounded-full p-4 text-gray-500 hover:text-white",
|
||||
"transition-all duration-300 ease-in-out relative",
|
||||
disabled ? "hover:bg-mti-gray-dim cursor-not-allowed" : "hover:bg-mti-purple-light cursor-pointer",
|
||||
disabled
|
||||
? "hover:bg-mti-gray-dim cursor-not-allowed"
|
||||
: "hover:bg-mti-purple-light cursor-pointer",
|
||||
path === keyPath && "bg-mti-purple-light text-white",
|
||||
isMinimized ? "w-fit" : "w-full min-w-[200px] px-8 2xl:min-w-[220px]",
|
||||
)}>
|
||||
isMinimized ? "w-fit" : "w-full min-w-[200px] px-8 2xl:min-w-[220px]"
|
||||
)}
|
||||
>
|
||||
<Icon size={24} />
|
||||
{!isMinimized && <span className="text-lg font-semibold">{label}</span>}
|
||||
{!!badge && badge > 0 && (
|
||||
@@ -63,8 +75,9 @@ const Nav = ({Icon, label, path, keyPath, disabled = false, isMinimized = false,
|
||||
className={clsx(
|
||||
"bg-mti-purple-light h-5 w-5 text-xs rounded-full flex items-center justify-center text-white",
|
||||
"transition ease-in-out duration-300",
|
||||
isMinimized && "absolute right-0 top-0",
|
||||
)}>
|
||||
isMinimized && "absolute right-0 top-0"
|
||||
)}
|
||||
>
|
||||
{badge}
|
||||
</div>
|
||||
)}
|
||||
@@ -72,12 +85,22 @@ const Nav = ({Icon, label, path, keyPath, disabled = false, isMinimized = false,
|
||||
);
|
||||
};
|
||||
|
||||
export default function Sidebar({path, navDisabled = false, focusMode = false, userType, onFocusLayerMouseEnter, className, userId}: Props) {
|
||||
export default function Sidebar({
|
||||
path,
|
||||
navDisabled = false,
|
||||
focusMode = false,
|
||||
user,
|
||||
onFocusLayerMouseEnter,
|
||||
className,
|
||||
}: Props) {
|
||||
const router = useRouter();
|
||||
|
||||
const [isMinimized, toggleMinimize] = usePreferencesStore((state) => [state.isSidebarMinimized, state.toggleSidebarMinimized]);
|
||||
const [isMinimized, toggleMinimize] = usePreferencesStore((state) => [
|
||||
state.isSidebarMinimized,
|
||||
state.toggleSidebarMinimized,
|
||||
]);
|
||||
|
||||
const {totalAssignedTickets} = useTicketsListener(userId);
|
||||
const { totalAssignedTickets } = useTicketsListener(user.id);
|
||||
|
||||
const logout = async () => {
|
||||
axios.post("/api/logout").finally(() => {
|
||||
@@ -92,12 +115,23 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
||||
className={clsx(
|
||||
"relative flex h-full flex-col justify-between bg-transparent px-4 py-4 pb-8",
|
||||
isMinimized ? "w-fit" : "-xl:w-fit w-1/6",
|
||||
className,
|
||||
)}>
|
||||
className
|
||||
)}
|
||||
>
|
||||
<div className="-xl:hidden flex-col gap-3 xl:flex">
|
||||
<Nav disabled={disableNavigation} Icon={MdSpaceDashboard} label="Dashboard" path={path} keyPath="/" isMinimized={isMinimized} />
|
||||
{(userType === "student" || userType === "teacher" || userType === "developer") && (
|
||||
<>
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={MdSpaceDashboard}
|
||||
label="Dashboard"
|
||||
path={path}
|
||||
keyPath="/"
|
||||
isMinimized={isMinimized}
|
||||
/>
|
||||
{checkAccess(
|
||||
user,
|
||||
["student", "teacher", "developer"],
|
||||
"viewExams"
|
||||
) && (
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsFileEarmarkText}
|
||||
@@ -106,6 +140,12 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
||||
keyPath="/exam"
|
||||
isMinimized={isMinimized}
|
||||
/>
|
||||
)}
|
||||
{checkAccess(
|
||||
user,
|
||||
["student", "teacher", "developer"],
|
||||
"viewExercises"
|
||||
) && (
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsPencil}
|
||||
@@ -114,15 +154,32 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
||||
keyPath="/exercises"
|
||||
isMinimized={isMinimized}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{(userType || "") !== 'agent' && (
|
||||
<>
|
||||
<Nav disabled={disableNavigation} Icon={BsGraphUp} label="Stats" path={path} keyPath="/stats" isMinimized={isMinimized} />
|
||||
<Nav disabled={disableNavigation} Icon={BsClockHistory} label="Record" path={path} keyPath="/record" isMinimized={isMinimized} />
|
||||
</>
|
||||
{checkAccess(user, getTypesOfUser(["agent"]), "viewStats") && (
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsGraphUp}
|
||||
label="Stats"
|
||||
path={path}
|
||||
keyPath="/stats"
|
||||
isMinimized={isMinimized}
|
||||
/>
|
||||
)}
|
||||
{["admin", "developer", "agent", "corporate"].includes(userType || "") && (
|
||||
{checkAccess(user, getTypesOfUser(["agent"]), "viewRecords") && (
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsClockHistory}
|
||||
label="Record"
|
||||
path={path}
|
||||
keyPath="/record"
|
||||
isMinimized={isMinimized}
|
||||
/>
|
||||
)}
|
||||
{checkAccess(
|
||||
user,
|
||||
["admin", "developer", "agent", "corporate", "mastercorporate"],
|
||||
"viewPaymentRecords"
|
||||
) && (
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsCurrencyDollar}
|
||||
@@ -132,7 +189,13 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
||||
isMinimized={isMinimized}
|
||||
/>
|
||||
)}
|
||||
{["admin", "developer", "corporate", "teacher"].includes(userType || "") && (
|
||||
{checkAccess(user, [
|
||||
"admin",
|
||||
"developer",
|
||||
"corporate",
|
||||
"teacher",
|
||||
"mastercorporate",
|
||||
]) && (
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsShieldFill}
|
||||
@@ -142,7 +205,23 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
||||
isMinimized={isMinimized}
|
||||
/>
|
||||
)}
|
||||
{["admin", "developer", "agent"].includes(userType || "") && (
|
||||
{checkAccess(user, [
|
||||
"admin",
|
||||
"developer",
|
||||
"corporate",
|
||||
"teacher",
|
||||
"mastercorporate",
|
||||
]) && (
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsShieldFill}
|
||||
label="Permissions"
|
||||
path={path}
|
||||
keyPath="/permissions"
|
||||
isMinimized={isMinimized}
|
||||
/>
|
||||
)}
|
||||
{checkAccess(user, ["admin", "developer", "agent"], "viewTickets") && (
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsClipboardData}
|
||||
@@ -153,7 +232,8 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
||||
badge={totalAssignedTickets}
|
||||
/>
|
||||
)}
|
||||
{userType === "developer" && (
|
||||
{checkAccess(user, ["developer"]) && (
|
||||
<>
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsCloudFill}
|
||||
@@ -162,24 +242,102 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
||||
keyPath="/generation"
|
||||
isMinimized={isMinimized}
|
||||
/>
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsFileLock}
|
||||
label="Permissions"
|
||||
path={path}
|
||||
keyPath="/permissions"
|
||||
isMinimized={isMinimized}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="-xl:flex flex-col gap-3 xl:hidden">
|
||||
<Nav disabled={disableNavigation} Icon={MdSpaceDashboard} label="Dashboard" path={path} keyPath="/" isMinimized={true} />
|
||||
<Nav disabled={disableNavigation} Icon={BsFileEarmarkText} label="Exams" path={path} keyPath="/exam" isMinimized={true} />
|
||||
<Nav disabled={disableNavigation} Icon={BsPencil} label="Exercises" path={path} keyPath="/exercises" isMinimized={true} />
|
||||
{(userType || "") !== 'agent' && (
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={MdSpaceDashboard}
|
||||
label="Dashboard"
|
||||
path={path}
|
||||
keyPath="/"
|
||||
isMinimized={true}
|
||||
/>
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsFileEarmarkText}
|
||||
label="Exams"
|
||||
path={path}
|
||||
keyPath="/exam"
|
||||
isMinimized={true}
|
||||
/>
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsPencil}
|
||||
label="Exercises"
|
||||
path={path}
|
||||
keyPath="/exercises"
|
||||
isMinimized={true}
|
||||
/>
|
||||
{checkAccess(user, getTypesOfUser(["agent"]), "viewStats") && (
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsGraphUp}
|
||||
label="Stats"
|
||||
path={path}
|
||||
keyPath="/stats"
|
||||
isMinimized={true}
|
||||
/>
|
||||
)}
|
||||
{checkAccess(user, getTypesOfUser(["agent"]), "viewRecords") && (
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsClockHistory}
|
||||
label="Record"
|
||||
path={path}
|
||||
keyPath="/record"
|
||||
isMinimized={true}
|
||||
/>
|
||||
)}
|
||||
{checkAccess(user, getTypesOfUser(["student"])) && (
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsShieldFill}
|
||||
label="Settings"
|
||||
path={path}
|
||||
keyPath="/settings"
|
||||
isMinimized={true}
|
||||
/>
|
||||
)}
|
||||
{checkAccess(user, getTypesOfUser(["student"])) && (
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsShieldFill}
|
||||
label="Permissions"
|
||||
path={path}
|
||||
keyPath="/permissions"
|
||||
isMinimized={true}
|
||||
/>
|
||||
)}
|
||||
{checkAccess(user, ["developer"]) && (
|
||||
<>
|
||||
<Nav disabled={disableNavigation} Icon={BsGraphUp} label="Stats" path={path} keyPath="/stats" isMinimized={true} />
|
||||
<Nav disabled={disableNavigation} Icon={BsClockHistory} label="Record" path={path} keyPath="/record" isMinimized={true} />
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsCloudFill}
|
||||
label="Generation"
|
||||
path={path}
|
||||
keyPath="/generation"
|
||||
isMinimized={true}
|
||||
/>
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsFileLock}
|
||||
label="Permissions"
|
||||
path={path}
|
||||
keyPath="/permissions"
|
||||
isMinimized={true}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{userType !== "student" && (
|
||||
<Nav disabled={disableNavigation} Icon={BsShieldFill} label="Settings" path={path} keyPath="/settings" isMinimized={true} />
|
||||
)}
|
||||
{userType === "developer" && (
|
||||
<Nav disabled={disableNavigation} Icon={BsCloudFill} label="Generation" path={path} keyPath="/generation" isMinimized={true} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="fixed bottom-12 flex flex-col gap-0">
|
||||
@@ -189,10 +347,17 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
||||
onClick={toggleMinimize}
|
||||
className={clsx(
|
||||
"hover:text-mti-rose -xl:hidden flex cursor-pointer items-center gap-4 rounded-full p-4 text-black transition duration-300 ease-in-out",
|
||||
isMinimized ? "w-fit" : "w-full min-w-[250px] px-8",
|
||||
)}>
|
||||
{isMinimized ? <BsChevronBarRight size={24} /> : <BsChevronBarLeft size={24} />}
|
||||
{!isMinimized && <span className="text-lg font-medium">Minimize</span>}
|
||||
isMinimized ? "w-fit" : "w-full min-w-[250px] px-8"
|
||||
)}
|
||||
>
|
||||
{isMinimized ? (
|
||||
<BsChevronBarRight size={24} />
|
||||
) : (
|
||||
<BsChevronBarLeft size={24} />
|
||||
)}
|
||||
{!isMinimized && (
|
||||
<span className="text-lg font-medium">Minimize</span>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
role="button"
|
||||
@@ -200,13 +365,18 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
||||
onClick={focusMode ? () => {} : logout}
|
||||
className={clsx(
|
||||
"hover:text-mti-rose flex cursor-pointer items-center gap-4 rounded-full p-4 text-black transition duration-300 ease-in-out",
|
||||
isMinimized ? "w-fit" : "w-full min-w-[250px] px-8",
|
||||
)}>
|
||||
isMinimized ? "w-fit" : "w-full min-w-[250px] px-8"
|
||||
)}
|
||||
>
|
||||
<RiLogoutBoxFill size={24} />
|
||||
{!isMinimized && <span className="-xl:hidden text-lg font-medium">Log Out</span>}
|
||||
{!isMinimized && (
|
||||
<span className="-xl:hidden text-lg font-medium">Log Out</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{focusMode && <FocusLayer onFocusLayerMouseEnter={onFocusLayerMouseEnter} />}
|
||||
{focusMode && (
|
||||
<FocusLayer onFocusLayerMouseEnter={onFocusLayerMouseEnter} />
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import useStats from "@/hooks/useStats";
|
||||
import {CorporateInformation, CorporateUser, EMPLOYMENT_STATUS, User} from "@/interfaces/user";
|
||||
import {
|
||||
CorporateInformation,
|
||||
CorporateUser,
|
||||
EMPLOYMENT_STATUS,
|
||||
User,
|
||||
Type,
|
||||
} from "@/interfaces/user";
|
||||
import { groupBySession, averageScore } from "@/utils/stats";
|
||||
import { RadioGroup } from "@headlessui/react";
|
||||
import axios from "axios";
|
||||
@@ -8,7 +14,13 @@ import moment from "moment";
|
||||
import { Divider } from "primereact/divider";
|
||||
import { useEffect, useState } from "react";
|
||||
import ReactDatePicker from "react-datepicker";
|
||||
import {BsFileEarmarkText, BsPencil, BsPerson, BsPersonAdd, BsStar} from "react-icons/bs";
|
||||
import {
|
||||
BsFileEarmarkText,
|
||||
BsPencil,
|
||||
BsPerson,
|
||||
BsPersonAdd,
|
||||
BsStar,
|
||||
} from "react-icons/bs";
|
||||
import { toast } from "react-toastify";
|
||||
import Button from "./Low/Button";
|
||||
import Checkbox from "./Low/Checkbox";
|
||||
@@ -20,14 +32,20 @@ import useUsers from "@/hooks/useUsers";
|
||||
import { USER_TYPE_LABELS } from "@/resources/user";
|
||||
import { CURRENCIES } from "@/resources/paypal";
|
||||
import useCodes from "@/hooks/useCodes";
|
||||
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
|
||||
import { PERMISSIONS } from "@/constants/userPermissions";
|
||||
import { PermissionType } from "@/interfaces/permissions";
|
||||
|
||||
const expirationDateColor = (date: Date) => {
|
||||
const momentDate = moment(date);
|
||||
const today = moment(new Date());
|
||||
|
||||
if (today.add(1, "days").isAfter(momentDate)) return "!bg-mti-red-ultralight border-mti-red-light";
|
||||
if (today.add(3, "days").isAfter(momentDate)) return "!bg-mti-rose-ultralight border-mti-rose-light";
|
||||
if (today.add(7, "days").isAfter(momentDate)) return "!bg-mti-orange-ultralight border-mti-orange-light";
|
||||
if (today.add(1, "days").isAfter(momentDate))
|
||||
return "!bg-mti-red-ultralight border-mti-red-light";
|
||||
if (today.add(3, "days").isAfter(momentDate))
|
||||
return "!bg-mti-rose-ultralight border-mti-rose-light";
|
||||
if (today.add(7, "days").isAfter(momentDate))
|
||||
return "!bg-mti-orange-ultralight border-mti-orange-light";
|
||||
};
|
||||
|
||||
interface Props {
|
||||
@@ -68,31 +86,78 @@ const CURRENCIES_OPTIONS = CURRENCIES.map(({label, currency}) => ({
|
||||
label,
|
||||
}));
|
||||
|
||||
const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers, onViewCorporate, disabled = false, disabledFields = {}}: Props) => {
|
||||
const [expiryDate, setExpiryDate] = useState<Date | null | undefined>(user.subscriptionExpirationDate);
|
||||
const UserCard = ({
|
||||
user,
|
||||
loggedInUser,
|
||||
onClose,
|
||||
onViewStudents,
|
||||
onViewTeachers,
|
||||
onViewCorporate,
|
||||
disabled = false,
|
||||
disabledFields = {},
|
||||
}: Props) => {
|
||||
const [expiryDate, setExpiryDate] = useState<Date | null | undefined>(
|
||||
user.subscriptionExpirationDate
|
||||
);
|
||||
const [type, setType] = useState(user.type);
|
||||
const [status, setStatus] = useState(user.status);
|
||||
const [referralAgentLabel, setReferralAgentLabel] = useState<string>();
|
||||
const [position, setPosition] = useState<string | undefined>(user.type === "corporate" ? user.demographicInformation?.position : undefined);
|
||||
const [passport_id, setPassportID] = useState<string | undefined>(user.type === "student" ? user.demographicInformation?.passport_id : undefined);
|
||||
const [position, setPosition] = useState<string | undefined>(
|
||||
user.type === "corporate"
|
||||
? user.demographicInformation?.position
|
||||
: undefined
|
||||
);
|
||||
const [passport_id, setPassportID] = useState<string | undefined>(
|
||||
user.type === "student"
|
||||
? user.demographicInformation?.passport_id
|
||||
: undefined
|
||||
);
|
||||
|
||||
const [referralAgent, setReferralAgent] = useState(user.type === "corporate" ? user.corporateInformation?.referralAgent : undefined);
|
||||
const [referralAgent, setReferralAgent] = useState(
|
||||
user.type === "corporate"
|
||||
? user.corporateInformation?.referralAgent
|
||||
: undefined
|
||||
);
|
||||
const [companyName, setCompanyName] = useState(
|
||||
user.type === "corporate"
|
||||
? user.corporateInformation?.companyInformation.name
|
||||
: user.type === "agent"
|
||||
? user.agentInformation?.companyName
|
||||
: undefined,
|
||||
: undefined
|
||||
);
|
||||
const [arabName, setArabName] = useState(
|
||||
user.type === "agent" ? user.agentInformation?.companyArabName : undefined
|
||||
);
|
||||
const [arabName, setArabName] = useState(user.type === "agent" ? user.agentInformation?.companyArabName : undefined);
|
||||
const [commercialRegistration, setCommercialRegistration] = useState(
|
||||
user.type === "agent" ? user.agentInformation?.commercialRegistration : undefined,
|
||||
user.type === "agent"
|
||||
? user.agentInformation?.commercialRegistration
|
||||
: undefined
|
||||
);
|
||||
const [userAmount, setUserAmount] = useState(
|
||||
user.type === "corporate"
|
||||
? user.corporateInformation?.companyInformation.userAmount
|
||||
: undefined
|
||||
);
|
||||
const [paymentValue, setPaymentValue] = useState(
|
||||
user.type === "corporate"
|
||||
? user.corporateInformation?.payment?.value
|
||||
: undefined
|
||||
);
|
||||
const [paymentCurrency, setPaymentCurrency] = useState(
|
||||
user.type === "corporate"
|
||||
? user.corporateInformation?.payment?.currency
|
||||
: "EUR"
|
||||
);
|
||||
const [monthlyDuration, setMonthlyDuration] = useState(
|
||||
user.type === "corporate"
|
||||
? user.corporateInformation?.monthlyDuration
|
||||
: undefined
|
||||
);
|
||||
const [commissionValue, setCommission] = useState(
|
||||
user.type === "corporate"
|
||||
? user.corporateInformation?.payment?.commission
|
||||
: undefined
|
||||
);
|
||||
const [userAmount, setUserAmount] = useState(user.type === "corporate" ? user.corporateInformation?.companyInformation.userAmount : undefined);
|
||||
const [paymentValue, setPaymentValue] = useState(user.type === "corporate" ? user.corporateInformation?.payment?.value : undefined);
|
||||
const [paymentCurrency, setPaymentCurrency] = useState(user.type === "corporate" ? user.corporateInformation?.payment?.currency : "EUR");
|
||||
const [monthlyDuration, setMonthlyDuration] = useState(user.type === "corporate" ? user.corporateInformation?.monthlyDuration : undefined);
|
||||
const [commissionValue, setCommission] = useState(user.type === "corporate" ? user.corporateInformation?.payment?.commission : undefined);
|
||||
const { stats } = useStats(user.id);
|
||||
const { users } = useUsers();
|
||||
const { codes } = useCodes(user.id);
|
||||
@@ -111,8 +176,11 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
|
||||
const updateUser = () => {
|
||||
if (user.type === "corporate" && (!paymentValue || paymentValue < 0))
|
||||
return toast.error("Please set a price for the user's package before updating!");
|
||||
if (!confirm(`Are you sure you want to update ${user.name}'s account?`)) return;
|
||||
return toast.error(
|
||||
"Please set a price for the user's package before updating!"
|
||||
);
|
||||
if (!confirm(`Are you sure you want to update ${user.name}'s account?`))
|
||||
return;
|
||||
|
||||
axios
|
||||
.post<{ user?: User; ok?: boolean }>(`/api/users/update?id=${user.id}`, {
|
||||
@@ -140,7 +208,9 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
payment: {
|
||||
value: paymentValue,
|
||||
currency: paymentCurrency,
|
||||
...(referralAgent === "" ? {} : {commission: commissionValue}),
|
||||
...(referralAgent === ""
|
||||
? {}
|
||||
: { commission: commissionValue }),
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
@@ -156,7 +226,9 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
|
||||
const generalProfileItems = [
|
||||
{
|
||||
icon: <BsFileEarmarkText className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />,
|
||||
icon: (
|
||||
<BsFileEarmarkText className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />
|
||||
),
|
||||
value: Object.keys(groupBySession(stats)).length,
|
||||
label: "Exams",
|
||||
},
|
||||
@@ -176,21 +248,36 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
user.type === "corporate"
|
||||
? [
|
||||
{
|
||||
icon: <BsPerson className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />,
|
||||
icon: (
|
||||
<BsPerson className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />
|
||||
),
|
||||
value: codes.length,
|
||||
label: "Users Used",
|
||||
},
|
||||
{
|
||||
icon: <BsPersonAdd className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />,
|
||||
icon: (
|
||||
<BsPersonAdd className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />
|
||||
),
|
||||
value: user.corporateInformation.companyInformation.userAmount,
|
||||
label: "Number of Users",
|
||||
},
|
||||
]
|
||||
: [];
|
||||
|
||||
const updateUserPermission = PERMISSIONS.updateUser[user.type] as {
|
||||
list: Type[];
|
||||
perm: PermissionType;
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<ProfileSummary user={user} items={user.type === "corporate" ? corporateProfileItems : generalProfileItems} />
|
||||
<ProfileSummary
|
||||
user={user}
|
||||
items={
|
||||
user.type === "corporate"
|
||||
? corporateProfileItems
|
||||
: generalProfileItems
|
||||
}
|
||||
/>
|
||||
|
||||
{user.type === "agent" && (
|
||||
<>
|
||||
@@ -260,7 +347,9 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
disabled={disabled}
|
||||
/>
|
||||
<div className="flex flex-col gap-3 w-full lg:col-span-3">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Pricing</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Pricing
|
||||
</label>
|
||||
<div className="w-full grid grid-cols-6 gap-2">
|
||||
<Input
|
||||
name="paymentValue"
|
||||
@@ -273,10 +362,13 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
<Select
|
||||
className={clsx(
|
||||
"px-4 py-4 col-span-3 w-full text-sm font-normal placeholder:text-mti-gray-cool bg-white rounded-full border border-mti-gray-platinum focus:outline-none",
|
||||
disabled && "!bg-mti-gray-platinum/40 !text-mti-gray-dim cursor-not-allowed",
|
||||
disabled &&
|
||||
"!bg-mti-gray-platinum/40 !text-mti-gray-dim cursor-not-allowed"
|
||||
)}
|
||||
options={CURRENCIES_OPTIONS}
|
||||
value={CURRENCIES_OPTIONS.find((c) => c.value === paymentCurrency)}
|
||||
value={CURRENCIES_OPTIONS.find(
|
||||
(c) => c.value === paymentCurrency
|
||||
)}
|
||||
onChange={(value) => setPaymentCurrency(value?.value)}
|
||||
menuPortalTarget={document?.body}
|
||||
styles={{
|
||||
@@ -292,7 +384,11 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
}),
|
||||
option: (styles, state) => ({
|
||||
...styles,
|
||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
||||
backgroundColor: state.isFocused
|
||||
? "#D5D9F0"
|
||||
: state.isSelected
|
||||
? "#7872BF"
|
||||
: "white",
|
||||
color: state.isFocused ? "black" : styles.color,
|
||||
}),
|
||||
}}
|
||||
@@ -303,13 +399,19 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
</div>
|
||||
<div className="flex gap-3 w-full">
|
||||
<div className="flex flex-col gap-3 w-8/12">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Country Manager</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Country Manager
|
||||
</label>
|
||||
{referralAgentLabel && (
|
||||
<Select
|
||||
className={clsx(
|
||||
"px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool bg-white rounded-full border border-mti-gray-platinum focus:outline-none",
|
||||
(!["developer", "admin"].includes(loggedInUser.type) || disabledFields.countryManager) &&
|
||||
"!bg-mti-gray-platinum/40 !text-mti-gray-dim cursor-not-allowed",
|
||||
(checkAccess(
|
||||
loggedInUser,
|
||||
getTypesOfUser(["developer", "admin"])
|
||||
) ||
|
||||
disabledFields.countryManager) &&
|
||||
"!bg-mti-gray-platinum/40 !text-mti-gray-dim cursor-not-allowed"
|
||||
)}
|
||||
options={[
|
||||
{ value: "", label: "No referral" },
|
||||
@@ -339,19 +441,30 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
}),
|
||||
option: (styles, state) => ({
|
||||
...styles,
|
||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
||||
backgroundColor: state.isFocused
|
||||
? "#D5D9F0"
|
||||
: state.isSelected
|
||||
? "#7872BF"
|
||||
: "white",
|
||||
color: state.isFocused ? "black" : styles.color,
|
||||
}),
|
||||
}}
|
||||
// editing country manager should only be available for dev/admin
|
||||
isDisabled={!["developer", "admin"].includes(loggedInUser.type) || disabledFields.countryManager}
|
||||
isDisabled={
|
||||
checkAccess(
|
||||
loggedInUser,
|
||||
getTypesOfUser(["developer", "admin"])
|
||||
) || disabledFields.countryManager
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col gap-3 w-4/12">
|
||||
{referralAgent !== "" && loggedInUser.type !== "corporate" ? (
|
||||
<>
|
||||
<label className="font-normal text-base text-mti-gray-dim">Commission</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Commission
|
||||
</label>
|
||||
<Input
|
||||
name="commissionValue"
|
||||
onChange={(e) => setCommission(e ? parseInt(e) : undefined)}
|
||||
@@ -393,8 +506,13 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
|
||||
<div className="flex flex-col md:flex-row gap-8 w-full">
|
||||
<div className="flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Country</label>
|
||||
<CountrySelect disabled value={user.demographicInformation?.country} />
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Country
|
||||
</label>
|
||||
<CountrySelect
|
||||
disabled
|
||||
value={user.demographicInformation?.country}
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
type="tel"
|
||||
@@ -414,20 +532,27 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
label="Passport/National ID"
|
||||
onChange={() => null}
|
||||
placeholder="Enter National ID or Passport number"
|
||||
value={user.type === "student" ? user.demographicInformation?.passport_id : undefined}
|
||||
value={
|
||||
user.type === "student"
|
||||
? user.demographicInformation?.passport_id
|
||||
: undefined
|
||||
}
|
||||
disabled
|
||||
required
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col md:flex-row gap-8 w-full">
|
||||
{user.type !== "corporate" && (
|
||||
{user.type !== "corporate" && user.type !== "mastercorporate" && (
|
||||
<div className="relative flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Employment Status</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Employment Status
|
||||
</label>
|
||||
<RadioGroup
|
||||
value={user.demographicInformation?.employment}
|
||||
className="grid grid-cols-2 items-center gap-4 place-items-center"
|
||||
disabled={disabled}>
|
||||
disabled={disabled}
|
||||
>
|
||||
{EMPLOYMENT_STATUS.map(({ status, label }) => (
|
||||
<RadioGroup.Option value={status} key={status}>
|
||||
{({ checked }) => (
|
||||
@@ -437,8 +562,9 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
"transition duration-300 ease-in-out",
|
||||
!checked
|
||||
? "bg-white border-mti-gray-platinum"
|
||||
: "bg-mti-purple-light border-mti-purple-dark text-white",
|
||||
)}>
|
||||
: "bg-mti-purple-light border-mti-purple-dark text-white"
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
)}
|
||||
@@ -461,11 +587,14 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
)}
|
||||
<div className="flex flex-col gap-8 w-full">
|
||||
<div className="relative flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Gender</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Gender
|
||||
</label>
|
||||
<RadioGroup
|
||||
value={user.demographicInformation?.gender}
|
||||
className="flex flex-row gap-4 justify-between"
|
||||
disabled={disabled}>
|
||||
disabled={disabled}
|
||||
>
|
||||
<RadioGroup.Option value="male">
|
||||
{({ checked }) => (
|
||||
<span
|
||||
@@ -474,8 +603,9 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
"transition duration-300 ease-in-out",
|
||||
!checked
|
||||
? "bg-white border-mti-gray-platinum"
|
||||
: "bg-mti-purple-light border-mti-purple-dark text-white",
|
||||
)}>
|
||||
: "bg-mti-purple-light border-mti-purple-dark text-white"
|
||||
)}
|
||||
>
|
||||
Male
|
||||
</span>
|
||||
)}
|
||||
@@ -488,8 +618,9 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
"transition duration-300 ease-in-out",
|
||||
!checked
|
||||
? "bg-white border-mti-gray-platinum"
|
||||
: "bg-mti-purple-light border-mti-purple-dark text-white",
|
||||
)}>
|
||||
: "bg-mti-purple-light border-mti-purple-dark text-white"
|
||||
)}
|
||||
>
|
||||
Female
|
||||
</span>
|
||||
)}
|
||||
@@ -502,8 +633,9 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
"transition duration-300 ease-in-out",
|
||||
!checked
|
||||
? "bg-white border-mti-gray-platinum"
|
||||
: "bg-mti-purple-light border-mti-purple-dark text-white",
|
||||
)}>
|
||||
: "bg-mti-purple-light border-mti-purple-dark text-white"
|
||||
)}
|
||||
>
|
||||
Other
|
||||
</span>
|
||||
)}
|
||||
@@ -512,11 +644,20 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
</div>
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex justify-between items-center">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Expiry Date</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Expiry Date
|
||||
</label>
|
||||
<Checkbox
|
||||
isChecked={!!expiryDate}
|
||||
onChange={(checked) => setExpiryDate(checked ? user.subscriptionExpirationDate || new Date() : null)}
|
||||
disabled={disabled}>
|
||||
onChange={(checked) =>
|
||||
setExpiryDate(
|
||||
checked
|
||||
? user.subscriptionExpirationDate || new Date()
|
||||
: null
|
||||
)
|
||||
}
|
||||
disabled={disabled}
|
||||
>
|
||||
Enabled
|
||||
</Checkbox>
|
||||
</div>
|
||||
@@ -525,9 +666,12 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
className={clsx(
|
||||
"p-6 w-full flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
|
||||
"transition duration-300 ease-in-out",
|
||||
!expiryDate ? "!bg-mti-green-ultralight !border-mti-green-light" : expirationDateColor(expiryDate),
|
||||
"bg-white border-mti-gray-platinum",
|
||||
)}>
|
||||
!expiryDate
|
||||
? "!bg-mti-green-ultralight !border-mti-green-light"
|
||||
: expirationDateColor(expiryDate),
|
||||
"bg-white border-mti-gray-platinum"
|
||||
)}
|
||||
>
|
||||
{!expiryDate && "Unlimited"}
|
||||
{expiryDate && moment(expiryDate).format("DD/MM/YYYY")}
|
||||
</div>
|
||||
@@ -538,12 +682,14 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
"p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
|
||||
"hover:border-mti-purple tooltip",
|
||||
expirationDateColor(expiryDate),
|
||||
"transition duration-300 ease-in-out",
|
||||
"transition duration-300 ease-in-out"
|
||||
)}
|
||||
filterDate={(date) =>
|
||||
moment(date).isAfter(new Date()) &&
|
||||
(loggedInUser.subscriptionExpirationDate
|
||||
? moment(date).isBefore(moment(loggedInUser.subscriptionExpirationDate))
|
||||
? moment(date).isBefore(
|
||||
moment(loggedInUser.subscriptionExpirationDate)
|
||||
)
|
||||
: true)
|
||||
}
|
||||
dateFormat="dd/MM/yyyy"
|
||||
@@ -555,18 +701,22 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{(loggedInUser.type === "developer" || loggedInUser.type === "admin") && (
|
||||
{checkAccess(loggedInUser, ["developer", "admin"]) && (
|
||||
<>
|
||||
<Divider className="w-full !m-0" />
|
||||
<div className="flex flex-col md:flex-row gap-8 w-full">
|
||||
<div className="flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Status</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Status
|
||||
</label>
|
||||
<Select
|
||||
className="px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed bg-white rounded-full border border-mti-gray-platinum focus:outline-none"
|
||||
options={USER_STATUS_OPTIONS}
|
||||
menuPortalTarget={document?.body}
|
||||
value={USER_STATUS_OPTIONS.find((o) => o.value === status)}
|
||||
onChange={(value) => setStatus(value?.value as typeof user.status)}
|
||||
onChange={(value) =>
|
||||
setStatus(value?.value as typeof user.status)
|
||||
}
|
||||
styles={{
|
||||
control: (styles) => ({
|
||||
...styles,
|
||||
@@ -580,7 +730,11 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||
option: (styles, state) => ({
|
||||
...styles,
|
||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
||||
backgroundColor: state.isFocused
|
||||
? "#D5D9F0"
|
||||
: state.isSelected
|
||||
? "#7872BF"
|
||||
: "white",
|
||||
color: state.isFocused ? "black" : styles.color,
|
||||
}),
|
||||
}}
|
||||
@@ -588,13 +742,17 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Type</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Type
|
||||
</label>
|
||||
<Select
|
||||
className="px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed bg-white rounded-full border border-mti-gray-platinum focus:outline-none"
|
||||
options={USER_TYPE_OPTIONS}
|
||||
menuPortalTarget={document?.body}
|
||||
value={USER_TYPE_OPTIONS.find((o) => o.value === type)}
|
||||
onChange={(value) => setType(value?.value as typeof user.type)}
|
||||
onChange={(value) =>
|
||||
setType(value?.value as typeof user.type)
|
||||
}
|
||||
styles={{
|
||||
control: (styles) => ({
|
||||
...styles,
|
||||
@@ -608,7 +766,11 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||
option: (styles, state) => ({
|
||||
...styles,
|
||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
||||
backgroundColor: state.isFocused
|
||||
? "#D5D9F0"
|
||||
: state.isSelected
|
||||
? "#7872BF"
|
||||
: "white",
|
||||
color: state.isFocused ? "black" : styles.color,
|
||||
}),
|
||||
}}
|
||||
@@ -623,26 +785,56 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
||||
<div className="flex gap-4 justify-between mt-4 w-full">
|
||||
<div className="self-start flex gap-4 justify-start items-center w-full">
|
||||
{onViewCorporate && ["student", "teacher"].includes(user.type) && (
|
||||
<Button className="w-full max-w-[200px]" variant="outline" color="rose" onClick={onViewCorporate}>
|
||||
<Button
|
||||
className="w-full max-w-[200px]"
|
||||
variant="outline"
|
||||
color="rose"
|
||||
onClick={onViewCorporate}
|
||||
>
|
||||
View Corporate
|
||||
</Button>
|
||||
)}
|
||||
{onViewStudents && ["corporate", "teacher"].includes(user.type) && (
|
||||
<Button className="w-full max-w-[200px]" variant="outline" color="rose" onClick={onViewStudents}>
|
||||
<Button
|
||||
className="w-full max-w-[200px]"
|
||||
variant="outline"
|
||||
color="rose"
|
||||
onClick={onViewStudents}
|
||||
>
|
||||
View Students
|
||||
</Button>
|
||||
)}
|
||||
{onViewTeachers && ["student", "corporate"].includes(user.type) && (
|
||||
<Button className="w-full max-w-[200px]" variant="outline" color="rose" onClick={onViewTeachers}>
|
||||
<Button
|
||||
className="w-full max-w-[200px]"
|
||||
variant="outline"
|
||||
color="rose"
|
||||
onClick={onViewTeachers}
|
||||
>
|
||||
View Teachers
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="self-end flex gap-4 w-full justify-end">
|
||||
<Button className="w-full max-w-[200px]" variant="outline" onClick={onClose}>
|
||||
<Button
|
||||
className="w-full max-w-[200px]"
|
||||
variant="outline"
|
||||
onClick={onClose}
|
||||
>
|
||||
Close
|
||||
</Button>
|
||||
<Button disabled={disabled} onClick={updateUser} className="w-full max-w-[200px]">
|
||||
<Button
|
||||
disabled={
|
||||
disabled ||
|
||||
!checkAccess(
|
||||
loggedInUser,
|
||||
updateUserPermission.list,
|
||||
updateUserPermission.perm
|
||||
)
|
||||
}
|
||||
onClick={updateUser}
|
||||
className="w-full max-w-[200px]"
|
||||
>
|
||||
Update
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -2,33 +2,85 @@ import {Type} from "@/interfaces/user";
|
||||
|
||||
export const PERMISSIONS = {
|
||||
generateCode: {
|
||||
student: ["corporate", "developer", "admin"],
|
||||
teacher: ["corporate", "developer", "admin"],
|
||||
student: ["corporate", "developer", "admin", "mastercorporate"],
|
||||
teacher: ["corporate", "developer", "admin", "mastercorporate"],
|
||||
corporate: ["admin", "developer"],
|
||||
mastercorporate: ["admin", "developer"],
|
||||
|
||||
admin: ["developer", "admin"],
|
||||
agent: ["developer", "admin"],
|
||||
developer: ["developer"],
|
||||
},
|
||||
deleteUser: {
|
||||
student: ["corporate", "developer", "admin"],
|
||||
teacher: ["corporate", "developer", "admin"],
|
||||
corporate: ["admin", "developer"],
|
||||
admin: ["developer", "admin"],
|
||||
agent: ["developer", "admin"],
|
||||
developer: ["developer"],
|
||||
student: {
|
||||
perm: "deleteStudent",
|
||||
list: ["corporate", "developer", "admin", "mastercorporate"],
|
||||
},
|
||||
teacher: {
|
||||
perm: "deleteTeacher",
|
||||
list: ["corporate", "developer", "admin", "mastercorporate"],
|
||||
},
|
||||
corporate: {
|
||||
perm: "deleteCorporate",
|
||||
list: ["admin", "developer"],
|
||||
},
|
||||
mastercorporate: {
|
||||
perm: undefined,
|
||||
list: ["admin", "developer"],
|
||||
},
|
||||
|
||||
admin: {
|
||||
perm: "deleteAdmin",
|
||||
list: ["developer", "admin"],
|
||||
},
|
||||
agent: {
|
||||
perm: "deleteCountryManager",
|
||||
list: ["developer", "admin"],
|
||||
},
|
||||
developer: {
|
||||
perm: undefined,
|
||||
list: ["developer"],
|
||||
},
|
||||
},
|
||||
updateUser: {
|
||||
student: ["developer", "admin"],
|
||||
teacher: ["developer", "admin"],
|
||||
corporate: ["admin", "developer"],
|
||||
admin: ["developer", "admin"],
|
||||
agent: ["developer", "admin"],
|
||||
developer: ["developer"],
|
||||
student: {
|
||||
perm: "editStudent",
|
||||
list: ["developer", "admin"],
|
||||
},
|
||||
teacher: {
|
||||
perm: "editTeacher",
|
||||
list: ["developer", "admin"],
|
||||
},
|
||||
|
||||
corporate: {
|
||||
perm: "editCorporate",
|
||||
list: ["admin", "developer"],
|
||||
},
|
||||
mastercorporate: {
|
||||
perm: undefined,
|
||||
list: ["admin", "developer"],
|
||||
},
|
||||
|
||||
admin: {
|
||||
perm: "editAdmin",
|
||||
list: ["developer", "admin"],
|
||||
},
|
||||
|
||||
agent: {
|
||||
perm: "editCountryManager",
|
||||
list: ["developer", "admin"],
|
||||
},
|
||||
developer: {
|
||||
perm: undefined,
|
||||
list: ["developer"],
|
||||
},
|
||||
},
|
||||
updateExpiryDate: {
|
||||
student: ["developer", "admin"],
|
||||
teacher: ["developer", "admin"],
|
||||
corporate: ["admin", "developer"],
|
||||
mastercorporate: ["admin", "developer"],
|
||||
|
||||
admin: ["developer", "admin"],
|
||||
agent: ["developer", "admin"],
|
||||
developer: ["developer"],
|
||||
|
||||
@@ -35,6 +35,7 @@ import GroupList from "@/pages/(admin)/Lists/GroupList";
|
||||
import useFilterStore from "@/stores/listFilterStore";
|
||||
import { useRouter } from "next/router";
|
||||
import useCodes from "@/hooks/useCodes";
|
||||
import { getUserCorporate } from "@/utils/groups";
|
||||
|
||||
interface Props {
|
||||
user: CorporateUser;
|
||||
@@ -44,6 +45,8 @@ export default function CorporateDashboard({ user }: Props) {
|
||||
const [page, setPage] = useState("");
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [corporateUserToShow, setCorporateUserToShow] =
|
||||
useState<CorporateUser>();
|
||||
|
||||
const { stats } = useStats();
|
||||
const { users, reload } = useUsers();
|
||||
@@ -57,6 +60,11 @@ export default function CorporateDashboard({ user }: Props) {
|
||||
setShowModal(!!selectedUser && page === "");
|
||||
}, [selectedUser, page]);
|
||||
|
||||
useEffect(() => {
|
||||
// in this case it fetches the master corporate account
|
||||
getUserCorporate(user.id).then(setCorporateUserToShow);
|
||||
}, [user]);
|
||||
|
||||
const studentFilter = (user: User) =>
|
||||
user.type === "student" &&
|
||||
groups.flatMap((g) => g.participants).includes(user.id);
|
||||
@@ -200,6 +208,15 @@ export default function CorporateDashboard({ user }: Props) {
|
||||
|
||||
const DefaultDashboard = () => (
|
||||
<>
|
||||
{corporateUserToShow && (
|
||||
<div className="absolute top-4 right-4 bg-neutral-200 px-2 rounded-lg py-1">
|
||||
Linked to:{" "}
|
||||
<b>
|
||||
{corporateUserToShow?.corporateInformation?.companyInformation
|
||||
.name || corporateUserToShow.name}
|
||||
</b>
|
||||
</div>
|
||||
)}
|
||||
<section className="flex flex-wrap gap-2 items-center -lg:justify-center lg:justify-between text-center">
|
||||
<IconCard
|
||||
onClick={() => setPage("students")}
|
||||
|
||||
424
src/dashboards/MasterCorporate.tsx
Normal file
424
src/dashboards/MasterCorporate.tsx
Normal file
@@ -0,0 +1,424 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import Modal from "@/components/Modal";
|
||||
import useStats from "@/hooks/useStats";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import { Group, MasterCorporateUser, Stat, User } from "@/interfaces/user";
|
||||
import UserList from "@/pages/(admin)/Lists/UserList";
|
||||
import { dateSorter } from "@/utils";
|
||||
import moment from "moment";
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
BsArrowLeft,
|
||||
BsClipboard2Data,
|
||||
BsClock,
|
||||
BsPaperclip,
|
||||
BsPersonFill,
|
||||
BsPencilSquare,
|
||||
BsPersonCheck,
|
||||
BsPeople,
|
||||
BsBank,
|
||||
} from "react-icons/bs";
|
||||
import UserCard from "@/components/UserCard";
|
||||
import useGroups from "@/hooks/useGroups";
|
||||
|
||||
import { 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 useCodes from "@/hooks/useCodes";
|
||||
|
||||
interface Props {
|
||||
user: MasterCorporateUser;
|
||||
}
|
||||
|
||||
export default function MasterCorporateDashboard({ user }: Props) {
|
||||
const [page, setPage] = useState("");
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
|
||||
const { stats } = useStats();
|
||||
const { users, reload } = useUsers();
|
||||
const { codes } = useCodes(user.id);
|
||||
const { groups } = useGroups(user.id, user.type);
|
||||
|
||||
const masterCorporateUserGroups = [
|
||||
...new Set(
|
||||
groups.filter((u) => u.admin === user.id).flatMap((g) => g.participants)
|
||||
),
|
||||
];
|
||||
const corporateUserGroups = [
|
||||
...new Set(groups.flatMap((g) => g.participants)),
|
||||
];
|
||||
|
||||
const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
setShowModal(!!selectedUser && page === "");
|
||||
}, [selectedUser, page]);
|
||||
|
||||
const studentFilter = (user: User) =>
|
||||
user.type === "student" && corporateUserGroups.includes(user.id);
|
||||
const teacherFilter = (user: User) =>
|
||||
user.type === "teacher" && corporateUserGroups.includes(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 StudentsList = () => {
|
||||
const filter = (x: User) =>
|
||||
x.type === "student" &&
|
||||
(!!selectedUser
|
||||
? corporateUserGroups.includes(x.id) || false
|
||||
: corporateUserGroups.includes(x.id));
|
||||
|
||||
return (
|
||||
<UserList
|
||||
user={user}
|
||||
filters={[filter]}
|
||||
renderHeader={(total) => (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
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>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const TeachersList = () => {
|
||||
const filter = (x: User) =>
|
||||
x.type === "teacher" &&
|
||||
(!!selectedUser
|
||||
? corporateUserGroups.includes(x.id) || false
|
||||
: corporateUserGroups.includes(x.id));
|
||||
|
||||
return (
|
||||
<UserList
|
||||
user={user}
|
||||
filters={[filter]}
|
||||
renderHeader={(total) => (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
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>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const corporateUserFilter = (x: User) =>
|
||||
x.type === "corporate" &&
|
||||
(!!selectedUser
|
||||
? masterCorporateUserGroups.includes(x.id) || false
|
||||
: masterCorporateUserGroups.includes(x.id));
|
||||
|
||||
const CorporateList = () => {
|
||||
return (
|
||||
<UserList
|
||||
user={user}
|
||||
filters={[corporateUserFilter]}
|
||||
renderHeader={(total) => (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
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">Corporates ({total})</h2>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const GroupsList = () => {
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
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.length})
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<GroupList user={user} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const averageLevelCalculator = (studentStats: Stat[]) => {
|
||||
const formattedStats = studentStats
|
||||
.map((s) => ({
|
||||
focus: users.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!
|
||||
),
|
||||
}));
|
||||
|
||||
const levels: { [key in Module]: number } = {
|
||||
reading: 0,
|
||||
listening: 0,
|
||||
writing: 0,
|
||||
speaking: 0,
|
||||
level: 0,
|
||||
};
|
||||
bandScores.forEach((b) => (levels[b.module] += b.level));
|
||||
|
||||
return calculateAverageLevel(levels);
|
||||
};
|
||||
|
||||
const DefaultDashboard = () => (
|
||||
<>
|
||||
<section className="flex flex-wrap gap-2 items-center -lg:justify-center lg:justify-between text-center">
|
||||
<IconCard
|
||||
onClick={() => setPage("students")}
|
||||
Icon={BsPersonFill}
|
||||
label="Students"
|
||||
value={users.filter(studentFilter).length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => setPage("teachers")}
|
||||
Icon={BsPencilSquare}
|
||||
label="Teachers"
|
||||
value={users.filter(teacherFilter).length}
|
||||
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}
|
||||
label="Average Level"
|
||||
value={averageLevelCalculator(
|
||||
stats.filter((s) =>
|
||||
groups.flatMap((g) => g.participants).includes(s.user)
|
||||
)
|
||||
).toFixed(1)}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => setPage("groups")}
|
||||
Icon={BsPeople}
|
||||
label="Groups"
|
||||
value={groups.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsPersonCheck}
|
||||
label="User Balance"
|
||||
value={`${codes.length}/${
|
||||
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={BsBank}
|
||||
label="Corporate"
|
||||
value={masterCorporateUserGroups.length}
|
||||
color="purple"
|
||||
onClick={() => setPage("corporate")}
|
||||
/>
|
||||
</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">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.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">
|
||||
{users
|
||||
.filter(teacherFilter)
|
||||
.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">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.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">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.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>
|
||||
</>
|
||||
);
|
||||
|
||||
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) reload();
|
||||
}}
|
||||
onViewStudents={
|
||||
selectedUser.type === "corporate" ||
|
||||
selectedUser.type === "teacher"
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-students",
|
||||
filter: (x: User) => x.type === "student",
|
||||
});
|
||||
appendUserFilters({
|
||||
id: "belongs-to-admin",
|
||||
filter: (x: User) =>
|
||||
groups
|
||||
.filter(
|
||||
(g) =>
|
||||
g.admin === selectedUser.id ||
|
||||
g.participants.includes(selectedUser.id)
|
||||
)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id),
|
||||
});
|
||||
|
||||
router.push("/list/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
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),
|
||||
});
|
||||
|
||||
router.push("/list/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
user={selectedUser}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</Modal>
|
||||
{page === "students" && <StudentsList />}
|
||||
{page === "teachers" && <TeachersList />}
|
||||
{page === "groups" && <GroupsList />}
|
||||
{page === "corporate" && <CorporateList />}
|
||||
{page === "" && <DefaultDashboard />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -2,16 +2,23 @@ import {Group, User} from "@/interfaces/user";
|
||||
import axios from "axios";
|
||||
import {useEffect, useState} from "react";
|
||||
|
||||
export default function useGroups(admin?: string) {
|
||||
export default function useGroups(admin?: string, userType?: string) {
|
||||
const [groups, setGroups] = useState<Group[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isError, setIsError] = useState(false);
|
||||
|
||||
const isMasterType = userType?.startsWith('master');
|
||||
|
||||
const getData = () => {
|
||||
setIsLoading(true);
|
||||
|
||||
const url = admin ? `/api/groups?admin=${admin}` : "/api/groups";
|
||||
axios
|
||||
.get<Group[]>("/api/groups")
|
||||
.get<Group[]>(url)
|
||||
.then((response) => {
|
||||
if(isMasterType) {
|
||||
return setGroups(response.data);
|
||||
}
|
||||
const filter = (g: Group) => g.admin === admin || g.participants.includes(admin || "");
|
||||
|
||||
const filteredGroups = admin ? response.data.filter(filter) : response.data;
|
||||
@@ -20,7 +27,7 @@ export default function useGroups(admin?: string) {
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
useEffect(getData, [admin]);
|
||||
useEffect(getData, [admin, isMasterType]);
|
||||
|
||||
return {groups, isLoading, isError, reload: getData};
|
||||
}
|
||||
|
||||
49
src/interfaces/permissions.ts
Normal file
49
src/interfaces/permissions.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
export const markets = ["au", "br", "de"] as const;
|
||||
|
||||
export const permissions = [
|
||||
// generate codes are basicly invites
|
||||
"createCodeStudent",
|
||||
"createCodeTeacher",
|
||||
"createCodeCorporate",
|
||||
"createCodeCountryManager",
|
||||
"createCodeAdmin",
|
||||
// exams
|
||||
"createReadingExam",
|
||||
"createListeningExam",
|
||||
"createWritingExam",
|
||||
"createSpeakingExam",
|
||||
"createLevelExam",
|
||||
// view pages
|
||||
"viewExams",
|
||||
"viewExercises",
|
||||
"viewRecords",
|
||||
"viewStats",
|
||||
"viewTickets",
|
||||
"viewPaymentRecords",
|
||||
// view data
|
||||
"viewStudent",
|
||||
"viewTeacher",
|
||||
"viewCorporate",
|
||||
"viewCountryManager",
|
||||
"viewAdmin",
|
||||
// edit data
|
||||
"editStudent",
|
||||
"editTeacher",
|
||||
"editCorporate",
|
||||
"editCountryManager",
|
||||
"editAdmin",
|
||||
// delete data
|
||||
"deleteStudent",
|
||||
"deleteTeacher",
|
||||
"deleteCorporate",
|
||||
"deleteCountryManager",
|
||||
"deleteAdmin",
|
||||
] as const;
|
||||
|
||||
export type PermissionType = (typeof permissions)[keyof typeof permissions];
|
||||
|
||||
export interface Permission {
|
||||
id: string;
|
||||
type: PermissionType;
|
||||
users: string[];
|
||||
}
|
||||
@@ -1,7 +1,15 @@
|
||||
import { Module } from ".";
|
||||
import { InstructorGender } from "./exam";
|
||||
import { PermissionType } from "./permissions";
|
||||
|
||||
export type User = StudentUser | TeacherUser | CorporateUser | AgentUser | AdminUser | DeveloperUser;
|
||||
export type User =
|
||||
| StudentUser
|
||||
| TeacherUser
|
||||
| CorporateUser
|
||||
| AgentUser
|
||||
| AdminUser
|
||||
| DeveloperUser
|
||||
| MasterCorporateUser;
|
||||
export type UserStatus = "active" | "disabled" | "paymentDue";
|
||||
|
||||
export interface BasicUser {
|
||||
@@ -19,6 +27,7 @@ export interface BasicUser {
|
||||
subscriptionExpirationDate?: null | Date;
|
||||
registrationDate?: Date;
|
||||
status: UserStatus;
|
||||
permissions: PermissionType[],
|
||||
}
|
||||
|
||||
export interface StudentUser extends BasicUser {
|
||||
@@ -39,6 +48,12 @@ export interface CorporateUser extends BasicUser {
|
||||
demographicInformation?: DemographicCorporateInformation;
|
||||
}
|
||||
|
||||
export interface MasterCorporateUser extends BasicUser {
|
||||
type: "mastercorporate";
|
||||
corporateInformation: CorporateInformation;
|
||||
demographicInformation?: DemographicCorporateInformation;
|
||||
}
|
||||
|
||||
export interface AgentUser extends BasicUser {
|
||||
type: "agent";
|
||||
agentInformation: AgentInformation;
|
||||
@@ -97,8 +112,15 @@ export interface DemographicCorporateInformation {
|
||||
}
|
||||
|
||||
export type Gender = "male" | "female" | "other";
|
||||
export type EmploymentStatus = "employed" | "student" | "self-employed" | "unemployed" | "retired" | "other";
|
||||
export const EMPLOYMENT_STATUS: {status: EmploymentStatus; label: string}[] = [
|
||||
export type EmploymentStatus =
|
||||
| "employed"
|
||||
| "student"
|
||||
| "self-employed"
|
||||
| "unemployed"
|
||||
| "retired"
|
||||
| "other";
|
||||
export const EMPLOYMENT_STATUS: { status: EmploymentStatus; label: string }[] =
|
||||
[
|
||||
{ status: "student", label: "Student" },
|
||||
{ status: "employed", label: "Employed" },
|
||||
{ status: "unemployed", label: "Unemployed" },
|
||||
@@ -148,5 +170,20 @@ export interface Code {
|
||||
passport_id?: string;
|
||||
}
|
||||
|
||||
export type Type = "student" | "teacher" | "corporate" | "admin" | "developer" | "agent";
|
||||
export const userTypes: Type[] = ["student", "teacher", "corporate", "admin", "developer", "agent"];
|
||||
export type Type =
|
||||
| "student"
|
||||
| "teacher"
|
||||
| "corporate"
|
||||
| "admin"
|
||||
| "developer"
|
||||
| "agent"
|
||||
| "mastercorporate";
|
||||
export const userTypes: Type[] = [
|
||||
"student",
|
||||
"teacher",
|
||||
"corporate",
|
||||
"admin",
|
||||
"developer",
|
||||
"agent",
|
||||
"mastercorporate",
|
||||
];
|
||||
|
||||
@@ -16,23 +16,69 @@ import {useFilePicker} from "use-file-picker";
|
||||
import readXlsxFile from "read-excel-file";
|
||||
import Modal from "@/components/Modal";
|
||||
import { BsFileEarmarkEaselFill, BsQuestionCircleFill } from "react-icons/bs";
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
import { PermissionType } from "@/interfaces/permissions";
|
||||
const EMAIL_REGEX = new RegExp(
|
||||
/^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$/
|
||||
);
|
||||
|
||||
const EMAIL_REGEX = new RegExp(/^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$/);
|
||||
|
||||
const USER_TYPE_PERMISSIONS: {[key in Type]: Type[]} = {
|
||||
student: [],
|
||||
teacher: [],
|
||||
agent: [],
|
||||
corporate: ["student", "teacher"],
|
||||
admin: ["student", "teacher", "agent", "corporate", "admin"],
|
||||
developer: ["student", "teacher", "agent", "corporate", "admin", "developer"],
|
||||
const USER_TYPE_PERMISSIONS: {
|
||||
[key in Type]: { perm: PermissionType | undefined; list: Type[] };
|
||||
} = {
|
||||
student: {
|
||||
perm: "createCodeStudent",
|
||||
list: [],
|
||||
},
|
||||
teacher: {
|
||||
perm: "createCodeTeacher",
|
||||
list: [],
|
||||
},
|
||||
agent: {
|
||||
perm: "createCodeCountryManager",
|
||||
list: [],
|
||||
},
|
||||
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",
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export default function BatchCodeGenerator({ user }: { user: User }) {
|
||||
const [infos, setInfos] = useState<{email: string; name: string; passport_id: string}[]>([]);
|
||||
const [infos, setInfos] = useState<
|
||||
{ email: string; name: string; passport_id: string }[]
|
||||
>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [expiryDate, setExpiryDate] = useState<Date | null>(
|
||||
user?.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).toDate() : null,
|
||||
user?.subscriptionExpirationDate
|
||||
? moment(user.subscriptionExpirationDate).toDate()
|
||||
: null
|
||||
);
|
||||
const [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true);
|
||||
const [type, setType] = useState<Type>("student");
|
||||
@@ -58,7 +104,14 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
||||
const information = uniqBy(
|
||||
rows
|
||||
.map((row) => {
|
||||
const [firstName, lastName, country, passport_id, email, ...phone] = row as string[];
|
||||
const [
|
||||
firstName,
|
||||
lastName,
|
||||
country,
|
||||
passport_id,
|
||||
email,
|
||||
...phone
|
||||
] = row as string[];
|
||||
return EMAIL_REGEX.test(email.toString().trim())
|
||||
? {
|
||||
email: email.toString().trim().toLowerCase(),
|
||||
@@ -68,12 +121,12 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
||||
: undefined;
|
||||
})
|
||||
.filter((x) => !!x) as typeof infos,
|
||||
(x) => x.email,
|
||||
(x) => x.email
|
||||
);
|
||||
|
||||
if (information.length === 0) {
|
||||
toast.error(
|
||||
"Please upload an Excel file containing user information, one per line! All already registered e-mails have also been ignored!",
|
||||
"Please upload an Excel file containing user information, one per line! All already registered e-mails have also been ignored!"
|
||||
);
|
||||
return clear();
|
||||
}
|
||||
@@ -81,7 +134,7 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
||||
setInfos(information);
|
||||
} catch {
|
||||
toast.error(
|
||||
"Please upload an Excel file containing user information, one per line! All already registered e-mails have also been ignored!",
|
||||
"Please upload an Excel file containing user information, one per line! All already registered e-mails have also been ignored!"
|
||||
);
|
||||
return clear();
|
||||
}
|
||||
@@ -91,24 +144,41 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
||||
}, [filesContent]);
|
||||
|
||||
const generateAndInvite = async () => {
|
||||
const newUsers = infos.filter((x) => !users.map((u) => u.email).includes(x.email));
|
||||
const newUsers = infos.filter(
|
||||
(x) => !users.map((u) => u.email).includes(x.email)
|
||||
);
|
||||
const existingUsers = infos
|
||||
.filter((x) => users.map((u) => u.email).includes(x.email))
|
||||
.map((i) => users.find((u) => u.email === i.email))
|
||||
.filter((x) => !!x && x.type === "student") as User[];
|
||||
|
||||
const newUsersSentence = newUsers.length > 0 ? `generate ${newUsers.length} code(s)` : undefined;
|
||||
const existingUsersSentence = existingUsers.length > 0 ? `invite ${existingUsers.length} registered student(s)` : undefined;
|
||||
const newUsersSentence =
|
||||
newUsers.length > 0 ? `generate ${newUsers.length} code(s)` : undefined;
|
||||
const existingUsersSentence =
|
||||
existingUsers.length > 0
|
||||
? `invite ${existingUsers.length} registered student(s)`
|
||||
: undefined;
|
||||
if (
|
||||
!confirm(
|
||||
`You are about to ${[newUsersSentence, existingUsersSentence].filter((x) => !!x).join(" and ")}, are you sure you want to continue?`,
|
||||
`You are about to ${[newUsersSentence, existingUsersSentence]
|
||||
.filter((x) => !!x)
|
||||
.join(" and ")}, are you sure you want to continue?`
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
setIsLoading(true);
|
||||
Promise.all(existingUsers.map(async (u) => await axios.post(`/api/invites`, {to: u.id, from: user.id})))
|
||||
.then(() => toast.success(`Successfully invited ${existingUsers.length} registered student(s)!`))
|
||||
Promise.all(
|
||||
existingUsers.map(
|
||||
async (u) =>
|
||||
await axios.post(`/api/invites`, { to: u.id, from: user.id })
|
||||
)
|
||||
)
|
||||
.then(() =>
|
||||
toast.success(
|
||||
`Successfully invited ${existingUsers.length} registered student(s)!`
|
||||
)
|
||||
)
|
||||
.finally(() => {
|
||||
if (newUsers.length === 0) setIsLoading(false);
|
||||
});
|
||||
@@ -132,10 +202,10 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
||||
.then(({ data, status }) => {
|
||||
if (data.ok) {
|
||||
toast.success(
|
||||
`Successfully generated${data.valid ? ` ${data.valid}/${informations.length}` : ""} ${capitalize(
|
||||
type,
|
||||
)} codes and they have been notified by e-mail!`,
|
||||
{toastId: "success"},
|
||||
`Successfully generated${
|
||||
data.valid ? ` ${data.valid}/${informations.length}` : ""
|
||||
} ${capitalize(type)} codes and they have been notified by e-mail!`,
|
||||
{ toastId: "success" }
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -162,18 +232,30 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal isOpen={showHelp} onClose={() => setShowHelp(false)} title="Excel File Format">
|
||||
<Modal
|
||||
isOpen={showHelp}
|
||||
onClose={() => setShowHelp(false)}
|
||||
title="Excel File Format"
|
||||
>
|
||||
<div className="mt-4 flex flex-col gap-2">
|
||||
<span>Please upload an Excel file with the following format:</span>
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="border border-neutral-200 px-2 py-1">First Name</th>
|
||||
<th className="border border-neutral-200 px-2 py-1">Last Name</th>
|
||||
<th className="border border-neutral-200 px-2 py-1">
|
||||
First Name
|
||||
</th>
|
||||
<th className="border border-neutral-200 px-2 py-1">
|
||||
Last Name
|
||||
</th>
|
||||
<th className="border border-neutral-200 px-2 py-1">Country</th>
|
||||
<th className="border border-neutral-200 px-2 py-1">Passport/National ID</th>
|
||||
<th className="border border-neutral-200 px-2 py-1">
|
||||
Passport/National ID
|
||||
</th>
|
||||
<th className="border border-neutral-200 px-2 py-1">E-mail</th>
|
||||
<th className="border border-neutral-200 px-2 py-1">Phone Number</th>
|
||||
<th className="border border-neutral-200 px-2 py-1">
|
||||
Phone Number
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
</table>
|
||||
@@ -182,27 +264,50 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
||||
<ul>
|
||||
<li>- All incorrect e-mails will be ignored;</li>
|
||||
<li>- All already registered e-mails will be ignored;</li>
|
||||
<li>- You may have a header row with the format above, however, it is not necessary;</li>
|
||||
<li>- All of the e-mails in the file will receive an e-mail to join EnCoach with the role selected below.</li>
|
||||
<li>
|
||||
- You may have a header row with the format above, however, it
|
||||
is not necessary;
|
||||
</li>
|
||||
<li>
|
||||
- All of the e-mails in the file will receive an e-mail to join
|
||||
EnCoach with the role selected below.
|
||||
</li>
|
||||
</ul>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
<div className="border-mti-gray-platinum flex flex-col gap-4 rounded-xl border p-4">
|
||||
<div className="flex items-end justify-between">
|
||||
<label className="text-mti-gray-dim text-base font-normal">Choose an Excel file</label>
|
||||
<div className="tooltip cursor-pointer" data-tip="Excel File Format" onClick={() => setShowHelp(true)}>
|
||||
<label className="text-mti-gray-dim text-base font-normal">
|
||||
Choose an Excel file
|
||||
</label>
|
||||
<div
|
||||
className="tooltip cursor-pointer"
|
||||
data-tip="Excel File Format"
|
||||
onClick={() => setShowHelp(true)}
|
||||
>
|
||||
<BsQuestionCircleFill />
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={openFilePicker} isLoading={isLoading} disabled={isLoading}>
|
||||
<Button
|
||||
onClick={openFilePicker}
|
||||
isLoading={isLoading}
|
||||
disabled={isLoading}
|
||||
>
|
||||
{filesContent.length > 0 ? filesContent[0].name : "Choose a file"}
|
||||
</Button>
|
||||
{user && (user.type === "developer" || user.type === "admin" || user.type === "corporate") && (
|
||||
{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}>
|
||||
<label className="text-mti-gray-dim text-base font-normal">
|
||||
Expiry Date
|
||||
</label>
|
||||
<Checkbox
|
||||
isChecked={isExpiryDateEnabled}
|
||||
onChange={setIsExpiryDateEnabled}
|
||||
disabled={!!user.subscriptionExpirationDate}
|
||||
>
|
||||
Enabled
|
||||
</Checkbox>
|
||||
</div>
|
||||
@@ -211,11 +316,13 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
||||
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",
|
||||
"transition duration-300 ease-in-out"
|
||||
)}
|
||||
filterDate={(date) =>
|
||||
moment(date).isAfter(new Date()) &&
|
||||
(user.subscriptionExpirationDate ? moment(date).isBefore(user.subscriptionExpirationDate) : true)
|
||||
(user.subscriptionExpirationDate
|
||||
? moment(date).isBefore(user.subscriptionExpirationDate)
|
||||
: true)
|
||||
}
|
||||
dateFormat="dd/MM/yyyy"
|
||||
selected={expiryDate}
|
||||
@@ -224,14 +331,20 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<label className="text-mti-gray-dim text-base font-normal">Select the type of user they should be</label>
|
||||
<label className="text-mti-gray-dim text-base font-normal">
|
||||
Select the type of user they should be
|
||||
</label>
|
||||
{user && (
|
||||
<select
|
||||
defaultValue="student"
|
||||
onChange={(e) => setType(e.target.value as typeof user.type)}
|
||||
className="flex min-h-[70px] w-full min-w-[350px] cursor-pointer justify-center rounded-full border bg-white p-6 text-sm font-normal focus:outline-none">
|
||||
className="flex min-h-[70px] w-full min-w-[350px] cursor-pointer justify-center rounded-full border bg-white p-6 text-sm font-normal focus:outline-none"
|
||||
>
|
||||
{Object.keys(USER_TYPE_LABELS)
|
||||
.filter((x) => USER_TYPE_PERMISSIONS[user.type].includes(x as Type))
|
||||
.filter((x) => {
|
||||
const { list, perm } = USER_TYPE_PERMISSIONS[x as Type];
|
||||
return checkAccess(user, list, perm);
|
||||
})
|
||||
.map((type) => (
|
||||
<option key={type} value={type}>
|
||||
{USER_TYPE_LABELS[type as keyof typeof USER_TYPE_LABELS]}
|
||||
@@ -239,7 +352,12 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<Button onClick={generateAndInvite} disabled={infos.length === 0 || (isExpiryDateEnabled ? !expiryDate : false)}>
|
||||
<Button
|
||||
onClick={generateAndInvite}
|
||||
disabled={
|
||||
infos.length === 0 || (isExpiryDateEnabled ? !expiryDate : false)
|
||||
}
|
||||
>
|
||||
Generate & Send
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -11,20 +11,63 @@ import {useEffect, useState} from "react";
|
||||
import ReactDatePicker from "react-datepicker";
|
||||
import { toast } from "react-toastify";
|
||||
import ShortUniqueId from "short-unique-id";
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
import { PermissionType } from "@/interfaces/permissions";
|
||||
|
||||
const USER_TYPE_PERMISSIONS: {[key in Type]: Type[]} = {
|
||||
student: [],
|
||||
teacher: [],
|
||||
agent: [],
|
||||
corporate: ["student", "teacher"],
|
||||
admin: ["student", "teacher", "agent", "corporate", "admin"],
|
||||
developer: ["student", "teacher", "agent", "corporate", "admin", "developer"],
|
||||
const USER_TYPE_PERMISSIONS: {
|
||||
[key in Type]: { perm: PermissionType | undefined; list: Type[] };
|
||||
} = {
|
||||
student: {
|
||||
perm: "createCodeStudent",
|
||||
list: [],
|
||||
},
|
||||
teacher: {
|
||||
perm: "createCodeTeacher",
|
||||
list: [],
|
||||
},
|
||||
agent: {
|
||||
perm: "createCodeCountryManager",
|
||||
list: [],
|
||||
},
|
||||
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",
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export default function CodeGenerator({ user }: { user: User }) {
|
||||
const [generatedCode, setGeneratedCode] = useState<string>();
|
||||
const [expiryDate, setExpiryDate] = useState<Date | null>(
|
||||
user?.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).toDate() : null,
|
||||
user?.subscriptionExpirationDate
|
||||
? moment(user.subscriptionExpirationDate).toDate()
|
||||
: null
|
||||
);
|
||||
const [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true);
|
||||
const [type, setType] = useState<Type>("student");
|
||||
@@ -41,7 +84,9 @@ export default function CodeGenerator({user}: {user: User}) {
|
||||
.post("/api/code", { type, codes: [code], expiryDate })
|
||||
.then(({ data, status }) => {
|
||||
if (data.ok) {
|
||||
toast.success(`Successfully generated a ${capitalize(type)} code!`, {toastId: "success"});
|
||||
toast.success(`Successfully generated a ${capitalize(type)} code!`, {
|
||||
toastId: "success",
|
||||
});
|
||||
setGeneratedCode(code);
|
||||
return;
|
||||
}
|
||||
@@ -56,20 +101,28 @@ export default function CodeGenerator({user}: {user: User}) {
|
||||
return;
|
||||
}
|
||||
|
||||
toast.error(`Something went wrong, please try again later!`, {toastId: "error"});
|
||||
toast.error(`Something went wrong, please try again later!`, {
|
||||
toastId: "error",
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 border p-4 border-mti-gray-platinum rounded-xl">
|
||||
<label className="font-normal text-base text-mti-gray-dim">User Code Generator</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
User Code Generator
|
||||
</label>
|
||||
{user && (
|
||||
<select
|
||||
defaultValue="student"
|
||||
onChange={(e) => setType(e.target.value as typeof user.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">
|
||||
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) => USER_TYPE_PERMISSIONS[user.type].includes(x as Type))
|
||||
.filter((x) => {
|
||||
const { list, perm } = USER_TYPE_PERMISSIONS[x as Type];
|
||||
return checkAccess(user, list, perm);
|
||||
})
|
||||
.map((type) => (
|
||||
<option key={type} value={type}>
|
||||
{USER_TYPE_LABELS[type as keyof typeof USER_TYPE_LABELS]}
|
||||
@@ -77,11 +130,18 @@ export default function CodeGenerator({user}: {user: User}) {
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
{user && (user.type === "developer" || user.type === "admin" || user.type === "corporate") && (
|
||||
{user &&
|
||||
checkAccess(user, ["developer", "admin", "corporate"]) && (
|
||||
<>
|
||||
<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}>
|
||||
<label className="text-mti-gray-dim text-base font-normal">
|
||||
Expiry Date
|
||||
</label>
|
||||
<Checkbox
|
||||
isChecked={isExpiryDateEnabled}
|
||||
onChange={setIsExpiryDateEnabled}
|
||||
disabled={!!user.subscriptionExpirationDate}
|
||||
>
|
||||
Enabled
|
||||
</Checkbox>
|
||||
</div>
|
||||
@@ -90,11 +150,13 @@ export default function CodeGenerator({user}: {user: User}) {
|
||||
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",
|
||||
"transition duration-300 ease-in-out"
|
||||
)}
|
||||
filterDate={(date) =>
|
||||
moment(date).isAfter(new Date()) &&
|
||||
(user.subscriptionExpirationDate ? moment(date).isBefore(user.subscriptionExpirationDate) : true)
|
||||
(user.subscriptionExpirationDate
|
||||
? moment(date).isBefore(user.subscriptionExpirationDate)
|
||||
: true)
|
||||
}
|
||||
dateFormat="dd/MM/yyyy"
|
||||
selected={expiryDate}
|
||||
@@ -103,23 +165,33 @@ export default function CodeGenerator({user}: {user: User}) {
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<Button onClick={() => generateCode(type)} disabled={isExpiryDateEnabled ? !expiryDate : false}>
|
||||
<Button
|
||||
onClick={() => generateCode(type)}
|
||||
disabled={isExpiryDateEnabled ? !expiryDate : false}
|
||||
>
|
||||
Generate
|
||||
</Button>
|
||||
<label className="font-normal text-base text-mti-gray-dim">Generated Code:</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Generated Code:
|
||||
</label>
|
||||
<div
|
||||
className={clsx(
|
||||
"p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
|
||||
"hover:border-mti-purple tooltip",
|
||||
"transition duration-300 ease-in-out",
|
||||
"transition duration-300 ease-in-out"
|
||||
)}
|
||||
data-tip="Click to copy"
|
||||
onClick={() => {
|
||||
if (generatedCode) navigator.clipboard.writeText(generatedCode);
|
||||
}}>
|
||||
}}
|
||||
>
|
||||
{generatedCode}
|
||||
</div>
|
||||
{generatedCode && <span className="text-sm text-mti-gray-dim font-light">Give this code to the user to complete their registration</span>}
|
||||
{generatedCode && (
|
||||
<span className="text-sm text-mti-gray-dim font-light">
|
||||
Give this code to the user to complete their registration
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -86,7 +86,7 @@ const CreatePanel = ({user, users, group, onClose}: CreateDialogProps) => {
|
||||
const emailUsers = [...new Set(emails)].map((x) => users.find((y) => y.email.toLowerCase() === x)).filter((x) => x !== undefined);
|
||||
const filteredUsers = emailUsers.filter(
|
||||
(x) =>
|
||||
((user.type === "developer" || user.type === "admin" || user.type === "corporate") &&
|
||||
((user.type === "developer" || user.type === "admin" || user.type === "corporate" || user.type === "mastercorporate") &&
|
||||
(x?.type === "student" || x?.type === "teacher")) ||
|
||||
(user.type === "teacher" && x?.type === "student"),
|
||||
);
|
||||
@@ -189,7 +189,7 @@ const CreatePanel = ({user, users, group, onClose}: CreateDialogProps) => {
|
||||
);
|
||||
};
|
||||
|
||||
const filterTypes = ["corporate", "teacher"];
|
||||
const filterTypes = ["corporate", "teacher", "mastercorporate"];
|
||||
|
||||
export default function GroupList({user}: {user: User}) {
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
@@ -197,10 +197,10 @@ export default function GroupList({user}: {user: User}) {
|
||||
const [filterByUser, setFilterByUser] = useState(false);
|
||||
|
||||
const {users} = useUsers();
|
||||
const {groups, reload} = useGroups(user && filterTypes.includes(user?.type) ? user.id : undefined);
|
||||
const {groups, reload} = useGroups(user && filterTypes.includes(user?.type) ? user.id : undefined, user?.type);
|
||||
|
||||
useEffect(() => {
|
||||
if (user && (user.type === "corporate" || user.type === "teacher")) {
|
||||
if (user && (['corporate', 'teacher', 'mastercorporate'].includes(user.type))) {
|
||||
setFilterByUser(true);
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
@@ -4,19 +4,38 @@ import useGroups from "@/hooks/useGroups";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import { Type, User, userTypes, CorporateUser, Group } from "@/interfaces/user";
|
||||
import { Popover, Transition } from "@headlessui/react";
|
||||
import {createColumnHelper, flexRender, getCoreRowModel, useReactTable} from "@tanstack/react-table";
|
||||
import {
|
||||
createColumnHelper,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
} from "@tanstack/react-table";
|
||||
import axios from "axios";
|
||||
import clsx from "clsx";
|
||||
import { capitalize, reverse } from "lodash";
|
||||
import moment from "moment";
|
||||
import { Fragment, useEffect, useState } from "react";
|
||||
import {BsArrowDown, BsArrowDownUp, BsArrowUp, BsCheck, BsCheckCircle, BsEye, BsFillExclamationOctagonFill, BsPerson, BsTrash} from "react-icons/bs";
|
||||
import {
|
||||
BsArrowDown,
|
||||
BsArrowDownUp,
|
||||
BsArrowUp,
|
||||
BsCheck,
|
||||
BsCheckCircle,
|
||||
BsEye,
|
||||
BsFillExclamationOctagonFill,
|
||||
BsPerson,
|
||||
BsTrash,
|
||||
} from "react-icons/bs";
|
||||
import { toast } from "react-toastify";
|
||||
import { countries, TCountries } from "countries-list";
|
||||
import countryCodes from "country-codes-list";
|
||||
import Modal from "@/components/Modal";
|
||||
import UserCard from "@/components/UserCard";
|
||||
import {getUserCompanyName, isAgentUser, USER_TYPE_LABELS} from "@/resources/user";
|
||||
import {
|
||||
getUserCompanyName,
|
||||
isAgentUser,
|
||||
USER_TYPE_LABELS,
|
||||
} from "@/resources/user";
|
||||
import useFilterStore from "@/stores/listFilterStore";
|
||||
import { useRouter } from "next/router";
|
||||
import { isCorporateUser } from "@/resources/user";
|
||||
@@ -24,11 +43,24 @@ import {useListSearch} from "@/hooks/useListSearch";
|
||||
import { getUserCorporate } from "@/utils/groups";
|
||||
import { asyncSorter } from "@/utils";
|
||||
import { exportListToExcel, UserListRow } from "@/utils/users";
|
||||
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
import { PermissionType } from "@/interfaces/permissions";
|
||||
const columnHelper = createColumnHelper<User>();
|
||||
const searchFields = [["name"], ["email"], ["corporateInformation", "companyInformation", "name"]];
|
||||
const searchFields = [
|
||||
["name"],
|
||||
["email"],
|
||||
["corporateInformation", "companyInformation", "name"],
|
||||
];
|
||||
|
||||
const CompanyNameCell = ({users, user, groups}: {user: User; users: User[]; groups: Group[]}) => {
|
||||
const CompanyNameCell = ({
|
||||
users,
|
||||
user,
|
||||
groups,
|
||||
}: {
|
||||
user: User;
|
||||
users: User[];
|
||||
groups: Group[];
|
||||
}) => {
|
||||
const [companyName, setCompanyName] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
@@ -37,7 +69,11 @@ const CompanyNameCell = ({users, user, groups}: {user: User; users: User[]; grou
|
||||
setCompanyName(name);
|
||||
}, [user, users, groups]);
|
||||
|
||||
return isLoading ? <span className="animate-pulse">Loading...</span> : <>{companyName}</>;
|
||||
return isLoading ? (
|
||||
<span className="animate-pulse">Loading...</span>
|
||||
) : (
|
||||
<>{companyName}</>
|
||||
);
|
||||
};
|
||||
|
||||
export default function UserList({
|
||||
@@ -49,13 +85,18 @@ export default function UserList({
|
||||
filters?: ((user: User) => boolean)[];
|
||||
renderHeader?: (total: number) => JSX.Element;
|
||||
}) {
|
||||
const [showDemographicInformation, setShowDemographicInformation] = useState(false);
|
||||
const [showDemographicInformation, setShowDemographicInformation] =
|
||||
useState(false);
|
||||
const [sorter, setSorter] = useState<string>();
|
||||
const [displayUsers, setDisplayUsers] = useState<User[]>([]);
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
|
||||
const { users, reload } = useUsers();
|
||||
const {groups} = useGroups(user && (user?.type === "corporate" || user?.type === "teacher") ? user.id : undefined);
|
||||
const { groups } = useGroups(
|
||||
user && ["corporate", "teacher", "mastercorporate"].includes(user?.type)
|
||||
? user.id
|
||||
: undefined
|
||||
);
|
||||
|
||||
const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
|
||||
const router = useRouter();
|
||||
@@ -64,10 +105,13 @@ export default function UserList({
|
||||
const momentDate = moment(date);
|
||||
const today = moment(new Date());
|
||||
|
||||
if (today.isAfter(momentDate)) return "!text-mti-red-light font-bold line-through";
|
||||
if (today.isAfter(momentDate))
|
||||
return "!text-mti-red-light font-bold line-through";
|
||||
if (today.add(1, "weeks").isAfter(momentDate)) return "!text-mti-red-light";
|
||||
if (today.add(2, "weeks").isAfter(momentDate)) return "!text-mti-rose-light";
|
||||
if (today.add(1, "months").isAfter(momentDate)) return "!text-mti-orange-light";
|
||||
if (today.add(2, "weeks").isAfter(momentDate))
|
||||
return "!text-mti-rose-light";
|
||||
if (today.add(1, "months").isAfter(momentDate))
|
||||
return "!text-mti-orange-light";
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -75,11 +119,19 @@ export default function UserList({
|
||||
if (user && users) {
|
||||
const filterUsers =
|
||||
user.type === "corporate" || user.type === "teacher"
|
||||
? users.filter((u) => groups.flatMap((g) => g.participants).includes(u.id))
|
||||
? users.filter((u) =>
|
||||
groups.flatMap((g) => g.participants).includes(u.id)
|
||||
)
|
||||
: users;
|
||||
|
||||
const filteredUsers = filters.reduce((d, f) => d.filter(f), filterUsers);
|
||||
const sortedUsers = await asyncSorter<User>(filteredUsers, sortFunction);
|
||||
const filteredUsers = filters.reduce(
|
||||
(d, f) => d.filter(f),
|
||||
filterUsers
|
||||
);
|
||||
const sortedUsers = await asyncSorter<User>(
|
||||
filteredUsers,
|
||||
sortFunction
|
||||
);
|
||||
|
||||
setDisplayUsers([...sortedUsers]);
|
||||
}
|
||||
@@ -88,7 +140,8 @@ export default function UserList({
|
||||
}, [user, users, sorter, groups]);
|
||||
|
||||
const deleteAccount = (user: User) => {
|
||||
if (!confirm(`Are you sure you want to delete ${user.name}'s account?`)) return;
|
||||
if (!confirm(`Are you sure you want to delete ${user.name}'s account?`))
|
||||
return;
|
||||
|
||||
axios
|
||||
.delete<{ ok: boolean }>(`/api/user?id=${user.id}`)
|
||||
@@ -103,7 +156,14 @@ export default function UserList({
|
||||
};
|
||||
|
||||
const updateAccountType = (user: User, type: Type) => {
|
||||
if (!confirm(`Are you sure you want to update ${user.name}'s account from ${capitalize(user.type)} to ${capitalize(type)}?`)) return;
|
||||
if (
|
||||
!confirm(
|
||||
`Are you sure you want to update ${
|
||||
user.name
|
||||
}'s account from ${capitalize(user.type)} to ${capitalize(type)}?`
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
axios
|
||||
.post<{ user?: User; ok?: boolean }>(`/api/users/update?id=${user.id}`, {
|
||||
@@ -137,9 +197,11 @@ export default function UserList({
|
||||
const toggleDisableAccount = (user: User) => {
|
||||
if (
|
||||
!confirm(
|
||||
`Are you sure you want to ${user.status === "disabled" ? "enable" : "disable"} ${
|
||||
`Are you sure you want to ${
|
||||
user.status === "disabled" ? "enable" : "disable"
|
||||
} ${
|
||||
user.name
|
||||
}'s account? This change is usually related to their payment state.`,
|
||||
}'s account? This change is usually related to their payment state.`
|
||||
)
|
||||
)
|
||||
return;
|
||||
@@ -150,7 +212,11 @@ export default function UserList({
|
||||
status: user.status === "disabled" ? "active" : "disabled",
|
||||
})
|
||||
.then(() => {
|
||||
toast.success(`User ${user.status === "disabled" ? "enabled" : "disabled"} successfully!`);
|
||||
toast.success(
|
||||
`User ${
|
||||
user.status === "disabled" ? "enabled" : "disabled"
|
||||
} successfully!`
|
||||
);
|
||||
reload();
|
||||
})
|
||||
.catch(() => {
|
||||
@@ -166,9 +232,21 @@ export default function UserList({
|
||||
};
|
||||
|
||||
const actionColumn = ({ row }: { row: { original: User } }) => {
|
||||
const updateUserPermission = PERMISSIONS.updateUser[row.original.type] as {
|
||||
list: Type[];
|
||||
perm: PermissionType;
|
||||
};
|
||||
const deleteUserPermission = PERMISSIONS.deleteUser[row.original.type] as {
|
||||
list: Type[];
|
||||
perm: PermissionType;
|
||||
};
|
||||
return (
|
||||
<div className="flex gap-4">
|
||||
{PERMISSIONS.updateUser[row.original.type]?.includes(user.type) && (
|
||||
{checkAccess(
|
||||
user,
|
||||
updateUserPermission.list,
|
||||
updateUserPermission.perm
|
||||
) && (
|
||||
<Popover className="relative">
|
||||
<Popover.Button>
|
||||
<div data-tip="Change Type" className="cursor-pointer tooltip">
|
||||
@@ -182,31 +260,48 @@ export default function UserList({
|
||||
enterTo="opacity-100 translate-y-0"
|
||||
leave="transition ease-in duration-150"
|
||||
leaveFrom="opacity-100 translate-y-0"
|
||||
leaveTo="opacity-0 translate-y-1">
|
||||
leaveTo="opacity-0 translate-y-1"
|
||||
>
|
||||
<Popover.Panel className="absolute z-10 w-screen right-1/2 translate-x-1/3 max-w-sm">
|
||||
<div className="bg-white p-4 rounded-lg grid grid-cols-2 gap-2 w-full drop-shadow-xl">
|
||||
<Button
|
||||
onClick={() => updateAccountType(row.original, "student")}
|
||||
className="text-sm !py-2 !px-4"
|
||||
disabled={row.original.type === "student" || !PERMISSIONS.generateCode["student"].includes(user.type)}>
|
||||
disabled={
|
||||
row.original.type === "student" ||
|
||||
!PERMISSIONS.generateCode["student"].includes(user.type)
|
||||
}
|
||||
>
|
||||
Student
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => updateAccountType(row.original, "teacher")}
|
||||
className="text-sm !py-2 !px-4"
|
||||
disabled={row.original.type === "teacher" || !PERMISSIONS.generateCode["teacher"].includes(user.type)}>
|
||||
disabled={
|
||||
row.original.type === "teacher" ||
|
||||
!PERMISSIONS.generateCode["teacher"].includes(user.type)
|
||||
}
|
||||
>
|
||||
Teacher
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => updateAccountType(row.original, "corporate")}
|
||||
className="text-sm !py-2 !px-4"
|
||||
disabled={row.original.type === "corporate" || !PERMISSIONS.generateCode["corporate"].includes(user.type)}>
|
||||
disabled={
|
||||
row.original.type === "corporate" ||
|
||||
!PERMISSIONS.generateCode["corporate"].includes(user.type)
|
||||
}
|
||||
>
|
||||
Corporate
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => updateAccountType(row.original, "admin")}
|
||||
className="text-sm !py-2 !px-4"
|
||||
disabled={row.original.type === "admin" || !PERMISSIONS.generateCode["admin"].includes(user.type)}>
|
||||
disabled={
|
||||
row.original.type === "admin" ||
|
||||
!PERMISSIONS.generateCode["admin"].includes(user.type)
|
||||
}
|
||||
>
|
||||
Admin
|
||||
</Button>
|
||||
</div>
|
||||
@@ -214,16 +309,34 @@ export default function UserList({
|
||||
</Transition>
|
||||
</Popover>
|
||||
)}
|
||||
{!row.original.isVerified && PERMISSIONS.updateUser[row.original.type]?.includes(user.type) && (
|
||||
<div data-tip="Verify User" className="cursor-pointer tooltip" onClick={() => verifyAccount(row.original)}>
|
||||
{!row.original.isVerified &&
|
||||
checkAccess(
|
||||
user,
|
||||
updateUserPermission.list,
|
||||
updateUserPermission.perm
|
||||
) && (
|
||||
<div
|
||||
data-tip="Verify User"
|
||||
className="cursor-pointer tooltip"
|
||||
onClick={() => verifyAccount(row.original)}
|
||||
>
|
||||
<BsCheck className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||
</div>
|
||||
)}
|
||||
{PERMISSIONS.updateUser[row.original.type]?.includes(user.type) && (
|
||||
{checkAccess(
|
||||
user,
|
||||
updateUserPermission.list,
|
||||
updateUserPermission.perm
|
||||
) && (
|
||||
<div
|
||||
data-tip={row.original.status === "disabled" ? "Enable User" : "Disable User"}
|
||||
data-tip={
|
||||
row.original.status === "disabled"
|
||||
? "Enable User"
|
||||
: "Disable User"
|
||||
}
|
||||
className="cursor-pointer tooltip"
|
||||
onClick={() => toggleDisableAccount(row.original)}>
|
||||
onClick={() => toggleDisableAccount(row.original)}
|
||||
>
|
||||
{row.original.status === "disabled" ? (
|
||||
<BsCheckCircle className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||
) : (
|
||||
@@ -231,8 +344,16 @@ export default function UserList({
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{PERMISSIONS.deleteUser[row.original.type]?.includes(user.type) && (
|
||||
<div data-tip="Delete" className="cursor-pointer tooltip" onClick={() => deleteAccount(row.original)}>
|
||||
{checkAccess(
|
||||
user,
|
||||
deleteUserPermission.list,
|
||||
deleteUserPermission.perm
|
||||
) && (
|
||||
<div
|
||||
data-tip="Delete"
|
||||
className="cursor-pointer tooltip"
|
||||
onClick={() => deleteAccount(row.original)}
|
||||
>
|
||||
<BsTrash className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||
</div>
|
||||
)}
|
||||
@@ -243,7 +364,10 @@ export default function UserList({
|
||||
const demographicColumns = [
|
||||
columnHelper.accessor("name", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "name"))}>
|
||||
<button
|
||||
className="flex gap-2 items-center"
|
||||
onClick={() => setSorter((prev) => selectSorter(prev, "name"))}
|
||||
>
|
||||
<span>Name</span>
|
||||
<SorterArrow name="name" />
|
||||
</button>
|
||||
@@ -251,31 +375,49 @@ export default function UserList({
|
||||
cell: ({ row, getValue }) => (
|
||||
<div
|
||||
className={clsx(
|
||||
PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type) &&
|
||||
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer",
|
||||
PERMISSIONS.updateExpiryDate[row.original.type]?.includes(
|
||||
user.type
|
||||
) &&
|
||||
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer"
|
||||
)}
|
||||
onClick={() => (PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type) ? setSelectedUser(row.original) : null)}>
|
||||
onClick={() =>
|
||||
PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type)
|
||||
? setSelectedUser(row.original)
|
||||
: null
|
||||
}
|
||||
>
|
||||
{getValue()}
|
||||
</div>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("demographicInformation.country", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "country"))}>
|
||||
<button
|
||||
className="flex gap-2 items-center"
|
||||
onClick={() => setSorter((prev) => selectSorter(prev, "country"))}
|
||||
>
|
||||
<span>Country</span>
|
||||
<SorterArrow name="country" />
|
||||
</button>
|
||||
) as any,
|
||||
cell: (info) =>
|
||||
info.getValue()
|
||||
? `${countryCodes.findOne("countryCode" as any, info.getValue()).flag} ${
|
||||
? `${
|
||||
countryCodes.findOne("countryCode" as any, info.getValue()).flag
|
||||
} ${
|
||||
countries[info.getValue() as unknown as keyof TCountries].name
|
||||
} (+${countryCodes.findOne("countryCode" as any, info.getValue()).countryCallingCode})`
|
||||
} (+${
|
||||
countryCodes.findOne("countryCode" as any, info.getValue())
|
||||
.countryCallingCode
|
||||
})`
|
||||
: "Not available",
|
||||
}),
|
||||
columnHelper.accessor("demographicInformation.phone", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "phone"))}>
|
||||
<button
|
||||
className="flex gap-2 items-center"
|
||||
onClick={() => setSorter((prev) => selectSorter(prev, "phone"))}
|
||||
>
|
||||
<span>Phone</span>
|
||||
<SorterArrow name="phone" />
|
||||
</button>
|
||||
@@ -283,20 +425,37 @@ export default function UserList({
|
||||
cell: (info) => info.getValue() || "Not available",
|
||||
enableSorting: true,
|
||||
}),
|
||||
columnHelper.accessor((x) => (x.type === "corporate" ? x.demographicInformation?.position : x.demographicInformation?.employment), {
|
||||
columnHelper.accessor(
|
||||
(x) =>
|
||||
x.type === "corporate" || x.type === "mastercorporate"
|
||||
? x.demographicInformation?.position
|
||||
: x.demographicInformation?.employment,
|
||||
{
|
||||
id: "employment",
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "employment"))}>
|
||||
<button
|
||||
className="flex gap-2 items-center"
|
||||
onClick={() =>
|
||||
setSorter((prev) => selectSorter(prev, "employment"))
|
||||
}
|
||||
>
|
||||
<span>Employment/Position</span>
|
||||
<SorterArrow name="employment" />
|
||||
</button>
|
||||
) as any,
|
||||
cell: (info) => (info.row.original.type === "corporate" ? info.getValue() : capitalize(info.getValue())) || "Not available",
|
||||
cell: (info) =>
|
||||
(info.row.original.type === "corporate"
|
||||
? info.getValue()
|
||||
: capitalize(info.getValue())) || "Not available",
|
||||
enableSorting: true,
|
||||
}),
|
||||
}
|
||||
),
|
||||
columnHelper.accessor("demographicInformation.gender", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "gender"))}>
|
||||
<button
|
||||
className="flex gap-2 items-center"
|
||||
onClick={() => setSorter((prev) => selectSorter(prev, "gender"))}
|
||||
>
|
||||
<span>Gender</span>
|
||||
<SorterArrow name="gender" />
|
||||
</button>
|
||||
@@ -306,7 +465,10 @@ export default function UserList({
|
||||
}),
|
||||
{
|
||||
header: (
|
||||
<span className="cursor-pointer" onClick={() => setShowDemographicInformation((prev) => !prev)}>
|
||||
<span
|
||||
className="cursor-pointer"
|
||||
onClick={() => setShowDemographicInformation((prev) => !prev)}
|
||||
>
|
||||
Switch
|
||||
</span>
|
||||
),
|
||||
@@ -318,7 +480,10 @@ export default function UserList({
|
||||
const defaultColumns = [
|
||||
columnHelper.accessor("name", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "name"))}>
|
||||
<button
|
||||
className="flex gap-2 items-center"
|
||||
onClick={() => setSorter((prev) => selectSorter(prev, "name"))}
|
||||
>
|
||||
<span>Name</span>
|
||||
<SorterArrow name="name" />
|
||||
</button>
|
||||
@@ -326,17 +491,30 @@ export default function UserList({
|
||||
cell: ({ row, getValue }) => (
|
||||
<div
|
||||
className={clsx(
|
||||
PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type) &&
|
||||
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer",
|
||||
PERMISSIONS.updateExpiryDate[row.original.type]?.includes(
|
||||
user.type
|
||||
) &&
|
||||
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer"
|
||||
)}
|
||||
onClick={() => (PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type) ? setSelectedUser(row.original) : null)}>
|
||||
{row.original.type === "corporate" ? row.original.corporateInformation?.companyInformation?.name || getValue() : getValue()}
|
||||
onClick={() =>
|
||||
PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type)
|
||||
? setSelectedUser(row.original)
|
||||
: null
|
||||
}
|
||||
>
|
||||
{row.original.type === "corporate"
|
||||
? row.original.corporateInformation?.companyInformation?.name ||
|
||||
getValue()
|
||||
: getValue()}
|
||||
</div>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("email", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "email"))}>
|
||||
<button
|
||||
className="flex gap-2 items-center"
|
||||
onClick={() => setSorter((prev) => selectSorter(prev, "email"))}
|
||||
>
|
||||
<span>E-mail</span>
|
||||
<SorterArrow name="email" />
|
||||
</button>
|
||||
@@ -344,17 +522,27 @@ export default function UserList({
|
||||
cell: ({ row, getValue }) => (
|
||||
<div
|
||||
className={clsx(
|
||||
PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type) &&
|
||||
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer",
|
||||
PERMISSIONS.updateExpiryDate[row.original.type]?.includes(
|
||||
user.type
|
||||
) &&
|
||||
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer"
|
||||
)}
|
||||
onClick={() => (PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type) ? setSelectedUser(row.original) : null)}>
|
||||
onClick={() =>
|
||||
PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type)
|
||||
? setSelectedUser(row.original)
|
||||
: null
|
||||
}
|
||||
>
|
||||
{getValue()}
|
||||
</div>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("type", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "type"))}>
|
||||
<button
|
||||
className="flex gap-2 items-center"
|
||||
onClick={() => setSorter((prev) => selectSorter(prev, "type"))}
|
||||
>
|
||||
<span>Type</span>
|
||||
<SorterArrow name="type" />
|
||||
</button>
|
||||
@@ -363,29 +551,54 @@ export default function UserList({
|
||||
}),
|
||||
columnHelper.accessor("corporateInformation.companyInformation.name", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "companyName"))}>
|
||||
<button
|
||||
className="flex gap-2 items-center"
|
||||
onClick={() => setSorter((prev) => selectSorter(prev, "companyName"))}
|
||||
>
|
||||
<span>Company Name</span>
|
||||
<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={users}
|
||||
groups={groups}
|
||||
/>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("subscriptionExpirationDate", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "expiryDate"))}>
|
||||
<button
|
||||
className="flex gap-2 items-center"
|
||||
onClick={() => setSorter((prev) => selectSorter(prev, "expiryDate"))}
|
||||
>
|
||||
<span>Expiry Date</span>
|
||||
<SorterArrow name="expiryDate" />
|
||||
</button>
|
||||
) as any,
|
||||
cell: (info) => (
|
||||
<span className={clsx(info.getValue() ? expirationDateColor(moment(info.getValue()).toDate()) : "")}>
|
||||
{!info.getValue() ? "No expiry date" : moment(info.getValue()).format("DD/MM/YYYY")}
|
||||
<span
|
||||
className={clsx(
|
||||
info.getValue()
|
||||
? expirationDateColor(moment(info.getValue()).toDate())
|
||||
: ""
|
||||
)}
|
||||
>
|
||||
{!info.getValue()
|
||||
? "No expiry date"
|
||||
: moment(info.getValue()).format("DD/MM/YYYY")}
|
||||
</span>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("isVerified", {
|
||||
header: (
|
||||
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "verification"))}>
|
||||
<button
|
||||
className="flex gap-2 items-center"
|
||||
onClick={() =>
|
||||
setSorter((prev) => selectSorter(prev, "verification"))
|
||||
}
|
||||
>
|
||||
<span>Verification</span>
|
||||
<SorterArrow name="verification" />
|
||||
</button>
|
||||
@@ -396,8 +609,9 @@ export default function UserList({
|
||||
className={clsx(
|
||||
"w-6 h-6 rounded-md flex items-center justify-center border border-mti-purple-light bg-white",
|
||||
"transition duration-300 ease-in-out",
|
||||
info.getValue() && "!bg-mti-purple-light ",
|
||||
)}>
|
||||
info.getValue() && "!bg-mti-purple-light "
|
||||
)}
|
||||
>
|
||||
<BsCheck color="white" className="w-full h-full" />
|
||||
</div>
|
||||
</div>
|
||||
@@ -405,7 +619,10 @@ export default function UserList({
|
||||
}),
|
||||
{
|
||||
header: (
|
||||
<span className="cursor-pointer" onClick={() => setShowDemographicInformation((prev) => !prev)}>
|
||||
<span
|
||||
className="cursor-pointer"
|
||||
onClick={() => setShowDemographicInformation((prev) => !prev)}
|
||||
>
|
||||
Switch
|
||||
</span>
|
||||
),
|
||||
@@ -425,15 +642,21 @@ export default function UserList({
|
||||
|
||||
const sortFunction = async (a: User, b: User) => {
|
||||
if (sorter === "name" || sorter === reverseString("name"))
|
||||
return sorter === "name" ? a.name.localeCompare(b.name) : b.name.localeCompare(a.name);
|
||||
return sorter === "name"
|
||||
? a.name.localeCompare(b.name)
|
||||
: b.name.localeCompare(a.name);
|
||||
|
||||
if (sorter === "email" || sorter === reverseString("email"))
|
||||
return sorter === "email" ? a.email.localeCompare(b.email) : b.email.localeCompare(a.email);
|
||||
return sorter === "email"
|
||||
? a.email.localeCompare(b.email)
|
||||
: b.email.localeCompare(a.email);
|
||||
|
||||
if (sorter === "type" || sorter === reverseString("type"))
|
||||
return sorter === "type"
|
||||
? userTypes.findIndex((t) => a.type === t) - userTypes.findIndex((t) => b.type === t)
|
||||
: userTypes.findIndex((t) => b.type === t) - userTypes.findIndex((t) => a.type === t);
|
||||
? userTypes.findIndex((t) => a.type === t) -
|
||||
userTypes.findIndex((t) => b.type === t)
|
||||
: userTypes.findIndex((t) => b.type === t) -
|
||||
userTypes.findIndex((t) => a.type === t);
|
||||
|
||||
if (sorter === "verification" || sorter === reverseString("verification"))
|
||||
return sorter === "verification"
|
||||
@@ -441,73 +664,138 @@ export default function UserList({
|
||||
: b.isVerified.toString().localeCompare(a.isVerified.toString());
|
||||
|
||||
if (sorter === "expiryDate" || sorter === reverseString("expiryDate")) {
|
||||
if (!a.subscriptionExpirationDate && b.subscriptionExpirationDate) return sorter === "expiryDate" ? -1 : 1;
|
||||
if (a.subscriptionExpirationDate && !b.subscriptionExpirationDate) return sorter === "expiryDate" ? 1 : -1;
|
||||
if (!a.subscriptionExpirationDate && !b.subscriptionExpirationDate) return 0;
|
||||
if (moment(a.subscriptionExpirationDate).isAfter(b.subscriptionExpirationDate)) return sorter === "expiryDate" ? -1 : 1;
|
||||
if (moment(b.subscriptionExpirationDate).isAfter(a.subscriptionExpirationDate)) return sorter === "expiryDate" ? 1 : -1;
|
||||
if (!a.subscriptionExpirationDate && b.subscriptionExpirationDate)
|
||||
return sorter === "expiryDate" ? -1 : 1;
|
||||
if (a.subscriptionExpirationDate && !b.subscriptionExpirationDate)
|
||||
return sorter === "expiryDate" ? 1 : -1;
|
||||
if (!a.subscriptionExpirationDate && !b.subscriptionExpirationDate)
|
||||
return 0;
|
||||
if (
|
||||
moment(a.subscriptionExpirationDate).isAfter(
|
||||
b.subscriptionExpirationDate
|
||||
)
|
||||
)
|
||||
return sorter === "expiryDate" ? -1 : 1;
|
||||
if (
|
||||
moment(b.subscriptionExpirationDate).isAfter(
|
||||
a.subscriptionExpirationDate
|
||||
)
|
||||
)
|
||||
return sorter === "expiryDate" ? 1 : -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (sorter === "country" || sorter === reverseString("country")) {
|
||||
if (!a.demographicInformation?.country && b.demographicInformation?.country) return sorter === "country" ? -1 : 1;
|
||||
if (a.demographicInformation?.country && !b.demographicInformation?.country) return sorter === "country" ? 1 : -1;
|
||||
if (!a.demographicInformation?.country && !b.demographicInformation?.country) return 0;
|
||||
if (
|
||||
!a.demographicInformation?.country &&
|
||||
b.demographicInformation?.country
|
||||
)
|
||||
return sorter === "country" ? -1 : 1;
|
||||
if (
|
||||
a.demographicInformation?.country &&
|
||||
!b.demographicInformation?.country
|
||||
)
|
||||
return sorter === "country" ? 1 : -1;
|
||||
if (
|
||||
!a.demographicInformation?.country &&
|
||||
!b.demographicInformation?.country
|
||||
)
|
||||
return 0;
|
||||
|
||||
return sorter === "country"
|
||||
? a.demographicInformation!.country.localeCompare(b.demographicInformation!.country)
|
||||
: b.demographicInformation!.country.localeCompare(a.demographicInformation!.country);
|
||||
? a.demographicInformation!.country.localeCompare(
|
||||
b.demographicInformation!.country
|
||||
)
|
||||
: b.demographicInformation!.country.localeCompare(
|
||||
a.demographicInformation!.country
|
||||
);
|
||||
}
|
||||
|
||||
if (sorter === "phone" || sorter === reverseString("phone")) {
|
||||
if (!a.demographicInformation?.phone && b.demographicInformation?.phone) return sorter === "phone" ? -1 : 1;
|
||||
if (a.demographicInformation?.phone && !b.demographicInformation?.phone) return sorter === "phone" ? 1 : -1;
|
||||
if (!a.demographicInformation?.phone && !b.demographicInformation?.phone) return 0;
|
||||
if (!a.demographicInformation?.phone && b.demographicInformation?.phone)
|
||||
return sorter === "phone" ? -1 : 1;
|
||||
if (a.demographicInformation?.phone && !b.demographicInformation?.phone)
|
||||
return sorter === "phone" ? 1 : -1;
|
||||
if (!a.demographicInformation?.phone && !b.demographicInformation?.phone)
|
||||
return 0;
|
||||
|
||||
return sorter === "phone"
|
||||
? a.demographicInformation!.phone.localeCompare(b.demographicInformation!.phone)
|
||||
: b.demographicInformation!.phone.localeCompare(a.demographicInformation!.phone);
|
||||
? a.demographicInformation!.phone.localeCompare(
|
||||
b.demographicInformation!.phone
|
||||
)
|
||||
: b.demographicInformation!.phone.localeCompare(
|
||||
a.demographicInformation!.phone
|
||||
);
|
||||
}
|
||||
|
||||
if (sorter === "employment" || sorter === reverseString("employment")) {
|
||||
const aSortingItem = a.type === "corporate" ? a.demographicInformation?.position : a.demographicInformation?.employment;
|
||||
const bSortingItem = b.type === "corporate" ? b.demographicInformation?.position : b.demographicInformation?.employment;
|
||||
const aSortingItem =
|
||||
a.type === "corporate" || a.type === "mastercorporate"
|
||||
? a.demographicInformation?.position
|
||||
: a.demographicInformation?.employment;
|
||||
const bSortingItem =
|
||||
b.type === "corporate" || b.type === "mastercorporate"
|
||||
? b.demographicInformation?.position
|
||||
: b.demographicInformation?.employment;
|
||||
|
||||
if (!aSortingItem && bSortingItem) return sorter === "employment" ? -1 : 1;
|
||||
if (aSortingItem && !bSortingItem) return sorter === "employment" ? 1 : -1;
|
||||
if (!aSortingItem && bSortingItem)
|
||||
return sorter === "employment" ? -1 : 1;
|
||||
if (aSortingItem && !bSortingItem)
|
||||
return sorter === "employment" ? 1 : -1;
|
||||
if (!aSortingItem && !bSortingItem) return 0;
|
||||
|
||||
return sorter === "employment" ? aSortingItem!.localeCompare(bSortingItem!) : bSortingItem!.localeCompare(aSortingItem!);
|
||||
return sorter === "employment"
|
||||
? aSortingItem!.localeCompare(bSortingItem!)
|
||||
: bSortingItem!.localeCompare(aSortingItem!);
|
||||
}
|
||||
|
||||
if (sorter === "gender" || sorter === reverseString("gender")) {
|
||||
if (!a.demographicInformation?.gender && b.demographicInformation?.gender) return sorter === "employment" ? -1 : 1;
|
||||
if (a.demographicInformation?.gender && !b.demographicInformation?.gender) return sorter === "employment" ? 1 : -1;
|
||||
if (!a.demographicInformation?.gender && !b.demographicInformation?.gender) return 0;
|
||||
if (!a.demographicInformation?.gender && b.demographicInformation?.gender)
|
||||
return sorter === "employment" ? -1 : 1;
|
||||
if (a.demographicInformation?.gender && !b.demographicInformation?.gender)
|
||||
return sorter === "employment" ? 1 : -1;
|
||||
if (
|
||||
!a.demographicInformation?.gender &&
|
||||
!b.demographicInformation?.gender
|
||||
)
|
||||
return 0;
|
||||
|
||||
return sorter === "gender"
|
||||
? a.demographicInformation!.gender.localeCompare(b.demographicInformation!.gender)
|
||||
: b.demographicInformation!.gender.localeCompare(a.demographicInformation!.gender);
|
||||
? a.demographicInformation!.gender.localeCompare(
|
||||
b.demographicInformation!.gender
|
||||
)
|
||||
: b.demographicInformation!.gender.localeCompare(
|
||||
a.demographicInformation!.gender
|
||||
);
|
||||
}
|
||||
|
||||
if (sorter === "companyName" || sorter === reverseString("companyName")) {
|
||||
const aCorporateName = getUserCompanyName(a, users, groups);
|
||||
const bCorporateName = getUserCompanyName(b, users, groups);
|
||||
if (!aCorporateName && bCorporateName) return sorter === "companyName" ? -1 : 1;
|
||||
if (aCorporateName && !bCorporateName) return sorter === "companyName" ? 1 : -1;
|
||||
if (!aCorporateName && bCorporateName)
|
||||
return sorter === "companyName" ? -1 : 1;
|
||||
if (aCorporateName && !bCorporateName)
|
||||
return sorter === "companyName" ? 1 : -1;
|
||||
if (!aCorporateName && !bCorporateName) return 0;
|
||||
|
||||
return sorter === "companyName" ? aCorporateName.localeCompare(bCorporateName) : bCorporateName.localeCompare(aCorporateName);
|
||||
return sorter === "companyName"
|
||||
? aCorporateName.localeCompare(bCorporateName)
|
||||
: bCorporateName.localeCompare(aCorporateName);
|
||||
}
|
||||
|
||||
return a.id.localeCompare(b.id);
|
||||
};
|
||||
|
||||
const {rows: filteredRows, renderSearch} = useListSearch<User>(searchFields, displayUsers);
|
||||
const { rows: filteredRows, renderSearch } = useListSearch<User>(
|
||||
searchFields,
|
||||
displayUsers
|
||||
);
|
||||
|
||||
const table = useReactTable({
|
||||
data: filteredRows,
|
||||
columns: (!showDemographicInformation ? defaultColumns : demographicColumns) as any,
|
||||
columns: (!showDemographicInformation
|
||||
? defaultColumns
|
||||
: demographicColumns) as any,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
|
||||
@@ -528,13 +816,19 @@ export default function UserList({
|
||||
const belongsToAdminFilter = (x: User) => {
|
||||
if (!selectedUser) return false;
|
||||
return groups
|
||||
.filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id))
|
||||
.filter(
|
||||
(g) =>
|
||||
g.admin === selectedUser.id ||
|
||||
g.participants.includes(selectedUser.id)
|
||||
)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id);
|
||||
};
|
||||
|
||||
const viewStudentFilterBelongsToAdmin = (x: User) => x.type === "student" && belongsToAdminFilter(x);
|
||||
const viewTeacherFilterBelongsToAdmin = (x: User) => x.type === "teacher" && belongsToAdminFilter(x);
|
||||
const viewStudentFilterBelongsToAdmin = (x: User) =>
|
||||
x.type === "student" && belongsToAdminFilter(x);
|
||||
const viewTeacherFilterBelongsToAdmin = (x: User) =>
|
||||
x.type === "teacher" && belongsToAdminFilter(x);
|
||||
|
||||
const renderUserCard = (selectedUser: User) => {
|
||||
const studentsFromAdmin = users.filter(viewStudentFilterBelongsToAdmin);
|
||||
@@ -544,7 +838,9 @@ export default function UserList({
|
||||
<UserCard
|
||||
loggedInUser={user}
|
||||
onViewStudents={
|
||||
(selectedUser.type === "corporate" || selectedUser.type === "teacher") && studentsFromAdmin.length > 0
|
||||
(selectedUser.type === "corporate" ||
|
||||
selectedUser.type === "teacher") &&
|
||||
studentsFromAdmin.length > 0
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-students",
|
||||
@@ -560,7 +856,9 @@ export default function UserList({
|
||||
: undefined
|
||||
}
|
||||
onViewTeachers={
|
||||
(selectedUser.type === "corporate" || selectedUser.type === "student") && teachersFromAdmin.length > 0
|
||||
(selectedUser.type === "corporate" ||
|
||||
selectedUser.type === "student") &&
|
||||
teachersFromAdmin.length > 0
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-teachers",
|
||||
@@ -609,13 +907,20 @@ export default function UserList({
|
||||
<>
|
||||
{renderHeader && renderHeader(displayUsers.length)}
|
||||
<div className="w-full">
|
||||
<Modal isOpen={!!selectedUser} onClose={() => setSelectedUser(undefined)}>
|
||||
<Modal
|
||||
isOpen={!!selectedUser}
|
||||
onClose={() => setSelectedUser(undefined)}
|
||||
>
|
||||
{selectedUser && renderUserCard(selectedUser)}
|
||||
</Modal>
|
||||
<div className="w-full flex flex-col gap-2">
|
||||
<div className="w-full flex gap-2 items-end">
|
||||
{renderSearch()}
|
||||
<Button className="w-full max-w-[200px] mb-1" variant="outline" onClick={downloadExcel}>
|
||||
<Button
|
||||
className="w-full max-w-[200px] mb-1"
|
||||
variant="outline"
|
||||
onClick={downloadExcel}
|
||||
>
|
||||
Download List
|
||||
</Button>
|
||||
</div>
|
||||
@@ -625,7 +930,12 @@ export default function UserList({
|
||||
<tr key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => (
|
||||
<th className="py-4 px-4 text-left" key={header.id}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext()
|
||||
)}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
@@ -633,10 +943,16 @@ export default function UserList({
|
||||
</thead>
|
||||
<tbody className="px-2">
|
||||
{table.getRowModel().rows.map((row) => (
|
||||
<tr className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2" key={row.id}>
|
||||
<tr
|
||||
className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2"
|
||||
key={row.id}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<td className="px-4 py-2 items-center w-fit" key={cell.id}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
{flexRender(
|
||||
cell.column.columnDef.cell,
|
||||
cell.getContext()
|
||||
)}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
|
||||
@@ -30,12 +30,8 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "POST") await post(req, res);
|
||||
}
|
||||
|
||||
async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||
const { admin, participant } = req.query as {
|
||||
admin: string;
|
||||
participant: string;
|
||||
};
|
||||
|
||||
const getGroupsForUser = async (admin: string, participant: string) => {
|
||||
try {
|
||||
const queryConstraints = [
|
||||
...(admin ? [where("admin", "==", admin)] : []),
|
||||
...(participant
|
||||
@@ -45,14 +41,63 @@ async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||
const snapshot = await getDocs(
|
||||
queryConstraints.length > 0
|
||||
? query(collection(db, "groups"), ...queryConstraints)
|
||||
: collection(db, "groups"),
|
||||
: collection(db, "groups")
|
||||
);
|
||||
const groups = snapshot.docs.map((doc) => ({
|
||||
id: doc.id,
|
||||
...doc.data(),
|
||||
})) as Group[];
|
||||
|
||||
return groups;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||
const { admin, participant } = req.query as {
|
||||
admin: string;
|
||||
participant: string;
|
||||
};
|
||||
|
||||
if (req.session?.user?.type === "mastercorporate") {
|
||||
try {
|
||||
const masterCorporateGroups = await getGroupsForUser(admin, participant);
|
||||
const corporatesFromMaster = masterCorporateGroups
|
||||
.filter((g) => g.name === "Corporate")
|
||||
.flatMap((g) => g.participants);
|
||||
|
||||
if (corporatesFromMaster.length === 0) {
|
||||
res.status(200).json([]);
|
||||
return;
|
||||
}
|
||||
Promise.all(
|
||||
corporatesFromMaster.map((c) => getGroupsForUser(c, participant))
|
||||
)
|
||||
.then((groups) => {
|
||||
res.status(200).json([...masterCorporateGroups, ...groups.flat()]);
|
||||
return;
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
res.status(500).json({ ok: false });
|
||||
return;
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
res.status(500).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const groups = await getGroupsForUser(admin, participant);
|
||||
res.status(200).json(groups);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
res.status(500).json({ ok: false });
|
||||
}
|
||||
}
|
||||
|
||||
async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
@@ -60,8 +105,8 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
await Promise.all(
|
||||
body.participants.map(
|
||||
async (p) => await updateExpiryDateOnGroup(p, body.admin),
|
||||
),
|
||||
async (p) => await updateExpiryDateOnGroup(p, body.admin)
|
||||
)
|
||||
);
|
||||
|
||||
await setDoc(doc(db, "groups", v4()), {
|
||||
|
||||
30
src/pages/api/permissions/[id].ts
Normal file
30
src/pages/api/permissions/[id].ts
Normal file
@@ -0,0 +1,30 @@
|
||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { app } from "@/firebase";
|
||||
import { getFirestore, doc, setDoc } from "firebase/firestore";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
|
||||
const db = getFirestore(app);
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "PATCH") return patch(req, res);
|
||||
}
|
||||
|
||||
async function patch(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
const { id } = req.query as { id: string };
|
||||
const { users } = req.body;
|
||||
try {
|
||||
await setDoc(doc(db, "permissions", id), { users }, { merge: true });
|
||||
return res.status(200).json({ ok: true });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
return res.status(500).json({ ok: false });
|
||||
}
|
||||
}
|
||||
43
src/pages/api/permissions/bootstrap.ts
Normal file
43
src/pages/api/permissions/bootstrap.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { app } from "@/firebase";
|
||||
import {
|
||||
getFirestore,
|
||||
collection,
|
||||
getDocs,
|
||||
query,
|
||||
where,
|
||||
doc,
|
||||
setDoc,
|
||||
addDoc,
|
||||
getDoc,
|
||||
deleteDoc,
|
||||
} from "firebase/firestore";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { Permission } from "@/interfaces/permissions";
|
||||
import { bootstrap } from "@/utils/permissions.be";
|
||||
|
||||
const db = getFirestore(app);
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "GET") return get(req, res);
|
||||
}
|
||||
|
||||
async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("Boostrap");
|
||||
try {
|
||||
await bootstrap();
|
||||
return res.status(200).json({ ok: true });
|
||||
} catch (err) {
|
||||
console.error("Failed to update permissions", err);
|
||||
return res.status(500).json({ ok: false });
|
||||
}
|
||||
}
|
||||
36
src/pages/api/permissions/index.ts
Normal file
36
src/pages/api/permissions/index.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { app } from "@/firebase";
|
||||
import {
|
||||
getFirestore,
|
||||
collection,
|
||||
getDocs,
|
||||
query,
|
||||
where,
|
||||
doc,
|
||||
setDoc,
|
||||
addDoc,
|
||||
getDoc,
|
||||
deleteDoc,
|
||||
} from "firebase/firestore";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { Permission } from "@/interfaces/permissions";
|
||||
import { getPermissions, getPermissionDocs } from "@/utils/permissions.be";
|
||||
|
||||
const db = getFirestore(app);
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "GET") return get(req, res);
|
||||
}
|
||||
|
||||
async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
const docs = await getPermissionDocs();
|
||||
res.status(200).json(docs);
|
||||
}
|
||||
@@ -143,9 +143,18 @@ async function registerCorporate(req: NextApiRequest, res: NextApiResponse) {
|
||||
disableEditing: true,
|
||||
};
|
||||
|
||||
const defaultCorporateGroup: Group = {
|
||||
admin: userId,
|
||||
id: v4(),
|
||||
name: "Corporate",
|
||||
participants: [],
|
||||
disableEditing: true,
|
||||
};
|
||||
|
||||
await setDoc(doc(db, "users", userId), user);
|
||||
await setDoc(doc(db, "groups", defaultTeachersGroup.id), defaultTeachersGroup);
|
||||
await setDoc(doc(db, "groups", defaultStudentsGroup.id), defaultStudentsGroup);
|
||||
await setDoc(doc(db, "groups", defaultCorporateGroup.id), defaultCorporateGroup);
|
||||
|
||||
req.session.user = {...user, id: userId};
|
||||
await req.session.save();
|
||||
|
||||
@@ -2,10 +2,21 @@ import {PERMISSIONS} from "@/constants/userPermissions";
|
||||
import { app, adminApp } from "@/firebase";
|
||||
import { Group, User } from "@/interfaces/user";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import {collection, deleteDoc, doc, getDoc, getDocs, getFirestore, query, setDoc, where} from "firebase/firestore";
|
||||
import {
|
||||
collection,
|
||||
deleteDoc,
|
||||
doc,
|
||||
getDoc,
|
||||
getDocs,
|
||||
getFirestore,
|
||||
query,
|
||||
setDoc,
|
||||
where,
|
||||
} from "firebase/firestore";
|
||||
import { getAuth } from "firebase-admin/auth";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getPermissions, getPermissionDocs } from "@/utils/permissions.be";
|
||||
|
||||
const db = getFirestore(app);
|
||||
const auth = getAuth(adminApp);
|
||||
@@ -43,21 +54,40 @@ async function del(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
const targetUser = { ...docTargetUser.data(), id: docTargetUser.id } as User;
|
||||
|
||||
if (user.type === "corporate" && (targetUser.type === "student" || targetUser.type === "teacher")) {
|
||||
if (
|
||||
user.type === "corporate" &&
|
||||
(targetUser.type === "student" || targetUser.type === "teacher")
|
||||
) {
|
||||
res.json({ ok: true });
|
||||
|
||||
const userParticipantGroup = await getDocs(query(collection(db, "groups"), where("participants", "array-contains", id)));
|
||||
const userParticipantGroup = await getDocs(
|
||||
query(
|
||||
collection(db, "groups"),
|
||||
where("participants", "array-contains", id)
|
||||
)
|
||||
);
|
||||
await Promise.all([
|
||||
...userParticipantGroup.docs
|
||||
.filter((x) => (x.data() as Group).admin === user.id)
|
||||
.map(async (x) => await setDoc(x.ref, {participants: x.data().participants.filter((y: string) => y !== id)}, {merge: true})),
|
||||
.map(
|
||||
async (x) =>
|
||||
await setDoc(
|
||||
x.ref,
|
||||
{
|
||||
participants: x
|
||||
.data()
|
||||
.participants.filter((y: string) => y !== id),
|
||||
},
|
||||
{ merge: true }
|
||||
)
|
||||
),
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const permission = PERMISSIONS.deleteUser[targetUser.type];
|
||||
if (!permission.includes(user.type)) {
|
||||
if (!permission.list.includes(user.type)) {
|
||||
res.status(403).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
@@ -66,17 +96,32 @@ async function del(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
await auth.deleteUser(id);
|
||||
await deleteDoc(doc(db, "users", id));
|
||||
const userCodeDocs = await getDocs(query(collection(db, "codes"), where("userId", "==", id)));
|
||||
const userParticipantGroup = await getDocs(query(collection(db, "groups"), where("participants", "array-contains", id)));
|
||||
const userGroupAdminDocs = await getDocs(query(collection(db, "groups"), where("admin", "==", id)));
|
||||
const userStatsDocs = await getDocs(query(collection(db, "stats"), where("user", "==", id)));
|
||||
const userCodeDocs = await getDocs(
|
||||
query(collection(db, "codes"), where("userId", "==", id))
|
||||
);
|
||||
const userParticipantGroup = await getDocs(
|
||||
query(collection(db, "groups"), where("participants", "array-contains", id))
|
||||
);
|
||||
const userGroupAdminDocs = await getDocs(
|
||||
query(collection(db, "groups"), where("admin", "==", id))
|
||||
);
|
||||
const userStatsDocs = await getDocs(
|
||||
query(collection(db, "stats"), where("user", "==", id))
|
||||
);
|
||||
|
||||
await Promise.all([
|
||||
...userCodeDocs.docs.map(async (x) => await deleteDoc(x.ref)),
|
||||
...userGroupAdminDocs.docs.map(async (x) => await deleteDoc(x.ref)),
|
||||
...userStatsDocs.docs.map(async (x) => await deleteDoc(x.ref)),
|
||||
...userParticipantGroup.docs.map(
|
||||
async (x) => await setDoc(x.ref, {participants: x.data().participants.filter((y: string) => y !== id)}, {merge: true}),
|
||||
async (x) =>
|
||||
await setDoc(
|
||||
x.ref,
|
||||
{
|
||||
participants: x.data().participants.filter((y: string) => y !== id),
|
||||
},
|
||||
{ merge: true }
|
||||
)
|
||||
),
|
||||
]);
|
||||
}
|
||||
@@ -91,10 +136,19 @@ async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
const user = docUser.data() as User;
|
||||
|
||||
req.session.user = {...user, id: req.session.user.id};
|
||||
const permissionDocs = await getPermissionDocs();
|
||||
|
||||
const userWithPermissions = {
|
||||
...user,
|
||||
permissions: getPermissions(req.session.user.id, permissionDocs),
|
||||
};
|
||||
req.session.user = {
|
||||
...userWithPermissions,
|
||||
id: req.session.user.id,
|
||||
};
|
||||
await req.session.save();
|
||||
|
||||
res.json({...user, id: req.session.user.id});
|
||||
res.json({ ...userWithPermissions, id: req.session.user.id });
|
||||
} else {
|
||||
res.status(401).json(undefined);
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import ListeningGeneration from "./(generation)/ListeningGeneration";
|
||||
import WritingGeneration from "./(generation)/WritingGeneration";
|
||||
import LevelGeneration from "./(generation)/LevelGeneration";
|
||||
import SpeakingGeneration from "./(generation)/SpeakingGeneration";
|
||||
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(({ req, res }) => {
|
||||
const user = req.session.user;
|
||||
@@ -30,16 +31,19 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
permanent: false,
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (shouldRedirectHome(user) || user.type !== "developer") {
|
||||
if (
|
||||
shouldRedirectHome(user) ||
|
||||
checkAccess(user, getTypesOfUser(["developer"]))
|
||||
) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/",
|
||||
permanent: false,
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -69,11 +73,14 @@ export default function Generation() {
|
||||
<Layout user={user} className="gap-6">
|
||||
<h1 className="text-2xl font-semibold">Exam Generation</h1>
|
||||
<div className="flex flex-col gap-3">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Module</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Module
|
||||
</label>
|
||||
<RadioGroup
|
||||
value={module}
|
||||
onChange={setModule}
|
||||
className="flex flex-row -2xl:flex-wrap w-full gap-4 -md:justify-center justify-between">
|
||||
className="flex flex-row -2xl:flex-wrap w-full gap-4 -md:justify-center justify-between"
|
||||
>
|
||||
{[...MODULE_ARRAY].map((x) => (
|
||||
<RadioGroup.Option value={x} key={x}>
|
||||
{({ checked }) => (
|
||||
@@ -100,8 +107,9 @@ export default function Generation() {
|
||||
x === "level" &&
|
||||
(!checked
|
||||
? "bg-white border-mti-gray-platinum"
|
||||
: "bg-ielts-level/70 border-ielts-level text-white"),
|
||||
)}>
|
||||
: "bg-ielts-level/70 border-ielts-level text-white")
|
||||
)}
|
||||
>
|
||||
{capitalize(x)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import Head from "next/head";
|
||||
import Navbar from "@/components/Navbar";
|
||||
import {BsFileEarmarkText, BsPencil, BsStar, BsBook, BsHeadphones, BsPen, BsMegaphone} from "react-icons/bs";
|
||||
import {
|
||||
BsFileEarmarkText,
|
||||
BsPencil,
|
||||
BsStar,
|
||||
BsBook,
|
||||
BsHeadphones,
|
||||
BsPen,
|
||||
BsMegaphone,
|
||||
} from "react-icons/bs";
|
||||
import { withIronSessionSsr } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { useEffect, useState } from "react";
|
||||
import useStats from "@/hooks/useStats";
|
||||
import { averageScore, groupBySession, totalExams } from "@/utils/stats";
|
||||
import useUser from "@/hooks/useUser";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
import Diagnostic from "@/components/Diagnostic";
|
||||
import { ToastContainer } from "react-toastify";
|
||||
import { capitalize } from "lodash";
|
||||
@@ -27,12 +34,19 @@ import AdminDashboard from "@/dashboards/Admin";
|
||||
import CorporateDashboard from "@/dashboards/Corporate";
|
||||
import TeacherDashboard from "@/dashboards/Teacher";
|
||||
import AgentDashboard from "@/dashboards/Agent";
|
||||
import MasterCorporateDashboard from "@/dashboards/MasterCorporate";
|
||||
import PaymentDue from "./(status)/PaymentDue";
|
||||
import { useRouter } from "next/router";
|
||||
import { PayPalScriptProvider } from "@paypal/react-paypal-js";
|
||||
import {CorporateUser, Type, userTypes} from "@/interfaces/user";
|
||||
import {
|
||||
CorporateUser,
|
||||
MasterCorporateUser,
|
||||
Type,
|
||||
userTypes,
|
||||
} from "@/interfaces/user";
|
||||
import Select from "react-select";
|
||||
import { USER_TYPE_LABELS } from "@/resources/user";
|
||||
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(({ req, res }) => {
|
||||
const user = req.session.user;
|
||||
@@ -77,7 +91,7 @@ export default function Home(props: Props) {
|
||||
!user.demographicInformation ||
|
||||
!user.demographicInformation.country ||
|
||||
!user.demographicInformation.gender ||
|
||||
!user.demographicInformation.phone,
|
||||
!user.demographicInformation.phone
|
||||
);
|
||||
setShowDiagnostics(user.isFirstLogin && user.type === "student");
|
||||
}
|
||||
@@ -92,7 +106,12 @@ export default function Home(props: Props) {
|
||||
return true;
|
||||
};
|
||||
|
||||
if (user && (user.status === "paymentDue" || user.status === "disabled" || checkIfUserExpired())) {
|
||||
if (
|
||||
user &&
|
||||
(user.status === "paymentDue" ||
|
||||
user.status === "disabled" ||
|
||||
checkIfUserExpired())
|
||||
) {
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
@@ -107,12 +126,19 @@ export default function Home(props: Props) {
|
||||
{user.status === "disabled" && (
|
||||
<Layout user={user} navDisabled>
|
||||
<div className="flex flex-col items-center justify-center text-center w-full gap-4">
|
||||
<span className="font-bold text-lg">Your account has been disabled!</span>
|
||||
<span>Please contact an administrator if you believe this to be a mistake.</span>
|
||||
<span className="font-bold text-lg">
|
||||
Your account has been disabled!
|
||||
</span>
|
||||
<span>
|
||||
Please contact an administrator if you believe this to be a
|
||||
mistake.
|
||||
</span>
|
||||
</div>
|
||||
</Layout>
|
||||
)}
|
||||
{(user.status === "paymentDue" || checkIfUserExpired()) && <PaymentDue hasExpired user={user} reload={router.reload} />}
|
||||
{(user.status === "paymentDue" || checkIfUserExpired()) && (
|
||||
<PaymentDue hasExpired user={user} reload={router.reload} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -169,22 +195,44 @@ export default function Home(props: Props) {
|
||||
<ToastContainer />
|
||||
{user && (
|
||||
<Layout user={user}>
|
||||
{user.type === "student" && <StudentDashboard user={user} />}
|
||||
{user.type === "teacher" && <TeacherDashboard user={user} />}
|
||||
{user.type === "corporate" && <CorporateDashboard user={user} />}
|
||||
{user.type === "agent" && <AgentDashboard user={user} />}
|
||||
{user.type === "admin" && <AdminDashboard user={user} />}
|
||||
{user.type === "developer" && (
|
||||
{checkAccess(user, ["student"]) && <StudentDashboard user={user} />}
|
||||
{checkAccess(user, ["teacher"]) && <TeacherDashboard user={user} />}
|
||||
{checkAccess(user, ["corporate"]) && (
|
||||
<CorporateDashboard user={user as CorporateUser} />
|
||||
)}
|
||||
{checkAccess(user, ["mastercorporate"]) && (
|
||||
<MasterCorporateDashboard user={user as MasterCorporateUser} />
|
||||
)}
|
||||
{checkAccess(user, ["agent"]) && <AgentDashboard user={user} />}
|
||||
{checkAccess(user, ["admin"]) && <AdminDashboard user={user} />}
|
||||
{checkAccess(user, ["developer"]) && (
|
||||
<>
|
||||
<Select
|
||||
options={userTypes.map((u) => ({value: u, label: USER_TYPE_LABELS[u]}))}
|
||||
value={{value: selectedScreen, label: USER_TYPE_LABELS[selectedScreen]}}
|
||||
onChange={(value) => (value ? setSelectedScreen(value.value) : setSelectedScreen("admin"))}
|
||||
options={userTypes.map((u) => ({
|
||||
value: u,
|
||||
label: USER_TYPE_LABELS[u],
|
||||
}))}
|
||||
value={{
|
||||
value: selectedScreen,
|
||||
label: USER_TYPE_LABELS[selectedScreen],
|
||||
}}
|
||||
onChange={(value) =>
|
||||
value
|
||||
? setSelectedScreen(value.value)
|
||||
: setSelectedScreen("admin")
|
||||
}
|
||||
/>
|
||||
|
||||
{selectedScreen === "student" && <StudentDashboard user={user} />}
|
||||
{selectedScreen === "teacher" && <TeacherDashboard user={user} />}
|
||||
{selectedScreen === "corporate" && <CorporateDashboard user={user as unknown as CorporateUser} />}
|
||||
{selectedScreen === "corporate" && (
|
||||
<CorporateDashboard user={user as unknown as CorporateUser} />
|
||||
)}
|
||||
{selectedScreen === "mastercorporate" && (
|
||||
<MasterCorporateDashboard
|
||||
user={user as unknown as MasterCorporateUser}
|
||||
/>
|
||||
)}
|
||||
{selectedScreen === "agent" && <AgentDashboard user={user} />}
|
||||
{selectedScreen === "admin" && <AdminDashboard user={user} />}
|
||||
</>
|
||||
|
||||
@@ -9,7 +9,15 @@ import {shouldRedirectHome} from "@/utils/navigation.disabled";
|
||||
import usePayments from "@/hooks/usePayments";
|
||||
import usePaypalPayments from "@/hooks/usePaypalPayments";
|
||||
import { Payment, PaypalPayment } from "@/interfaces/paypal";
|
||||
import {CellContext, createColumnHelper, flexRender, getCoreRowModel, HeaderGroup, Table, useReactTable} from "@tanstack/react-table";
|
||||
import {
|
||||
CellContext,
|
||||
createColumnHelper,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
HeaderGroup,
|
||||
Table,
|
||||
useReactTable,
|
||||
} from "@tanstack/react-table";
|
||||
import { CURRENCIES } from "@/resources/paypal";
|
||||
import { BsTrash } from "react-icons/bs";
|
||||
import axios from "axios";
|
||||
@@ -30,6 +38,8 @@ import {toFixedNumber} from "@/utils/number";
|
||||
import { CSVLink } from "react-csv";
|
||||
import { Tab } from "@headlessui/react";
|
||||
import { useListSearch } from "@/hooks/useListSearch";
|
||||
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(({ req, res }) => {
|
||||
const user = req.session.user;
|
||||
|
||||
@@ -42,7 +52,19 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
};
|
||||
}
|
||||
|
||||
if (shouldRedirectHome(user) || !["admin", "developer", "agent", "corporate"].includes(user.type)) {
|
||||
if (
|
||||
shouldRedirectHome(user) ||
|
||||
checkAccess(
|
||||
user,
|
||||
getTypesOfUser([
|
||||
"admin",
|
||||
"developer",
|
||||
"agent",
|
||||
"corporate",
|
||||
"mastercorporate",
|
||||
])
|
||||
)
|
||||
) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/",
|
||||
@@ -59,7 +81,15 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
const columnHelper = createColumnHelper<Payment>();
|
||||
const paypalColumnHelper = createColumnHelper<PaypalPaymentWithUserData>();
|
||||
|
||||
const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () => void; reload: () => void; showComission: boolean}) => {
|
||||
const PaymentCreator = ({
|
||||
onClose,
|
||||
reload,
|
||||
showComission = false,
|
||||
}: {
|
||||
onClose: () => void;
|
||||
reload: () => void;
|
||||
showComission: boolean;
|
||||
}) => {
|
||||
const [corporate, setCorporate] = useState<CorporateUser>();
|
||||
const [date, setDate] = useState<Date>(new Date());
|
||||
|
||||
@@ -71,7 +101,9 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
||||
|
||||
const referralAgent = useMemo(() => {
|
||||
if (corporate?.corporateInformation?.referralAgent) {
|
||||
return users.find((u) => u.id === corporate.corporateInformation.referralAgent);
|
||||
return users.find(
|
||||
(u) => u.id === corporate.corporateInformation.referralAgent
|
||||
);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
@@ -104,16 +136,24 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
||||
<h1 className="text-2xl font-semibold">New Payment</h1>
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-3">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Corporate account *</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Corporate account *
|
||||
</label>
|
||||
<Select
|
||||
className="px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed bg-white rounded-full border border-mti-gray-platinum focus:outline-none"
|
||||
options={(users.filter((u) => u.type === "corporate") as CorporateUser[]).map((user) => ({
|
||||
options={(
|
||||
users.filter((u) => u.type === "corporate") as CorporateUser[]
|
||||
).map((user) => ({
|
||||
value: user.id,
|
||||
meta: user,
|
||||
label: `${user.corporateInformation?.companyInformation?.name || user.name} - ${user.email}`,
|
||||
label: `${
|
||||
user.corporateInformation?.companyInformation?.name || user.name
|
||||
} - ${user.email}`,
|
||||
}))}
|
||||
defaultValue={{ value: "undefined", label: "Select an account" }}
|
||||
onChange={(value) => setCorporate((value as any)?.meta ?? undefined)}
|
||||
onChange={(value) =>
|
||||
setCorporate((value as any)?.meta ?? undefined)
|
||||
}
|
||||
menuPortalTarget={document?.body}
|
||||
styles={{
|
||||
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||
@@ -128,7 +168,11 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
||||
}),
|
||||
option: (styles, state) => ({
|
||||
...styles,
|
||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
||||
backgroundColor: state.isFocused
|
||||
? "#D5D9F0"
|
||||
: state.isSelected
|
||||
? "#7872BF"
|
||||
: "white",
|
||||
color: state.isFocused ? "black" : styles.color,
|
||||
}),
|
||||
}}
|
||||
@@ -136,9 +180,19 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Price *</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Price *
|
||||
</label>
|
||||
<div className="w-full grid grid-cols-5 gap-2">
|
||||
<Input name="paymentValue" onChange={() => {}} type="number" value={price} defaultValue={0} className="col-span-3" disabled />
|
||||
<Input
|
||||
name="paymentValue"
|
||||
onChange={() => {}}
|
||||
type="number"
|
||||
value={price}
|
||||
defaultValue={0}
|
||||
className="col-span-3"
|
||||
disabled
|
||||
/>
|
||||
<Select
|
||||
className="px-4 col-span-2 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool bg-mti-gray-platinum/40 text-mti-gray-dim cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none"
|
||||
options={CURRENCIES.map(({ label, currency }) => ({
|
||||
@@ -147,12 +201,16 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
||||
}))}
|
||||
defaultValue={{
|
||||
value: currency || "EUR",
|
||||
label: CURRENCIES.find((c) => c.currency === currency)?.label || "Euro",
|
||||
label:
|
||||
CURRENCIES.find((c) => c.currency === currency)?.label ||
|
||||
"Euro",
|
||||
}}
|
||||
onChange={() => {}}
|
||||
value={{
|
||||
value: currency || "EUR",
|
||||
label: CURRENCIES.find((c) => c.currency === currency)?.label || "Euro",
|
||||
label:
|
||||
CURRENCIES.find((c) => c.currency === currency)?.label ||
|
||||
"Euro",
|
||||
}}
|
||||
menuPortalTarget={document?.body}
|
||||
styles={{
|
||||
@@ -168,7 +226,11 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
||||
}),
|
||||
option: (styles, state) => ({
|
||||
...styles,
|
||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
||||
backgroundColor: state.isFocused
|
||||
? "#D5D9F0"
|
||||
: state.isSelected
|
||||
? "#7872BF"
|
||||
: "white",
|
||||
color: state.isFocused ? "black" : styles.color,
|
||||
}),
|
||||
}}
|
||||
@@ -179,14 +241,27 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
||||
{showComission && (
|
||||
<div className="flex gap-4 w-full">
|
||||
<div className="flex flex-col w-full gap-3">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Commission *</label>
|
||||
<Input name="commission" onChange={() => {}} type="number" defaultValue={0} value={commission} disabled />
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Commission *
|
||||
</label>
|
||||
<Input
|
||||
name="commission"
|
||||
onChange={() => {}}
|
||||
type="number"
|
||||
defaultValue={0}
|
||||
value={commission}
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col w-full gap-3">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Commission Value*</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Commission Value*
|
||||
</label>
|
||||
<Input
|
||||
name="commissionValue"
|
||||
value={`${(commission! / 100) * price!} ${CURRENCIES.find((c) => c.currency === currency)?.label}`}
|
||||
value={`${(commission! / 100) * price!} ${
|
||||
CURRENCIES.find((c) => c.currency === currency)?.label
|
||||
}`}
|
||||
onChange={() => null}
|
||||
type="text"
|
||||
defaultValue={0}
|
||||
@@ -198,12 +273,14 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
||||
|
||||
<div className="flex gap-4">
|
||||
<div className="flex flex-col w-full gap-3">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Date *</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Date *
|
||||
</label>
|
||||
<ReactDatePicker
|
||||
className={clsx(
|
||||
"p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
|
||||
"hover:border-mti-purple tooltip",
|
||||
"transition duration-300 ease-in-out",
|
||||
"transition duration-300 ease-in-out"
|
||||
)}
|
||||
dateFormat="dd/MM/yyyy"
|
||||
selected={moment(date).toDate()}
|
||||
@@ -212,10 +289,16 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col w-full gap-3">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Country Manager *</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Country Manager *
|
||||
</label>
|
||||
<Input
|
||||
name="referralAgent"
|
||||
value={referralAgent ? `${referralAgent.name} - ${referralAgent.email}` : "No country manager"}
|
||||
value={
|
||||
referralAgent
|
||||
? `${referralAgent.name} - ${referralAgent.email}`
|
||||
: "No country manager"
|
||||
}
|
||||
onChange={() => null}
|
||||
type="text"
|
||||
defaultValue={"No country manager"}
|
||||
@@ -224,10 +307,19 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex w-full justify-end items-center gap-8 mt-4">
|
||||
<Button variant="outline" color="red" className="w-full max-w-[200px]" onClick={onClose}>
|
||||
<Button
|
||||
variant="outline"
|
||||
color="red"
|
||||
className="w-full max-w-[200px]"
|
||||
onClick={onClose}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button className="w-full max-w-[200px]" onClick={submit} disabled={!corporate || !price}>
|
||||
<Button
|
||||
className="w-full max-w-[200px]"
|
||||
onClick={submit}
|
||||
disabled={!corporate || !price}
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
</div>
|
||||
@@ -266,9 +358,26 @@ const IS_FILE_SUBMITTED_OPTIONS = [
|
||||
},
|
||||
];
|
||||
|
||||
const CSV_PAYMENTS_WHITELISTED_KEYS = ["corporateId", "corporate", "date", "amount", "agent", "agentCommission", "agentValue", "isPaid"];
|
||||
const CSV_PAYMENTS_WHITELISTED_KEYS = [
|
||||
"corporateId",
|
||||
"corporate",
|
||||
"date",
|
||||
"amount",
|
||||
"agent",
|
||||
"agentCommission",
|
||||
"agentValue",
|
||||
"isPaid",
|
||||
];
|
||||
|
||||
const CSV_PAYPAL_WHITELISTED_KEYS = ["orderId", "status", "name", "email", "value", "createdAt", "subscriptionExpirationDate"];
|
||||
const CSV_PAYPAL_WHITELISTED_KEYS = [
|
||||
"orderId",
|
||||
"status",
|
||||
"name",
|
||||
"email",
|
||||
"value",
|
||||
"createdAt",
|
||||
"subscriptionExpirationDate",
|
||||
];
|
||||
|
||||
interface SimpleCSVColumn {
|
||||
key: string;
|
||||
@@ -286,7 +395,9 @@ export default function PaymentRecord() {
|
||||
const [selectedCorporateUser, setSelectedCorporateUser] = useState<User>();
|
||||
const [selectedAgentUser, setSelectedAgentUser] = useState<User>();
|
||||
const [isCreatingPayment, setIsCreatingPayment] = useState(false);
|
||||
const [filters, setFilters] = useState<{filter: (p: Payment) => boolean; id: string}[]>([]);
|
||||
const [filters, setFilters] = useState<
|
||||
{ filter: (p: Payment) => boolean; id: string }[]
|
||||
>([]);
|
||||
const [displayPayments, setDisplayPayments] = useState<Payment[]>([]);
|
||||
|
||||
const [corporate, setCorporate] = useState<User>();
|
||||
@@ -295,12 +406,21 @@ export default function PaymentRecord() {
|
||||
const { user } = useUser({ redirectTo: "/login" });
|
||||
const { users, reload: reloadUsers } = useUsers();
|
||||
const { payments: originalPayments, reload: reloadPayment } = usePayments();
|
||||
const {payments: paypalPayments, reload: reloadPaypalPayment} = usePaypalPayments();
|
||||
const [startDate, setStartDate] = useState<Date | null>(moment("01/01/2023").toDate());
|
||||
const [endDate, setEndDate] = useState<Date | null>(moment().endOf("day").toDate());
|
||||
const { payments: paypalPayments, reload: reloadPaypalPayment } =
|
||||
usePaypalPayments();
|
||||
const [startDate, setStartDate] = useState<Date | null>(
|
||||
moment("01/01/2023").toDate()
|
||||
);
|
||||
const [endDate, setEndDate] = useState<Date | null>(
|
||||
moment().endOf("day").toDate()
|
||||
);
|
||||
const [paid, setPaid] = useState<Boolean | null>(IS_PAID_OPTIONS[0].value);
|
||||
const [commissionTransfer, setCommissionTransfer] = useState<Boolean | null>(IS_FILE_SUBMITTED_OPTIONS[0].value);
|
||||
const [corporateTransfer, setCorporateTransfer] = useState<Boolean | null>(IS_FILE_SUBMITTED_OPTIONS[0].value);
|
||||
const [commissionTransfer, setCommissionTransfer] = useState<Boolean | null>(
|
||||
IS_FILE_SUBMITTED_OPTIONS[0].value
|
||||
);
|
||||
const [corporateTransfer, setCorporateTransfer] = useState<Boolean | null>(
|
||||
IS_FILE_SUBMITTED_OPTIONS[0].value
|
||||
);
|
||||
const reload = () => {
|
||||
reloadUsers();
|
||||
reloadPayment();
|
||||
@@ -320,7 +440,7 @@ export default function PaymentRecord() {
|
||||
filters
|
||||
.map((f) => f.filter)
|
||||
.reduce((d, f) => d.filter(f), payments)
|
||||
.sort((a, b) => moment(b.date).diff(moment(a.date))),
|
||||
.sort((a, b) => moment(b.date).diff(moment(a.date)))
|
||||
);
|
||||
}, [payments, filters]);
|
||||
|
||||
@@ -361,7 +481,9 @@ export default function PaymentRecord() {
|
||||
useEffect(() => {
|
||||
setFilters((prev) => [
|
||||
...prev.filter((x) => x.id !== "paid"),
|
||||
...(typeof paid !== "boolean" ? [] : [{id: "paid", filter: (p: Payment) => p.isPaid === paid}]),
|
||||
...(typeof paid !== "boolean"
|
||||
? []
|
||||
: [{ id: "paid", filter: (p: Payment) => p.isPaid === paid }]),
|
||||
]);
|
||||
}, [paid]);
|
||||
|
||||
@@ -373,7 +495,8 @@ export default function PaymentRecord() {
|
||||
: [
|
||||
{
|
||||
id: "commissionTransfer",
|
||||
filter: (p: Payment) => !p.commissionTransfer === commissionTransfer,
|
||||
filter: (p: Payment) =>
|
||||
!p.commissionTransfer === commissionTransfer,
|
||||
},
|
||||
]),
|
||||
]);
|
||||
@@ -387,7 +510,8 @@ export default function PaymentRecord() {
|
||||
: [
|
||||
{
|
||||
id: "corporateTransfer",
|
||||
filter: (p: Payment) => !p.corporateTransfer === corporateTransfer,
|
||||
filter: (p: Payment) =>
|
||||
!p.corporateTransfer === corporateTransfer,
|
||||
},
|
||||
]),
|
||||
]);
|
||||
@@ -418,7 +542,9 @@ export default function PaymentRecord() {
|
||||
}
|
||||
|
||||
if (reason.response.status === 403) {
|
||||
toast.error("You do not have permission to delete an approved payment record!");
|
||||
toast.error(
|
||||
"You do not have permission to delete an approved payment record!"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -429,7 +555,8 @@ export default function PaymentRecord() {
|
||||
|
||||
const getFileAssetsColumns = () => {
|
||||
if (user) {
|
||||
const containerClassName = "flex gap-2 text-mti-purple-light hover:text-mti-purple-dark ease-in-out duration-300 cursor-pointer";
|
||||
const containerClassName =
|
||||
"flex gap-2 text-mti-purple-light hover:text-mti-purple-dark ease-in-out duration-300 cursor-pointer";
|
||||
switch (user.type) {
|
||||
case "corporate":
|
||||
return [
|
||||
@@ -548,7 +675,9 @@ export default function PaymentRecord() {
|
||||
return { value: `${value}%` };
|
||||
}
|
||||
case "agent": {
|
||||
const user = users.find((x) => x.id === info.row.original.agent) as AgentUser;
|
||||
const user = users.find(
|
||||
(x) => x.id === info.row.original.agent
|
||||
) as AgentUser;
|
||||
return {
|
||||
value: user?.name,
|
||||
user,
|
||||
@@ -569,7 +698,8 @@ export default function PaymentRecord() {
|
||||
const user = users.find((x) => x.id === specificValue) as CorporateUser;
|
||||
return {
|
||||
user,
|
||||
value: user?.corporateInformation.companyInformation.name || user?.name,
|
||||
value:
|
||||
user?.corporateInformation.companyInformation.name || user?.name,
|
||||
};
|
||||
}
|
||||
case "currency": {
|
||||
@@ -597,9 +727,10 @@ export default function PaymentRecord() {
|
||||
return (
|
||||
<div
|
||||
className={clsx(
|
||||
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer",
|
||||
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer"
|
||||
)}
|
||||
onClick={() => setSelectedAgentUser(user)}>
|
||||
onClick={() => setSelectedAgentUser(user)}
|
||||
>
|
||||
{value}
|
||||
</div>
|
||||
);
|
||||
@@ -643,9 +774,10 @@ export default function PaymentRecord() {
|
||||
return (
|
||||
<div
|
||||
className={clsx(
|
||||
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer",
|
||||
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer"
|
||||
)}
|
||||
onClick={() => setSelectedCorporateUser(user)}>
|
||||
onClick={() => setSelectedCorporateUser(user)}
|
||||
>
|
||||
{value}
|
||||
</div>
|
||||
);
|
||||
@@ -664,7 +796,9 @@ export default function PaymentRecord() {
|
||||
id: "amount",
|
||||
cell: (info) => {
|
||||
const { value } = columHelperValue(info.column.id, info);
|
||||
const currency = CURRENCIES.find((x) => x.currency === info.row.original.currency)?.label;
|
||||
const currency = CURRENCIES.find(
|
||||
(x) => x.currency === info.row.original.currency
|
||||
)?.label;
|
||||
const finalValue = `${value} ${currency}`;
|
||||
return <span>{finalValue}</span>;
|
||||
},
|
||||
@@ -680,13 +814,23 @@ export default function PaymentRecord() {
|
||||
<Checkbox
|
||||
isChecked={value}
|
||||
onChange={(e) => {
|
||||
if (user?.type === agent || user?.type === "corporate" || value) return null;
|
||||
if (!info.row.original.commissionTransfer || !info.row.original.corporateTransfer)
|
||||
return alert("All files need to be uploaded to consider it paid!");
|
||||
if (!confirm(`Are you sure you want to consider this payment paid?`)) return null;
|
||||
if (user?.type === agent || user?.type === "corporate" || value)
|
||||
return null;
|
||||
if (
|
||||
!info.row.original.commissionTransfer ||
|
||||
!info.row.original.corporateTransfer
|
||||
)
|
||||
return alert(
|
||||
"All files need to be uploaded to consider it paid!"
|
||||
);
|
||||
if (
|
||||
!confirm(`Are you sure you want to consider this payment paid?`)
|
||||
)
|
||||
return null;
|
||||
|
||||
return updatePayment(info.row.original, "isPaid", e);
|
||||
}}>
|
||||
}}
|
||||
>
|
||||
<span></span>
|
||||
</Checkbox>
|
||||
);
|
||||
@@ -700,7 +844,11 @@ export default function PaymentRecord() {
|
||||
return (
|
||||
<div className="flex gap-4">
|
||||
{user?.type !== "agent" && (
|
||||
<div data-tip="Delete" className="cursor-pointer tooltip" onClick={() => deletePayment(row.original.id)}>
|
||||
<div
|
||||
data-tip="Delete"
|
||||
className="cursor-pointer tooltip"
|
||||
onClick={() => deletePayment(row.original.id)}
|
||||
>
|
||||
<BsTrash className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||
</div>
|
||||
)}
|
||||
@@ -722,7 +870,7 @@ export default function PaymentRecord() {
|
||||
const user = users.find((x) => x.id === p.userId) as User;
|
||||
return { ...p, name: user?.name, email: user?.email };
|
||||
}),
|
||||
[paypalPayments, users],
|
||||
[paypalPayments, users]
|
||||
);
|
||||
|
||||
const paypalColumns = [
|
||||
@@ -785,10 +933,15 @@ export default function PaymentRecord() {
|
||||
}),
|
||||
];
|
||||
|
||||
const {rows: filteredRows, renderSearch} = useListSearch(paypalFilterRows, updatedPaypalPayments);
|
||||
const { rows: filteredRows, renderSearch } = useListSearch(
|
||||
paypalFilterRows,
|
||||
updatedPaypalPayments
|
||||
);
|
||||
|
||||
const paypalTable = useReactTable({
|
||||
data: filteredRows.sort((a, b) => moment(b.createdAt).diff(moment(a.createdAt), "second")),
|
||||
data: filteredRows.sort((a, b) =>
|
||||
moment(b.createdAt).diff(moment(a.createdAt), "second")
|
||||
),
|
||||
columns: paypalColumns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
@@ -797,7 +950,10 @@ export default function PaymentRecord() {
|
||||
if (user) {
|
||||
if (selectedCorporateUser) {
|
||||
return (
|
||||
<Modal isOpen={!!selectedCorporateUser} onClose={() => setSelectedCorporateUser(undefined)}>
|
||||
<Modal
|
||||
isOpen={!!selectedCorporateUser}
|
||||
onClose={() => setSelectedCorporateUser(undefined)}
|
||||
>
|
||||
<>
|
||||
{selectedCorporateUser && (
|
||||
<div className="w-full flex flex-col gap-8">
|
||||
@@ -820,7 +976,10 @@ export default function PaymentRecord() {
|
||||
|
||||
if (selectedAgentUser) {
|
||||
return (
|
||||
<Modal isOpen={!!selectedAgentUser} onClose={() => setSelectedAgentUser(undefined)}>
|
||||
<Modal
|
||||
isOpen={!!selectedAgentUser}
|
||||
onClose={() => setSelectedAgentUser(undefined)}
|
||||
>
|
||||
<>
|
||||
{selectedAgentUser && (
|
||||
<div className="w-full flex flex-col gap-8">
|
||||
@@ -845,11 +1004,17 @@ export default function PaymentRecord() {
|
||||
|
||||
const getCSVData = () => {
|
||||
const tables = [table, paypalTable];
|
||||
const whitelists = [CSV_PAYMENTS_WHITELISTED_KEYS, CSV_PAYPAL_WHITELISTED_KEYS];
|
||||
const whitelists = [
|
||||
CSV_PAYMENTS_WHITELISTED_KEYS,
|
||||
CSV_PAYPAL_WHITELISTED_KEYS,
|
||||
];
|
||||
const currentTable = tables[selectedIndex];
|
||||
const whitelist = whitelists[selectedIndex];
|
||||
const columns = (currentTable.getHeaderGroups() as any[]).reduce((accm: any[], group: any) => {
|
||||
const whitelistedColumns = group.headers.filter((header: any) => whitelist.includes(header.id));
|
||||
const columns = (currentTable.getHeaderGroups() as any[]).reduce(
|
||||
(accm: any[], group: any) => {
|
||||
const whitelistedColumns = group.headers.filter((header: any) =>
|
||||
whitelist.includes(header.id)
|
||||
);
|
||||
|
||||
const data = whitelistedColumns.map((data: any) => ({
|
||||
key: data.column.columnDef.id,
|
||||
@@ -857,7 +1022,9 @@ export default function PaymentRecord() {
|
||||
})) as SimpleCSVColumn[];
|
||||
|
||||
return [...accm, ...data];
|
||||
}, []);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const { rows } = currentTable.getRowModel();
|
||||
|
||||
@@ -895,7 +1062,12 @@ export default function PaymentRecord() {
|
||||
<tr key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => (
|
||||
<th className="p-4 text-left" key={header.id}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext()
|
||||
)}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
@@ -903,7 +1075,10 @@ export default function PaymentRecord() {
|
||||
</thead>
|
||||
<tbody className="px-2">
|
||||
{table.getRowModel().rows.map((row) => (
|
||||
<tr className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2" key={row.id}>
|
||||
<tr
|
||||
className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2"
|
||||
key={row.id}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<td className="px-4 py-2" key={cell.id}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
@@ -930,26 +1105,43 @@ export default function PaymentRecord() {
|
||||
{user && (
|
||||
<Layout user={user} className="gap-6">
|
||||
{getUserModal()}
|
||||
<Modal isOpen={isCreatingPayment} onClose={() => setIsCreatingPayment(false)}>
|
||||
<Modal
|
||||
isOpen={isCreatingPayment}
|
||||
onClose={() => setIsCreatingPayment(false)}
|
||||
>
|
||||
<PaymentCreator
|
||||
onClose={() => setIsCreatingPayment(false)}
|
||||
reload={reload}
|
||||
showComission={user.type === "developer" || user.type === "admin"}
|
||||
showComission={checkAccess(user, ["developer", "admin"])}
|
||||
/>
|
||||
</Modal>
|
||||
|
||||
<div className="w-full flex flex-end justify-between p-2">
|
||||
<h1 className="text-2xl font-semibold">Payment Record</h1>
|
||||
<div className="flex justify-end gap-2">
|
||||
{(user.type === "developer" || user.type === "admin" || user.type === "agent" || user.type === "corporate") && (
|
||||
{checkAccess(user, [
|
||||
"developer",
|
||||
"admin",
|
||||
"agent",
|
||||
"corporate",
|
||||
"mastercorporate",
|
||||
]) && (
|
||||
<Button className="max-w-[200px]" variant="outline">
|
||||
<CSVLink data={csvRows} headers={csvColumns} filename="payment-records.csv">
|
||||
<CSVLink
|
||||
data={csvRows}
|
||||
headers={csvColumns}
|
||||
filename="payment-records.csv"
|
||||
>
|
||||
Download CSV
|
||||
</CSVLink>
|
||||
</Button>
|
||||
)}
|
||||
{(user.type === "developer" || user.type === "admin") && (
|
||||
<Button className="max-w-[200px]" variant="outline" onClick={() => setIsCreatingPayment(true)}>
|
||||
{checkAccess(user, ["developer", "admin"]) && (
|
||||
<Button
|
||||
className="max-w-[200px]"
|
||||
variant="outline"
|
||||
onClick={() => setIsCreatingPayment(true)}
|
||||
>
|
||||
New Payment
|
||||
</Button>
|
||||
)}
|
||||
@@ -963,54 +1155,78 @@ export default function PaymentRecord() {
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-mti-purple-light",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-mti-purple-light focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
|
||||
selected
|
||||
? "bg-white shadow"
|
||||
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark"
|
||||
)
|
||||
}>
|
||||
}
|
||||
>
|
||||
Payments
|
||||
</Tab>
|
||||
{["admin", "developer"].includes(user.type) && (
|
||||
{checkAccess(user, ["developer", "admin"]) && (
|
||||
<Tab
|
||||
className={({ selected }) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-mti-purple-light",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-mti-purple-light focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
|
||||
selected
|
||||
? "bg-white shadow"
|
||||
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark"
|
||||
)
|
||||
}>
|
||||
}
|
||||
>
|
||||
Paymob
|
||||
</Tab>
|
||||
)}
|
||||
</Tab.List>
|
||||
<Tab.Panels>
|
||||
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide gap-8 flex flex-col">
|
||||
<div className={clsx("grid grid-cols-1 md:grid-cols-2 gap-8 w-full", user.type !== "corporate" && "lg:grid-cols-3")}>
|
||||
<div
|
||||
className={clsx(
|
||||
"grid grid-cols-1 md:grid-cols-2 gap-8 w-full",
|
||||
user.type !== "corporate" && "lg:grid-cols-3"
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Corporate account *</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Corporate account *
|
||||
</label>
|
||||
<Select
|
||||
isClearable={user.type !== "corporate"}
|
||||
className={clsx(
|
||||
"px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool bg-white rounded-full border border-mti-gray-platinum focus:outline-none",
|
||||
user.type === "corporate" && "!bg-mti-gray-platinum/40 !text-mti-gray-dim !cursor-not-allowed",
|
||||
user.type === "corporate" &&
|
||||
"!bg-mti-gray-platinum/40 !text-mti-gray-dim !cursor-not-allowed"
|
||||
)}
|
||||
options={(users.filter((u) => u.type === "corporate") as CorporateUser[]).map((user) => ({
|
||||
options={(
|
||||
users.filter(
|
||||
(u) => u.type === "corporate"
|
||||
) as CorporateUser[]
|
||||
).map((user) => ({
|
||||
value: user.id,
|
||||
meta: user,
|
||||
label: `${user.corporateInformation?.companyInformation?.name || user.name} - ${user.email}`,
|
||||
label: `${
|
||||
user.corporateInformation?.companyInformation?.name ||
|
||||
user.name
|
||||
} - ${user.email}`,
|
||||
}))}
|
||||
defaultValue={
|
||||
user.type === "corporate"
|
||||
? {
|
||||
value: user.id,
|
||||
meta: user,
|
||||
label: `${user.corporateInformation?.companyInformation?.name || user.name} - ${
|
||||
user.email
|
||||
}`,
|
||||
label: `${
|
||||
user.corporateInformation?.companyInformation
|
||||
?.name || user.name
|
||||
} - ${user.email}`,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
isDisabled={user.type === "corporate"}
|
||||
onChange={(value) => setCorporate((value as any)?.meta ?? undefined)}
|
||||
onChange={(value) =>
|
||||
setCorporate((value as any)?.meta ?? undefined)
|
||||
}
|
||||
menuPortalTarget={document?.body}
|
||||
styles={{
|
||||
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||
@@ -1025,7 +1241,11 @@ export default function PaymentRecord() {
|
||||
}),
|
||||
option: (styles, state) => ({
|
||||
...styles,
|
||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
||||
backgroundColor: state.isFocused
|
||||
? "#D5D9F0"
|
||||
: state.isSelected
|
||||
? "#7872BF"
|
||||
: "white",
|
||||
color: state.isFocused ? "black" : styles.color,
|
||||
}),
|
||||
}}
|
||||
@@ -1033,15 +1253,21 @@ export default function PaymentRecord() {
|
||||
</div>
|
||||
{user.type !== "corporate" && (
|
||||
<div className="flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Country manager *</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Country manager *
|
||||
</label>
|
||||
<Select
|
||||
isClearable
|
||||
isDisabled={user.type === "agent"}
|
||||
className={clsx(
|
||||
"px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none",
|
||||
user.type === "agent" ? "bg-mti-gray-platinum/40" : "bg-white",
|
||||
user.type === "agent"
|
||||
? "bg-mti-gray-platinum/40"
|
||||
: "bg-white"
|
||||
)}
|
||||
options={(users.filter((u) => u.type === "agent") as AgentUser[]).map((user) => ({
|
||||
options={(
|
||||
users.filter((u) => u.type === "agent") as AgentUser[]
|
||||
).map((user) => ({
|
||||
value: user.id,
|
||||
meta: user,
|
||||
label: `${user.name} - ${user.email}`,
|
||||
@@ -1054,7 +1280,11 @@ export default function PaymentRecord() {
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onChange={(value) => setAgent(value !== null ? (value as any).meta : undefined)}
|
||||
onChange={(value) =>
|
||||
setAgent(
|
||||
value !== null ? (value as any).meta : undefined
|
||||
)
|
||||
}
|
||||
menuPortalTarget={document?.body}
|
||||
styles={{
|
||||
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||
@@ -1069,7 +1299,11 @@ export default function PaymentRecord() {
|
||||
}),
|
||||
option: (styles, state) => ({
|
||||
...styles,
|
||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
||||
backgroundColor: state.isFocused
|
||||
? "#D5D9F0"
|
||||
: state.isSelected
|
||||
? "#7872BF"
|
||||
: "white",
|
||||
color: state.isFocused ? "black" : styles.color,
|
||||
}),
|
||||
}}
|
||||
@@ -1077,12 +1311,16 @@ export default function PaymentRecord() {
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Paid</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Paid
|
||||
</label>
|
||||
<Select
|
||||
isClearable
|
||||
className={clsx(
|
||||
"px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none",
|
||||
user.type === "agent" ? "bg-mti-gray-platinum/40" : "bg-white",
|
||||
user.type === "agent"
|
||||
? "bg-mti-gray-platinum/40"
|
||||
: "bg-white"
|
||||
)}
|
||||
options={IS_PAID_OPTIONS}
|
||||
value={IS_PAID_OPTIONS.find((e) => e.value === paid)}
|
||||
@@ -1104,14 +1342,20 @@ export default function PaymentRecord() {
|
||||
}),
|
||||
option: (styles, state) => ({
|
||||
...styles,
|
||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
||||
backgroundColor: state.isFocused
|
||||
? "#D5D9F0"
|
||||
: state.isSelected
|
||||
? "#7872BF"
|
||||
: "white",
|
||||
color: state.isFocused ? "black" : styles.color,
|
||||
}),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Date</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Date
|
||||
</label>
|
||||
<ReactDatePicker
|
||||
dateFormat="dd/MM/yyyy"
|
||||
className="px-4 py-6 w-full text-sm text-center font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none"
|
||||
@@ -1120,9 +1364,13 @@ export default function PaymentRecord() {
|
||||
endDate={endDate}
|
||||
selectsRange
|
||||
showMonthDropdown
|
||||
filterDate={(date: Date) => moment(date).isSameOrBefore(moment(new Date()))}
|
||||
filterDate={(date: Date) =>
|
||||
moment(date).isSameOrBefore(moment(new Date()))
|
||||
}
|
||||
onChange={([initialDate, finalDate]: [Date, Date]) => {
|
||||
setStartDate(initialDate ?? moment("01/01/2023").toDate());
|
||||
setStartDate(
|
||||
initialDate ?? moment("01/01/2023").toDate()
|
||||
);
|
||||
if (finalDate) {
|
||||
// basicly selecting a final day works as if I'm selecting the first
|
||||
// minute of that day. this way it covers the whole day
|
||||
@@ -1135,14 +1383,18 @@ export default function PaymentRecord() {
|
||||
</div>
|
||||
{user.type !== "corporate" && (
|
||||
<div className="flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Commission transfer</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Commission transfer
|
||||
</label>
|
||||
<Select
|
||||
isClearable
|
||||
className={clsx(
|
||||
"px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none",
|
||||
"px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none"
|
||||
)}
|
||||
options={IS_FILE_SUBMITTED_OPTIONS}
|
||||
value={IS_FILE_SUBMITTED_OPTIONS.find((e) => e.value === commissionTransfer)}
|
||||
value={IS_FILE_SUBMITTED_OPTIONS.find(
|
||||
(e) => e.value === commissionTransfer
|
||||
)}
|
||||
onChange={(value) => {
|
||||
if (value) return setCommissionTransfer(value.value);
|
||||
setCommissionTransfer(null);
|
||||
@@ -1161,7 +1413,11 @@ export default function PaymentRecord() {
|
||||
}),
|
||||
option: (styles, state) => ({
|
||||
...styles,
|
||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
||||
backgroundColor: state.isFocused
|
||||
? "#D5D9F0"
|
||||
: state.isSelected
|
||||
? "#7872BF"
|
||||
: "white",
|
||||
color: state.isFocused ? "black" : styles.color,
|
||||
}),
|
||||
}}
|
||||
@@ -1169,14 +1425,18 @@ export default function PaymentRecord() {
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Corporate transfer</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Corporate transfer
|
||||
</label>
|
||||
<Select
|
||||
isClearable
|
||||
className={clsx(
|
||||
"px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none",
|
||||
"px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none"
|
||||
)}
|
||||
options={IS_FILE_SUBMITTED_OPTIONS}
|
||||
value={IS_FILE_SUBMITTED_OPTIONS.find((e) => e.value === corporateTransfer)}
|
||||
value={IS_FILE_SUBMITTED_OPTIONS.find(
|
||||
(e) => e.value === corporateTransfer
|
||||
)}
|
||||
onChange={(value) => {
|
||||
if (value) return setCorporateTransfer(value.value);
|
||||
setCorporateTransfer(null);
|
||||
@@ -1195,7 +1455,11 @@ export default function PaymentRecord() {
|
||||
}),
|
||||
option: (styles, state) => ({
|
||||
...styles,
|
||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
||||
backgroundColor: state.isFocused
|
||||
? "#D5D9F0"
|
||||
: state.isSelected
|
||||
? "#7872BF"
|
||||
: "white",
|
||||
color: state.isFocused ? "black" : styles.color,
|
||||
}),
|
||||
}}
|
||||
|
||||
190
src/pages/permissions/[id].tsx
Normal file
190
src/pages/permissions/[id].tsx
Normal file
@@ -0,0 +1,190 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import Head from "next/head";
|
||||
import { useState } from "react";
|
||||
import { withIronSessionSsr } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { shouldRedirectHome } from "@/utils/navigation.disabled";
|
||||
import { Permission, PermissionType } from "@/interfaces/permissions";
|
||||
import { getPermissionDoc } from "@/utils/permissions.be";
|
||||
import { User } from "@/interfaces/user";
|
||||
import Layout from "@/components/High/Layout";
|
||||
import { getUsers } from "@/utils/users.be";
|
||||
import { BsTrash } from "react-icons/bs";
|
||||
import Select from "@/components/Low/Select";
|
||||
import Button from "@/components/Low/Button";
|
||||
import axios from "axios";
|
||||
import { toast, ToastContainer } from "react-toastify";
|
||||
|
||||
interface BasicUser {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface PermissionWithBasicUsers {
|
||||
id: string;
|
||||
type: PermissionType;
|
||||
users: BasicUser[];
|
||||
}
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(async (context) => {
|
||||
const { req, params } = context;
|
||||
const user = req.session.user;
|
||||
|
||||
if (!user || !user.isVerified) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (shouldRedirectHome(user)) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (!params?.id) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/permissions",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Fetch data from external API
|
||||
const permission: Permission = await getPermissionDoc(params.id as string);
|
||||
|
||||
const allUserData: User[] = await getUsers();
|
||||
const users = allUserData.map((u) => ({
|
||||
id: u.id,
|
||||
name: u.name,
|
||||
})) as BasicUser[];
|
||||
|
||||
// const res = await fetch("api/permissions");
|
||||
// const permissions: Permission[] = await res.json();
|
||||
// Pass data to the page via props
|
||||
const usersData: BasicUser[] = permission.users.reduce(
|
||||
(acc: BasicUser[], userId) => {
|
||||
const user = users.find((u) => u.id === userId) as BasicUser;
|
||||
if (user) {
|
||||
acc.push(user);
|
||||
}
|
||||
return acc;
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
return {
|
||||
props: {
|
||||
// permissions: permissions.map((p) => ({ id: p.id, type: p.type })),
|
||||
permission: {
|
||||
...permission,
|
||||
id: params.id,
|
||||
users: usersData,
|
||||
},
|
||||
user: req.session.user,
|
||||
users,
|
||||
},
|
||||
};
|
||||
}, sessionOptions);
|
||||
|
||||
interface Props {
|
||||
permission: PermissionWithBasicUsers;
|
||||
user: User;
|
||||
users: BasicUser[];
|
||||
}
|
||||
|
||||
export default function Page(props: Props) {
|
||||
console.log("Props", props);
|
||||
|
||||
const { permission, user, users } = props;
|
||||
|
||||
const [selectedUsers, setSelectedUsers] = useState<string[]>(() =>
|
||||
permission.users.map((u) => u.id)
|
||||
);
|
||||
|
||||
const onChange = (value: any) => {
|
||||
console.log("value", value);
|
||||
setSelectedUsers((prev) => {
|
||||
if (value?.value) {
|
||||
return [...prev, value?.value];
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
};
|
||||
const removeUser = (id: string) => {
|
||||
setSelectedUsers((prev) => prev.filter((u) => u !== id));
|
||||
};
|
||||
|
||||
const update = async () => {
|
||||
console.log("update", selectedUsers);
|
||||
try {
|
||||
await axios.patch(`/api/permissions/${permission.id}`, {
|
||||
users: selectedUsers,
|
||||
});
|
||||
toast.success("Permission updated");
|
||||
} catch (err) {
|
||||
toast.error("Failed to update permission");
|
||||
}
|
||||
};
|
||||
|
||||
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 />
|
||||
<Layout user={user} className="gap-6">
|
||||
<h1 className="text-2xl font-semibold">
|
||||
Permission: {permission.type as string}
|
||||
</h1>
|
||||
<div className="flex gap-3">
|
||||
<Select
|
||||
value={null}
|
||||
options={users
|
||||
.filter((u) => !selectedUsers.includes(u.id))
|
||||
.map((u) => ({
|
||||
label: u.name,
|
||||
value: u.id,
|
||||
}))}
|
||||
onChange={onChange}
|
||||
/>
|
||||
<Button onClick={update}>Update</Button>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3">
|
||||
<h2>Blacklisted Users</h2>
|
||||
<div className="flex gap-3 flex-wrap">
|
||||
{selectedUsers.map((userId) => {
|
||||
const name = users.find((u) => u.id === userId)?.name;
|
||||
return (
|
||||
<div
|
||||
className="flex p-4 rounded-xl w-auto bg-mti-purple-light text-white gap-4"
|
||||
key={userId}
|
||||
>
|
||||
<span className="text-base">{name}</span>
|
||||
<BsTrash
|
||||
style={{ cursor: "pointer" }}
|
||||
onClick={() => removeUser(userId)}
|
||||
size={20}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</Layout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
94
src/pages/permissions/index.tsx
Normal file
94
src/pages/permissions/index.tsx
Normal file
@@ -0,0 +1,94 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import Head from "next/head";
|
||||
import { withIronSessionSsr } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { shouldRedirectHome } from "@/utils/navigation.disabled";
|
||||
import { Permission } from "@/interfaces/permissions";
|
||||
import { getPermissionDocs } from "@/utils/permissions.be";
|
||||
import { User } from "@/interfaces/user";
|
||||
import Layout from "@/components/High/Layout";
|
||||
import Link from "next/link";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(async ({ req }) => {
|
||||
const user = req.session.user;
|
||||
|
||||
if (!user || !user.isVerified) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/login",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (shouldRedirectHome(user)) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Fetch data from external API
|
||||
const permissions: Permission[] = await getPermissionDocs();
|
||||
|
||||
console.log("Permissions", permissions);
|
||||
|
||||
// const res = await fetch("api/permissions");
|
||||
// const permissions: Permission[] = await res.json();
|
||||
// Pass data to the page via props
|
||||
return {
|
||||
props: {
|
||||
// permissions: permissions.map((p) => ({ id: p.id, type: p.type })),
|
||||
permissions: permissions.map((p) => {
|
||||
const { users, ...rest } = p;
|
||||
return rest;
|
||||
}),
|
||||
user: req.session.user,
|
||||
},
|
||||
};
|
||||
}, sessionOptions);
|
||||
|
||||
interface Props {
|
||||
permissions: Permission[];
|
||||
user: User;
|
||||
}
|
||||
|
||||
export default function Page(props: Props) {
|
||||
console.log("Props", props);
|
||||
|
||||
const { permissions, user } = props;
|
||||
|
||||
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>
|
||||
<Layout user={user} className="gap-6">
|
||||
<h1 className="text-2xl font-semibold">Permissions</h1>
|
||||
<div className="flex gap-3 flex-wrap">
|
||||
{permissions.map((permission: Permission) => {
|
||||
const id = permission.id as string;
|
||||
const type = permission.type as string;
|
||||
return (
|
||||
<Link href={`/permissions/${id}`} key={id}>
|
||||
<div className="card bg-primary text-primary-content">
|
||||
<div className="card-body">
|
||||
<h1 className="card-title">{type}</h1>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Layout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,15 @@
|
||||
import Head from "next/head";
|
||||
import { withIronSessionSsr } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import {ChangeEvent, Dispatch, ReactNode, SetStateAction, useEffect, useRef, useState} from "react";
|
||||
import {
|
||||
ChangeEvent,
|
||||
Dispatch,
|
||||
ReactNode,
|
||||
SetStateAction,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import useUser from "@/hooks/useUser";
|
||||
import { toast, ToastContainer } from "react-toastify";
|
||||
import Layout from "@/components/High/Layout";
|
||||
@@ -12,7 +20,14 @@ import Link from "next/link";
|
||||
import axios from "axios";
|
||||
import { ErrorMessage } from "@/constants/errors";
|
||||
import clsx from "clsx";
|
||||
import {CorporateUser, EmploymentStatus, EMPLOYMENT_STATUS, Gender, User} from "@/interfaces/user";
|
||||
import {
|
||||
CorporateUser,
|
||||
EmploymentStatus,
|
||||
EMPLOYMENT_STATUS,
|
||||
Gender,
|
||||
User,
|
||||
DemographicInformation,
|
||||
} from "@/interfaces/user";
|
||||
import CountrySelect from "@/components/Low/CountrySelect";
|
||||
import { shouldRedirectHome } from "@/utils/navigation.disabled";
|
||||
import moment from "moment";
|
||||
@@ -33,6 +48,8 @@ import {InstructorGender} from "@/interfaces/exam";
|
||||
import { capitalize } from "lodash";
|
||||
import TopicModal from "@/components/Medium/TopicModal";
|
||||
import { v4 } from "uuid";
|
||||
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(({ req, res }) => {
|
||||
const user = req.session.user;
|
||||
|
||||
@@ -64,7 +81,9 @@ interface Props {
|
||||
mutateUser: Function;
|
||||
}
|
||||
|
||||
const DoubleColumnRow = ({children}: {children: ReactNode}) => <div className="flex flex-col lg:flex-row gap-8 w-full">{children}</div>;
|
||||
const DoubleColumnRow = ({ children }: { children: ReactNode }) => (
|
||||
<div className="flex flex-col lg:flex-row gap-8 w-full">{children}</div>
|
||||
);
|
||||
|
||||
function UserProfile({ user, mutateUser }: Props) {
|
||||
const [bio, setBio] = useState(user.bio || "");
|
||||
@@ -75,35 +94,71 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [profilePicture, setProfilePicture] = useState(user.profilePicture);
|
||||
|
||||
const [desiredLevels, setDesiredLevels] = useState<{[key in Module]: number} | undefined>(
|
||||
["developer", "student"].includes(user.type) ? user.desiredLevels : undefined,
|
||||
const [desiredLevels, setDesiredLevels] = useState<
|
||||
{ [key in Module]: number } | undefined
|
||||
>(
|
||||
checkAccess(user, ["developer", "student"]) ? user.desiredLevels : undefined
|
||||
);
|
||||
const [focus, setFocus] = useState<"academic" | "general">(user.focus);
|
||||
|
||||
const [country, setCountry] = useState<string>(user.demographicInformation?.country || "");
|
||||
const [phone, setPhone] = useState<string>(user.demographicInformation?.phone || "");
|
||||
const [gender, setGender] = useState<Gender | undefined>(user.demographicInformation?.gender || undefined);
|
||||
const [employment, setEmployment] = useState<EmploymentStatus | undefined>(
|
||||
user.type === "corporate" ? undefined : user.demographicInformation?.employment,
|
||||
const [country, setCountry] = useState<string>(
|
||||
user.demographicInformation?.country || ""
|
||||
);
|
||||
const [phone, setPhone] = useState<string>(
|
||||
user.demographicInformation?.phone || ""
|
||||
);
|
||||
const [gender, setGender] = useState<Gender | undefined>(
|
||||
user.demographicInformation?.gender || undefined
|
||||
);
|
||||
const [employment, setEmployment] = useState<EmploymentStatus | undefined>(
|
||||
checkAccess(user, ["corporate", "mastercorporate"])
|
||||
? undefined
|
||||
: (user.demographicInformation as DemographicInformation)?.employment
|
||||
);
|
||||
const [passport_id, setPassportID] = useState<string | undefined>(
|
||||
checkAccess(user, ["student"])
|
||||
? (user.demographicInformation as DemographicInformation)?.passport_id
|
||||
: undefined
|
||||
);
|
||||
const [passport_id, setPassportID] = useState<string | undefined>(user.type === "student" ? user.demographicInformation?.passport_id : undefined);
|
||||
|
||||
const [preferredGender, setPreferredGender] = useState<InstructorGender | undefined>(
|
||||
user.type === "student" || user.type === "developer" ? user.preferredGender || "varied" : undefined,
|
||||
const [preferredGender, setPreferredGender] = useState<
|
||||
InstructorGender | undefined
|
||||
>(
|
||||
user.type === "student" || user.type === "developer"
|
||||
? user.preferredGender || "varied"
|
||||
: undefined
|
||||
);
|
||||
const [preferredTopics, setPreferredTopics] = useState<string[] | undefined>(
|
||||
user.type === "student" || user.type === "developer" ? user.preferredTopics : undefined,
|
||||
user.type === "student" || user.type === "developer"
|
||||
? user.preferredTopics
|
||||
: undefined
|
||||
);
|
||||
|
||||
const [position, setPosition] = useState<string | undefined>(user.type === "corporate" ? user.demographicInformation?.position : undefined);
|
||||
const [corporateInformation, setCorporateInformation] = useState(user.type === "corporate" ? user.corporateInformation : undefined);
|
||||
const [companyName, setCompanyName] = useState<string | undefined>(user.type === "agent" ? user.agentInformation?.companyName : undefined);
|
||||
const [commercialRegistration, setCommercialRegistration] = useState<string | undefined>(
|
||||
user.type === "agent" ? user.agentInformation?.commercialRegistration : undefined,
|
||||
const [position, setPosition] = useState<string | undefined>(
|
||||
user.type === "corporate"
|
||||
? user.demographicInformation?.position
|
||||
: undefined
|
||||
);
|
||||
const [corporateInformation, setCorporateInformation] = useState(
|
||||
user.type === "corporate" ? user.corporateInformation : undefined
|
||||
);
|
||||
const [companyName, setCompanyName] = useState<string | undefined>(
|
||||
user.type === "agent" ? user.agentInformation?.companyName : undefined
|
||||
);
|
||||
const [commercialRegistration, setCommercialRegistration] = useState<
|
||||
string | undefined
|
||||
>(
|
||||
user.type === "agent"
|
||||
? user.agentInformation?.commercialRegistration
|
||||
: undefined
|
||||
);
|
||||
const [arabName, setArabName] = useState<string | undefined>(
|
||||
user.type === "agent" ? user.agentInformation?.companyArabName : undefined
|
||||
);
|
||||
const [arabName, setArabName] = useState<string | undefined>(user.type === "agent" ? user.agentInformation?.companyArabName : undefined);
|
||||
|
||||
const [timezone, setTimezone] = useState<string>(user.demographicInformation?.timezone || moment.tz.guess());
|
||||
const [timezone, setTimezone] = useState<string>(
|
||||
user.demographicInformation?.timezone || moment.tz.guess()
|
||||
);
|
||||
|
||||
const [isPreferredTopicsOpen, setIsPreferredTopicsOpen] = useState(false);
|
||||
|
||||
@@ -115,9 +170,12 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
const momentDate = moment(date);
|
||||
const today = moment(new Date());
|
||||
|
||||
if (today.add(1, "days").isAfter(momentDate)) return "!bg-mti-red-ultralight border-mti-red-light";
|
||||
if (today.add(3, "days").isAfter(momentDate)) return "!bg-mti-rose-ultralight border-mti-rose-light";
|
||||
if (today.add(7, "days").isAfter(momentDate)) return "!bg-mti-orange-ultralight border-mti-orange-light";
|
||||
if (today.add(1, "days").isAfter(momentDate))
|
||||
return "!bg-mti-red-ultralight border-mti-red-light";
|
||||
if (today.add(3, "days").isAfter(momentDate))
|
||||
return "!bg-mti-rose-ultralight border-mti-rose-light";
|
||||
if (today.add(7, "days").isAfter(momentDate))
|
||||
return "!bg-mti-orange-ultralight border-mti-orange-light";
|
||||
};
|
||||
|
||||
const uploadProfilePicture = async (event: ChangeEvent<HTMLInputElement>) => {
|
||||
@@ -137,15 +195,20 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
}
|
||||
|
||||
if (newPassword && !password) {
|
||||
toast.error("To update your password you need to input your current one!");
|
||||
toast.error(
|
||||
"To update your password you need to input your current one!"
|
||||
);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (email !== user?.email) {
|
||||
const userAdmins = groups.filter((x) => x.participants.includes(user.id)).map((x) => x.admin);
|
||||
const userAdmins = groups
|
||||
.filter((x) => x.participants.includes(user.id))
|
||||
.map((x) => x.admin);
|
||||
const message =
|
||||
users.filter((x) => userAdmins.includes(x.id) && x.type === "corporate").length > 0
|
||||
users.filter((x) => userAdmins.includes(x.id) && x.type === "corporate")
|
||||
.length > 0
|
||||
? "If you change your e-mail address, you will lose all benefits from your university/institute. Are you sure you want to continue?"
|
||||
: "Are you sure you want to update your e-mail address?";
|
||||
|
||||
@@ -206,7 +269,9 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
|
||||
const ExpirationDate = () => (
|
||||
<div className="flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Expiry Date (click to purchase)</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Expiry Date (click to purchase)
|
||||
</label>
|
||||
<Link
|
||||
href="/payment"
|
||||
className={clsx(
|
||||
@@ -215,22 +280,30 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
!user.subscriptionExpirationDate
|
||||
? "!bg-mti-green-ultralight !border-mti-green-light"
|
||||
: expirationDateColor(user.subscriptionExpirationDate),
|
||||
"bg-white border-mti-gray-platinum",
|
||||
)}>
|
||||
"bg-white border-mti-gray-platinum"
|
||||
)}
|
||||
>
|
||||
{!user.subscriptionExpirationDate && "Unlimited"}
|
||||
{user.subscriptionExpirationDate && moment(user.subscriptionExpirationDate).format("DD/MM/YYYY")}
|
||||
{user.subscriptionExpirationDate &&
|
||||
moment(user.subscriptionExpirationDate).format("DD/MM/YYYY")}
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
|
||||
const TimezoneInput = () => (
|
||||
<div className="flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Timezone</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Timezone
|
||||
</label>
|
||||
<TimezoneSelect value={timezone} onChange={setTimezone} />
|
||||
</div>
|
||||
);
|
||||
|
||||
const manualDownloadLink = ["student", "teacher", "corporate"].includes(user.type) ? `/manuals/${user.type}.pdf` : "";
|
||||
const manualDownloadLink = ["student", "teacher", "corporate"].includes(
|
||||
user.type
|
||||
)
|
||||
? `/manuals/${user.type}.pdf`
|
||||
: "";
|
||||
|
||||
return (
|
||||
<Layout user={user}>
|
||||
@@ -239,7 +312,10 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
<div className="flex -md:flex-col-reverse -md:items-center w-full justify-between">
|
||||
<div className="flex flex-col gap-8 w-full md:w-2/3">
|
||||
<h1 className="text-4xl font-bold mb-6 -md:hidden">Edit Profile</h1>
|
||||
<form className="flex flex-col items-center gap-6 w-full" onSubmit={(e) => e.preventDefault()}>
|
||||
<form
|
||||
className="flex flex-col items-center gap-6 w-full"
|
||||
onSubmit={(e) => e.preventDefault()}
|
||||
>
|
||||
<DoubleColumnRow>
|
||||
{user.type !== "corporate" ? (
|
||||
<Input
|
||||
@@ -335,7 +411,9 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
|
||||
<DoubleColumnRow>
|
||||
<div className="flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Country *</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Country *
|
||||
</label>
|
||||
<CountrySelect value={country} onChange={setCountry} />
|
||||
</div>
|
||||
<Input
|
||||
@@ -368,26 +446,37 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
|
||||
<Divider />
|
||||
|
||||
{desiredLevels && ["developer", "student"].includes(user.type) && (
|
||||
{desiredLevels &&
|
||||
["developer", "student"].includes(user.type) && (
|
||||
<>
|
||||
<div className="flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Desired Levels</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Desired Levels
|
||||
</label>
|
||||
<ModuleLevelSelector
|
||||
levels={desiredLevels}
|
||||
setLevels={setDesiredLevels as Dispatch<SetStateAction<{[key in Module]: number}>>}
|
||||
setLevels={
|
||||
setDesiredLevels as Dispatch<
|
||||
SetStateAction<{ [key in Module]: number }>
|
||||
>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Focus</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Focus
|
||||
</label>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-y-4 gap-x-16 w-full">
|
||||
<button
|
||||
onClick={() => setFocus("academic")}
|
||||
className={clsx(
|
||||
"w-full border border-mti-gray-platinum rounded-full px-6 py-4 flex justify-center items-center gap-12 bg-white",
|
||||
"hover:bg-mti-purple-light hover:text-white",
|
||||
focus === "academic" && "!bg-mti-purple-light !text-white",
|
||||
"transition duration-300 ease-in-out",
|
||||
)}>
|
||||
focus === "academic" &&
|
||||
"!bg-mti-purple-light !text-white",
|
||||
"transition duration-300 ease-in-out"
|
||||
)}
|
||||
>
|
||||
Academic
|
||||
</button>
|
||||
<button
|
||||
@@ -395,9 +484,11 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
className={clsx(
|
||||
"w-full border border-mti-gray-platinum rounded-full px-6 py-4 flex justify-center items-center gap-12 bg-white",
|
||||
"hover:bg-mti-purple-light hover:text-white",
|
||||
focus === "general" && "!bg-mti-purple-light !text-white",
|
||||
"transition duration-300 ease-in-out",
|
||||
)}>
|
||||
focus === "general" &&
|
||||
"!bg-mti-purple-light !text-white",
|
||||
"transition duration-300 ease-in-out"
|
||||
)}
|
||||
>
|
||||
General
|
||||
</button>
|
||||
</div>
|
||||
@@ -405,18 +496,27 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
</>
|
||||
)}
|
||||
|
||||
{preferredGender && ["developer", "student"].includes(user.type) && (
|
||||
{preferredGender &&
|
||||
["developer", "student"].includes(user.type) && (
|
||||
<>
|
||||
<Divider />
|
||||
<DoubleColumnRow>
|
||||
<div className="flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Speaking Instructor's Gender</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Speaking Instructor's Gender
|
||||
</label>
|
||||
<Select
|
||||
value={{
|
||||
value: preferredGender,
|
||||
label: capitalize(preferredGender),
|
||||
}}
|
||||
onChange={(value) => (value ? setPreferredGender(value.value as InstructorGender) : null)}
|
||||
onChange={(value) =>
|
||||
value
|
||||
? setPreferredGender(
|
||||
value.value as InstructorGender
|
||||
)
|
||||
: null
|
||||
}
|
||||
options={[
|
||||
{ value: "male", label: "Male" },
|
||||
{ value: "female", label: "Female" },
|
||||
@@ -429,12 +529,18 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
Preferred Topics{" "}
|
||||
<span
|
||||
className="tooltip"
|
||||
data-tip="These topics will be considered for speaking and writing modules, aiming to include at least one exercise containing of the these in the selected exams.">
|
||||
data-tip="These topics will be considered for speaking and writing modules, aiming to include at least one exercise containing of the these in the selected exams."
|
||||
>
|
||||
<BsQuestionCircleFill />
|
||||
</span>
|
||||
</label>
|
||||
<Button className="w-full" variant="outline" onClick={() => setIsPreferredTopicsOpen(true)}>
|
||||
Select Topics ({preferredTopics?.length || "All"} selected)
|
||||
<Button
|
||||
className="w-full"
|
||||
variant="outline"
|
||||
onClick={() => setIsPreferredTopicsOpen(true)}
|
||||
>
|
||||
Select Topics ({preferredTopics?.length || "All"}{" "}
|
||||
selected)
|
||||
</Button>
|
||||
</div>
|
||||
</DoubleColumnRow>
|
||||
@@ -459,7 +565,9 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
name="companyUsers"
|
||||
onChange={() => null}
|
||||
label="Number of users"
|
||||
defaultValue={user.corporateInformation.companyInformation.userAmount}
|
||||
defaultValue={
|
||||
user.corporateInformation.companyInformation.userAmount
|
||||
}
|
||||
disabled
|
||||
required
|
||||
/>
|
||||
@@ -503,14 +611,20 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
</>
|
||||
)}
|
||||
|
||||
{user.type === "corporate" && user.corporateInformation.referralAgent && (
|
||||
{user.type === "corporate" &&
|
||||
user.corporateInformation.referralAgent && (
|
||||
<>
|
||||
<Divider />
|
||||
<DoubleColumnRow>
|
||||
<Input
|
||||
name="agentName"
|
||||
onChange={() => null}
|
||||
defaultValue={users.find((x) => x.id === user.corporateInformation.referralAgent)?.name}
|
||||
defaultValue={
|
||||
users.find(
|
||||
(x) =>
|
||||
x.id === user.corporateInformation.referralAgent
|
||||
)?.name
|
||||
}
|
||||
type="text"
|
||||
label="Country Manager's Name"
|
||||
placeholder="Not available"
|
||||
@@ -520,7 +634,12 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
<Input
|
||||
name="agentEmail"
|
||||
onChange={() => null}
|
||||
defaultValue={users.find((x) => x.id === user.corporateInformation.referralAgent)?.email}
|
||||
defaultValue={
|
||||
users.find(
|
||||
(x) =>
|
||||
x.id === user.corporateInformation.referralAgent
|
||||
)?.email
|
||||
}
|
||||
type="text"
|
||||
label="Country Manager's E-mail"
|
||||
placeholder="Not available"
|
||||
@@ -530,11 +649,15 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
</DoubleColumnRow>
|
||||
<DoubleColumnRow>
|
||||
<div className="flex flex-col gap-2 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Country Manager's Country *</label>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Country Manager's Country *
|
||||
</label>
|
||||
<CountrySelect
|
||||
value={
|
||||
users.find((x) => x.id === user.corporateInformation.referralAgent)?.demographicInformation
|
||||
?.country
|
||||
users.find(
|
||||
(x) =>
|
||||
x.id === user.corporateInformation.referralAgent
|
||||
)?.demographicInformation?.country
|
||||
}
|
||||
onChange={() => null}
|
||||
disabled
|
||||
@@ -548,7 +671,10 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
onChange={() => null}
|
||||
placeholder="Not available"
|
||||
defaultValue={
|
||||
users.find((x) => x.id === user.corporateInformation.referralAgent)?.demographicInformation?.phone
|
||||
users.find(
|
||||
(x) =>
|
||||
x.id === user.corporateInformation.referralAgent
|
||||
)?.demographicInformation?.phone
|
||||
}
|
||||
disabled
|
||||
required
|
||||
@@ -559,7 +685,10 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
|
||||
{user.type !== "corporate" && (
|
||||
<DoubleColumnRow>
|
||||
<EmploymentStatusInput value={employment} onChange={setEmployment} />
|
||||
<EmploymentStatusInput
|
||||
value={employment}
|
||||
onChange={setEmployment}
|
||||
/>
|
||||
|
||||
<div className="flex flex-col gap-8 w-full">
|
||||
<GenderInput value={gender} onChange={setGender} />
|
||||
@@ -572,37 +701,62 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
<div className="flex flex-col gap-6 w-48">
|
||||
<div
|
||||
className="flex flex-col gap-3 items-center h-fit cursor-pointer group"
|
||||
onClick={() => (profilePictureInput.current as any)?.click()}>
|
||||
onClick={() => (profilePictureInput.current as any)?.click()}
|
||||
>
|
||||
<div className="relative overflow-hidden h-48 w-48 rounded-full">
|
||||
<div
|
||||
className={clsx(
|
||||
"absolute top-0 left-0 bg-mti-purple-light/60 w-full h-full z-20 flex items-center justify-center opacity-0 group-hover:opacity-100",
|
||||
"transition ease-in-out duration-300",
|
||||
)}>
|
||||
"transition ease-in-out duration-300"
|
||||
)}
|
||||
>
|
||||
<BsCamera className="text-6xl text-mti-purple-ultralight/80" />
|
||||
</div>
|
||||
<img src={profilePicture} alt={user.name} className="aspect-square drop-shadow-xl self-end object-cover" />
|
||||
<img
|
||||
src={profilePicture}
|
||||
alt={user.name}
|
||||
className="aspect-square drop-shadow-xl self-end object-cover"
|
||||
/>
|
||||
</div>
|
||||
<input type="file" className="hidden" onChange={uploadProfilePicture} accept="image/*" ref={profilePictureInput} />
|
||||
<input
|
||||
type="file"
|
||||
className="hidden"
|
||||
onChange={uploadProfilePicture}
|
||||
accept="image/*"
|
||||
ref={profilePictureInput}
|
||||
/>
|
||||
<span
|
||||
onClick={() => (profilePictureInput.current as any)?.click()}
|
||||
className="cursor-pointer text-mti-purple-light text-sm">
|
||||
className="cursor-pointer text-mti-purple-light text-sm"
|
||||
>
|
||||
Change picture
|
||||
</span>
|
||||
<h6 className="font-normal text-base text-mti-gray-taupe">{USER_TYPE_LABELS[user.type]}</h6>
|
||||
<h6 className="font-normal text-base text-mti-gray-taupe">
|
||||
{USER_TYPE_LABELS[user.type]}
|
||||
</h6>
|
||||
</div>
|
||||
{user.type === "agent" && (
|
||||
<div className="flag items-center h-fit">
|
||||
<img
|
||||
alt={user.demographicInformation?.country.toLowerCase() + "_flag"}
|
||||
alt={
|
||||
user.demographicInformation?.country.toLowerCase() + "_flag"
|
||||
}
|
||||
src={`https://flagcdn.com/w320/${user.demographicInformation?.country.toLowerCase()}.png`}
|
||||
width="320"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{manualDownloadLink && (
|
||||
<a href={manualDownloadLink} className="max-w-[200px] self-end w-full" download>
|
||||
<Button color="purple" variant="outline" className="max-w-[200px] self-end w-full">
|
||||
<a
|
||||
href={manualDownloadLink}
|
||||
className="max-w-[200px] self-end w-full"
|
||||
download
|
||||
>
|
||||
<Button
|
||||
color="purple"
|
||||
variant="outline"
|
||||
className="max-w-[200px] self-end w-full"
|
||||
>
|
||||
Download Manual
|
||||
</Button>
|
||||
</a>
|
||||
@@ -621,11 +775,20 @@ function UserProfile({user, mutateUser}: Props) {
|
||||
|
||||
<div className="self-end flex justify-between w-full gap-8 absolute bottom-8 left-0 px-8">
|
||||
<Link href="/" className="max-w-[200px] self-end w-full">
|
||||
<Button color="purple" variant="outline" className="max-w-[200px] self-end w-full">
|
||||
<Button
|
||||
color="purple"
|
||||
variant="outline"
|
||||
className="max-w-[200px] self-end w-full"
|
||||
>
|
||||
Back
|
||||
</Button>
|
||||
</Link>
|
||||
<Button color="purple" className="max-w-[200px] self-end w-full" onClick={updateUser} disabled={isLoading}>
|
||||
<Button
|
||||
color="purple"
|
||||
className="max-w-[200px] self-end w-full"
|
||||
onClick={updateUser}
|
||||
disabled={isLoading}
|
||||
>
|
||||
Save Changes
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -26,7 +26,7 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
};
|
||||
}
|
||||
|
||||
if (shouldRedirectHome(user) || !["developer", "admin", "corporate", "agent"].includes(user.type)) {
|
||||
if (shouldRedirectHome(user) || !["developer", "admin", "corporate", "agent", "mastercorporate"].includes(user.type)) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/",
|
||||
|
||||
@@ -202,7 +202,7 @@ export default function Stats() {
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{(user.type === "corporate" || user.type === "teacher") && groups.length > 0 && (
|
||||
{(["corporate", "teacher", "mastercorporate"].includes(user.type) ) && groups.length > 0 && (
|
||||
<Select
|
||||
className="w-full"
|
||||
options={users
|
||||
|
||||
@@ -7,6 +7,7 @@ export const USER_TYPE_LABELS: {[key in Type]: string} = {
|
||||
agent: "Country Manager",
|
||||
admin: "Admin",
|
||||
developer: "Developer",
|
||||
mastercorporate: "Master Corporate"
|
||||
};
|
||||
|
||||
export function isCorporateUser(user: User): user is CorporateUser {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CorporateUser, Group, User } from "@/interfaces/user";
|
||||
import { CorporateUser, Group, User, Type } from "@/interfaces/user";
|
||||
import axios from "axios";
|
||||
|
||||
export const isUserFromCorporate = async (userID: string) => {
|
||||
@@ -7,20 +7,12 @@ export const isUserFromCorporate = async (userID: string) => {
|
||||
const users = (await axios.get<User[]>("/api/users/list")).data;
|
||||
|
||||
const adminTypes = groups.map(
|
||||
(g) => users.find((u) => u.id === g.admin)?.type,
|
||||
(g) => users.find((u) => u.id === g.admin)?.type
|
||||
);
|
||||
return adminTypes.includes("corporate");
|
||||
};
|
||||
|
||||
export const getUserCorporate = async (
|
||||
userID: string,
|
||||
): Promise<CorporateUser | undefined> => {
|
||||
const userRequest = await axios.get<User>(`/api/users/${userID}`);
|
||||
if (userRequest.status === 200) {
|
||||
const user = userRequest.data;
|
||||
if (user.type === "corporate") return user;
|
||||
}
|
||||
|
||||
const getAdminForGroup = async (userID: string, role: Type) => {
|
||||
const groups = (await axios.get<Group[]>(`/api/groups?participant=${userID}`))
|
||||
.data;
|
||||
|
||||
@@ -29,9 +21,23 @@ export const getUserCorporate = async (
|
||||
const userRequest = await axios.get<User>(`/api/users/${g.admin}`);
|
||||
if (userRequest.status === 200) return userRequest.data;
|
||||
return undefined;
|
||||
}),
|
||||
})
|
||||
);
|
||||
|
||||
const admins = adminRequests.filter((x) => x?.type === "corporate");
|
||||
const admins = adminRequests.filter((x) => x?.type === role);
|
||||
return admins.length > 0 ? (admins[0] as CorporateUser) : undefined;
|
||||
};
|
||||
|
||||
export const getUserCorporate = async (
|
||||
userID: string
|
||||
): Promise<CorporateUser | undefined> => {
|
||||
const userRequest = await axios.get<User>(`/api/users/${userID}`);
|
||||
if (userRequest.status === 200) {
|
||||
const user = userRequest.data;
|
||||
if (user.type === "corporate") {
|
||||
return getAdminForGroup(userID, "mastercorporate");
|
||||
}
|
||||
}
|
||||
|
||||
return getAdminForGroup(userID, "corporate");
|
||||
};
|
||||
|
||||
83
src/utils/permissions.be.ts
Normal file
83
src/utils/permissions.be.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { app, adminApp } from "@/firebase";
|
||||
import { getAuth } from "firebase-admin/auth";
|
||||
|
||||
import {
|
||||
collection,
|
||||
deleteDoc,
|
||||
doc,
|
||||
getDoc,
|
||||
getDocs,
|
||||
getFirestore,
|
||||
query,
|
||||
setDoc,
|
||||
where,
|
||||
} from "firebase/firestore";
|
||||
import {
|
||||
Permission,
|
||||
PermissionType,
|
||||
permissions,
|
||||
} from "@/interfaces/permissions";
|
||||
import {v4} from "uuid";
|
||||
|
||||
const db = getFirestore(app);
|
||||
|
||||
async function createPermission(type: string) {
|
||||
const permData = doc(db, "permissions", v4());
|
||||
const permDoc = await getDoc(permData);
|
||||
if (permDoc.exists()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
await setDoc(permData, {
|
||||
type,
|
||||
users: [],
|
||||
});
|
||||
}
|
||||
export function getPermissions(userId: string | undefined, docs: Permission[]) {
|
||||
if (!userId) {
|
||||
return [];
|
||||
}
|
||||
// the concept is like a blacklist
|
||||
// if the user exists in the list, he can't access this permission
|
||||
// even if his profile allows
|
||||
const permissions = docs.reduce((acc: PermissionType[], doc: Permission) => {
|
||||
// typescript was complaining even with the validation on the top
|
||||
if (doc.users.includes(userId)) {
|
||||
return acc;
|
||||
}
|
||||
|
||||
return [...acc, doc.type];
|
||||
}, []) as PermissionType[];
|
||||
return permissions;
|
||||
}
|
||||
|
||||
export async function bootstrap() {
|
||||
await permissions.forEach(async (type) => {
|
||||
await createPermission(type);
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPermissionDoc(id: string) {
|
||||
const docRef = doc(db, "permissions", id);
|
||||
const docSnap = await getDoc(docRef);
|
||||
|
||||
if (docSnap.exists()) {
|
||||
return docSnap.data() as Permission;
|
||||
}
|
||||
|
||||
throw new Error("Permission not found");
|
||||
}
|
||||
|
||||
export async function getPermissionDocs() {
|
||||
const q = query(collection(db, "permissions"));
|
||||
// firebase is missing something like array-not-contains
|
||||
|
||||
const snapshot = await getDocs(q);
|
||||
|
||||
const docs = snapshot.docs.map((doc) => ({
|
||||
id: doc.id,
|
||||
...doc.data(),
|
||||
})) as Permission[];
|
||||
|
||||
return docs;
|
||||
}
|
||||
45
src/utils/permissions.ts
Normal file
45
src/utils/permissions.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { PermissionType } from "@/interfaces/permissions";
|
||||
import { User, Type, userTypes } from "@/interfaces/user";
|
||||
|
||||
export function checkAccess(
|
||||
user: User,
|
||||
types: Type[],
|
||||
permission?: PermissionType
|
||||
) {
|
||||
if (!user) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// if(user.type === '') {
|
||||
if (!user.type) {
|
||||
console.warn("User type is empty");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (types.length === 0) {
|
||||
console.warn("No types provided");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!types.includes(user.type)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// we may not want a permission check as most screens dont even havr a specific permission
|
||||
if (permission) {
|
||||
// this works more like a blacklist
|
||||
// therefore if we don't find the permission here, he can't do it
|
||||
if (!(user.permissions || []).includes(permission)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export function getTypesOfUser(types: Type[]) {
|
||||
// basicly generate a list of all types except the excluded ones
|
||||
return userTypes.filter((userType) => {
|
||||
return !types.includes(userType);
|
||||
})
|
||||
}
|
||||
14
src/utils/users.be.ts
Normal file
14
src/utils/users.be.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { app } from "@/firebase";
|
||||
|
||||
import { collection, getDocs, getFirestore } from "firebase/firestore";
|
||||
import { User } from "@/interfaces/user";
|
||||
const db = getFirestore(app);
|
||||
|
||||
export async function getUsers() {
|
||||
const snapshot = await getDocs(collection(db, "users"));
|
||||
|
||||
return snapshot.docs.map((doc) => ({
|
||||
id: doc.id,
|
||||
...doc.data(),
|
||||
})) as User[];
|
||||
}
|
||||
@@ -25,7 +25,7 @@ export const exportListToExcel = (rowUsers: User[], users: User[], groups: Group
|
||||
expiryDate: user.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).format("DD/MM/YYYY") : "Unlimited",
|
||||
country: user.demographicInformation?.country || "N/A",
|
||||
phone: user.demographicInformation?.phone || "N/A",
|
||||
employmentPosition: (user.type === "corporate" ? user.demographicInformation?.position : user.demographicInformation?.employment) || "N/A",
|
||||
employmentPosition: (user.type === "corporate" || user.type === "mastercorporate" ? user.demographicInformation?.position : user.demographicInformation?.employment) || "N/A",
|
||||
gender: user.demographicInformation?.gender ? capitalize(user.demographicInformation.gender) : "N/A",
|
||||
verified: user.isVerified?.toString() || "FALSE",
|
||||
}));
|
||||
|
||||
Reference in New Issue
Block a user