Stripe add the ability to place hold on cards (#8022)

* Add payment option to schema

* Add payment option to Stripe zod

* Set payment option on event type

* Create manual payment intent in Stripe

* Set payment option from Stripe app

* Add payment option to DB

* Pass React.ReactNode to checkbox

* Create uncaptured payment intent

* WIP

* Capture card in setup intent

* Show charge card option

* Charge card from booking page

* Bug fixes

* Clean up

* Clean up app card

* Add no-show fee messaging on booking page

* Send payment email on payment & add price

* Fix messaging

* Create no show fee charged email

* Send charge fee collected email

* Disable submit on card failure

* Clean up

* Serverside prevent charging card again if already charged

* Only confirm booking if paid for

* Type fixes

* More type fixes

* More type fixes

* Type fix

* Type fixes

* UI changes

* Payment component rework

* Update apps/web/public/static/locales/en/common.json

Co-authored-by: Alex van Andel <[email protected]>

* Update apps/web/public/static/locales/en/common.json

Co-authored-by: Alex van Andel <[email protected]>

* Update apps/web/components/dialog/ChargeCardDialog.tsx

Co-authored-by: Alex van Andel <[email protected]>

* Update packages/trpc/server/routers/viewer/payments.tsx

Co-authored-by: Alex van Andel <[email protected]>

* Revert GTM config

* Adjust payment option dropdown

* Show alert when seats are set

* Small bug fixes

* Create collect card method

* clean up

* Prevent seats & charge no-show fee to be enabled together

* Do not charge no-show fee on unconfirmed bookings

* Add check to collect card method

* Webhook send request emails

* Fix some dark mode colours

* Change awaiting payment language

* Type fixes

* Set height of Select and TextField both to 38px to fix alignment

* Fix message seats & payment error message

* Type fix

---------

Co-authored-by: Alex van Andel <[email protected]>
This commit is contained in:
Joe Au-YeungandAlex van Andel authored and GitHub committed 2023-04-11 23:44:14 +02:00
1 parent af0123a606
commit 817e20f11e
47 files changed
+1149 -221

No files matched your search

@@ -1412,7 +1412,8 @@ async function handler(
evt,
eventType,
eventTypePaymentAppCredential as IEventTypePaymentCredentialType,
booking
booking,
bookerEmail
);
return {
@@ -1846,17 +1847,18 @@ async function handler(
}
}
if (!isConfirmedByDefault && noEmail !== true) {
const bookingRequiresPayment =
!Number.isNaN(paymentAppData.price) &&
paymentAppData.price > 0 &&
!originalRescheduledBooking?.paid &&
!!booking;
if (!isConfirmedByDefault && noEmail !== true && !bookingRequiresPayment) {
await sendOrganizerRequestEmail({ ...evt, additionalNotes });
await sendAttendeeRequestEmail({ ...evt, additionalNotes }, attendeesList[0]);
}
if (
!Number.isNaN(paymentAppData.price) &&
paymentAppData.price > 0 &&
!originalRescheduledBooking?.paid &&
!!booking
) {
if (bookingRequiresPayment) {
// Load credentials.app.categories
const credentialPaymentAppCategories = await prisma.credential.findMany({
where: {
@@ -1892,7 +1894,8 @@ async function handler(
evt,
eventType,
eventTypePaymentAppCredential as IEventTypePaymentCredentialType,
booking
booking,
bookerEmail
);
req.statusCode = 201;
@@ -56,7 +56,7 @@ export function Calendar(props: CalendarComponentProps) {
containerRef={container}
/> */}
<div className="flex flex-auto">
<div className="bg-default sticky left-0 z-10 w-14 flex-none ring-1 ring-muted" />
<div className="bg-default ring-muted sticky left-0 z-10 w-14 flex-none ring-1" />
<div className="grid flex-auto grid-cols-1 grid-rows-1 ">
<HorizontalLines
hours={hours}
+138 -1
View File
@@ -6,7 +6,7 @@ import type Stripe from "stripe";
import stripe from "@calcom/app-store/stripepayment/lib/server";
import EventManager from "@calcom/core/EventManager";
import { sendScheduledEmails } from "@calcom/emails";
import { sendScheduledEmails, sendOrganizerRequestEmail, sendAttendeeRequestEmail } from "@calcom/emails";
import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";
import { handleConfirmation } from "@calcom/features/bookings/lib/handleConfirmation";
import { isPrismaObjOrUndefined, parseRecurringEvent } from "@calcom/lib";
@@ -35,6 +35,92 @@ async function getEventType(id: number) {
});
}
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,
credentials: true,
timeZone: 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 { 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 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,
language: { translate: t, locale: user.locale ?? "en" },
id: user.id,
},
attendees: attendeesList,
uid: booking.uid,
destinationCalendar: booking.destinationCalendar || user.destinationCalendar,
recurringEvent: parseRecurringEvent(eventTypeRaw?.recurringEvent),
};
return {
booking,
user,
evt,
eventTypeRaw,
};
}
async function handlePaymentSuccess(event: Stripe.Event) {
const paymentIntent = event.data.object as Stripe.PaymentIntent;
const payment = await prisma.payment.findFirst({
@@ -180,10 +266,61 @@ async function handlePaymentSuccess(event: Stripe.Event) {
});
}
const handleSetupSuccess = async (event: Stripe.Event) => {
const setupIntent = event.data.object as Stripe.SetupIntent;
const payment = await prisma.payment.findFirst({
where: {
externalId: setupIntent.id,
},
});
if (!payment?.data || !payment?.id) throw new HttpCode({ statusCode: 204, message: "Payment not found" });
const { booking, user, evt, eventTypeRaw } = await getBooking(payment.bookingId);
const bookingData: Prisma.BookingUpdateInput = {
paid: true,
};
if (!eventTypeRaw?.requiresConfirmation) {
const eventManager = new EventManager(user);
const scheduleResult = await eventManager.create(evt);
bookingData.references = { create: scheduleResult.referencesToCreate };
bookingData.status = BookingStatus.ACCEPTED;
}
await prisma.payment.update({
where: {
id: payment.id,
},
data: {
data: {
...(payment.data as Prisma.JsonObject),
setupIntent: setupIntent as unknown as Prisma.JsonObject,
},
booking: {
update: {
...bookingData,
},
},
},
});
// If the card information was already captured in the same customer. Delete the previous payment method
if (!eventTypeRaw?.requiresConfirmation) {
await sendScheduledEmails({ ...evt });
} else {
await sendOrganizerRequestEmail({ ...evt });
await sendAttendeeRequestEmail({ ...evt }, evt.attendees[0]);
}
};
type WebhookHandler = (event: Stripe.Event) => Promise<void>;
const webhookHandlers: Record<string, WebhookHandler | undefined> = {
"payment_intent.succeeded": handlePaymentSuccess,
"setup_intent.succeeded": handleSetupSuccess,
};
/**
@@ -1,3 +1,4 @@
import type { Payment } from "@prisma/client";
import { CardElement, useElements, useStripe } from "@stripe/react-stripe-js";
import type { StripeCardElementChangeEvent, StripeElementLocale } from "@stripe/stripe-js";
import type stripejs from "@stripe/stripe-js";
@@ -5,10 +6,10 @@ import { useRouter } from "next/router";
import type { SyntheticEvent } from "react";
import { useEffect, useState } from "react";
import type { StripePaymentData } from "@calcom/app-store/stripepayment/lib/server";
import type { StripePaymentData, StripeSetupIntentData } from "@calcom/app-store/stripepayment/lib/server";
import { bookingSuccessRedirect } from "@calcom/lib/bookingSuccessRedirect";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui";
import { Button, Checkbox } from "@calcom/ui";
import type { EventType } from ".prisma/client";
@@ -32,8 +33,8 @@ const CARD_OPTIONS: stripejs.StripeCardElementOptions = {
} as const;
type Props = {
payment: {
data: StripePaymentData;
payment: Omit<Payment, "id" | "fee" | "success" | "refunded" | "externalId" | "data"> & {
data: StripePaymentData | StripeSetupIntentData;
};
eventType: { id: number; successRedirectUrl: EventType["successRedirectUrl"] };
user: { username: string | null };
@@ -54,6 +55,8 @@ export default function PaymentComponent(props: Props) {
const [state, setState] = useState<States>({ status: "idle" });
const stripe = useStripe();
const elements = useElements();
const paymentOption = props.payment.paymentOption;
const [holdAcknowledged, setHoldAcknowledged] = useState<boolean>(paymentOption === "HOLD" ? false : true);
useEffect(() => {
elements?.update({ locale: i18n.language as StripeElementLocale });
@@ -74,22 +77,33 @@ export default function PaymentComponent(props: Props) {
const card = elements.getElement(CardElement);
if (!card) return;
setState({ status: "processing" });
const payload = await stripe.confirmCardPayment(props.payment.data.client_secret!, {
payment_method: {
card,
},
});
if (payload.error) {
let payload;
const params: { [k: string]: any } = {
uid: props.bookingUid,
email: router.query.email,
};
if (paymentOption === "HOLD" && "setupIntent" in props.payment.data) {
const setupIntentData = props.payment.data as unknown as StripeSetupIntentData;
payload = await stripe.confirmCardSetup(setupIntentData.setupIntent.client_secret!, {
payment_method: {
card,
},
});
} else if (paymentOption === "ON_BOOKING") {
const paymentData = props.payment.data as unknown as StripePaymentData;
payload = await stripe.confirmCardPayment(paymentData.client_secret!, {
payment_method: {
card,
},
});
}
if (payload?.error) {
setState({
status: "error",
error: new Error(`Payment failed: ${payload.error.message}`),
});
} else {
const params: { [k: string]: any } = {
uid: props.bookingUid,
email: router.query.email,
};
if (props.location) {
if (props.location.includes("integration")) {
params.location = t("web_conferencing_details_to_follow");
@@ -107,22 +121,53 @@ export default function PaymentComponent(props: Props) {
}
};
return (
<form id="payment-form" className="mt-4" onSubmit={handleSubmit}>
<CardElement id="card-element" options={CARD_OPTIONS} onChange={handleChange} />
<div className="mt-2 flex justify-center">
<form id="payment-form" className="bg-subtle mt-4 rounded-md p-6" onSubmit={handleSubmit}>
<p className="font-semibold">{t("card_details")}</p>
<CardElement
className="my-5 bg-white p-2"
id="card-element"
options={CARD_OPTIONS}
onChange={handleChange}
/>
{paymentOption === "HOLD" && (
<div className="bg-info mt-2 mb-5 rounded-md p-3">
<Checkbox
description={t("acknowledge_booking_no_show_fee", {
amount: props.payment.amount / 100,
formatParams: { amount: { currency: props.payment.currency } },
})}
onChange={(e) => setHoldAcknowledged(e.target.checked)}
descriptionClassName="text-blue-900 font-semibold"
/>
</div>
)}
<div className="mt-2 flex justify-end space-x-2">
<Button
color="minimal"
disabled={!holdAcknowledged || ["processing", "error"].includes(state.status)}
id="cancel">
<span id="button-text">{t("cancel")}</span>
</Button>
<Button
color="primary"
type="submit"
disabled={["processing", "error"].includes(state.status)}
disabled={!holdAcknowledged || ["processing", "error"].includes(state.status)}
loading={state.status === "processing"}
id="submit">
id="submit"
className="border-subtle border">
<span id="button-text">
{state.status === "processing" ? <div className="spinner" id="spinner" /> : t("pay_now")}
{state.status === "processing" ? (
<div className="spinner" id="spinner" />
) : paymentOption === "HOLD" ? (
t("submit_card")
) : (
t("pay_now")
)}
</span>
</Button>
</div>
{state.status === "error" && (
<div className="text-default mt-4 text-center dark:text-gray-300" role="alert">
<div className="mt-4 text-center text-red-900 dark:text-gray-300" role="alert">
{state.error.message}
</div>
)}
@@ -73,7 +73,7 @@ const PaymentPage: FC<PaymentPageProps> = (props) => {
</span>
<div
className={classNames(
"main bg-default inline-block transform overflow-hidden rounded-lg border border-neutral-200 px-8 pt-5 pb-4 text-left align-bottom transition-all dark:border-neutral-700 dark:bg-gray-800 sm:w-full sm:max-w-lg sm:py-6 sm:align-middle",
"main bg-default border-subtle inline-block transform overflow-hidden rounded-lg border px-8 pt-5 pb-4 text-left align-bottom transition-all sm:w-full sm:max-w-lg sm:py-6 sm:align-middle",
isEmbed ? "" : "sm:my-8"
)}
role="dialog"
@@ -85,10 +85,8 @@ const PaymentPage: FC<PaymentPageProps> = (props) => {
</div>
<div className="mt-3 text-center sm:mt-5">
<h3
className="text-emphasis dark:text-inverted text-2xl font-semibold leading-6"
id="modal-headline">
{t("payment")}
<h3 className="text-emphasis text-2xl font-semibold leading-6" id="modal-headline">
{paymentAppData.paymentOption === "HOLD" ? t("complete_your_booking") : t("payment")}
</h3>
<div className="text-default mt-4 grid grid-cols-3 border-t border-b py-4 text-left dark:border-gray-900 dark:text-gray-300">
<div className="font-medium">{t("what")}</div>
@@ -108,8 +106,10 @@ const PaymentPage: FC<PaymentPageProps> = (props) => {
</div>
</>
)}
<div className="font-medium">{t("price")}</div>
<div className="col-span-2 mb-6">
<div className="font-medium">
{props.payment.paymentOption === "HOLD" ? t("no_show_fee") : t("price")}
</div>
<div className="col-span-2 mb-6 font-semibold">
<IntlProvider locale="en">
<FormattedNumber
value={paymentAppData.price / 100.0}
@@ -2,7 +2,7 @@ import { BookingStatus } from "@prisma/client";
import type { GetServerSidePropsContext } from "next";
import { z } from "zod";
import type { StripePaymentData } from "@calcom/app-store/stripepayment/lib/server";
import type { StripePaymentData, StripeSetupIntentData } from "@calcom/app-store/stripepayment/lib/server";
import prisma from "@calcom/prisma";
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import type { inferSSRProps } from "@calcom/types/inferSSRProps";
@@ -30,6 +30,9 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
refunded: true,
bookingId: true,
appId: true,
amount: true,
currency: true,
paymentOption: true,
booking: {
select: {
id: true,
@@ -87,7 +90,7 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
const { data, booking: _booking, ...restPayment } = rawPayment;
const payment = {
...restPayment,
data: data as unknown as StripePaymentData,
data: data as unknown as StripePaymentData | StripeSetupIntentData,
};
if (!_booking) return { notFound: true };
@@ -41,7 +41,7 @@ const SAMLSSO = () => {
}
return (
<div className="w-full bg-default sm:mx-0 xl:mt-0">
<div className="bg-default w-full sm:mx-0 xl:mt-0">
<Meta title={t("sso_configuration")} description={t("sso_configuration_description")} />
<SSOConfiguration teamId={teamId} />
</div>
@@ -19,7 +19,7 @@ const SAMLSSO = () => {
}, []);
return (
<div className="w-full bg-default sm:mx-0 xl:mt-0">
<div className="bg-default w-full sm:mx-0 xl:mt-0">
<Meta title={t("sso_configuration")} description={t("sso_configuration_description")} />
<SSOConfiguration teamId={null} />
</div>
@@ -98,7 +98,7 @@ const WorkflowListItem = (props: ItemProps) => {
});
return (
<div className="flex w-full items-center overflow-hidden rounded-md border border-subtle p-6 px-3 md:p-6">
<div className="border-subtle flex w-full items-center overflow-hidden rounded-md border p-6 px-3 md:p-6">
<div className="bg-subtle mr-4 flex h-10 w-10 items-center justify-center rounded-full text-xs font-medium">
{getActionIcon(
workflow.steps,
@@ -53,7 +53,7 @@ const DateOverrideList = ({
};
return (
<ul className="rounded border border-subtle" data-testid="date-overrides-list">
<ul className="border-subtle rounded border" data-testid="date-overrides-list">
{items.sort(sortByDate).map((item, index) => (
<li key={item.id} className="flex justify-between border-b px-5 py-4 last:border-b-0">
<div>
@@ -52,7 +52,7 @@ const ScheduleDay = <TFieldValues extends FieldValues>({
const watchDayRange = watch(name);
return (
<div className="flex mb-4 w-full flex-col last:mb-0 sm:flex-row sm:px-0">
<div className="mb-4 flex w-full flex-col last:mb-0 sm:flex-row sm:px-0">
{/* Label & switch container */}
<div className="flex h-[36px] items-center justify-between sm:w-32">
<div>
@@ -179,7 +179,7 @@ export const DayRanges = <TFieldValues extends FieldValues>({
<div>
{fields.map((field, index: number) => (
<Fragment key={field.id}>
<div className="flex mb-2 last:mb-0">
<div className="mb-2 flex last:mb-0">
<Controller name={`${name}.${index}`} render={({ field }) => <TimeRangeField {...field} />} />
{index === 0 && (
<Button