generated from muhtadeetaron/nextjs-template
fix(api): fix exam screen api logic
This commit is contained in:
@ -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;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user