feat: payment card atom (#17203)

* init stripe payment card atom

* cleanup

* update platform libraries

* fix import paths

* add function to get user payment info

* fixup

* resolve merge conflicts

* fixup fixup

* resolve merge conflicts

* fixup

* update payments page

* add props for event payment success and failure

* update props and fixup

* bump platform libraries

* fixup! bump platform libraries

* fixup! fixup! bump platform libraries

* resolve merge conflicts

* fix: add isActive to paymentsTab

---------

Co-authored-by: Morgan <[email protected]>
Co-authored-by: Morgan Vernay <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-10-31 11:21:13 +02:00
1 parent a5806cb100
commit fee3b73bda
15 files changed
+602 -129

No files matched your search

@@ -1,7 +1,7 @@
import type { Payment } from "@prisma/client";
import type { EventType } from "@prisma/client";
import { Elements, PaymentElement, useElements, useStripe } from "@stripe/react-stripe-js";
import type { StripeElementLocale } from "@stripe/stripe-js";
import type { StripeElementLocale, StripeElements } from "@stripe/stripe-js";
import { useRouter } from "next/navigation";
import type { SyntheticEvent } from "react";
import { useEffect, useState } from "react";
@@ -10,11 +10,12 @@ import getStripe from "@calcom/app-store/stripepayment/lib/client";
import { useBookingSuccessRedirect } from "@calcom/lib/bookingSuccessRedirect";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { PaymentOption } from "@calcom/prisma/enums";
import { Button, CheckboxField } from "@calcom/ui";
import type { PaymentPageProps } from "../pages/payment";
type Props = {
export type Props = {
payment: Omit<Payment, "id" | "fee" | "success" | "refunded" | "externalId" | "data"> & {
data: Record<string, unknown>;
};
@@ -31,7 +32,7 @@ type Props = {
booking: PaymentPageProps["booking"];
};
type States =
export type States =
| {
status: "idle";
}
@@ -46,23 +47,94 @@ type States =
status: "ok";
};
export const PaymentFormComponent = (
props: Props & {
onSubmit: (ev: SyntheticEvent) => void;
onCancel: () => void;
onPaymentElementChange: () => void;
elements: StripeElements | null;
paymentOption: PaymentOption | null;
state: States;
}
) => {
const { t, i18n } = useLocale();
const { paymentOption, elements, state, onPaymentElementChange } = props;
const [isCanceling, setIsCanceling] = useState<boolean>(false);
const [holdAcknowledged, setHoldAcknowledged] = useState<boolean>(paymentOption === "HOLD" ? false : true);
const disableButtons = isCanceling || !holdAcknowledged || ["processing", "error"].includes(state.status);
useEffect(() => {
elements?.update({ locale: i18n.language as StripeElementLocale });
}, [elements, i18n.language]);
return (
<form id="payment-form" className="bg-subtle mt-4 rounded-md p-6" onSubmit={props.onSubmit}>
<div>
<PaymentElement onChange={() => onPaymentElementChange()} />
</div>
{paymentOption === "HOLD" && (
<div className="bg-info mb-5 mt-2 rounded-md p-3">
<CheckboxField
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-info font-semibold"
/>
</div>
)}
<div className="mt-2 flex justify-end space-x-2">
<Button
color="minimal"
disabled={disableButtons}
id="cancel"
type="button"
loading={isCanceling}
onClick={() => {
setIsCanceling(true);
props.onCancel();
}}>
<span id="button-text">{t("cancel")}</span>
</Button>
<Button
type="submit"
disabled={disableButtons}
loading={state.status === "processing"}
id="submit"
color="secondary">
<span id="button-text">
{state.status === "processing" ? (
<div className="spinner" id="spinner" />
) : paymentOption === "HOLD" ? (
t("submit_card")
) : (
t("pay_now")
)}
</span>
</Button>
</div>
{state.status === "error" && (
<div className="mt-4 text-center text-red-900 dark:text-gray-300" role="alert">
{state.error.message}
</div>
)}
</form>
);
};
const PaymentForm = (props: Props) => {
const {
user: { username },
} = props;
const { t, i18n } = useLocale();
const { t } = useLocale();
const router = useRouter();
const searchParams = useCompatSearchParams();
const [state, setState] = useState<States>({ status: "idle" });
const [isCanceling, setIsCanceling] = useState<boolean>(false);
const stripe = useStripe();
const elements = useElements();
const paymentOption = props.payment.paymentOption;
const [holdAcknowledged, setHoldAcknowledged] = useState<boolean>(paymentOption === "HOLD" ? false : true);
const bookingSuccessRedirect = useBookingSuccessRedirect();
useEffect(() => {
elements?.update({ locale: i18n.language as StripeElementLocale });
}, [elements, i18n.language]);
const handleSubmit = async (ev: SyntheticEvent) => {
ev.preventDefault();
@@ -71,6 +143,10 @@ const PaymentForm = (props: Props) => {
return;
}
if (!stripe || !elements) {
return;
}
setState({ status: "processing" });
let payload;
@@ -130,64 +206,23 @@ const PaymentForm = (props: Props) => {
}
};
const disableButtons = isCanceling || !holdAcknowledged || ["processing", "error"].includes(state.status);
return (
<form id="payment-form" className="bg-subtle mt-4 rounded-md p-6" onSubmit={handleSubmit}>
<div>
<PaymentElement onChange={() => setState({ status: "idle" })} />
</div>
{paymentOption === "HOLD" && (
<div className="bg-info mb-5 mt-2 rounded-md p-3">
<CheckboxField
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-info font-semibold"
/>
</div>
)}
<div className="mt-2 flex justify-end space-x-2">
<Button
color="minimal"
disabled={disableButtons}
id="cancel"
type="button"
loading={isCanceling}
onClick={() => {
setIsCanceling(true);
if (username) {
return router.push(`/${username}`);
}
return router.back();
}}>
<span id="button-text">{t("cancel")}</span>
</Button>
<Button
type="submit"
disabled={disableButtons}
loading={state.status === "processing"}
id="submit"
color="secondary">
<span id="button-text">
{state.status === "processing" ? (
<div className="spinner" id="spinner" />
) : paymentOption === "HOLD" ? (
t("submit_card")
) : (
t("pay_now")
)}
</span>
</Button>
</div>
{state.status === "error" && (
<div className="mt-4 text-center text-red-900 dark:text-gray-300" role="alert">
{state.error.message}
</div>
)}
</form>
<PaymentFormComponent
{...props}
elements={elements}
paymentOption={paymentOption}
state={state}
onSubmit={handleSubmit}
onCancel={() => {
if (username) {
return router.push(`/${username}`);
}
return router.back();
}}
onPaymentElementChange={() => {
setState({ status: "idle" });
}}
/>
);
};
@@ -4,6 +4,7 @@ import { z } from "zod";
import { getClientSecretFromPayment } from "@calcom/features/ee/payments/pages/getClientSecretFromPayment";
import prisma from "@calcom/prisma";
import { BookingStatus } from "@calcom/prisma/enums";
import { paymentDataSelect } from "@calcom/prisma/selects/payment";
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import type { inferSSRProps } from "@calcom/types/inferSSRProps";
@@ -23,68 +24,7 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
where: {
uid,
},
select: {
data: true,
success: true,
uid: true,
refunded: true,
bookingId: true,
appId: true,
amount: true,
currency: true,
paymentOption: true,
booking: {
select: {
id: true,
uid: true,
description: true,
title: true,
startTime: true,
endTime: true,
attendees: {
select: {
email: true,
name: true,
},
},
eventTypeId: true,
location: true,
status: true,
rejectionReason: true,
cancellationReason: true,
eventType: {
select: {
id: true,
title: true,
description: true,
length: true,
eventName: true,
requiresConfirmation: true,
userId: true,
metadata: true,
users: {
select: {
name: true,
username: true,
hideBranding: true,
theme: true,
},
},
team: {
select: {
name: true,
hideBranding: true,
},
},
price: true,
currency: true,
successRedirectUrl: true,
forwardParamsSuccessRedirect: true,
},
},
},
},
},
select: paymentDataSelect,
});
if (!rawPayment) return { notFound: true } as const;