Refactor most getServerProps to fetch independent request in parallel and projected the data only to return the necessary fields and changed some functions
This commit is contained in:
@@ -18,328 +18,476 @@ import { getEntityUsers, getSpecificUsers } from "@/utils/users.be";
|
||||
import axios from "axios";
|
||||
import clsx from "clsx";
|
||||
import { withIronSessionSsr } from "iron-session/next";
|
||||
import { capitalize } from "lodash";
|
||||
import { capitalize, last } from "lodash";
|
||||
import moment from "moment";
|
||||
import Head from "next/head";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { Divider } from "primereact/divider";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { BsBuilding, BsChevronLeft, BsClockFill, BsEnvelopeFill, BsFillPersonVcardFill, BsPlus, BsStopwatchFill, BsTag, BsTrash, BsX } from "react-icons/bs";
|
||||
import {
|
||||
BsBuilding,
|
||||
BsChevronLeft,
|
||||
BsClockFill,
|
||||
BsEnvelopeFill,
|
||||
BsFillPersonVcardFill,
|
||||
BsPlus,
|
||||
BsStopwatchFill,
|
||||
BsTag,
|
||||
BsTrash,
|
||||
BsX,
|
||||
} from "react-icons/bs";
|
||||
import { toast, ToastContainer } from "react-toastify";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(async ({ req, res, params }) => {
|
||||
const user = await requestUser(req, res)
|
||||
if (!user) return redirect("/login")
|
||||
export const getServerSideProps = withIronSessionSsr(
|
||||
async ({ req, res, params }) => {
|
||||
const user = await requestUser(req, res);
|
||||
if (!user) return redirect("/login");
|
||||
|
||||
if (shouldRedirectHome(user)) return redirect("/")
|
||||
if (shouldRedirectHome(user)) return redirect("/");
|
||||
|
||||
const { id } = params as { id: string };
|
||||
const { id } = params as { id: string };
|
||||
|
||||
const group = await getGroup(id);
|
||||
if (!group || !group.entity) return redirect("/classrooms")
|
||||
const group = await getGroup(id);
|
||||
if (!group || !group.entity) return redirect("/classrooms");
|
||||
|
||||
const entity = await getEntityWithRoles(group.entity)
|
||||
if (!entity) return redirect("/classrooms")
|
||||
const entity = await getEntityWithRoles(group.entity);
|
||||
if (!entity) return redirect("/classrooms");
|
||||
|
||||
const canView = doesEntityAllow(user, entity, "view_classrooms")
|
||||
if (!canView) return redirect("/")
|
||||
const canView = doesEntityAllow(user, entity, "view_classrooms");
|
||||
if (!canView) return redirect("/");
|
||||
const [linkedUsers, users] = await Promise.all([
|
||||
getEntityUsers(
|
||||
entity.id,
|
||||
0,
|
||||
{},
|
||||
{
|
||||
_id: 0,
|
||||
id: 1,
|
||||
name: 1,
|
||||
email: 1,
|
||||
corporateInformation: 1,
|
||||
type: 1,
|
||||
profilePicture: 1,
|
||||
subscriptionExpirationDate: 1,
|
||||
lastLogin: 1,
|
||||
}
|
||||
),
|
||||
getSpecificUsers([...group.participants, group.admin], {
|
||||
_id: 0,
|
||||
id: 1,
|
||||
name: 1,
|
||||
email: 1,
|
||||
corporateInformation: 1,
|
||||
type: 1,
|
||||
profilePicture: 1,
|
||||
subscriptionExpirationDate: 1,
|
||||
lastLogin: 1,
|
||||
}),
|
||||
]);
|
||||
|
||||
const linkedUsers = await getEntityUsers(entity.id)
|
||||
const users = await getSpecificUsers([...group.participants, group.admin]);
|
||||
const groupWithUser = convertToUsers(group, users);
|
||||
const groupWithUser = convertToUsers(group, users);
|
||||
|
||||
return {
|
||||
props: serialize({ user, group: groupWithUser, users: linkedUsers.filter(x => isAdmin(user) ? true : !isAdmin(x)), entity }),
|
||||
};
|
||||
}, sessionOptions);
|
||||
return {
|
||||
props: serialize({
|
||||
user,
|
||||
group: groupWithUser,
|
||||
users: linkedUsers.filter((x) => (isAdmin(user) ? true : !isAdmin(x))),
|
||||
entity,
|
||||
}),
|
||||
};
|
||||
},
|
||||
sessionOptions
|
||||
);
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
group: GroupWithUsers;
|
||||
users: User[];
|
||||
entity: EntityWithRoles
|
||||
user: User;
|
||||
group: GroupWithUsers;
|
||||
users: User[];
|
||||
entity: EntityWithRoles;
|
||||
}
|
||||
|
||||
export default function Home({ user, group, users, entity }: Props) {
|
||||
const [isAdding, setIsAdding] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [selectedUsers, setSelectedUsers] = useState<string[]>([]);
|
||||
const [isAdding, setIsAdding] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [selectedUsers, setSelectedUsers] = useState<string[]>([]);
|
||||
|
||||
const canAddParticipants = useEntityPermission(user, entity, "add_to_classroom")
|
||||
const canRemoveParticipants = useEntityPermission(user, entity, "remove_from_classroom")
|
||||
const canRenameClassroom = useEntityPermission(user, entity, "rename_classrooms")
|
||||
const canDeleteClassroom = useEntityPermission(user, entity, "delete_classroom")
|
||||
const canAddParticipants = useEntityPermission(
|
||||
user,
|
||||
entity,
|
||||
"add_to_classroom"
|
||||
);
|
||||
const canRemoveParticipants = useEntityPermission(
|
||||
user,
|
||||
entity,
|
||||
"remove_from_classroom"
|
||||
);
|
||||
const canRenameClassroom = useEntityPermission(
|
||||
user,
|
||||
entity,
|
||||
"rename_classrooms"
|
||||
);
|
||||
const canDeleteClassroom = useEntityPermission(
|
||||
user,
|
||||
entity,
|
||||
"delete_classroom"
|
||||
);
|
||||
|
||||
const nonParticipantUsers = useMemo(
|
||||
() => users.filter((x) => ![...group.participants.map((g) => g.id), group.admin.id, user.id].includes(x.id)),
|
||||
[users, group.participants, group.admin.id, user.id],
|
||||
);
|
||||
const nonParticipantUsers = useMemo(
|
||||
() =>
|
||||
users.filter(
|
||||
(x) =>
|
||||
![
|
||||
...group.participants.map((g) => g.id),
|
||||
group.admin.id,
|
||||
user.id,
|
||||
].includes(x.id)
|
||||
),
|
||||
[users, group.participants, group.admin.id, user.id]
|
||||
);
|
||||
|
||||
const { rows, renderSearch } = useListSearch<User>(
|
||||
[["name"], ["corporateInformation", "companyInformation", "name"]],
|
||||
isAdding ? nonParticipantUsers : group.participants,
|
||||
);
|
||||
const { items, renderMinimal } = usePagination<User>(rows, 20);
|
||||
const { rows, renderSearch } = useListSearch<User>(
|
||||
[["name"], ["corporateInformation", "companyInformation", "name"]],
|
||||
isAdding ? nonParticipantUsers : group.participants
|
||||
);
|
||||
const { items, renderMinimal } = usePagination<User>(rows, 20);
|
||||
|
||||
const router = useRouter();
|
||||
const router = useRouter();
|
||||
|
||||
const toggleUser = (u: User) => setSelectedUsers((prev) => (prev.includes(u.id) ? prev.filter((p) => p !== u.id) : [...prev, u.id]));
|
||||
const toggleUser = (u: User) =>
|
||||
setSelectedUsers((prev) =>
|
||||
prev.includes(u.id) ? prev.filter((p) => p !== u.id) : [...prev, u.id]
|
||||
);
|
||||
|
||||
const removeParticipants = () => {
|
||||
if (selectedUsers.length === 0) return;
|
||||
if (!canRemoveParticipants) return;
|
||||
if (!confirm(`Are you sure you want to remove ${selectedUsers.length} participant${selectedUsers.length === 1 ? "" : "s"} from this group?`))
|
||||
return;
|
||||
const removeParticipants = () => {
|
||||
if (selectedUsers.length === 0) return;
|
||||
if (!canRemoveParticipants) return;
|
||||
if (
|
||||
!confirm(
|
||||
`Are you sure you want to remove ${selectedUsers.length} participant${
|
||||
selectedUsers.length === 1 ? "" : "s"
|
||||
} from this group?`
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
setIsLoading(true);
|
||||
setIsLoading(true);
|
||||
|
||||
axios
|
||||
.patch(`/api/groups/${group.id}`, { participants: group.participants.map((x) => x.id).filter((x) => !selectedUsers.includes(x)) })
|
||||
.then(() => {
|
||||
toast.success("The group has been updated successfully!");
|
||||
router.replace(router.asPath);
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
toast.error("Something went wrong!");
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
axios
|
||||
.patch(`/api/groups/${group.id}`, {
|
||||
participants: group.participants
|
||||
.map((x) => x.id)
|
||||
.filter((x) => !selectedUsers.includes(x)),
|
||||
})
|
||||
.then(() => {
|
||||
toast.success("The group has been updated successfully!");
|
||||
router.replace(router.asPath);
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
toast.error("Something went wrong!");
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
const addParticipants = () => {
|
||||
if (selectedUsers.length === 0) return;
|
||||
if (!canAddParticipants || !isAdding) return;
|
||||
if (!confirm(`Are you sure you want to add ${selectedUsers.length} participant${selectedUsers.length === 1 ? "" : "s"} to this group?`))
|
||||
return;
|
||||
const addParticipants = () => {
|
||||
if (selectedUsers.length === 0) return;
|
||||
if (!canAddParticipants || !isAdding) return;
|
||||
if (
|
||||
!confirm(
|
||||
`Are you sure you want to add ${selectedUsers.length} participant${
|
||||
selectedUsers.length === 1 ? "" : "s"
|
||||
} to this group?`
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
setIsLoading(true);
|
||||
setIsLoading(true);
|
||||
|
||||
axios
|
||||
.patch(`/api/groups/${group.id}`, { participants: [...group.participants.map((x) => x.id), ...selectedUsers] })
|
||||
.then(() => {
|
||||
toast.success("The group has been updated successfully!");
|
||||
router.replace(router.asPath);
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
toast.error("Something went wrong!");
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
axios
|
||||
.patch(`/api/groups/${group.id}`, {
|
||||
participants: [
|
||||
...group.participants.map((x) => x.id),
|
||||
...selectedUsers,
|
||||
],
|
||||
})
|
||||
.then(() => {
|
||||
toast.success("The group has been updated successfully!");
|
||||
router.replace(router.asPath);
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
toast.error("Something went wrong!");
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
const renameGroup = () => {
|
||||
if (!canRenameClassroom) return;
|
||||
const renameGroup = () => {
|
||||
if (!canRenameClassroom) return;
|
||||
|
||||
const name = prompt("Rename this classroom:", group.name);
|
||||
if (!name) return;
|
||||
const name = prompt("Rename this classroom:", group.name);
|
||||
if (!name) return;
|
||||
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.patch(`/api/groups/${group.id}`, { name })
|
||||
.then(() => {
|
||||
toast.success("The classroom has been updated successfully!");
|
||||
router.replace(router.asPath);
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
toast.error("Something went wrong!");
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.patch(`/api/groups/${group.id}`, { name })
|
||||
.then(() => {
|
||||
toast.success("The classroom has been updated successfully!");
|
||||
router.replace(router.asPath);
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
toast.error("Something went wrong!");
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
const deleteGroup = () => {
|
||||
if (!canDeleteClassroom) return;
|
||||
if (!confirm("Are you sure you want to delete this classroom?")) return;
|
||||
const deleteGroup = () => {
|
||||
if (!canDeleteClassroom) return;
|
||||
if (!confirm("Are you sure you want to delete this classroom?")) return;
|
||||
|
||||
setIsLoading(true);
|
||||
setIsLoading(true);
|
||||
|
||||
axios
|
||||
.delete(`/api/groups/${group.id}`)
|
||||
.then(() => {
|
||||
toast.success("This classroom has been successfully deleted!");
|
||||
router.replace("/classrooms");
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
toast.error("Something went wrong!");
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
axios
|
||||
.delete(`/api/groups/${group.id}`)
|
||||
.then(() => {
|
||||
toast.success("This classroom has been successfully deleted!");
|
||||
router.replace("/classrooms");
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
toast.error("Something went wrong!");
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
useEffect(() => setSelectedUsers([]), [isAdding]);
|
||||
useEffect(() => setSelectedUsers([]), [isAdding]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{group.name} | EnCoach</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<ToastContainer />
|
||||
{user && (
|
||||
<>
|
||||
<section className="flex flex-col gap-0">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Link
|
||||
href="/classrooms"
|
||||
className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
|
||||
<BsChevronLeft />
|
||||
</Link>
|
||||
<h2 className="font-bold text-2xl">{group.name}</h2>
|
||||
</div>
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{group.name} | EnCoach</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<ToastContainer />
|
||||
{user && (
|
||||
<>
|
||||
<section className="flex flex-col gap-0">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Link
|
||||
href="/classrooms"
|
||||
className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl"
|
||||
>
|
||||
<BsChevronLeft />
|
||||
</Link>
|
||||
<h2 className="font-bold text-2xl">{group.name}</h2>
|
||||
</div>
|
||||
|
||||
{!isAdding && (
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={renameGroup}
|
||||
disabled={isLoading || !canRenameClassroom}
|
||||
className="flex items-center gap-1 px-2 py-2 border rounded-full hover:bg-neutral-100 disabled:hover:bg-transparent disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
|
||||
<BsTag />
|
||||
<span className="text-xs">Rename Classroom</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={deleteGroup}
|
||||
disabled={isLoading || !canDeleteClassroom}
|
||||
className="flex items-center gap-1 px-2 py-2 border border-mti-rose rounded-full bg-mti-rose-light text-white hover:bg-mti-rose-dark disabled:hover:bg-mti-rose-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
|
||||
<BsTrash />
|
||||
<span className="text-xs">Delete Classroom</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="flex items-center gap-2">
|
||||
<BsBuilding className="text-xl" /> {entity.label}
|
||||
</span>
|
||||
<span className="flex items-center gap-2">
|
||||
<BsFillPersonVcardFill className="text-xl" /> {getUserName(group.admin)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<Divider />
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<span className="font-semibold text-xl">Participants</span>
|
||||
{!isAdding && (
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => setIsAdding(true)}
|
||||
disabled={isLoading || !canAddParticipants}
|
||||
className="flex items-center gap-1 px-2 py-2 border rounded-full hover:bg-neutral-100 disabled:hover:bg-transparent disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
|
||||
<BsPlus />
|
||||
<span className="text-xs">Add Participants</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={removeParticipants}
|
||||
disabled={selectedUsers.length === 0 || isLoading || !canRemoveParticipants}
|
||||
className="flex items-center gap-1 px-2 py-2 border border-mti-rose rounded-full bg-mti-rose-light text-white hover:bg-mti-rose-dark disabled:hover:bg-mti-rose-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
|
||||
<BsTrash />
|
||||
<span className="text-xs">Remove Participants</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{isAdding && (
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => setIsAdding(false)}
|
||||
disabled={isLoading}
|
||||
className="flex items-center gap-1 px-2 py-2 border rounded-full border-mti-rose bg-mti-rose-light text-white hover:bg-mti-rose-dark disabled:hover:bg-mti-rose-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
|
||||
<BsX />
|
||||
<span className="text-xs">Discard Selection</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={addParticipants}
|
||||
disabled={selectedUsers.length === 0 || isLoading || !canAddParticipants}
|
||||
className="flex items-center gap-1 px-2 py-2 border rounded-full border-mti-green bg-mti-green-light text-white hover:bg-mti-green-dark disabled:hover:bg-mti-green-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
|
||||
<BsPlus />
|
||||
<span className="text-xs">Add Participants</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="w-full flex items-center gap-4">
|
||||
{renderSearch()}
|
||||
{renderMinimal()}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mt-4">
|
||||
{['student', 'teacher', 'corporate'].map((type) => (
|
||||
<button
|
||||
key={type}
|
||||
onClick={() => {
|
||||
const typeUsers = mapBy(filterBy(isAdding ? nonParticipantUsers : group.participants, 'type', type), 'id')
|
||||
if (typeUsers.every((u) => selectedUsers.includes(u))) {
|
||||
setSelectedUsers((prev) => prev.filter((a) => !typeUsers.includes(a)));
|
||||
} else {
|
||||
setSelectedUsers((prev) => [...prev.filter((a) => !typeUsers.includes(a)), ...typeUsers]);
|
||||
}
|
||||
}}
|
||||
disabled={filterBy(isAdding ? nonParticipantUsers : group.participants, 'type', type).length === 0}
|
||||
className={clsx(
|
||||
"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
|
||||
"transition duration-300 ease-in-out",
|
||||
"disabled:grayscale disabled:hover:bg-mti-purple-ultralight disabled:hover:text-mti-purple disabled:cursor-not-allowed",
|
||||
filterBy(isAdding ? nonParticipantUsers : group.participants, 'type', type).length > 0 &&
|
||||
filterBy(isAdding ? nonParticipantUsers : group.participants, 'type', type).every((u) => selectedUsers.includes(u.id)) &&
|
||||
"!bg-mti-purple-light !text-white",
|
||||
)}>
|
||||
{capitalize(type)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
{!isAdding && (
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={renameGroup}
|
||||
disabled={isLoading || !canRenameClassroom}
|
||||
className="flex items-center gap-1 px-2 py-2 border rounded-full hover:bg-neutral-100 disabled:hover:bg-transparent disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300"
|
||||
>
|
||||
<BsTag />
|
||||
<span className="text-xs">Rename Classroom</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={deleteGroup}
|
||||
disabled={isLoading || !canDeleteClassroom}
|
||||
className="flex items-center gap-1 px-2 py-2 border border-mti-rose rounded-full bg-mti-rose-light text-white hover:bg-mti-rose-dark disabled:hover:bg-mti-rose-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300"
|
||||
>
|
||||
<BsTrash />
|
||||
<span className="text-xs">Delete Classroom</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="flex items-center gap-2">
|
||||
<BsBuilding className="text-xl" /> {entity.label}
|
||||
</span>
|
||||
<span className="flex items-center gap-2">
|
||||
<BsFillPersonVcardFill className="text-xl" />{" "}
|
||||
{getUserName(group.admin)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<Divider />
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<span className="font-semibold text-xl">Participants</span>
|
||||
{!isAdding && (
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => setIsAdding(true)}
|
||||
disabled={isLoading || !canAddParticipants}
|
||||
className="flex items-center gap-1 px-2 py-2 border rounded-full hover:bg-neutral-100 disabled:hover:bg-transparent disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300"
|
||||
>
|
||||
<BsPlus />
|
||||
<span className="text-xs">Add Participants</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={removeParticipants}
|
||||
disabled={
|
||||
selectedUsers.length === 0 ||
|
||||
isLoading ||
|
||||
!canRemoveParticipants
|
||||
}
|
||||
className="flex items-center gap-1 px-2 py-2 border border-mti-rose rounded-full bg-mti-rose-light text-white hover:bg-mti-rose-dark disabled:hover:bg-mti-rose-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300"
|
||||
>
|
||||
<BsTrash />
|
||||
<span className="text-xs">Remove Participants</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{isAdding && (
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => setIsAdding(false)}
|
||||
disabled={isLoading}
|
||||
className="flex items-center gap-1 px-2 py-2 border rounded-full border-mti-rose bg-mti-rose-light text-white hover:bg-mti-rose-dark disabled:hover:bg-mti-rose-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300"
|
||||
>
|
||||
<BsX />
|
||||
<span className="text-xs">Discard Selection</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={addParticipants}
|
||||
disabled={
|
||||
selectedUsers.length === 0 ||
|
||||
isLoading ||
|
||||
!canAddParticipants
|
||||
}
|
||||
className="flex items-center gap-1 px-2 py-2 border rounded-full border-mti-green bg-mti-green-light text-white hover:bg-mti-green-dark disabled:hover:bg-mti-green-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300"
|
||||
>
|
||||
<BsPlus />
|
||||
<span className="text-xs">Add Participants</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="w-full flex items-center gap-4">
|
||||
{renderSearch()}
|
||||
{renderMinimal()}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mt-4">
|
||||
{["student", "teacher", "corporate"].map((type) => (
|
||||
<button
|
||||
key={type}
|
||||
onClick={() => {
|
||||
const typeUsers = mapBy(
|
||||
filterBy(
|
||||
isAdding ? nonParticipantUsers : group.participants,
|
||||
"type",
|
||||
type
|
||||
),
|
||||
"id"
|
||||
);
|
||||
if (typeUsers.every((u) => selectedUsers.includes(u))) {
|
||||
setSelectedUsers((prev) =>
|
||||
prev.filter((a) => !typeUsers.includes(a))
|
||||
);
|
||||
} else {
|
||||
setSelectedUsers((prev) => [
|
||||
...prev.filter((a) => !typeUsers.includes(a)),
|
||||
...typeUsers,
|
||||
]);
|
||||
}
|
||||
}}
|
||||
disabled={
|
||||
filterBy(
|
||||
isAdding ? nonParticipantUsers : group.participants,
|
||||
"type",
|
||||
type
|
||||
).length === 0
|
||||
}
|
||||
className={clsx(
|
||||
"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
|
||||
"transition duration-300 ease-in-out",
|
||||
"disabled:grayscale disabled:hover:bg-mti-purple-ultralight disabled:hover:text-mti-purple disabled:cursor-not-allowed",
|
||||
filterBy(
|
||||
isAdding ? nonParticipantUsers : group.participants,
|
||||
"type",
|
||||
type
|
||||
).length > 0 &&
|
||||
filterBy(
|
||||
isAdding ? nonParticipantUsers : group.participants,
|
||||
"type",
|
||||
type
|
||||
).every((u) => selectedUsers.includes(u.id)) &&
|
||||
"!bg-mti-purple-light !text-white"
|
||||
)}
|
||||
>
|
||||
{capitalize(type)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="w-full h-full grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{items.map((u) => (
|
||||
<button
|
||||
onClick={() => toggleUser(u)}
|
||||
disabled={isAdding ? !canAddParticipants : !canRemoveParticipants}
|
||||
key={u.id}
|
||||
className={clsx(
|
||||
"p-4 pr-6 h-48 relative border rounded-xl flex flex-col gap-3 justify-between text-left cursor-pointer",
|
||||
"hover:border-mti-purple transition ease-in-out duration-300",
|
||||
selectedUsers.includes(u.id) && "border-mti-purple",
|
||||
)}>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="min-w-[3rem] min-h-[3rem] w-12 h-12 border flex items-center justify-center overflow-hidden rounded-full">
|
||||
<img src={u.profilePicture} alt={u.name} />
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<span className="font-semibold">{getUserName(u)}</span>
|
||||
<span className="opacity-80 text-sm">{USER_TYPE_LABELS[u.type]}</span>
|
||||
</div>
|
||||
</div>
|
||||
<section className="w-full h-full grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{items.map((u) => (
|
||||
<button
|
||||
onClick={() => toggleUser(u)}
|
||||
disabled={
|
||||
isAdding ? !canAddParticipants : !canRemoveParticipants
|
||||
}
|
||||
key={u.id}
|
||||
className={clsx(
|
||||
"p-4 pr-6 h-48 relative border rounded-xl flex flex-col gap-3 justify-between text-left cursor-pointer",
|
||||
"hover:border-mti-purple transition ease-in-out duration-300",
|
||||
selectedUsers.includes(u.id) && "border-mti-purple"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="min-w-[3rem] min-h-[3rem] w-12 h-12 border flex items-center justify-center overflow-hidden rounded-full">
|
||||
<img src={u.profilePicture} alt={u.name} />
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<span className="font-semibold">{getUserName(u)}</span>
|
||||
<span className="opacity-80 text-sm">
|
||||
{USER_TYPE_LABELS[u.type]}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="flex items-center gap-2">
|
||||
<Tooltip tooltip="E-mail address">
|
||||
<BsEnvelopeFill />
|
||||
</Tooltip>
|
||||
{u.email}
|
||||
</span>
|
||||
<span className="flex items-center gap-2">
|
||||
<Tooltip tooltip="Expiration Date">
|
||||
<BsStopwatchFill />
|
||||
</Tooltip>
|
||||
{u.subscriptionExpirationDate ? moment(u.subscriptionExpirationDate).format("DD/MM/YYYY") : "Unlimited"}
|
||||
</span>
|
||||
<span className="flex items-center gap-2">
|
||||
<Tooltip tooltip="Last Login">
|
||||
<BsClockFill />
|
||||
</Tooltip>
|
||||
{u.lastLogin ? moment(u.lastLogin).format("DD/MM/YYYY - HH:mm") : "N/A"}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="flex items-center gap-2">
|
||||
<Tooltip tooltip="E-mail address">
|
||||
<BsEnvelopeFill />
|
||||
</Tooltip>
|
||||
{u.email}
|
||||
</span>
|
||||
<span className="flex items-center gap-2">
|
||||
<Tooltip tooltip="Expiration Date">
|
||||
<BsStopwatchFill />
|
||||
</Tooltip>
|
||||
{u.subscriptionExpirationDate
|
||||
? moment(u.subscriptionExpirationDate).format(
|
||||
"DD/MM/YYYY"
|
||||
)
|
||||
: "Unlimited"}
|
||||
</span>
|
||||
<span className="flex items-center gap-2">
|
||||
<Tooltip tooltip="Last Login">
|
||||
<BsClockFill />
|
||||
</Tooltip>
|
||||
{u.lastLogin
|
||||
? moment(u.lastLogin).format("DD/MM/YYYY - HH:mm")
|
||||
: "N/A"}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,221 +2,308 @@
|
||||
import Input from "@/components/Low/Input";
|
||||
import Select from "@/components/Low/Select";
|
||||
import Tooltip from "@/components/Low/Tooltip";
|
||||
import {useListSearch} from "@/hooks/useListSearch";
|
||||
import { useListSearch } from "@/hooks/useListSearch";
|
||||
import usePagination from "@/hooks/usePagination";
|
||||
import {EntityWithRoles} from "@/interfaces/entity";
|
||||
import {User} from "@/interfaces/user";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {USER_TYPE_LABELS} from "@/resources/user";
|
||||
import {filterBy, mapBy, redirect, serialize} from "@/utils";
|
||||
import { getEntitiesWithRoles} from "@/utils/entities.be";
|
||||
import {shouldRedirectHome} from "@/utils/navigation.disabled";
|
||||
import {getUserName, isAdmin} from "@/utils/users";
|
||||
import {getEntitiesUsers} from "@/utils/users.be";
|
||||
import { EntityWithRoles } from "@/interfaces/entity";
|
||||
import { User } from "@/interfaces/user";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { USER_TYPE_LABELS } from "@/resources/user";
|
||||
import { filterBy, mapBy, redirect, serialize } from "@/utils";
|
||||
import { getEntitiesWithRoles } from "@/utils/entities.be";
|
||||
import { shouldRedirectHome } from "@/utils/navigation.disabled";
|
||||
import { getUserName, isAdmin } from "@/utils/users";
|
||||
import { getEntitiesUsers } from "@/utils/users.be";
|
||||
import axios from "axios";
|
||||
import clsx from "clsx";
|
||||
import {withIronSessionSsr} from "iron-session/next";
|
||||
import { withIronSessionSsr } from "iron-session/next";
|
||||
import moment from "moment";
|
||||
import Head from "next/head";
|
||||
import Link from "next/link";
|
||||
import {useRouter} from "next/router";
|
||||
import {Divider} from "primereact/divider";
|
||||
import {useEffect, useMemo, useState} from "react";
|
||||
import {BsCheck, BsChevronLeft, BsClockFill, BsEnvelopeFill, BsStopwatchFill} from "react-icons/bs";
|
||||
import {toast, ToastContainer} from "react-toastify";
|
||||
import { useRouter } from "next/router";
|
||||
import { Divider } from "primereact/divider";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
BsCheck,
|
||||
BsChevronLeft,
|
||||
BsClockFill,
|
||||
BsEnvelopeFill,
|
||||
BsStopwatchFill,
|
||||
} from "react-icons/bs";
|
||||
import { toast, ToastContainer } from "react-toastify";
|
||||
import { requestUser } from "@/utils/api";
|
||||
import { findAllowedEntities } from "@/utils/permissions";
|
||||
import { capitalize } from "lodash";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||
const user = await requestUser(req, res)
|
||||
if (!user) return redirect("/login")
|
||||
export const getServerSideProps = withIronSessionSsr(async ({ req, res }) => {
|
||||
const user = await requestUser(req, res);
|
||||
if (!user) return redirect("/login");
|
||||
|
||||
if (shouldRedirectHome(user)) return redirect("/")
|
||||
if (shouldRedirectHome(user)) return redirect("/");
|
||||
|
||||
const entities = await getEntitiesWithRoles(isAdmin(user) ? undefined : mapBy(user.entities, "id"));
|
||||
const users = await getEntitiesUsers(mapBy(entities, 'id'))
|
||||
const allowedEntities = findAllowedEntities(user, entities, "create_classroom")
|
||||
const entities = await getEntitiesWithRoles(
|
||||
isAdmin(user) ? undefined : mapBy(user.entities, "id")
|
||||
);
|
||||
const users = await getEntitiesUsers(
|
||||
mapBy(entities, "id"),
|
||||
{
|
||||
id: { $ne: user.id },
|
||||
},
|
||||
0,
|
||||
{
|
||||
_id: 0,
|
||||
id: 1,
|
||||
name: 1,
|
||||
email: 1,
|
||||
profilePicture: 1,
|
||||
type: 1,
|
||||
corporateInformation: 1,
|
||||
lastLogin: 1,
|
||||
subscriptionExpirationDate: 1,
|
||||
}
|
||||
);
|
||||
const allowedEntities = findAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"create_classroom"
|
||||
);
|
||||
|
||||
return {
|
||||
props: serialize({user, entities: allowedEntities, users: users.filter((x) => x.id !== user.id)}),
|
||||
};
|
||||
return {
|
||||
props: serialize({
|
||||
user,
|
||||
entities: allowedEntities,
|
||||
users: users,
|
||||
}),
|
||||
};
|
||||
}, sessionOptions);
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
users: User[];
|
||||
entities: EntityWithRoles[];
|
||||
user: User;
|
||||
users: User[];
|
||||
entities: EntityWithRoles[];
|
||||
}
|
||||
|
||||
export default function Home({user, users, entities}: Props) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [selectedUsers, setSelectedUsers] = useState<string[]>([]);
|
||||
const [name, setName] = useState("");
|
||||
const [entity, setEntity] = useState<string | undefined>(entities[0]?.id);
|
||||
export default function Home({ user, users, entities }: Props) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [selectedUsers, setSelectedUsers] = useState<string[]>([]);
|
||||
const [name, setName] = useState("");
|
||||
const [entity, setEntity] = useState<string | undefined>(entities[0]?.id);
|
||||
|
||||
const entityUsers = useMemo(() => !entity ? users : users.filter(u => mapBy(u.entities, 'id').includes(entity)), [entity, users])
|
||||
const entityUsers = useMemo(
|
||||
() =>
|
||||
!entity
|
||||
? users
|
||||
: users.filter((u) => mapBy(u.entities, "id").includes(entity)),
|
||||
[entity, users]
|
||||
);
|
||||
|
||||
const {rows, renderSearch} = useListSearch<User>(
|
||||
[["name"], ["type"], ["corporateInformation", "companyInformation", "name"]], entityUsers
|
||||
);
|
||||
const { rows, renderSearch } = useListSearch<User>(
|
||||
[
|
||||
["name"],
|
||||
["type"],
|
||||
["corporateInformation", "companyInformation", "name"],
|
||||
],
|
||||
entityUsers
|
||||
);
|
||||
|
||||
const {items, renderMinimal} = usePagination<User>(rows, 16);
|
||||
const { items, renderMinimal } = usePagination<User>(rows, 16);
|
||||
|
||||
const router = useRouter();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => setSelectedUsers([]), [entity])
|
||||
useEffect(() => setSelectedUsers([]), [entity]);
|
||||
|
||||
const createGroup = () => {
|
||||
if (!name.trim()) return;
|
||||
if (!entity) return;
|
||||
if (!confirm(`Are you sure you want to create this group with ${selectedUsers.length} participants?`)) return;
|
||||
const createGroup = () => {
|
||||
if (!name.trim()) return;
|
||||
if (!entity) return;
|
||||
if (
|
||||
!confirm(
|
||||
`Are you sure you want to create this group with ${selectedUsers.length} participants?`
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
setIsLoading(true);
|
||||
setIsLoading(true);
|
||||
|
||||
axios
|
||||
.post<{id: string}>(`/api/groups`, {name, participants: selectedUsers, admin: user.id, entity})
|
||||
.then((result) => {
|
||||
toast.success("Your group has been created successfully!");
|
||||
router.replace(`/classrooms/${result.data.id}`);
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
toast.error("Something went wrong!");
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
axios
|
||||
.post<{ id: string }>(`/api/groups`, {
|
||||
name,
|
||||
participants: selectedUsers,
|
||||
admin: user.id,
|
||||
entity,
|
||||
})
|
||||
.then((result) => {
|
||||
toast.success("Your group has been created successfully!");
|
||||
router.replace(`/classrooms/${result.data.id}`);
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
toast.error("Something went wrong!");
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
const toggleUser = (u: User) => setSelectedUsers((prev) => (prev.includes(u.id) ? prev.filter((p) => p !== u.id) : [...prev, u.id]));
|
||||
const toggleUser = (u: User) =>
|
||||
setSelectedUsers((prev) =>
|
||||
prev.includes(u.id) ? prev.filter((p) => p !== u.id) : [...prev, u.id]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Create Group | EnCoach</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<ToastContainer />
|
||||
<>
|
||||
<section className="flex flex-col gap-0">
|
||||
<div className="flex gap-3 justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Link
|
||||
href="/classrooms"
|
||||
className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
|
||||
<BsChevronLeft />
|
||||
</Link>
|
||||
<h2 className="font-bold text-2xl">Create Classroom</h2>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
onClick={createGroup}
|
||||
disabled={!name.trim() || !entity || isLoading}
|
||||
className="flex items-center gap-1 px-2 py-2 border rounded-full border-mti-green bg-mti-green-light text-white hover:bg-mti-green-dark disabled:hover:bg-mti-green-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
|
||||
<BsCheck />
|
||||
<span className="text-xs">Create Classroom</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<Divider />
|
||||
<div className="grid grid-cols-2 gap-4 place-items-end">
|
||||
<div className="flex flex-col gap-4 w-full">
|
||||
<span className="font-semibold text-xl">Classroom Name:</span>
|
||||
<Input name="name" onChange={setName} type="text" placeholder="Classroom A" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-4 w-full">
|
||||
<span className="font-semibold text-xl">Entity:</span>
|
||||
<Select
|
||||
options={entities.map((e) => ({value: e.id, label: e.label}))}
|
||||
onChange={(v) => setEntity(v ? v.value! : undefined)}
|
||||
defaultValue={{value: entities[0]?.id, label: entities[0]?.label}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<Divider />
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<span className="font-semibold text-xl">Participants ({selectedUsers.length} selected):</span>
|
||||
</div>
|
||||
<div className="w-full flex items-center gap-4">
|
||||
{renderSearch()}
|
||||
{renderMinimal()}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mt-4">
|
||||
{['student', 'teacher', 'corporate'].map((type) => (
|
||||
<button
|
||||
key={type}
|
||||
onClick={() => {
|
||||
const typeUsers = mapBy(filterBy(entityUsers, 'type', type), 'id')
|
||||
if (typeUsers.every((u) => selectedUsers.includes(u))) {
|
||||
setSelectedUsers((prev) => prev.filter((a) => !typeUsers.includes(a)));
|
||||
} else {
|
||||
setSelectedUsers((prev) => [...prev.filter((a) => !typeUsers.includes(a)), ...typeUsers]);
|
||||
}
|
||||
}}
|
||||
disabled={filterBy(entityUsers, 'type', type).length === 0}
|
||||
className={clsx(
|
||||
"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
|
||||
"transition duration-300 ease-in-out",
|
||||
"disabled:grayscale disabled:hover:bg-mti-purple-ultralight disabled:hover:text-mti-purple disabled:cursor-not-allowed",
|
||||
filterBy(entityUsers, 'type', type).length > 0 &&
|
||||
filterBy(entityUsers, 'type', type).every((u) => selectedUsers.includes(u.id)) &&
|
||||
"!bg-mti-purple-light !text-white",
|
||||
)}>
|
||||
{capitalize(type)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Create Group | EnCoach</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<ToastContainer />
|
||||
<>
|
||||
<section className="flex flex-col gap-0">
|
||||
<div className="flex gap-3 justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Link
|
||||
href="/classrooms"
|
||||
className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl"
|
||||
>
|
||||
<BsChevronLeft />
|
||||
</Link>
|
||||
<h2 className="font-bold text-2xl">Create Classroom</h2>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
onClick={createGroup}
|
||||
disabled={!name.trim() || !entity || isLoading}
|
||||
className="flex items-center gap-1 px-2 py-2 border rounded-full border-mti-green bg-mti-green-light text-white hover:bg-mti-green-dark disabled:hover:bg-mti-green-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300"
|
||||
>
|
||||
<BsCheck />
|
||||
<span className="text-xs">Create Classroom</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<Divider />
|
||||
<div className="grid grid-cols-2 gap-4 place-items-end">
|
||||
<div className="flex flex-col gap-4 w-full">
|
||||
<span className="font-semibold text-xl">Classroom Name:</span>
|
||||
<Input
|
||||
name="name"
|
||||
onChange={setName}
|
||||
type="text"
|
||||
placeholder="Classroom A"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-4 w-full">
|
||||
<span className="font-semibold text-xl">Entity:</span>
|
||||
<Select
|
||||
options={entities.map((e) => ({ value: e.id, label: e.label }))}
|
||||
onChange={(v) => setEntity(v ? v.value! : undefined)}
|
||||
defaultValue={{
|
||||
value: entities[0]?.id,
|
||||
label: entities[0]?.label,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<Divider />
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<span className="font-semibold text-xl">
|
||||
Participants ({selectedUsers.length} selected):
|
||||
</span>
|
||||
</div>
|
||||
<div className="w-full flex items-center gap-4">
|
||||
{renderSearch()}
|
||||
{renderMinimal()}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mt-4">
|
||||
{["student", "teacher", "corporate"].map((type) => (
|
||||
<button
|
||||
key={type}
|
||||
onClick={() => {
|
||||
const typeUsers = mapBy(
|
||||
filterBy(entityUsers, "type", type),
|
||||
"id"
|
||||
);
|
||||
if (typeUsers.every((u) => selectedUsers.includes(u))) {
|
||||
setSelectedUsers((prev) =>
|
||||
prev.filter((a) => !typeUsers.includes(a))
|
||||
);
|
||||
} else {
|
||||
setSelectedUsers((prev) => [
|
||||
...prev.filter((a) => !typeUsers.includes(a)),
|
||||
...typeUsers,
|
||||
]);
|
||||
}
|
||||
}}
|
||||
disabled={filterBy(entityUsers, "type", type).length === 0}
|
||||
className={clsx(
|
||||
"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
|
||||
"transition duration-300 ease-in-out",
|
||||
"disabled:grayscale disabled:hover:bg-mti-purple-ultralight disabled:hover:text-mti-purple disabled:cursor-not-allowed",
|
||||
filterBy(entityUsers, "type", type).length > 0 &&
|
||||
filterBy(entityUsers, "type", type).every((u) =>
|
||||
selectedUsers.includes(u.id)
|
||||
) &&
|
||||
"!bg-mti-purple-light !text-white"
|
||||
)}
|
||||
>
|
||||
{capitalize(type)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="w-full h-full grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{items.map((u) => (
|
||||
<button
|
||||
onClick={() => toggleUser(u)}
|
||||
disabled={isLoading}
|
||||
key={u.id}
|
||||
className={clsx(
|
||||
"p-4 pr-6 h-48 relative border rounded-xl flex flex-col gap-3 justify-between text-left cursor-pointer",
|
||||
"hover:border-mti-purple transition ease-in-out duration-300",
|
||||
selectedUsers.includes(u.id) && "border-mti-purple",
|
||||
)}>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="min-w-[3rem] min-h-[3rem] w-12 h-12 border flex items-center justify-center overflow-hidden rounded-full">
|
||||
<img src={u.profilePicture} alt={u.name} />
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<span className="font-semibold">{getUserName(u)}</span>
|
||||
<span className="opacity-80 text-sm">{USER_TYPE_LABELS[u.type]}</span>
|
||||
</div>
|
||||
</div>
|
||||
<section className="w-full h-full grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{items.map((u) => (
|
||||
<button
|
||||
onClick={() => toggleUser(u)}
|
||||
disabled={isLoading}
|
||||
key={u.id}
|
||||
className={clsx(
|
||||
"p-4 pr-6 h-48 relative border rounded-xl flex flex-col gap-3 justify-between text-left cursor-pointer",
|
||||
"hover:border-mti-purple transition ease-in-out duration-300",
|
||||
selectedUsers.includes(u.id) && "border-mti-purple"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="min-w-[3rem] min-h-[3rem] w-12 h-12 border flex items-center justify-center overflow-hidden rounded-full">
|
||||
<img src={u.profilePicture} alt={u.name} />
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<span className="font-semibold">{getUserName(u)}</span>
|
||||
<span className="opacity-80 text-sm">
|
||||
{USER_TYPE_LABELS[u.type]}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="flex items-center gap-2">
|
||||
<Tooltip tooltip="E-mail address">
|
||||
<BsEnvelopeFill />
|
||||
</Tooltip>
|
||||
{u.email}
|
||||
</span>
|
||||
<span className="flex items-center gap-2">
|
||||
<Tooltip tooltip="Expiration Date">
|
||||
<BsStopwatchFill />
|
||||
</Tooltip>
|
||||
{u.subscriptionExpirationDate ? moment(u.subscriptionExpirationDate).format("DD/MM/YYYY") : "Unlimited"}
|
||||
</span>
|
||||
<span className="flex items-center gap-2">
|
||||
<Tooltip tooltip="Last Login">
|
||||
<BsClockFill />
|
||||
</Tooltip>
|
||||
{u.lastLogin ? moment(u.lastLogin).format("DD/MM/YYYY - HH:mm") : "N/A"}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</section>
|
||||
</>
|
||||
</>
|
||||
);
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="flex items-center gap-2">
|
||||
<Tooltip tooltip="E-mail address">
|
||||
<BsEnvelopeFill />
|
||||
</Tooltip>
|
||||
{u.email}
|
||||
</span>
|
||||
<span className="flex items-center gap-2">
|
||||
<Tooltip tooltip="Expiration Date">
|
||||
<BsStopwatchFill />
|
||||
</Tooltip>
|
||||
{u.subscriptionExpirationDate
|
||||
? moment(u.subscriptionExpirationDate).format("DD/MM/YYYY")
|
||||
: "Unlimited"}
|
||||
</span>
|
||||
<span className="flex items-center gap-2">
|
||||
<Tooltip tooltip="Last Login">
|
||||
<BsClockFill />
|
||||
</Tooltip>
|
||||
{u.lastLogin
|
||||
? moment(u.lastLogin).format("DD/MM/YYYY - HH:mm")
|
||||
: "N/A"}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</section>
|
||||
</>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -27,132 +27,182 @@ import StudentClassroomTransfer from "@/components/Imports/StudentClassroomTrans
|
||||
import Modal from "@/components/Modal";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(async ({ req, res }) => {
|
||||
const user = await requestUser(req, res)
|
||||
if (!user) return redirect("/login")
|
||||
const user = await requestUser(req, res);
|
||||
if (!user) return redirect("/login");
|
||||
|
||||
if (shouldRedirectHome(user)) return redirect("/")
|
||||
if (shouldRedirectHome(user)) return redirect("/");
|
||||
|
||||
const entityIDS = mapBy(user.entities, "id");
|
||||
const entities = await getEntitiesWithRoles(isAdmin(user) ? undefined : entityIDS)
|
||||
const allowedEntities = findAllowedEntities(user, entities, "view_classrooms")
|
||||
const entityIDS = mapBy(user.entities, "id");
|
||||
const entities = await getEntitiesWithRoles(
|
||||
isAdmin(user) ? undefined : entityIDS
|
||||
);
|
||||
|
||||
const groups = await getGroupsForEntities(mapBy(allowedEntities, 'id'));
|
||||
const allowedEntities = findAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"view_classrooms"
|
||||
);
|
||||
|
||||
const users = await getSpecificUsers(uniq(groups.flatMap((g) => [...g.participants, g.admin])));
|
||||
const groupsWithUsers: GroupWithUsers[] = groups.map((g) => convertToUsers(g, users.filter(x => isAdmin(user) ? true : !isAdmin(x))));
|
||||
const groups = await getGroupsForEntities(mapBy(allowedEntities, "id"));
|
||||
|
||||
return {
|
||||
props: serialize({ user, groups: groupsWithUsers, entities: allowedEntities }),
|
||||
};
|
||||
const users = await getSpecificUsers(
|
||||
uniq(groups.flatMap((g) => [...g.participants, g.admin])),
|
||||
{ _id: 0, id: 1, name: 1, email: 1, corporateInformation: 1, type: 1 }
|
||||
);
|
||||
const groupsWithUsers: GroupWithUsers[] = groups.map((g) =>
|
||||
convertToUsers(
|
||||
g,
|
||||
users.filter((x) => (isAdmin(user) ? true : !isAdmin(x)))
|
||||
)
|
||||
);
|
||||
|
||||
return {
|
||||
props: serialize({
|
||||
user,
|
||||
groups: groupsWithUsers,
|
||||
entities: allowedEntities,
|
||||
}),
|
||||
};
|
||||
}, sessionOptions);
|
||||
|
||||
const SEARCH_FIELDS = [
|
||||
["name"],
|
||||
["admin", "name"],
|
||||
["admin", "email"],
|
||||
["admin", "corporateInformation", "companyInformation", "name"],
|
||||
["participants", "name"],
|
||||
["participants", "email"],
|
||||
["participants", "corporateInformation", "companyInformation", "name"],
|
||||
["name"],
|
||||
["admin", "name"],
|
||||
["admin", "email"],
|
||||
["admin", "corporateInformation", "companyInformation", "name"],
|
||||
["participants", "name"],
|
||||
["participants", "email"],
|
||||
["participants", "corporateInformation", "companyInformation", "name"],
|
||||
];
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
groups: GroupWithUsers[];
|
||||
entities: EntityWithRoles[]
|
||||
user: User;
|
||||
groups: GroupWithUsers[];
|
||||
entities: EntityWithRoles[];
|
||||
}
|
||||
export default function Home({ user, groups, entities }: Props) {
|
||||
const entitiesAllowCreate = useAllowedEntities(user, entities, 'create_classroom');
|
||||
const [showImport, setShowImport] = useState(false);
|
||||
const entitiesAllowCreate = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"create_classroom"
|
||||
);
|
||||
const [showImport, setShowImport] = useState(false);
|
||||
|
||||
const renderCard = (group: GroupWithUsers) => (
|
||||
<Link
|
||||
href={`/classrooms/${group.id}`}
|
||||
key={group.id}
|
||||
className="p-4 border-2 border-mti-purple-light/20 rounded-xl flex gap-2 justify-between hover:border-mti-purple group transition ease-in-out duration-300 text-left cursor-pointer">
|
||||
<div className="flex flex-col gap-2 w-full">
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="bg-mti-purple text-white font-semibold px-2">Classroom</span>
|
||||
{group.name}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="bg-mti-purple text-white font-semibold px-2">Admin</span>
|
||||
{getUserName(group.admin)}
|
||||
</span>
|
||||
{!!group.entity && (
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="bg-mti-purple text-white font-semibold px-2">Entity</span>
|
||||
{findBy(entities, 'id', group.entity)?.label}
|
||||
</span>
|
||||
)}
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="bg-mti-purple text-white font-semibold px-2">Participants</span>
|
||||
<span className="bg-mti-purple-light/50 px-2">{group.participants.length}</span>
|
||||
</span>
|
||||
<span>
|
||||
{group.participants.slice(0, 3).map(getUserName).join(", ")}{' '}
|
||||
{group.participants.length > 3 ? <span className="opacity-50 bg-mti-purple-light/50 px-1 text-sm">and {group.participants.length - 3} more</span> : ""}
|
||||
</span>
|
||||
</div>
|
||||
<div className="w-fit">
|
||||
<FaPersonChalkboard className="w-full h-20 -translate-y-[15%] group-hover:text-mti-purple transition ease-in-out duration-300" />
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
const renderCard = (group: GroupWithUsers) => (
|
||||
<Link
|
||||
href={`/classrooms/${group.id}`}
|
||||
key={group.id}
|
||||
className="p-4 border-2 border-mti-purple-light/20 rounded-xl flex gap-2 justify-between hover:border-mti-purple group transition ease-in-out duration-300 text-left cursor-pointer"
|
||||
>
|
||||
<div className="flex flex-col gap-2 w-full">
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="bg-mti-purple text-white font-semibold px-2">
|
||||
Classroom
|
||||
</span>
|
||||
{group.name}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="bg-mti-purple text-white font-semibold px-2">
|
||||
Admin
|
||||
</span>
|
||||
{getUserName(group.admin)}
|
||||
</span>
|
||||
{!!group.entity && (
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="bg-mti-purple text-white font-semibold px-2">
|
||||
Entity
|
||||
</span>
|
||||
{findBy(entities, "id", group.entity)?.label}
|
||||
</span>
|
||||
)}
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="bg-mti-purple text-white font-semibold px-2">
|
||||
Participants
|
||||
</span>
|
||||
<span className="bg-mti-purple-light/50 px-2">
|
||||
{group.participants.length}
|
||||
</span>
|
||||
</span>
|
||||
<span>
|
||||
{group.participants.slice(0, 3).map(getUserName).join(", ")}{" "}
|
||||
{group.participants.length > 3 ? (
|
||||
<span className="opacity-50 bg-mti-purple-light/50 px-1 text-sm">
|
||||
and {group.participants.length - 3} more
|
||||
</span>
|
||||
) : (
|
||||
""
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="w-fit">
|
||||
<FaPersonChalkboard className="w-full h-20 -translate-y-[15%] group-hover:text-mti-purple transition ease-in-out duration-300" />
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
|
||||
const firstCard = () => (
|
||||
<Link
|
||||
href={`/classrooms/create`}
|
||||
className="p-4 border-2 hover:text-mti-purple rounded-xl flex flex-col items-center justify-center gap-0 hover:border-mti-purple transition ease-in-out duration-300 text-left cursor-pointer">
|
||||
<BsPlus size={40} />
|
||||
<span className="font-semibold">Create Classroom</span>
|
||||
</Link>
|
||||
);
|
||||
const firstCard = () => (
|
||||
<Link
|
||||
href={`/classrooms/create`}
|
||||
className="p-4 border-2 hover:text-mti-purple rounded-xl flex flex-col items-center justify-center gap-0 hover:border-mti-purple transition ease-in-out duration-300 text-left cursor-pointer"
|
||||
>
|
||||
<BsPlus size={40} />
|
||||
<span className="font-semibold">Create Classroom</span>
|
||||
</Link>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Classrooms | EnCoach</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<ToastContainer />
|
||||
<>
|
||||
<section className="flex flex-col gap-4 w-full h-full">
|
||||
<Modal isOpen={showImport} onClose={() => setShowImport(false)} maxWidth="max-w-[85%]">
|
||||
<StudentClassroomTransfer user={user} entities={entities} onFinish={() => setShowImport(false)} />
|
||||
</Modal>
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex justify-between">
|
||||
<h2 className="font-bold text-2xl">Classrooms</h2>
|
||||
{entitiesAllowCreate.length !== 0 && <button
|
||||
className={clsx(
|
||||
"flex flex-row gap-3 items-center py-1.5 px-4 text-lg",
|
||||
"bg-mti-purple-light border border-mti-purple-light rounded-xl text-white",
|
||||
"hover:bg-white hover:text-mti-purple-light transition duration-300 ease-in-out",
|
||||
)}
|
||||
onClick={() => setShowImport(true)}
|
||||
>
|
||||
<FaFileUpload className="w-5 h-5" />
|
||||
Transfer Students
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
<Separator />
|
||||
</div>
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Classrooms | EnCoach</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<ToastContainer />
|
||||
<>
|
||||
<section className="flex flex-col gap-4 w-full h-full">
|
||||
<Modal
|
||||
isOpen={showImport}
|
||||
onClose={() => setShowImport(false)}
|
||||
maxWidth="max-w-[85%]"
|
||||
>
|
||||
<StudentClassroomTransfer
|
||||
user={user}
|
||||
entities={entities}
|
||||
onFinish={() => setShowImport(false)}
|
||||
/>
|
||||
</Modal>
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex justify-between">
|
||||
<h2 className="font-bold text-2xl">Classrooms</h2>
|
||||
{entitiesAllowCreate.length !== 0 && (
|
||||
<button
|
||||
className={clsx(
|
||||
"flex flex-row gap-3 items-center py-1.5 px-4 text-lg",
|
||||
"bg-mti-purple-light border border-mti-purple-light rounded-xl text-white",
|
||||
"hover:bg-white hover:text-mti-purple-light transition duration-300 ease-in-out"
|
||||
)}
|
||||
onClick={() => setShowImport(true)}
|
||||
>
|
||||
<FaFileUpload className="w-5 h-5" />
|
||||
Transfer Students
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<Separator />
|
||||
</div>
|
||||
|
||||
<CardList<GroupWithUsers>
|
||||
list={groups}
|
||||
searchFields={SEARCH_FIELDS}
|
||||
renderCard={renderCard}
|
||||
firstCard={entitiesAllowCreate.length === 0 ? undefined : firstCard}
|
||||
/>
|
||||
</section>
|
||||
</>
|
||||
</>
|
||||
);
|
||||
<CardList<GroupWithUsers>
|
||||
list={groups}
|
||||
searchFields={SEARCH_FIELDS}
|
||||
renderCard={renderCard}
|
||||
firstCard={entitiesAllowCreate.length === 0 ? undefined : firstCard}
|
||||
/>
|
||||
</section>
|
||||
</>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user