Scheduling infrastructure for absolutely everyone.
feat: useApiV2AvailableSlots (#21138)
Morgan048e56806c96
diff --git a/apps/api/v2/src/modules/slots/slots-2024-04-15/controllers/slots.controller.ts b/apps/api/v2/src/modules/slots/slots-2024-04-15/controllers/slots.controller.tsindex d8d2f20e064..501503f915f 100644--- a/apps/api/v2/src/modules/slots/slots-2024-04-15/controllers/slots.controller.ts+++ b/apps/api/v2/src/modules/slots/slots-2024-04-15/controllers/slots.controller.ts@@ -157,7 +157,10 @@ export class SlotsController_2024_04_15 {@Query() query: GetAvailableSlotsInput_2024_04_15,@Req() req: ExpressRequest): Promise<ApiResponse<{ slots: TimeSlots["slots"] | RangeSlots["slots"] }>> {- const isTeamEvent = await this.slotsService.checkIfIsTeamEvent(query.eventTypeId);+ const isTeamEvent =+ query.isTeamEvent === undefined+ ? await this.slotsService.checkIfIsTeamEvent(query.eventTypeId)+ : query.isTeamEvent;const availableSlots = await getAvailableSlots({input: {...query,diff --git a/apps/api/v2/swagger/documentation.json b/apps/api/v2/swagger/documentation.jsonindex 785d34d0bd2..ad281f3b001 100644--- a/apps/api/v2/swagger/documentation.json+++ b/apps/api/v2/swagger/documentation.json@@ -18293,10 +18293,10 @@"type": {"type": "string"},- "value": {+ "option": {"type": "string"},- "valueId": {+ "optionId": {"type": "string"}},@@ -18304,8 +18304,8 @@"id","name","type",- "value",- "valueId"+ "option",+ "optionId"]},"NumberAttribute": {@@ -18320,10 +18320,10 @@"type": {"type": "string"},- "value": {+ "option": {"type": "number"},- "valueId": {+ "optionId": {"type": "string"}},@@ -18331,8 +18331,8 @@"id","name","type",- "value",- "valueId"+ "option",+ "optionId"]},"SingleSelectAttribute": {@@ -18347,10 +18347,10 @@"type": {"type": "string"},- "value": {+ "option": {"type": "string"},- "valueId": {+ "optionId": {"type": "string"}},@@ -18358,23 +18358,23 @@"id","name","type",- "value",- "valueId"+ "option",+ "optionId"]},- "MultiSelectAttributeValue": {+ "MultiSelectAttributeOption": {"type": "object","properties": {- "valueId": {+ "optionId": {"type": "string"},- "value": {+ "option": {"type": "string"}},"required": [- "valueId",- "value"+ "optionId",+ "option"]},"MultiSelectAttribute": {@@ -18389,10 +18389,10 @@"type": {"type": "string"},- "values": {+ "options": {"type": "array","items": {- "$ref": "#/components/schemas/MultiSelectAttributeValue"+ "$ref": "#/components/schemas/MultiSelectAttributeOption"}}},@@ -18400,7 +18400,7 @@"id","name","type",- "values"+ "options"]},"MembershipUserOutputDto": {diff --git a/apps/web/lib/team/[slug]/[type]/getServerSideProps.tsx b/apps/web/lib/team/[slug]/[type]/getServerSideProps.tsxindex 20b15904a21..1d075be0cc9 100644--- a/apps/web/lib/team/[slug]/[type]/getServerSideProps.tsx+++ b/apps/web/lib/team/[slug]/[type]/getServerSideProps.tsx@@ -6,6 +6,7 @@ import type { GetBookingType } from "@calcom/features/bookings/lib/get-booking";import { getBookingForReschedule } from "@calcom/features/bookings/lib/get-booking";import { getSlugOrRequestedSlug, orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";import { getOrganizationSEOSettings } from "@calcom/features/ee/organizations/lib/orgSettings";+import { FeaturesRepository } from "@calcom/features/flags/features.repository";import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";import slugify from "@calcom/lib/slugify";import prisma from "@calcom/prisma";@@ -113,8 +114,12 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>const organizationSettings = getOrganizationSEOSettings(team);const allowSEOIndexing = organizationSettings?.allowSEOIndexing ?? false;+ const featureRepo = new FeaturesRepository();+ const useApiV2 = await featureRepo.checkIfTeamHasFeature(team.id, "use-api-v2-for-team-slots");+return {props: {+ useApiV2,eventData: {eventTypeId,entity: {diff --git a/apps/web/modules/team/type-view.tsx b/apps/web/modules/team/type-view.tsxindex 6153b6a0257..2aaf43faef8 100644--- a/apps/web/modules/team/type-view.tsx+++ b/apps/web/modules/team/type-view.tsx@@ -35,6 +35,7 @@ function Type({crmOwnerRecordType,crmAppSlug,isEmbed,+ useApiV2,}: PageProps) {const searchParams = useSearchParams();@@ -42,6 +43,7 @@ function Type({<BookingPageErrorBoundary><main className={getBookerWrapperClasses({ isEmbed: !!isEmbed })}><Booker+ useApiV2={useApiV2}username={user}eventSlug={slug}bookingData={booking}diff --git a/docs/api-reference/v2/openapi.json b/docs/api-reference/v2/openapi.jsonindex 56469e69c16..16892a1f6ce 100644--- a/docs/api-reference/v2/openapi.json+++ b/docs/api-reference/v2/openapi.json@@ -16992,14 +16992,14 @@"type": {"type": "string"},- "value": {+ "option": {"type": "string"},- "valueId": {+ "optionId": {"type": "string"}},- "required": ["id", "name", "type", "value", "valueId"]+ "required": ["id", "name", "type", "option", "optionId"]},"NumberAttribute": {"type": "object",@@ -17013,14 +17013,14 @@"type": {"type": "string"},- "value": {+ "option": {"type": "number"},- "valueId": {+ "optionId": {"type": "string"}},- "required": ["id", "name", "type", "value", "valueId"]+ "required": ["id", "name", "type", "option", "optionId"]},"SingleSelectAttribute": {"type": "object",@@ -17034,26 +17034,26 @@"type": {"type": "string"},- "value": {+ "option": {"type": "string"},- "valueId": {+ "optionId": {"type": "string"}},- "required": ["id", "name", "type", "value", "valueId"]+ "required": ["id", "name", "type", "option", "optionId"]},- "MultiSelectAttributeValue": {+ "MultiSelectAttributeOption": {"type": "object","properties": {- "valueId": {+ "optionId": {"type": "string"},- "value": {+ "option": {"type": "string"}},- "required": ["valueId", "value"]+ "required": ["optionId", "option"]},"MultiSelectAttribute": {"type": "object",@@ -17067,14 +17067,14 @@"type": {"type": "string"},- "values": {+ "options": {"type": "array","items": {- "$ref": "#/components/schemas/MultiSelectAttributeValue"+ "$ref": "#/components/schemas/MultiSelectAttributeOption"}}},- "required": ["id", "name", "type", "values"]+ "required": ["id", "name", "type", "options"]},"MembershipUserOutputDto": {"type": "object",diff --git a/packages/features/bookings/Booker/types.ts b/packages/features/bookings/Booker/types.tsindex 9d2360cd072..49b335df1cb 100644--- a/packages/features/bookings/Booker/types.ts+++ b/packages/features/bookings/Booker/types.ts@@ -96,6 +96,7 @@ export interface BookerProps {areInstantMeetingParametersSet?: boolean | null;userLocale?: string | null;hasValidLicense?: boolean;+ useApiV2?: boolean;}export type WrappedBookerPropsMain = {diff --git a/packages/features/bookings/Booker/utils/event.ts b/packages/features/bookings/Booker/utils/event.tsindex 4b4508750e3..919fe3b5b53 100644--- a/packages/features/bookings/Booker/utils/event.ts+++ b/packages/features/bookings/Booker/utils/event.ts@@ -71,6 +71,7 @@ export const useScheduleForEvent = ({orgSlug,teamMemberEmail,isTeamEvent,+ useApiV2 = true,}: {prefetchNextMonth?: boolean;username?: string | null;@@ -85,6 +86,7 @@ export const useScheduleForEvent = ({teamMemberEmail?: string | null;fromRedirectOfNonOrgLink?: boolean;isTeamEvent?: boolean;+ useApiV2?: boolean;} = {}) => {const { timezone } = useBookerTime();const [usernameFromStore, eventSlugFromStore, monthFromStore, durationFromStore] = useBookerStore(@@ -95,7 +97,7 @@ export const useScheduleForEvent = ({const searchParams = useCompatSearchParams();const rescheduleUid = searchParams?.get("rescheduleUid");- const schedule = useSchedule({+ const scheduleUsingApiV2 = useSchedule({username: usernameFromStore ?? username,eventSlug: eventSlugFromStore ?? eventSlug,eventId,@@ -110,8 +112,32 @@ export const useScheduleForEvent = ({isTeamEvent,orgSlug,teamMemberEmail,+ useApiV2: useApiV2,});+ const scheduleNotUsingApiV2 = useSchedule({+ username: usernameFromStore ?? username,+ eventSlug: eventSlugFromStore ?? eventSlug,+ eventId,+ timezone,+ selectedDate,+ prefetchNextMonth,+ monthCount,+ dayCount,+ rescheduleUid,+ month: monthFromStore ?? month,+ duration: durationFromStore ?? duration,+ isTeamEvent,+ orgSlug,+ teamMemberEmail,+ useApiV2: false,+ // only run this query if the one using Api v2 fails+ // Network error does not trigger `isError` flag, so we are instead using `failureReason` here+ enabled: isTeamEvent && !!scheduleUsingApiV2?.failureReason,+ });++ const schedule = scheduleUsingApiV2?.isSuccess ? scheduleUsingApiV2 : scheduleNotUsingApiV2;+return {data: schedule?.data,isPending: schedule?.isPending,diff --git a/packages/features/embed/Embed.tsx b/packages/features/embed/Embed.tsxindex 715427837e8..f43690a9a7f 100644--- a/packages/features/embed/Embed.tsx+++ b/packages/features/embed/Embed.tsx@@ -278,6 +278,7 @@ const EmailEmbed = ({eventId: eventType?.id,isTeamEvent,duration: selectedDuration,+ useApiV2: false,});const nonEmptyScheduleDays = useNonEmptyScheduleDays(schedule?.data?.slots);diff --git a/packages/features/flags/config.ts b/packages/features/flags/config.tsindex 640bc7fb48f..0e026221c2f 100644--- a/packages/features/flags/config.ts+++ b/packages/features/flags/config.ts@@ -20,4 +20,5 @@ export type AppFlags = {"salesforce-crm-tasker": boolean;"workflow-smtp-emails": boolean;"cal-video-log-in-overlay": boolean;+ "use-api-v2-for-team-slots": boolean;};diff --git a/packages/features/flags/hooks/index.ts b/packages/features/flags/hooks/index.tsindex 6cadd3bcd33..1e98dd2e221 100644--- a/packages/features/flags/hooks/index.ts+++ b/packages/features/flags/hooks/index.ts@@ -19,6 +19,7 @@ const initialData: AppFlags = {"salesforce-crm-tasker": false,"workflow-smtp-emails": false,"cal-video-log-in-overlay": false,+ "use-api-v2-for-team-slots": false,};if (process.env.NEXT_PUBLIC_IS_E2E) {diff --git a/packages/features/schedules/lib/use-schedule/useApiV2AvailableSlots.ts b/packages/features/schedules/lib/use-schedule/useApiV2AvailableSlots.tsnew file mode 100644index 00000000000..34ec55a3a2e--- /dev/null+++ b/packages/features/schedules/lib/use-schedule/useApiV2AvailableSlots.ts@@ -0,0 +1,48 @@+import { useQuery } from "@tanstack/react-query";+import axios from "axios";++import type { AvailableSlotsType } from "@calcom/platform-libraries";+import type {+ GetAvailableSlotsInput_2024_04_15,+ ApiResponse,+ ApiSuccessResponse,+} from "@calcom/platform-types";++export const QUERY_KEY = "get-available-slots";++export const useApiV2AvailableSlots = ({+ enabled,+ ...rest+}: GetAvailableSlotsInput_2024_04_15 & { enabled: boolean }) => {+ const availableSlots = useQuery({+ queryKey: [+ QUERY_KEY,+ rest.startTime,+ rest.endTime,+ rest.eventTypeId,+ rest.eventTypeSlug,+ rest.isTeamEvent ?? false,+ rest.teamId ?? false,+ rest.usernameList,+ rest.routedTeamMemberIds,+ rest.skipContactOwner,+ rest._shouldServeCache,+ rest.teamMemberEmail,+ rest.embedConnectVersion ?? false,+ ],+ queryFn: () => {+ return axios+ .get<ApiResponse<AvailableSlotsType>>(`${process.env.NEXT_PUBLIC_API_V2_URL}/slots/available`, {+ params: rest,+ })+ .then((res) => {+ if (res.data.status === "success") {+ return (res.data as ApiSuccessResponse<AvailableSlotsType>).data;+ }+ throw new Error(res.data.error.message);+ });+ },+ enabled: enabled,+ });+ return availableSlots;+};diff --git a/packages/features/schedules/lib/use-schedule/useSchedule.ts b/packages/features/schedules/lib/use-schedule/useSchedule.tsindex e619bcb9d6d..3fc02f95f0e 100644--- a/packages/features/schedules/lib/use-schedule/useSchedule.ts+++ b/packages/features/schedules/lib/use-schedule/useSchedule.ts@@ -8,6 +8,8 @@ import { PUBLIC_QUERY_AVAILABLE_SLOTS_INTERVAL_SECONDS } from "@calcom/lib/constimport { getUsernameList } from "@calcom/lib/defaultEvents";import { trpc } from "@calcom/trpc/react";+import { useApiV2AvailableSlots } from "./useApiV2AvailableSlots";+export type UseScheduleWithCacheArgs = {username?: string | null;eventSlug?: string | null;@@ -23,6 +25,8 @@ export type UseScheduleWithCacheArgs = {isTeamEvent?: boolean;orgSlug?: string;teamMemberEmail?: string | null;+ useApiV2?: boolean;+ enabled?: boolean;};export const useSchedule = ({@@ -40,6 +44,8 @@ export const useSchedule = ({isTeamEvent,orgSlug,teamMemberEmail,+ useApiV2 = false,+ enabled: enabledProp = true,}: UseScheduleWithCacheArgs) => {const bookerState = useBookerStore((state) => state.state);@@ -111,16 +117,40 @@ export const useSchedule = ({Boolean(month) &&Boolean(timezone) &&// Should only wait for one or the other, not both.- (Boolean(eventSlug) || Boolean(eventId) || eventId === 0),+ (Boolean(eventSlug) || Boolean(eventId) || eventId === 0) &&+ enabledProp,};- let schedule;- if (isTeamEvent) {- schedule = trpc.viewer.highPerf.getTeamSchedule.useQuery(input, options);- } else {- schedule = trpc.viewer.slots.getSchedule.useQuery(input, options);+ const isCallingApiV2Slots = useApiV2 && Boolean(isTeamEvent) && options.enabled;+ const teamSchedule = useApiV2AvailableSlots({+ ...input,+ enabled: isCallingApiV2Slots,+ duration: input.duration ? Number(input.duration) : undefined,+ routedTeamMemberIds: input.routedTeamMemberIds ?? undefined,+ teamMemberEmail: input.teamMemberEmail ?? undefined,+ eventTypeId: eventId ?? undefined,+ });++ if (isCallingApiV2Slots) {+ updateEmbedBookerState({+ bookerState,+ slotsQuery: teamSchedule,+ });+ return {+ ...teamSchedule,+ /**+ * Invalidates the request and resends it regardless of any other configuration including staleTime+ */+ invalidate: () => {+ return teamSchedule.refetch();+ },+ };}+ const schedule = isTeamEvent+ ? trpc.viewer.highPerf.getTeamSchedule.useQuery(input, options)+ : trpc.viewer.slots.getSchedule.useQuery(input, options);+updateEmbedBookerState({bookerState,slotsQuery: schedule,diff --git a/packages/platform/atoms/booker/BookerWebWrapper.tsx b/packages/platform/atoms/booker/BookerWebWrapper.tsxindex 49c8fc70418..3dd99c3b15f 100644--- a/packages/platform/atoms/booker/BookerWebWrapper.tsx+++ b/packages/platform/atoms/booker/BookerWebWrapper.tsx@@ -158,6 +158,7 @@ export const BookerWebWrapper = (props: BookerWebWrapperAtomProps) => {teamMemberEmail: props.teamMemberEmail,fromRedirectOfNonOrgLink: props.entity.fromRedirectOfNonOrgLink,isTeamEvent: props.isTeamEvent ?? !!event.data?.team,+ useApiV2: props.useApiV2,});const bookings = useBookings({event,diff --git a/packages/platform/atoms/hooks/useAvailableSlots.ts b/packages/platform/atoms/hooks/useAvailableSlots.tsindex 158dac96fc8..5258257fbfb 100644--- a/packages/platform/atoms/hooks/useAvailableSlots.ts+++ b/packages/platform/atoms/hooks/useAvailableSlots.ts@@ -15,7 +15,7 @@ export const QUERY_KEY = "get-available-slots";export const useAvailableSlots = ({enabled,...rest-}: GetAvailableSlotsInput_2024_04_15 & { enabled: boolean; isTeamEvent?: boolean; teamId?: number }) => {+}: GetAvailableSlotsInput_2024_04_15 & { enabled: boolean }) => {const availableSlots = useQuery({queryKey: [QUERY_KEY,@@ -28,7 +28,7 @@ export const useAvailableSlots = ({rest.usernameList,rest.routedTeamMemberIds,rest.skipContactOwner,- rest.shouldServeCache,+ rest._shouldServeCache,rest.teamMemberEmail,],queryFn: () => {diff --git a/packages/platform/types/slots/slots-2024-04-15/inputs/index.ts b/packages/platform/types/slots/slots-2024-04-15/inputs/index.tsindex b225caf3904..cc4f9cd5646 100644--- a/packages/platform/types/slots/slots-2024-04-15/inputs/index.ts+++ b/packages/platform/types/slots/slots-2024-04-15/inputs/index.ts@@ -129,6 +129,50 @@ export class GetAvailableSlotsInput_2024_04_15 {@IsOptional()@ApiPropertyOptional()teamMemberEmail?: string;++ @IsString()+ @IsOptional()+ @ApiPropertyOptional()+ @ApiHideProperty()+ embedConnectVersion?: string;++ @IsString()+ @IsOptional()+ @ApiPropertyOptional()+ @ApiHideProperty()+ email?: string | null;++ @Transform(({ value }: { value: string }) => value && parseInt(value))+ @IsNumber()+ @IsOptional()+ @Min(1, { message: "routingFormResponseId must be a positive number" })+ @ApiPropertyOptional()+ @ApiHideProperty()+ routingFormResponseId?: number;++ @Transform(({ value }) => value && value.toLowerCase() === "true")+ @IsBoolean()+ @IsOptional()+ @ApiHideProperty()+ _shouldServeCache?: boolean;++ @Transform(({ value }) => value && value.toLowerCase() === "true")+ @IsBoolean()+ @IsOptional()+ @ApiHideProperty()+ _bypassCalendarBusyTimes?: boolean;++ @Transform(({ value }) => (value ? value.toLowerCase() === "true" : false))+ @IsBoolean()+ @IsOptional()+ @ApiHideProperty()+ isTeamEvent?: boolean;++ @Transform(({ value }: { value: string }) => value && parseInt(value))+ @IsNumber()+ @IsOptional()+ @ApiHideProperty()+ teamId?: number;}export class RemoveSelectedSlotInput_2024_04_15 {diff --git a/packages/prisma/migrations/20250512153630_add_use_api_v2_for_team_slots_feature_flag/migration.sql b/packages/prisma/migrations/20250512153630_add_use_api_v2_for_team_slots_feature_flag/migration.sqlnew file mode 100644index 00000000000..de67248fde5--- /dev/null+++ b/packages/prisma/migrations/20250512153630_add_use_api_v2_for_team_slots_feature_flag/migration.sql@@ -0,0 +1,9 @@+INSERT INTO+ "Feature" (slug, enabled, description, "type")+VALUES+ (+ 'use-api-v2-for-team-slots',+ false,+ 'Whether to use API v2 for fetching team schedule slots.',+ 'OPERATIONAL'+ ) ON CONFLICT (slug) DO NOTHING;