From 2f18fec901882b9f0474ccfab5e87aa1dba1f624 Mon Sep 17 00:00:00 2001 From: Bahugunajii Date: Thu, 4 Jan 2024 16:34:40 +0530 Subject: [PATCH 1/5] show sessions for logged in user --- api/afdb/session.ts | 18 +++- app/page.tsx | 214 +++++++++++++++++---------------------- app/types.ts | 26 ++--- services/AuthContext.tsx | 3 +- 4 files changed, 123 insertions(+), 138 deletions(-) diff --git a/api/afdb/session.ts b/api/afdb/session.ts index a4ae1dc..89296c7 100644 --- a/api/afdb/session.ts +++ b/api/afdb/session.ts @@ -6,14 +6,26 @@ import getAxiosConfig from '../axiosConfig'; const url = process.env.AF_DB_SERVICE_URL; const bearerToken = process.env.AF_DB_SERVICE_BEARER_TOKEN || ''; -export const getSessionOccurrences = async () => { +export const getGroupUser = async (userDbId: number) => { try { - const response = await axios.get(`${url}/session-occurrence`, { + const response = await axios.get(`${url}/group-user?user_id=${userDbId}`, { ...getAxiosConfig(bearerToken), }); return response.data; } catch (error) { - console.error("Error in fetching Session Occurrence:", error); + console.error("Error in fetching Session Details:", error); + throw error; + } +}; + +export const getGroupSessions = async (groupTypeId: number) => { + try { + const response = await axios.get(`${url}/group-session?group_type_id=${groupTypeId}`, { + ...getAxiosConfig(bearerToken), + }); + return response.data; + } catch (error) { + console.error("Error in fetching Session Details:", error); throw error; } }; diff --git a/app/page.tsx b/app/page.tsx index 02b44b1..8fadb0a 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -3,72 +3,53 @@ import { useAuth } from "@/services/AuthContext"; import TopBar from "@/components/TopBar"; import BottomNavigationBar from "@/components/BottomNavigationBar"; -import { getSessionOccurrences, getSessions } from "@/api/afdb/session"; +import { getSessions, getGroupUser, getGroupSessions } from "@/api/afdb/session"; import { useState, useEffect } from "react"; -import { LiveClasses } from "./types"; +import { GroupSession, Session } from "./types"; import Link from "next/link"; import PrimaryButton from "@/components/Button"; import Loading from "./loading"; -import { isSameDay, formatCurrentTime, formatSessionTime } from "@/utils/dateUtils"; +import { formatCurrentTime, formatSessionTime } from "@/utils/dateUtils"; import { generateQuizLink } from "@/utils/quizUtils"; export default function Home() { - const { loggedIn, userId } = useAuth(); - const [liveClasses, setLiveClasses] = useState([]); + const { loggedIn, userId, userDbId } = useAuth(); + const [liveClasses, setLiveClasses] = useState([]); const [isLoading, setIsLoading] = useState(true); - const [quizzes, setQuizzes] = useState([]); + const [quizzes, setQuizzes] = useState([]); const commonTextClass = "text-gray-700 text-sm md:text-base mx-6 md:mx-8"; const infoMessageClass = "flex items-center justify-center text-center h-72 mx-4 pb-40"; - const fetchSessionOccurrencesAndDetails = async () => { + const fetchUserSessions = async () => { try { - const sessionOccurrenceData = await getSessionOccurrences(); - const currentDate = new Date(); - currentDate.setHours(0, 0, 0, 0); + const groupUserData = await getGroupUser(userDbId!); + const groupSessionData = await getGroupSessions(groupUserData[0].group_type_id); + const sessionIds = groupSessionData.map((groupSession: GroupSession) => groupSession.session_id); + const sessionsData = await Promise.all(sessionIds.map((sessionId: number) => getSessions(sessionId))); - const todaySessions = []; + const liveClassesData = sessionsData.filter((session: Session) => session.platform === 'meet'); + const quizzesData = sessionsData.filter((session: Session) => session.platform === 'quiz'); - for (const sessionOccurrence of sessionOccurrenceData) { - const sessionStartTime = new Date(sessionOccurrence.start_time); - const formattedSessionTime = formatSessionTime(sessionOccurrence.end_time); - const formattedCurrentTime = formatCurrentTime(new Date().toISOString()); - - if (isSameDay(sessionStartTime, currentDate) && formattedSessionTime > formattedCurrentTime) { - try { - const sessionDetail = await getSessions(sessionOccurrence.session_fk); - todaySessions.push({ - sessionOccurrence, - sessionDetail, - }); - } catch (error) { - console.error("Error fetching session details for session ID:", sessionOccurrence.session_fk, error); - } - } - } - - const liveClassesToday = todaySessions.filter(data => data.sessionDetail.platform === "meet"); - const quizzesToday = todaySessions.filter(data => data.sessionDetail.platform === "quiz"); - - setLiveClasses(liveClassesToday); - setQuizzes(quizzesToday); + setLiveClasses(liveClassesData); + setQuizzes(quizzesData); } catch (error) { - console.error("Error in fetching Live Classes:", error); + console.error("Error fetching user sessions:", error); } - } + }; - function renderButton(data: { sessionOccurrence: any, sessionDetail: any }) { + function renderButton(data: any) { const currentTime = new Date(); - const sessionTimeStr = formatSessionTime(data.sessionOccurrence.start_time); + const sessionTimeStr = formatSessionTime(data.start_time); const currentTimeStr = formatCurrentTime(currentTime.toISOString()); const sessionTime = new Date(`2000-01-01T${sessionTimeStr}`); const currentTimeObj = new Date(`2000-01-01T${currentTimeStr}`); const timeDifference = (sessionTime.getTime() - currentTimeObj.getTime()) / (1000 * 60); - if (data.sessionDetail.platform === 'meet') { + if (data.platform === 'meet') { if (timeDifference <= 5) { return ( - + JOIN @@ -81,8 +62,8 @@ export default function Home() {

); } - } else if (data.sessionDetail.platform === 'quiz') { - generateQuizLink(data.sessionDetail.platform_link, userId!) + } else if (data.platform === 'quiz') { + generateQuizLink(data.platform_link, userId!) .then((quizLink) => { return ( @@ -101,9 +82,10 @@ export default function Home() { const fetchData = async () => { setIsLoading(true); - try { - await fetchSessionOccurrencesAndDetails(); + if (userDbId !== null) { + await fetchUserSessions(); + } } catch (error) { console.log("Error:", error); } finally { @@ -115,94 +97,84 @@ export default function Home() { if (loggedIn) { fetchData(); } - }, [loggedIn]); + }, [loggedIn, userDbId]); return ( <> - {loggedIn ? ( - isLoading ? ( -
- - -
- ) : ( -
- -
-

Live Classes

- {liveClasses.length > 0 ? ( -
- {liveClasses.map((data, index) => ( -
-
-

- {formatSessionTime(data.sessionOccurrence.start_time)} -

-

- {formatSessionTime(data.sessionOccurrence.end_time)} -

-
-
-
-
- Subject: {data.sessionDetail.meta_data.subject ?? "Science"} -
- Batch: {data.sessionDetail.meta_data.batch ?? "Master Batch"} -
+ {isLoading && loggedIn ? ( +
+ + +
+ ) : ( +
+ +
+

Live Classes

+ {liveClasses.length > 0 ? ( +
+ {liveClasses.map((data, index) => ( +
+
+

+ {formatSessionTime(data.start_time)} +

+

+ {formatSessionTime(data.end_time)} +

+
+
+
+
+ Subject: {data.meta_data.subject ?? "Science"} +
+ Batch: {data.meta_data.batch ?? "Master Batch"}
- {renderButton(data)}
+ {renderButton(data)}
- ))} -
) : ( -

- There are no more live classes today. You can relax! -

- )} -
-
-

Tests

- {quizzes.length > 0 ? ( -
- {quizzes.map((data, index) => ( -
-
-

- {formatSessionTime(data.sessionOccurrence.start_time)} -

-

- {formatSessionTime(data.sessionOccurrence.end_time)} -

-
-
-
-
- Subject: {data.sessionDetail.meta_data.stream} -
- Type: {data.sessionDetail.meta_data.test_type} -
+
+ ))} +
) : ( +

+ There are no more live classes today. You can relax! +

+ )} +
+
+

Tests

+ {quizzes.length > 0 ? ( +
+ {quizzes.map((data, index) => ( +
+
+

+ {formatSessionTime(data.start_time)} +

+

+ {formatSessionTime(data.end_time)} +

+
+
+
+
+ Subject: {data.meta_data.stream} +
+ Type: {data.meta_data.test_type}
- {renderButton(data)}
+ {renderButton(data)}
- ))} -
) : ( -

- There are no more tests today. You can relax! -

- )} -
- -
) - ) : ( -
- -
-

User not logged in

+
+ ))} +
) : ( +

+ There are no more tests today. You can relax! +

+ )}
-
- )} + )} ); } diff --git a/app/types.ts b/app/types.ts index 5fdbd25..c492751 100644 --- a/app/types.ts +++ b/app/types.ts @@ -8,6 +8,7 @@ export interface AuthContextProps { loggedIn: boolean; userId?: string | null; userName?: string | null; + userDbId?: number | null; } export interface CurrentTimeProps { @@ -66,15 +67,6 @@ export interface Topic { chapter_id: number; } -export interface SessionOccurrence { - id: number; - name: string; - session_id: string; - session_fk: number; - start_time: string; - end_time: string; -} - export interface Session { id: number; name: string; @@ -86,12 +78,15 @@ export interface Session { stream: string; test_type: string; }; + start_time: string; + end_time: string; + is_active: boolean; + repeat_schedule: { + type: string; + params: Object[]; + } } -export interface LiveClasses { - sessionOccurrence: SessionOccurrence; - sessionDetail: Session; -} export interface ReportsListProps { userId: string; @@ -105,3 +100,8 @@ export interface User { first_name: string; last_name: string; } + +export interface GroupSession { + session_id?: number; + group_type_id?: number +} diff --git a/services/AuthContext.tsx b/services/AuthContext.tsx index fe30ea7..99c6bd9 100644 --- a/services/AuthContext.tsx +++ b/services/AuthContext.tsx @@ -48,9 +48,10 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { }, []); const userName = user ? `${user.first_name} ${user.last_name}` : ''; + const userDbId = user ? user.id : null; return ( - + {children} ); From 8a6e90a538b080827997d1335d67f7d2ef8aa35a Mon Sep 17 00:00:00 2001 From: Bahugunajii Date: Thu, 4 Jan 2024 17:10:21 +0530 Subject: [PATCH 2/5] show sessions happening today --- app/page.tsx | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/app/page.tsx b/app/page.tsx index 8fadb0a..99d218a 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -24,11 +24,26 @@ export default function Home() { try { const groupUserData = await getGroupUser(userDbId!); const groupSessionData = await getGroupSessions(groupUserData[0].group_type_id); - const sessionIds = groupSessionData.map((groupSession: GroupSession) => groupSession.session_id); - const sessionsData = await Promise.all(sessionIds.map((sessionId: number) => getSessions(sessionId))); - const liveClassesData = sessionsData.filter((session: Session) => session.platform === 'meet'); - const quizzesData = sessionsData.filter((session: Session) => session.platform === 'quiz'); + const currentDay = new Date().getDay(); + + const sessionsData = await Promise.all(groupSessionData.map(async (groupSession: GroupSession) => { + if (groupSession.session_id !== undefined) { + const sessionData = await getSessions(groupSession.session_id); + 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 liveClassesData = filteredSessions.filter((session: Session) => session.platform === 'meet'); + const quizzesData = filteredSessions.filter((session: Session) => session.platform === 'quiz'); setLiveClasses(liveClassesData); setQuizzes(quizzesData); From 910cfe600602a4f90f0449d22ce1186c9206a286 Mon Sep 17 00:00:00 2001 From: Bahugunajii Date: Thu, 4 Jan 2024 17:18:45 +0530 Subject: [PATCH 3/5] code optimizations --- app/page.tsx | 25 ++++++++++++++----------- app/types.ts | 9 +++++++-- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/app/page.tsx b/app/page.tsx index 99d218a..9774bce 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -5,7 +5,7 @@ import TopBar from "@/components/TopBar"; import BottomNavigationBar from "@/components/BottomNavigationBar"; import { getSessions, getGroupUser, getGroupSessions } from "@/api/afdb/session"; import { useState, useEffect } from "react"; -import { GroupSession, Session } from "./types"; +import { GroupUser, GroupSession, Session } from "./types"; import Link from "next/link"; import PrimaryButton from "@/components/Button"; import Loading from "./loading"; @@ -22,20 +22,23 @@ export default function Home() { const fetchUserSessions = async () => { try { + const currentDay = new Date().getDay(); const groupUserData = await getGroupUser(userDbId!); - const groupSessionData = await getGroupSessions(groupUserData[0].group_type_id); - const currentDay = new Date().getDay(); + const groupSessions = await Promise.all(groupUserData.map(async (userData: GroupUser) => { + const groupSessionData = await getGroupSessions(userData.group_type_id); + return groupSessionData; + })); + + const flattenedGroupSessions = groupSessions.flat(); - const sessionsData = await Promise.all(groupSessionData.map(async (groupSession: GroupSession) => { - if (groupSession.session_id !== undefined) { - const sessionData = await getSessions(groupSession.session_id); - const isActive = sessionData.is_active; - const repeatSchedule = sessionData.repeat_schedule; + const sessionsData = await Promise.all(flattenedGroupSessions.map(async (groupSession: GroupSession) => { + const sessionData = await getSessions(groupSession.session_id); + const isActive = sessionData.is_active; + const repeatSchedule = sessionData.repeat_schedule; - if (isActive && repeatSchedule && repeatSchedule.type === 'weekly' && repeatSchedule.params.includes(currentDay)) { - return sessionData; - } + if (isActive && repeatSchedule && repeatSchedule.type === 'weekly' && repeatSchedule.params.includes(currentDay)) { + return sessionData; } return null; })); diff --git a/app/types.ts b/app/types.ts index c492751..f728956 100644 --- a/app/types.ts +++ b/app/types.ts @@ -102,6 +102,11 @@ export interface User { } export interface GroupSession { - session_id?: number; - group_type_id?: number + session_id: number; + group_type_id: number +} + +export interface GroupUser { + user_id: number; + group_type_id: number } From 01555c678ee1f9a8b65860ecfd5f898e5c5d342c Mon Sep 17 00:00:00 2001 From: Bahugunajii Date: Thu, 4 Jan 2024 17:25:04 +0530 Subject: [PATCH 4/5] more code optimizations --- api/afdb/session.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/api/afdb/session.ts b/api/afdb/session.ts index 89296c7..d49c06d 100644 --- a/api/afdb/session.ts +++ b/api/afdb/session.ts @@ -8,7 +8,8 @@ const bearerToken = process.env.AF_DB_SERVICE_BEARER_TOKEN || ''; export const getGroupUser = async (userDbId: number) => { try { - const response = await axios.get(`${url}/group-user?user_id=${userDbId}`, { + const response = await axios.get(`${url}/group-user`, { + params: { user_id: userDbId }, ...getAxiosConfig(bearerToken), }); return response.data; @@ -20,7 +21,8 @@ export const getGroupUser = async (userDbId: number) => { export const getGroupSessions = async (groupTypeId: number) => { try { - const response = await axios.get(`${url}/group-session?group_type_id=${groupTypeId}`, { + const response = await axios.get(`${url}/group-session`, { + params: { group_type_id: groupTypeId }, ...getAxiosConfig(bearerToken), }); return response.data; From 85c8d172cfc6de60fab5c9fa7d0b5967ee101f59 Mon Sep 17 00:00:00 2001 From: Bahugunajii Date: Fri, 5 Jan 2024 12:13:42 +0530 Subject: [PATCH 5/5] suggested changes --- api/afdb/session.ts | 13 +++++++++++++ app/page.tsx | 15 ++++++++++++--- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/api/afdb/session.ts b/api/afdb/session.ts index d49c06d..6823bb6 100644 --- a/api/afdb/session.ts +++ b/api/afdb/session.ts @@ -43,3 +43,16 @@ export const getSessions = async (sessionId: number) => { throw error; } }; + +export const getGroupTypes = async (groupTypeId: number) => { + try { + const response = await axios.get(`${url}/group-type`, { + params: { id: groupTypeId, type: "batch" }, + ...getAxiosConfig(bearerToken), + }); + return response.data; + } catch (error) { + console.error("Error in fetching Group Types:", error); + throw error; + } +}; diff --git a/app/page.tsx b/app/page.tsx index 9774bce..164c899 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -3,7 +3,7 @@ import { useAuth } from "@/services/AuthContext"; import TopBar from "@/components/TopBar"; import BottomNavigationBar from "@/components/BottomNavigationBar"; -import { getSessions, getGroupUser, getGroupSessions } from "@/api/afdb/session"; +import { getSessions, getGroupUser, getGroupSessions, getGroupTypes } from "@/api/afdb/session"; import { useState, useEffect } from "react"; import { GroupUser, GroupSession, Session } from "./types"; import Link from "next/link"; @@ -26,8 +26,17 @@ export default function Home() { const groupUserData = await getGroupUser(userDbId!); const groupSessions = await Promise.all(groupUserData.map(async (userData: GroupUser) => { - const groupSessionData = await getGroupSessions(userData.group_type_id); - return groupSessionData; + const groupType = await getGroupTypes(userData.group_type_id); + + const groupTypeIds = groupType.map((type: any) => type.id); + + const groupSessionData = await Promise.all(groupTypeIds.map(async (groupId: number) => { + return await getGroupSessions(groupId); + })); + + const flattenedGroupSessions = groupSessionData.flat(); + + return flattenedGroupSessions; })); const flattenedGroupSessions = groupSessions.flat();