fix(api): fix exam screen api logic

This commit is contained in:
shafin-r
2025-08-27 23:45:37 +06:00
parent 84bc192e02
commit 08a560abe5
4 changed files with 143 additions and 203 deletions

View File

@ -2,26 +2,26 @@
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useEffect, useState } from "react";
import { ArrowLeft, HelpCircle, Clock, XCircle, OctagonX } from "lucide-react";
import {
ArrowLeft,
HelpCircle,
Clock,
XCircle,
OctagonX,
RotateCw,
} from "lucide-react";
import DestructibleAlert from "@/components/DestructibleAlert";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import { API_URL, getToken } from "@/lib/auth";
import { useExam } from "@/context/ExamContext";
import { Test } from "@/types/exam";
import { Metadata, MockMeta, SubjectMeta, TopicMeta } from "@/types/exam";
type MetadataType = "mock" | "subject" | "topic";
type MetadataMap = {
mock: MockMeta;
subject: SubjectMeta;
topic: TopicMeta;
};
import { Question } from "@/types/exam";
import { Metadata } from "@/types/exam";
function PretestPageContent() {
const router = useRouter();
const searchParams = useSearchParams();
const { startExam, setCurrentExam } = useExam();
const [examData, setExamData] = useState<Question[]>();
// Get params from URL search params
const id = searchParams.get("test_id") || "";
@ -31,19 +31,10 @@ function PretestPageContent() {
? typeParam
: null;
const [metadata, setMetadata] = useState<MetadataMap[MetadataType] | null>(
null
);
const [metadata, setMetadata] = useState<Metadata | 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 || !type) return;
@ -63,9 +54,11 @@ function PretestPageContent() {
}
const data = await questionResponse.json();
const fetchedMetadata = fetchMetadata(type, data.metadata);
const fetchedMetadata: Metadata = data.metadata;
const fetchedQuestions: Question[] = data.questions;
setMetadata(fetchedMetadata);
setExamData(fetchedQuestions);
} catch (error) {
console.error(error);
setError(error instanceof Error ? error.message : "An error occurred");
@ -80,19 +73,25 @@ function PretestPageContent() {
if (error) {
return (
<BackgroundWrapper>
<div className="min-h-screen">
<div className="mx-10 pt-10">
<button
onClick={() => router.push("/categories/subjects")}
className="mb-4"
>
<ArrowLeft size={30} color="black" />
</button>
<div className="">
<div className="min-h-screen mx-10 pt-10 flex flex-col justify-center items-center gap-4">
<div className="flex flex-col justify-center items-center gap-4 w-full">
<DestructibleAlert
text={error}
icon={<OctagonX size={150} color="red" />}
/>
<div className="flex items-center justify-evenly w-full">
<button
onClick={() => router.push(`/categories/${type}s`)}
className="p-4 border border-blue-200 rounded-full bg-blue-400"
>
<ArrowLeft size={35} color="white" />
</button>
<button
onClick={() => router.refresh()}
className="p-4 border border-blue-200 rounded-full bg-red-400"
>
<RotateCw size={35} color="white" />
</button>
</div>
</div>
</div>
@ -121,13 +120,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}?test_id=${metadata?.test_id}`);
}
return (
<BackgroundWrapper>
<div className="min-h-screen flex flex-col justify-between">
@ -226,7 +225,7 @@ function PretestPageContent() {
</div>
<button
onClick={() => console.log("Exam started")}
onClick={() => handleStartExam()}
className="fixed bottom-0 w-full bg-[#113768] h-[78px] justify-center items-center flex text-white text-2xl font-bold"
>
Start Test

View File

@ -10,7 +10,7 @@ const DestructibleAlert: React.FC<DestructibleAlertProps> = ({
icon,
}) => {
return (
<div className=" bg-red-200 rounded-3xl py-6 flex flex-col items-center justify-center gap-2 ">
<div className=" bg-red-200 rounded-3xl py-6 flex flex-col items-center justify-center gap-2 w-full ">
<div>{icon}</div>
<p className="text-lg font-bold text-center text-red-800">{text}</p>
</div>

View File

@ -9,10 +9,11 @@ import React, {
} from "react";
import { useRouter } from "next/navigation";
import { Exam, ExamAnswer, ExamAttempt, ExamContextType } from "@/types/exam";
import { Test, TestAttempt, TestContextType, Answer } from "@/types/exam";
import { getFromStorage, removeFromStorage, setToStorage } from "@/lib/utils";
import { useAuth } from "./AuthContext";
const ExamContext = createContext<ExamContextType | undefined>(undefined);
const ExamContext = createContext<TestContextType | undefined>(undefined);
const STORAGE_KEYS = {
CURRENT_EXAM: "current-exam",
@ -23,47 +24,30 @@ export const ExamProvider: React.FC<{ children: ReactNode }> = ({
children,
}) => {
const router = useRouter();
const [currentExam, setCurrentExamState] = useState<Exam | null>(null);
const [currentAttempt, setCurrentAttemptState] = useState<ExamAttempt | null>(
const [currentExam, setCurrentExamState] = useState<Test | null>(null);
const [currentAttempt, setCurrentAttemptState] = useState<TestAttempt | null>(
null
);
const [isHydrated, setIsHydrated] = useState(false);
const [isInitialized, setIsInitialized] = useState(false);
const { user } = useAuth();
// Hydrate from session storage on mount
// Hydrate from storage
useEffect(() => {
const savedExam = getFromStorage<Exam>(STORAGE_KEYS.CURRENT_EXAM);
const savedAttempt = getFromStorage<ExamAttempt>(
const savedExam = getFromStorage<Test>(STORAGE_KEYS.CURRENT_EXAM);
const savedAttempt = getFromStorage<TestAttempt>(
STORAGE_KEYS.CURRENT_ATTEMPT
);
if (savedExam) {
setCurrentExamState(savedExam);
}
if (savedAttempt) {
// Convert date strings back to Date objects
const hydratedAttempt = {
...savedAttempt,
startTime: new Date(savedAttempt.startTime),
endTime: savedAttempt.endTime
? new Date(savedAttempt.endTime)
: undefined,
answers: savedAttempt.answers.map((answer) => ({
...answer,
timestamp: new Date(answer.timestamp),
})),
};
setCurrentAttemptState(hydratedAttempt);
}
if (savedExam) setCurrentExamState(savedExam);
if (savedAttempt) setCurrentAttemptState(savedAttempt);
setIsHydrated(true);
}, []);
// Persist to session storage whenever state changes
// Persist exam
useEffect(() => {
if (!isHydrated) return;
if (currentExam) {
setToStorage(STORAGE_KEYS.CURRENT_EXAM, currentExam);
} else {
@ -71,9 +55,9 @@ export const ExamProvider: React.FC<{ children: ReactNode }> = ({
}
}, [currentExam, isHydrated]);
// Persist attempt
useEffect(() => {
if (!isHydrated) return;
if (currentAttempt) {
setToStorage(STORAGE_KEYS.CURRENT_ATTEMPT, currentAttempt);
} else {
@ -81,13 +65,14 @@ export const ExamProvider: React.FC<{ children: ReactNode }> = ({
}
}, [currentAttempt, isHydrated]);
const setCurrentExam = (exam: Exam) => {
const setCurrentExam = (exam: Test) => {
setCurrentExamState(exam);
setCurrentAttemptState(null);
};
const startExam = (exam?: Exam): void => {
const startExam = (exam?: Test): void => {
const examToUse = exam || currentExam;
const user_id = user?.user_id;
if (!examToUse) {
console.warn("No exam selected, redirecting to /unit");
@ -95,95 +80,79 @@ export const ExamProvider: React.FC<{ children: ReactNode }> = ({
return;
}
const attempt: ExamAttempt = {
examId: examToUse.id,
exam: examToUse,
answers: [],
startTime: new Date(),
totalQuestions: 0,
score: 0,
const attempt: TestAttempt = {
user_id: user_id, // TODO: inject from auth
test_id: examToUse.metadata.test_id,
subject_id: "temp-subject", // TODO: might delete
topic_id: "temp-topic", // TODO: might delete
test_type: "Mock", // or "Subject"/"Topic" depending on flow
attempt_id: crypto.randomUUID(),
start_time: new Date().toISOString(),
end_time: "",
user_questions: examToUse.questions,
user_answers: Array(examToUse.questions.length).fill(null),
correct_answers: [],
correct_answers_count: 0,
wrong_answers_count: 0,
skipped_questions_count: 0,
};
setCurrentAttemptState(attempt);
setIsInitialized(true);
};
const setAnswer = (questionId: string, answer: any) => {
const setAnswer = (questionId: string, answer: Answer) => {
if (!currentAttempt) {
console.warn("No exam attempt started, redirecting to /unit");
router.push("/unit");
return;
}
const questionIndex = currentAttempt.user_questions.findIndex(
(q) => q.question_id === questionId
);
if (questionIndex === -1) return;
setCurrentAttemptState((prev) => {
if (!prev) return null;
const existingAnswerIndex = prev.answers.findIndex(
(a) => a.questionId === questionId
);
const newAnswer: ExamAnswer = {
questionId,
answer,
timestamp: new Date(),
};
let newAnswers: ExamAnswer[];
if (existingAnswerIndex >= 0) {
// Update existing answer
newAnswers = [...prev.answers];
newAnswers[existingAnswerIndex] = newAnswer;
} else {
// Add new answer
newAnswers = [...prev.answers, newAnswer];
}
return {
...prev,
answers: newAnswers,
};
const updatedAnswers = [...prev.user_answers];
updatedAnswers[questionIndex] = answer;
return { ...prev, user_answers: updatedAnswers };
});
};
const setApiResponse = (response: any) => {
if (!currentAttempt) {
console.warn("No exam attempt started, redirecting to /unit");
router.push("/unit");
return;
}
setCurrentAttemptState((prev) => {
if (!prev) return null;
return {
...prev,
apiResponse: response,
};
});
// If you want to store API response in attempt
setCurrentAttemptState((prev) =>
prev ? { ...prev, apiResponse: response } : null
);
};
const submitExam = (): ExamAttempt | null => {
const submitExam = (): TestAttempt | null => {
if (!currentAttempt) {
console.warn("No exam attempt to submit, redirecting to /unit");
router.push("/unit");
return null;
}
// Calculate score (simple example - you can customize this)
const attemptQuestions = currentAttempt.exam.questions;
const totalQuestions = attemptQuestions.length;
const answeredQuestions = currentAttempt.answers.filter(
(a) => a.questionId !== "__api_response__"
).length;
const score = Math.round((answeredQuestions / totalQuestions) * 100);
const totalQuestions = currentAttempt.user_questions.length;
const completedAttempt: ExamAttempt = {
// Example evaluation (assumes correct answers in `correct_answers`)
const wrong = currentAttempt.user_answers.filter(
(ans, idx) => ans !== null && ans !== currentAttempt.correct_answers[idx]
).length;
const skipped = currentAttempt.user_answers.filter(
(ans) => ans === null
).length;
const correct = totalQuestions - wrong - skipped;
const completedAttempt: TestAttempt = {
...currentAttempt,
endTime: new Date(),
score,
totalQuestions,
passed: currentAttempt.exam.passingScore
? score >= currentAttempt.exam.passingScore
: undefined,
end_time: new Date().toISOString(),
correct_answers_count: correct,
wrong_answers_count: wrong,
skipped_questions_count: skipped,
};
setCurrentAttemptState(completedAttempt);
@ -195,38 +164,35 @@ export const ExamProvider: React.FC<{ children: ReactNode }> = ({
setCurrentAttemptState(null);
};
const getAnswer = (questionId: string): any => {
if (!currentAttempt) return undefined;
const answer = currentAttempt.answers.find(
(a) => a.questionId === questionId
const getAnswer = (questionId: string): Answer => {
if (!currentAttempt) return null;
const index = currentAttempt.user_questions.findIndex(
(q) => q.question_id === questionId
);
return answer?.answer;
return index >= 0 ? currentAttempt.user_answers[index] : null;
};
const getApiResponse = (): any => {
return currentAttempt?.apiResponse;
return (currentAttempt as any)?.apiResponse;
};
const getProgress = (): number => {
if (!currentAttempt || !currentAttempt.exam) return 0;
const totalQuestions = currentAttempt.exam.questions.length;
const answeredQuestions = currentAttempt.answers.filter(
(a) => a.questionId !== "__api_response__"
if (!currentAttempt) return 0;
const totalQuestions = currentAttempt.user_questions.length;
const answered = currentAttempt.user_answers.filter(
(a) => a !== null
).length;
return totalQuestions > 0 ? (answeredQuestions / totalQuestions) * 100 : 0;
return totalQuestions > 0 ? (answered / totalQuestions) * 100 : 0;
};
const isExamStarted = () => !!currentExam && !!currentAttempt;
const isExamCompleted = (): boolean => {
if (!isHydrated) return false; // wait for hydration
return currentAttempt !== null && currentAttempt.endTime !== undefined;
if (!isHydrated) return false;
return !!currentAttempt?.end_time;
};
const contextValue: ExamContextType = {
const contextValue: TestContextType = {
currentExam,
currentAttempt,
setCurrentExam,
@ -249,29 +215,17 @@ export const ExamProvider: React.FC<{ children: ReactNode }> = ({
);
};
export const useExam = (): ExamContextType => {
export const useExam = (): TestContextType => {
const context = useContext(ExamContext);
if (context === undefined) {
if (!context) {
throw new Error("useExam must be used within an ExamProvider");
}
return context;
};
// Hook for exam results (only when exam is completed) - now returns null instead of throwing
export const useExamResults = (): ExamAttempt | null => {
export const useExamResults = (): TestAttempt | null => {
const { currentAttempt, isExamCompleted, isHydrated } = useExam();
// Wait for hydration before making decisions
if (!isHydrated) {
return null;
}
// If no completed exam is found, return null (let component handle redirect)
if (!isExamCompleted() || !currentAttempt) {
return null;
}
if (!isHydrated) return null;
if (!isExamCompleted() || !currentAttempt) return null;
return currentAttempt;
};

55
types/exam.d.ts vendored
View File

@ -1,32 +1,20 @@
export interface Metadata {
attempt_id: string;
test_id: string;
type: string;
total_possible_score: number;
deduction: string;
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;
start_time: string; // keep ISO string for consistency
time_limit_minutes?: number;
}
export type Question = {
question_id: string;
question: string;
options: string[];
type: string;
type: "Single" | "Multiple";
};
export interface Test {
@ -34,28 +22,27 @@ export interface Test {
questions: Question[];
}
type Answers = number | null;
export type Answer = number | null;
export type AnswersMap = Record<string, Answer>;
export interface TestAttempt {
user_id: string;
user_id: string | undefined;
test_id: string;
subject_id: string;
topic_id: string;
test_type: "Subject" | "Topic" | "Mock" | "Past";
attempt_id: string;
start_time: Date;
end_time: Date;
user_questions: {
question_id: string;
question: string;
options: string[];
type: string;
};
user_answers: Record<string, Answers>;
correct_answers: Record<string, Answers>;
start_time: string;
end_time: string;
user_questions: Question[];
user_answers: (number | null)[];
correct_answers: number[];
correct_answers_count: number;
wrong_answers_count: number;
skipped_questions_count: number;
}
export interface ExamContextType {
export interface TestContextType {
currentExam: Test | null;
currentAttempt: TestAttempt | null;
isHydrated: boolean;
@ -64,13 +51,13 @@ export interface ExamContextType {
// Actions
setCurrentExam: (exam: Test) => void;
startExam: (exam?: Test) => void;
setAnswer: (questionId: string, answer: Answers) => void;
submitExam: () => TestAttempt | null;
setAnswer: (questionId: string, answer: Answer) => void;
submitExam: () => TestAttempt | null; // or Promise<TestAttempt | null> if API
clearExam: () => void;
setApiResponse: (response: any) => void;
// Getters
getAnswer: (questionId: string) => Answers;
getAnswer: (questionId: string) => Answer;
getProgress: () => number;
isExamStarted: () => boolean;
isExamCompleted: () => boolean;