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
onClick={() =>
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"

View File

@ -1,6 +1,5 @@
"use client";
import { useSearchParams } from "next/navigation";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import Header from "@/components/Header";
@ -9,7 +8,6 @@ import BackgroundWrapper from "@/components/BackgroundWrapper";
import { API_URL, getToken } from "@/lib/auth";
import { Loader, RefreshCw } from "lucide-react";
import { useAuth } from "@/context/AuthContext";
import { Question } from "@/types/exam";
type Topic = {
topic_id: string;
@ -95,7 +93,7 @@ export default function TopicScreen() {
<div>
<Header displayTabTitle="Topics" />
<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}
</h1>
<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}>
<button
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"
>

View File

@ -77,11 +77,10 @@ const HomePage = () => {
<ChevronRight size={24} color="#113768" />
</button>
</div>
<div className={styles.categoriesContainer}>
<div className={styles.categoryRow}>
<div className="grid grid-cols-2 gap-4 pt-6 ">
<button
onClick={() => router.push("/topics")}
className={`${styles.categoryButton} `}
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"
@ -89,13 +88,14 @@ const HomePage = () => {
width={85}
height={85}
/>
<span className={styles.categoryButtonText}>
<span className="font-medium text-[#113768]">
Topic Test
</span>
</button>
<button
onClick={() => router.push("/mocks")}
className={styles.categoryButton}
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"
@ -103,29 +103,30 @@ const HomePage = () => {
width={85}
height={85}
/>
<span className={styles.categoryButtonText}>
<span className="font-medium text-[#113768]">
Mock Test
</span>
</button>
</div>
<div className={styles.categoryRow}>
<button
disabled
className={`${styles.categoryButton} ${styles.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={styles.categoryButtonText}>
<span className="font-medium text-[#113768]/50">
Past Papers
</span>
</button>
<button
onClick={() => router.push("/subjects")}
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"
@ -133,13 +134,12 @@ const HomePage = () => {
width={80}
height={80}
/>
<span className={styles.categoryButtonText}>
<span className="font-medium text-[#113768]">
Subject Test
</span>
</button>
</div>
</div>
</div>
{/* Leaderboard Section */}
<div className={styles.leaderboardWrapper}>

View File

@ -11,7 +11,7 @@ const tabs = [
{ name: "Home", href: "/home", component: <House size={30} /> },
{
name: "Categories",
href: "/subjects",
href: "/categories",
component: <LayoutGrid 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 DestructibleAlert from "@/components/DestructibleAlert";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import { API_URL } from "@/lib/auth";
import { API_URL, getToken } from "@/lib/auth";
import { useExam } from "@/context/ExamContext";
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() {
const router = useRouter();
const searchParams = useSearchParams();
const [examData, setExamData] = useState<Test>();
const { startExam, setCurrentExam } = useExam();
// 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 [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(() => {
async function fetchQuestions() {
if (!id) return;
if (!id || !type) return;
try {
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",
headers: {
authorization: `Bearer ${token}`,
},
});
if (!questionResponse.ok) {
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);
} catch (error) {
console.error(error);
@ -47,17 +73,19 @@ function PretestPageContent() {
setLoading(false);
}
}
if (id) {
fetchQuestions();
}
}, [id]);
}, [id, type]);
if (error) {
return (
<BackgroundWrapper>
<div className="min-h-screen">
<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" />
</button>
<DestructibleAlert text={error} extraStyles="" />
@ -72,7 +100,10 @@ function PretestPageContent() {
<BackgroundWrapper>
<div className="min-h-screen">
<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" />
</button>
<div className="flex flex-col items-center justify-center">
@ -85,13 +116,13 @@ function PretestPageContent() {
);
}
function handleStartExam() {
if (!examData) return;
// function handleStartExam() {
// if (!examData) return;
setCurrentExam(examData);
startExam(examData);
router.push(`/exam/${id}?time=${metadata?.metadata.duration}`);
}
// setCurrentExam(examData);
// startExam(examData);
// router.push(`/exam/${id}?time=${metadata?.metadata.duration}`);
// }
return (
<BackgroundWrapper>
<div className="min-h-screen flex flex-col justify-between">
@ -102,10 +133,12 @@ function PretestPageContent() {
<ArrowLeft size={30} color="black" />
</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]">
Rating: {rating} / 10
Rating: 8 / 10
</p>
<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" />
<div className="space-y-2">
<p className="font-bold text-4xl text-[#113768]">
{metadata.metadata.quantity}
{metadata.num_questions}
</p>
<p className="font-normal text-lg">
{metadata.metadata.type}
Multiple Choice Questions
</p>
</div>
</div>
@ -125,7 +158,7 @@ function PretestPageContent() {
<Clock size={40} color="#113768" />
<div className="space-y-2">
<p className="font-bold text-4xl text-[#113768]">
{metadata.metadata.duration} mins
{String(metadata.time_limit_minutes)} mins
</p>
<p className="font-normal text-lg">Time Taken</p>
</div>
@ -135,7 +168,7 @@ function PretestPageContent() {
<XCircle size={40} color="#113768" />
<div className="space-y-2">
<p className="font-bold text-4xl text-[#113768]">
{metadata.metadata.marking}
{metadata.deduction} marks
</p>
<p className="font-normal text-lg">
From each wrong answer
@ -188,7 +221,7 @@ function PretestPageContent() {
</div>
<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"
>
Start Test

22
types/exam.d.ts vendored
View File

@ -1,19 +1,33 @@
export type Metadata = {
test_id: string;
export interface Metadata {
attempt_id: string;
total_possible_score: number;
deduction: number;
deduction: string;
num_questions: number;
name: string;
start_time: Date;
time_limit_minutes: number;
}
export interface MockMeta extends Metadata {
test_id: 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 {
metadata: Metadata;