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

View File

@ -10,7 +10,7 @@ const DestructibleAlert: React.FC<DestructibleAlertProps> = ({
icon, icon,
}) => { }) => {
return ( 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> <div>{icon}</div>
<p className="text-lg font-bold text-center text-red-800">{text}</p> <p className="text-lg font-bold text-center text-red-800">{text}</p>
</div> </div>

View File

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

55
types/exam.d.ts vendored
View File

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