Added the possibility to upload a file containing users to a group

This commit is contained in:
Tiago Ribeiro
2023-10-03 16:48:52 +01:00
parent 9239068cde
commit 07e73b0d88
10 changed files with 252 additions and 31 deletions

View File

@@ -1,6 +1,5 @@
import {User} from "@/interfaces/user";
import Link from "next/link";
import {Avatar} from "primereact/avatar";
import FocusLayer from "@/components/FocusLayer";
import {preventNavigation} from "@/utils/navigation.disabled";
import {useRouter} from "next/router";

View File

@@ -0,0 +1,81 @@
import Button from "@/components/Low/Button";
import {Type} from "@/interfaces/user";
import axios from "axios";
import clsx from "clsx";
import {capitalize} from "lodash";
import {useEffect, useState} from "react";
import {toast} from "react-toastify";
import ShortUniqueId from "short-unique-id";
import {useFilePicker} from "use-file-picker";
export default function BatchCodeGenerator() {
const [emails, setEmails] = useState<string[]>([]);
const {openFilePicker, filesContent} = useFilePicker({
accept: ".txt",
multiple: false,
});
useEffect(() => {
if (filesContent.length > 0) {
const file = filesContent[0];
const emails = file.content
.split("\n")
.filter((x) => new RegExp(/^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$/).test(x));
if (emails.length === 0) {
toast.error("Please upload a .txt file containing e-mails, one per line!");
return;
}
setEmails(emails);
}
}, [filesContent]);
const generateCode = (type: Type) => {
const uid = new ShortUniqueId();
const codes = emails.map(() => uid.randomUUID(6));
axios
.post("/api/code", {type, codes})
.then(({data, status}) => {
if (data.ok) {
toast.success(`Successfully generated ${capitalize(type)} codes!`, {toastId: "success"});
return;
}
if (status === 403) {
toast.error(`You do not have permission to generate ${capitalize(type)} codes!`, {toastId: "forbidden"});
}
})
.catch(({response: {status}}) => {
if (status === 403) {
toast.error(`You do not have permission to generate ${capitalize(type)} codes!`, {toastId: "forbidden"});
return;
}
toast.error(`Something went wrong, please try again later!`, {toastId: "error"});
});
};
return (
<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">Choose a .txt file containing e-mails</label>
<Button onClick={openFilePicker}>{filesContent.length > 0 ? filesContent[0].name : "Choose a file"}</Button>
<label className="font-normal text-base text-mti-gray-dim">Select the type of user they should be</label>
<div className="grid grid-cols-2 gap-4">
<Button className="w-48" variant="outline" onClick={() => generateCode("student")} disabled={emails.length === 0}>
Student
</Button>
<Button className="w-48" variant="outline" onClick={() => generateCode("teacher")} disabled={emails.length === 0}>
Teacher
</Button>
<Button className="w-48" variant="outline" onClick={() => generateCode("admin")} disabled={emails.length === 0}>
Admin
</Button>
<Button className="w-48" variant="outline" onClick={() => generateCode("owner")} disabled={emails.length === 0}>
Owner
</Button>
</div>
</div>
);
}

View File

@@ -15,7 +15,7 @@ export default function CodeGenerator() {
const code = uid.randomUUID(6);
axios
.post("/api/code", {type, code})
.post("/api/code", {type, codes: [code]})
.then(({data, status}) => {
if (data.ok) {
toast.success(`Successfully generated a ${capitalize(type)} code!`, {toastId: "success"});

View File

@@ -15,6 +15,7 @@ import {BsCheck, BsDash, BsPencil, BsPlus, BsTrash} from "react-icons/bs";
import {toast} from "react-toastify";
import Select from "react-select";
import {uuidv4} from "@firebase/util";
import {useFilePicker} from "use-file-picker";
const columnHelper = createColumnHelper<Group>();
@@ -29,6 +30,41 @@ const CreatePanel = ({user, users, group, onCreate}: 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 {openFilePicker, filesContent} = useFilePicker({
accept: ".txt",
multiple: false,
});
useEffect(() => {
if (filesContent.length > 0) {
const file = filesContent[0];
const emails = file.content
.toLowerCase()
.split("\n")
.filter((x) => new RegExp(/^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$/).test(x));
if (emails.length === 0) {
toast.error("Please upload a .txt file containing e-mails, one per line!");
return;
}
const emailUsers = emails.map((x) => users.find((y) => y.email.toLowerCase() === x)).filter((x) => x !== undefined);
const filteredUsers = emailUsers.filter(
(x) =>
((user.type === "developer" || user.type === "owner" || user.type === "admin") &&
(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"},
);
}
}, [filesContent, user.type, users]);
return (
<div className="flex flex-col gap-12 mt-4 w-full px-4 py-2">
@@ -36,28 +72,38 @@ const CreatePanel = ({user, users, group, onCreate}: CreateDialogProps) => {
<Input name="name" type="text" label="Name" defaultValue={name} onChange={setName} required />
<div className="flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Participants</label>
<Select
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
styles={{
control: (styles) => ({
...styles,
backgroundColor: "white",
borderRadius: "999px",
padding: "1rem 1.5rem",
zIndex: "40",
}),
}}
/>
<div className="flex gap-8 w-full">
<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
styles={{
control: (styles) => ({
...styles,
backgroundColor: "white",
borderRadius: "999px",
padding: "1rem 1.5rem",
zIndex: "40",
}),
}}
/>
<Button className="w-full max-w-[300px]" onClick={openFilePicker} variant="outline">
{filesContent.length === 0 ? "Upload participants .txt file" : filesContent[0].name}
</Button>
</div>
</div>
</div>
<Button

View File

@@ -5,6 +5,7 @@ import type {AppProps} from "next/app";
import "primereact/resources/themes/lara-light-indigo/theme.css";
import "primereact/resources/primereact.min.css";
import "primeicons/primeicons.css";
import "react-datepicker/dist/react-datepicker.css";
import {useRouter} from "next/router";
import {useEffect} from "react";
import useExamStore from "@/stores/examStore";

View File

@@ -10,6 +10,7 @@ import ExamLoader from "./(admin)/ExamLoader";
import {Tab} from "@headlessui/react";
import clsx from "clsx";
import Lists from "./(admin)/Lists";
import BatchCodeGenerator from "./(admin)/BatchCodeGenerator";
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
const user = req.session.user;
@@ -58,9 +59,10 @@ export default function Admin() {
<ToastContainer />
{user && (
<Layout user={user} className="gap-6">
<section className="w-full flex gap-8">
<section className="w-full flex gap-8 justify-between">
<ExamLoader />
<CodeGenerator />
<BatchCodeGenerator />
</section>
<section className="w-full">
<Lists user={user} />

View File

@@ -18,7 +18,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
return;
}
const {type, code} = req.body as {type: Type; code: string};
const {type, codes} = req.body as {type: Type; codes: string[]};
const permission = PERMISSIONS.generateCode[type];
if (!permission.includes(req.session.user.type)) {
@@ -26,8 +26,10 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
return;
}
const codeRef = doc(db, "codes", uuidv4());
await setDoc(codeRef, {type, code});
for (const code of codes) {
const codeRef = doc(db, "codes", uuidv4());
await setDoc(codeRef, {type, code});
}
res.status(200).json({ok: true});
}

View File

@@ -227,6 +227,13 @@ export default function History({user}: {user: User}) {
options={users.map((x) => ({value: x.id, label: `${x.name} - ${x.email}`}))}
defaultValue={{value: user.id, label: `${user.name} - ${user.email}`}}
onChange={(value) => setStatsUserId(value?.value)}
styles={{
option: (styles, state) => ({
...styles,
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
color: state.isFocused ? "black" : styles.color,
}),
}}
/>
)}
{(user.type === "admin" || user.type === "teacher") && groups.length > 0 && (
@@ -236,6 +243,13 @@ export default function History({user}: {user: User}) {
.map((x) => ({value: x.id, label: `${x.name} - ${x.email}`}))}
defaultValue={{value: user.id, label: `${user.name} - ${user.email}`}}
onChange={(value) => setStatsUserId(value?.value)}
styles={{
option: (styles, state) => ({
...styles,
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
color: state.isFocused ? "black" : styles.color,
}),
}}
/>
)}
</div>