Scheduling infrastructure for absolutely everyone.
fix: Handle more dry-run cases (#18286)
Hariom Balharad2930bc2435b
diff --git a/apps/web/app/booking/dry-run-successful/page.tsx b/apps/web/app/booking/dry-run-successful/page.tsxnew file mode 100644index 00000000000..0749c15a924--- /dev/null+++ b/apps/web/app/booking/dry-run-successful/page.tsx@@ -0,0 +1,17 @@+import { _generateMetadata } from "app/_utils";+import { WithLayout } from "app/layoutHOC";++import BookingDryRunSuccessView from "~/bookings/views/booking-dry-run-success-view";++export const generateMetadata = async () => {+ return await _generateMetadata(+ (t) => t("booking_dry_run_successful"),+ (t) => t("booking_dry_run_successful_description")+ );+};++const Page = async () => {+ return <BookingDryRunSuccessView />;+};++export default WithLayout({ ServerPage: Page });diff --git a/apps/web/modules/bookings/views/booking-dry-run-success-view.tsx b/apps/web/modules/bookings/views/booking-dry-run-success-view.tsxnew file mode 100644index 00000000000..6c3228752b1--- /dev/null+++ b/apps/web/modules/bookings/views/booking-dry-run-success-view.tsx@@ -0,0 +1,76 @@+"use client";++import { useLocale } from "@calcom/lib/hooks/useLocale";+import { Icon } from "@calcom/ui";++export default function DryRunSuccessful() {+ const { t } = useLocale();++ const sampleBookingInfo = {+ startTime: "2024-01-20T10:00:00Z",+ endTime: "2024-01-20T11:00:00Z",+ title: "Sample Meeting",+ description: "This is a sample dry run booking",+ attendees: [+ {+ email: "[email protected]",+ name: "Sample Attendee",+ timeZone: "America/New_York",+ },+ ],+ user: {+ name: "Sample Host",+ email: "[email protected]",+ },+ location: "Zoom Meeting",+ status: "ACCEPTED",+ uid: "sample-uid",+ };++ const sampleEventType = {+ title: "Sample Event Type",+ length: 60,+ eventName: "Sample Meeting",+ description: "This is a sample event type for dry run",+ requiresConfirmation: false,+ recurringEvent: null,+ };++ return (+ <div className="flex h-screen">+ <div className="bg-default m-auto rounded-md p-10 text-center">+ <div className="bg-success mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full">+ <Icon name="check" className="h-6 w-6 text-green-600 dark:text-green-400" />+ </div>+ <h1 className="text-emphasis mb-4 text-2xl font-medium">{t("booking_dry_run_successful")}</h1>+ <p className="text-default mb-8 max-w-2xl text-sm">{t("booking_dry_run_successful_description")}</p>++ {/* <div className="border-subtle text-default mt-8 grid grid-cols-3 border-t pt-8 text-left">+ <div className="font-medium">{t("what")}</div>+ <div className="col-span-2 mb-6">{sampleBookingInfo.title}</div>++ <div className="font-medium">{t("when")}</div>+ <div className="col-span-2 mb-6">{new Date(sampleBookingInfo.startTime).toLocaleString()}</div>++ <div className="font-medium">{t("who")}</div>+ <div className="col-span-2 mb-6">+ <div className="mb-3">+ <div>+ <span className="mr-2">{sampleBookingInfo.user.name}</span>+ <Badge variant="blue">{t("Host")}</Badge>+ </div>+ <p className="text-default">{sampleBookingInfo.user.email}</p>+ </div>+ <div>+ <p>{sampleBookingInfo.attendees[0].name}</p>+ <p>{sampleBookingInfo.attendees[0].email}</p>+ </div>+ </div>++ <div className="font-medium">{t("where")}</div>+ <div className="col-span-2 mb-6">{sampleBookingInfo.location}</div>+ </div> */}+ </div>+ </div>+ );+}diff --git a/apps/web/public/static/locales/en/common.json b/apps/web/public/static/locales/en/common.jsonindex f1a21d53d17..482b6153daa 100644--- a/apps/web/public/static/locales/en/common.json+++ b/apps/web/public/static/locales/en/common.json@@ -2815,6 +2815,7 @@"salesforce_owner_name_to_change": "Owner name to change","no_filter_set": "No filter set","booking_dry_run_successful": "Booking dry run successful",+ "booking_dry_run_successful_description": "The dry run was completed successfully.","dont_have_access_this_page": "You don't have access to this page","you_need_admin_or_owner_privileges_to_access": "In order to view or interact with this page, you must have admin or owner privileges","field_type": "Field type",diff --git a/packages/features/bookings/Booker/components/hooks/useBookings.ts b/packages/features/bookings/Booker/components/hooks/useBookings.tsindex 875475a7436..cafb2c67404 100644--- a/packages/features/bookings/Booker/components/hooks/useBookings.ts+++ b/packages/features/bookings/Booker/components/hooks/useBookings.ts@@ -181,7 +181,7 @@ export const useBookings = ({ event, hashedLink, bookingForm, metadata, teamMembmutationFn: createBooking,onSuccess: (booking) => {if (booking.isDryRun) {- showToast(t("booking_dry_run_successful"), "success");+ router.push("/booking/dry-run-successful");return;}const { uid, paymentUid } = booking;@@ -311,7 +311,7 @@ export const useBookings = ({ event, hashedLink, bookingForm, metadata, teamMembconst booking = bookings[0] || {};if (booking.isDryRun) {- showToast(t("booking_dry_run_successful"), "success");+ router.push("/booking/dry-run-successful");return;}diff --git a/packages/features/bookings/lib/handleConfirmation.ts b/packages/features/bookings/lib/handleConfirmation.tsindex 2254bba6edf..75510ed52ec 100644--- a/packages/features/bookings/lib/handleConfirmation.ts+++ b/packages/features/bookings/lib/handleConfirmation.ts@@ -89,7 +89,6 @@ export async function handleConfirmation(args: {const scheduleResult = await eventManager.create(evt);const results = scheduleResult.results;const metadata: AdditionalInformation = {};-const workflows = await getAllWorkflowsFromEventType(eventType, booking.userId);if (results.length > 0 && results.every((res) => !res.success)) {@@ -339,14 +338,14 @@ export async function handleConfirmation(args: {const isFirstBooking = index === 0;if (!eventTypeMetadata?.disableStandardEmails?.all?.attendee) {- await scheduleMandatoryReminder(- evtOfBooking,+ await scheduleMandatoryReminder({+ evt: evtOfBooking,workflows,- false,- !!updatedBookings[index].eventType?.owner?.hideBranding,- evt.attendeeSeatId,- !emailsEnabled && Boolean(platformClientParams?.platformClientId)- );+ requiresConfirmation: false,+ hideBranding: !!updatedBookings[index].eventType?.owner?.hideBranding,+ seatReferenceUid: evt.attendeeSeatId,+ isPlatformNoEmail: !emailsEnabled && Boolean(platformClientParams?.platformClientId),+ });}await scheduleWorkflowReminders({diff --git a/packages/features/bookings/lib/handleNewBooking.ts b/packages/features/bookings/lib/handleNewBooking.tsindex e378ad231b9..b87dac07fe4 100644--- a/packages/features/bookings/lib/handleNewBooking.ts+++ b/packages/features/bookings/lib/handleNewBooking.ts@@ -1109,6 +1109,7 @@ async function handler(responses,workflows,rescheduledBy: reqBody.rescheduledBy,+ isDryRun,});if (newBooking) {@@ -1778,15 +1779,16 @@ async function handler(// Convert type of eventTypePaymentAppCredential to appId: EventTypeAppListif (!booking.user) booking.user = organizerUser;- const payment = await handlePayment(+ const payment = await handlePayment({evt,- eventType,- eventTypePaymentAppCredential as IEventTypePaymentCredentialType,+ selectedEventType: eventType,+ paymentAppCredentials: eventTypePaymentAppCredential as IEventTypePaymentCredentialType,booking,- fullName,+ bookerName: fullName,bookerEmail,- bookerPhoneNumber- );+ bookerPhoneNumber,+ isDryRun,+ });const subscriberOptionsPaymentInitiated: GetSubscriberOptions = {userId: triggerForUser ? organizerUser.id : null,eventTypeId,@@ -1802,6 +1804,7 @@ async function handler(...webhookData,paymentId: payment?.id,},+ isDryRun,});req.statusCode = 201;@@ -1844,6 +1847,7 @@ async function handler(//delete all scheduled triggers for meeting ended and meeting started of bookingdeleteWebhookScheduledTriggerPromise = deleteWebhookScheduledTriggers({booking: originalRescheduledBooking,+ isDryRun,});}@@ -1855,6 +1859,7 @@ async function handler(subscriberUrl: subscriber.subscriberUrl,subscriber,triggerEvent: WebhookTriggerEvents.MEETING_ENDED,+ isDryRun,}));}@@ -1866,6 +1871,7 @@ async function handler(subscriberUrl: subscriber.subscriberUrl,subscriber,triggerEvent: WebhookTriggerEvents.MEETING_STARTED,+ isDryRun,}));}@@ -1879,13 +1885,23 @@ async function handler(});// Send Webhook call if hooked to BOOKING_CREATED & BOOKING_RESCHEDULED- await monitorCallbackAsync(handleWebhookTrigger, { subscriberOptions, eventTrigger, webhookData });+ await monitorCallbackAsync(handleWebhookTrigger, {+ subscriberOptions,+ eventTrigger,+ webhookData,+ isDryRun,+ });} else {// if eventType requires confirmation we will trigger the BOOKING REQUESTED Webhookconst eventTrigger: WebhookTriggerEvents = WebhookTriggerEvents.BOOKING_REQUESTED;subscriberOptions.triggerEvent = eventTrigger;webhookData.status = "PENDING";- await monitorCallbackAsync(handleWebhookTrigger, { subscriberOptions, eventTrigger, webhookData });+ await monitorCallbackAsync(handleWebhookTrigger, {+ subscriberOptions,+ eventTrigger,+ webhookData,+ isDryRun,+ });}try {@@ -1931,14 +1947,15 @@ async function handler(};if (!eventType.metadata?.disableStandardEmails?.all?.attendee) {- await scheduleMandatoryReminder(- evtWithMetadata,+ await scheduleMandatoryReminder({+ evt: evtWithMetadata,workflows,- !isConfirmedByDefault,- !!eventType.owner?.hideBranding,- evt.attendeeSeatId,- noEmail && Boolean(platformClientId)- );+ requiresConfirmation: !isConfirmedByDefault,+ hideBranding: !!eventType.owner?.hideBranding,+ seatReferenceUid: evt.attendeeSeatId,+ isPlatformNoEmail: noEmail && Boolean(platformClientId),+ isDryRun,+ });}try {@@ -1951,6 +1968,7 @@ async function handler(isFirstRecurringEvent: req.body.allRecurringDates ? req.body.isFirstRecurringSlot : undefined,hideBranding: !!eventType.owner?.hideBranding,seatReferenceUid: evt.attendeeSeatId,+ isDryRun,});} catch (error) {loggerWithEventDetails.error("Error while scheduling workflow reminders", JSON.stringify({ error }));@@ -1965,6 +1983,7 @@ async function handler(eventTypeId,teamId,orgId,+ isDryRun,});}} catch (error) {diff --git a/packages/features/bookings/lib/handleNewBooking/scheduleNoShowTriggers.ts b/packages/features/bookings/lib/handleNewBooking/scheduleNoShowTriggers.tsindex 83664fcfa13..a716c56a8ee 100644--- a/packages/features/bookings/lib/handleNewBooking/scheduleNoShowTriggers.ts+++ b/packages/features/bookings/lib/handleNewBooking/scheduleNoShowTriggers.ts@@ -14,10 +14,22 @@ type ScheduleNoShowTriggersArgs = {teamId?: number | null;orgId?: number | null;oAuthClientId?: string | null;+ isDryRun?: boolean;};export const scheduleNoShowTriggers = async (args: ScheduleNoShowTriggersArgs) => {- const { booking, triggerForUser, organizerUser, eventTypeId, teamId, orgId, oAuthClientId } = args;+ const {+ booking,+ triggerForUser,+ organizerUser,+ eventTypeId,+ teamId,+ orgId,+ oAuthClientId,+ isDryRun = false,+ } = args;++ if (isDryRun) return;// Add task for automatic no show in cal videoconst noShowPromises: Promise<any>[] = [];diff --git a/packages/features/bookings/lib/handleSeats/create/createNewSeat.ts b/packages/features/bookings/lib/handleSeats/create/createNewSeat.tsindex 2de6dd853ce..0905d865ed7 100644--- a/packages/features/bookings/lib/handleSeats/create/createNewSeat.ts+++ b/packages/features/bookings/lib/handleSeats/create/createNewSeat.ts@@ -187,15 +187,15 @@ const createNewSeat = async (throw new HttpError({ statusCode: 400, message: ErrorCode.MissingPaymentAppId });}- const payment = await handlePayment(+ const payment = await handlePayment({evt,- eventType,- eventTypePaymentAppCredential as IEventTypePaymentCredentialType,- seatedBooking,- fullName,+ selectedEventType: eventType,+ paymentAppCredentials: eventTypePaymentAppCredential as IEventTypePaymentCredentialType,+ booking: seatedBooking,+ bookerName: fullName,bookerEmail,- bookerPhoneNumber- );+ bookerPhoneNumber,+ });resultBooking = { ...foundBooking };resultBooking["message"] = "Payment required";diff --git a/packages/features/bookings/lib/handleSeats/handleSeats.ts b/packages/features/bookings/lib/handleSeats/handleSeats.tsindex 6705e9e0f5a..c4d4b672ace 100644--- a/packages/features/bookings/lib/handleSeats/handleSeats.ts+++ b/packages/features/bookings/lib/handleSeats/handleSeats.ts@@ -32,8 +32,10 @@ const handleSeats = async (newSeatedBookingObject: NewSeatedBookingObject) => {evt,workflows,rescheduledBy,+ isDryRun = false,} = newSeatedBookingObject;-+ // TODO: We could allow doing more things to support good dry run for seats+ if (isDryRun) return;const loggerWithEventDetails = createLoggerWithEventDetails(eventType.id, reqBodyUser, eventType.slug);let resultBooking: HandleSeatsResultBooking = null;@@ -124,6 +126,7 @@ const handleSeats = async (newSeatedBookingObject: NewSeatedBookingObject) => {isFirstRecurringEvent: true,emailAttendeeSendToOverride: bookerEmail,seatReferenceUid: evt.attendeeSeatId,+ isDryRun,});} catch (error) {loggerWithEventDetails.error("Error while scheduling workflow reminders", JSON.stringify({ error }));@@ -149,7 +152,7 @@ const handleSeats = async (newSeatedBookingObject: NewSeatedBookingObject) => {rescheduledBy,};- await handleWebhookTrigger({ subscriberOptions, eventTrigger, webhookData });+ await handleWebhookTrigger({ subscriberOptions, eventTrigger, webhookData, isDryRun });}return resultBooking;diff --git a/packages/features/bookings/lib/handleSeats/types.d.ts b/packages/features/bookings/lib/handleSeats/types.d.tsindex 3eb691c6371..cf67e2d7447 100644--- a/packages/features/bookings/lib/handleSeats/types.d.ts+++ b/packages/features/bookings/lib/handleSeats/types.d.ts@@ -43,6 +43,7 @@ export type NewSeatedBookingObject = {responses: z.infer<ReturnType<typeof getBookingDataSchema>>["responses"] | null;rescheduledBy?: string;workflows: Workflow[];+ isDryRun?: boolean;};export type RescheduleSeatedBookingObject = NewSeatedBookingObject & { rescheduleUid: string };diff --git a/packages/features/bookings/lib/handleWebhookTrigger.ts b/packages/features/bookings/lib/handleWebhookTrigger.tsindex abbcc855821..53758177af5 100644--- a/packages/features/bookings/lib/handleWebhookTrigger.ts+++ b/packages/features/bookings/lib/handleWebhookTrigger.ts@@ -9,8 +9,10 @@ export async function handleWebhookTrigger(args: {subscriberOptions: GetSubscriberOptions;eventTrigger: string;webhookData: WebhookPayloadType;+ isDryRun?: boolean;}) {try {+ if (args.isDryRun) return;const subscribers = await getWebhooks(args.subscriberOptions);const promises = subscribers.map((sub) =>diff --git a/packages/features/ee/workflows/lib/reminders/reminderScheduler.ts b/packages/features/ee/workflows/lib/reminders/reminderScheduler.tsindex a345f514e87..cd8875f02d7 100644--- a/packages/features/ee/workflows/lib/reminders/reminderScheduler.ts+++ b/packages/features/ee/workflows/lib/reminders/reminderScheduler.ts@@ -37,6 +37,7 @@ export interface ScheduleWorkflowRemindersArgs extends ProcessWorkflowStepParamsisNotConfirmed?: boolean;isRescheduleEvent?: boolean;isFirstRecurringEvent?: boolean;+ isDryRun?: boolean;}const processWorkflowStep = async (@@ -159,7 +160,9 @@ export const scheduleWorkflowReminders = async (args: ScheduleWorkflowRemindersAemailAttendeeSendToOverride = "",hideBranding,seatReferenceUid,+ isDryRun = false,} = args;+ if (isDryRun) return;if (isNotConfirmed || !workflows.length) return;for (const workflow of workflows) {diff --git a/packages/features/ee/workflows/lib/reminders/scheduleMandatoryReminder.ts b/packages/features/ee/workflows/lib/reminders/scheduleMandatoryReminder.tsindex 06d6aa09447..a8b3ec15a14 100644--- a/packages/features/ee/workflows/lib/reminders/scheduleMandatoryReminder.ts+++ b/packages/features/ee/workflows/lib/reminders/scheduleMandatoryReminder.ts@@ -11,14 +11,24 @@ const log = logger.getSubLogger({ prefix: ["[scheduleMandatoryReminder]"] });export type NewBookingEventType = Awaited<ReturnType<typeof getDefaultEvent>> | getEventTypeResponse;-export async function scheduleMandatoryReminder(- evt: ExtendedCalendarEvent,- workflows: Workflow[],- requiresConfirmation: boolean,- hideBranding: boolean,- seatReferenceUid: string | undefined,- isPlatformNoEmail = false-) {+export async function scheduleMandatoryReminder({+ evt,+ workflows,+ requiresConfirmation,+ hideBranding,+ seatReferenceUid,+ isPlatformNoEmail = false,+ isDryRun = false,+}: {+ evt: ExtendedCalendarEvent;+ workflows: Workflow[];+ requiresConfirmation: boolean;+ hideBranding: boolean;+ seatReferenceUid: string | undefined;+ isPlatformNoEmail?: boolean;+ isDryRun?: boolean;+}) {+ if (isDryRun) return;if (isPlatformNoEmail) return;try {const hasExistingWorkflow = workflows.some((workflow) => {diff --git a/packages/features/webhooks/lib/scheduleTrigger.ts b/packages/features/webhooks/lib/scheduleTrigger.tsindex 6529e8e7994..65d7ffeea42 100644--- a/packages/features/webhooks/lib/scheduleTrigger.ts+++ b/packages/features/webhooks/lib/scheduleTrigger.ts@@ -246,12 +246,15 @@ export async function scheduleTrigger({subscriberUrl,subscriber,triggerEvent,+ isDryRun = false,}: {booking: { id: number; endTime: Date; startTime: Date };subscriberUrl: string;subscriber: { id: string; appId: string | null };triggerEvent: WebhookTriggerEvents;+ isDryRun?: boolean;}) {+ if (isDryRun) return;try {const payload = JSON.stringify({ triggerEvent, ...booking });@@ -285,6 +288,7 @@ export async function deleteWebhookScheduledTriggers({webhookId,userId,teamId,+ isDryRun = false,}: {booking?: { id: number; uid: string };appId?: string | null;@@ -292,7 +296,9 @@ export async function deleteWebhookScheduledTriggers({webhookId?: string;userId?: number;teamId?: number;+ isDryRun?: boolean;}) {+ if (isDryRun) return;try {if (appId && (userId || teamId)) {const where: Prisma.BookingWhereInput = {};diff --git a/packages/lib/payment/handlePayment.ts b/packages/lib/payment/handlePayment.tsindex ae4b8b27726..c0fb1c275bc 100644--- a/packages/lib/payment/handlePayment.ts+++ b/packages/lib/payment/handlePayment.ts@@ -7,9 +7,18 @@ import { eventTypeAppMetadataOptionalSchema } from "@calcom/prisma/zod-utils";import type { CalendarEvent } from "@calcom/types/Calendar";import type { IAbstractPaymentService, PaymentApp } from "@calcom/types/PaymentService";-const handlePayment = async (- evt: CalendarEvent,- selectedEventType: Pick<CompleteEventType, "metadata" | "title">,+const handlePayment = async ({+ evt,+ selectedEventType,+ paymentAppCredentials,+ booking,+ bookerName,+ bookerEmail,+ bookerPhoneNumber,+ isDryRun = false,+}: {+ evt: CalendarEvent;+ selectedEventType: Pick<CompleteEventType, "metadata" | "title">;paymentAppCredentials: {key: Prisma.JsonValue;appId: EventTypeAppsList;@@ -17,18 +26,20 @@ const handlePayment = async (dirName: string;categories: AppCategories[];} | null;- },+ };booking: {user: { email: string | null; name: string | null; timeZone: string; username: string | null } | null;id: number;userId: number | null;startTime: { toISOString: () => string };uid: string;- },- bookerName: string,- bookerEmail: string,- bookerPhoneNumber?: string | null-) => {+ };+ bookerName: string;+ bookerEmail: string;+ bookerPhoneNumber?: string | null;+ isDryRun?: boolean;+}) => {+ if (isDryRun) return null;const paymentApp = (await appStore[paymentAppCredentials?.app?.dirName as keyof typeof appStore]?.()) as PaymentApp;