Update the Group List to always allow editing for developers and admins

This commit is contained in:
Tiago Ribeiro
2024-01-26 19:13:44 +00:00
parent 213bdd0c8f
commit 5e6af11156

View File

@@ -1,301 +1,387 @@
import Button from "@/components/Low/Button"; import Button from "@/components/Low/Button";
import Checkbox from "@/components/Low/Checkbox";
import Input from "@/components/Low/Input"; import Input from "@/components/Low/Input";
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 {Module} from "@/interfaces"; import { Group, User } from "@/interfaces/user";
import {Group, User} from "@/interfaces/user"; import {
import {Disclosure, Transition} from "@headlessui/react"; createColumnHelper,
import {createColumnHelper, flexRender, getCoreRowModel, useReactTable} from "@tanstack/react-table"; flexRender,
getCoreRowModel,
useReactTable,
} from "@tanstack/react-table";
import axios from "axios"; import axios from "axios";
import clsx from "clsx"; import { capitalize, uniq } from "lodash";
import {capitalize, uniq, uniqBy} from "lodash"; import { useEffect, useState } from "react";
import {useEffect, useRef, useState} from "react"; import { BsPencil, BsQuestionCircleFill, BsTrash } from "react-icons/bs";
import {BsCheck, BsDash, BsPencil, BsPlus, BsQuestionCircleFill, BsTrash} from "react-icons/bs";
import {toast} from "react-toastify";
import Select from "react-select"; import Select from "react-select";
import {uuidv4} from "@firebase/util"; import { toast } from "react-toastify";
import {useFilePicker} from "use-file-picker";
import Modal from "@/components/Modal";
import readXlsxFile from "read-excel-file"; import readXlsxFile from "read-excel-file";
import { useFilePicker } from "use-file-picker";
const columnHelper = createColumnHelper<Group>(); 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]+)*$/,
);
interface CreateDialogProps { interface CreateDialogProps {
user: User; user: User;
users: User[]; users: User[];
group?: Group; group?: Group;
onClose: () => void; onClose: () => void;
} }
const CreatePanel = ({user, users, group, onClose}: CreateDialogProps) => { const CreatePanel = ({ user, users, group, onClose }: CreateDialogProps) => {
const [name, setName] = useState<string | undefined>(group?.name || undefined); const [name, setName] = useState<string | undefined>(
const [admin, setAdmin] = useState<string>(group?.admin || user.id); group?.name || undefined,
const [participants, setParticipants] = useState<string[]>(group?.participants || []); );
const {openFilePicker, filesContent, clear} = useFilePicker({ const [admin, setAdmin] = useState<string>(group?.admin || user.id);
accept: ".xlsx", const [participants, setParticipants] = useState<string[]>(
multiple: false, group?.participants || [],
readAs: "ArrayBuffer", );
}); const { openFilePicker, filesContent, clear } = useFilePicker({
accept: ".xlsx",
multiple: false,
readAs: "ArrayBuffer",
});
useEffect(() => { useEffect(() => {
if (filesContent.length > 0) { if (filesContent.length > 0) {
const file = filesContent[0]; const file = filesContent[0];
readXlsxFile(file.content).then((rows) => { readXlsxFile(file.content).then((rows) => {
const emails = uniq( const emails = uniq(
rows rows
.map((row) => { .map((row) => {
const [email] = row as string[]; const [email] = row as string[];
return EMAIL_REGEX.test(email) && !users.map((u) => u.email).includes(email) ? email.toString().trim() : undefined; return EMAIL_REGEX.test(email) &&
}) !users.map((u) => u.email).includes(email)
.filter((x) => !!x), ? email.toString().trim()
); : undefined;
})
.filter((x) => !!x),
);
if (emails.length === 0) { if (emails.length === 0) {
toast.error("Please upload an Excel file containing e-mails!"); toast.error("Please upload an Excel file containing e-mails!");
clear(); clear();
return; return;
} }
const emailUsers = [...new Set(emails)].map((x) => users.find((y) => y.email.toLowerCase() === x)).filter((x) => x !== undefined); const emailUsers = [...new Set(emails)]
const filteredUsers = emailUsers.filter( .map((x) => users.find((y) => y.email.toLowerCase() === x))
(x) => .filter((x) => x !== undefined);
((user.type === "developer" || user.type === "admin" || user.type === "corporate") && const filteredUsers = emailUsers.filter(
(x?.type === "student" || x?.type === "teacher")) || (x) =>
(user.type === "teacher" && x?.type === "student"), ((user.type === "developer" ||
); user.type === "admin" ||
user.type === "corporate") &&
(x?.type === "student" || x?.type === "teacher")) ||
(user.type === "teacher" && x?.type === "student"),
);
setParticipants(filteredUsers.filter((x) => !!x).map((x) => x!.id)); setParticipants(filteredUsers.filter((x) => !!x).map((x) => x!.id));
toast.success( toast.success(
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" },
); );
}); });
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [filesContent, user.type, users]); }, [filesContent, user.type, users]);
const submit = () => { const submit = () => {
if (name !== group?.name && (name === "Students" || name === "Teachers")) { if (name !== group?.name && (name === "Students" || name === "Teachers")) {
toast.error("That group name is reserved and cannot be used, please enter another one."); toast.error(
return; "That group name is reserved and cannot be used, please enter another one.",
} );
return;
}
(group ? axios.patch : axios.post)(group ? `/api/groups/${group.id}` : "/api/groups", {name, admin, participants}) (group ? axios.patch : axios.post)(
.then(() => { group ? `/api/groups/${group.id}` : "/api/groups",
toast.success(`Group "${name}" ${group ? "edited" : "created"} successfully`); { name, admin, participants },
return true; )
}) .then(() => {
.catch(() => { toast.success(
toast.error("Something went wrong, please try again later!"); `Group "${name}" ${group ? "edited" : "created"} successfully`,
return false; );
}) return true;
.finally(onClose); })
}; .catch(() => {
toast.error("Something went wrong, please try again later!");
return false;
})
.finally(onClose);
};
return ( return (
<div className="flex flex-col gap-12 mt-4 w-full 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 name="name" type="text" label="Name" defaultValue={name} onChange={setName} required disabled={group?.disableEditing} /> <Input
<div className="flex flex-col gap-3 w-full"> name="name"
<div className="flex gap-2 items-center"> type="text"
<label className="font-normal text-base text-mti-gray-dim">Participants</label> label="Name"
<div className="tooltip" data-tip="The Excel file should only include a column with the desired e-mails."> defaultValue={name}
<BsQuestionCircleFill /> onChange={setName}
</div> required
</div> disabled={group?.disableEditing}
<div className="flex gap-8 w-full"> />
<Select <div className="flex w-full flex-col gap-3">
className="w-full" <div className="flex items-center gap-2">
value={participants.map((x) => ({ <label className="text-mti-gray-dim text-base font-normal">
value: x, Participants
label: `${users.find((y) => y.id === x)?.email} - ${users.find((y) => y.id === x)?.name}`, </label>
}))} <div
placeholder="Participants..." className="tooltip"
defaultValue={participants.map((x) => ({ data-tip="The Excel file should only include a column with the desired e-mails."
value: x, >
label: `${users.find((y) => y.id === x)?.email} - ${users.find((y) => y.id === x)?.name}`, <BsQuestionCircleFill />
}))} </div>
options={users </div>
.filter((x) => (user.type === "teacher" ? x.type === "student" : x.type === "student" || x.type === "teacher")) <div className="flex w-full gap-8">
.map((x) => ({value: x.id, label: `${x.email} - ${x.name}`}))} <Select
onChange={(value) => setParticipants(value.map((x) => x.value))} className="w-full"
isMulti value={participants.map((x) => ({
isSearchable value: x,
menuPortalTarget={document?.body} label: `${users.find((y) => y.id === x)?.email} - ${users.find((y) => y.id === x)?.name}`,
styles={{ }))}
menuPortal: (base) => ({...base, zIndex: 9999}), placeholder="Participants..."
control: (styles) => ({ defaultValue={participants.map((x) => ({
...styles, value: x,
backgroundColor: "white", label: `${users.find((y) => y.id === x)?.email} - ${users.find((y) => y.id === x)?.name}`,
borderRadius: "999px", }))}
padding: "1rem 1.5rem", options={users
zIndex: "40", .filter((x) =>
}), user.type === "teacher"
}} ? x.type === "student"
/> : x.type === "student" || x.type === "teacher",
{user.type !== "teacher" && ( )
<Button className="w-full max-w-[300px]" onClick={openFilePicker} variant="outline"> .map((x) => ({ value: x.id, label: `${x.email} - ${x.name}` }))}
{filesContent.length === 0 ? "Upload participants Excel file" : filesContent[0].name} onChange={(value) => setParticipants(value.map((x) => x.value))}
</Button> isMulti
)} isSearchable
</div> menuPortalTarget={document?.body}
</div> styles={{
</div> menuPortal: (base) => ({ ...base, zIndex: 9999 }),
<div className="flex w-full justify-end items-center gap-8 mt-8"> control: (styles) => ({
<Button variant="outline" color="red" className="w-full max-w-[200px]" onClick={onClose}> ...styles,
Cancel backgroundColor: "white",
</Button> borderRadius: "999px",
<Button className="w-full max-w-[200px]" onClick={submit} disabled={!name}> padding: "1rem 1.5rem",
Submit zIndex: "40",
</Button> }),
</div> }}
</div> />
); {user.type !== "teacher" && (
<Button
className="w-full max-w-[300px]"
onClick={openFilePicker}
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]"
onClick={onClose}
>
Cancel
</Button>
<Button
className="w-full max-w-[200px]"
onClick={submit}
disabled={!name}
>
Submit
</Button>
</div>
</div>
);
}; };
const filterTypes = ["corporate", "teacher"]; const filterTypes = ["corporate", "teacher"];
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 { users } = useUsers();
const {groups, reload} = useGroups(user && filterTypes.includes(user?.type) ? user.id : undefined); const { groups, reload } = useGroups(
user && filterTypes.includes(user?.type) ? user.id : undefined,
);
useEffect(() => { useEffect(() => {
if (user && (user.type === "corporate" || user.type === "teacher")) { if (user && (user.type === "corporate" || user.type === "teacher")) {
setFilterByUser(true); setFilterByUser(true);
} }
}, [user]); }, [user]);
const deleteGroup = (group: Group) => { const deleteGroup = (group: Group) => {
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);
}; };
const defaultColumns = [ const defaultColumns = [
columnHelper.accessor("id", { columnHelper.accessor("id", {
header: "ID", header: "ID",
cell: (info) => info.getValue(), cell: (info) => info.getValue(),
}), }),
columnHelper.accessor("name", { columnHelper.accessor("name", {
header: "Name", header: "Name",
cell: (info) => info.getValue(), cell: (info) => info.getValue(),
}), }),
columnHelper.accessor("admin", { columnHelper.accessor("admin", {
header: "Admin", header: "Admin",
cell: (info) => ( cell: (info) => (
<div className="tooltip" data-tip={capitalize(users.find((x) => x.id === info.getValue())?.type)}> <div
{users.find((x) => x.id === info.getValue())?.name} className="tooltip"
</div> data-tip={capitalize(
), users.find((x) => x.id === info.getValue())?.type,
}), )}
columnHelper.accessor("participants", { >
header: "Participants", {users.find((x) => x.id === info.getValue())?.name}
cell: (info) => </div>
info ),
.getValue() }),
.map((x) => users.find((y) => y.id === x)?.name) columnHelper.accessor("participants", {
.join(", "), header: "Participants",
}), cell: (info) =>
{ info
header: "", .getValue()
id: "actions", .map((x) => users.find((y) => y.id === x)?.name)
cell: ({row}: {row: {original: Group}}) => { .join(", "),
return ( }),
<> {
{user && (user.type === "developer" || user.type === "admin" || user.id === row.original.admin) && ( header: "",
<div className="flex gap-2"> id: "actions",
{!row.original.disableEditing && ( cell: ({ row }: { row: { original: Group } }) => {
<div data-tip="Edit" className="cursor-pointer tooltip" onClick={() => setEditingGroup(row.original)}> return (
<BsPencil className="hover:text-mti-purple-light transition ease-in-out duration-300" /> <>
</div> {user &&
)} (user.type === "developer" ||
{!row.original.disableEditing && ( user.type === "admin" ||
<div data-tip="Delete" className="cursor-pointer tooltip" onClick={() => deleteGroup(row.original)}> user.id === row.original.admin) && (
<BsTrash className="hover:text-mti-purple-light transition ease-in-out duration-300" /> <div className="flex gap-2">
</div> {(!row.original.disableEditing ||
)} ["developer", "admin"].includes(user.type)) && (
</div> <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 table = useReactTable({ const table = useReactTable({
data: groups, data: groups,
columns: defaultColumns, columns: defaultColumns,
getCoreRowModel: getCoreRowModel(), getCoreRowModel: getCoreRowModel(),
}); });
const closeModal = () => { const closeModal = () => {
setIsCreating(false); setIsCreating(false);
setEditingGroup(undefined); setEditingGroup(undefined);
reload(); reload();
}; };
return ( return (
<div className="w-full h-full rounded-xl"> <div className="h-full w-full rounded-xl">
<Modal isOpen={isCreating || !!editingGroup} onClose={closeModal} title={editingGroup ? `Editing ${editingGroup.name}` : "New Group"}> <Modal
<CreatePanel isOpen={isCreating || !!editingGroup}
group={editingGroup} onClose={closeModal}
user={user} title={editingGroup ? `Editing ${editingGroup.name}` : "New Group"}
onClose={closeModal} >
users={ <CreatePanel
user?.type === "corporate" || user?.type === "teacher" group={editingGroup}
? users.filter( user={user}
(u) => onClose={closeModal}
groups users={
.filter((g) => g.admin === user.id) user?.type === "corporate" || user?.type === "teacher"
.flatMap((g) => g.participants) ? users.filter(
.includes(u.id) || groups.flatMap((g) => g.participants).includes(u.id), (u) =>
) groups
: users .filter((g) => g.admin === user.id)
} .flatMap((g) => g.participants)
/> .includes(u.id) ||
</Modal> groups.flatMap((g) => g.participants).includes(u.id),
<table className="rounded-xl bg-mti-purple-ultralight/40 w-full"> )
<thead> : users
{table.getHeaderGroups().map((headerGroup) => ( }
<tr key={headerGroup.id}> />
{headerGroup.headers.map((header) => ( </Modal>
<th className="py-4" key={header.id}> <table className="bg-mti-purple-ultralight/40 w-full rounded-xl">
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())} <thead>
</th> {table.getHeaderGroups().map((headerGroup) => (
))} <tr key={headerGroup.id}>
</tr> {headerGroup.headers.map((header) => (
))} <th className="py-4" key={header.id}>
</thead> {header.isPlaceholder
<tbody className="px-2"> ? null
{table.getRowModel().rows.map((row) => ( : flexRender(
<tr className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2" key={row.id}> header.column.columnDef.header,
{row.getVisibleCells().map((cell) => ( header.getContext(),
<td className="px-4 py-2" key={cell.id}> )}
{flexRender(cell.column.columnDef.cell, cell.getContext())} </th>
</td> ))}
))} </tr>
</tr> ))}
))} </thead>
</tbody> <tbody className="px-2">
</table> {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 <button
onClick={() => setIsCreating(true)} onClick={() => setIsCreating(true)}
className="w-full py-2 bg-mti-purple-light hover:bg-mti-purple transition ease-in-out duration-300 text-white"> className="bg-mti-purple-light hover:bg-mti-purple w-full py-2 text-white transition duration-300 ease-in-out"
New Group >
</button> New Group
</div> </button>
); </div>
);
} }