fix: Handle payment flow webhooks in case of event requiring confirmation (#11458)
Co-authored-by: alannnc <[email protected]>
This commit is contained in:
1 parent
0bb99fc667
commit
20898e1505
29 files changed
+3379
-1656
No files matched your search
@@ -0,0 +1,36 @@
|
||||
import type { z } from "zod";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import type { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
/**
|
||||
* Determines if a booking actually requires confirmation(considering requiresConfirmationThreshold)
|
||||
*/
|
||||
export const doesBookingRequireConfirmation = ({
|
||||
booking: { startTime, eventType },
|
||||
}: {
|
||||
booking: {
|
||||
startTime: Date;
|
||||
eventType: {
|
||||
requiresConfirmation?: boolean;
|
||||
metadata: z.infer<typeof EventTypeMetaDataSchema>;
|
||||
} | null;
|
||||
};
|
||||
}) => {
|
||||
let requiresConfirmation = eventType?.requiresConfirmation;
|
||||
const rcThreshold = eventType?.metadata?.requiresConfirmationThreshold;
|
||||
if (rcThreshold) {
|
||||
// Convert startTime to UTC and create Day.js instances
|
||||
const startTimeUTC = dayjs(startTime).utc();
|
||||
const currentTime = dayjs();
|
||||
|
||||
// Calculate the time difference in the specified unit
|
||||
const timeDifference = startTimeUTC.diff(currentTime, rcThreshold.unit);
|
||||
|
||||
// Check if the time difference exceeds the threshold
|
||||
if (timeDifference > rcThreshold.time) {
|
||||
requiresConfirmation = false;
|
||||
}
|
||||
}
|
||||
return requiresConfirmation;
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
export const getWebhookPayloadForBooking = ({
|
||||
booking,
|
||||
evt,
|
||||
}: {
|
||||
booking: {
|
||||
eventType: {
|
||||
title: string;
|
||||
description: string | null;
|
||||
requiresConfirmation: boolean;
|
||||
price: number;
|
||||
currency: string;
|
||||
length: number;
|
||||
id: number;
|
||||
} | null;
|
||||
id: number;
|
||||
eventTypeId: number | null;
|
||||
userId: number | null;
|
||||
};
|
||||
evt: CalendarEvent;
|
||||
}) => {
|
||||
const eventTypeInfo: EventTypeInfo = {
|
||||
eventTitle: booking.eventType?.title,
|
||||
eventDescription: booking.eventType?.description,
|
||||
requiresConfirmation: booking.eventType?.requiresConfirmation || null,
|
||||
price: booking.eventType?.price,
|
||||
currency: booking.eventType?.currency,
|
||||
length: booking.eventType?.length,
|
||||
};
|
||||
return {
|
||||
...evt,
|
||||
...eventTypeInfo,
|
||||
bookingId: booking.id,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,69 @@
|
||||
import { sendAttendeeRequestEmail, sendOrganizerRequestEmail } from "@calcom/emails";
|
||||
import { getWebhookPayloadForBooking } from "@calcom/features/bookings/lib/getWebhookPayloadForBooking";
|
||||
import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";
|
||||
import sendPayload from "@calcom/features/webhooks/lib/sendPayload";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
const log = logger.getChildLogger({ prefix: ["[handleConfirmation] book:user"] });
|
||||
|
||||
/**
|
||||
* Supposed to do whatever is needed when a booking is requested.
|
||||
*/
|
||||
export async function handleBookingRequested(args: {
|
||||
evt: CalendarEvent;
|
||||
booking: {
|
||||
eventType: {
|
||||
currency: string;
|
||||
description: string | null;
|
||||
id: number;
|
||||
length: number;
|
||||
price: number;
|
||||
requiresConfirmation: boolean;
|
||||
title: string;
|
||||
teamId?: number | null;
|
||||
} | null;
|
||||
eventTypeId: number | null;
|
||||
userId: number | null;
|
||||
id: number;
|
||||
};
|
||||
}) {
|
||||
const { evt, booking } = args;
|
||||
|
||||
await sendOrganizerRequestEmail({ ...evt });
|
||||
await sendAttendeeRequestEmail({ ...evt }, evt.attendees[0]);
|
||||
|
||||
try {
|
||||
const subscribersBookingRequested = await getWebhooks({
|
||||
userId: booking.userId,
|
||||
eventTypeId: booking.eventTypeId,
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
teamId: booking.eventType?.teamId,
|
||||
});
|
||||
|
||||
const webhookPayload = getWebhookPayloadForBooking({
|
||||
booking,
|
||||
evt,
|
||||
});
|
||||
|
||||
const promises = subscribersBookingRequested.map((sub) =>
|
||||
sendPayload(
|
||||
sub.secret,
|
||||
WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
new Date().toISOString(),
|
||||
sub,
|
||||
webhookPayload
|
||||
).catch((e) => {
|
||||
console.error(
|
||||
`Error executing webhook for event: ${WebhookTriggerEvents.BOOKING_REQUESTED}, URL: ${sub.subscriberUrl}`,
|
||||
e
|
||||
);
|
||||
})
|
||||
);
|
||||
await Promise.all(promises);
|
||||
} catch (error) {
|
||||
// Silently fail
|
||||
log.error(error);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1210,8 +1210,6 @@ async function handler(
|
||||
teamId,
|
||||
};
|
||||
|
||||
const subscribersMeetingEnded = await getWebhooks(subscriberOptionsMeetingEnded);
|
||||
|
||||
const handleSeats = async () => {
|
||||
let resultBooking:
|
||||
| (Partial<Booking> & {
|
||||
@@ -1219,6 +1217,7 @@ async function handler(
|
||||
seatReferenceUid?: string;
|
||||
paymentUid?: string;
|
||||
message?: string;
|
||||
paymentId?: number;
|
||||
})
|
||||
| null = null;
|
||||
|
||||
@@ -1762,6 +1761,7 @@ async function handler(
|
||||
resultBooking = { ...foundBooking };
|
||||
resultBooking["message"] = "Payment required";
|
||||
resultBooking["paymentUid"] = payment?.uid;
|
||||
resultBooking["id"] = payment?.id;
|
||||
} else {
|
||||
resultBooking = { ...foundBooking };
|
||||
}
|
||||
@@ -2082,7 +2082,9 @@ async function handler(
|
||||
}
|
||||
|
||||
let videoCallUrl;
|
||||
|
||||
if (originalRescheduledBooking?.uid) {
|
||||
log.silly("Rescheduling booking", originalRescheduledBooking.uid);
|
||||
try {
|
||||
// cancel workflow reminders from previous rescheduled booking
|
||||
await cancelWorkflowReminders(originalRescheduledBooking.workflowReminders);
|
||||
@@ -2288,6 +2290,27 @@ async function handler(
|
||||
await sendOrganizerRequestEmail({ ...evt, additionalNotes });
|
||||
await sendAttendeeRequestEmail({ ...evt, additionalNotes }, attendeesList[0]);
|
||||
}
|
||||
const metadata = videoCallUrl
|
||||
? {
|
||||
videoCallUrl: getVideoCallUrlFromCalEvent(evt),
|
||||
}
|
||||
: undefined;
|
||||
const webhookData = {
|
||||
...evt,
|
||||
...eventTypeInfo,
|
||||
bookingId: booking?.id,
|
||||
rescheduleUid,
|
||||
rescheduleStartTime: originalRescheduledBooking?.startTime
|
||||
? dayjs(originalRescheduledBooking?.startTime).utc().format()
|
||||
: undefined,
|
||||
rescheduleEndTime: originalRescheduledBooking?.endTime
|
||||
? dayjs(originalRescheduledBooking?.endTime).utc().format()
|
||||
: undefined,
|
||||
metadata: { ...metadata, ...reqBody.metadata },
|
||||
eventTypeId,
|
||||
status: "ACCEPTED",
|
||||
smsReminderNumber: booking?.smsReminderNumber || undefined,
|
||||
};
|
||||
|
||||
if (bookingRequiresPayment) {
|
||||
// Load credentials.app.categories
|
||||
@@ -2329,9 +2352,23 @@ async function handler(
|
||||
fullName,
|
||||
bookerEmail
|
||||
);
|
||||
const subscriberOptionsPaymentInitiated: GetSubscriberOptions = {
|
||||
userId: triggerForUser ? organizerUser.id : null,
|
||||
eventTypeId,
|
||||
triggerEvent: WebhookTriggerEvents.BOOKING_PAYMENT_INITIATED,
|
||||
teamId,
|
||||
};
|
||||
await handleWebhookTrigger({
|
||||
subscriberOptions: subscriberOptionsPaymentInitiated,
|
||||
eventTrigger: WebhookTriggerEvents.BOOKING_PAYMENT_INITIATED,
|
||||
webhookData: {
|
||||
...webhookData,
|
||||
paymentId: payment?.id,
|
||||
},
|
||||
});
|
||||
|
||||
req.statusCode = 201;
|
||||
return { ...booking, message: "Payment required", paymentUid: payment?.uid };
|
||||
return { ...booking, message: "Payment required", paymentUid: payment?.uid, paymentId: payment?.id };
|
||||
}
|
||||
|
||||
loggerWithEventDetails.debug(`Booking ${organizerUser.username} completed`);
|
||||
@@ -2340,28 +2377,6 @@ async function handler(
|
||||
videoCallUrl = booking.location;
|
||||
}
|
||||
|
||||
const metadata = videoCallUrl
|
||||
? {
|
||||
videoCallUrl: getVideoCallUrlFromCalEvent(evt),
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const webhookData = {
|
||||
...evt,
|
||||
...eventTypeInfo,
|
||||
bookingId: booking?.id,
|
||||
rescheduleUid,
|
||||
rescheduleStartTime: originalRescheduledBooking?.startTime
|
||||
? dayjs(originalRescheduledBooking?.startTime).utc().format()
|
||||
: undefined,
|
||||
rescheduleEndTime: originalRescheduledBooking?.endTime
|
||||
? dayjs(originalRescheduledBooking?.endTime).utc().format()
|
||||
: undefined,
|
||||
metadata: { ...metadata, ...reqBody.metadata },
|
||||
eventTypeId,
|
||||
status: "ACCEPTED",
|
||||
smsReminderNumber: booking?.smsReminderNumber || undefined,
|
||||
};
|
||||
if (isConfirmedByDefault) {
|
||||
try {
|
||||
const subscribersMeetingEnded = await getWebhooks(subscriberOptionsMeetingEnded);
|
||||
|
||||
@@ -5,21 +5,19 @@ import type Stripe from "stripe";
|
||||
|
||||
import stripe from "@calcom/app-store/stripepayment/lib/server";
|
||||
import EventManager from "@calcom/core/EventManager";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { sendOrganizerRequestEmail, sendAttendeeRequestEmail } from "@calcom/emails";
|
||||
import { sendAttendeeRequestEmail, sendOrganizerRequestEmail } from "@calcom/emails";
|
||||
import { doesBookingRequireConfirmation } from "@calcom/features/bookings/lib/doesBookingRequireConfirmation";
|
||||
import { handleConfirmation } from "@calcom/features/bookings/lib/handleConfirmation";
|
||||
import { isPrismaObjOrUndefined, parseRecurringEvent } from "@calcom/lib";
|
||||
import { IS_PRODUCTION } from "@calcom/lib/constants";
|
||||
import { getErrorFromUnknown } from "@calcom/lib/errors";
|
||||
import { HttpError as HttpCode } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { getBooking } from "@calcom/lib/payment/getBooking";
|
||||
import { handlePaymentSuccess } from "@calcom/lib/payment/handlePaymentSuccess";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
|
||||
import { bookingMinimalSelect, prisma } from "@calcom/prisma";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { BookingStatus } from "@calcom/prisma/enums";
|
||||
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
|
||||
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
const log = logger.getChildLogger({ prefix: ["[paymentWebhook]"] });
|
||||
|
||||
export const config = {
|
||||
api: {
|
||||
@@ -27,109 +25,7 @@ export const config = {
|
||||
},
|
||||
};
|
||||
|
||||
async function getEventType(id: number) {
|
||||
return prisma.eventType.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
select: {
|
||||
recurringEvent: true,
|
||||
requiresConfirmation: true,
|
||||
metadata: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function getBooking(bookingId: number) {
|
||||
const booking = await prisma.booking.findUnique({
|
||||
where: {
|
||||
id: bookingId,
|
||||
},
|
||||
select: {
|
||||
...bookingMinimalSelect,
|
||||
eventType: true,
|
||||
smsReminderNumber: true,
|
||||
location: true,
|
||||
eventTypeId: true,
|
||||
userId: true,
|
||||
uid: true,
|
||||
paid: true,
|
||||
destinationCalendar: true,
|
||||
status: true,
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
timeZone: true,
|
||||
timeFormat: true,
|
||||
email: true,
|
||||
name: true,
|
||||
locale: true,
|
||||
destinationCalendar: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!booking) throw new HttpCode({ statusCode: 204, message: "No booking found" });
|
||||
|
||||
type EventTypeRaw = Awaited<ReturnType<typeof getEventType>>;
|
||||
let eventTypeRaw: EventTypeRaw | null = null;
|
||||
if (booking.eventTypeId) {
|
||||
eventTypeRaw = await getEventType(booking.eventTypeId);
|
||||
}
|
||||
|
||||
const eventType = { ...eventTypeRaw, metadata: EventTypeMetaDataSchema.parse(eventTypeRaw?.metadata) };
|
||||
|
||||
const { user } = booking;
|
||||
|
||||
if (!user) throw new HttpCode({ statusCode: 204, message: "No user found" });
|
||||
|
||||
const t = await getTranslation(user.locale ?? "en", "common");
|
||||
const attendeesListPromises = booking.attendees.map(async (attendee) => {
|
||||
return {
|
||||
name: attendee.name,
|
||||
email: attendee.email,
|
||||
timeZone: attendee.timeZone,
|
||||
language: {
|
||||
translate: await getTranslation(attendee.locale ?? "en", "common"),
|
||||
locale: attendee.locale ?? "en",
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const attendeesList = await Promise.all(attendeesListPromises);
|
||||
const selectedDestinationCalendar = booking.destinationCalendar || user.destinationCalendar;
|
||||
const evt: CalendarEvent = {
|
||||
type: booking.title,
|
||||
title: booking.title,
|
||||
description: booking.description || undefined,
|
||||
startTime: booking.startTime.toISOString(),
|
||||
endTime: booking.endTime.toISOString(),
|
||||
customInputs: isPrismaObjOrUndefined(booking.customInputs),
|
||||
organizer: {
|
||||
email: user.email,
|
||||
name: user.name!,
|
||||
timeZone: user.timeZone,
|
||||
timeFormat: getTimeFormatStringFromUserTimeFormat(user.timeFormat),
|
||||
language: { translate: t, locale: user.locale ?? "en" },
|
||||
id: user.id,
|
||||
},
|
||||
attendees: attendeesList,
|
||||
uid: booking.uid,
|
||||
destinationCalendar: selectedDestinationCalendar ? [selectedDestinationCalendar] : [],
|
||||
recurringEvent: parseRecurringEvent(eventType?.recurringEvent),
|
||||
};
|
||||
|
||||
return {
|
||||
booking,
|
||||
user,
|
||||
evt,
|
||||
eventType,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleStripePaymentSuccess(event: Stripe.Event) {
|
||||
export async function handleStripePaymentSuccess(event: Stripe.Event) {
|
||||
const paymentIntent = event.data.object as Stripe.PaymentIntent;
|
||||
const payment = await prisma.payment.findFirst({
|
||||
where: {
|
||||
@@ -140,8 +36,10 @@ async function handleStripePaymentSuccess(event: Stripe.Event) {
|
||||
bookingId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!payment?.bookingId) {
|
||||
console.log(JSON.stringify(paymentIntent), JSON.stringify(payment));
|
||||
log.error(JSON.stringify(paymentIntent), JSON.stringify(payment));
|
||||
throw new HttpCode({ statusCode: 204, message: "Payment not found" });
|
||||
}
|
||||
if (!payment?.bookingId) throw new HttpCode({ statusCode: 204, message: "Payment not found" });
|
||||
|
||||
@@ -164,34 +62,16 @@ const handleSetupSuccess = async (event: Stripe.Event) => {
|
||||
paid: true,
|
||||
};
|
||||
|
||||
const userWithCredentials = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
timeZone: true,
|
||||
email: true,
|
||||
name: true,
|
||||
locale: true,
|
||||
destinationCalendar: true,
|
||||
credentials: { select: credentialForCalendarServiceSelect },
|
||||
if (!user) throw new HttpCode({ statusCode: 204, message: "No user found" });
|
||||
|
||||
const requiresConfirmation = doesBookingRequireConfirmation({
|
||||
booking: {
|
||||
...booking,
|
||||
eventType,
|
||||
},
|
||||
});
|
||||
|
||||
if (!userWithCredentials) throw new HttpCode({ statusCode: 204, message: "No user found" });
|
||||
|
||||
let requiresConfirmation = eventType?.requiresConfirmation;
|
||||
const rcThreshold = eventType?.metadata?.requiresConfirmationThreshold;
|
||||
if (rcThreshold) {
|
||||
if (dayjs(dayjs(booking.startTime).utc().format()).diff(dayjs(), rcThreshold.unit) > rcThreshold.time) {
|
||||
requiresConfirmation = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!requiresConfirmation) {
|
||||
const eventManager = new EventManager(userWithCredentials);
|
||||
const eventManager = new EventManager(user);
|
||||
const scheduleResult = await eventManager.create(evt);
|
||||
bookingData.references = { create: scheduleResult.referencesToCreate };
|
||||
bookingData.status = BookingStatus.ACCEPTED;
|
||||
@@ -218,7 +98,7 @@ const handleSetupSuccess = async (event: Stripe.Event) => {
|
||||
|
||||
if (!requiresConfirmation) {
|
||||
await handleConfirmation({
|
||||
user: userWithCredentials,
|
||||
user,
|
||||
evt,
|
||||
prisma,
|
||||
bookingId: booking.id,
|
||||
|
||||
@@ -35,6 +35,7 @@ const WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP_V2: Record<string, WebhookTriggerEve
|
||||
{ value: WebhookTriggerEvents.BOOKING_CREATED, label: "booking_created" },
|
||||
{ value: WebhookTriggerEvents.BOOKING_REJECTED, label: "booking_rejected" },
|
||||
{ value: WebhookTriggerEvents.BOOKING_REQUESTED, label: "booking_requested" },
|
||||
{ value: WebhookTriggerEvents.BOOKING_PAYMENT_INITIATED, label: "booking_payment_initiated" },
|
||||
{ value: WebhookTriggerEvents.BOOKING_RESCHEDULED, label: "booking_rescheduled" },
|
||||
{ value: WebhookTriggerEvents.BOOKING_PAID, label: "booking_paid" },
|
||||
{ value: WebhookTriggerEvents.MEETING_ENDED, label: "meeting_ended" },
|
||||
|
||||
@@ -8,6 +8,7 @@ export const WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP = {
|
||||
WebhookTriggerEvents.BOOKING_CREATED,
|
||||
WebhookTriggerEvents.BOOKING_RESCHEDULED,
|
||||
WebhookTriggerEvents.BOOKING_PAID,
|
||||
WebhookTriggerEvents.BOOKING_PAYMENT_INITIATED,
|
||||
WebhookTriggerEvents.MEETING_ENDED,
|
||||
WebhookTriggerEvents.BOOKING_REQUESTED,
|
||||
WebhookTriggerEvents.BOOKING_REJECTED,
|
||||
|
||||
Reference in new issue
Block a user