Repository navigation
Feat/94-tutor-list-page #135
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| import type { NextFunction, Request, Response } from "express"; | ||
| import { z } from "zod"; | ||
| import { successResponse } from "../common/utils/response.js"; | ||
| import { tutorService } from "../service/tutor.service.js"; | ||
|
|
||
| const optionalPrice = (label: string) => | ||
| z.coerce | ||
| .number({ invalid_type_error: `${label} must be a number` }) | ||
| .finite(`${label} must be finite`) | ||
| .nonnegative(`${label} must not be negative`) | ||
| .optional(); | ||
|
|
||
| const tutorListQuerySchema = z | ||
| .object({ | ||
| search: z | ||
| .string() | ||
| .trim() | ||
| .max(100, "Search term is too long") | ||
| .optional() | ||
| .transform((value) => value || undefined), | ||
| subjectId: z | ||
| .string() | ||
| .uuid("Subject ID must be a valid UUID") | ||
| .optional() | ||
| .or(z.literal("").transform(() => undefined)), | ||
| minPrice: z.preprocess( | ||
| (value) => (value === "" ? undefined : value), | ||
| optionalPrice("Minimum price") | ||
| ), | ||
| maxPrice: z.preprocess( | ||
| (value) => (value === "" ? undefined : value), | ||
| optionalPrice("Maximum price") | ||
| ), | ||
| sortBy: z | ||
| .enum(["rating", "price", "popularity"], { | ||
| message: 'Sort must be one of "rating", "price", or "popularity"', | ||
| }) | ||
| .optional(), | ||
| order: z.enum(["asc", "desc"], { message: 'Order must be "asc" or "desc"' }).optional(), | ||
| }) | ||
| .refine( | ||
| ({ minPrice, maxPrice }) => | ||
| minPrice === undefined || maxPrice === undefined || minPrice <= maxPrice, | ||
| "Minimum price must not exceed maximum price" | ||
| ); | ||
|
|
||
| export const tutorController = { | ||
| async listTutors(req: Request, res: Response, next: NextFunction) { | ||
| try { | ||
| const query = tutorListQuerySchema.parse(req.query); | ||
| const tutors = await tutorService.listTutors(query); | ||
| res.status(200).json(successResponse(tutors, "Tutors retrieved successfully.")); | ||
| } catch (error) { | ||
| next(error); | ||
| } | ||
| }, | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| import { AccountStatus, Prisma, Role } from "@prisma/client"; | ||
| import { prisma } from "../config/prisma.js"; | ||
|
|
||
| const tutorListSelect = { | ||
| id: true, | ||
| name: true, | ||
| profileUrl: true, | ||
| bio: true, | ||
| hourlyRate: true, | ||
| tutorSubjects: { | ||
| select: { | ||
| subject: { | ||
| select: { | ||
| id: true, | ||
| name: true, | ||
| }, | ||
| }, | ||
| }, | ||
| }, | ||
| } as const; | ||
|
|
||
| export type TutorListRow = Prisma.UserGetPayload<{ select: typeof tutorListSelect }>; | ||
|
|
||
| export type TutorListFilter = { | ||
| search?: string; | ||
| subjectId?: string; | ||
| minPrice?: number; | ||
| maxPrice?: number; | ||
| }; | ||
|
|
||
| export type TutorRatingRow = { tutorId: string; averageRating: number | null; reviewCount: number }; | ||
| export type TutorPopularityRow = { tutorId: string; studentCount: number }; | ||
|
|
||
| export const tutorRepository = { | ||
| /** Active tutors with a completed profile, narrowed by the given filters. */ | ||
| async findActive(filter: TutorListFilter): Promise<TutorListRow[]> { | ||
| const { search, subjectId, minPrice, maxPrice } = filter; | ||
|
|
||
| return prisma.user.findMany({ | ||
| where: { | ||
| role: Role.tutor, | ||
| accountStatus: AccountStatus.ACTIVE, | ||
| profileComplete: true, | ||
| ...(search && { name: { contains: search, mode: "insensitive" } }), | ||
| ...(subjectId && { tutorSubjects: { some: { subjectId } } }), | ||
| ...((minPrice !== undefined || maxPrice !== undefined) && { | ||
| hourlyRate: { | ||
| ...(minPrice !== undefined && { gte: new Prisma.Decimal(minPrice) }), | ||
| ...(maxPrice !== undefined && { lte: new Prisma.Decimal(maxPrice) }), | ||
| }, | ||
| }), | ||
| }, | ||
| select: tutorListSelect, | ||
| }); | ||
| }, | ||
|
|
||
| async findRatings(tutorIds: string[]): Promise<TutorRatingRow[]> { | ||
| if (tutorIds.length === 0) { | ||
| return []; | ||
| } | ||
|
|
||
| const rows = await prisma.review.groupBy({ | ||
| by: ["tutorId"], | ||
| where: { tutorId: { in: tutorIds } }, | ||
| _avg: { rating: true }, | ||
| _count: { _all: true }, | ||
| }); | ||
|
|
||
| return rows.map((row) => ({ | ||
| tutorId: row.tutorId, | ||
| averageRating: row._avg.rating, | ||
| reviewCount: row._count._all, | ||
| })); | ||
| }, | ||
|
|
||
| /** Number of distinct students who have had a classroom with each tutor. */ | ||
| async findPopularity(tutorIds: string[]): Promise<TutorPopularityRow[]> { | ||
| if (tutorIds.length === 0) { | ||
| return []; | ||
| } | ||
|
|
||
| // Prisma's groupBy has no COUNT(DISTINCT), so let Postgres do the counting. | ||
| const rows = await prisma.$queryRaw<{ tutorId: string; studentCount: bigint }[]>` | ||
| SELECT "tutorId", COUNT(DISTINCT "studentId") AS "studentCount" | ||
| FROM "classrooms" | ||
| WHERE "tutorId" IN (${Prisma.join(tutorIds)}) | ||
| GROUP BY "tutorId" | ||
| `; | ||
|
|
||
| return rows.map((row) => ({ tutorId: row.tutorId, studentCount: Number(row.studentCount) })); | ||
| }, | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| import { Router } from "express"; | ||
| import { tutorController } from "../controller/tutor.controller.js"; | ||
|
|
||
| export const tutorRouter = Router(); | ||
|
|
||
| /** | ||
| * @swagger | ||
| * components: | ||
| * schemas: | ||
| * TutorListItem: | ||
| * type: object | ||
| * properties: | ||
| * id: { type: string, format: uuid } | ||
| * name: { type: string, nullable: true, example: Tutor Name } | ||
| * profileUrl: { type: string, format: uri, nullable: true } | ||
| * bio: { type: string, nullable: true } | ||
| * hourlyRate: { type: number, nullable: true, example: 25 } | ||
| * subjects: | ||
| * type: array | ||
| * items: | ||
| * type: object | ||
| * properties: | ||
| * id: { type: string, format: uuid } | ||
| * name: { type: string, example: Mathematics } | ||
| * rating: | ||
| * type: number | ||
| * nullable: true | ||
| * description: Average review score out of 5, rounded to one decimal; null when the tutor has no reviews | ||
| * example: 4.8 | ||
| * reviewCount: { type: integer, example: 12 } | ||
| * studentCount: | ||
| * type: integer | ||
| * description: Number of distinct students who have learned with the tutor | ||
| * example: 30 | ||
| */ | ||
|
|
||
| /** | ||
| * @swagger | ||
| * /tutors: | ||
| * get: | ||
| * summary: List active tutors | ||
| * description: > | ||
| * Public list of tutors whose account is active and whose profile is complete. | ||
| * Search, subject, and price filters combine (AND). Tutors with no value for the | ||
| * sort key (e.g. no reviews when sorting by rating) are listed last. | ||
| * tags: [Tutors] | ||
| * parameters: | ||
| * - in: query | ||
| * name: search | ||
| * schema: { type: string, maxLength: 100 } | ||
| * description: Case-insensitive match against the tutor's name | ||
| * - in: query | ||
| * name: subjectId | ||
| * schema: { type: string, format: uuid } | ||
| * - in: query | ||
| * name: minPrice | ||
| * schema: { type: number, minimum: 0 } | ||
| * description: Minimum hourly rate (inclusive) | ||
| * - in: query | ||
| * name: maxPrice | ||
| * schema: { type: number, minimum: 0 } | ||
| * description: Maximum hourly rate (inclusive) | ||
| * - in: query | ||
| * name: sortBy | ||
| * schema: { type: string, enum: [rating, price, popularity], default: rating } | ||
| * - in: query | ||
| * name: order | ||
| * schema: { type: string, enum: [asc, desc] } | ||
| * description: Defaults to desc for rating and popularity, asc for price | ||
| * responses: | ||
| * 200: | ||
| * description: Tutors retrieved successfully | ||
| * content: | ||
| * application/json: | ||
| * schema: | ||
| * type: object | ||
| * properties: | ||
| * success: { type: boolean, example: true } | ||
| * message: { type: string, example: Tutors retrieved successfully. } | ||
| * data: | ||
| * type: array | ||
| * items: | ||
| * $ref: '#/components/schemas/TutorListItem' | ||
| * 400: { description: Invalid query parameters } | ||
| */ | ||
| tutorRouter.get("/", tutorController.listTutors); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,12 +1,14 @@ | ||
| import { Router } from "express"; | ||
| import { authRouter } from "./router/auth.router.js"; | ||
| import { subjectRouter } from "./router/subject.router.js"; | ||
| import { tutorRouter } from "./router/tutor.router.js"; | ||
| import { userRouter } from "./router/user.router.js"; | ||
| import { walletRouter } from "./router/wallet.router.js"; | ||
|
|
||
| export const apiRoutes = Router(); | ||
|
|
||
| apiRoutes.use("/auth", authRouter); | ||
| apiRoutes.use("/subjects", subjectRouter); | ||
| apiRoutes.use("/tutors", tutorRouter); | ||
| apiRoutes.use("/users", userRouter); | ||
| apiRoutes.use("/wallet", walletRouter); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| import { tutorRepository, type TutorListFilter } from "../repository/tutor.repository.js"; | ||
|
|
||
| export type TutorSortBy = "rating" | "price" | "popularity"; | ||
| export type SortOrder = "asc" | "desc"; | ||
|
|
||
| export type TutorListQuery = TutorListFilter & { | ||
| sortBy?: TutorSortBy; | ||
| order?: SortOrder; | ||
| }; | ||
|
|
||
| export type TutorListItem = { | ||
| id: string; | ||
| name: string | null; | ||
| profileUrl: string | null; | ||
| bio: string | null; | ||
| hourlyRate: number | null; | ||
| subjects: { id: string; name: string }[]; | ||
| /** Average review score out of 5, rounded to one decimal; null when unreviewed. */ | ||
| rating: number | null; | ||
| reviewCount: number; | ||
| /** Distinct students who have had a classroom with this tutor. */ | ||
| studentCount: number; | ||
| }; | ||
|
|
||
| const DEFAULT_ORDER: Record<TutorSortBy, SortOrder> = { | ||
| rating: "desc", | ||
| price: "asc", | ||
| popularity: "desc", | ||
| }; | ||
|
|
||
| /** A list item plus the unrounded average, so 4.84 still outranks 4.76 though both show "4.8". */ | ||
| type RankedTutor = { item: TutorListItem; averageRating: number | null }; | ||
|
|
||
| const SORT_VALUE: Record<TutorSortBy, (tutor: RankedTutor) => number | null> = { | ||
| rating: (tutor) => tutor.averageRating, | ||
| price: (tutor) => tutor.item.hourlyRate, | ||
| popularity: (tutor) => tutor.item.studentCount, | ||
| }; | ||
|
|
||
| function compareTutors(sortBy: TutorSortBy, order: SortOrder) { | ||
| const valueOf = SORT_VALUE[sortBy]; | ||
| const direction = order === "asc" ? 1 : -1; | ||
|
|
||
| return (a: RankedTutor, b: RankedTutor) => { | ||
| const left = valueOf(a); | ||
| const right = valueOf(b); | ||
|
|
||
| // Missing values (no reviews, no rate) always sink to the bottom. | ||
| if (left !== right) { | ||
| if (left === null) return 1; | ||
| if (right === null) return -1; | ||
| return (left - right) * direction; | ||
| } | ||
| return (a.item.name ?? "").localeCompare(b.item.name ?? ""); | ||
| }; | ||
| } | ||
|
|
||
| export const tutorService = { | ||
| async listTutors(query: TutorListQuery): Promise<TutorListItem[]> { | ||
| const { sortBy, order, ...filter } = query; | ||
|
|
||
| const tutors = await tutorRepository.findActive(filter); | ||
| const tutorIds = tutors.map((tutor) => tutor.id); | ||
| const [ratings, popularity] = await Promise.all([ | ||
| tutorRepository.findRatings(tutorIds), | ||
| tutorRepository.findPopularity(tutorIds), | ||
| ]); | ||
|
|
||
| const ratingByTutor = new Map(ratings.map((row) => [row.tutorId, row])); | ||
| const studentsByTutor = new Map(popularity.map((row) => [row.tutorId, row.studentCount])); | ||
|
|
||
| const ranked: RankedTutor[] = tutors.map((tutor) => { | ||
| const rating = ratingByTutor.get(tutor.id); | ||
| const averageRating = rating?.averageRating ?? null; | ||
| const item: TutorListItem = { | ||
| id: tutor.id, | ||
| name: tutor.name, | ||
| profileUrl: tutor.profileUrl, | ||
| bio: tutor.bio, | ||
| hourlyRate: tutor.hourlyRate === null ? null : Number(tutor.hourlyRate), | ||
| subjects: tutor.tutorSubjects.map((tutorSubject) => tutorSubject.subject), | ||
| rating: averageRating === null ? null : Math.round(averageRating * 10) / 10, | ||
| reviewCount: rating?.reviewCount ?? 0, | ||
| studentCount: studentsByTutor.get(tutor.id) ?? 0, | ||
| }; | ||
| return { item, averageRating }; | ||
| }); | ||
|
|
||
| const effectiveSort = sortBy ?? "rating"; | ||
| return ranked | ||
| .sort(compareTutors(effectiveSort, order ?? DEFAULT_ORDER[effectiveSort])) | ||
| .map(({ item }) => item); | ||
| }, | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,19 @@ | ||
| import type { Metadata } from "next"; | ||
|
|
||
| import { TutorListPanel } from "@/features/tutors/tutor-list-panel"; | ||
|
|
||
| export const metadata: Metadata = { | ||
| title: "Find tutors | Tutorist", | ||
| description: "Browse active tutors by subject, price, rating, and popularity.", | ||
| }; | ||
|
|
||
| export default function TutorsPage() { | ||
| return ( | ||
| <main className="px-4 py-10 md:px-16"> | ||
| <h1 className="font-outfit text-2xl font-bold text-ink">Find tutors</h1> | ||
| <main className="min-h-[calc(100vh-64px)] bg-[#faf9fc] px-4 py-6 sm:px-6 sm:py-10 lg:px-10"> | ||
| <div className="gap-xl mx-auto flex w-full max-w-6xl flex-col"> | ||
| <h1 className="text-heading-md text-ink-black">Find tutors</h1> | ||
| <TutorListPanel /> | ||
| </div> | ||
| </main> | ||
| ); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.