test: Booking flow App failure and ics file tests and improved logging (#11646)

This commit is contained in:
Hariom Balhara authored and GitHub committed 2023-10-02 16:21:04 +05:30
1 parent 07bfaec24e
commit 3ca7456885
17 files changed
+513 -239

No files matched your search

@@ -147,7 +147,8 @@ describe("handleNewBooking", () => {
const calendarMock = mockCalendarToHaveNoBusySlots("googlecalendar", {
create: {
uid: "MOCK_ID",
id: "MOCKED_GOOGLE_CALENDAR_EVENT_ID",
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
},
});
@@ -193,8 +194,8 @@ describe("handleNewBooking", () => {
},
{
type: "google_calendar",
uid: "MOCK_ID",
meetingId: "MOCK_ID",
uid: "MOCKED_GOOGLE_CALENDAR_EVENT_ID",
meetingId: "MOCKED_GOOGLE_CALENDAR_EVENT_ID",
meetingPassword: "MOCK_PASSWORD",
meetingUrl: "https://UNUSED_URL",
},
@@ -207,7 +208,13 @@ describe("handleNewBooking", () => {
videoCallUrl: "http://mock-dailyvideo.example.com/meeting-1",
});
expectSuccessfulBookingCreationEmails({ booker, organizer, emails });
expectSuccessfulBookingCreationEmails({
booker,
organizer,
emails,
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
});
expectBookingCreatedWebhookToHaveBeenFired({
booker,
organizer,
@@ -281,9 +288,12 @@ describe("handleNewBooking", () => {
},
});
// Mock a Scenario where iCalUID isn't returned by Google Calendar in which case booking UID is used as the ics UID
const calendarMock = mockCalendarToHaveNoBusySlots("googlecalendar", {
create: {
id: "GOOGLE_CALENDAR_EVENT_ID",
uid: "MOCK_ID",
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
},
});
@@ -329,8 +339,8 @@ describe("handleNewBooking", () => {
},
{
type: "google_calendar",
uid: "MOCK_ID",
meetingId: "MOCK_ID",
uid: "GOOGLE_CALENDAR_EVENT_ID",
meetingId: "GOOGLE_CALENDAR_EVENT_ID",
meetingPassword: "MOCK_PASSWORD",
meetingUrl: "https://UNUSED_URL",
},
@@ -346,7 +356,12 @@ describe("handleNewBooking", () => {
calendarId: null,
});
expectSuccessfulBookingCreationEmails({ booker, organizer, emails });
expectSuccessfulBookingCreationEmails({
booker,
organizer,
emails,
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
});
expectBookingCreatedWebhookToHaveBeenFired({
booker,
organizer,
@@ -425,6 +440,8 @@ describe("handleNewBooking", () => {
const calendarMock = mockCalendarToHaveNoBusySlots("googlecalendar", {
create: {
uid: "MOCK_ID",
id: "GOOGLE_CALENDAR_EVENT_ID",
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
},
});
@@ -470,8 +487,8 @@ describe("handleNewBooking", () => {
},
{
type: "google_calendar",
uid: "MOCK_ID",
meetingId: "MOCK_ID",
uid: "GOOGLE_CALENDAR_EVENT_ID",
meetingId: "GOOGLE_CALENDAR_EVENT_ID",
meetingPassword: "MOCK_PASSWORD",
meetingUrl: "https://UNUSED_URL",
},
@@ -484,7 +501,13 @@ describe("handleNewBooking", () => {
videoCallUrl: "http://mock-dailyvideo.example.com/meeting-1",
});
expectSuccessfulBookingCreationEmails({ booker, organizer, emails });
expectSuccessfulBookingCreationEmails({
booker,
organizer,
emails,
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
});
expectBookingCreatedWebhookToHaveBeenFired({
booker,
organizer,
@@ -498,7 +521,7 @@ describe("handleNewBooking", () => {
test(
`an error in creating a calendar event should not stop the booking creation - Current behaviour is wrong as the booking is created but no-one is notified of it`,
async ({ emails }) => {
async ({}) => {
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
const booker = getBooker({
email: "[email protected]",
@@ -546,7 +569,7 @@ describe("handleNewBooking", () => {
})
);
const calendarMock = mockCalendarToCrashOnCreateEvent("googlecalendar");
const _calendarMock = mockCalendarToCrashOnCreateEvent("googlecalendar");
const mockBookingData = getMockRequestDataForBooking({
data: {
@@ -672,9 +695,15 @@ describe("handleNewBooking", () => {
},
}),
});
await handleNewBooking(req);
const createdBooking = await handleNewBooking(req);
expectSuccessfulBookingCreationEmails({ booker, organizer, emails });
expectSuccessfulBookingCreationEmails({
booker,
organizer,
emails,
// Because no calendar was involved, we don't have an ics UID
iCalUID: createdBooking.uid,
});
expectBookingCreatedWebhookToHaveBeenFired({
booker,
@@ -893,95 +922,10 @@ describe("handleNewBooking", () => {
})
);
const calendarMock = mockCalendar("googlecalendar", {
create: {
uid: "MOCK_ID",
},
busySlots: [
{
start: `${plus1DateString}T05:00:00.000Z`,
end: `${plus1DateString}T05:15:00.000Z`,
},
],
});
const mockBookingData = getMockRequestDataForBooking({
data: {
start: `${getDate({ dateIncrement: 1 }).dateString}T04:00:00.000Z`,
end: `${getDate({ dateIncrement: 1 }).dateString}T05:30:00.000Z`,
eventTypeId: 1,
responses: {
email: booker.email,
name: booker.name,
location: { optionValue: "", value: "New York" },
},
},
});
const { req } = createMockNextJsRequest({
method: "POST",
body: mockBookingData,
});
await expect(async () => await handleNewBooking(req)).rejects.toThrowError(
"No available users found"
);
},
timeout
);
test(
`should fail a booking if there is already a booking in the organizer's selectedCalendars(Single Calendar) with the overlapping time`,
async () => {
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
const organizerId = 101;
const booker = getBooker({
email: "[email protected]",
name: "Booker",
});
const organizer = getOrganizer({
name: "Organizer",
email: "[email protected]",
id: organizerId,
schedules: [TestData.schedules.IstWorkHours],
credentials: [getGoogleCalendarCredential()],
selectedCalendars: [TestData.selectedCalendars.google],
});
const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });
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: 45,
length: 45,
users: [
{
id: 101,
},
],
},
],
organizer,
apps: [TestData.apps["google-calendar"]],
})
);
const calendarMock = mockCalendar("googlecalendar", {
const _calendarMock = mockCalendar("googlecalendar", {
create: {
uid: "MOCK_ID",
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
},
busySlots: [
{
@@ -1075,7 +1019,11 @@ describe("handleNewBooking", () => {
metadataLookupKey: "dailyvideo",
});
mockCalendarToHaveNoBusySlots("googlecalendar");
mockCalendarToHaveNoBusySlots("googlecalendar", {
create: {
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
},
});
const mockBookingData = getMockRequestDataForBooking({
data: {
@@ -1193,7 +1141,11 @@ describe("handleNewBooking", () => {
metadataLookupKey: "dailyvideo",
});
mockCalendarToHaveNoBusySlots("googlecalendar");
mockCalendarToHaveNoBusySlots("googlecalendar", {
create: {
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
},
});
const mockBookingData = getMockRequestDataForBooking({
data: {
@@ -1231,7 +1183,12 @@ describe("handleNewBooking", () => {
expectWorkflowToBeTriggered();
expectSuccessfulBookingCreationEmails({ booker, organizer, emails });
expectSuccessfulBookingCreationEmails({
booker,
organizer,
emails,
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
});
expectBookingCreatedWebhookToHaveBeenFired({
booker,
@@ -1306,7 +1263,11 @@ describe("handleNewBooking", () => {
metadataLookupKey: "dailyvideo",
});
mockCalendarToHaveNoBusySlots("googlecalendar");
mockCalendarToHaveNoBusySlots("googlecalendar", {
create: {
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
},
});
const mockBookingData = getMockRequestDataForBooking({
data: {
@@ -1489,7 +1450,11 @@ describe("handleNewBooking", () => {
apps: [TestData.apps["google-calendar"], TestData.apps["daily-video"]],
});
mockCalendarToHaveNoBusySlots("googlecalendar");
mockCalendarToHaveNoBusySlots("googlecalendar", {
create: {
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
},
});
await createBookingScenario(scenarioData);
const createdBooking = await handleNewBooking(req);
@@ -1512,7 +1477,12 @@ describe("handleNewBooking", () => {
expectWorkflowToBeTriggered();
expectSuccessfulBookingCreationEmails({ booker, organizer, emails });
expectSuccessfulBookingCreationEmails({
booker,
organizer,
emails,
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
});
expectBookingCreatedWebhookToHaveBeenFired({
booker,
organizer,
@@ -1918,6 +1888,7 @@ describe("handleNewBooking", () => {
},
update: {
uid: "UPDATED_MOCK_ID",
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
},
});
@@ -2027,7 +1998,12 @@ describe("handleNewBooking", () => {
uid: "MOCK_ID",
});
expectSuccessfulBookingRescheduledEmails({ booker, organizer, emails });
expectSuccessfulBookingRescheduledEmails({
booker,
organizer,
emails,
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
});
expectBookingRescheduledWebhookToHaveBeenFired({
booker,
organizer,
@@ -2132,6 +2108,7 @@ describe("handleNewBooking", () => {
uid: "MOCK_ID",
},
update: {
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
uid: "UPDATED_MOCK_ID",
},
});
@@ -2223,7 +2200,12 @@ describe("handleNewBooking", () => {
uid: "MOCK_ID",
});
expectSuccessfulBookingRescheduledEmails({ booker, organizer, emails });
expectSuccessfulBookingRescheduledEmails({
booker,
organizer,
emails,
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
});
expectBookingRescheduledWebhookToHaveBeenFired({
booker,
organizer,
@@ -2237,7 +2219,7 @@ describe("handleNewBooking", () => {
test(
`an error in updating a calendar event should not stop the rescheduling - Current behaviour is wrong as the booking is resheduled but no-one is notified of it`,
async ({ emails }) => {
async ({}) => {
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
const booker = getBooker({
email: "[email protected]",
@@ -2315,7 +2297,7 @@ describe("handleNewBooking", () => {
})
);
const calendarMock = mockCalendarToCrashOnUpdateEvent("googlecalendar");
const _calendarMock = mockCalendarToCrashOnUpdateEvent("googlecalendar");
const mockBookingData = getMockRequestDataForBooking({
data: {
@@ -35,6 +35,7 @@ import {
import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/getBookingFields";
import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";
import { handleWebhookTrigger } from "@calcom/features/bookings/lib/handleWebhookTrigger";
import { isEventTypeLoggingEnabled } from "@calcom/features/bookings/lib/isEventTypeLoggingEnabled";
import { userOrgQuery } from "@calcom/features/ee/organizations/lib/orgDomains";
import {
allowDisablingAttendeeConfirmationEmails,
@@ -60,6 +61,7 @@ import { HttpError } from "@calcom/lib/http-error";
import isOutOfBounds, { BookingDateInPastError } from "@calcom/lib/isOutOfBounds";
import logger from "@calcom/lib/logger";
import { handlePayment } from "@calcom/lib/payment/handlePayment";
import { getPiiFreeCalendarEvent, getPiiFreeEventType, getPiiFreeUser } from "@calcom/lib/piiFreeData";
import { safeStringify } from "@calcom/lib/safeStringify";
import { checkBookingLimits, checkDurationLimits, getLuckyUser } from "@calcom/lib/server";
import { getBookerUrl } from "@calcom/lib/server/getBookerUrl";
@@ -688,25 +690,14 @@ async function handler(
prefix: ["book:user", `${eventTypeId}:${reqBody.user}/${eventTypeSlug}`],
});
if (isLoggingEnabled({ eventTypeId, usernameOrTeamName: reqBody.user })) {
if (isEventTypeLoggingEnabled({ eventTypeId, usernameOrTeamName: reqBody.user })) {
logger.setSettings({ minLevel: "silly" });
}
loggerWithEventDetails.debug(
"handleNewBooking called",
JSON.stringify({
eventTypeId,
eventTypeSlug,
startTime: reqBody.start,
endTime: reqBody.end,
rescheduleUid: reqBody.rescheduleUid,
})
);
const fullName = getFullName(bookerName);
const tGuests = await getTranslation("en", "common");
loggerWithEventDetails.debug(`Booking eventType ${eventTypeId} started`);
const dynamicUserList = Array.isArray(reqBody.user) ? reqBody.user : getUsernameList(reqBody.user);
if (!eventType) throw new HttpError({ statusCode: 404, message: "eventType.notFound" });
@@ -714,6 +705,30 @@ async function handler(
!!eventType.schedulingType && ["COLLECTIVE", "ROUND_ROBIN"].includes(eventType.schedulingType);
const paymentAppData = getPaymentAppData(eventType);
loggerWithEventDetails.debug(
`Booking eventType ${eventTypeId} started`,
safeStringify({
reqBody: {
user: reqBody.user,
eventTypeId,
eventTypeSlug,
startTime: reqBody.start,
endTime: reqBody.end,
rescheduleUid: reqBody.rescheduleUid,
location: location,
},
isTeamEventType,
eventType: getPiiFreeEventType(eventType),
dynamicUserList,
paymentAppData: {
enabled: paymentAppData.enabled,
price: paymentAppData.price,
paymentOption: paymentAppData.paymentOption,
currency: paymentAppData.currency,
appId: paymentAppData.appId,
},
})
);
let timeOutOfBounds = false;
try {
@@ -837,6 +852,13 @@ async function handler(
: user.isFixed || eventType.schedulingType !== SchedulingType.ROUND_ROBIN,
}));
loggerWithEventDetails.debug(
"Concerned users",
safeStringify({
users: users.map(getPiiFreeUser),
})
);
let locationBodyString = location;
// TODO: It's definition should be moved to getLocationValueForDb
@@ -921,6 +943,13 @@ async function handler(
const luckyUsers: typeof users = [];
const luckyUserPool = availableUsers.filter((user) => !user.isFixed);
loggerWithEventDetails.debug(
"Computed available users",
safeStringify({
availableUsers: availableUsers.map((user) => user.id),
luckyUserPool: luckyUserPool.map((user) => user.id),
})
);
// loop through all non-fixed hosts and get the lucky users
while (luckyUserPool.length > 0 && luckyUsers.length < 1 /* TODO: Add variable */) {
const newLuckyUser = await getLuckyUser("MAXIMIZE_AVAILABILITY", {
@@ -946,6 +975,7 @@ async function handler(
}
const [organizerUser] = users;
const tOrganizer = await getTranslation(organizerUser?.locale ?? "en", "common");
const allCredentials = await getAllCredentials(organizerUser, eventType);
@@ -1988,6 +2018,17 @@ async function handler(
type Booking = Prisma.PromiseReturnType<typeof createBooking>;
let booking: (Booking & { appsStatus?: AppsStatus[] }) | null = null;
loggerWithEventDetails.debug(
"Going to create booking in DB now",
safeStringify({
organizerUser: organizerUser.id,
attendeesList: attendeesList.map((guest) => ({ timeZone: guest.timeZone })),
requiresConfirmation,
isConfirmedByDefault,
userReschedulingIsOwner,
})
);
try {
booking = await createBooking();
@@ -2177,7 +2218,7 @@ async function handler(
};
loggerWithEventDetails.error(
`Booking ${organizerUser.username} failed`,
`Failure in creating events in some of the integrations ${organizerUser.username} failed`,
safeStringify({ error, results })
);
} else {
@@ -2201,6 +2242,7 @@ async function handler(
const googleCalResult = results[googleCalIndex];
if (!googleCalResult) {
loggerWithEventDetails.warn("Google Calendar not installed but using Google Meet as location");
results.push({
...googleMeetResult,
success: false,
@@ -2263,6 +2305,12 @@ async function handler(
}
}
loggerWithEventDetails.debug(
"Sending scheduled emails for booking confirmation",
safeStringify({
calEvent: getPiiFreeCalendarEvent(evt),
})
);
await sendScheduledEmails(
{
...evt,
@@ -2285,9 +2333,16 @@ async function handler(
!!booking;
if (!isConfirmedByDefault && noEmail !== true && !bookingRequiresPayment) {
loggerWithEventDetails.debug(
`Booking ${organizerUser.username} requires confirmation, sending request emails`,
safeStringify({
calEvent: getPiiFreeCalendarEvent(evt),
})
);
await sendOrganizerRequestEmail({ ...evt, additionalNotes });
await sendAttendeeRequestEmail({ ...evt, additionalNotes }, attendeesList[0]);
}
const metadata = videoCallUrl
? {
videoCallUrl: getVideoCallUrlFromCalEvent(evt),
@@ -2311,6 +2366,7 @@ async function handler(
};
if (bookingRequiresPayment) {
loggerWithEventDetails.debug(`Booking ${organizerUser.username} requires payment`);
// Load credentials.app.categories
const credentialPaymentAppCategories = await prisma.credential.findMany({
where: {
@@ -2555,31 +2611,3 @@ const findBookingQuery = async (bookingId: number) => {
// Don't leak any sensitive data
return foundBooking;
};
function isLoggingEnabled({
eventTypeId,
usernameOrTeamName,
}: {
eventTypeId?: number | null;
usernameOrTeamName?: string | string[];
}) {
const usernameOrTeamnamesList =
usernameOrTeamName instanceof Array ? usernameOrTeamName : [usernameOrTeamName];
// eslint-disable-next-line turbo/no-undeclared-env-vars
const bookingLoggingEventIds = process.env.BOOKING_LOGGING_EVENT_IDS || "";
const isEnabled = bookingLoggingEventIds.split(",").some((id) => {
if (Number(id.trim()) === eventTypeId) {
return true;
}
});
if (isEnabled) {
return true;
}
// eslint-disable-next-line turbo/no-undeclared-env-vars
const bookingLoggingUsername = process.env.BOOKING_LOGGING_USER_OR_TEAM_NAME || "";
return bookingLoggingUsername.split(",").some((u) => {
return usernameOrTeamnamesList.some((foundUsername) => foundUsername === u.trim());
});
}
@@ -0,0 +1,27 @@
export function isEventTypeLoggingEnabled({
eventTypeId,
usernameOrTeamName,
}: {
eventTypeId?: number | null;
usernameOrTeamName?: string | string[];
}) {
const usernameOrTeamnamesList =
usernameOrTeamName instanceof Array ? usernameOrTeamName : [usernameOrTeamName];
// eslint-disable-next-line turbo/no-undeclared-env-vars
const bookingLoggingEventIds = process.env.BOOKING_LOGGING_EVENT_IDS || "";
const isEnabled = bookingLoggingEventIds.split(",").some((id) => {
if (Number(id.trim()) === eventTypeId) {
return true;
}
});
if (isEnabled) {
return true;
}
// eslint-disable-next-line turbo/no-undeclared-env-vars
const bookingLoggingUsername = process.env.BOOKING_LOGGING_USER_OR_TEAM_NAME || "";
return bookingLoggingUsername.split(",").some((u) => {
return usernameOrTeamnamesList.some((foundUsername) => foundUsername === u.trim());
});
}