|
2 | 2 | getAllCoursesAndContentHierarchy, |
3 | 3 | getAllVideos, |
4 | 4 | getVideoProgressForUser, |
| 5 | + getAllContent, |
5 | 6 | } from '@/db/course'; |
6 | 7 | import { authOptions } from '@/lib/auth'; |
7 | 8 | import { Course } from '@/store/atoms'; |
@@ -153,26 +154,42 @@ export async function getPurchases(email: string): Promise<CoursesResponse> { |
153 | 154 | session?.user?.id || '', |
154 | 155 | true, |
155 | 156 | ); |
156 | | - const allVideos = await getAllVideos(); |
| 157 | + const allContents = await getAllContent(); |
157 | 158 |
|
158 | 159 | const completedVideosLookup: { [key: string]: boolean } = |
159 | 160 | userVideoProgress?.reduce((acc: any, progress) => { |
160 | 161 | acc[progress.contentId] = true; |
161 | 162 | return acc; |
162 | 163 | }, {}); |
163 | 164 |
|
| 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 | + |
164 | 173 | const courses = _courses.map((course) => { |
165 | 174 | let totalVideos = 0; |
166 | 175 | let totalVideosWatched = 0; |
| 176 | + |
167 | 177 | 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 | + } |
174 | 188 | } |
175 | | - }); |
| 189 | + |
| 190 | + const children = childrenMap.get(currentId) || []; |
| 191 | + queue.push(...children); |
| 192 | + } |
176 | 193 | }); |
177 | 194 |
|
178 | 195 | return { |
|
0 commit comments