Solved an issue where, for developers, because of the amount of permissions, the cookie was too big, so I separated the permissions logic into a hook

This commit is contained in:
Tiago Ribeiro
2024-08-12 19:35:11 +01:00
parent cb489bf0ca
commit 58300e32ff
17 changed files with 3060 additions and 4025 deletions

View File

@@ -1,22 +1,16 @@
import useUsers from "@/hooks/useUsers"; import useUsers from "@/hooks/useUsers";
import { import {Ticket, TicketStatus, TicketStatusLabel, TicketType, TicketTypeLabel} from "@/interfaces/ticket";
Ticket, import {User} from "@/interfaces/user";
TicketStatus, import {USER_TYPE_LABELS} from "@/resources/user";
TicketStatusLabel,
TicketType,
TicketTypeLabel,
} from "@/interfaces/ticket";
import { User } from "@/interfaces/user";
import { USER_TYPE_LABELS } from "@/resources/user";
import axios from "axios"; import axios from "axios";
import moment from "moment"; import moment from "moment";
import { useState } from "react"; import {useState} from "react";
import { toast } from "react-toastify"; import {toast} from "react-toastify";
import ShortUniqueId from "short-unique-id"; 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"; import {checkAccess} from "@/utils/permissions";
interface Props { interface Props {
user: User; user: User;
@@ -24,23 +18,20 @@ interface Props {
onClose: () => void; onClose: () => void;
} }
export default function TicketDisplay({ user, ticket, onClose }: Props) { export default function TicketDisplay({user, ticket, onClose}: Props) {
const [subject] = useState(ticket.subject); const [subject] = useState(ticket.subject);
const [type, setType] = useState<TicketType>(ticket.type); const [type, setType] = useState<TicketType>(ticket.type);
const [description] = useState(ticket.description); const [description] = useState(ticket.description);
const [reporter] = useState(ticket.reporter); const [reporter] = useState(ticket.reporter);
const [reportedFrom] = useState(ticket.reportedFrom); const [reportedFrom] = useState(ticket.reportedFrom);
const [status, setStatus] = useState(ticket.status); const [status, setStatus] = useState(ticket.status);
const [assignedTo, setAssignedTo] = useState<string | null>( const [assignedTo, setAssignedTo] = useState<string | null>(ticket.assignedTo || null);
ticket.assignedTo || null,
);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const { users } = useUsers(); const {users} = useUsers();
const submit = () => { const submit = () => {
if (!type) if (!type) return toast.error("Please choose a type!", {toastId: "missing-type"});
return toast.error("Please choose a type!", { toastId: "missing-type" });
setIsLoading(true); setIsLoading(true);
axios axios
@@ -54,7 +45,7 @@ export default function TicketDisplay({ user, ticket, onClose }: Props) {
assignedTo, assignedTo,
}) })
.then(() => { .then(() => {
toast.success(`The ticket has been updated!`, { toastId: "submitted" }); toast.success(`The ticket has been updated!`, {toastId: "submitted"});
onClose(); onClose();
}) })
.catch((e) => { .catch((e) => {
@@ -73,7 +64,7 @@ export default function TicketDisplay({ user, ticket, onClose }: Props) {
axios axios
.delete(`/api/tickets/${ticket.id}`) .delete(`/api/tickets/${ticket.id}`)
.then(() => { .then(() => {
toast.success(`The ticket has been deleted!`, { toastId: "submitted" }); toast.success(`The ticket has been deleted!`, {toastId: "submitted"});
onClose(); onClose();
}) })
.catch((e) => { .catch((e) => {
@@ -87,43 +78,29 @@ export default function TicketDisplay({ user, ticket, onClose }: Props) {
return ( return (
<form className="flex flex-col gap-4 pt-8"> <form className="flex flex-col gap-4 pt-8">
<Input <Input label="Subject" type="text" name="subject" placeholder="Subject..." value={subject} onChange={(e) => null} disabled />
label="Subject"
type="text"
name="subject"
placeholder="Subject..."
value={subject}
onChange={(e) => null}
disabled
/>
<div className="-md:flex-col flex w-full items-center gap-4"> <div className="-md:flex-col flex w-full items-center gap-4">
<div className="flex w-full flex-col gap-3"> <div className="flex w-full flex-col gap-3">
<label className="text-mti-gray-dim text-base font-normal"> <label className="text-mti-gray-dim text-base font-normal">Status</label>
Status
</label>
<Select <Select
options={Object.keys(TicketStatusLabel).map((x) => ({ options={Object.keys(TicketStatusLabel).map((x) => ({
value: x, value: x,
label: TicketStatusLabel[x as keyof typeof TicketStatusLabel], label: TicketStatusLabel[x as keyof typeof TicketStatusLabel],
}))} }))}
value={{ value: status, label: TicketStatusLabel[status] }} value={{value: status, label: TicketStatusLabel[status]}}
onChange={(value) => onChange={(value) => setStatus((value?.value as TicketStatus) ?? undefined)}
setStatus((value?.value as TicketStatus) ?? undefined)
}
placeholder="Status..." placeholder="Status..."
/> />
</div> </div>
<div className="flex w-full flex-col gap-3"> <div className="flex w-full flex-col gap-3">
<label className="text-mti-gray-dim text-base font-normal"> <label className="text-mti-gray-dim text-base font-normal">Type</label>
Type
</label>
<Select <Select
options={Object.keys(TicketTypeLabel).map((x) => ({ options={Object.keys(TicketTypeLabel).map((x) => ({
value: x, value: x,
label: TicketTypeLabel[x as keyof typeof TicketTypeLabel], label: TicketTypeLabel[x as keyof typeof TicketTypeLabel],
}))} }))}
value={{ value: type, label: TicketTypeLabel[type] }} value={{value: type, label: TicketTypeLabel[type]}}
onChange={(value) => setType(value!.value as TicketType)} onChange={(value) => setType(value!.value as TicketType)}
placeholder="Type..." placeholder="Type..."
/> />
@@ -131,12 +108,10 @@ export default function TicketDisplay({ user, ticket, onClose }: Props) {
</div> </div>
<div className="flex w-full flex-col gap-3"> <div className="flex w-full flex-col gap-3">
<label className="text-mti-gray-dim text-base font-normal"> <label className="text-mti-gray-dim text-base font-normal">Assignee</label>
Assignee
</label>
<Select <Select
options={[ options={[
{ value: "me", label: "Assign to me" }, {value: "me", label: "Assign to me"},
...users ...users
.filter((x) => checkAccess(x, ["admin", "developer", "agent"])) .filter((x) => checkAccess(x, ["admin", "developer", "agent"]))
.map((u) => ({ .map((u) => ({
@@ -153,52 +128,20 @@ export default function TicketDisplay({ user, ticket, onClose }: Props) {
} }
: null : null
} }
onChange={(value) => onChange={(value) => (value ? setAssignedTo(value.value === "me" ? user.id : value.value) : setAssignedTo(null))}
value
? setAssignedTo(value.value === "me" ? user.id : value.value)
: setAssignedTo(null)
}
placeholder="Assignee..." placeholder="Assignee..."
isClearable isClearable
/> />
</div> </div>
<div className="-md:flex-col flex w-full items-center gap-4"> <div className="-md:flex-col flex w-full items-center gap-4">
<Input <Input label="Reported From" type="text" name="reportedFrom" onChange={() => null} value={reportedFrom} disabled />
label="Reported From" <Input label="Date" type="text" name="date" onChange={() => null} value={moment(ticket.date).format("DD/MM/YYYY - HH:mm")} disabled />
type="text"
name="reportedFrom"
onChange={() => null}
value={reportedFrom}
disabled
/>
<Input
label="Date"
type="text"
name="date"
onChange={() => null}
value={moment(ticket.date).format("DD/MM/YYYY - HH:mm")}
disabled
/>
</div> </div>
<div className="-md:flex-col flex w-full items-center gap-4"> <div className="-md:flex-col flex w-full items-center gap-4">
<Input <Input label="Reporter's Name" type="text" name="reporter" onChange={() => null} value={reporter.name} disabled />
label="Reporter's Name" <Input label="Reporter's E-mail" type="text" name="reporter" onChange={() => null} value={reporter.email} disabled />
type="text"
name="reporter"
onChange={() => null}
value={reporter.name}
disabled
/>
<Input
label="Reporter's E-mail"
type="text"
name="reporter"
onChange={() => null}
value={reporter.email}
disabled
/>
<Input <Input
label="Reporter's Type" label="Reporter's Type"
type="text" type="text"
@@ -218,34 +161,15 @@ export default function TicketDisplay({ user, ticket, onClose }: Props) {
/> />
<div className="-md:flex-col-reverse mt-2 flex w-full items-center justify-between gap-4"> <div className="-md:flex-col-reverse mt-2 flex w-full items-center justify-between gap-4">
<Button <Button type="button" color="red" className="w-full md:max-w-[200px]" variant="outline" onClick={del} isLoading={isLoading}>
type="button"
color="red"
className="w-full md:max-w-[200px]"
variant="outline"
onClick={del}
isLoading={isLoading}
>
Delete Delete
</Button> </Button>
<div className="-md:flex-col-reverse flex w-full items-center justify-end gap-4"> <div className="-md:flex-col-reverse flex w-full items-center justify-end gap-4">
<Button <Button type="button" color="red" className="w-full md:max-w-[200px]" variant="outline" onClick={onClose} isLoading={isLoading}>
type="button"
color="red"
className="w-full md:max-w-[200px]"
variant="outline"
onClick={onClose}
isLoading={isLoading}
>
Cancel Cancel
</Button> </Button>
<Button <Button type="button" className="w-full md:max-w-[200px]" isLoading={isLoading} onClick={submit}>
type="button"
className="w-full md:max-w-[200px]"
isLoading={isLoading}
onClick={submit}
>
Update Update
</Button> </Button>
</div> </div>

View File

@@ -14,7 +14,7 @@ import {
BsClipboardData, BsClipboardData,
BsFileLock, BsFileLock,
} from "react-icons/bs"; } from "react-icons/bs";
import { CiDumbbell } from "react-icons/ci"; import {CiDumbbell} from "react-icons/ci";
import {RiLogoutBoxFill} from "react-icons/ri"; import {RiLogoutBoxFill} from "react-icons/ri";
import {SlPencil} from "react-icons/sl"; import {SlPencil} from "react-icons/sl";
import {FaAward} from "react-icons/fa"; import {FaAward} from "react-icons/fa";
@@ -28,6 +28,7 @@ import usePreferencesStore from "@/stores/preferencesStore";
import {User} from "@/interfaces/user"; import {User} from "@/interfaces/user";
import useTicketsListener from "@/hooks/useTicketsListener"; import useTicketsListener from "@/hooks/useTicketsListener";
import {checkAccess, getTypesOfUser} from "@/utils/permissions"; import {checkAccess, getTypesOfUser} from "@/utils/permissions";
import usePermissions from "@/hooks/usePermissions";
interface Props { interface Props {
path: string; path: string;
navDisabled?: boolean; navDisabled?: boolean;
@@ -80,6 +81,7 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
const [isMinimized, toggleMinimize] = usePreferencesStore((state) => [state.isSidebarMinimized, state.toggleSidebarMinimized]); const [isMinimized, toggleMinimize] = usePreferencesStore((state) => [state.isSidebarMinimized, state.toggleSidebarMinimized]);
const {totalAssignedTickets} = useTicketsListener(user.id); const {totalAssignedTickets} = useTicketsListener(user.id);
const {permissions} = usePermissions(user.id);
const logout = async () => { const logout = async () => {
axios.post("/api/logout").finally(() => { axios.post("/api/logout").finally(() => {
@@ -98,22 +100,22 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
)}> )}>
<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 disabled={disableNavigation} Icon={MdSpaceDashboard} label="Dashboard" path={path} keyPath="/" isMinimized={isMinimized} />
{checkAccess(user, ["student", "teacher", "developer"], "viewExams") && ( {checkAccess(user, ["student", "teacher", "developer"], permissions, "viewExams") && (
<Nav disabled={disableNavigation} Icon={BsFileEarmarkText} label="Exams" path={path} keyPath="/exam" isMinimized={isMinimized} /> <Nav disabled={disableNavigation} Icon={BsFileEarmarkText} label="Exams" path={path} keyPath="/exam" isMinimized={isMinimized} />
)} )}
{checkAccess(user, ["student", "teacher", "developer"], "viewExercises") && ( {checkAccess(user, ["student", "teacher", "developer"], permissions, "viewExercises") && (
<Nav disabled={disableNavigation} Icon={BsPencil} label="Exercises" path={path} keyPath="/exercises" isMinimized={isMinimized} /> <Nav disabled={disableNavigation} Icon={BsPencil} label="Exercises" path={path} keyPath="/exercises" isMinimized={isMinimized} />
)} )}
{checkAccess(user, getTypesOfUser(["agent"]), "viewStats") && ( {checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewStats") && (
<Nav disabled={disableNavigation} Icon={BsGraphUp} label="Stats" path={path} keyPath="/stats" isMinimized={isMinimized} /> <Nav disabled={disableNavigation} Icon={BsGraphUp} label="Stats" path={path} keyPath="/stats" isMinimized={isMinimized} />
)} )}
{checkAccess(user, getTypesOfUser(["agent"]), "viewRecords") && ( {checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewRecords") && (
<Nav disabled={disableNavigation} Icon={BsClockHistory} label="Record" path={path} keyPath="/record" isMinimized={isMinimized} /> <Nav disabled={disableNavigation} Icon={BsClockHistory} label="Record" path={path} keyPath="/record" isMinimized={isMinimized} />
)} )}
{checkAccess(user, getTypesOfUser(["agent"]), "viewRecords") && ( {checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewRecords") && (
<Nav disabled={disableNavigation} Icon={CiDumbbell} label="Training" path={path} keyPath="/training" isMinimized={isMinimized} /> <Nav disabled={disableNavigation} Icon={CiDumbbell} label="Training" path={path} keyPath="/training" isMinimized={isMinimized} />
)} )}
{checkAccess(user, ["admin", "developer", "agent", "corporate", "mastercorporate"], "viewPaymentRecords") && ( {checkAccess(user, ["admin", "developer", "agent", "corporate", "mastercorporate"], permissions, "viewPaymentRecords") && (
<Nav <Nav
disabled={disableNavigation} disabled={disableNavigation}
Icon={BsCurrencyDollar} Icon={BsCurrencyDollar}
@@ -133,7 +135,7 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
isMinimized={isMinimized} isMinimized={isMinimized}
/> />
)} )}
{checkAccess(user, ["admin", "developer", "agent"], "viewTickets") && ( {checkAccess(user, ["admin", "developer", "agent"], permissions, "viewTickets") && (
<Nav <Nav
disabled={disableNavigation} disabled={disableNavigation}
Icon={BsClipboardData} Icon={BsClipboardData}
@@ -169,13 +171,13 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
<Nav disabled={disableNavigation} Icon={MdSpaceDashboard} label="Dashboard" path={path} keyPath="/" isMinimized={true} /> <Nav disabled={disableNavigation} Icon={MdSpaceDashboard} label="Dashboard" path={path} keyPath="/" isMinimized={true} />
<Nav disabled={disableNavigation} Icon={BsFileEarmarkText} label="Exams" path={path} keyPath="/exam" isMinimized={true} /> <Nav disabled={disableNavigation} Icon={BsFileEarmarkText} label="Exams" path={path} keyPath="/exam" isMinimized={true} />
<Nav disabled={disableNavigation} Icon={BsPencil} label="Exercises" path={path} keyPath="/exercises" isMinimized={true} /> <Nav disabled={disableNavigation} Icon={BsPencil} label="Exercises" path={path} keyPath="/exercises" isMinimized={true} />
{checkAccess(user, getTypesOfUser(["agent"]), "viewStats") && ( {checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewStats") && (
<Nav disabled={disableNavigation} Icon={BsGraphUp} label="Stats" path={path} keyPath="/stats" isMinimized={true} /> <Nav disabled={disableNavigation} Icon={BsGraphUp} label="Stats" path={path} keyPath="/stats" isMinimized={true} />
)} )}
{checkAccess(user, getTypesOfUser(["agent"]), "viewRecords") && ( {checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewRecords") && (
<Nav disabled={disableNavigation} Icon={BsClockHistory} label="Record" path={path} keyPath="/record" isMinimized={true} /> <Nav disabled={disableNavigation} Icon={BsClockHistory} label="Record" path={path} keyPath="/record" isMinimized={true} />
)} )}
{checkAccess(user, getTypesOfUser(["agent"]), "viewRecords") && ( {checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewRecords") && (
<Nav disabled={disableNavigation} Icon={CiDumbbell} label="Training" path={path} keyPath="/training" isMinimized={true} /> <Nav disabled={disableNavigation} Icon={CiDumbbell} label="Training" path={path} keyPath="/training" isMinimized={true} />
)} )}
{checkAccess(user, getTypesOfUser(["student"])) && ( {checkAccess(user, getTypesOfUser(["student"])) && (

View File

@@ -1,27 +1,15 @@
import useStats from "@/hooks/useStats"; import useStats from "@/hooks/useStats";
import { import {CorporateInformation, CorporateUser, EMPLOYMENT_STATUS, User, Type} from "@/interfaces/user";
CorporateInformation, import {groupBySession, averageScore} from "@/utils/stats";
CorporateUser, import {RadioGroup} from "@headlessui/react";
EMPLOYMENT_STATUS,
User,
Type,
} from "@/interfaces/user";
import { groupBySession, averageScore } from "@/utils/stats";
import { RadioGroup } from "@headlessui/react";
import axios from "axios"; import axios from "axios";
import clsx from "clsx"; import clsx from "clsx";
import moment from "moment"; import moment from "moment";
import { Divider } from "primereact/divider"; import {Divider} from "primereact/divider";
import { useEffect, useState } from "react"; import {useEffect, useState} from "react";
import ReactDatePicker from "react-datepicker"; import ReactDatePicker from "react-datepicker";
import { import {BsFileEarmarkText, BsPencil, BsPerson, BsPersonAdd, BsStar} from "react-icons/bs";
BsFileEarmarkText, import {toast} from "react-toastify";
BsPencil,
BsPerson,
BsPersonAdd,
BsStar,
} from "react-icons/bs";
import { toast } from "react-toastify";
import Button from "./Low/Button"; import Button from "./Low/Button";
import Checkbox from "./Low/Checkbox"; import Checkbox from "./Low/Checkbox";
import CountrySelect from "./Low/CountrySelect"; import CountrySelect from "./Low/CountrySelect";
@@ -29,23 +17,21 @@ import Input from "./Low/Input";
import ProfileSummary from "./ProfileSummary"; import ProfileSummary from "./ProfileSummary";
import Select from "react-select"; import Select from "react-select";
import useUsers from "@/hooks/useUsers"; import useUsers from "@/hooks/useUsers";
import { USER_TYPE_LABELS } from "@/resources/user"; import {USER_TYPE_LABELS} from "@/resources/user";
import { CURRENCIES } from "@/resources/paypal"; import {CURRENCIES} from "@/resources/paypal";
import useCodes from "@/hooks/useCodes"; import useCodes from "@/hooks/useCodes";
import { checkAccess, getTypesOfUser } from "@/utils/permissions"; import {checkAccess, getTypesOfUser} from "@/utils/permissions";
import { PERMISSIONS } from "@/constants/userPermissions"; import {PERMISSIONS} from "@/constants/userPermissions";
import { PermissionType } from "@/interfaces/permissions"; import {PermissionType} from "@/interfaces/permissions";
import usePermissions from "@/hooks/usePermissions";
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)) if (today.add(1, "days").isAfter(momentDate)) return "!bg-mti-red-ultralight border-mti-red-light";
return "!bg-mti-red-ultralight border-mti-red-light"; if (today.add(3, "days").isAfter(momentDate)) return "!bg-mti-rose-ultralight border-mti-rose-light";
if (today.add(3, "days").isAfter(momentDate)) if (today.add(7, "days").isAfter(momentDate)) return "!bg-mti-orange-ultralight border-mti-orange-light";
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 {
@@ -81,86 +67,40 @@ const USER_TYPE_OPTIONS = Object.keys(USER_TYPE_LABELS).map((type) => ({
label: USER_TYPE_LABELS[type as keyof typeof USER_TYPE_LABELS], label: USER_TYPE_LABELS[type as keyof typeof USER_TYPE_LABELS],
})); }));
const CURRENCIES_OPTIONS = CURRENCIES.map(({ label, currency }) => ({ const CURRENCIES_OPTIONS = CURRENCIES.map(({label, currency}) => ({
value: currency, value: currency,
label, label,
})); }));
const UserCard = ({ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers, onViewCorporate, disabled = false, disabledFields = {}}: Props) => {
user, const [expiryDate, setExpiryDate] = useState<Date | null | undefined>(user.subscriptionExpirationDate);
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>( const [position, setPosition] = useState<string | undefined>(user.type === "corporate" ? user.demographicInformation?.position : undefined);
user.type === "corporate" const [passport_id, setPassportID] = useState<string | undefined>(user.type === "student" ? user.demographicInformation?.passport_id : undefined);
? user.demographicInformation?.position
: undefined
);
const [passport_id, setPassportID] = useState<string | undefined>(
user.type === "student"
? user.demographicInformation?.passport_id
: undefined
);
const [referralAgent, setReferralAgent] = useState( const [referralAgent, setReferralAgent] = useState(user.type === "corporate" ? user.corporateInformation?.referralAgent : undefined);
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.type === "agent" ? user.agentInformation?.commercialRegistration : undefined,
? user.agentInformation?.commercialRegistration
: undefined
); );
const [userAmount, setUserAmount] = useState( const [userAmount, setUserAmount] = useState(user.type === "corporate" ? user.corporateInformation?.companyInformation.userAmount : undefined);
user.type === "corporate" const [paymentValue, setPaymentValue] = useState(user.type === "corporate" ? user.corporateInformation?.payment?.value : undefined);
? user.corporateInformation?.companyInformation.userAmount const [paymentCurrency, setPaymentCurrency] = useState(user.type === "corporate" ? user.corporateInformation?.payment?.currency : "EUR");
: undefined const [monthlyDuration, setMonthlyDuration] = useState(user.type === "corporate" ? user.corporateInformation?.monthlyDuration : undefined);
); const [commissionValue, setCommission] = useState(user.type === "corporate" ? user.corporateInformation?.payment?.commission : undefined);
const [paymentValue, setPaymentValue] = useState( const {stats} = useStats(user.id);
user.type === "corporate" const {users} = useUsers();
? user.corporateInformation?.payment?.value const {codes} = useCodes(user.id);
: undefined const {permissions} = usePermissions(loggedInUser.id);
);
const [paymentCurrency, setPaymentCurrency] = useState(
user.type === "corporate"
? user.corporateInformation?.payment?.currency
: "EUR"
);
const [monthlyDuration, setMonthlyDuration] = useState(
user.type === "corporate"
? user.corporateInformation?.monthlyDuration
: undefined
);
const [commissionValue, setCommission] = useState(
user.type === "corporate"
? user.corporateInformation?.payment?.commission
: undefined
);
const { stats } = useStats(user.id);
const { users } = useUsers();
const { codes } = useCodes(user.id);
useEffect(() => { useEffect(() => {
if (users && users.length > 0) { if (users && users.length > 0) {
@@ -176,14 +116,11 @@ const UserCard = ({
const updateUser = () => { const updateUser = () => {
if (user.type === "corporate" && (!paymentValue || paymentValue < 0)) if (user.type === "corporate" && (!paymentValue || paymentValue < 0))
return toast.error( return toast.error("Please set a price for the user's package before updating!");
"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;
);
if (!confirm(`Are you sure you want to update ${user.name}'s account?`))
return;
axios axios
.post<{ user?: User; ok?: boolean }>(`/api/users/update?id=${user.id}`, { .post<{user?: User; ok?: boolean}>(`/api/users/update?id=${user.id}`, {
...user, ...user,
subscriptionExpirationDate: expiryDate, subscriptionExpirationDate: expiryDate,
type, type,
@@ -208,9 +145,7 @@ const UserCard = ({
payment: { payment: {
value: paymentValue, value: paymentValue,
currency: paymentCurrency, currency: paymentCurrency,
...(referralAgent === "" ...(referralAgent === "" ? {} : {commission: commissionValue}),
? {}
: { commission: commissionValue }),
}, },
} }
: undefined, : undefined,
@@ -220,15 +155,13 @@ const UserCard = ({
onClose(true); onClose(true);
}) })
.catch(() => { .catch(() => {
toast.error("Something went wrong!", { toastId: "update-error" }); toast.error("Something went wrong!", {toastId: "update-error"});
}); });
}; };
const generalProfileItems = [ const generalProfileItems = [
{ {
icon: ( icon: <BsFileEarmarkText className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />,
<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",
}, },
@@ -248,16 +181,12 @@ const UserCard = ({
user.type === "corporate" user.type === "corporate"
? [ ? [
{ {
icon: ( icon: <BsPerson className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />,
<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: ( icon: <BsPersonAdd className="w-6 h-6 md:w-8 md:h-8 text-mti-red-light" />,
<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",
}, },
@@ -270,14 +199,7 @@ const UserCard = ({
}; };
return ( return (
<> <>
<ProfileSummary <ProfileSummary user={user} items={user.type === "corporate" ? corporateProfileItems : generalProfileItems} />
user={user}
items={
user.type === "corporate"
? corporateProfileItems
: generalProfileItems
}
/>
{user.type === "agent" && ( {user.type === "agent" && (
<> <>
@@ -347,9 +269,7 @@ const UserCard = ({
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"> <label className="font-normal text-base text-mti-gray-dim">Pricing</label>
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"
@@ -362,17 +282,14 @@ const UserCard = ({
<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 && disabled && "!bg-mti-gray-platinum/40 !text-mti-gray-dim cursor-not-allowed",
"!bg-mti-gray-platinum/40 !text-mti-gray-dim cursor-not-allowed"
)} )}
options={CURRENCIES_OPTIONS} options={CURRENCIES_OPTIONS}
value={CURRENCIES_OPTIONS.find( value={CURRENCIES_OPTIONS.find((c) => c.value === paymentCurrency)}
(c) => c.value === paymentCurrency
)}
onChange={(value) => setPaymentCurrency(value?.value)} onChange={(value) => setPaymentCurrency(value?.value)}
menuPortalTarget={document?.body} menuPortalTarget={document?.body}
styles={{ styles={{
menuPortal: (base) => ({ ...base, zIndex: 9999 }), menuPortal: (base) => ({...base, zIndex: 9999}),
control: (styles) => ({ control: (styles) => ({
...styles, ...styles,
paddingLeft: "4px", paddingLeft: "4px",
@@ -384,11 +301,7 @@ const UserCard = ({
}), }),
option: (styles, state) => ({ option: (styles, state) => ({
...styles, ...styles,
backgroundColor: state.isFocused backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
? "#D5D9F0"
: state.isSelected
? "#7872BF"
: "white",
color: state.isFocused ? "black" : styles.color, color: state.isFocused ? "black" : styles.color,
}), }),
}} }}
@@ -399,22 +312,16 @@ const UserCard = ({
</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"> <label className="font-normal text-base text-mti-gray-dim">Country Manager</label>
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",
(checkAccess( (checkAccess(loggedInUser, getTypesOfUser(["developer", "admin"])) || disabledFields.countryManager) &&
loggedInUser, "!bg-mti-gray-platinum/40 !text-mti-gray-dim cursor-not-allowed",
getTypesOfUser(["developer", "admin"])
) ||
disabledFields.countryManager) &&
"!bg-mti-gray-platinum/40 !text-mti-gray-dim cursor-not-allowed"
)} )}
options={[ options={[
{ value: "", label: "No referral" }, {value: "", label: "No referral"},
...users ...users
.filter((u) => u.type === "agent") .filter((u) => u.type === "agent")
.map((x) => ({ .map((x) => ({
@@ -429,7 +336,7 @@ const UserCard = ({
menuPortalTarget={document?.body} menuPortalTarget={document?.body}
onChange={(value) => setReferralAgent(value?.value)} onChange={(value) => setReferralAgent(value?.value)}
styles={{ styles={{
menuPortal: (base) => ({ ...base, zIndex: 9999 }), menuPortal: (base) => ({...base, zIndex: 9999}),
control: (styles) => ({ control: (styles) => ({
...styles, ...styles,
paddingLeft: "4px", paddingLeft: "4px",
@@ -441,30 +348,19 @@ const UserCard = ({
}), }),
option: (styles, state) => ({ option: (styles, state) => ({
...styles, ...styles,
backgroundColor: state.isFocused backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
? "#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={ isDisabled={checkAccess(loggedInUser, getTypesOfUser(["developer", "admin"])) || disabledFields.countryManager}
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"> <label className="font-normal text-base text-mti-gray-dim">Commission</label>
Commission
</label>
<Input <Input
name="commissionValue" name="commissionValue"
onChange={(e) => setCommission(e ? parseInt(e) : undefined)} onChange={(e) => setCommission(e ? parseInt(e) : undefined)}
@@ -506,13 +402,8 @@ const UserCard = ({
<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"> <label className="font-normal text-base text-mti-gray-dim">Country</label>
Country <CountrySelect disabled value={user.demographicInformation?.country} />
</label>
<CountrySelect
disabled
value={user.demographicInformation?.country}
/>
</div> </div>
<Input <Input
type="tel" type="tel"
@@ -532,11 +423,7 @@ const UserCard = ({
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={ value={user.type === "student" ? user.demographicInformation?.passport_id : undefined}
user.type === "student"
? user.demographicInformation?.passport_id
: undefined
}
disabled disabled
required required
/> />
@@ -545,26 +432,22 @@ const UserCard = ({
<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"> <label className="font-normal text-base text-mti-gray-dim">Employment Status</label>
Employment Status
</label>
<RadioGroup <RadioGroup
value={user.demographicInformation?.employment} value={user.demographicInformation?.employment}
className="grid grid-cols-2 items-center gap-4 place-items-center" className="grid grid-cols-2 items-center gap-4 place-items-center"
disabled={disabled} disabled={disabled}>
> {EMPLOYMENT_STATUS.map(({status, label}) => (
{EMPLOYMENT_STATUS.map(({ status, label }) => (
<RadioGroup.Option value={status} key={status}> <RadioGroup.Option value={status} key={status}>
{({ checked }) => ( {({checked}) => (
<span <span
className={clsx( className={clsx(
"px-6 py-4 w-40 md:w-48 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer", "px-6 py-4 w-40 md:w-48 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"transition duration-300 ease-in-out", "transition duration-300 ease-in-out",
!checked !checked
? "bg-white border-mti-gray-platinum" ? "bg-white border-mti-gray-platinum"
: "bg-mti-purple-light border-mti-purple-dark text-white" : "bg-mti-purple-light border-mti-purple-dark text-white",
)} )}>
>
{label} {label}
</span> </span>
)} )}
@@ -587,55 +470,49 @@ const UserCard = ({
)} )}
<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"> <label className="font-normal text-base text-mti-gray-dim">Gender</label>
Gender
</label>
<RadioGroup <RadioGroup
value={user.demographicInformation?.gender} value={user.demographicInformation?.gender}
className="flex flex-row gap-4 justify-between" className="flex flex-row gap-4 justify-between"
disabled={disabled} disabled={disabled}>
>
<RadioGroup.Option value="male"> <RadioGroup.Option value="male">
{({ checked }) => ( {({checked}) => (
<span <span
className={clsx( className={clsx(
"px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer", "px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"transition duration-300 ease-in-out", "transition duration-300 ease-in-out",
!checked !checked
? "bg-white border-mti-gray-platinum" ? "bg-white border-mti-gray-platinum"
: "bg-mti-purple-light border-mti-purple-dark text-white" : "bg-mti-purple-light border-mti-purple-dark text-white",
)} )}>
>
Male Male
</span> </span>
)} )}
</RadioGroup.Option> </RadioGroup.Option>
<RadioGroup.Option value="female"> <RadioGroup.Option value="female">
{({ checked }) => ( {({checked}) => (
<span <span
className={clsx( className={clsx(
"px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer", "px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"transition duration-300 ease-in-out", "transition duration-300 ease-in-out",
!checked !checked
? "bg-white border-mti-gray-platinum" ? "bg-white border-mti-gray-platinum"
: "bg-mti-purple-light border-mti-purple-dark text-white" : "bg-mti-purple-light border-mti-purple-dark text-white",
)} )}>
>
Female Female
</span> </span>
)} )}
</RadioGroup.Option> </RadioGroup.Option>
<RadioGroup.Option value="other"> <RadioGroup.Option value="other">
{({ checked }) => ( {({checked}) => (
<span <span
className={clsx( className={clsx(
"px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer", "px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"transition duration-300 ease-in-out", "transition duration-300 ease-in-out",
!checked !checked
? "bg-white border-mti-gray-platinum" ? "bg-white border-mti-gray-platinum"
: "bg-mti-purple-light border-mti-purple-dark text-white" : "bg-mti-purple-light border-mti-purple-dark text-white",
)} )}>
>
Other Other
</span> </span>
)} )}
@@ -644,20 +521,11 @@ const UserCard = ({
</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"> <label className="font-normal text-base text-mti-gray-dim">Expiry Date</label>
Expiry Date
</label>
<Checkbox <Checkbox
isChecked={!!expiryDate} isChecked={!!expiryDate}
onChange={(checked) => onChange={(checked) => setExpiryDate(checked ? user.subscriptionExpirationDate || new Date() : null)}
setExpiryDate( disabled={disabled}>
checked
? user.subscriptionExpirationDate || new Date()
: null
)
}
disabled={disabled}
>
Enabled Enabled
</Checkbox> </Checkbox>
</div> </div>
@@ -666,12 +534,9 @@ const UserCard = ({
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 !expiryDate ? "!bg-mti-green-ultralight !border-mti-green-light" : expirationDateColor(expiryDate),
? "!bg-mti-green-ultralight !border-mti-green-light" "bg-white border-mti-gray-platinum",
: 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>
@@ -682,14 +547,12 @@ const UserCard = ({
"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(date).isBefore(moment(loggedInUser.subscriptionExpirationDate))
moment(loggedInUser.subscriptionExpirationDate)
)
: true) : true)
} }
dateFormat="dd/MM/yyyy" dateFormat="dd/MM/yyyy"
@@ -706,17 +569,13 @@ const UserCard = ({
<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"> <label className="font-normal text-base text-mti-gray-dim">Status</label>
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) => onChange={(value) => setStatus(value?.value as typeof user.status)}
setStatus(value?.value as typeof user.status)
}
styles={{ styles={{
control: (styles) => ({ control: (styles) => ({
...styles, ...styles,
@@ -727,14 +586,10 @@ const UserCard = ({
outline: "none", outline: "none",
}, },
}), }),
menuPortal: (base) => ({ ...base, zIndex: 9999 }), menuPortal: (base) => ({...base, zIndex: 9999}),
option: (styles, state) => ({ option: (styles, state) => ({
...styles, ...styles,
backgroundColor: state.isFocused backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
? "#D5D9F0"
: state.isSelected
? "#7872BF"
: "white",
color: state.isFocused ? "black" : styles.color, color: state.isFocused ? "black" : styles.color,
}), }),
}} }}
@@ -742,17 +597,13 @@ const UserCard = ({
/> />
</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"> <label className="font-normal text-base text-mti-gray-dim">Type</label>
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) => onChange={(value) => setType(value?.value as typeof user.type)}
setType(value?.value as typeof user.type)
}
styles={{ styles={{
control: (styles) => ({ control: (styles) => ({
...styles, ...styles,
@@ -763,14 +614,10 @@ const UserCard = ({
outline: "none", outline: "none",
}, },
}), }),
menuPortal: (base) => ({ ...base, zIndex: 9999 }), menuPortal: (base) => ({...base, zIndex: 9999}),
option: (styles, state) => ({ option: (styles, state) => ({
...styles, ...styles,
backgroundColor: state.isFocused backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
? "#D5D9F0"
: state.isSelected
? "#7872BF"
: "white",
color: state.isFocused ? "black" : styles.color, color: state.isFocused ? "black" : styles.color,
}), }),
}} }}
@@ -785,56 +632,29 @@ const UserCard = ({
<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 <Button className="w-full max-w-[200px]" variant="outline" color="rose" onClick={onViewCorporate}>
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 <Button className="w-full max-w-[200px]" variant="outline" color="rose" onClick={onViewStudents}>
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 <Button className="w-full max-w-[200px]" variant="outline" color="rose" onClick={onViewTeachers}>
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 <Button className="w-full max-w-[200px]" variant="outline" onClick={onClose}>
className="w-full max-w-[200px]"
variant="outline"
onClick={onClose}
>
Close Close
</Button> </Button>
<Button <Button
disabled={ disabled={disabled || !checkAccess(loggedInUser, updateUserPermission.list, permissions, updateUserPermission.perm)}
disabled ||
!checkAccess(
loggedInUser,
updateUserPermission.list,
updateUserPermission.perm
)
}
onClick={updateUser} onClick={updateUser}
className="w-full max-w-[200px]" className="w-full max-w-[200px]">
>
Update Update
</Button> </Button>
</div> </div>

View File

@@ -2,11 +2,11 @@
import Modal from "@/components/Modal"; import Modal from "@/components/Modal";
import useStats from "@/hooks/useStats"; import useStats from "@/hooks/useStats";
import useUsers from "@/hooks/useUsers"; import useUsers from "@/hooks/useUsers";
import { CorporateUser, Group, Stat, User } from "@/interfaces/user"; import {CorporateUser, Group, Stat, User} from "@/interfaces/user";
import UserList from "@/pages/(admin)/Lists/UserList"; import UserList from "@/pages/(admin)/Lists/UserList";
import { dateSorter } from "@/utils"; import {dateSorter} from "@/utils";
import moment from "moment"; import moment from "moment";
import { useEffect, useState } from "react"; import {useEffect, useState} from "react";
import { import {
BsArrowLeft, BsArrowLeft,
BsArrowRepeat, BsArrowRepeat,
@@ -31,44 +31,41 @@ import {
} from "react-icons/bs"; } from "react-icons/bs";
import UserCard from "@/components/UserCard"; import UserCard from "@/components/UserCard";
import useGroups from "@/hooks/useGroups"; import useGroups from "@/hooks/useGroups";
import { calculateAverageLevel, calculateBandScore } from "@/utils/score"; import {calculateAverageLevel, calculateBandScore} from "@/utils/score";
import { MODULE_ARRAY } from "@/utils/moduleUtils"; import {MODULE_ARRAY} from "@/utils/moduleUtils";
import { Module } from "@/interfaces"; import {Module} from "@/interfaces";
import { groupByExam } from "@/utils/stats"; import {groupByExam} from "@/utils/stats";
import IconCard from "./IconCard"; import IconCard from "./IconCard";
import GroupList from "@/pages/(admin)/Lists/GroupList"; import GroupList from "@/pages/(admin)/Lists/GroupList";
import useAssignments from "@/hooks/useAssignments"; import useAssignments from "@/hooks/useAssignments";
import { Assignment } from "@/interfaces/results"; import {Assignment} from "@/interfaces/results";
import AssignmentCard from "./AssignmentCard"; import AssignmentCard from "./AssignmentCard";
import Button from "@/components/Low/Button"; import Button from "@/components/Low/Button";
import clsx from "clsx"; import clsx from "clsx";
import ProgressBar from "@/components/Low/ProgressBar"; import ProgressBar from "@/components/Low/ProgressBar";
import AssignmentCreator from "./AssignmentCreator"; import AssignmentCreator from "./AssignmentCreator";
import AssignmentView from "./AssignmentView"; import AssignmentView from "./AssignmentView";
import { getUserCorporate } from "@/utils/groups"; import {getUserCorporate} from "@/utils/groups";
import { checkAccess } from "@/utils/permissions"; import {checkAccess} from "@/utils/permissions";
import usePermissions from "@/hooks/usePermissions";
interface Props { interface Props {
user: User; user: User;
} }
export default function TeacherDashboard({ user }: Props) { export default function TeacherDashboard({user}: Props) {
const [page, setPage] = useState(""); const [page, setPage] = useState("");
const [selectedUser, setSelectedUser] = useState<User>(); const [selectedUser, setSelectedUser] = useState<User>();
const [showModal, setShowModal] = useState(false); const [showModal, setShowModal] = useState(false);
const [selectedAssignment, setSelectedAssignment] = useState<Assignment>(); const [selectedAssignment, setSelectedAssignment] = useState<Assignment>();
const [isCreatingAssignment, setIsCreatingAssignment] = useState(false); const [isCreatingAssignment, setIsCreatingAssignment] = useState(false);
const [corporateUserToShow, setCorporateUserToShow] = const [corporateUserToShow, setCorporateUserToShow] = useState<CorporateUser>();
useState<CorporateUser>();
const { stats } = useStats(); const {stats} = useStats();
const { users, reload } = useUsers(); const {users, reload} = useUsers();
const { groups } = useGroups(user.id); const {groups} = useGroups(user.id);
const { const {permissions} = usePermissions(user.id);
assignments, const {assignments, isLoading: isAssignmentsLoading, reload: reloadAssignments} = useAssignments({assigner: user.id});
isLoading: isAssignmentsLoading,
reload: reloadAssignments,
} = useAssignments({ assigner: user.id });
useEffect(() => { useEffect(() => {
setShowModal(!!selectedUser && page === ""); setShowModal(!!selectedUser && page === "");
@@ -78,23 +75,15 @@ export default function TeacherDashboard({ user }: Props) {
getUserCorporate(user.id).then(setCorporateUserToShow); getUserCorporate(user.id).then(setCorporateUserToShow);
}, [user]); }, [user]);
const studentFilter = (user: User) => const studentFilter = (user: User) => user.type === "student" && groups.flatMap((g) => g.participants).includes(user.id);
user.type === "student" &&
groups.flatMap((g) => g.participants).includes(user.id);
const getStatsByStudent = (user: User) => const getStatsByStudent = (user: User) => stats.filter((s) => s.user === user.id);
stats.filter((s) => s.user === user.id);
const UserDisplay = (displayUser: User) => ( const UserDisplay = (displayUser: User) => (
<div <div
onClick={() => setSelectedUser(displayUser)} onClick={() => setSelectedUser(displayUser)}
className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300" className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300">
> <img src={displayUser.profilePicture} alt={displayUser.name} className="rounded-full w-10 h-10" />
<img
src={displayUser.profilePicture}
alt={displayUser.name}
className="rounded-full w-10 h-10"
/>
<div className="flex flex-col gap-1 items-start"> <div className="flex flex-col gap-1 items-start">
<span>{displayUser.name}</span> <span>{displayUser.name}</span>
<span className="text-sm opacity-75">{displayUser.email}</span> <span className="text-sm opacity-75">{displayUser.email}</span>
@@ -120,8 +109,7 @@ export default function TeacherDashboard({ user }: Props) {
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<div <div
onClick={() => setPage("")} onClick={() => setPage("")}
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300" className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
>
<BsArrowLeft className="text-xl" /> <BsArrowLeft className="text-xl" />
<span>Back</span> <span>Back</span>
</div> </div>
@@ -133,22 +121,18 @@ export default function TeacherDashboard({ user }: Props) {
}; };
const GroupsList = () => { const GroupsList = () => {
const filter = (x: Group) => const filter = (x: Group) => x.admin === user.id || x.participants.includes(user.id);
x.admin === user.id || x.participants.includes(user.id);
return ( return (
<> <>
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<div <div
onClick={() => setPage("")} onClick={() => setPage("")}
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300" className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
>
<BsArrowLeft className="text-xl" /> <BsArrowLeft className="text-xl" />
<span>Back</span> <span>Back</span>
</div> </div>
<h2 className="text-2xl font-semibold"> <h2 className="text-2xl font-semibold">Groups ({groups.filter(filter).length})</h2>
Groups ({groups.filter(filter).length})
</h2>
</div> </div>
<GroupList user={user} /> <GroupList user={user} />
@@ -166,15 +150,10 @@ export default function TeacherDashboard({ user }: Props) {
.filter((f) => !!f.focus); .filter((f) => !!f.focus);
const bandScores = formattedStats.map((s) => ({ const bandScores = formattedStats.map((s) => ({
module: s.module, module: s.module,
level: calculateBandScore( level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!),
s.score.correct,
s.score.total,
s.module,
s.focus!
),
})); }));
const levels: { [key in Module]: number } = { const levels: {[key in Module]: number} = {
reading: 0, reading: 0,
listening: 0, listening: 0,
writing: 0, writing: 0,
@@ -188,16 +167,10 @@ export default function TeacherDashboard({ user }: Props) {
const AssignmentsPage = () => { const AssignmentsPage = () => {
const activeFilter = (a: Assignment) => const activeFilter = (a: Assignment) =>
moment(a.endDate).isAfter(moment()) && moment(a.endDate).isAfter(moment()) && moment(a.startDate).isBefore(moment()) && a.assignees.length > a.results.length;
moment(a.startDate).isBefore(moment()) && const pastFilter = (a: Assignment) => (moment(a.endDate).isBefore(moment()) || a.assignees.length === a.results.length) && !a.archived;
a.assignees.length > a.results.length;
const pastFilter = (a: Assignment) =>
(moment(a.endDate).isBefore(moment()) ||
a.assignees.length === a.results.length) &&
!a.archived;
const archivedFilter = (a: Assignment) => a.archived; const archivedFilter = (a: Assignment) => a.archived;
const futureFilter = (a: Assignment) => const futureFilter = (a: Assignment) => moment(a.startDate).isAfter(moment());
moment(a.startDate).isAfter(moment());
return ( return (
<> <>
@@ -212,9 +185,7 @@ export default function TeacherDashboard({ user }: Props) {
/> />
<AssignmentCreator <AssignmentCreator
assignment={selectedAssignment} assignment={selectedAssignment}
groups={groups.filter( groups={groups.filter((x) => x.admin === user.id || x.participants.includes(user.id))}
(x) => x.admin === user.id || x.participants.includes(user.id)
)}
users={users.filter( users={users.filter(
(x) => (x) =>
x.type === "student" && x.type === "student" &&
@@ -223,7 +194,7 @@ export default function TeacherDashboard({ user }: Props) {
.filter((g) => g.admin === selectedUser.id) .filter((g) => g.admin === selectedUser.id)
.flatMap((g) => g.participants) .flatMap((g) => g.participants)
.includes(x.id) || false .includes(x.id) || false
: groups.flatMap((g) => g.participants).includes(x.id)) : groups.flatMap((g) => g.participants).includes(x.id)),
)} )}
assigner={user.id} assigner={user.id}
isCreating={isCreatingAssignment} isCreating={isCreatingAssignment}
@@ -236,47 +207,31 @@ export default function TeacherDashboard({ user }: Props) {
<div className="w-full flex justify-between items-center"> <div className="w-full flex justify-between items-center">
<div <div
onClick={() => setPage("")} onClick={() => setPage("")}
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300" className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
>
<BsArrowLeft className="text-xl" /> <BsArrowLeft className="text-xl" />
<span>Back</span> <span>Back</span>
</div> </div>
<div <div
onClick={reloadAssignments} onClick={reloadAssignments}
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300" className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
>
<span>Reload</span> <span>Reload</span>
<BsArrowRepeat <BsArrowRepeat className={clsx("text-xl", isAssignmentsLoading && "animate-spin")} />
className={clsx(
"text-xl",
isAssignmentsLoading && "animate-spin"
)}
/>
</div> </div>
</div> </div>
<section className="flex flex-col gap-4"> <section className="flex flex-col gap-4">
<h2 className="text-2xl font-semibold"> <h2 className="text-2xl font-semibold">Active Assignments ({assignments.filter(activeFilter).length})</h2>
Active Assignments ({assignments.filter(activeFilter).length})
</h2>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
{assignments.filter(activeFilter).map((a) => ( {assignments.filter(activeFilter).map((a) => (
<AssignmentCard <AssignmentCard {...a} onClick={() => setSelectedAssignment(a)} key={a.id} />
{...a}
onClick={() => setSelectedAssignment(a)}
key={a.id}
/>
))} ))}
</div> </div>
</section> </section>
<section className="flex flex-col gap-4"> <section className="flex flex-col gap-4">
<h2 className="text-2xl font-semibold"> <h2 className="text-2xl font-semibold">Planned Assignments ({assignments.filter(futureFilter).length})</h2>
Planned Assignments ({assignments.filter(futureFilter).length})
</h2>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
<div <div
onClick={() => setIsCreatingAssignment(true)} onClick={() => setIsCreatingAssignment(true)}
className="w-[250px] h-[200px] flex flex-col gap-2 items-center justify-center bg-white hover:bg-mti-purple-ultralight text-mti-purple-light hover:text-mti-purple-dark border border-mti-gray-platinum hover:drop-shadow p-4 cursor-pointer rounded-xl transition ease-in-out duration-300" className="w-[250px] h-[200px] flex flex-col gap-2 items-center justify-center bg-white hover:bg-mti-purple-ultralight text-mti-purple-light hover:text-mti-purple-dark border border-mti-gray-platinum hover:drop-shadow p-4 cursor-pointer rounded-xl transition ease-in-out duration-300">
>
<BsPlus className="text-6xl" /> <BsPlus className="text-6xl" />
<span className="text-lg">New Assignment</span> <span className="text-lg">New Assignment</span>
</div> </div>
@@ -293,9 +248,7 @@ export default function TeacherDashboard({ user }: Props) {
</div> </div>
</section> </section>
<section className="flex flex-col gap-4"> <section className="flex flex-col gap-4">
<h2 className="text-2xl font-semibold"> <h2 className="text-2xl font-semibold">Past Assignments ({assignments.filter(pastFilter).length})</h2>
Past Assignments ({assignments.filter(pastFilter).length})
</h2>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
{assignments.filter(pastFilter).map((a) => ( {assignments.filter(pastFilter).map((a) => (
<AssignmentCard <AssignmentCard
@@ -310,9 +263,7 @@ export default function TeacherDashboard({ user }: Props) {
</div> </div>
</section> </section>
<section className="flex flex-col gap-4"> <section className="flex flex-col gap-4">
<h2 className="text-2xl font-semibold"> <h2 className="text-2xl font-semibold">Archived Assignments ({assignments.filter(archivedFilter).length})</h2>
Archived Assignments ({assignments.filter(archivedFilter).length})
</h2>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
{assignments.filter(archivedFilter).map((a) => ( {assignments.filter(archivedFilter).map((a) => (
<AssignmentCard <AssignmentCard
@@ -334,19 +285,14 @@ export default function TeacherDashboard({ user }: Props) {
<> <>
{corporateUserToShow && ( {corporateUserToShow && (
<div className="absolute top-4 right-4 bg-neutral-200 px-2 rounded-lg py-1"> <div className="absolute top-4 right-4 bg-neutral-200 px-2 rounded-lg py-1">
Linked to:{" "} Linked to: <b>{corporateUserToShow?.corporateInformation?.companyInformation.name || corporateUserToShow.name}</b>
<b>
{corporateUserToShow?.corporateInformation?.companyInformation
.name || corporateUserToShow.name}
</b>
</div> </div>
)} )}
<section <section
className={clsx( className={clsx(
"flex -lg:flex-wrap gap-4 items-center -lg:justify-center lg:justify-start text-center", "flex -lg:flex-wrap gap-4 items-center -lg:justify-center lg:justify-start text-center",
!!corporateUserToShow && "mt-12 xl:mt-6" !!corporateUserToShow && "mt-12 xl:mt-6",
)} )}>
>
<IconCard <IconCard
onClick={() => setPage("students")} onClick={() => setPage("students")}
Icon={BsPersonFill} Icon={BsPersonFill}
@@ -357,42 +303,25 @@ export default function TeacherDashboard({ user }: Props) {
<IconCard <IconCard
Icon={BsClipboard2Data} Icon={BsClipboard2Data}
label="Exams Performed" label="Exams Performed"
value={ value={stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user)).length}
stats.filter((s) =>
groups.flatMap((g) => g.participants).includes(s.user)
).length
}
color="purple" color="purple"
/> />
<IconCard <IconCard
Icon={BsPaperclip} Icon={BsPaperclip}
label="Average Level" label="Average Level"
value={averageLevelCalculator( value={averageLevelCalculator(stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user))).toFixed(1)}
stats.filter((s) =>
groups.flatMap((g) => g.participants).includes(s.user)
)
).toFixed(1)}
color="purple" color="purple"
/> />
{checkAccess(user, ["teacher", "developer"], "viewGroup") && ( {checkAccess(user, ["teacher", "developer"], permissions, "viewGroup") && (
<IconCard <IconCard Icon={BsPeople} label="Groups" value={groups.length} color="purple" onClick={() => setPage("groups")} />
Icon={BsPeople}
label="Groups"
value={groups.length}
color="purple"
onClick={() => setPage("groups")}
/>
)} )}
<div <div
onClick={() => setPage("assignments")} onClick={() => setPage("assignments")}
className="bg-white rounded-xl shadow p-4 flex flex-col gap-4 items-center w-96 h-52 justify-center cursor-pointer hover:shadow-xl transition ease-in-out duration-300" className="bg-white rounded-xl shadow p-4 flex flex-col gap-4 items-center w-96 h-52 justify-center cursor-pointer hover:shadow-xl transition ease-in-out duration-300">
>
<BsEnvelopePaper className="text-6xl text-mti-purple-light" /> <BsEnvelopePaper className="text-6xl text-mti-purple-light" />
<span className="flex flex-col gap-1 items-center text-xl"> <span className="flex flex-col gap-1 items-center text-xl">
<span className="text-lg">Assignments</span> <span className="text-lg">Assignments</span>
<span className="font-semibold text-mti-purple-light"> <span className="font-semibold text-mti-purple-light">{assignments.filter((a) => !a.archived).length}</span>
{assignments.filter((a) => !a.archived).length}
</span>
</span> </span>
</div> </div>
</section> </section>
@@ -414,11 +343,7 @@ export default function TeacherDashboard({ user }: Props) {
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide"> <div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
{users {users
.filter(studentFilter) .filter(studentFilter)
.sort( .sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))
(a, b) =>
calculateAverageLevel(b.levels) -
calculateAverageLevel(a.levels)
)
.map((x) => ( .map((x) => (
<UserDisplay key={x.id} {...x} /> <UserDisplay key={x.id} {...x} />
))} ))}
@@ -431,8 +356,7 @@ export default function TeacherDashboard({ user }: Props) {
.filter(studentFilter) .filter(studentFilter)
.sort( .sort(
(a, b) => (a, b) =>
Object.keys(groupByExam(getStatsByStudent(b))).length - Object.keys(groupByExam(getStatsByStudent(b))).length - Object.keys(groupByExam(getStatsByStudent(a))).length,
Object.keys(groupByExam(getStatsByStudent(a))).length
) )
.map((x) => ( .map((x) => (
<UserDisplay key={x.id} {...x} /> <UserDisplay key={x.id} {...x} />
@@ -456,16 +380,9 @@ export default function TeacherDashboard({ user }: Props) {
if (shouldReload) reload(); if (shouldReload) reload();
}} }}
onViewStudents={ onViewStudents={
selectedUser.type === "corporate" || selectedUser.type === "corporate" || selectedUser.type === "teacher" ? () => setPage("students") : undefined
selectedUser.type === "teacher"
? () => setPage("students")
: undefined
}
onViewTeachers={
selectedUser.type === "corporate"
? () => setPage("teachers")
: undefined
} }
onViewTeachers={selectedUser.type === "corporate" ? () => setPage("teachers") : undefined}
user={selectedUser} user={selectedUser}
/> />
</div> </div>

View File

@@ -0,0 +1,29 @@
import {Exam} from "@/interfaces/exam";
import {Permission, PermissionType} from "@/interfaces/permissions";
import {ExamState} from "@/stores/examStore";
import axios from "axios";
import {useEffect, useState} from "react";
export default function usePermissions(user: string) {
const [permissions, setPermissions] = useState<PermissionType[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const getData = () => {
setIsLoading(true);
axios
.get<Permission[]>(`/api/permissions`)
.then((response) => {
const permissionTypes = response.data
.filter((x) => !x.users.includes(user))
.reduce((acc, curr) => [...acc, curr.type], [] as PermissionType[]);
console.log(response.data, permissionTypes);
setPermissions(permissionTypes);
})
.finally(() => setIsLoading(false));
};
useEffect(getData, [user]);
return {permissions, isLoading, isError, reload: getData};
}

View File

@@ -45,7 +45,8 @@ export const permissions = [
"deleteCodes", "deleteCodes",
// create options // create options
"createGroup", "createGroup",
"createCodes" "createCodes",
"all",
] as const; ] as const;
export type PermissionType = (typeof permissions)[keyof typeof permissions]; export type PermissionType = (typeof permissions)[keyof typeof permissions];

View File

@@ -1,29 +1,28 @@
import Button from "@/components/Low/Button"; import Button from "@/components/Low/Button";
import Checkbox from "@/components/Low/Checkbox"; import Checkbox from "@/components/Low/Checkbox";
import { PERMISSIONS } from "@/constants/userPermissions"; import {PERMISSIONS} from "@/constants/userPermissions";
import useUsers from "@/hooks/useUsers"; import useUsers from "@/hooks/useUsers";
import { Type, User } from "@/interfaces/user"; import {Type, User} from "@/interfaces/user";
import { USER_TYPE_LABELS } from "@/resources/user"; import {USER_TYPE_LABELS} from "@/resources/user";
import axios from "axios"; import axios from "axios";
import clsx from "clsx"; import clsx from "clsx";
import { capitalize, uniqBy } from "lodash"; import {capitalize, uniqBy} from "lodash";
import moment from "moment"; import moment from "moment";
import { useEffect, useState } from "react"; import {useEffect, useState} from "react";
import ReactDatePicker from "react-datepicker"; import ReactDatePicker from "react-datepicker";
import { toast } from "react-toastify"; import {toast} from "react-toastify";
import ShortUniqueId from "short-unique-id"; import ShortUniqueId from "short-unique-id";
import { useFilePicker } from "use-file-picker"; import {useFilePicker} from "use-file-picker";
import readXlsxFile from "read-excel-file"; import readXlsxFile from "read-excel-file";
import Modal from "@/components/Modal"; import Modal from "@/components/Modal";
import { BsFileEarmarkEaselFill, BsQuestionCircleFill } from "react-icons/bs"; import {BsFileEarmarkEaselFill, BsQuestionCircleFill} from "react-icons/bs";
import { checkAccess, getTypesOfUser } from "@/utils/permissions"; import {checkAccess, getTypesOfUser} from "@/utils/permissions";
import { PermissionType } from "@/interfaces/permissions"; import {PermissionType} from "@/interfaces/permissions";
const EMAIL_REGEX = new RegExp( import usePermissions from "@/hooks/usePermissions";
/^[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: { const USER_TYPE_PERMISSIONS: {
[key in Type]: { perm: PermissionType | undefined; list: Type[] }; [key in Type]: {perm: PermissionType | undefined; list: Type[]};
} = { } = {
student: { student: {
perm: "createCodeStudent", perm: "createCodeStudent",
@@ -47,46 +46,28 @@ const USER_TYPE_PERMISSIONS: {
}, },
admin: { admin: {
perm: "createCodeAdmin", perm: "createCodeAdmin",
list: [ list: ["student", "teacher", "agent", "corporate", "admin", "mastercorporate"],
"student",
"teacher",
"agent",
"corporate",
"admin",
"mastercorporate",
],
}, },
developer: { developer: {
perm: undefined, perm: undefined,
list: [ list: ["student", "teacher", "agent", "corporate", "admin", "developer", "mastercorporate"],
"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< const [infos, setInfos] = useState<{email: string; name: string; passport_id: string}[]>([]);
{ 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 user?.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).toDate() : null,
? moment(user.subscriptionExpirationDate).toDate()
: null
); );
const [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true); const [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true);
const [type, setType] = useState<Type>("student"); const [type, setType] = useState<Type>("student");
const [showHelp, setShowHelp] = useState(false); const [showHelp, setShowHelp] = useState(false);
const { users } = useUsers(); const {users} = useUsers();
const {permissions} = usePermissions(user?.id || "");
const { openFilePicker, filesContent, clear } = useFilePicker({ const {openFilePicker, filesContent, clear} = useFilePicker({
accept: ".xlsx", accept: ".xlsx",
multiple: false, multiple: false,
readAs: "ArrayBuffer", readAs: "ArrayBuffer",
@@ -104,14 +85,7 @@ export default function BatchCodeGenerator({ user }: { user: User }) {
const information = uniqBy( const information = uniqBy(
rows rows
.map((row) => { .map((row) => {
const [ const [firstName, lastName, country, passport_id, email, ...phone] = row as string[];
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(),
@@ -121,12 +95,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();
} }
@@ -134,7 +108,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();
} }
@@ -144,41 +118,24 @@ export default function BatchCodeGenerator({ user }: { user: User }) {
}, [filesContent]); }, [filesContent]);
const generateAndInvite = async () => { const generateAndInvite = async () => {
const newUsers = infos.filter( const newUsers = infos.filter((x) => !users.map((u) => u.email).includes(x.email));
(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 = const newUsersSentence = newUsers.length > 0 ? `generate ${newUsers.length} code(s)` : undefined;
newUsers.length > 0 ? `generate ${newUsers.length} code(s)` : undefined; const existingUsersSentence = existingUsers.length > 0 ? `invite ${existingUsers.length} registered student(s)` : undefined;
const existingUsersSentence =
existingUsers.length > 0
? `invite ${existingUsers.length} registered student(s)`
: undefined;
if ( if (
!confirm( !confirm(
`You are about to ${[newUsersSentence, existingUsersSentence] `You are about to ${[newUsersSentence, existingUsersSentence].filter((x) => !!x).join(" and ")}, are you sure you want to continue?`,
.filter((x) => !!x)
.join(" and ")}, are you sure you want to continue?`
) )
) )
return; return;
setIsLoading(true); setIsLoading(true);
Promise.all( Promise.all(existingUsers.map(async (u) => await axios.post(`/api/invites`, {to: u.id, from: user.id})))
existingUsers.map( .then(() => toast.success(`Successfully invited ${existingUsers.length} registered student(s)!`))
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);
}); });
@@ -193,30 +150,30 @@ export default function BatchCodeGenerator({ user }: { user: User }) {
setIsLoading(true); setIsLoading(true);
axios axios
.post<{ ok: boolean; valid?: number; reason?: string }>("/api/code", { .post<{ok: boolean; valid?: number; reason?: string}>("/api/code", {
type, type,
codes, codes,
infos: informations, infos: informations,
expiryDate, expiryDate,
}) })
.then(({ data, status }) => { .then(({data, status}) => {
if (data.ok) { if (data.ok) {
toast.success( toast.success(
`Successfully generated${ `Successfully generated${data.valid ? ` ${data.valid}/${informations.length}` : ""} ${capitalize(
data.valid ? ` ${data.valid}/${informations.length}` : "" type,
} ${capitalize(type)} codes and they have been notified by e-mail!`, )} codes and they have been notified by e-mail!`,
{ toastId: "success" } {toastId: "success"},
); );
return; return;
} }
if (status === 403) { if (status === 403) {
toast.error(data.reason, { toastId: "forbidden" }); toast.error(data.reason, {toastId: "forbidden"});
} }
}) })
.catch(({ response: { status, data } }) => { .catch(({response: {status, data}}) => {
if (status === 403) { if (status === 403) {
toast.error(data.reason, { toastId: "forbidden" }); toast.error(data.reason, {toastId: "forbidden"});
return; return;
} }
@@ -232,30 +189,18 @@ export default function BatchCodeGenerator({ user }: { user: User }) {
return ( return (
<> <>
<Modal <Modal isOpen={showHelp} onClose={() => setShowHelp(false)} title="Excel File Format">
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"> <th className="border border-neutral-200 px-2 py-1">First Name</th>
First Name <th className="border border-neutral-200 px-2 py-1">Last Name</th>
</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"> <th className="border border-neutral-200 px-2 py-1">Passport/National ID</th>
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"> <th className="border border-neutral-200 px-2 py-1">Phone Number</th>
Phone Number
</th>
</tr> </tr>
</thead> </thead>
</table> </table>
@@ -264,55 +209,27 @@ 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> <li>- You may have a header row with the format above, however, it is not necessary;</li>
- You may have a header row with the format above, however, it <li>- All of the e-mails in the file will receive an e-mail to join EnCoach with the role selected below.</li>
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"> <label className="text-mti-gray-dim text-base font-normal">Choose an Excel file</label>
Choose an Excel file <div className="tooltip cursor-pointer" data-tip="Excel File Format" onClick={() => setShowHelp(true)}>
</label>
<div
className="tooltip cursor-pointer"
data-tip="Excel File Format"
onClick={() => setShowHelp(true)}
>
<BsQuestionCircleFill /> <BsQuestionCircleFill />
</div> </div>
</div> </div>
<Button <Button onClick={openFilePicker} isLoading={isLoading} disabled={isLoading}>
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 && {user && checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"]) && (
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"> <label className="text-mti-gray-dim text-base font-normal">Expiry Date</label>
Expiry Date <Checkbox isChecked={isExpiryDateEnabled} onChange={setIsExpiryDateEnabled} disabled={!!user.subscriptionExpirationDate}>
</label>
<Checkbox
isChecked={isExpiryDateEnabled}
onChange={setIsExpiryDateEnabled}
disabled={!!user.subscriptionExpirationDate}
>
Enabled Enabled
</Checkbox> </Checkbox>
</div> </div>
@@ -321,13 +238,11 @@ 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 (user.subscriptionExpirationDate ? moment(date).isBefore(user.subscriptionExpirationDate) : true)
? moment(date).isBefore(user.subscriptionExpirationDate)
: true)
} }
dateFormat="dd/MM/yyyy" dateFormat="dd/MM/yyyy"
selected={expiryDate} selected={expiryDate}
@@ -336,19 +251,16 @@ export default function BatchCodeGenerator({ user }: { user: User }) {
)} )}
</> </>
)} )}
<label className="text-mti-gray-dim text-base font-normal"> <label className="text-mti-gray-dim text-base font-normal">Select the type of user they should be</label>
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) => { .filter((x) => {
const { list, perm } = USER_TYPE_PERMISSIONS[x as Type]; const {list, perm} = USER_TYPE_PERMISSIONS[x as Type];
return checkAccess(user, getTypesOfUser(list), perm); return checkAccess(user, getTypesOfUser(list), permissions, perm);
}) })
.map((type) => ( .map((type) => (
<option key={type} value={type}> <option key={type} value={type}>
@@ -357,17 +269,8 @@ export default function BatchCodeGenerator({ user }: { user: User }) {
))} ))}
</select> </select>
)} )}
{checkAccess( {checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"], permissions, "createCodes") && (
user, <Button onClick={generateAndInvite} disabled={infos.length === 0 || (isExpiryDateEnabled ? !expiryDate : false)}>
["developer", "admin", "corporate", "mastercorporate"],
"createCodes"
) && (
<Button
onClick={generateAndInvite}
disabled={
infos.length === 0 || (isExpiryDateEnabled ? !expiryDate : false)
}
>
Generate & Send Generate & Send
</Button> </Button>
)} )}

View File

@@ -1,21 +1,22 @@
import Button from "@/components/Low/Button"; import Button from "@/components/Low/Button";
import Checkbox from "@/components/Low/Checkbox"; import Checkbox from "@/components/Low/Checkbox";
import { PERMISSIONS } from "@/constants/userPermissions"; import {PERMISSIONS} from "@/constants/userPermissions";
import { Type, User } from "@/interfaces/user"; import {Type, User} from "@/interfaces/user";
import { USER_TYPE_LABELS } from "@/resources/user"; import {USER_TYPE_LABELS} from "@/resources/user";
import axios from "axios"; import axios from "axios";
import clsx from "clsx"; import clsx from "clsx";
import { capitalize } from "lodash"; import {capitalize} from "lodash";
import moment from "moment"; import moment from "moment";
import { useEffect, useState } from "react"; import {useEffect, useState} from "react";
import ReactDatePicker from "react-datepicker"; import ReactDatePicker from "react-datepicker";
import { toast } from "react-toastify"; import {toast} from "react-toastify";
import ShortUniqueId from "short-unique-id"; import ShortUniqueId from "short-unique-id";
import { checkAccess } from "@/utils/permissions"; import {checkAccess} from "@/utils/permissions";
import { PermissionType } from "@/interfaces/permissions"; import {PermissionType} from "@/interfaces/permissions";
import usePermissions from "@/hooks/usePermissions";
const USER_TYPE_PERMISSIONS: { const USER_TYPE_PERMISSIONS: {
[key in Type]: { perm: PermissionType | undefined; list: Type[] }; [key in Type]: {perm: PermissionType | undefined; list: Type[]};
} = { } = {
student: { student: {
perm: "createCodeStudent", perm: "createCodeStudent",
@@ -39,38 +40,22 @@ const USER_TYPE_PERMISSIONS: {
}, },
admin: { admin: {
perm: "createCodeAdmin", perm: "createCodeAdmin",
list: [ list: ["student", "teacher", "agent", "corporate", "admin", "mastercorporate"],
"student",
"teacher",
"agent",
"corporate",
"admin",
"mastercorporate",
],
}, },
developer: { developer: {
perm: undefined, perm: undefined,
list: [ list: ["student", "teacher", "agent", "corporate", "admin", "developer", "mastercorporate"],
"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 user?.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).toDate() : null,
? moment(user.subscriptionExpirationDate).toDate()
: null
); );
const [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true); const [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true);
const [type, setType] = useState<Type>("student"); const [type, setType] = useState<Type>("student");
const {permissions} = usePermissions(user?.id || "");
useEffect(() => { useEffect(() => {
if (!isExpiryDateEnabled) setExpiryDate(null); if (!isExpiryDateEnabled) setExpiryDate(null);
@@ -81,8 +66,8 @@ export default function CodeGenerator({ user }: { user: User }) {
const code = uid.randomUUID(6); const code = uid.randomUUID(6);
axios axios
.post("/api/code", { type, codes: [code], expiryDate }) .post("/api/code", {type, codes: [code], expiryDate})
.then(({ data, status }) => { .then(({data, status}) => {
if (data.ok) { if (data.ok) {
toast.success(`Successfully generated a ${capitalize(type)} code!`, { toast.success(`Successfully generated a ${capitalize(type)} code!`, {
toastId: "success", toastId: "success",
@@ -92,12 +77,12 @@ export default function CodeGenerator({ user }: { user: User }) {
} }
if (status === 403) { if (status === 403) {
toast.error(data.reason, { toastId: "forbidden" }); toast.error(data.reason, {toastId: "forbidden"});
} }
}) })
.catch(({ response: { status, data } }) => { .catch(({response: {status, data}}) => {
if (status === 403) { if (status === 403) {
toast.error(data.reason, { toastId: "forbidden" }); toast.error(data.reason, {toastId: "forbidden"});
return; return;
} }
@@ -109,19 +94,16 @@ export default function CodeGenerator({ user }: { user: User }) {
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"> <label className="font-normal text-base text-mti-gray-dim">User Code Generator</label>
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) => { .filter((x) => {
const { list, perm } = USER_TYPE_PERMISSIONS[x as Type]; const {list, perm} = USER_TYPE_PERMISSIONS[x as Type];
return checkAccess(user, list, perm); return checkAccess(user, list, permissions, perm);
}) })
.map((type) => ( .map((type) => (
<option key={type} value={type}> <option key={type} value={type}>
@@ -133,14 +115,8 @@ export default function CodeGenerator({ user }: { user: User }) {
{user && checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"]) && ( {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"> <label className="text-mti-gray-dim text-base font-normal">Expiry Date</label>
Expiry Date <Checkbox isChecked={isExpiryDateEnabled} onChange={setIsExpiryDateEnabled} disabled={!!user.subscriptionExpirationDate}>
</label>
<Checkbox
isChecked={isExpiryDateEnabled}
onChange={setIsExpiryDateEnabled}
disabled={!!user.subscriptionExpirationDate}
>
Enabled Enabled
</Checkbox> </Checkbox>
</div> </div>
@@ -149,13 +125,11 @@ 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 (user.subscriptionExpirationDate ? moment(date).isBefore(user.subscriptionExpirationDate) : true)
? moment(date).isBefore(user.subscriptionExpirationDate)
: true)
} }
dateFormat="dd/MM/yyyy" dateFormat="dd/MM/yyyy"
selected={expiryDate} selected={expiryDate}
@@ -164,35 +138,25 @@ export default function CodeGenerator({ user }: { user: User }) {
)} )}
</> </>
)} )}
{checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"], 'createCodes') && ( {checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"], permissions, "createCodes") && (
<Button <Button onClick={() => generateCode(type)} disabled={isExpiryDateEnabled ? !expiryDate : false}>
onClick={() => generateCode(type)}
disabled={isExpiryDateEnabled ? !expiryDate : false}
>
Generate Generate
</Button> </Button>
)} )}
<label className="font-normal text-base text-mti-gray-dim"> <label className="font-normal text-base text-mti-gray-dim">Generated Code:</label>
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 && ( {generatedCode && <span className="text-sm text-mti-gray-dim font-light">Give this code to the user to complete their registration</span>}
<span className="text-sm text-mti-gray-dim font-light">
Give this code to the user to complete their registration
</span>
)}
</div> </div>
); );
} }

View File

@@ -4,26 +4,22 @@ import Select from "@/components/Low/Select";
import useCodes from "@/hooks/useCodes"; import useCodes from "@/hooks/useCodes";
import useUser from "@/hooks/useUser"; import useUser from "@/hooks/useUser";
import useUsers from "@/hooks/useUsers"; import useUsers from "@/hooks/useUsers";
import { Code, User } from "@/interfaces/user"; import {Code, User} from "@/interfaces/user";
import { USER_TYPE_LABELS } from "@/resources/user"; import {USER_TYPE_LABELS} from "@/resources/user";
import { import {createColumnHelper, flexRender, getCoreRowModel, useReactTable} from "@tanstack/react-table";
createColumnHelper,
flexRender,
getCoreRowModel,
useReactTable,
} from "@tanstack/react-table";
import axios from "axios"; import axios from "axios";
import moment from "moment"; import moment from "moment";
import { useEffect, useState, useMemo } from "react"; import {useEffect, useState, useMemo} from "react";
import { BsTrash } from "react-icons/bs"; import {BsTrash} from "react-icons/bs";
import { toast } from "react-toastify"; import {toast} from "react-toastify";
import ReactDatePicker from "react-datepicker"; import ReactDatePicker from "react-datepicker";
import clsx from "clsx"; import clsx from "clsx";
import { checkAccess } from "@/utils/permissions"; import {checkAccess} from "@/utils/permissions";
import usePermissions from "@/hooks/usePermissions";
const columnHelper = createColumnHelper<Code>(); const columnHelper = createColumnHelper<Code>();
const CreatorCell = ({ id, users }: { id: string; users: User[] }) => { const CreatorCell = ({id, users}: {id: string; users: User[]}) => {
const [creatorUser, setCreatorUser] = useState<User>(); const [creatorUser, setCreatorUser] = useState<User>();
useEffect(() => { useEffect(() => {
@@ -32,30 +28,24 @@ const CreatorCell = ({ id, users }: { id: string; users: User[] }) => {
return ( return (
<> <>
{(creatorUser?.type === "corporate" {(creatorUser?.type === "corporate" ? creatorUser?.corporateInformation?.companyInformation?.name : creatorUser?.name || "N/A") || "N/A"}{" "}
? creatorUser?.corporateInformation?.companyInformation?.name
: creatorUser?.name || "N/A") || "N/A"}{" "}
{creatorUser && `(${USER_TYPE_LABELS[creatorUser.type]})`} {creatorUser && `(${USER_TYPE_LABELS[creatorUser.type]})`}
</> </>
); );
}; };
export default function CodeList({ user }: { user: User }) { export default function CodeList({user}: {user: User}) {
const [selectedCodes, setSelectedCodes] = useState<string[]>([]); const [selectedCodes, setSelectedCodes] = useState<string[]>([]);
const [filteredCorporate, setFilteredCorporate] = useState<User | undefined>( const [filteredCorporate, setFilteredCorporate] = useState<User | undefined>(user?.type === "corporate" ? user : undefined);
user?.type === "corporate" ? user : undefined const [filterAvailability, setFilterAvailability] = useState<"in-use" | "unused">();
);
const [filterAvailability, setFilterAvailability] = useState< const {permissions} = usePermissions(user?.id || "");
"in-use" | "unused"
>();
// const [filteredCodes, setFilteredCodes] = useState<Code[]>([]); // const [filteredCodes, setFilteredCodes] = useState<Code[]>([]);
const { users } = useUsers(); const {users} = useUsers();
const { codes, reload } = useCodes( const {codes, reload} = useCodes(user?.type === "corporate" ? user?.id : undefined);
user?.type === "corporate" ? user?.id : undefined
);
const [startDate, setStartDate] = useState<Date | null>(moment("01/01/2023").toDate()); const [startDate, setStartDate] = useState<Date | null>(moment("01/01/2023").toDate());
const [endDate, setEndDate] = useState<Date | null>(moment().endOf("day").toDate()); const [endDate, setEndDate] = useState<Date | null>(moment().endOf("day").toDate());
@@ -63,9 +53,9 @@ export default function CodeList({ user }: { user: User }) {
return codes.filter((x) => { return codes.filter((x) => {
// TODO: if the expiry date is missing, it does not make sense to filter by date // TODO: if the expiry date is missing, it does not make sense to filter by date
// so we need to find a way to handle this edge case // so we need to find a way to handle this edge case
if(startDate && endDate && x.expiryDate) { if (startDate && endDate && x.expiryDate) {
const date = moment(x.expiryDate); const date = moment(x.expiryDate);
if(date.isBefore(startDate) || date.isAfter(endDate)) { if (date.isBefore(startDate) || date.isAfter(endDate)) {
return false; return false;
} }
} }
@@ -80,25 +70,17 @@ export default function CodeList({ user }: { user: User }) {
}, [codes, startDate, endDate, filteredCorporate, filterAvailability]); }, [codes, startDate, endDate, filteredCorporate, filterAvailability]);
const toggleCode = (id: string) => { const toggleCode = (id: string) => {
setSelectedCodes((prev) => setSelectedCodes((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
);
}; };
const toggleAllCodes = (checked: boolean) => { const toggleAllCodes = (checked: boolean) => {
if (checked) if (checked) return setSelectedCodes(filteredCodes.filter((x) => !x.userId).map((x) => x.code));
return setSelectedCodes(
filteredCodes.filter((x) => !x.userId).map((x) => x.code)
);
return setSelectedCodes([]); return setSelectedCodes([]);
}; };
const deleteCodes = async (codes: string[]) => { const deleteCodes = async (codes: string[]) => {
if ( if (!confirm(`Are you sure you want to delete these ${codes.length} code(s)?`)) return;
!confirm(`Are you sure you want to delete these ${codes.length} code(s)?`)
)
return;
const params = new URLSearchParams(); const params = new URLSearchParams();
codes.forEach((code) => params.append("code", code)); codes.forEach((code) => params.append("code", code));
@@ -126,8 +108,7 @@ export default function CodeList({ user }: { user: User }) {
}; };
const deleteCode = async (code: Code) => { const deleteCode = async (code: Code) => {
if (!confirm(`Are you sure you want to delete this "${code.code}" code?`)) if (!confirm(`Are you sure you want to delete this "${code.code}" code?`)) return;
return;
axios axios
.delete(`/api/code/${code.code}`) .delete(`/api/code/${code.code}`)
@@ -148,11 +129,7 @@ export default function CodeList({ user }: { user: User }) {
.finally(reload); .finally(reload);
}; };
const allowedToDelete = checkAccess( const allowedToDelete = checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"], permissions, "deleteCodes");
user,
["developer", "admin", "corporate", "mastercorporate"],
"deleteCodes"
);
const defaultColumns = [ const defaultColumns = [
columnHelper.accessor("code", { columnHelper.accessor("code", {
@@ -161,21 +138,15 @@ export default function CodeList({ user }: { user: User }) {
<Checkbox <Checkbox
disabled={filteredCodes.filter((x) => !x.userId).length === 0} disabled={filteredCodes.filter((x) => !x.userId).length === 0}
isChecked={ isChecked={
selectedCodes.length === selectedCodes.length === filteredCodes.filter((x) => !x.userId).length && filteredCodes.filter((x) => !x.userId).length > 0
filteredCodes.filter((x) => !x.userId).length &&
filteredCodes.filter((x) => !x.userId).length > 0
} }
onChange={(checked) => toggleAllCodes(checked)} onChange={(checked) => toggleAllCodes(checked)}>
>
{""} {""}
</Checkbox> </Checkbox>
), ),
cell: (info) => cell: (info) =>
!info.row.original.userId ? ( !info.row.original.userId ? (
<Checkbox <Checkbox isChecked={selectedCodes.includes(info.getValue())} onChange={() => toggleCode(info.getValue())}>
isChecked={selectedCodes.includes(info.getValue())}
onChange={() => toggleCode(info.getValue())}
>
{""} {""}
</Checkbox> </Checkbox>
) : null, ) : null,
@@ -186,8 +157,7 @@ export default function CodeList({ user }: { user: User }) {
}), }),
columnHelper.accessor("creationDate", { columnHelper.accessor("creationDate", {
header: "Creation Date", header: "Creation Date",
cell: (info) => cell: (info) => (info.getValue() ? moment(info.getValue()).format("DD/MM/YYYY") : "N/A"),
info.getValue() ? moment(info.getValue()).format("DD/MM/YYYY") : "N/A",
}), }),
columnHelper.accessor("email", { columnHelper.accessor("email", {
header: "Invited E-mail", header: "Invited E-mail",
@@ -213,15 +183,11 @@ export default function CodeList({ user }: { user: User }) {
{ {
header: "", header: "",
id: "actions", id: "actions",
cell: ({ row }: { row: { original: Code } }) => { cell: ({row}: {row: {original: Code}}) => {
return ( return (
<div className="flex gap-4"> <div className="flex gap-4">
{allowedToDelete && !row.original.userId && ( {allowedToDelete && !row.original.userId && (
<div <div data-tip="Delete" className="cursor-pointer tooltip" onClick={() => deleteCode(row.original)}>
data-tip="Delete"
className="cursor-pointer tooltip"
onClick={() => deleteCode(row.original)}
>
<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>
)} )}
@@ -251,8 +217,7 @@ export default function CodeList({ user }: { user: User }) {
? { ? {
label: `${ label: `${
filteredCorporate.type === "corporate" filteredCorporate.type === "corporate"
? filteredCorporate.corporateInformation ? filteredCorporate.corporateInformation?.companyInformation?.name || filteredCorporate.name
?.companyInformation?.name || filteredCorporate.name
: filteredCorporate.name : filteredCorporate.name
} (${USER_TYPE_LABELS[filteredCorporate.type]})`, } (${USER_TYPE_LABELS[filteredCorporate.type]})`,
value: filteredCorporate.id, value: filteredCorporate.id,
@@ -260,37 +225,25 @@ export default function CodeList({ user }: { user: User }) {
: null : null
} }
options={users options={users
.filter((x) => .filter((x) => ["admin", "developer", "corporate"].includes(x.type))
["admin", "developer", "corporate"].includes(x.type)
)
.map((x) => ({ .map((x) => ({
label: `${ label: `${x.type === "corporate" ? x.corporateInformation?.companyInformation?.name || x.name : x.name} (${
x.type === "corporate" USER_TYPE_LABELS[x.type]
? x.corporateInformation?.companyInformation?.name || x.name })`,
: x.name
} (${USER_TYPE_LABELS[x.type]})`,
value: x.id, value: x.id,
user: x, user: x,
}))} }))}
onChange={(value) => onChange={(value) => setFilteredCorporate(value ? users.find((x) => x.id === value?.value) : undefined)}
setFilteredCorporate(
value ? users.find((x) => x.id === value?.value) : undefined
)
}
/> />
<Select <Select
className="!w-96 !py-1" className="!w-96 !py-1"
placeholder="Availability" placeholder="Availability"
isClearable isClearable
options={[ options={[
{ label: "In Use", value: "in-use" }, {label: "In Use", value: "in-use"},
{ label: "Unused", value: "unused" }, {label: "Unused", value: "unused"},
]} ]}
onChange={(value) => onChange={(value) => setFilterAvailability(value ? (value.value as typeof filterAvailability) : undefined)}
setFilterAvailability(
value ? (value.value as typeof filterAvailability) : undefined
)
}
/> />
<ReactDatePicker <ReactDatePicker
dateFormat="dd/MM/yyyy" dateFormat="dd/MM/yyyy"
@@ -300,9 +253,7 @@ export default function CodeList({ user }: { user: User }) {
endDate={endDate} endDate={endDate}
selectsRange selectsRange
showMonthDropdown showMonthDropdown
filterDate={(date: Date) => filterDate={(date: Date) => moment(date).isSameOrBefore(moment(new 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) {
@@ -323,8 +274,7 @@ export default function CodeList({ user }: { user: User }) {
variant="outline" variant="outline"
color="red" color="red"
className="!py-1 px-10" className="!py-1 px-10"
onClick={() => deleteCodes(selectedCodes)} onClick={() => deleteCodes(selectedCodes)}>
>
Delete Delete
</Button> </Button>
</div> </div>
@@ -336,12 +286,7 @@ export default function CodeList({ user }: { user: User }) {
<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 {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</th> </th>
))} ))}
</tr> </tr>
@@ -349,10 +294,7 @@ export default function CodeList({ user }: { user: User }) {
</thead> </thead>
<tbody className="px-2"> <tbody className="px-2">
{table.getRowModel().rows.map((row) => ( {table.getRowModel().rows.map((row) => (
<tr <tr className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2" key={row.id}>
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())}

View File

@@ -3,39 +3,25 @@ import Input from "@/components/Low/Input";
import Modal from "@/components/Modal"; import Modal from "@/components/Modal";
import useGroups from "@/hooks/useGroups"; import useGroups from "@/hooks/useGroups";
import useUsers from "@/hooks/useUsers"; import useUsers from "@/hooks/useUsers";
import { CorporateUser, Group, User } from "@/interfaces/user"; import {CorporateUser, Group, User} from "@/interfaces/user";
import { import {createColumnHelper, flexRender, getCoreRowModel, useReactTable} from "@tanstack/react-table";
createColumnHelper,
flexRender,
getCoreRowModel,
useReactTable,
} from "@tanstack/react-table";
import axios from "axios"; import axios from "axios";
import { capitalize, uniq } from "lodash"; import {capitalize, uniq} from "lodash";
import { useEffect, useState } from "react"; import {useEffect, useState} from "react";
import { BsPencil, BsQuestionCircleFill, BsTrash } from "react-icons/bs"; import {BsPencil, BsQuestionCircleFill, BsTrash} from "react-icons/bs";
import Select from "react-select"; import Select from "react-select";
import { toast } from "react-toastify"; import {toast} from "react-toastify";
import readXlsxFile from "read-excel-file"; import readXlsxFile from "read-excel-file";
import { useFilePicker } from "use-file-picker"; import {useFilePicker} from "use-file-picker";
import { getUserCorporate } from "@/utils/groups"; import {getUserCorporate} from "@/utils/groups";
import { isAgentUser, isCorporateUser } from "@/resources/user"; import {isAgentUser, isCorporateUser} from "@/resources/user";
import { checkAccess } from "@/utils/permissions"; import {checkAccess} from "@/utils/permissions";
import usePermissions from "@/hooks/usePermissions";
const columnHelper = createColumnHelper<Group>(); const columnHelper = createColumnHelper<Group>();
const EMAIL_REGEX = new RegExp( const EMAIL_REGEX = new RegExp(/^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$/);
/^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$/
);
const LinkedCorporate = ({ const LinkedCorporate = ({userId, users, groups}: {userId: string; users: User[]; groups: Group[]}) => {
userId,
users,
groups,
}: {
userId: string;
users: User[];
groups: Group[];
}) => {
const [companyName, setCompanyName] = useState(""); const [companyName, setCompanyName] = useState("");
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
@@ -43,33 +29,19 @@ const LinkedCorporate = ({
const user = users.find((u) => u.id === userId); const user = users.find((u) => u.id === userId);
if (!user) return setCompanyName(""); if (!user) return setCompanyName("");
if (isCorporateUser(user)) if (isCorporateUser(user)) return setCompanyName(user.corporateInformation?.companyInformation?.name || user.name);
return setCompanyName( if (isAgentUser(user)) return setCompanyName(user.agentInformation?.companyName || user.name);
user.corporateInformation?.companyInformation?.name || user.name
);
if (isAgentUser(user))
return setCompanyName(user.agentInformation?.companyName || user.name);
const belongingGroups = groups.filter((x) => const belongingGroups = groups.filter((x) => x.participants.includes(userId));
x.participants.includes(userId) const belongingGroupsAdmins = belongingGroups.map((x) => users.find((u) => u.id === x.admin)).filter((x) => !!x && isCorporateUser(x));
);
const belongingGroupsAdmins = belongingGroups
.map((x) => users.find((u) => u.id === x.admin))
.filter((x) => !!x && isCorporateUser(x));
if (belongingGroupsAdmins.length === 0) return setCompanyName(""); if (belongingGroupsAdmins.length === 0) return setCompanyName("");
const admin = belongingGroupsAdmins[0] as CorporateUser; const admin = belongingGroupsAdmins[0] as CorporateUser;
setCompanyName( setCompanyName(admin.corporateInformation?.companyInformation.name || admin.name);
admin.corporateInformation?.companyInformation.name || admin.name
);
}, [userId, users, groups]); }, [userId, users, groups]);
return isLoading ? ( return isLoading ? <span className="animate-pulse">Loading...</span> : <>{companyName}</>;
<span className="animate-pulse">Loading...</span>
) : (
<>{companyName}</>
);
}; };
interface CreateDialogProps { interface CreateDialogProps {
@@ -79,17 +51,13 @@ interface CreateDialogProps {
onClose: () => void; onClose: () => void;
} }
const CreatePanel = ({ user, users, group, onClose }: CreateDialogProps) => { const CreatePanel = ({user, users, group, onClose}: CreateDialogProps) => {
const [name, setName] = useState<string | undefined>( const [name, setName] = useState<string | undefined>(group?.name || undefined);
group?.name || undefined
);
const [admin, setAdmin] = useState<string>(group?.admin || user.id); const [admin, setAdmin] = useState<string>(group?.admin || user.id);
const [participants, setParticipants] = useState<string[]>( const [participants, setParticipants] = useState<string[]>(group?.participants || []);
group?.participants || []
);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const { openFilePicker, filesContent, clear } = useFilePicker({ const {openFilePicker, filesContent, clear} = useFilePicker({
accept: ".xlsx", accept: ".xlsx",
multiple: false, multiple: false,
readAs: "ArrayBuffer", readAs: "ArrayBuffer",
@@ -105,12 +73,9 @@ const CreatePanel = ({ user, users, group, onClose }: CreateDialogProps) => {
rows rows
.map((row) => { .map((row) => {
const [email] = row as string[]; const [email] = row as string[];
return EMAIL_REGEX.test(email) && return EMAIL_REGEX.test(email) && !users.map((u) => u.email).includes(email) ? email.toString().trim() : undefined;
!users.map((u) => u.email).includes(email)
? email.toString().trim()
: undefined;
}) })
.filter((x) => !!x) .filter((x) => !!x),
); );
if (emails.length === 0) { if (emails.length === 0) {
@@ -120,17 +85,12 @@ const CreatePanel = ({ user, users, group, onClose }: CreateDialogProps) => {
return; return;
} }
const emailUsers = [...new Set(emails)] const emailUsers = [...new Set(emails)].map((x) => users.find((y) => y.email.toLowerCase() === x)).filter((x) => x !== undefined);
.map((x) => users.find((y) => y.email.toLowerCase() === x))
.filter((x) => x !== undefined);
const filteredUsers = emailUsers.filter( const filteredUsers = emailUsers.filter(
(x) => (x) =>
((user.type === "developer" || ((user.type === "developer" || user.type === "admin" || user.type === "corporate" || user.type === "mastercorporate") &&
user.type === "admin" ||
user.type === "corporate" ||
user.type === "mastercorporate") &&
(x?.type === "student" || x?.type === "teacher")) || (x?.type === "student" || x?.type === "teacher")) ||
(user.type === "teacher" && x?.type === "student") (user.type === "teacher" && x?.type === "student"),
); );
setParticipants(filteredUsers.filter((x) => !!x).map((x) => x!.id)); setParticipants(filteredUsers.filter((x) => !!x).map((x) => x!.id));
@@ -138,7 +98,7 @@ const CreatePanel = ({ user, users, group, onClose }: CreateDialogProps) => {
user.type !== "teacher" user.type !== "teacher"
? "Added all teachers and students found in the file you've provided!" ? "Added all teachers and students found in the file you've provided!"
: "Added all students found in the file you've provided!", : "Added all students found in the file you've provided!",
{ toastId: "upload-success" } {toastId: "upload-success"},
); );
setIsLoading(false); setIsLoading(false);
}); });
@@ -150,21 +110,14 @@ const CreatePanel = ({ user, users, group, onClose }: CreateDialogProps) => {
setIsLoading(true); setIsLoading(true);
if (name !== group?.name && (name === "Students" || name === "Teachers")) { if (name !== group?.name && (name === "Students" || name === "Teachers")) {
toast.error( toast.error("That group name is reserved and cannot be used, please enter another one.");
"That group name is reserved and cannot be used, please enter another one."
);
setIsLoading(false); setIsLoading(false);
return; return;
} }
(group ? axios.patch : axios.post)( (group ? axios.patch : axios.post)(group ? `/api/groups/${group.id}` : "/api/groups", {name, admin, participants})
group ? `/api/groups/${group.id}` : "/api/groups",
{ name, admin, participants }
)
.then(() => { .then(() => {
toast.success( toast.success(`Group "${name}" ${group ? "edited" : "created"} successfully`);
`Group "${name}" ${group ? "edited" : "created"} successfully`
);
return true; return true;
}) })
.catch(() => { .catch(() => {
@@ -180,24 +133,11 @@ const CreatePanel = ({ user, users, group, onClose }: CreateDialogProps) => {
return ( return (
<div className="mt-4 flex w-full flex-col gap-12 px-4 py-2"> <div className="mt-4 flex w-full flex-col gap-12 px-4 py-2">
<div className="flex flex-col gap-8"> <div className="flex flex-col gap-8">
<Input <Input name="name" type="text" label="Name" defaultValue={name} onChange={setName} required disabled={group?.disableEditing} />
name="name"
type="text"
label="Name"
defaultValue={name}
onChange={setName}
required
disabled={group?.disableEditing}
/>
<div className="flex w-full flex-col gap-3"> <div className="flex w-full flex-col gap-3">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<label className="text-mti-gray-dim text-base font-normal"> <label className="text-mti-gray-dim text-base font-normal">Participants</label>
Participants <div className="tooltip" data-tip="The Excel file should only include a column with the desired e-mails.">
</label>
<div
className="tooltip"
data-tip="The Excel file should only include a column with the desired e-mails."
>
<BsQuestionCircleFill /> <BsQuestionCircleFill />
</div> </div>
</div> </div>
@@ -206,30 +146,22 @@ const CreatePanel = ({ user, users, group, onClose }: CreateDialogProps) => {
className="w-full" className="w-full"
value={participants.map((x) => ({ value={participants.map((x) => ({
value: x, value: x,
label: `${users.find((y) => y.id === x)?.email} - ${ label: `${users.find((y) => y.id === x)?.email} - ${users.find((y) => y.id === x)?.name}`,
users.find((y) => y.id === x)?.name
}`,
}))} }))}
placeholder="Participants..." placeholder="Participants..."
defaultValue={participants.map((x) => ({ defaultValue={participants.map((x) => ({
value: x, value: x,
label: `${users.find((y) => y.id === x)?.email} - ${ label: `${users.find((y) => y.id === x)?.email} - ${users.find((y) => y.id === x)?.name}`,
users.find((y) => y.id === x)?.name
}`,
}))} }))}
options={users options={users
.filter((x) => .filter((x) => (user.type === "teacher" ? x.type === "student" : x.type === "student" || x.type === "teacher"))
user.type === "teacher" .map((x) => ({value: x.id, label: `${x.email} - ${x.name}`}))}
? x.type === "student"
: x.type === "student" || x.type === "teacher"
)
.map((x) => ({ value: x.id, label: `${x.email} - ${x.name}` }))}
onChange={(value) => setParticipants(value.map((x) => x.value))} onChange={(value) => setParticipants(value.map((x) => x.value))}
isMulti isMulti
isSearchable isSearchable
menuPortalTarget={document?.body} menuPortalTarget={document?.body}
styles={{ styles={{
menuPortal: (base) => ({ ...base, zIndex: 9999 }), menuPortal: (base) => ({...base, zIndex: 9999}),
control: (styles) => ({ control: (styles) => ({
...styles, ...styles,
backgroundColor: "white", backgroundColor: "white",
@@ -240,36 +172,18 @@ const CreatePanel = ({ user, users, group, onClose }: CreateDialogProps) => {
}} }}
/> />
{user.type !== "teacher" && ( {user.type !== "teacher" && (
<Button <Button className="w-full max-w-[300px]" onClick={openFilePicker} isLoading={isLoading} variant="outline">
className="w-full max-w-[300px]" {filesContent.length === 0 ? "Upload participants Excel file" : filesContent[0].name}
onClick={openFilePicker}
isLoading={isLoading}
variant="outline"
>
{filesContent.length === 0
? "Upload participants Excel file"
: filesContent[0].name}
</Button> </Button>
)} )}
</div> </div>
</div> </div>
</div> </div>
<div className="mt-8 flex w-full items-center justify-end gap-8"> <div className="mt-8 flex w-full items-center justify-end gap-8">
<Button <Button variant="outline" color="red" className="w-full max-w-[200px]" isLoading={isLoading} onClick={onClose}>
variant="outline"
color="red"
className="w-full max-w-[200px]"
isLoading={isLoading}
onClick={onClose}
>
Cancel Cancel
</Button> </Button>
<Button <Button className="w-full max-w-[200px]" onClick={submit} isLoading={isLoading} disabled={!name}>
className="w-full max-w-[200px]"
onClick={submit}
isLoading={isLoading}
disabled={!name}
>
Submit Submit
</Button> </Button>
</div> </div>
@@ -279,22 +193,18 @@ const CreatePanel = ({ user, users, group, onClose }: CreateDialogProps) => {
const filterTypes = ["corporate", "teacher", "mastercorporate"]; const filterTypes = ["corporate", "teacher", "mastercorporate"];
export default function GroupList({ user }: { user: User }) { export default function GroupList({user}: {user: User}) {
const [isCreating, setIsCreating] = useState(false); const [isCreating, setIsCreating] = useState(false);
const [editingGroup, setEditingGroup] = useState<Group>(); const [editingGroup, setEditingGroup] = useState<Group>();
const [filterByUser, setFilterByUser] = useState(false); const [filterByUser, setFilterByUser] = useState(false);
const { users } = useUsers(); const {permissions} = usePermissions(user?.id || "");
const { groups, reload } = useGroups(
user && filterTypes.includes(user?.type) ? user.id : undefined, const {users} = useUsers();
user?.type const {groups, reload} = useGroups(user && filterTypes.includes(user?.type) ? user.id : undefined, user?.type);
);
useEffect(() => { useEffect(() => {
if ( if (user && ["corporate", "teacher", "mastercorporate"].includes(user.type)) {
user &&
["corporate", "teacher", "mastercorporate"].includes(user.type)
) {
setFilterByUser(true); setFilterByUser(true);
} }
}, [user]); }, [user]);
@@ -303,7 +213,7 @@ export default function GroupList({ user }: { user: User }) {
if (!confirm(`Are you sure you want to delete "${group.name}"?`)) return; if (!confirm(`Are you sure you want to delete "${group.name}"?`)) return;
axios axios
.delete<{ ok: boolean }>(`/api/groups/${group.id}`) .delete<{ok: boolean}>(`/api/groups/${group.id}`)
.then(() => toast.success(`Group "${group.name}" deleted successfully`)) .then(() => toast.success(`Group "${group.name}" deleted successfully`))
.catch(() => toast.error("Something went wrong, please try again later!")) .catch(() => toast.error("Something went wrong, please try again later!"))
.finally(reload); .finally(reload);
@@ -321,25 +231,14 @@ export default function GroupList({ user }: { user: User }) {
columnHelper.accessor("admin", { columnHelper.accessor("admin", {
header: "Admin", header: "Admin",
cell: (info) => ( cell: (info) => (
<div <div className="tooltip" data-tip={capitalize(users.find((x) => x.id === info.getValue())?.type)}>
className="tooltip"
data-tip={capitalize(
users.find((x) => x.id === info.getValue())?.type
)}
>
{users.find((x) => x.id === info.getValue())?.name} {users.find((x) => x.id === info.getValue())?.name}
</div> </div>
), ),
}), }),
columnHelper.accessor("admin", { columnHelper.accessor("admin", {
header: "Linked Corporate", header: "Linked Corporate",
cell: (info) => ( cell: (info) => <LinkedCorporate userId={info.getValue()} users={users} groups={groups} />,
<LinkedCorporate
userId={info.getValue()}
users={users}
groups={groups}
/>
),
}), }),
columnHelper.accessor("participants", { columnHelper.accessor("participants", {
header: "Participants", header: "Participants",
@@ -352,32 +251,18 @@ export default function GroupList({ user }: { user: User }) {
{ {
header: "", header: "",
id: "actions", id: "actions",
cell: ({ row }: { row: { original: Group } }) => { cell: ({row}: {row: {original: Group}}) => {
return ( return (
<> <>
{user && {user && (checkAccess(user, ["developer", "admin"]) || user.id === row.original.admin) && (
(checkAccess(user, ["developer", "admin"]) ||
user.id === row.original.admin) && (
<div className="flex gap-2"> <div className="flex gap-2">
{(!row.original.disableEditing || {(!row.original.disableEditing || checkAccess(user, ["developer", "admin"]), "editGroup") && (
checkAccess(user, ["developer", "admin"]), <div data-tip="Edit" className="tooltip cursor-pointer" onClick={() => setEditingGroup(row.original)}>
"editGroup") && (
<div
data-tip="Edit"
className="tooltip cursor-pointer"
onClick={() => setEditingGroup(row.original)}
>
<BsPencil className="hover:text-mti-purple-light transition duration-300 ease-in-out" /> <BsPencil className="hover:text-mti-purple-light transition duration-300 ease-in-out" />
</div> </div>
)} )}
{(!row.original.disableEditing || {(!row.original.disableEditing || checkAccess(user, ["developer", "admin"]), "deleteGroup") && (
checkAccess(user, ["developer", "admin"]), <div data-tip="Delete" className="tooltip cursor-pointer" onClick={() => deleteGroup(row.original)}>
"deleteGroup") && (
<div
data-tip="Delete"
className="tooltip cursor-pointer"
onClick={() => deleteGroup(row.original)}
>
<BsTrash className="hover:text-mti-purple-light transition duration-300 ease-in-out" /> <BsTrash className="hover:text-mti-purple-light transition duration-300 ease-in-out" />
</div> </div>
)} )}
@@ -403,11 +288,7 @@ export default function GroupList({ user }: { user: User }) {
return ( return (
<div className="h-full w-full rounded-xl"> <div className="h-full w-full rounded-xl">
<Modal <Modal isOpen={isCreating || !!editingGroup} onClose={closeModal} title={editingGroup ? `Editing ${editingGroup.name}` : "New Group"}>
isOpen={isCreating || !!editingGroup}
onClose={closeModal}
title={editingGroup ? `Editing ${editingGroup.name}` : "New Group"}
>
<CreatePanel <CreatePanel
group={editingGroup} group={editingGroup}
user={user} user={user}
@@ -419,8 +300,7 @@ export default function GroupList({ user }: { user: User }) {
groups groups
.filter((g) => g.admin === user.id) .filter((g) => g.admin === user.id)
.flatMap((g) => g.participants) .flatMap((g) => g.participants)
.includes(u.id) || .includes(u.id) || groups.flatMap((g) => g.participants).includes(u.id),
groups.flatMap((g) => g.participants).includes(u.id)
) )
: users : users
} }
@@ -432,12 +312,7 @@ export default function GroupList({ user }: { user: User }) {
<tr key={headerGroup.id}> <tr key={headerGroup.id}>
{headerGroup.headers.map((header) => ( {headerGroup.headers.map((header) => (
<th className="py-4" key={header.id}> <th className="py-4" key={header.id}>
{header.isPlaceholder {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</th> </th>
))} ))}
</tr> </tr>
@@ -445,10 +320,7 @@ export default function GroupList({ user }: { user: User }) {
</thead> </thead>
<tbody className="px-2"> <tbody className="px-2">
{table.getRowModel().rows.map((row) => ( {table.getRowModel().rows.map((row) => (
<tr <tr className="even:bg-mti-purple-ultralight/40 rounded-lg py-2 odd:bg-white" key={row.id}>
className="even:bg-mti-purple-ultralight/40 rounded-lg py-2 odd:bg-white"
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())}
@@ -459,15 +331,10 @@ export default function GroupList({ user }: { user: User }) {
</tbody> </tbody>
</table> </table>
{checkAccess( {checkAccess(user, ["teacher", "corporate", "mastercorporate", "admin", "developer"], permissions, "createGroup") && (
user,
["teacher", "corporate", "mastercorporate", "admin", "developer"],
"createGroup"
) && (
<button <button
onClick={() => setIsCreating(true)} onClick={() => setIsCreating(true)}
className="bg-mti-purple-light hover:bg-mti-purple w-full py-2 text-white transition duration-300 ease-in-out" className="bg-mti-purple-light hover:bg-mti-purple w-full py-2 text-white transition duration-300 ease-in-out">
>
New Group New Group
</button> </button>
)} )}

View File

@@ -1,66 +1,36 @@
import Button from "@/components/Low/Button"; import Button from "@/components/Low/Button";
import { PERMISSIONS } from "@/constants/userPermissions"; import {PERMISSIONS} from "@/constants/userPermissions";
import useGroups from "@/hooks/useGroups"; import useGroups from "@/hooks/useGroups";
import useUsers from "@/hooks/useUsers"; import useUsers from "@/hooks/useUsers";
import { Type, User, userTypes, CorporateUser, Group } from "@/interfaces/user"; import {Type, User, userTypes, CorporateUser, Group} from "@/interfaces/user";
import { Popover, Transition } from "@headlessui/react"; import {Popover, Transition} from "@headlessui/react";
import { import {createColumnHelper, flexRender, getCoreRowModel, useReactTable} from "@tanstack/react-table";
createColumnHelper,
flexRender,
getCoreRowModel,
useReactTable,
} from "@tanstack/react-table";
import axios from "axios"; import axios from "axios";
import clsx from "clsx"; import clsx from "clsx";
import { capitalize, reverse } from "lodash"; import {capitalize, reverse} from "lodash";
import moment from "moment"; import moment from "moment";
import { Fragment, useEffect, useState } from "react"; import {Fragment, useEffect, useState} from "react";
import { import {BsArrowDown, BsArrowDownUp, BsArrowUp, BsCheck, BsCheckCircle, BsEye, BsFillExclamationOctagonFill, BsPerson, BsTrash} from "react-icons/bs";
BsArrowDown, import {toast} from "react-toastify";
BsArrowDownUp, import {countries, TCountries} from "countries-list";
BsArrowUp,
BsCheck,
BsCheckCircle,
BsEye,
BsFillExclamationOctagonFill,
BsPerson,
BsTrash,
} from "react-icons/bs";
import { toast } from "react-toastify";
import { countries, TCountries } from "countries-list";
import countryCodes from "country-codes-list"; import countryCodes from "country-codes-list";
import Modal from "@/components/Modal"; import Modal from "@/components/Modal";
import UserCard from "@/components/UserCard"; import UserCard from "@/components/UserCard";
import { import {getUserCompanyName, isAgentUser, USER_TYPE_LABELS} from "@/resources/user";
getUserCompanyName,
isAgentUser,
USER_TYPE_LABELS,
} from "@/resources/user";
import useFilterStore from "@/stores/listFilterStore"; import useFilterStore from "@/stores/listFilterStore";
import { useRouter } from "next/router"; import {useRouter} from "next/router";
import { isCorporateUser } from "@/resources/user"; import {isCorporateUser} from "@/resources/user";
import { useListSearch } from "@/hooks/useListSearch"; 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 {checkAccess} from "@/utils/permissions";
import { PermissionType } from "@/interfaces/permissions"; import {PermissionType} from "@/interfaces/permissions";
import usePermissions from "@/hooks/usePermissions";
const columnHelper = createColumnHelper<User>(); const columnHelper = createColumnHelper<User>();
const searchFields = [ const searchFields = [["name"], ["email"], ["corporateInformation", "companyInformation", "name"]];
["name"],
["email"],
["corporateInformation", "companyInformation", "name"],
];
const CompanyNameCell = ({ const CompanyNameCell = ({users, user, groups}: {user: User; users: User[]; groups: Group[]}) => {
users,
user,
groups,
}: {
user: User;
users: User[];
groups: Group[];
}) => {
const [companyName, setCompanyName] = useState(""); const [companyName, setCompanyName] = useState("");
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
@@ -69,11 +39,7 @@ const CompanyNameCell = ({
setCompanyName(name); setCompanyName(name);
}, [user, users, groups]); }, [user, users, groups]);
return isLoading ? ( return isLoading ? <span className="animate-pulse">Loading...</span> : <>{companyName}</>;
<span className="animate-pulse">Loading...</span>
) : (
<>{companyName}</>
);
}; };
export default function UserList({ export default function UserList({
@@ -85,18 +51,14 @@ export default function UserList({
filters?: ((user: User) => boolean)[]; filters?: ((user: User) => boolean)[];
renderHeader?: (total: number) => JSX.Element; renderHeader?: (total: number) => JSX.Element;
}) { }) {
const [showDemographicInformation, setShowDemographicInformation] = const [showDemographicInformation, setShowDemographicInformation] = useState(false);
useState(false);
const [sorter, setSorter] = useState<string>(); const [sorter, setSorter] = useState<string>();
const [displayUsers, setDisplayUsers] = useState<User[]>([]); const [displayUsers, setDisplayUsers] = useState<User[]>([]);
const [selectedUser, setSelectedUser] = useState<User>(); const [selectedUser, setSelectedUser] = useState<User>();
const { users, reload } = useUsers(); const {users, reload} = useUsers();
const { groups } = useGroups( const {permissions} = usePermissions(user?.id || "");
user && ["corporate", "teacher", "mastercorporate"].includes(user?.type) const {groups} = useGroups(user && ["corporate", "teacher", "mastercorporate"].includes(user?.type) ? user.id : undefined);
? user.id
: undefined
);
const appendUserFilters = useFilterStore((state) => state.appendUserFilter); const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
const router = useRouter(); const router = useRouter();
@@ -105,13 +67,10 @@ export default function UserList({
const momentDate = moment(date); const momentDate = moment(date);
const today = moment(new Date()); const today = moment(new Date());
if (today.isAfter(momentDate)) if (today.isAfter(momentDate)) return "!text-mti-red-light font-bold line-through";
return "!text-mti-red-light font-bold line-through";
if (today.add(1, "weeks").isAfter(momentDate)) return "!text-mti-red-light"; if (today.add(1, "weeks").isAfter(momentDate)) return "!text-mti-red-light";
if (today.add(2, "weeks").isAfter(momentDate)) if (today.add(2, "weeks").isAfter(momentDate)) return "!text-mti-rose-light";
return "!text-mti-rose-light"; if (today.add(1, "months").isAfter(momentDate)) return "!text-mti-orange-light";
if (today.add(1, "months").isAfter(momentDate))
return "!text-mti-orange-light";
}; };
useEffect(() => { useEffect(() => {
@@ -119,19 +78,11 @@ export default function UserList({
if (user && users) { if (user && users) {
const filterUsers = const filterUsers =
user.type === "corporate" || user.type === "teacher" user.type === "corporate" || user.type === "teacher"
? users.filter((u) => ? users.filter((u) => groups.flatMap((g) => g.participants).includes(u.id))
groups.flatMap((g) => g.participants).includes(u.id)
)
: users; : users;
const filteredUsers = filters.reduce( const filteredUsers = filters.reduce((d, f) => d.filter(f), filterUsers);
(d, f) => d.filter(f), const sortedUsers = await asyncSorter<User>(filteredUsers, sortFunction);
filterUsers
);
const sortedUsers = await asyncSorter<User>(
filteredUsers,
sortFunction
);
setDisplayUsers([...sortedUsers]); setDisplayUsers([...sortedUsers]);
} }
@@ -140,33 +91,25 @@ export default function UserList({
}, [user, users, sorter, groups]); }, [user, users, sorter, groups]);
const deleteAccount = (user: User) => { const deleteAccount = (user: User) => {
if (!confirm(`Are you sure you want to delete ${user.name}'s account?`)) if (!confirm(`Are you sure you want to delete ${user.name}'s account?`)) return;
return;
axios axios
.delete<{ ok: boolean }>(`/api/user?id=${user.id}`) .delete<{ok: boolean}>(`/api/user?id=${user.id}`)
.then(() => { .then(() => {
toast.success("User deleted successfully!"); toast.success("User deleted successfully!");
reload(); reload();
}) })
.catch(() => { .catch(() => {
toast.error("Something went wrong!", { toastId: "delete-error" }); toast.error("Something went wrong!", {toastId: "delete-error"});
}) })
.finally(reload); .finally(reload);
}; };
const updateAccountType = (user: User, type: Type) => { const updateAccountType = (user: User, type: Type) => {
if ( if (!confirm(`Are you sure you want to update ${user.name}'s account from ${capitalize(user.type)} to ${capitalize(type)}?`)) return;
!confirm(
`Are you sure you want to update ${
user.name
}'s account from ${capitalize(user.type)} to ${capitalize(type)}?`
)
)
return;
axios axios
.post<{ user?: User; ok?: boolean }>(`/api/users/update?id=${user.id}`, { .post<{user?: User; ok?: boolean}>(`/api/users/update?id=${user.id}`, {
...user, ...user,
type, type,
}) })
@@ -175,13 +118,13 @@ export default function UserList({
reload(); reload();
}) })
.catch(() => { .catch(() => {
toast.error("Something went wrong!", { toastId: "update-error" }); toast.error("Something went wrong!", {toastId: "update-error"});
}); });
}; };
const verifyAccount = (user: User) => { const verifyAccount = (user: User) => {
axios axios
.post<{ user?: User; ok?: boolean }>(`/api/users/update?id=${user.id}`, { .post<{user?: User; ok?: boolean}>(`/api/users/update?id=${user.id}`, {
...user, ...user,
isVerified: true, isVerified: true,
}) })
@@ -190,48 +133,42 @@ export default function UserList({
reload(); reload();
}) })
.catch(() => { .catch(() => {
toast.error("Something went wrong!", { toastId: "update-error" }); toast.error("Something went wrong!", {toastId: "update-error"});
}); });
}; };
const toggleDisableAccount = (user: User) => { const toggleDisableAccount = (user: User) => {
if ( if (
!confirm( !confirm(
`Are you sure you want to ${ `Are you sure you want to ${user.status === "disabled" ? "enable" : "disable"} ${
user.status === "disabled" ? "enable" : "disable"
} ${
user.name user.name
}'s account? This change is usually related to their payment state.` }'s account? This change is usually related to their payment state.`,
) )
) )
return; return;
axios axios
.post<{ user?: User; ok?: boolean }>(`/api/users/update?id=${user.id}`, { .post<{user?: User; ok?: boolean}>(`/api/users/update?id=${user.id}`, {
...user, ...user,
status: user.status === "disabled" ? "active" : "disabled", status: user.status === "disabled" ? "active" : "disabled",
}) })
.then(() => { .then(() => {
toast.success( toast.success(`User ${user.status === "disabled" ? "enabled" : "disabled"} successfully!`);
`User ${
user.status === "disabled" ? "enabled" : "disabled"
} successfully!`
);
reload(); reload();
}) })
.catch(() => { .catch(() => {
toast.error("Something went wrong!", { toastId: "update-error" }); toast.error("Something went wrong!", {toastId: "update-error"});
}); });
}; };
const SorterArrow = ({ name }: { name: string }) => { const SorterArrow = ({name}: {name: string}) => {
if (sorter === name) return <BsArrowUp />; if (sorter === name) return <BsArrowUp />;
if (sorter === reverseString(name)) return <BsArrowDown />; if (sorter === reverseString(name)) return <BsArrowDown />;
return <BsArrowDownUp />; return <BsArrowDownUp />;
}; };
const actionColumn = ({ row }: { row: { original: User } }) => { const actionColumn = ({row}: {row: {original: User}}) => {
const updateUserPermission = PERMISSIONS.updateUser[row.original.type] as { const updateUserPermission = PERMISSIONS.updateUser[row.original.type] as {
list: Type[]; list: Type[];
perm: PermissionType; perm: PermissionType;
@@ -242,11 +179,7 @@ export default function UserList({
}; };
return ( return (
<div className="flex gap-4"> <div className="flex gap-4">
{checkAccess( {checkAccess(user, updateUserPermission.list, permissions, updateUserPermission.perm) && (
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">
@@ -260,48 +193,31 @@ export default function UserList({
enterTo="opacity-100 translate-y-0" enterTo="opacity-100 translate-y-0"
leave="transition ease-in duration-150" leave="transition ease-in duration-150"
leaveFrom="opacity-100 translate-y-0" leaveFrom="opacity-100 translate-y-0"
leaveTo="opacity-0 translate-y-1" leaveTo="opacity-0 translate-y-1">
>
<Popover.Panel className="absolute z-10 w-screen right-1/2 translate-x-1/3 max-w-sm"> <Popover.Panel className="absolute z-10 w-screen right-1/2 translate-x-1/3 max-w-sm">
<div className="bg-white p-4 rounded-lg grid grid-cols-2 gap-2 w-full drop-shadow-xl"> <div className="bg-white p-4 rounded-lg grid grid-cols-2 gap-2 w-full drop-shadow-xl">
<Button <Button
onClick={() => updateAccountType(row.original, "student")} onClick={() => updateAccountType(row.original, "student")}
className="text-sm !py-2 !px-4" className="text-sm !py-2 !px-4"
disabled={ disabled={row.original.type === "student" || !PERMISSIONS.generateCode["student"].includes(user.type)}>
row.original.type === "student" ||
!PERMISSIONS.generateCode["student"].includes(user.type)
}
>
Student Student
</Button> </Button>
<Button <Button
onClick={() => updateAccountType(row.original, "teacher")} onClick={() => updateAccountType(row.original, "teacher")}
className="text-sm !py-2 !px-4" className="text-sm !py-2 !px-4"
disabled={ disabled={row.original.type === "teacher" || !PERMISSIONS.generateCode["teacher"].includes(user.type)}>
row.original.type === "teacher" ||
!PERMISSIONS.generateCode["teacher"].includes(user.type)
}
>
Teacher Teacher
</Button> </Button>
<Button <Button
onClick={() => updateAccountType(row.original, "corporate")} onClick={() => updateAccountType(row.original, "corporate")}
className="text-sm !py-2 !px-4" className="text-sm !py-2 !px-4"
disabled={ disabled={row.original.type === "corporate" || !PERMISSIONS.generateCode["corporate"].includes(user.type)}>
row.original.type === "corporate" ||
!PERMISSIONS.generateCode["corporate"].includes(user.type)
}
>
Corporate Corporate
</Button> </Button>
<Button <Button
onClick={() => updateAccountType(row.original, "admin")} onClick={() => updateAccountType(row.original, "admin")}
className="text-sm !py-2 !px-4" className="text-sm !py-2 !px-4"
disabled={ disabled={row.original.type === "admin" || !PERMISSIONS.generateCode["admin"].includes(user.type)}>
row.original.type === "admin" ||
!PERMISSIONS.generateCode["admin"].includes(user.type)
}
>
Admin Admin
</Button> </Button>
</div> </div>
@@ -309,34 +225,16 @@ export default function UserList({
</Transition> </Transition>
</Popover> </Popover>
)} )}
{!row.original.isVerified && {!row.original.isVerified && checkAccess(user, updateUserPermission.list, permissions, updateUserPermission.perm) && (
checkAccess( <div data-tip="Verify User" className="cursor-pointer tooltip" onClick={() => verifyAccount(row.original)}>
user,
updateUserPermission.list,
updateUserPermission.perm
) && (
<div
data-tip="Verify User"
className="cursor-pointer tooltip"
onClick={() => verifyAccount(row.original)}
>
<BsCheck className="hover:text-mti-purple-light transition ease-in-out duration-300" /> <BsCheck className="hover:text-mti-purple-light transition ease-in-out duration-300" />
</div> </div>
)} )}
{checkAccess( {checkAccess(user, updateUserPermission.list, permissions, updateUserPermission.perm) && (
user,
updateUserPermission.list,
updateUserPermission.perm
) && (
<div <div
data-tip={ data-tip={row.original.status === "disabled" ? "Enable User" : "Disable User"}
row.original.status === "disabled"
? "Enable User"
: "Disable User"
}
className="cursor-pointer tooltip" className="cursor-pointer tooltip"
onClick={() => toggleDisableAccount(row.original)} onClick={() => toggleDisableAccount(row.original)}>
>
{row.original.status === "disabled" ? ( {row.original.status === "disabled" ? (
<BsCheckCircle className="hover:text-mti-purple-light transition ease-in-out duration-300" /> <BsCheckCircle className="hover:text-mti-purple-light transition ease-in-out duration-300" />
) : ( ) : (
@@ -344,16 +242,8 @@ export default function UserList({
)} )}
</div> </div>
)} )}
{checkAccess( {checkAccess(user, deleteUserPermission.list, permissions, deleteUserPermission.perm) && (
user, <div data-tip="Delete" className="cursor-pointer tooltip" onClick={() => deleteAccount(row.original)}>
deleteUserPermission.list,
deleteUserPermission.perm
) && (
<div
data-tip="Delete"
className="cursor-pointer tooltip"
onClick={() => deleteAccount(row.original)}
>
<BsTrash className="hover:text-mti-purple-light transition ease-in-out duration-300" /> <BsTrash className="hover:text-mti-purple-light transition ease-in-out duration-300" />
</div> </div>
)} )}
@@ -364,60 +254,39 @@ export default function UserList({
const demographicColumns = [ const demographicColumns = [
columnHelper.accessor("name", { columnHelper.accessor("name", {
header: ( header: (
<button <button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "name"))}>
className="flex gap-2 items-center"
onClick={() => setSorter((prev) => selectSorter(prev, "name"))}
>
<span>Name</span> <span>Name</span>
<SorterArrow name="name" /> <SorterArrow name="name" />
</button> </button>
) as any, ) as any,
cell: ({ row, getValue }) => ( cell: ({row, getValue}) => (
<div <div
className={clsx( className={clsx(
PERMISSIONS.updateExpiryDate[row.original.type]?.includes( PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type) &&
user.type "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={() => onClick={() => (PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type) ? setSelectedUser(row.original) : null)}>
PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type)
? setSelectedUser(row.original)
: null
}
>
{getValue()} {getValue()}
</div> </div>
), ),
}), }),
columnHelper.accessor("demographicInformation.country", { columnHelper.accessor("demographicInformation.country", {
header: ( header: (
<button <button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "country"))}>
className="flex gap-2 items-center"
onClick={() => setSorter((prev) => selectSorter(prev, "country"))}
>
<span>Country</span> <span>Country</span>
<SorterArrow name="country" /> <SorterArrow name="country" />
</button> </button>
) as any, ) as any,
cell: (info) => cell: (info) =>
info.getValue() info.getValue()
? `${ ? `${countryCodes.findOne("countryCode" as any, info.getValue()).flag} ${
countryCodes.findOne("countryCode" as any, info.getValue()).flag
} ${
countries[info.getValue() as unknown as keyof TCountries].name countries[info.getValue() as unknown as keyof TCountries].name
} (+${ } (+${countryCodes.findOne("countryCode" as any, info.getValue()).countryCallingCode})`
countryCodes.findOne("countryCode" as any, info.getValue())
.countryCallingCode
})`
: "Not available", : "Not available",
}), }),
columnHelper.accessor("demographicInformation.phone", { columnHelper.accessor("demographicInformation.phone", {
header: ( header: (
<button <button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "phone"))}>
className="flex gap-2 items-center"
onClick={() => setSorter((prev) => selectSorter(prev, "phone"))}
>
<span>Phone</span> <span>Phone</span>
<SorterArrow name="phone" /> <SorterArrow name="phone" />
</button> </button>
@@ -427,35 +296,22 @@ export default function UserList({
}), }),
columnHelper.accessor( columnHelper.accessor(
(x) => (x) =>
x.type === "corporate" || x.type === "mastercorporate" x.type === "corporate" || x.type === "mastercorporate" ? x.demographicInformation?.position : x.demographicInformation?.employment,
? x.demographicInformation?.position
: x.demographicInformation?.employment,
{ {
id: "employment", id: "employment",
header: ( header: (
<button <button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "employment"))}>
className="flex gap-2 items-center"
onClick={() =>
setSorter((prev) => selectSorter(prev, "employment"))
}
>
<span>Employment/Position</span> <span>Employment/Position</span>
<SorterArrow name="employment" /> <SorterArrow name="employment" />
</button> </button>
) as any, ) as any,
cell: (info) => cell: (info) => (info.row.original.type === "corporate" ? info.getValue() : capitalize(info.getValue())) || "Not available",
(info.row.original.type === "corporate"
? info.getValue()
: capitalize(info.getValue())) || "Not available",
enableSorting: true, enableSorting: true,
} },
), ),
columnHelper.accessor("demographicInformation.gender", { columnHelper.accessor("demographicInformation.gender", {
header: ( header: (
<button <button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "gender"))}>
className="flex gap-2 items-center"
onClick={() => setSorter((prev) => selectSorter(prev, "gender"))}
>
<span>Gender</span> <span>Gender</span>
<SorterArrow name="gender" /> <SorterArrow name="gender" />
</button> </button>
@@ -465,10 +321,7 @@ export default function UserList({
}), }),
{ {
header: ( header: (
<span <span className="cursor-pointer" onClick={() => setShowDemographicInformation((prev) => !prev)}>
className="cursor-pointer"
onClick={() => setShowDemographicInformation((prev) => !prev)}
>
Switch Switch
</span> </span>
), ),
@@ -480,69 +333,43 @@ export default function UserList({
const defaultColumns = [ const defaultColumns = [
columnHelper.accessor("name", { columnHelper.accessor("name", {
header: ( header: (
<button <button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "name"))}>
className="flex gap-2 items-center"
onClick={() => setSorter((prev) => selectSorter(prev, "name"))}
>
<span>Name</span> <span>Name</span>
<SorterArrow name="name" /> <SorterArrow name="name" />
</button> </button>
) as any, ) as any,
cell: ({ row, getValue }) => ( cell: ({row, getValue}) => (
<div <div
className={clsx( className={clsx(
PERMISSIONS.updateExpiryDate[row.original.type]?.includes( PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type) &&
user.type "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={() => onClick={() => (PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type) ? setSelectedUser(row.original) : null)}>
PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type) {row.original.type === "corporate" ? row.original.corporateInformation?.companyInformation?.name || getValue() : getValue()}
? setSelectedUser(row.original)
: null
}
>
{row.original.type === "corporate"
? row.original.corporateInformation?.companyInformation?.name ||
getValue()
: getValue()}
</div> </div>
), ),
}), }),
columnHelper.accessor("email", { columnHelper.accessor("email", {
header: ( header: (
<button <button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "email"))}>
className="flex gap-2 items-center"
onClick={() => setSorter((prev) => selectSorter(prev, "email"))}
>
<span>E-mail</span> <span>E-mail</span>
<SorterArrow name="email" /> <SorterArrow name="email" />
</button> </button>
) as any, ) as any,
cell: ({ row, getValue }) => ( cell: ({row, getValue}) => (
<div <div
className={clsx( className={clsx(
PERMISSIONS.updateExpiryDate[row.original.type]?.includes( PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type) &&
user.type "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={() => onClick={() => (PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type) ? setSelectedUser(row.original) : null)}>
PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type)
? setSelectedUser(row.original)
: null
}
>
{getValue()} {getValue()}
</div> </div>
), ),
}), }),
columnHelper.accessor("type", { columnHelper.accessor("type", {
header: ( header: (
<button <button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "type"))}>
className="flex gap-2 items-center"
onClick={() => setSorter((prev) => selectSorter(prev, "type"))}
>
<span>Type</span> <span>Type</span>
<SorterArrow name="type" /> <SorterArrow name="type" />
</button> </button>
@@ -551,54 +378,29 @@ export default function UserList({
}), }),
columnHelper.accessor("corporateInformation.companyInformation.name", { columnHelper.accessor("corporateInformation.companyInformation.name", {
header: ( header: (
<button <button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "companyName"))}>
className="flex gap-2 items-center"
onClick={() => setSorter((prev) => selectSorter(prev, "companyName"))}
>
<span>Company Name</span> <span>Company Name</span>
<SorterArrow name="companyName" /> <SorterArrow name="companyName" />
</button> </button>
) as any, ) as any,
cell: (info) => ( cell: (info) => <CompanyNameCell user={info.row.original} users={users} groups={groups} />,
<CompanyNameCell
user={info.row.original}
users={users}
groups={groups}
/>
),
}), }),
columnHelper.accessor("subscriptionExpirationDate", { columnHelper.accessor("subscriptionExpirationDate", {
header: ( header: (
<button <button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "expiryDate"))}>
className="flex gap-2 items-center"
onClick={() => setSorter((prev) => selectSorter(prev, "expiryDate"))}
>
<span>Expiry Date</span> <span>Expiry Date</span>
<SorterArrow name="expiryDate" /> <SorterArrow name="expiryDate" />
</button> </button>
) as any, ) as any,
cell: (info) => ( cell: (info) => (
<span <span className={clsx(info.getValue() ? expirationDateColor(moment(info.getValue()).toDate()) : "")}>
className={clsx( {!info.getValue() ? "No expiry date" : moment(info.getValue()).format("DD/MM/YYYY")}
info.getValue()
? expirationDateColor(moment(info.getValue()).toDate())
: ""
)}
>
{!info.getValue()
? "No expiry date"
: moment(info.getValue()).format("DD/MM/YYYY")}
</span> </span>
), ),
}), }),
columnHelper.accessor("isVerified", { columnHelper.accessor("isVerified", {
header: ( header: (
<button <button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "verification"))}>
className="flex gap-2 items-center"
onClick={() =>
setSorter((prev) => selectSorter(prev, "verification"))
}
>
<span>Verification</span> <span>Verification</span>
<SorterArrow name="verification" /> <SorterArrow name="verification" />
</button> </button>
@@ -609,9 +411,8 @@ export default function UserList({
className={clsx( className={clsx(
"w-6 h-6 rounded-md flex items-center justify-center border border-mti-purple-light bg-white", "w-6 h-6 rounded-md flex items-center justify-center border border-mti-purple-light bg-white",
"transition duration-300 ease-in-out", "transition duration-300 ease-in-out",
info.getValue() && "!bg-mti-purple-light " info.getValue() && "!bg-mti-purple-light ",
)} )}>
>
<BsCheck color="white" className="w-full h-full" /> <BsCheck color="white" className="w-full h-full" />
</div> </div>
</div> </div>
@@ -619,10 +420,7 @@ export default function UserList({
}), }),
{ {
header: ( header: (
<span <span className="cursor-pointer" onClick={() => setShowDemographicInformation((prev) => !prev)}>
className="cursor-pointer"
onClick={() => setShowDemographicInformation((prev) => !prev)}
>
Switch Switch
</span> </span>
), ),
@@ -642,21 +440,15 @@ export default function UserList({
const sortFunction = async (a: User, b: User) => { const sortFunction = async (a: User, b: User) => {
if (sorter === "name" || sorter === reverseString("name")) if (sorter === "name" || sorter === reverseString("name"))
return sorter === "name" return sorter === "name" ? a.name.localeCompare(b.name) : b.name.localeCompare(a.name);
? a.name.localeCompare(b.name)
: b.name.localeCompare(a.name);
if (sorter === "email" || sorter === reverseString("email")) if (sorter === "email" || sorter === reverseString("email"))
return sorter === "email" return sorter === "email" ? a.email.localeCompare(b.email) : b.email.localeCompare(a.email);
? a.email.localeCompare(b.email)
: b.email.localeCompare(a.email);
if (sorter === "type" || sorter === reverseString("type")) if (sorter === "type" || sorter === reverseString("type"))
return sorter === "type" return sorter === "type"
? userTypes.findIndex((t) => a.type === t) - ? userTypes.findIndex((t) => a.type === t) - userTypes.findIndex((t) => b.type === t)
userTypes.findIndex((t) => b.type === t) : userTypes.findIndex((t) => b.type === t) - userTypes.findIndex((t) => a.type === t);
: userTypes.findIndex((t) => b.type === t) -
userTypes.findIndex((t) => a.type === t);
if (sorter === "verification" || sorter === reverseString("verification")) if (sorter === "verification" || sorter === reverseString("verification"))
return sorter === "verification" return sorter === "verification"
@@ -664,138 +456,75 @@ export default function UserList({
: b.isVerified.toString().localeCompare(a.isVerified.toString()); : b.isVerified.toString().localeCompare(a.isVerified.toString());
if (sorter === "expiryDate" || sorter === reverseString("expiryDate")) { if (sorter === "expiryDate" || sorter === reverseString("expiryDate")) {
if (!a.subscriptionExpirationDate && b.subscriptionExpirationDate) if (!a.subscriptionExpirationDate && b.subscriptionExpirationDate) return sorter === "expiryDate" ? -1 : 1;
return sorter === "expiryDate" ? -1 : 1; if (a.subscriptionExpirationDate && !b.subscriptionExpirationDate) return sorter === "expiryDate" ? 1 : -1;
if (a.subscriptionExpirationDate && !b.subscriptionExpirationDate) if (!a.subscriptionExpirationDate && !b.subscriptionExpirationDate) return 0;
return sorter === "expiryDate" ? 1 : -1; if (moment(a.subscriptionExpirationDate).isAfter(b.subscriptionExpirationDate)) return sorter === "expiryDate" ? -1 : 1;
if (!a.subscriptionExpirationDate && !b.subscriptionExpirationDate) if (moment(b.subscriptionExpirationDate).isAfter(a.subscriptionExpirationDate)) return sorter === "expiryDate" ? 1 : -1;
return 0;
if (
moment(a.subscriptionExpirationDate).isAfter(
b.subscriptionExpirationDate
)
)
return sorter === "expiryDate" ? -1 : 1;
if (
moment(b.subscriptionExpirationDate).isAfter(
a.subscriptionExpirationDate
)
)
return sorter === "expiryDate" ? 1 : -1;
return 0; return 0;
} }
if (sorter === "country" || sorter === reverseString("country")) { if (sorter === "country" || sorter === reverseString("country")) {
if ( if (!a.demographicInformation?.country && b.demographicInformation?.country) return sorter === "country" ? -1 : 1;
!a.demographicInformation?.country && if (a.demographicInformation?.country && !b.demographicInformation?.country) return sorter === "country" ? 1 : -1;
b.demographicInformation?.country if (!a.demographicInformation?.country && !b.demographicInformation?.country) return 0;
)
return sorter === "country" ? -1 : 1;
if (
a.demographicInformation?.country &&
!b.demographicInformation?.country
)
return sorter === "country" ? 1 : -1;
if (
!a.demographicInformation?.country &&
!b.demographicInformation?.country
)
return 0;
return sorter === "country" return sorter === "country"
? a.demographicInformation!.country.localeCompare( ? a.demographicInformation!.country.localeCompare(b.demographicInformation!.country)
b.demographicInformation!.country : b.demographicInformation!.country.localeCompare(a.demographicInformation!.country);
)
: b.demographicInformation!.country.localeCompare(
a.demographicInformation!.country
);
} }
if (sorter === "phone" || sorter === reverseString("phone")) { if (sorter === "phone" || sorter === reverseString("phone")) {
if (!a.demographicInformation?.phone && b.demographicInformation?.phone) if (!a.demographicInformation?.phone && b.demographicInformation?.phone) return sorter === "phone" ? -1 : 1;
return sorter === "phone" ? -1 : 1; if (a.demographicInformation?.phone && !b.demographicInformation?.phone) return sorter === "phone" ? 1 : -1;
if (a.demographicInformation?.phone && !b.demographicInformation?.phone) if (!a.demographicInformation?.phone && !b.demographicInformation?.phone) return 0;
return sorter === "phone" ? 1 : -1;
if (!a.demographicInformation?.phone && !b.demographicInformation?.phone)
return 0;
return sorter === "phone" return sorter === "phone"
? a.demographicInformation!.phone.localeCompare( ? a.demographicInformation!.phone.localeCompare(b.demographicInformation!.phone)
b.demographicInformation!.phone : b.demographicInformation!.phone.localeCompare(a.demographicInformation!.phone);
)
: b.demographicInformation!.phone.localeCompare(
a.demographicInformation!.phone
);
} }
if (sorter === "employment" || sorter === reverseString("employment")) { if (sorter === "employment" || sorter === reverseString("employment")) {
const aSortingItem = const aSortingItem =
a.type === "corporate" || a.type === "mastercorporate" a.type === "corporate" || a.type === "mastercorporate" ? a.demographicInformation?.position : a.demographicInformation?.employment;
? a.demographicInformation?.position
: a.demographicInformation?.employment;
const bSortingItem = const bSortingItem =
b.type === "corporate" || b.type === "mastercorporate" b.type === "corporate" || b.type === "mastercorporate" ? b.demographicInformation?.position : b.demographicInformation?.employment;
? b.demographicInformation?.position
: b.demographicInformation?.employment;
if (!aSortingItem && bSortingItem) if (!aSortingItem && bSortingItem) return sorter === "employment" ? -1 : 1;
return sorter === "employment" ? -1 : 1; if (aSortingItem && !bSortingItem) return sorter === "employment" ? 1 : -1;
if (aSortingItem && !bSortingItem)
return sorter === "employment" ? 1 : -1;
if (!aSortingItem && !bSortingItem) return 0; if (!aSortingItem && !bSortingItem) return 0;
return sorter === "employment" return sorter === "employment" ? aSortingItem!.localeCompare(bSortingItem!) : bSortingItem!.localeCompare(aSortingItem!);
? aSortingItem!.localeCompare(bSortingItem!)
: bSortingItem!.localeCompare(aSortingItem!);
} }
if (sorter === "gender" || sorter === reverseString("gender")) { if (sorter === "gender" || sorter === reverseString("gender")) {
if (!a.demographicInformation?.gender && b.demographicInformation?.gender) if (!a.demographicInformation?.gender && b.demographicInformation?.gender) return sorter === "employment" ? -1 : 1;
return sorter === "employment" ? -1 : 1; if (a.demographicInformation?.gender && !b.demographicInformation?.gender) return sorter === "employment" ? 1 : -1;
if (a.demographicInformation?.gender && !b.demographicInformation?.gender) if (!a.demographicInformation?.gender && !b.demographicInformation?.gender) return 0;
return sorter === "employment" ? 1 : -1;
if (
!a.demographicInformation?.gender &&
!b.demographicInformation?.gender
)
return 0;
return sorter === "gender" return sorter === "gender"
? a.demographicInformation!.gender.localeCompare( ? a.demographicInformation!.gender.localeCompare(b.demographicInformation!.gender)
b.demographicInformation!.gender : b.demographicInformation!.gender.localeCompare(a.demographicInformation!.gender);
)
: b.demographicInformation!.gender.localeCompare(
a.demographicInformation!.gender
);
} }
if (sorter === "companyName" || sorter === reverseString("companyName")) { if (sorter === "companyName" || sorter === reverseString("companyName")) {
const aCorporateName = getUserCompanyName(a, users, groups); const aCorporateName = getUserCompanyName(a, users, groups);
const bCorporateName = getUserCompanyName(b, users, groups); const bCorporateName = getUserCompanyName(b, users, groups);
if (!aCorporateName && bCorporateName) if (!aCorporateName && bCorporateName) return sorter === "companyName" ? -1 : 1;
return sorter === "companyName" ? -1 : 1; if (aCorporateName && !bCorporateName) return sorter === "companyName" ? 1 : -1;
if (aCorporateName && !bCorporateName)
return sorter === "companyName" ? 1 : -1;
if (!aCorporateName && !bCorporateName) return 0; if (!aCorporateName && !bCorporateName) return 0;
return sorter === "companyName" return sorter === "companyName" ? aCorporateName.localeCompare(bCorporateName) : bCorporateName.localeCompare(aCorporateName);
? aCorporateName.localeCompare(bCorporateName)
: bCorporateName.localeCompare(aCorporateName);
} }
return a.id.localeCompare(b.id); return a.id.localeCompare(b.id);
}; };
const { rows: filteredRows, renderSearch } = useListSearch<User>( const {rows: filteredRows, renderSearch} = useListSearch<User>(searchFields, displayUsers);
searchFields,
displayUsers
);
const table = useReactTable({ const table = useReactTable({
data: filteredRows, data: filteredRows,
columns: (!showDemographicInformation columns: (!showDemographicInformation ? defaultColumns : demographicColumns) as any,
? defaultColumns
: demographicColumns) as any,
getCoreRowModel: getCoreRowModel(), getCoreRowModel: getCoreRowModel(),
}); });
@@ -803,7 +532,7 @@ export default function UserList({
const csv = exportListToExcel(filteredRows, users, groups); const csv = exportListToExcel(filteredRows, users, groups);
const element = document.createElement("a"); const element = document.createElement("a");
const file = new Blob([csv], { type: "text/csv" }); const file = new Blob([csv], {type: "text/csv"});
element.href = URL.createObjectURL(file); element.href = URL.createObjectURL(file);
element.download = "users.csv"; element.download = "users.csv";
document.body.appendChild(element); document.body.appendChild(element);
@@ -816,19 +545,13 @@ export default function UserList({
const belongsToAdminFilter = (x: User) => { const belongsToAdminFilter = (x: User) => {
if (!selectedUser) return false; if (!selectedUser) return false;
return groups return groups
.filter( .filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id))
(g) =>
g.admin === selectedUser.id ||
g.participants.includes(selectedUser.id)
)
.flatMap((g) => g.participants) .flatMap((g) => g.participants)
.includes(x.id); .includes(x.id);
}; };
const viewStudentFilterBelongsToAdmin = (x: User) => const viewStudentFilterBelongsToAdmin = (x: User) => x.type === "student" && belongsToAdminFilter(x);
x.type === "student" && belongsToAdminFilter(x); const viewTeacherFilterBelongsToAdmin = (x: User) => x.type === "teacher" && belongsToAdminFilter(x);
const viewTeacherFilterBelongsToAdmin = (x: User) =>
x.type === "teacher" && belongsToAdminFilter(x);
const renderUserCard = (selectedUser: User) => { const renderUserCard = (selectedUser: User) => {
const studentsFromAdmin = users.filter(viewStudentFilterBelongsToAdmin); const studentsFromAdmin = users.filter(viewStudentFilterBelongsToAdmin);
@@ -838,9 +561,7 @@ export default function UserList({
<UserCard <UserCard
loggedInUser={user} loggedInUser={user}
onViewStudents={ onViewStudents={
(selectedUser.type === "corporate" || (selectedUser.type === "corporate" || selectedUser.type === "teacher") && studentsFromAdmin.length > 0
selectedUser.type === "teacher") &&
studentsFromAdmin.length > 0
? () => { ? () => {
appendUserFilters({ appendUserFilters({
id: "view-students", id: "view-students",
@@ -856,9 +577,7 @@ export default function UserList({
: undefined : undefined
} }
onViewTeachers={ onViewTeachers={
(selectedUser.type === "corporate" || (selectedUser.type === "corporate" || selectedUser.type === "student") && teachersFromAdmin.length > 0
selectedUser.type === "student") &&
teachersFromAdmin.length > 0
? () => { ? () => {
appendUserFilters({ appendUserFilters({
id: "view-teachers", id: "view-teachers",
@@ -907,20 +626,13 @@ export default function UserList({
<> <>
{renderHeader && renderHeader(displayUsers.length)} {renderHeader && renderHeader(displayUsers.length)}
<div className="w-full"> <div className="w-full">
<Modal <Modal isOpen={!!selectedUser} onClose={() => setSelectedUser(undefined)}>
isOpen={!!selectedUser}
onClose={() => setSelectedUser(undefined)}
>
{selectedUser && renderUserCard(selectedUser)} {selectedUser && renderUserCard(selectedUser)}
</Modal> </Modal>
<div className="w-full flex flex-col gap-2"> <div className="w-full flex flex-col gap-2">
<div className="w-full flex gap-2 items-end"> <div className="w-full flex gap-2 items-end">
{renderSearch()} {renderSearch()}
<Button <Button className="w-full max-w-[200px] mb-1" variant="outline" onClick={downloadExcel}>
className="w-full max-w-[200px] mb-1"
variant="outline"
onClick={downloadExcel}
>
Download List Download List
</Button> </Button>
</div> </div>
@@ -930,12 +642,7 @@ export default function UserList({
<tr key={headerGroup.id}> <tr key={headerGroup.id}>
{headerGroup.headers.map((header) => ( {headerGroup.headers.map((header) => (
<th className="py-4 px-4 text-left" key={header.id}> <th className="py-4 px-4 text-left" key={header.id}>
{header.isPlaceholder {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</th> </th>
))} ))}
</tr> </tr>
@@ -943,16 +650,10 @@ export default function UserList({
</thead> </thead>
<tbody className="px-2"> <tbody className="px-2">
{table.getRowModel().rows.map((row) => ( {table.getRowModel().rows.map((row) => (
<tr <tr className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2" key={row.id}>
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 items-center w-fit" key={cell.id}> <td className="px-4 py-2 items-center w-fit" key={cell.id}>
{flexRender( {flexRender(cell.column.columnDef.cell, cell.getContext())}
cell.column.columnDef.cell,
cell.getContext()
)}
</td> </td>
))} ))}
</tr> </tr>

View File

@@ -1,5 +1,5 @@
import { User } from "@/interfaces/user"; import {User} from "@/interfaces/user";
import { Tab } from "@headlessui/react"; import {Tab} from "@headlessui/react";
import clsx from "clsx"; import clsx from "clsx";
import CodeList from "./CodeList"; import CodeList from "./CodeList";
import DiscountList from "./DiscountList"; import DiscountList from "./DiscountList";
@@ -7,101 +7,86 @@ import ExamList from "./ExamList";
import GroupList from "./GroupList"; import GroupList from "./GroupList";
import PackageList from "./PackageList"; import PackageList from "./PackageList";
import UserList from "./UserList"; import UserList from "./UserList";
import { checkAccess } from "@/utils/permissions"; import {checkAccess} from "@/utils/permissions";
import usePermissions from "@/hooks/usePermissions";
export default function Lists({user}: {user: User}) {
const {permissions} = usePermissions(user?.id || "");
export default function Lists({ user }: { user: User }) {
return ( return (
<Tab.Group> <Tab.Group>
<Tab.List className="flex space-x-1 rounded-xl bg-mti-purple-ultralight/40 p-1"> <Tab.List className="flex space-x-1 rounded-xl bg-mti-purple-ultralight/40 p-1">
<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 selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark"
) )
} }>
>
User List User List
</Tab> </Tab>
{checkAccess(user, ["developer"]) && ( {checkAccess(user, ["developer"]) && (
<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 selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark"
) )
} }>
>
Exam List Exam List
</Tab> </Tab>
)} )}
<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 selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark"
) )
} }>
>
Group List Group List
</Tab> </Tab>
{checkAccess(user, ["developer", "admin", "corporate"]) && ( {checkAccess(user, ["developer", "admin", "corporate"]) && (
<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 selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark"
) )
} }>
>
Code List Code List
</Tab> </Tab>
)} )}
{checkAccess(user, ["developer", "admin"]) && ( {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 selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark"
) )
} }>
>
Package List Package List
</Tab> </Tab>
)} )}
{checkAccess(user, ["developer", "admin"]) && ( {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 selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark"
) )
} }>
>
Discount List Discount List
</Tab> </Tab>
)} )}
@@ -118,11 +103,7 @@ export default function Lists({ user }: { user: User }) {
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide"> <Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
<GroupList user={user} /> <GroupList user={user} />
</Tab.Panel> </Tab.Panel>
{checkAccess( {checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"], permissions, "viewCodes") && (
user,
["developer", "admin", "corporate", "mastercorporate"],
"viewCodes"
) && (
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide"> <Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
<CodeList user={user} /> <CodeList user={user} />
</Tab.Panel> </Tab.Panel>

View File

@@ -1,9 +1,10 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction // Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next"; import type {NextApiRequest, NextApiResponse} from "next";
import { app } from "@/firebase"; import {app} from "@/firebase";
import { getFirestore, doc, setDoc } from "firebase/firestore"; import {getFirestore, doc, setDoc, getDoc} from "firebase/firestore";
import { withIronSessionApiRoute } from "iron-session/next"; import {withIronSessionApiRoute} from "iron-session/next";
import { sessionOptions } from "@/lib/session"; import {sessionOptions} from "@/lib/session";
import {getPermissionDoc} from "@/utils/permissions.be";
const db = getFirestore(app); const db = getFirestore(app);
@@ -11,20 +12,35 @@ export default withIronSessionApiRoute(handler, sessionOptions);
async function handler(req: NextApiRequest, res: NextApiResponse) { async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "PATCH") return patch(req, res); if (req.method === "PATCH") return patch(req, res);
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 {id} = req.query as {id: string};
const permissionDoc = await getPermissionDoc(id);
return res.status(200).json({allowed: permissionDoc.users.includes(req.session.user.id)});
} }
async function patch(req: NextApiRequest, res: NextApiResponse) { async function patch(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) { if (!req.session.user) {
res.status(401).json({ ok: false }); res.status(401).json({ok: false});
return; return;
} }
const { id } = req.query as { id: string };
const { users } = req.body; const {id} = req.query as {id: string};
const {users} = req.body;
try { try {
await setDoc(doc(db, "permissions", id), { users }, { merge: true }); await setDoc(doc(db, "permissions", id), {users}, {merge: true});
return res.status(200).json({ ok: true }); return res.status(200).json({ok: true});
} catch (err) { } catch (err) {
console.error(err); console.error(err);
return res.status(500).json({ ok: false }); return res.status(500).json({ok: false});
} }
} }

View File

@@ -53,7 +53,10 @@ async function get(req: NextApiRequest, res: NextApiResponse) {
// based on the admin of each group, verify if it exists and it's of type corporate // based on the admin of each group, verify if it exists and it's of type corporate
const groupsAdmins = [...new Set(groups.map((g) => g.admin).filter((id) => id))]; const groupsAdmins = [...new Set(groups.map((g) => g.admin).filter((id) => id))];
const adminsSnapshot = await getDocs(query(collection(db, "users"), where("id", "in", groupsAdmins), where("type", "==", "corporate"))); const adminsSnapshot =
groupsAdmins.length > 0
? await getDocs(query(collection(db, "users"), where("id", "in", groupsAdmins), where("type", "==", "corporate")))
: {docs: []};
const admins = adminsSnapshot.docs.map((doc) => doc.data()); const admins = adminsSnapshot.docs.map((doc) => doc.data());
const docsWithAdmins = docs.map((d) => { const docsWithAdmins = docs.map((d) => {

View File

@@ -1,22 +1,12 @@
import { PERMISSIONS } from "@/constants/userPermissions"; import {PERMISSIONS} from "@/constants/userPermissions";
import { app, adminApp } from "@/firebase"; import {app, adminApp} from "@/firebase";
import { Group, User } from "@/interfaces/user"; import {Group, User} from "@/interfaces/user";
import { sessionOptions } from "@/lib/session"; import {sessionOptions} from "@/lib/session";
import { import {collection, deleteDoc, doc, getDoc, getDocs, getFirestore, query, setDoc, where} from "firebase/firestore";
collection, import {getAuth} from "firebase-admin/auth";
deleteDoc, import {withIronSessionApiRoute} from "iron-session/next";
doc, import {NextApiRequest, NextApiResponse} from "next";
getDoc, import {getPermissions, getPermissionDocs} from "@/utils/permissions.be";
getDocs,
getFirestore,
query,
setDoc,
where,
} from "firebase/firestore";
import { getAuth } from "firebase-admin/auth";
import { withIronSessionApiRoute } from "iron-session/next";
import { NextApiRequest, NextApiResponse } from "next";
import { getPermissions, getPermissionDocs } from "@/utils/permissions.be";
const db = getFirestore(app); const db = getFirestore(app);
const auth = getAuth(adminApp); const auth = getAuth(adminApp);
@@ -32,15 +22,15 @@ async function user(req: NextApiRequest, res: NextApiResponse) {
async function del(req: NextApiRequest, res: NextApiResponse) { async function del(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) { if (!req.session.user) {
res.status(401).json({ ok: false }); res.status(401).json({ok: false});
return; return;
} }
const { id } = req.query as { id: string }; const {id} = req.query as {id: string};
const docUser = await getDoc(doc(db, "users", req.session.user.id)); const docUser = await getDoc(doc(db, "users", req.session.user.id));
if (!docUser.exists()) { if (!docUser.exists()) {
res.status(401).json({ ok: false }); res.status(401).json({ok: false});
return; return;
} }
@@ -48,24 +38,16 @@ async function del(req: NextApiRequest, res: NextApiResponse) {
const docTargetUser = await getDoc(doc(db, "users", id)); const docTargetUser = await getDoc(doc(db, "users", id));
if (!docTargetUser.exists()) { if (!docTargetUser.exists()) {
res.status(404).json({ ok: false }); res.status(404).json({ok: false});
return; return;
} }
const targetUser = { ...docTargetUser.data(), id: docTargetUser.id } as User; const targetUser = {...docTargetUser.data(), id: docTargetUser.id} as User;
if ( if (user.type === "corporate" && (targetUser.type === "student" || targetUser.type === "teacher")) {
user.type === "corporate" && res.json({ok: true});
(targetUser.type === "student" || targetUser.type === "teacher")
) {
res.json({ ok: true });
const userParticipantGroup = await getDocs( const userParticipantGroup = await getDocs(query(collection(db, "groups"), where("participants", "array-contains", id)));
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)
@@ -74,12 +56,10 @@ async function del(req: NextApiRequest, res: NextApiResponse) {
await setDoc( await setDoc(
x.ref, x.ref,
{ {
participants: x participants: x.data().participants.filter((y: string) => y !== id),
.data()
.participants.filter((y: string) => y !== id),
}, },
{ merge: true } {merge: true},
) ),
), ),
]); ]);
@@ -88,26 +68,18 @@ async function del(req: NextApiRequest, res: NextApiResponse) {
const permission = PERMISSIONS.deleteUser[targetUser.type]; const permission = PERMISSIONS.deleteUser[targetUser.type];
if (!permission.list.includes(user.type)) { if (!permission.list.includes(user.type)) {
res.status(403).json({ ok: false }); res.status(403).json({ok: false});
return; return;
} }
res.json({ ok: true }); res.json({ok: true});
await auth.deleteUser(id); await auth.deleteUser(id);
await deleteDoc(doc(db, "users", id)); await deleteDoc(doc(db, "users", id));
const userCodeDocs = await getDocs( const userCodeDocs = await getDocs(query(collection(db, "codes"), where("userId", "==", id)));
query(collection(db, "codes"), where("userId", "==", id)) const userParticipantGroup = await getDocs(query(collection(db, "groups"), where("participants", "array-contains", id)));
); const userGroupAdminDocs = await getDocs(query(collection(db, "groups"), where("admin", "==", id)));
const userParticipantGroup = await getDocs( const userStatsDocs = await getDocs(query(collection(db, "stats"), where("user", "==", id)));
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)),
@@ -120,8 +92,8 @@ async function del(req: NextApiRequest, res: NextApiResponse) {
{ {
participants: x.data().participants.filter((y: string) => y !== id), participants: x.data().participants.filter((y: string) => y !== id),
}, },
{ merge: true } {merge: true},
) ),
), ),
]); ]);
} }
@@ -136,19 +108,13 @@ async function get(req: NextApiRequest, res: NextApiResponse) {
const user = docUser.data() as User; const user = docUser.data() as User;
const permissionDocs = await getPermissionDocs();
const userWithPermissions = {
...user,
permissions: getPermissions(req.session.user.id, permissionDocs),
};
req.session.user = { req.session.user = {
...userWithPermissions, ...user,
id: req.session.user.id, id: req.session.user.id,
}; };
await req.session.save(); await req.session.save();
res.json({ ...userWithPermissions, id: req.session.user.id }); res.json({...user, id: req.session.user.id});
} else { } else {
res.status(401).json(undefined); res.status(401).json(undefined);
} }

View File

@@ -14,7 +14,8 @@ import BatchCodeGenerator from "./(admin)/BatchCodeGenerator";
import {shouldRedirectHome} from "@/utils/navigation.disabled"; import {shouldRedirectHome} from "@/utils/navigation.disabled";
import ExamGenerator from "./(admin)/ExamGenerator"; import ExamGenerator from "./(admin)/ExamGenerator";
import BatchCreateUser from "./(admin)/BatchCreateUser"; import BatchCreateUser from "./(admin)/BatchCreateUser";
import { checkAccess, getTypesOfUser } from "@/utils/permissions"; import {checkAccess, getTypesOfUser} from "@/utils/permissions";
import usePermissions from "@/hooks/usePermissions";
export const getServerSideProps = withIronSessionSsr(({req, res}) => { export const getServerSideProps = withIronSessionSsr(({req, res}) => {
const user = req.session.user; const user = req.session.user;
@@ -43,6 +44,7 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
export default function Admin() { export default function Admin() {
const {user} = useUser({redirectTo: "/login"}); const {user} = useUser({redirectTo: "/login"});
const {permissions} = usePermissions(user?.id || "");
return ( return (
<> <>
@@ -61,7 +63,7 @@ export default function Admin() {
<section className="w-full flex -md:flex-col -xl:gap-2 gap-8 justify-between"> <section className="w-full flex -md:flex-col -xl:gap-2 gap-8 justify-between">
<ExamLoader /> <ExamLoader />
<BatchCreateUser user={user} /> <BatchCreateUser user={user} />
{checkAccess(user, getTypesOfUser(["teacher"]), 'viewCodes') && ( {checkAccess(user, getTypesOfUser(["teacher"]), permissions, "viewCodes") && (
<> <>
<CodeGenerator user={user} /> <CodeGenerator user={user} />
<BatchCodeGenerator user={user} /> <BatchCodeGenerator user={user} />

View File

@@ -1,11 +1,8 @@
import { PermissionType } from "@/interfaces/permissions"; import {PermissionType} from "@/interfaces/permissions";
import { User, Type, userTypes } from "@/interfaces/user"; import {User, Type, userTypes} from "@/interfaces/user";
import axios from "axios";
export function checkAccess( export function checkAccess(user: User, types: Type[], permissions?: PermissionType[], permission?: PermissionType) {
user: User,
types: Type[],
permission?: PermissionType
) {
if (!user) { if (!user) {
return false; return false;
} }
@@ -29,7 +26,7 @@ export function checkAccess(
if (permission) { if (permission) {
// this works more like a blacklist // this works more like a blacklist
// therefore if we don't find the permission here, he can't do it // therefore if we don't find the permission here, he can't do it
if (!(user.permissions || []).includes(permission)) { if (!(permissions || []).includes(permission)) {
return false; return false;
} }
} }
@@ -41,5 +38,5 @@ export function getTypesOfUser(types: Type[]) {
// basicly generate a list of all types except the excluded ones // basicly generate a list of all types except the excluded ones
return userTypes.filter((userType) => { return userTypes.filter((userType) => {
return !types.includes(userType); return !types.includes(userType);
}) });
} }