Merged in ENCOA-56_Permissions (pull request #55)
ENCOA-56 Permissions Approved-by: Tiago Ribeiro
This commit is contained in:
@@ -33,8 +33,7 @@ export default function Layout({user, children, className, navDisabled = false,
|
|||||||
focusMode={focusMode}
|
focusMode={focusMode}
|
||||||
onFocusLayerMouseEnter={onFocusLayerMouseEnter}
|
onFocusLayerMouseEnter={onFocusLayerMouseEnter}
|
||||||
className="-md:hidden"
|
className="-md:hidden"
|
||||||
userType={user.type}
|
user={user}
|
||||||
userId={user.id}
|
|
||||||
/>
|
/>
|
||||||
<div
|
<div
|
||||||
className={clsx(
|
className={clsx(
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import ShortUniqueId from "short-unique-id";
|
|||||||
import Button from "../Low/Button";
|
import Button from "../Low/Button";
|
||||||
import Input from "../Low/Input";
|
import Input from "../Low/Input";
|
||||||
import Select from "../Low/Select";
|
import Select from "../Low/Select";
|
||||||
|
import { checkAccess } from "@/utils/permissions";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
user: User;
|
user: User;
|
||||||
@@ -137,13 +138,13 @@ export default function TicketDisplay({ user, ticket, onClose }: Props) {
|
|||||||
options={[
|
options={[
|
||||||
{ value: "me", label: "Assign to me" },
|
{ value: "me", label: "Assign to me" },
|
||||||
...users
|
...users
|
||||||
.filter((x) => ["admin", "developer", "agent"].includes(x.type))
|
.filter((x) => checkAccess(x, ["admin", "developer", "agent"]))
|
||||||
.map((u) => ({
|
.map((u) => ({
|
||||||
value: u.id,
|
value: u.id,
|
||||||
label: `${u.name} - ${u.email}`,
|
label: `${u.name} - ${u.email}`,
|
||||||
})),
|
})),
|
||||||
]}
|
]}
|
||||||
disabled={user.type === "agent"}
|
disabled={checkAccess(user, ["agent"])}
|
||||||
value={
|
value={
|
||||||
assignedTo
|
assignedTo
|
||||||
? {
|
? {
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import {User} from "@/interfaces/user";
|
import { User } from "@/interfaces/user";
|
||||||
import {Dialog, Transition} from "@headlessui/react";
|
import { Dialog, Transition } from "@headlessui/react";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import clsx from "clsx";
|
import clsx from "clsx";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import {useRouter} from "next/router";
|
import { useRouter } from "next/router";
|
||||||
import {Fragment} from "react";
|
import { Fragment } from "react";
|
||||||
import {BsXLg} from "react-icons/bs";
|
import { BsXLg } from "react-icons/bs";
|
||||||
|
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
@@ -16,7 +17,13 @@ interface Props {
|
|||||||
disableNavigation?: boolean;
|
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 router = useRouter();
|
||||||
|
|
||||||
const logout = async () => {
|
const logout = async () => {
|
||||||
@@ -35,7 +42,8 @@ export default function MobileMenu({isOpen, onClose, path, user, disableNavigati
|
|||||||
enterTo="opacity-100"
|
enterTo="opacity-100"
|
||||||
leave="ease-in duration-200"
|
leave="ease-in duration-200"
|
||||||
leaveFrom="opacity-100"
|
leaveFrom="opacity-100"
|
||||||
leaveTo="opacity-0">
|
leaveTo="opacity-0"
|
||||||
|
>
|
||||||
<div className="fixed inset-0 bg-black bg-opacity-25" />
|
<div className="fixed inset-0 bg-black bg-opacity-25" />
|
||||||
</Transition.Child>
|
</Transition.Child>
|
||||||
|
|
||||||
@@ -48,14 +56,30 @@ export default function MobileMenu({isOpen, onClose, path, user, disableNavigati
|
|||||||
enterTo="opacity-100 scale-100"
|
enterTo="opacity-100 scale-100"
|
||||||
leave="ease-in duration-200"
|
leave="ease-in duration-200"
|
||||||
leaveFrom="opacity-100 scale-100"
|
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.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 ? "" : "/"}>
|
<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>
|
</Link>
|
||||||
<div className="cursor-pointer" onClick={onClose} tabIndex={0}>
|
<div
|
||||||
<BsXLg className="text-mti-purple-light text-2xl" onClick={onClose} />
|
className="cursor-pointer"
|
||||||
|
onClick={onClose}
|
||||||
|
tabIndex={0}
|
||||||
|
>
|
||||||
|
<BsXLg
|
||||||
|
className="text-mti-purple-light text-2xl"
|
||||||
|
onClick={onClose}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</Dialog.Title>
|
</Dialog.Title>
|
||||||
<div className="flex h-full flex-col gap-6 px-8 text-lg">
|
<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 ? "" : "/"}
|
href={disableNavigation ? "" : "/"}
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"w-fit transition duration-300 ease-in-out",
|
"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
|
Dashboard
|
||||||
</Link>
|
</Link>
|
||||||
{(user.type === "student" || user.type === "teacher" || user.type === "developer") && (
|
{checkAccess(user, ["student", "teacher", "developer"]) && (
|
||||||
<>
|
<>
|
||||||
<Link
|
<Link
|
||||||
href={disableNavigation ? "" : "/exam"}
|
href={disableNavigation ? "" : "/exam"}
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"w-fit transition duration-300 ease-in-out",
|
"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
|
Exams
|
||||||
</Link>
|
</Link>
|
||||||
<Link
|
<Link
|
||||||
@@ -82,8 +110,9 @@ export default function MobileMenu({isOpen, onClose, path, user, disableNavigati
|
|||||||
className={clsx(
|
className={clsx(
|
||||||
"w-fit transition duration-300 ease-in-out",
|
"w-fit transition duration-300 ease-in-out",
|
||||||
path === "/exercises" &&
|
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
|
Exercises
|
||||||
</Link>
|
</Link>
|
||||||
</>
|
</>
|
||||||
@@ -92,46 +121,67 @@ export default function MobileMenu({isOpen, onClose, path, user, disableNavigati
|
|||||||
href={disableNavigation ? "" : "/stats"}
|
href={disableNavigation ? "" : "/stats"}
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"w-fit transition duration-300 ease-in-out",
|
"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
|
Stats
|
||||||
</Link>
|
</Link>
|
||||||
<Link
|
<Link
|
||||||
href={disableNavigation ? "" : "/record"}
|
href={disableNavigation ? "" : "/record"}
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"w-fit transition duration-300 ease-in-out",
|
"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
|
Record
|
||||||
</Link>
|
</Link>
|
||||||
{["admin", "developer", "agent", "corporate", "mastercorporate"].includes(user.type) && (
|
{checkAccess(user, [
|
||||||
|
"admin",
|
||||||
|
"developer",
|
||||||
|
"agent",
|
||||||
|
"corporate",
|
||||||
|
"mastercorporate",
|
||||||
|
]) && (
|
||||||
<Link
|
<Link
|
||||||
href={disableNavigation ? "" : "/payment-record"}
|
href={disableNavigation ? "" : "/payment-record"}
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"w-fit transition duration-300 ease-in-out",
|
"w-fit transition duration-300 ease-in-out",
|
||||||
path === "/payment-record" &&
|
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
|
Payment Record
|
||||||
</Link>
|
</Link>
|
||||||
)}
|
)}
|
||||||
{["admin", "developer", "corporate", "teacher", "mastercorporate"].includes(user.type) && (
|
{checkAccess(user, [
|
||||||
|
"admin",
|
||||||
|
"developer",
|
||||||
|
"corporate",
|
||||||
|
"teacher",
|
||||||
|
"mastercorporate",
|
||||||
|
]) && (
|
||||||
<Link
|
<Link
|
||||||
href={disableNavigation ? "" : "/settings"}
|
href={disableNavigation ? "" : "/settings"}
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"w-fit transition duration-300 ease-in-out",
|
"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
|
Settings
|
||||||
</Link>
|
</Link>
|
||||||
)}
|
)}
|
||||||
{["admin", "developer", "agent"].includes(user.type) && (
|
{checkAccess(user, ["admin", "developer", "agent"]) && (
|
||||||
<Link
|
<Link
|
||||||
href={disableNavigation ? "" : "/tickets"}
|
href={disableNavigation ? "" : "/tickets"}
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"w-fit transition duration-300 ease-in-out",
|
"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
|
Tickets
|
||||||
</Link>
|
</Link>
|
||||||
)}
|
)}
|
||||||
@@ -139,14 +189,19 @@ export default function MobileMenu({isOpen, onClose, path, user, disableNavigati
|
|||||||
href={disableNavigation ? "" : "/profile"}
|
href={disableNavigation ? "" : "/profile"}
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"w-fit transition duration-300 ease-in-out",
|
"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
|
Profile
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
<span
|
<span
|
||||||
className={clsx("w-fit cursor-pointer justify-self-end transition duration-300 ease-in-out")}
|
className={clsx(
|
||||||
onClick={logout}>
|
"w-fit cursor-pointer justify-self-end transition duration-300 ease-in-out"
|
||||||
|
)}
|
||||||
|
onClick={logout}
|
||||||
|
>
|
||||||
Logout
|
Logout
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import clsx from "clsx";
|
import clsx from "clsx";
|
||||||
import {IconType} from "react-icons";
|
import { IconType } from "react-icons";
|
||||||
import {MdSpaceDashboard} from "react-icons/md";
|
import { MdSpaceDashboard } from "react-icons/md";
|
||||||
import {
|
import {
|
||||||
BsFileEarmarkText,
|
BsFileEarmarkText,
|
||||||
BsClockHistory,
|
BsClockHistory,
|
||||||
@@ -12,27 +12,28 @@ import {
|
|||||||
BsCloudFill,
|
BsCloudFill,
|
||||||
BsCurrencyDollar,
|
BsCurrencyDollar,
|
||||||
BsClipboardData,
|
BsClipboardData,
|
||||||
|
BsFileLock,
|
||||||
} from "react-icons/bs";
|
} from "react-icons/bs";
|
||||||
import {RiLogoutBoxFill} from "react-icons/ri";
|
import { RiLogoutBoxFill } from "react-icons/ri";
|
||||||
import {SlPencil} from "react-icons/sl";
|
import { SlPencil } from "react-icons/sl";
|
||||||
import {FaAward} from "react-icons/fa";
|
import { FaAward } from "react-icons/fa";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import {useRouter} from "next/router";
|
import { useRouter } from "next/router";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import FocusLayer from "@/components/FocusLayer";
|
import FocusLayer from "@/components/FocusLayer";
|
||||||
import {preventNavigation} from "@/utils/navigation.disabled";
|
import { preventNavigation } from "@/utils/navigation.disabled";
|
||||||
import {useEffect, useState} from "react";
|
import { useEffect, useState } from "react";
|
||||||
import usePreferencesStore from "@/stores/preferencesStore";
|
import usePreferencesStore from "@/stores/preferencesStore";
|
||||||
import {Type} from "@/interfaces/user";
|
import { User } from "@/interfaces/user";
|
||||||
import useTicketsListener from "@/hooks/useTicketsListener";
|
import useTicketsListener from "@/hooks/useTicketsListener";
|
||||||
|
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
|
||||||
interface Props {
|
interface Props {
|
||||||
path: string;
|
path: string;
|
||||||
navDisabled?: boolean;
|
navDisabled?: boolean;
|
||||||
focusMode?: boolean;
|
focusMode?: boolean;
|
||||||
onFocusLayerMouseEnter?: () => void;
|
onFocusLayerMouseEnter?: () => void;
|
||||||
className?: string;
|
className?: string;
|
||||||
userType?: Type;
|
user: User;
|
||||||
userId?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface NavProps {
|
interface NavProps {
|
||||||
@@ -45,17 +46,28 @@ interface NavProps {
|
|||||||
badge?: number;
|
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 (
|
return (
|
||||||
<Link
|
<Link
|
||||||
href={!disabled ? keyPath : ""}
|
href={!disabled ? keyPath : ""}
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"flex items-center gap-4 rounded-full p-4 text-gray-500 hover:text-white",
|
"flex items-center gap-4 rounded-full p-4 text-gray-500 hover:text-white",
|
||||||
"transition-all duration-300 ease-in-out relative",
|
"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",
|
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} />
|
<Icon size={24} />
|
||||||
{!isMinimized && <span className="text-lg font-semibold">{label}</span>}
|
{!isMinimized && <span className="text-lg font-semibold">{label}</span>}
|
||||||
{!!badge && badge > 0 && (
|
{!!badge && badge > 0 && (
|
||||||
@@ -63,8 +75,9 @@ const Nav = ({Icon, label, path, keyPath, disabled = false, isMinimized = false,
|
|||||||
className={clsx(
|
className={clsx(
|
||||||
"bg-mti-purple-light h-5 w-5 text-xs rounded-full flex items-center justify-center text-white",
|
"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",
|
"transition ease-in-out duration-300",
|
||||||
isMinimized && "absolute right-0 top-0",
|
isMinimized && "absolute right-0 top-0"
|
||||||
)}>
|
)}
|
||||||
|
>
|
||||||
{badge}
|
{badge}
|
||||||
</div>
|
</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 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 () => {
|
const logout = async () => {
|
||||||
axios.post("/api/logout").finally(() => {
|
axios.post("/api/logout").finally(() => {
|
||||||
@@ -92,12 +115,23 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
|||||||
className={clsx(
|
className={clsx(
|
||||||
"relative flex h-full flex-col justify-between bg-transparent px-4 py-4 pb-8",
|
"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",
|
isMinimized ? "w-fit" : "-xl:w-fit w-1/6",
|
||||||
className,
|
className
|
||||||
)}>
|
)}
|
||||||
|
>
|
||||||
<div className="-xl:hidden flex-col gap-3 xl:flex">
|
<div className="-xl:hidden flex-col gap-3 xl:flex">
|
||||||
<Nav disabled={disableNavigation} Icon={MdSpaceDashboard} label="Dashboard" path={path} keyPath="/" isMinimized={isMinimized} />
|
<Nav
|
||||||
{(userType === "student" || userType === "teacher" || userType === "developer") && (
|
disabled={disableNavigation}
|
||||||
<>
|
Icon={MdSpaceDashboard}
|
||||||
|
label="Dashboard"
|
||||||
|
path={path}
|
||||||
|
keyPath="/"
|
||||||
|
isMinimized={isMinimized}
|
||||||
|
/>
|
||||||
|
{checkAccess(
|
||||||
|
user,
|
||||||
|
["student", "teacher", "developer"],
|
||||||
|
"viewExams"
|
||||||
|
) && (
|
||||||
<Nav
|
<Nav
|
||||||
disabled={disableNavigation}
|
disabled={disableNavigation}
|
||||||
Icon={BsFileEarmarkText}
|
Icon={BsFileEarmarkText}
|
||||||
@@ -106,6 +140,12 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
|||||||
keyPath="/exam"
|
keyPath="/exam"
|
||||||
isMinimized={isMinimized}
|
isMinimized={isMinimized}
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
|
{checkAccess(
|
||||||
|
user,
|
||||||
|
["student", "teacher", "developer"],
|
||||||
|
"viewExercises"
|
||||||
|
) && (
|
||||||
<Nav
|
<Nav
|
||||||
disabled={disableNavigation}
|
disabled={disableNavigation}
|
||||||
Icon={BsPencil}
|
Icon={BsPencil}
|
||||||
@@ -114,15 +154,32 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
|||||||
keyPath="/exercises"
|
keyPath="/exercises"
|
||||||
isMinimized={isMinimized}
|
isMinimized={isMinimized}
|
||||||
/>
|
/>
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
{(userType || "") !== 'agent' && (
|
{checkAccess(user, getTypesOfUser(["agent"]), "viewStats") && (
|
||||||
<>
|
<Nav
|
||||||
<Nav disabled={disableNavigation} Icon={BsGraphUp} label="Stats" path={path} keyPath="/stats" isMinimized={isMinimized} />
|
disabled={disableNavigation}
|
||||||
<Nav disabled={disableNavigation} Icon={BsClockHistory} label="Record" path={path} keyPath="/record" isMinimized={isMinimized} />
|
Icon={BsGraphUp}
|
||||||
</>
|
label="Stats"
|
||||||
|
path={path}
|
||||||
|
keyPath="/stats"
|
||||||
|
isMinimized={isMinimized}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
{["admin", "developer", "agent", "corporate", "mastercorporate"].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
|
<Nav
|
||||||
disabled={disableNavigation}
|
disabled={disableNavigation}
|
||||||
Icon={BsCurrencyDollar}
|
Icon={BsCurrencyDollar}
|
||||||
@@ -132,7 +189,13 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
|||||||
isMinimized={isMinimized}
|
isMinimized={isMinimized}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{["admin", "developer", "corporate", "teacher", "mastercorporate"].includes(userType || "") && (
|
{checkAccess(user, [
|
||||||
|
"admin",
|
||||||
|
"developer",
|
||||||
|
"corporate",
|
||||||
|
"teacher",
|
||||||
|
"mastercorporate",
|
||||||
|
]) && (
|
||||||
<Nav
|
<Nav
|
||||||
disabled={disableNavigation}
|
disabled={disableNavigation}
|
||||||
Icon={BsShieldFill}
|
Icon={BsShieldFill}
|
||||||
@@ -142,7 +205,23 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
|||||||
isMinimized={isMinimized}
|
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
|
<Nav
|
||||||
disabled={disableNavigation}
|
disabled={disableNavigation}
|
||||||
Icon={BsClipboardData}
|
Icon={BsClipboardData}
|
||||||
@@ -153,7 +232,8 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
|||||||
badge={totalAssignedTickets}
|
badge={totalAssignedTickets}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{userType === "developer" && (
|
{checkAccess(user, ["developer"]) && (
|
||||||
|
<>
|
||||||
<Nav
|
<Nav
|
||||||
disabled={disableNavigation}
|
disabled={disableNavigation}
|
||||||
Icon={BsCloudFill}
|
Icon={BsCloudFill}
|
||||||
@@ -162,24 +242,102 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
|||||||
keyPath="/generation"
|
keyPath="/generation"
|
||||||
isMinimized={isMinimized}
|
isMinimized={isMinimized}
|
||||||
/>
|
/>
|
||||||
|
<Nav
|
||||||
|
disabled={disableNavigation}
|
||||||
|
Icon={BsFileLock}
|
||||||
|
label="Permissions"
|
||||||
|
path={path}
|
||||||
|
keyPath="/permissions"
|
||||||
|
isMinimized={isMinimized}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="-xl:flex flex-col gap-3 xl:hidden">
|
<div className="-xl:flex flex-col gap-3 xl:hidden">
|
||||||
<Nav disabled={disableNavigation} Icon={MdSpaceDashboard} label="Dashboard" path={path} keyPath="/" isMinimized={true} />
|
<Nav
|
||||||
<Nav disabled={disableNavigation} Icon={BsFileEarmarkText} label="Exams" path={path} keyPath="/exam" isMinimized={true} />
|
disabled={disableNavigation}
|
||||||
<Nav disabled={disableNavigation} Icon={BsPencil} label="Exercises" path={path} keyPath="/exercises" isMinimized={true} />
|
Icon={MdSpaceDashboard}
|
||||||
{(userType || "") !== 'agent' && (
|
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
|
||||||
<Nav disabled={disableNavigation} Icon={BsClockHistory} label="Record" path={path} keyPath="/record" isMinimized={true} />
|
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>
|
||||||
|
|
||||||
<div className="fixed bottom-12 flex flex-col gap-0">
|
<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}
|
onClick={toggleMinimize}
|
||||||
className={clsx(
|
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",
|
"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 ? "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 ? (
|
||||||
|
<BsChevronBarRight size={24} />
|
||||||
|
) : (
|
||||||
|
<BsChevronBarLeft size={24} />
|
||||||
|
)}
|
||||||
|
{!isMinimized && (
|
||||||
|
<span className="text-lg font-medium">Minimize</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
role="button"
|
role="button"
|
||||||
@@ -200,13 +365,18 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
|||||||
onClick={focusMode ? () => {} : logout}
|
onClick={focusMode ? () => {} : logout}
|
||||||
className={clsx(
|
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",
|
"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} />
|
<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>
|
||||||
</div>
|
</div>
|
||||||
{focusMode && <FocusLayer onFocusLayerMouseEnter={onFocusLayerMouseEnter} />}
|
{focusMode && (
|
||||||
|
<FocusLayer onFocusLayerMouseEnter={onFocusLayerMouseEnter} />
|
||||||
|
)}
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,27 @@
|
|||||||
import useStats from "@/hooks/useStats";
|
import useStats from "@/hooks/useStats";
|
||||||
import {CorporateInformation, CorporateUser, EMPLOYMENT_STATUS, User} from "@/interfaces/user";
|
import {
|
||||||
import {groupBySession, averageScore} from "@/utils/stats";
|
CorporateInformation,
|
||||||
import {RadioGroup} from "@headlessui/react";
|
CorporateUser,
|
||||||
|
EMPLOYMENT_STATUS,
|
||||||
|
User,
|
||||||
|
Type,
|
||||||
|
} from "@/interfaces/user";
|
||||||
|
import { groupBySession, averageScore } from "@/utils/stats";
|
||||||
|
import { RadioGroup } from "@headlessui/react";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import clsx from "clsx";
|
import clsx from "clsx";
|
||||||
import moment from "moment";
|
import moment from "moment";
|
||||||
import {Divider} from "primereact/divider";
|
import { Divider } from "primereact/divider";
|
||||||
import {useEffect, useState} from "react";
|
import { useEffect, useState } from "react";
|
||||||
import ReactDatePicker from "react-datepicker";
|
import ReactDatePicker from "react-datepicker";
|
||||||
import {BsFileEarmarkText, BsPencil, BsPerson, BsPersonAdd, BsStar} from "react-icons/bs";
|
import {
|
||||||
import {toast} from "react-toastify";
|
BsFileEarmarkText,
|
||||||
|
BsPencil,
|
||||||
|
BsPerson,
|
||||||
|
BsPersonAdd,
|
||||||
|
BsStar,
|
||||||
|
} from "react-icons/bs";
|
||||||
|
import { toast } from "react-toastify";
|
||||||
import Button from "./Low/Button";
|
import Button from "./Low/Button";
|
||||||
import Checkbox from "./Low/Checkbox";
|
import Checkbox from "./Low/Checkbox";
|
||||||
import CountrySelect from "./Low/CountrySelect";
|
import CountrySelect from "./Low/CountrySelect";
|
||||||
@@ -17,17 +29,23 @@ import Input from "./Low/Input";
|
|||||||
import ProfileSummary from "./ProfileSummary";
|
import ProfileSummary from "./ProfileSummary";
|
||||||
import Select from "react-select";
|
import Select from "react-select";
|
||||||
import useUsers from "@/hooks/useUsers";
|
import useUsers from "@/hooks/useUsers";
|
||||||
import {USER_TYPE_LABELS} from "@/resources/user";
|
import { USER_TYPE_LABELS } from "@/resources/user";
|
||||||
import {CURRENCIES} from "@/resources/paypal";
|
import { CURRENCIES } from "@/resources/paypal";
|
||||||
import useCodes from "@/hooks/useCodes";
|
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 expirationDateColor = (date: Date) => {
|
||||||
const momentDate = moment(date);
|
const momentDate = moment(date);
|
||||||
const today = moment(new 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(1, "days").isAfter(momentDate))
|
||||||
if (today.add(3, "days").isAfter(momentDate)) return "!bg-mti-rose-ultralight border-mti-rose-light";
|
return "!bg-mti-red-ultralight border-mti-red-light";
|
||||||
if (today.add(7, "days").isAfter(momentDate)) return "!bg-mti-orange-ultralight border-mti-orange-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 {
|
interface Props {
|
||||||
@@ -63,39 +81,86 @@ const USER_TYPE_OPTIONS = Object.keys(USER_TYPE_LABELS).map((type) => ({
|
|||||||
label: USER_TYPE_LABELS[type as keyof typeof USER_TYPE_LABELS],
|
label: USER_TYPE_LABELS[type as keyof typeof USER_TYPE_LABELS],
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const CURRENCIES_OPTIONS = CURRENCIES.map(({label, currency}) => ({
|
const CURRENCIES_OPTIONS = CURRENCIES.map(({ label, currency }) => ({
|
||||||
value: currency,
|
value: currency,
|
||||||
label,
|
label,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers, onViewCorporate, disabled = false, disabledFields = {}}: Props) => {
|
const UserCard = ({
|
||||||
const [expiryDate, setExpiryDate] = useState<Date | null | undefined>(user.subscriptionExpirationDate);
|
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 [type, setType] = useState(user.type);
|
||||||
const [status, setStatus] = useState(user.status);
|
const [status, setStatus] = useState(user.status);
|
||||||
const [referralAgentLabel, setReferralAgentLabel] = useState<string>();
|
const [referralAgentLabel, setReferralAgentLabel] = useState<string>();
|
||||||
const [position, setPosition] = useState<string | undefined>(user.type === "corporate" ? user.demographicInformation?.position : undefined);
|
const [position, setPosition] = useState<string | undefined>(
|
||||||
const [passport_id, setPassportID] = useState<string | undefined>(user.type === "student" ? user.demographicInformation?.passport_id : 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(
|
const [companyName, setCompanyName] = useState(
|
||||||
user.type === "corporate"
|
user.type === "corporate"
|
||||||
? user.corporateInformation?.companyInformation.name
|
? user.corporateInformation?.companyInformation.name
|
||||||
: user.type === "agent"
|
: user.type === "agent"
|
||||||
? user.agentInformation?.companyName
|
? 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(
|
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 [userAmount, setUserAmount] = useState(
|
||||||
const [paymentValue, setPaymentValue] = useState(user.type === "corporate" ? user.corporateInformation?.payment?.value : undefined);
|
user.type === "corporate"
|
||||||
const [paymentCurrency, setPaymentCurrency] = useState(user.type === "corporate" ? user.corporateInformation?.payment?.currency : "EUR");
|
? user.corporateInformation?.companyInformation.userAmount
|
||||||
const [monthlyDuration, setMonthlyDuration] = useState(user.type === "corporate" ? user.corporateInformation?.monthlyDuration : undefined);
|
: undefined
|
||||||
const [commissionValue, setCommission] = useState(user.type === "corporate" ? user.corporateInformation?.payment?.commission : undefined);
|
);
|
||||||
const {stats} = useStats(user.id);
|
const [paymentValue, setPaymentValue] = useState(
|
||||||
const {users} = useUsers();
|
user.type === "corporate"
|
||||||
const {codes} = useCodes(user.id);
|
? 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);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (users && users.length > 0) {
|
if (users && users.length > 0) {
|
||||||
@@ -111,11 +176,14 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
|
|
||||||
const updateUser = () => {
|
const updateUser = () => {
|
||||||
if (user.type === "corporate" && (!paymentValue || paymentValue < 0))
|
if (user.type === "corporate" && (!paymentValue || paymentValue < 0))
|
||||||
return toast.error("Please set a price for the user's package before updating!");
|
return toast.error(
|
||||||
if (!confirm(`Are you sure you want to update ${user.name}'s account?`)) return;
|
"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
|
axios
|
||||||
.post<{user?: User; ok?: boolean}>(`/api/users/update?id=${user.id}`, {
|
.post<{ user?: User; ok?: boolean }>(`/api/users/update?id=${user.id}`, {
|
||||||
...user,
|
...user,
|
||||||
subscriptionExpirationDate: expiryDate,
|
subscriptionExpirationDate: expiryDate,
|
||||||
type,
|
type,
|
||||||
@@ -140,7 +208,9 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
payment: {
|
payment: {
|
||||||
value: paymentValue,
|
value: paymentValue,
|
||||||
currency: paymentCurrency,
|
currency: paymentCurrency,
|
||||||
...(referralAgent === "" ? {} : {commission: commissionValue}),
|
...(referralAgent === ""
|
||||||
|
? {}
|
||||||
|
: { commission: commissionValue }),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
: undefined,
|
: undefined,
|
||||||
@@ -150,13 +220,15 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
onClose(true);
|
onClose(true);
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
toast.error("Something went wrong!", {toastId: "update-error"});
|
toast.error("Something went wrong!", { toastId: "update-error" });
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const generalProfileItems = [
|
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,
|
value: Object.keys(groupBySession(stats)).length,
|
||||||
label: "Exams",
|
label: "Exams",
|
||||||
},
|
},
|
||||||
@@ -176,21 +248,36 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
user.type === "corporate"
|
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,
|
value: codes.length,
|
||||||
label: "Users Used",
|
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,
|
value: user.corporateInformation.companyInformation.userAmount,
|
||||||
label: "Number of Users",
|
label: "Number of Users",
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
: [];
|
: [];
|
||||||
|
|
||||||
|
const updateUserPermission = PERMISSIONS.updateUser[user.type] as {
|
||||||
|
list: Type[];
|
||||||
|
perm: PermissionType;
|
||||||
|
};
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<ProfileSummary user={user} items={user.type === "corporate" ? corporateProfileItems : generalProfileItems} />
|
<ProfileSummary
|
||||||
|
user={user}
|
||||||
|
items={
|
||||||
|
user.type === "corporate"
|
||||||
|
? corporateProfileItems
|
||||||
|
: generalProfileItems
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
{user.type === "agent" && (
|
{user.type === "agent" && (
|
||||||
<>
|
<>
|
||||||
@@ -260,7 +347,9 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
/>
|
/>
|
||||||
<div className="flex flex-col gap-3 w-full lg:col-span-3">
|
<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">
|
<div className="w-full grid grid-cols-6 gap-2">
|
||||||
<Input
|
<Input
|
||||||
name="paymentValue"
|
name="paymentValue"
|
||||||
@@ -273,14 +362,17 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
<Select
|
<Select
|
||||||
className={clsx(
|
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",
|
"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}
|
options={CURRENCIES_OPTIONS}
|
||||||
value={CURRENCIES_OPTIONS.find((c) => c.value === paymentCurrency)}
|
value={CURRENCIES_OPTIONS.find(
|
||||||
|
(c) => c.value === paymentCurrency
|
||||||
|
)}
|
||||||
onChange={(value) => setPaymentCurrency(value?.value)}
|
onChange={(value) => setPaymentCurrency(value?.value)}
|
||||||
menuPortalTarget={document?.body}
|
menuPortalTarget={document?.body}
|
||||||
styles={{
|
styles={{
|
||||||
menuPortal: (base) => ({...base, zIndex: 9999}),
|
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||||
control: (styles) => ({
|
control: (styles) => ({
|
||||||
...styles,
|
...styles,
|
||||||
paddingLeft: "4px",
|
paddingLeft: "4px",
|
||||||
@@ -292,7 +384,11 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
}),
|
}),
|
||||||
option: (styles, state) => ({
|
option: (styles, state) => ({
|
||||||
...styles,
|
...styles,
|
||||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
backgroundColor: state.isFocused
|
||||||
|
? "#D5D9F0"
|
||||||
|
: state.isSelected
|
||||||
|
? "#7872BF"
|
||||||
|
: "white",
|
||||||
color: state.isFocused ? "black" : styles.color,
|
color: state.isFocused ? "black" : styles.color,
|
||||||
}),
|
}),
|
||||||
}}
|
}}
|
||||||
@@ -303,16 +399,22 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
</div>
|
</div>
|
||||||
<div className="flex gap-3 w-full">
|
<div className="flex gap-3 w-full">
|
||||||
<div className="flex flex-col gap-3 w-8/12">
|
<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 && (
|
{referralAgentLabel && (
|
||||||
<Select
|
<Select
|
||||||
className={clsx(
|
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",
|
"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) &&
|
(checkAccess(
|
||||||
"!bg-mti-gray-platinum/40 !text-mti-gray-dim cursor-not-allowed",
|
loggedInUser,
|
||||||
|
getTypesOfUser(["developer", "admin"])
|
||||||
|
) ||
|
||||||
|
disabledFields.countryManager) &&
|
||||||
|
"!bg-mti-gray-platinum/40 !text-mti-gray-dim cursor-not-allowed"
|
||||||
)}
|
)}
|
||||||
options={[
|
options={[
|
||||||
{value: "", label: "No referral"},
|
{ value: "", label: "No referral" },
|
||||||
...users
|
...users
|
||||||
.filter((u) => u.type === "agent")
|
.filter((u) => u.type === "agent")
|
||||||
.map((x) => ({
|
.map((x) => ({
|
||||||
@@ -327,7 +429,7 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
menuPortalTarget={document?.body}
|
menuPortalTarget={document?.body}
|
||||||
onChange={(value) => setReferralAgent(value?.value)}
|
onChange={(value) => setReferralAgent(value?.value)}
|
||||||
styles={{
|
styles={{
|
||||||
menuPortal: (base) => ({...base, zIndex: 9999}),
|
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||||
control: (styles) => ({
|
control: (styles) => ({
|
||||||
...styles,
|
...styles,
|
||||||
paddingLeft: "4px",
|
paddingLeft: "4px",
|
||||||
@@ -339,19 +441,30 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
}),
|
}),
|
||||||
option: (styles, state) => ({
|
option: (styles, state) => ({
|
||||||
...styles,
|
...styles,
|
||||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
backgroundColor: state.isFocused
|
||||||
|
? "#D5D9F0"
|
||||||
|
: state.isSelected
|
||||||
|
? "#7872BF"
|
||||||
|
: "white",
|
||||||
color: state.isFocused ? "black" : styles.color,
|
color: state.isFocused ? "black" : styles.color,
|
||||||
}),
|
}),
|
||||||
}}
|
}}
|
||||||
// editing country manager should only be available for dev/admin
|
// 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>
|
||||||
<div className="flex flex-col gap-3 w-4/12">
|
<div className="flex flex-col gap-3 w-4/12">
|
||||||
{referralAgent !== "" && loggedInUser.type !== "corporate" ? (
|
{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
|
<Input
|
||||||
name="commissionValue"
|
name="commissionValue"
|
||||||
onChange={(e) => setCommission(e ? parseInt(e) : undefined)}
|
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 md:flex-row gap-8 w-full">
|
||||||
<div className="flex flex-col gap-3 w-full">
|
<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">
|
||||||
<CountrySelect disabled value={user.demographicInformation?.country} />
|
Country
|
||||||
|
</label>
|
||||||
|
<CountrySelect
|
||||||
|
disabled
|
||||||
|
value={user.demographicInformation?.country}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<Input
|
<Input
|
||||||
type="tel"
|
type="tel"
|
||||||
@@ -414,31 +532,39 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
label="Passport/National ID"
|
label="Passport/National ID"
|
||||||
onChange={() => null}
|
onChange={() => null}
|
||||||
placeholder="Enter National ID or Passport number"
|
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
|
disabled
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="flex flex-col md:flex-row gap-8 w-full">
|
<div className="flex flex-col md:flex-row gap-8 w-full">
|
||||||
{user.type !== "corporate" && user.type !== 'mastercorporate' && (
|
{user.type !== "corporate" && user.type !== "mastercorporate" && (
|
||||||
<div className="relative flex flex-col gap-3 w-full">
|
<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
|
<RadioGroup
|
||||||
value={user.demographicInformation?.employment}
|
value={user.demographicInformation?.employment}
|
||||||
className="grid grid-cols-2 items-center gap-4 place-items-center"
|
className="grid grid-cols-2 items-center gap-4 place-items-center"
|
||||||
disabled={disabled}>
|
disabled={disabled}
|
||||||
{EMPLOYMENT_STATUS.map(({status, label}) => (
|
>
|
||||||
|
{EMPLOYMENT_STATUS.map(({ status, label }) => (
|
||||||
<RadioGroup.Option value={status} key={status}>
|
<RadioGroup.Option value={status} key={status}>
|
||||||
{({checked}) => (
|
{({ checked }) => (
|
||||||
<span
|
<span
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"px-6 py-4 w-40 md:w-48 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
|
"px-6 py-4 w-40 md:w-48 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
|
||||||
"transition duration-300 ease-in-out",
|
"transition duration-300 ease-in-out",
|
||||||
!checked
|
!checked
|
||||||
? "bg-white border-mti-gray-platinum"
|
? "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}
|
{label}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
@@ -461,49 +587,55 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
)}
|
)}
|
||||||
<div className="flex flex-col gap-8 w-full">
|
<div className="flex flex-col gap-8 w-full">
|
||||||
<div className="relative flex flex-col gap-3 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
|
<RadioGroup
|
||||||
value={user.demographicInformation?.gender}
|
value={user.demographicInformation?.gender}
|
||||||
className="flex flex-row gap-4 justify-between"
|
className="flex flex-row gap-4 justify-between"
|
||||||
disabled={disabled}>
|
disabled={disabled}
|
||||||
|
>
|
||||||
<RadioGroup.Option value="male">
|
<RadioGroup.Option value="male">
|
||||||
{({checked}) => (
|
{({ checked }) => (
|
||||||
<span
|
<span
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
|
"px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
|
||||||
"transition duration-300 ease-in-out",
|
"transition duration-300 ease-in-out",
|
||||||
!checked
|
!checked
|
||||||
? "bg-white border-mti-gray-platinum"
|
? "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
|
Male
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</RadioGroup.Option>
|
</RadioGroup.Option>
|
||||||
<RadioGroup.Option value="female">
|
<RadioGroup.Option value="female">
|
||||||
{({checked}) => (
|
{({ checked }) => (
|
||||||
<span
|
<span
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
|
"px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
|
||||||
"transition duration-300 ease-in-out",
|
"transition duration-300 ease-in-out",
|
||||||
!checked
|
!checked
|
||||||
? "bg-white border-mti-gray-platinum"
|
? "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
|
Female
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</RadioGroup.Option>
|
</RadioGroup.Option>
|
||||||
<RadioGroup.Option value="other">
|
<RadioGroup.Option value="other">
|
||||||
{({checked}) => (
|
{({ checked }) => (
|
||||||
<span
|
<span
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
|
"px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
|
||||||
"transition duration-300 ease-in-out",
|
"transition duration-300 ease-in-out",
|
||||||
!checked
|
!checked
|
||||||
? "bg-white border-mti-gray-platinum"
|
? "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
|
Other
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
@@ -512,11 +644,20 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col gap-3">
|
<div className="flex flex-col gap-3">
|
||||||
<div className="flex justify-between items-center">
|
<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
|
<Checkbox
|
||||||
isChecked={!!expiryDate}
|
isChecked={!!expiryDate}
|
||||||
onChange={(checked) => setExpiryDate(checked ? user.subscriptionExpirationDate || new Date() : null)}
|
onChange={(checked) =>
|
||||||
disabled={disabled}>
|
setExpiryDate(
|
||||||
|
checked
|
||||||
|
? user.subscriptionExpirationDate || new Date()
|
||||||
|
: null
|
||||||
|
)
|
||||||
|
}
|
||||||
|
disabled={disabled}
|
||||||
|
>
|
||||||
Enabled
|
Enabled
|
||||||
</Checkbox>
|
</Checkbox>
|
||||||
</div>
|
</div>
|
||||||
@@ -525,9 +666,12 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
className={clsx(
|
className={clsx(
|
||||||
"p-6 w-full flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
|
"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",
|
"transition duration-300 ease-in-out",
|
||||||
!expiryDate ? "!bg-mti-green-ultralight !border-mti-green-light" : expirationDateColor(expiryDate),
|
!expiryDate
|
||||||
"bg-white border-mti-gray-platinum",
|
? "!bg-mti-green-ultralight !border-mti-green-light"
|
||||||
)}>
|
: expirationDateColor(expiryDate),
|
||||||
|
"bg-white border-mti-gray-platinum"
|
||||||
|
)}
|
||||||
|
>
|
||||||
{!expiryDate && "Unlimited"}
|
{!expiryDate && "Unlimited"}
|
||||||
{expiryDate && moment(expiryDate).format("DD/MM/YYYY")}
|
{expiryDate && moment(expiryDate).format("DD/MM/YYYY")}
|
||||||
</div>
|
</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",
|
"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",
|
"hover:border-mti-purple tooltip",
|
||||||
expirationDateColor(expiryDate),
|
expirationDateColor(expiryDate),
|
||||||
"transition duration-300 ease-in-out",
|
"transition duration-300 ease-in-out"
|
||||||
)}
|
)}
|
||||||
filterDate={(date) =>
|
filterDate={(date) =>
|
||||||
moment(date).isAfter(new Date()) &&
|
moment(date).isAfter(new Date()) &&
|
||||||
(loggedInUser.subscriptionExpirationDate
|
(loggedInUser.subscriptionExpirationDate
|
||||||
? moment(date).isBefore(moment(loggedInUser.subscriptionExpirationDate))
|
? moment(date).isBefore(
|
||||||
|
moment(loggedInUser.subscriptionExpirationDate)
|
||||||
|
)
|
||||||
: true)
|
: true)
|
||||||
}
|
}
|
||||||
dateFormat="dd/MM/yyyy"
|
dateFormat="dd/MM/yyyy"
|
||||||
@@ -555,18 +701,22 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{(loggedInUser.type === "developer" || loggedInUser.type === "admin") && (
|
{checkAccess(loggedInUser, ["developer", "admin"]) && (
|
||||||
<>
|
<>
|
||||||
<Divider className="w-full !m-0" />
|
<Divider className="w-full !m-0" />
|
||||||
<div className="flex flex-col md:flex-row gap-8 w-full">
|
<div className="flex flex-col md:flex-row gap-8 w-full">
|
||||||
<div className="flex flex-col gap-3 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
|
<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"
|
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}
|
options={USER_STATUS_OPTIONS}
|
||||||
menuPortalTarget={document?.body}
|
menuPortalTarget={document?.body}
|
||||||
value={USER_STATUS_OPTIONS.find((o) => o.value === status)}
|
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={{
|
styles={{
|
||||||
control: (styles) => ({
|
control: (styles) => ({
|
||||||
...styles,
|
...styles,
|
||||||
@@ -577,10 +727,14 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
outline: "none",
|
outline: "none",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
menuPortal: (base) => ({...base, zIndex: 9999}),
|
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||||
option: (styles, state) => ({
|
option: (styles, state) => ({
|
||||||
...styles,
|
...styles,
|
||||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
backgroundColor: state.isFocused
|
||||||
|
? "#D5D9F0"
|
||||||
|
: state.isSelected
|
||||||
|
? "#7872BF"
|
||||||
|
: "white",
|
||||||
color: state.isFocused ? "black" : styles.color,
|
color: state.isFocused ? "black" : styles.color,
|
||||||
}),
|
}),
|
||||||
}}
|
}}
|
||||||
@@ -588,13 +742,17 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col gap-3 w-full">
|
<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
|
<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"
|
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}
|
options={USER_TYPE_OPTIONS}
|
||||||
menuPortalTarget={document?.body}
|
menuPortalTarget={document?.body}
|
||||||
value={USER_TYPE_OPTIONS.find((o) => o.value === type)}
|
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={{
|
styles={{
|
||||||
control: (styles) => ({
|
control: (styles) => ({
|
||||||
...styles,
|
...styles,
|
||||||
@@ -605,10 +763,14 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
outline: "none",
|
outline: "none",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
menuPortal: (base) => ({...base, zIndex: 9999}),
|
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||||
option: (styles, state) => ({
|
option: (styles, state) => ({
|
||||||
...styles,
|
...styles,
|
||||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
backgroundColor: state.isFocused
|
||||||
|
? "#D5D9F0"
|
||||||
|
: state.isSelected
|
||||||
|
? "#7872BF"
|
||||||
|
: "white",
|
||||||
color: state.isFocused ? "black" : styles.color,
|
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="flex gap-4 justify-between mt-4 w-full">
|
||||||
<div className="self-start flex gap-4 justify-start items-center w-full">
|
<div className="self-start flex gap-4 justify-start items-center w-full">
|
||||||
{onViewCorporate && ["student", "teacher"].includes(user.type) && (
|
{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
|
View Corporate
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{onViewStudents && ["corporate", "teacher"].includes(user.type) && (
|
{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
|
View Students
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{onViewTeachers && ["student", "corporate"].includes(user.type) && (
|
{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
|
View Teachers
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="self-end flex gap-4 w-full justify-end">
|
<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
|
Close
|
||||||
</Button>
|
</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
|
Update
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -12,25 +12,68 @@ export const PERMISSIONS = {
|
|||||||
developer: ["developer"],
|
developer: ["developer"],
|
||||||
},
|
},
|
||||||
deleteUser: {
|
deleteUser: {
|
||||||
student: ["corporate", "developer", "admin", "mastercorporate"],
|
student: {
|
||||||
teacher: ["corporate", "developer", "admin", "mastercorporate"],
|
perm: "deleteStudent",
|
||||||
corporate: ["admin", "developer"],
|
list: ["corporate", "developer", "admin", "mastercorporate"],
|
||||||
mastercorporate: ["admin", "developer"],
|
},
|
||||||
|
teacher: {
|
||||||
|
perm: "deleteTeacher",
|
||||||
|
list: ["corporate", "developer", "admin", "mastercorporate"],
|
||||||
|
},
|
||||||
|
corporate: {
|
||||||
|
perm: "deleteCorporate",
|
||||||
|
list: ["admin", "developer"],
|
||||||
|
},
|
||||||
|
mastercorporate: {
|
||||||
|
perm: undefined,
|
||||||
|
list: ["admin", "developer"],
|
||||||
|
},
|
||||||
|
|
||||||
admin: ["developer", "admin"],
|
admin: {
|
||||||
agent: ["developer", "admin"],
|
perm: "deleteAdmin",
|
||||||
developer: ["developer"],
|
list: ["developer", "admin"],
|
||||||
|
},
|
||||||
|
agent: {
|
||||||
|
perm: "deleteCountryManager",
|
||||||
|
list: ["developer", "admin"],
|
||||||
|
},
|
||||||
|
developer: {
|
||||||
|
perm: undefined,
|
||||||
|
list: ["developer"],
|
||||||
|
},
|
||||||
},
|
},
|
||||||
updateUser: {
|
updateUser: {
|
||||||
student: ["developer", "admin"],
|
student: {
|
||||||
teacher: ["developer", "admin"],
|
perm: "editStudent",
|
||||||
|
list: ["developer", "admin"],
|
||||||
|
},
|
||||||
|
teacher: {
|
||||||
|
perm: "editTeacher",
|
||||||
|
list: ["developer", "admin"],
|
||||||
|
},
|
||||||
|
|
||||||
corporate: ["admin", "developer"],
|
corporate: {
|
||||||
mastercorporate: ["admin", "developer"],
|
perm: "editCorporate",
|
||||||
|
list: ["admin", "developer"],
|
||||||
|
},
|
||||||
|
mastercorporate: {
|
||||||
|
perm: undefined,
|
||||||
|
list: ["admin", "developer"],
|
||||||
|
},
|
||||||
|
|
||||||
admin: ["developer", "admin"],
|
admin: {
|
||||||
agent: ["developer", "admin"],
|
perm: "editAdmin",
|
||||||
developer: ["developer"],
|
list: ["developer", "admin"],
|
||||||
|
},
|
||||||
|
|
||||||
|
agent: {
|
||||||
|
perm: "editCountryManager",
|
||||||
|
list: ["developer", "admin"],
|
||||||
|
},
|
||||||
|
developer: {
|
||||||
|
perm: undefined,
|
||||||
|
list: ["developer"],
|
||||||
|
},
|
||||||
},
|
},
|
||||||
updateExpiryDate: {
|
updateExpiryDate: {
|
||||||
student: ["developer", "admin"],
|
student: ["developer", "admin"],
|
||||||
|
|||||||
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,5 +1,6 @@
|
|||||||
import { Module } from ".";
|
import { Module } from ".";
|
||||||
import { InstructorGender } from "./exam";
|
import { InstructorGender } from "./exam";
|
||||||
|
import { PermissionType } from "./permissions";
|
||||||
|
|
||||||
export type User =
|
export type User =
|
||||||
| StudentUser
|
| StudentUser
|
||||||
@@ -26,6 +27,7 @@ export interface BasicUser {
|
|||||||
subscriptionExpirationDate?: null | Date;
|
subscriptionExpirationDate?: null | Date;
|
||||||
registrationDate?: Date;
|
registrationDate?: Date;
|
||||||
status: UserStatus;
|
status: UserStatus;
|
||||||
|
permissions: PermissionType[],
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface StudentUser extends BasicUser {
|
export interface StudentUser extends BasicUser {
|
||||||
|
|||||||
@@ -1,47 +1,92 @@
|
|||||||
import Button from "@/components/Low/Button";
|
import Button from "@/components/Low/Button";
|
||||||
import Checkbox from "@/components/Low/Checkbox";
|
import Checkbox from "@/components/Low/Checkbox";
|
||||||
import {PERMISSIONS} from "@/constants/userPermissions";
|
import { PERMISSIONS } from "@/constants/userPermissions";
|
||||||
import useUsers from "@/hooks/useUsers";
|
import useUsers from "@/hooks/useUsers";
|
||||||
import {Type, User} from "@/interfaces/user";
|
import { Type, User } from "@/interfaces/user";
|
||||||
import {USER_TYPE_LABELS} from "@/resources/user";
|
import { USER_TYPE_LABELS } from "@/resources/user";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import clsx from "clsx";
|
import clsx from "clsx";
|
||||||
import {capitalize, uniqBy} from "lodash";
|
import { capitalize, uniqBy } from "lodash";
|
||||||
import moment from "moment";
|
import moment from "moment";
|
||||||
import {useEffect, useState} from "react";
|
import { useEffect, useState } from "react";
|
||||||
import ReactDatePicker from "react-datepicker";
|
import ReactDatePicker from "react-datepicker";
|
||||||
import {toast} from "react-toastify";
|
import { toast } from "react-toastify";
|
||||||
import ShortUniqueId from "short-unique-id";
|
import ShortUniqueId from "short-unique-id";
|
||||||
import {useFilePicker} from "use-file-picker";
|
import { useFilePicker } from "use-file-picker";
|
||||||
import readXlsxFile from "read-excel-file";
|
import readXlsxFile from "read-excel-file";
|
||||||
import Modal from "@/components/Modal";
|
import Modal from "@/components/Modal";
|
||||||
import {BsFileEarmarkEaselFill, BsQuestionCircleFill} from "react-icons/bs";
|
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]: { perm: PermissionType | undefined; list: Type[] };
|
||||||
const USER_TYPE_PERMISSIONS: {[key in Type]: Type[]} = {
|
} = {
|
||||||
student: [],
|
student: {
|
||||||
teacher: [],
|
perm: "createCodeStudent",
|
||||||
agent: [],
|
list: [],
|
||||||
corporate: ["student", "teacher"],
|
},
|
||||||
mastercorporate: ["student", "teacher", "corporate"],
|
teacher: {
|
||||||
admin: ["student", "teacher", "agent", "corporate", "admin", "mastercorporate"],
|
perm: "createCodeTeacher",
|
||||||
developer: ["student", "teacher", "agent", "corporate", "admin", "developer", "mastercorporate"],
|
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}) {
|
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 [isLoading, setIsLoading] = useState(false);
|
||||||
const [expiryDate, setExpiryDate] = useState<Date | null>(
|
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 [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true);
|
||||||
const [type, setType] = useState<Type>("student");
|
const [type, setType] = useState<Type>("student");
|
||||||
const [showHelp, setShowHelp] = useState(false);
|
const [showHelp, setShowHelp] = useState(false);
|
||||||
|
|
||||||
const {users} = useUsers();
|
const { users } = useUsers();
|
||||||
|
|
||||||
const {openFilePicker, filesContent, clear} = useFilePicker({
|
const { openFilePicker, filesContent, clear } = useFilePicker({
|
||||||
accept: ".xlsx",
|
accept: ".xlsx",
|
||||||
multiple: false,
|
multiple: false,
|
||||||
readAs: "ArrayBuffer",
|
readAs: "ArrayBuffer",
|
||||||
@@ -59,7 +104,14 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
|||||||
const information = uniqBy(
|
const information = uniqBy(
|
||||||
rows
|
rows
|
||||||
.map((row) => {
|
.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())
|
return EMAIL_REGEX.test(email.toString().trim())
|
||||||
? {
|
? {
|
||||||
email: email.toString().trim().toLowerCase(),
|
email: email.toString().trim().toLowerCase(),
|
||||||
@@ -69,12 +121,12 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
|||||||
: undefined;
|
: undefined;
|
||||||
})
|
})
|
||||||
.filter((x) => !!x) as typeof infos,
|
.filter((x) => !!x) as typeof infos,
|
||||||
(x) => x.email,
|
(x) => x.email
|
||||||
);
|
);
|
||||||
|
|
||||||
if (information.length === 0) {
|
if (information.length === 0) {
|
||||||
toast.error(
|
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();
|
return clear();
|
||||||
}
|
}
|
||||||
@@ -82,7 +134,7 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
|||||||
setInfos(information);
|
setInfos(information);
|
||||||
} catch {
|
} catch {
|
||||||
toast.error(
|
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();
|
return clear();
|
||||||
}
|
}
|
||||||
@@ -92,24 +144,41 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
|||||||
}, [filesContent]);
|
}, [filesContent]);
|
||||||
|
|
||||||
const generateAndInvite = async () => {
|
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
|
const existingUsers = infos
|
||||||
.filter((x) => users.map((u) => u.email).includes(x.email))
|
.filter((x) => users.map((u) => u.email).includes(x.email))
|
||||||
.map((i) => users.find((u) => u.email === i.email))
|
.map((i) => users.find((u) => u.email === i.email))
|
||||||
.filter((x) => !!x && x.type === "student") as User[];
|
.filter((x) => !!x && x.type === "student") as User[];
|
||||||
|
|
||||||
const newUsersSentence = newUsers.length > 0 ? `generate ${newUsers.length} code(s)` : undefined;
|
const newUsersSentence =
|
||||||
const existingUsersSentence = existingUsers.length > 0 ? `invite ${existingUsers.length} registered student(s)` : undefined;
|
newUsers.length > 0 ? `generate ${newUsers.length} code(s)` : undefined;
|
||||||
|
const existingUsersSentence =
|
||||||
|
existingUsers.length > 0
|
||||||
|
? `invite ${existingUsers.length} registered student(s)`
|
||||||
|
: undefined;
|
||||||
if (
|
if (
|
||||||
!confirm(
|
!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;
|
return;
|
||||||
|
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
Promise.all(existingUsers.map(async (u) => await axios.post(`/api/invites`, {to: u.id, from: user.id})))
|
Promise.all(
|
||||||
.then(() => toast.success(`Successfully invited ${existingUsers.length} registered student(s)!`))
|
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(() => {
|
.finally(() => {
|
||||||
if (newUsers.length === 0) setIsLoading(false);
|
if (newUsers.length === 0) setIsLoading(false);
|
||||||
});
|
});
|
||||||
@@ -124,30 +193,30 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
|||||||
|
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
axios
|
axios
|
||||||
.post<{ok: boolean; valid?: number; reason?: string}>("/api/code", {
|
.post<{ ok: boolean; valid?: number; reason?: string }>("/api/code", {
|
||||||
type,
|
type,
|
||||||
codes,
|
codes,
|
||||||
infos: informations,
|
infos: informations,
|
||||||
expiryDate,
|
expiryDate,
|
||||||
})
|
})
|
||||||
.then(({data, status}) => {
|
.then(({ data, status }) => {
|
||||||
if (data.ok) {
|
if (data.ok) {
|
||||||
toast.success(
|
toast.success(
|
||||||
`Successfully generated${data.valid ? ` ${data.valid}/${informations.length}` : ""} ${capitalize(
|
`Successfully generated${
|
||||||
type,
|
data.valid ? ` ${data.valid}/${informations.length}` : ""
|
||||||
)} codes and they have been notified by e-mail!`,
|
} ${capitalize(type)} codes and they have been notified by e-mail!`,
|
||||||
{toastId: "success"},
|
{ toastId: "success" }
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (status === 403) {
|
if (status === 403) {
|
||||||
toast.error(data.reason, {toastId: "forbidden"});
|
toast.error(data.reason, { toastId: "forbidden" });
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch(({response: {status, data}}) => {
|
.catch(({ response: { status, data } }) => {
|
||||||
if (status === 403) {
|
if (status === 403) {
|
||||||
toast.error(data.reason, {toastId: "forbidden"});
|
toast.error(data.reason, { toastId: "forbidden" });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -163,18 +232,30 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
|||||||
|
|
||||||
return (
|
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">
|
<div className="mt-4 flex flex-col gap-2">
|
||||||
<span>Please upload an Excel file with the following format:</span>
|
<span>Please upload an Excel file with the following format:</span>
|
||||||
<table className="w-full">
|
<table className="w-full">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th className="border border-neutral-200 px-2 py-1">First Name</th>
|
<th className="border border-neutral-200 px-2 py-1">
|
||||||
<th className="border border-neutral-200 px-2 py-1">Last Name</th>
|
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">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">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>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
</table>
|
</table>
|
||||||
@@ -183,27 +264,50 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
|||||||
<ul>
|
<ul>
|
||||||
<li>- All incorrect e-mails will be ignored;</li>
|
<li>- All incorrect e-mails will be ignored;</li>
|
||||||
<li>- All already registered 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>
|
||||||
<li>- All of the e-mails in the file will receive an e-mail to join EnCoach with the role selected below.</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>
|
</ul>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</Modal>
|
</Modal>
|
||||||
<div className="border-mti-gray-platinum flex flex-col gap-4 rounded-xl border p-4">
|
<div className="border-mti-gray-platinum flex flex-col gap-4 rounded-xl border p-4">
|
||||||
<div className="flex items-end justify-between">
|
<div className="flex items-end justify-between">
|
||||||
<label className="text-mti-gray-dim text-base font-normal">Choose an Excel file</label>
|
<label className="text-mti-gray-dim text-base font-normal">
|
||||||
<div className="tooltip cursor-pointer" data-tip="Excel File Format" onClick={() => setShowHelp(true)}>
|
Choose an Excel file
|
||||||
|
</label>
|
||||||
|
<div
|
||||||
|
className="tooltip cursor-pointer"
|
||||||
|
data-tip="Excel File Format"
|
||||||
|
onClick={() => setShowHelp(true)}
|
||||||
|
>
|
||||||
<BsQuestionCircleFill />
|
<BsQuestionCircleFill />
|
||||||
</div>
|
</div>
|
||||||
</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"}
|
{filesContent.length > 0 ? filesContent[0].name : "Choose a file"}
|
||||||
</Button>
|
</Button>
|
||||||
{user && (["developer","admin","corporate", "mastercorporate"].includes(user.type)) && (
|
{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">
|
<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>
|
<label className="text-mti-gray-dim text-base font-normal">
|
||||||
<Checkbox isChecked={isExpiryDateEnabled} onChange={setIsExpiryDateEnabled} disabled={!!user.subscriptionExpirationDate}>
|
Expiry Date
|
||||||
|
</label>
|
||||||
|
<Checkbox
|
||||||
|
isChecked={isExpiryDateEnabled}
|
||||||
|
onChange={setIsExpiryDateEnabled}
|
||||||
|
disabled={!!user.subscriptionExpirationDate}
|
||||||
|
>
|
||||||
Enabled
|
Enabled
|
||||||
</Checkbox>
|
</Checkbox>
|
||||||
</div>
|
</div>
|
||||||
@@ -212,11 +316,13 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
|||||||
className={clsx(
|
className={clsx(
|
||||||
"flex min-h-[70px] w-full cursor-pointer justify-center rounded-full border p-6 text-sm font-normal focus:outline-none",
|
"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",
|
"hover:border-mti-purple tooltip",
|
||||||
"transition duration-300 ease-in-out",
|
"transition duration-300 ease-in-out"
|
||||||
)}
|
)}
|
||||||
filterDate={(date) =>
|
filterDate={(date) =>
|
||||||
moment(date).isAfter(new 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"
|
dateFormat="dd/MM/yyyy"
|
||||||
selected={expiryDate}
|
selected={expiryDate}
|
||||||
@@ -225,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 && (
|
{user && (
|
||||||
<select
|
<select
|
||||||
defaultValue="student"
|
defaultValue="student"
|
||||||
onChange={(e) => setType(e.target.value as typeof user.type)}
|
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)
|
{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) => (
|
.map((type) => (
|
||||||
<option key={type} value={type}>
|
<option key={type} value={type}>
|
||||||
{USER_TYPE_LABELS[type as keyof typeof USER_TYPE_LABELS]}
|
{USER_TYPE_LABELS[type as keyof typeof USER_TYPE_LABELS]}
|
||||||
@@ -240,7 +352,12 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
|||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
)}
|
)}
|
||||||
<Button onClick={generateAndInvite} disabled={infos.length === 0 || (isExpiryDateEnabled ? !expiryDate : false)}>
|
<Button
|
||||||
|
onClick={generateAndInvite}
|
||||||
|
disabled={
|
||||||
|
infos.length === 0 || (isExpiryDateEnabled ? !expiryDate : false)
|
||||||
|
}
|
||||||
|
>
|
||||||
Generate & Send
|
Generate & Send
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,31 +1,73 @@
|
|||||||
import Button from "@/components/Low/Button";
|
import Button from "@/components/Low/Button";
|
||||||
import Checkbox from "@/components/Low/Checkbox";
|
import Checkbox from "@/components/Low/Checkbox";
|
||||||
import {PERMISSIONS} from "@/constants/userPermissions";
|
import { PERMISSIONS } from "@/constants/userPermissions";
|
||||||
import {Type, User} from "@/interfaces/user";
|
import { Type, User } from "@/interfaces/user";
|
||||||
import {USER_TYPE_LABELS} from "@/resources/user";
|
import { USER_TYPE_LABELS } from "@/resources/user";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import clsx from "clsx";
|
import clsx from "clsx";
|
||||||
import {capitalize} from "lodash";
|
import { capitalize } from "lodash";
|
||||||
import moment from "moment";
|
import moment from "moment";
|
||||||
import {useEffect, useState} from "react";
|
import { useEffect, useState } from "react";
|
||||||
import ReactDatePicker from "react-datepicker";
|
import ReactDatePicker from "react-datepicker";
|
||||||
import {toast} from "react-toastify";
|
import { toast } from "react-toastify";
|
||||||
import ShortUniqueId from "short-unique-id";
|
import ShortUniqueId from "short-unique-id";
|
||||||
|
import { checkAccess } from "@/utils/permissions";
|
||||||
|
import { PermissionType } from "@/interfaces/permissions";
|
||||||
|
|
||||||
const USER_TYPE_PERMISSIONS: {[key in Type]: Type[]} = {
|
const USER_TYPE_PERMISSIONS: {
|
||||||
student: [],
|
[key in Type]: { perm: PermissionType | undefined; list: Type[] };
|
||||||
teacher: [],
|
} = {
|
||||||
agent: [],
|
student: {
|
||||||
corporate: ["student", "teacher"],
|
perm: "createCodeStudent",
|
||||||
mastercorporate: ["student", "teacher", "corporate"],
|
list: [],
|
||||||
admin: ["student", "teacher", "agent", "corporate", "admin", "mastercorporate"],
|
},
|
||||||
developer: ["student", "teacher", "agent", "corporate", "admin", "developer","mastercorporate"],
|
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}) {
|
export default function CodeGenerator({ user }: { user: User }) {
|
||||||
const [generatedCode, setGeneratedCode] = useState<string>();
|
const [generatedCode, setGeneratedCode] = useState<string>();
|
||||||
const [expiryDate, setExpiryDate] = useState<Date | null>(
|
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 [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true);
|
||||||
const [type, setType] = useState<Type>("student");
|
const [type, setType] = useState<Type>("student");
|
||||||
@@ -39,38 +81,48 @@ export default function CodeGenerator({user}: {user: User}) {
|
|||||||
const code = uid.randomUUID(6);
|
const code = uid.randomUUID(6);
|
||||||
|
|
||||||
axios
|
axios
|
||||||
.post("/api/code", {type, codes: [code], expiryDate})
|
.post("/api/code", { type, codes: [code], expiryDate })
|
||||||
.then(({data, status}) => {
|
.then(({ data, status }) => {
|
||||||
if (data.ok) {
|
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);
|
setGeneratedCode(code);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (status === 403) {
|
if (status === 403) {
|
||||||
toast.error(data.reason, {toastId: "forbidden"});
|
toast.error(data.reason, { toastId: "forbidden" });
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch(({response: {status, data}}) => {
|
.catch(({ response: { status, data } }) => {
|
||||||
if (status === 403) {
|
if (status === 403) {
|
||||||
toast.error(data.reason, {toastId: "forbidden"});
|
toast.error(data.reason, { toastId: "forbidden" });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
toast.error(`Something went wrong, please try again later!`, {toastId: "error"});
|
toast.error(`Something went wrong, please try again later!`, {
|
||||||
|
toastId: "error",
|
||||||
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-4 border p-4 border-mti-gray-platinum rounded-xl">
|
<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 && (
|
{user && (
|
||||||
<select
|
<select
|
||||||
defaultValue="student"
|
defaultValue="student"
|
||||||
onChange={(e) => setType(e.target.value as typeof user.type)}
|
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)
|
{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) => (
|
.map((type) => (
|
||||||
<option key={type} value={type}>
|
<option key={type} value={type}>
|
||||||
{USER_TYPE_LABELS[type as keyof typeof USER_TYPE_LABELS]}
|
{USER_TYPE_LABELS[type as keyof typeof USER_TYPE_LABELS]}
|
||||||
@@ -78,11 +130,18 @@ export default function CodeGenerator({user}: {user: User}) {
|
|||||||
))}
|
))}
|
||||||
</select>
|
</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">
|
<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>
|
<label className="text-mti-gray-dim text-base font-normal">
|
||||||
<Checkbox isChecked={isExpiryDateEnabled} onChange={setIsExpiryDateEnabled} disabled={!!user.subscriptionExpirationDate}>
|
Expiry Date
|
||||||
|
</label>
|
||||||
|
<Checkbox
|
||||||
|
isChecked={isExpiryDateEnabled}
|
||||||
|
onChange={setIsExpiryDateEnabled}
|
||||||
|
disabled={!!user.subscriptionExpirationDate}
|
||||||
|
>
|
||||||
Enabled
|
Enabled
|
||||||
</Checkbox>
|
</Checkbox>
|
||||||
</div>
|
</div>
|
||||||
@@ -91,11 +150,13 @@ export default function CodeGenerator({user}: {user: User}) {
|
|||||||
className={clsx(
|
className={clsx(
|
||||||
"flex min-h-[70px] w-full cursor-pointer justify-center rounded-full border p-6 text-sm font-normal focus:outline-none",
|
"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",
|
"hover:border-mti-purple tooltip",
|
||||||
"transition duration-300 ease-in-out",
|
"transition duration-300 ease-in-out"
|
||||||
)}
|
)}
|
||||||
filterDate={(date) =>
|
filterDate={(date) =>
|
||||||
moment(date).isAfter(new 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"
|
dateFormat="dd/MM/yyyy"
|
||||||
selected={expiryDate}
|
selected={expiryDate}
|
||||||
@@ -104,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
|
Generate
|
||||||
</Button>
|
</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
|
<div
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
|
"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",
|
"hover:border-mti-purple tooltip",
|
||||||
"transition duration-300 ease-in-out",
|
"transition duration-300 ease-in-out"
|
||||||
)}
|
)}
|
||||||
data-tip="Click to copy"
|
data-tip="Click to copy"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (generatedCode) navigator.clipboard.writeText(generatedCode);
|
if (generatedCode) navigator.clipboard.writeText(generatedCode);
|
||||||
}}>
|
}}
|
||||||
|
>
|
||||||
{generatedCode}
|
{generatedCode}
|
||||||
</div>
|
</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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,7 +43,8 @@ import { useListSearch } from "@/hooks/useListSearch";
|
|||||||
import { getUserCorporate } from "@/utils/groups";
|
import { getUserCorporate } from "@/utils/groups";
|
||||||
import { asyncSorter } from "@/utils";
|
import { asyncSorter } from "@/utils";
|
||||||
import { exportListToExcel, UserListRow } from "@/utils/users";
|
import { exportListToExcel, UserListRow } from "@/utils/users";
|
||||||
|
import { checkAccess } from "@/utils/permissions";
|
||||||
|
import { PermissionType } from "@/interfaces/permissions";
|
||||||
const columnHelper = createColumnHelper<User>();
|
const columnHelper = createColumnHelper<User>();
|
||||||
const searchFields = [
|
const searchFields = [
|
||||||
["name"],
|
["name"],
|
||||||
@@ -92,7 +93,7 @@ export default function UserList({
|
|||||||
|
|
||||||
const { users, reload } = useUsers();
|
const { users, reload } = useUsers();
|
||||||
const { groups } = useGroups(
|
const { groups } = useGroups(
|
||||||
user && (['corporate', 'teacher', 'mastercorporate'].includes(user?.type))
|
user && ["corporate", "teacher", "mastercorporate"].includes(user?.type)
|
||||||
? user.id
|
? user.id
|
||||||
: undefined
|
: undefined
|
||||||
);
|
);
|
||||||
@@ -231,9 +232,21 @@ export default function UserList({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const actionColumn = ({ row }: { row: { original: User } }) => {
|
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 (
|
return (
|
||||||
<div className="flex gap-4">
|
<div className="flex gap-4">
|
||||||
{PERMISSIONS.updateUser[row.original.type]?.includes(user.type) && (
|
{checkAccess(
|
||||||
|
user,
|
||||||
|
updateUserPermission.list,
|
||||||
|
updateUserPermission.perm
|
||||||
|
) && (
|
||||||
<Popover className="relative">
|
<Popover className="relative">
|
||||||
<Popover.Button>
|
<Popover.Button>
|
||||||
<div data-tip="Change Type" className="cursor-pointer tooltip">
|
<div data-tip="Change Type" className="cursor-pointer tooltip">
|
||||||
@@ -297,7 +310,11 @@ export default function UserList({
|
|||||||
</Popover>
|
</Popover>
|
||||||
)}
|
)}
|
||||||
{!row.original.isVerified &&
|
{!row.original.isVerified &&
|
||||||
PERMISSIONS.updateUser[row.original.type]?.includes(user.type) && (
|
checkAccess(
|
||||||
|
user,
|
||||||
|
updateUserPermission.list,
|
||||||
|
updateUserPermission.perm
|
||||||
|
) && (
|
||||||
<div
|
<div
|
||||||
data-tip="Verify User"
|
data-tip="Verify User"
|
||||||
className="cursor-pointer tooltip"
|
className="cursor-pointer tooltip"
|
||||||
@@ -306,7 +323,11 @@ export default function UserList({
|
|||||||
<BsCheck className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
<BsCheck className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{PERMISSIONS.updateUser[row.original.type]?.includes(user.type) && (
|
{checkAccess(
|
||||||
|
user,
|
||||||
|
updateUserPermission.list,
|
||||||
|
updateUserPermission.perm
|
||||||
|
) && (
|
||||||
<div
|
<div
|
||||||
data-tip={
|
data-tip={
|
||||||
row.original.status === "disabled"
|
row.original.status === "disabled"
|
||||||
@@ -323,7 +344,11 @@ export default function UserList({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{PERMISSIONS.deleteUser[row.original.type]?.includes(user.type) && (
|
{checkAccess(
|
||||||
|
user,
|
||||||
|
deleteUserPermission.list,
|
||||||
|
deleteUserPermission.perm
|
||||||
|
) && (
|
||||||
<div
|
<div
|
||||||
data-tip="Delete"
|
data-tip="Delete"
|
||||||
className="cursor-pointer tooltip"
|
className="cursor-pointer tooltip"
|
||||||
|
|||||||
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);
|
||||||
|
}
|
||||||
@@ -1,11 +1,22 @@
|
|||||||
import {PERMISSIONS} from "@/constants/userPermissions";
|
import { PERMISSIONS } from "@/constants/userPermissions";
|
||||||
import {app, adminApp} from "@/firebase";
|
import { app, adminApp } from "@/firebase";
|
||||||
import {Group, User} from "@/interfaces/user";
|
import { Group, User } from "@/interfaces/user";
|
||||||
import {sessionOptions} from "@/lib/session";
|
import { sessionOptions } from "@/lib/session";
|
||||||
import {collection, deleteDoc, doc, getDoc, getDocs, getFirestore, query, setDoc, where} from "firebase/firestore";
|
import {
|
||||||
import {getAuth} from "firebase-admin/auth";
|
collection,
|
||||||
import {withIronSessionApiRoute} from "iron-session/next";
|
deleteDoc,
|
||||||
import {NextApiRequest, NextApiResponse} from "next";
|
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 db = getFirestore(app);
|
||||||
const auth = getAuth(adminApp);
|
const auth = getAuth(adminApp);
|
||||||
@@ -21,15 +32,15 @@ async function user(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
|
|
||||||
async function del(req: NextApiRequest, res: NextApiResponse) {
|
async function del(req: NextApiRequest, res: NextApiResponse) {
|
||||||
if (!req.session.user) {
|
if (!req.session.user) {
|
||||||
res.status(401).json({ok: false});
|
res.status(401).json({ ok: false });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const {id} = req.query as {id: string};
|
const { id } = req.query as { id: string };
|
||||||
|
|
||||||
const docUser = await getDoc(doc(db, "users", req.session.user.id));
|
const docUser = await getDoc(doc(db, "users", req.session.user.id));
|
||||||
if (!docUser.exists()) {
|
if (!docUser.exists()) {
|
||||||
res.status(401).json({ok: false});
|
res.status(401).json({ ok: false });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,46 +48,80 @@ async function del(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
|
|
||||||
const docTargetUser = await getDoc(doc(db, "users", id));
|
const docTargetUser = await getDoc(doc(db, "users", id));
|
||||||
if (!docTargetUser.exists()) {
|
if (!docTargetUser.exists()) {
|
||||||
res.status(404).json({ok: false});
|
res.status(404).json({ ok: false });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const targetUser = {...docTargetUser.data(), id: docTargetUser.id} as User;
|
const targetUser = { ...docTargetUser.data(), id: docTargetUser.id } as User;
|
||||||
|
|
||||||
if (user.type === "corporate" && (targetUser.type === "student" || targetUser.type === "teacher")) {
|
if (
|
||||||
res.json({ok: true});
|
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([
|
await Promise.all([
|
||||||
...userParticipantGroup.docs
|
...userParticipantGroup.docs
|
||||||
.filter((x) => (x.data() as Group).admin === user.id)
|
.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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const permission = PERMISSIONS.deleteUser[targetUser.type];
|
const permission = PERMISSIONS.deleteUser[targetUser.type];
|
||||||
if (!permission.includes(user.type)) {
|
if (!permission.list.includes(user.type)) {
|
||||||
res.status(403).json({ok: false});
|
res.status(403).json({ ok: false });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
res.json({ok: true});
|
res.json({ ok: true });
|
||||||
|
|
||||||
await auth.deleteUser(id);
|
await auth.deleteUser(id);
|
||||||
await deleteDoc(doc(db, "users", id));
|
await deleteDoc(doc(db, "users", id));
|
||||||
const userCodeDocs = await getDocs(query(collection(db, "codes"), where("userId", "==", id)));
|
const userCodeDocs = await getDocs(
|
||||||
const userParticipantGroup = await getDocs(query(collection(db, "groups"), where("participants", "array-contains", id)));
|
query(collection(db, "codes"), where("userId", "==", id))
|
||||||
const userGroupAdminDocs = await getDocs(query(collection(db, "groups"), where("admin", "==", id)));
|
);
|
||||||
const userStatsDocs = await getDocs(query(collection(db, "stats"), where("user", "==", 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([
|
await Promise.all([
|
||||||
...userCodeDocs.docs.map(async (x) => await deleteDoc(x.ref)),
|
...userCodeDocs.docs.map(async (x) => await deleteDoc(x.ref)),
|
||||||
...userGroupAdminDocs.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)),
|
...userStatsDocs.docs.map(async (x) => await deleteDoc(x.ref)),
|
||||||
...userParticipantGroup.docs.map(
|
...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;
|
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();
|
await req.session.save();
|
||||||
|
|
||||||
res.json({...user, id: req.session.user.id});
|
res.json({ ...userWithPermissions, id: req.session.user.id });
|
||||||
} else {
|
} else {
|
||||||
res.status(401).json(undefined);
|
res.status(401).json(undefined);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,19 @@
|
|||||||
/* eslint-disable @next/next/no-img-element */
|
/* eslint-disable @next/next/no-img-element */
|
||||||
import Head from "next/head";
|
import Head from "next/head";
|
||||||
import {withIronSessionSsr} from "iron-session/next";
|
import { withIronSessionSsr } from "iron-session/next";
|
||||||
import {sessionOptions} from "@/lib/session";
|
import { sessionOptions } from "@/lib/session";
|
||||||
import useUser from "@/hooks/useUser";
|
import useUser from "@/hooks/useUser";
|
||||||
import {toast, ToastContainer} from "react-toastify";
|
import { toast, ToastContainer } from "react-toastify";
|
||||||
import Layout from "@/components/High/Layout";
|
import Layout from "@/components/High/Layout";
|
||||||
import {shouldRedirectHome} from "@/utils/navigation.disabled";
|
import { shouldRedirectHome } from "@/utils/navigation.disabled";
|
||||||
import {useState} from "react";
|
import { useState } from "react";
|
||||||
import {Module} from "@/interfaces";
|
import { Module } from "@/interfaces";
|
||||||
import {RadioGroup, Tab} from "@headlessui/react";
|
import { RadioGroup, Tab } from "@headlessui/react";
|
||||||
import clsx from "clsx";
|
import clsx from "clsx";
|
||||||
import {MODULE_ARRAY} from "@/utils/moduleUtils";
|
import { MODULE_ARRAY } from "@/utils/moduleUtils";
|
||||||
import {capitalize} from "lodash";
|
import { capitalize } from "lodash";
|
||||||
import Button from "@/components/Low/Button";
|
import Button from "@/components/Low/Button";
|
||||||
import {Exercise, ReadingPart} from "@/interfaces/exam";
|
import { Exercise, ReadingPart } from "@/interfaces/exam";
|
||||||
import Input from "@/components/Low/Input";
|
import Input from "@/components/Low/Input";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import ReadingGeneration from "./(generation)/ReadingGeneration";
|
import ReadingGeneration from "./(generation)/ReadingGeneration";
|
||||||
@@ -21,8 +21,9 @@ import ListeningGeneration from "./(generation)/ListeningGeneration";
|
|||||||
import WritingGeneration from "./(generation)/WritingGeneration";
|
import WritingGeneration from "./(generation)/WritingGeneration";
|
||||||
import LevelGeneration from "./(generation)/LevelGeneration";
|
import LevelGeneration from "./(generation)/LevelGeneration";
|
||||||
import SpeakingGeneration from "./(generation)/SpeakingGeneration";
|
import SpeakingGeneration from "./(generation)/SpeakingGeneration";
|
||||||
|
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
|
||||||
|
|
||||||
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
export const getServerSideProps = withIronSessionSsr(({ req, res }) => {
|
||||||
const user = req.session.user;
|
const user = req.session.user;
|
||||||
|
|
||||||
if (!user || !user.isVerified) {
|
if (!user || !user.isVerified) {
|
||||||
@@ -30,28 +31,31 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
|||||||
redirect: {
|
redirect: {
|
||||||
destination: "/login",
|
destination: "/login",
|
||||||
permanent: false,
|
permanent: false,
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (shouldRedirectHome(user) || user.type !== "developer") {
|
if (
|
||||||
|
shouldRedirectHome(user) ||
|
||||||
|
checkAccess(user, getTypesOfUser(["developer"]))
|
||||||
|
) {
|
||||||
return {
|
return {
|
||||||
redirect: {
|
redirect: {
|
||||||
destination: "/",
|
destination: "/",
|
||||||
permanent: false,
|
permanent: false,
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
props: {user: req.session.user},
|
props: { user: req.session.user },
|
||||||
};
|
};
|
||||||
}, sessionOptions);
|
}, sessionOptions);
|
||||||
|
|
||||||
export default function Generation() {
|
export default function Generation() {
|
||||||
const [module, setModule] = useState<Module>("reading");
|
const [module, setModule] = useState<Module>("reading");
|
||||||
|
|
||||||
const {user} = useUser({redirectTo: "/login"});
|
const { user } = useUser({ redirectTo: "/login" });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -69,14 +73,17 @@ export default function Generation() {
|
|||||||
<Layout user={user} className="gap-6">
|
<Layout user={user} className="gap-6">
|
||||||
<h1 className="text-2xl font-semibold">Exam Generation</h1>
|
<h1 className="text-2xl font-semibold">Exam Generation</h1>
|
||||||
<div className="flex flex-col gap-3">
|
<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
|
<RadioGroup
|
||||||
value={module}
|
value={module}
|
||||||
onChange={setModule}
|
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) => (
|
{[...MODULE_ARRAY].map((x) => (
|
||||||
<RadioGroup.Option value={x} key={x}>
|
<RadioGroup.Option value={x} key={x}>
|
||||||
{({checked}) => (
|
{({ checked }) => (
|
||||||
<span
|
<span
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"px-6 py-4 w-64 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
|
"px-6 py-4 w-64 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
|
||||||
@@ -100,8 +107,9 @@ export default function Generation() {
|
|||||||
x === "level" &&
|
x === "level" &&
|
||||||
(!checked
|
(!checked
|
||||||
? "bg-white border-mti-gray-platinum"
|
? "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)}
|
{capitalize(x)}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,26 +1,33 @@
|
|||||||
/* eslint-disable @next/next/no-img-element */
|
/* eslint-disable @next/next/no-img-element */
|
||||||
import Head from "next/head";
|
import Head from "next/head";
|
||||||
import Navbar from "@/components/Navbar";
|
import Navbar from "@/components/Navbar";
|
||||||
import {BsFileEarmarkText, BsPencil, BsStar, BsBook, BsHeadphones, BsPen, BsMegaphone} from "react-icons/bs";
|
import {
|
||||||
import {withIronSessionSsr} from "iron-session/next";
|
BsFileEarmarkText,
|
||||||
import {sessionOptions} from "@/lib/session";
|
BsPencil,
|
||||||
import {useEffect, useState} from "react";
|
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 useStats from "@/hooks/useStats";
|
||||||
import {averageScore, groupBySession, totalExams} from "@/utils/stats";
|
import { averageScore, groupBySession, totalExams } from "@/utils/stats";
|
||||||
import useUser from "@/hooks/useUser";
|
import useUser from "@/hooks/useUser";
|
||||||
import Sidebar from "@/components/Sidebar";
|
|
||||||
import Diagnostic from "@/components/Diagnostic";
|
import Diagnostic from "@/components/Diagnostic";
|
||||||
import {ToastContainer} from "react-toastify";
|
import { ToastContainer } from "react-toastify";
|
||||||
import {capitalize} from "lodash";
|
import { capitalize } from "lodash";
|
||||||
import {Module} from "@/interfaces";
|
import { Module } from "@/interfaces";
|
||||||
import ProgressBar from "@/components/Low/ProgressBar";
|
import ProgressBar from "@/components/Low/ProgressBar";
|
||||||
import Layout from "@/components/High/Layout";
|
import Layout from "@/components/High/Layout";
|
||||||
import {calculateAverageLevel} from "@/utils/score";
|
import { calculateAverageLevel } from "@/utils/score";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import DemographicInformationInput from "@/components/DemographicInformationInput";
|
import DemographicInformationInput from "@/components/DemographicInformationInput";
|
||||||
import moment from "moment";
|
import moment from "moment";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import {MODULE_ARRAY} from "@/utils/moduleUtils";
|
import { MODULE_ARRAY } from "@/utils/moduleUtils";
|
||||||
import ProfileSummary from "@/components/ProfileSummary";
|
import ProfileSummary from "@/components/ProfileSummary";
|
||||||
import StudentDashboard from "@/dashboards/Student";
|
import StudentDashboard from "@/dashboards/Student";
|
||||||
import AdminDashboard from "@/dashboards/Admin";
|
import AdminDashboard from "@/dashboards/Admin";
|
||||||
@@ -29,16 +36,22 @@ import TeacherDashboard from "@/dashboards/Teacher";
|
|||||||
import AgentDashboard from "@/dashboards/Agent";
|
import AgentDashboard from "@/dashboards/Agent";
|
||||||
import MasterCorporateDashboard from "@/dashboards/MasterCorporate";
|
import MasterCorporateDashboard from "@/dashboards/MasterCorporate";
|
||||||
import PaymentDue from "./(status)/PaymentDue";
|
import PaymentDue from "./(status)/PaymentDue";
|
||||||
import {useRouter} from "next/router";
|
import { useRouter } from "next/router";
|
||||||
import {PayPalScriptProvider} from "@paypal/react-paypal-js";
|
import { PayPalScriptProvider } from "@paypal/react-paypal-js";
|
||||||
import {CorporateUser, MasterCorporateUser, Type, userTypes} from "@/interfaces/user";
|
import {
|
||||||
|
CorporateUser,
|
||||||
|
MasterCorporateUser,
|
||||||
|
Type,
|
||||||
|
userTypes,
|
||||||
|
} from "@/interfaces/user";
|
||||||
import Select from "react-select";
|
import Select from "react-select";
|
||||||
import {USER_TYPE_LABELS} from "@/resources/user";
|
import { USER_TYPE_LABELS } from "@/resources/user";
|
||||||
|
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
|
||||||
|
|
||||||
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
export const getServerSideProps = withIronSessionSsr(({ req, res }) => {
|
||||||
const user = req.session.user;
|
const user = req.session.user;
|
||||||
|
|
||||||
const envVariables: {[key: string]: string} = {};
|
const envVariables: { [key: string]: string } = {};
|
||||||
Object.keys(process.env)
|
Object.keys(process.env)
|
||||||
.filter((x) => x.startsWith("NEXT_PUBLIC"))
|
.filter((x) => x.startsWith("NEXT_PUBLIC"))
|
||||||
.forEach((x: string) => {
|
.forEach((x: string) => {
|
||||||
@@ -55,21 +68,21 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
props: {user: req.session.user, envVariables},
|
props: { user: req.session.user, envVariables },
|
||||||
};
|
};
|
||||||
}, sessionOptions);
|
}, sessionOptions);
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
user: any;
|
user: any;
|
||||||
envVariables: {[key: string]: string};
|
envVariables: { [key: string]: string };
|
||||||
}
|
}
|
||||||
export default function Home(props: Props) {
|
export default function Home(props: Props) {
|
||||||
const {envVariables} = props;
|
const { envVariables } = props;
|
||||||
const [showDiagnostics, setShowDiagnostics] = useState(false);
|
const [showDiagnostics, setShowDiagnostics] = useState(false);
|
||||||
const [showDemographicInput, setShowDemographicInput] = useState(false);
|
const [showDemographicInput, setShowDemographicInput] = useState(false);
|
||||||
const [selectedScreen, setSelectedScreen] = useState<Type>("admin");
|
const [selectedScreen, setSelectedScreen] = useState<Type>("admin");
|
||||||
|
|
||||||
const {user, mutateUser} = useUser({redirectTo: "/login"});
|
const { user, mutateUser } = useUser({ redirectTo: "/login" });
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -78,7 +91,7 @@ export default function Home(props: Props) {
|
|||||||
!user.demographicInformation ||
|
!user.demographicInformation ||
|
||||||
!user.demographicInformation.country ||
|
!user.demographicInformation.country ||
|
||||||
!user.demographicInformation.gender ||
|
!user.demographicInformation.gender ||
|
||||||
!user.demographicInformation.phone,
|
!user.demographicInformation.phone
|
||||||
);
|
);
|
||||||
setShowDiagnostics(user.isFirstLogin && user.type === "student");
|
setShowDiagnostics(user.isFirstLogin && user.type === "student");
|
||||||
}
|
}
|
||||||
@@ -93,7 +106,12 @@ export default function Home(props: Props) {
|
|||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
||||||
if (user && (user.status === "paymentDue" || user.status === "disabled" || checkIfUserExpired())) {
|
if (
|
||||||
|
user &&
|
||||||
|
(user.status === "paymentDue" ||
|
||||||
|
user.status === "disabled" ||
|
||||||
|
checkIfUserExpired())
|
||||||
|
) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Head>
|
<Head>
|
||||||
@@ -108,12 +126,19 @@ export default function Home(props: Props) {
|
|||||||
{user.status === "disabled" && (
|
{user.status === "disabled" && (
|
||||||
<Layout user={user} navDisabled>
|
<Layout user={user} navDisabled>
|
||||||
<div className="flex flex-col items-center justify-center text-center w-full gap-4">
|
<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 className="font-bold text-lg">
|
||||||
<span>Please contact an administrator if you believe this to be a mistake.</span>
|
Your account has been disabled!
|
||||||
|
</span>
|
||||||
|
<span>
|
||||||
|
Please contact an administrator if you believe this to be a
|
||||||
|
mistake.
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</Layout>
|
</Layout>
|
||||||
)}
|
)}
|
||||||
{(user.status === "paymentDue" || checkIfUserExpired()) && <PaymentDue hasExpired user={user} reload={router.reload} />}
|
{(user.status === "paymentDue" || checkIfUserExpired()) && (
|
||||||
|
<PaymentDue hasExpired user={user} reload={router.reload} />
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -170,24 +195,44 @@ export default function Home(props: Props) {
|
|||||||
<ToastContainer />
|
<ToastContainer />
|
||||||
{user && (
|
{user && (
|
||||||
<Layout user={user}>
|
<Layout user={user}>
|
||||||
{user.type === "student" && <StudentDashboard user={user} />}
|
{checkAccess(user, ["student"]) && <StudentDashboard user={user} />}
|
||||||
{user.type === "teacher" && <TeacherDashboard user={user} />}
|
{checkAccess(user, ["teacher"]) && <TeacherDashboard user={user} />}
|
||||||
{user.type === "corporate" && <CorporateDashboard user={user} />}
|
{checkAccess(user, ["corporate"]) && (
|
||||||
{user.type === "mastercorporate" && <MasterCorporateDashboard user={user} />}
|
<CorporateDashboard user={user as CorporateUser} />
|
||||||
{user.type === "agent" && <AgentDashboard user={user} />}
|
)}
|
||||||
{user.type === "admin" && <AdminDashboard user={user} />}
|
{checkAccess(user, ["mastercorporate"]) && (
|
||||||
{user.type === "developer" && (
|
<MasterCorporateDashboard user={user as MasterCorporateUser} />
|
||||||
|
)}
|
||||||
|
{checkAccess(user, ["agent"]) && <AgentDashboard user={user} />}
|
||||||
|
{checkAccess(user, ["admin"]) && <AdminDashboard user={user} />}
|
||||||
|
{checkAccess(user, ["developer"]) && (
|
||||||
<>
|
<>
|
||||||
<Select
|
<Select
|
||||||
options={userTypes.map((u) => ({value: u, label: USER_TYPE_LABELS[u]}))}
|
options={userTypes.map((u) => ({
|
||||||
value={{value: selectedScreen, label: USER_TYPE_LABELS[selectedScreen]}}
|
value: u,
|
||||||
onChange={(value) => (value ? setSelectedScreen(value.value) : setSelectedScreen("admin"))}
|
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 === "student" && <StudentDashboard user={user} />}
|
||||||
{selectedScreen === "teacher" && <TeacherDashboard user={user} />}
|
{selectedScreen === "teacher" && <TeacherDashboard user={user} />}
|
||||||
{selectedScreen === "corporate" && <CorporateDashboard user={user as unknown as CorporateUser} />}
|
{selectedScreen === "corporate" && (
|
||||||
{selectedScreen === "mastercorporate" && <MasterCorporateDashboard user={user as unknown as MasterCorporateUser} />}
|
<CorporateDashboard user={user as unknown as CorporateUser} />
|
||||||
|
)}
|
||||||
|
{selectedScreen === "mastercorporate" && (
|
||||||
|
<MasterCorporateDashboard
|
||||||
|
user={user as unknown as MasterCorporateUser}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{selectedScreen === "agent" && <AgentDashboard user={user} />}
|
{selectedScreen === "agent" && <AgentDashboard user={user} />}
|
||||||
{selectedScreen === "admin" && <AdminDashboard user={user} />}
|
{selectedScreen === "admin" && <AdminDashboard user={user} />}
|
||||||
</>
|
</>
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
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>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,39 +1,56 @@
|
|||||||
/* eslint-disable @next/next/no-img-element */
|
/* eslint-disable @next/next/no-img-element */
|
||||||
import Head from "next/head";
|
import Head from "next/head";
|
||||||
import {withIronSessionSsr} from "iron-session/next";
|
import { withIronSessionSsr } from "iron-session/next";
|
||||||
import {sessionOptions} from "@/lib/session";
|
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 useUser from "@/hooks/useUser";
|
||||||
import {toast, ToastContainer} from "react-toastify";
|
import { toast, ToastContainer } from "react-toastify";
|
||||||
import Layout from "@/components/High/Layout";
|
import Layout from "@/components/High/Layout";
|
||||||
import Input from "@/components/Low/Input";
|
import Input from "@/components/Low/Input";
|
||||||
import Button from "@/components/Low/Button";
|
import Button from "@/components/Low/Button";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import {ErrorMessage} from "@/constants/errors";
|
import { ErrorMessage } from "@/constants/errors";
|
||||||
import clsx from "clsx";
|
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 CountrySelect from "@/components/Low/CountrySelect";
|
||||||
import {shouldRedirectHome} from "@/utils/navigation.disabled";
|
import { shouldRedirectHome } from "@/utils/navigation.disabled";
|
||||||
import moment from "moment";
|
import moment from "moment";
|
||||||
import {BsCamera, BsQuestionCircleFill} from "react-icons/bs";
|
import { BsCamera, BsQuestionCircleFill } from "react-icons/bs";
|
||||||
import {USER_TYPE_LABELS} from "@/resources/user";
|
import { USER_TYPE_LABELS } from "@/resources/user";
|
||||||
import useGroups from "@/hooks/useGroups";
|
import useGroups from "@/hooks/useGroups";
|
||||||
import useUsers from "@/hooks/useUsers";
|
import useUsers from "@/hooks/useUsers";
|
||||||
import {convertBase64} from "@/utils";
|
import { convertBase64 } from "@/utils";
|
||||||
import {Divider} from "primereact/divider";
|
import { Divider } from "primereact/divider";
|
||||||
import GenderInput from "@/components/High/GenderInput";
|
import GenderInput from "@/components/High/GenderInput";
|
||||||
import EmploymentStatusInput from "@/components/High/EmploymentStatusInput";
|
import EmploymentStatusInput from "@/components/High/EmploymentStatusInput";
|
||||||
import TimezoneSelect from "@/components/Low/TImezoneSelect";
|
import TimezoneSelect from "@/components/Low/TImezoneSelect";
|
||||||
import Modal from "@/components/Modal";
|
import Modal from "@/components/Modal";
|
||||||
import {Module} from "@/interfaces";
|
import { Module } from "@/interfaces";
|
||||||
import ModuleLevelSelector from "@/components/Medium/ModuleLevelSelector";
|
import ModuleLevelSelector from "@/components/Medium/ModuleLevelSelector";
|
||||||
import Select from "@/components/Low/Select";
|
import Select from "@/components/Low/Select";
|
||||||
import {InstructorGender} from "@/interfaces/exam";
|
import { InstructorGender } from "@/interfaces/exam";
|
||||||
import {capitalize} from "lodash";
|
import { capitalize } from "lodash";
|
||||||
import TopicModal from "@/components/Medium/TopicModal";
|
import TopicModal from "@/components/Medium/TopicModal";
|
||||||
import {v4} from "uuid";
|
import { v4 } from "uuid";
|
||||||
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
|
||||||
|
|
||||||
|
export const getServerSideProps = withIronSessionSsr(({ req, res }) => {
|
||||||
const user = req.session.user;
|
const user = req.session.user;
|
||||||
|
|
||||||
if (!user || !user.isVerified) {
|
if (!user || !user.isVerified) {
|
||||||
@@ -55,7 +72,7 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
props: {user: req.session.user},
|
props: { user: req.session.user },
|
||||||
};
|
};
|
||||||
}, sessionOptions);
|
}, sessionOptions);
|
||||||
|
|
||||||
@@ -64,9 +81,11 @@ interface Props {
|
|||||||
mutateUser: Function;
|
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) {
|
function UserProfile({ user, mutateUser }: Props) {
|
||||||
const [bio, setBio] = useState(user.bio || "");
|
const [bio, setBio] = useState(user.bio || "");
|
||||||
const [name, setName] = useState(user.name || "");
|
const [name, setName] = useState(user.name || "");
|
||||||
const [email, setEmail] = useState(user.email || "");
|
const [email, setEmail] = useState(user.email || "");
|
||||||
@@ -75,49 +94,88 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [profilePicture, setProfilePicture] = useState(user.profilePicture);
|
const [profilePicture, setProfilePicture] = useState(user.profilePicture);
|
||||||
|
|
||||||
const [desiredLevels, setDesiredLevels] = useState<{[key in Module]: number} | undefined>(
|
const [desiredLevels, setDesiredLevels] = useState<
|
||||||
["developer", "student"].includes(user.type) ? user.desiredLevels : undefined,
|
{ [key in Module]: number } | undefined
|
||||||
|
>(
|
||||||
|
checkAccess(user, ["developer", "student"]) ? user.desiredLevels : undefined
|
||||||
);
|
);
|
||||||
const [focus, setFocus] = useState<"academic" | "general">(user.focus);
|
const [focus, setFocus] = useState<"academic" | "general">(user.focus);
|
||||||
|
|
||||||
const [country, setCountry] = useState<string>(user.demographicInformation?.country || "");
|
const [country, setCountry] = useState<string>(
|
||||||
const [phone, setPhone] = useState<string>(user.demographicInformation?.phone || "");
|
user.demographicInformation?.country || ""
|
||||||
const [gender, setGender] = useState<Gender | undefined>(user.demographicInformation?.gender || undefined);
|
);
|
||||||
const [employment, setEmployment] = useState<EmploymentStatus | undefined>(
|
const [phone, setPhone] = useState<string>(
|
||||||
user.type === "corporate" || user.type === "mastercorporate" ? undefined : user.demographicInformation?.employment,
|
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>(
|
const [preferredGender, setPreferredGender] = useState<
|
||||||
user.type === "student" || user.type === "developer" ? user.preferredGender || "varied" : undefined,
|
InstructorGender | undefined
|
||||||
|
>(
|
||||||
|
user.type === "student" || user.type === "developer"
|
||||||
|
? user.preferredGender || "varied"
|
||||||
|
: undefined
|
||||||
);
|
);
|
||||||
const [preferredTopics, setPreferredTopics] = useState<string[] | 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 [position, setPosition] = useState<string | undefined>(
|
||||||
const [corporateInformation, setCorporateInformation] = useState(user.type === "corporate" ? user.corporateInformation : undefined);
|
user.type === "corporate"
|
||||||
const [companyName, setCompanyName] = useState<string | undefined>(user.type === "agent" ? user.agentInformation?.companyName : undefined);
|
? user.demographicInformation?.position
|
||||||
const [commercialRegistration, setCommercialRegistration] = useState<string | undefined>(
|
: undefined
|
||||||
user.type === "agent" ? user.agentInformation?.commercialRegistration : 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);
|
const [isPreferredTopicsOpen, setIsPreferredTopicsOpen] = useState(false);
|
||||||
|
|
||||||
const {groups} = useGroups();
|
const { groups } = useGroups();
|
||||||
const {users} = useUsers();
|
const { users } = useUsers();
|
||||||
|
|
||||||
const profilePictureInput = useRef(null);
|
const profilePictureInput = useRef(null);
|
||||||
const expirationDateColor = (date: Date) => {
|
const expirationDateColor = (date: Date) => {
|
||||||
const momentDate = moment(date);
|
const momentDate = moment(date);
|
||||||
const today = moment(new 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(1, "days").isAfter(momentDate))
|
||||||
if (today.add(3, "days").isAfter(momentDate)) return "!bg-mti-rose-ultralight border-mti-rose-light";
|
return "!bg-mti-red-ultralight border-mti-red-light";
|
||||||
if (today.add(7, "days").isAfter(momentDate)) return "!bg-mti-orange-ultralight border-mti-orange-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>) => {
|
const uploadProfilePicture = async (event: ChangeEvent<HTMLInputElement>) => {
|
||||||
@@ -137,15 +195,20 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (newPassword && !password) {
|
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);
|
setIsLoading(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (email !== user?.email) {
|
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 =
|
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?"
|
? "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?";
|
: "Are you sure you want to update your e-mail address?";
|
||||||
|
|
||||||
@@ -176,7 +239,7 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
passport_id,
|
passport_id,
|
||||||
timezone,
|
timezone,
|
||||||
},
|
},
|
||||||
...(user.type === "corporate" ? {corporateInformation} : {}),
|
...(user.type === "corporate" ? { corporateInformation } : {}),
|
||||||
...(user.type === "agent"
|
...(user.type === "agent"
|
||||||
? {
|
? {
|
||||||
agentInformation: {
|
agentInformation: {
|
||||||
@@ -190,7 +253,7 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
.then((response) => {
|
.then((response) => {
|
||||||
if (response.status === 200) {
|
if (response.status === 200) {
|
||||||
toast.success("Your profile has been updated!");
|
toast.success("Your profile has been updated!");
|
||||||
mutateUser((response.data as {user: User}).user);
|
mutateUser((response.data as { user: User }).user);
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -206,7 +269,9 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
|
|
||||||
const ExpirationDate = () => (
|
const ExpirationDate = () => (
|
||||||
<div className="flex flex-col gap-3 w-full">
|
<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
|
<Link
|
||||||
href="/payment"
|
href="/payment"
|
||||||
className={clsx(
|
className={clsx(
|
||||||
@@ -215,22 +280,30 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
!user.subscriptionExpirationDate
|
!user.subscriptionExpirationDate
|
||||||
? "!bg-mti-green-ultralight !border-mti-green-light"
|
? "!bg-mti-green-ultralight !border-mti-green-light"
|
||||||
: expirationDateColor(user.subscriptionExpirationDate),
|
: expirationDateColor(user.subscriptionExpirationDate),
|
||||||
"bg-white border-mti-gray-platinum",
|
"bg-white border-mti-gray-platinum"
|
||||||
)}>
|
)}
|
||||||
|
>
|
||||||
{!user.subscriptionExpirationDate && "Unlimited"}
|
{!user.subscriptionExpirationDate && "Unlimited"}
|
||||||
{user.subscriptionExpirationDate && moment(user.subscriptionExpirationDate).format("DD/MM/YYYY")}
|
{user.subscriptionExpirationDate &&
|
||||||
|
moment(user.subscriptionExpirationDate).format("DD/MM/YYYY")}
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
||||||
const TimezoneInput = () => (
|
const TimezoneInput = () => (
|
||||||
<div className="flex flex-col gap-3 w-full">
|
<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} />
|
<TimezoneSelect value={timezone} onChange={setTimezone} />
|
||||||
</div>
|
</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 (
|
return (
|
||||||
<Layout user={user}>
|
<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 -md:flex-col-reverse -md:items-center w-full justify-between">
|
||||||
<div className="flex flex-col gap-8 w-full md:w-2/3">
|
<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>
|
<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>
|
<DoubleColumnRow>
|
||||||
{user.type !== "corporate" ? (
|
{user.type !== "corporate" ? (
|
||||||
<Input
|
<Input
|
||||||
@@ -335,7 +411,9 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
|
|
||||||
<DoubleColumnRow>
|
<DoubleColumnRow>
|
||||||
<div className="flex flex-col gap-3 w-full">
|
<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} />
|
<CountrySelect value={country} onChange={setCountry} />
|
||||||
</div>
|
</div>
|
||||||
<Input
|
<Input
|
||||||
@@ -368,26 +446,37 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
|
|
||||||
<Divider />
|
<Divider />
|
||||||
|
|
||||||
{desiredLevels && ["developer", "student"].includes(user.type) && (
|
{desiredLevels &&
|
||||||
|
["developer", "student"].includes(user.type) && (
|
||||||
<>
|
<>
|
||||||
<div className="flex flex-col gap-3 w-full">
|
<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
|
<ModuleLevelSelector
|
||||||
levels={desiredLevels}
|
levels={desiredLevels}
|
||||||
setLevels={setDesiredLevels as Dispatch<SetStateAction<{[key in Module]: number}>>}
|
setLevels={
|
||||||
|
setDesiredLevels as Dispatch<
|
||||||
|
SetStateAction<{ [key in Module]: number }>
|
||||||
|
>
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col gap-3 w-full">
|
<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">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-y-4 gap-x-16 w-full">
|
||||||
<button
|
<button
|
||||||
onClick={() => setFocus("academic")}
|
onClick={() => setFocus("academic")}
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"w-full border border-mti-gray-platinum rounded-full px-6 py-4 flex justify-center items-center gap-12 bg-white",
|
"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",
|
"hover:bg-mti-purple-light hover:text-white",
|
||||||
focus === "academic" && "!bg-mti-purple-light !text-white",
|
focus === "academic" &&
|
||||||
"transition duration-300 ease-in-out",
|
"!bg-mti-purple-light !text-white",
|
||||||
)}>
|
"transition duration-300 ease-in-out"
|
||||||
|
)}
|
||||||
|
>
|
||||||
Academic
|
Academic
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
@@ -395,9 +484,11 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
className={clsx(
|
className={clsx(
|
||||||
"w-full border border-mti-gray-platinum rounded-full px-6 py-4 flex justify-center items-center gap-12 bg-white",
|
"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",
|
"hover:bg-mti-purple-light hover:text-white",
|
||||||
focus === "general" && "!bg-mti-purple-light !text-white",
|
focus === "general" &&
|
||||||
"transition duration-300 ease-in-out",
|
"!bg-mti-purple-light !text-white",
|
||||||
)}>
|
"transition duration-300 ease-in-out"
|
||||||
|
)}
|
||||||
|
>
|
||||||
General
|
General
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -405,22 +496,31 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{preferredGender && ["developer", "student"].includes(user.type) && (
|
{preferredGender &&
|
||||||
|
["developer", "student"].includes(user.type) && (
|
||||||
<>
|
<>
|
||||||
<Divider />
|
<Divider />
|
||||||
<DoubleColumnRow>
|
<DoubleColumnRow>
|
||||||
<div className="flex flex-col gap-3 w-full">
|
<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
|
<Select
|
||||||
value={{
|
value={{
|
||||||
value: preferredGender,
|
value: preferredGender,
|
||||||
label: capitalize(preferredGender),
|
label: capitalize(preferredGender),
|
||||||
}}
|
}}
|
||||||
onChange={(value) => (value ? setPreferredGender(value.value as InstructorGender) : null)}
|
onChange={(value) =>
|
||||||
|
value
|
||||||
|
? setPreferredGender(
|
||||||
|
value.value as InstructorGender
|
||||||
|
)
|
||||||
|
: null
|
||||||
|
}
|
||||||
options={[
|
options={[
|
||||||
{value: "male", label: "Male"},
|
{ value: "male", label: "Male" },
|
||||||
{value: "female", label: "Female"},
|
{ value: "female", label: "Female" },
|
||||||
{value: "varied", label: "Varied"},
|
{ value: "varied", label: "Varied" },
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -429,12 +529,18 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
Preferred Topics{" "}
|
Preferred Topics{" "}
|
||||||
<span
|
<span
|
||||||
className="tooltip"
|
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 />
|
<BsQuestionCircleFill />
|
||||||
</span>
|
</span>
|
||||||
</label>
|
</label>
|
||||||
<Button className="w-full" variant="outline" onClick={() => setIsPreferredTopicsOpen(true)}>
|
<Button
|
||||||
Select Topics ({preferredTopics?.length || "All"} selected)
|
className="w-full"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setIsPreferredTopicsOpen(true)}
|
||||||
|
>
|
||||||
|
Select Topics ({preferredTopics?.length || "All"}{" "}
|
||||||
|
selected)
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</DoubleColumnRow>
|
</DoubleColumnRow>
|
||||||
@@ -459,7 +565,9 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
name="companyUsers"
|
name="companyUsers"
|
||||||
onChange={() => null}
|
onChange={() => null}
|
||||||
label="Number of users"
|
label="Number of users"
|
||||||
defaultValue={user.corporateInformation.companyInformation.userAmount}
|
defaultValue={
|
||||||
|
user.corporateInformation.companyInformation.userAmount
|
||||||
|
}
|
||||||
disabled
|
disabled
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
@@ -503,14 +611,20 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{user.type === "corporate" && user.corporateInformation.referralAgent && (
|
{user.type === "corporate" &&
|
||||||
|
user.corporateInformation.referralAgent && (
|
||||||
<>
|
<>
|
||||||
<Divider />
|
<Divider />
|
||||||
<DoubleColumnRow>
|
<DoubleColumnRow>
|
||||||
<Input
|
<Input
|
||||||
name="agentName"
|
name="agentName"
|
||||||
onChange={() => null}
|
onChange={() => null}
|
||||||
defaultValue={users.find((x) => x.id === user.corporateInformation.referralAgent)?.name}
|
defaultValue={
|
||||||
|
users.find(
|
||||||
|
(x) =>
|
||||||
|
x.id === user.corporateInformation.referralAgent
|
||||||
|
)?.name
|
||||||
|
}
|
||||||
type="text"
|
type="text"
|
||||||
label="Country Manager's Name"
|
label="Country Manager's Name"
|
||||||
placeholder="Not available"
|
placeholder="Not available"
|
||||||
@@ -520,7 +634,12 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
<Input
|
<Input
|
||||||
name="agentEmail"
|
name="agentEmail"
|
||||||
onChange={() => null}
|
onChange={() => null}
|
||||||
defaultValue={users.find((x) => x.id === user.corporateInformation.referralAgent)?.email}
|
defaultValue={
|
||||||
|
users.find(
|
||||||
|
(x) =>
|
||||||
|
x.id === user.corporateInformation.referralAgent
|
||||||
|
)?.email
|
||||||
|
}
|
||||||
type="text"
|
type="text"
|
||||||
label="Country Manager's E-mail"
|
label="Country Manager's E-mail"
|
||||||
placeholder="Not available"
|
placeholder="Not available"
|
||||||
@@ -530,11 +649,15 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
</DoubleColumnRow>
|
</DoubleColumnRow>
|
||||||
<DoubleColumnRow>
|
<DoubleColumnRow>
|
||||||
<div className="flex flex-col gap-2 w-full">
|
<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
|
<CountrySelect
|
||||||
value={
|
value={
|
||||||
users.find((x) => x.id === user.corporateInformation.referralAgent)?.demographicInformation
|
users.find(
|
||||||
?.country
|
(x) =>
|
||||||
|
x.id === user.corporateInformation.referralAgent
|
||||||
|
)?.demographicInformation?.country
|
||||||
}
|
}
|
||||||
onChange={() => null}
|
onChange={() => null}
|
||||||
disabled
|
disabled
|
||||||
@@ -548,7 +671,10 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
onChange={() => null}
|
onChange={() => null}
|
||||||
placeholder="Not available"
|
placeholder="Not available"
|
||||||
defaultValue={
|
defaultValue={
|
||||||
users.find((x) => x.id === user.corporateInformation.referralAgent)?.demographicInformation?.phone
|
users.find(
|
||||||
|
(x) =>
|
||||||
|
x.id === user.corporateInformation.referralAgent
|
||||||
|
)?.demographicInformation?.phone
|
||||||
}
|
}
|
||||||
disabled
|
disabled
|
||||||
required
|
required
|
||||||
@@ -559,7 +685,10 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
|
|
||||||
{user.type !== "corporate" && (
|
{user.type !== "corporate" && (
|
||||||
<DoubleColumnRow>
|
<DoubleColumnRow>
|
||||||
<EmploymentStatusInput value={employment} onChange={setEmployment} />
|
<EmploymentStatusInput
|
||||||
|
value={employment}
|
||||||
|
onChange={setEmployment}
|
||||||
|
/>
|
||||||
|
|
||||||
<div className="flex flex-col gap-8 w-full">
|
<div className="flex flex-col gap-8 w-full">
|
||||||
<GenderInput value={gender} onChange={setGender} />
|
<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-6 w-48">
|
||||||
<div
|
<div
|
||||||
className="flex flex-col gap-3 items-center h-fit cursor-pointer group"
|
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="relative overflow-hidden h-48 w-48 rounded-full">
|
||||||
<div
|
<div
|
||||||
className={clsx(
|
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",
|
"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" />
|
<BsCamera className="text-6xl text-mti-purple-ultralight/80" />
|
||||||
</div>
|
</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>
|
</div>
|
||||||
<input type="file" className="hidden" onChange={uploadProfilePicture} accept="image/*" ref={profilePictureInput} />
|
<input
|
||||||
|
type="file"
|
||||||
|
className="hidden"
|
||||||
|
onChange={uploadProfilePicture}
|
||||||
|
accept="image/*"
|
||||||
|
ref={profilePictureInput}
|
||||||
|
/>
|
||||||
<span
|
<span
|
||||||
onClick={() => (profilePictureInput.current as any)?.click()}
|
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
|
Change picture
|
||||||
</span>
|
</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>
|
</div>
|
||||||
{user.type === "agent" && (
|
{user.type === "agent" && (
|
||||||
<div className="flag items-center h-fit">
|
<div className="flag items-center h-fit">
|
||||||
<img
|
<img
|
||||||
alt={user.demographicInformation?.country.toLowerCase() + "_flag"}
|
alt={
|
||||||
|
user.demographicInformation?.country.toLowerCase() + "_flag"
|
||||||
|
}
|
||||||
src={`https://flagcdn.com/w320/${user.demographicInformation?.country.toLowerCase()}.png`}
|
src={`https://flagcdn.com/w320/${user.demographicInformation?.country.toLowerCase()}.png`}
|
||||||
width="320"
|
width="320"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{manualDownloadLink && (
|
{manualDownloadLink && (
|
||||||
<a href={manualDownloadLink} className="max-w-[200px] self-end w-full" download>
|
<a
|
||||||
<Button color="purple" variant="outline" className="max-w-[200px] self-end w-full">
|
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
|
Download Manual
|
||||||
</Button>
|
</Button>
|
||||||
</a>
|
</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">
|
<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">
|
<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
|
Back
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</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
|
Save Changes
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
@@ -635,7 +798,7 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
const {user, mutateUser} = useUser({redirectTo: "/login"});
|
const { user, mutateUser } = useUser({ redirectTo: "/login" });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
|||||||
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[];
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user