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:
File diff suppressed because it is too large
Load Diff
@@ -10,7 +10,7 @@ import { USER_TYPE_LABELS } from "@/resources/user";
|
||||
import { redirect, serialize } from "@/utils";
|
||||
import { shouldRedirectHome } from "@/utils/navigation.disabled";
|
||||
import { getUserName } from "@/utils/users";
|
||||
import { getUsers } from "@/utils/users.be";
|
||||
import { getUsers } from "@/utils/users.be";
|
||||
import axios from "axios";
|
||||
import clsx from "clsx";
|
||||
import { withIronSessionSsr } from "iron-session/next";
|
||||
@@ -20,161 +20,218 @@ import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { Divider } from "primereact/divider";
|
||||
import { useState } from "react";
|
||||
import { BsCheck, BsChevronLeft, BsClockFill, BsEnvelopeFill, BsStopwatchFill } from "react-icons/bs";
|
||||
import {
|
||||
BsCheck,
|
||||
BsChevronLeft,
|
||||
BsClockFill,
|
||||
BsEnvelopeFill,
|
||||
BsStopwatchFill,
|
||||
} from "react-icons/bs";
|
||||
import { toast, ToastContainer } from "react-toastify";
|
||||
import { requestUser } from "@/utils/api";
|
||||
|
||||
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 (!["admin", "developer"].includes(user.type)) return redirect("/entities")
|
||||
if (shouldRedirectHome(user)) return redirect("/");
|
||||
if (!["admin", "developer"].includes(user.type)) return redirect("/entities");
|
||||
|
||||
const users = await getUsers()
|
||||
const users = await getUsers(
|
||||
{ id: { $ne: user.id } },
|
||||
0,
|
||||
{},
|
||||
{
|
||||
_id: 0,
|
||||
id: 1,
|
||||
name: 1,
|
||||
type: 1,
|
||||
profilePicture: 1,
|
||||
email: 1,
|
||||
lastLogin: 1,
|
||||
subscriptionExpirationDate: 1,
|
||||
}
|
||||
);
|
||||
|
||||
return {
|
||||
props: serialize({ user, users: users.filter((x) => x.id !== user.id) }),
|
||||
};
|
||||
return {
|
||||
props: serialize({ user, users }),
|
||||
};
|
||||
}, sessionOptions);
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
users: User[];
|
||||
user: User;
|
||||
users: User[];
|
||||
}
|
||||
|
||||
export default function Home({ user, users }: Props) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [selectedUsers, setSelectedUsers] = useState<string[]>([]);
|
||||
const [label, setLabel] = useState("");
|
||||
const [licenses, setLicenses] = useState(0);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [selectedUsers, setSelectedUsers] = useState<string[]>([]);
|
||||
const [label, setLabel] = useState("");
|
||||
const [licenses, setLicenses] = useState(0);
|
||||
|
||||
const { rows, renderSearch } = useListSearch<User>([["name"], ["corporateInformation", "companyInformation", "name"]], users);
|
||||
const { items, renderMinimal } = usePagination<User>(rows, 16);
|
||||
const { rows, renderSearch } = useListSearch<User>(
|
||||
[["name"], ["corporateInformation", "companyInformation", "name"]],
|
||||
users
|
||||
);
|
||||
const { items, renderMinimal } = usePagination<User>(rows, 16);
|
||||
|
||||
const router = useRouter();
|
||||
const router = useRouter();
|
||||
|
||||
const createGroup = () => {
|
||||
if (!label.trim()) return;
|
||||
if (!confirm(`Are you sure you want to create this entity with ${selectedUsers.length} members?`)) return;
|
||||
const createGroup = () => {
|
||||
if (!label.trim()) return;
|
||||
if (
|
||||
!confirm(
|
||||
`Are you sure you want to create this entity with ${selectedUsers.length} members?`
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
setIsLoading(true);
|
||||
setIsLoading(true);
|
||||
|
||||
axios
|
||||
.post<Entity>(`/api/entities`, { label, licenses, members: selectedUsers })
|
||||
.then((result) => {
|
||||
toast.success("Your entity has been created successfully!");
|
||||
router.replace(`/entities/${result.data.id}`);
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
toast.error("Something went wrong!");
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
axios
|
||||
.post<Entity>(`/api/entities`, {
|
||||
label,
|
||||
licenses,
|
||||
members: selectedUsers,
|
||||
})
|
||||
.then((result) => {
|
||||
toast.success("Your entity has been created successfully!");
|
||||
router.replace(`/entities/${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 Entity | 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 Entity</h2>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
onClick={createGroup}
|
||||
disabled={!label.trim() || licenses <= 0 || 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 Entity</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<Divider />
|
||||
<div className="w-full grid grid-cols-2 gap-4">
|
||||
<div className="flex flex-col gap-4 w-full">
|
||||
<span className="font-semibold text-xl">Entity Label:</span>
|
||||
<Input name="name" onChange={setLabel} type="text" placeholder="Entity A" />
|
||||
</div>
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Create Entity | 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 Entity</h2>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
onClick={createGroup}
|
||||
disabled={!label.trim() || licenses <= 0 || 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 Entity</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<Divider />
|
||||
<div className="w-full grid grid-cols-2 gap-4">
|
||||
<div className="flex flex-col gap-4 w-full">
|
||||
<span className="font-semibold text-xl">Entity Label:</span>
|
||||
<Input
|
||||
name="name"
|
||||
onChange={setLabel}
|
||||
type="text"
|
||||
placeholder="Entity A"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4 w-full">
|
||||
<span className="font-semibold text-xl">Licenses:</span>
|
||||
<Input name="licenses" min={0} onChange={(v) => setLicenses(parseInt(v))} type="number" placeholder="12" />
|
||||
</div>
|
||||
</div>
|
||||
<Divider />
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<span className="font-semibold text-xl">Members ({selectedUsers.length} selected):</span>
|
||||
</div>
|
||||
<div className="w-full flex items-center gap-4">
|
||||
{renderSearch()}
|
||||
{renderMinimal()}
|
||||
</div>
|
||||
</section>
|
||||
<div className="flex flex-col gap-4 w-full">
|
||||
<span className="font-semibold text-xl">Licenses:</span>
|
||||
<Input
|
||||
name="licenses"
|
||||
min={0}
|
||||
onChange={(v) => setLicenses(parseInt(v))}
|
||||
type="number"
|
||||
placeholder="12"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<Divider />
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<span className="font-semibold text-xl">
|
||||
Members ({selectedUsers.length} selected):
|
||||
</span>
|
||||
</div>
|
||||
<div className="w-full flex items-center gap-4">
|
||||
{renderSearch()}
|
||||
{renderMinimal()}
|
||||
</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>
|
||||
</>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -35,17 +35,35 @@ export const getServerSideProps = withIronSessionSsr(async ({ req, res }) => {
|
||||
);
|
||||
const allowedEntities = findAllowedEntities(user, entities, "view_entities");
|
||||
|
||||
const entitiesWithCount = await Promise.all(
|
||||
allowedEntities.map(async (e) => ({
|
||||
entity: e,
|
||||
count: await countEntityUsers(e.id, {
|
||||
type: { $in: ["student", "teacher", "corporate", "mastercorporate"] },
|
||||
}),
|
||||
users: await getEntityUsers(e.id, 5, {
|
||||
type: { $in: ["student", "teacher", "corporate", "mastercorporate"] },
|
||||
}),
|
||||
}))
|
||||
);
|
||||
const [counts, users] = await Promise.all([
|
||||
await Promise.all(
|
||||
allowedEntities.map(async (e) =>
|
||||
countEntityUsers(e.id, {
|
||||
type: { $in: ["student", "teacher", "corporate", "mastercorporate"] },
|
||||
})
|
||||
)
|
||||
),
|
||||
await Promise.all(
|
||||
allowedEntities.map(async (e) =>
|
||||
getEntityUsers(
|
||||
e.id,
|
||||
5,
|
||||
{
|
||||
type: {
|
||||
$in: ["student", "teacher", "corporate", "mastercorporate"],
|
||||
},
|
||||
},
|
||||
{ name: 1 }
|
||||
)
|
||||
)
|
||||
),
|
||||
]);
|
||||
|
||||
const entitiesWithCount = allowedEntities.map<{
|
||||
entity: EntityWithRoles;
|
||||
users: User[];
|
||||
count: number;
|
||||
}>((e, i) => ({ entity: e, users: users[i], count: counts[i] }));
|
||||
|
||||
return {
|
||||
props: serialize({ user, entities: entitiesWithCount }),
|
||||
|
||||
Reference in New Issue
Block a user