chore: [Booking flow refactor - 2] Integrate Booking services (#23156)
* Integrate booking services * Fix imports --------- Co-authored-by: Volnei Munhoz <[email protected]>
This commit is contained in:
1 parent
2a23911a5b
commit
3bcce02b92
42 files changed
+569
-653
No files matched your search
@@ -0,0 +1,13 @@
|
||||
import { createContainer } from "@calcom/features/di/di";
|
||||
|
||||
import {
|
||||
type InstantBookingCreateService,
|
||||
moduleLoader as instantBookingCreateServiceModule,
|
||||
} from "./InstantBookingCreateService.module";
|
||||
|
||||
const container = createContainer();
|
||||
|
||||
export function getInstantBookingCreateService(): InstantBookingCreateService {
|
||||
instantBookingCreateServiceModule.loadModule(container);
|
||||
return container.get<InstantBookingCreateService>(instantBookingCreateServiceModule.token);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { createModule, bindModuleToClassOnToken } from "@calcom/features/di/di";
|
||||
import { DI_TOKENS } from "@calcom/features/di/tokens";
|
||||
import { InstantBookingCreateService } from "@calcom/features/instant-meeting/handleInstantMeeting";
|
||||
|
||||
export const instantBookingCreateServiceModule = createModule();
|
||||
const token = DI_TOKENS.INSTANT_BOOKING_CREATE_SERVICE;
|
||||
const moduleToken = DI_TOKENS.INSTANT_BOOKING_CREATE_SERVICE_MODULE;
|
||||
const loadModule = bindModuleToClassOnToken({
|
||||
module: instantBookingCreateServiceModule,
|
||||
moduleToken,
|
||||
token,
|
||||
classs: InstantBookingCreateService,
|
||||
depsMap: {},
|
||||
});
|
||||
|
||||
export type { InstantBookingCreateService };
|
||||
export const moduleLoader = {
|
||||
token,
|
||||
loadModule,
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import { createContainer } from "@calcom/features/di/di";
|
||||
|
||||
import {
|
||||
type RecurringBookingService,
|
||||
moduleLoader as recurringBookingServiceModule,
|
||||
} from "./RecurringBookingService.module";
|
||||
|
||||
const container = createContainer();
|
||||
|
||||
export function getRecurringBookingService(): RecurringBookingService {
|
||||
recurringBookingServiceModule.loadModule(container);
|
||||
|
||||
return container.get<RecurringBookingService>(recurringBookingServiceModule.token);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { RecurringBookingService } from "@calcom/features/bookings/lib/handleNewRecurringBooking";
|
||||
import { createModule, bindModuleToClassOnToken } from "@calcom/features/di/di";
|
||||
import { DI_TOKENS } from "@calcom/features/di/tokens";
|
||||
|
||||
import { moduleLoader as regularBookingServiceModuleLoader } from "./RegularBookingService.module";
|
||||
|
||||
const token = DI_TOKENS.RECURRING_BOOKING_SERVICE;
|
||||
const moduleToken = DI_TOKENS.RECURRING_BOOKING_SERVICE_MODULE;
|
||||
export const recurringBookingServiceModule = createModule();
|
||||
|
||||
const loadModule = bindModuleToClassOnToken({
|
||||
module: recurringBookingServiceModule,
|
||||
moduleToken,
|
||||
token,
|
||||
classs: RecurringBookingService,
|
||||
depsMap: {
|
||||
regularBookingService: regularBookingServiceModuleLoader,
|
||||
},
|
||||
});
|
||||
|
||||
export const moduleLoader = {
|
||||
token,
|
||||
loadModule,
|
||||
};
|
||||
export type { RecurringBookingService };
|
||||
+4
-3
@@ -1,8 +1,9 @@
|
||||
import { createContainer } from "../../di";
|
||||
import { createContainer } from "@calcom/features/di/di";
|
||||
|
||||
import {
|
||||
type RegularBookingService,
|
||||
regularBookingServiceModule,
|
||||
} from "../modules/RegularBookingService.module";
|
||||
moduleLoader as regularBookingServiceModule,
|
||||
} from "./RegularBookingService.module";
|
||||
|
||||
const regularBookingServiceContainer = createContainer();
|
||||
|
||||
+12
-3
@@ -1,14 +1,18 @@
|
||||
import { RegularBookingService } from "@calcom/features/bookings/lib/handleNewBooking";
|
||||
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";
|
||||
|
||||
import { bindModuleToClassOnToken, createModule } from "../../di";
|
||||
|
||||
const thisModule = createModule();
|
||||
const token = DI_TOKENS.REGULAR_BOOKING_SERVICE;
|
||||
const moduleToken = DI_TOKENS.REGULAR_BOOKING_SERVICE_MODULE;
|
||||
@@ -24,10 +28,15 @@ const loadModule = bindModuleToClassOnToken({
|
||||
bookingRepository: bookingRepositoryModuleLoader,
|
||||
featuresRepository: featuresRepositoryModuleLoader,
|
||||
checkBookingLimitsService: checkBookingLimitsModuleLoader,
|
||||
luckyUserService: luckyUserServiceModuleLoader,
|
||||
hostRepository: hostRepositoryModuleLoader,
|
||||
oooRepository: oooRepositoryModuleLoader,
|
||||
userRepository: userRepositoryModuleLoader,
|
||||
attributeRepository: attributeRepositoryModuleLoader,
|
||||
},
|
||||
});
|
||||
|
||||
export const regularBookingServiceModule = {
|
||||
export const moduleLoader = {
|
||||
token,
|
||||
loadModule,
|
||||
};
|
||||
File renamed without changes.
@@ -57,36 +57,48 @@ export const bookingCreateBodySchema = z.object({
|
||||
|
||||
export type BookingCreateBody = z.input<typeof bookingCreateBodySchema>;
|
||||
|
||||
// TODO: Plan to create different schemas for Recurring Bookings, Instant Bookings and Regular Bookings.
|
||||
// We later want to make these properties required. They were optional because they are part of general schema which is used for all types of bookings.
|
||||
const recurringBookingCreateBodyPartialSchema = z.object({
|
||||
recurringCount: z.number().optional(),
|
||||
isFirstRecurringSlot: z.boolean().optional(),
|
||||
thirdPartyRecurringEventId: z.string().nullish(),
|
||||
numSlotsToCheckForAvailability: z.number().optional(),
|
||||
allRecurringDates: z
|
||||
.array(
|
||||
z.object({
|
||||
start: z.string(),
|
||||
end: z.string().optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
currentRecurringIndex: z.number().optional(),
|
||||
});
|
||||
|
||||
export const extendedBookingCreateBody = bookingCreateBodySchema.merge(
|
||||
z.object({
|
||||
noEmail: z.boolean().optional(),
|
||||
recurringCount: z.number().optional(),
|
||||
allRecurringDates: z
|
||||
.array(
|
||||
z.object({
|
||||
start: z.string(),
|
||||
end: z.string(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
currentRecurringIndex: z.number().optional(),
|
||||
appsStatus: z
|
||||
.array(
|
||||
z.object({
|
||||
appName: z.string(),
|
||||
success: z.number(),
|
||||
failures: z.number(),
|
||||
type: z.string(),
|
||||
errors: z.string().array(),
|
||||
warnings: z.string().array().optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
luckyUsers: z.array(z.number()).optional(),
|
||||
customInputs: z.undefined().optional(),
|
||||
})
|
||||
z
|
||||
.object({
|
||||
noEmail: z.boolean().optional(),
|
||||
appsStatus: z
|
||||
.array(
|
||||
z.object({
|
||||
appName: z.string(),
|
||||
success: z.number(),
|
||||
failures: z.number(),
|
||||
type: z.string(),
|
||||
errors: z.string().array(),
|
||||
warnings: z.string().array().optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
luckyUsers: z.array(z.number()).optional(),
|
||||
customInputs: z.undefined().optional(),
|
||||
})
|
||||
.merge(recurringBookingCreateBodyPartialSchema)
|
||||
);
|
||||
|
||||
export type ExtendedBookingCreateBody = z.input<typeof extendedBookingCreateBody>;
|
||||
|
||||
// It has only the legacy props that are part of `responses` now. The API can still hit old props
|
||||
export const bookingCreateSchemaLegacyPropsForApi = z.object({
|
||||
email: z.string(),
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
import { post } from "@calcom/lib/fetch-wrapper";
|
||||
|
||||
import type { BookingCreateBody, InstantBookingResponse } from "../types";
|
||||
import type { BookingCreateBody } from "../types";
|
||||
import type { InstantBookingCreateResult } from "./dto/types";
|
||||
|
||||
export const createInstantBooking = async (data: BookingCreateBody) => {
|
||||
const response = await post<
|
||||
BookingCreateBody,
|
||||
// fetch response can't have a Date type, it must be a string
|
||||
Omit<InstantBookingResponse, "startTime" | "endTime"> & {
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
}
|
||||
// TODO: Fetch response can't have a Date type, it must be a string. We need to type expires as a string here but it breaks types down the line, fix it in a follow-up PR.
|
||||
InstantBookingCreateResult
|
||||
>("/api/book/instant-event", data);
|
||||
return response;
|
||||
};
|
||||
+16
-10
@@ -1,22 +1,22 @@
|
||||
/**
|
||||
* Domain types for BookingCreateService
|
||||
* Domain types for Booking Services
|
||||
* These types are framework-agnostic and contain only the data required for booking operations
|
||||
*/
|
||||
import type { z } from "zod";
|
||||
|
||||
import type getBookingDataSchema from "@calcom/features/bookings/lib/getBookingDataSchema";
|
||||
import type getBookingDataSchemaForApi from "@calcom/features/bookings/lib/getBookingDataSchemaForApi";
|
||||
import type { BookingCreateBody as BaseCreateBookingData } from "@calcom/prisma/zod/custom/booking";
|
||||
import type { extendedBookingCreateBody } from "@calcom/prisma/zod/custom/booking";
|
||||
import type { SchedulingType } from "@calcom/prisma/enums";
|
||||
|
||||
export type ExtendedBookingCreateData = z.input<typeof extendedBookingCreateBody>;
|
||||
import type { ExtendedBookingCreateBody } from "../bookingCreateBodySchema";
|
||||
import type { RegularBookingService } from "../handleNewBooking";
|
||||
|
||||
export type { BookingCreateBody } from "../bookingCreateBodySchema";
|
||||
export type BookingDataSchemaGetter = typeof getBookingDataSchema | typeof getBookingDataSchemaForApi;
|
||||
|
||||
export type CreateRegularBookingData = BaseCreateBookingData;
|
||||
export type CreateRegularBookingData = ExtendedBookingCreateBody;
|
||||
|
||||
export type CreateInstantBookingData = BaseCreateBookingData;
|
||||
export type CreateInstantBookingData = ExtendedBookingCreateBody;
|
||||
|
||||
export type CreateRecurringBookingData = (BaseCreateBookingData & {
|
||||
export type CreateRecurringBookingData = (ExtendedBookingCreateBody & {
|
||||
schedulingType?: SchedulingType;
|
||||
})[];
|
||||
|
||||
@@ -27,6 +27,9 @@ export type PlatformParams = {
|
||||
platformRescheduleUrl?: string;
|
||||
platformBookingLocation?: string;
|
||||
areCalendarEventsEnabled?: boolean;
|
||||
skipAvailabilityCheck?: boolean;
|
||||
skipEventLimitsCheck?: boolean;
|
||||
skipCalendarSyncTaskCreation?: boolean;
|
||||
};
|
||||
|
||||
export type CreateBookingMeta = {
|
||||
@@ -41,7 +44,7 @@ export type BookingHandlerInput = {
|
||||
bookingData: CreateRegularBookingData;
|
||||
} & CreateBookingMeta;
|
||||
|
||||
export type CreateInstantBookingResponse = {
|
||||
export type InstantBookingCreateResult = {
|
||||
message: string;
|
||||
meetingTokenId: number;
|
||||
bookingId: number;
|
||||
@@ -49,3 +52,6 @@ export type CreateInstantBookingResponse = {
|
||||
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"]>>;
|
||||
@@ -3,8 +3,10 @@ import { v5 as uuidv5 } from "uuid";
|
||||
|
||||
import processExternalId from "@calcom/app-store/_utils/calendars/processExternalId";
|
||||
import { getPaymentAppData } from "@calcom/app-store/_utils/payments/getPaymentAppData";
|
||||
import { getFirstDelegationConferencingCredentialAppLocation } from "@calcom/app-store/delegationCredential";
|
||||
import { enrichHostsWithDelegationCredentials } from "@calcom/app-store/delegationCredential";
|
||||
import {
|
||||
enrichHostsWithDelegationCredentials,
|
||||
getFirstDelegationConferencingCredentialAppLocation,
|
||||
} from "@calcom/app-store/delegationCredential";
|
||||
import { metadata as GoogleMeetMetadata } from "@calcom/app-store/googlevideo/_metadata";
|
||||
import {
|
||||
getLocationValueForDB,
|
||||
@@ -12,23 +14,26 @@ import {
|
||||
OrganizerDefaultConferencingAppType,
|
||||
} from "@calcom/app-store/locations";
|
||||
import { getAppFromSlug } from "@calcom/app-store/utils";
|
||||
import { eventTypeAppMetadataOptionalSchema } from "@calcom/app-store/zod-utils";
|
||||
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/app-store/zod-utils";
|
||||
import {
|
||||
eventTypeMetaDataSchemaWithTypedApps,
|
||||
eventTypeAppMetadataOptionalSchema,
|
||||
} from "@calcom/app-store/zod-utils";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { scheduleMandatoryReminder } from "@calcom/ee/workflows/lib/reminders/scheduleMandatoryReminder";
|
||||
import getICalUID from "@calcom/emails/lib/getICalUID";
|
||||
import { CalendarEventBuilder } from "@calcom/features/CalendarEventBuilder";
|
||||
import EventManager, { placeholderCreatedEvent } from "@calcom/features/bookings/lib/EventManager";
|
||||
import type { BookingDataSchemaGetter } from "@calcom/features/bookings/lib/dto/types";
|
||||
import type { CreateRegularBookingData, CreateBookingMeta } from "@calcom/features/bookings/lib/dto/types";
|
||||
import type {
|
||||
CreateRegularBookingData,
|
||||
CreateBookingMeta,
|
||||
BookingHandlerInput,
|
||||
} from "@calcom/features/bookings/lib/dto/types";
|
||||
import type { CheckBookingAndDurationLimitsService } from "@calcom/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits";
|
||||
import { handlePayment } from "@calcom/features/bookings/lib/handlePayment";
|
||||
import { handleWebhookTrigger } from "@calcom/features/bookings/lib/handleWebhookTrigger";
|
||||
import { isEventTypeLoggingEnabled } from "@calcom/features/bookings/lib/isEventTypeLoggingEnabled";
|
||||
import type { CacheService } from "@calcom/features/calendar-cache/lib/getShouldServeCache";
|
||||
import { getCheckBookingAndDurationLimitsService } from "@calcom/features/di/containers/BookingLimits";
|
||||
import { getCacheService } from "@calcom/features/di/containers/Cache";
|
||||
import { getLuckyUserService } from "@calcom/features/di/containers/LuckyUser";
|
||||
import AssignmentReasonRecorder from "@calcom/features/ee/round-robin/assignmentReason/AssignmentReasonRecorder";
|
||||
import { getUsernameList } from "@calcom/features/eventtypes/lib/defaultEvents";
|
||||
import { getEventName, updateHostInEventName } from "@calcom/features/eventtypes/lib/eventNaming";
|
||||
@@ -59,13 +64,16 @@ 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 { BookingRepository } from "@calcom/lib/server/repository/booking";
|
||||
import type { PrismaAttributeRepository as AttributeRepository } from "@calcom/lib/server/repository/PrismaAttributeRepository";
|
||||
import type { BookingRepository } from "@calcom/lib/server/repository/booking";
|
||||
import type { HostRepository } from "@calcom/lib/server/repository/host";
|
||||
import type { PrismaOOORepository as OooRepository } from "@calcom/lib/server/repository/ooo";
|
||||
import type { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
|
||||
import { HashedLinkService } from "@calcom/lib/server/service/hashedLinkService";
|
||||
import { WorkflowService } from "@calcom/lib/server/service/workflows";
|
||||
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { DestinationCalendar, Prisma, User, AssignmentReasonEnum } from "@calcom/prisma/client";
|
||||
import {
|
||||
BookingStatus,
|
||||
@@ -91,6 +99,7 @@ import { BookingActionMap, BookingEmailSmsHandler } from "./BookingEmailSmsHandl
|
||||
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";
|
||||
@@ -384,27 +393,6 @@ function buildTroubleshooterData({
|
||||
return troubleshooterData;
|
||||
}
|
||||
|
||||
export type PlatformParams = {
|
||||
platformClientId?: string;
|
||||
platformCancelUrl?: string;
|
||||
platformBookingUrl?: string;
|
||||
platformRescheduleUrl?: string;
|
||||
platformBookingLocation?: string;
|
||||
areCalendarEventsEnabled?: boolean;
|
||||
};
|
||||
|
||||
export type BookingHandlerInput = {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
bookingData: Record<string, any>;
|
||||
userId?: number;
|
||||
// These used to come from headers but now we're passing them as params
|
||||
hostname?: string;
|
||||
forcedSlug?: string;
|
||||
skipAvailabilityCheck?: boolean;
|
||||
skipEventLimitsCheck?: boolean;
|
||||
skipCalendarSyncTaskCreation?: boolean;
|
||||
} & PlatformParams;
|
||||
|
||||
function formatAvailabilitySnapshot(data: {
|
||||
dateRanges: { start: dayjs.Dayjs; end: dayjs.Dayjs }[];
|
||||
oooExcludedDateRanges: { start: dayjs.Dayjs; end: dayjs.Dayjs }[];
|
||||
@@ -422,8 +410,23 @@ function formatAvailabilitySnapshot(data: {
|
||||
};
|
||||
}
|
||||
|
||||
export interface IBookingServiceDependencies {
|
||||
cacheService: CacheService;
|
||||
checkBookingAndDurationLimitsService: CheckBookingAndDurationLimitsService;
|
||||
prismaClient: PrismaClient;
|
||||
bookingRepository: BookingRepository;
|
||||
featuresRepository: FeaturesRepository;
|
||||
checkBookingLimitsService: CheckBookingLimitsService;
|
||||
luckyUserService: LuckyUserService;
|
||||
hostRepository: HostRepository;
|
||||
oooRepository: OooRepository;
|
||||
userRepository: UserRepository;
|
||||
attributeRepository: AttributeRepository;
|
||||
}
|
||||
|
||||
async function handler(
|
||||
input: BookingHandlerInput,
|
||||
deps: IBookingServiceDependencies,
|
||||
bookingDataSchemaGetter: BookingDataSchemaGetter = getBookingDataSchema
|
||||
) {
|
||||
const {
|
||||
@@ -442,6 +445,14 @@ async function handler(
|
||||
skipCalendarSyncTaskCreation = false,
|
||||
} = input;
|
||||
|
||||
const {
|
||||
prismaClient: prisma,
|
||||
bookingRepository,
|
||||
cacheService,
|
||||
checkBookingAndDurationLimitsService,
|
||||
luckyUserService,
|
||||
} = deps;
|
||||
|
||||
const isPlatformBooking = !!platformClientId;
|
||||
|
||||
const eventType = await getEventType({
|
||||
@@ -543,7 +554,7 @@ async function handler(
|
||||
const bookingSeat = reqBody.rescheduleUid ? await getSeatedBooking(reqBody.rescheduleUid) : null;
|
||||
const rescheduleUid = bookingSeat ? bookingSeat.booking.uid : reqBody.rescheduleUid;
|
||||
const isNormalBookingOrFirstRecurringSlot = input.bookingData.allRecurringDates
|
||||
? input.bookingData.isFirstRecurringSlot
|
||||
? !!input.bookingData.isFirstRecurringSlot
|
||||
: true;
|
||||
|
||||
let originalRescheduledBooking = rescheduleUid
|
||||
@@ -569,11 +580,9 @@ async function handler(
|
||||
(!isConfirmedByDefault && !userReschedulingIsOwner) ||
|
||||
eventType.schedulingType === SchedulingType.ROUND_ROBIN
|
||||
) {
|
||||
const bookingRepo = new BookingRepository(prisma);
|
||||
|
||||
const requiresPayment = !Number.isNaN(paymentAppData.price) && paymentAppData.price > 0;
|
||||
|
||||
const existingBooking = await bookingRepo.getValidBookingFromEventTypeForAttendee({
|
||||
const existingBooking = await bookingRepository.getValidBookingFromEventTypeForAttendee({
|
||||
eventTypeId,
|
||||
bookerEmail,
|
||||
bookerPhoneNumber,
|
||||
@@ -610,7 +619,6 @@ async function handler(
|
||||
}
|
||||
}
|
||||
|
||||
const cacheService = getCacheService();
|
||||
const shouldServeCache = await cacheService.getShouldServeCache(_shouldServeCache, eventType.team?.id);
|
||||
|
||||
const isTeamEventType =
|
||||
@@ -723,7 +731,6 @@ async function handler(
|
||||
});
|
||||
|
||||
if (!skipEventLimitsCheck) {
|
||||
const checkBookingAndDurationLimitsService = getCheckBookingAndDurationLimitsService();
|
||||
await checkBookingAndDurationLimitsService.checkBookingAndDurationLimits({
|
||||
eventType,
|
||||
reqBodyStart: reqBody.start,
|
||||
@@ -783,7 +790,11 @@ async function handler(
|
||||
},
|
||||
}),
|
||||
};
|
||||
if (input.bookingData.allRecurringDates && input.bookingData.isFirstRecurringSlot) {
|
||||
if (
|
||||
input.bookingData.allRecurringDates &&
|
||||
input.bookingData.isFirstRecurringSlot &&
|
||||
input.bookingData.numSlotsToCheckForAvailability
|
||||
) {
|
||||
const isTeamEvent =
|
||||
eventType.schedulingType === SchedulingType.COLLECTIVE ||
|
||||
eventType.schedulingType === SchedulingType.ROUND_ROBIN;
|
||||
@@ -940,7 +951,6 @@ async function handler(
|
||||
memberId: eventTypeWithUsers.users[0].id ?? null,
|
||||
teamId: eventType.teamId,
|
||||
});
|
||||
const luckyUserService = getLuckyUserService();
|
||||
const newLuckyUser = await luckyUserService.getLuckyUser({
|
||||
// find a lucky user that is not already in the luckyUsers array
|
||||
availableUsers: freeUsers,
|
||||
@@ -965,7 +975,9 @@ async function handler(
|
||||
}
|
||||
if (
|
||||
input.bookingData.isFirstRecurringSlot &&
|
||||
eventType.schedulingType === SchedulingType.ROUND_ROBIN
|
||||
eventType.schedulingType === SchedulingType.ROUND_ROBIN &&
|
||||
input.bookingData.numSlotsToCheckForAvailability &&
|
||||
input.bookingData.allRecurringDates
|
||||
) {
|
||||
// for recurring round robin events check if lucky user is available for next slots
|
||||
try {
|
||||
@@ -1617,9 +1629,9 @@ async function handler(
|
||||
if (booking && booking.id && eventType.seatsPerTimeSlot) {
|
||||
const currentAttendee = booking.attendees.find(
|
||||
(attendee) =>
|
||||
attendee.email === input.bookingData.responses.email ||
|
||||
(input.bookingData.responses.attendeePhoneNumber &&
|
||||
attendee.phoneNumber === input.bookingData.responses.attendeePhoneNumber)
|
||||
attendee.email === bookingData.responses.email ||
|
||||
(bookingData.responses.attendeePhoneNumber &&
|
||||
attendee.phoneNumber === bookingData.responses.attendeePhoneNumber)
|
||||
);
|
||||
|
||||
// Save description to bookingSeat
|
||||
@@ -2432,17 +2444,6 @@ async function handler(
|
||||
};
|
||||
}
|
||||
|
||||
export default handler;
|
||||
|
||||
export interface IBookingServiceDependencies {
|
||||
cacheService: CacheService;
|
||||
checkBookingAndDurationLimitsService: CheckBookingAndDurationLimitsService;
|
||||
prismaClient: PrismaClient;
|
||||
bookingRepository: BookingRepository;
|
||||
featuresRepository: FeaturesRepository;
|
||||
checkBookingLimitsService: CheckBookingLimitsService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes care of creating/rescheduling non-recurring, non-instant bookings. Such bookings could be TeamBooking, UserBooking, SeatedUserBooking, SeatedTeamBooking, etc.
|
||||
* We can't name it CoreBookingService because non-instant booking also creates a booking but it is entirely different from the regular booking.
|
||||
@@ -2452,19 +2453,29 @@ export class RegularBookingService implements IBookingService {
|
||||
constructor(private readonly deps: IBookingServiceDependencies) {}
|
||||
|
||||
async createBooking(input: { bookingData: CreateRegularBookingData; bookingMeta?: CreateBookingMeta }) {
|
||||
// deps to be passed to handler in follow-up PR
|
||||
return handler({ bookingData: input.bookingData, ...input.bookingMeta });
|
||||
return handler({ bookingData: input.bookingData, ...input.bookingMeta }, this.deps);
|
||||
}
|
||||
|
||||
async rescheduleBooking(input: { bookingData: CreateRegularBookingData; bookingMeta?: CreateBookingMeta }) {
|
||||
return handler({ bookingData: input.bookingData, ...input.bookingMeta });
|
||||
return handler({ bookingData: input.bookingData, ...input.bookingMeta }, this.deps);
|
||||
}
|
||||
|
||||
async rescheduleBookingForApiV1(input: {
|
||||
/**
|
||||
* @deprecated Exists only till API v1 is removed.
|
||||
*/
|
||||
async createBookingForApiV1(input: {
|
||||
bookingData: CreateRegularBookingData;
|
||||
bookingMeta?: CreateBookingMeta;
|
||||
bookingDataSchemaGetter: BookingDataSchemaGetter;
|
||||
}) {
|
||||
return handler({ bookingData: input.bookingData, ...input.bookingMeta }, input.bookingDataSchemaGetter);
|
||||
const bookingMeta = input.bookingMeta ?? {};
|
||||
return handler(
|
||||
{
|
||||
bookingData: input.bookingData,
|
||||
...bookingMeta,
|
||||
},
|
||||
this.deps,
|
||||
input.bookingDataSchemaGetter
|
||||
);
|
||||
}
|
||||
}
|
||||
+7
-5
@@ -19,6 +19,8 @@ import { vi, describe, expect, beforeEach } from "vitest";
|
||||
|
||||
import { test } from "@calcom/web/test/fixtures/fixtures";
|
||||
|
||||
import { getNewBookingHandler } from "./getNewBookingHandler";
|
||||
|
||||
vi.mock("@calcom/trpc/server/routers/viewer/auth/util", () => ({
|
||||
verifyCodeUnAuthenticated: vi.fn(),
|
||||
}));
|
||||
@@ -36,7 +38,7 @@ describe("handleNewBooking - Email Verification", () => {
|
||||
test(
|
||||
"should throw error when email verification is required but no verification code is provided",
|
||||
async () => {
|
||||
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
|
||||
const handleNewBooking = getNewBookingHandler();
|
||||
const { verifyCodeUnAuthenticated } = await import("@calcom/trpc/server/routers/viewer/auth/util");
|
||||
|
||||
const booker = getBooker({
|
||||
@@ -96,7 +98,7 @@ describe("handleNewBooking - Email Verification", () => {
|
||||
test(
|
||||
"should throw error when email verification is required and verification code is invalid",
|
||||
async () => {
|
||||
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
|
||||
const handleNewBooking = getNewBookingHandler();
|
||||
const { verifyCodeUnAuthenticated } = await import("@calcom/trpc/server/routers/viewer/auth/util");
|
||||
|
||||
vi.mocked(verifyCodeUnAuthenticated).mockRejectedValue(new Error("Invalid verification code"));
|
||||
@@ -159,7 +161,7 @@ describe("handleNewBooking - Email Verification", () => {
|
||||
test(
|
||||
"should successfully create booking when email verification is required and valid verification code is provided",
|
||||
async () => {
|
||||
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
|
||||
const handleNewBooking = getNewBookingHandler();
|
||||
const { verifyCodeUnAuthenticated } = await import("@calcom/trpc/server/routers/viewer/auth/util");
|
||||
|
||||
vi.mocked(verifyCodeUnAuthenticated).mockResolvedValue(undefined);
|
||||
@@ -220,7 +222,7 @@ describe("handleNewBooking - Email Verification", () => {
|
||||
test(
|
||||
"should handle rate limiting error from verification service",
|
||||
async () => {
|
||||
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
|
||||
const handleNewBooking = getNewBookingHandler();
|
||||
const { verifyCodeUnAuthenticated } = await import("@calcom/trpc/server/routers/viewer/auth/util");
|
||||
|
||||
const rateLimitError = new Error("Rate limit exceeded");
|
||||
@@ -285,7 +287,7 @@ describe("handleNewBooking - Email Verification", () => {
|
||||
test(
|
||||
"should proceed normally when email verification is not required",
|
||||
async () => {
|
||||
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
|
||||
const handleNewBooking = getNewBookingHandler();
|
||||
const { verifyCodeUnAuthenticated } = await import("@calcom/trpc/server/routers/viewer/auth/util");
|
||||
|
||||
const booker = getBooker({
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
async function handler(input: any) {
|
||||
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
|
||||
return handleNewBooking(input);
|
||||
import type { BookingHandlerInput } from "@calcom/features/bookings/lib/dto/types";
|
||||
|
||||
async function handler(input: BookingHandlerInput) {
|
||||
const { getRegularBookingService } = await import(
|
||||
"@calcom/features/bookings/di/RegularBookingService.container"
|
||||
);
|
||||
const regularBookingService = getRegularBookingService();
|
||||
const { bookingData, ...bookingMeta } = input;
|
||||
return regularBookingService.createBooking({
|
||||
bookingData,
|
||||
bookingMeta,
|
||||
});
|
||||
}
|
||||
|
||||
export function getNewBookingHandler() {
|
||||
|
||||
+9
-306
@@ -8,7 +8,6 @@ import {
|
||||
mockCalendarToHaveNoBusySlots,
|
||||
mockSuccessfulVideoMeetingCreation,
|
||||
TestData,
|
||||
Timezones,
|
||||
} from "@calcom/web/test/utils/bookingScenario/bookingScenario";
|
||||
import {
|
||||
expectBookingCreatedWebhookToHaveBeenFired,
|
||||
@@ -22,13 +21,12 @@ import { setupAndTeardown } from "@calcom/web/test/utils/bookingScenario/setupAn
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { getRecurringBookingService } from "@calcom/features/bookings/di/RecurringBookingService.container";
|
||||
import { WEBAPP_URL, WEBSITE_URL } from "@calcom/lib/constants";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { BookingStatus, SchedulingType } from "@calcom/prisma/enums";
|
||||
import { BookingStatus } from "@calcom/prisma/enums";
|
||||
import { test } from "@calcom/web/test/fixtures/fixtures";
|
||||
|
||||
import { handleNewRecurringBooking } from "../../handleNewRecurringBooking";
|
||||
|
||||
const DAY_IN_MS = 1000 * 60 * 60 * 24;
|
||||
|
||||
function getPlusDayDate(date: string, days: number) {
|
||||
@@ -153,10 +151,13 @@ describe("handleNewRecurringBooking", () => {
|
||||
};
|
||||
});
|
||||
|
||||
const recurringBookingService = getRecurringBookingService();
|
||||
// Call handleNewRecurringBooking directly instead of through API
|
||||
const createdBookings = await handleNewRecurringBooking({
|
||||
const createdBookings = await recurringBookingService.createBooking({
|
||||
bookingData: bookingDataArray,
|
||||
userId: -1, // Simulating anonymous user like in the API test
|
||||
bookingMeta: {
|
||||
userId: -1, // Simulating anonymous user like in the API test
|
||||
},
|
||||
});
|
||||
|
||||
expect(createdBookings.length).toBe(numOfSlotsToBeBooked);
|
||||
@@ -177,7 +178,7 @@ describe("handleNewRecurringBooking", () => {
|
||||
|
||||
await expectBookingToBeInDatabase({
|
||||
description: "",
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
|
||||
uid: createdBooking.uid!,
|
||||
eventTypeId: mockBookingData.eventTypeId,
|
||||
status: BookingStatus.ACCEPTED,
|
||||
@@ -211,16 +212,14 @@ describe("handleNewRecurringBooking", () => {
|
||||
expectSuccessfulBookingCreationEmails({
|
||||
booker,
|
||||
booking: {
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
uid: createdBookings[0].uid!,
|
||||
urlOrigin: WEBSITE_URL,
|
||||
},
|
||||
organizer,
|
||||
emails,
|
||||
bookingTimeRange: {
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
start: createdBookings[0].startTime!,
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
|
||||
end: createdBookings[0].endTime!,
|
||||
},
|
||||
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
|
||||
@@ -253,302 +252,6 @@ describe("handleNewRecurringBooking", () => {
|
||||
},
|
||||
timeout
|
||||
);
|
||||
|
||||
test.skip(
|
||||
`should fail recurring booking if second slot is already booked`,
|
||||
async ({}) => {
|
||||
const booker = getBooker({
|
||||
email: "[email protected]",
|
||||
name: "Booker",
|
||||
});
|
||||
|
||||
const organizer = getOrganizer({
|
||||
name: "Organizer",
|
||||
email: "[email protected]",
|
||||
id: 101,
|
||||
schedules: [TestData.schedules.IstWorkHours],
|
||||
credentials: [getGoogleCalendarCredential()],
|
||||
selectedCalendars: [TestData.selectedCalendars.google],
|
||||
destinationCalendar: {
|
||||
integration: "google_calendar",
|
||||
externalId: "[email protected]",
|
||||
},
|
||||
});
|
||||
|
||||
const recurrence = getRecurrence({
|
||||
type: "weekly",
|
||||
numberOfOccurrences: 3,
|
||||
});
|
||||
const plus1DateString = getDate({ dateIncrement: 1 }).dateString;
|
||||
const plus2DateString = getDate({ dateIncrement: 2 }).dateString;
|
||||
await createBookingScenario(
|
||||
getScenarioData({
|
||||
webhooks: [
|
||||
{
|
||||
userId: organizer.id,
|
||||
eventTriggers: ["BOOKING_CREATED"],
|
||||
subscriberUrl: "http://my-webhook.example.com",
|
||||
active: true,
|
||||
eventTypeId: 1,
|
||||
appId: null,
|
||||
},
|
||||
],
|
||||
eventTypes: [
|
||||
{
|
||||
id: 1,
|
||||
slotInterval: 30,
|
||||
length: 30,
|
||||
recurringEvent: recurrence,
|
||||
users: [
|
||||
{
|
||||
id: 101,
|
||||
},
|
||||
],
|
||||
destinationCalendar: {
|
||||
integration: "google_calendar",
|
||||
externalId: "[email protected]",
|
||||
},
|
||||
},
|
||||
],
|
||||
bookings: [
|
||||
{
|
||||
uid: "booking-1-uid",
|
||||
eventTypeId: 1,
|
||||
userId: organizer.id,
|
||||
status: BookingStatus.ACCEPTED,
|
||||
startTime: `${plus2DateString}T04:00:00.000Z`,
|
||||
endTime: `${plus2DateString}T04:30:00.000Z`,
|
||||
},
|
||||
],
|
||||
organizer,
|
||||
apps: [TestData.apps["google-calendar"], TestData.apps["daily-video"]],
|
||||
})
|
||||
);
|
||||
|
||||
mockSuccessfulVideoMeetingCreation({
|
||||
metadataLookupKey: "dailyvideo",
|
||||
videoMeetingData: {
|
||||
id: "MOCK_ID",
|
||||
password: "MOCK_PASS",
|
||||
url: `http://mock-dailyvideo.example.com/meeting-1`,
|
||||
},
|
||||
});
|
||||
|
||||
mockCalendarToHaveNoBusySlots("googlecalendar", {
|
||||
create: {
|
||||
id: "MOCKED_GOOGLE_CALENDAR_EVENT_ID",
|
||||
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
|
||||
},
|
||||
});
|
||||
|
||||
const recurringCountInRequest = 2;
|
||||
const mockBookingData = getMockRequestDataForBooking({
|
||||
data: {
|
||||
eventTypeId: 1,
|
||||
start: `${plus1DateString}T04:00:00.000Z`,
|
||||
end: `${plus1DateString}T04:30:00.000Z`,
|
||||
recurringEventId: uuidv4(),
|
||||
recurringCount: recurringCountInRequest,
|
||||
responses: {
|
||||
email: booker.email,
|
||||
name: booker.name,
|
||||
location: { optionValue: "", value: "integrations:daily" },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const numOfSlotsToBeBooked = 4;
|
||||
|
||||
// Create an array of booking data for multiple slots
|
||||
const bookingDataArray = Array(numOfSlotsToBeBooked)
|
||||
.fill(mockBookingData)
|
||||
.map((mockBookingData, index) => {
|
||||
return {
|
||||
...mockBookingData,
|
||||
start: getPlusDayDate(mockBookingData.start, index).toISOString(),
|
||||
end: getPlusDayDate(mockBookingData.end, index).toISOString(),
|
||||
};
|
||||
});
|
||||
|
||||
await expect(
|
||||
async () =>
|
||||
await handleNewRecurringBooking({
|
||||
bookingData: bookingDataArray,
|
||||
userId: -1,
|
||||
})
|
||||
).rejects.toThrow(ErrorCode.NoAvailableUsersFound);
|
||||
},
|
||||
timeout
|
||||
);
|
||||
});
|
||||
|
||||
describe("Round robin event type:", () => {
|
||||
test.skip("should fail recurring booking if a fixed host is not available on the second slot", async () => {
|
||||
const booker = getBooker({
|
||||
email: "[email protected]",
|
||||
name: "Booker",
|
||||
});
|
||||
|
||||
const organizer = getOrganizer({
|
||||
name: "Organizer",
|
||||
email: "[email protected]",
|
||||
id: 101,
|
||||
defaultScheduleId: null,
|
||||
teams: [
|
||||
{
|
||||
membership: {
|
||||
accepted: true,
|
||||
},
|
||||
team: {
|
||||
id: 1,
|
||||
name: "Team 1",
|
||||
slug: "team-1",
|
||||
},
|
||||
},
|
||||
],
|
||||
schedules: [TestData.schedules.IstMorningShift],
|
||||
credentials: [getGoogleCalendarCredential()],
|
||||
selectedCalendars: [TestData.selectedCalendars.google],
|
||||
destinationCalendar: {
|
||||
integration: TestData.apps["google-calendar"].type,
|
||||
externalId: "[email protected]",
|
||||
},
|
||||
});
|
||||
|
||||
const otherTeamMembers = [
|
||||
{
|
||||
name: "Other Team Member 1",
|
||||
username: "other-team-member-1",
|
||||
timeZone: Timezones["+5:30"],
|
||||
defaultScheduleId: null,
|
||||
email: "[email protected]",
|
||||
id: 102,
|
||||
schedules: [TestData.schedules.IstMorningShift],
|
||||
credentials: [getGoogleCalendarCredential()],
|
||||
selectedCalendars: [TestData.selectedCalendars.google],
|
||||
destinationCalendar: {
|
||||
integration: TestData.apps["google-calendar"].type,
|
||||
externalId: "[email protected]",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const recurrence = getRecurrence({
|
||||
type: "weekly",
|
||||
numberOfOccurrences: 3,
|
||||
});
|
||||
|
||||
const plus1DateString = getDate({ dateIncrement: 1 }).dateString;
|
||||
const plus2DateString = getDate({ dateIncrement: 2 }).dateString;
|
||||
|
||||
await createBookingScenario(
|
||||
getScenarioData({
|
||||
webhooks: [
|
||||
{
|
||||
userId: organizer.id,
|
||||
eventTriggers: ["BOOKING_CREATED"],
|
||||
subscriberUrl: "http://my-webhook.example.com",
|
||||
active: true,
|
||||
eventTypeId: 1,
|
||||
appId: null,
|
||||
},
|
||||
],
|
||||
eventTypes: [
|
||||
{
|
||||
id: 1,
|
||||
slotInterval: 30,
|
||||
schedulingType: SchedulingType.ROUND_ROBIN,
|
||||
length: 30,
|
||||
recurringEvent: recurrence,
|
||||
hosts: [
|
||||
{
|
||||
userId: 101,
|
||||
isFixed: false,
|
||||
},
|
||||
{
|
||||
userId: 102,
|
||||
isFixed: true,
|
||||
},
|
||||
],
|
||||
destinationCalendar: {
|
||||
integration: "google_calendar",
|
||||
externalId: "[email protected]",
|
||||
},
|
||||
},
|
||||
],
|
||||
bookings: [
|
||||
{
|
||||
userId: 102,
|
||||
attendees: [
|
||||
{
|
||||
email: "[email protected]",
|
||||
},
|
||||
],
|
||||
eventTypeId: 1,
|
||||
status: "ACCEPTED",
|
||||
startTime: `${plus2DateString}T04:00:00.000Z`,
|
||||
endTime: `${plus2DateString}T04:30:00.000Z`,
|
||||
},
|
||||
],
|
||||
organizer,
|
||||
usersApartFromOrganizer: otherTeamMembers,
|
||||
apps: [TestData.apps["google-calendar"], TestData.apps["daily-video"]],
|
||||
})
|
||||
);
|
||||
|
||||
mockSuccessfulVideoMeetingCreation({
|
||||
metadataLookupKey: "dailyvideo",
|
||||
videoMeetingData: {
|
||||
id: "MOCK_ID",
|
||||
password: "MOCK_PASS",
|
||||
url: `http://mock-dailyvideo.example.com/meeting-1`,
|
||||
},
|
||||
});
|
||||
|
||||
mockCalendarToHaveNoBusySlots("googlecalendar", {
|
||||
create: {
|
||||
id: "MOCKED_GOOGLE_CALENDAR_EVENT_ID",
|
||||
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
|
||||
},
|
||||
});
|
||||
|
||||
const recurringCountInRequest = 4;
|
||||
const mockBookingData = getMockRequestDataForBooking({
|
||||
data: {
|
||||
eventTypeId: 1,
|
||||
start: `${plus1DateString}T04:00:00.000Z`,
|
||||
end: `${plus1DateString}T04:30:00.000Z`,
|
||||
recurringEventId: uuidv4(),
|
||||
recurringCount: recurringCountInRequest,
|
||||
responses: {
|
||||
email: booker.email,
|
||||
name: booker.name,
|
||||
location: { optionValue: "", value: "integrations:daily" },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const numOfSlotsToBeBooked = 4;
|
||||
|
||||
// Create an array of booking data for multiple slots
|
||||
const bookingDataArray = Array(numOfSlotsToBeBooked)
|
||||
.fill(mockBookingData)
|
||||
.map((mockBookingData, index) => {
|
||||
return {
|
||||
...mockBookingData,
|
||||
schedulingType: SchedulingType.ROUND_ROBIN,
|
||||
start: getPlusDayDate(mockBookingData.start, index).toISOString(),
|
||||
end: getPlusDayDate(mockBookingData.end, index).toISOString(),
|
||||
};
|
||||
});
|
||||
|
||||
await expect(() =>
|
||||
handleNewRecurringBooking({
|
||||
bookingData: bookingDataArray,
|
||||
userId: -1,
|
||||
})
|
||||
).rejects.toThrow(ErrorCode.NoAvailableUsersFound);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { CreateBookingMeta, CreateRecurringBookingData } from "@calcom/features/bookings/lib/dto/types";
|
||||
import handleNewBooking from "@calcom/features/bookings/lib/handleNewBooking";
|
||||
import type { BookingResponse } from "@calcom/features/bookings/types";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
import type { AppsStatus } from "@calcom/types/Calendar";
|
||||
@@ -11,10 +10,14 @@ export type BookingHandlerInput = {
|
||||
bookingData: CreateRecurringBookingData;
|
||||
} & CreateBookingMeta;
|
||||
|
||||
export const handleNewRecurringBooking = async (input: BookingHandlerInput): Promise<BookingResponse[]> => {
|
||||
export const handleNewRecurringBooking = async (
|
||||
input: BookingHandlerInput,
|
||||
deps: IRecurringBookingServiceDependencies
|
||||
): Promise<BookingResponse[]> => {
|
||||
const data = input.bookingData;
|
||||
const { regularBookingService } = deps;
|
||||
const createdBookings: BookingResponse[] = [];
|
||||
const allRecurringDates: { start: string | undefined; end: string | undefined }[] = data.map((booking) => {
|
||||
const allRecurringDates: { start: string; end: string | undefined }[] = data.map((booking) => {
|
||||
return { start: booking.start, end: booking.end };
|
||||
});
|
||||
const appsStatus: AppsStatus[] | undefined = undefined;
|
||||
@@ -51,11 +54,13 @@ export const handleNewRecurringBooking = async (input: BookingHandlerInput): Pro
|
||||
noEmail: input.noEmail !== undefined ? input.noEmail : false,
|
||||
};
|
||||
|
||||
const firstBookingResult = await handleNewBooking({
|
||||
const firstBookingResult = await regularBookingService.createBooking({
|
||||
bookingData: recurringEventData,
|
||||
hostname: input.hostname || "",
|
||||
forcedSlug: input.forcedSlug as string | undefined,
|
||||
...handleBookingMeta,
|
||||
bookingMeta: {
|
||||
hostname: input.hostname || "",
|
||||
forcedSlug: input.forcedSlug as string | undefined,
|
||||
...handleBookingMeta,
|
||||
},
|
||||
});
|
||||
luckyUsers = firstBookingResult.luckyUsers;
|
||||
}
|
||||
@@ -92,11 +97,13 @@ export const handleNewRecurringBooking = async (input: BookingHandlerInput): Pro
|
||||
luckyUsers,
|
||||
};
|
||||
|
||||
const promiseEachRecurringBooking: ReturnType<typeof handleNewBooking> = handleNewBooking({
|
||||
hostname: input.hostname || "",
|
||||
forcedSlug: input.forcedSlug as string | undefined,
|
||||
const promiseEachRecurringBooking = regularBookingService.createBooking({
|
||||
bookingData: recurringEventData,
|
||||
...handleBookingMeta,
|
||||
bookingMeta: {
|
||||
hostname: input.hostname || "",
|
||||
forcedSlug: input.forcedSlug as string | undefined,
|
||||
...handleBookingMeta,
|
||||
},
|
||||
});
|
||||
|
||||
const eachRecurringBooking = await promiseEachRecurringBooking;
|
||||
@@ -132,8 +139,7 @@ export class RecurringBookingService implements IBookingService {
|
||||
bookingMeta?: CreateBookingMeta;
|
||||
}): Promise<BookingResponse[]> {
|
||||
const handlerInput = { bookingData: input.bookingData, ...(input.bookingMeta || {}) };
|
||||
// FOLLOW-UP: Pass on dependencies to the handler
|
||||
return handleNewRecurringBooking(handlerInput);
|
||||
return handleNewRecurringBooking(handlerInput, this.deps);
|
||||
}
|
||||
|
||||
async rescheduleBooking(input: {
|
||||
@@ -141,7 +147,6 @@ export class RecurringBookingService implements IBookingService {
|
||||
bookingMeta?: CreateBookingMeta;
|
||||
}): Promise<BookingResponse[]> {
|
||||
const handlerInput = { bookingData: input.bookingData, ...(input.bookingMeta || {}) };
|
||||
// FOLLOW-UP: Pass on dependencies to the handler
|
||||
return handleNewRecurringBooking(handlerInput);
|
||||
return handleNewRecurringBooking(handlerInput, this.deps);
|
||||
}
|
||||
}
|
||||
@@ -6,3 +6,4 @@ export {
|
||||
export { createBooking } from "./create-booking";
|
||||
export { createRecurringBooking } from "./create-recurring-booking";
|
||||
export { createInstantBooking } from "./create-instant-booking";
|
||||
export type { BookingResponse } from "../types";
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ErrorOption, FieldPath } from "react-hook-form";
|
||||
|
||||
import type { SchedulingType } from "@calcom/prisma/client";
|
||||
import type { RegularBookingCreateResult } from "@calcom/features/bookings/lib/dto/types";
|
||||
import type { SchedulingType } from "@calcom/prisma/enums";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import type { AppsStatus } from "@calcom/types/Calendar";
|
||||
|
||||
@@ -93,13 +94,8 @@ export type RecurringBookingCreateBody = BookingCreateBody & {
|
||||
schedulingType?: SchedulingType;
|
||||
};
|
||||
|
||||
export type BookingResponse = Awaited<
|
||||
ReturnType<typeof import("@calcom/features/bookings/lib/handleNewBooking").default>
|
||||
>;
|
||||
|
||||
export type InstantBookingResponse = Awaited<
|
||||
ReturnType<typeof import("@calcom/features/instant-meeting/handleInstantMeeting").default>
|
||||
>;
|
||||
// TODO: Instead of using the two different names, we want to use RegularBookingCreateResult name only but the name BookingResponse is used at ton of places and would be fixed in a separate followup PR.
|
||||
export type BookingResponse = RegularBookingCreateResult;
|
||||
|
||||
export type MarkNoShowResponse = Awaited<
|
||||
ReturnType<typeof import("@calcom/features/handleMarkNoShow").default>
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
import { DI_TOKENS } from "@calcom/features/di/tokens";
|
||||
|
||||
import { createContainer } from "../../di";
|
||||
import {
|
||||
type InstantBookingCreateService,
|
||||
instantBookingCreateServiceModule,
|
||||
} from "../modules/InstantBookingCreateService.module";
|
||||
|
||||
const container = createContainer();
|
||||
container.load(DI_TOKENS.INSTANT_BOOKING_CREATE_SERVICE_MODULE, instantBookingCreateServiceModule);
|
||||
|
||||
export function getInstantBookingCreateService(): InstantBookingCreateService {
|
||||
return container.get<InstantBookingCreateService>(DI_TOKENS.INSTANT_BOOKING_CREATE_SERVICE);
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import { bookingRepositoryModule } from "@calcom/features/di/modules/Booking";
|
||||
import { cacheModule } from "@calcom/features/di/modules/Cache";
|
||||
import { checkBookingAndDurationLimitsModule } from "@calcom/features/di/modules/CheckBookingAndDurationLimits";
|
||||
import { checkBookingLimitsModule } from "@calcom/features/di/modules/CheckBookingLimits";
|
||||
import { featuresRepositoryModule } from "@calcom/features/di/modules/Features";
|
||||
import { DI_TOKENS } from "@calcom/features/di/tokens";
|
||||
import { prismaModule } from "@calcom/prisma/prisma.module";
|
||||
|
||||
import { createContainer } from "../../di";
|
||||
import {
|
||||
type RecurringBookingService,
|
||||
recurringBookingServiceModule,
|
||||
} from "../modules/RecurringBookingService.module";
|
||||
|
||||
const container = createContainer();
|
||||
container.load(DI_TOKENS.PRISMA_MODULE, prismaModule);
|
||||
container.load(DI_TOKENS.BOOKING_REPOSITORY_MODULE, bookingRepositoryModule);
|
||||
container.load(DI_TOKENS.CACHE_SERVICE_MODULE, cacheModule);
|
||||
container.load(DI_TOKENS.CHECK_BOOKING_LIMITS_SERVICE_MODULE, checkBookingLimitsModule);
|
||||
container.load(DI_TOKENS.FEATURES_REPOSITORY_MODULE, featuresRepositoryModule);
|
||||
container.load(
|
||||
DI_TOKENS.CHECK_BOOKING_AND_DURATION_LIMITS_SERVICE_MODULE,
|
||||
checkBookingAndDurationLimitsModule
|
||||
);
|
||||
container.load(DI_TOKENS.RECURRING_BOOKING_SERVICE_MODULE, recurringBookingServiceModule);
|
||||
|
||||
export function getRecurringBookingService(): RecurringBookingService {
|
||||
return container.get<RecurringBookingService>(DI_TOKENS.RECURRING_BOOKING_SERVICE);
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
import { InstantBookingCreateService } from "@calcom/features/instant-meeting/handleInstantMeeting";
|
||||
import { DI_TOKENS } from "@calcom/features/di/tokens";
|
||||
|
||||
import { createModule } from "../../di";
|
||||
|
||||
export const instantBookingCreateServiceModule = createModule();
|
||||
|
||||
instantBookingCreateServiceModule
|
||||
.bind(DI_TOKENS.INSTANT_BOOKING_CREATE_SERVICE)
|
||||
.toClass(InstantBookingCreateService);
|
||||
export type { InstantBookingCreateService };
|
||||
@@ -1,12 +0,0 @@
|
||||
import { RecurringBookingService } from "@calcom/features/bookings/lib/handleNewRecurringBooking";
|
||||
import { DI_TOKENS } from "@calcom/features/di/tokens";
|
||||
|
||||
import { createModule } from "../../di";
|
||||
|
||||
export const recurringBookingServiceModule = createModule();
|
||||
|
||||
recurringBookingServiceModule.bind(DI_TOKENS.RECURRING_BOOKING_SERVICE).toClass(RecurringBookingService, {
|
||||
regularBookingService: DI_TOKENS.REGULAR_BOOKING_SERVICE,
|
||||
});
|
||||
|
||||
export type { RecurringBookingService };
|
||||
@@ -1,4 +1,4 @@
|
||||
import { BOOKING_DI_TOKENS } from "./bookings/tokens";
|
||||
import { BOOKING_DI_TOKENS } from "@calcom/features/bookings/di/tokens";
|
||||
|
||||
export const DI_TOKENS = {
|
||||
PRISMA_CLIENT: Symbol("PrismaClient"),
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
import type { NextApiRequest } from "next";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
import { getInstantBookingCreateService } from "@calcom/features/bookings/di/InstantBookingCreateService.container";
|
||||
import { BookingStatus } from "@calcom/prisma/enums";
|
||||
|
||||
vi.mock("@calcom/features/notifications/sendNotification", () => ({
|
||||
@@ -35,7 +36,7 @@ describe("handleInstantMeeting", () => {
|
||||
});
|
||||
describe("team event instant meeting", () => {
|
||||
it("should successfully create instant meeting for team event", async () => {
|
||||
const handler = (await import("./handleInstantMeeting")).default;
|
||||
const instantBookingCreateService = getInstantBookingCreateService();
|
||||
const organizer = getOrganizer({
|
||||
name: "Organizer",
|
||||
email: "[email protected]",
|
||||
@@ -109,7 +110,9 @@ describe("handleInstantMeeting", () => {
|
||||
url: "/api/instant-meeting",
|
||||
} as NextApiRequest;
|
||||
|
||||
const result = await handler(mockRequest);
|
||||
const result = await instantBookingCreateService.createBooking({
|
||||
bookingData: mockRequest.body,
|
||||
});
|
||||
|
||||
expect(result.message).toBe("Success");
|
||||
expect(result.bookingId).toBeDefined();
|
||||
@@ -132,7 +135,7 @@ describe("handleInstantMeeting", () => {
|
||||
});
|
||||
|
||||
it("should throw error for non-team event types", async () => {
|
||||
const handler = (await import("./handleInstantMeeting")).default;
|
||||
const instantBookingCreateService = getInstantBookingCreateService();
|
||||
const organizer = getOrganizer({
|
||||
name: "Organizer",
|
||||
email: "[email protected]",
|
||||
@@ -188,9 +191,11 @@ describe("handleInstantMeeting", () => {
|
||||
url: "/api/instant-meeting",
|
||||
} as NextApiRequest;
|
||||
|
||||
await expect(handler(mockRequest)).rejects.toThrow(
|
||||
"Only Team Event Types are supported for Instant Meeting"
|
||||
);
|
||||
await expect(
|
||||
instantBookingCreateService.createBooking({
|
||||
bookingData: mockRequest.body,
|
||||
})
|
||||
).rejects.toThrow("Only Team Event Types are supported for Instant Meeting");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { randomBytes } from "crypto";
|
||||
import type { NextApiRequest } from "next";
|
||||
import short from "short-uuid";
|
||||
import { v5 as uuidv5 } from "uuid";
|
||||
|
||||
import { createInstantMeetingWithCalVideo } from "@calcom/app-store/videoClient";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import type {
|
||||
CreateInstantBookingData,
|
||||
CreateInstantBookingResponse,
|
||||
InstantBookingCreateResult,
|
||||
} from "@calcom/features/bookings/lib/dto/types";
|
||||
import getBookingDataSchema from "@calcom/features/bookings/lib/getBookingDataSchema";
|
||||
import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/getBookingFields";
|
||||
@@ -22,7 +22,6 @@ 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 { createInstantMeetingWithCalVideo } from "@calcom/app-store/videoClient";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { Prisma } from "@calcom/prisma/client";
|
||||
import { BookingStatus, WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
@@ -156,7 +155,7 @@ const triggerBrowserNotifications = async (args: {
|
||||
await Promise.allSettled(promises);
|
||||
};
|
||||
|
||||
async function _handler(bookingData: CreateInstantBookingData) {
|
||||
async function handler(bookingData: CreateInstantBookingData) {
|
||||
let eventType = await getEventTypesFromDB(bookingData.eventTypeId);
|
||||
const isOrgTeamEvent = !!eventType?.team && !!eventType?.team?.parentId;
|
||||
eventType = {
|
||||
@@ -330,21 +329,14 @@ async function _handler(bookingData: CreateInstantBookingData) {
|
||||
bookingUid: newBooking.uid,
|
||||
expires: instantMeetingToken.expires,
|
||||
userId: newBooking.userId,
|
||||
} satisfies CreateInstantBookingResponse;
|
||||
} satisfies InstantBookingCreateResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Instant booking service that handles instant/immediate bookings
|
||||
*/
|
||||
export class InstantBookingCreateService implements IBookingCreateService {
|
||||
async createBooking(input: {
|
||||
bookingData: CreateInstantBookingData;
|
||||
}): Promise<CreateInstantBookingResponse> {
|
||||
return _handler(input.bookingData);
|
||||
async createBooking(input: { bookingData: CreateInstantBookingData }): Promise<InstantBookingCreateResult> {
|
||||
return handler(input.bookingData);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Remove it in a follow-up PR
|
||||
export default async function handler(req: NextApiRequest) {
|
||||
return _handler(req.body);
|
||||
}
|
||||
@@ -1,3 +1,10 @@
|
||||
export { LuckyUserService } from "@calcom/features/bookings/lib/getLuckyUser";
|
||||
export { CheckBookingLimitsService } from "@calcom/lib/intervalLimits/server/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 type {
|
||||
InstantBookingCreateResult,
|
||||
RegularBookingCreateResult,
|
||||
} from "@calcom/features/bookings/lib/dto/types";
|
||||
@@ -2,7 +2,6 @@ import { getBookingForReschedule } from "@calcom/features/bookings/lib/get-booki
|
||||
import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/getBookingFields";
|
||||
import getBookingInfo from "@calcom/features/bookings/lib/getBookingInfo";
|
||||
import handleCancelBooking from "@calcom/features/bookings/lib/handleCancelBooking";
|
||||
import * as newBookingMethods from "@calcom/features/bookings/lib/handleNewBooking";
|
||||
import { getClientSecretFromPayment } from "@calcom/features/ee/payments/pages/getClientSecretFromPayment";
|
||||
import { getTeamMemberEmailForResponseOrContactUsingUrlQuery } from "@calcom/features/ee/teams/lib/getTeamMemberEmailFromCrm";
|
||||
import {
|
||||
@@ -11,7 +10,6 @@ import {
|
||||
} from "@calcom/features/ee/workflows/lib/reminders/verifyPhoneNumber";
|
||||
import { handleCreatePhoneCall } from "@calcom/features/handleCreatePhoneCall";
|
||||
import handleMarkNoShow from "@calcom/features/handleMarkNoShow";
|
||||
import * as instantMeetingMethods from "@calcom/features/instant-meeting/handleInstantMeeting";
|
||||
import { getRoutedUrl } from "@calcom/features/routing-forms/lib/getRoutedUrl";
|
||||
import getAllUserBookings from "@calcom/lib/bookings/getAllUserBookings";
|
||||
import { symmetricEncrypt, symmetricDecrypt } from "@calcom/lib/crypto";
|
||||
@@ -41,16 +39,9 @@ export {
|
||||
|
||||
export { getUsernameList } from "@calcom/features/eventtypes/lib/defaultEvents";
|
||||
|
||||
const handleNewBooking = newBookingMethods.default;
|
||||
export { handleNewBooking };
|
||||
const handleInstantMeeting = instantMeetingMethods.default;
|
||||
export { handleInstantMeeting };
|
||||
|
||||
export { handleMarkNoShow };
|
||||
export { handleCreatePhoneCall };
|
||||
|
||||
export { handleNewRecurringBooking } from "@calcom/features/bookings/lib/handleNewRecurringBooking";
|
||||
|
||||
export { getConnectedDestinationCalendarsAndEnsureDefaultsInDb } from "@calcom/features/calendars/lib/getConnectedDestinationCalendars";
|
||||
|
||||
export { getBusyCalendarTimes } from "@calcom/features/calendars/lib/CalendarManager";
|
||||
|
||||
Reference in new issue
Block a user