Skip to content

Commit

Permalink
refactor: wip
Browse files Browse the repository at this point in the history
  • Loading branch information
piotr-pajak committed Dec 12, 2024
1 parent eefad3a commit 19d3c02
Show file tree
Hide file tree
Showing 9 changed files with 55 additions and 36 deletions.
31 changes: 27 additions & 4 deletions apps/api/src/courses/course.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ export class CourseService {
WHERE ${studentChapterProgress.chapterId} = ${chapters.id}
AND ${studentChapterProgress.courseId} = ${course.id}
AND ${studentChapterProgress.studentId} = ${userId}
AND ${studentChapterProgress.completedAt}
AND ${studentChapterProgress.completedAt} IS NOT NULL
)::BOOLEAN`,
lessonCount: chapters.lessonCount,
completedLessonCount: sql<number>`COALESCE(${studentChapterProgress.completedLessonCount}, 0)`,
Expand All @@ -342,13 +342,15 @@ export class CourseService {
) = (
SELECT COUNT(*)
FROM ${studentLessonProgress}
LEFT JOIN ${lessons} ON ${lessons.chapterId} = ${chapters.id}
WHERE ${studentLessonProgress.lessonId} = ${lessons.id}
AND ${studentLessonProgress.studentId} = ${userId}
)
THEN ${ChapterProgress.completed}
WHEN (
SELECT COUNT(*)
FROM ${studentLessonProgress}
LEFT JOIN ${lessons} ON ${lessons.id} = ${studentLessonProgress.lessonId}
WHERE ${studentLessonProgress.lessonId} = ${lessons.id}
AND ${studentLessonProgress.studentId} = ${userId}
) > 0
Expand Down Expand Up @@ -520,9 +522,32 @@ export class CourseService {
};
}

//TODO: Needs to be refactored
async getTeacherCourses(authorId: UUIDType): Promise<AllCoursesForTeacherResponse> {
return this.db
.select(this.getSelectField())
.select({
id: courses.id,
description: sql<string>`${courses.description}`,
title: courses.title,
thumbnailUrl: courses.thumbnailS3Key,
authorId: sql<string>`${courses.authorId}`,
author: sql<string>`CONCAT(${users.firstName} || ' ' || ${users.lastName})`,
authorEmail: sql<string>`${users.email}`,
category: sql<string>`${categories.title}`,
enrolled: sql<boolean>`CASE WHEN ${studentCourses.studentId} IS NOT NULL THEN true ELSE false END`,
enrolledParticipantCount: sql<number>`0`,
courseChapterCount: courses.chapterCount,
completedChapterCount: sql<number>`0`,
priceInCents: courses.priceInCents,
currency: courses.currency,
hasFreeChapters: sql<boolean>`
EXISTS (
SELECT 1
FROM ${chapters}
WHERE ${chapters.courseId} = ${courses.id}
AND ${chapters.isFreemium} = true
)`,
})
.from(courses)
.leftJoin(studentCourses, eq(studentCourses.courseId, courses.id))
.leftJoin(categories, eq(courses.categoryId, categories.id))
Expand All @@ -545,8 +570,6 @@ export class CourseService {
users.email,
studentCourses.studentId,
categories.title,
coursesSummaryStats.freePurchasedCount,
coursesSummaryStats.paidPurchasedCount,
)
.orderBy(
sql<boolean>`CASE WHEN ${studentCourses.studentId} IS NULL THEN TRUE ELSE FALSE END`,
Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/courses/schemas/course.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const courseSchema = Type.Object({
currency: Type.String(),
isPublished: Type.Optional(Type.Boolean()),
createdAt: Type.Optional(Type.String()),
hasFreeLessons: Type.Optional(Type.Boolean()),
hasFreeChapters: Type.Optional(Type.Boolean()),
});

export const allCoursesSchema = Type.Array(courseSchema);
Expand Down
8 changes: 4 additions & 4 deletions apps/api/src/swagger/api-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -2953,7 +2953,7 @@
"createdAt": {
"type": "string"
},
"hasFreeLessons": {
"hasFreeChapters": {
"type": "boolean"
}
},
Expand Down Expand Up @@ -3068,7 +3068,7 @@
"createdAt": {
"type": "string"
},
"hasFreeLessons": {
"hasFreeChapters": {
"type": "boolean"
}
},
Expand Down Expand Up @@ -3183,7 +3183,7 @@
"createdAt": {
"type": "string"
},
"hasFreeLessons": {
"hasFreeChapters": {
"type": "boolean"
}
},
Expand Down Expand Up @@ -3298,7 +3298,7 @@
"createdAt": {
"type": "string"
},
"hasFreeLessons": {
"hasFreeChapters": {
"type": "boolean"
}
},
Expand Down
12 changes: 6 additions & 6 deletions apps/web/app/modules/Admin/Categories/Categories.page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
import { format } from "date-fns";
import { isEmpty } from "lodash-es";
import { Trash } from "lucide-react";
import React from "react";
import { useState, useTransition } from "react";

import { useCategoriesSuspense, usersQueryOptions } from "~/api/queries";
import { queryClient } from "~/api/queryClient";
Expand Down Expand Up @@ -47,13 +47,13 @@ export const clientLoader = async () => {

const Categories = () => {
const navigate = useNavigate();
const [sorting, setSorting] = React.useState<SortingState>([]);
const [rowSelection, setRowSelection] = React.useState<RowSelectionState>({});
const [searchParams, setSearchParams] = React.useState<{
const [sorting, setSorting] = useState<SortingState>([]);
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
const [searchParams, setSearchParams] = useState<{
title?: string;
archived?: boolean;
}>({});
const [isPending, startTransition] = React.useTransition();
}>({ archived: false });
const [isPending, startTransition] = useTransition();
const { data } = useCategoriesSuspense(searchParams);

const filterConfig: FilterConfig[] = [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export default function CoursesViewPage() {
</BreadcrumbList>
<div className="flex flex-col md:flex-row h-full gap-6">
<CourseViewMainCard {...course} />
<LessonsList lessons={course.lessons} isEnrolled={course.enrolled || isAdmin} />
<LessonsList lessons={course.chapters} isEnrolled={course.enrolled || isAdmin} />
</div>
</PageWrapper>
);
Expand Down
22 changes: 11 additions & 11 deletions apps/web/app/modules/Courses/CourseView/CourseViewMainCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,16 @@ export const CourseViewMainCard = ({
authorEmail = "",
authorId,
category,
completedLessonCount = 0,
courseLessonCount,
completedChapterCount = 0,
courseChapterCount,
currency,
description,
enrolled: isEnrolled,
hasFreeLessons = false,
imageUrl,
hasFreeChapter = false,
thumbnailUrl,
priceInCents,
title,
lessons,
chapters,
}: CourseViewMainCardProps) => {
const { mutateAsync: enrollCourse } = useEnrollCourse();
const { mutateAsync: unenrollCourse } = useUnenrollCourse();
Expand All @@ -56,8 +56,8 @@ export const CourseViewMainCard = ({
}

const firstUncompletedLesson =
lessons.find((lesson) => (lesson.itemsCompletedCount ?? 0) < lesson.itemsCount)?.id ??
last(lessons)?.id;
chapters.find((lesson) => (lesson.itemsCompletedCount ?? 0) < lesson.itemsCount)?.id ??
last(chapters)?.id;

const handleEnroll = () => {
enrollCourse({ id: courseId }).then(() => {
Expand All @@ -75,15 +75,15 @@ export const CourseViewMainCard = ({
<div className="md:w-[380px] xl:w-[480px] shrink-0 flex flex-col rounded-2xl bg-white drop-shadow-primary relative">
<div className="absolute top-4 left-4 right-4 flex flex-col gap-y-1">
<CategoryChip category={category} />
{hasFreeLessons && !isEnrolled && (
{hasFreeChapter && !isEnrolled && (
<CardBadge variant="successFilled">
<Icon name="FreeRight" className="w-4" />
Free Lessons!
</CardBadge>
)}
</div>
<img
src={imageUrl || CardPlaceholder}
src={thumbnailUrl || CardPlaceholder}
alt="Course"
loading="eager"
decoding="async"
Expand All @@ -95,8 +95,8 @@ export const CourseViewMainCard = ({
<div className="flex flex-col h-full bg-white p-6 lg:p-8 pt-6 rounded-b-2xl min-h-0">
<CourseProgress
label="Course progress:"
completedLessonCount={completedLessonCount}
courseLessonCount={courseLessonCount}
completedLessonCount={completedChapterCount}
courseLessonCount={courseChapterCount}
/>
<h4 className="text-2xl font-bold mt-4 lg:mt-6 leading-10 text-neutral-950">{title}</h4>
<Link to={`/teachers/${authorId}`} className="flex items-center gap-x-1.5 mt-3 mb-4">
Expand Down
10 changes: 4 additions & 6 deletions apps/web/app/modules/Courses/CourseView/LessonsList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { LessonCard } from "~/modules/Courses/CourseView/LessonCard";
import type { GetCourseResponse } from "~/api/generated-api";

type LessonsListProps = {
lessons: GetCourseResponse["data"]["lessons"];
lessons: GetCourseResponse["data"]["chapters"];
isEnrolled: GetCourseResponse["data"]["enrolled"];
};

Expand All @@ -25,15 +25,13 @@ export const LessonsList = ({ lessons, isEnrolled }: LessonsListProps) => {

if (!type) return setFilteredLessons(lessons);

const lessonsByType = lessons.filter((lesson) => lesson.type === type);

setFilteredLessons(lessonsByType);
setFilteredLessons(lessons);
},
[lessons],
);

const lessonCards = useMemo(() => {
return filteredLessons.map((lesson, index) => (
return filteredLessons?.map((lesson, index) => (
<LessonCard
{...lesson}
key={lesson.id}
Expand All @@ -48,7 +46,7 @@ export const LessonsList = ({ lessons, isEnrolled }: LessonsListProps) => {
<div className="grow flex flex-col gap-y-4 rounded-2xl bg-white drop-shadow-primary relative p-6 lg:p-8">
<h3 className="text-xl font-semibold">
Lessons
<span className="text-primary-700"> ({lessons.length})</span>
<span className="text-primary-700"> ({lessons?.length})</span>
</h3>
<ButtonGroup
className="sr-only lg:not-sr-only"
Expand Down
2 changes: 0 additions & 2 deletions apps/web/app/modules/Statistics/Admin/AdminStatistics.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import type { ChartConfig } from "~/components/ui/chart";
export const AdminStatistics = () => {
const { data: user } = useCurrentUser();
const { data: statistics, isLoading } = useTeacherStatistics();
console.log({ statistics });
const totalCoursesCompletion =
statistics?.totalCoursesCompletionStats.totalCoursesCompletion ?? 0;
const totalCourses = statistics?.totalCoursesCompletionStats.totalCourses ?? 0;
Expand All @@ -24,7 +23,6 @@ export const AdminStatistics = () => {
const remainedOnFreemium = statistics?.conversionAfterFreemiumLesson.remainedOnFreemium ?? 0;

const correctAnswers = statistics?.avgQuizScore.correctAnswerCount ?? 0;
const wrongAnswers = statistics?.avgQuizScore.wrongAnswerCount ?? 0;
const totalAnswers = statistics?.avgQuizScore.answerCount ?? 0;

const coursesCompletionChartConfig = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export const EnrollmentChart = ({ data, isLoading = false }: EnrollmentChartProp

if (isLoading) {
return (
<div className="w-full bg-white rounded-lg gap-4 drop-shadow-card p-8 flex flex-col">
<div className="w-full bg-white rounded-lg gap-4 md:col-span-2 drop-shadow-card p-8 flex flex-col">
<hgroup className="gap-y-[5px] flex flex-col items-center py-3">
<Skeleton className="h-6 w-[240px] rounded-lg" />
<Skeleton className="w-40 h-4 rounded-lg" />
Expand Down

0 comments on commit 19d3c02

Please sign in to comment.