Updated the Group List to show the name of the corporate

This commit is contained in:
Tiago Ribeiro
2024-03-26 14:03:58 +00:00
parent 1086e78936
commit bf6c805487

View File

@@ -3,26 +3,19 @@ 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 { 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";
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]+)*$/,
);
interface CreateDialogProps { interface CreateDialogProps {
user: User; user: User;
@@ -31,17 +24,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",
@@ -57,10 +46,7 @@ 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),
); );
@@ -72,14 +58,10 @@ 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 === "admin" ||
user.type === "corporate") &&
(x?.type === "student" || x?.type === "teacher")) || (x?.type === "student" || x?.type === "teacher")) ||
(user.type === "teacher" && x?.type === "student"), (user.type === "teacher" && x?.type === "student"),
); );
@@ -89,7 +71,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);
}); });
@@ -101,21 +83,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(() => {
@@ -131,24 +106,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>
@@ -165,18 +127,14 @@ const CreatePanel = ({ user, users, group, onClose }: CreateDialogProps) => {
label: `${users.find((y) => y.id === x)?.email} - ${users.find((y) => y.id === x)?.name}`, label: `${users.find((y) => y.id === x)?.email} - ${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",
@@ -187,36 +145,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>
@@ -226,15 +166,13 @@ const CreatePanel = ({ user, users, group, onClose }: CreateDialogProps) => {
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( const {groups, reload} = useGroups(user && filterTypes.includes(user?.type) ? user.id : undefined);
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")) {
@@ -246,7 +184,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);
@@ -264,13 +202,10 @@ 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" {users.find((x) => x.id === info.getValue())?.type === "corporate"
data-tip={capitalize( ? (users.find((x) => x.id === info.getValue()) as CorporateUser)?.corporateInformation?.companyInformation?.name
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>
), ),
}), }),
@@ -285,31 +220,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 && (user.type === "developer" || user.type === "admin" || user.id === row.original.admin) && (
(user.type === "developer" ||
user.type === "admin" ||
user.id === row.original.admin) && (
<div className="flex gap-2"> <div className="flex gap-2">
{(!row.original.disableEditing || {(!row.original.disableEditing || ["developer", "admin"].includes(user.type)) && (
["developer", "admin"].includes(user.type)) && ( <div data-tip="Edit" className="tooltip cursor-pointer" onClick={() => setEditingGroup(row.original)}>
<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 || ["developer", "admin"].includes(user.type)) && (
["developer", "admin"].includes(user.type)) && ( <div data-tip="Delete" className="tooltip cursor-pointer" onClick={() => deleteGroup(row.original)}>
<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>
)} )}
@@ -335,11 +257,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}
@@ -351,8 +269,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
} }
@@ -364,12 +281,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>
@@ -377,10 +289,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())}
@@ -393,8 +302,7 @@ export default function GroupList({ user }: { user: User }) {
<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>
</div> </div>