Scheduling infrastructure for absolutely everyone.
Rename handleNewBooking to BookingCreateService (#23682)
Hariom Balhara870ad57a7e5f
diff --git a/apps/api/v2/src/lib/services/regular-booking.service.ts b/apps/api/v2/src/lib/services/regular-booking.service.tsindex f18775301b1..39ca6b2c156 100644--- a/apps/api/v2/src/lib/services/regular-booking.service.ts+++ b/apps/api/v2/src/lib/services/regular-booking.service.ts@@ -1,12 +1,7 @@-import { PrismaAttributeRepository } from "@/lib/repositories/prisma-attribute.repository";import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repository";-import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";-import { PrismaHostRepository } from "@/lib/repositories/prisma-host.repository";-import { PrismaOOORepository } from "@/lib/repositories/prisma-ooo.repository";import { PrismaUserRepository } from "@/lib/repositories/prisma-user.repository";import { CacheService } from "@/lib/services/cache.service";import { CheckBookingAndDurationLimitsService } from "@/lib/services/check-booking-and-duration-limits.service";-import { CheckBookingLimitsService } from "@/lib/services/check-booking-limits.service";import { LuckyUserService } from "@/lib/services/lucky-user.service";import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";import { Injectable } from "@nestjs/common";@@ -21,26 +16,16 @@ export class RegularBookingService extends BaseRegularBookingService {checkBookingAndDurationLimitsService: CheckBookingAndDurationLimitsService,prismaWriteService: PrismaWriteService,bookingRepository: PrismaBookingRepository,- featuresRepository: PrismaFeaturesRepository,- checkBookingLimitsService: CheckBookingLimitsService,luckyUserService: LuckyUserService,- hostRepository: PrismaHostRepository,- oooRepository: PrismaOOORepository,- userRepository: PrismaUserRepository,- attributeRepository: PrismaAttributeRepository+ userRepository: PrismaUserRepository) {super({cacheService,checkBookingAndDurationLimitsService,prismaClient: prismaWriteService.prisma as unknown as PrismaClient,bookingRepository,- featuresRepository,- checkBookingLimitsService,luckyUserService,- hostRepository,- oooRepository,userRepository,- attributeRepository,});}}diff --git a/apps/web/lib/types/booking.ts b/apps/web/lib/types/booking.tsdeleted file mode 100644index df61be8354f..00000000000--- a/apps/web/lib/types/booking.ts+++ /dev/null@@ -1,3 +0,0 @@-import type { RegularBookingCreateResult } from "@calcom/features/bookings/lib/dto/types";--export type BookingResponse = RegularBookingCreateResult;diff --git a/apps/web/test/utils/bookingScenario/createMockNextJsRequest.ts b/apps/web/test/utils/bookingScenario/createMockNextJsRequest.tsindex f3ac967ec21..97ddde43253 100644--- a/apps/web/test/utils/bookingScenario/createMockNextJsRequest.ts+++ b/apps/web/test/utils/bookingScenario/createMockNextJsRequest.ts@@ -1,9 +1,6 @@import { createMocks } from "node-mocks-http";-import type {- CustomNextApiRequest,- CustomNextApiResponse,-} from "@calcom/features/bookings/lib/handleNewBooking/test/fresh-booking.test";+import type { CustomNextApiRequest, CustomNextApiResponse } from "./types";export function createMockNextJsRequest(...args: Parameters<typeof createMocks>) {return createMocks<CustomNextApiRequest, CustomNextApiResponse>(...args);diff --git a/apps/web/test/utils/bookingScenario/types.d.ts b/apps/web/test/utils/bookingScenario/types.d.tsnew file mode 100644index 00000000000..ce509030d65--- /dev/null+++ b/apps/web/test/utils/bookingScenario/types.d.ts@@ -0,0 +1,6 @@+import type { Request, Response } from "express";+import type { NextApiRequest, NextApiResponse } from "next";++export type CustomNextApiRequest = NextApiRequest & Request;++export type CustomNextApiResponse = NextApiResponse & Response;diff --git a/packages/features/bookings/di/InstantBookingCreateService.module.ts b/packages/features/bookings/di/InstantBookingCreateService.module.tsindex 76c3319e33f..54d2c1042f1 100644--- a/packages/features/bookings/di/InstantBookingCreateService.module.ts+++ b/packages/features/bookings/di/InstantBookingCreateService.module.ts@@ -1,6 +1,7 @@+import { InstantBookingCreateService } from "@calcom/features/bookings/lib/service/InstantBookingCreateService";import { createModule, bindModuleToClassOnToken } from "@calcom/features/di/di";import { DI_TOKENS } from "@calcom/features/di/tokens";-import { InstantBookingCreateService } from "@calcom/features/instant-meeting/handleInstantMeeting";+import { moduleLoader as prismaModuleLoader } from "@calcom/prisma/prisma.module";export const instantBookingCreateServiceModule = createModule();const token = DI_TOKENS.INSTANT_BOOKING_CREATE_SERVICE;@@ -10,7 +11,10 @@ const loadModule = bindModuleToClassOnToken({moduleToken,token,classs: InstantBookingCreateService,- depsMap: {},+ depsMap: {+ // TODO: In a followup PR, we aim to remove prisma dependency and instead inject the repositories as dependencies.+ prismaClient: prismaModuleLoader,+ },});export type { InstantBookingCreateService };diff --git a/packages/features/bookings/di/RecurringBookingService.module.ts b/packages/features/bookings/di/RecurringBookingService.module.tsindex 8e71dacfa23..4217d73306b 100644--- a/packages/features/bookings/di/RecurringBookingService.module.ts+++ b/packages/features/bookings/di/RecurringBookingService.module.ts@@ -1,4 +1,5 @@-import { RecurringBookingService } from "@calcom/features/bookings/lib/handleNewRecurringBooking";+import { RecurringBookingService } from "@calcom/features/bookings/lib/service/RecurringBookingService";+import { createModule, bindModuleToClassOnToken } from "@calcom/features/di/di";import { DI_TOKENS } from "@calcom/features/di/tokens";diff --git a/packages/features/bookings/di/RegularBookingService.module.ts b/packages/features/bookings/di/RegularBookingService.module.tsindex 187b12a2ec4..db8b56c5e51 100644--- a/packages/features/bookings/di/RegularBookingService.module.ts+++ b/packages/features/bookings/di/RegularBookingService.module.ts@@ -1,14 +1,11 @@-import { RegularBookingService } from "@calcom/features/bookings/lib/handleNewBooking";++import { RegularBookingService } from "@calcom/features/bookings/lib/service/RegularBookingService";import { bindModuleToClassOnToken, createModule } from "@calcom/features/di/di";-import { moduleLoader as attributeRepositoryModuleLoader } from "@calcom/features/di/modules/Attribute";import { moduleLoader as bookingRepositoryModuleLoader } from "@calcom/features/di/modules/Booking";import { moduleLoader as cacheModuleLoader } from "@calcom/features/di/modules/Cache";import { moduleLoader as checkBookingAndDurationLimitsModuleLoader } from "@calcom/features/di/modules/CheckBookingAndDurationLimits";-import { moduleLoader as checkBookingLimitsModuleLoader } from "@calcom/features/di/modules/CheckBookingLimits";-import { moduleLoader as featuresRepositoryModuleLoader } from "@calcom/features/di/modules/Features";-import { moduleLoader as hostRepositoryModuleLoader } from "@calcom/features/di/modules/Host";+import { moduleLoader as luckyUserServiceModuleLoader } from "@calcom/features/di/modules/LuckyUser";-import { moduleLoader as oooRepositoryModuleLoader } from "@calcom/features/di/modules/Ooo";import { moduleLoader as userRepositoryModuleLoader } from "@calcom/features/di/modules/User";import { DI_TOKENS } from "@calcom/features/di/tokens";import { moduleLoader as prismaModuleLoader } from "@calcom/prisma/prisma.module";@@ -22,17 +19,13 @@ const loadModule = bindModuleToClassOnToken({token,classs: RegularBookingService,depsMap: {+ // TODO: In a followup PR, we aim to remove prisma dependency and instead inject the repositories as dependencies.+ prismaClient: prismaModuleLoader,cacheService: cacheModuleLoader,checkBookingAndDurationLimitsService: checkBookingAndDurationLimitsModuleLoader,- prismaClient: prismaModuleLoader,bookingRepository: bookingRepositoryModuleLoader,- featuresRepository: featuresRepositoryModuleLoader,- checkBookingLimitsService: checkBookingLimitsModuleLoader,luckyUserService: luckyUserServiceModuleLoader,- hostRepository: hostRepositoryModuleLoader,- oooRepository: oooRepositoryModuleLoader,userRepository: userRepositoryModuleLoader,- attributeRepository: attributeRepositoryModuleLoader,},});diff --git a/packages/features/bookings/lib/book-event-form/booking-to-mutation-input-mapper.tsx b/packages/features/bookings/lib/client/booking-event-form/booking-to-mutation-input-mapper.tsxsimilarity index 97%rename from packages/features/bookings/lib/book-event-form/booking-to-mutation-input-mapper.tsxrename to packages/features/bookings/lib/client/booking-event-form/booking-to-mutation-input-mapper.tsxindex caadc7c3e9d..42d3f44e9d6 100644--- a/packages/features/bookings/lib/book-event-form/booking-to-mutation-input-mapper.tsx+++ b/packages/features/bookings/lib/client/booking-event-form/booking-to-mutation-input-mapper.tsx@@ -6,8 +6,8 @@ import { getRoutedTeamMemberIdsFromSearchParams } from "@calcom/lib/bookings/getimport { parseRecurringDates } from "@calcom/lib/parse-dates";import type { RoutingFormSearchParams } from "@calcom/platform-types";-import type { BookerEvent, BookingCreateBody, RecurringBookingCreateBody } from "../../types";-import type { Tracking } from "../handleNewBooking/types";+import type { BookerEvent, BookingCreateBody, RecurringBookingCreateBody } from "../../../types";+import type { Tracking } from "../../handleNewBooking/types";export type BookingOptions = {values: Record<string, unknown>;diff --git a/packages/features/bookings/lib/dto/schema.ts b/packages/features/bookings/lib/dto/schema.tsnew file mode 100644index 00000000000..e31b834a509--- /dev/null+++ b/packages/features/bookings/lib/dto/schema.ts@@ -0,0 +1,10 @@+import { z } from "zod";++export const instantMeetingSubscriptionSchema = z.object({+ endpoint: z.string(),+ expirationTime: z.any().optional(),+ keys: z.object({+ auth: z.string(),+ p256dh: z.string(),+ }),+});diff --git a/packages/features/bookings/lib/dto/types.d.ts b/packages/features/bookings/lib/dto/types.d.tsindex 652cd2b47c1..3a5f3ea91be 100644--- a/packages/features/bookings/lib/dto/types.d.ts+++ b/packages/features/bookings/lib/dto/types.d.ts@@ -7,9 +7,8 @@ import type getBookingDataSchemaForApi from "@calcom/features/bookings/lib/getBoimport type { SchedulingType } from "@calcom/prisma/enums";import type { ExtendedBookingCreateBody } from "../bookingCreateBodySchema";-import type { RegularBookingService } from "../handleNewBooking";+import type { RegularBookingService } from "../service/RegularBookingService";-export type { BookingCreateBody } from "../bookingCreateBodySchema";export type BookingDataSchemaGetter = typeof getBookingDataSchema | typeof getBookingDataSchemaForApi;export type CreateRegularBookingData = ExtendedBookingCreateBody;@@ -44,14 +43,14 @@ export type BookingHandlerInput = {bookingData: CreateRegularBookingData;} & CreateBookingMeta;+// TODO: In a followup PR, we working on defining the type here itself instead of inferring it.+export type RegularBookingCreateResult = Awaited<ReturnType<RegularBookingService["createBooking"]>>;+export type InstantBookingCreateResult = {- message: string;+ message: "Success";meetingTokenId: number;bookingId: number;bookingUid: string;expires: Date;userId: number | null;};--// TODO: In a followup PR, we working on defining the type here itself instead of inferring it.-export type RegularBookingCreateResult = Awaited<ReturnType<RegularBookingService["createBooking"]>>;diff --git a/packages/features/bookings/lib/handleNewBooking/test/buildDryRunBooking.test.ts b/packages/features/bookings/lib/handleNewBooking/test/buildDryRunBooking.test.tsindex 51a271c5044..96a0b046bef 100644--- a/packages/features/bookings/lib/handleNewBooking/test/buildDryRunBooking.test.ts+++ b/packages/features/bookings/lib/handleNewBooking/test/buildDryRunBooking.test.ts@@ -2,7 +2,7 @@ import { describe, it, expect, vi } from "vitest";import { BookingStatus, CreationSource } from "@calcom/prisma/enums";-import { buildDryRunBooking } from "../../handleNewBooking";+import { buildDryRunBooking } from "../../service/RegularBookingService";vi.mock("@calcom/prisma", () => ({default: {}, // empty object as default exportdiff --git a/packages/features/bookings/lib/handleNewBooking/test/buildEventForTeamEventType.test.ts b/packages/features/bookings/lib/handleNewBooking/test/buildEventForTeamEventType.test.tsindex 77ef9de0b57..de7175f2248 100644--- a/packages/features/bookings/lib/handleNewBooking/test/buildEventForTeamEventType.test.ts+++ b/packages/features/bookings/lib/handleNewBooking/test/buildEventForTeamEventType.test.ts@@ -3,7 +3,7 @@ import { vi, describe, it, expect, beforeEach } from "vitest";import { SchedulingType } from "@calcom/prisma/enums";-import { buildEventForTeamEventType } from "../../handleNewBooking";+import { buildEventForTeamEventType } from "../../service/RegularBookingService";vi.mock("@calcom/lib/server/i18n", () => ({getTranslation: vi.fn().mockResolvedValue("translated"),@@ -22,12 +22,12 @@ const withDestinationCalendarSpy = vi.fn().mockReturnThis();vi.mock("@calcom/features/CalendarEventBuilder", () => {return {CalendarEventBuilder: {- fromEvent: vi.fn().mockImplementation((evt) => ({+ fromEvent: vi.fn().mockImplementation((_evt) => ({withDestinationCalendar: withDestinationCalendarSpy,withTeam: withTeamSpy,build: vi.fn().mockImplementation(() => ({destinationCalendar: [],- team: {}, // <- you won’t use this result anyway+ team: {}, // <- you won't use this result anyway})),})),},@@ -72,7 +72,7 @@ describe("buildEventForTeamEventType", () => {});it("filters out the organizer", async () => {- const result = await buildEventForTeamEventType({+ await buildEventForTeamEventType({existingEvent: {},users: [baseUser({ email: "[email protected]" })],organizerUser: { email: "[email protected]" },@@ -80,7 +80,7 @@ describe("buildEventForTeamEventType", () => {});const teamArgs = withTeamSpy.mock.calls[0][0];- const memberEmails = teamArgs.members.map((m: any) => m.email);+ const memberEmails = teamArgs.members.map((m: { email: string }) => m.email);expect(memberEmails).not.toContain("[email protected]");});@@ -123,7 +123,7 @@ describe("buildEventForTeamEventType", () => {});const teamArgs = withTeamSpy.mock.calls[0][0];- const memberEmails = teamArgs.members.map((m: any) => m.email);+ const memberEmails = teamArgs.members.map((m: { email: string }) => m.email);expect(memberEmails).toContain("[email protected]");expect(memberEmails).toContain("[email protected]");@@ -142,7 +142,7 @@ describe("buildEventForTeamEventType", () => {});const teamArgs = withTeamSpy.mock.calls[0][0];- const memberEmails = teamArgs.members.map((m: any) => m.email);+ const memberEmails = teamArgs.members.map((m: { email: string }) => m.email);expect(memberEmails).toContain("[email protected]");expect(memberEmails).toContain("[email protected]");diff --git a/packages/features/bookings/lib/index.ts b/packages/features/bookings/lib/index.tsindex a6c78e87f1f..9f300ae1be0 100644--- a/packages/features/bookings/lib/index.ts+++ b/packages/features/bookings/lib/index.ts@@ -2,7 +2,7 @@ export { useTimePreferences, timePreferencesStore } from "./timePreferences";export {mapBookingToMutationInput,mapRecurringBookingToMutationInput,-} from "./book-event-form/booking-to-mutation-input-mapper";+} from "./client/booking-event-form/booking-to-mutation-input-mapper";export { createBooking } from "./create-booking";export { createRecurringBooking } from "./create-recurring-booking";export { createInstantBooking } from "./create-instant-booking";diff --git a/packages/features/instant-meeting/handleInstantMeeting.test.ts b/packages/features/bookings/lib/service/InstantBookingCreateService.test.tssimilarity index 85%rename from packages/features/instant-meeting/handleInstantMeeting.test.tsrename to packages/features/bookings/lib/service/InstantBookingCreateService.test.tsindex b51669aa2b5..34080a43a8d 100644--- a/packages/features/instant-meeting/handleInstantMeeting.test.ts+++ b/packages/features/bookings/lib/service/InstantBookingCreateService.test.ts@@ -1,4 +1,4 @@-import prismock from "../../../tests/libs/__mocks__/prisma";+import prismock from "../../../../../tests/libs/__mocks__/prisma";import {createBookingScenario,@@ -11,10 +11,10 @@ import {mockNoTranslations,} from "@calcom/web/test/utils/bookingScenario/bookingScenario";-import type { NextApiRequest } from "next";import { describe, it, expect, vi, beforeEach } from "vitest";-import { getInstantBookingCreateService } from "@calcom/features/bookings/di/InstantBookingCreateService.container";+import type { CreateInstantBookingData } from "../dto/types";+import { getInstantBookingCreateService } from "../../di/InstantBookingCreateService.container";import { BookingStatus } from "@calcom/prisma/enums";vi.mock("@calcom/features/notifications/sendNotification", () => ({@@ -85,10 +85,8 @@ describe("handleInstantMeeting", () => {},});- const mockReqBody = {+ const mockBookingData: CreateInstantBookingData = {eventTypeId: 1,- name: "Test User",- email: "[email protected]",timeZone: "UTC",language: "en",start: `${plus1DateString}T04:00:00.000Z`,@@ -99,19 +97,11 @@ describe("handleInstantMeeting", () => {attendeePhoneNumber: "+918888888888",},metadata: {},+ instant: true,};- const mockRequest = {- body: mockReqBody,- method: "POST",- headers: {},- query: {},- cookies: {},- url: "/api/instant-meeting",- } as NextApiRequest;-const result = await instantBookingCreateService.createBooking({- bookingData: mockRequest.body,+ bookingData: mockBookingData,});expect(result.message).toBe("Success");@@ -166,10 +156,8 @@ describe("handleInstantMeeting", () => {}));- const mockReqBody = {+ const mockBookingData: CreateInstantBookingData = {eventTypeId: 1,- name: "Test User",- email: "[email protected]",timeZone: "UTC",language: "en",start: `${plus1DateString}T04:00:00.000Z`,@@ -180,20 +168,12 @@ describe("handleInstantMeeting", () => {attendeePhoneNumber: "+918888888888",},metadata: {},+ instant: true,};- const mockRequest = {- body: mockReqBody,- method: "POST",- headers: {},- query: {},- cookies: {},- url: "/api/instant-meeting",- } as NextApiRequest;-await expect(instantBookingCreateService.createBooking({- bookingData: mockRequest.body,+ bookingData: mockBookingData,})).rejects.toThrow("Only Team Event Types are supported for Instant Meeting");});diff --git a/packages/features/instant-meeting/handleInstantMeeting.ts b/packages/features/bookings/lib/service/InstantBookingCreateService.tssimilarity index 91%rename from packages/features/instant-meeting/handleInstantMeeting.tsrename to packages/features/bookings/lib/service/InstantBookingCreateService.tsindex 787d38252c3..b6a5260ccd4 100644--- a/packages/features/instant-meeting/handleInstantMeeting.ts+++ b/packages/features/bookings/lib/service/InstantBookingCreateService.ts@@ -22,19 +22,24 @@ import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";import { isPrismaObjOrUndefined } from "@calcom/lib/isPrismaObj";import logger from "@calcom/lib/logger";import { getTranslation } from "@calcom/lib/server/i18n";-import prisma from "@calcom/prisma";+import type { PrismaClient } from "@calcom/prisma";import { Prisma } from "@calcom/prisma/client";import { BookingStatus, WebhookTriggerEvents } from "@calcom/prisma/enums";-import { subscriptionSchema } from "./schema";+import { instantMeetingSubscriptionSchema as subscriptionSchema } from "../dto/schema";++interface IInstantBookingCreateServiceDependencies {+ prismaClient: PrismaClient;+}const handleInstantMeetingWebhookTrigger = async (args: {eventTypeId: number;webhookData: Record<string, unknown>;teamId: number;+ prismaClient: PrismaClient;}) => {const orgId = (await getOrgIdFromMemberOrTeamId({ teamId: args.teamId })) ?? 0;-+ const { prismaClient: prisma } = args;try {const eventTrigger = WebhookTriggerEvents.INSTANT_MEETING;@@ -97,8 +102,9 @@ const triggerBrowserNotifications = async (args: {title: string;connectAndJoinUrl: string;teamId?: number | null;+ prismaClient: PrismaClient;}) => {- const { title, connectAndJoinUrl, teamId } = args;+ const { title, connectAndJoinUrl, teamId, prismaClient: prisma } = args;if (!teamId) {logger.warn("No teamId provided, skipping browser notification trigger");@@ -155,7 +161,12 @@ const triggerBrowserNotifications = async (args: {await Promise.allSettled(promises);};-async function handler(bookingData: CreateInstantBookingData) {+export async function handler(+ bookingData: CreateInstantBookingData,+ deps: IInstantBookingCreateServiceDependencies+) {+ // TODO: In a followup PR, we aim to remove prisma dependency and instead inject the repositories as dependencies.+ const { prismaClient: prisma } = deps;let eventType = await getEventTypesFromDB(bookingData.eventTypeId);const isOrgTeamEvent = !!eventType?.team && !!eventType?.team?.parentId;eventType = {@@ -314,12 +325,14 @@ async function handler(bookingData: CreateInstantBookingData) {eventTypeId: eventType.id,webhookData,teamId: eventType.team?.id,+ prismaClient: prisma,});await triggerBrowserNotifications({title: newBooking.title,connectAndJoinUrl: webhookData.connectAndJoinUrl,teamId: eventType.team?.id,+ prismaClient: prisma,});return {@@ -336,7 +349,9 @@ async function handler(bookingData: CreateInstantBookingData) {* Instant booking service that handles instant/immediate bookings*/export class InstantBookingCreateService implements IBookingCreateService {+ constructor(private readonly deps: IInstantBookingCreateServiceDependencies) {}+async createBooking(input: { bookingData: CreateInstantBookingData }): Promise<InstantBookingCreateResult> {- return handler(input.bookingData);+ return handler(input.bookingData, this.deps);}}diff --git a/packages/features/bookings/lib/handleNewBooking/test/handleNewRecurringBooking.test.ts b/packages/features/bookings/lib/service/RecurringBookingService.test.tssimilarity index 100%rename from packages/features/bookings/lib/handleNewBooking/test/handleNewRecurringBooking.test.tsrename to packages/features/bookings/lib/service/RecurringBookingService.test.tsdiff --git a/packages/features/bookings/lib/handleNewRecurringBooking.ts b/packages/features/bookings/lib/service/RecurringBookingService.tssimilarity index 97%rename from packages/features/bookings/lib/handleNewRecurringBooking.tsrename to packages/features/bookings/lib/service/RecurringBookingService.tsindex 47a8f143508..3a1cf759ba2 100644--- a/packages/features/bookings/lib/handleNewRecurringBooking.ts+++ b/packages/features/bookings/lib/service/RecurringBookingService.ts@@ -3,8 +3,8 @@ import type { BookingResponse } from "@calcom/features/bookings/types";import { SchedulingType } from "@calcom/prisma/enums";import type { AppsStatus } from "@calcom/types/Calendar";-import type { RegularBookingService } from "./handleNewBooking";-import type { IBookingService } from "./interfaces/IBookingService";+import type { IBookingService } from "../interfaces/IBookingService";+import type { RegularBookingService } from "./RegularBookingService";export type BookingHandlerInput = {bookingData: CreateRecurringBookingData;diff --git a/packages/features/bookings/lib/handleNewBooking.ts b/packages/features/bookings/lib/service/RegularBookingService.tssimilarity index 95%rename from packages/features/bookings/lib/handleNewBooking.tsrename to packages/features/bookings/lib/service/RegularBookingService.tsindex ffec09d50f8..b2465a19999 100644--- a/packages/features/bookings/lib/handleNewBooking.ts+++ b/packages/features/bookings/lib/service/RegularBookingService.ts@@ -41,7 +41,6 @@ import AssignmentReasonRecorder from "@calcom/features/ee/round-robin/assignmentimport { WorkflowRepository } from "@calcom/features/ee/workflows/repositories/WorkflowRepository";import { getUsernameList } from "@calcom/features/eventtypes/lib/defaultEvents";import { getEventName, updateHostInEventName } from "@calcom/features/eventtypes/lib/eventNaming";-import type { FeaturesRepository } from "@calcom/features/flags/features.repository";import { getFullName } from "@calcom/features/form-builder/utils";import { handleAnalyticsEvents } from "@calcom/features/tasker/tasks/analytics/handleAnalyticsEvents";import type { UserRepository } from "@calcom/features/users/repositories/UserRepository";@@ -53,10 +52,13 @@ import {cancelNoShowTasksForBooking,scheduleTrigger,} from "@calcom/features/webhooks/lib/scheduleTrigger";+import type { EventPayloadType, EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";import { groupHostsByGroupId } from "@calcom/lib/bookings/hostGroupUtils";import { shouldIgnoreContactOwner } from "@calcom/lib/bookings/routing/utils";import { DEFAULT_GROUP_ID } from "@calcom/lib/constants";+import type { BookingRepository } from "../../repositories/BookingRepository";+import { ErrorCode } from "@calcom/lib/errorCodes";import { getErrorFromUnknown, ErrorWithCode } from "@calcom/lib/errors";import { extractBaseEmail } from "@calcom/lib/extract-base-email";@@ -67,9 +69,6 @@ import logger from "@calcom/lib/logger";import { getPiiFreeCalendarEvent, getPiiFreeEventType } from "@calcom/lib/piiFreeData";import { safeStringify } from "@calcom/lib/safeStringify";import { getTranslation } from "@calcom/lib/server/i18n";-import type { PrismaAttributeRepository as AttributeRepository } from "@calcom/lib/server/repository/PrismaAttributeRepository";-import type { HostRepository } from "@calcom/lib/server/repository/host";-import type { PrismaOOORepository as OooRepository } from "@calcom/lib/server/repository/ooo";import { HashedLinkService } from "@calcom/features/hashedLink/services/hashedLinkService";import { WorkflowService } from "@calcom/features/ee/workflows/lib/service/WorkflowService";import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";@@ -94,38 +93,36 @@ import type {import type { CredentialForCalendarService } from "@calcom/types/Credential";import type { EventResult, PartialReference } from "@calcom/types/EventManager";-import type { EventPayloadType, EventTypeInfo } from "../../webhooks/lib/sendPayload";-import type { BookingRepository } from "../repositories/BookingRepository";-import { BookingActionMap, BookingEmailSmsHandler } from "./BookingEmailSmsHandler";-import { getAllCredentialsIncludeServiceAccountKey } from "./getAllCredentialsForUsersOnEvent/getAllCredentials";-import { refreshCredentials } from "./getAllCredentialsForUsersOnEvent/refreshCredentials";-import getBookingDataSchema from "./getBookingDataSchema";-import { LuckyUserService } from "./getLuckyUser";-import { addVideoCallDataToEvent } from "./handleNewBooking/addVideoCallDataToEvent";-import { checkActiveBookingsLimitForBooker } from "./handleNewBooking/checkActiveBookingsLimitForBooker";-import { checkIfBookerEmailIsBlocked } from "./handleNewBooking/checkIfBookerEmailIsBlocked";-import type { Booking } from "./handleNewBooking/createBooking";-import { createBooking } from "./handleNewBooking/createBooking";-import { ensureAvailableUsers } from "./handleNewBooking/ensureAvailableUsers";-import { getBookingData } from "./handleNewBooking/getBookingData";-import { getCustomInputsResponses } from "./handleNewBooking/getCustomInputsResponses";-import { getEventType } from "./handleNewBooking/getEventType";-import type { getEventTypeResponse } from "./handleNewBooking/getEventTypesFromDB";-import { getLocationValuesForDb } from "./handleNewBooking/getLocationValuesForDb";-import { getRequiresConfirmationFlags } from "./handleNewBooking/getRequiresConfirmationFlags";-import { getSeatedBooking } from "./handleNewBooking/getSeatedBooking";-import { getVideoCallDetails } from "./handleNewBooking/getVideoCallDetails";-import { handleAppsStatus } from "./handleNewBooking/handleAppsStatus";-import { loadAndValidateUsers } from "./handleNewBooking/loadAndValidateUsers";-import { createLoggerWithEventDetails } from "./handleNewBooking/logger";-import type { BookingType } from "./handleNewBooking/originalRescheduledBookingUtils";-import { getOriginalRescheduledBooking } from "./handleNewBooking/originalRescheduledBookingUtils";-import { scheduleNoShowTriggers } from "./handleNewBooking/scheduleNoShowTriggers";-import type { IEventTypePaymentCredentialType, Invitee, IsFixedAwareUser } from "./handleNewBooking/types";-import { validateBookingTimeIsNotOutOfBounds } from "./handleNewBooking/validateBookingTimeIsNotOutOfBounds";-import { validateEventLength } from "./handleNewBooking/validateEventLength";-import handleSeats from "./handleSeats/handleSeats";-import type { IBookingService } from "./interfaces/IBookingService";+import { BookingActionMap, BookingEmailSmsHandler } from "../BookingEmailSmsHandler";+import { getAllCredentialsIncludeServiceAccountKey } from "../getAllCredentialsForUsersOnEvent/getAllCredentials";+import { refreshCredentials } from "../getAllCredentialsForUsersOnEvent/refreshCredentials";+import getBookingDataSchema from "../getBookingDataSchema";+import { LuckyUserService } from "../getLuckyUser";+import { addVideoCallDataToEvent } from "../handleNewBooking/addVideoCallDataToEvent";+import { checkActiveBookingsLimitForBooker } from "../handleNewBooking/checkActiveBookingsLimitForBooker";+import { checkIfBookerEmailIsBlocked } from "../handleNewBooking/checkIfBookerEmailIsBlocked";+import { createBooking } from "../handleNewBooking/createBooking";+import type { Booking } from "../handleNewBooking/createBooking";+import { ensureAvailableUsers } from "../handleNewBooking/ensureAvailableUsers";+import { getBookingData } from "../handleNewBooking/getBookingData";+import { getCustomInputsResponses } from "../handleNewBooking/getCustomInputsResponses";+import { getEventType } from "../handleNewBooking/getEventType";+import type { getEventTypeResponse } from "../handleNewBooking/getEventTypesFromDB";+import { getLocationValuesForDb } from "../handleNewBooking/getLocationValuesForDb";+import { getRequiresConfirmationFlags } from "../handleNewBooking/getRequiresConfirmationFlags";+import { getSeatedBooking } from "../handleNewBooking/getSeatedBooking";+import { getVideoCallDetails } from "../handleNewBooking/getVideoCallDetails";+import { handleAppsStatus } from "../handleNewBooking/handleAppsStatus";+import { loadAndValidateUsers } from "../handleNewBooking/loadAndValidateUsers";+import { createLoggerWithEventDetails } from "../handleNewBooking/logger";+import { getOriginalRescheduledBooking } from "../handleNewBooking/originalRescheduledBookingUtils";+import type { BookingType } from "../handleNewBooking/originalRescheduledBookingUtils";+import { scheduleNoShowTriggers } from "../handleNewBooking/scheduleNoShowTriggers";+import type { IEventTypePaymentCredentialType, Invitee, IsFixedAwareUser } from "../handleNewBooking/types";+import { validateBookingTimeIsNotOutOfBounds } from "../handleNewBooking/validateBookingTimeIsNotOutOfBounds";+import { validateEventLength } from "../handleNewBooking/validateEventLength";+import handleSeats from "../handleSeats/handleSeats";+import type { IBookingService } from "../interfaces/IBookingService";const translator = short();const log = logger.getSubLogger({ prefix: ["[api] book:user"] });@@ -418,13 +415,8 @@ export interface IBookingServiceDependencies {checkBookingAndDurationLimitsService: CheckBookingAndDurationLimitsService;prismaClient: PrismaClient;bookingRepository: BookingRepository;- featuresRepository: FeaturesRepository;- checkBookingLimitsService: CheckBookingLimitsService;luckyUserService: LuckyUserService;- hostRepository: HostRepository;- oooRepository: OooRepository;userRepository: UserRepository;- attributeRepository: AttributeRepository;}/**@@ -488,6 +480,10 @@ async function handler(} = input;const {+ /**+ * TODO: In a followup PR, we aim to remove prisma dependency and instead inject the repositories as dependencies.+ * This would require moving multiple queries to appropriate repositories.+ */prismaClient: prisma,bookingRepository,userRepository,@@ -1259,9 +1255,9 @@ async function handler(// This ensures that createMeeting isn't called for static video apps as bookingLocation becomes just a regular value for them.const { bookingLocation, conferenceCredentialId } = organizerOrFirstDynamicGroupMemberDefaultLocationUrl? {- bookingLocation: organizerOrFirstDynamicGroupMemberDefaultLocationUrl,- conferenceCredentialId: undefined,- }+ bookingLocation: organizerOrFirstDynamicGroupMemberDefaultLocationUrl,+ conferenceCredentialId: undefined,+ }: getLocationValueForDB(locationBodyString, eventType.locations);log.info("locationBodyString", locationBodyString);@@ -1307,8 +1303,8 @@ async function handler(const destinationCalendar = eventType.destinationCalendar? [eventType.destinationCalendar]: organizerUser.destinationCalendar- ? [organizerUser.destinationCalendar]- : null;+ ? [organizerUser.destinationCalendar]+ : null;let organizerEmail = organizerUser.email || "Email-less";if (eventType.useEventTypeDestinationCalendarEmail && destinationCalendar?.[0]?.primaryEmail) {@@ -1650,8 +1646,7 @@ async function handler(const changedOrganizer =!!originalRescheduledBooking &&- (eventType.schedulingType === SchedulingType.ROUND_ROBIN ||- eventType.schedulingType === SchedulingType.COLLECTIVE) &&+ (eventType.schedulingType === SchedulingType.ROUND_ROBIN || eventType.schedulingType === SchedulingType.COLLECTIVE) &&originalRescheduledBooking.userId !== evt.organizer.id;const skipDeleteEventsAndMeetings = changedOrganizer;@@ -1927,14 +1922,14 @@ async function handler(}const updateManager = !skipCalendarSyncTaskCreation? await eventManager.reschedule(- evt,- originalRescheduledBooking.uid,- undefined,- changedOrganizer,- previousHostDestinationCalendar,- isBookingRequestedReschedule,- skipDeleteEventsAndMeetings- )+ evt,+ originalRescheduledBooking.uid,+ undefined,+ changedOrganizer,+ previousHostDestinationCalendar,+ isBookingRequestedReschedule,+ skipDeleteEventsAndMeetings+ ): placeholderCreatedEvent;// This gets overridden when updating the event - to check if notes have been hidden or not. We just reset this back// to the default description when we are sending the emails.@@ -2232,8 +2227,8 @@ async function handler(const metadata = videoCallUrl? {- videoCallUrl: getVideoCallUrlFromCalEvent(evt) || videoCallUrl,- }+ videoCallUrl: getVideoCallUrlFromCalEvent(evt) || videoCallUrl,+ }: undefined;const webhookData: EventPayloadType = {@@ -2295,9 +2290,9 @@ async function handler(...eventType,metadata: eventType.metadata? {- ...eventType.metadata,- apps: eventType.metadata?.apps as Prisma.JsonValue,- }+ ...eventType.metadata,+ apps: eventType.metadata?.apps as Prisma.JsonValue,+ }: {},},paymentAppCredentials: eventTypePaymentAppCredential as IEventTypePaymentCredentialType,@@ -2611,7 +2606,7 @@ async function handler(* We are open to renaming it to something more descriptive.*/export class RegularBookingService implements IBookingService {- constructor(private readonly deps: IBookingServiceDependencies) {}+ constructor(private readonly deps: IBookingServiceDependencies) { }async createBooking(input: { bookingData: CreateRegularBookingData; bookingMeta?: CreateBookingMeta }) {return handler({ bookingData: input.bookingData, ...input.bookingMeta }, this.deps);diff --git a/packages/features/di/modules/Cache.ts b/packages/features/di/modules/Cache.tsindex 0c876b8471b..dcb213c035b 100644--- a/packages/features/di/modules/Cache.ts+++ b/packages/features/di/modules/Cache.ts@@ -1,19 +1,21 @@-import type { ICacheService } from "@calcom/features/calendar-cache/lib/getShouldServeCache";import { CacheService } from "@calcom/features/calendar-cache/lib/getShouldServeCache";--import { type Container, createModule } from "../di";+import { createModule, bindModuleToClassOnToken, type ModuleLoader } from "../di";import { DI_TOKENS } from "../tokens";-+import { moduleLoader as featuresRepositoryModuleLoader } from "./Features";export const cacheModule = createModule();const token = DI_TOKENS.CACHE_SERVICE;const moduleToken = DI_TOKENS.CACHE_SERVICE_MODULE;-cacheModule.bind(token).toClass(CacheService, {- featuresRepository: DI_TOKENS.FEATURES_REPOSITORY,-} satisfies Record<keyof ICacheService, symbol>);--export const moduleLoader = {+const loadModule = bindModuleToClassOnToken({+ module: cacheModule,+ moduleToken,token,- loadModule: (container: Container) => {- container.load(moduleToken, cacheModule);+ classs: CacheService,+ depsMap: {+ featuresRepository: featuresRepositoryModuleLoader,},+});++export const moduleLoader: ModuleLoader = {+ token,+ loadModule,};diff --git a/packages/features/di/modules/CheckBookingAndDurationLimits.ts b/packages/features/di/modules/CheckBookingAndDurationLimits.tsindex 5c4020f73fc..ced47d7df71 100644--- a/packages/features/di/modules/CheckBookingAndDurationLimits.ts+++ b/packages/features/di/modules/CheckBookingAndDurationLimits.ts@@ -1,19 +1,24 @@-import type { ICheckBookingAndDurationLimitsService } from "@calcom/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits";+import { CheckBookingAndDurationLimitsService } from "@calcom/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits";-import { type Container, createModule } from "../di";+import { createModule, bindModuleToClassOnToken, type ModuleLoader } from "../di";import { DI_TOKENS } from "../tokens";+import { moduleLoader as checkBookingLimitsModuleLoader } from "./CheckBookingLimits";export const checkBookingAndDurationLimitsModule = createModule();const token = DI_TOKENS.CHECK_BOOKING_AND_DURATION_LIMITS_SERVICE;const moduleToken = DI_TOKENS.CHECK_BOOKING_AND_DURATION_LIMITS_SERVICE_MODULE;-checkBookingAndDurationLimitsModule.bind(token).toClass(CheckBookingAndDurationLimitsService, {- checkBookingLimitsService: DI_TOKENS.CHECK_BOOKING_LIMITS_SERVICE,-} satisfies Record<keyof ICheckBookingAndDurationLimitsService, symbol>);--export const moduleLoader = {+const loadModule = bindModuleToClassOnToken({+ module: checkBookingAndDurationLimitsModule,+ moduleToken,token,- loadModule: (container: Container) => {- container.load(moduleToken, checkBookingAndDurationLimitsModule);+ classs: CheckBookingAndDurationLimitsService,+ depsMap: {+ checkBookingLimitsService: checkBookingLimitsModuleLoader,},+});++export const moduleLoader: ModuleLoader = {+ token,+ loadModule,};diff --git a/packages/features/instant-meeting/schema.ts b/packages/features/instant-meeting/schema.tsindex 0cad150e256..0e5f9bfc573 100644--- a/packages/features/instant-meeting/schema.ts+++ b/packages/features/instant-meeting/schema.ts@@ -1,10 +1,3 @@-import { z } from "zod";+import { instantMeetingSubscriptionSchema as subscriptionSchema } from "@calcom/features/bookings/lib/dto/schema";-export const subscriptionSchema = z.object({- endpoint: z.string(),- expirationTime: z.any().optional(),- keys: z.object({- auth: z.string(),- p256dh: z.string(),- }),-});+export { subscriptionSchema };diff --git a/packages/platform/libraries/bookings.ts b/packages/platform/libraries/bookings.tsindex 75b7b23163c..b46a24d51b4 100644--- a/packages/platform/libraries/bookings.ts+++ b/packages/platform/libraries/bookings.ts@@ -1,9 +1,9 @@export { LuckyUserService } from "@calcom/features/bookings/lib/getLuckyUser";export { CheckBookingLimitsService } from "@calcom/features/bookings/lib/checkBookingLimits";export { CheckBookingAndDurationLimitsService } from "@calcom/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits";-export { RegularBookingService } from "@calcom/features/bookings/lib/handleNewBooking";-export { RecurringBookingService } from "@calcom/features/bookings/lib/handleNewRecurringBooking";-export { InstantBookingCreateService } from "@calcom/features/instant-meeting/handleInstantMeeting";+export { RegularBookingService } from "@calcom/features/bookings/lib/service/RegularBookingService";+export { RecurringBookingService } from "@calcom/features/bookings/lib/service/RecurringBookingService";+export { InstantBookingCreateService } from "@calcom/features/bookings/lib/service/InstantBookingCreateService";export type {InstantBookingCreateResult,RegularBookingCreateResult,