Created the stats page where a user can select another user to view their stats;
Improved the whole stats and the home page
This commit is contained in:
@@ -41,7 +41,7 @@ export default function Speaking({id, title, text, type, prompts, onNext, onBack
|
||||
</button>
|
||||
<button
|
||||
className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)}
|
||||
onClick={() => onNext({exercise: id, solutions: [], score: {correct: 0, total: 0}, type})}>
|
||||
onClick={() => onNext({exercise: id, solutions: [], score: {correct: 1, total: 1}, type})}>
|
||||
Next
|
||||
<div className="absolute right-4">
|
||||
<Icon path={mdiArrowRight} color="white" size={1} />
|
||||
|
||||
@@ -42,7 +42,7 @@ export default function Navbar({profilePicture, timer, showExamEnd = false}: Pro
|
||||
icon: "pi pi-fw pi-users",
|
||||
items: [
|
||||
{label: "List", icon: "pi pi-fw pi-users", url: "/users"},
|
||||
{label: "Stats", icon: "pi pi-fw pi-chart-pie", url: "/user-stats"},
|
||||
{label: "Stats", icon: "pi pi-fw pi-chart-pie", url: "/stats"},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -2,32 +2,29 @@ import {SEMI_TRANSPARENT} from "@/resources/colors";
|
||||
import {Chart as ChartJS, RadialLinearScale, ArcElement, Tooltip, Legend} from "chart.js";
|
||||
import clsx from "clsx";
|
||||
import {PolarArea} from "react-chartjs-2";
|
||||
import {Chart} from "primereact/chart";
|
||||
|
||||
interface Props {
|
||||
data: {label: string; value: number}[];
|
||||
label?: string;
|
||||
title: string;
|
||||
className?: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
ChartJS.register(RadialLinearScale, ArcElement, Tooltip, Legend);
|
||||
|
||||
export default function UserResultChart({data, title, className = ""}: Props) {
|
||||
export default function UserResultChart({data, type, label, title}: Props) {
|
||||
const labels = data.map((x) => x.label);
|
||||
const chartData = {
|
||||
labels,
|
||||
datasets: [
|
||||
{
|
||||
title,
|
||||
label,
|
||||
data: data.map((x) => x.value),
|
||||
backgroundColor: Object.values(SEMI_TRANSPARENT),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={clsx("flex flex-col gap-4 items-center", className)}>
|
||||
<PolarArea data={chartData} options={{plugins: {title: {text: title, display: true}}}} />
|
||||
<h2 className="text-neutral-600 font-semibold text-lg">{title}</h2>
|
||||
</div>
|
||||
);
|
||||
return <Chart type={type} data={chartData} options={{plugins: {title: {text: title, display: true}}}} />;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import {Stat, User} from "@/interfaces/user";
|
||||
import axios from "axios";
|
||||
import {useEffect, useState} from "react";
|
||||
|
||||
export default function useStats() {
|
||||
export default function useStats(id?: string) {
|
||||
const [stats, setStats] = useState<Stat[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isError, setIsError] = useState(false);
|
||||
@@ -10,10 +10,10 @@ export default function useStats() {
|
||||
useEffect(() => {
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.get<Stat[]>("/api/stats")
|
||||
.get<Stat[]>(!id ? "/api/stats" : `/api/stats/${id}`)
|
||||
.then((response) => setStats(response.data))
|
||||
.finally(() => setIsLoading(false));
|
||||
}, []);
|
||||
}, [id]);
|
||||
|
||||
return {stats, isLoading, isError};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {Module} from ".";
|
||||
import {UserSolution} from "./exam";
|
||||
|
||||
export interface User {
|
||||
email: string;
|
||||
@@ -14,6 +13,7 @@ export interface Stat {
|
||||
user: string;
|
||||
exam: string;
|
||||
exercise: string;
|
||||
session: string;
|
||||
module: Module;
|
||||
solutions: any[];
|
||||
type: string;
|
||||
|
||||
29
src/pages/api/stats/[user].ts
Normal file
29
src/pages/api/stats/[user].ts
Normal file
@@ -0,0 +1,29 @@
|
||||
// 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, doc, setDoc, addDoc} from "firebase/firestore";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
const {user} = req.query;
|
||||
const q = query(collection(db, "stats"), where("user", "==", user));
|
||||
|
||||
const snapshot = await getDocs(q);
|
||||
|
||||
res.status(200).json(
|
||||
snapshot.docs.map((doc) => ({
|
||||
id: doc.id,
|
||||
...doc.data(),
|
||||
})),
|
||||
);
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import {withIronSessionSsr} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {Stat, User} from "@/interfaces/user";
|
||||
import Speaking from "@/exams/Speaking";
|
||||
import {v4 as uuidv4} from "uuid";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
const user = req.session.user;
|
||||
@@ -42,9 +43,12 @@ export default function Page({user}: {user: User}) {
|
||||
const [hasBeenUploaded, setHasBeenUploaded] = useState(false);
|
||||
const [showSolutions, setShowSolutions] = useState(false);
|
||||
const [moduleIndex, setModuleIndex] = useState(0);
|
||||
const [sessionId, setSessionId] = useState("");
|
||||
const [exam, setExam] = useState<Exam>();
|
||||
const [timer, setTimer] = useState(-1);
|
||||
|
||||
useEffect(() => setSessionId(uuidv4()), []);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
if (selectedModules.length > 0 && moduleIndex < selectedModules.length) {
|
||||
@@ -60,6 +64,7 @@ export default function Page({user}: {user: User}) {
|
||||
if (selectedModules.length > 0 && moduleIndex >= selectedModules.length && !hasBeenUploaded) {
|
||||
const stats: Stat[] = userSolutions.map((solution) => ({
|
||||
...solution,
|
||||
session: sessionId,
|
||||
exam: solution.exam!,
|
||||
module: solution.module!,
|
||||
user: user.id,
|
||||
|
||||
@@ -8,7 +8,8 @@ import {sessionOptions} from "@/lib/session";
|
||||
import {User} from "@/interfaces/user";
|
||||
import {useEffect, useState} from "react";
|
||||
import useStats from "@/hooks/useStats";
|
||||
import {formatModuleTotalStats} from "@/utils/stats";
|
||||
import {averageScore, formatModuleTotalStats, totalExams} from "@/utils/stats";
|
||||
import {Divider} from "primereact/divider";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
const user = req.session.user;
|
||||
@@ -31,10 +32,11 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
|
||||
export default function Home({user}: {user: User}) {
|
||||
const [showEndExam, setShowEndExam] = useState(false);
|
||||
const [windowWidth, setWindowWidth] = useState(0);
|
||||
const {stats, isLoading} = useStats();
|
||||
|
||||
useEffect(() => setShowEndExam(window.innerWidth <= 960), []);
|
||||
useEffect(() => console.log(stats), [stats]);
|
||||
useEffect(() => setWindowWidth(window.innerWidth), []);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -47,19 +49,32 @@ export default function Home({user}: {user: User}) {
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<main className="w-full h-full min-h-[100vh] flex flex-col items-center bg-neutral-100">
|
||||
<main className="w-full h-full min-h-[100vh] flex flex-col items-center bg-neutral-100 text-black">
|
||||
<Navbar profilePicture={user.profilePicture} showExamEnd={showEndExam} />
|
||||
<div className="w-full h-full p-4 relative">
|
||||
<section className="h-full w-full flex flex-col lg:flex-row gap-12 justify-center items-center md:items-start">
|
||||
<section className="w-full lg:w-1/2 h-full flex items-center">
|
||||
<div className="w-full h-full p-4 relative flex flex-col gap-8">
|
||||
<section className="h-full w-full flex lg:gap-8 flex-col lg:flex-row justify-center md:justify-start md:items-start">
|
||||
<section className="w-full h-full flex items-center">
|
||||
<ProfileCard user={user} className="text-black self-start" />
|
||||
</section>
|
||||
{!isLoading && stats && (
|
||||
<section className="w-full lg:w-1/3 h-full flex items-center justify-center">
|
||||
<UserResultChart data={formatModuleTotalStats(stats)} title="Total exams" className="w-2/3" />
|
||||
</section>
|
||||
)}
|
||||
{windowWidth <= 960 && <Divider />}
|
||||
<div className="flex flex-col w-full gap-4">
|
||||
<span className="font-bold text-2xl">Statistics</span>
|
||||
{!isLoading && stats && (
|
||||
<div className="text-neutral-600 flex flex-wrap gap-2 md:gap-4 w-full justify-between md:justify-start">
|
||||
<div className="bg-white p-4 rounded-xl drop-shadow-xl flex flex-col gap-2 md:gap-4 w-full">
|
||||
<span className="font-bold text-xl">Exams: {totalExams(stats)}</span>
|
||||
<span className="font-bold text-xl">Exercises: {stats.length}</span>
|
||||
<span className="font-bold text-xl">Average Score: {averageScore(stats)}%</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
{!isLoading && stats && (
|
||||
<section className="w-full lg:w-1/3 h-full flex items-center justify-center">
|
||||
<UserResultChart type="polarArea" data={formatModuleTotalStats(stats)} title="Exams per Module" />
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
</>
|
||||
|
||||
126
src/pages/stats.tsx
Normal file
126
src/pages/stats.tsx
Normal file
@@ -0,0 +1,126 @@
|
||||
import Navbar from "@/components/Navbar";
|
||||
import UserResultChart from "@/components/UserResultChart";
|
||||
import useStats from "@/hooks/useStats";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import {User} from "@/interfaces/user";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {formatExerciseAverageScoreStats, formatModuleAverageScoreStats, formatModuleTotalStats} from "@/utils/stats";
|
||||
import {withIronSessionSsr} from "iron-session/next";
|
||||
import Head from "next/head";
|
||||
import {AutoComplete} from "primereact/autocomplete";
|
||||
import {Divider} from "primereact/divider";
|
||||
import {useEffect, useState} from "react";
|
||||
|
||||
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
|
||||
const user = req.session.user;
|
||||
|
||||
if (!user) {
|
||||
res.setHeader("location", "/login");
|
||||
res.statusCode = 302;
|
||||
res.end();
|
||||
return {
|
||||
props: {
|
||||
user: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
props: {user: req.session.user},
|
||||
};
|
||||
}, sessionOptions);
|
||||
|
||||
export default function Stats({user}: {user: User}) {
|
||||
const [autocompleteValue, setAutocompleteValue] = useState(user.name);
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
const [items, setItems] = useState<User[]>([]);
|
||||
|
||||
const {users, isLoading} = useUsers();
|
||||
const {stats, isLoading: isStatsLoading} = useStats(selectedUser?.id);
|
||||
|
||||
useEffect(() => console.log({stats}), [stats]);
|
||||
|
||||
const search = (event: {query: string}) => {
|
||||
setItems(event.query ? users.filter((x) => x.name.startsWith(event.query)) : users);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>IELTS GPT | Stats</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>
|
||||
<main className="w-full h-full min-h-[100vh] flex flex-col items-center bg-neutral-100 text-neutral-600">
|
||||
<Navbar profilePicture={user.profilePicture} />
|
||||
<div className="w-full h-full flex flex-col items-center justify-center p-4 relative gap-8">
|
||||
<AutoComplete
|
||||
value={autocompleteValue}
|
||||
suggestions={items}
|
||||
field="name"
|
||||
onChange={(e) => setAutocompleteValue(e.target.value)}
|
||||
completeMethod={search}
|
||||
onSelect={(e) => setSelectedUser(e.value)}
|
||||
dropdown
|
||||
/>
|
||||
|
||||
<section className="flex flex-col gap-2 md:gap-4 w-full">
|
||||
<div className="flex flex-col">
|
||||
<span className="font-semibold">Module Statistics</span>
|
||||
<Divider />
|
||||
</div>
|
||||
<div className="flex flex-col md:grid md:grid-cols-3 w-full gap-4">
|
||||
{!isStatsLoading && stats && (
|
||||
<>
|
||||
<div className="max-w-lg">
|
||||
<UserResultChart
|
||||
type="polarArea"
|
||||
data={formatModuleTotalStats(stats)}
|
||||
title="Exams per Module"
|
||||
label="Total"
|
||||
/>
|
||||
</div>
|
||||
<div className="max-w-lg">
|
||||
<UserResultChart
|
||||
type="polarArea"
|
||||
data={formatModuleAverageScoreStats(stats)}
|
||||
title="Average Score per Module"
|
||||
label="Score (in %)"
|
||||
/>
|
||||
</div>
|
||||
<div className="max-w-lg">
|
||||
<UserResultChart type="polarArea" data={formatModuleTotalStats(stats)} title="Total exams" />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="flex flex-col gap-2 md:gap-4 w-full">
|
||||
<div className="flex flex-col">
|
||||
<span className="font-semibold">Exam Statistics</span>
|
||||
<Divider />
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col md:grid md:grid-cols-3 w-full gap-4">
|
||||
{!isStatsLoading && stats && (
|
||||
<div className="max-w-lg">
|
||||
<UserResultChart
|
||||
type="polarArea"
|
||||
data={formatExerciseAverageScoreStats(stats)}
|
||||
title="Average Score by Exercise"
|
||||
label="Average"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -58,7 +58,7 @@ export default function Users({user}: {user: User}) {
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>IELTS GPT | Profile</title>
|
||||
<title>IELTS GPT | Users</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
|
||||
@@ -66,7 +66,7 @@ export default function Users({user}: {user: User}) {
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<main className="w-full h-screen flex flex-col items-center bg-neutral-100">
|
||||
<main className="w-full h-full min-h-[100vh] flex flex-col items-center bg-neutral-100">
|
||||
<Navbar profilePicture={user.profilePicture} />
|
||||
<div className="w-full h-full flex flex-col items-center justify-center p-4 relative">
|
||||
<DataTable
|
||||
|
||||
@@ -1,37 +1,37 @@
|
||||
import {Module} from "@/interfaces";
|
||||
import {Stat} from "@/interfaces/user";
|
||||
import {capitalize} from "lodash";
|
||||
import {convertCamelCaseToReadable} from "@/utils/string";
|
||||
|
||||
export const totalExams = (stats: Stat[]): number => {
|
||||
const moduleStats = formatModuleTotalStats(stats);
|
||||
return moduleStats.reduce((previous, current) => previous + current.value, 0);
|
||||
};
|
||||
|
||||
export const averageScore = (stats: Stat[]): number => {
|
||||
const {correct, total} = stats.reduce(
|
||||
(acc, current) => ({correct: acc.correct + current.score.correct, total: acc.total + current.score.total}),
|
||||
{correct: 0, total: 0},
|
||||
);
|
||||
return parseFloat(((correct / total) * 100).toFixed(2));
|
||||
};
|
||||
|
||||
export const formatModuleTotalStats = (stats: Stat[]): {label: string; value: number}[] => {
|
||||
const result: {[key in Module]: {exams: string[]; total: number}} = {
|
||||
reading: {
|
||||
exams: [],
|
||||
total: 0,
|
||||
},
|
||||
listening: {
|
||||
exams: [],
|
||||
total: 0,
|
||||
},
|
||||
writing: {
|
||||
exams: [],
|
||||
total: 0,
|
||||
},
|
||||
speaking: {
|
||||
exams: [],
|
||||
total: 0,
|
||||
},
|
||||
};
|
||||
const moduleSessions: {[key: string]: string[]} = {};
|
||||
|
||||
stats.forEach((stat) => {
|
||||
if (result[stat.module].exams)
|
||||
result[stat.module] = {
|
||||
exams: [...result[stat.module].exams.filter((x) => x !== stat.exam), stat.exam],
|
||||
total: result[stat.module].total + 1,
|
||||
};
|
||||
if (stat.module in moduleSessions) {
|
||||
if (!moduleSessions[stat.module].includes(stat.session)) {
|
||||
moduleSessions[stat.module] = [...moduleSessions[stat.module], stat.session];
|
||||
}
|
||||
} else {
|
||||
moduleSessions[stat.module] = [stat.session];
|
||||
}
|
||||
});
|
||||
|
||||
return Object.keys(result).map((key) => ({label: capitalize(key), value: result[key as Module].total}));
|
||||
return ["reading", "listening", "writing", "speaking"].map((module) => ({
|
||||
label: capitalize(module),
|
||||
value: moduleSessions[module]?.length || 0,
|
||||
}));
|
||||
};
|
||||
|
||||
export const formatModuleAverageScoreStats = (stats: Stat[]): {label: string; value: number}[] => {
|
||||
@@ -48,12 +48,12 @@ export const formatModuleAverageScoreStats = (stats: Stat[]): {label: string; va
|
||||
}
|
||||
});
|
||||
|
||||
return Object.keys(moduleScores).map((x) => {
|
||||
const {correct, total} = moduleScores[x as keyof typeof moduleScores];
|
||||
return ["reading", "listening", "writing", "speaking"].map((x) => {
|
||||
const score = moduleScores[x as keyof typeof moduleScores];
|
||||
|
||||
return {
|
||||
label: capitalize(x),
|
||||
value: correct / total,
|
||||
value: score ? parseFloat(((score.correct / score.total) * 100).toFixed(2)) : 0,
|
||||
};
|
||||
});
|
||||
};
|
||||
@@ -86,7 +86,7 @@ export const formatExerciseAverageScoreStats = (stats: Stat[]): {label: string;
|
||||
|
||||
return {
|
||||
label: convertCamelCaseToReadable(x),
|
||||
value: correct / total,
|
||||
value: parseFloat(((correct / total) * 100).toFixed(2)),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user