feat(ui): add topic, subject screen

fix(api): fix api endpoint logic for pretest screen
This commit is contained in:
shafin-r
2025-08-21 14:19:55 +06:00
parent be5c723bff
commit 6f4f2a8668
8 changed files with 369 additions and 105 deletions

View File

@ -0,0 +1,142 @@
"use client";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import Header from "@/components/Header";
import DestructibleAlert from "@/components/DestructibleAlert";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import { API_URL, getToken } from "@/lib/auth";
import { Loader, RefreshCw } from "lucide-react";
import { useAuth } from "@/context/AuthContext";
type Mock = {
test_id: string;
name: string;
type: string;
num_questions: number;
time_limit_minutes: number;
deduction: number;
total_possible_score: number;
unit: string;
};
export default function MockScreen() {
const router = useRouter();
const { user } = useAuth();
const [mocks, setMocks] = useState<Mock[]>([]);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState<boolean>(false);
async function fetchMocks() {
setRefreshing(true);
try {
const token = await getToken();
const response = await fetch(`${API_URL}/tests/mock/`, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
});
if (!response.ok) {
throw new Error("Failed to fetch topics");
}
const fetchedMocks: Mock[] = await response.json();
setMocks(fetchedMocks);
} catch (error) {
setErrorMsg(
"Error fetching mocks: " +
(error instanceof Error ? error.message : "Unknown error")
);
} finally {
setRefreshing(false);
}
}
useEffect(() => {
const fetchData = async () => {
if (await getToken()) {
fetchMocks();
}
};
fetchData();
}, []);
const onRefresh = async () => {
fetchMocks();
};
if (errorMsg) {
return (
<BackgroundWrapper>
<Header displayTabTitle="Mocks" />
<div className="overflow-y-auto">
<div className="mt-5 px-5">
<DestructibleAlert text={errorMsg} extraStyles="" />
</div>
<div className="flex justify-center mt-4">
<button
onClick={onRefresh}
disabled={refreshing}
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50"
>
{refreshing ? <Loader /> : <RefreshCw />}
</button>
</div>
</div>
</BackgroundWrapper>
);
}
return (
<BackgroundWrapper>
<div>
<Header displayTabTitle="Mocks" />
<div className="mx-10 pb-20 overflow-y-auto">
<h1 className="text-2xl font-semibold my-5">
{user?.preparation_unit}
</h1>
<div className="border border-[#c0dafc] flex flex-col gap-4 w-full rounded-[25px] p-4">
{mocks.length > 0 ? (
mocks.map((mocks) => (
<div key={mocks.test_id}>
<button
onClick={() =>
router.push(
`/exam/pretest?type=mock&test_id=${mocks.test_id}`
)
}
className="w-full border-2 border-[#B0C2DA] py-4 rounded-[10px] px-6 space-y-2 text-left hover:bg-gray-50 transition-colors"
>
<h3 className="text-xl font-medium">{mocks.name}</h3>
<div className="flex space-x-2">
<p className="text-md font-normal bg-slate-500 w-fit px-3 py-1 rounded-full text-white">
{mocks.unit}
</p>
</div>
</button>
</div>
))
) : (
<div className="flex flex-col items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
<p className="text-xl font-medium text-center">Loading...</p>
</div>
)}
</div>
<div className="flex justify-center mt-4">
<button
onClick={onRefresh}
disabled={refreshing}
className="p-2 bg-blue-500 text-white hover:bg-blue-600 disabled:opacity-50 rounded-full"
>
{refreshing ? <Loader /> : <RefreshCw />}
</button>
</div>
</div>
</div>
{/* <CustomBackHandler fallbackRoute="unit" useCustomHandler={false} /> */}
</BackgroundWrapper>
);
}

View File

@ -0,0 +1,75 @@
"use client";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import Header from "@/components/Header";
import React from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
const CategoriesPage = () => {
const router = useRouter();
return (
<BackgroundWrapper>
<main>
<Header displayTabTitle="Categories" />
<div className="grid grid-cols-2 gap-4 pt-6 mx-4">
<button
onClick={() => router.push("/categories/topics")}
className="flex flex-col justify-center items-center border-[1px] border-blue-200 aspect-square rounded-3xl gap-2 bg-white"
>
<Image
src="/images/icons/topic-test.png"
alt="Topic Test"
width={85}
height={85}
/>
<span className="font-medium text-[#113768]">Topic Test</span>
</button>
<button
onClick={() => router.push("/categories/mocks")}
className="flex flex-col justify-center items-center border-[1px] border-blue-200 aspect-square rounded-3xl gap-2 bg-white"
>
<Image
src="/images/icons/mock-test.png"
alt="Mock Test"
width={85}
height={85}
/>
<span className="font-medium text-[#113768]">Mock Test</span>
</button>
<button
disabled
className="flex flex-col justify-center items-center border-[1px] border-blue-200 aspect-square rounded-3xl gap-2 bg-white"
>
<Image
src="/images/icons/past-paper.png"
alt="Past Papers"
width={68}
height={68}
className="opacity-50"
/>
<span className="font-medium text-[#113768]/50">Past Papers</span>
</button>
<button
onClick={() => router.push("/categories/subjects")}
className="flex flex-col justify-center items-center border-[1px] border-blue-200 aspect-square rounded-3xl gap-2 bg-white"
>
<Image
src="/images/icons/subject-test.png"
alt="Subject Test"
width={80}
height={80}
/>
<span className="font-medium text-[#113768]">Subject Test</span>
</button>
</div>
</main>
</BackgroundWrapper>
);
};
export default CategoriesPage;

View File

@ -103,7 +103,7 @@ export default function PaperScreen() {
<button <button
onClick={() => onClick={() =>
router.push( router.push(
`/exam/pretest?test_id=${subject.subject_id}` `/exam/pretest?type=subject&test_id=${subject.subject_id}`
) )
} }
className="w-full border-2 border-[#B0C2DA] py-4 rounded-[10px] px-6 space-y-2 text-left hover:bg-gray-50 transition-colors" className="w-full border-2 border-[#B0C2DA] py-4 rounded-[10px] px-6 space-y-2 text-left hover:bg-gray-50 transition-colors"

View File

@ -1,6 +1,5 @@
"use client"; "use client";
import { useSearchParams } from "next/navigation";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import Header from "@/components/Header"; import Header from "@/components/Header";
@ -9,7 +8,6 @@ import BackgroundWrapper from "@/components/BackgroundWrapper";
import { API_URL, getToken } from "@/lib/auth"; import { API_URL, getToken } from "@/lib/auth";
import { Loader, RefreshCw } from "lucide-react"; import { Loader, RefreshCw } from "lucide-react";
import { useAuth } from "@/context/AuthContext"; import { useAuth } from "@/context/AuthContext";
import { Question } from "@/types/exam";
type Topic = { type Topic = {
topic_id: string; topic_id: string;
@ -95,7 +93,7 @@ export default function TopicScreen() {
<div> <div>
<Header displayTabTitle="Topics" /> <Header displayTabTitle="Topics" />
<div className="mx-10 pb-20 overflow-y-auto"> <div className="mx-10 pb-20 overflow-y-auto">
<h1 className="text-2xl font-semibold mb-5"> <h1 className="text-2xl font-semibold my-5">
{user?.preparation_unit} {user?.preparation_unit}
</h1> </h1>
<div className="border border-[#c0dafc] flex flex-col gap-4 w-full rounded-[25px] p-4"> <div className="border border-[#c0dafc] flex flex-col gap-4 w-full rounded-[25px] p-4">
@ -104,7 +102,9 @@ export default function TopicScreen() {
<div key={topic.topic_id}> <div key={topic.topic_id}>
<button <button
onClick={() => onClick={() =>
router.push(`/exam/pretest?test_id=${topic.topic_id}`) router.push(
`/exam/pretest?type=topic&test_id=${topic.topic_id}`
)
} }
className="w-full border-2 border-[#B0C2DA] py-4 rounded-[10px] px-6 space-y-2 text-left hover:bg-gray-50 transition-colors" className="w-full border-2 border-[#B0C2DA] py-4 rounded-[10px] px-6 space-y-2 text-left hover:bg-gray-50 transition-colors"
> >

View File

@ -77,67 +77,67 @@ const HomePage = () => {
<ChevronRight size={24} color="#113768" /> <ChevronRight size={24} color="#113768" />
</button> </button>
</div> </div>
<div className={styles.categoriesContainer}> <div className="grid grid-cols-2 gap-4 pt-6 ">
<div className={styles.categoryRow}> <button
<button onClick={() => router.push("/categories/topics")}
onClick={() => router.push("/topics")} className="flex flex-col justify-center items-center border-[1px] border-blue-200 aspect-square rounded-3xl gap-2 bg-white"
className={`${styles.categoryButton} `} >
> <Image
<Image src="/images/icons/topic-test.png"
src="/images/icons/topic-test.png" alt="Topic Test"
alt="Topic Test" width={85}
width={85} height={85}
height={85} />
/> <span className="font-medium text-[#113768]">
<span className={styles.categoryButtonText}> Topic Test
Topic Test </span>
</span> </button>
</button>
<button <button
onClick={() => router.push("/mocks")} onClick={() => router.push("/categories/mocks")}
className={styles.categoryButton} className="flex flex-col justify-center items-center border-[1px] border-blue-200 aspect-square rounded-3xl gap-2 bg-white"
> >
<Image <Image
src="/images/icons/mock-test.png" src="/images/icons/mock-test.png"
alt="Mock Test" alt="Mock Test"
width={85} width={85}
height={85} height={85}
/> />
<span className={styles.categoryButtonText}> <span className="font-medium text-[#113768]">
Mock Test Mock Test
</span> </span>
</button> </button>
</div>
<div className={styles.categoryRow}> <button
<button disabled
disabled className="flex flex-col justify-center items-center border-[1px] border-blue-200 aspect-square rounded-3xl gap-2 bg-white"
className={`${styles.categoryButton} ${styles.disabled}`} >
> <Image
<Image src="/images/icons/past-paper.png"
src="/images/icons/past-paper.png" alt="Past Papers"
alt="Past Papers" width={68}
width={68} height={68}
height={68} className="opacity-50"
/> />
<span className={styles.categoryButtonText}> <span className="font-medium text-[#113768]/50">
Past Papers Past Papers
</span> </span>
</button> </button>
<button
onClick={() => router.push("/subjects")} <button
className={`${styles.categoryButton}`} onClick={() => router.push("/categories/subjects")}
> className="flex flex-col justify-center items-center border-[1px] border-blue-200 aspect-square rounded-3xl gap-2 bg-white"
<Image >
src="/images/icons/subject-test.png" <Image
alt="Subject Test" src="/images/icons/subject-test.png"
width={80} alt="Subject Test"
height={80} width={80}
/> height={80}
<span className={styles.categoryButtonText}> />
Subject Test <span className="font-medium text-[#113768]">
</span> Subject Test
</button> </span>
</div> </button>
</div> </div>
</div> </div>

View File

@ -11,7 +11,7 @@ const tabs = [
{ name: "Home", href: "/home", component: <House size={30} /> }, { name: "Home", href: "/home", component: <House size={30} /> },
{ {
name: "Categories", name: "Categories",
href: "/subjects", href: "/categories",
component: <LayoutGrid size={30} />, component: <LayoutGrid size={30} />,
}, },
{ name: "Bookmark", href: "/bookmark", component: <Bookmark size={30} /> }, { name: "Bookmark", href: "/bookmark", component: <Bookmark size={30} /> },

View File

@ -5,40 +5,66 @@ import { Suspense, useEffect, useState } from "react";
import { ArrowLeft, HelpCircle, Clock, XCircle } from "lucide-react"; import { ArrowLeft, HelpCircle, Clock, XCircle } from "lucide-react";
import DestructibleAlert from "@/components/DestructibleAlert"; import DestructibleAlert from "@/components/DestructibleAlert";
import BackgroundWrapper from "@/components/BackgroundWrapper"; import BackgroundWrapper from "@/components/BackgroundWrapper";
import { API_URL } from "@/lib/auth"; import { API_URL, getToken } from "@/lib/auth";
import { useExam } from "@/context/ExamContext"; import { useExam } from "@/context/ExamContext";
import { Test } from "@/types/exam"; import { Test } from "@/types/exam";
import { Metadata } from "@/types/exam"; import { Metadata, MockMeta, SubjectMeta, TopicMeta } from "@/types/exam";
type MetadataType = "mock" | "subject" | "topic";
type MetadataMap = {
mock: MockMeta;
subject: SubjectMeta;
topic: TopicMeta;
};
function PretestPageContent() { function PretestPageContent() {
const router = useRouter(); const router = useRouter();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const [examData, setExamData] = useState<Test>();
const { startExam, setCurrentExam } = useExam(); const { startExam, setCurrentExam } = useExam();
// Get params from URL search params // Get params from URL search params
const id = searchParams.get("id") || ""; const id = searchParams.get("test_id") || "";
const typeParam = searchParams.get("type");
const type =
typeParam === "mock" || typeParam === "subject" || typeParam === "topic"
? typeParam
: null;
const [metadata, setMetadata] = useState<Metadata | null>(null); const [metadata, setMetadata] = useState<MetadataMap[MetadataType] | null>(
null
);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string>(); const [error, setError] = useState<string>();
function fetchMetadata<T extends MetadataType>(
type: T,
data: unknown
): MetadataMap[T] {
return data as MetadataMap[T]; // you'd validate in real code
}
useEffect(() => { useEffect(() => {
async function fetchQuestions() { async function fetchQuestions() {
if (!id) return; if (!id || !type) return;
try { try {
setLoading(true); setLoading(true);
const questionResponse = await fetch(`${API_URL}/mock/${id}`, { const token = await getToken();
const questionResponse = await fetch(`${API_URL}/tests/${type}/${id}`, {
method: "GET", method: "GET",
headers: {
authorization: `Bearer ${token}`,
},
}); });
if (!questionResponse.ok) { if (!questionResponse.ok) {
throw new Error("Failed to fetch questions"); throw new Error("Failed to fetch questions");
} }
const data = await questionResponse.json();
const fetchedMetadata: Metadata = data;
setExamData(data); const data = await questionResponse.json();
const fetchedMetadata = fetchMetadata(type, data.metadata);
setMetadata(fetchedMetadata); setMetadata(fetchedMetadata);
} catch (error) { } catch (error) {
console.error(error); console.error(error);
@ -47,17 +73,19 @@ function PretestPageContent() {
setLoading(false); setLoading(false);
} }
} }
if (id) {
fetchQuestions(); fetchQuestions();
} }, [id, type]);
}, [id]);
if (error) { if (error) {
return ( return (
<BackgroundWrapper> <BackgroundWrapper>
<div className="min-h-screen"> <div className="min-h-screen">
<div className="mx-10 mt-10"> <div className="mx-10 mt-10">
<button onClick={() => router.push("/subjects")} className="mb-4"> <button
onClick={() => router.push("/categories/subjects")}
className="mb-4"
>
<ArrowLeft size={30} color="black" /> <ArrowLeft size={30} color="black" />
</button> </button>
<DestructibleAlert text={error} extraStyles="" /> <DestructibleAlert text={error} extraStyles="" />
@ -72,12 +100,15 @@ function PretestPageContent() {
<BackgroundWrapper> <BackgroundWrapper>
<div className="min-h-screen"> <div className="min-h-screen">
<div className="mx-10 pt-10"> <div className="mx-10 pt-10">
<button onClick={() => router.push("/subjects")} className="mb-4"> <button
onClick={() => router.push(`/categories/${type}s`)}
className="mb-4"
>
<ArrowLeft size={30} color="black" /> <ArrowLeft size={30} color="black" />
</button> </button>
<div className="flex flex-col items-center justify-center"> <div className="flex flex-col items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div> <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
<p className="text-lg font-medium text-gray-900">Loading...</p> <p className="text-lg font-medium text-gray-900">Loading...</p>
</div> </div>
</div> </div>
</div> </div>
@ -85,13 +116,13 @@ function PretestPageContent() {
); );
} }
function handleStartExam() { // function handleStartExam() {
if (!examData) return; // if (!examData) return;
setCurrentExam(examData); // setCurrentExam(examData);
startExam(examData); // startExam(examData);
router.push(`/exam/${id}?time=${metadata?.metadata.duration}`); // router.push(`/exam/${id}?time=${metadata?.metadata.duration}`);
} // }
return ( return (
<BackgroundWrapper> <BackgroundWrapper>
<div className="min-h-screen flex flex-col justify-between"> <div className="min-h-screen flex flex-col justify-between">
@ -102,10 +133,12 @@ function PretestPageContent() {
<ArrowLeft size={30} color="black" /> <ArrowLeft size={30} color="black" />
</button> </button>
<h1 className="text-4xl font-semibold text-[#113768]">{title}</h1> <h1 className="text-4xl font-semibold text-[#113768]">
{metadata.name}
</h1>
<p className="text-xl font-medium text-[#113768]"> <p className="text-xl font-medium text-[#113768]">
Rating: {rating} / 10 Rating: 8 / 10
</p> </p>
<div className="border-[1.5px] border-[#226DCE]/30 rounded-[25px] gap-8 py-7 px-5 space-y-8"> <div className="border-[1.5px] border-[#226DCE]/30 rounded-[25px] gap-8 py-7 px-5 space-y-8">
@ -113,10 +146,10 @@ function PretestPageContent() {
<HelpCircle size={40} color="#113768" /> <HelpCircle size={40} color="#113768" />
<div className="space-y-2"> <div className="space-y-2">
<p className="font-bold text-4xl text-[#113768]"> <p className="font-bold text-4xl text-[#113768]">
{metadata.metadata.quantity} {metadata.num_questions}
</p> </p>
<p className="font-normal text-lg"> <p className="font-normal text-lg">
{metadata.metadata.type} Multiple Choice Questions
</p> </p>
</div> </div>
</div> </div>
@ -125,7 +158,7 @@ function PretestPageContent() {
<Clock size={40} color="#113768" /> <Clock size={40} color="#113768" />
<div className="space-y-2"> <div className="space-y-2">
<p className="font-bold text-4xl text-[#113768]"> <p className="font-bold text-4xl text-[#113768]">
{metadata.metadata.duration} mins {String(metadata.time_limit_minutes)} mins
</p> </p>
<p className="font-normal text-lg">Time Taken</p> <p className="font-normal text-lg">Time Taken</p>
</div> </div>
@ -135,7 +168,7 @@ function PretestPageContent() {
<XCircle size={40} color="#113768" /> <XCircle size={40} color="#113768" />
<div className="space-y-2"> <div className="space-y-2">
<p className="font-bold text-4xl text-[#113768]"> <p className="font-bold text-4xl text-[#113768]">
{metadata.metadata.marking} {metadata.deduction} marks
</p> </p>
<p className="font-normal text-lg"> <p className="font-normal text-lg">
From each wrong answer From each wrong answer
@ -188,7 +221,7 @@ function PretestPageContent() {
</div> </div>
<button <button
onClick={async () => handleStartExam()} onClick={() => console.log("Exam started")}
className="fixed bottom-0 w-full bg-[#113768] h-[78px] justify-center items-center flex text-white text-2xl font-bold" className="fixed bottom-0 w-full bg-[#113768] h-[78px] justify-center items-center flex text-white text-2xl font-bold"
> >
Start Test Start Test

30
types/exam.d.ts vendored
View File

@ -1,20 +1,34 @@
export type Metadata = { export interface Metadata {
test_id: string; attempt_id: string;
total_possible_score: number; total_possible_score: number;
deduction: number; deduction: string;
num_questions: number; num_questions: number;
name: string; name: string;
start_time: Date; start_time: Date;
time_limit_minutes: number; time_limit_minutes: number;
} }
export type Question = { export interface MockMeta extends Metadata {
question_id: string; test_id: string;
question: string;
options: string[];
type: string;
} }
export interface SubjectMeta extends Metadata {
subject_id: string;
subject_name: string;
}
export interface TopicMeta extends Metadata {
topic_id: string;
topic_name: string;
}
export type Question = {
question_id: string;
question: string;
options: string[];
type: string;
};
export interface Test { export interface Test {
metadata: Metadata; metadata: Metadata;
questions: Question[]; questions: Question[];