From 7ff5b66f46dc743caa3dc2357e8e8d0770393819 Mon Sep 17 00:00:00 2001 From: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com> Date: Wed, 26 Apr 2023 10:12:14 -0400 Subject: [PATCH] Bookings with no-show fee to set proper location & prevent broken payments from blocking payment page (#8508) * Better error logging on Stripe payment service * Update booking * If missing payment, load rest of bookings * Address feedback * Move requires confirmation threshold to webhook * Use requiresConfirmation * Revert unnecessary prettier changes --------- Co-authored-by: Hariom Balhara --- .../components/booking/BookingListItem.tsx | 16 +- apps/web/public/static/locales/en/common.json | 1 + .../stripepayment/lib/PaymentService.ts | 145 +++++++++--------- packages/features/ee/payments/api/webhook.ts | 33 +++- 4 files changed, 113 insertions(+), 82 deletions(-) diff --git a/apps/web/components/booking/BookingListItem.tsx b/apps/web/components/booking/BookingListItem.tsx index 0644aa5e0f..63a8a9fe2d 100644 --- a/apps/web/components/booking/BookingListItem.tsx +++ b/apps/web/components/booking/BookingListItem.tsx @@ -280,13 +280,13 @@ function BookingListItem(booking: BookingItemProps) { isOpenDialog={isOpenSetLocationDialog} setShowLocationModal={setIsOpenLocationDialog} /> - {booking.paid && ( + {booking.paid && booking.payment[0] && ( )} {showRecordingsButtons && ( @@ -354,11 +354,15 @@ function BookingListItem(booking: BookingItemProps) { {booking.eventType.team.name} )} - {booking.paid && ( + {booking.paid && !booking.payment[0] ? ( + + {t("error_collecting_card")} + + ) : booking.paid ? ( {booking.payment[0].paymentOption === "HOLD" ? t("card_held") : t("paid")} - )} + ) : null} {recurringDates !== undefined && (
@@ -458,7 +462,7 @@ function BookingListItem(booking: BookingItemProps) {
)} - {booking.status === "ACCEPTED" && booking.paid && booking?.payment[0]?.paymentOption === "HOLD" && ( + {booking.status === "ACCEPTED" && booking.paid && booking.payment[0]?.paymentOption === "HOLD" && (
diff --git a/apps/web/public/static/locales/en/common.json b/apps/web/public/static/locales/en/common.json index d9b9200a9a..c001b9ddde 100644 --- a/apps/web/public/static/locales/en/common.json +++ b/apps/web/public/static/locales/en/common.json @@ -1799,5 +1799,6 @@ "charge_attendee": "Charge attendee {{amount, currency}}", "payment_app_commission": "Require payment ({{paymentFeePercentage}}% + {{fee, currency}} commission per transaction)", "email_invite_team": "{{email}} has been invited", + "error_collecting_card": "Error collecting card", "image_size_limit_exceed": "Uploaded image shouldn't exceed 5mb size limit" } diff --git a/packages/app-store/stripepayment/lib/PaymentService.ts b/packages/app-store/stripepayment/lib/PaymentService.ts index ee18a9a8e7..e7155b1a79 100644 --- a/packages/app-store/stripepayment/lib/PaymentService.ts +++ b/packages/app-store/stripepayment/lib/PaymentService.ts @@ -113,7 +113,7 @@ export class PaymentService implements IAbstractPaymentService { } return paymentData; } catch (error) { - console.error(error); + console.error(`Payment could not be created for bookingId ${bookingId}`, error); throw new Error("Payment could not be created"); } } @@ -124,75 +124,80 @@ export class PaymentService implements IAbstractPaymentService { bookerEmail: string, paymentOption: PaymentOption ): Promise { - // Ensure that the payment service can support the passed payment option - if (paymentOptionEnum.parse(paymentOption) !== "HOLD") { - throw new Error("Payment option is not compatible with create method"); + try { + // Ensure that the payment service can support the passed payment option + if (paymentOptionEnum.parse(paymentOption) !== "HOLD") { + throw new Error("Payment option is not compatible with create method"); + } + + // Load stripe keys + const stripeAppKeys = await prisma?.app.findFirst({ + select: { + keys: true, + }, + where: { + slug: "stripe", + }, + }); + + // Parse keys with zod + const { payment_fee_fixed, payment_fee_percentage } = stripeAppKeysSchema.parse(stripeAppKeys?.keys); + const paymentFee = Math.round(payment.amount * payment_fee_percentage + payment_fee_fixed); + + const customer = await retrieveOrCreateStripeCustomerByEmail( + bookerEmail, + this.credentials.stripe_user_id + ); + + const params = { + customer: customer.id, + payment_method_types: ["card"], + metadata: { + bookingId, + }, + }; + + const setupIntent = await this.stripe.setupIntents.create(params, { + stripeAccount: this.credentials.stripe_user_id, + }); + + const paymentData = await prisma?.payment.create({ + data: { + uid: uuidv4(), + app: { + connect: { + slug: "stripe", + }, + }, + booking: { + connect: { + id: bookingId, + }, + }, + amount: payment.amount, + currency: payment.currency, + externalId: setupIntent.id, + + data: Object.assign( + {}, + { + setupIntent, + stripe_publishable_key: this.credentials.stripe_publishable_key, + stripeAccount: this.credentials.stripe_user_id, + } + ) as unknown as Prisma.InputJsonValue, + fee: paymentFee, + refunded: false, + success: false, + paymentOption: paymentOption || "ON_BOOKING", + }, + }); + + return paymentData; + } catch (error) { + console.error(`Payment method could not be collected for bookingId ${bookingId}`, error); + throw new Error("Payment could not be created"); } - - // Load stripe keys - const stripeAppKeys = await prisma?.app.findFirst({ - select: { - keys: true, - }, - where: { - slug: "stripe", - }, - }); - - // Parse keys with zod - const { payment_fee_fixed, payment_fee_percentage } = stripeAppKeysSchema.parse(stripeAppKeys?.keys); - const paymentFee = Math.round(payment.amount * payment_fee_percentage + payment_fee_fixed); - - const customer = await retrieveOrCreateStripeCustomerByEmail( - bookerEmail, - this.credentials.stripe_user_id - ); - - const params = { - customer: customer.id, - payment_method_types: ["card"], - metadata: { - bookingId, - }, - }; - - const setupIntent = await this.stripe.setupIntents.create(params, { - stripeAccount: this.credentials.stripe_user_id, - }); - - const paymentData = await prisma?.payment.create({ - data: { - uid: uuidv4(), - app: { - connect: { - slug: "stripe", - }, - }, - booking: { - connect: { - id: bookingId, - }, - }, - amount: payment.amount, - currency: payment.currency, - externalId: setupIntent.id, - - data: Object.assign( - {}, - { - setupIntent, - stripe_publishable_key: this.credentials.stripe_publishable_key, - stripeAccount: this.credentials.stripe_user_id, - } - ) as unknown as Prisma.InputJsonValue, - fee: paymentFee, - refunded: false, - success: false, - paymentOption: paymentOption || "ON_BOOKING", - }, - }); - - return paymentData; } async chargeCard(payment: Payment): Promise { @@ -264,7 +269,7 @@ export class PaymentService implements IAbstractPaymentService { return paymentData; } catch (error) { - console.error(error); + console.error(`Could not charge card for payment ${payment.id}`, error); throw new Error("Payment could not be created"); } } diff --git a/packages/features/ee/payments/api/webhook.ts b/packages/features/ee/payments/api/webhook.ts index 9bae3030e9..458b7a6cd1 100644 --- a/packages/features/ee/payments/api/webhook.ts +++ b/packages/features/ee/payments/api/webhook.ts @@ -6,6 +6,7 @@ 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 { sendScheduledEmails, sendOrganizerRequestEmail, sendAttendeeRequestEmail } from "@calcom/emails"; import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses"; import { handleConfirmation } from "@calcom/features/bookings/lib/handleConfirmation"; @@ -15,6 +16,7 @@ import { getErrorFromUnknown } from "@calcom/lib/errors"; import { HttpError as HttpCode } from "@calcom/lib/http-error"; import { getTranslation } from "@calcom/lib/server/i18n"; import { prisma, bookingMinimalSelect } from "@calcom/prisma"; +import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils"; import type { CalendarEvent } from "@calcom/types/Calendar"; export const config = { @@ -31,6 +33,7 @@ async function getEventType(id: number) { select: { recurringEvent: true, requiresConfirmation: true, + metadata: true, }, }); } @@ -73,6 +76,8 @@ async function getBooking(bookingId: number) { 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" }); @@ -109,14 +114,14 @@ async function getBooking(bookingId: number) { attendees: attendeesList, uid: booking.uid, destinationCalendar: booking.destinationCalendar || user.destinationCalendar, - recurringEvent: parseRecurringEvent(eventTypeRaw?.recurringEvent), + recurringEvent: parseRecurringEvent(eventType?.recurringEvent), }; return { booking, user, evt, - eventTypeRaw, + eventType, }; } @@ -214,6 +219,7 @@ async function handlePaymentSuccess(event: Stripe.Event) { language: { translate: t, locale: user.locale ?? "en" }, }, attendees: attendeesList, + location: booking.location, uid: booking.uid, destinationCalendar: booking.destinationCalendar || user.destinationCalendar, recurringEvent: parseRecurringEvent(eventTypeRaw?.recurringEvent), @@ -284,7 +290,7 @@ const handleSetupSuccess = async (event: Stripe.Event) => { if (!payment?.data || !payment?.id) throw new HttpCode({ statusCode: 204, message: "Payment not found" }); - const { user, evt, eventTypeRaw } = await getBooking(payment.bookingId); + const { booking, user, evt, eventType } = await getBooking(payment.bookingId); const bookingData: Prisma.BookingUpdateInput = { paid: true, @@ -308,7 +314,15 @@ const handleSetupSuccess = async (event: Stripe.Event) => { if (!userWithCredentials) throw new HttpCode({ statusCode: 204, message: "No user found" }); - if (!eventTypeRaw?.requiresConfirmation) { + 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 scheduleResult = await eventManager.create(evt); bookingData.references = { create: scheduleResult.referencesToCreate }; @@ -334,8 +348,15 @@ const handleSetupSuccess = async (event: Stripe.Event) => { // If the card information was already captured in the same customer. Delete the previous payment method - if (!eventTypeRaw?.requiresConfirmation) { - await sendScheduledEmails({ ...evt }); + if (!requiresConfirmation) { + await handleConfirmation({ + user: userWithCredentials, + evt, + prisma, + bookingId: booking.id, + booking, + paid: true, + }); } else { await sendOrganizerRequestEmail({ ...evt }); await sendAttendeeRequestEmail({ ...evt }, evt.attendees[0]);