Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Fetch quiz from dbservice #44

Merged
merged 3 commits into from
Apr 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
51 changes: 34 additions & 17 deletions app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +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 { generateQuizLinks } from "@/utils/quizUtils";
import { formatCurrentTime, formatSessionTime, formatQuizSessionTime, formatTime, isSessionActive, format12HrQuizSessionTime } from "@/utils/dateUtils";
import { api } from "@/services/url";
import { MixpanelTracking } from "@/services/mixpanel";

Expand All @@ -34,7 +33,11 @@ export default function Home() {

const groupIds = group.map((type: any) => type.id);

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

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

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

const batchId = group.map((groupData: any) => groupData.child_id.id)
setBatchId(batchId[0])
Expand All @@ -43,15 +46,29 @@ export default function Home() {
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 +127,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 +139,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 +217,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 +241,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
53 changes: 0 additions & 53 deletions utils/quizUtils.tsx

This file was deleted.

Loading