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
|
||||||
? {
|
? {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ 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>
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ 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";
|
||||||
@@ -23,16 +24,16 @@ 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,5 +1,11 @@
|
|||||||
import useStats from "@/hooks/useStats";
|
import useStats from "@/hooks/useStats";
|
||||||
import {CorporateInformation, CorporateUser, EMPLOYMENT_STATUS, User} from "@/interfaces/user";
|
import {
|
||||||
|
CorporateInformation,
|
||||||
|
CorporateUser,
|
||||||
|
EMPLOYMENT_STATUS,
|
||||||
|
User,
|
||||||
|
Type,
|
||||||
|
} from "@/interfaces/user";
|
||||||
import { groupBySession, averageScore } from "@/utils/stats";
|
import { groupBySession, averageScore } from "@/utils/stats";
|
||||||
import { RadioGroup } from "@headlessui/react";
|
import { RadioGroup } from "@headlessui/react";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
@@ -8,7 +14,13 @@ 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 {
|
||||||
|
BsFileEarmarkText,
|
||||||
|
BsPencil,
|
||||||
|
BsPerson,
|
||||||
|
BsPersonAdd,
|
||||||
|
BsStar,
|
||||||
|
} from "react-icons/bs";
|
||||||
import { toast } from "react-toastify";
|
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";
|
||||||
@@ -20,14 +32,20 @@ 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 {
|
||||||
@@ -68,31 +86,78 @@ const CURRENCIES_OPTIONS = CURRENCIES.map(({label, 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 [paymentValue, setPaymentValue] = useState(
|
||||||
|
user.type === "corporate"
|
||||||
|
? user.corporateInformation?.payment?.value
|
||||||
|
: undefined
|
||||||
|
);
|
||||||
|
const [paymentCurrency, setPaymentCurrency] = useState(
|
||||||
|
user.type === "corporate"
|
||||||
|
? user.corporateInformation?.payment?.currency
|
||||||
|
: "EUR"
|
||||||
|
);
|
||||||
|
const [monthlyDuration, setMonthlyDuration] = useState(
|
||||||
|
user.type === "corporate"
|
||||||
|
? user.corporateInformation?.monthlyDuration
|
||||||
|
: undefined
|
||||||
|
);
|
||||||
|
const [commissionValue, setCommission] = useState(
|
||||||
|
user.type === "corporate"
|
||||||
|
? user.corporateInformation?.payment?.commission
|
||||||
|
: undefined
|
||||||
);
|
);
|
||||||
const [userAmount, setUserAmount] = useState(user.type === "corporate" ? user.corporateInformation?.companyInformation.userAmount : undefined);
|
|
||||||
const [paymentValue, setPaymentValue] = useState(user.type === "corporate" ? user.corporateInformation?.payment?.value : undefined);
|
|
||||||
const [paymentCurrency, setPaymentCurrency] = useState(user.type === "corporate" ? user.corporateInformation?.payment?.currency : "EUR");
|
|
||||||
const [monthlyDuration, setMonthlyDuration] = useState(user.type === "corporate" ? user.corporateInformation?.monthlyDuration : undefined);
|
|
||||||
const [commissionValue, setCommission] = useState(user.type === "corporate" ? user.corporateInformation?.payment?.commission : undefined);
|
|
||||||
const { stats } = useStats(user.id);
|
const { stats } = useStats(user.id);
|
||||||
const { users } = useUsers();
|
const { users } = useUsers();
|
||||||
const { codes } = useCodes(user.id);
|
const { codes } = useCodes(user.id);
|
||||||
@@ -111,8 +176,11 @@ 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}`, {
|
||||||
@@ -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,
|
||||||
@@ -156,7 +226,9 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
|
|
||||||
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,10 +362,13 @@ 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={{
|
||||||
@@ -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,13 +399,19 @@ 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" },
|
||||||
@@ -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,20 +532,27 @@ 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 }) => (
|
||||||
@@ -437,8 +562,9 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
"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,11 +587,14 @@ 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
|
||||||
@@ -474,8 +603,9 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
"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>
|
||||||
)}
|
)}
|
||||||
@@ -488,8 +618,9 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
"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>
|
||||||
)}
|
)}
|
||||||
@@ -502,8 +633,9 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
"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,
|
||||||
@@ -580,7 +730,11 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
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,
|
||||||
@@ -608,7 +766,11 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers,
|
|||||||
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 {
|
||||||
|
|||||||
@@ -16,24 +16,69 @@ 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");
|
||||||
@@ -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);
|
||||||
});
|
});
|
||||||
@@ -133,10 +202,10 @@ export default function BatchCodeGenerator({user}: {user: User}) {
|
|||||||
.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;
|
||||||
}
|
}
|
||||||
@@ -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>
|
||||||
|
|||||||
@@ -11,21 +11,63 @@ 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");
|
||||||
@@ -42,7 +84,9 @@ export default function CodeGenerator({user}: {user: User}) {
|
|||||||
.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;
|
||||||
}
|
}
|
||||||
@@ -57,20 +101,28 @@ export default function CodeGenerator({user}: {user: User}) {
|
|||||||
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);
|
||||||
|
}
|
||||||
@@ -2,10 +2,21 @@ 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 {
|
||||||
|
collection,
|
||||||
|
deleteDoc,
|
||||||
|
doc,
|
||||||
|
getDoc,
|
||||||
|
getDocs,
|
||||||
|
getFirestore,
|
||||||
|
query,
|
||||||
|
setDoc,
|
||||||
|
where,
|
||||||
|
} from "firebase/firestore";
|
||||||
import { getAuth } from "firebase-admin/auth";
|
import { getAuth } from "firebase-admin/auth";
|
||||||
import { withIronSessionApiRoute } from "iron-session/next";
|
import { withIronSessionApiRoute } from "iron-session/next";
|
||||||
import { NextApiRequest, NextApiResponse } from "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);
|
||||||
@@ -43,21 +54,40 @@ async function del(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
|
|
||||||
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 (
|
||||||
|
user.type === "corporate" &&
|
||||||
|
(targetUser.type === "student" || targetUser.type === "teacher")
|
||||||
|
) {
|
||||||
res.json({ ok: true });
|
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;
|
||||||
}
|
}
|
||||||
@@ -66,17 +96,32 @@ async function del(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
|
|
||||||
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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ 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;
|
||||||
@@ -30,16 +31,19 @@ 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,
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,11 +73,14 @@ 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 }) => (
|
||||||
@@ -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,14 +1,21 @@
|
|||||||
/* 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 {
|
||||||
|
BsFileEarmarkText,
|
||||||
|
BsPencil,
|
||||||
|
BsStar,
|
||||||
|
BsBook,
|
||||||
|
BsHeadphones,
|
||||||
|
BsPen,
|
||||||
|
BsMegaphone,
|
||||||
|
} from "react-icons/bs";
|
||||||
import { withIronSessionSsr } from "iron-session/next";
|
import { withIronSessionSsr } from "iron-session/next";
|
||||||
import { sessionOptions } from "@/lib/session";
|
import { sessionOptions } from "@/lib/session";
|
||||||
import { useEffect, useState } from "react";
|
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";
|
||||||
@@ -31,9 +38,15 @@ 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;
|
||||||
@@ -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} />}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -9,7 +9,15 @@ import {shouldRedirectHome} from "@/utils/navigation.disabled";
|
|||||||
import usePayments from "@/hooks/usePayments";
|
import usePayments from "@/hooks/usePayments";
|
||||||
import usePaypalPayments from "@/hooks/usePaypalPayments";
|
import usePaypalPayments from "@/hooks/usePaypalPayments";
|
||||||
import { Payment, PaypalPayment } from "@/interfaces/paypal";
|
import { Payment, PaypalPayment } from "@/interfaces/paypal";
|
||||||
import {CellContext, createColumnHelper, flexRender, getCoreRowModel, HeaderGroup, Table, useReactTable} from "@tanstack/react-table";
|
import {
|
||||||
|
CellContext,
|
||||||
|
createColumnHelper,
|
||||||
|
flexRender,
|
||||||
|
getCoreRowModel,
|
||||||
|
HeaderGroup,
|
||||||
|
Table,
|
||||||
|
useReactTable,
|
||||||
|
} from "@tanstack/react-table";
|
||||||
import { CURRENCIES } from "@/resources/paypal";
|
import { CURRENCIES } from "@/resources/paypal";
|
||||||
import { BsTrash } from "react-icons/bs";
|
import { BsTrash } from "react-icons/bs";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
@@ -30,6 +38,8 @@ import {toFixedNumber} from "@/utils/number";
|
|||||||
import { CSVLink } from "react-csv";
|
import { CSVLink } from "react-csv";
|
||||||
import { Tab } from "@headlessui/react";
|
import { Tab } from "@headlessui/react";
|
||||||
import { useListSearch } from "@/hooks/useListSearch";
|
import { useListSearch } from "@/hooks/useListSearch";
|
||||||
|
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;
|
||||||
|
|
||||||
@@ -42,7 +52,19 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (shouldRedirectHome(user) || !["admin", "developer", "agent", "corporate", "mastercorporate"].includes(user.type)) {
|
if (
|
||||||
|
shouldRedirectHome(user) ||
|
||||||
|
checkAccess(
|
||||||
|
user,
|
||||||
|
getTypesOfUser([
|
||||||
|
"admin",
|
||||||
|
"developer",
|
||||||
|
"agent",
|
||||||
|
"corporate",
|
||||||
|
"mastercorporate",
|
||||||
|
])
|
||||||
|
)
|
||||||
|
) {
|
||||||
return {
|
return {
|
||||||
redirect: {
|
redirect: {
|
||||||
destination: "/",
|
destination: "/",
|
||||||
@@ -59,7 +81,15 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
|||||||
const columnHelper = createColumnHelper<Payment>();
|
const columnHelper = createColumnHelper<Payment>();
|
||||||
const paypalColumnHelper = createColumnHelper<PaypalPaymentWithUserData>();
|
const paypalColumnHelper = createColumnHelper<PaypalPaymentWithUserData>();
|
||||||
|
|
||||||
const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () => void; reload: () => void; showComission: boolean}) => {
|
const PaymentCreator = ({
|
||||||
|
onClose,
|
||||||
|
reload,
|
||||||
|
showComission = false,
|
||||||
|
}: {
|
||||||
|
onClose: () => void;
|
||||||
|
reload: () => void;
|
||||||
|
showComission: boolean;
|
||||||
|
}) => {
|
||||||
const [corporate, setCorporate] = useState<CorporateUser>();
|
const [corporate, setCorporate] = useState<CorporateUser>();
|
||||||
const [date, setDate] = useState<Date>(new Date());
|
const [date, setDate] = useState<Date>(new Date());
|
||||||
|
|
||||||
@@ -71,7 +101,9 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
|||||||
|
|
||||||
const referralAgent = useMemo(() => {
|
const referralAgent = useMemo(() => {
|
||||||
if (corporate?.corporateInformation?.referralAgent) {
|
if (corporate?.corporateInformation?.referralAgent) {
|
||||||
return users.find((u) => u.id === corporate.corporateInformation.referralAgent);
|
return users.find(
|
||||||
|
(u) => u.id === corporate.corporateInformation.referralAgent
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return undefined;
|
return undefined;
|
||||||
@@ -104,16 +136,24 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
|||||||
<h1 className="text-2xl font-semibold">New Payment</h1>
|
<h1 className="text-2xl font-semibold">New Payment</h1>
|
||||||
<div className="flex flex-col gap-4">
|
<div className="flex flex-col gap-4">
|
||||||
<div className="flex flex-col gap-3">
|
<div className="flex flex-col gap-3">
|
||||||
<label className="font-normal text-base text-mti-gray-dim">Corporate account *</label>
|
<label className="font-normal text-base text-mti-gray-dim">
|
||||||
|
Corporate account *
|
||||||
|
</label>
|
||||||
<Select
|
<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={(users.filter((u) => u.type === "corporate") as CorporateUser[]).map((user) => ({
|
options={(
|
||||||
|
users.filter((u) => u.type === "corporate") as CorporateUser[]
|
||||||
|
).map((user) => ({
|
||||||
value: user.id,
|
value: user.id,
|
||||||
meta: user,
|
meta: user,
|
||||||
label: `${user.corporateInformation?.companyInformation?.name || user.name} - ${user.email}`,
|
label: `${
|
||||||
|
user.corporateInformation?.companyInformation?.name || user.name
|
||||||
|
} - ${user.email}`,
|
||||||
}))}
|
}))}
|
||||||
defaultValue={{ value: "undefined", label: "Select an account" }}
|
defaultValue={{ value: "undefined", label: "Select an account" }}
|
||||||
onChange={(value) => setCorporate((value as any)?.meta ?? undefined)}
|
onChange={(value) =>
|
||||||
|
setCorporate((value as any)?.meta ?? undefined)
|
||||||
|
}
|
||||||
menuPortalTarget={document?.body}
|
menuPortalTarget={document?.body}
|
||||||
styles={{
|
styles={{
|
||||||
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||||
@@ -128,7 +168,11 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
|||||||
}),
|
}),
|
||||||
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,
|
||||||
}),
|
}),
|
||||||
}}
|
}}
|
||||||
@@ -136,9 +180,19 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
|||||||
</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">Price *</label>
|
<label className="font-normal text-base text-mti-gray-dim">
|
||||||
|
Price *
|
||||||
|
</label>
|
||||||
<div className="w-full grid grid-cols-5 gap-2">
|
<div className="w-full grid grid-cols-5 gap-2">
|
||||||
<Input name="paymentValue" onChange={() => {}} type="number" value={price} defaultValue={0} className="col-span-3" disabled />
|
<Input
|
||||||
|
name="paymentValue"
|
||||||
|
onChange={() => {}}
|
||||||
|
type="number"
|
||||||
|
value={price}
|
||||||
|
defaultValue={0}
|
||||||
|
className="col-span-3"
|
||||||
|
disabled
|
||||||
|
/>
|
||||||
<Select
|
<Select
|
||||||
className="px-4 col-span-2 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool bg-mti-gray-platinum/40 text-mti-gray-dim cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none"
|
className="px-4 col-span-2 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool bg-mti-gray-platinum/40 text-mti-gray-dim cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none"
|
||||||
options={CURRENCIES.map(({ label, currency }) => ({
|
options={CURRENCIES.map(({ label, currency }) => ({
|
||||||
@@ -147,12 +201,16 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
|||||||
}))}
|
}))}
|
||||||
defaultValue={{
|
defaultValue={{
|
||||||
value: currency || "EUR",
|
value: currency || "EUR",
|
||||||
label: CURRENCIES.find((c) => c.currency === currency)?.label || "Euro",
|
label:
|
||||||
|
CURRENCIES.find((c) => c.currency === currency)?.label ||
|
||||||
|
"Euro",
|
||||||
}}
|
}}
|
||||||
onChange={() => {}}
|
onChange={() => {}}
|
||||||
value={{
|
value={{
|
||||||
value: currency || "EUR",
|
value: currency || "EUR",
|
||||||
label: CURRENCIES.find((c) => c.currency === currency)?.label || "Euro",
|
label:
|
||||||
|
CURRENCIES.find((c) => c.currency === currency)?.label ||
|
||||||
|
"Euro",
|
||||||
}}
|
}}
|
||||||
menuPortalTarget={document?.body}
|
menuPortalTarget={document?.body}
|
||||||
styles={{
|
styles={{
|
||||||
@@ -168,7 +226,11 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
|||||||
}),
|
}),
|
||||||
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,
|
||||||
}),
|
}),
|
||||||
}}
|
}}
|
||||||
@@ -179,14 +241,27 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
|||||||
{showComission && (
|
{showComission && (
|
||||||
<div className="flex gap-4 w-full">
|
<div className="flex gap-4 w-full">
|
||||||
<div className="flex flex-col w-full gap-3">
|
<div className="flex flex-col w-full gap-3">
|
||||||
<label className="font-normal text-base text-mti-gray-dim">Commission *</label>
|
<label className="font-normal text-base text-mti-gray-dim">
|
||||||
<Input name="commission" onChange={() => {}} type="number" defaultValue={0} value={commission} disabled />
|
Commission *
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
name="commission"
|
||||||
|
onChange={() => {}}
|
||||||
|
type="number"
|
||||||
|
defaultValue={0}
|
||||||
|
value={commission}
|
||||||
|
disabled
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col w-full gap-3">
|
<div className="flex flex-col w-full gap-3">
|
||||||
<label className="font-normal text-base text-mti-gray-dim">Commission Value*</label>
|
<label className="font-normal text-base text-mti-gray-dim">
|
||||||
|
Commission Value*
|
||||||
|
</label>
|
||||||
<Input
|
<Input
|
||||||
name="commissionValue"
|
name="commissionValue"
|
||||||
value={`${(commission! / 100) * price!} ${CURRENCIES.find((c) => c.currency === currency)?.label}`}
|
value={`${(commission! / 100) * price!} ${
|
||||||
|
CURRENCIES.find((c) => c.currency === currency)?.label
|
||||||
|
}`}
|
||||||
onChange={() => null}
|
onChange={() => null}
|
||||||
type="text"
|
type="text"
|
||||||
defaultValue={0}
|
defaultValue={0}
|
||||||
@@ -198,12 +273,14 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
|||||||
|
|
||||||
<div className="flex gap-4">
|
<div className="flex gap-4">
|
||||||
<div className="flex flex-col w-full gap-3">
|
<div className="flex flex-col w-full gap-3">
|
||||||
<label className="font-normal text-base text-mti-gray-dim">Date *</label>
|
<label className="font-normal text-base text-mti-gray-dim">
|
||||||
|
Date *
|
||||||
|
</label>
|
||||||
<ReactDatePicker
|
<ReactDatePicker
|
||||||
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"
|
||||||
)}
|
)}
|
||||||
dateFormat="dd/MM/yyyy"
|
dateFormat="dd/MM/yyyy"
|
||||||
selected={moment(date).toDate()}
|
selected={moment(date).toDate()}
|
||||||
@@ -212,10 +289,16 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-col w-full gap-3">
|
<div className="flex flex-col w-full gap-3">
|
||||||
<label className="font-normal text-base text-mti-gray-dim">Country Manager *</label>
|
<label className="font-normal text-base text-mti-gray-dim">
|
||||||
|
Country Manager *
|
||||||
|
</label>
|
||||||
<Input
|
<Input
|
||||||
name="referralAgent"
|
name="referralAgent"
|
||||||
value={referralAgent ? `${referralAgent.name} - ${referralAgent.email}` : "No country manager"}
|
value={
|
||||||
|
referralAgent
|
||||||
|
? `${referralAgent.name} - ${referralAgent.email}`
|
||||||
|
: "No country manager"
|
||||||
|
}
|
||||||
onChange={() => null}
|
onChange={() => null}
|
||||||
type="text"
|
type="text"
|
||||||
defaultValue={"No country manager"}
|
defaultValue={"No country manager"}
|
||||||
@@ -224,10 +307,19 @@ const PaymentCreator = ({onClose, reload, showComission = false}: {onClose: () =
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex w-full justify-end items-center gap-8 mt-4">
|
<div className="flex w-full justify-end items-center gap-8 mt-4">
|
||||||
<Button variant="outline" color="red" className="w-full max-w-[200px]" onClick={onClose}>
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
color="red"
|
||||||
|
className="w-full max-w-[200px]"
|
||||||
|
onClick={onClose}
|
||||||
|
>
|
||||||
Cancel
|
Cancel
|
||||||
</Button>
|
</Button>
|
||||||
<Button className="w-full max-w-[200px]" onClick={submit} disabled={!corporate || !price}>
|
<Button
|
||||||
|
className="w-full max-w-[200px]"
|
||||||
|
onClick={submit}
|
||||||
|
disabled={!corporate || !price}
|
||||||
|
>
|
||||||
Submit
|
Submit
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
@@ -266,9 +358,26 @@ const IS_FILE_SUBMITTED_OPTIONS = [
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const CSV_PAYMENTS_WHITELISTED_KEYS = ["corporateId", "corporate", "date", "amount", "agent", "agentCommission", "agentValue", "isPaid"];
|
const CSV_PAYMENTS_WHITELISTED_KEYS = [
|
||||||
|
"corporateId",
|
||||||
|
"corporate",
|
||||||
|
"date",
|
||||||
|
"amount",
|
||||||
|
"agent",
|
||||||
|
"agentCommission",
|
||||||
|
"agentValue",
|
||||||
|
"isPaid",
|
||||||
|
];
|
||||||
|
|
||||||
const CSV_PAYPAL_WHITELISTED_KEYS = ["orderId", "status", "name", "email", "value", "createdAt", "subscriptionExpirationDate"];
|
const CSV_PAYPAL_WHITELISTED_KEYS = [
|
||||||
|
"orderId",
|
||||||
|
"status",
|
||||||
|
"name",
|
||||||
|
"email",
|
||||||
|
"value",
|
||||||
|
"createdAt",
|
||||||
|
"subscriptionExpirationDate",
|
||||||
|
];
|
||||||
|
|
||||||
interface SimpleCSVColumn {
|
interface SimpleCSVColumn {
|
||||||
key: string;
|
key: string;
|
||||||
@@ -286,7 +395,9 @@ export default function PaymentRecord() {
|
|||||||
const [selectedCorporateUser, setSelectedCorporateUser] = useState<User>();
|
const [selectedCorporateUser, setSelectedCorporateUser] = useState<User>();
|
||||||
const [selectedAgentUser, setSelectedAgentUser] = useState<User>();
|
const [selectedAgentUser, setSelectedAgentUser] = useState<User>();
|
||||||
const [isCreatingPayment, setIsCreatingPayment] = useState(false);
|
const [isCreatingPayment, setIsCreatingPayment] = useState(false);
|
||||||
const [filters, setFilters] = useState<{filter: (p: Payment) => boolean; id: string}[]>([]);
|
const [filters, setFilters] = useState<
|
||||||
|
{ filter: (p: Payment) => boolean; id: string }[]
|
||||||
|
>([]);
|
||||||
const [displayPayments, setDisplayPayments] = useState<Payment[]>([]);
|
const [displayPayments, setDisplayPayments] = useState<Payment[]>([]);
|
||||||
|
|
||||||
const [corporate, setCorporate] = useState<User>();
|
const [corporate, setCorporate] = useState<User>();
|
||||||
@@ -295,12 +406,21 @@ export default function PaymentRecord() {
|
|||||||
const { user } = useUser({ redirectTo: "/login" });
|
const { user } = useUser({ redirectTo: "/login" });
|
||||||
const { users, reload: reloadUsers } = useUsers();
|
const { users, reload: reloadUsers } = useUsers();
|
||||||
const { payments: originalPayments, reload: reloadPayment } = usePayments();
|
const { payments: originalPayments, reload: reloadPayment } = usePayments();
|
||||||
const {payments: paypalPayments, reload: reloadPaypalPayment} = usePaypalPayments();
|
const { payments: paypalPayments, reload: reloadPaypalPayment } =
|
||||||
const [startDate, setStartDate] = useState<Date | null>(moment("01/01/2023").toDate());
|
usePaypalPayments();
|
||||||
const [endDate, setEndDate] = useState<Date | null>(moment().endOf("day").toDate());
|
const [startDate, setStartDate] = useState<Date | null>(
|
||||||
|
moment("01/01/2023").toDate()
|
||||||
|
);
|
||||||
|
const [endDate, setEndDate] = useState<Date | null>(
|
||||||
|
moment().endOf("day").toDate()
|
||||||
|
);
|
||||||
const [paid, setPaid] = useState<Boolean | null>(IS_PAID_OPTIONS[0].value);
|
const [paid, setPaid] = useState<Boolean | null>(IS_PAID_OPTIONS[0].value);
|
||||||
const [commissionTransfer, setCommissionTransfer] = useState<Boolean | null>(IS_FILE_SUBMITTED_OPTIONS[0].value);
|
const [commissionTransfer, setCommissionTransfer] = useState<Boolean | null>(
|
||||||
const [corporateTransfer, setCorporateTransfer] = useState<Boolean | null>(IS_FILE_SUBMITTED_OPTIONS[0].value);
|
IS_FILE_SUBMITTED_OPTIONS[0].value
|
||||||
|
);
|
||||||
|
const [corporateTransfer, setCorporateTransfer] = useState<Boolean | null>(
|
||||||
|
IS_FILE_SUBMITTED_OPTIONS[0].value
|
||||||
|
);
|
||||||
const reload = () => {
|
const reload = () => {
|
||||||
reloadUsers();
|
reloadUsers();
|
||||||
reloadPayment();
|
reloadPayment();
|
||||||
@@ -320,7 +440,7 @@ export default function PaymentRecord() {
|
|||||||
filters
|
filters
|
||||||
.map((f) => f.filter)
|
.map((f) => f.filter)
|
||||||
.reduce((d, f) => d.filter(f), payments)
|
.reduce((d, f) => d.filter(f), payments)
|
||||||
.sort((a, b) => moment(b.date).diff(moment(a.date))),
|
.sort((a, b) => moment(b.date).diff(moment(a.date)))
|
||||||
);
|
);
|
||||||
}, [payments, filters]);
|
}, [payments, filters]);
|
||||||
|
|
||||||
@@ -361,7 +481,9 @@ export default function PaymentRecord() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setFilters((prev) => [
|
setFilters((prev) => [
|
||||||
...prev.filter((x) => x.id !== "paid"),
|
...prev.filter((x) => x.id !== "paid"),
|
||||||
...(typeof paid !== "boolean" ? [] : [{id: "paid", filter: (p: Payment) => p.isPaid === paid}]),
|
...(typeof paid !== "boolean"
|
||||||
|
? []
|
||||||
|
: [{ id: "paid", filter: (p: Payment) => p.isPaid === paid }]),
|
||||||
]);
|
]);
|
||||||
}, [paid]);
|
}, [paid]);
|
||||||
|
|
||||||
@@ -373,7 +495,8 @@ export default function PaymentRecord() {
|
|||||||
: [
|
: [
|
||||||
{
|
{
|
||||||
id: "commissionTransfer",
|
id: "commissionTransfer",
|
||||||
filter: (p: Payment) => !p.commissionTransfer === commissionTransfer,
|
filter: (p: Payment) =>
|
||||||
|
!p.commissionTransfer === commissionTransfer,
|
||||||
},
|
},
|
||||||
]),
|
]),
|
||||||
]);
|
]);
|
||||||
@@ -387,7 +510,8 @@ export default function PaymentRecord() {
|
|||||||
: [
|
: [
|
||||||
{
|
{
|
||||||
id: "corporateTransfer",
|
id: "corporateTransfer",
|
||||||
filter: (p: Payment) => !p.corporateTransfer === corporateTransfer,
|
filter: (p: Payment) =>
|
||||||
|
!p.corporateTransfer === corporateTransfer,
|
||||||
},
|
},
|
||||||
]),
|
]),
|
||||||
]);
|
]);
|
||||||
@@ -418,7 +542,9 @@ export default function PaymentRecord() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (reason.response.status === 403) {
|
if (reason.response.status === 403) {
|
||||||
toast.error("You do not have permission to delete an approved payment record!");
|
toast.error(
|
||||||
|
"You do not have permission to delete an approved payment record!"
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -429,7 +555,8 @@ export default function PaymentRecord() {
|
|||||||
|
|
||||||
const getFileAssetsColumns = () => {
|
const getFileAssetsColumns = () => {
|
||||||
if (user) {
|
if (user) {
|
||||||
const containerClassName = "flex gap-2 text-mti-purple-light hover:text-mti-purple-dark ease-in-out duration-300 cursor-pointer";
|
const containerClassName =
|
||||||
|
"flex gap-2 text-mti-purple-light hover:text-mti-purple-dark ease-in-out duration-300 cursor-pointer";
|
||||||
switch (user.type) {
|
switch (user.type) {
|
||||||
case "corporate":
|
case "corporate":
|
||||||
return [
|
return [
|
||||||
@@ -548,7 +675,9 @@ export default function PaymentRecord() {
|
|||||||
return { value: `${value}%` };
|
return { value: `${value}%` };
|
||||||
}
|
}
|
||||||
case "agent": {
|
case "agent": {
|
||||||
const user = users.find((x) => x.id === info.row.original.agent) as AgentUser;
|
const user = users.find(
|
||||||
|
(x) => x.id === info.row.original.agent
|
||||||
|
) as AgentUser;
|
||||||
return {
|
return {
|
||||||
value: user?.name,
|
value: user?.name,
|
||||||
user,
|
user,
|
||||||
@@ -569,7 +698,8 @@ export default function PaymentRecord() {
|
|||||||
const user = users.find((x) => x.id === specificValue) as CorporateUser;
|
const user = users.find((x) => x.id === specificValue) as CorporateUser;
|
||||||
return {
|
return {
|
||||||
user,
|
user,
|
||||||
value: user?.corporateInformation.companyInformation.name || user?.name,
|
value:
|
||||||
|
user?.corporateInformation.companyInformation.name || user?.name,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
case "currency": {
|
case "currency": {
|
||||||
@@ -597,9 +727,10 @@ export default function PaymentRecord() {
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer",
|
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer"
|
||||||
)}
|
)}
|
||||||
onClick={() => setSelectedAgentUser(user)}>
|
onClick={() => setSelectedAgentUser(user)}
|
||||||
|
>
|
||||||
{value}
|
{value}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -643,9 +774,10 @@ export default function PaymentRecord() {
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer",
|
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer"
|
||||||
)}
|
)}
|
||||||
onClick={() => setSelectedCorporateUser(user)}>
|
onClick={() => setSelectedCorporateUser(user)}
|
||||||
|
>
|
||||||
{value}
|
{value}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -664,7 +796,9 @@ export default function PaymentRecord() {
|
|||||||
id: "amount",
|
id: "amount",
|
||||||
cell: (info) => {
|
cell: (info) => {
|
||||||
const { value } = columHelperValue(info.column.id, info);
|
const { value } = columHelperValue(info.column.id, info);
|
||||||
const currency = CURRENCIES.find((x) => x.currency === info.row.original.currency)?.label;
|
const currency = CURRENCIES.find(
|
||||||
|
(x) => x.currency === info.row.original.currency
|
||||||
|
)?.label;
|
||||||
const finalValue = `${value} ${currency}`;
|
const finalValue = `${value} ${currency}`;
|
||||||
return <span>{finalValue}</span>;
|
return <span>{finalValue}</span>;
|
||||||
},
|
},
|
||||||
@@ -680,13 +814,23 @@ export default function PaymentRecord() {
|
|||||||
<Checkbox
|
<Checkbox
|
||||||
isChecked={value}
|
isChecked={value}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
if (user?.type === agent || user?.type === "corporate" || value) return null;
|
if (user?.type === agent || user?.type === "corporate" || value)
|
||||||
if (!info.row.original.commissionTransfer || !info.row.original.corporateTransfer)
|
return null;
|
||||||
return alert("All files need to be uploaded to consider it paid!");
|
if (
|
||||||
if (!confirm(`Are you sure you want to consider this payment paid?`)) return null;
|
!info.row.original.commissionTransfer ||
|
||||||
|
!info.row.original.corporateTransfer
|
||||||
|
)
|
||||||
|
return alert(
|
||||||
|
"All files need to be uploaded to consider it paid!"
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
!confirm(`Are you sure you want to consider this payment paid?`)
|
||||||
|
)
|
||||||
|
return null;
|
||||||
|
|
||||||
return updatePayment(info.row.original, "isPaid", e);
|
return updatePayment(info.row.original, "isPaid", e);
|
||||||
}}>
|
}}
|
||||||
|
>
|
||||||
<span></span>
|
<span></span>
|
||||||
</Checkbox>
|
</Checkbox>
|
||||||
);
|
);
|
||||||
@@ -700,7 +844,11 @@ export default function PaymentRecord() {
|
|||||||
return (
|
return (
|
||||||
<div className="flex gap-4">
|
<div className="flex gap-4">
|
||||||
{user?.type !== "agent" && (
|
{user?.type !== "agent" && (
|
||||||
<div data-tip="Delete" className="cursor-pointer tooltip" onClick={() => deletePayment(row.original.id)}>
|
<div
|
||||||
|
data-tip="Delete"
|
||||||
|
className="cursor-pointer tooltip"
|
||||||
|
onClick={() => deletePayment(row.original.id)}
|
||||||
|
>
|
||||||
<BsTrash className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
<BsTrash className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -722,7 +870,7 @@ export default function PaymentRecord() {
|
|||||||
const user = users.find((x) => x.id === p.userId) as User;
|
const user = users.find((x) => x.id === p.userId) as User;
|
||||||
return { ...p, name: user?.name, email: user?.email };
|
return { ...p, name: user?.name, email: user?.email };
|
||||||
}),
|
}),
|
||||||
[paypalPayments, users],
|
[paypalPayments, users]
|
||||||
);
|
);
|
||||||
|
|
||||||
const paypalColumns = [
|
const paypalColumns = [
|
||||||
@@ -785,10 +933,15 @@ export default function PaymentRecord() {
|
|||||||
}),
|
}),
|
||||||
];
|
];
|
||||||
|
|
||||||
const {rows: filteredRows, renderSearch} = useListSearch(paypalFilterRows, updatedPaypalPayments);
|
const { rows: filteredRows, renderSearch } = useListSearch(
|
||||||
|
paypalFilterRows,
|
||||||
|
updatedPaypalPayments
|
||||||
|
);
|
||||||
|
|
||||||
const paypalTable = useReactTable({
|
const paypalTable = useReactTable({
|
||||||
data: filteredRows.sort((a, b) => moment(b.createdAt).diff(moment(a.createdAt), "second")),
|
data: filteredRows.sort((a, b) =>
|
||||||
|
moment(b.createdAt).diff(moment(a.createdAt), "second")
|
||||||
|
),
|
||||||
columns: paypalColumns,
|
columns: paypalColumns,
|
||||||
getCoreRowModel: getCoreRowModel(),
|
getCoreRowModel: getCoreRowModel(),
|
||||||
});
|
});
|
||||||
@@ -797,7 +950,10 @@ export default function PaymentRecord() {
|
|||||||
if (user) {
|
if (user) {
|
||||||
if (selectedCorporateUser) {
|
if (selectedCorporateUser) {
|
||||||
return (
|
return (
|
||||||
<Modal isOpen={!!selectedCorporateUser} onClose={() => setSelectedCorporateUser(undefined)}>
|
<Modal
|
||||||
|
isOpen={!!selectedCorporateUser}
|
||||||
|
onClose={() => setSelectedCorporateUser(undefined)}
|
||||||
|
>
|
||||||
<>
|
<>
|
||||||
{selectedCorporateUser && (
|
{selectedCorporateUser && (
|
||||||
<div className="w-full flex flex-col gap-8">
|
<div className="w-full flex flex-col gap-8">
|
||||||
@@ -820,7 +976,10 @@ export default function PaymentRecord() {
|
|||||||
|
|
||||||
if (selectedAgentUser) {
|
if (selectedAgentUser) {
|
||||||
return (
|
return (
|
||||||
<Modal isOpen={!!selectedAgentUser} onClose={() => setSelectedAgentUser(undefined)}>
|
<Modal
|
||||||
|
isOpen={!!selectedAgentUser}
|
||||||
|
onClose={() => setSelectedAgentUser(undefined)}
|
||||||
|
>
|
||||||
<>
|
<>
|
||||||
{selectedAgentUser && (
|
{selectedAgentUser && (
|
||||||
<div className="w-full flex flex-col gap-8">
|
<div className="w-full flex flex-col gap-8">
|
||||||
@@ -845,11 +1004,17 @@ export default function PaymentRecord() {
|
|||||||
|
|
||||||
const getCSVData = () => {
|
const getCSVData = () => {
|
||||||
const tables = [table, paypalTable];
|
const tables = [table, paypalTable];
|
||||||
const whitelists = [CSV_PAYMENTS_WHITELISTED_KEYS, CSV_PAYPAL_WHITELISTED_KEYS];
|
const whitelists = [
|
||||||
|
CSV_PAYMENTS_WHITELISTED_KEYS,
|
||||||
|
CSV_PAYPAL_WHITELISTED_KEYS,
|
||||||
|
];
|
||||||
const currentTable = tables[selectedIndex];
|
const currentTable = tables[selectedIndex];
|
||||||
const whitelist = whitelists[selectedIndex];
|
const whitelist = whitelists[selectedIndex];
|
||||||
const columns = (currentTable.getHeaderGroups() as any[]).reduce((accm: any[], group: any) => {
|
const columns = (currentTable.getHeaderGroups() as any[]).reduce(
|
||||||
const whitelistedColumns = group.headers.filter((header: any) => whitelist.includes(header.id));
|
(accm: any[], group: any) => {
|
||||||
|
const whitelistedColumns = group.headers.filter((header: any) =>
|
||||||
|
whitelist.includes(header.id)
|
||||||
|
);
|
||||||
|
|
||||||
const data = whitelistedColumns.map((data: any) => ({
|
const data = whitelistedColumns.map((data: any) => ({
|
||||||
key: data.column.columnDef.id,
|
key: data.column.columnDef.id,
|
||||||
@@ -857,7 +1022,9 @@ export default function PaymentRecord() {
|
|||||||
})) as SimpleCSVColumn[];
|
})) as SimpleCSVColumn[];
|
||||||
|
|
||||||
return [...accm, ...data];
|
return [...accm, ...data];
|
||||||
}, []);
|
},
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
const { rows } = currentTable.getRowModel();
|
const { rows } = currentTable.getRowModel();
|
||||||
|
|
||||||
@@ -895,7 +1062,12 @@ export default function PaymentRecord() {
|
|||||||
<tr key={headerGroup.id}>
|
<tr key={headerGroup.id}>
|
||||||
{headerGroup.headers.map((header) => (
|
{headerGroup.headers.map((header) => (
|
||||||
<th className="p-4 text-left" key={header.id}>
|
<th className="p-4 text-left" key={header.id}>
|
||||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
{header.isPlaceholder
|
||||||
|
? null
|
||||||
|
: flexRender(
|
||||||
|
header.column.columnDef.header,
|
||||||
|
header.getContext()
|
||||||
|
)}
|
||||||
</th>
|
</th>
|
||||||
))}
|
))}
|
||||||
</tr>
|
</tr>
|
||||||
@@ -903,7 +1075,10 @@ export default function PaymentRecord() {
|
|||||||
</thead>
|
</thead>
|
||||||
<tbody className="px-2">
|
<tbody className="px-2">
|
||||||
{table.getRowModel().rows.map((row) => (
|
{table.getRowModel().rows.map((row) => (
|
||||||
<tr className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2" key={row.id}>
|
<tr
|
||||||
|
className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2"
|
||||||
|
key={row.id}
|
||||||
|
>
|
||||||
{row.getVisibleCells().map((cell) => (
|
{row.getVisibleCells().map((cell) => (
|
||||||
<td className="px-4 py-2" key={cell.id}>
|
<td className="px-4 py-2" key={cell.id}>
|
||||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||||
@@ -930,26 +1105,43 @@ export default function PaymentRecord() {
|
|||||||
{user && (
|
{user && (
|
||||||
<Layout user={user} className="gap-6">
|
<Layout user={user} className="gap-6">
|
||||||
{getUserModal()}
|
{getUserModal()}
|
||||||
<Modal isOpen={isCreatingPayment} onClose={() => setIsCreatingPayment(false)}>
|
<Modal
|
||||||
|
isOpen={isCreatingPayment}
|
||||||
|
onClose={() => setIsCreatingPayment(false)}
|
||||||
|
>
|
||||||
<PaymentCreator
|
<PaymentCreator
|
||||||
onClose={() => setIsCreatingPayment(false)}
|
onClose={() => setIsCreatingPayment(false)}
|
||||||
reload={reload}
|
reload={reload}
|
||||||
showComission={user.type === "developer" || user.type === "admin"}
|
showComission={checkAccess(user, ["developer", "admin"])}
|
||||||
/>
|
/>
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|
||||||
<div className="w-full flex flex-end justify-between p-2">
|
<div className="w-full flex flex-end justify-between p-2">
|
||||||
<h1 className="text-2xl font-semibold">Payment Record</h1>
|
<h1 className="text-2xl font-semibold">Payment Record</h1>
|
||||||
<div className="flex justify-end gap-2">
|
<div className="flex justify-end gap-2">
|
||||||
{(["developer", "admin", "agent", "corporate", "mastercorporate"].includes(user.type)) && (
|
{checkAccess(user, [
|
||||||
|
"developer",
|
||||||
|
"admin",
|
||||||
|
"agent",
|
||||||
|
"corporate",
|
||||||
|
"mastercorporate",
|
||||||
|
]) && (
|
||||||
<Button className="max-w-[200px]" variant="outline">
|
<Button className="max-w-[200px]" variant="outline">
|
||||||
<CSVLink data={csvRows} headers={csvColumns} filename="payment-records.csv">
|
<CSVLink
|
||||||
|
data={csvRows}
|
||||||
|
headers={csvColumns}
|
||||||
|
filename="payment-records.csv"
|
||||||
|
>
|
||||||
Download CSV
|
Download CSV
|
||||||
</CSVLink>
|
</CSVLink>
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{(user.type === "developer" || user.type === "admin") && (
|
{checkAccess(user, ["developer", "admin"]) && (
|
||||||
<Button className="max-w-[200px]" variant="outline" onClick={() => setIsCreatingPayment(true)}>
|
<Button
|
||||||
|
className="max-w-[200px]"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setIsCreatingPayment(true)}
|
||||||
|
>
|
||||||
New Payment
|
New Payment
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
@@ -963,54 +1155,78 @@ export default function PaymentRecord() {
|
|||||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-mti-purple-light",
|
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-mti-purple-light",
|
||||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-mti-purple-light focus:outline-none focus:ring-2",
|
"ring-white ring-opacity-60 ring-offset-2 ring-offset-mti-purple-light focus:outline-none focus:ring-2",
|
||||||
"transition duration-300 ease-in-out",
|
"transition duration-300 ease-in-out",
|
||||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
|
selected
|
||||||
|
? "bg-white shadow"
|
||||||
|
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark"
|
||||||
)
|
)
|
||||||
}>
|
}
|
||||||
|
>
|
||||||
Payments
|
Payments
|
||||||
</Tab>
|
</Tab>
|
||||||
{["admin", "developer"].includes(user.type) && (
|
{checkAccess(user, ["developer", "admin"]) && (
|
||||||
<Tab
|
<Tab
|
||||||
className={({ selected }) =>
|
className={({ selected }) =>
|
||||||
clsx(
|
clsx(
|
||||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-mti-purple-light",
|
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-mti-purple-light",
|
||||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-mti-purple-light focus:outline-none focus:ring-2",
|
"ring-white ring-opacity-60 ring-offset-2 ring-offset-mti-purple-light focus:outline-none focus:ring-2",
|
||||||
"transition duration-300 ease-in-out",
|
"transition duration-300 ease-in-out",
|
||||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
|
selected
|
||||||
|
? "bg-white shadow"
|
||||||
|
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark"
|
||||||
)
|
)
|
||||||
}>
|
}
|
||||||
|
>
|
||||||
Paymob
|
Paymob
|
||||||
</Tab>
|
</Tab>
|
||||||
)}
|
)}
|
||||||
</Tab.List>
|
</Tab.List>
|
||||||
<Tab.Panels>
|
<Tab.Panels>
|
||||||
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide gap-8 flex flex-col">
|
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide gap-8 flex flex-col">
|
||||||
<div className={clsx("grid grid-cols-1 md:grid-cols-2 gap-8 w-full", user.type !== "corporate" && "lg:grid-cols-3")}>
|
<div
|
||||||
|
className={clsx(
|
||||||
|
"grid grid-cols-1 md:grid-cols-2 gap-8 w-full",
|
||||||
|
user.type !== "corporate" && "lg:grid-cols-3"
|
||||||
|
)}
|
||||||
|
>
|
||||||
<div className="flex flex-col gap-3 w-full">
|
<div className="flex flex-col gap-3 w-full">
|
||||||
<label className="font-normal text-base text-mti-gray-dim">Corporate account *</label>
|
<label className="font-normal text-base text-mti-gray-dim">
|
||||||
|
Corporate account *
|
||||||
|
</label>
|
||||||
<Select
|
<Select
|
||||||
isClearable={user.type !== "corporate"}
|
isClearable={user.type !== "corporate"}
|
||||||
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",
|
||||||
user.type === "corporate" && "!bg-mti-gray-platinum/40 !text-mti-gray-dim !cursor-not-allowed",
|
user.type === "corporate" &&
|
||||||
|
"!bg-mti-gray-platinum/40 !text-mti-gray-dim !cursor-not-allowed"
|
||||||
)}
|
)}
|
||||||
options={(users.filter((u) => u.type === "corporate") as CorporateUser[]).map((user) => ({
|
options={(
|
||||||
|
users.filter(
|
||||||
|
(u) => u.type === "corporate"
|
||||||
|
) as CorporateUser[]
|
||||||
|
).map((user) => ({
|
||||||
value: user.id,
|
value: user.id,
|
||||||
meta: user,
|
meta: user,
|
||||||
label: `${user.corporateInformation?.companyInformation?.name || user.name} - ${user.email}`,
|
label: `${
|
||||||
|
user.corporateInformation?.companyInformation?.name ||
|
||||||
|
user.name
|
||||||
|
} - ${user.email}`,
|
||||||
}))}
|
}))}
|
||||||
defaultValue={
|
defaultValue={
|
||||||
user.type === "corporate"
|
user.type === "corporate"
|
||||||
? {
|
? {
|
||||||
value: user.id,
|
value: user.id,
|
||||||
meta: user,
|
meta: user,
|
||||||
label: `${user.corporateInformation?.companyInformation?.name || user.name} - ${
|
label: `${
|
||||||
user.email
|
user.corporateInformation?.companyInformation
|
||||||
}`,
|
?.name || user.name
|
||||||
|
} - ${user.email}`,
|
||||||
}
|
}
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
isDisabled={user.type === "corporate"}
|
isDisabled={user.type === "corporate"}
|
||||||
onChange={(value) => setCorporate((value as any)?.meta ?? undefined)}
|
onChange={(value) =>
|
||||||
|
setCorporate((value as any)?.meta ?? undefined)
|
||||||
|
}
|
||||||
menuPortalTarget={document?.body}
|
menuPortalTarget={document?.body}
|
||||||
styles={{
|
styles={{
|
||||||
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||||
@@ -1025,7 +1241,11 @@ export default function PaymentRecord() {
|
|||||||
}),
|
}),
|
||||||
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,
|
||||||
}),
|
}),
|
||||||
}}
|
}}
|
||||||
@@ -1033,15 +1253,21 @@ export default function PaymentRecord() {
|
|||||||
</div>
|
</div>
|
||||||
{user.type !== "corporate" && (
|
{user.type !== "corporate" && (
|
||||||
<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 manager *</label>
|
<label className="font-normal text-base text-mti-gray-dim">
|
||||||
|
Country manager *
|
||||||
|
</label>
|
||||||
<Select
|
<Select
|
||||||
isClearable
|
isClearable
|
||||||
isDisabled={user.type === "agent"}
|
isDisabled={user.type === "agent"}
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none",
|
"px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none",
|
||||||
user.type === "agent" ? "bg-mti-gray-platinum/40" : "bg-white",
|
user.type === "agent"
|
||||||
|
? "bg-mti-gray-platinum/40"
|
||||||
|
: "bg-white"
|
||||||
)}
|
)}
|
||||||
options={(users.filter((u) => u.type === "agent") as AgentUser[]).map((user) => ({
|
options={(
|
||||||
|
users.filter((u) => u.type === "agent") as AgentUser[]
|
||||||
|
).map((user) => ({
|
||||||
value: user.id,
|
value: user.id,
|
||||||
meta: user,
|
meta: user,
|
||||||
label: `${user.name} - ${user.email}`,
|
label: `${user.name} - ${user.email}`,
|
||||||
@@ -1054,7 +1280,11 @@ export default function PaymentRecord() {
|
|||||||
}
|
}
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
onChange={(value) => setAgent(value !== null ? (value as any).meta : undefined)}
|
onChange={(value) =>
|
||||||
|
setAgent(
|
||||||
|
value !== null ? (value as any).meta : undefined
|
||||||
|
)
|
||||||
|
}
|
||||||
menuPortalTarget={document?.body}
|
menuPortalTarget={document?.body}
|
||||||
styles={{
|
styles={{
|
||||||
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||||
@@ -1069,7 +1299,11 @@ export default function PaymentRecord() {
|
|||||||
}),
|
}),
|
||||||
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,
|
||||||
}),
|
}),
|
||||||
}}
|
}}
|
||||||
@@ -1077,12 +1311,16 @@ export default function PaymentRecord() {
|
|||||||
</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">Paid</label>
|
<label className="font-normal text-base text-mti-gray-dim">
|
||||||
|
Paid
|
||||||
|
</label>
|
||||||
<Select
|
<Select
|
||||||
isClearable
|
isClearable
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none",
|
"px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none",
|
||||||
user.type === "agent" ? "bg-mti-gray-platinum/40" : "bg-white",
|
user.type === "agent"
|
||||||
|
? "bg-mti-gray-platinum/40"
|
||||||
|
: "bg-white"
|
||||||
)}
|
)}
|
||||||
options={IS_PAID_OPTIONS}
|
options={IS_PAID_OPTIONS}
|
||||||
value={IS_PAID_OPTIONS.find((e) => e.value === paid)}
|
value={IS_PAID_OPTIONS.find((e) => e.value === paid)}
|
||||||
@@ -1104,14 +1342,20 @@ export default function PaymentRecord() {
|
|||||||
}),
|
}),
|
||||||
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,
|
||||||
}),
|
}),
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</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">Date</label>
|
<label className="font-normal text-base text-mti-gray-dim">
|
||||||
|
Date
|
||||||
|
</label>
|
||||||
<ReactDatePicker
|
<ReactDatePicker
|
||||||
dateFormat="dd/MM/yyyy"
|
dateFormat="dd/MM/yyyy"
|
||||||
className="px-4 py-6 w-full text-sm text-center font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none"
|
className="px-4 py-6 w-full text-sm text-center font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none"
|
||||||
@@ -1120,9 +1364,13 @@ export default function PaymentRecord() {
|
|||||||
endDate={endDate}
|
endDate={endDate}
|
||||||
selectsRange
|
selectsRange
|
||||||
showMonthDropdown
|
showMonthDropdown
|
||||||
filterDate={(date: Date) => moment(date).isSameOrBefore(moment(new Date()))}
|
filterDate={(date: Date) =>
|
||||||
|
moment(date).isSameOrBefore(moment(new Date()))
|
||||||
|
}
|
||||||
onChange={([initialDate, finalDate]: [Date, Date]) => {
|
onChange={([initialDate, finalDate]: [Date, Date]) => {
|
||||||
setStartDate(initialDate ?? moment("01/01/2023").toDate());
|
setStartDate(
|
||||||
|
initialDate ?? moment("01/01/2023").toDate()
|
||||||
|
);
|
||||||
if (finalDate) {
|
if (finalDate) {
|
||||||
// basicly selecting a final day works as if I'm selecting the first
|
// basicly selecting a final day works as if I'm selecting the first
|
||||||
// minute of that day. this way it covers the whole day
|
// minute of that day. this way it covers the whole day
|
||||||
@@ -1135,14 +1383,18 @@ export default function PaymentRecord() {
|
|||||||
</div>
|
</div>
|
||||||
{user.type !== "corporate" && (
|
{user.type !== "corporate" && (
|
||||||
<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">Commission transfer</label>
|
<label className="font-normal text-base text-mti-gray-dim">
|
||||||
|
Commission transfer
|
||||||
|
</label>
|
||||||
<Select
|
<Select
|
||||||
isClearable
|
isClearable
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none",
|
"px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none"
|
||||||
)}
|
)}
|
||||||
options={IS_FILE_SUBMITTED_OPTIONS}
|
options={IS_FILE_SUBMITTED_OPTIONS}
|
||||||
value={IS_FILE_SUBMITTED_OPTIONS.find((e) => e.value === commissionTransfer)}
|
value={IS_FILE_SUBMITTED_OPTIONS.find(
|
||||||
|
(e) => e.value === commissionTransfer
|
||||||
|
)}
|
||||||
onChange={(value) => {
|
onChange={(value) => {
|
||||||
if (value) return setCommissionTransfer(value.value);
|
if (value) return setCommissionTransfer(value.value);
|
||||||
setCommissionTransfer(null);
|
setCommissionTransfer(null);
|
||||||
@@ -1161,7 +1413,11 @@ export default function PaymentRecord() {
|
|||||||
}),
|
}),
|
||||||
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,
|
||||||
}),
|
}),
|
||||||
}}
|
}}
|
||||||
@@ -1169,14 +1425,18 @@ export default function PaymentRecord() {
|
|||||||
</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">Corporate transfer</label>
|
<label className="font-normal text-base text-mti-gray-dim">
|
||||||
|
Corporate transfer
|
||||||
|
</label>
|
||||||
<Select
|
<Select
|
||||||
isClearable
|
isClearable
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none",
|
"px-4 py-4 w-full text-sm font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none"
|
||||||
)}
|
)}
|
||||||
options={IS_FILE_SUBMITTED_OPTIONS}
|
options={IS_FILE_SUBMITTED_OPTIONS}
|
||||||
value={IS_FILE_SUBMITTED_OPTIONS.find((e) => e.value === corporateTransfer)}
|
value={IS_FILE_SUBMITTED_OPTIONS.find(
|
||||||
|
(e) => e.value === corporateTransfer
|
||||||
|
)}
|
||||||
onChange={(value) => {
|
onChange={(value) => {
|
||||||
if (value) return setCorporateTransfer(value.value);
|
if (value) return setCorporateTransfer(value.value);
|
||||||
setCorporateTransfer(null);
|
setCorporateTransfer(null);
|
||||||
@@ -1195,7 +1455,11 @@ export default function PaymentRecord() {
|
|||||||
}),
|
}),
|
||||||
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,
|
||||||
}),
|
}),
|
||||||
}}
|
}}
|
||||||
|
|||||||
190
src/pages/permissions/[id].tsx
Normal file
190
src/pages/permissions/[id].tsx
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
/* eslint-disable @next/next/no-img-element */
|
||||||
|
import Head from "next/head";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { withIronSessionSsr } from "iron-session/next";
|
||||||
|
import { sessionOptions } from "@/lib/session";
|
||||||
|
import { shouldRedirectHome } from "@/utils/navigation.disabled";
|
||||||
|
import { Permission, PermissionType } from "@/interfaces/permissions";
|
||||||
|
import { getPermissionDoc } from "@/utils/permissions.be";
|
||||||
|
import { User } from "@/interfaces/user";
|
||||||
|
import Layout from "@/components/High/Layout";
|
||||||
|
import { getUsers } from "@/utils/users.be";
|
||||||
|
import { BsTrash } from "react-icons/bs";
|
||||||
|
import Select from "@/components/Low/Select";
|
||||||
|
import Button from "@/components/Low/Button";
|
||||||
|
import axios from "axios";
|
||||||
|
import { toast, ToastContainer } from "react-toastify";
|
||||||
|
|
||||||
|
interface BasicUser {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PermissionWithBasicUsers {
|
||||||
|
id: string;
|
||||||
|
type: PermissionType;
|
||||||
|
users: BasicUser[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getServerSideProps = withIronSessionSsr(async (context) => {
|
||||||
|
const { req, params } = context;
|
||||||
|
const user = req.session.user;
|
||||||
|
|
||||||
|
if (!user || !user.isVerified) {
|
||||||
|
return {
|
||||||
|
redirect: {
|
||||||
|
destination: "/login",
|
||||||
|
permanent: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shouldRedirectHome(user)) {
|
||||||
|
return {
|
||||||
|
redirect: {
|
||||||
|
destination: "/",
|
||||||
|
permanent: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!params?.id) {
|
||||||
|
return {
|
||||||
|
redirect: {
|
||||||
|
destination: "/permissions",
|
||||||
|
permanent: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch data from external API
|
||||||
|
const permission: Permission = await getPermissionDoc(params.id as string);
|
||||||
|
|
||||||
|
const allUserData: User[] = await getUsers();
|
||||||
|
const users = allUserData.map((u) => ({
|
||||||
|
id: u.id,
|
||||||
|
name: u.name,
|
||||||
|
})) as BasicUser[];
|
||||||
|
|
||||||
|
// const res = await fetch("api/permissions");
|
||||||
|
// const permissions: Permission[] = await res.json();
|
||||||
|
// Pass data to the page via props
|
||||||
|
const usersData: BasicUser[] = permission.users.reduce(
|
||||||
|
(acc: BasicUser[], userId) => {
|
||||||
|
const user = users.find((u) => u.id === userId) as BasicUser;
|
||||||
|
if (user) {
|
||||||
|
acc.push(user);
|
||||||
|
}
|
||||||
|
return acc;
|
||||||
|
},
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
props: {
|
||||||
|
// permissions: permissions.map((p) => ({ id: p.id, type: p.type })),
|
||||||
|
permission: {
|
||||||
|
...permission,
|
||||||
|
id: params.id,
|
||||||
|
users: usersData,
|
||||||
|
},
|
||||||
|
user: req.session.user,
|
||||||
|
users,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}, sessionOptions);
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
permission: PermissionWithBasicUsers;
|
||||||
|
user: User;
|
||||||
|
users: BasicUser[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Page(props: Props) {
|
||||||
|
console.log("Props", props);
|
||||||
|
|
||||||
|
const { permission, user, users } = props;
|
||||||
|
|
||||||
|
const [selectedUsers, setSelectedUsers] = useState<string[]>(() =>
|
||||||
|
permission.users.map((u) => u.id)
|
||||||
|
);
|
||||||
|
|
||||||
|
const onChange = (value: any) => {
|
||||||
|
console.log("value", value);
|
||||||
|
setSelectedUsers((prev) => {
|
||||||
|
if (value?.value) {
|
||||||
|
return [...prev, value?.value];
|
||||||
|
}
|
||||||
|
return prev;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const removeUser = (id: string) => {
|
||||||
|
setSelectedUsers((prev) => prev.filter((u) => u !== id));
|
||||||
|
};
|
||||||
|
|
||||||
|
const update = async () => {
|
||||||
|
console.log("update", selectedUsers);
|
||||||
|
try {
|
||||||
|
await axios.patch(`/api/permissions/${permission.id}`, {
|
||||||
|
users: selectedUsers,
|
||||||
|
});
|
||||||
|
toast.success("Permission updated");
|
||||||
|
} catch (err) {
|
||||||
|
toast.error("Failed to update permission");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Head>
|
||||||
|
<title>EnCoach</title>
|
||||||
|
<meta
|
||||||
|
name="description"
|
||||||
|
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||||
|
/>
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<link rel="icon" href="/favicon.ico" />
|
||||||
|
</Head>
|
||||||
|
<ToastContainer />
|
||||||
|
<Layout user={user} className="gap-6">
|
||||||
|
<h1 className="text-2xl font-semibold">
|
||||||
|
Permission: {permission.type as string}
|
||||||
|
</h1>
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<Select
|
||||||
|
value={null}
|
||||||
|
options={users
|
||||||
|
.filter((u) => !selectedUsers.includes(u.id))
|
||||||
|
.map((u) => ({
|
||||||
|
label: u.name,
|
||||||
|
value: u.id,
|
||||||
|
}))}
|
||||||
|
onChange={onChange}
|
||||||
|
/>
|
||||||
|
<Button onClick={update}>Update</Button>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
<h2>Blacklisted Users</h2>
|
||||||
|
<div className="flex gap-3 flex-wrap">
|
||||||
|
{selectedUsers.map((userId) => {
|
||||||
|
const name = users.find((u) => u.id === userId)?.name;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="flex p-4 rounded-xl w-auto bg-mti-purple-light text-white gap-4"
|
||||||
|
key={userId}
|
||||||
|
>
|
||||||
|
<span className="text-base">{name}</span>
|
||||||
|
<BsTrash
|
||||||
|
style={{ cursor: "pointer" }}
|
||||||
|
onClick={() => removeUser(userId)}
|
||||||
|
size={20}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Layout>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
94
src/pages/permissions/index.tsx
Normal file
94
src/pages/permissions/index.tsx
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
/* eslint-disable @next/next/no-img-element */
|
||||||
|
import Head from "next/head";
|
||||||
|
import { withIronSessionSsr } from "iron-session/next";
|
||||||
|
import { sessionOptions } from "@/lib/session";
|
||||||
|
import { shouldRedirectHome } from "@/utils/navigation.disabled";
|
||||||
|
import { Permission } from "@/interfaces/permissions";
|
||||||
|
import { getPermissionDocs } from "@/utils/permissions.be";
|
||||||
|
import { User } from "@/interfaces/user";
|
||||||
|
import Layout from "@/components/High/Layout";
|
||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
export const getServerSideProps = withIronSessionSsr(async ({ req }) => {
|
||||||
|
const user = req.session.user;
|
||||||
|
|
||||||
|
if (!user || !user.isVerified) {
|
||||||
|
return {
|
||||||
|
redirect: {
|
||||||
|
destination: "/login",
|
||||||
|
permanent: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shouldRedirectHome(user)) {
|
||||||
|
return {
|
||||||
|
redirect: {
|
||||||
|
destination: "/",
|
||||||
|
permanent: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch data from external API
|
||||||
|
const permissions: Permission[] = await getPermissionDocs();
|
||||||
|
|
||||||
|
console.log("Permissions", permissions);
|
||||||
|
|
||||||
|
// const res = await fetch("api/permissions");
|
||||||
|
// const permissions: Permission[] = await res.json();
|
||||||
|
// Pass data to the page via props
|
||||||
|
return {
|
||||||
|
props: {
|
||||||
|
// permissions: permissions.map((p) => ({ id: p.id, type: p.type })),
|
||||||
|
permissions: permissions.map((p) => {
|
||||||
|
const { users, ...rest } = p;
|
||||||
|
return rest;
|
||||||
|
}),
|
||||||
|
user: req.session.user,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}, sessionOptions);
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
permissions: Permission[];
|
||||||
|
user: User;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Page(props: Props) {
|
||||||
|
console.log("Props", props);
|
||||||
|
|
||||||
|
const { permissions, user } = props;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Head>
|
||||||
|
<title>EnCoach</title>
|
||||||
|
<meta
|
||||||
|
name="description"
|
||||||
|
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||||
|
/>
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<link rel="icon" href="/favicon.ico" />
|
||||||
|
</Head>
|
||||||
|
<Layout user={user} className="gap-6">
|
||||||
|
<h1 className="text-2xl font-semibold">Permissions</h1>
|
||||||
|
<div className="flex gap-3 flex-wrap">
|
||||||
|
{permissions.map((permission: Permission) => {
|
||||||
|
const id = permission.id as string;
|
||||||
|
const type = permission.type as string;
|
||||||
|
return (
|
||||||
|
<Link href={`/permissions/${id}`} key={id}>
|
||||||
|
<div className="card bg-primary text-primary-content">
|
||||||
|
<div className="card-body">
|
||||||
|
<h1 className="card-title">{type}</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</Layout>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,7 +2,15 @@
|
|||||||
import Head from "next/head";
|
import 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";
|
||||||
@@ -12,7 +20,14 @@ 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";
|
||||||
@@ -33,6 +48,8 @@ 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";
|
||||||
|
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;
|
||||||
|
|
||||||
@@ -64,7 +81,9 @@ 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 || "");
|
||||||
@@ -75,35 +94,71 @@ 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);
|
||||||
|
|
||||||
@@ -115,9 +170,12 @@ function UserProfile({user, mutateUser}: Props) {
|
|||||||
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?";
|
||||||
|
|
||||||
@@ -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,18 +496,27 @@ 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" },
|
||||||
@@ -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>
|
||||||
|
|||||||
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