Skip to content

Commit

Permalink
fetch quiz from dbservice
Browse files Browse the repository at this point in the history
  • Loading branch information
Bahugunajii committed Apr 1, 2024
1 parent a234cb4 commit d8c7ee4
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 23 deletions.
10 changes: 5 additions & 5 deletions api/afdb/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,12 @@ export const getSessionSchedule = async (sessionId: number, batchId?: number) =>
}
};

export const getGroup = async (groupId: number) => {
export const getGroup = async (groupId?: number, childId?: number) => {
try {
const queryParams = new URLSearchParams({
id: groupId.toString(),
type: "batch"
});
const queryParams = new URLSearchParams();
if (groupId !== undefined) queryParams.append('id', groupId.toString());
if (childId !== undefined) queryParams.append('child_id', childId.toString());
queryParams.append('type', "batch")
const urlWithParams = `${url}/group?${queryParams.toString()}`;
const response = await fetch(urlWithParams, getFetchConfig(bearerToken));

Expand Down
48 changes: 33 additions & 15 deletions app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
import { useAuth } from "@/services/AuthContext";
import TopBar from "@/components/TopBar";
import BottomNavigationBar from "@/components/BottomNavigationBar";
import { getGroupUser, getGroupSessions, getGroup, getQuizBatchData, getSessionSchedule } from "@/api/afdb/session";
import { getGroupUser, getGroupSessions, getGroup, getSessions, getSessionSchedule } from "@/api/afdb/session";
import { useState, useEffect } from "react";
import { GroupUser, GroupSession, QuizSession, SessionSchedule, MessageDisplayProps } from "./types";
import Link from "next/link";
import PrimaryButton from "@/components/Button";
import Loading from "./loading";
import { formatCurrentTime, formatSessionTime, formatQuizSessionTime, formatTime, isSessionActive } from "@/utils/dateUtils";
import { formatCurrentTime, formatSessionTime, formatQuizSessionTime, formatTime, isSessionActive, format12HrQuizSessionTime } from "@/utils/dateUtils";
import { generateQuizLinks } from "@/utils/quizUtils";
import { api } from "@/services/url";
import { MixpanelTracking } from "@/services/mixpanel";
Expand All @@ -36,22 +36,40 @@ export default function Home() {

const quizIds = group.map((quiz: any) => quiz.child_id.parent_id)

const quizGroup = await getGroup(undefined, quizIds[0]);

const quizGroupIds = quizGroup.map((quizGroup: any) => quizGroup.id);

const batchId = group.map((groupData: any) => groupData.child_id.id)
setBatchId(batchId[0])

const groupSessionData = await Promise.all(groupIds.map(async (groupId: number) => {
return await getGroupSessions(groupId);
}));

const quizData = await Promise.all(quizIds.map(async (quizId: number) => {
return await getQuizBatchData(quizId);
const quizGroupSessionData = await Promise.all(quizGroupIds.map(async (quizGroupId: number) => {
return await getGroupSessions(quizGroupId);
}));
const flattenedQuizGroupSessions = quizGroupSessionData.flat();

const sessionsData = await Promise.all(flattenedQuizGroupSessions.map(async (groupSession: GroupSession) => {
const sessionData = await getSessions(groupSession.session_id);
if (!sessionData) {
return null;
}
const isActive = sessionData.is_active;
const repeatSchedule = sessionData.repeat_schedule;

if (isActive && repeatSchedule && repeatSchedule.type === 'weekly' && repeatSchedule.params.includes(currentDay)) {
return sessionData;
}
return null;
}));
const filteredSessions = sessionsData.filter(session => session !== null);
const quizzesData = filteredSessions.filter((session: any) => session.platform === 'quiz');

const flattenedGroupSessions = groupSessionData.flat();
const flattenedQuizData = quizData.flat();
const quizzesData = await generateQuizLinks(flattenedQuizData);
setQuizzes(quizzesData);

return flattenedGroupSessions;
}));

Expand Down Expand Up @@ -110,10 +128,10 @@ export default function Home() {
);
}
}
else if (data.redirectPlatform === 'quiz') {
if (minutesUntilSessionStart <= 5 && sessionEndTime.getTime() > currentTimeObj.getTime()) {
else if (data.platform === 'quiz') {
if (minutesUntilSessionStart <= 5 && hasSessionNotEnded) {
return (
<Link href={`${portalBaseUrl}/?sessionId=${data.id}`} target="_blank">
<Link href={`${portalBaseUrl}/?sessionId=${data.session_id}`} target="_blank">
<PrimaryButton
className="bg-primary text-white text-sm rounded-lg w-16 h-8 mr-4 shadow-md shadow-slate-400">START</PrimaryButton>
</Link>
Expand All @@ -122,7 +140,7 @@ export default function Home() {
return (
<p className="text-xs italic font-normal mr-4">
Starts at <br />
{formatTime(sessionStartTimeStr)}
{format12HrQuizSessionTime(data.start_time)}
</p>
);
}
Expand Down Expand Up @@ -200,14 +218,14 @@ export default function Home() {
<h1 className="text-primary ml-4 font-semibold text-xl">Tests</h1>
{quizzes.length > 0 ? (
<div className="grid grid-cols-1 gap-4 pb-40">
{quizzes.map((data, index) => (isSessionActive(formatSessionTime(data.end_time)) &&
{quizzes.map((data, index) => (isSessionActive(formatQuizSessionTime(data.end_time)) &&
<div key={index} className="flex mt-4 items-center" >
<div>
<p className={`${commonTextClass}`}>
{formatQuizSessionTime(data.start_time)}
{format12HrQuizSessionTime(data.start_time)}
</p>
<p className={`${commonTextClass}`}>
{formatQuizSessionTime(data.end_time)}
{format12HrQuizSessionTime(data.end_time)}
</p>
</div>
<div className="bg-white rounded-lg shadow-lg min-h-24 h-auto py-6 relative w-full flex flex-row justify-between mr-4 items-center">
Expand All @@ -224,7 +242,7 @@ export default function Home() {
</div>
</div>
))}
{quizzes.filter((data) => isSessionActive(formatSessionTime(data.end_time))).length === 0 && (
{quizzes.filter((data) => isSessionActive(formatQuizSessionTime(data.end_time))).length === 0 && (
<MessageDisplay message="No more tests are scheduled for today!" />
)}
</div>) : (
Expand Down
23 changes: 20 additions & 3 deletions utils/dateUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ export function formatSessionTime(dateTimeStr: string) {
}

date = new Date(2000, 0, 1, hours, minutes);
} else if (dateTimeStr.includes('T') && dateTimeStr.includes('Z')) {
const isoDate = new Date(dateTimeStr);
date = new Date(2000, 0, 1, isoDate.getUTCHours(), isoDate.getUTCMinutes());
} else {
const [hours, minutes, seconds] = dateTimeStr.split(':').map(Number);
date = new Date(2000, 0, 1, hours, minutes, seconds);
Expand All @@ -29,16 +32,30 @@ export function formatCurrentTime(dateTimeStr: string) {
return `${hours}:${minutes}`;
}

export function formatQuizSessionTime(dateTimeStr: string) {
const time = new Date(`01/01/2000 ${dateTimeStr}`);
return time.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
export function formatQuizSessionTime(dateTimeString: string): string {
const dateTime = new Date(dateTimeString);
const hours = dateTime.getUTCHours().toString().padStart(2, '0');
const minutes = dateTime.getUTCMinutes().toString().padStart(2, '0');
const time = hours + ':' + minutes;
return time;
}

export function formatTime(dateTimeStr: string) {
const time = new Date(`2000-01-01T${dateTimeStr}`);
return time.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
}

export function format12HrQuizSessionTime(time: string): string {
const isoDate = new Date(time);
const hours = isoDate.getUTCHours();
const minutes = isoDate.getUTCMinutes();
const period = hours >= 12 ? 'PM' : 'AM';
let formattedHours = hours % 12;
formattedHours = formattedHours ? formattedHours : 12;
const formattedMinutes = String(minutes).padStart(2, '0');
return `${formattedHours}:${formattedMinutes} ${period}`;
}

export function isSessionActive(endTime: string): boolean {
const currentTime = new Date();
const currentTimeStr = formatCurrentTime(currentTime.toISOString());
Expand Down

0 comments on commit d8c7ee4

Please sign in to comment.