Skip to content

Commit

Permalink
Merge pull request #20 from avantifellows/feature/show-session-for-a-…
Browse files Browse the repository at this point in the history
…user

Home page: Show sessions belonging to a user
  • Loading branch information
Bahugunajii authored Jan 11, 2024
2 parents 4d21834 + 85c8d17 commit 43f2388
Show file tree
Hide file tree
Showing 4 changed files with 169 additions and 137 deletions.
33 changes: 30 additions & 3 deletions api/afdb/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,28 @@ 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`, {
params: { 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`, {
params: { group_type_id: groupTypeId },
...getAxiosConfig(bearerToken),
});
return response.data;
} catch (error) {
console.error("Error in fetching Session Details:", error);
throw error;
}
};
Expand All @@ -29,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;
}
};
239 changes: 119 additions & 120 deletions app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,72 +3,80 @@
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, getGroupTypes } from "@/api/afdb/session";
import { useState, useEffect } from "react";
import { LiveClasses } from "./types";
import { GroupUser, 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<LiveClasses[]>([]);
const { loggedIn, userId, userDbId } = useAuth();
const [liveClasses, setLiveClasses] = useState<Session[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [quizzes, setQuizzes] = useState<LiveClasses[]>([]);
const [quizzes, setQuizzes] = useState<Session[]>([]);
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 todaySessions = [];

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 currentDay = new Date().getDay();
const groupUserData = await getGroupUser(userDbId!);

const groupSessions = await Promise.all(groupUserData.map(async (userData: GroupUser) => {
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();

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;
}
}
return null;
}));

const filteredSessions = sessionsData.filter(session => session !== null);

const liveClassesToday = todaySessions.filter(data => data.sessionDetail.platform === "meet");
const quizzesToday = todaySessions.filter(data => data.sessionDetail.platform === "quiz");
const liveClassesData = filteredSessions.filter((session: Session) => session.platform === 'meet');
const quizzesData = filteredSessions.filter((session: Session) => session.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 (
<Link href={`https://${data.sessionDetail.platform_link}`} target="_blank">
<Link href={data.platform_link} target="_blank">
<PrimaryButton
className="bg-primary text-white text-sm rounded-lg w-14 h-8 mr-4 shadow-md shadow-slate-400">JOIN</PrimaryButton>
</Link>
Expand All @@ -81,8 +89,8 @@ export default function Home() {
</p>
);
}
} 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 (
<Link href={quizLink} target="_blank">
Expand All @@ -101,9 +109,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 {
Expand All @@ -115,94 +124,84 @@ export default function Home() {
if (loggedIn) {
fetchData();
}
}, [loggedIn]);
}, [loggedIn, userDbId]);

return (
<>
{loggedIn ? (
isLoading ? (
<div className="max-w-xl mx-auto">
<TopBar />
<Loading />
</div>
) : (
<main className="min-h-screen max-w-xl mx-auto md:mx-auto bg-white">
<TopBar />
<div className="bg-heading">
<h1 className="text-primary ml-4 font-semibold text-xl pt-6">Live Classes</h1>
{liveClasses.length > 0 ? (
<div className="grid grid-cols-1 gap-4 pb-16">
{liveClasses.map((data, index) => (
<div key={index} className="flex mt-4 items-center" >
<div>
<p className={`${commonTextClass}`}>
{formatSessionTime(data.sessionOccurrence.start_time)}
</p>
<p className={`${commonTextClass}`}>
{formatSessionTime(data.sessionOccurrence.end_time)}
</p>
</div>
<div className="bg-card rounded-lg shadow-lg min-h-24 h-auto py-6 relative w-full flex flex-row justify-between mr-4">
<div className={`${index % 2 === 0 ? 'bg-orange-200' : 'bg-red-200'} h-full w-2 absolute left-0 top-0 rounded-s-md`}></div>
<div className="text-sm md:text-base font-semibold mx-6 md:mx-8">
<span className="font-normal pr-4">Subject:</span> {data.sessionDetail.meta_data.subject ?? "Science"}
<div className="text-sm md:text-base font-semibold ">
<span className="font-normal pr-7">Batch:</span> {data.sessionDetail.meta_data.batch ?? "Master Batch"}
</div>
{isLoading && loggedIn ? (
<div className="max-w-xl mx-auto">
<TopBar />
<Loading />
</div>
) : (
<main className="min-h-screen max-w-xl mx-auto md:mx-auto bg-white">
<TopBar />
<div className="bg-heading">
<h1 className="text-primary ml-4 font-semibold text-xl pt-6">Live Classes</h1>
{liveClasses.length > 0 ? (
<div className="grid grid-cols-1 gap-4 pb-16">
{liveClasses.map((data, index) => (
<div key={index} className="flex mt-4 items-center" >
<div>
<p className={`${commonTextClass}`}>
{formatSessionTime(data.start_time)}
</p>
<p className={`${commonTextClass}`}>
{formatSessionTime(data.end_time)}
</p>
</div>
<div className="bg-card rounded-lg shadow-lg min-h-24 h-auto py-6 relative w-full flex flex-row justify-between mr-4">
<div className={`${index % 2 === 0 ? 'bg-orange-200' : 'bg-red-200'} h-full w-2 absolute left-0 top-0 rounded-s-md`}></div>
<div className="text-sm md:text-base font-semibold mx-6 md:mx-8">
<span className="font-normal pr-4">Subject:</span> {data.meta_data.subject ?? "Science"}
<div className="text-sm md:text-base font-semibold ">
<span className="font-normal pr-7">Batch:</span> {data.meta_data.batch ?? "Master Batch"}
</div>
{renderButton(data)}
</div>
{renderButton(data)}
</div>
))}
</div>) : (
<p className={infoMessageClass}>
There are no more live classes today. You can relax!
</p>
)}
</div>
<div className="bg-heading">
<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) => (
<div key={index} className="flex mt-4 items-center" >
<div>
<p className={`${commonTextClass}`}>
{formatSessionTime(data.sessionOccurrence.start_time)}
</p>
<p className={`${commonTextClass}`}>
{formatSessionTime(data.sessionOccurrence.end_time)}
</p>
</div>
<div className="bg-card rounded-lg shadow-lg min-h-24 h-auto py-6 relative w-full flex flex-row justify-between mr-4">
<div className={`${index % 2 === 0 ? 'bg-orange-200' : 'bg-red-200'} h-full w-2 absolute left-0 top-0 rounded-s-md`}></div>
<div className="text-sm md:text-base font-semibold mx-6 md:mx-8">
<span className="font-normal pr-4">Subject:</span> {data.sessionDetail.meta_data.stream}
<div className="text-sm md:text-base font-semibold ">
<span className="font-normal pr-9">Type:</span> {data.sessionDetail.meta_data.test_type}
</div>
</div>
))}
</div>) : (
<p className={infoMessageClass}>
There are no more live classes today. You can relax!
</p>
)}
</div>
<div className="bg-heading">
<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) => (
<div key={index} className="flex mt-4 items-center" >
<div>
<p className={`${commonTextClass}`}>
{formatSessionTime(data.start_time)}
</p>
<p className={`${commonTextClass}`}>
{formatSessionTime(data.end_time)}
</p>
</div>
<div className="bg-card rounded-lg shadow-lg min-h-24 h-auto py-6 relative w-full flex flex-row justify-between mr-4">
<div className={`${index % 2 === 0 ? 'bg-orange-200' : 'bg-red-200'} h-full w-2 absolute left-0 top-0 rounded-s-md`}></div>
<div className="text-sm md:text-base font-semibold mx-6 md:mx-8">
<span className="font-normal pr-4">Subject:</span> {data.meta_data.stream}
<div className="text-sm md:text-base font-semibold ">
<span className="font-normal pr-9">Type:</span> {data.meta_data.test_type}
</div>
{renderButton(data)}
</div>
{renderButton(data)}
</div>
))}
</div>) : (
<p className={`${infoMessageClass}`}>
There are no more tests today. You can relax!
</p>
)}
</div>
<BottomNavigationBar />
</main>)
) : (
<main className="max-w-xl mx-auto bg-white">
<TopBar />
<div className="min-h-screen flex flex-col items-center justify-between p-24">
<p>User not logged in</p>
</div>
))}
</div>) : (
<p className={`${infoMessageClass}`}>
There are no more tests today. You can relax!
</p>
)}
</div>
<BottomNavigationBar />
</main>
)}
</main>)}
</>
);
}
Loading

0 comments on commit 43f2388

Please sign in to comment.