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:
@@ -1,225 +1,269 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import Head from "next/head";
|
||||
import {withIronSessionSsr} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {User} from "@/interfaces/user";
|
||||
import {ToastContainer} from "react-toastify";
|
||||
import {shouldRedirectHome} from "@/utils/navigation.disabled";
|
||||
import {useEffect, useState} from "react";
|
||||
import { withIronSessionSsr } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { User } from "@/interfaces/user";
|
||||
import { ToastContainer } from "react-toastify";
|
||||
import { shouldRedirectHome } from "@/utils/navigation.disabled";
|
||||
import { useEffect, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import {FaPlus} from "react-icons/fa";
|
||||
import { FaPlus } from "react-icons/fa";
|
||||
import useRecordStore from "@/stores/recordStore";
|
||||
import router from "next/router";
|
||||
import useTrainingContentStore from "@/stores/trainingContentStore";
|
||||
import axios from "axios";
|
||||
import {ITrainingContent} from "@/training/TrainingInterfaces";
|
||||
import { ITrainingContent } from "@/training/TrainingInterfaces";
|
||||
import moment from "moment";
|
||||
import {uuidv4} from "@firebase/util";
|
||||
import { uuidv4 } from "@firebase/util";
|
||||
import TrainingScore from "@/training/TrainingScore";
|
||||
import ModuleBadge from "@/components/ModuleBadge";
|
||||
import RecordFilter from "@/components/Medium/RecordFilter";
|
||||
import useFilterRecordsByUser from "@/hooks/useFilterRecordsByUser";
|
||||
import { mapBy, redirect, serialize } from "@/utils";
|
||||
import { getEntitiesWithRoles } from "@/utils/entities.be";
|
||||
import { getEntitiesUsers } from "@/utils/users.be";
|
||||
import { EntityWithRoles } from "@/interfaces/entity";
|
||||
import { requestUser } from "@/utils/api";
|
||||
import { checkAccess } from "../../utils/permissions";
|
||||
|
||||
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 isAdmin = checkAccess(user, ["admin", "developer"]);
|
||||
const entityIDs = mapBy(user.entities, "id");
|
||||
const users = await getEntitiesUsers(entityIDs);
|
||||
|
||||
const entityIDs = mapBy(user.entities, 'id')
|
||||
const entities = await getEntitiesWithRoles(entityIDs)
|
||||
const users = await getEntitiesUsers(entityIDs)
|
||||
|
||||
return {
|
||||
props: serialize({user, users, entities}),
|
||||
};
|
||||
return {
|
||||
props: serialize({ user, users, isAdmin }),
|
||||
};
|
||||
}, sessionOptions);
|
||||
|
||||
const Training: React.FC<{user: User, entities: EntityWithRoles[], users: User[] }> = ({user, entities, users}) => {
|
||||
const [recordUserId, setRecordTraining] = useRecordStore((state) => [state.selectedUser, state.setTraining]);
|
||||
const [filter, setFilter] = useState<"months" | "weeks" | "days" | "assignments">();
|
||||
const Training: React.FC<{
|
||||
user: User;
|
||||
entities: EntityWithRoles[];
|
||||
users: User[];
|
||||
isAdmin: boolean;
|
||||
}> = ({ user, entities, isAdmin }) => {
|
||||
const [recordUserId, setRecordTraining] = useRecordStore((state) => [
|
||||
state.selectedUser,
|
||||
state.setTraining,
|
||||
]);
|
||||
const [filter, setFilter] = useState<
|
||||
"months" | "weeks" | "days" | "assignments"
|
||||
>();
|
||||
|
||||
const [stats, setTrainingStats] = useTrainingContentStore((state) => [state.stats, state.setStats]);
|
||||
const [isNewContentLoading, setIsNewContentLoading] = useState(stats.length != 0);
|
||||
const [groupedByTrainingContent, setGroupedByTrainingContent] = useState<{[key: string]: ITrainingContent}>();
|
||||
const [stats, setTrainingStats] = useTrainingContentStore((state) => [
|
||||
state.stats,
|
||||
state.setStats,
|
||||
]);
|
||||
const [isNewContentLoading, setIsNewContentLoading] = useState(
|
||||
stats.length != 0
|
||||
);
|
||||
const [groupedByTrainingContent, setGroupedByTrainingContent] = useState<{
|
||||
[key: string]: ITrainingContent;
|
||||
}>();
|
||||
|
||||
const {data: trainingContent, isLoading: areRecordsLoading} = useFilterRecordsByUser<ITrainingContent[]>(
|
||||
recordUserId || user?.id,
|
||||
undefined,
|
||||
"training",
|
||||
);
|
||||
const { data: trainingContent, isLoading: areRecordsLoading } =
|
||||
useFilterRecordsByUser<ITrainingContent[]>(
|
||||
recordUserId || user?.id,
|
||||
undefined,
|
||||
"training"
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const handleRouteChange = (url: string) => {
|
||||
setTrainingStats([]);
|
||||
};
|
||||
router.events.on("routeChangeStart", handleRouteChange);
|
||||
return () => {
|
||||
router.events.off("routeChangeStart", handleRouteChange);
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [router.events, setTrainingStats]);
|
||||
useEffect(() => {
|
||||
const handleRouteChange = (url: string) => {
|
||||
setTrainingStats([]);
|
||||
};
|
||||
router.events.on("routeChangeStart", handleRouteChange);
|
||||
return () => {
|
||||
router.events.off("routeChangeStart", handleRouteChange);
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [router.events, setTrainingStats]);
|
||||
|
||||
useEffect(() => {
|
||||
const postStats = async () => {
|
||||
try {
|
||||
const response = await axios.post<{id: string}>(`/api/training`, {userID: user.id, stats: stats});
|
||||
return response.data.id;
|
||||
} catch (error) {
|
||||
setIsNewContentLoading(false);
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
const postStats = async () => {
|
||||
try {
|
||||
const response = await axios.post<{ id: string }>(`/api/training`, {
|
||||
userID: user.id,
|
||||
stats: stats,
|
||||
});
|
||||
return response.data.id;
|
||||
} catch (error) {
|
||||
setIsNewContentLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isNewContentLoading) {
|
||||
postStats().then((id) => {
|
||||
setTrainingStats([]);
|
||||
if (id) {
|
||||
router.push(`/training/${id}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isNewContentLoading]);
|
||||
if (isNewContentLoading) {
|
||||
postStats().then((id) => {
|
||||
setTrainingStats([]);
|
||||
if (id) {
|
||||
router.push(`/training/${id}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isNewContentLoading]);
|
||||
|
||||
const handleNewTrainingContent = () => {
|
||||
setRecordTraining(true);
|
||||
router.push("/record");
|
||||
};
|
||||
const handleNewTrainingContent = () => {
|
||||
setRecordTraining(true);
|
||||
router.push("/record");
|
||||
};
|
||||
|
||||
const filterTrainingContentByDate = (trainingContent: {[key: string]: ITrainingContent}) => {
|
||||
if (filter) {
|
||||
const filterDate = moment()
|
||||
.subtract({[filter as string]: 1})
|
||||
.format("x");
|
||||
const filteredTrainingContent: {[key: string]: ITrainingContent} = {};
|
||||
const filterTrainingContentByDate = (trainingContent: {
|
||||
[key: string]: ITrainingContent;
|
||||
}) => {
|
||||
if (filter) {
|
||||
const filterDate = moment()
|
||||
.subtract({ [filter as string]: 1 })
|
||||
.format("x");
|
||||
const filteredTrainingContent: { [key: string]: ITrainingContent } = {};
|
||||
|
||||
Object.keys(trainingContent).forEach((timestamp) => {
|
||||
if (timestamp >= filterDate) filteredTrainingContent[timestamp] = trainingContent[timestamp];
|
||||
});
|
||||
return filteredTrainingContent;
|
||||
}
|
||||
return trainingContent;
|
||||
};
|
||||
Object.keys(trainingContent).forEach((timestamp) => {
|
||||
if (timestamp >= filterDate)
|
||||
filteredTrainingContent[timestamp] = trainingContent[timestamp];
|
||||
});
|
||||
return filteredTrainingContent;
|
||||
}
|
||||
return trainingContent;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (trainingContent.length > 0) {
|
||||
const grouped = trainingContent.reduce((acc, content) => {
|
||||
acc[content.created_at] = content;
|
||||
return acc;
|
||||
}, {} as {[key: number]: ITrainingContent});
|
||||
useEffect(() => {
|
||||
if (trainingContent.length > 0) {
|
||||
const grouped = trainingContent.reduce((acc, content) => {
|
||||
acc[content.created_at] = content;
|
||||
return acc;
|
||||
}, {} as { [key: number]: ITrainingContent });
|
||||
|
||||
setGroupedByTrainingContent(grouped);
|
||||
} else {
|
||||
setGroupedByTrainingContent(undefined);
|
||||
}
|
||||
}, [trainingContent]);
|
||||
setGroupedByTrainingContent(grouped);
|
||||
} else {
|
||||
setGroupedByTrainingContent(undefined);
|
||||
}
|
||||
}, [trainingContent]);
|
||||
|
||||
const formatTimestamp = (timestamp: string) => {
|
||||
const date = moment(parseInt(timestamp));
|
||||
const formatter = "YYYY/MM/DD - HH:mm";
|
||||
const formatTimestamp = (timestamp: string) => {
|
||||
const date = moment(parseInt(timestamp));
|
||||
const formatter = "YYYY/MM/DD - HH:mm";
|
||||
|
||||
return date.format(formatter);
|
||||
};
|
||||
return date.format(formatter);
|
||||
};
|
||||
|
||||
const selectTrainingContent = (trainingContent: ITrainingContent) => {
|
||||
router.push(`/training/${trainingContent.id}`);
|
||||
};
|
||||
const selectTrainingContent = (trainingContent: ITrainingContent) => {
|
||||
router.push(`/training/${trainingContent.id}`);
|
||||
};
|
||||
|
||||
const trainingContentContainer = (timestamp: string) => {
|
||||
if (!groupedByTrainingContent) return <></>;
|
||||
const trainingContentContainer = (timestamp: string) => {
|
||||
if (!groupedByTrainingContent) return <></>;
|
||||
|
||||
const trainingContent: ITrainingContent = groupedByTrainingContent[timestamp];
|
||||
const uniqueModules = [...new Set(trainingContent.exams.map((exam) => exam.module))];
|
||||
const trainingContent: ITrainingContent =
|
||||
groupedByTrainingContent[timestamp];
|
||||
const uniqueModules = [
|
||||
...new Set(trainingContent.exams.map((exam) => exam.module)),
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
key={uuidv4()}
|
||||
className={clsx(
|
||||
"flex flex-col justify-between gap-4 border border-mti-gray-platinum p-4 cursor-pointer rounded-xl transition ease-in-out duration-300 -md:hidden",
|
||||
)}
|
||||
onClick={() => selectTrainingContent(trainingContent)}
|
||||
role="button">
|
||||
<div className="w-full flex justify-between -md:items-center 2xl:items-center">
|
||||
<div className="flex flex-col md:gap-1 -md:gap-2 2xl:gap-2">
|
||||
<span className="font-medium">{formatTimestamp(timestamp)}</span>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="w-full flex flex-row gap-1">
|
||||
{uniqueModules.map((module) => (
|
||||
<ModuleBadge key={module} module={module} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<TrainingScore trainingContent={trainingContent} gridView={true} />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
key={uuidv4()}
|
||||
className={clsx(
|
||||
"flex flex-col justify-between gap-4 border border-mti-gray-platinum p-4 cursor-pointer rounded-xl transition ease-in-out duration-300 -md:hidden"
|
||||
)}
|
||||
onClick={() => selectTrainingContent(trainingContent)}
|
||||
role="button"
|
||||
>
|
||||
<div className="w-full flex justify-between -md:items-center 2xl:items-center">
|
||||
<div className="flex flex-col md:gap-1 -md:gap-2 2xl:gap-2">
|
||||
<span className="font-medium">{formatTimestamp(timestamp)}</span>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="w-full flex flex-row gap-1">
|
||||
{uniqueModules.map((module) => (
|
||||
<ModuleBadge key={module} module={module} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<TrainingScore trainingContent={trainingContent} gridView={true} />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Training | 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 />
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Training | 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 />
|
||||
|
||||
<>
|
||||
{isNewContentLoading || areRecordsLoading ? (
|
||||
<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" />
|
||||
{isNewContentLoading && (
|
||||
<span className="text-center text-2xl font-bold text-mti-green-light">Assessing your exams, please be patient...</span>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<RecordFilter entities={entities} user={user} filterState={{filter: filter, setFilter: setFilter}} assignments={false}>
|
||||
{user.type === "student" && (
|
||||
<>
|
||||
<div className="flex items-center">
|
||||
<div className="font-semibold text-2xl">Generate New Training Material</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",
|
||||
"transition duration-300 ease-in-out",
|
||||
)}
|
||||
onClick={handleNewTrainingContent}>
|
||||
<FaPlus />
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</RecordFilter>
|
||||
{trainingContent.length == 0 && (
|
||||
<div className="flex flex-grow justify-center items-center">
|
||||
<span className="font-semibold ml-1">No training content to display...</span>
|
||||
</div>
|
||||
)}
|
||||
{!areRecordsLoading && groupedByTrainingContent && Object.keys(groupedByTrainingContent).length > 0 && (
|
||||
<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)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
</>
|
||||
);
|
||||
<>
|
||||
{isNewContentLoading || areRecordsLoading ? (
|
||||
<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" />
|
||||
{isNewContentLoading && (
|
||||
<span className="text-center text-2xl font-bold text-mti-green-light">
|
||||
Assessing your exams, please be patient...
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<RecordFilter
|
||||
entities={entities}
|
||||
user={user}
|
||||
isAdmin={isAdmin}
|
||||
filterState={{ filter: filter, setFilter: setFilter }}
|
||||
assignments={false}
|
||||
>
|
||||
{user.type === "student" && (
|
||||
<>
|
||||
<div className="flex items-center">
|
||||
<div className="font-semibold text-2xl">
|
||||
Generate New Training Material
|
||||
</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",
|
||||
"transition duration-300 ease-in-out"
|
||||
)}
|
||||
onClick={handleNewTrainingContent}
|
||||
>
|
||||
<FaPlus />
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</RecordFilter>
|
||||
{trainingContent.length == 0 && (
|
||||
<div className="flex flex-grow justify-center items-center">
|
||||
<span className="font-semibold ml-1">
|
||||
No training content to display...
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{!areRecordsLoading &&
|
||||
groupedByTrainingContent &&
|
||||
Object.keys(groupedByTrainingContent).length > 0 && (
|
||||
<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)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Training;
|
||||
|
||||
Reference in New Issue
Block a user