Skip to content

Commit 6d9619f

Browse files
committed
fix: recursively calculate nested course progress percentage
1 parent 9f3c8f4 commit 6d9619f

2 files changed

Lines changed: 26 additions & 9 deletions

File tree

src/db/course.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ export const getNextVideo = async (currentVideoId: number) => {
166166
return latestContent;
167167
};
168168

169-
async function getAllContent(): Promise<
169+
export async function getAllContent(): Promise<
170170
{
171171
id: number;
172172
type: string;

src/utiles/appx.ts

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {
22
getAllCoursesAndContentHierarchy,
33
getAllVideos,
44
getVideoProgressForUser,
5+
getAllContent,
56
} from '@/db/course';
67
import { authOptions } from '@/lib/auth';
78
import { Course } from '@/store/atoms';
@@ -153,26 +154,42 @@ export async function getPurchases(email: string): Promise<CoursesResponse> {
153154
session?.user?.id || '',
154155
true,
155156
);
156-
const allVideos = await getAllVideos();
157+
const allContents = await getAllContent();
157158

158159
const completedVideosLookup: { [key: string]: boolean } =
159160
userVideoProgress?.reduce((acc: any, progress) => {
160161
acc[progress.contentId] = true;
161162
return acc;
162163
}, {});
163164

165+
const childrenMap = new Map<number, number[]>();
166+
allContents.forEach(c => {
167+
if (c.parentId) {
168+
if (!childrenMap.has(c.parentId)) childrenMap.set(c.parentId, []);
169+
childrenMap.get(c.parentId)!.push(c.id);
170+
}
171+
});
172+
164173
const courses = _courses.map((course) => {
165174
let totalVideos = 0;
166175
let totalVideosWatched = 0;
176+
167177
course.content.forEach(({ contentId }) => {
168-
allVideos.forEach(({ parentId, id }) => {
169-
if (parentId === contentId) {
170-
totalVideos++;
171-
if (completedVideosLookup[id]) {
172-
totalVideosWatched++;
173-
}
178+
const queue: number[] = [contentId];
179+
while(queue.length > 0) {
180+
const currentId = queue.shift()!;
181+
const content = allContents.find(c => c.id === currentId);
182+
183+
if (content?.type === 'video') {
184+
totalVideos++;
185+
if (completedVideosLookup[currentId]) {
186+
totalVideosWatched++;
187+
}
174188
}
175-
});
189+
190+
const children = childrenMap.get(currentId) || [];
191+
queue.push(...children);
192+
}
176193
});
177194

178195
return {

0 commit comments

Comments
 (0)