-
Notifications
You must be signed in to change notification settings - Fork 12k
fix: refactor AverageEventDurationChart to use InsightsBookingService #22702
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
sean-brydon
merged 7 commits into
main
from
eunjae/cal-6142-replace-existing-charts-to-use-insightsbookingservice
Jul 25, 2025
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
593db06
fix: refactor AverageEventDurationChart to use InsightsBookingService
eunjae-lee 87728c2
update implementations
eunjae-lee 39073f9
put status back to the booking hourly query
eunjae-lee ab9da4e
clean up
eunjae-lee 63dfc18
improve types
eunjae-lee 67cfda4
Merge branch 'main' into eunjae/cal-6142-replace-existing-charts-to-u…
eunjae-lee a5ebd3f
address feedback
eunjae-lee 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
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
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 |
|---|---|---|
|
|
@@ -7,6 +7,53 @@ import { MembershipRole } from "@calcom/prisma/enums"; | |
| import { MembershipRepository } from "../repository/membership"; | ||
| import { TeamRepository } from "../repository/team"; | ||
|
|
||
| // Type definition for BookingTimeStatusDenormalized view | ||
| export type BookingTimeStatusDenormalized = z.infer<typeof bookingDataSchema>; | ||
|
|
||
| // Helper type for select parameter | ||
| export type BookingSelect = { | ||
| [K in keyof BookingTimeStatusDenormalized]?: boolean; | ||
| }; | ||
|
|
||
| // Helper type for selected fields | ||
| export type SelectedFields<T> = T extends undefined | ||
| ? BookingTimeStatusDenormalized | ||
| : { | ||
| [K in keyof T as T[K] extends true ? K : never]: K extends keyof BookingTimeStatusDenormalized | ||
| ? BookingTimeStatusDenormalized[K] | ||
| : never; | ||
| }; | ||
|
|
||
| export const bookingDataSchema = z | ||
| .object({ | ||
| id: z.number(), | ||
| uid: z.string(), | ||
| eventTypeId: z.number().nullable(), | ||
| title: z.string(), | ||
| description: z.string().nullable(), | ||
| startTime: z.date(), | ||
| endTime: z.date(), | ||
| createdAt: z.date(), | ||
| updatedAt: z.date().nullable(), | ||
| location: z.string().nullable(), | ||
| paid: z.boolean(), | ||
| status: z.string(), // BookingStatus enum | ||
| rescheduled: z.boolean().nullable(), | ||
| userId: z.number().nullable(), | ||
| teamId: z.number().nullable(), | ||
| eventLength: z.number().nullable(), | ||
| eventParentId: z.number().nullable(), | ||
| userEmail: z.string().nullable(), | ||
| userName: z.string().nullable(), | ||
| userUsername: z.string().nullable(), | ||
| ratingFeedback: z.string().nullable(), | ||
| rating: z.number().nullable(), | ||
| noShowHost: z.boolean().nullable(), | ||
| isTeamBooking: z.boolean(), | ||
| timeStatus: z.string().nullable(), | ||
| }) | ||
| .strict(); | ||
|
|
||
| export const insightsBookingServiceOptionsSchema = z.discriminatedUnion("scope", [ | ||
| z.object({ | ||
| scope: z.literal("user"), | ||
|
|
@@ -35,17 +82,28 @@ export type InsightsBookingServicePublicOptions = { | |
|
|
||
| export type InsightsBookingServiceOptions = z.infer<typeof insightsBookingServiceOptionsSchema>; | ||
|
|
||
| export type InsightsBookingServiceFilterOptions = { | ||
| eventTypeId?: number; | ||
| memberUserId?: number; | ||
| }; | ||
| export type InsightsBookingServiceFilterOptions = z.infer<typeof insightsBookingServiceFilterOptionsSchema>; | ||
|
|
||
| export const insightsBookingServiceFilterOptionsSchema = z.object({ | ||
| eventTypeId: z.number().optional(), | ||
| memberUserId: z.number().optional(), | ||
| dateRange: z | ||
| .object({ | ||
| target: z.enum(["createdAt", "startTime"]), | ||
| startDate: z.string(), | ||
| endDate: z.string(), | ||
| }) | ||
| .optional(), | ||
| }); | ||
|
|
||
| const NOTHING_CONDITION = Prisma.sql`1=0`; | ||
|
|
||
| const bookingDataKeys = new Set(Object.keys(bookingDataSchema.shape)); | ||
|
|
||
| export class InsightsBookingService { | ||
| private prisma: typeof readonlyPrisma; | ||
| private options: InsightsBookingServiceOptions | null; | ||
| private filters?: InsightsBookingServiceFilterOptions; | ||
| private filters: InsightsBookingServiceFilterOptions | null; | ||
| private cachedAuthConditions?: Prisma.Sql; | ||
| private cachedFilterConditions?: Prisma.Sql | null; | ||
|
|
||
|
|
@@ -59,26 +117,14 @@ export class InsightsBookingService { | |
| filters?: InsightsBookingServiceFilterOptions; | ||
| }) { | ||
| this.prisma = prisma; | ||
| const validation = insightsBookingServiceOptionsSchema.safeParse(options); | ||
| this.options = validation.success ? validation.data : null; | ||
| const optionsValidated = insightsBookingServiceOptionsSchema.safeParse(options); | ||
| this.options = optionsValidated.success ? optionsValidated.data : null; | ||
|
|
||
| this.filters = filters; | ||
| const filtersValidated = insightsBookingServiceFilterOptionsSchema.safeParse(filters); | ||
| this.filters = filtersValidated.success ? filtersValidated.data : null; | ||
eunjae-lee marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| async getBookingsByHourStats({ | ||
| startDate, | ||
| endDate, | ||
| timeZone, | ||
| }: { | ||
| startDate: string; | ||
| endDate: string; | ||
| timeZone: string; | ||
| }) { | ||
| // Validate date formats | ||
| if (isNaN(Date.parse(startDate)) || isNaN(Date.parse(endDate))) { | ||
| throw new Error(`Invalid date format: ${startDate} - ${endDate}`); | ||
| } | ||
|
|
||
| async getBookingsByHourStats({ timeZone }: { timeZone: string }) { | ||
| const baseConditions = await this.getBaseConditions(); | ||
|
|
||
| const results = await this.prisma.$queryRaw< | ||
|
|
@@ -92,8 +138,6 @@ export class InsightsBookingService { | |
| COUNT(*)::int as "count" | ||
| FROM "BookingTimeStatusDenormalized" | ||
| WHERE ${baseConditions} | ||
| AND "startTime" >= ${startDate}::timestamp | ||
| AND "startTime" <= ${endDate}::timestamp | ||
| AND "status" = 'accepted' | ||
|
Comment on lines
139
to
141
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this |
||
| GROUP BY 1 | ||
| ORDER BY 1 | ||
|
|
@@ -109,6 +153,35 @@ export class InsightsBookingService { | |
| })); | ||
| } | ||
|
|
||
| async findAll<TSelect extends BookingSelect | undefined = undefined>({ | ||
| select, | ||
| }: { | ||
| select?: TSelect; | ||
| } = {}): Promise<Array<SelectedFields<TSelect>>> { | ||
| const baseConditions = await this.getBaseConditions(); | ||
|
|
||
| // Build the select clause with validated fields | ||
| let selectFields = Prisma.sql`*`; | ||
| if (select) { | ||
| const keys = Object.keys(select); | ||
| if (keys.some((key) => !bookingDataKeys.has(key))) { | ||
| throw new Error("Invalid select keys provided"); | ||
| } | ||
|
|
||
| if (keys.length > 0) { | ||
| // Use Prisma.sql for each field to ensure proper escaping | ||
| const sqlFields = keys.map((field) => Prisma.sql`"${Prisma.raw(field)}"`); | ||
| selectFields = Prisma.join(sqlFields, ", "); | ||
| } | ||
| } | ||
|
|
||
| return await this.prisma.$queryRaw<Array<SelectedFields<TSelect>>>` | ||
| SELECT ${selectFields} | ||
| FROM "BookingTimeStatusDenormalized" | ||
| WHERE ${baseConditions} | ||
| `; | ||
| } | ||
|
|
||
| async getBaseConditions(): Promise<Prisma.Sql> { | ||
| const authConditions = await this.getAuthorizationConditions(); | ||
| const filterConditions = await this.getFilterConditions(); | ||
|
|
@@ -155,6 +228,23 @@ export class InsightsBookingService { | |
| conditions.push(Prisma.sql`"userId" = ${this.filters.memberUserId}`); | ||
| } | ||
|
|
||
| // Use dateRange object for date filtering | ||
| if (this.filters.dateRange) { | ||
| const { target, startDate, endDate } = this.filters.dateRange; | ||
| if (startDate) { | ||
| if (isNaN(Date.parse(startDate))) { | ||
| throw new Error(`Invalid date format: ${startDate}`); | ||
| } | ||
| conditions.push(Prisma.sql`"${Prisma.raw(target)}" >= ${startDate}::timestamp`); | ||
| } | ||
| if (endDate) { | ||
| if (isNaN(Date.parse(endDate))) { | ||
| throw new Error(`Invalid date format: ${endDate}`); | ||
| } | ||
| conditions.push(Prisma.sql`"${Prisma.raw(target)}" <= ${endDate}::timestamp`); | ||
| } | ||
| } | ||
|
|
||
| if (conditions.length === 0) { | ||
| return null; | ||
| } | ||
|
|
||
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.