Skip to content

Commit

Permalink
Merge pull request #1506 from hngx-org/Great/Fix-3-Question-logic-fix
Browse files Browse the repository at this point in the history
Great/fix 3 question logic fix
  • Loading branch information
incredible-phoenix246 authored Nov 27, 2023
2 parents 3813757 + 338953f commit dec595c
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 41 deletions.
8 changes: 4 additions & 4 deletions http/userTakenAssessment.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import axios from 'axios';
import $http from './axios';

const assessmentBaseUrl = `https://assessment.cofucan.tech/api/v1`;
const assessmentBaseUrl = `https://hng-stage-9.onrender.com/api/v1`;

export const fetchAssessmentHistory = async (token: string) => {
try {
Expand All @@ -10,7 +10,7 @@ export const fetchAssessmentHistory = async (token: string) => {
token: token,
},
});
return res.data;
return res.data.data;
} catch (error) {
console.error('Error Assessment History:', error);
throw error;
Expand Down Expand Up @@ -73,13 +73,13 @@ export const fetchUserTakenAssessment = async (token: string, id: any) => {

export const fetchUserAssessmentSession = async (token: string) => {
try {
const res = await axios.get(`${assessmentBaseUrl}/assessments/session/`, {
const res = await axios.get(`${assessmentBaseUrl}/assessments/session`, {
headers: {
'Content-Type': 'application/json',
token: token,
},
});
return res.data.data;
return res.data;
} catch (error) {
console.error('Error fetching user taken assessment:', error);
throw new Error('Failed to fetch user taken assessment');
Expand Down
5 changes: 2 additions & 3 deletions modules/assessment/component/History.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const History: React.FC = () => {
} = useQuery(['assessmentsHistory'], () => fetchAssessmentHistory(tokenRef.current as string));
console.log('history', assessmentsHistory);

const assessments = assessmentsHistory;


React.useEffect(() => {
tokenRef.current = localStorage.getItem('zpt');
Expand Down Expand Up @@ -71,8 +71,7 @@ const History: React.FC = () => {
setCurrentPage(1);
};

const filteredAssessments = assessments
?.filter(
const filteredAssessments = assessmentsHistory?.filter(
(assessment: Assessment) =>
assessment.assessment_name?.toLowerCase().includes(searchTerm.toLowerCase()) &&
(selectedLevel === 'All' ? true : assessment.badge_name?.toLowerCase() === selectedLevel),
Expand Down
79 changes: 54 additions & 25 deletions pages/assessments/overview/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { TimerStart } from 'iconsax-react';
import { withUserAuth } from '../../../helpers/withAuth';
import Head from 'next/head';
import Loader from '@ui/Loader';
import { useQuery } from '@tanstack/react-query';

export interface Question {
answer_id: number;
Expand Down Expand Up @@ -56,7 +57,6 @@ function AssessmentOverview() {

useEffect(() => {
tokenRef.current = localStorage.getItem('zpt');
handleGetSession();
}, []);

useEffect(() => {
Expand Down Expand Up @@ -85,21 +85,6 @@ function AssessmentOverview() {
setTimeFunction();
}, [duration, minute, second]);

const handleGetSession = async () => {
const token = tokenRef.current;
try {
const res = await fetchUserAssessmentSession(token as string);
setResult(res);
if (!res) {
setIsLoading(false);
throw new Error('Network response was not ok');
} else {
setResult(res);
setIsLoading(false);
}
} catch (error) {}
};

function sortQuestionsByQuestionNo(input: QuestionArrays | undefined): Question[] {
if (!input) return [];
// Concatenate the 'answered_questions' and 'unanswered_questions' arrays
Expand Down Expand Up @@ -130,13 +115,57 @@ function AssessmentOverview() {
console.error('Error submitting assessment:', error);
}
};

return (
const {data:sessionData,isLoading:sessionIsLoading,isError} = useQuery(['assessment'], () => fetchUserAssessmentSession(tokenRef.current as string), {
notifyOnChangeProps: ['data',"isError","isLoading"],
})
console.log("data",sessionData)
console.log("isLoading",sessionIsLoading)
console.log("isError",isError)
if (isError) {
return (
<>
<Head>
<style>
{`
.overscroll::-webkit-scrollbar{
width: 7px;
height: 10px;
background: #eee;
}
.overscroll::-webkit-scrollbar-thumb{
background: #009254;
border-radius: 5px;
}
`}
</style>
<title>Assessment | Overview</title>
<meta name="description" content="Zuri Portfolio Assessment Question Page" />
<link rel="icon" href="/assets/zuriLogo.svg" />
</Head>
<MainLayout activePage={'Overview'} showTopbar showFooter showDashboardSidebar={false}>
<AssessmentBanner
title="Assessment test"
subtitle="Something went wrong while trying to get your assessment"
bannerImageSrc="/assets/images/banner/assm_1.svg"
/>
<div className="flex justify-center items-center h-screen">
<div className="flex flex-col items-center gap-5">
<h1 className="text-7xl font-extrabold text-brand-green-primary text-center">OOPS!</h1>
<h1 className="text-2xl text-brand-green-primary text-center font-bold mb-4">something went wrong</h1>
</div>
</div>
</MainLayout>
</>
);
}
else
{return (
<>
<Head>
<title>Assessment | Overview</title>
<title>Overview</title>
<meta name="description" content="Zuri Portfolio Assessment Overview" />
<link rel="icon" href="./public/assets/zuriLogo.svg" />
<link rel="icon" href="/assets/zuriLogo.svg" />
</Head>
{isTimeOut && (
<OutOfTime
Expand All @@ -151,7 +180,7 @@ function AssessmentOverview() {

<ConfirmSubmitModal showModal={showConfirm} setShowModal={setShowConfirm} onConfirmFn={handleOnSubmit} />
<SuccessFeedbackModal showModal={showSuccessConfirm} setShowModal={setShowSuccessConfirm} badgeID={badgeEarn} />
{isLoading ? (
{sessionIsLoading ? (
<div className="flex justify-center items-center h-screen">
<Loader />
</div>
Expand All @@ -165,21 +194,21 @@ function AssessmentOverview() {
/>
<div className="w-full md:max-w-full px-4 max-w-xs mt-8 mb-16 mx-auto font-manropeL flex flex-col items-stretch justify-between gap-y-8">
<div className="w-full lg:max-w-lg md:max-w-full sm:mx-w-xs rounded-lg flex items-center justify-between py-4 px-8 bg-brand-green-primary mt-5">
<p className="text-white-100 text-2xl font-bold">
<div className="text-white-100 text-2xl font-bold">
{(minute !== null || undefined) && (second !== null || undefined) ? (
<CountdownTimer action={() => setTimeUp(true)} minutes={minute} seconds={second} />
) : (
<span>- - : - -</span>
)}
</p>
</div>
<span>
<TimerStart color="#fff" />
</span>
</div>
</div>
<div className="w-full max-w-[1240px] mx-auto flex flex-col px-4">
<div className="w-full py-6 md:py-9 lg:py-12 flex flex-col gap-6 md:gap-8 lg:gap-10">
{sortQuestionsByQuestionNo(result)?.map((item) => (
{sessionData?.data?.length>1 && sortQuestionsByQuestionNo(sessionData)?.map((item) => (
<OverviewItem
key={item?.question_id}
data={item}
Expand All @@ -200,7 +229,7 @@ function AssessmentOverview() {
)}
</MainLayout>
</>
);
);}
}

export default withUserAuth(AssessmentOverview);
28 changes: 19 additions & 9 deletions pages/assessments/take-test/questions/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,10 @@ const Questions: React.FC = () => {
function sortQuestionsByQuestionNo(input: QuestionArrays | undefined): Question[] {
if (!input) return [];
// Concatenate the 'answered_questions' and 'unanswered_questions' arrays
const allQuestions = input.answered_questions.concat(input.unanswered_questions);
const allQuestions = input.answered_questions?.concat(input.unanswered_questions);

// Sort the combined array based on 'question_no'
return allQuestions.sort((a, b) => a.question_no - b.question_no);
return allQuestions?.sort((a, b) => a.question_no - b.question_no);
}
const handleUserAnswerClick = async (question_id: number, user_answer_id: number, answer_text: string) => {
const token = tokenRef.current;
Expand All @@ -123,8 +123,16 @@ const Questions: React.FC = () => {
useEffect(() => {
if (!sessionLoading && !sessionIsErrorr && session?.length !== 0 && !sessionError) {
const assessmentData = sortQuestionsByQuestionNo(session);
setStoredAssessment(assessmentData);
setIsLoading(false);
if (
session.data?.questions?.length === 0 ||
session?.data?.length <= 1 ||
session?.data?.questions === undefined
) {
setStoredAssessment(newQuestions?.data?.questions);
} else {
setStoredAssessment(assessmentData);
}
setIsLoading(sessionLoading);
setIsError(false);
} else if (!newIsLoading && !newIsError && newQuestions?.data?.questions?.length !== 0 && !newError) {
setStoredAssessment(newQuestions?.data?.questions);
Expand All @@ -133,11 +141,12 @@ const Questions: React.FC = () => {
} else {
setIsError(true);
}
setAssessmentData(assessment);
setAssessmentData(assessment?.data);
setDuration(assessmentData?.duration_minutes as number);
console.log(newIsLoading, newIsError, newQuestions?.data?.questions, newError);
console.log(sessionLoading, sessionIsErrorr, session, sessionError);
console.log(assessmentData);
console.log('stored', storedAssessment);
}, [
newQuestions?.data,
newIsLoading,
Expand All @@ -150,13 +159,14 @@ const Questions: React.FC = () => {
newError,
assessmentData?.duration_minutes,
assessmentData,
storedAssessment,
]);
useEffect(() => {
const setTimeFunction = () => {
if (typeof window !== 'undefined' && window.localStorage) {
const minuteString = localStorage.getItem('minute');
const secondString = localStorage.getItem('second');
const minuteInt = minuteString !== null ? parseInt(minuteString, 10) : 30;
const minuteInt = minuteString !== null ? parseInt(minuteString, 10) : duration as number;
const secondInt = secondString !== null ? parseInt(secondString, 10) : 0;
setMinute(minuteInt);
setSecond(secondInt);
Expand Down Expand Up @@ -200,7 +210,7 @@ const Questions: React.FC = () => {
getItemWithExpiry('duration');
}, [duration, minute, second]);

if (isError) {
if (newIsError) {
return (
<>
<Head>
Expand Down Expand Up @@ -274,7 +284,7 @@ const Questions: React.FC = () => {
<meta name="description" content={metaDescription} />
</Head>
<MainLayout activePage={'questions'} showTopbar showFooter showDashboardSidebar={false}>
{isLoading ? (
{newIsLoading ? (
<div className="flex justify-center items-center h-screen">
<Loader />
</div>
Expand All @@ -300,7 +310,7 @@ const Questions: React.FC = () => {
</div>
<form action="#">
<ul className="overscroll md:max-w-xl max-w-xs flex flex-col w-full gap-y-4 overflow-y-scroll max-h-screen h-full mb-4">
{storedAssessment.map((question: any, index: number) => (
{storedAssessment?.map((question: any, index: number) => (
<li key={index} className="w-full md:max-w-lg py-8 px-4 border border-slate-100 rounded-lg">
<h1 className="text-xl text-brand-green-primary text-center font-bold mb-4">
Question {storedAssessment.indexOf(question) + 1} of {storedAssessment?.length}
Expand Down

0 comments on commit dec595c

Please sign in to comment.