Skip to content

Commit

Permalink
SimpleQuizResponse updates
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewtan2000 committed Sep 26, 2024
1 parent d800067 commit 7fdd301
Show file tree
Hide file tree
Showing 9 changed files with 41 additions and 88 deletions.
7 changes: 1 addition & 6 deletions app/(main)/classes/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,7 @@ const Classes = () => {
return { descriptionName, apiName, defaultValue, value, setValue };
};

const classMapList = [
useGenerateClassMap('Class Code', 'code'),
useGenerateClassMap('Class Name', 'description'),
useGenerateClassMap('Class Education Level', 'educationLevel'),
useGenerateClassMap('Class Subject', 'subject', 'Chemistry')
];
const classMapList = [useGenerateClassMap('Class Code', 'code'), useGenerateClassMap('Class Name', 'description'), useGenerateClassMap('Class Education Level', 'educationLevel'), useGenerateClassMap('Class Subject', 'subject', 'Chemistry')];

const clearNewClass = () => {
setAddClass(false);
Expand Down
16 changes: 8 additions & 8 deletions app/(main)/quiz/history/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,20 +76,20 @@ const QuizHistory: React.FC = () => {
const fetchData = async () => {
try {
const responseData = await QuizService.getQuizCompleted();
if (responseData.message === 'Quiz not found') {
setError('Quiz not found');
setLoading(false);
return;
}
// if (responseData.message === 'Quiz not found') {
// setError('Quiz not found');
// setLoading(false);
// return;
// }
setQuiz(responseData);

// Process the data to calculate counts and extract unique topics and skills
const processedData = responseData.quizzes
const processedData = responseData.content
.map((quiz: Quiz.QuizTaken) => {
const topicsMap = new Map<number, Topic>();
const skillsMap = new Map<number, Skill>();

quiz.mcqs.forEach((mcq: Quiz.Mcq) => {
quiz.mcqs.forEach((mcq: Quiz.SimpleQuizResponse) => {
mcq.topics.forEach((topic) => topicsMap.set(topic.id, topic));
mcq.skills.forEach((skill) => skillsMap.set(skill.id, skill));
});
Expand Down Expand Up @@ -154,7 +154,7 @@ const QuizHistory: React.FC = () => {
<div className="col-12">
<div className="card">
<h5>History</h5>
<p>You currently have completed {quiz?.quizzes ? quiz.quizzes.length : 0} quizzes.</p>
<p>You currently have completed {quiz?.content ? quiz.content.length : 0} quizzes.</p>
<DataTable value={processedQuizzes} tableStyle={{ minWidth: '50rem' }} sortField="attemptOn" sortOrder={-1} defaultSortOrder={1}>
<Column body={dateBodyTemplate} header="Attempted On" sortable field="attemptOn"></Column>
{/* <Column body={idBodyTemplate} header="Quiz Number" sortable field="id"></Column> */}
Expand Down
12 changes: 5 additions & 7 deletions app/(main)/quiz/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,14 @@ const QuizPage: React.FC = () => {
useEffect(() => {
const fetchData = async () => {
try {
const responseData = await QuizService.getQuizInProgress();
const responseData = await QuizService.getQuizInProgress(selectedQuestionCount);
if (responseData.message === 'Quiz not found') {
setIsQuizOngoing(false);
return;
}
setQuiz(responseData);
const initialSelectedOptions: { [key: number]: number | 0 } = {};
responseData.mcqs.forEach((mcq) => {
responseData.mcqs.content.forEach((mcq) => {
initialSelectedOptions[mcq.id] = 0;
});
setSelectedOptions(initialSelectedOptions);
Expand All @@ -127,7 +127,6 @@ const QuizPage: React.FC = () => {
invitationResponse(invitationResult);
}
}, 500);

}, []);

const invitationResponse = (isSucceeded: boolean) => {
Expand Down Expand Up @@ -315,7 +314,6 @@ const QuizPage: React.FC = () => {
};

fetchData();

}, [selectedTopics, selectedSkills]);

const calculateScore = () => {
Expand Down Expand Up @@ -432,7 +430,7 @@ const QuizPage: React.FC = () => {

const questionOptions = Array.from({ length: generatedQuestionCount }, (_, i) => ({
label: `${i + 1} question${i + 1 > 1 ? 's' : ''}`,
value: i + 1,
value: i + 1
})).reverse(); // Reverse the array

return (
Expand Down Expand Up @@ -571,7 +569,7 @@ const QuizPage: React.FC = () => {
<b>{currentQuestion.topics.map((topic) => topic.name).join(', ')}</b>
</h6>
</div>
<ProgressBar value={Math.round(((currentQuestionIndex + 1) / quiz?.mcqs?.length) * 100)} />
<ProgressBar value={Math.round(((currentQuestionIndex + 1) / quiz?.mcqs?.content?.length) * 100)} />
</div>
)}
{showScore && showScoreMessage && (
Expand All @@ -590,4 +588,4 @@ const QuizPage: React.FC = () => {
);
};

export default QuizPage;
export default QuizPage;
2 changes: 1 addition & 1 deletion app/(main)/quiz/results/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { QuizService } from '@/service/QuizService';
const ResultsPage: React.FC = () => {
const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
const [reload, setReload] = useState(false);
const [quiz, setQuiz] = useState<Quiz.ApiResponse | null>(null); // Add state for the quiz data
const [quiz, setQuiz] = useState<Quiz.QuizTaken | null>(null); // Add state for the quiz data

const searchParams = useSearchParams();
const quizIdParam = searchParams.get('quizId');
Expand Down
20 changes: 1 addition & 19 deletions app/(main)/test/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,25 +68,7 @@ const TestPage: React.FC = () => {
};

useEffect(() => {
const fetchData = async () => {
try {
const responseData = await TestService.getTestInProgress();
if (responseData.message === 'Test not found') {
setIsTestOngoing(false);
return;
}
setTest(responseData);
const initialSelectedOptions: { [key: number]: number | 0 } = {};
responseData.mcqs.forEach((mcq) => {
initialSelectedOptions[mcq.id] = 0;
});
setSelectedOptions(initialSelectedOptions);
setTestIdAvailable(true); // Set quizIdAvailable to true once quiz data is fetched
setExplanationsVisible({}); // Initialize explanationsVisible
} catch (error) {
console.error('Error fetching data:', error);
}
};
const fetchData = async () => {};

fetchData();
}, []);
Expand Down
6 changes: 3 additions & 3 deletions components/ResultsTop.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,19 +56,19 @@ export default function ResultsTopComponent({ onQuestionClick, currentQuestionIn
return <div className="card">{error}</div>;
}

if (!quiz || !quiz.quizzes || quiz.quizzes.length === 0) {
if (!quiz || !quiz.content || quiz.content.length === 0) {
return <div className="card">No quiz data available</div>;
}

// Find the specific quiz by ID
const specificQuiz = quiz.quizzes.find((quiz: Quiz.QuizTaken) => quiz.id === parseInt(quizId, 10));
const specificQuiz = quiz.content.find((quiz: Quiz.QuizTaken) => quiz.id === parseInt(quizId, 10));

if (!specificQuiz || !specificQuiz.mcqs || specificQuiz.mcqs.length === 0) {
return <div className="card">No questions available for this quiz</div>;
}

// Update the progress calculation
const progress = specificQuiz.mcqs.map((mcq: Quiz.Mcq) => {
const progress = specificQuiz.mcqs.map((mcq: Quiz.SimpleQuizResponse) => {
const attemptOption = mcq.attemptOption ?? 0;
const selectedOption = mcq.options[attemptOption - 1];
return selectedOption && selectedOption.isAnswer;
Expand Down
4 changes: 2 additions & 2 deletions service/QuizService.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export const QuizService = {
}
},

fetchQuizById: async (quizId: number): Promise<Quiz.ApiResponse> => {
fetchQuizById: async (quizId: number): Promise<Quiz.QuizTaken> => {
const headers = ApiHelper.getRequestHeaders();
try {
const response = await fetch(
Expand All @@ -110,7 +110,7 @@ export const QuizService = {
throw new Error(`HTTP error! status: ${response.status}`);
}

const data: Quiz.ApiResponse = await response.json();
const data: Quiz.QuizTaken = await response.json();
return data;
} catch (error) {
console.error(`Error fetching quiz for Quiz ID: ${quizId}`, error);
Expand Down
40 changes: 0 additions & 40 deletions service/TestService.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,46 +35,6 @@ export const TestService = {
});
},

getTestInProgress: async (): Promise<ClassTest.ApiResponse> => {
try {
console.log('Fetching data from API...');
const headers = ApiHelper.getRequestHeaders();
const response = await fetch(
`${process.env.NEXT_PUBLIC_QUEMISTRY_QUIZZES_URL}/me/in-progress?pageNumber=0&pageSize=60`,
{
headers: headers,
credentials: "include"
}
);
const responseData: Quiz.ApiResponse = await response.json();
console.log('Data fetched successfully:', responseData);
return responseData;
} catch (error) {
console.error('No data could be displayed: ', error);
throw error;
}
},

getTestCompleted: async (): Promise<ClassTest.CompletedResponse> => {
try {
console.log('Fetching data from API...');
const headers = ApiHelper.getRequestHeaders();
const response = await fetch(
`${process.env.NEXT_PUBLIC_QUEMISTRY_QUIZZES_URL}/me/completed?pageNumber=0&pageSize=60`,
{
headers: headers,
credentials: "include"
}
);
const responseData: Quiz.CompletedResponse = await response.json();
console.log('Data fetched successfully:', responseData);
return responseData;
} catch (error) {
console.error('No data could be displayed: ', error);
throw error;
}
},

getTestById: async (quizId: number): Promise<Response> => {
const headers = ApiHelper.getRequestHeaders();
try {
Expand Down
22 changes: 20 additions & 2 deletions types/quiz.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,23 @@ declare namespace Quiz {
attemptOn: number | null;
}

interface SimpleQuizResponse {
id: number;
stem: string;
options: Option[];
topics: Topic[];
skills: Skill[];
status: string;
publishedOn: number;
publishedBy: string;
closedOn: number | null;
closedBy: string | null;
createdOn: number;
createdBy: string;
attemptOption: number | null;
attemptOn: number | null;
}

interface ApiResponse {
id: number;
mcqs: Mcq;
Expand All @@ -56,12 +73,13 @@ declare namespace Quiz {
// totalPages: number;
// totalRecords: number;
message?: string;
quizzes: QuizTaken[];
content: QuizTaken[];
// quizzes: QuizTaken[];
}

interface QuizTaken {
id: number;
mcqs: Mcq[];
mcqs: SimpleQuizResponse[];
status: string;
points: number;
pageNumber: number;
Expand Down

0 comments on commit 7fdd301

Please sign in to comment.