Merge branch 'develop' into ENCOA-77_GenerationTitle
This commit is contained in:
@@ -2,7 +2,7 @@ import React, { useState, ReactNode, useRef, useEffect } from 'react';
|
||||
import { animated, useSpring } from '@react-spring/web';
|
||||
|
||||
interface DropdownProps {
|
||||
title: string;
|
||||
title: ReactNode;
|
||||
open?: boolean;
|
||||
className?: string;
|
||||
contentWrapperClassName?: string;
|
||||
@@ -81,4 +81,4 @@ const Dropdown: React.FC<DropdownProps> = ({
|
||||
);
|
||||
};
|
||||
|
||||
export default Dropdown;
|
||||
export default Dropdown;
|
||||
|
||||
@@ -1,33 +1,34 @@
|
||||
import {SpeakingExercise} from "@/interfaces/exam";
|
||||
import {CommonProps} from ".";
|
||||
import {Fragment, useEffect, useState} from "react";
|
||||
import {BsCheckCircleFill, BsMicFill, BsPauseCircle, BsPlayCircle, BsTrashFill} from "react-icons/bs";
|
||||
import { SpeakingExercise } from "@/interfaces/exam";
|
||||
import { CommonProps } from ".";
|
||||
import { Fragment, useEffect, useState } from "react";
|
||||
import { BsCheckCircleFill, BsMicFill, BsPauseCircle, BsPlayCircle, BsTrashFill } from "react-icons/bs";
|
||||
import dynamic from "next/dynamic";
|
||||
import Button from "../Low/Button";
|
||||
import useExamStore from "@/stores/examStore";
|
||||
import {downloadBlob} from "@/utils/evaluation";
|
||||
import { downloadBlob } from "@/utils/evaluation";
|
||||
import axios from "axios";
|
||||
import Modal from "../Modal";
|
||||
|
||||
const Waveform = dynamic(() => import("../Waveform"), {ssr: false});
|
||||
const Waveform = dynamic(() => import("../Waveform"), { ssr: false });
|
||||
const ReactMediaRecorder = dynamic(() => import("react-media-recorder").then((mod) => mod.ReactMediaRecorder), {
|
||||
ssr: false,
|
||||
});
|
||||
|
||||
export default function Speaking({id, title, text, video_url, type, prompts, suffix, userSolutions, onNext, onBack}: SpeakingExercise & CommonProps) {
|
||||
export default function Speaking({ id, title, text, video_url, type, prompts, suffix, userSolutions, onNext, onBack }: SpeakingExercise & CommonProps) {
|
||||
const [recordingDuration, setRecordingDuration] = useState(0);
|
||||
const [isRecording, setIsRecording] = useState(false);
|
||||
const [mediaBlob, setMediaBlob] = useState<string>();
|
||||
const [audioURL, setAudioURL] = useState<string>();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isPromptsModalOpen, setIsPromptsModalOpen] = useState(false);
|
||||
const [inputText, setInputText] = useState("");
|
||||
|
||||
const hasExamEnded = useExamStore((state) => state.hasExamEnded);
|
||||
|
||||
const saveToStorage = async () => {
|
||||
if (mediaBlob && mediaBlob.startsWith("blob")) {
|
||||
const blobBuffer = await downloadBlob(mediaBlob);
|
||||
const audioFile = new File([blobBuffer], "audio.wav", {type: "audio/wav"});
|
||||
const audioFile = new File([blobBuffer], "audio.wav", { type: "audio/wav" });
|
||||
|
||||
const seed = Math.random().toString().replace("0.", "");
|
||||
|
||||
@@ -41,8 +42,8 @@ export default function Speaking({id, title, text, video_url, type, prompts, suf
|
||||
},
|
||||
};
|
||||
|
||||
const response = await axios.post<{path: string}>("/api/storage/insert", formData, config);
|
||||
if (audioURL) await axios.post("/api/storage/delete", {path: audioURL});
|
||||
const response = await axios.post<{ path: string }>("/api/storage/insert", formData, config);
|
||||
if (audioURL) await axios.post("/api/storage/delete", { path: audioURL });
|
||||
return response.data.path;
|
||||
}
|
||||
|
||||
@@ -51,7 +52,7 @@ export default function Speaking({id, title, text, video_url, type, prompts, suf
|
||||
|
||||
useEffect(() => {
|
||||
if (userSolutions.length > 0) {
|
||||
const {solution} = userSolutions[0] as {solution?: string};
|
||||
const { solution } = userSolutions[0] as { solution?: string };
|
||||
if (solution && !mediaBlob) setMediaBlob(solution);
|
||||
if (solution && !solution.startsWith("blob")) setAudioURL(solution);
|
||||
}
|
||||
@@ -78,8 +79,8 @@ export default function Speaking({id, title, text, video_url, type, prompts, suf
|
||||
const next = async () => {
|
||||
onNext({
|
||||
exercise: id,
|
||||
solutions: mediaBlob ? [{id, solution: mediaBlob}] : [],
|
||||
score: {correct: 0, total: 100, missing: 0},
|
||||
solutions: mediaBlob ? [{ id, solution: mediaBlob }] : [],
|
||||
score: { correct: 0, total: 100, missing: 0 },
|
||||
type,
|
||||
});
|
||||
};
|
||||
@@ -87,12 +88,33 @@ export default function Speaking({id, title, text, video_url, type, prompts, suf
|
||||
const back = async () => {
|
||||
onBack({
|
||||
exercise: id,
|
||||
solutions: mediaBlob ? [{id, solution: mediaBlob}] : [],
|
||||
score: {correct: 0, total: 100, missing: 0},
|
||||
solutions: mediaBlob ? [{ id, solution: mediaBlob }] : [],
|
||||
score: { correct: 0, total: 100, missing: 0 },
|
||||
type,
|
||||
});
|
||||
};
|
||||
|
||||
const handleNoteWriting = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const newText = e.target.value;
|
||||
const words = newText.match(/\S+/g);
|
||||
const wordCount = words ? words.length : 0;
|
||||
|
||||
if (wordCount <= 100) {
|
||||
setInputText(newText);
|
||||
} else {
|
||||
let count = 0;
|
||||
let lastIndex = 0;
|
||||
const matches = newText.matchAll(/\S+/g);
|
||||
for (const match of matches) {
|
||||
count++;
|
||||
if (count > 100) break;
|
||||
lastIndex = match.index! + match[0].length;
|
||||
}
|
||||
|
||||
setInputText(newText.slice(0, lastIndex));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full w-full gap-9">
|
||||
<Modal title="Prompts" className="!w-96 aspect-square" isOpen={isPromptsModalOpen} onClose={() => setIsPromptsModalOpen(false)}>
|
||||
@@ -112,7 +134,7 @@ export default function Speaking({id, title, text, video_url, type, prompts, suf
|
||||
<div className="flex flex-col gap-0">
|
||||
<span className="font-semibold">{title}</span>
|
||||
{prompts.length > 0 && (
|
||||
<span className="font-semibold">You should talk for at least 30 seconds for your answer to be valid.</span>
|
||||
<span className="font-semibold">You should talk for at least 1 minute and 30 seconds for your answer to be valid.</span>
|
||||
)}
|
||||
</div>
|
||||
{!video_url && (
|
||||
@@ -138,10 +160,24 @@ export default function Speaking({id, title, text, video_url, type, prompts, suf
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{prompts && prompts.length > 0 && (
|
||||
<div className="w-full h-full flex flex-col gap-4">
|
||||
<textarea
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
className="w-full h-full min-h-[200px] cursor-text px-7 py-8 input border-2 border-mti-gray-platinum bg-white rounded-3xl"
|
||||
onChange={handleNoteWriting}
|
||||
value={inputText}
|
||||
placeholder="Write your notes here..."
|
||||
spellCheck={false}
|
||||
/>
|
||||
<span className="text-base self-end text-mti-gray-cool">Word Count: {(inputText.match(/\S+/g) || []).length}/100</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ReactMediaRecorder
|
||||
audio
|
||||
onStop={(blob) => setMediaBlob(blob)}
|
||||
render={({status, startRecording, stopRecording, pauseRecording, resumeRecording, clearBlobUrl, mediaBlobUrl}) => (
|
||||
render={({ status, startRecording, stopRecording, pauseRecording, resumeRecording, clearBlobUrl, mediaBlobUrl }) => (
|
||||
<div className="w-full p-4 px-8 bg-transparent border-2 border-mti-gray-platinum rounded-2xl flex-col gap-8 items-center">
|
||||
<p className="text-base font-normal">Record your answer:</p>
|
||||
<div className="flex gap-8 items-center justify-center py-8">
|
||||
|
||||
@@ -1,255 +1,179 @@
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import {
|
||||
Ticket,
|
||||
TicketStatus,
|
||||
TicketStatusLabel,
|
||||
TicketType,
|
||||
TicketTypeLabel,
|
||||
} from "@/interfaces/ticket";
|
||||
import { User } from "@/interfaces/user";
|
||||
import { USER_TYPE_LABELS } from "@/resources/user";
|
||||
import {Ticket, TicketStatus, TicketStatusLabel, TicketType, TicketTypeLabel} from "@/interfaces/ticket";
|
||||
import {User} from "@/interfaces/user";
|
||||
import {USER_TYPE_LABELS} from "@/resources/user";
|
||||
import axios from "axios";
|
||||
import moment from "moment";
|
||||
import { useState } from "react";
|
||||
import { toast } from "react-toastify";
|
||||
import {useState} from "react";
|
||||
import {toast} from "react-toastify";
|
||||
import ShortUniqueId from "short-unique-id";
|
||||
import Button from "../Low/Button";
|
||||
import Input from "../Low/Input";
|
||||
import Select from "../Low/Select";
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
import {checkAccess} from "@/utils/permissions";
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
ticket: Ticket;
|
||||
onClose: () => void;
|
||||
user: User;
|
||||
ticket: Ticket;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export default function TicketDisplay({ user, ticket, onClose }: Props) {
|
||||
const [subject] = useState(ticket.subject);
|
||||
const [type, setType] = useState<TicketType>(ticket.type);
|
||||
const [description] = useState(ticket.description);
|
||||
const [reporter] = useState(ticket.reporter);
|
||||
const [reportedFrom] = useState(ticket.reportedFrom);
|
||||
const [status, setStatus] = useState(ticket.status);
|
||||
const [assignedTo, setAssignedTo] = useState<string | null>(
|
||||
ticket.assignedTo || null,
|
||||
);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
export default function TicketDisplay({user, ticket, onClose}: Props) {
|
||||
const [subject] = useState(ticket.subject);
|
||||
const [type, setType] = useState<TicketType>(ticket.type);
|
||||
const [description] = useState(ticket.description);
|
||||
const [reporter] = useState(ticket.reporter);
|
||||
const [reportedFrom] = useState(ticket.reportedFrom);
|
||||
const [status, setStatus] = useState(ticket.status);
|
||||
const [assignedTo, setAssignedTo] = useState<string | null>(ticket.assignedTo || null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const { users } = useUsers();
|
||||
const {users} = useUsers();
|
||||
|
||||
const submit = () => {
|
||||
if (!type)
|
||||
return toast.error("Please choose a type!", { toastId: "missing-type" });
|
||||
const submit = () => {
|
||||
if (!type) return toast.error("Please choose a type!", {toastId: "missing-type"});
|
||||
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.patch(`/api/tickets/${ticket.id}`, {
|
||||
subject,
|
||||
type,
|
||||
description,
|
||||
reporter,
|
||||
reportedFrom,
|
||||
status,
|
||||
assignedTo,
|
||||
})
|
||||
.then(() => {
|
||||
toast.success(`The ticket has been updated!`, { toastId: "submitted" });
|
||||
onClose();
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
toast.error("Something went wrong, please try again later!", {
|
||||
toastId: "error",
|
||||
});
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.patch(`/api/tickets/${ticket.id}`, {
|
||||
subject,
|
||||
type,
|
||||
description,
|
||||
reporter,
|
||||
reportedFrom,
|
||||
status,
|
||||
assignedTo,
|
||||
})
|
||||
.then(() => {
|
||||
toast.success(`The ticket has been updated!`, {toastId: "submitted"});
|
||||
onClose();
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
toast.error("Something went wrong, please try again later!", {
|
||||
toastId: "error",
|
||||
});
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
const del = () => {
|
||||
if (!confirm("Are you sure you want to delete this ticket?")) return;
|
||||
const del = () => {
|
||||
if (!confirm("Are you sure you want to delete this ticket?")) return;
|
||||
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.delete(`/api/tickets/${ticket.id}`)
|
||||
.then(() => {
|
||||
toast.success(`The ticket has been deleted!`, { toastId: "submitted" });
|
||||
onClose();
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
toast.error("Something went wrong, please try again later!", {
|
||||
toastId: "error",
|
||||
});
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.delete(`/api/tickets/${ticket.id}`)
|
||||
.then(() => {
|
||||
toast.success(`The ticket has been deleted!`, {toastId: "submitted"});
|
||||
onClose();
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
toast.error("Something went wrong, please try again later!", {
|
||||
toastId: "error",
|
||||
});
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
return (
|
||||
<form className="flex flex-col gap-4 pt-8">
|
||||
<Input
|
||||
label="Subject"
|
||||
type="text"
|
||||
name="subject"
|
||||
placeholder="Subject..."
|
||||
value={subject}
|
||||
onChange={(e) => null}
|
||||
disabled
|
||||
/>
|
||||
return (
|
||||
<form className="flex flex-col gap-4 pt-8">
|
||||
<Input label="Subject" type="text" name="subject" placeholder="Subject..." value={subject} onChange={(e) => null} disabled />
|
||||
|
||||
<div className="-md:flex-col flex w-full items-center gap-4">
|
||||
<div className="flex w-full flex-col gap-3">
|
||||
<label className="text-mti-gray-dim text-base font-normal">
|
||||
Status
|
||||
</label>
|
||||
<Select
|
||||
options={Object.keys(TicketStatusLabel).map((x) => ({
|
||||
value: x,
|
||||
label: TicketStatusLabel[x as keyof typeof TicketStatusLabel],
|
||||
}))}
|
||||
value={{ value: status, label: TicketStatusLabel[status] }}
|
||||
onChange={(value) =>
|
||||
setStatus((value?.value as TicketStatus) ?? undefined)
|
||||
}
|
||||
placeholder="Status..."
|
||||
/>
|
||||
</div>
|
||||
<div className="flex w-full flex-col gap-3">
|
||||
<label className="text-mti-gray-dim text-base font-normal">
|
||||
Type
|
||||
</label>
|
||||
<Select
|
||||
options={Object.keys(TicketTypeLabel).map((x) => ({
|
||||
value: x,
|
||||
label: TicketTypeLabel[x as keyof typeof TicketTypeLabel],
|
||||
}))}
|
||||
value={{ value: type, label: TicketTypeLabel[type] }}
|
||||
onChange={(value) => setType(value!.value as TicketType)}
|
||||
placeholder="Type..."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="-md:flex-col flex w-full items-center gap-4">
|
||||
<div className="flex w-full flex-col gap-3">
|
||||
<label className="text-mti-gray-dim text-base font-normal">Status</label>
|
||||
<Select
|
||||
options={Object.keys(TicketStatusLabel).map((x) => ({
|
||||
value: x,
|
||||
label: TicketStatusLabel[x as keyof typeof TicketStatusLabel],
|
||||
}))}
|
||||
value={{value: status, label: TicketStatusLabel[status]}}
|
||||
onChange={(value) => setStatus((value?.value as TicketStatus) ?? undefined)}
|
||||
placeholder="Status..."
|
||||
/>
|
||||
</div>
|
||||
<div className="flex w-full flex-col gap-3">
|
||||
<label className="text-mti-gray-dim text-base font-normal">Type</label>
|
||||
<Select
|
||||
options={Object.keys(TicketTypeLabel).map((x) => ({
|
||||
value: x,
|
||||
label: TicketTypeLabel[x as keyof typeof TicketTypeLabel],
|
||||
}))}
|
||||
value={{value: type, label: TicketTypeLabel[type]}}
|
||||
onChange={(value) => setType(value!.value as TicketType)}
|
||||
placeholder="Type..."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex w-full flex-col gap-3">
|
||||
<label className="text-mti-gray-dim text-base font-normal">
|
||||
Assignee
|
||||
</label>
|
||||
<Select
|
||||
options={[
|
||||
{ value: "me", label: "Assign to me" },
|
||||
...users
|
||||
.filter((x) => checkAccess(x, ["admin", "developer", "agent"]))
|
||||
.map((u) => ({
|
||||
value: u.id,
|
||||
label: `${u.name} - ${u.email}`,
|
||||
})),
|
||||
]}
|
||||
disabled={checkAccess(user, ["agent"])}
|
||||
value={
|
||||
assignedTo
|
||||
? {
|
||||
value: assignedTo,
|
||||
label: `${users.find((u) => u.id === assignedTo)?.name} - ${users.find((u) => u.id === assignedTo)?.email}`,
|
||||
}
|
||||
: null
|
||||
}
|
||||
onChange={(value) =>
|
||||
value
|
||||
? setAssignedTo(value.value === "me" ? user.id : value.value)
|
||||
: setAssignedTo(null)
|
||||
}
|
||||
placeholder="Assignee..."
|
||||
isClearable
|
||||
/>
|
||||
</div>
|
||||
<div className="flex w-full flex-col gap-3">
|
||||
<label className="text-mti-gray-dim text-base font-normal">Assignee</label>
|
||||
<Select
|
||||
options={[
|
||||
{value: "me", label: "Assign to me"},
|
||||
...users
|
||||
.filter((x) => checkAccess(x, ["admin", "developer", "agent"]))
|
||||
.map((u) => ({
|
||||
value: u.id,
|
||||
label: `${u.name} - ${u.email}`,
|
||||
})),
|
||||
]}
|
||||
disabled={checkAccess(user, ["agent"])}
|
||||
value={
|
||||
assignedTo
|
||||
? {
|
||||
value: assignedTo,
|
||||
label: `${users.find((u) => u.id === assignedTo)?.name} - ${users.find((u) => u.id === assignedTo)?.email}`,
|
||||
}
|
||||
: null
|
||||
}
|
||||
onChange={(value) => (value ? setAssignedTo(value.value === "me" ? user.id : value.value) : setAssignedTo(null))}
|
||||
placeholder="Assignee..."
|
||||
isClearable
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="-md:flex-col flex w-full items-center gap-4">
|
||||
<Input
|
||||
label="Reported From"
|
||||
type="text"
|
||||
name="reportedFrom"
|
||||
onChange={() => null}
|
||||
value={reportedFrom}
|
||||
disabled
|
||||
/>
|
||||
<Input
|
||||
label="Date"
|
||||
type="text"
|
||||
name="date"
|
||||
onChange={() => null}
|
||||
value={moment(ticket.date).format("DD/MM/YYYY - HH:mm")}
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
<div className="-md:flex-col flex w-full items-center gap-4">
|
||||
<Input label="Reported From" type="text" name="reportedFrom" onChange={() => null} value={reportedFrom} disabled />
|
||||
<Input label="Date" type="text" name="date" onChange={() => null} value={moment(ticket.date).format("DD/MM/YYYY - HH:mm")} disabled />
|
||||
</div>
|
||||
|
||||
<div className="-md:flex-col flex w-full items-center gap-4">
|
||||
<Input
|
||||
label="Reporter's Name"
|
||||
type="text"
|
||||
name="reporter"
|
||||
onChange={() => null}
|
||||
value={reporter.name}
|
||||
disabled
|
||||
/>
|
||||
<Input
|
||||
label="Reporter's E-mail"
|
||||
type="text"
|
||||
name="reporter"
|
||||
onChange={() => null}
|
||||
value={reporter.email}
|
||||
disabled
|
||||
/>
|
||||
<Input
|
||||
label="Reporter's Type"
|
||||
type="text"
|
||||
name="reporterType"
|
||||
onChange={() => null}
|
||||
value={USER_TYPE_LABELS[reporter.type]}
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
<div className="-md:flex-col flex w-full items-center gap-4">
|
||||
<Input label="Reporter's Name" type="text" name="reporter" onChange={() => null} value={reporter.name} disabled />
|
||||
<Input label="Reporter's E-mail" type="text" name="reporter" onChange={() => null} value={reporter.email} disabled />
|
||||
<Input
|
||||
label="Reporter's Type"
|
||||
type="text"
|
||||
name="reporterType"
|
||||
onChange={() => null}
|
||||
value={USER_TYPE_LABELS[reporter.type]}
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
|
||||
<textarea
|
||||
className="input border-mti-gray-platinum h-full min-h-[300px] w-full cursor-text rounded-3xl border bg-white px-7 py-8"
|
||||
placeholder="Write your ticket's description here..."
|
||||
contentEditable={false}
|
||||
value={description}
|
||||
spellCheck
|
||||
/>
|
||||
<textarea
|
||||
className="input border-mti-gray-platinum h-full min-h-[300px] w-full cursor-text rounded-3xl border bg-white px-7 py-8"
|
||||
placeholder="Write your ticket's description here..."
|
||||
contentEditable={false}
|
||||
value={description}
|
||||
spellCheck
|
||||
/>
|
||||
|
||||
<div className="-md:flex-col-reverse mt-2 flex w-full items-center justify-between gap-4">
|
||||
<Button
|
||||
type="button"
|
||||
color="red"
|
||||
className="w-full md:max-w-[200px]"
|
||||
variant="outline"
|
||||
onClick={del}
|
||||
isLoading={isLoading}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
<div className="-md:flex-col-reverse mt-2 flex w-full items-center justify-between gap-4">
|
||||
<Button type="button" color="red" className="w-full md:max-w-[200px]" variant="outline" onClick={del} isLoading={isLoading}>
|
||||
Delete
|
||||
</Button>
|
||||
|
||||
<div className="-md:flex-col-reverse flex w-full items-center justify-end gap-4">
|
||||
<Button
|
||||
type="button"
|
||||
color="red"
|
||||
className="w-full md:max-w-[200px]"
|
||||
variant="outline"
|
||||
onClick={onClose}
|
||||
isLoading={isLoading}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
className="w-full md:max-w-[200px]"
|
||||
isLoading={isLoading}
|
||||
onClick={submit}
|
||||
>
|
||||
Update
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
<div className="-md:flex-col-reverse flex w-full items-center justify-end gap-4">
|
||||
<Button type="button" color="red" className="w-full md:max-w-[200px]" variant="outline" onClick={onClose} isLoading={isLoading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="button" className="w-full md:max-w-[200px]" isLoading={isLoading} onClick={submit}>
|
||||
Update
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
168
src/components/InfiniteCarousel.tsx
Normal file
168
src/components/InfiniteCarousel.tsx
Normal file
@@ -0,0 +1,168 @@
|
||||
import React, { useRef, useEffect, useState, useCallback, ReactNode } from 'react';
|
||||
import { useSpring, animated } from '@react-spring/web';
|
||||
import { useDrag } from '@use-gesture/react';
|
||||
import clsx from 'clsx';
|
||||
|
||||
interface InfiniteCarouselProps {
|
||||
children: React.ReactNode;
|
||||
height: string;
|
||||
speed?: number;
|
||||
gap?: number;
|
||||
overlay?: ReactNode;
|
||||
overlayFunc?: (index: number) => void;
|
||||
overlayClassName?: string;
|
||||
}
|
||||
|
||||
const InfiniteCarousel: React.FC<InfiniteCarouselProps> = ({
|
||||
children,
|
||||
height,
|
||||
speed = 20000,
|
||||
gap = 16,
|
||||
overlay = undefined,
|
||||
overlayFunc = undefined,
|
||||
overlayClassName = ""
|
||||
}) => {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [containerWidth, setContainerWidth] = useState<number>(0);
|
||||
const itemCount = React.Children.count(children);
|
||||
const [isDragging, setIsDragging] = useState<boolean>(false);
|
||||
const [itemWidth, setItemWidth] = useState<number>(0);
|
||||
const [isInfinite, setIsInfinite] = useState<boolean>(true);
|
||||
const dragStartX = useRef<number>(0);
|
||||
|
||||
useEffect(() => {
|
||||
const handleResize = () => {
|
||||
if (containerRef.current) {
|
||||
const containerWidth = containerRef.current.clientWidth;
|
||||
setContainerWidth(containerWidth);
|
||||
|
||||
const firstChild = containerRef.current.firstElementChild?.firstElementChild as HTMLElement;
|
||||
if (firstChild) {
|
||||
const childWidth = firstChild.offsetWidth;
|
||||
setItemWidth(childWidth);
|
||||
|
||||
const totalContentWidth = (childWidth + gap) * itemCount - gap;
|
||||
setIsInfinite(totalContentWidth > containerWidth);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
handleResize();
|
||||
window.addEventListener('resize', handleResize);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('resize', handleResize);
|
||||
};
|
||||
}, [gap, itemCount]);
|
||||
|
||||
const totalWidth = (itemWidth + gap) * itemCount;
|
||||
|
||||
const [{ x }, api] = useSpring(() => ({
|
||||
from: { x: 0 },
|
||||
to: { x: -totalWidth },
|
||||
config: { duration: speed },
|
||||
loop: true,
|
||||
}));
|
||||
|
||||
const startAnimation = useCallback(() => {
|
||||
if (isInfinite) {
|
||||
api.start({
|
||||
from: { x: x.get() },
|
||||
to: { x: x.get() - totalWidth },
|
||||
config: { duration: speed },
|
||||
loop: true,
|
||||
});
|
||||
} else {
|
||||
api.stop();
|
||||
api.start({ x: 0, immediate: true });
|
||||
}
|
||||
}, [api, x, totalWidth, speed, isInfinite]);
|
||||
|
||||
useEffect(() => {
|
||||
if (containerWidth > 0 && !isDragging) {
|
||||
startAnimation();
|
||||
}
|
||||
}, [containerWidth, isDragging, startAnimation]);
|
||||
|
||||
const bind = useDrag(({ down, movement: [mx], first }) => {
|
||||
if (!isInfinite) return;
|
||||
if (first) {
|
||||
setIsDragging(true);
|
||||
api.stop();
|
||||
dragStartX.current = x.get();
|
||||
}
|
||||
if (down) {
|
||||
let newX = dragStartX.current + mx;
|
||||
newX = ((newX % totalWidth) + totalWidth) % totalWidth;
|
||||
if (newX > 0) newX -= totalWidth;
|
||||
api.start({ x: newX, immediate: true });
|
||||
} else {
|
||||
setIsDragging(false);
|
||||
startAnimation();
|
||||
}
|
||||
}, {
|
||||
filterTaps: true,
|
||||
from: () => [x.get(), 0],
|
||||
});
|
||||
|
||||
return (
|
||||
<div
|
||||
className="overflow-hidden relative select-none"
|
||||
style={{ height, touchAction: 'pan-y' }}
|
||||
ref={containerRef}
|
||||
{...(isInfinite ? bind() : {})}
|
||||
>
|
||||
<animated.div
|
||||
className="flex"
|
||||
style={{
|
||||
display: 'flex',
|
||||
willChange: 'transform',
|
||||
transform: isInfinite
|
||||
? x.to((x) => `translate3d(${x}px, 0, 0)`)
|
||||
: 'none',
|
||||
gap: `${gap}px`,
|
||||
width: 'fit-content',
|
||||
}}
|
||||
>
|
||||
{React.Children.map(children, (child, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="flex-shrink-0 relative"
|
||||
>
|
||||
{overlay !== undefined && overlayFunc !== undefined && (
|
||||
<div className={clsx('absolute', overlayClassName)} onClick={() => overlayFunc(i)}>
|
||||
{overlay}
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className="select-none"
|
||||
style={{ pointerEvents: 'none' }}
|
||||
>
|
||||
{child}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{isInfinite && React.Children.map(children, (child, i) => (
|
||||
<div
|
||||
key={`clone-${i}`}
|
||||
className="flex-shrink-0 relative"
|
||||
>
|
||||
{overlay !== undefined && overlayFunc !== undefined && (
|
||||
<div className={clsx('absolute', overlayClassName)} onClick={() => overlayFunc(i)}>
|
||||
{overlay}
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className="select-none"
|
||||
style={{ pointerEvents: 'none' }}
|
||||
>
|
||||
{child}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</animated.div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default InfiniteCarousel;
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
BsClipboardData,
|
||||
BsFileLock,
|
||||
} from "react-icons/bs";
|
||||
import { CiDumbbell } from "react-icons/ci";
|
||||
import {CiDumbbell} from "react-icons/ci";
|
||||
import {RiLogoutBoxFill} from "react-icons/ri";
|
||||
import {SlPencil} from "react-icons/sl";
|
||||
import {FaAward} from "react-icons/fa";
|
||||
@@ -28,6 +28,7 @@ import usePreferencesStore from "@/stores/preferencesStore";
|
||||
import {User} from "@/interfaces/user";
|
||||
import useTicketsListener from "@/hooks/useTicketsListener";
|
||||
import {checkAccess, getTypesOfUser} from "@/utils/permissions";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
interface Props {
|
||||
path: string;
|
||||
navDisabled?: boolean;
|
||||
@@ -80,6 +81,7 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
||||
const [isMinimized, toggleMinimize] = usePreferencesStore((state) => [state.isSidebarMinimized, state.toggleSidebarMinimized]);
|
||||
|
||||
const {totalAssignedTickets} = useTicketsListener(user.id);
|
||||
const {permissions} = usePermissions(user.id);
|
||||
|
||||
const logout = async () => {
|
||||
axios.post("/api/logout").finally(() => {
|
||||
@@ -98,22 +100,22 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
||||
)}>
|
||||
<div className="-xl:hidden flex-col gap-3 xl:flex">
|
||||
<Nav disabled={disableNavigation} Icon={MdSpaceDashboard} label="Dashboard" path={path} keyPath="/" isMinimized={isMinimized} />
|
||||
{checkAccess(user, ["student", "teacher", "developer"], "viewExams") && (
|
||||
{checkAccess(user, ["student", "teacher", "developer"], permissions, "viewExams") && (
|
||||
<Nav disabled={disableNavigation} Icon={BsFileEarmarkText} label="Exams" path={path} keyPath="/exam" isMinimized={isMinimized} />
|
||||
)}
|
||||
{checkAccess(user, ["student", "teacher", "developer"], "viewExercises") && (
|
||||
{checkAccess(user, ["student", "teacher", "developer"], permissions, "viewExercises") && (
|
||||
<Nav disabled={disableNavigation} Icon={BsPencil} label="Exercises" path={path} keyPath="/exercises" isMinimized={isMinimized} />
|
||||
)}
|
||||
{checkAccess(user, getTypesOfUser(["agent"]), "viewStats") && (
|
||||
{checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewStats") && (
|
||||
<Nav disabled={disableNavigation} Icon={BsGraphUp} label="Stats" path={path} keyPath="/stats" isMinimized={isMinimized} />
|
||||
)}
|
||||
{checkAccess(user, getTypesOfUser(["agent"]), "viewRecords") && (
|
||||
{checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewRecords") && (
|
||||
<Nav disabled={disableNavigation} Icon={BsClockHistory} label="Record" path={path} keyPath="/record" isMinimized={isMinimized} />
|
||||
)}
|
||||
{checkAccess(user, getTypesOfUser(["agent"]), "viewRecords") && (
|
||||
{checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewRecords") && (
|
||||
<Nav disabled={disableNavigation} Icon={CiDumbbell} label="Training" path={path} keyPath="/training" isMinimized={isMinimized} />
|
||||
)}
|
||||
{checkAccess(user, ["admin", "developer", "agent", "corporate", "mastercorporate"], "viewPaymentRecords") && (
|
||||
{checkAccess(user, ["admin", "developer", "agent", "corporate", "mastercorporate"], permissions, "viewPaymentRecords") && (
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsCurrencyDollar}
|
||||
@@ -133,7 +135,7 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
||||
isMinimized={isMinimized}
|
||||
/>
|
||||
)}
|
||||
{checkAccess(user, ["admin", "developer", "agent"], "viewTickets") && (
|
||||
{checkAccess(user, ["admin", "developer", "agent"], permissions, "viewTickets") && (
|
||||
<Nav
|
||||
disabled={disableNavigation}
|
||||
Icon={BsClipboardData}
|
||||
@@ -169,12 +171,15 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
||||
<Nav disabled={disableNavigation} Icon={MdSpaceDashboard} label="Dashboard" path={path} keyPath="/" isMinimized={true} />
|
||||
<Nav disabled={disableNavigation} Icon={BsFileEarmarkText} label="Exams" path={path} keyPath="/exam" isMinimized={true} />
|
||||
<Nav disabled={disableNavigation} Icon={BsPencil} label="Exercises" path={path} keyPath="/exercises" isMinimized={true} />
|
||||
{checkAccess(user, getTypesOfUser(["agent"]), "viewStats") && (
|
||||
{checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewStats") && (
|
||||
<Nav disabled={disableNavigation} Icon={BsGraphUp} label="Stats" path={path} keyPath="/stats" isMinimized={true} />
|
||||
)}
|
||||
{checkAccess(user, getTypesOfUser(["agent"]), "viewRecords") && (
|
||||
{checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewRecords") && (
|
||||
<Nav disabled={disableNavigation} Icon={BsClockHistory} label="Record" path={path} keyPath="/record" isMinimized={true} />
|
||||
)}
|
||||
{checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewRecords") && (
|
||||
<Nav disabled={disableNavigation} Icon={CiDumbbell} label="Training" path={path} keyPath="/training" isMinimized={true} />
|
||||
)}
|
||||
{checkAccess(user, getTypesOfUser(["student"])) && (
|
||||
<Nav disabled={disableNavigation} Icon={BsShieldFill} label="Settings" path={path} keyPath="/settings" isMinimized={true} />
|
||||
)}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import {InteractiveSpeakingExercise} from "@/interfaces/exam";
|
||||
import {CommonProps} from ".";
|
||||
import {useEffect, useState} from "react";
|
||||
import { InteractiveSpeakingExercise } from "@/interfaces/exam";
|
||||
import { CommonProps } from ".";
|
||||
import { useEffect, useState } from "react";
|
||||
import Button from "../Low/Button";
|
||||
import dynamic from "next/dynamic";
|
||||
import axios from "axios";
|
||||
import {speakingReverseMarking} from "@/utils/score";
|
||||
import {Tab} from "@headlessui/react";
|
||||
import { speakingReverseMarking } from "@/utils/score";
|
||||
import { Tab } from "@headlessui/react";
|
||||
import clsx from "clsx";
|
||||
import Modal from "../Modal";
|
||||
import ReactDiffViewer, {DiffMethod} from "react-diff-viewer";
|
||||
import ReactDiffViewer, { DiffMethod } from "react-diff-viewer";
|
||||
|
||||
const Waveform = dynamic(() => import("../Waveform"), {ssr: false});
|
||||
const Waveform = dynamic(() => import("../Waveform"), { ssr: false });
|
||||
|
||||
export default function InteractiveSpeaking({
|
||||
id,
|
||||
@@ -24,15 +24,22 @@ export default function InteractiveSpeaking({
|
||||
onBack,
|
||||
}: InteractiveSpeakingExercise & CommonProps) {
|
||||
const [solutionsURL, setSolutionsURL] = useState<string[]>([]);
|
||||
const [diffNumber, setDiffNumber] = useState<0 | 1 | 2 | 3>(0);
|
||||
const [diffNumber, setDiffNumber] = useState(0);
|
||||
|
||||
const tooltips: { [key: string]: string } = {
|
||||
"Grammatical Range and Accuracy": "Assesses the variety and correctness of grammatical structures used. A higher score indicates a wide range of complex and accurate grammar; a lower score suggests the need for more basic grammar practice.",
|
||||
"Fluency and Coherence": "Evaluates smoothness and logical flow of speech. A higher score means natural, effortless speech and clear idea progression; a lower score indicates frequent pauses and difficulty in maintaining coherence.",
|
||||
"Pronunciation": "Measures clarity and accuracy of spoken words. A higher score reflects clear, well-articulated speech with correct intonation; a lower score shows challenges in being understood.",
|
||||
"Lexical Resource": "Looks at the range and appropriateness of vocabulary. A higher score demonstrates a rich and precise vocabulary; a lower score suggests limited vocabulary usage and appropriateness.",
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (userSolutions && userSolutions.length > 0 && userSolutions[0].solution) {
|
||||
Promise.all(userSolutions[0].solution.map((x) => axios.post(`/api/speaking`, {path: x.answer}, {responseType: "arraybuffer"}))).then(
|
||||
Promise.all(userSolutions[0].solution.map((x) => axios.post(`/api/speaking`, { path: x.answer }, { responseType: "arraybuffer" }))).then(
|
||||
(values) => {
|
||||
setSolutionsURL(
|
||||
values.map(({data}) => {
|
||||
const blob = new Blob([data], {type: "audio/wav"});
|
||||
values.map(({ data }) => {
|
||||
const blob = new Blob([data], { type: "audio/wav" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
return url;
|
||||
@@ -64,13 +71,13 @@ export default function InteractiveSpeaking({
|
||||
fontFamily: '"Open Sans", system-ui, -apple-system, "Helvetica Neue", sans-serif',
|
||||
padding: "32px 28px",
|
||||
},
|
||||
marker: {display: "none"},
|
||||
diffRemoved: {padding: "32px 28px"},
|
||||
diffAdded: {padding: "32px 28px"},
|
||||
marker: { display: "none" },
|
||||
diffRemoved: { padding: "32px 28px" },
|
||||
diffAdded: { padding: "32px 28px" },
|
||||
|
||||
wordRemoved: {padding: "0px", display: "initial"},
|
||||
wordAdded: {padding: "0px", display: "initial"},
|
||||
wordDiff: {padding: "0px", display: "initial"},
|
||||
wordRemoved: { padding: "0px", display: "initial" },
|
||||
wordAdded: { padding: "0px", display: "initial" },
|
||||
wordDiff: { padding: "0px", display: "initial" },
|
||||
}}
|
||||
oldValue={userSolutions[0].evaluation[`transcript_${diffNumber}`]?.replaceAll("\\n", "\n")}
|
||||
newValue={userSolutions[0].evaluation[`fixed_text_${diffNumber}`]?.replaceAll("\\n", "\n")}
|
||||
@@ -115,13 +122,13 @@ export default function InteractiveSpeaking({
|
||||
{userSolutions &&
|
||||
userSolutions.length > 0 &&
|
||||
userSolutions[0].evaluation &&
|
||||
userSolutions[0].evaluation[`transcript_${(index + 1) as 1 | 2 | 3}`] &&
|
||||
userSolutions[0].evaluation[`fixed_text_${(index + 1) as 1 | 2 | 3}`] && (
|
||||
userSolutions[0].evaluation[`transcript_${(index + 1)}`] &&
|
||||
userSolutions[0].evaluation[`fixed_text_${(index + 1)}`] && (
|
||||
<Button
|
||||
className="w-full max-w-[180px] !py-2 self-center"
|
||||
color="pink"
|
||||
variant="outline"
|
||||
onClick={() => setDiffNumber((index + 1) as 1 | 2 | 3)}>
|
||||
onClick={() => setDiffNumber((index + 1))}>
|
||||
View Correction
|
||||
</Button>
|
||||
)}
|
||||
@@ -132,23 +139,36 @@ export default function InteractiveSpeaking({
|
||||
{userSolutions && userSolutions.length > 0 && userSolutions[0].evaluation && typeof userSolutions[0].evaluation !== "string" && (
|
||||
<div className="flex flex-col gap-4 w-full">
|
||||
<div className="flex gap-4 px-1">
|
||||
{Object.keys(userSolutions[0].evaluation!.task_response).map((key) => {
|
||||
{Object.keys(userSolutions[0].evaluation!.task_response).map((key, index) => {
|
||||
const taskResponse = userSolutions[0].evaluation!.task_response[key];
|
||||
const grade: number = typeof taskResponse === "number" ? taskResponse : taskResponse.grade;
|
||||
|
||||
return (
|
||||
<div className={clsx("bg-ielts-speaking text-ielts-speaking-light rounded-xl px-4 py-2")} key={key}>
|
||||
<div className={clsx("bg-ielts-speaking text-ielts-speaking-light rounded-xl px-4 py-2 tooltip tooltip-bottom",
|
||||
index === 0 && "tooltip-right"
|
||||
)} key={key} data-tip={tooltips[key] || "No additional information available"}>
|
||||
{key}: Level {grade}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{userSolutions[0].evaluation &&
|
||||
Object.keys(userSolutions[0].evaluation).filter((x) => x.startsWith("perfect_answer")).length === 3 ? (
|
||||
Object.keys(userSolutions[0].evaluation).filter((x) => x.startsWith("perfect_answer")).length > 0 ? (
|
||||
<Tab.Group>
|
||||
<Tab.List className="flex space-x-1 rounded-xl bg-ielts-speaking/20 p-1">
|
||||
<Tab
|
||||
className={({selected}) =>
|
||||
className={({ selected }) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/80",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-speaking",
|
||||
)
|
||||
}>
|
||||
General Feedback
|
||||
</Tab>
|
||||
<Tab
|
||||
className={({ selected }) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/80",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
|
||||
@@ -158,70 +178,22 @@ export default function InteractiveSpeaking({
|
||||
}>
|
||||
Evaluation
|
||||
</Tab>
|
||||
<Tab
|
||||
className={({selected}) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/80",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-speaking",
|
||||
)
|
||||
}>
|
||||
Recommended Answer (Prompt 1)
|
||||
</Tab>
|
||||
<Tab
|
||||
className={({selected}) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/80",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-speaking",
|
||||
)
|
||||
}>
|
||||
Recommended Answer (Prompt 2)
|
||||
</Tab>
|
||||
<Tab
|
||||
className={({selected}) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/80",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-speaking",
|
||||
)
|
||||
}>
|
||||
Recommended Answer (Prompt 3)
|
||||
</Tab>
|
||||
<Tab
|
||||
className={({selected}) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/80",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-speaking",
|
||||
)
|
||||
}>
|
||||
Global Overview
|
||||
</Tab>
|
||||
{Object.keys(userSolutions[0].evaluation).filter((x) => x.startsWith("perfect_answer")).map((key, index) => (
|
||||
<Tab
|
||||
key={key}
|
||||
className={({ selected }) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/80",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-speaking",
|
||||
)
|
||||
}>
|
||||
Recommended Answer<br />(Prompt {index + 1})
|
||||
</Tab>
|
||||
))}
|
||||
</Tab.List>
|
||||
<Tab.Panels>
|
||||
<Tab.Panel className="w-full bg-ielts-speaking/10 h-fit rounded-xl p-6 flex flex-col gap-4">
|
||||
<span className="w-full h-full min-h-fit cursor-text">{userSolutions[0].evaluation!.comment}</span>
|
||||
</Tab.Panel>
|
||||
<Tab.Panel className="w-full bg-ielts-speaking/10 h-fit rounded-xl p-6 flex flex-col gap-4">
|
||||
<span className="w-full h-full min-h-fit cursor-text whitespace-pre-wrap">
|
||||
{userSolutions[0].evaluation!.perfect_answer_1!.answer.replaceAll(/\s{2,}/g, "\n\n")}
|
||||
</span>
|
||||
</Tab.Panel>
|
||||
<Tab.Panel className="w-full bg-ielts-speaking/10 h-fit rounded-xl p-6 flex flex-col gap-4">
|
||||
<span className="w-full h-full min-h-fit cursor-text whitespace-pre-wrap">
|
||||
{userSolutions[0].evaluation!.perfect_answer_2!.answer.replaceAll(/\s{2,}/g, "\n\n")}
|
||||
</span>
|
||||
</Tab.Panel>
|
||||
<Tab.Panel className="w-full bg-ielts-speaking/10 h-fit rounded-xl p-6 flex flex-col gap-4">
|
||||
<span className="w-full h-full min-h-fit cursor-text whitespace-pre-wrap">
|
||||
{userSolutions[0].evaluation!.perfect_answer_3!.answer.replaceAll(/\s{2,}/g, "\n\n")}
|
||||
</span>
|
||||
</Tab.Panel>
|
||||
<Tab.Panel className="w-full bg-ielts-speaking/10 h-fit rounded-xl p-6 flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-4">
|
||||
{Object.keys(userSolutions[0].evaluation!.task_response).map((key) => {
|
||||
@@ -230,15 +202,25 @@ export default function InteractiveSpeaking({
|
||||
|
||||
return (
|
||||
<div key={key} className="flex flex-col gap-2">
|
||||
<span className={"font-semibold"}>
|
||||
<div className={clsx("bg-ielts-speaking text-ielts-speaking-light rounded-xl px-4 py-2 w-fit")} key={key}>
|
||||
{key}: Level {grade}
|
||||
</span>
|
||||
{typeof taskResponse !== "number" && <span>{taskResponse.comment}</span>}
|
||||
</div>
|
||||
{typeof taskResponse !== "number" && <span className="px-2 py-2">{taskResponse.comment}</span>}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Tab.Panel>
|
||||
<Tab.Panel className="w-full bg-ielts-speaking/10 h-fit rounded-xl p-6 flex flex-col gap-4">
|
||||
<span className="w-full h-full min-h-fit cursor-text">{userSolutions[0].evaluation!.comment}</span>
|
||||
</Tab.Panel>
|
||||
{Object.keys(userSolutions[0].evaluation).filter((x) => x.startsWith("perfect_answer")).map((key, index) => (
|
||||
<Tab.Panel key={key} className="w-full bg-ielts-speaking/10 h-fit rounded-xl p-6 flex flex-col gap-4">
|
||||
<span className="w-full h-full min-h-fit cursor-text whitespace-pre-wrap">
|
||||
{userSolutions[0].evaluation![`perfect_answer_${(index + 1)}`].answer.replaceAll(/\s{2,}/g, "\n\n")}
|
||||
</span>
|
||||
</Tab.Panel>
|
||||
))}
|
||||
</Tab.Panels>
|
||||
</Tab.Group>
|
||||
) : (
|
||||
@@ -259,7 +241,7 @@ export default function InteractiveSpeaking({
|
||||
onBack({
|
||||
exercise: id,
|
||||
solutions: userSolutions,
|
||||
score: {total: 100, missing: 0, correct: speakingReverseMarking[userSolutions[0]!.evaluation!.overall] || 0},
|
||||
score: { total: 100, missing: 0, correct: speakingReverseMarking[userSolutions[0]!.evaluation!.overall] || 0 },
|
||||
type,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import {SpeakingExercise} from "@/interfaces/exam";
|
||||
import {CommonProps} from ".";
|
||||
import {Fragment, useEffect, useState} from "react";
|
||||
import { SpeakingExercise } from "@/interfaces/exam";
|
||||
import { CommonProps } from ".";
|
||||
import { Fragment, useEffect, useState } from "react";
|
||||
import Button from "../Low/Button";
|
||||
import dynamic from "next/dynamic";
|
||||
import axios from "axios";
|
||||
import {speakingReverseMarking} from "@/utils/score";
|
||||
import {Tab} from "@headlessui/react";
|
||||
import { speakingReverseMarking } from "@/utils/score";
|
||||
import { Tab } from "@headlessui/react";
|
||||
import clsx from "clsx";
|
||||
import Modal from "../Modal";
|
||||
import {BsQuestionCircleFill} from "react-icons/bs";
|
||||
import ReactDiffViewer, {DiffMethod} from "react-diff-viewer";
|
||||
import { BsQuestionCircleFill } from "react-icons/bs";
|
||||
import ReactDiffViewer, { DiffMethod } from "react-diff-viewer";
|
||||
|
||||
const Waveform = dynamic(() => import("../Waveform"), {ssr: false});
|
||||
const Waveform = dynamic(() => import("../Waveform"), { ssr: false });
|
||||
|
||||
export default function Speaking({id, type, title, video_url, text, prompts, userSolutions, onNext, onBack}: SpeakingExercise & CommonProps) {
|
||||
export default function Speaking({ id, type, title, video_url, text, prompts, userSolutions, onNext, onBack }: SpeakingExercise & CommonProps) {
|
||||
const [solutionURL, setSolutionURL] = useState<string>();
|
||||
const [showDiff, setShowDiff] = useState(false);
|
||||
|
||||
@@ -23,8 +23,8 @@ export default function Speaking({id, type, title, video_url, text, prompts, use
|
||||
const solution = userSolutions[0].solution;
|
||||
|
||||
if (solution.startsWith("https://")) return setSolutionURL(solution);
|
||||
axios.post(`/api/speaking`, {path: userSolutions[0].solution}, {responseType: "arraybuffer"}).then(({data}) => {
|
||||
const blob = new Blob([data], {type: "audio/wav"});
|
||||
axios.post(`/api/speaking`, { path: userSolutions[0].solution }, { responseType: "arraybuffer" }).then(({ data }) => {
|
||||
const blob = new Blob([data], { type: "audio/wav" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
setSolutionURL(url);
|
||||
@@ -32,6 +32,13 @@ export default function Speaking({id, type, title, video_url, text, prompts, use
|
||||
}
|
||||
}, [userSolutions]);
|
||||
|
||||
const tooltips: { [key: string]: string } = {
|
||||
"Grammatical Range and Accuracy": "Assesses the variety and correctness of grammatical structures used. A higher score indicates a wide range of complex and accurate grammar; a lower score suggests the need for more basic grammar practice.",
|
||||
"Fluency and Coherence": "Evaluates smoothness and logical flow of speech. A higher score means natural, effortless speech and clear idea progression; a lower score indicates frequent pauses and difficulty in maintaining coherence.",
|
||||
"Pronunciation": "Measures clarity and accuracy of spoken words. A higher score reflects clear, well-articulated speech with correct intonation; a lower score shows challenges in being understood.",
|
||||
"Lexical Resource": "Looks at the range and appropriateness of vocabulary. A higher score demonstrates a rich and precise vocabulary; a lower score suggests limited vocabulary usage and appropriateness.",
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal title="Correction" isOpen={showDiff} onClose={() => setShowDiff(false)}>
|
||||
@@ -51,13 +58,13 @@ export default function Speaking({id, type, title, video_url, text, prompts, use
|
||||
fontFamily: '"Open Sans", system-ui, -apple-system, "Helvetica Neue", sans-serif',
|
||||
padding: "32px 28px",
|
||||
},
|
||||
marker: {display: "none"},
|
||||
diffRemoved: {padding: "32px 28px"},
|
||||
diffAdded: {padding: "32px 28px"},
|
||||
marker: { display: "none" },
|
||||
diffRemoved: { padding: "32px 28px" },
|
||||
diffAdded: { padding: "32px 28px" },
|
||||
|
||||
wordRemoved: {padding: "0px", display: "initial"},
|
||||
wordAdded: {padding: "0px", display: "initial"},
|
||||
wordDiff: {padding: "0px", display: "initial"},
|
||||
wordRemoved: { padding: "0px", display: "initial" },
|
||||
wordAdded: { padding: "0px", display: "initial" },
|
||||
wordDiff: { padding: "0px", display: "initial" },
|
||||
}}
|
||||
oldValue={userSolutions[0].evaluation.transcript_1.replaceAll("\\n", "\n")}
|
||||
newValue={userSolutions[0].evaluation.fixed_text_1.replaceAll("\\n", "\n")}
|
||||
@@ -126,23 +133,36 @@ export default function Speaking({id, type, title, video_url, text, prompts, use
|
||||
{userSolutions && userSolutions.length > 0 && userSolutions[0].evaluation && typeof userSolutions[0].evaluation !== "string" && (
|
||||
<div className="flex flex-col gap-4 w-full">
|
||||
<div className="flex gap-4 px-1">
|
||||
{Object.keys(userSolutions[0].evaluation!.task_response).map((key) => {
|
||||
{Object.keys(userSolutions[0].evaluation!.task_response).map((key, index) => {
|
||||
const taskResponse = userSolutions[0].evaluation!.task_response[key];
|
||||
const grade: number = typeof taskResponse === "number" ? taskResponse : taskResponse.grade;
|
||||
|
||||
return (
|
||||
<div className={clsx("bg-ielts-speaking text-ielts-speaking-light rounded-xl px-4 py-2")} key={key}>
|
||||
<div className={clsx("bg-ielts-speaking text-ielts-speaking-light rounded-xl px-4 py-2 tooltip tooltip-bottom",
|
||||
index === 0 && "tooltip-right"
|
||||
)} key={key} data-tip={tooltips[key] || "No additional information available"}>
|
||||
{key}: Level {grade}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{userSolutions[0].evaluation &&
|
||||
(userSolutions[0].evaluation.perfect_answer || userSolutions[0].evaluation.perfect_answer_1) ? (
|
||||
(userSolutions[0].evaluation.perfect_answer || userSolutions[0].evaluation.perfect_answer_1) ? (
|
||||
<Tab.Group>
|
||||
<Tab.List className="flex space-x-1 rounded-xl bg-ielts-speaking/20 p-1">
|
||||
<Tab
|
||||
className={({selected}) =>
|
||||
className={({ selected }) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/80",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-speaking",
|
||||
)
|
||||
}>
|
||||
General Feedback
|
||||
</Tab>
|
||||
<Tab
|
||||
className={({ selected }) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/80",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
|
||||
@@ -153,7 +173,7 @@ export default function Speaking({id, type, title, video_url, text, prompts, use
|
||||
Evaluation
|
||||
</Tab>
|
||||
<Tab
|
||||
className={({selected}) =>
|
||||
className={({ selected }) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/80",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
|
||||
@@ -163,30 +183,9 @@ export default function Speaking({id, type, title, video_url, text, prompts, use
|
||||
}>
|
||||
Recommended Answer
|
||||
</Tab>
|
||||
<Tab
|
||||
className={({selected}) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/80",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-speaking",
|
||||
)
|
||||
}>
|
||||
Global Overview
|
||||
</Tab>
|
||||
</Tab.List>
|
||||
<Tab.Panels>
|
||||
<Tab.Panel className="w-full bg-ielts-speaking/10 h-fit rounded-xl p-6 flex flex-col gap-4">
|
||||
<span className="w-full h-full min-h-fit cursor-text">{userSolutions[0].evaluation!.comment}</span>
|
||||
</Tab.Panel>
|
||||
<Tab.Panel className="w-full bg-ielts-speaking/10 h-fit rounded-xl p-6 flex flex-col gap-4">
|
||||
<span className="w-full h-full min-h-fit cursor-text whitespace-pre-wrap">
|
||||
{userSolutions[0].evaluation!.perfect_answer &&
|
||||
userSolutions[0].evaluation!.perfect_answer.replaceAll(/\s{2,}/g, "\n\n")}
|
||||
{userSolutions[0].evaluation!.perfect_answer_1 &&
|
||||
userSolutions[0].evaluation!.perfect_answer_1.replaceAll(/\s{2,}/g, "\n\n")}
|
||||
</span>
|
||||
</Tab.Panel>
|
||||
{/* General Feedback */}
|
||||
<Tab.Panel className="w-full bg-ielts-speaking/10 h-fit rounded-xl p-6 flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-4">
|
||||
{Object.keys(userSolutions[0].evaluation!.task_response).map((key) => {
|
||||
@@ -195,15 +194,28 @@ export default function Speaking({id, type, title, video_url, text, prompts, use
|
||||
|
||||
return (
|
||||
<div key={key} className="flex flex-col gap-2">
|
||||
<span className={"font-semibold"}>
|
||||
<div className={clsx("bg-ielts-speaking text-ielts-speaking-light rounded-xl px-4 py-2 w-fit")} key={key}>
|
||||
{key}: Level {grade}
|
||||
</span>
|
||||
{typeof taskResponse !== "number" && <span>{taskResponse.comment}</span>}
|
||||
</div>
|
||||
{typeof taskResponse !== "number" && <span className="px-2 py-2">{taskResponse.comment}</span>}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Tab.Panel>
|
||||
{/* Evaluation */}
|
||||
<Tab.Panel className="w-full bg-ielts-speaking/10 h-fit rounded-xl p-6 flex flex-col gap-4">
|
||||
<span className="w-full h-full min-h-fit cursor-text">{userSolutions[0].evaluation!.comment}</span>
|
||||
</Tab.Panel>
|
||||
{/* Recommended Answer */}
|
||||
<Tab.Panel className="w-full bg-ielts-speaking/10 h-fit rounded-xl p-6 flex flex-col gap-4">
|
||||
<span className="w-full h-full min-h-fit cursor-text whitespace-pre-wrap">
|
||||
{userSolutions[0].evaluation!.perfect_answer &&
|
||||
userSolutions[0].evaluation!.perfect_answer.replaceAll(/\s{2,}/g, "\n\n")}
|
||||
{userSolutions[0].evaluation!.perfect_answer_1 &&
|
||||
userSolutions[0].evaluation!.perfect_answer_1.replaceAll(/\s{2,}/g, "\n\n")}
|
||||
</span>
|
||||
</Tab.Panel>
|
||||
</Tab.Panels>
|
||||
</Tab.Group>
|
||||
) : (
|
||||
@@ -224,7 +236,7 @@ export default function Speaking({id, type, title, video_url, text, prompts, use
|
||||
onBack({
|
||||
exercise: id,
|
||||
solutions: userSolutions,
|
||||
score: {total: 100, missing: 0, correct: speakingReverseMarking[userSolutions[0]!.evaluation!.overall] || 0},
|
||||
score: { total: 100, missing: 0, correct: speakingReverseMarking[userSolutions[0]!.evaluation!.overall] || 0 },
|
||||
type,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,23 +1,30 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import {WritingExercise} from "@/interfaces/exam";
|
||||
import {CommonProps} from ".";
|
||||
import {Fragment, useEffect, useState} from "react";
|
||||
import { WritingExercise } from "@/interfaces/exam";
|
||||
import { CommonProps } from ".";
|
||||
import { Fragment, useEffect, useState } from "react";
|
||||
import Button from "../Low/Button";
|
||||
import {Dialog, Tab, Transition} from "@headlessui/react";
|
||||
import {writingReverseMarking} from "@/utils/score";
|
||||
import { Dialog, Tab, Transition } from "@headlessui/react";
|
||||
import { writingReverseMarking } from "@/utils/score";
|
||||
import clsx from "clsx";
|
||||
import ReactDiffViewer, {DiffMethod} from "react-diff-viewer";
|
||||
import ReactDiffViewer, { DiffMethod } from "react-diff-viewer";
|
||||
import useUser from "@/hooks/useUser";
|
||||
import AIDetection from "../AIDetection";
|
||||
|
||||
export default function Writing({id, type, prompt, attachment, userSolutions, onNext, onBack}: WritingExercise & CommonProps) {
|
||||
export default function Writing({ id, type, prompt, attachment, userSolutions, onNext, onBack }: WritingExercise & CommonProps) {
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [showDiff, setShowDiff] = useState(false);
|
||||
|
||||
const {user} = useUser();
|
||||
const { user } = useUser();
|
||||
|
||||
const aiEval = userSolutions && userSolutions.length > 0 ? userSolutions[0].evaluation?.ai_detection : undefined;
|
||||
|
||||
const tooltips: { [key: string]: string } = {
|
||||
"Lexical Resource": "Assesses the diversity and accuracy of vocabulary used. A higher score indicates varied and precise word choice; a lower score points to limited vocabulary and inaccuracies.",
|
||||
"Task Achievement": "Evaluates how well the task requirements are fulfilled. A higher score means all parts of the task are addressed thoroughly; a lower score shows incomplete or inadequate task response.",
|
||||
"Coherence and Cohesion": "Measures logical organization and flow of writing. A higher score reflects well-structured and connected ideas; a lower score indicates disorganized writing and poor linkage between ideas.",
|
||||
"Grammatical Range and Accuracy": "Looks at the range and precision of grammatical structures. A higher score shows varied and accurate grammar use; a lower score suggests frequent errors and limited range.",
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{attachment && (
|
||||
@@ -92,13 +99,13 @@ export default function Writing({id, type, prompt, attachment, userSolutions, on
|
||||
fontFamily: '"Open Sans", system-ui, -apple-system, "Helvetica Neue", sans-serif',
|
||||
padding: "32px 28px",
|
||||
},
|
||||
marker: {display: "none"},
|
||||
diffRemoved: {padding: "32px 28px"},
|
||||
diffAdded: {padding: "32px 28px"},
|
||||
marker: { display: "none" },
|
||||
diffRemoved: { padding: "32px 28px" },
|
||||
diffAdded: { padding: "32px 28px" },
|
||||
|
||||
wordRemoved: {padding: "0px", display: "initial"},
|
||||
wordAdded: {padding: "0px", display: "initial"},
|
||||
wordDiff: {padding: "0px", display: "initial"},
|
||||
wordRemoved: { padding: "0px", display: "initial" },
|
||||
wordAdded: { padding: "0px", display: "initial" },
|
||||
wordDiff: { padding: "0px", display: "initial" },
|
||||
}}
|
||||
oldValue={userSolutions[0].solution.replaceAll("\\n", "\n")}
|
||||
newValue={userSolutions[0].evaluation!.fixed_text!.replaceAll("\\n", "\n")}
|
||||
@@ -123,12 +130,15 @@ export default function Writing({id, type, prompt, attachment, userSolutions, on
|
||||
{userSolutions && userSolutions.length > 0 && userSolutions[0].evaluation && typeof userSolutions[0].evaluation !== "string" && (
|
||||
<div className="flex flex-col gap-4 w-full">
|
||||
<div className="flex gap-4 px-1">
|
||||
{Object.keys(userSolutions[0].evaluation!.task_response).map((key) => {
|
||||
{Object.keys(userSolutions[0].evaluation!.task_response).map((key, index) => {
|
||||
const taskResponse = userSolutions[0].evaluation!.task_response[key];
|
||||
const grade: number = typeof taskResponse === "number" ? taskResponse : taskResponse.grade;
|
||||
|
||||
return (
|
||||
<div className={clsx("bg-ielts-writing text-ielts-writing-light rounded-xl px-4 py-2")} key={key}>
|
||||
<div className={clsx(
|
||||
"bg-ielts-writing text-ielts-writing-light rounded-xl px-4 py-2 tooltip tooltip-bottom",
|
||||
index === 0 && "tooltip-right"
|
||||
)} key={key} data-tip={tooltips[key] || "No additional information available"}>
|
||||
{key}: Level {grade}
|
||||
</div>
|
||||
);
|
||||
@@ -138,7 +148,18 @@ export default function Writing({id, type, prompt, attachment, userSolutions, on
|
||||
<Tab.Group>
|
||||
<Tab.List className="flex space-x-1 rounded-xl bg-ielts-writing/20 p-1">
|
||||
<Tab
|
||||
className={({selected}) =>
|
||||
className={({ selected }) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-writing/80",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-writing focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-writing",
|
||||
)
|
||||
}>
|
||||
General Feedback
|
||||
</Tab>
|
||||
<Tab
|
||||
className={({ selected }) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-writing/80",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-writing focus:outline-none focus:ring-2",
|
||||
@@ -149,7 +170,7 @@ export default function Writing({id, type, prompt, attachment, userSolutions, on
|
||||
Evaluation
|
||||
</Tab>
|
||||
<Tab
|
||||
className={({selected}) =>
|
||||
className={({ selected }) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-writing/80",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-writing focus:outline-none focus:ring-2",
|
||||
@@ -159,20 +180,9 @@ export default function Writing({id, type, prompt, attachment, userSolutions, on
|
||||
}>
|
||||
Recommended Answer
|
||||
</Tab>
|
||||
<Tab
|
||||
className={({selected}) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-writing/80",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-writing focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-writing",
|
||||
)
|
||||
}>
|
||||
Global Overview
|
||||
</Tab>
|
||||
{aiEval && user?.type !== "student" && (
|
||||
<Tab
|
||||
className={({selected}) =>
|
||||
className={({ selected }) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-writing/80",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-writing focus:outline-none focus:ring-2",
|
||||
@@ -185,14 +195,7 @@ export default function Writing({id, type, prompt, attachment, userSolutions, on
|
||||
)}
|
||||
</Tab.List>
|
||||
<Tab.Panels>
|
||||
<Tab.Panel className="w-full bg-ielts-writing/10 h-fit rounded-xl p-6 flex flex-col gap-4">
|
||||
<span className="w-full h-full min-h-fit cursor-text">{userSolutions[0].evaluation!.comment}</span>
|
||||
</Tab.Panel>
|
||||
<Tab.Panel className="w-full bg-ielts-writing/10 h-fit rounded-xl p-6 flex flex-col gap-4">
|
||||
<span className="w-full h-full min-h-fit cursor-text whitespace-pre-wrap">
|
||||
{userSolutions[0].evaluation!.perfect_answer.replaceAll(/\s{2,}/g, "\n\n").replaceAll("\\n", "\n")}
|
||||
</span>
|
||||
</Tab.Panel>
|
||||
{/* Global */}
|
||||
<Tab.Panel className="w-full bg-ielts-writing/10 h-fit rounded-xl p-6 flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-4">
|
||||
{Object.keys(userSolutions[0].evaluation!.task_response).map((key) => {
|
||||
@@ -201,15 +204,25 @@ export default function Writing({id, type, prompt, attachment, userSolutions, on
|
||||
|
||||
return (
|
||||
<div key={key} className="flex flex-col gap-2">
|
||||
<span className={"font-semibold"}>
|
||||
<div className={clsx("bg-ielts-writing text-ielts-writing-light rounded-xl px-4 py-2 w-fit")} key={key}>
|
||||
{key}: Level {grade}
|
||||
</span>
|
||||
{typeof taskResponse !== "number" && <span>{taskResponse.comment}</span>}
|
||||
</div>
|
||||
{typeof taskResponse !== "number" && <span className="px-2 py-2">{taskResponse.comment}</span>}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Tab.Panel>
|
||||
{/* Evaluation */}
|
||||
<Tab.Panel className="w-full bg-ielts-writing/10 h-fit rounded-xl p-6 flex flex-col gap-4">
|
||||
<span className="w-full h-full min-h-fit cursor-text">{userSolutions[0].evaluation!.comment}</span>
|
||||
</Tab.Panel>
|
||||
{/* Recommended Answer */}
|
||||
<Tab.Panel className="w-full bg-ielts-writing/10 h-fit rounded-xl p-6 flex flex-col gap-4">
|
||||
<span className="w-full h-full min-h-fit cursor-text whitespace-pre-wrap">
|
||||
{userSolutions[0].evaluation!.perfect_answer.replaceAll(/\s{2,}/g, "\n\n").replaceAll("\\n", "\n")}
|
||||
</span>
|
||||
</Tab.Panel>
|
||||
{aiEval && user?.type !== "student" && (
|
||||
<Tab.Panel className="w-full bg-ielts-writing/10 h-fit rounded-xl p-6 flex flex-col gap-4">
|
||||
<AIDetection {...aiEval} />
|
||||
@@ -235,7 +248,7 @@ export default function Writing({id, type, prompt, attachment, userSolutions, on
|
||||
onBack({
|
||||
exercise: id,
|
||||
solutions: userSolutions,
|
||||
score: {total: 100, missing: 0, correct: writingReverseMarking[userSolutions[0]!.evaluation!.overall] || 0},
|
||||
score: { total: 100, missing: 0, correct: writingReverseMarking[userSolutions[0]!.evaluation!.overall] || 0 },
|
||||
type,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import { Exam, UserSolution } from '@/interfaces/exam';
|
||||
import ModuleBadge from './ModuleBadge';
|
||||
|
||||
const formatTimestamp = (timestamp: string | number) => {
|
||||
const time = typeof timestamp === "string" ? parseInt(timestamp) : timestamp;
|
||||
const time = typeof timestamp === "string" ? parseInt(timestamp) : timestamp;
|
||||
const date = moment(time);
|
||||
const formatter = "YYYY/MM/DD - HH:mm";
|
||||
return date.format(formatter);
|
||||
@@ -68,6 +68,9 @@ const aggregateScoresByModule = (stats: Stat[]): { module: Module; total: number
|
||||
};
|
||||
|
||||
interface StatsGridItemProps {
|
||||
width?: string | undefined;
|
||||
height?: string | undefined;
|
||||
examNumber?: number | undefined;
|
||||
stats: Stat[];
|
||||
timestamp: string | number;
|
||||
user: User,
|
||||
@@ -75,6 +78,7 @@ interface StatsGridItemProps {
|
||||
users: User[];
|
||||
training?: boolean,
|
||||
selectedTrainingExams?: string[];
|
||||
maxTrainingExams?: number;
|
||||
setSelectedTrainingExams?: React.Dispatch<React.SetStateAction<string[]>>;
|
||||
setExams: (exams: Exam[]) => void;
|
||||
setShowSolutions: (show: boolean) => void;
|
||||
@@ -100,7 +104,11 @@ const StatsGridItem: React.FC<StatsGridItemProps> = ({
|
||||
setSelectedModules,
|
||||
setInactivity,
|
||||
setTimeSpent,
|
||||
renderPdfIcon
|
||||
renderPdfIcon,
|
||||
width = undefined,
|
||||
height = undefined,
|
||||
examNumber = undefined,
|
||||
maxTrainingExams = undefined
|
||||
}) => {
|
||||
const router = useRouter();
|
||||
const correct = stats.reduce((accumulator, current) => accumulator + current.score.correct, 0);
|
||||
@@ -126,16 +134,22 @@ const StatsGridItem: React.FC<StatsGridItemProps> = ({
|
||||
const { timeSpent, inactivity, session } = stats[0];
|
||||
|
||||
const selectExam = () => {
|
||||
if (training && !isDisabled && typeof setSelectedTrainingExams !== "undefined" && typeof timestamp == "string") {
|
||||
if (training && !isDisabled && typeof maxTrainingExams !== "undefined" && typeof setSelectedTrainingExams !== "undefined" && typeof timestamp == "string") {
|
||||
setSelectedTrainingExams(prevExams => {
|
||||
const index = prevExams.indexOf(timestamp);
|
||||
|
||||
if (index !== -1) {
|
||||
const uniqueExams = [...new Set(stats.map(stat => `${stat.module}-${stat.date}`))];
|
||||
const indexes = uniqueExams.map(exam => prevExams.indexOf(exam)).filter(index => index !== -1);
|
||||
if (indexes.length > 0) {
|
||||
const newExams = [...prevExams];
|
||||
newExams.splice(index, 1);
|
||||
indexes.sort((a, b) => b - a).forEach(index => {
|
||||
newExams.splice(index, 1);
|
||||
});
|
||||
return newExams;
|
||||
} else {
|
||||
return [...prevExams, timestamp];
|
||||
if (prevExams.length + uniqueExams.length <= maxTrainingExams) {
|
||||
return [...prevExams, ...uniqueExams];
|
||||
} else {
|
||||
return prevExams;
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
@@ -190,22 +204,33 @@ const StatsGridItem: React.FC<StatsGridItemProps> = ({
|
||||
</span>
|
||||
{renderPdfIcon(session, textColor, textColor)}
|
||||
</div>
|
||||
{aiUsage >= 50 && user.type !== "student" && (
|
||||
<div className={clsx(
|
||||
"ml-auto border px-1 rounded w-fit mr-1",
|
||||
{
|
||||
'bg-orange-100 border-orange-400 text-orange-700': aiUsage < 80,
|
||||
'bg-red-100 border-red-400 text-red-700': aiUsage >= 80,
|
||||
}
|
||||
)}>
|
||||
<span className="text-xs">AI Usage</span>
|
||||
{examNumber === undefined ? (
|
||||
<>
|
||||
{aiUsage >= 50 && user.type !== "student" && (
|
||||
<div className={clsx(
|
||||
"ml-auto border px-1 rounded w-fit mr-1",
|
||||
{
|
||||
'bg-orange-100 border-orange-400 text-orange-700': aiUsage < 80,
|
||||
'bg-red-100 border-red-400 text-red-700': aiUsage >= 80,
|
||||
}
|
||||
)}>
|
||||
<span className="text-xs">AI Usage</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className='flex justify-end'>
|
||||
<span className="font-semibold bg-gray-200 text-gray-800 px-2.5 py-0.5 rounded-full mt-0.5">{examNumber}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="w-full flex flex-col gap-1">
|
||||
<div className="grid grid-cols-4 gap-2 place-items-start w-full -md:mt-2">
|
||||
<div className={clsx(
|
||||
"grid grid-cols-4 gap-2 place-items-start w-full -md:mt-2",
|
||||
examNumber !== undefined && "pr-10"
|
||||
)}>
|
||||
{aggregatedLevels.map(({ module, level }) => (
|
||||
<ModuleBadge key={module} module={module} level={level} />
|
||||
))}
|
||||
@@ -230,9 +255,13 @@ const StatsGridItem: React.FC<StatsGridItemProps> = ({
|
||||
correct / total >= 0.7 && "hover:border-mti-purple",
|
||||
correct / total >= 0.3 && correct / total < 0.7 && "hover:border-mti-red",
|
||||
correct / total < 0.3 && "hover:border-mti-rose",
|
||||
typeof selectedTrainingExams !== "undefined" && typeof timestamp === "string" && selectedTrainingExams.includes(timestamp) && "border-2 border-slate-600",
|
||||
typeof selectedTrainingExams !== "undefined" && typeof timestamp === "string" && selectedTrainingExams.some(exam => exam.includes(timestamp)) && "border-2 border-slate-600",
|
||||
)}
|
||||
onClick={selectExam}
|
||||
onClick={examNumber === undefined ? selectExam : undefined}
|
||||
style={{
|
||||
...(width !== undefined && { width }),
|
||||
...(height !== undefined && { height }),
|
||||
}}
|
||||
data-tip="This exam is still being evaluated..."
|
||||
role="button">
|
||||
{content}
|
||||
@@ -246,6 +275,10 @@ const StatsGridItem: React.FC<StatsGridItemProps> = ({
|
||||
correct / total < 0.3 && "hover:border-mti-rose",
|
||||
)}
|
||||
data-tip="Your screen size is too small to view previous exams."
|
||||
style={{
|
||||
...(width !== undefined && { width }),
|
||||
...(height !== undefined && { height }),
|
||||
}}
|
||||
role="button">
|
||||
{content}
|
||||
</div>
|
||||
|
||||
@@ -17,9 +17,10 @@ const TrainingScore: React.FC<TrainingScoreProps> = ({
|
||||
const scores = trainingContent.exams.map(exam => exam.score);
|
||||
const highestScore = Math.max(...scores);
|
||||
const lowestScore = Math.min(...scores);
|
||||
const averageScore = scores.length > 0
|
||||
let averageScore = scores.length > 0
|
||||
? scores.reduce((sum, score) => sum + score, 0) / scores.length
|
||||
: 0;
|
||||
averageScore = Math.round(averageScore);
|
||||
|
||||
const containerClasses = clsx(
|
||||
"flex flex-row mb-4",
|
||||
@@ -76,7 +77,7 @@ const TrainingScore: React.FC<TrainingScoreProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
{gridView && (
|
||||
<div className="flex flex-col items-center justify-center gap-2">
|
||||
<div className="flex flex-col items-center justify-center gap-2 -lg:hidden">
|
||||
<div className="flex w-14 h-14 bg-[#F5F5F5] items-center justify-center rounded-xl border border-[#DBDBDB]">
|
||||
<GiLightBulb color={"#FFCC00"} size={28} />
|
||||
</div>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -10,6 +10,7 @@ import {usePDFDownload} from "@/hooks/usePDFDownload";
|
||||
import {useAssignmentArchive} from "@/hooks/useAssignmentArchive";
|
||||
import {uniqBy} from "lodash";
|
||||
import {useAssignmentUnarchive} from "@/hooks/useAssignmentUnarchive";
|
||||
import {getUserName} from "@/utils/users";
|
||||
|
||||
interface Props {
|
||||
onClick?: () => void;
|
||||
@@ -35,6 +36,8 @@ export default function AssignmentCard({
|
||||
allowArchive,
|
||||
allowUnarchive,
|
||||
}: Assignment & Props) {
|
||||
const {users} = useUsers();
|
||||
|
||||
const renderPdfIcon = usePDFDownload("assignments");
|
||||
const renderArchiveIcon = useAssignmentArchive(id, reload);
|
||||
const renderUnarchiveIcon = useAssignmentUnarchive(id, reload);
|
||||
@@ -72,11 +75,14 @@ export default function AssignmentCard({
|
||||
textClassName={results.length / assignees.length < 0.5 ? "!text-mti-gray-dim font-light" : "text-white"}
|
||||
/>
|
||||
</div>
|
||||
<span className="flex justify-between gap-1">
|
||||
<span>{moment(startDate).format("DD/MM/YY, HH:mm")}</span>
|
||||
<span>-</span>
|
||||
<span>{moment(endDate).format("DD/MM/YY, HH:mm")}</span>
|
||||
</span>
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="flex justify-between gap-1">
|
||||
<span>{moment(startDate).format("DD/MM/YY, HH:mm")}</span>
|
||||
<span>-</span>
|
||||
<span>{moment(endDate).format("DD/MM/YY, HH:mm")}</span>
|
||||
</span>
|
||||
<span>Assigner: {getUserName(users.find((x) => x.id === assigner))}</span>
|
||||
</div>
|
||||
<div className="-md:mt-2 grid w-full grid-cols-4 place-items-start gap-2">
|
||||
{uniqBy(exams, (x) => x.module).map(({module}) => (
|
||||
<div
|
||||
|
||||
@@ -10,6 +10,7 @@ import {getExamById} from "@/utils/exams";
|
||||
import {sortByModule} from "@/utils/moduleUtils";
|
||||
import {calculateBandScore} from "@/utils/score";
|
||||
import {convertToUserSolutions} from "@/utils/stats";
|
||||
import {getUserName} from "@/utils/users";
|
||||
import axios from "axios";
|
||||
import clsx from "clsx";
|
||||
import {capitalize, uniqBy} from "lodash";
|
||||
@@ -241,13 +242,16 @@ export default function AssignmentView({isOpen, assignment, onClose}: Props) {
|
||||
<span>Start Date: {moment(assignment?.startDate).format("DD/MM/YY, HH:mm")}</span>
|
||||
<span>End Date: {moment(assignment?.endDate).format("DD/MM/YY, HH:mm")}</span>
|
||||
</div>
|
||||
<span>
|
||||
Assignees:{" "}
|
||||
{users
|
||||
.filter((u) => assignment?.assignees.includes(u.id))
|
||||
.map((u) => `${u.name} (${u.email})`)
|
||||
.join(", ")}
|
||||
</span>
|
||||
<div className="flex flex-col gap-2">
|
||||
<span>
|
||||
Assignees:{" "}
|
||||
{users
|
||||
.filter((u) => assignment?.assignees.includes(u.id))
|
||||
.map((u) => `${u.name} (${u.email})`)
|
||||
.join(", ")}
|
||||
</span>
|
||||
<span>Assigner: {getUserName(users.find((x) => x.id === assignment?.assigner))}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-xl font-bold">Average Scores</span>
|
||||
|
||||
@@ -2,412 +2,492 @@
|
||||
import Modal from "@/components/Modal";
|
||||
import useStats from "@/hooks/useStats";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import { CorporateUser, Group, Stat, User } from "@/interfaces/user";
|
||||
import {CorporateUser, Group, Stat, User} from "@/interfaces/user";
|
||||
import UserList from "@/pages/(admin)/Lists/UserList";
|
||||
import { dateSorter } from "@/utils";
|
||||
import {dateSorter} from "@/utils";
|
||||
import moment from "moment";
|
||||
import { useEffect, useState } from "react";
|
||||
import {useEffect, useState} from "react";
|
||||
import {
|
||||
BsArrowLeft,
|
||||
BsClipboard2Data,
|
||||
BsClipboard2DataFill,
|
||||
BsClock,
|
||||
BsGlobeCentralSouthAsia,
|
||||
BsPaperclip,
|
||||
BsPerson,
|
||||
BsPersonAdd,
|
||||
BsPersonFill,
|
||||
BsPersonFillGear,
|
||||
BsPersonGear,
|
||||
BsPencilSquare,
|
||||
BsPersonBadge,
|
||||
BsPersonCheck,
|
||||
BsPeople,
|
||||
BsArrowLeft,
|
||||
BsClipboard2Data,
|
||||
BsClipboard2DataFill,
|
||||
BsClock,
|
||||
BsGlobeCentralSouthAsia,
|
||||
BsPaperclip,
|
||||
BsPerson,
|
||||
BsPersonAdd,
|
||||
BsPersonFill,
|
||||
BsPersonFillGear,
|
||||
BsPersonGear,
|
||||
BsPencilSquare,
|
||||
BsPersonBadge,
|
||||
BsPersonCheck,
|
||||
BsPeople,
|
||||
BsArrowRepeat,
|
||||
BsPlus,
|
||||
BsEnvelopePaper,
|
||||
} from "react-icons/bs";
|
||||
import UserCard from "@/components/UserCard";
|
||||
import useGroups from "@/hooks/useGroups";
|
||||
import { calculateAverageLevel, calculateBandScore } from "@/utils/score";
|
||||
import { MODULE_ARRAY } from "@/utils/moduleUtils";
|
||||
import { Module } from "@/interfaces";
|
||||
import { groupByExam } from "@/utils/stats";
|
||||
import {calculateAverageLevel, calculateBandScore} from "@/utils/score";
|
||||
import {MODULE_ARRAY} from "@/utils/moduleUtils";
|
||||
import {Module} from "@/interfaces";
|
||||
import {groupByExam} from "@/utils/stats";
|
||||
import IconCard from "./IconCard";
|
||||
import GroupList from "@/pages/(admin)/Lists/GroupList";
|
||||
import useFilterStore from "@/stores/listFilterStore";
|
||||
import { useRouter } from "next/router";
|
||||
import {useRouter} from "next/router";
|
||||
import useCodes from "@/hooks/useCodes";
|
||||
import { getUserCorporate } from "@/utils/groups";
|
||||
import {getUserCorporate} from "@/utils/groups";
|
||||
import useAssignments from "@/hooks/useAssignments";
|
||||
import {Assignment} from "@/interfaces/results";
|
||||
import AssignmentView from "./AssignmentView";
|
||||
import AssignmentCreator from "./AssignmentCreator";
|
||||
import clsx from "clsx";
|
||||
import AssignmentCard from "./AssignmentCard";
|
||||
|
||||
interface Props {
|
||||
user: CorporateUser;
|
||||
user: CorporateUser;
|
||||
}
|
||||
|
||||
export default function CorporateDashboard({ user }: Props) {
|
||||
const [page, setPage] = useState("");
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [corporateUserToShow, setCorporateUserToShow] =
|
||||
useState<CorporateUser>();
|
||||
export default function CorporateDashboard({user}: Props) {
|
||||
const [page, setPage] = useState("");
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [corporateUserToShow, setCorporateUserToShow] = useState<CorporateUser>();
|
||||
const [selectedAssignment, setSelectedAssignment] = useState<Assignment>();
|
||||
const [isCreatingAssignment, setIsCreatingAssignment] = useState(false);
|
||||
|
||||
const { stats } = useStats();
|
||||
const { users, reload } = useUsers();
|
||||
const { codes } = useCodes(user.id);
|
||||
const { groups } = useGroups(user.id);
|
||||
const {stats} = useStats();
|
||||
const {users, reload} = useUsers();
|
||||
const {codes} = useCodes(user.id);
|
||||
const {groups} = useGroups(user.id);
|
||||
const {assignments, isLoading: isAssignmentsLoading, reload: reloadAssignments} = useAssignments({corporate: user.id});
|
||||
|
||||
const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
|
||||
const router = useRouter();
|
||||
const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
setShowModal(!!selectedUser && page === "");
|
||||
}, [selectedUser, page]);
|
||||
useEffect(() => {
|
||||
setShowModal(!!selectedUser && page === "");
|
||||
}, [selectedUser, page]);
|
||||
|
||||
useEffect(() => {
|
||||
// in this case it fetches the master corporate account
|
||||
getUserCorporate(user.id).then(setCorporateUserToShow);
|
||||
}, [user]);
|
||||
useEffect(() => {
|
||||
// in this case it fetches the master corporate account
|
||||
getUserCorporate(user.id).then(setCorporateUserToShow);
|
||||
}, [user]);
|
||||
|
||||
const studentFilter = (user: User) =>
|
||||
user.type === "student" &&
|
||||
groups.flatMap((g) => g.participants).includes(user.id);
|
||||
const teacherFilter = (user: User) =>
|
||||
user.type === "teacher" &&
|
||||
groups.flatMap((g) => g.participants).includes(user.id);
|
||||
const studentFilter = (user: User) => user.type === "student" && groups.flatMap((g) => g.participants).includes(user.id);
|
||||
const teacherFilter = (user: User) => user.type === "teacher" && groups.flatMap((g) => g.participants).includes(user.id);
|
||||
|
||||
const getStatsByStudent = (user: User) =>
|
||||
stats.filter((s) => s.user === user.id);
|
||||
const getStatsByStudent = (user: User) => stats.filter((s) => s.user === user.id);
|
||||
|
||||
const UserDisplay = (displayUser: User) => (
|
||||
<div
|
||||
onClick={() => setSelectedUser(displayUser)}
|
||||
className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300"
|
||||
>
|
||||
<img
|
||||
src={displayUser.profilePicture}
|
||||
alt={displayUser.name}
|
||||
className="rounded-full w-10 h-10"
|
||||
/>
|
||||
<div className="flex flex-col gap-1 items-start">
|
||||
<span>{displayUser.name}</span>
|
||||
<span className="text-sm opacity-75">{displayUser.email}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
const UserDisplay = (displayUser: User) => (
|
||||
<div
|
||||
onClick={() => setSelectedUser(displayUser)}
|
||||
className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300">
|
||||
<img src={displayUser.profilePicture} alt={displayUser.name} className="rounded-full w-10 h-10" />
|
||||
<div className="flex flex-col gap-1 items-start">
|
||||
<span>{displayUser.name}</span>
|
||||
<span className="text-sm opacity-75">{displayUser.email}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const StudentsList = () => {
|
||||
const filter = (x: User) =>
|
||||
x.type === "student" &&
|
||||
(!!selectedUser
|
||||
? groups
|
||||
.filter((g) => g.admin === selectedUser.id)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id) || false
|
||||
: groups.flatMap((g) => g.participants).includes(x.id));
|
||||
const StudentsList = () => {
|
||||
const filter = (x: User) =>
|
||||
x.type === "student" &&
|
||||
(!!selectedUser
|
||||
? groups
|
||||
.filter((g) => g.admin === selectedUser.id)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id) || false
|
||||
: groups.flatMap((g) => g.participants).includes(x.id));
|
||||
|
||||
return (
|
||||
<UserList
|
||||
user={user}
|
||||
filters={[filter]}
|
||||
renderHeader={(total) => (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
|
||||
>
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">Students ({total})</h2>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
return (
|
||||
<UserList
|
||||
user={user}
|
||||
filters={[filter]}
|
||||
renderHeader={(total) => (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">Students ({total})</h2>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const TeachersList = () => {
|
||||
const filter = (x: User) =>
|
||||
x.type === "teacher" &&
|
||||
(!!selectedUser
|
||||
? groups
|
||||
.filter((g) => g.admin === selectedUser.id)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id) || false
|
||||
: groups.flatMap((g) => g.participants).includes(x.id));
|
||||
const TeachersList = () => {
|
||||
const filter = (x: User) =>
|
||||
x.type === "teacher" &&
|
||||
(!!selectedUser
|
||||
? groups
|
||||
.filter((g) => g.admin === selectedUser.id)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id) || false
|
||||
: groups.flatMap((g) => g.participants).includes(x.id));
|
||||
|
||||
return (
|
||||
<UserList
|
||||
user={user}
|
||||
filters={[filter]}
|
||||
renderHeader={(total) => (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
|
||||
>
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">Teachers ({total})</h2>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
return (
|
||||
<UserList
|
||||
user={user}
|
||||
filters={[filter]}
|
||||
renderHeader={(total) => (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">Teachers ({total})</h2>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const GroupsList = () => {
|
||||
const filter = (x: Group) =>
|
||||
x.admin === user.id || x.participants.includes(user.id);
|
||||
const GroupsList = () => {
|
||||
const filter = (x: Group) => x.admin === user.id || x.participants.includes(user.id);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
|
||||
>
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">
|
||||
Groups ({groups.filter(filter).length})
|
||||
</h2>
|
||||
</div>
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">Groups ({groups.filter(filter).length})</h2>
|
||||
</div>
|
||||
|
||||
<GroupList user={user} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
<GroupList user={user} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const averageLevelCalculator = (studentStats: Stat[]) => {
|
||||
const formattedStats = studentStats
|
||||
.map((s) => ({
|
||||
focus: users.find((u) => u.id === s.user)?.focus,
|
||||
score: s.score,
|
||||
module: s.module,
|
||||
}))
|
||||
.filter((f) => !!f.focus);
|
||||
const bandScores = formattedStats.map((s) => ({
|
||||
module: s.module,
|
||||
level: calculateBandScore(
|
||||
s.score.correct,
|
||||
s.score.total,
|
||||
s.module,
|
||||
s.focus!
|
||||
),
|
||||
}));
|
||||
const AssignmentsPage = () => {
|
||||
const activeFilter = (a: Assignment) =>
|
||||
moment(a.endDate).isAfter(moment()) && moment(a.startDate).isBefore(moment()) && a.assignees.length > a.results.length;
|
||||
const pastFilter = (a: Assignment) => (moment(a.endDate).isBefore(moment()) || a.assignees.length === a.results.length) && !a.archived;
|
||||
const archivedFilter = (a: Assignment) => a.archived;
|
||||
const futureFilter = (a: Assignment) => moment(a.startDate).isAfter(moment());
|
||||
|
||||
const levels: { [key in Module]: number } = {
|
||||
reading: 0,
|
||||
listening: 0,
|
||||
writing: 0,
|
||||
speaking: 0,
|
||||
level: 0,
|
||||
};
|
||||
bandScores.forEach((b) => (levels[b.module] += b.level));
|
||||
return (
|
||||
<>
|
||||
<AssignmentView
|
||||
isOpen={!!selectedAssignment && !isCreatingAssignment}
|
||||
onClose={() => {
|
||||
setSelectedAssignment(undefined);
|
||||
setIsCreatingAssignment(false);
|
||||
reloadAssignments();
|
||||
}}
|
||||
assignment={selectedAssignment}
|
||||
/>
|
||||
<AssignmentCreator
|
||||
assignment={selectedAssignment}
|
||||
groups={groups.filter((x) => x.admin === user.id || x.participants.includes(user.id))}
|
||||
users={users.filter(
|
||||
(x) =>
|
||||
x.type === "student" &&
|
||||
(!!selectedUser
|
||||
? groups
|
||||
.filter((g) => g.admin === selectedUser.id)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id) || false
|
||||
: groups.flatMap((g) => g.participants).includes(x.id)),
|
||||
)}
|
||||
assigner={user.id}
|
||||
isCreating={isCreatingAssignment}
|
||||
cancelCreation={() => {
|
||||
setIsCreatingAssignment(false);
|
||||
setSelectedAssignment(undefined);
|
||||
reloadAssignments();
|
||||
}}
|
||||
/>
|
||||
<div className="w-full flex justify-between items-center">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<div
|
||||
onClick={reloadAssignments}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||
<span>Reload</span>
|
||||
<BsArrowRepeat className={clsx("text-xl", isAssignmentsLoading && "animate-spin")} />
|
||||
</div>
|
||||
</div>
|
||||
<section className="flex flex-col gap-4">
|
||||
<h2 className="text-2xl font-semibold">Active Assignments ({assignments.filter(activeFilter).length})</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{assignments.filter(activeFilter).map((a) => (
|
||||
<AssignmentCard {...a} onClick={() => setSelectedAssignment(a)} key={a.id} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<section className="flex flex-col gap-4">
|
||||
<h2 className="text-2xl font-semibold">Planned Assignments ({assignments.filter(futureFilter).length})</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<div
|
||||
onClick={() => setIsCreatingAssignment(true)}
|
||||
className="w-[250px] h-[200px] flex flex-col gap-2 items-center justify-center bg-white hover:bg-mti-purple-ultralight text-mti-purple-light hover:text-mti-purple-dark border border-mti-gray-platinum hover:drop-shadow p-4 cursor-pointer rounded-xl transition ease-in-out duration-300">
|
||||
<BsPlus className="text-6xl" />
|
||||
<span className="text-lg">New Assignment</span>
|
||||
</div>
|
||||
{assignments.filter(futureFilter).map((a) => (
|
||||
<AssignmentCard
|
||||
{...a}
|
||||
onClick={() => {
|
||||
setSelectedAssignment(a);
|
||||
setIsCreatingAssignment(true);
|
||||
}}
|
||||
key={a.id}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<section className="flex flex-col gap-4">
|
||||
<h2 className="text-2xl font-semibold">Past Assignments ({assignments.filter(pastFilter).length})</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{assignments.filter(pastFilter).map((a) => (
|
||||
<AssignmentCard
|
||||
{...a}
|
||||
onClick={() => setSelectedAssignment(a)}
|
||||
key={a.id}
|
||||
allowDownload
|
||||
reload={reloadAssignments}
|
||||
allowArchive
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<section className="flex flex-col gap-4">
|
||||
<h2 className="text-2xl font-semibold">Archived Assignments ({assignments.filter(archivedFilter).length})</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{assignments.filter(archivedFilter).map((a) => (
|
||||
<AssignmentCard
|
||||
{...a}
|
||||
onClick={() => setSelectedAssignment(a)}
|
||||
key={a.id}
|
||||
allowDownload
|
||||
reload={reloadAssignments}
|
||||
allowUnarchive
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
return calculateAverageLevel(levels);
|
||||
};
|
||||
const averageLevelCalculator = (studentStats: Stat[]) => {
|
||||
const formattedStats = studentStats
|
||||
.map((s) => ({
|
||||
focus: users.find((u) => u.id === s.user)?.focus,
|
||||
score: s.score,
|
||||
module: s.module,
|
||||
}))
|
||||
.filter((f) => !!f.focus);
|
||||
const bandScores = formattedStats.map((s) => ({
|
||||
module: s.module,
|
||||
level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!),
|
||||
}));
|
||||
|
||||
const DefaultDashboard = () => (
|
||||
<>
|
||||
{corporateUserToShow && (
|
||||
<div className="absolute top-4 right-4 bg-neutral-200 px-2 rounded-lg py-1">
|
||||
Linked to:{" "}
|
||||
<b>
|
||||
{corporateUserToShow?.corporateInformation?.companyInformation
|
||||
.name || corporateUserToShow.name}
|
||||
</b>
|
||||
</div>
|
||||
)}
|
||||
<section className="flex flex-wrap gap-2 items-center -lg:justify-center lg:justify-between text-center">
|
||||
<IconCard
|
||||
onClick={() => setPage("students")}
|
||||
Icon={BsPersonFill}
|
||||
label="Students"
|
||||
value={users.filter(studentFilter).length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => setPage("teachers")}
|
||||
Icon={BsPencilSquare}
|
||||
label="Teachers"
|
||||
value={users.filter(teacherFilter).length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsClipboard2Data}
|
||||
label="Exams Performed"
|
||||
value={
|
||||
stats.filter((s) =>
|
||||
groups.flatMap((g) => g.participants).includes(s.user)
|
||||
).length
|
||||
}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsPaperclip}
|
||||
label="Average Level"
|
||||
value={averageLevelCalculator(
|
||||
stats.filter((s) =>
|
||||
groups.flatMap((g) => g.participants).includes(s.user)
|
||||
)
|
||||
).toFixed(1)}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => setPage("groups")}
|
||||
Icon={BsPeople}
|
||||
label="Groups"
|
||||
value={groups.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsPersonCheck}
|
||||
label="User Balance"
|
||||
value={`${codes.length}/${
|
||||
user.corporateInformation?.companyInformation?.userAmount || 0
|
||||
}`}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsClock}
|
||||
label="Expiration Date"
|
||||
value={
|
||||
user.subscriptionExpirationDate
|
||||
? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy")
|
||||
: "Unlimited"
|
||||
}
|
||||
color="rose"
|
||||
/>
|
||||
</section>
|
||||
const levels: {[key in Module]: number} = {
|
||||
reading: 0,
|
||||
listening: 0,
|
||||
writing: 0,
|
||||
speaking: 0,
|
||||
level: 0,
|
||||
};
|
||||
bandScores.forEach((b) => (levels[b.module] += b.level));
|
||||
|
||||
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest teachers</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(teacherFilter)
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest level students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
calculateAverageLevel(b.levels) -
|
||||
calculateAverageLevel(a.levels)
|
||||
)
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest exam count students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Object.keys(groupByExam(getStatsByStudent(b))).length -
|
||||
Object.keys(groupByExam(getStatsByStudent(a))).length
|
||||
)
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
return calculateAverageLevel(levels);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal isOpen={showModal} onClose={() => setSelectedUser(undefined)}>
|
||||
<>
|
||||
{selectedUser && (
|
||||
<div className="w-full flex flex-col gap-8">
|
||||
<UserCard
|
||||
loggedInUser={user}
|
||||
onClose={(shouldReload) => {
|
||||
setSelectedUser(undefined);
|
||||
if (shouldReload) reload();
|
||||
}}
|
||||
onViewStudents={
|
||||
selectedUser.type === "corporate" ||
|
||||
selectedUser.type === "teacher"
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-students",
|
||||
filter: (x: User) => x.type === "student",
|
||||
});
|
||||
appendUserFilters({
|
||||
id: "belongs-to-admin",
|
||||
filter: (x: User) =>
|
||||
groups
|
||||
.filter(
|
||||
(g) =>
|
||||
g.admin === selectedUser.id ||
|
||||
g.participants.includes(selectedUser.id)
|
||||
)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id),
|
||||
});
|
||||
const DefaultDashboard = () => (
|
||||
<>
|
||||
{corporateUserToShow && (
|
||||
<div className="absolute top-4 right-4 bg-neutral-200 px-2 rounded-lg py-1">
|
||||
Linked to: <b>{corporateUserToShow?.corporateInformation?.companyInformation.name || corporateUserToShow.name}</b>
|
||||
</div>
|
||||
)}
|
||||
<section className="grid grid-cols-5 -md:grid-cols-2 gap-4 text-center">
|
||||
<IconCard
|
||||
onClick={() => setPage("students")}
|
||||
Icon={BsPersonFill}
|
||||
label="Students"
|
||||
value={users.filter(studentFilter).length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => setPage("teachers")}
|
||||
Icon={BsPencilSquare}
|
||||
label="Teachers"
|
||||
value={users.filter(teacherFilter).length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsClipboard2Data}
|
||||
label="Exams Performed"
|
||||
value={stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user)).length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsPaperclip}
|
||||
label="Average Level"
|
||||
value={averageLevelCalculator(stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user))).toFixed(1)}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard onClick={() => setPage("groups")} Icon={BsPeople} label="Groups" value={groups.length} color="purple" />
|
||||
<IconCard
|
||||
Icon={BsPersonCheck}
|
||||
label="User Balance"
|
||||
value={`${codes.length}/${user.corporateInformation?.companyInformation?.userAmount || 0}`}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsClock}
|
||||
label="Expiration Date"
|
||||
value={user.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy") : "Unlimited"}
|
||||
color="rose"
|
||||
/>
|
||||
<button
|
||||
disabled={isAssignmentsLoading}
|
||||
onClick={() => setPage("assignments")}
|
||||
className="bg-white col-span-2 rounded-xl shadow p-4 flex flex-col gap-4 items-center w-96 h-52 justify-center cursor-pointer hover:shadow-xl transition ease-in-out duration-300">
|
||||
<BsEnvelopePaper className="text-6xl text-mti-purple-light" />
|
||||
<span className="flex flex-col gap-1 items-center text-xl">
|
||||
<span className="text-lg">Assignments</span>
|
||||
<span className="font-semibold text-mti-purple-light">
|
||||
{isAssignmentsLoading ? "Loading..." : assignments.filter((a) => !a.archived).length}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</section>
|
||||
|
||||
router.push("/list/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onViewTeachers={
|
||||
selectedUser.type === "corporate" ||
|
||||
selectedUser.type === "student"
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-teachers",
|
||||
filter: (x: User) => x.type === "teacher",
|
||||
});
|
||||
appendUserFilters({
|
||||
id: "belongs-to-admin",
|
||||
filter: (x: User) =>
|
||||
groups
|
||||
.filter(
|
||||
(g) =>
|
||||
g.admin === selectedUser.id ||
|
||||
g.participants.includes(selectedUser.id)
|
||||
)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id),
|
||||
});
|
||||
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest teachers</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(teacherFilter)
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest level students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest exam count students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Object.keys(groupByExam(getStatsByStudent(b))).length - Object.keys(groupByExam(getStatsByStudent(a))).length,
|
||||
)
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
|
||||
router.push("/list/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
user={selectedUser}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</Modal>
|
||||
{page === "students" && <StudentsList />}
|
||||
{page === "teachers" && <TeachersList />}
|
||||
{page === "groups" && <GroupsList />}
|
||||
{page === "" && <DefaultDashboard />}
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Modal isOpen={showModal} onClose={() => setSelectedUser(undefined)}>
|
||||
<>
|
||||
{selectedUser && (
|
||||
<div className="w-full flex flex-col gap-8">
|
||||
<UserCard
|
||||
loggedInUser={user}
|
||||
onClose={(shouldReload) => {
|
||||
setSelectedUser(undefined);
|
||||
if (shouldReload) reload();
|
||||
}}
|
||||
onViewStudents={
|
||||
selectedUser.type === "corporate" || selectedUser.type === "teacher"
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-students",
|
||||
filter: (x: User) => x.type === "student",
|
||||
});
|
||||
appendUserFilters({
|
||||
id: "belongs-to-admin",
|
||||
filter: (x: User) =>
|
||||
groups
|
||||
.filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id))
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id),
|
||||
});
|
||||
|
||||
router.push("/list/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onViewTeachers={
|
||||
selectedUser.type === "corporate" || selectedUser.type === "student"
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-teachers",
|
||||
filter: (x: User) => x.type === "teacher",
|
||||
});
|
||||
appendUserFilters({
|
||||
id: "belongs-to-admin",
|
||||
filter: (x: User) =>
|
||||
groups
|
||||
.filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id))
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id),
|
||||
});
|
||||
|
||||
router.push("/list/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
user={selectedUser}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</Modal>
|
||||
{page === "students" && <StudentsList />}
|
||||
{page === "teachers" && <TeachersList />}
|
||||
{page === "groups" && <GroupsList />}
|
||||
{page === "assignments" && <AssignmentsPage />}
|
||||
{page === "" && <DefaultDashboard />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,423 +2,496 @@
|
||||
import Modal from "@/components/Modal";
|
||||
import useStats from "@/hooks/useStats";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import { Group, MasterCorporateUser, Stat, User } from "@/interfaces/user";
|
||||
import {Group, MasterCorporateUser, Stat, User} from "@/interfaces/user";
|
||||
import UserList from "@/pages/(admin)/Lists/UserList";
|
||||
import { dateSorter } from "@/utils";
|
||||
import {dateSorter} from "@/utils";
|
||||
import moment from "moment";
|
||||
import { useEffect, useState } from "react";
|
||||
import {useEffect, useState} from "react";
|
||||
import {
|
||||
BsArrowLeft,
|
||||
BsClipboard2Data,
|
||||
BsClock,
|
||||
BsPaperclip,
|
||||
BsPersonFill,
|
||||
BsPencilSquare,
|
||||
BsPersonCheck,
|
||||
BsPeople,
|
||||
BsBank,
|
||||
BsArrowLeft,
|
||||
BsClipboard2Data,
|
||||
BsClock,
|
||||
BsPaperclip,
|
||||
BsPersonFill,
|
||||
BsPencilSquare,
|
||||
BsPersonCheck,
|
||||
BsPeople,
|
||||
BsBank,
|
||||
BsEnvelopePaper,
|
||||
BsArrowRepeat,
|
||||
BsPlus,
|
||||
} from "react-icons/bs";
|
||||
import UserCard from "@/components/UserCard";
|
||||
import useGroups from "@/hooks/useGroups";
|
||||
|
||||
import { calculateAverageLevel, calculateBandScore } from "@/utils/score";
|
||||
import { MODULE_ARRAY } from "@/utils/moduleUtils";
|
||||
import { Module } from "@/interfaces";
|
||||
import { groupByExam } from "@/utils/stats";
|
||||
import {calculateAverageLevel, calculateBandScore} from "@/utils/score";
|
||||
import {MODULE_ARRAY} from "@/utils/moduleUtils";
|
||||
import {Module} from "@/interfaces";
|
||||
import {groupByExam} from "@/utils/stats";
|
||||
import IconCard from "./IconCard";
|
||||
import GroupList from "@/pages/(admin)/Lists/GroupList";
|
||||
import useFilterStore from "@/stores/listFilterStore";
|
||||
import { useRouter } from "next/router";
|
||||
import {useRouter} from "next/router";
|
||||
import useCodes from "@/hooks/useCodes";
|
||||
import useAssignments from "@/hooks/useAssignments";
|
||||
import {Assignment} from "@/interfaces/results";
|
||||
import AssignmentView from "./AssignmentView";
|
||||
import AssignmentCreator from "./AssignmentCreator";
|
||||
import clsx from "clsx";
|
||||
import AssignmentCard from "./AssignmentCard";
|
||||
|
||||
interface Props {
|
||||
user: MasterCorporateUser;
|
||||
user: MasterCorporateUser;
|
||||
}
|
||||
|
||||
export default function MasterCorporateDashboard({ user }: Props) {
|
||||
const [page, setPage] = useState("");
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
export default function MasterCorporateDashboard({user}: Props) {
|
||||
const [page, setPage] = useState("");
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [selectedAssignment, setSelectedAssignment] = useState<Assignment>();
|
||||
const [isCreatingAssignment, setIsCreatingAssignment] = useState(false);
|
||||
|
||||
const { stats } = useStats();
|
||||
const { users, reload } = useUsers();
|
||||
const { codes } = useCodes(user.id);
|
||||
const { groups } = useGroups(user.id, user.type);
|
||||
const {stats} = useStats();
|
||||
const {users, reload} = useUsers();
|
||||
const {codes} = useCodes(user.id);
|
||||
const {groups} = useGroups(user.id, user.type);
|
||||
|
||||
const masterCorporateUserGroups = [
|
||||
...new Set(
|
||||
groups.filter((u) => u.admin === user.id).flatMap((g) => g.participants)
|
||||
),
|
||||
];
|
||||
const corporateUserGroups = [
|
||||
...new Set(groups.flatMap((g) => g.participants)),
|
||||
];
|
||||
const masterCorporateUserGroups = [...new Set(groups.filter((u) => u.admin === user.id).flatMap((g) => g.participants))];
|
||||
const corporateUserGroups = [...new Set(groups.flatMap((g) => g.participants))];
|
||||
|
||||
const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
|
||||
const router = useRouter();
|
||||
const {assignments, isLoading: isAssignmentsLoading, reload: reloadAssignments} = useAssignments({corporate: user.id});
|
||||
|
||||
useEffect(() => {
|
||||
setShowModal(!!selectedUser && page === "");
|
||||
}, [selectedUser, page]);
|
||||
const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
|
||||
const router = useRouter();
|
||||
|
||||
const studentFilter = (user: User) =>
|
||||
user.type === "student" && corporateUserGroups.includes(user.id);
|
||||
const teacherFilter = (user: User) =>
|
||||
user.type === "teacher" && corporateUserGroups.includes(user.id);
|
||||
useEffect(() => {
|
||||
setShowModal(!!selectedUser && page === "");
|
||||
}, [selectedUser, page]);
|
||||
|
||||
const getStatsByStudent = (user: User) =>
|
||||
stats.filter((s) => s.user === user.id);
|
||||
const studentFilter = (user: User) => user.type === "student" && corporateUserGroups.includes(user.id);
|
||||
const teacherFilter = (user: User) => user.type === "teacher" && corporateUserGroups.includes(user.id);
|
||||
|
||||
const UserDisplay = (displayUser: User) => (
|
||||
<div
|
||||
onClick={() => setSelectedUser(displayUser)}
|
||||
className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300"
|
||||
>
|
||||
<img
|
||||
src={displayUser.profilePicture}
|
||||
alt={displayUser.name}
|
||||
className="rounded-full w-10 h-10"
|
||||
/>
|
||||
<div className="flex flex-col gap-1 items-start">
|
||||
<span>{displayUser.name}</span>
|
||||
<span className="text-sm opacity-75">{displayUser.email}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
const getStatsByStudent = (user: User) => stats.filter((s) => s.user === user.id);
|
||||
|
||||
const StudentsList = () => {
|
||||
const filter = (x: User) =>
|
||||
x.type === "student" &&
|
||||
(!!selectedUser
|
||||
? corporateUserGroups.includes(x.id) || false
|
||||
: corporateUserGroups.includes(x.id));
|
||||
const UserDisplay = (displayUser: User) => (
|
||||
<div
|
||||
onClick={() => setSelectedUser(displayUser)}
|
||||
className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300">
|
||||
<img src={displayUser.profilePicture} alt={displayUser.name} className="rounded-full w-10 h-10" />
|
||||
<div className="flex flex-col gap-1 items-start">
|
||||
<span>{displayUser.name}</span>
|
||||
<span className="text-sm opacity-75">{displayUser.email}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<UserList
|
||||
user={user}
|
||||
filters={[filter]}
|
||||
renderHeader={(total) => (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
|
||||
>
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">Students ({total})</h2>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
const StudentsList = () => {
|
||||
const filter = (x: User) =>
|
||||
x.type === "student" && (!!selectedUser ? corporateUserGroups.includes(x.id) || false : corporateUserGroups.includes(x.id));
|
||||
|
||||
const TeachersList = () => {
|
||||
const filter = (x: User) =>
|
||||
x.type === "teacher" &&
|
||||
(!!selectedUser
|
||||
? corporateUserGroups.includes(x.id) || false
|
||||
: corporateUserGroups.includes(x.id));
|
||||
return (
|
||||
<UserList
|
||||
user={user}
|
||||
filters={[filter]}
|
||||
renderHeader={(total) => (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">Students ({total})</h2>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<UserList
|
||||
user={user}
|
||||
filters={[filter]}
|
||||
renderHeader={(total) => (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
|
||||
>
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">Teachers ({total})</h2>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
const TeachersList = () => {
|
||||
const filter = (x: User) =>
|
||||
x.type === "teacher" && (!!selectedUser ? corporateUserGroups.includes(x.id) || false : corporateUserGroups.includes(x.id));
|
||||
|
||||
const corporateUserFilter = (x: User) =>
|
||||
x.type === "corporate" &&
|
||||
(!!selectedUser
|
||||
? masterCorporateUserGroups.includes(x.id) || false
|
||||
: masterCorporateUserGroups.includes(x.id));
|
||||
return (
|
||||
<UserList
|
||||
user={user}
|
||||
filters={[filter]}
|
||||
renderHeader={(total) => (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">Teachers ({total})</h2>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const CorporateList = () => {
|
||||
return (
|
||||
<UserList
|
||||
user={user}
|
||||
filters={[corporateUserFilter]}
|
||||
renderHeader={(total) => (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
|
||||
>
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">Corporates ({total})</h2>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
const corporateUserFilter = (x: User) =>
|
||||
x.type === "corporate" && (!!selectedUser ? masterCorporateUserGroups.includes(x.id) || false : masterCorporateUserGroups.includes(x.id));
|
||||
|
||||
const GroupsList = () => {
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
|
||||
>
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">
|
||||
Groups ({groups.length})
|
||||
</h2>
|
||||
</div>
|
||||
const CorporateList = () => {
|
||||
return (
|
||||
<UserList
|
||||
user={user}
|
||||
filters={[corporateUserFilter]}
|
||||
renderHeader={(total) => (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">Corporates ({total})</h2>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
<GroupList user={user} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
const GroupsList = () => {
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">Groups ({groups.length})</h2>
|
||||
</div>
|
||||
|
||||
const averageLevelCalculator = (studentStats: Stat[]) => {
|
||||
const formattedStats = studentStats
|
||||
.map((s) => ({
|
||||
focus: users.find((u) => u.id === s.user)?.focus,
|
||||
score: s.score,
|
||||
module: s.module,
|
||||
}))
|
||||
.filter((f) => !!f.focus);
|
||||
const bandScores = formattedStats.map((s) => ({
|
||||
module: s.module,
|
||||
level: calculateBandScore(
|
||||
s.score.correct,
|
||||
s.score.total,
|
||||
s.module,
|
||||
s.focus!
|
||||
),
|
||||
}));
|
||||
<GroupList user={user} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const levels: { [key in Module]: number } = {
|
||||
reading: 0,
|
||||
listening: 0,
|
||||
writing: 0,
|
||||
speaking: 0,
|
||||
level: 0,
|
||||
};
|
||||
bandScores.forEach((b) => (levels[b.module] += b.level));
|
||||
const AssignmentsPage = () => {
|
||||
const activeFilter = (a: Assignment) =>
|
||||
moment(a.endDate).isAfter(moment()) && moment(a.startDate).isBefore(moment()) && a.assignees.length > a.results.length;
|
||||
const pastFilter = (a: Assignment) => (moment(a.endDate).isBefore(moment()) || a.assignees.length === a.results.length) && !a.archived;
|
||||
const archivedFilter = (a: Assignment) => a.archived;
|
||||
const futureFilter = (a: Assignment) => moment(a.startDate).isAfter(moment());
|
||||
|
||||
return calculateAverageLevel(levels);
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<AssignmentView
|
||||
isOpen={!!selectedAssignment && !isCreatingAssignment}
|
||||
onClose={() => {
|
||||
setSelectedAssignment(undefined);
|
||||
setIsCreatingAssignment(false);
|
||||
reloadAssignments();
|
||||
}}
|
||||
assignment={selectedAssignment}
|
||||
/>
|
||||
<AssignmentCreator
|
||||
assignment={selectedAssignment}
|
||||
groups={groups.filter((x) => x.admin === user.id || x.participants.includes(user.id))}
|
||||
users={users.filter(
|
||||
(x) =>
|
||||
x.type === "student" &&
|
||||
(!!selectedUser
|
||||
? groups
|
||||
.filter((g) => g.admin === selectedUser.id)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id) || false
|
||||
: groups.flatMap((g) => g.participants).includes(x.id)),
|
||||
)}
|
||||
assigner={user.id}
|
||||
isCreating={isCreatingAssignment}
|
||||
cancelCreation={() => {
|
||||
setIsCreatingAssignment(false);
|
||||
setSelectedAssignment(undefined);
|
||||
reloadAssignments();
|
||||
}}
|
||||
/>
|
||||
<div className="w-full flex justify-between items-center">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<div
|
||||
onClick={reloadAssignments}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||
<span>Reload</span>
|
||||
<BsArrowRepeat className={clsx("text-xl", isAssignmentsLoading && "animate-spin")} />
|
||||
</div>
|
||||
</div>
|
||||
<section className="flex flex-col gap-4">
|
||||
<h2 className="text-2xl font-semibold">Active Assignments ({assignments.filter(activeFilter).length})</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{assignments.filter(activeFilter).map((a) => (
|
||||
<AssignmentCard {...a} onClick={() => setSelectedAssignment(a)} key={a.id} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<section className="flex flex-col gap-4">
|
||||
<h2 className="text-2xl font-semibold">Planned Assignments ({assignments.filter(futureFilter).length})</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<div
|
||||
onClick={() => setIsCreatingAssignment(true)}
|
||||
className="w-[250px] h-[200px] flex flex-col gap-2 items-center justify-center bg-white hover:bg-mti-purple-ultralight text-mti-purple-light hover:text-mti-purple-dark border border-mti-gray-platinum hover:drop-shadow p-4 cursor-pointer rounded-xl transition ease-in-out duration-300">
|
||||
<BsPlus className="text-6xl" />
|
||||
<span className="text-lg">New Assignment</span>
|
||||
</div>
|
||||
{assignments.filter(futureFilter).map((a) => (
|
||||
<AssignmentCard
|
||||
{...a}
|
||||
onClick={() => {
|
||||
setSelectedAssignment(a);
|
||||
setIsCreatingAssignment(true);
|
||||
}}
|
||||
key={a.id}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<section className="flex flex-col gap-4">
|
||||
<h2 className="text-2xl font-semibold">Past Assignments ({assignments.filter(pastFilter).length})</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{assignments.filter(pastFilter).map((a) => (
|
||||
<AssignmentCard
|
||||
{...a}
|
||||
onClick={() => setSelectedAssignment(a)}
|
||||
key={a.id}
|
||||
allowDownload
|
||||
reload={reloadAssignments}
|
||||
allowArchive
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<section className="flex flex-col gap-4">
|
||||
<h2 className="text-2xl font-semibold">Archived Assignments ({assignments.filter(archivedFilter).length})</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{assignments.filter(archivedFilter).map((a) => (
|
||||
<AssignmentCard
|
||||
{...a}
|
||||
onClick={() => setSelectedAssignment(a)}
|
||||
key={a.id}
|
||||
allowDownload
|
||||
reload={reloadAssignments}
|
||||
allowUnarchive
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const DefaultDashboard = () => (
|
||||
<>
|
||||
<section className="flex flex-wrap gap-2 items-center -lg:justify-center lg:justify-between text-center">
|
||||
<IconCard
|
||||
onClick={() => setPage("students")}
|
||||
Icon={BsPersonFill}
|
||||
label="Students"
|
||||
value={users.filter(studentFilter).length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => setPage("teachers")}
|
||||
Icon={BsPencilSquare}
|
||||
label="Teachers"
|
||||
value={users.filter(teacherFilter).length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsClipboard2Data}
|
||||
label="Exams Performed"
|
||||
value={
|
||||
stats.filter((s) =>
|
||||
groups.flatMap((g) => g.participants).includes(s.user)
|
||||
).length
|
||||
}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsPaperclip}
|
||||
label="Average Level"
|
||||
value={averageLevelCalculator(
|
||||
stats.filter((s) =>
|
||||
groups.flatMap((g) => g.participants).includes(s.user)
|
||||
)
|
||||
).toFixed(1)}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => setPage("groups")}
|
||||
Icon={BsPeople}
|
||||
label="Groups"
|
||||
value={groups.length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsPersonCheck}
|
||||
label="User Balance"
|
||||
value={`${codes.length}/${
|
||||
user.corporateInformation?.companyInformation?.userAmount || 0
|
||||
}`}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsClock}
|
||||
label="Expiration Date"
|
||||
value={
|
||||
user.subscriptionExpirationDate
|
||||
? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy")
|
||||
: "Unlimited"
|
||||
}
|
||||
color="rose"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsBank}
|
||||
label="Corporate"
|
||||
value={masterCorporateUserGroups.length}
|
||||
color="purple"
|
||||
onClick={() => setPage("corporate")}
|
||||
/>
|
||||
</section>
|
||||
const averageLevelCalculator = (studentStats: Stat[]) => {
|
||||
const formattedStats = studentStats
|
||||
.map((s) => ({
|
||||
focus: users.find((u) => u.id === s.user)?.focus,
|
||||
score: s.score,
|
||||
module: s.module,
|
||||
}))
|
||||
.filter((f) => !!f.focus);
|
||||
const bandScores = formattedStats.map((s) => ({
|
||||
module: s.module,
|
||||
level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!),
|
||||
}));
|
||||
|
||||
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest teachers</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(teacherFilter)
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest level students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
calculateAverageLevel(b.levels) -
|
||||
calculateAverageLevel(a.levels)
|
||||
)
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest exam count students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Object.keys(groupByExam(getStatsByStudent(b))).length -
|
||||
Object.keys(groupByExam(getStatsByStudent(a))).length
|
||||
)
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
const levels: {[key in Module]: number} = {
|
||||
reading: 0,
|
||||
listening: 0,
|
||||
writing: 0,
|
||||
speaking: 0,
|
||||
level: 0,
|
||||
};
|
||||
bandScores.forEach((b) => (levels[b.module] += b.level));
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal isOpen={showModal} onClose={() => setSelectedUser(undefined)}>
|
||||
<>
|
||||
{selectedUser && (
|
||||
<div className="w-full flex flex-col gap-8">
|
||||
<UserCard
|
||||
loggedInUser={user}
|
||||
onClose={(shouldReload) => {
|
||||
setSelectedUser(undefined);
|
||||
if (shouldReload) reload();
|
||||
}}
|
||||
onViewStudents={
|
||||
selectedUser.type === "corporate" ||
|
||||
selectedUser.type === "teacher"
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-students",
|
||||
filter: (x: User) => x.type === "student",
|
||||
});
|
||||
appendUserFilters({
|
||||
id: "belongs-to-admin",
|
||||
filter: (x: User) =>
|
||||
groups
|
||||
.filter(
|
||||
(g) =>
|
||||
g.admin === selectedUser.id ||
|
||||
g.participants.includes(selectedUser.id)
|
||||
)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id),
|
||||
});
|
||||
return calculateAverageLevel(levels);
|
||||
};
|
||||
|
||||
router.push("/list/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onViewTeachers={
|
||||
selectedUser.type === "corporate" ||
|
||||
selectedUser.type === "student"
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-teachers",
|
||||
filter: (x: User) => x.type === "teacher",
|
||||
});
|
||||
appendUserFilters({
|
||||
id: "belongs-to-admin",
|
||||
filter: (x: User) =>
|
||||
groups
|
||||
.filter(
|
||||
(g) =>
|
||||
g.admin === selectedUser.id ||
|
||||
g.participants.includes(selectedUser.id)
|
||||
)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id),
|
||||
});
|
||||
const DefaultDashboard = () => (
|
||||
<>
|
||||
<section className="flex flex-wrap gap-2 items-center -lg:justify-center lg:justify-between text-center">
|
||||
<IconCard
|
||||
onClick={() => setPage("students")}
|
||||
Icon={BsPersonFill}
|
||||
label="Students"
|
||||
value={users.filter(studentFilter).length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
onClick={() => setPage("teachers")}
|
||||
Icon={BsPencilSquare}
|
||||
label="Teachers"
|
||||
value={users.filter(teacherFilter).length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsClipboard2Data}
|
||||
label="Exams Performed"
|
||||
value={stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user)).length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsPaperclip}
|
||||
label="Average Level"
|
||||
value={averageLevelCalculator(stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user))).toFixed(1)}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard onClick={() => setPage("groups")} Icon={BsPeople} label="Groups" value={groups.length} color="purple" />
|
||||
<IconCard
|
||||
Icon={BsPersonCheck}
|
||||
label="User Balance"
|
||||
value={`${codes.length}/${user.corporateInformation?.companyInformation?.userAmount || 0}`}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsClock}
|
||||
label="Expiration Date"
|
||||
value={user.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy") : "Unlimited"}
|
||||
color="rose"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsBank}
|
||||
label="Corporate"
|
||||
value={masterCorporateUserGroups.length}
|
||||
color="purple"
|
||||
onClick={() => setPage("corporate")}
|
||||
/>
|
||||
<button
|
||||
disabled={isAssignmentsLoading}
|
||||
onClick={() => setPage("assignments")}
|
||||
className="bg-white col-span-2 rounded-xl shadow p-4 flex flex-col gap-4 items-center w-96 h-52 justify-center cursor-pointer hover:shadow-xl transition ease-in-out duration-300">
|
||||
<BsEnvelopePaper className="text-6xl text-mti-purple-light" />
|
||||
<span className="flex flex-col gap-1 items-center text-xl">
|
||||
<span className="text-lg">Assignments</span>
|
||||
<span className="font-semibold text-mti-purple-light">
|
||||
{isAssignmentsLoading ? "Loading..." : assignments.filter((a) => !a.archived).length}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</section>
|
||||
|
||||
router.push("/list/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
user={selectedUser}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</Modal>
|
||||
{page === "students" && <StudentsList />}
|
||||
{page === "teachers" && <TeachersList />}
|
||||
{page === "groups" && <GroupsList />}
|
||||
{page === "corporate" && <CorporateList />}
|
||||
{page === "" && <DefaultDashboard />}
|
||||
</>
|
||||
);
|
||||
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest teachers</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(teacherFilter)
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest level students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest exam count students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Object.keys(groupByExam(getStatsByStudent(b))).length - Object.keys(groupByExam(getStatsByStudent(a))).length,
|
||||
)
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal isOpen={showModal} onClose={() => setSelectedUser(undefined)}>
|
||||
<>
|
||||
{selectedUser && (
|
||||
<div className="w-full flex flex-col gap-8">
|
||||
<UserCard
|
||||
loggedInUser={user}
|
||||
onClose={(shouldReload) => {
|
||||
setSelectedUser(undefined);
|
||||
if (shouldReload) reload();
|
||||
}}
|
||||
onViewStudents={
|
||||
selectedUser.type === "corporate" || selectedUser.type === "teacher"
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-students",
|
||||
filter: (x: User) => x.type === "student",
|
||||
});
|
||||
appendUserFilters({
|
||||
id: "belongs-to-admin",
|
||||
filter: (x: User) =>
|
||||
groups
|
||||
.filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id))
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id),
|
||||
});
|
||||
|
||||
router.push("/list/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onViewTeachers={
|
||||
selectedUser.type === "corporate" || selectedUser.type === "student"
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-teachers",
|
||||
filter: (x: User) => x.type === "teacher",
|
||||
});
|
||||
appendUserFilters({
|
||||
id: "belongs-to-admin",
|
||||
filter: (x: User) =>
|
||||
groups
|
||||
.filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id))
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id),
|
||||
});
|
||||
|
||||
router.push("/list/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
user={selectedUser}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</Modal>
|
||||
{page === "students" && <StudentsList />}
|
||||
{page === "teachers" && <TeachersList />}
|
||||
{page === "groups" && <GroupsList />}
|
||||
{page === "corporate" && <CorporateList />}
|
||||
{page === "assignments" && <AssignmentsPage />}
|
||||
{page === "" && <DefaultDashboard />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,477 +2,397 @@
|
||||
import Modal from "@/components/Modal";
|
||||
import useStats from "@/hooks/useStats";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import { CorporateUser, Group, Stat, User } from "@/interfaces/user";
|
||||
import {CorporateUser, Group, Stat, User} from "@/interfaces/user";
|
||||
import UserList from "@/pages/(admin)/Lists/UserList";
|
||||
import { dateSorter } from "@/utils";
|
||||
import {dateSorter} from "@/utils";
|
||||
import moment from "moment";
|
||||
import { useEffect, useState } from "react";
|
||||
import {useEffect, useState} from "react";
|
||||
import {
|
||||
BsArrowLeft,
|
||||
BsArrowRepeat,
|
||||
BsClipboard2Data,
|
||||
BsClipboard2DataFill,
|
||||
BsClipboard2Heart,
|
||||
BsClipboard2X,
|
||||
BsClipboardPulse,
|
||||
BsClock,
|
||||
BsEnvelopePaper,
|
||||
BsGlobeCentralSouthAsia,
|
||||
BsPaperclip,
|
||||
BsPeople,
|
||||
BsPerson,
|
||||
BsPersonAdd,
|
||||
BsPersonFill,
|
||||
BsPersonFillGear,
|
||||
BsPersonGear,
|
||||
BsPlus,
|
||||
BsRepeat,
|
||||
BsRepeat1,
|
||||
BsArrowLeft,
|
||||
BsArrowRepeat,
|
||||
BsClipboard2Data,
|
||||
BsClipboard2DataFill,
|
||||
BsClipboard2Heart,
|
||||
BsClipboard2X,
|
||||
BsClipboardPulse,
|
||||
BsClock,
|
||||
BsEnvelopePaper,
|
||||
BsGlobeCentralSouthAsia,
|
||||
BsPaperclip,
|
||||
BsPeople,
|
||||
BsPerson,
|
||||
BsPersonAdd,
|
||||
BsPersonFill,
|
||||
BsPersonFillGear,
|
||||
BsPersonGear,
|
||||
BsPlus,
|
||||
BsRepeat,
|
||||
BsRepeat1,
|
||||
} from "react-icons/bs";
|
||||
import UserCard from "@/components/UserCard";
|
||||
import useGroups from "@/hooks/useGroups";
|
||||
import { calculateAverageLevel, calculateBandScore } from "@/utils/score";
|
||||
import { MODULE_ARRAY } from "@/utils/moduleUtils";
|
||||
import { Module } from "@/interfaces";
|
||||
import { groupByExam } from "@/utils/stats";
|
||||
import {calculateAverageLevel, calculateBandScore} from "@/utils/score";
|
||||
import {MODULE_ARRAY} from "@/utils/moduleUtils";
|
||||
import {Module} from "@/interfaces";
|
||||
import {groupByExam} from "@/utils/stats";
|
||||
import IconCard from "./IconCard";
|
||||
import GroupList from "@/pages/(admin)/Lists/GroupList";
|
||||
import useAssignments from "@/hooks/useAssignments";
|
||||
import { Assignment } from "@/interfaces/results";
|
||||
import {Assignment} from "@/interfaces/results";
|
||||
import AssignmentCard from "./AssignmentCard";
|
||||
import Button from "@/components/Low/Button";
|
||||
import clsx from "clsx";
|
||||
import ProgressBar from "@/components/Low/ProgressBar";
|
||||
import AssignmentCreator from "./AssignmentCreator";
|
||||
import AssignmentView from "./AssignmentView";
|
||||
import { getUserCorporate } from "@/utils/groups";
|
||||
import {getUserCorporate} from "@/utils/groups";
|
||||
import {checkAccess} from "@/utils/permissions";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
user: User;
|
||||
}
|
||||
|
||||
export default function TeacherDashboard({ user }: Props) {
|
||||
const [page, setPage] = useState("");
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [selectedAssignment, setSelectedAssignment] = useState<Assignment>();
|
||||
const [isCreatingAssignment, setIsCreatingAssignment] = useState(false);
|
||||
const [corporateUserToShow, setCorporateUserToShow] =
|
||||
useState<CorporateUser>();
|
||||
export default function TeacherDashboard({user}: Props) {
|
||||
const [page, setPage] = useState("");
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [selectedAssignment, setSelectedAssignment] = useState<Assignment>();
|
||||
const [isCreatingAssignment, setIsCreatingAssignment] = useState(false);
|
||||
const [corporateUserToShow, setCorporateUserToShow] = useState<CorporateUser>();
|
||||
|
||||
const { stats } = useStats();
|
||||
const { users, reload } = useUsers();
|
||||
const { groups } = useGroups(user.id);
|
||||
const {
|
||||
assignments,
|
||||
isLoading: isAssignmentsLoading,
|
||||
reload: reloadAssignments,
|
||||
} = useAssignments({ assigner: user.id });
|
||||
const {stats} = useStats();
|
||||
const {users, reload} = useUsers();
|
||||
const {groups} = useGroups(user.id);
|
||||
const {permissions} = usePermissions(user.id);
|
||||
const {assignments, isLoading: isAssignmentsLoading, reload: reloadAssignments} = useAssignments({assigner: user.id});
|
||||
|
||||
useEffect(() => {
|
||||
setShowModal(!!selectedUser && page === "");
|
||||
}, [selectedUser, page]);
|
||||
useEffect(() => {
|
||||
setShowModal(!!selectedUser && page === "");
|
||||
}, [selectedUser, page]);
|
||||
|
||||
useEffect(() => {
|
||||
getUserCorporate(user.id).then(setCorporateUserToShow);
|
||||
}, [user]);
|
||||
useEffect(() => {
|
||||
getUserCorporate(user.id).then(setCorporateUserToShow);
|
||||
}, [user]);
|
||||
|
||||
const studentFilter = (user: User) =>
|
||||
user.type === "student" &&
|
||||
groups.flatMap((g) => g.participants).includes(user.id);
|
||||
const studentFilter = (user: User) => user.type === "student" && groups.flatMap((g) => g.participants).includes(user.id);
|
||||
|
||||
const getStatsByStudent = (user: User) =>
|
||||
stats.filter((s) => s.user === user.id);
|
||||
const getStatsByStudent = (user: User) => stats.filter((s) => s.user === user.id);
|
||||
|
||||
const UserDisplay = (displayUser: User) => (
|
||||
<div
|
||||
onClick={() => setSelectedUser(displayUser)}
|
||||
className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300"
|
||||
>
|
||||
<img
|
||||
src={displayUser.profilePicture}
|
||||
alt={displayUser.name}
|
||||
className="rounded-full w-10 h-10"
|
||||
/>
|
||||
<div className="flex flex-col gap-1 items-start">
|
||||
<span>{displayUser.name}</span>
|
||||
<span className="text-sm opacity-75">{displayUser.email}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
const UserDisplay = (displayUser: User) => (
|
||||
<div
|
||||
onClick={() => setSelectedUser(displayUser)}
|
||||
className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300">
|
||||
<img src={displayUser.profilePicture} alt={displayUser.name} className="rounded-full w-10 h-10" />
|
||||
<div className="flex flex-col gap-1 items-start">
|
||||
<span>{displayUser.name}</span>
|
||||
<span className="text-sm opacity-75">{displayUser.email}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const StudentsList = () => {
|
||||
const filter = (x: User) =>
|
||||
x.type === "student" &&
|
||||
(!!selectedUser
|
||||
? groups
|
||||
.filter((g) => g.admin === selectedUser.id)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id) || false
|
||||
: groups.flatMap((g) => g.participants).includes(x.id));
|
||||
const StudentsList = () => {
|
||||
const filter = (x: User) =>
|
||||
x.type === "student" &&
|
||||
(!!selectedUser
|
||||
? groups
|
||||
.filter((g) => g.admin === selectedUser.id)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id) || false
|
||||
: groups.flatMap((g) => g.participants).includes(x.id));
|
||||
|
||||
return (
|
||||
<UserList
|
||||
user={user}
|
||||
filters={[filter]}
|
||||
renderHeader={(total) => (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
|
||||
>
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">Students ({total})</h2>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
return (
|
||||
<UserList
|
||||
user={user}
|
||||
filters={[filter]}
|
||||
renderHeader={(total) => (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">Students ({total})</h2>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const GroupsList = () => {
|
||||
const filter = (x: Group) =>
|
||||
x.admin === user.id || x.participants.includes(user.id);
|
||||
const GroupsList = () => {
|
||||
const filter = (x: Group) => x.admin === user.id || x.participants.includes(user.id);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
|
||||
>
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">
|
||||
Groups ({groups.filter(filter).length})
|
||||
</h2>
|
||||
</div>
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col gap-4">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold">Groups ({groups.filter(filter).length})</h2>
|
||||
</div>
|
||||
|
||||
<GroupList user={user} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
<GroupList user={user} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const averageLevelCalculator = (studentStats: Stat[]) => {
|
||||
const formattedStats = studentStats
|
||||
.map((s) => ({
|
||||
focus: users.find((u) => u.id === s.user)?.focus,
|
||||
score: s.score,
|
||||
module: s.module,
|
||||
}))
|
||||
.filter((f) => !!f.focus);
|
||||
const bandScores = formattedStats.map((s) => ({
|
||||
module: s.module,
|
||||
level: calculateBandScore(
|
||||
s.score.correct,
|
||||
s.score.total,
|
||||
s.module,
|
||||
s.focus!
|
||||
),
|
||||
}));
|
||||
const averageLevelCalculator = (studentStats: Stat[]) => {
|
||||
const formattedStats = studentStats
|
||||
.map((s) => ({
|
||||
focus: users.find((u) => u.id === s.user)?.focus,
|
||||
score: s.score,
|
||||
module: s.module,
|
||||
}))
|
||||
.filter((f) => !!f.focus);
|
||||
const bandScores = formattedStats.map((s) => ({
|
||||
module: s.module,
|
||||
level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!),
|
||||
}));
|
||||
|
||||
const levels: { [key in Module]: number } = {
|
||||
reading: 0,
|
||||
listening: 0,
|
||||
writing: 0,
|
||||
speaking: 0,
|
||||
level: 0,
|
||||
};
|
||||
bandScores.forEach((b) => (levels[b.module] += b.level));
|
||||
const levels: {[key in Module]: number} = {
|
||||
reading: 0,
|
||||
listening: 0,
|
||||
writing: 0,
|
||||
speaking: 0,
|
||||
level: 0,
|
||||
};
|
||||
bandScores.forEach((b) => (levels[b.module] += b.level));
|
||||
|
||||
return calculateAverageLevel(levels);
|
||||
};
|
||||
return calculateAverageLevel(levels);
|
||||
};
|
||||
|
||||
const AssignmentsPage = () => {
|
||||
const activeFilter = (a: Assignment) =>
|
||||
moment(a.endDate).isAfter(moment()) &&
|
||||
moment(a.startDate).isBefore(moment()) &&
|
||||
a.assignees.length > a.results.length;
|
||||
const pastFilter = (a: Assignment) =>
|
||||
(moment(a.endDate).isBefore(moment()) ||
|
||||
a.assignees.length === a.results.length) &&
|
||||
!a.archived;
|
||||
const archivedFilter = (a: Assignment) => a.archived;
|
||||
const futureFilter = (a: Assignment) =>
|
||||
moment(a.startDate).isAfter(moment());
|
||||
const AssignmentsPage = () => {
|
||||
const activeFilter = (a: Assignment) =>
|
||||
moment(a.endDate).isAfter(moment()) && moment(a.startDate).isBefore(moment()) && a.assignees.length > a.results.length;
|
||||
const pastFilter = (a: Assignment) => (moment(a.endDate).isBefore(moment()) || a.assignees.length === a.results.length) && !a.archived;
|
||||
const archivedFilter = (a: Assignment) => a.archived;
|
||||
const futureFilter = (a: Assignment) => moment(a.startDate).isAfter(moment());
|
||||
|
||||
return (
|
||||
<>
|
||||
<AssignmentView
|
||||
isOpen={!!selectedAssignment && !isCreatingAssignment}
|
||||
onClose={() => {
|
||||
setSelectedAssignment(undefined);
|
||||
setIsCreatingAssignment(false);
|
||||
reloadAssignments();
|
||||
}}
|
||||
assignment={selectedAssignment}
|
||||
/>
|
||||
<AssignmentCreator
|
||||
assignment={selectedAssignment}
|
||||
groups={groups.filter(
|
||||
(x) => x.admin === user.id || x.participants.includes(user.id)
|
||||
)}
|
||||
users={users.filter(
|
||||
(x) =>
|
||||
x.type === "student" &&
|
||||
(!!selectedUser
|
||||
? groups
|
||||
.filter((g) => g.admin === selectedUser.id)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id) || false
|
||||
: groups.flatMap((g) => g.participants).includes(x.id))
|
||||
)}
|
||||
assigner={user.id}
|
||||
isCreating={isCreatingAssignment}
|
||||
cancelCreation={() => {
|
||||
setIsCreatingAssignment(false);
|
||||
setSelectedAssignment(undefined);
|
||||
reloadAssignments();
|
||||
}}
|
||||
/>
|
||||
<div className="w-full flex justify-between items-center">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
|
||||
>
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<div
|
||||
onClick={reloadAssignments}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
|
||||
>
|
||||
<span>Reload</span>
|
||||
<BsArrowRepeat
|
||||
className={clsx(
|
||||
"text-xl",
|
||||
isAssignmentsLoading && "animate-spin"
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<section className="flex flex-col gap-4">
|
||||
<h2 className="text-2xl font-semibold">
|
||||
Active Assignments ({assignments.filter(activeFilter).length})
|
||||
</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{assignments.filter(activeFilter).map((a) => (
|
||||
<AssignmentCard
|
||||
{...a}
|
||||
onClick={() => setSelectedAssignment(a)}
|
||||
key={a.id}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<section className="flex flex-col gap-4">
|
||||
<h2 className="text-2xl font-semibold">
|
||||
Planned Assignments ({assignments.filter(futureFilter).length})
|
||||
</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<div
|
||||
onClick={() => setIsCreatingAssignment(true)}
|
||||
className="w-[250px] h-[200px] flex flex-col gap-2 items-center justify-center bg-white hover:bg-mti-purple-ultralight text-mti-purple-light hover:text-mti-purple-dark border border-mti-gray-platinum hover:drop-shadow p-4 cursor-pointer rounded-xl transition ease-in-out duration-300"
|
||||
>
|
||||
<BsPlus className="text-6xl" />
|
||||
<span className="text-lg">New Assignment</span>
|
||||
</div>
|
||||
{assignments.filter(futureFilter).map((a) => (
|
||||
<AssignmentCard
|
||||
{...a}
|
||||
onClick={() => {
|
||||
setSelectedAssignment(a);
|
||||
setIsCreatingAssignment(true);
|
||||
}}
|
||||
key={a.id}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<section className="flex flex-col gap-4">
|
||||
<h2 className="text-2xl font-semibold">
|
||||
Past Assignments ({assignments.filter(pastFilter).length})
|
||||
</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{assignments.filter(pastFilter).map((a) => (
|
||||
<AssignmentCard
|
||||
{...a}
|
||||
onClick={() => setSelectedAssignment(a)}
|
||||
key={a.id}
|
||||
allowDownload
|
||||
reload={reloadAssignments}
|
||||
allowArchive
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<section className="flex flex-col gap-4">
|
||||
<h2 className="text-2xl font-semibold">
|
||||
Archived Assignments ({assignments.filter(archivedFilter).length})
|
||||
</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{assignments.filter(archivedFilter).map((a) => (
|
||||
<AssignmentCard
|
||||
{...a}
|
||||
onClick={() => setSelectedAssignment(a)}
|
||||
key={a.id}
|
||||
allowDownload
|
||||
reload={reloadAssignments}
|
||||
allowUnarchive
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<AssignmentView
|
||||
isOpen={!!selectedAssignment && !isCreatingAssignment}
|
||||
onClose={() => {
|
||||
setSelectedAssignment(undefined);
|
||||
setIsCreatingAssignment(false);
|
||||
reloadAssignments();
|
||||
}}
|
||||
assignment={selectedAssignment}
|
||||
/>
|
||||
<AssignmentCreator
|
||||
assignment={selectedAssignment}
|
||||
groups={groups.filter((x) => x.admin === user.id || x.participants.includes(user.id))}
|
||||
users={users.filter(
|
||||
(x) =>
|
||||
x.type === "student" &&
|
||||
(!!selectedUser
|
||||
? groups
|
||||
.filter((g) => g.admin === selectedUser.id)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id) || false
|
||||
: groups.flatMap((g) => g.participants).includes(x.id)),
|
||||
)}
|
||||
assigner={user.id}
|
||||
isCreating={isCreatingAssignment}
|
||||
cancelCreation={() => {
|
||||
setIsCreatingAssignment(false);
|
||||
setSelectedAssignment(undefined);
|
||||
reloadAssignments();
|
||||
}}
|
||||
/>
|
||||
<div className="w-full flex justify-between items-center">
|
||||
<div
|
||||
onClick={() => setPage("")}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||
<BsArrowLeft className="text-xl" />
|
||||
<span>Back</span>
|
||||
</div>
|
||||
<div
|
||||
onClick={reloadAssignments}
|
||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||
<span>Reload</span>
|
||||
<BsArrowRepeat className={clsx("text-xl", isAssignmentsLoading && "animate-spin")} />
|
||||
</div>
|
||||
</div>
|
||||
<section className="flex flex-col gap-4">
|
||||
<h2 className="text-2xl font-semibold">Active Assignments ({assignments.filter(activeFilter).length})</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{assignments.filter(activeFilter).map((a) => (
|
||||
<AssignmentCard {...a} onClick={() => setSelectedAssignment(a)} key={a.id} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<section className="flex flex-col gap-4">
|
||||
<h2 className="text-2xl font-semibold">Planned Assignments ({assignments.filter(futureFilter).length})</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<div
|
||||
onClick={() => setIsCreatingAssignment(true)}
|
||||
className="w-[250px] h-[200px] flex flex-col gap-2 items-center justify-center bg-white hover:bg-mti-purple-ultralight text-mti-purple-light hover:text-mti-purple-dark border border-mti-gray-platinum hover:drop-shadow p-4 cursor-pointer rounded-xl transition ease-in-out duration-300">
|
||||
<BsPlus className="text-6xl" />
|
||||
<span className="text-lg">New Assignment</span>
|
||||
</div>
|
||||
{assignments.filter(futureFilter).map((a) => (
|
||||
<AssignmentCard
|
||||
{...a}
|
||||
onClick={() => {
|
||||
setSelectedAssignment(a);
|
||||
setIsCreatingAssignment(true);
|
||||
}}
|
||||
key={a.id}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<section className="flex flex-col gap-4">
|
||||
<h2 className="text-2xl font-semibold">Past Assignments ({assignments.filter(pastFilter).length})</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{assignments.filter(pastFilter).map((a) => (
|
||||
<AssignmentCard
|
||||
{...a}
|
||||
onClick={() => setSelectedAssignment(a)}
|
||||
key={a.id}
|
||||
allowDownload
|
||||
reload={reloadAssignments}
|
||||
allowArchive
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<section className="flex flex-col gap-4">
|
||||
<h2 className="text-2xl font-semibold">Archived Assignments ({assignments.filter(archivedFilter).length})</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{assignments.filter(archivedFilter).map((a) => (
|
||||
<AssignmentCard
|
||||
{...a}
|
||||
onClick={() => setSelectedAssignment(a)}
|
||||
key={a.id}
|
||||
allowDownload
|
||||
reload={reloadAssignments}
|
||||
allowUnarchive
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const DefaultDashboard = () => (
|
||||
<>
|
||||
{corporateUserToShow && (
|
||||
<div className="absolute top-4 right-4 bg-neutral-200 px-2 rounded-lg py-1">
|
||||
Linked to:{" "}
|
||||
<b>
|
||||
{corporateUserToShow?.corporateInformation?.companyInformation
|
||||
.name || corporateUserToShow.name}
|
||||
</b>
|
||||
</div>
|
||||
)}
|
||||
<section
|
||||
className={clsx(
|
||||
"flex -lg:flex-wrap gap-4 items-center -lg:justify-center lg:justify-start text-center",
|
||||
!!corporateUserToShow && "mt-12 xl:mt-6"
|
||||
)}
|
||||
>
|
||||
<IconCard
|
||||
onClick={() => setPage("students")}
|
||||
Icon={BsPersonFill}
|
||||
label="Students"
|
||||
value={users.filter(studentFilter).length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsClipboard2Data}
|
||||
label="Exams Performed"
|
||||
value={
|
||||
stats.filter((s) =>
|
||||
groups.flatMap((g) => g.participants).includes(s.user)
|
||||
).length
|
||||
}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsPaperclip}
|
||||
label="Average Level"
|
||||
value={averageLevelCalculator(
|
||||
stats.filter((s) =>
|
||||
groups.flatMap((g) => g.participants).includes(s.user)
|
||||
)
|
||||
).toFixed(1)}
|
||||
color="purple"
|
||||
/>
|
||||
<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"
|
||||
>
|
||||
<BsEnvelopePaper className="text-6xl text-mti-purple-light" />
|
||||
<span className="flex flex-col gap-1 items-center text-xl">
|
||||
<span className="text-lg">Assignments</span>
|
||||
<span className="font-semibold text-mti-purple-light">
|
||||
{assignments.filter((a) => !a.archived).length}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</section>
|
||||
const DefaultDashboard = () => (
|
||||
<>
|
||||
{corporateUserToShow && (
|
||||
<div className="absolute top-4 right-4 bg-neutral-200 px-2 rounded-lg py-1">
|
||||
Linked to: <b>{corporateUserToShow?.corporateInformation?.companyInformation.name || corporateUserToShow.name}</b>
|
||||
</div>
|
||||
)}
|
||||
<section
|
||||
className={clsx(
|
||||
"flex -lg:flex-wrap gap-4 items-center -lg:justify-center lg:justify-start text-center",
|
||||
!!corporateUserToShow && "mt-12 xl:mt-6",
|
||||
)}>
|
||||
<IconCard
|
||||
onClick={() => setPage("students")}
|
||||
Icon={BsPersonFill}
|
||||
label="Students"
|
||||
value={users.filter(studentFilter).length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsClipboard2Data}
|
||||
label="Exams Performed"
|
||||
value={stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user)).length}
|
||||
color="purple"
|
||||
/>
|
||||
<IconCard
|
||||
Icon={BsPaperclip}
|
||||
label="Average Level"
|
||||
value={averageLevelCalculator(stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user))).toFixed(1)}
|
||||
color="purple"
|
||||
/>
|
||||
{checkAccess(user, ["teacher", "developer"], permissions, "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">
|
||||
<BsEnvelopePaper className="text-6xl text-mti-purple-light" />
|
||||
<span className="flex flex-col gap-1 items-center text-xl">
|
||||
<span className="text-lg">Assignments</span>
|
||||
<span className="font-semibold text-mti-purple-light">{assignments.filter((a) => !a.archived).length}</span>
|
||||
</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 w-full justify-between">
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest level students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
calculateAverageLevel(b.levels) -
|
||||
calculateAverageLevel(a.levels)
|
||||
)
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest exam count students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Object.keys(groupByExam(getStatsByStudent(b))).length -
|
||||
Object.keys(groupByExam(getStatsByStudent(a))).length
|
||||
)
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
<section className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 w-full justify-between">
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Latest students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest level students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||
<span className="p-4">Highest exam count students</span>
|
||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||
{users
|
||||
.filter(studentFilter)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Object.keys(groupByExam(getStatsByStudent(b))).length - Object.keys(groupByExam(getStatsByStudent(a))).length,
|
||||
)
|
||||
.map((x) => (
|
||||
<UserDisplay key={x.id} {...x} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal isOpen={showModal} onClose={() => setSelectedUser(undefined)}>
|
||||
<>
|
||||
{selectedUser && (
|
||||
<div className="w-full flex flex-col gap-8">
|
||||
<UserCard
|
||||
loggedInUser={user}
|
||||
onClose={(shouldReload) => {
|
||||
setSelectedUser(undefined);
|
||||
if (shouldReload) reload();
|
||||
}}
|
||||
onViewStudents={
|
||||
selectedUser.type === "corporate" ||
|
||||
selectedUser.type === "teacher"
|
||||
? () => setPage("students")
|
||||
: undefined
|
||||
}
|
||||
onViewTeachers={
|
||||
selectedUser.type === "corporate"
|
||||
? () => setPage("teachers")
|
||||
: undefined
|
||||
}
|
||||
user={selectedUser}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</Modal>
|
||||
{page === "students" && <StudentsList />}
|
||||
{page === "groups" && <GroupsList />}
|
||||
{page === "assignments" && <AssignmentsPage />}
|
||||
{page === "" && <DefaultDashboard />}
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Modal isOpen={showModal} onClose={() => setSelectedUser(undefined)}>
|
||||
<>
|
||||
{selectedUser && (
|
||||
<div className="w-full flex flex-col gap-8">
|
||||
<UserCard
|
||||
loggedInUser={user}
|
||||
onClose={(shouldReload) => {
|
||||
setSelectedUser(undefined);
|
||||
if (shouldReload) reload();
|
||||
}}
|
||||
onViewStudents={
|
||||
selectedUser.type === "corporate" || selectedUser.type === "teacher" ? () => setPage("students") : undefined
|
||||
}
|
||||
onViewTeachers={selectedUser.type === "corporate" ? () => setPage("teachers") : undefined}
|
||||
user={selectedUser}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</Modal>
|
||||
{page === "students" && <StudentsList />}
|
||||
{page === "groups" && <GroupsList />}
|
||||
{page === "assignments" && <AssignmentsPage />}
|
||||
{page === "" && <DefaultDashboard />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import {Assignment} from "@/interfaces/results";
|
||||
import axios from "axios";
|
||||
import {useEffect, useState} from "react";
|
||||
|
||||
export default function useAssignments({assigner, assignees}: {assigner?: string; assignees?: string}) {
|
||||
export default function useAssignments({assigner, assignees, corporate}: {assigner?: string; assignees?: string; corporate?: string}) {
|
||||
const [assignments, setAssignments] = useState<Assignment[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isError, setIsError] = useState(false);
|
||||
@@ -10,12 +10,13 @@ export default function useAssignments({assigner, assignees}: {assigner?: string
|
||||
const getData = () => {
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.get<Assignment[]>("/api/assignments")
|
||||
.then((response) => {
|
||||
.get<Assignment[]>(!corporate ? "/api/assignments" : `/api/assignments/corporate?id=${corporate}`)
|
||||
.then(async (response) => {
|
||||
if (assigner) {
|
||||
setAssignments(response.data.filter((a) => a.assigner === assigner));
|
||||
return;
|
||||
}
|
||||
|
||||
if (assignees) {
|
||||
setAssignments(response.data.filter((a) => a.assignees.filter((x) => assignees.includes(x)).length > 0));
|
||||
return;
|
||||
@@ -26,7 +27,7 @@ export default function useAssignments({assigner, assignees}: {assigner?: string
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
useEffect(getData, [assignees, assigner]);
|
||||
useEffect(getData, [assignees, assigner, corporate]);
|
||||
|
||||
return {assignments, isLoading, isError, reload: getData};
|
||||
}
|
||||
|
||||
29
src/hooks/usePermissions.tsx
Normal file
29
src/hooks/usePermissions.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import {Exam} from "@/interfaces/exam";
|
||||
import {Permission, PermissionType} from "@/interfaces/permissions";
|
||||
import {ExamState} from "@/stores/examStore";
|
||||
import axios from "axios";
|
||||
import {useEffect, useState} from "react";
|
||||
|
||||
export default function usePermissions(user: string) {
|
||||
const [permissions, setPermissions] = useState<PermissionType[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isError, setIsError] = useState(false);
|
||||
|
||||
const getData = () => {
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.get<Permission[]>(`/api/permissions`)
|
||||
.then((response) => {
|
||||
const permissionTypes = response.data
|
||||
.filter((x) => !x.users.includes(user))
|
||||
.reduce((acc, curr) => [...acc, curr.type], [] as PermissionType[]);
|
||||
console.log(response.data, permissionTypes);
|
||||
setPermissions(permissionTypes);
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
useEffect(getData, [user]);
|
||||
|
||||
return {permissions, isLoading, isError, reload: getData};
|
||||
}
|
||||
@@ -1,19 +1,24 @@
|
||||
import {Module} from ".";
|
||||
import { Module } from ".";
|
||||
|
||||
export type Exam = ReadingExam | ListeningExam | WritingExam | SpeakingExam | LevelExam;
|
||||
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 =
|
||||
@@ -115,17 +100,21 @@ export interface Evaluation {
|
||||
misspelled_pairs?: {correction: string | null; misspelled: string}[];
|
||||
}
|
||||
|
||||
interface InteractiveSpeakingEvaluation extends Evaluation {
|
||||
perfect_answer_1?: {answer: string};
|
||||
transcript_1?: string;
|
||||
fixed_text_1?: string;
|
||||
perfect_answer_2?: {answer: string};
|
||||
transcript_2?: string;
|
||||
fixed_text_2?: string;
|
||||
perfect_answer_3?: {answer: string};
|
||||
transcript_3?: string;
|
||||
fixed_text_3?: string;
|
||||
}
|
||||
|
||||
type InteractivePerfectAnswerKey = `perfect_answer_${number}`;
|
||||
type InteractiveTranscriptKey = `transcript_${number}`;
|
||||
type InteractiveFixedTextKey = `fixed_text_${number}`;
|
||||
|
||||
type InteractivePerfectAnswerType = { [key in InteractivePerfectAnswerKey]: { answer: string } };
|
||||
type InteractiveTranscriptType = { [key in InteractiveTranscriptKey]?: string };
|
||||
type InteractiveFixedTextType = { [key in InteractiveFixedTextKey]?: string };
|
||||
|
||||
interface InteractiveSpeakingEvaluation extends Evaluation,
|
||||
InteractivePerfectAnswerType,
|
||||
InteractiveTranscriptType,
|
||||
InteractiveFixedTextType
|
||||
{}
|
||||
|
||||
|
||||
interface SpeakingEvaluation extends CommonEvaluation {
|
||||
perfect_answer_1?: string;
|
||||
|
||||
@@ -1,49 +1,58 @@
|
||||
export const markets = ["au", "br", "de"] as const;
|
||||
|
||||
export const permissions = [
|
||||
// generate codes are basicly invites
|
||||
"createCodeStudent",
|
||||
"createCodeTeacher",
|
||||
"createCodeCorporate",
|
||||
"createCodeCountryManager",
|
||||
"createCodeAdmin",
|
||||
// exams
|
||||
"createReadingExam",
|
||||
"createListeningExam",
|
||||
"createWritingExam",
|
||||
"createSpeakingExam",
|
||||
"createLevelExam",
|
||||
// view pages
|
||||
"viewExams",
|
||||
"viewExercises",
|
||||
"viewRecords",
|
||||
"viewStats",
|
||||
"viewTickets",
|
||||
"viewPaymentRecords",
|
||||
// view data
|
||||
"viewStudent",
|
||||
"viewTeacher",
|
||||
"viewCorporate",
|
||||
"viewCountryManager",
|
||||
"viewAdmin",
|
||||
// edit data
|
||||
"editStudent",
|
||||
"editTeacher",
|
||||
"editCorporate",
|
||||
"editCountryManager",
|
||||
"editAdmin",
|
||||
// delete data
|
||||
"deleteStudent",
|
||||
"deleteTeacher",
|
||||
"deleteCorporate",
|
||||
"deleteCountryManager",
|
||||
"deleteAdmin",
|
||||
// generate codes are basicly invites
|
||||
"createCodeStudent",
|
||||
"createCodeTeacher",
|
||||
"createCodeCorporate",
|
||||
"createCodeCountryManager",
|
||||
"createCodeAdmin",
|
||||
// exams
|
||||
"createReadingExam",
|
||||
"createListeningExam",
|
||||
"createWritingExam",
|
||||
"createSpeakingExam",
|
||||
"createLevelExam",
|
||||
// view pages
|
||||
"viewExams",
|
||||
"viewExercises",
|
||||
"viewRecords",
|
||||
"viewStats",
|
||||
"viewTickets",
|
||||
"viewPaymentRecords",
|
||||
// view data
|
||||
"viewStudent",
|
||||
"viewTeacher",
|
||||
"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",
|
||||
"all",
|
||||
] as const;
|
||||
|
||||
export type PermissionType = (typeof permissions)[keyof typeof permissions];
|
||||
|
||||
export interface Permission {
|
||||
id: string;
|
||||
type: PermissionType;
|
||||
users: string[];
|
||||
id: string;
|
||||
type: PermissionType;
|
||||
users: string[];
|
||||
}
|
||||
|
||||
@@ -1,366 +1,280 @@
|
||||
import Button from "@/components/Low/Button";
|
||||
import Checkbox from "@/components/Low/Checkbox";
|
||||
import { PERMISSIONS } from "@/constants/userPermissions";
|
||||
import {PERMISSIONS} from "@/constants/userPermissions";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import { Type, User } from "@/interfaces/user";
|
||||
import { USER_TYPE_LABELS } from "@/resources/user";
|
||||
import {Type, User} from "@/interfaces/user";
|
||||
import {USER_TYPE_LABELS} from "@/resources/user";
|
||||
import axios from "axios";
|
||||
import clsx from "clsx";
|
||||
import { capitalize, uniqBy } from "lodash";
|
||||
import {capitalize, uniqBy} from "lodash";
|
||||
import moment from "moment";
|
||||
import { useEffect, useState } from "react";
|
||||
import {useEffect, useState} from "react";
|
||||
import ReactDatePicker from "react-datepicker";
|
||||
import { toast } from "react-toastify";
|
||||
import {toast} from "react-toastify";
|
||||
import ShortUniqueId from "short-unique-id";
|
||||
import { useFilePicker } from "use-file-picker";
|
||||
import {useFilePicker} from "use-file-picker";
|
||||
import readXlsxFile from "read-excel-file";
|
||||
import Modal from "@/components/Modal";
|
||||
import { BsFileEarmarkEaselFill, BsQuestionCircleFill } from "react-icons/bs";
|
||||
import { checkAccess } 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]+)*$/
|
||||
);
|
||||
import {BsFileEarmarkEaselFill, BsQuestionCircleFill} from "react-icons/bs";
|
||||
import {checkAccess, getTypesOfUser} from "@/utils/permissions";
|
||||
import {PermissionType} from "@/interfaces/permissions";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
const EMAIL_REGEX = new RegExp(/^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$/);
|
||||
|
||||
const USER_TYPE_PERMISSIONS: {
|
||||
[key in Type]: { perm: PermissionType | undefined; list: Type[] };
|
||||
[key in Type]: {perm: PermissionType | undefined; list: Type[]};
|
||||
} = {
|
||||
student: {
|
||||
perm: "createCodeStudent",
|
||||
list: [],
|
||||
},
|
||||
teacher: {
|
||||
perm: "createCodeTeacher",
|
||||
list: [],
|
||||
},
|
||||
agent: {
|
||||
perm: "createCodeCountryManager",
|
||||
list: [],
|
||||
},
|
||||
corporate: {
|
||||
perm: "createCodeCorporate",
|
||||
list: ["student", "teacher"],
|
||||
},
|
||||
mastercorporate: {
|
||||
perm: undefined,
|
||||
list: ["student", "teacher", "corporate"],
|
||||
},
|
||||
admin: {
|
||||
perm: "createCodeAdmin",
|
||||
list: [
|
||||
"student",
|
||||
"teacher",
|
||||
"agent",
|
||||
"corporate",
|
||||
"admin",
|
||||
"mastercorporate",
|
||||
],
|
||||
},
|
||||
developer: {
|
||||
perm: undefined,
|
||||
list: [
|
||||
"student",
|
||||
"teacher",
|
||||
"agent",
|
||||
"corporate",
|
||||
"admin",
|
||||
"developer",
|
||||
"mastercorporate",
|
||||
],
|
||||
},
|
||||
student: {
|
||||
perm: "createCodeStudent",
|
||||
list: [],
|
||||
},
|
||||
teacher: {
|
||||
perm: "createCodeTeacher",
|
||||
list: [],
|
||||
},
|
||||
agent: {
|
||||
perm: "createCodeCountryManager",
|
||||
list: [],
|
||||
},
|
||||
corporate: {
|
||||
perm: "createCodeCorporate",
|
||||
list: ["student", "teacher"],
|
||||
},
|
||||
mastercorporate: {
|
||||
perm: undefined,
|
||||
list: ["student", "teacher", "corporate"],
|
||||
},
|
||||
admin: {
|
||||
perm: "createCodeAdmin",
|
||||
list: ["student", "teacher", "agent", "corporate", "admin", "mastercorporate"],
|
||||
},
|
||||
developer: {
|
||||
perm: undefined,
|
||||
list: ["student", "teacher", "agent", "corporate", "admin", "developer", "mastercorporate"],
|
||||
},
|
||||
};
|
||||
|
||||
export default function BatchCodeGenerator({ user }: { user: User }) {
|
||||
const [infos, setInfos] = useState<
|
||||
{ email: string; name: string; passport_id: string }[]
|
||||
>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [expiryDate, setExpiryDate] = useState<Date | null>(
|
||||
user?.subscriptionExpirationDate
|
||||
? moment(user.subscriptionExpirationDate).toDate()
|
||||
: null
|
||||
);
|
||||
const [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true);
|
||||
const [type, setType] = useState<Type>("student");
|
||||
const [showHelp, setShowHelp] = useState(false);
|
||||
export default function BatchCodeGenerator({user}: {user: User}) {
|
||||
const [infos, setInfos] = useState<{email: string; name: string; passport_id: string}[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [expiryDate, setExpiryDate] = useState<Date | null>(
|
||||
user?.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).toDate() : null,
|
||||
);
|
||||
const [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true);
|
||||
const [type, setType] = useState<Type>("student");
|
||||
const [showHelp, setShowHelp] = useState(false);
|
||||
|
||||
const { users } = useUsers();
|
||||
const {users} = useUsers();
|
||||
const {permissions} = usePermissions(user?.id || "");
|
||||
|
||||
const { openFilePicker, filesContent, clear } = useFilePicker({
|
||||
accept: ".xlsx",
|
||||
multiple: false,
|
||||
readAs: "ArrayBuffer",
|
||||
});
|
||||
const {openFilePicker, filesContent, clear} = useFilePicker({
|
||||
accept: ".xlsx",
|
||||
multiple: false,
|
||||
readAs: "ArrayBuffer",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!isExpiryDateEnabled) setExpiryDate(null);
|
||||
}, [isExpiryDateEnabled]);
|
||||
useEffect(() => {
|
||||
if (!isExpiryDateEnabled) setExpiryDate(null);
|
||||
}, [isExpiryDateEnabled]);
|
||||
|
||||
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
|
||||
] = row as string[];
|
||||
return EMAIL_REGEX.test(email.toString().trim())
|
||||
? {
|
||||
email: email.toString().trim().toLowerCase(),
|
||||
name: `${firstName ?? ""} ${lastName ?? ""}`.trim(),
|
||||
passport_id: passport_id?.toString().trim() || undefined,
|
||||
}
|
||||
: undefined;
|
||||
})
|
||||
.filter((x) => !!x) as typeof infos,
|
||||
(x) => x.email
|
||||
);
|
||||
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] = row as string[];
|
||||
return EMAIL_REGEX.test(email.toString().trim())
|
||||
? {
|
||||
email: email.toString().trim().toLowerCase(),
|
||||
name: `${firstName ?? ""} ${lastName ?? ""}`.trim(),
|
||||
passport_id: passport_id?.toString().trim() || undefined,
|
||||
}
|
||||
: 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();
|
||||
}
|
||||
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]);
|
||||
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 generateAndInvite = async () => {
|
||||
const newUsers = infos.filter(
|
||||
(x) => !users.map((u) => u.email).includes(x.email)
|
||||
);
|
||||
const existingUsers = infos
|
||||
.filter((x) => users.map((u) => u.email).includes(x.email))
|
||||
.map((i) => users.find((u) => u.email === i.email))
|
||||
.filter((x) => !!x && x.type === "student") as User[];
|
||||
const generateAndInvite = async () => {
|
||||
const newUsers = infos.filter((x) => !users.map((u) => u.email).includes(x.email));
|
||||
const existingUsers = infos
|
||||
.filter((x) => users.map((u) => u.email).includes(x.email))
|
||||
.map((i) => users.find((u) => u.email === i.email))
|
||||
.filter((x) => !!x && x.type === "student") as User[];
|
||||
|
||||
const newUsersSentence =
|
||||
newUsers.length > 0 ? `generate ${newUsers.length} code(s)` : undefined;
|
||||
const existingUsersSentence =
|
||||
existingUsers.length > 0
|
||||
? `invite ${existingUsers.length} registered student(s)`
|
||||
: undefined;
|
||||
if (
|
||||
!confirm(
|
||||
`You are about to ${[newUsersSentence, existingUsersSentence]
|
||||
.filter((x) => !!x)
|
||||
.join(" and ")}, are you sure you want to continue?`
|
||||
)
|
||||
)
|
||||
return;
|
||||
const newUsersSentence = newUsers.length > 0 ? `generate ${newUsers.length} code(s)` : undefined;
|
||||
const existingUsersSentence = existingUsers.length > 0 ? `invite ${existingUsers.length} registered student(s)` : undefined;
|
||||
if (
|
||||
!confirm(
|
||||
`You are about to ${[newUsersSentence, existingUsersSentence].filter((x) => !!x).join(" and ")}, are you sure you want to continue?`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
setIsLoading(true);
|
||||
Promise.all(
|
||||
existingUsers.map(
|
||||
async (u) =>
|
||||
await axios.post(`/api/invites`, { to: u.id, from: user.id })
|
||||
)
|
||||
)
|
||||
.then(() =>
|
||||
toast.success(
|
||||
`Successfully invited ${existingUsers.length} registered student(s)!`
|
||||
)
|
||||
)
|
||||
.finally(() => {
|
||||
if (newUsers.length === 0) setIsLoading(false);
|
||||
});
|
||||
setIsLoading(true);
|
||||
Promise.all(existingUsers.map(async (u) => await axios.post(`/api/invites`, {to: u.id, from: user.id})))
|
||||
.then(() => toast.success(`Successfully invited ${existingUsers.length} registered student(s)!`))
|
||||
.finally(() => {
|
||||
if (newUsers.length === 0) setIsLoading(false);
|
||||
});
|
||||
|
||||
if (newUsers.length > 0) generateCode(type, newUsers);
|
||||
setInfos([]);
|
||||
};
|
||||
if (newUsers.length > 0) generateCode(type, newUsers);
|
||||
setInfos([]);
|
||||
};
|
||||
|
||||
const generateCode = (type: Type, informations: typeof infos) => {
|
||||
const uid = new ShortUniqueId();
|
||||
const codes = informations.map(() => uid.randomUUID(6));
|
||||
const generateCode = (type: Type, informations: typeof infos) => {
|
||||
const uid = new ShortUniqueId();
|
||||
const codes = informations.map(() => uid.randomUUID(6));
|
||||
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.post<{ ok: boolean; valid?: number; reason?: string }>("/api/code", {
|
||||
type,
|
||||
codes,
|
||||
infos: informations,
|
||||
expiryDate,
|
||||
})
|
||||
.then(({ data, status }) => {
|
||||
if (data.ok) {
|
||||
toast.success(
|
||||
`Successfully generated${
|
||||
data.valid ? ` ${data.valid}/${informations.length}` : ""
|
||||
} ${capitalize(type)} codes and they have been notified by e-mail!`,
|
||||
{ toastId: "success" }
|
||||
);
|
||||
return;
|
||||
}
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.post<{ok: boolean; valid?: number; reason?: string}>("/api/code", {
|
||||
type,
|
||||
codes,
|
||||
infos: informations,
|
||||
expiryDate,
|
||||
})
|
||||
.then(({data, status}) => {
|
||||
if (data.ok) {
|
||||
toast.success(
|
||||
`Successfully generated${data.valid ? ` ${data.valid}/${informations.length}` : ""} ${capitalize(
|
||||
type,
|
||||
)} codes and they have been notified by e-mail!`,
|
||||
{toastId: "success"},
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (status === 403) {
|
||||
toast.error(data.reason, { toastId: "forbidden" });
|
||||
}
|
||||
})
|
||||
.catch(({ response: { status, data } }) => {
|
||||
if (status === 403) {
|
||||
toast.error(data.reason, { toastId: "forbidden" });
|
||||
return;
|
||||
}
|
||||
if (status === 403) {
|
||||
toast.error(data.reason, {toastId: "forbidden"});
|
||||
}
|
||||
})
|
||||
.catch(({response: {status, data}}) => {
|
||||
if (status === 403) {
|
||||
toast.error(data.reason, {toastId: "forbidden"});
|
||||
return;
|
||||
}
|
||||
|
||||
toast.error(`Something went wrong, please try again later!`, {
|
||||
toastId: "error",
|
||||
});
|
||||
})
|
||||
.finally(() => {
|
||||
setIsLoading(false);
|
||||
return clear();
|
||||
});
|
||||
};
|
||||
toast.error(`Something went wrong, please try again later!`, {
|
||||
toastId: "error",
|
||||
});
|
||||
})
|
||||
.finally(() => {
|
||||
setIsLoading(false);
|
||||
return clear();
|
||||
});
|
||||
};
|
||||
|
||||
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>
|
||||
</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>
|
||||
{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)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<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 typeof user.type)}
|
||||
className="flex min-h-[70px] w-full min-w-[350px] cursor-pointer justify-center rounded-full border bg-white p-6 text-sm font-normal focus:outline-none"
|
||||
>
|
||||
{Object.keys(USER_TYPE_LABELS)
|
||||
.filter((x) => {
|
||||
const { list, perm } = USER_TYPE_PERMISSIONS[x as Type];
|
||||
return checkAccess(user, list, perm);
|
||||
})
|
||||
.map((type) => (
|
||||
<option key={type} value={type}>
|
||||
{USER_TYPE_LABELS[type as keyof typeof USER_TYPE_LABELS]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<Button
|
||||
onClick={generateAndInvite}
|
||||
disabled={
|
||||
infos.length === 0 || (isExpiryDateEnabled ? !expiryDate : false)
|
||||
}
|
||||
>
|
||||
Generate & Send
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
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>
|
||||
</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>
|
||||
{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)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<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 typeof user.type)}
|
||||
className="flex min-h-[70px] w-full min-w-[350px] cursor-pointer justify-center rounded-full border bg-white p-6 text-sm font-normal focus:outline-none">
|
||||
{Object.keys(USER_TYPE_LABELS)
|
||||
.filter((x) => {
|
||||
const {list, perm} = USER_TYPE_PERMISSIONS[x as Type];
|
||||
return checkAccess(user, getTypesOfUser(list), permissions, perm);
|
||||
})
|
||||
.map((type) => (
|
||||
<option key={type} value={type}>
|
||||
{USER_TYPE_LABELS[type as keyof typeof USER_TYPE_LABELS]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
{checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"], permissions, "createCodes") && (
|
||||
<Button onClick={generateAndInvite} disabled={infos.length === 0 || (isExpiryDateEnabled ? !expiryDate : false)}>
|
||||
Generate & Send
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
232
src/pages/(admin)/BatchCreateUser.tsx
Normal file
232
src/pages/(admin)/BatchCreateUser.tsx
Normal file
@@ -0,0 +1,232 @@
|
||||
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";
|
||||
import moment from "moment";
|
||||
import {checkAccess} from "@/utils/permissions";
|
||||
import Checkbox from "@/components/Low/Checkbox";
|
||||
import ReactDatePicker from "react-datepicker";
|
||||
import clsx from "clsx";
|
||||
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 [expiryDate, setExpiryDate] = useState<Date | null>(
|
||||
user?.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).toDate() : null,
|
||||
);
|
||||
const [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true);
|
||||
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 (!isExpiryDateEnabled) setExpiryDate(null);
|
||||
}, [isExpiryDateEnabled]);
|
||||
|
||||
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>
|
||||
{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)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,197 +1,162 @@
|
||||
import Button from "@/components/Low/Button";
|
||||
import Checkbox from "@/components/Low/Checkbox";
|
||||
import { PERMISSIONS } from "@/constants/userPermissions";
|
||||
import { Type, User } from "@/interfaces/user";
|
||||
import { USER_TYPE_LABELS } from "@/resources/user";
|
||||
import {PERMISSIONS} from "@/constants/userPermissions";
|
||||
import {Type, User} from "@/interfaces/user";
|
||||
import {USER_TYPE_LABELS} from "@/resources/user";
|
||||
import axios from "axios";
|
||||
import clsx from "clsx";
|
||||
import { capitalize } from "lodash";
|
||||
import {capitalize} from "lodash";
|
||||
import moment from "moment";
|
||||
import { useEffect, useState } from "react";
|
||||
import {useEffect, useState} from "react";
|
||||
import ReactDatePicker from "react-datepicker";
|
||||
import { toast } from "react-toastify";
|
||||
import {toast} from "react-toastify";
|
||||
import ShortUniqueId from "short-unique-id";
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
import { PermissionType } from "@/interfaces/permissions";
|
||||
import {checkAccess} from "@/utils/permissions";
|
||||
import {PermissionType} from "@/interfaces/permissions";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
|
||||
const USER_TYPE_PERMISSIONS: {
|
||||
[key in Type]: { perm: PermissionType | undefined; list: Type[] };
|
||||
[key in Type]: {perm: PermissionType | undefined; list: Type[]};
|
||||
} = {
|
||||
student: {
|
||||
perm: "createCodeStudent",
|
||||
list: [],
|
||||
},
|
||||
teacher: {
|
||||
perm: "createCodeTeacher",
|
||||
list: [],
|
||||
},
|
||||
agent: {
|
||||
perm: "createCodeCountryManager",
|
||||
list: [],
|
||||
},
|
||||
corporate: {
|
||||
perm: "createCodeCorporate",
|
||||
list: ["student", "teacher"],
|
||||
},
|
||||
mastercorporate: {
|
||||
perm: undefined,
|
||||
list: ["student", "teacher", "corporate"],
|
||||
},
|
||||
admin: {
|
||||
perm: "createCodeAdmin",
|
||||
list: [
|
||||
"student",
|
||||
"teacher",
|
||||
"agent",
|
||||
"corporate",
|
||||
"admin",
|
||||
"mastercorporate",
|
||||
],
|
||||
},
|
||||
developer: {
|
||||
perm: undefined,
|
||||
list: [
|
||||
"student",
|
||||
"teacher",
|
||||
"agent",
|
||||
"corporate",
|
||||
"admin",
|
||||
"developer",
|
||||
"mastercorporate",
|
||||
],
|
||||
},
|
||||
student: {
|
||||
perm: "createCodeStudent",
|
||||
list: [],
|
||||
},
|
||||
teacher: {
|
||||
perm: "createCodeTeacher",
|
||||
list: [],
|
||||
},
|
||||
agent: {
|
||||
perm: "createCodeCountryManager",
|
||||
list: [],
|
||||
},
|
||||
corporate: {
|
||||
perm: "createCodeCorporate",
|
||||
list: ["student", "teacher"],
|
||||
},
|
||||
mastercorporate: {
|
||||
perm: undefined,
|
||||
list: ["student", "teacher", "corporate"],
|
||||
},
|
||||
admin: {
|
||||
perm: "createCodeAdmin",
|
||||
list: ["student", "teacher", "agent", "corporate", "admin", "mastercorporate"],
|
||||
},
|
||||
developer: {
|
||||
perm: undefined,
|
||||
list: ["student", "teacher", "agent", "corporate", "admin", "developer", "mastercorporate"],
|
||||
},
|
||||
};
|
||||
|
||||
export default function CodeGenerator({ user }: { user: User }) {
|
||||
const [generatedCode, setGeneratedCode] = useState<string>();
|
||||
const [expiryDate, setExpiryDate] = useState<Date | null>(
|
||||
user?.subscriptionExpirationDate
|
||||
? moment(user.subscriptionExpirationDate).toDate()
|
||||
: null
|
||||
);
|
||||
const [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true);
|
||||
const [type, setType] = useState<Type>("student");
|
||||
export default function CodeGenerator({user}: {user: User}) {
|
||||
const [generatedCode, setGeneratedCode] = useState<string>();
|
||||
const [expiryDate, setExpiryDate] = useState<Date | null>(
|
||||
user?.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).toDate() : null,
|
||||
);
|
||||
const [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true);
|
||||
const [type, setType] = useState<Type>("student");
|
||||
const {permissions} = usePermissions(user?.id || "");
|
||||
|
||||
useEffect(() => {
|
||||
if (!isExpiryDateEnabled) setExpiryDate(null);
|
||||
}, [isExpiryDateEnabled]);
|
||||
useEffect(() => {
|
||||
if (!isExpiryDateEnabled) setExpiryDate(null);
|
||||
}, [isExpiryDateEnabled]);
|
||||
|
||||
const generateCode = (type: Type) => {
|
||||
const uid = new ShortUniqueId();
|
||||
const code = uid.randomUUID(6);
|
||||
const generateCode = (type: Type) => {
|
||||
const uid = new ShortUniqueId();
|
||||
const code = uid.randomUUID(6);
|
||||
|
||||
axios
|
||||
.post("/api/code", { type, codes: [code], expiryDate })
|
||||
.then(({ data, status }) => {
|
||||
if (data.ok) {
|
||||
toast.success(`Successfully generated a ${capitalize(type)} code!`, {
|
||||
toastId: "success",
|
||||
});
|
||||
setGeneratedCode(code);
|
||||
return;
|
||||
}
|
||||
axios
|
||||
.post("/api/code", {type, codes: [code], expiryDate})
|
||||
.then(({data, status}) => {
|
||||
if (data.ok) {
|
||||
toast.success(`Successfully generated a ${capitalize(type)} code!`, {
|
||||
toastId: "success",
|
||||
});
|
||||
setGeneratedCode(code);
|
||||
return;
|
||||
}
|
||||
|
||||
if (status === 403) {
|
||||
toast.error(data.reason, { toastId: "forbidden" });
|
||||
}
|
||||
})
|
||||
.catch(({ response: { status, data } }) => {
|
||||
if (status === 403) {
|
||||
toast.error(data.reason, { toastId: "forbidden" });
|
||||
return;
|
||||
}
|
||||
if (status === 403) {
|
||||
toast.error(data.reason, {toastId: "forbidden"});
|
||||
}
|
||||
})
|
||||
.catch(({response: {status, data}}) => {
|
||||
if (status === 403) {
|
||||
toast.error(data.reason, {toastId: "forbidden"});
|
||||
return;
|
||||
}
|
||||
|
||||
toast.error(`Something went wrong, please try again later!`, {
|
||||
toastId: "error",
|
||||
});
|
||||
});
|
||||
};
|
||||
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">
|
||||
User Code Generator
|
||||
</label>
|
||||
{user && (
|
||||
<select
|
||||
defaultValue="student"
|
||||
onChange={(e) => setType(e.target.value as typeof user.type)}
|
||||
className="p-6 w-full min-w-[350px] min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer bg-white"
|
||||
>
|
||||
{Object.keys(USER_TYPE_LABELS)
|
||||
.filter((x) => {
|
||||
const { list, perm } = USER_TYPE_PERMISSIONS[x as Type];
|
||||
return checkAccess(user, list, perm);
|
||||
})
|
||||
.map((type) => (
|
||||
<option key={type} value={type}>
|
||||
{USER_TYPE_LABELS[type as keyof typeof USER_TYPE_LABELS]}
|
||||
</option>
|
||||
))}
|
||||
</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>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Generated Code:
|
||||
</label>
|
||||
<div
|
||||
className={clsx(
|
||||
"p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
|
||||
"hover:border-mti-purple tooltip",
|
||||
"transition duration-300 ease-in-out"
|
||||
)}
|
||||
data-tip="Click to copy"
|
||||
onClick={() => {
|
||||
if (generatedCode) navigator.clipboard.writeText(generatedCode);
|
||||
}}
|
||||
>
|
||||
{generatedCode}
|
||||
</div>
|
||||
{generatedCode && (
|
||||
<span className="text-sm text-mti-gray-dim font-light">
|
||||
Give this code to the user to complete their registration
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
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">User Code Generator</label>
|
||||
{user && (
|
||||
<select
|
||||
defaultValue="student"
|
||||
onChange={(e) => setType(e.target.value as typeof user.type)}
|
||||
className="p-6 w-full min-w-[350px] min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer bg-white">
|
||||
{Object.keys(USER_TYPE_LABELS)
|
||||
.filter((x) => {
|
||||
const {list, perm} = USER_TYPE_PERMISSIONS[x as Type];
|
||||
return checkAccess(user, list, permissions, perm);
|
||||
})
|
||||
.map((type) => (
|
||||
<option key={type} value={type}>
|
||||
{USER_TYPE_LABELS[type as keyof typeof USER_TYPE_LABELS]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
{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"], permissions, "createCodes") && (
|
||||
<Button onClick={() => generateCode(type)} disabled={isExpiryDateEnabled ? !expiryDate : false}>
|
||||
Generate
|
||||
</Button>
|
||||
)}
|
||||
<label className="font-normal text-base text-mti-gray-dim">Generated Code:</label>
|
||||
<div
|
||||
className={clsx(
|
||||
"p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
|
||||
"hover:border-mti-purple tooltip",
|
||||
"transition duration-300 ease-in-out",
|
||||
)}
|
||||
data-tip="Click to copy"
|
||||
onClick={() => {
|
||||
if (generatedCode) navigator.clipboard.writeText(generatedCode);
|
||||
}}>
|
||||
{generatedCode}
|
||||
</div>
|
||||
{generatedCode && <span className="text-sm text-mti-gray-dim font-light">Give this code to the user to complete their registration</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,355 +4,306 @@ import Select from "@/components/Low/Select";
|
||||
import useCodes from "@/hooks/useCodes";
|
||||
import useUser from "@/hooks/useUser";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import { Code, User } from "@/interfaces/user";
|
||||
import { USER_TYPE_LABELS } from "@/resources/user";
|
||||
import {
|
||||
createColumnHelper,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
} from "@tanstack/react-table";
|
||||
import {Code, User} from "@/interfaces/user";
|
||||
import {USER_TYPE_LABELS} from "@/resources/user";
|
||||
import {createColumnHelper, flexRender, getCoreRowModel, useReactTable} from "@tanstack/react-table";
|
||||
import axios from "axios";
|
||||
import moment from "moment";
|
||||
import { useEffect, useState, useMemo } from "react";
|
||||
import { BsTrash } from "react-icons/bs";
|
||||
import { toast } from "react-toastify";
|
||||
import {useEffect, useState, useMemo} from "react";
|
||||
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";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
|
||||
const columnHelper = createColumnHelper<Code>();
|
||||
|
||||
const CreatorCell = ({ id, users }: { id: string; users: User[] }) => {
|
||||
const [creatorUser, setCreatorUser] = useState<User>();
|
||||
const CreatorCell = ({id, users}: {id: string; users: User[]}) => {
|
||||
const [creatorUser, setCreatorUser] = useState<User>();
|
||||
|
||||
useEffect(() => {
|
||||
setCreatorUser(users.find((x) => x.id === id));
|
||||
}, [id, users]);
|
||||
useEffect(() => {
|
||||
setCreatorUser(users.find((x) => x.id === id));
|
||||
}, [id, users]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{(creatorUser?.type === "corporate"
|
||||
? creatorUser?.corporateInformation?.companyInformation?.name
|
||||
: creatorUser?.name || "N/A") || "N/A"}{" "}
|
||||
{creatorUser && `(${USER_TYPE_LABELS[creatorUser.type]})`}
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
{(creatorUser?.type === "corporate" ? creatorUser?.corporateInformation?.companyInformation?.name : creatorUser?.name || "N/A") || "N/A"}{" "}
|
||||
{creatorUser && `(${USER_TYPE_LABELS[creatorUser.type]})`}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default function CodeList({ user }: { user: User }) {
|
||||
const [selectedCodes, setSelectedCodes] = useState<string[]>([]);
|
||||
export default function CodeList({user}: {user: User}) {
|
||||
const [selectedCodes, setSelectedCodes] = useState<string[]>([]);
|
||||
|
||||
const [filteredCorporate, setFilteredCorporate] = useState<User | undefined>(
|
||||
user?.type === "corporate" ? user : undefined
|
||||
);
|
||||
const [filterAvailability, setFilterAvailability] = useState<
|
||||
"in-use" | "unused"
|
||||
>();
|
||||
const [filteredCorporate, setFilteredCorporate] = useState<User | undefined>(user?.type === "corporate" ? user : undefined);
|
||||
const [filterAvailability, setFilterAvailability] = useState<"in-use" | "unused">();
|
||||
|
||||
// const [filteredCodes, setFilteredCodes] = useState<Code[]>([]);
|
||||
const {permissions} = usePermissions(user?.id || "");
|
||||
|
||||
const { users } = useUsers();
|
||||
const { codes, reload } = useCodes(
|
||||
user?.type === "corporate" ? user?.id : undefined
|
||||
);
|
||||
// const [filteredCodes, setFilteredCodes] = useState<Code[]>([]);
|
||||
|
||||
const [startDate, setStartDate] = useState<Date | null>(moment("01/01/2023").toDate());
|
||||
const {users} = useUsers();
|
||||
const {codes, reload} = useCodes(user?.type === "corporate" ? user?.id : undefined);
|
||||
|
||||
const [startDate, setStartDate] = useState<Date | null>(moment("01/01/2023").toDate());
|
||||
const [endDate, setEndDate] = useState<Date | null>(moment().endOf("day").toDate());
|
||||
const filteredCodes = useMemo(() => {
|
||||
return codes.filter((x) => {
|
||||
// TODO: if the expiry date is missing, it does not make sense to filter by date
|
||||
// so we need to find a way to handle this edge case
|
||||
if(startDate && endDate && x.expiryDate) {
|
||||
const date = moment(x.expiryDate);
|
||||
if(date.isBefore(startDate) || date.isAfter(endDate)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (filteredCorporate && x.creator !== filteredCorporate.id) return false;
|
||||
if (filterAvailability) {
|
||||
if (filterAvailability === "in-use" && !x.userId) return false;
|
||||
if (filterAvailability === "unused" && x.userId) return false;
|
||||
}
|
||||
const filteredCodes = useMemo(() => {
|
||||
return codes.filter((x) => {
|
||||
// TODO: if the expiry date is missing, it does not make sense to filter by date
|
||||
// so we need to find a way to handle this edge case
|
||||
if (startDate && endDate && x.expiryDate) {
|
||||
const date = moment(x.expiryDate);
|
||||
if (date.isBefore(startDate) || date.isAfter(endDate)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (filteredCorporate && x.creator !== filteredCorporate.id) return false;
|
||||
if (filterAvailability) {
|
||||
if (filterAvailability === "in-use" && !x.userId) return false;
|
||||
if (filterAvailability === "unused" && x.userId) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}, [codes, startDate, endDate, filteredCorporate, filterAvailability]);
|
||||
return true;
|
||||
});
|
||||
}, [codes, startDate, endDate, filteredCorporate, filterAvailability]);
|
||||
|
||||
const toggleCode = (id: string) => {
|
||||
setSelectedCodes((prev) =>
|
||||
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
|
||||
);
|
||||
};
|
||||
const toggleCode = (id: string) => {
|
||||
setSelectedCodes((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
|
||||
};
|
||||
|
||||
const toggleAllCodes = (checked: boolean) => {
|
||||
if (checked)
|
||||
return setSelectedCodes(
|
||||
filteredCodes.filter((x) => !x.userId).map((x) => x.code)
|
||||
);
|
||||
const toggleAllCodes = (checked: boolean) => {
|
||||
if (checked) return setSelectedCodes(filteredCodes.filter((x) => !x.userId).map((x) => x.code));
|
||||
|
||||
return setSelectedCodes([]);
|
||||
};
|
||||
return setSelectedCodes([]);
|
||||
};
|
||||
|
||||
const deleteCodes = async (codes: string[]) => {
|
||||
if (
|
||||
!confirm(`Are you sure you want to delete these ${codes.length} code(s)?`)
|
||||
)
|
||||
return;
|
||||
const deleteCodes = async (codes: string[]) => {
|
||||
if (!confirm(`Are you sure you want to delete these ${codes.length} code(s)?`)) return;
|
||||
|
||||
const params = new URLSearchParams();
|
||||
codes.forEach((code) => params.append("code", code));
|
||||
const params = new URLSearchParams();
|
||||
codes.forEach((code) => params.append("code", code));
|
||||
|
||||
axios
|
||||
.delete(`/api/code?${params.toString()}`)
|
||||
.then(() => {
|
||||
toast.success(`Deleted the codes!`);
|
||||
setSelectedCodes([]);
|
||||
})
|
||||
.catch((reason) => {
|
||||
if (reason.response.status === 404) {
|
||||
toast.error("Code not found!");
|
||||
return;
|
||||
}
|
||||
axios
|
||||
.delete(`/api/code?${params.toString()}`)
|
||||
.then(() => {
|
||||
toast.success(`Deleted the codes!`);
|
||||
setSelectedCodes([]);
|
||||
})
|
||||
.catch((reason) => {
|
||||
if (reason.response.status === 404) {
|
||||
toast.error("Code not found!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (reason.response.status === 403) {
|
||||
toast.error("You do not have permission to delete this code!");
|
||||
return;
|
||||
}
|
||||
if (reason.response.status === 403) {
|
||||
toast.error("You do not have permission to delete this code!");
|
||||
return;
|
||||
}
|
||||
|
||||
toast.error("Something went wrong, please try again later.");
|
||||
})
|
||||
.finally(reload);
|
||||
};
|
||||
toast.error("Something went wrong, please try again later.");
|
||||
})
|
||||
.finally(reload);
|
||||
};
|
||||
|
||||
const deleteCode = async (code: Code) => {
|
||||
if (!confirm(`Are you sure you want to delete this "${code.code}" code?`))
|
||||
return;
|
||||
const deleteCode = async (code: Code) => {
|
||||
if (!confirm(`Are you sure you want to delete this "${code.code}" code?`)) return;
|
||||
|
||||
axios
|
||||
.delete(`/api/code/${code.code}`)
|
||||
.then(() => toast.success(`Deleted the "${code.code}" exam`))
|
||||
.catch((reason) => {
|
||||
if (reason.response.status === 404) {
|
||||
toast.error("Code not found!");
|
||||
return;
|
||||
}
|
||||
axios
|
||||
.delete(`/api/code/${code.code}`)
|
||||
.then(() => toast.success(`Deleted the "${code.code}" exam`))
|
||||
.catch((reason) => {
|
||||
if (reason.response.status === 404) {
|
||||
toast.error("Code not found!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (reason.response.status === 403) {
|
||||
toast.error("You do not have permission to delete this code!");
|
||||
return;
|
||||
}
|
||||
if (reason.response.status === 403) {
|
||||
toast.error("You do not have permission to delete this code!");
|
||||
return;
|
||||
}
|
||||
|
||||
toast.error("Something went wrong, please try again later.");
|
||||
})
|
||||
.finally(reload);
|
||||
};
|
||||
toast.error("Something went wrong, please try again later.");
|
||||
})
|
||||
.finally(reload);
|
||||
};
|
||||
|
||||
const defaultColumns = [
|
||||
columnHelper.accessor("code", {
|
||||
id: "codeCheckbox",
|
||||
header: () => (
|
||||
<Checkbox
|
||||
disabled={filteredCodes.filter((x) => !x.userId).length === 0}
|
||||
isChecked={
|
||||
selectedCodes.length ===
|
||||
filteredCodes.filter((x) => !x.userId).length &&
|
||||
filteredCodes.filter((x) => !x.userId).length > 0
|
||||
}
|
||||
onChange={(checked) => toggleAllCodes(checked)}
|
||||
>
|
||||
{""}
|
||||
</Checkbox>
|
||||
),
|
||||
cell: (info) =>
|
||||
!info.row.original.userId ? (
|
||||
<Checkbox
|
||||
isChecked={selectedCodes.includes(info.getValue())}
|
||||
onChange={() => toggleCode(info.getValue())}
|
||||
>
|
||||
{""}
|
||||
</Checkbox>
|
||||
) : null,
|
||||
}),
|
||||
columnHelper.accessor("code", {
|
||||
header: "Code",
|
||||
cell: (info) => info.getValue(),
|
||||
}),
|
||||
columnHelper.accessor("creationDate", {
|
||||
header: "Creation Date",
|
||||
cell: (info) =>
|
||||
info.getValue() ? moment(info.getValue()).format("DD/MM/YYYY") : "N/A",
|
||||
}),
|
||||
columnHelper.accessor("email", {
|
||||
header: "Invited E-mail",
|
||||
cell: (info) => info.getValue() || "N/A",
|
||||
}),
|
||||
columnHelper.accessor("creator", {
|
||||
header: "Creator",
|
||||
cell: (info) => <CreatorCell id={info.getValue()} users={users} />,
|
||||
}),
|
||||
columnHelper.accessor("userId", {
|
||||
header: "Availability",
|
||||
cell: (info) =>
|
||||
info.getValue() ? (
|
||||
<span className="flex gap-1 items-center text-mti-green">
|
||||
<div className="w-2 h-2 rounded-full bg-mti-green" /> In Use
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex gap-1 items-center text-mti-red">
|
||||
<div className="w-2 h-2 rounded-full bg-mti-red" /> Unused
|
||||
</span>
|
||||
),
|
||||
}),
|
||||
{
|
||||
header: "",
|
||||
id: "actions",
|
||||
cell: ({ row }: { row: { original: Code } }) => {
|
||||
return (
|
||||
<div className="flex gap-4">
|
||||
{!row.original.userId && (
|
||||
<div
|
||||
data-tip="Delete"
|
||||
className="cursor-pointer tooltip"
|
||||
onClick={() => deleteCode(row.original)}
|
||||
>
|
||||
<BsTrash className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
const allowedToDelete = checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"], permissions, "deleteCodes");
|
||||
|
||||
const table = useReactTable({
|
||||
data: filteredCodes,
|
||||
columns: defaultColumns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
const defaultColumns = [
|
||||
columnHelper.accessor("code", {
|
||||
id: "codeCheckbox",
|
||||
header: () => (
|
||||
<Checkbox
|
||||
disabled={filteredCodes.filter((x) => !x.userId).length === 0}
|
||||
isChecked={
|
||||
selectedCodes.length === filteredCodes.filter((x) => !x.userId).length && filteredCodes.filter((x) => !x.userId).length > 0
|
||||
}
|
||||
onChange={(checked) => toggleAllCodes(checked)}>
|
||||
{""}
|
||||
</Checkbox>
|
||||
),
|
||||
cell: (info) =>
|
||||
!info.row.original.userId ? (
|
||||
<Checkbox isChecked={selectedCodes.includes(info.getValue())} onChange={() => toggleCode(info.getValue())}>
|
||||
{""}
|
||||
</Checkbox>
|
||||
) : null,
|
||||
}),
|
||||
columnHelper.accessor("code", {
|
||||
header: "Code",
|
||||
cell: (info) => info.getValue(),
|
||||
}),
|
||||
columnHelper.accessor("creationDate", {
|
||||
header: "Creation Date",
|
||||
cell: (info) => (info.getValue() ? moment(info.getValue()).format("DD/MM/YYYY") : "N/A"),
|
||||
}),
|
||||
columnHelper.accessor("email", {
|
||||
header: "Invited E-mail",
|
||||
cell: (info) => info.getValue() || "N/A",
|
||||
}),
|
||||
columnHelper.accessor("creator", {
|
||||
header: "Creator",
|
||||
cell: (info) => <CreatorCell id={info.getValue()} users={users} />,
|
||||
}),
|
||||
columnHelper.accessor("userId", {
|
||||
header: "Availability",
|
||||
cell: (info) =>
|
||||
info.getValue() ? (
|
||||
<span className="flex gap-1 items-center text-mti-green">
|
||||
<div className="w-2 h-2 rounded-full bg-mti-green" /> In Use
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex gap-1 items-center text-mti-red">
|
||||
<div className="w-2 h-2 rounded-full bg-mti-red" /> Unused
|
||||
</span>
|
||||
),
|
||||
}),
|
||||
{
|
||||
header: "",
|
||||
id: "actions",
|
||||
cell: ({row}: {row: {original: Code}}) => {
|
||||
return (
|
||||
<div className="flex gap-4">
|
||||
{allowedToDelete && !row.original.userId && (
|
||||
<div data-tip="Delete" className="cursor-pointer tooltip" onClick={() => deleteCode(row.original)}>
|
||||
<BsTrash className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between pb-4 pt-1">
|
||||
<div className="flex items-center gap-4">
|
||||
<Select
|
||||
className="!w-96 !py-1"
|
||||
disabled={user?.type === "corporate"}
|
||||
isClearable
|
||||
placeholder="Corporate"
|
||||
value={
|
||||
filteredCorporate
|
||||
? {
|
||||
label: `${
|
||||
filteredCorporate.type === "corporate"
|
||||
? filteredCorporate.corporateInformation
|
||||
?.companyInformation?.name || filteredCorporate.name
|
||||
: filteredCorporate.name
|
||||
} (${USER_TYPE_LABELS[filteredCorporate.type]})`,
|
||||
value: filteredCorporate.id,
|
||||
}
|
||||
: null
|
||||
}
|
||||
options={users
|
||||
.filter((x) =>
|
||||
["admin", "developer", "corporate"].includes(x.type)
|
||||
)
|
||||
.map((x) => ({
|
||||
label: `${
|
||||
x.type === "corporate"
|
||||
? x.corporateInformation?.companyInformation?.name || x.name
|
||||
: x.name
|
||||
} (${USER_TYPE_LABELS[x.type]})`,
|
||||
value: x.id,
|
||||
user: x,
|
||||
}))}
|
||||
onChange={(value) =>
|
||||
setFilteredCorporate(
|
||||
value ? users.find((x) => x.id === value?.value) : undefined
|
||||
)
|
||||
}
|
||||
/>
|
||||
<Select
|
||||
className="!w-96 !py-1"
|
||||
placeholder="Availability"
|
||||
isClearable
|
||||
options={[
|
||||
{ label: "In Use", value: "in-use" },
|
||||
{ label: "Unused", value: "unused" },
|
||||
]}
|
||||
onChange={(value) =>
|
||||
setFilterAvailability(
|
||||
value ? (value.value as typeof filterAvailability) : undefined
|
||||
)
|
||||
}
|
||||
/>
|
||||
<ReactDatePicker
|
||||
dateFormat="dd/MM/yyyy"
|
||||
className="px-4 py-6 w-full text-sm text-center font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none"
|
||||
selected={startDate}
|
||||
startDate={startDate}
|
||||
endDate={endDate}
|
||||
selectsRange
|
||||
showMonthDropdown
|
||||
filterDate={(date: Date) =>
|
||||
moment(date).isSameOrBefore(moment(new Date()))
|
||||
}
|
||||
onChange={([initialDate, finalDate]: [Date, Date]) => {
|
||||
setStartDate(initialDate ?? moment("01/01/2023").toDate());
|
||||
if (finalDate) {
|
||||
// basicly selecting a final day works as if I'm selecting the first
|
||||
// minute of that day. this way it covers the whole day
|
||||
setEndDate(moment(finalDate).endOf("day").toDate());
|
||||
return;
|
||||
}
|
||||
setEndDate(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-4 items-center">
|
||||
<span>{selectedCodes.length} code(s) selected</span>
|
||||
<Button
|
||||
disabled={selectedCodes.length === 0}
|
||||
variant="outline"
|
||||
color="red"
|
||||
className="!py-1 px-10"
|
||||
onClick={() => deleteCodes(selectedCodes)}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<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>
|
||||
</>
|
||||
);
|
||||
const table = useReactTable({
|
||||
data: filteredCodes,
|
||||
columns: defaultColumns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between pb-4 pt-1">
|
||||
<div className="flex items-center gap-4">
|
||||
<Select
|
||||
className="!w-96 !py-1"
|
||||
disabled={user?.type === "corporate"}
|
||||
isClearable
|
||||
placeholder="Corporate"
|
||||
value={
|
||||
filteredCorporate
|
||||
? {
|
||||
label: `${
|
||||
filteredCorporate.type === "corporate"
|
||||
? filteredCorporate.corporateInformation?.companyInformation?.name || filteredCorporate.name
|
||||
: filteredCorporate.name
|
||||
} (${USER_TYPE_LABELS[filteredCorporate.type]})`,
|
||||
value: filteredCorporate.id,
|
||||
}
|
||||
: null
|
||||
}
|
||||
options={users
|
||||
.filter((x) => ["admin", "developer", "corporate"].includes(x.type))
|
||||
.map((x) => ({
|
||||
label: `${x.type === "corporate" ? x.corporateInformation?.companyInformation?.name || x.name : x.name} (${
|
||||
USER_TYPE_LABELS[x.type]
|
||||
})`,
|
||||
value: x.id,
|
||||
user: x,
|
||||
}))}
|
||||
onChange={(value) => setFilteredCorporate(value ? users.find((x) => x.id === value?.value) : undefined)}
|
||||
/>
|
||||
<Select
|
||||
className="!w-96 !py-1"
|
||||
placeholder="Availability"
|
||||
isClearable
|
||||
options={[
|
||||
{label: "In Use", value: "in-use"},
|
||||
{label: "Unused", value: "unused"},
|
||||
]}
|
||||
onChange={(value) => setFilterAvailability(value ? (value.value as typeof filterAvailability) : undefined)}
|
||||
/>
|
||||
<ReactDatePicker
|
||||
dateFormat="dd/MM/yyyy"
|
||||
className="px-4 py-6 w-full text-sm text-center font-normal placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim disabled:cursor-not-allowed rounded-full border border-mti-gray-platinum focus:outline-none"
|
||||
selected={startDate}
|
||||
startDate={startDate}
|
||||
endDate={endDate}
|
||||
selectsRange
|
||||
showMonthDropdown
|
||||
filterDate={(date: Date) => moment(date).isSameOrBefore(moment(new Date()))}
|
||||
onChange={([initialDate, finalDate]: [Date, Date]) => {
|
||||
setStartDate(initialDate ?? moment("01/01/2023").toDate());
|
||||
if (finalDate) {
|
||||
// basicly selecting a final day works as if I'm selecting the first
|
||||
// minute of that day. this way it covers the whole day
|
||||
setEndDate(moment(finalDate).endOf("day").toDate());
|
||||
return;
|
||||
}
|
||||
setEndDate(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{allowedToDelete && (
|
||||
<div className="flex gap-4 items-center">
|
||||
<span>{selectedCodes.length} code(s) selected</span>
|
||||
<Button
|
||||
disabled={selectedCodes.length === 0}
|
||||
variant="outline"
|
||||
color="red"
|
||||
className="!py-1 px-10"
|
||||
onClick={() => deleteCodes(selectedCodes)}>
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,29 +14,31 @@ import {toast} from "react-toastify";
|
||||
import readXlsxFile from "read-excel-file";
|
||||
import {useFilePicker} from "use-file-picker";
|
||||
import {getUserCorporate} from "@/utils/groups";
|
||||
import { isAgentUser, isCorporateUser } from "@/resources/user";
|
||||
import {isAgentUser, isCorporateUser} from "@/resources/user";
|
||||
import {checkAccess} from "@/utils/permissions";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
|
||||
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 LinkedCorporate = ({userId, users, groups}: {userId: string, users: User[], groups: Group[]}) => {
|
||||
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)
|
||||
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]);
|
||||
|
||||
return isLoading ? <span className="animate-pulse">Loading...</span> : <>{companyName}</>;
|
||||
@@ -196,11 +198,13 @@ export default function GroupList({user}: {user: User}) {
|
||||
const [editingGroup, setEditingGroup] = useState<Group>();
|
||||
const [filterByUser, setFilterByUser] = useState(false);
|
||||
|
||||
const {permissions} = usePermissions(user?.id || "");
|
||||
|
||||
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))) {
|
||||
if (user && ["corporate", "teacher", "mastercorporate"].includes(user.type)) {
|
||||
setFilterByUser(true);
|
||||
}
|
||||
}, [user]);
|
||||
@@ -250,14 +254,14 @@ export default function GroupList({user}: {user: User}) {
|
||||
cell: ({row}: {row: {original: Group}}) => {
|
||||
return (
|
||||
<>
|
||||
{user && (user.type === "developer" || user.type === "admin" || user.id === row.original.admin) && (
|
||||
{user && (checkAccess(user, ["developer", "admin"]) || user.id === row.original.admin) && (
|
||||
<div className="flex gap-2">
|
||||
{(!row.original.disableEditing || ["developer", "admin"].includes(user.type)) && (
|
||||
{(!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 || ["developer", "admin"].includes(user.type)) && (
|
||||
{(!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>
|
||||
@@ -327,11 +331,13 @@ export default function GroupList({user}: {user: User}) {
|
||||
</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>
|
||||
{checkAccess(user, ["teacher", "corporate", "mastercorporate", "admin", "developer"], permissions, "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>
|
||||
);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,5 @@
|
||||
import { User } from "@/interfaces/user";
|
||||
import { Tab } from "@headlessui/react";
|
||||
import {User} from "@/interfaces/user";
|
||||
import {Tab} from "@headlessui/react";
|
||||
import clsx from "clsx";
|
||||
import CodeList from "./CodeList";
|
||||
import DiscountList from "./DiscountList";
|
||||
@@ -7,132 +7,118 @@ import ExamList from "./ExamList";
|
||||
import GroupList from "./GroupList";
|
||||
import PackageList from "./PackageList";
|
||||
import UserList from "./UserList";
|
||||
import {checkAccess} from "@/utils/permissions";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
|
||||
export default function Lists({ user }: { user: User }) {
|
||||
return (
|
||||
<Tab.Group>
|
||||
<Tab.List className="flex space-x-1 rounded-xl bg-mti-purple-ultralight/40 p-1">
|
||||
<Tab
|
||||
className={({ selected }) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-mti-purple-light",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-mti-purple-light focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected
|
||||
? "bg-white shadow"
|
||||
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
|
||||
)
|
||||
}
|
||||
>
|
||||
User List
|
||||
</Tab>
|
||||
{user?.type === "developer" && (
|
||||
<Tab
|
||||
className={({ selected }) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-mti-purple-light",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-mti-purple-light focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected
|
||||
? "bg-white shadow"
|
||||
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
|
||||
)
|
||||
}
|
||||
>
|
||||
Exam List
|
||||
</Tab>
|
||||
)}
|
||||
<Tab
|
||||
className={({ selected }) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-mti-purple-light",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-mti-purple-light focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected
|
||||
? "bg-white shadow"
|
||||
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
|
||||
)
|
||||
}
|
||||
>
|
||||
Group List
|
||||
</Tab>
|
||||
{user && ["developer", "admin", "corporate"].includes(user.type) && (
|
||||
<Tab
|
||||
className={({ selected }) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-mti-purple-light",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-mti-purple-light focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected
|
||||
? "bg-white shadow"
|
||||
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
|
||||
)
|
||||
}
|
||||
>
|
||||
Code List
|
||||
</Tab>
|
||||
)}
|
||||
{user && ["developer", "admin"].includes(user.type) && (
|
||||
<Tab
|
||||
className={({ selected }) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-mti-purple-light",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-mti-purple-light focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected
|
||||
? "bg-white shadow"
|
||||
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
|
||||
)
|
||||
}
|
||||
>
|
||||
Package List
|
||||
</Tab>
|
||||
)}
|
||||
{user && ["developer", "admin"].includes(user.type) && (
|
||||
<Tab
|
||||
className={({ selected }) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-mti-purple-light",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-mti-purple-light focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected
|
||||
? "bg-white shadow"
|
||||
: "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
|
||||
)
|
||||
}
|
||||
>
|
||||
Discount List
|
||||
</Tab>
|
||||
)}
|
||||
</Tab.List>
|
||||
<Tab.Panels className="mt-2">
|
||||
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
|
||||
<UserList user={user} />
|
||||
</Tab.Panel>
|
||||
{user?.type === "developer" && (
|
||||
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
|
||||
<ExamList user={user} />
|
||||
</Tab.Panel>
|
||||
)}
|
||||
<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) && (
|
||||
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
|
||||
<CodeList user={user} />
|
||||
</Tab.Panel>
|
||||
)}
|
||||
{user && ["developer", "admin"].includes(user.type) && (
|
||||
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
|
||||
<PackageList user={user} />
|
||||
</Tab.Panel>
|
||||
)}
|
||||
{user && ["developer", "admin"].includes(user.type) && (
|
||||
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
|
||||
<DiscountList user={user} />
|
||||
</Tab.Panel>
|
||||
)}
|
||||
</Tab.Panels>
|
||||
</Tab.Group>
|
||||
);
|
||||
export default function Lists({user}: {user: User}) {
|
||||
const {permissions} = usePermissions(user?.id || "");
|
||||
|
||||
return (
|
||||
<Tab.Group>
|
||||
<Tab.List className="flex space-x-1 rounded-xl bg-mti-purple-ultralight/40 p-1">
|
||||
<Tab
|
||||
className={({selected}) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-mti-purple-light",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-mti-purple-light focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
|
||||
)
|
||||
}>
|
||||
User List
|
||||
</Tab>
|
||||
{checkAccess(user, ["developer"]) && (
|
||||
<Tab
|
||||
className={({selected}) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-mti-purple-light",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-mti-purple-light focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
|
||||
)
|
||||
}>
|
||||
Exam List
|
||||
</Tab>
|
||||
)}
|
||||
<Tab
|
||||
className={({selected}) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-mti-purple-light",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-mti-purple-light focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
|
||||
)
|
||||
}>
|
||||
Group List
|
||||
</Tab>
|
||||
{checkAccess(user, ["developer", "admin", "corporate"]) && (
|
||||
<Tab
|
||||
className={({selected}) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-mti-purple-light",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-mti-purple-light focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
|
||||
)
|
||||
}>
|
||||
Code List
|
||||
</Tab>
|
||||
)}
|
||||
{checkAccess(user, ["developer", "admin"]) && (
|
||||
<Tab
|
||||
className={({selected}) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-mti-purple-light",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-mti-purple-light focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
|
||||
)
|
||||
}>
|
||||
Package List
|
||||
</Tab>
|
||||
)}
|
||||
{checkAccess(user, ["developer", "admin"]) && (
|
||||
<Tab
|
||||
className={({selected}) =>
|
||||
clsx(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-mti-purple-light",
|
||||
"ring-white ring-opacity-60 ring-offset-2 ring-offset-mti-purple-light focus:outline-none focus:ring-2",
|
||||
"transition duration-300 ease-in-out",
|
||||
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-mti-purple-dark",
|
||||
)
|
||||
}>
|
||||
Discount List
|
||||
</Tab>
|
||||
)}
|
||||
</Tab.List>
|
||||
<Tab.Panels className="mt-2">
|
||||
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
|
||||
<UserList user={user} />
|
||||
</Tab.Panel>
|
||||
{checkAccess(user, ["developer"]) && (
|
||||
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
|
||||
<ExamList user={user} />
|
||||
</Tab.Panel>
|
||||
)}
|
||||
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
|
||||
<GroupList user={user} />
|
||||
</Tab.Panel>
|
||||
{checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"], permissions, "viewCodes") && (
|
||||
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
|
||||
<CodeList user={user} />
|
||||
</Tab.Panel>
|
||||
)}
|
||||
{checkAccess(user, ["developer", "admin"]) && (
|
||||
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
|
||||
<PackageList user={user} />
|
||||
</Tab.Panel>
|
||||
)}
|
||||
{checkAccess(user, ["developer", "admin"]) && (
|
||||
<Tab.Panel className="overflow-y-scroll max-h-[600px] rounded-xl scrollbar-hide">
|
||||
<DiscountList user={user} />
|
||||
</Tab.Panel>
|
||||
)}
|
||||
</Tab.Panels>
|
||||
</Tab.Group>
|
||||
);
|
||||
}
|
||||
|
||||
40
src/pages/api/assignments/corporate.ts
Normal file
40
src/pages/api/assignments/corporate.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
import type {NextApiRequest, NextApiResponse} from "next";
|
||||
import {app} from "@/firebase";
|
||||
import {getFirestore, collection, getDocs, query, where, setDoc, doc, getDoc} from "firebase/firestore";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {uuidv4} from "@firebase/util";
|
||||
import {Module} from "@/interfaces";
|
||||
import {getExams} from "@/utils/exams.be";
|
||||
import {Exam, InstructorGender, Variant} from "@/interfaces/exam";
|
||||
import {capitalize, flatten, uniqBy} from "lodash";
|
||||
import {User} from "@/interfaces/user";
|
||||
import moment from "moment";
|
||||
import {sendEmail} from "@/email";
|
||||
import {getAllAssignersByCorporate} from "@/utils/groups.be";
|
||||
import {getAssignmentsByAssigners} from "@/utils/assignments.be";
|
||||
|
||||
const db = getFirestore(app);
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ok: false});
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === "GET") return GET(req, res);
|
||||
|
||||
res.status(404).json({ok: false});
|
||||
}
|
||||
|
||||
async function GET(req: NextApiRequest, res: NextApiResponse) {
|
||||
const {id} = req.query as {id: string};
|
||||
|
||||
const assigners = await getAllAssignersByCorporate(id);
|
||||
const assignments = await getAssignmentsByAssigners([...assigners, id]);
|
||||
|
||||
res.status(200).json(assignments);
|
||||
}
|
||||
@@ -1,71 +1,89 @@
|
||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
import type {NextApiRequest, NextApiResponse} from "next";
|
||||
import {app} from "@/firebase";
|
||||
import {getFirestore, setDoc, doc, runTransaction, collection, query, where, getDocs} from "firebase/firestore";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {Exam, InstructorGender, Variant} from "@/interfaces/exam";
|
||||
import {getExams} from "@/utils/exams.be";
|
||||
import {Module} from "@/interfaces";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { app } from "@/firebase";
|
||||
import {
|
||||
getFirestore,
|
||||
setDoc,
|
||||
doc,
|
||||
runTransaction,
|
||||
collection,
|
||||
query,
|
||||
where,
|
||||
getDocs,
|
||||
} from "firebase/firestore";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { Exam, InstructorGender, Variant } from "@/interfaces/exam";
|
||||
import { getExams } from "@/utils/exams.be";
|
||||
import { Module } from "@/interfaces";
|
||||
const db = getFirestore(app);
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "GET") return await GET(req, res);
|
||||
if (req.method === "POST") return await POST(req, res);
|
||||
if (req.method === "GET") return await GET(req, res);
|
||||
if (req.method === "POST") return await POST(req, res);
|
||||
|
||||
res.status(404).json({ok: false});
|
||||
res.status(404).json({ ok: false });
|
||||
}
|
||||
|
||||
async function GET(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ok: false});
|
||||
return;
|
||||
}
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
|
||||
const {module, avoidRepeated, variant, instructorGender} = req.query as {
|
||||
module: Module;
|
||||
avoidRepeated: string;
|
||||
variant?: Variant;
|
||||
instructorGender?: InstructorGender;
|
||||
};
|
||||
const { module, avoidRepeated, variant, instructorGender } = req.query as {
|
||||
module: Module;
|
||||
avoidRepeated: string;
|
||||
variant?: Variant;
|
||||
instructorGender?: InstructorGender;
|
||||
};
|
||||
|
||||
const exams: Exam[] = await getExams(db, module, avoidRepeated, req.session.user.id, variant, instructorGender);
|
||||
res.status(200).json(exams);
|
||||
const exams: Exam[] = await getExams(
|
||||
db,
|
||||
module,
|
||||
avoidRepeated,
|
||||
req.session.user.id,
|
||||
variant,
|
||||
instructorGender
|
||||
);
|
||||
res.status(200).json(exams);
|
||||
}
|
||||
|
||||
async function POST(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ok: false});
|
||||
return;
|
||||
}
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.session.user.type !== "developer") {
|
||||
res.status(403).json({ok: false});
|
||||
return;
|
||||
}
|
||||
const {module} = req.query as {module: string};
|
||||
if (req.session.user.type !== "developer") {
|
||||
res.status(403).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
const { module } = req.query as { module: string };
|
||||
|
||||
|
||||
try {
|
||||
const exam = {...req.body, module: module};
|
||||
await runTransaction(db, async (transaction) => {
|
||||
try {
|
||||
const exam = {
|
||||
...req.body,
|
||||
module: module,
|
||||
createdBy: req.session.user.id,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
await runTransaction(db, async (transaction) => {
|
||||
const docRef = doc(db, module, req.body.id);
|
||||
const docSnap = await transaction.get(docRef);
|
||||
|
||||
const docRef = doc(db, module, req.body.id);
|
||||
const docSnap = await transaction.get(docRef);
|
||||
|
||||
if (docSnap.exists()) {
|
||||
throw new Error('Name already exists');
|
||||
}
|
||||
if (docSnap.exists()) {
|
||||
throw new Error("Name already exists");
|
||||
}
|
||||
|
||||
|
||||
const newDocRef = doc(db, module, req.body.id);
|
||||
transaction.set(newDocRef, exam);
|
||||
});
|
||||
res.status(200).json(exam);
|
||||
} catch (error) {
|
||||
console.error("Transaction failed: ", error);
|
||||
res.status(500).json({ok: false, error: (error as any).message});
|
||||
}
|
||||
const newDocRef = doc(db, module, req.body.id);
|
||||
transaction.set(newDocRef, exam);
|
||||
});
|
||||
res.status(200).json(exam);
|
||||
} catch (error) {
|
||||
console.error("Transaction failed: ", error);
|
||||
res.status(500).json({ ok: false, error: (error as any).message });
|
||||
}
|
||||
}
|
||||
|
||||
129
src/pages/api/make_user.ts
Normal file
129
src/pages/api/make_user.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
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, expiryDate} = req.body as {
|
||||
email: string;
|
||||
passport_id: string;
|
||||
type: string;
|
||||
groupName: string;
|
||||
expiryDate: null | Date;
|
||||
};
|
||||
// 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,
|
||||
subscriptionExpirationDate: expiryDate || null,
|
||||
};
|
||||
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});
|
||||
}
|
||||
@@ -1,30 +1,46 @@
|
||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { app } from "@/firebase";
|
||||
import { getFirestore, doc, setDoc } from "firebase/firestore";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import type {NextApiRequest, NextApiResponse} from "next";
|
||||
import {app} from "@/firebase";
|
||||
import {getFirestore, doc, setDoc, getDoc} from "firebase/firestore";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {getPermissionDoc} from "@/utils/permissions.be";
|
||||
|
||||
const db = getFirestore(app);
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "PATCH") return patch(req, res);
|
||||
if (req.method === "PATCH") return patch(req, res);
|
||||
if (req.method === "GET") return get(req, res);
|
||||
}
|
||||
|
||||
async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ok: false});
|
||||
return;
|
||||
}
|
||||
|
||||
const {id} = req.query as {id: string};
|
||||
|
||||
const permissionDoc = await getPermissionDoc(id);
|
||||
return res.status(200).json({allowed: permissionDoc.users.includes(req.session.user.id)});
|
||||
}
|
||||
|
||||
async function patch(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
const { id } = req.query as { id: string };
|
||||
const { users } = req.body;
|
||||
try {
|
||||
await setDoc(doc(db, "permissions", id), { users }, { merge: true });
|
||||
return res.status(200).json({ ok: true });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
return res.status(500).json({ ok: false });
|
||||
}
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ok: false});
|
||||
return;
|
||||
}
|
||||
|
||||
const {id} = req.query as {id: string};
|
||||
const {users} = req.body;
|
||||
|
||||
try {
|
||||
await setDoc(doc(db, "permissions", id), {users}, {merge: true});
|
||||
return res.status(200).json({ok: true});
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
return res.status(500).json({ok: false});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,10 @@ async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
// based on the admin of each group, verify if it exists and it's of type corporate
|
||||
const groupsAdmins = [...new Set(groups.map((g) => g.admin).filter((id) => id))];
|
||||
const adminsSnapshot = await getDocs(query(collection(db, "users"), where("id", "in", groupsAdmins), where("type", "==", "corporate")));
|
||||
const adminsSnapshot =
|
||||
groupsAdmins.length > 0
|
||||
? await getDocs(query(collection(db, "users"), where("id", "in", groupsAdmins), where("type", "==", "corporate")))
|
||||
: {docs: []};
|
||||
const admins = adminsSnapshot.docs.map((doc) => doc.data());
|
||||
|
||||
const docsWithAdmins = docs.map((d) => {
|
||||
|
||||
@@ -1,22 +1,12 @@
|
||||
import { PERMISSIONS } from "@/constants/userPermissions";
|
||||
import { app, adminApp } from "@/firebase";
|
||||
import { Group, User } from "@/interfaces/user";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import {
|
||||
collection,
|
||||
deleteDoc,
|
||||
doc,
|
||||
getDoc,
|
||||
getDocs,
|
||||
getFirestore,
|
||||
query,
|
||||
setDoc,
|
||||
where,
|
||||
} from "firebase/firestore";
|
||||
import { getAuth } from "firebase-admin/auth";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getPermissions, getPermissionDocs } from "@/utils/permissions.be";
|
||||
import {PERMISSIONS} from "@/constants/userPermissions";
|
||||
import {app, adminApp} from "@/firebase";
|
||||
import {Group, User} from "@/interfaces/user";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {collection, deleteDoc, doc, getDoc, getDocs, getFirestore, query, setDoc, where} from "firebase/firestore";
|
||||
import {getAuth} from "firebase-admin/auth";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {NextApiRequest, NextApiResponse} from "next";
|
||||
import {getPermissions, getPermissionDocs} from "@/utils/permissions.be";
|
||||
|
||||
const db = getFirestore(app);
|
||||
const auth = getAuth(adminApp);
|
||||
@@ -24,132 +14,108 @@ const auth = getAuth(adminApp);
|
||||
export default withIronSessionApiRoute(user, sessionOptions);
|
||||
|
||||
async function user(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "GET") return get(req, res);
|
||||
if (req.method === "DELETE") return del(req, res);
|
||||
if (req.method === "GET") return get(req, res);
|
||||
if (req.method === "DELETE") return del(req, res);
|
||||
|
||||
res.status(404).json(undefined);
|
||||
res.status(404).json(undefined);
|
||||
}
|
||||
|
||||
async function del(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ok: false});
|
||||
return;
|
||||
}
|
||||
|
||||
const { id } = req.query as { id: string };
|
||||
const {id} = req.query as {id: string};
|
||||
|
||||
const docUser = await getDoc(doc(db, "users", req.session.user.id));
|
||||
if (!docUser.exists()) {
|
||||
res.status(401).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
const docUser = await getDoc(doc(db, "users", req.session.user.id));
|
||||
if (!docUser.exists()) {
|
||||
res.status(401).json({ok: false});
|
||||
return;
|
||||
}
|
||||
|
||||
const user = docUser.data() as User;
|
||||
const user = docUser.data() as User;
|
||||
|
||||
const docTargetUser = await getDoc(doc(db, "users", id));
|
||||
if (!docTargetUser.exists()) {
|
||||
res.status(404).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
const docTargetUser = await getDoc(doc(db, "users", id));
|
||||
if (!docTargetUser.exists()) {
|
||||
res.status(404).json({ok: false});
|
||||
return;
|
||||
}
|
||||
|
||||
const targetUser = { ...docTargetUser.data(), id: docTargetUser.id } as User;
|
||||
const targetUser = {...docTargetUser.data(), id: docTargetUser.id} as User;
|
||||
|
||||
if (
|
||||
user.type === "corporate" &&
|
||||
(targetUser.type === "student" || targetUser.type === "teacher")
|
||||
) {
|
||||
res.json({ ok: true });
|
||||
if (user.type === "corporate" && (targetUser.type === "student" || targetUser.type === "teacher")) {
|
||||
res.json({ok: true});
|
||||
|
||||
const userParticipantGroup = await getDocs(
|
||||
query(
|
||||
collection(db, "groups"),
|
||||
where("participants", "array-contains", id)
|
||||
)
|
||||
);
|
||||
await Promise.all([
|
||||
...userParticipantGroup.docs
|
||||
.filter((x) => (x.data() as Group).admin === user.id)
|
||||
.map(
|
||||
async (x) =>
|
||||
await setDoc(
|
||||
x.ref,
|
||||
{
|
||||
participants: x
|
||||
.data()
|
||||
.participants.filter((y: string) => y !== id),
|
||||
},
|
||||
{ merge: true }
|
||||
)
|
||||
),
|
||||
]);
|
||||
const userParticipantGroup = await getDocs(query(collection(db, "groups"), where("participants", "array-contains", id)));
|
||||
await Promise.all([
|
||||
...userParticipantGroup.docs
|
||||
.filter((x) => (x.data() as Group).admin === user.id)
|
||||
.map(
|
||||
async (x) =>
|
||||
await setDoc(
|
||||
x.ref,
|
||||
{
|
||||
participants: x.data().participants.filter((y: string) => y !== id),
|
||||
},
|
||||
{merge: true},
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const permission = PERMISSIONS.deleteUser[targetUser.type];
|
||||
if (!permission.list.includes(user.type)) {
|
||||
res.status(403).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
const permission = PERMISSIONS.deleteUser[targetUser.type];
|
||||
if (!permission.list.includes(user.type)) {
|
||||
res.status(403).json({ok: false});
|
||||
return;
|
||||
}
|
||||
|
||||
res.json({ ok: true });
|
||||
res.json({ok: true});
|
||||
|
||||
await auth.deleteUser(id);
|
||||
await deleteDoc(doc(db, "users", id));
|
||||
const userCodeDocs = await getDocs(
|
||||
query(collection(db, "codes"), where("userId", "==", id))
|
||||
);
|
||||
const userParticipantGroup = await getDocs(
|
||||
query(collection(db, "groups"), where("participants", "array-contains", id))
|
||||
);
|
||||
const userGroupAdminDocs = await getDocs(
|
||||
query(collection(db, "groups"), where("admin", "==", id))
|
||||
);
|
||||
const userStatsDocs = await getDocs(
|
||||
query(collection(db, "stats"), where("user", "==", id))
|
||||
);
|
||||
await auth.deleteUser(id);
|
||||
await deleteDoc(doc(db, "users", id));
|
||||
const userCodeDocs = await getDocs(query(collection(db, "codes"), where("userId", "==", id)));
|
||||
const userParticipantGroup = await getDocs(query(collection(db, "groups"), where("participants", "array-contains", id)));
|
||||
const userGroupAdminDocs = await getDocs(query(collection(db, "groups"), where("admin", "==", id)));
|
||||
const userStatsDocs = await getDocs(query(collection(db, "stats"), where("user", "==", id)));
|
||||
|
||||
await Promise.all([
|
||||
...userCodeDocs.docs.map(async (x) => await deleteDoc(x.ref)),
|
||||
...userGroupAdminDocs.docs.map(async (x) => await deleteDoc(x.ref)),
|
||||
...userStatsDocs.docs.map(async (x) => await deleteDoc(x.ref)),
|
||||
...userParticipantGroup.docs.map(
|
||||
async (x) =>
|
||||
await setDoc(
|
||||
x.ref,
|
||||
{
|
||||
participants: x.data().participants.filter((y: string) => y !== id),
|
||||
},
|
||||
{ merge: true }
|
||||
)
|
||||
),
|
||||
]);
|
||||
await Promise.all([
|
||||
...userCodeDocs.docs.map(async (x) => await deleteDoc(x.ref)),
|
||||
...userGroupAdminDocs.docs.map(async (x) => await deleteDoc(x.ref)),
|
||||
...userStatsDocs.docs.map(async (x) => await deleteDoc(x.ref)),
|
||||
...userParticipantGroup.docs.map(
|
||||
async (x) =>
|
||||
await setDoc(
|
||||
x.ref,
|
||||
{
|
||||
participants: x.data().participants.filter((y: string) => y !== id),
|
||||
},
|
||||
{merge: true},
|
||||
),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.session.user) {
|
||||
const docUser = await getDoc(doc(db, "users", req.session.user.id));
|
||||
if (!docUser.exists()) {
|
||||
res.status(401).json(undefined);
|
||||
return;
|
||||
}
|
||||
if (req.session.user) {
|
||||
const docUser = await getDoc(doc(db, "users", req.session.user.id));
|
||||
if (!docUser.exists()) {
|
||||
res.status(401).json(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
const user = docUser.data() as User;
|
||||
|
||||
const permissionDocs = await getPermissionDocs();
|
||||
const user = docUser.data() as User;
|
||||
|
||||
const userWithPermissions = {
|
||||
...user,
|
||||
permissions: getPermissions(req.session.user.id, permissionDocs),
|
||||
};
|
||||
req.session.user = {
|
||||
...userWithPermissions,
|
||||
id: req.session.user.id,
|
||||
};
|
||||
await req.session.save();
|
||||
req.session.user = {
|
||||
...user,
|
||||
id: req.session.user.id,
|
||||
};
|
||||
await req.session.save();
|
||||
|
||||
res.json({ ...userWithPermissions, id: req.session.user.id });
|
||||
} else {
|
||||
res.status(401).json(undefined);
|
||||
}
|
||||
res.json({...user, id: req.session.user.id});
|
||||
} else {
|
||||
res.status(401).json(undefined);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ import { uuidv4 } from "@firebase/util";
|
||||
import { usePDFDownload } from "@/hooks/usePDFDownload";
|
||||
import useRecordStore from "@/stores/recordStore";
|
||||
import useTrainingContentStore from "@/stores/trainingContentStore";
|
||||
import Button from "@/components/Low/Button";
|
||||
import StatsGridItem from "@/components/StatGridItem";
|
||||
|
||||
|
||||
@@ -148,10 +147,12 @@ export default function History({ user }: { user: User }) {
|
||||
|
||||
const handleTrainingContentSubmission = () => {
|
||||
if (groupedStats) {
|
||||
const allStats = Object.keys(filterStatsByDate(groupedStats));
|
||||
const selectedStats = selectedTrainingExams.reduce<Record<string, Stat[]>>((accumulator, timestamp) => {
|
||||
if (allStats.includes(timestamp)) {
|
||||
accumulator[timestamp] = filterStatsByDate(groupedStats)[timestamp];
|
||||
const groupedStatsByDate = filterStatsByDate(groupedStats);
|
||||
const allStats = Object.keys(groupedStatsByDate);
|
||||
const selectedStats = selectedTrainingExams.reduce<Record<string, Stat[]>>((accumulator, moduleAndTimestamp) => {
|
||||
const timestamp = moduleAndTimestamp.split("-")[1];
|
||||
if (allStats.includes(timestamp) && !accumulator.hasOwnProperty(timestamp)) {
|
||||
accumulator[timestamp] = groupedStatsByDate[timestamp];
|
||||
}
|
||||
return accumulator;
|
||||
}, {});
|
||||
@@ -177,6 +178,7 @@ export default function History({ user }: { user: User }) {
|
||||
training={training}
|
||||
selectedTrainingExams={selectedTrainingExams}
|
||||
setSelectedTrainingExams={setSelectedTrainingExams}
|
||||
maxTrainingExams={MAX_TRAINING_EXAMS}
|
||||
setExams={setExams}
|
||||
setShowSolutions={setShowSolutions}
|
||||
setUserSolutions={setUserSolutions}
|
||||
@@ -323,7 +325,8 @@ export default function History({ user }: { user: User }) {
|
||||
)}
|
||||
{(training && (
|
||||
<div className="flex flex-row">
|
||||
<div className="font-semibold text-2xl mr-4">Select up to 10 exams {`(${selectedTrainingExams.length}/${MAX_TRAINING_EXAMS})`}</div>
|
||||
<div className="font-semibold text-2xl mr-4">Select up to 10 exercises
|
||||
{`(${selectedTrainingExams.length}/${MAX_TRAINING_EXAMS})`}</div>
|
||||
<button
|
||||
className={clsx(
|
||||
"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light ml-4 disabled:cursor-not-allowed",
|
||||
@@ -385,6 +388,11 @@ export default function History({ user }: { user: User }) {
|
||||
{groupedStats && Object.keys(groupedStats).length === 0 && !isStatsLoading && (
|
||||
<span className="font-semibold ml-1">No record to display...</span>
|
||||
)}
|
||||
{isStatsLoading && (
|
||||
<div className="absolute left-1/2 top-1/2 flex h-fit w-fit -translate-x-1/2 -translate-y-1/2 animate-pulse flex-col items-center gap-12">
|
||||
<span className="loading loading-infinity w-32 bg-mti-green-light" />
|
||||
</div>
|
||||
)}
|
||||
</Layout>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -13,10 +13,12 @@ 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";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
const user = req.session.user;
|
||||
|
||||
if (!user || !user.isVerified) {
|
||||
return {
|
||||
redirect: {
|
||||
@@ -42,6 +44,7 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
|
||||
export default function Admin() {
|
||||
const {user} = useUser({redirectTo: "/login"});
|
||||
const {permissions} = usePermissions(user?.id || "");
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -57,9 +60,10 @@ export default function Admin() {
|
||||
<ToastContainer />
|
||||
{user && (
|
||||
<Layout user={user} className="gap-6">
|
||||
<section className="w-full flex -md:flex-col -xl:gap-2 gap-8 justify-between">
|
||||
<section className="w-full grid grid-cols-2 -md:grid-cols-1 gap-8">
|
||||
<ExamLoader />
|
||||
{user.type !== "teacher" && (
|
||||
<BatchCreateUser user={user} />
|
||||
{checkAccess(user, getTypesOfUser(["teacher"]), permissions, "viewCodes") && (
|
||||
<>
|
||||
<CodeGenerator user={user} />
|
||||
<BatchCodeGenerator user={user} />
|
||||
|
||||
@@ -24,6 +24,12 @@ import { usePDFDownload } from "@/hooks/usePDFDownload";
|
||||
import useAssignments from '@/hooks/useAssignments';
|
||||
import useUsers from '@/hooks/useUsers';
|
||||
import Dropdown from "@/components/Dropdown";
|
||||
import InfiniteCarousel from '@/components/InfiniteCarousel';
|
||||
import { LuExternalLink } from "react-icons/lu";
|
||||
import { uniqBy } from 'lodash';
|
||||
import { getExamById } from '@/utils/exams';
|
||||
import { convertToUserSolutions } from '@/utils/stats';
|
||||
import { sortByModule } from '@/utils/moduleUtils';
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(({ req, res }) => {
|
||||
const user = req.session.user;
|
||||
@@ -68,12 +74,9 @@ const TrainingContent: React.FC<{ user: User }> = ({ user }) => {
|
||||
const { assignments } = useAssignments({});
|
||||
const { users } = useUsers();
|
||||
|
||||
|
||||
|
||||
const router = useRouter();
|
||||
const { id } = router.query;
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
const fetchTrainingContent = async () => {
|
||||
if (!id || typeof id !== 'string') return;
|
||||
@@ -118,6 +121,32 @@ const TrainingContent: React.FC<{ user: User }> = ({ user }) => {
|
||||
setCurrentTipIndex((prevIndex) => (prevIndex - 1));
|
||||
};
|
||||
|
||||
const goToExam = (examNumber: number) => {
|
||||
const stats = trainingContent?.exams[examNumber].stats!;
|
||||
const examPromises = uniqBy(stats, "exam").map((stat) => {
|
||||
return getExamById(stat.module, stat.exam);
|
||||
});
|
||||
|
||||
const { timeSpent, inactivity } = stats[0];
|
||||
|
||||
Promise.all(examPromises).then((exams) => {
|
||||
if (exams.every((x) => !!x)) {
|
||||
if (!!timeSpent) setTimeSpent(timeSpent);
|
||||
if (!!inactivity) setInactivity(inactivity);
|
||||
setUserSolutions(convertToUserSolutions(stats));
|
||||
setShowSolutions(true);
|
||||
setExams(exams.map((x) => x!).sort(sortByModule));
|
||||
setSelectedModules(
|
||||
exams
|
||||
.map((x) => x!)
|
||||
.sort(sortByModule)
|
||||
.map((x) => x!.module),
|
||||
);
|
||||
router.push("/exercises");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
@@ -137,13 +166,25 @@ const TrainingContent: React.FC<{ user: User }> = ({ user }) => {
|
||||
<span className="loading loading-infinity w-32 bg-mti-green-light" />
|
||||
</div>
|
||||
) : (trainingContent && (
|
||||
<div className="flex flex-col gap-10">
|
||||
<div className="flex h-screen flex-col gap-4">
|
||||
<div className='flex flex-row h-[15%] gap-4'>
|
||||
{/*<Carousel itemsPerFrame={4} itemsPerScroll={4}>*/}
|
||||
<div className="flex flex-col gap-8">
|
||||
<div className="flex flex-row items-center">
|
||||
<span className="bg-gray-200 text-gray-800 px-3 py-0.5 rounded-full font-semibold text-lg mr-2">{trainingContent.exams.length}</span>
|
||||
<span>Exams Selected</span>
|
||||
</div>
|
||||
<div className='h-[15vh] mb-4'>
|
||||
<InfiniteCarousel height="150px"
|
||||
overlay={
|
||||
<LuExternalLink size={20} />
|
||||
}
|
||||
overlayFunc={goToExam}
|
||||
overlayClassName='bottom-6 right-5 cursor-pointer'
|
||||
>
|
||||
{trainingContent.exams.map((exam, examIndex) => (
|
||||
<StatsGridItem
|
||||
key={`exam-${examIndex}`}
|
||||
width='380px'
|
||||
height='150px'
|
||||
examNumber={examIndex + 1}
|
||||
stats={exam.stats || []}
|
||||
timestamp={exam.date}
|
||||
user={user}
|
||||
@@ -158,79 +199,51 @@ const TrainingContent: React.FC<{ user: User }> = ({ user }) => {
|
||||
renderPdfIcon={renderPdfIcon}
|
||||
/>
|
||||
))}
|
||||
{/* </Carousel> */}
|
||||
</div>
|
||||
<div className='flex flex-col h-[75%]' style={{ maxHeight: '85%' }}>
|
||||
<div className='flex flex-row gap-10 -md:flex-col'>
|
||||
<div className="rounded-3xl p-6 w-1/2 shadow-training-inset -md:w-full max-h-full">
|
||||
<div className="flex flex-row items-center mb-6 gap-1">
|
||||
<MdOutlinePlaylistAddCheckCircle color={"#40A1EA"} size={26} />
|
||||
<h2 className={`text-xl font-semibold text-[#40A1EA]`}>General Evaluation</h2>
|
||||
</div>
|
||||
<TrainingScore
|
||||
trainingContent={trainingContent}
|
||||
gridView={false}
|
||||
/>
|
||||
<div className="w-full h-px bg-[#D9D9D929] my-6"></div>
|
||||
<div className="flex flex-row gap-2 items-center mb-6">
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<mask id="mask0_112_168" maskUnits="userSpaceOnUse" x="0" y="0" width="24" height="24">
|
||||
<rect width="24" height="24" fill="#D9D9D9" />
|
||||
</mask>
|
||||
<g mask="url(#mask0_112_168)">
|
||||
<path d="M4 21C3.45 21 2.97917 20.8042 2.5875 20.4125C2.19583 20.0208 2 19.55 2 19V7H4V19H19V21H4ZM8 17C7.45 17 6.97917 16.8042 6.5875 16.4125C6.19583 16.0208 6 15.55 6 15V3H23V15C23 15.55 22.8042 16.0208 22.4125 16.4125C22.0208 16.8042 21.55 17 21 17H8ZM8 15H21V5H8V15ZM10 12H14V7H10V12ZM15 12H19V10H15V12ZM15 9H19V7H15V9Z" fill="#53B2F9" />
|
||||
</g>
|
||||
</svg>
|
||||
<h3 className="text-xl font-semibold text-[#40A1EA]">Performance Breakdown by Exam:</h3>
|
||||
</div>
|
||||
<ul>
|
||||
{trainingContent.exams.flatMap((exam, index) => (
|
||||
<li key={index} className="flex flex-col mb-2 bg-[#22E1B30F] p-4 rounded-xl border">
|
||||
<div className="flex flex-row font-semibold border-b-2 border-[#D9D9D929] text-[#22E1B3] mb-2">
|
||||
<span className="border-r-2 border-[#D9D9D929] pr-2">Exam {index + 1}</span>
|
||||
<span className="pl-2">{exam.score}%</span>
|
||||
</div>
|
||||
<div className="flex flex-row items-center gap-2">
|
||||
<BsChatLeftDots size={16} />
|
||||
<p className="text-sm">{exam.performance_comment}</p>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</InfiniteCarousel>
|
||||
</div>
|
||||
<div className='flex flex-col'>
|
||||
<div className='flex flex-row gap-10 -md:flex-col h-full'>
|
||||
<div className="flex flex-col rounded-3xl p-6 w-1/2 shadow-training-inset -md:w-full max-h-full">
|
||||
<div className="flex flex-row items-center mb-6 gap-1">
|
||||
<MdOutlinePlaylistAddCheckCircle color={"#40A1EA"} size={26} />
|
||||
<h2 className={`text-xl font-semibold text-[#40A1EA]`}>General Evaluation</h2>
|
||||
</div>
|
||||
<div className="rounded-3xl p-6 w-1/2 shadow-training-inset -md:w-full">
|
||||
<div className="flex flex-row items-center mb-4 gap-1">
|
||||
<MdOutlineSelfImprovement color={"#40A1EA"} size={24} />
|
||||
<h2 className={`text-xl font-semibold text-[#40A1EA]`}>Subjects that Need Improvement</h2>
|
||||
</div>
|
||||
|
||||
<div className="bg-[#FBFBFB] border rounded-xl p-4 max-h-[500px] overflow-y-auto scrollbar-hide">
|
||||
<div className='flex flex-col'>
|
||||
<div className="flex flex-row items-center gap-1 mb-4">
|
||||
<div className="flex items-center justify-center w-[48px] h-[48px]">
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<mask id="mask0_112_445" maskUnits="userSpaceOnUse" x="0" y="0" width="24" height="24">
|
||||
<rect width="24" height="24" fill="#D9D9D9" />
|
||||
</mask>
|
||||
<g mask="url(#mask0_112_445)">
|
||||
<path d="M6 17H11V15H6V17ZM16 17H18V15H16V17ZM6 13H11V11H6V13ZM16 13H18V7H16V13ZM6 9H11V7H6V9ZM4 21C3.45 21 2.97917 20.8042 2.5875 20.4125C2.19583 20.0208 2 19.55 2 19V5C2 4.45 2.19583 3.97917 2.5875 3.5875C2.97917 3.19583 3.45 3 4 3H20C20.55 3 21.0208 3.19583 21.4125 3.5875C21.8042 3.97917 22 4.45 22 5V19C22 19.55 21.8042 20.0208 21.4125 20.4125C21.0208 20.8042 20.55 21 20 21H4ZM4 19H20V5H4V19Z" fill="#1C1B1F" />
|
||||
</g>
|
||||
</svg>
|
||||
<TrainingScore
|
||||
trainingContent={trainingContent}
|
||||
gridView={false}
|
||||
/>
|
||||
<div className="w-full h-px bg-[#D9D9D929] my-6"></div>
|
||||
<div className="flex flex-row gap-2 items-center mb-6">
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<mask id="mask0_112_168" maskUnits="userSpaceOnUse" x="0" y="0" width="24" height="24">
|
||||
<rect width="24" height="24" fill="#D9D9D9" />
|
||||
</mask>
|
||||
<g mask="url(#mask0_112_168)">
|
||||
<path d="M4 21C3.45 21 2.97917 20.8042 2.5875 20.4125C2.19583 20.0208 2 19.55 2 19V7H4V19H19V21H4ZM8 17C7.45 17 6.97917 16.8042 6.5875 16.4125C6.19583 16.0208 6 15.55 6 15V3H23V15C23 15.55 22.8042 16.0208 22.4125 16.4125C22.0208 16.8042 21.55 17 21 17H8ZM8 15H21V5H8V15ZM10 12H14V7H10V12ZM15 12H19V10H15V12ZM15 9H19V7H15V9Z" fill="#53B2F9" />
|
||||
</g>
|
||||
</svg>
|
||||
<h3 className="text-xl font-semibold text-[#40A1EA]">Performance Breakdown by Exam:</h3>
|
||||
</div>
|
||||
<ul className='overflow-auto scrollbar-hide flex-grow'>
|
||||
{trainingContent.exams.flatMap((exam, index) => (
|
||||
<li key={index} className="flex flex-col mb-2 bg-[#22E1B30F] p-4 rounded-xl border">
|
||||
<div className="flex flex-row font-semibold border-b-2 border-[#D9D9D929] text-[#22E1B3] mb-2">
|
||||
<div className='flex items-center border-r-2 border-[#D9D9D929] pr-2'>
|
||||
<span className='mr-1'>Exam</span>
|
||||
<span className="font-semibold bg-gray-200 text-gray-800 px-2 rounded-full text-sm">{index + 1}</span>
|
||||
</div>
|
||||
<h3 className="text-lg font-semibold">Detailed Breakdown</h3>
|
||||
<span className="pl-2">{exam.score}%</span>
|
||||
</div>
|
||||
<ul className="space-y-4 pb-2">
|
||||
{trainingContent.exams.map((exam, index) => (
|
||||
<li key={index} className="border rounded-lg bg-white">
|
||||
<Dropdown title={`Exam ${index + 1}`}>
|
||||
<span>{exam.detailed_summary}</span>
|
||||
</Dropdown>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div className="w-full h-px bg-[#D9D9D929] my-6"></div>
|
||||
<div className="flex flex-row items-center gap-2">
|
||||
<BsChatLeftDots size={16} />
|
||||
<p className="text-sm">{exam.performance_comment}</p>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
<div className="flex flex-col rounded-3xl p-6 w-1/2 shadow-training-inset -md:w-full">
|
||||
<div className='flex flex-col'>
|
||||
<div className="flex flex-row items-center mb-4 gap-1">
|
||||
<AiOutlineFileSearch color="#40A1EA" size={24} />
|
||||
<h3 className="text-xl font-semibold text-[#40A1EA]">Identified Weak Areas</h3>
|
||||
@@ -238,7 +251,7 @@ const TrainingContent: React.FC<{ user: User }> = ({ user }) => {
|
||||
<Tab.Group>
|
||||
<div className="flex flex-col gap-4">
|
||||
<Tab.List>
|
||||
<div className="flex flex-row gap-6">
|
||||
<div className="flex flex-row gap-6 overflow-x-auto pb-1 training-scrollbar">
|
||||
{trainingContent.weak_areas.map((x, index) => (
|
||||
<Tab
|
||||
key={index}
|
||||
@@ -268,10 +281,47 @@ const TrainingContent: React.FC<{ user: User }> = ({ user }) => {
|
||||
</div>
|
||||
</Tab.Group>
|
||||
</div>
|
||||
<div className="w-full h-px bg-[#D9D9D929] my-6"></div>
|
||||
<div className="flex flex-row items-center mb-4 gap-1">
|
||||
<MdOutlineSelfImprovement color={"#40A1EA"} size={24} />
|
||||
<h2 className={`text-xl font-semibold text-[#40A1EA]`}>Subjects that Need Improvement</h2>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-grow bg-[#FBFBFB] border rounded-xl p-4">
|
||||
<div className='flex flex-col'>
|
||||
<div className="flex flex-row items-center gap-1 mb-4">
|
||||
<div className="flex items-center justify-center w-[48px] h-[48px]">
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<mask id="mask0_112_445" maskUnits="userSpaceOnUse" x="0" y="0" width="24" height="24">
|
||||
<rect width="24" height="24" fill="#D9D9D9" />
|
||||
</mask>
|
||||
<g mask="url(#mask0_112_445)">
|
||||
<path d="M6 17H11V15H6V17ZM16 17H18V15H16V17ZM6 13H11V11H6V13ZM16 13H18V7H16V13ZM6 9H11V7H6V9ZM4 21C3.45 21 2.97917 20.8042 2.5875 20.4125C2.19583 20.0208 2 19.55 2 19V5C2 4.45 2.19583 3.97917 2.5875 3.5875C2.97917 3.19583 3.45 3 4 3H20C20.55 3 21.0208 3.19583 21.4125 3.5875C21.8042 3.97917 22 4.45 22 5V19C22 19.55 21.8042 20.0208 21.4125 20.4125C21.0208 20.8042 20.55 21 20 21H4ZM4 19H20V5H4V19Z" fill="#1C1B1F" />
|
||||
</g>
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="text-lg font-semibold">Detailed Breakdown</h3>
|
||||
</div>
|
||||
<ul className="flex flex-col flex-grow space-y-4 pb-2 overflow-y-auto scrollbar-hide">
|
||||
{trainingContent.exams.map((exam, index) => (
|
||||
<li key={index} className="border rounded-lg bg-white">
|
||||
<Dropdown title={
|
||||
<div className='flex flex-row items-center'>
|
||||
<span className="mr-1">Exam</span>
|
||||
<span className="font-semibold bg-gray-200 text-gray-800 px-2 rounded-full text-sm mt-0.5">{index + 1}</span>
|
||||
</div>
|
||||
} open={index == 0}>
|
||||
<span>{exam.detailed_summary}</span>
|
||||
</Dropdown>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex">
|
||||
<div className="flex -md:hidden">
|
||||
<div className="rounded-3xl p-6 shadow-training-inset w-full">
|
||||
<div className="flex flex-col p-10">
|
||||
<Exercise key={currentTipIndex} {...trainingTips[currentTipIndex]} />
|
||||
@@ -294,6 +344,7 @@ const TrainingContent: React.FC<{ user: User }> = ({ user }) => {
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -389,7 +389,7 @@ const Training: React.FC<{ user: User }> = ({ user }) => {
|
||||
</div>
|
||||
)}
|
||||
{groupedByTrainingContent && Object.keys(groupedByTrainingContent).length > 0 && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 w-full gap-4 xl:gap-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-2 2xl:grid-cols-3 w-full gap-4 xl:gap-6">
|
||||
{Object.keys(filterTrainingContentByDate(groupedByTrainingContent))
|
||||
.sort((a, b) => parseInt(b) - parseInt(a))
|
||||
.map(trainingContentContainer)}
|
||||
|
||||
@@ -4,14 +4,35 @@
|
||||
|
||||
@layer utilities {
|
||||
.scrollbar-hide {
|
||||
-ms-overflow-style: none; /* IE and Edge */
|
||||
scrollbar-width: none; /* Firefox */
|
||||
-ms-overflow-style: none;
|
||||
/* IE and Edge */
|
||||
scrollbar-width: none;
|
||||
/* Firefox */
|
||||
}
|
||||
|
||||
.scrollbar-hide::-webkit-scrollbar {
|
||||
display: none; /* Chrome, Safari and Opera */
|
||||
display: none;
|
||||
/* Chrome, Safari and Opera */
|
||||
}
|
||||
}
|
||||
|
||||
.training-scrollbar::-webkit-scrollbar {
|
||||
@apply w-1.5;
|
||||
}
|
||||
|
||||
.training-scrollbar::-webkit-scrollbar-track {
|
||||
@apply bg-transparent;
|
||||
}
|
||||
|
||||
.training-scrollbar::-webkit-scrollbar-thumb {
|
||||
@apply bg-gray-400 hover:bg-gray-500 rounded-full transition-colors opacity-50 hover:opacity-75;
|
||||
}
|
||||
|
||||
.training-scrollbar {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: rgba(156, 163, 175, 0.5) transparent;
|
||||
}
|
||||
|
||||
:root {
|
||||
--max-width: 1100px;
|
||||
--border-radius: 12px;
|
||||
@@ -66,4 +87,4 @@ body {
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
}
|
||||
14
src/utils/assignments.be.ts
Normal file
14
src/utils/assignments.be.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import {app} from "@/firebase";
|
||||
import {Assignment} from "@/interfaces/results";
|
||||
import {collection, getDocs, getFirestore, query, where} from "firebase/firestore";
|
||||
|
||||
const db = getFirestore(app);
|
||||
|
||||
export const getAssignmentsByAssigner = async (id: string) => {
|
||||
const {docs} = await getDocs(query(collection(db, "assignments"), where("assigner", "==", id)));
|
||||
return docs.map((x) => ({...x.data(), id: x.id})) as Assignment[];
|
||||
};
|
||||
|
||||
export const getAssignmentsByAssigners = async (ids: string[]) => {
|
||||
return (await Promise.all(ids.map(getAssignmentsByAssigner))).flat();
|
||||
};
|
||||
@@ -1,53 +1,51 @@
|
||||
import { app } from "@/firebase";
|
||||
import { CorporateUser, StudentUser, TeacherUser } from "@/interfaces/user";
|
||||
import { doc, getDoc, getFirestore, setDoc } from "firebase/firestore";
|
||||
import {app} from "@/firebase";
|
||||
import {CorporateUser, Group, StudentUser, TeacherUser} from "@/interfaces/user";
|
||||
import {collection, doc, getDoc, getDocs, getFirestore, query, setDoc, where} from "firebase/firestore";
|
||||
import moment from "moment";
|
||||
import {getUser} from "./users.be";
|
||||
|
||||
const db = getFirestore(app);
|
||||
|
||||
export const updateExpiryDateOnGroup = async (
|
||||
participantID: string,
|
||||
corporateID: string,
|
||||
) => {
|
||||
const corporateRef = await getDoc(doc(db, "users", corporateID));
|
||||
const participantRef = await getDoc(doc(db, "users", participantID));
|
||||
export const updateExpiryDateOnGroup = async (participantID: string, corporateID: string) => {
|
||||
const corporateRef = await getDoc(doc(db, "users", corporateID));
|
||||
const participantRef = await getDoc(doc(db, "users", participantID));
|
||||
|
||||
if (!corporateRef.exists() || !participantRef.exists()) return;
|
||||
if (!corporateRef.exists() || !participantRef.exists()) return;
|
||||
|
||||
const corporate = {
|
||||
...corporateRef.data(),
|
||||
id: corporateRef.id,
|
||||
} as CorporateUser;
|
||||
const participant = { ...participantRef.data(), id: participantRef.id } as
|
||||
| StudentUser
|
||||
| TeacherUser;
|
||||
const corporate = {
|
||||
...corporateRef.data(),
|
||||
id: corporateRef.id,
|
||||
} as CorporateUser;
|
||||
const participant = {...participantRef.data(), id: participantRef.id} as StudentUser | TeacherUser;
|
||||
|
||||
if (
|
||||
corporate.type !== "corporate" ||
|
||||
(participant.type !== "student" && participant.type !== "teacher")
|
||||
)
|
||||
return;
|
||||
if (corporate.type !== "corporate" || (participant.type !== "student" && participant.type !== "teacher")) return;
|
||||
|
||||
if (
|
||||
!corporate.subscriptionExpirationDate ||
|
||||
!participant.subscriptionExpirationDate
|
||||
) {
|
||||
return await setDoc(
|
||||
doc(db, "users", participant.id),
|
||||
{ subscriptionExpirationDate: null },
|
||||
{ merge: true },
|
||||
);
|
||||
}
|
||||
if (!corporate.subscriptionExpirationDate || !participant.subscriptionExpirationDate) {
|
||||
return await setDoc(doc(db, "users", participant.id), {subscriptionExpirationDate: null}, {merge: true});
|
||||
}
|
||||
|
||||
const corporateDate = moment(corporate.subscriptionExpirationDate);
|
||||
const participantDate = moment(participant.subscriptionExpirationDate);
|
||||
const corporateDate = moment(corporate.subscriptionExpirationDate);
|
||||
const participantDate = moment(participant.subscriptionExpirationDate);
|
||||
|
||||
if (corporateDate.isAfter(participantDate))
|
||||
return await setDoc(
|
||||
doc(db, "users", participant.id),
|
||||
{ subscriptionExpirationDate: corporateDate.toISOString() },
|
||||
{ merge: true },
|
||||
);
|
||||
if (corporateDate.isAfter(participantDate))
|
||||
return await setDoc(doc(db, "users", participant.id), {subscriptionExpirationDate: corporateDate.toISOString()}, {merge: true});
|
||||
|
||||
return;
|
||||
return;
|
||||
};
|
||||
|
||||
export const getUserGroups = async (id: string): Promise<Group[]> => {
|
||||
const groupDocs = await getDocs(query(collection(db, "groups"), where("admin", "==", id)));
|
||||
return groupDocs.docs.map((x) => ({...x.data(), id})) as Group[];
|
||||
};
|
||||
|
||||
export const getAllAssignersByCorporate = async (corporateID: string): Promise<string[]> => {
|
||||
const groups = await getUserGroups(corporateID);
|
||||
const groupUsers = (await Promise.all(groups.map(async (g) => await Promise.all(g.participants.map(getUser))))).flat();
|
||||
const teacherPromises = await Promise.all(
|
||||
groupUsers.map(async (u) =>
|
||||
u.type === "teacher" ? u.id : u.type === "corporate" ? [...(await getAllAssignersByCorporate(u.id)), u.id] : undefined,
|
||||
),
|
||||
);
|
||||
|
||||
return teacherPromises.filter((x) => !!x).flat() as string[];
|
||||
};
|
||||
|
||||
@@ -1,45 +1,42 @@
|
||||
import { PermissionType } from "@/interfaces/permissions";
|
||||
import { User, Type, userTypes } from "@/interfaces/user";
|
||||
import {PermissionType} from "@/interfaces/permissions";
|
||||
import {User, Type, userTypes} from "@/interfaces/user";
|
||||
import axios from "axios";
|
||||
|
||||
export function checkAccess(
|
||||
user: User,
|
||||
types: Type[],
|
||||
permission?: PermissionType
|
||||
) {
|
||||
if (!user) {
|
||||
return false;
|
||||
}
|
||||
export function checkAccess(user: User, types: Type[], permissions?: PermissionType[], permission?: PermissionType) {
|
||||
if (!user) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// if(user.type === '') {
|
||||
if (!user.type) {
|
||||
console.warn("User type is empty");
|
||||
return false;
|
||||
}
|
||||
// if(user.type === '') {
|
||||
if (!user.type) {
|
||||
console.warn("User type is empty");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (types.length === 0) {
|
||||
console.warn("No types provided");
|
||||
return false;
|
||||
}
|
||||
if (types.length === 0) {
|
||||
console.warn("No types provided");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!types.includes(user.type)) {
|
||||
return false;
|
||||
}
|
||||
if (!types.includes(user.type)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// we may not want a permission check as most screens dont even havr a specific permission
|
||||
if (permission) {
|
||||
// this works more like a blacklist
|
||||
// therefore if we don't find the permission here, he can't do it
|
||||
if (!(user.permissions || []).includes(permission)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// we may not want a permission check as most screens dont even havr a specific permission
|
||||
if (permission) {
|
||||
// this works more like a blacklist
|
||||
// therefore if we don't find the permission here, he can't do it
|
||||
if (!(permissions || []).includes(permission)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function getTypesOfUser(types: Type[]) {
|
||||
// basicly generate a list of all types except the excluded ones
|
||||
return userTypes.filter((userType) => {
|
||||
return !types.includes(userType);
|
||||
})
|
||||
}
|
||||
// basicly generate a list of all types except the excluded ones
|
||||
return userTypes.filter((userType) => {
|
||||
return !types.includes(userType);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
import { app } from "@/firebase";
|
||||
import {app} from "@/firebase";
|
||||
|
||||
import { collection, getDocs, getFirestore } from "firebase/firestore";
|
||||
import { User } from "@/interfaces/user";
|
||||
import {collection, doc, getDoc, getDocs, getFirestore} from "firebase/firestore";
|
||||
import {User} from "@/interfaces/user";
|
||||
const db = getFirestore(app);
|
||||
|
||||
export async function getUsers() {
|
||||
const snapshot = await getDocs(collection(db, "users"));
|
||||
const snapshot = await getDocs(collection(db, "users"));
|
||||
|
||||
return snapshot.docs.map((doc) => ({
|
||||
id: doc.id,
|
||||
...doc.data(),
|
||||
})) as User[];
|
||||
return snapshot.docs.map((doc) => ({
|
||||
id: doc.id,
|
||||
...doc.data(),
|
||||
})) as User[];
|
||||
}
|
||||
|
||||
export async function getUser(id: string) {
|
||||
const userDoc = await getDoc(doc(db, "users", id));
|
||||
|
||||
return {...userDoc.data(), id} as User;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,10 @@ export const exportListToExcel = (rowUsers: User[], users: User[], groups: Group
|
||||
expiryDate: user.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).format("DD/MM/YYYY") : "Unlimited",
|
||||
country: user.demographicInformation?.country || "N/A",
|
||||
phone: user.demographicInformation?.phone || "N/A",
|
||||
employmentPosition: (user.type === "corporate" || user.type === "mastercorporate" ? user.demographicInformation?.position : user.demographicInformation?.employment) || "N/A",
|
||||
employmentPosition:
|
||||
(user.type === "corporate" || user.type === "mastercorporate"
|
||||
? user.demographicInformation?.position
|
||||
: user.demographicInformation?.employment) || "N/A",
|
||||
gender: user.demographicInformation?.gender ? capitalize(user.demographicInformation.gender) : "N/A",
|
||||
verified: user.isVerified?.toString() || "FALSE",
|
||||
}));
|
||||
@@ -34,3 +37,9 @@ export const exportListToExcel = (rowUsers: User[], users: User[], groups: Group
|
||||
|
||||
return `${header}\n${rowsString}`;
|
||||
};
|
||||
|
||||
export const getUserName = (user?: User) => {
|
||||
if (!user) return "N/A";
|
||||
if (user.type === "corporate" || user.type === "mastercorporate") return user.corporateInformation?.companyInformation?.name || user.name;
|
||||
return user.name;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user