Merged develop into feature/training-content

This commit is contained in:
Tiago Ribeiro
2024-08-12 14:12:55 +00:00
15 changed files with 1366 additions and 762 deletions

View File

@@ -46,6 +46,7 @@ import ProgressBar from "@/components/Low/ProgressBar";
import AssignmentCreator from "./AssignmentCreator";
import AssignmentView from "./AssignmentView";
import { getUserCorporate } from "@/utils/groups";
import { checkAccess } from "@/utils/permissions";
interface Props {
user: User;
@@ -373,13 +374,15 @@ export default function TeacherDashboard({ user }: Props) {
).toFixed(1)}
color="purple"
/>
<IconCard
Icon={BsPeople}
label="Groups"
value={groups.length}
color="purple"
onClick={() => setPage("groups")}
/>
{checkAccess(user, ["teacher", "developer"], "viewGroup") && (
<IconCard
Icon={BsPeople}
label="Groups"
value={groups.length}
color="purple"
onClick={() => setPage("groups")}
/>
)}
<div
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"

View File

@@ -5,15 +5,20 @@ export type Variant = "full" | "partial";
export type InstructorGender = "male" | "female" | "varied";
export type Difficulty = "easy" | "medium" | "hard";
export interface ReadingExam {
parts: ReadingPart[];
interface ExamBase {
id: string;
module: "reading";
module: Module;
minTimer: number;
type: "academic" | "general";
isDiagnostic: boolean;
variant?: Variant;
difficulty?: Difficulty;
createdBy?: string; // option as it has been added later
createdAt?: string; // option as it has been added later
}
export interface ReadingExam extends ExamBase {
module: "reading";
parts: ReadingPart[];
type: "academic" | "general";
}
export interface ReadingPart {
@@ -24,14 +29,9 @@ export interface ReadingPart {
exercises: Exercise[];
}
export interface LevelExam {
export interface LevelExam extends ExamBase {
module: "level";
id: string;
parts: LevelPart[];
minTimer: number;
isDiagnostic: boolean;
variant?: Variant;
difficulty?: Difficulty;
}
export interface LevelPart {
@@ -39,14 +39,9 @@ export interface LevelPart {
exercises: Exercise[];
}
export interface ListeningExam {
export interface ListeningExam extends ExamBase {
parts: ListeningPart[];
id: string;
module: "listening";
minTimer: number;
isDiagnostic: boolean;
variant?: Variant;
difficulty?: Difficulty;
}
export interface ListeningPart {
@@ -72,14 +67,9 @@ export interface UserSolution {
isDisabled?: boolean;
}
export interface WritingExam {
export interface WritingExam extends ExamBase {
module: "writing";
id: string;
exercises: WritingExercise[];
minTimer: number;
isDiagnostic: boolean;
variant?: Variant;
difficulty?: Difficulty;
}
interface WordCounter {
@@ -87,15 +77,10 @@ interface WordCounter {
limit: number;
}
export interface SpeakingExam {
id: string;
export interface SpeakingExam extends ExamBase {
module: "speaking";
exercises: (SpeakingExercise | InteractiveSpeakingExercise)[];
minTimer: number;
isDiagnostic: boolean;
variant?: Variant;
instructorGender: InstructorGender;
difficulty?: Difficulty;
}
export type Exercise =

View File

@@ -26,18 +26,26 @@ export const permissions = [
"viewCorporate",
"viewCountryManager",
"viewAdmin",
"viewGroup",
"viewCodes",
// edit data
"editStudent",
"editTeacher",
"editCorporate",
"editCountryManager",
"editAdmin",
"editGroup",
// delete data
"deleteStudent",
"deleteTeacher",
"deleteCorporate",
"deleteCountryManager",
"deleteAdmin",
"deleteGroup",
"deleteCodes",
// create options
"createGroup",
"createCodes"
] as const;
export type PermissionType = (typeof permissions)[keyof typeof permissions];

View File

@@ -16,7 +16,7 @@ import { useFilePicker } from "use-file-picker";
import readXlsxFile from "read-excel-file";
import Modal from "@/components/Modal";
import { BsFileEarmarkEaselFill, BsQuestionCircleFill } from "react-icons/bs";
import { checkAccess } from "@/utils/permissions";
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
import { PermissionType } from "@/interfaces/permissions";
const EMAIL_REGEX = new RegExp(
/^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$/
@@ -297,7 +297,12 @@ export default function BatchCodeGenerator({ user }: { user: User }) {
{filesContent.length > 0 ? filesContent[0].name : "Choose a file"}
</Button>
{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">
<label className="text-mti-gray-dim text-base font-normal">
@@ -343,7 +348,7 @@ export default function BatchCodeGenerator({ user }: { user: User }) {
{Object.keys(USER_TYPE_LABELS)
.filter((x) => {
const { list, perm } = USER_TYPE_PERMISSIONS[x as Type];
return checkAccess(user, list, perm);
return checkAccess(user, getTypesOfUser(list), perm);
})
.map((type) => (
<option key={type} value={type}>
@@ -352,14 +357,20 @@ export default function BatchCodeGenerator({ user }: { user: User }) {
))}
</select>
)}
<Button
onClick={generateAndInvite}
disabled={
infos.length === 0 || (isExpiryDateEnabled ? !expiryDate : false)
}
>
Generate & Send
</Button>
{checkAccess(
user,
["developer", "admin", "corporate", "mastercorporate"],
"createCodes"
) && (
<Button
onClick={generateAndInvite}
disabled={
infos.length === 0 || (isExpiryDateEnabled ? !expiryDate : false)
}
>
Generate & Send
</Button>
)}
</div>
</>
);

View File

@@ -0,0 +1,243 @@
import Button from "@/components/Low/Button";
import useUsers from "@/hooks/useUsers";
import { Type as UserType, User } from "@/interfaces/user";
import axios from "axios";
import { uniqBy } from "lodash";
import { useEffect, useState } from "react";
import { toast } from "react-toastify";
import { useFilePicker } from "use-file-picker";
import readXlsxFile from "read-excel-file";
import Modal from "@/components/Modal";
import { BsQuestionCircleFill } from "react-icons/bs";
import { PermissionType } from "@/interfaces/permissions";
const EMAIL_REGEX = new RegExp(
/^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$/
);
type Type = Exclude<UserType, "admin" | "developer" | "agent" | "mastercorporate">
const USER_TYPE_LABELS: {[key in Type]: string} = {
student: "Student",
teacher: "Teacher",
corporate: "Corporate",
};
const USER_TYPE_PERMISSIONS: {
[key in Type]: { perm: PermissionType | undefined; list: Type[] };
} = {
student: {
perm: "createCodeStudent",
list: [],
},
teacher: {
perm: "createCodeTeacher",
list: [],
},
corporate: {
perm: "createCodeCorporate",
list: ["student", "teacher"],
},
};
export default function BatchCreateUser({ user }: { user: User }) {
const [infos, setInfos] = useState<
{ email: string; name: string; passport_id:string, type: Type, demographicInformation: {
country: string,
passport_id:string,
phone: string
} }[]
>([]);
const [isLoading, setIsLoading] = useState(false);
const [type, setType] = useState<Type>("student");
const [showHelp, setShowHelp] = useState(false);
const { users } = useUsers();
const { openFilePicker, filesContent, clear } = useFilePicker({
accept: ".xlsx",
multiple: false,
readAs: "ArrayBuffer",
});
useEffect(() => {
if (filesContent.length > 0) {
const file = filesContent[0];
readXlsxFile(file.content).then((rows) => {
try {
const information = uniqBy(
rows
.map((row) => {
const [
firstName,
lastName,
country,
passport_id,
email,
phone,
group
] = row as string[];
return EMAIL_REGEX.test(email.toString().trim())
? {
email: email.toString().trim().toLowerCase(),
name: `${firstName ?? ""} ${lastName ?? ""}`.trim().toLowerCase(),
type: type,
passport_id: passport_id?.toString().trim() || undefined,
groupName: group,
demographicInformation: {
country: country,
passport_id: passport_id?.toString().trim() || undefined,
phone,
}
}
: undefined;
})
.filter((x) => !!x) as typeof infos,
(x) => x.email
);
if (information.length === 0) {
toast.error(
"Please upload an Excel file containing user information, one per line! All already registered e-mails have also been ignored!"
);
return clear();
}
setInfos(information);
} catch {
toast.error(
"Please upload an Excel file containing user information, one per line! All already registered e-mails have also been ignored!"
);
return clear();
}
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [filesContent]);
const makeUsers = async () => {
const newUsers = infos.filter(
(x) => !users.map((u) => u.email).includes(x.email)
);
const confirmed = confirm(
`You are about to add ${newUsers.length}, are you sure you want to continue?`
)
if (!confirmed)
return;
if (newUsers.length > 0)
{
setIsLoading(true);
Promise.all(newUsers.map(async (user) => {
await axios.post("/api/make_user", user)
})).then((res) =>{
toast.success(
`Successfully added ${newUsers.length} user(s)!`
)}).finally(() => {
return clear();
})
}
setIsLoading(false);
setInfos([]);
};
return (
<>
<Modal
isOpen={showHelp}
onClose={() => setShowHelp(false)}
title="Excel File Format"
>
<div className="mt-4 flex flex-col gap-2">
<span>Please upload an Excel file with the following format:</span>
<table className="w-full">
<thead>
<tr>
<th className="border border-neutral-200 px-2 py-1">
First Name
</th>
<th className="border border-neutral-200 px-2 py-1">
Last Name
</th>
<th className="border border-neutral-200 px-2 py-1">Country</th>
<th className="border border-neutral-200 px-2 py-1">
Passport/National ID
</th>
<th className="border border-neutral-200 px-2 py-1">E-mail</th>
<th className="border border-neutral-200 px-2 py-1">
Phone Number
</th>
<th className="border border-neutral-200 px-2 py-1">
Group Name
</th>
</tr>
</thead>
</table>
<span className="mt-4">
<b>Notes:</b>
<ul>
<li>- All incorrect e-mails will be ignored;</li>
<li>- All already registered e-mails will be ignored;</li>
<li>
- You may have a header row with the format above, however, it
is not necessary;
</li>
<li>
- All of the e-mails in the file will receive an e-mail to join
EnCoach with the role selected below.
</li>
</ul>
</span>
</div>
</Modal>
<div className="border-mti-gray-platinum flex flex-col gap-4 rounded-xl border p-4">
<div className="flex items-end justify-between">
<label className="text-mti-gray-dim text-base font-normal">
Choose an Excel file
</label>
<div
className="tooltip cursor-pointer"
data-tip="Excel File Format"
onClick={() => setShowHelp(true)}
>
<BsQuestionCircleFill />
</div>
</div>
<Button
onClick={openFilePicker}
isLoading={isLoading}
disabled={isLoading}
>
{filesContent.length > 0 ? filesContent[0].name : "Choose a file"}
</Button>
<label className="text-mti-gray-dim text-base font-normal">
Select the type of user they should be
</label>
{user && (
<select
defaultValue="student"
onChange={(e) => setType(e.target.value as 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"
>
{Object.keys(USER_TYPE_LABELS)
.map((type) => (
<option key={type} value={type}>
{USER_TYPE_LABELS[type as keyof typeof USER_TYPE_LABELS]}
</option>
))}
</select>
)}
<Button
className="my-auto"
onClick={makeUsers}
disabled={
infos.length === 0
}
>
Create
</Button>
</div>
</>
);
}

View File

@@ -130,47 +130,48 @@ export default function CodeGenerator({ user }: { user: User }) {
))}
</select>
)}
{user &&
checkAccess(user, ["developer", "admin", "corporate"]) && (
<>
<div className="-md:flex-row -md:items-center flex justify-between gap-2 md:flex-col 2xl:flex-row 2xl:items-center">
<label className="text-mti-gray-dim text-base font-normal">
Expiry Date
</label>
<Checkbox
isChecked={isExpiryDateEnabled}
onChange={setIsExpiryDateEnabled}
disabled={!!user.subscriptionExpirationDate}
>
Enabled
</Checkbox>
</div>
{isExpiryDateEnabled && (
<ReactDatePicker
className={clsx(
"flex min-h-[70px] w-full cursor-pointer justify-center rounded-full border p-6 text-sm font-normal focus:outline-none",
"hover:border-mti-purple tooltip",
"transition duration-300 ease-in-out"
)}
filterDate={(date) =>
moment(date).isAfter(new Date()) &&
(user.subscriptionExpirationDate
? moment(date).isBefore(user.subscriptionExpirationDate)
: true)
}
dateFormat="dd/MM/yyyy"
selected={expiryDate}
onChange={(date) => setExpiryDate(date)}
/>
)}
</>
)}
<Button
onClick={() => generateCode(type)}
disabled={isExpiryDateEnabled ? !expiryDate : false}
>
Generate
</Button>
{user && checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"]) && (
<>
<div className="-md:flex-row -md:items-center flex justify-between gap-2 md:flex-col 2xl:flex-row 2xl:items-center">
<label className="text-mti-gray-dim text-base font-normal">
Expiry Date
</label>
<Checkbox
isChecked={isExpiryDateEnabled}
onChange={setIsExpiryDateEnabled}
disabled={!!user.subscriptionExpirationDate}
>
Enabled
</Checkbox>
</div>
{isExpiryDateEnabled && (
<ReactDatePicker
className={clsx(
"flex min-h-[70px] w-full cursor-pointer justify-center rounded-full border p-6 text-sm font-normal focus:outline-none",
"hover:border-mti-purple tooltip",
"transition duration-300 ease-in-out"
)}
filterDate={(date) =>
moment(date).isAfter(new Date()) &&
(user.subscriptionExpirationDate
? moment(date).isBefore(user.subscriptionExpirationDate)
: true)
}
dateFormat="dd/MM/yyyy"
selected={expiryDate}
onChange={(date) => setExpiryDate(date)}
/>
)}
</>
)}
{checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"], 'createCodes') && (
<Button
onClick={() => generateCode(type)}
disabled={isExpiryDateEnabled ? !expiryDate : false}
>
Generate
</Button>
)}
<label className="font-normal text-base text-mti-gray-dim">
Generated Code:
</label>

View File

@@ -19,6 +19,7 @@ import { BsTrash } from "react-icons/bs";
import { toast } from "react-toastify";
import ReactDatePicker from "react-datepicker";
import clsx from "clsx";
import { checkAccess } from "@/utils/permissions";
const columnHelper = createColumnHelper<Code>();
@@ -147,6 +148,12 @@ export default function CodeList({ user }: { user: User }) {
.finally(reload);
};
const allowedToDelete = checkAccess(
user,
["developer", "admin", "corporate", "mastercorporate"],
"deleteCodes"
);
const defaultColumns = [
columnHelper.accessor("code", {
id: "codeCheckbox",
@@ -209,7 +216,7 @@ export default function CodeList({ user }: { user: User }) {
cell: ({ row }: { row: { original: Code } }) => {
return (
<div className="flex gap-4">
{!row.original.userId && (
{allowedToDelete && !row.original.userId && (
<div
data-tip="Delete"
className="cursor-pointer tooltip"
@@ -308,6 +315,7 @@ export default function CodeList({ user }: { user: User }) {
}}
/>
</div>
{allowedToDelete && (
<div className="flex gap-4 items-center">
<span>{selectedCodes.length} code(s) selected</span>
<Button
@@ -320,6 +328,7 @@ export default function CodeList({ user }: { user: User }) {
Delete
</Button>
</div>
)}
</div>
<table className="rounded-xl bg-mti-purple-ultralight/40 w-full">
<thead>

View File

@@ -1,154 +1,223 @@
import {PERMISSIONS} from "@/constants/userPermissions";
import { useMemo } from "react";
import { PERMISSIONS } from "@/constants/userPermissions";
import useExams from "@/hooks/useExams";
import useUsers from "@/hooks/useUsers";
import {Module} from "@/interfaces";
import {Exam} from "@/interfaces/exam";
import {Type, User} from "@/interfaces/user";
import { Module } from "@/interfaces";
import { Exam } from "@/interfaces/exam";
import { Type, User } from "@/interfaces/user";
import useExamStore from "@/stores/examStore";
import {getExamById} from "@/utils/exams";
import {countExercises} from "@/utils/moduleUtils";
import {createColumnHelper, flexRender, getCoreRowModel, useReactTable} from "@tanstack/react-table";
import { getExamById } from "@/utils/exams";
import { countExercises } from "@/utils/moduleUtils";
import {
createColumnHelper,
flexRender,
getCoreRowModel,
useReactTable,
} from "@tanstack/react-table";
import axios from "axios";
import clsx from "clsx";
import {capitalize} from "lodash";
import {useRouter} from "next/router";
import {BsCheck, BsTrash, BsUpload} from "react-icons/bs";
import {toast} from "react-toastify";
import { capitalize } from "lodash";
import { useRouter } from "next/router";
import { BsCheck, BsTrash, BsUpload } from "react-icons/bs";
import { toast } from "react-toastify";
const CLASSES: {[key in Module]: string} = {
reading: "text-ielts-reading",
listening: "text-ielts-listening",
speaking: "text-ielts-speaking",
writing: "text-ielts-writing",
level: "text-ielts-level",
const CLASSES: { [key in Module]: string } = {
reading: "text-ielts-reading",
listening: "text-ielts-listening",
speaking: "text-ielts-speaking",
writing: "text-ielts-writing",
level: "text-ielts-level",
};
const columnHelper = createColumnHelper<Exam>();
export default function ExamList({user}: {user: User}) {
const {exams, reload} = useExams();
export default function ExamList({ user }: { user: User }) {
const { exams, reload } = useExams();
const { users } = useUsers();
const setExams = useExamStore((state) => state.setExams);
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
const parsedExams = useMemo(() => {
return exams.map((exam) => {
if (exam.createdBy) {
const user = users.find((u) => u.id === exam.createdBy);
if (!user) return exam;
const router = useRouter();
return {
...exam,
createdBy: user.type === "developer" ? "system" : user.name,
};
}
const loadExam = async (module: Module, examId: string) => {
const exam = await getExamById(module, examId.trim());
if (!exam) {
toast.error("Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID", {
toastId: "invalid-exam-id",
});
return exam;
});
}, [exams, users]);
return;
}
const setExams = useExamStore((state) => state.setExams);
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
setExams([exam]);
setSelectedModules([module]);
const router = useRouter();
router.push("/exercises");
};
const loadExam = async (module: Module, examId: string) => {
const exam = await getExamById(module, examId.trim());
if (!exam) {
toast.error(
"Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID",
{
toastId: "invalid-exam-id",
}
);
const deleteExam = async (exam: Exam) => {
if (!confirm(`Are you sure you want to delete this ${capitalize(exam.module)} exam?`)) return;
return;
}
axios
.delete(`/api/exam/${exam.module}/${exam.id}`)
.then(() => toast.success(`Deleted the "${exam.id}" exam`))
.catch((reason) => {
if (reason.response.status === 404) {
toast.error("Exam not found!");
return;
}
setExams([exam]);
setSelectedModules([module]);
if (reason.response.status === 403) {
toast.error("You do not have permission to delete this exam!");
return;
}
router.push("/exercises");
};
toast.error("Something went wrong, please try again later.");
})
.finally(reload);
};
const deleteExam = async (exam: Exam) => {
if (
!confirm(
`Are you sure you want to delete this ${capitalize(exam.module)} exam?`
)
)
return;
const getTotalExercises = (exam: Exam) => {
if (exam.module === "reading" || exam.module === "listening" || exam.module === "level") {
return countExercises(exam.parts.flatMap((x) => x.exercises));
}
axios
.delete(`/api/exam/${exam.module}/${exam.id}`)
.then(() => toast.success(`Deleted the "${exam.id}" exam`))
.catch((reason) => {
if (reason.response.status === 404) {
toast.error("Exam not found!");
return;
}
return countExercises(exam.exercises);
};
if (reason.response.status === 403) {
toast.error("You do not have permission to delete this exam!");
return;
}
const defaultColumns = [
columnHelper.accessor("id", {
header: "ID",
cell: (info) => info.getValue(),
}),
columnHelper.accessor("module", {
header: "Module",
cell: (info) => <span className={CLASSES[info.getValue()]}>{capitalize(info.getValue())}</span>,
}),
columnHelper.accessor((x) => getTotalExercises(x), {
header: "Exercises",
cell: (info) => info.getValue(),
}),
columnHelper.accessor("minTimer", {
header: "Timer",
cell: (info) => <>{info.getValue()} minute(s)</>,
}),
{
header: "",
id: "actions",
cell: ({row}: {row: {original: Exam}}) => {
return (
<div className="flex gap-4">
<div
data-tip="Load exam"
className="cursor-pointer tooltip"
onClick={async () => await loadExam(row.original.module, row.original.id)}>
<BsUpload className="hover:text-mti-purple-light transition ease-in-out duration-300" />
</div>
{PERMISSIONS.examManagement.delete.includes(user.type) && (
<div data-tip="Delete" className="cursor-pointer tooltip" onClick={() => deleteExam(row.original)}>
<BsTrash className="hover:text-mti-purple-light transition ease-in-out duration-300" />
</div>
)}
</div>
);
},
},
];
toast.error("Something went wrong, please try again later.");
})
.finally(reload);
};
const table = useReactTable({
data: exams,
columns: defaultColumns,
getCoreRowModel: getCoreRowModel(),
});
const getTotalExercises = (exam: Exam) => {
if (
exam.module === "reading" ||
exam.module === "listening" ||
exam.module === "level"
) {
return countExercises(exam.parts.flatMap((x) => x.exercises));
}
return (
<table className="rounded-xl bg-mti-purple-ultralight/40 w-full">
<thead>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<th className="p-4 text-left" key={header.id}>
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
</th>
))}
</tr>
))}
</thead>
<tbody className="px-2">
{table.getRowModel().rows.map((row) => (
<tr className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2" key={row.id}>
{row.getVisibleCells().map((cell) => (
<td className="px-4 py-2" key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))}
</tbody>
</table>
);
return countExercises(exam.exercises);
};
const defaultColumns = [
columnHelper.accessor("id", {
header: "ID",
cell: (info) => info.getValue(),
}),
columnHelper.accessor("module", {
header: "Module",
cell: (info) => (
<span className={CLASSES[info.getValue()]}>
{capitalize(info.getValue())}
</span>
),
}),
columnHelper.accessor((x) => getTotalExercises(x), {
header: "Exercises",
cell: (info) => info.getValue(),
}),
columnHelper.accessor("minTimer", {
header: "Timer",
cell: (info) => <>{info.getValue()} minute(s)</>,
}),
columnHelper.accessor("createdAt", {
header: "Created At",
cell: (info) => {
const value = info.getValue();
if (value) {
return new Date(value).toLocaleDateString();
}
return null;
},
}),
columnHelper.accessor("createdBy", {
header: "Created By",
cell: (info) => info.getValue(),
}),
{
header: "",
id: "actions",
cell: ({ row }: { row: { original: Exam } }) => {
return (
<div className="flex gap-4">
<div
data-tip="Load exam"
className="cursor-pointer tooltip"
onClick={async () =>
await loadExam(row.original.module, row.original.id)
}
>
<BsUpload className="hover:text-mti-purple-light transition ease-in-out duration-300" />
</div>
{PERMISSIONS.examManagement.delete.includes(user.type) && (
<div
data-tip="Delete"
className="cursor-pointer tooltip"
onClick={() => deleteExam(row.original)}
>
<BsTrash className="hover:text-mti-purple-light transition ease-in-out duration-300" />
</div>
)}
</div>
);
},
},
];
const table = useReactTable({
data: parsedExams,
columns: defaultColumns,
getCoreRowModel: getCoreRowModel(),
});
return (
<table className="rounded-xl bg-mti-purple-ultralight/40 w-full">
<thead>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<th className="p-4 text-left" key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</th>
))}
</tr>
))}
</thead>
<tbody className="px-2">
{table.getRowModel().rows.map((row) => (
<tr
className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2"
key={row.id}
>
{row.getVisibleCells().map((cell) => (
<td className="px-4 py-2" key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))}
</tbody>
</table>
);
}

View File

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

View File

@@ -7,6 +7,7 @@ import ExamList from "./ExamList";
import GroupList from "./GroupList";
import PackageList from "./PackageList";
import UserList from "./UserList";
import { checkAccess } from "@/utils/permissions";
export default function Lists({ user }: { user: User }) {
return (
@@ -20,13 +21,13 @@ export default function Lists({ user }: { user: User }) {
"transition duration-300 ease-in-out",
selected
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark"
)
}
>
User List
</Tab>
{user?.type === "developer" && (
{checkAccess(user, ["developer"]) && (
<Tab
className={({ selected }) =>
clsx(
@@ -35,7 +36,7 @@ export default function Lists({ user }: { user: User }) {
"transition duration-300 ease-in-out",
selected
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark"
)
}
>
@@ -50,13 +51,13 @@ export default function Lists({ user }: { user: User }) {
"transition duration-300 ease-in-out",
selected
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark"
)
}
>
Group List
</Tab>
{user && ["developer", "admin", "corporate"].includes(user.type) && (
{checkAccess(user, ["developer", "admin", "corporate"]) && (
<Tab
className={({ selected }) =>
clsx(
@@ -65,14 +66,14 @@ export default function Lists({ user }: { user: User }) {
"transition duration-300 ease-in-out",
selected
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark"
)
}
>
Code List
</Tab>
)}
{user && ["developer", "admin"].includes(user.type) && (
{checkAccess(user, ["developer", "admin"]) && (
<Tab
className={({ selected }) =>
clsx(
@@ -81,14 +82,14 @@ export default function Lists({ user }: { user: User }) {
"transition duration-300 ease-in-out",
selected
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark"
)
}
>
Package List
</Tab>
)}
{user && ["developer", "admin"].includes(user.type) && (
{checkAccess(user, ["developer", "admin"]) && (
<Tab
className={({ selected }) =>
clsx(
@@ -97,7 +98,7 @@ export default function Lists({ user }: { user: User }) {
"transition duration-300 ease-in-out",
selected
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark"
)
}
>
@@ -109,7 +110,7 @@ export default function Lists({ user }: { user: User }) {
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
<UserList user={user} />
</Tab.Panel>
{user?.type === "developer" && (
{checkAccess(user, ["developer"]) && (
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
<ExamList user={user} />
</Tab.Panel>
@@ -117,17 +118,21 @@ export default function Lists({ user }: { user: User }) {
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
<GroupList user={user} />
</Tab.Panel>
{user && ["developer", "admin", "corporate"].includes(user.type) && (
{checkAccess(
user,
["developer", "admin", "corporate", "mastercorporate"],
"viewCodes"
) && (
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
<CodeList user={user} />
</Tab.Panel>
)}
{user && ["developer", "admin"].includes(user.type) && (
{checkAccess(user, ["developer", "admin"]) && (
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
<PackageList user={user} />
</Tab.Panel>
)}
{user && ["developer", "admin"].includes(user.type) && (
{checkAccess(user, ["developer", "admin"]) && (
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
<DiscountList user={user} />
</Tab.Panel>

View File

@@ -47,7 +47,7 @@ async function POST(req: NextApiRequest, res: NextApiResponse) {
}
const {module} = req.query as {module: string};
const exam = {...req.body, module: module};
const exam = {...req.body, module: module, createdBy: req.session.user.id, createdAt: new Date().toISOString()};
await setDoc(doc(db, module, req.body.id), exam);
res.status(200).json(exam);

152
src/pages/api/make_user.ts Normal file
View File

@@ -0,0 +1,152 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { app } from "@/firebase";
import {
getFirestore,
setDoc,
doc,
query,
collection,
where,
getDocs,
getDoc,
deleteDoc,
limit,
updateDoc,
} from "firebase/firestore";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import {v4} from "uuid";
import {Group} from "@/interfaces/user";
import {createUserWithEmailAndPassword, getAuth} from "firebase/auth";
const DEFAULT_DESIRED_LEVELS = {
reading: 9,
listening: 9,
writing: 9,
speaking: 9,
};
const DEFAULT_LEVELS = {
reading: 0,
listening: 0,
writing: 0,
speaking: 0,
};
const auth = getAuth(app);
const db = getFirestore(app);
export default withIronSessionApiRoute(handler, sessionOptions);
async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "POST") return post(req, res);
return res.status(404).json({ ok: false });
}
async function post(req: NextApiRequest, res: NextApiResponse) {
const maker = req.session.user;
if (!maker) {
return res
.status(401)
.json({ ok: false, reason: "You must be logged in to make user!" });
}
const { email, passport_id, type, groupName } = req.body as {
email: string;
passport_id: string;
type: string,
groupName: string
};
// cleaning data
delete req.body.passport_id;
delete req.body.groupName;
await createUserWithEmailAndPassword(auth, email.toLowerCase(), passport_id)
.then(async (userCredentials) => {
const userId = userCredentials.user.uid;
const user = {
...req.body,
bio: "",
type: type,
focus: "academic",
status: "paymentDue",
desiredLevels: DEFAULT_DESIRED_LEVELS,
levels: DEFAULT_LEVELS,
isFirstLogin: false,
isVerified: true
};
await setDoc(doc(db, "users", userId), user);
if (type === "corporate") {
const defaultTeachersGroup: Group = {
admin: userId,
id: v4(),
name: "Teachers",
participants: [],
disableEditing: true,
};
const defaultStudentsGroup: Group = {
admin: userId,
id: v4(),
name: "Students",
participants: [],
disableEditing: true,
};
const defaultCorporateGroup: Group = {
admin: userId,
id: v4(),
name: "Corporate",
participants: [],
disableEditing: true,
};
await setDoc(doc(db, "groups", defaultTeachersGroup.id), defaultTeachersGroup);
await setDoc(doc(db, "groups", defaultStudentsGroup.id), defaultStudentsGroup);
await setDoc(doc(db, "groups", defaultCorporateGroup.id), defaultCorporateGroup);
}
if(typeof groupName === 'string' && groupName.trim().length > 0){
const q = query(collection(db, "groups"), where("admin", "==", maker.id), where("name", "==", groupName.trim()), limit(1))
const snapshot = await getDocs(q)
if(snapshot.empty){
const values = {
id: v4(),
admin: maker.id,
name: groupName.trim(),
participants: [userId],
disableEditing: false,
}
await setDoc(doc(db, "groups", values.id) , values)
}else{
const doc = snapshot.docs[0]
const participants : string[] = doc.get('participants');
if(!participants.includes(userId)){
updateDoc(doc.ref, {
participants: [...participants, userId]
})
}
}
}
})
.catch((error) => {
console.log(error);
return res.status(401).json({error});
});
return res.status(200).json({ ok: true });
}

View File

@@ -13,10 +13,11 @@ import Lists from "./(admin)/Lists";
import BatchCodeGenerator from "./(admin)/BatchCodeGenerator";
import {shouldRedirectHome} from "@/utils/navigation.disabled";
import ExamGenerator from "./(admin)/ExamGenerator";
import BatchCreateUser from "./(admin)/BatchCreateUser";
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
const user = req.session.user;
if (!user || !user.isVerified) {
return {
redirect: {
@@ -59,10 +60,11 @@ export default function Admin() {
<Layout user={user} className="gap-6">
<section className="w-full flex -md:flex-col -xl:gap-2 gap-8 justify-between">
<ExamLoader />
{user.type !== "teacher" && (
<BatchCreateUser user={user} />
{checkAccess(user, getTypesOfUser(["teacher"]), 'viewCodes') && (
<>
<CodeGenerator user={user} />
<BatchCodeGenerator user={user} />
<CodeGenerator user={user} />
<BatchCodeGenerator user={user} />
</>
)}
</section>

View File

@@ -42,4 +42,4 @@ export function getTypesOfUser(types: Type[]) {
return userTypes.filter((userType) => {
return !types.includes(userType);
})
}
}