feat: Alby integration (#11495)

Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: alannnc <[email protected]>
Co-authored-by: Hariom Balhara <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
This commit is contained in:
authored and GitHub committed 2023-09-28 12:03:01 +00:00
1 parent ef45cbfb3f
commit 2021b641ce
77 files changed
+2479 -639

No files matched your search

@@ -4,14 +4,15 @@ import React from "react";
import classNames from "@calcom/lib/classNames";
import getPaymentAppData from "@calcom/lib/getPaymentAppData";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Clock, CheckSquare, RefreshCcw, CreditCard } from "@calcom/ui/components/icon";
import { Clock, CheckSquare, RefreshCcw } from "@calcom/ui/components/icon";
import type { PublicEvent } from "../../types";
import { EventDetailBlocks } from "../../types";
import { AvailableEventLocations } from "./AvailableEventLocations";
import { EventDuration } from "./Duration";
import { EventOccurences } from "./Occurences";
import { EventPrice } from "./Price";
import { Price } from "./Price";
import { getPriceIcon } from "./getPriceIcon";
type EventDetailsPropsBase = {
event: PublicEvent;
@@ -156,8 +157,12 @@ export const EventDetails = ({ event, blocks = defaultEventDetailsBlocks }: Even
if (event.price <= 0 || paymentAppData.price <= 0) return null;
return (
<EventMetaBlock key={block} icon={CreditCard}>
<EventPrice event={event} />
<EventMetaBlock key={block} icon={getPriceIcon(event.currency)}>
<Price
price={paymentAppData.price}
currency={event.currency}
displayAlternateSymbol={false}
/>
</EventMetaBlock>
);
}
@@ -1,18 +1,28 @@
import getPaymentAppData from "@calcom/lib/getPaymentAppData";
import dynamic from "next/dynamic";
import type { PublicEvent } from "../../types";
import { formatPrice } from "@calcom/lib/price";
export const EventPrice = ({ event }: { event: PublicEvent }) => {
const stripeAppData = getPaymentAppData(event);
import type { EventPrice } from "../../types";
if (stripeAppData.price === 0) return null;
const AlbyPriceComponent = dynamic(
() => import("@calcom/app-store/alby/components/AlbyPriceComponent").then((m) => m.AlbyPriceComponent),
{
ssr: false,
}
);
return (
<>
{Intl.NumberFormat("en", {
style: "currency",
currency: stripeAppData.currency.toUpperCase(),
}).format(stripeAppData.price / 100.0)}
</>
export const Price = ({ price, currency, displayAlternateSymbol = true }: EventPrice) => {
if (price === 0) return null;
const formattedPrice = formatPrice(price, currency);
return currency !== "BTC" ? (
<>{formattedPrice}</>
) : (
<AlbyPriceComponent
displaySymbol={displayAlternateSymbol}
price={price}
formattedPrice={formattedPrice}
/>
);
};
@@ -0,0 +1,5 @@
import { CreditCard, Zap } from "lucide-react";
export function getPayIcon(currency: string): React.FC<{ className: string }> | string {
return currency !== "BTC" ? CreditCard : Zap;
}
@@ -0,0 +1,7 @@
import { CreditCard } from "lucide-react";
import { SatSymbol } from "@calcom/ui/components/icon/SatSymbol";
export function getPriceIcon(currency: string): React.FC<{ className: string }> | string {
return currency !== "BTC" ? CreditCard : (SatSymbol as React.FC<{ className: string }>);
}
@@ -2,3 +2,5 @@ export { EventDetails, EventMetaBlock } from "./Details";
export { EventTitle } from "./Title";
export { EventMetaSkeleton } from "./Skeleton";
export { EventMembers } from "./Members";
export { getPriceIcon } from "./getPriceIcon";
export { getPayIcon } from "./getPayIcon";
+2
View File
@@ -7,6 +7,8 @@ import type { AppsStatus } from "@calcom/types/Calendar";
export type PublicEvent = NonNullable<RouterOutputs["viewer"]["public"]["event"]>;
export type ValidationErrors<T extends object> = { key: FieldPath<T>; error: ErrorOption }[];
export type EventPrice = { currency: string; price: number; displayAlternateSymbol?: boolean };
export enum EventDetailBlocks {
// Includes duration select when event has multiple durations.
DURATION,
@@ -1,345 +0,0 @@
import type { Prisma } from "@prisma/client";
import type { NextApiRequest, NextApiResponse } from "next";
import getRawBody from "raw-body";
import * as z from "zod";
import { paypalCredentialKeysSchema } from "@calcom/app-store/paypal/lib";
import Paypal from "@calcom/app-store/paypal/lib/Paypal";
import EventManager from "@calcom/core/EventManager";
import { sendScheduledEmails } 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";
import { IS_PRODUCTION } from "@calcom/lib/constants";
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 { BookingStatus } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { CalendarEvent } from "@calcom/types/Calendar";
export const config = {
api: {
bodyParser: false,
},
};
async function getEventType(id: number) {
return prisma.eventType.findUnique({
where: {
id,
},
select: {
recurringEvent: true,
requiresConfirmation: true,
},
});
}
export async function handlePaymentSuccess(
payload: z.infer<typeof eventSchema>,
rawPayload: string,
webhookHeaders: WebHookHeadersType
) {
const payment = await prisma.payment.findFirst({
where: {
externalId: payload?.resource?.id,
},
select: {
id: true,
bookingId: true,
success: true,
},
});
if (!payment?.bookingId) throw new HttpCode({ statusCode: 204, message: "Payment not found" });
const booking = await prisma.booking.findUnique({
where: {
id: payment.bookingId,
},
select: {
...bookingMinimalSelect,
eventType: true,
smsReminderNumber: true,
location: true,
eventTypeId: true,
userId: true,
uid: true,
paid: true,
destinationCalendar: true,
status: true,
responses: true,
user: {
select: {
id: true,
username: true,
credentials: {
select: credentialForCalendarServiceSelect,
},
timeZone: true,
email: true,
name: true,
locale: true,
destinationCalendar: true,
},
},
},
});
if (!booking) throw new HttpCode({ statusCode: 204, message: "No booking found" });
// Probably booking it's already paid from /capture but we need to send confirmation email
const foundCredentials = await findPaymentCredentials(booking.id);
if (!foundCredentials) throw new HttpCode({ statusCode: 204, message: "No credentials found" });
const { webhookId, ...credentials } = foundCredentials;
const paypalClient = new Paypal(credentials);
await paypalClient.getAccessToken();
await paypalClient.verifyWebhook({
body: {
auth_algo: webhookHeaders["paypal-auth-algo"],
cert_url: webhookHeaders["paypal-cert-url"],
transmission_id: webhookHeaders["paypal-transmission-id"],
transmission_sig: webhookHeaders["paypal-transmission-sig"],
transmission_time: webhookHeaders["paypal-transmission-time"],
webhook_id: webhookId,
webhook_event: rawPayload,
},
});
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),
...getCalEventResponses({
booking: booking,
bookingFields: booking.eventType?.bookingFields || null,
}),
organizer: {
email: user.email,
name: user.name!,
timeZone: user.timeZone,
language: { translate: t, locale: user.locale ?? "en" },
},
attendees: attendeesList,
uid: booking.uid,
destinationCalendar: booking.destinationCalendar
? [booking.destinationCalendar]
: user.destinationCalendar
? [user.destinationCalendar]
: [],
recurringEvent: parseRecurringEvent(eventTypeRaw?.recurringEvent),
};
if (booking.location) evt.location = booking.location;
const bookingData: Prisma.BookingUpdateInput = {
paid: true,
status: BookingStatus.ACCEPTED,
};
const isConfirmed = booking.status === BookingStatus.ACCEPTED;
if (isConfirmed) {
const eventManager = new EventManager(user);
const scheduleResult = await eventManager.create(evt);
bookingData.references = { create: scheduleResult.referencesToCreate };
}
if (eventTypeRaw?.requiresConfirmation) {
delete bookingData.status;
}
if (!payment?.success) {
await prisma.payment.update({
where: {
id: payment.id,
},
data: {
success: true,
},
});
}
if (booking.status === "PENDING") {
await prisma.booking.update({
where: {
id: booking.id,
},
data: bookingData,
});
}
if (!isConfirmed && !eventTypeRaw?.requiresConfirmation) {
await handleConfirmation({ user, evt, prisma, bookingId: booking.id, booking, paid: true });
} else {
await sendScheduledEmails({ ...evt });
}
throw new HttpCode({
statusCode: 200,
message: `Booking with id '${booking.id}' was paid and confirmed.`,
});
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
if (req.method !== "POST") {
throw new HttpCode({ statusCode: 405, message: "Method Not Allowed" });
}
const bodyRaw = await getRawBody(req);
const headers = req.headers;
const bodyAsString = bodyRaw.toString();
const parseHeaders = webhookHeadersSchema.safeParse(headers);
if (!parseHeaders.success) {
console.error(parseHeaders.error);
throw new HttpCode({ statusCode: 400, message: "Bad Request" });
}
const parse = eventSchema.safeParse(JSON.parse(bodyAsString));
if (!parse.success) {
console.error(parse.error);
throw new HttpCode({ statusCode: 400, message: "Bad Request" });
}
const { data: parsedPayload } = parse;
if (parsedPayload.event_type === "CHECKOUT.ORDER.APPROVED") {
return await handlePaymentSuccess(parsedPayload, bodyAsString, parseHeaders.data);
}
} catch (_err) {
const err = getErrorFromUnknown(_err);
console.error(`Webhook Error: ${err.message}`);
res.status(200).send({
message: err.message,
stack: IS_PRODUCTION ? undefined : err.stack,
});
return;
}
// Return a response to acknowledge receipt of the event
res.status(200).end();
}
const resourceSchema = z
.object({
create_time: z.string(),
id: z.string(),
payment_source: z.object({
paypal: z.object({}).optional(),
}),
intent: z.string(),
payer: z.object({
email_address: z.string(),
payer_id: z.string(),
address: z.object({
country_code: z.string(),
}),
}),
status: z.string().optional(),
})
.passthrough();
const eventSchema = z
.object({
id: z.string(),
create_time: z.string(),
resource_type: z.string(),
event_type: z.string(),
summary: z.string(),
resource: resourceSchema,
status: z.string().optional(),
event_version: z.string(),
resource_version: z.string(),
})
.passthrough();
const webhookHeadersSchema = z
.object({
"paypal-auth-algo": z.string(),
"paypal-cert-url": z.string(),
"paypal-transmission-id": z.string(),
"paypal-transmission-sig": z.string(),
"paypal-transmission-time": z.string(),
})
.passthrough();
type WebHookHeadersType = z.infer<typeof webhookHeadersSchema>;
export const findPaymentCredentials = async (
bookingId: number
): Promise<{ clientId: string; secretKey: string; webhookId: string }> => {
try {
// @TODO: what about team bookings with paypal?
const userFromBooking = await prisma.booking.findFirst({
where: {
id: bookingId,
},
select: {
id: true,
userId: true,
},
});
if (!userFromBooking) throw new Error("No user found");
const credentials = await prisma.credential.findFirst({
where: {
appId: "paypal",
userId: userFromBooking?.userId,
},
select: {
key: true,
},
});
if (!credentials) {
throw new Error("No credentials found");
}
const parsedCredentials = paypalCredentialKeysSchema.safeParse(credentials?.key);
if (!parsedCredentials.success) {
throw new Error("Credentials malformed");
}
return {
clientId: parsedCredentials.data.client_id,
secretKey: parsedCredentials.data.secret_key,
webhookId: parsedCredentials.data.webhook_id,
};
} catch (err) {
console.error(err);
return {
clientId: "",
secretKey: "",
webhookId: "",
};
}
};
+5 -143
View File
@@ -6,13 +6,13 @@ 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 { sendAttendeeRequestEmail, sendOrganizerRequestEmail, sendScheduledEmails } from "@calcom/emails";
import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";
import { sendOrganizerRequestEmail, sendAttendeeRequestEmail } from "@calcom/emails";
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 { 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";
@@ -129,7 +129,7 @@ async function getBooking(bookingId: number) {
};
}
async function handlePaymentSuccess(event: Stripe.Event) {
async function handleStripePaymentSuccess(event: Stripe.Event) {
const paymentIntent = event.data.object as Stripe.PaymentIntent;
const payment = await prisma.payment.findFirst({
where: {
@@ -145,145 +145,7 @@ async function handlePaymentSuccess(event: Stripe.Event) {
}
if (!payment?.bookingId) throw new HttpCode({ statusCode: 204, message: "Payment not found" });
const booking = await prisma.booking.findUnique({
where: {
id: payment.bookingId,
},
select: {
...bookingMinimalSelect,
eventType: true,
smsReminderNumber: true,
location: true,
eventTypeId: true,
userId: true,
uid: true,
paid: true,
destinationCalendar: true,
status: true,
responses: true,
user: {
select: {
id: true,
username: true,
credentials: { select: credentialForCalendarServiceSelect },
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 { user: userWithCredentials } = booking;
if (!userWithCredentials) throw new HttpCode({ statusCode: 204, message: "No user found" });
const { credentials, ...user } = userWithCredentials;
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),
...getCalEventResponses({
booking: booking,
bookingFields: booking.eventType?.bookingFields || null,
}),
organizer: {
email: user.email,
name: user.name!,
timeZone: user.timeZone,
timeFormat: getTimeFormatStringFromUserTimeFormat(user.timeFormat),
language: { translate: t, locale: user.locale ?? "en" },
},
attendees: attendeesList,
location: booking.location,
uid: booking.uid,
destinationCalendar: selectedDestinationCalendar ? [selectedDestinationCalendar] : [],
recurringEvent: parseRecurringEvent(eventTypeRaw?.recurringEvent),
};
if (booking.location) evt.location = booking.location;
const bookingData: Prisma.BookingUpdateInput = {
paid: true,
status: BookingStatus.ACCEPTED,
};
const isConfirmed = booking.status === BookingStatus.ACCEPTED;
if (isConfirmed) {
const eventManager = new EventManager(userWithCredentials);
const scheduleResult = await eventManager.create(evt);
bookingData.references = { create: scheduleResult.referencesToCreate };
}
if (eventTypeRaw?.requiresConfirmation) {
delete bookingData.status;
}
const paymentUpdate = prisma.payment.update({
where: {
id: payment.id,
},
data: {
success: true,
},
});
const bookingUpdate = prisma.booking.update({
where: {
id: booking.id,
},
data: bookingData,
});
await prisma.$transaction([paymentUpdate, bookingUpdate]);
if (!isConfirmed && !eventTypeRaw?.requiresConfirmation) {
await handleConfirmation({
user: userWithCredentials,
evt,
prisma,
bookingId: booking.id,
booking,
paid: true,
});
} else {
await sendScheduledEmails({ ...evt });
}
throw new HttpCode({
statusCode: 200,
message: `Booking with id '${booking.id}' was paid and confirmed.`,
});
await handlePaymentSuccess(payment.id, payment.bookingId);
}
const handleSetupSuccess = async (event: Stripe.Event) => {
@@ -372,7 +234,7 @@ const handleSetupSuccess = async (event: Stripe.Event) => {
type WebhookHandler = (event: Stripe.Event) => Promise<void>;
const webhookHandlers: Record<string, WebhookHandler | undefined> = {
"payment_intent.succeeded": handlePaymentSuccess,
"payment_intent.succeeded": handleStripePaymentSuccess,
"setup_intent.succeeded": handleSetupSuccess,
};
@@ -7,13 +7,14 @@ import { useEffect, useState } from "react";
import { getSuccessPageLocationMessage } from "@calcom/app-store/locations";
import dayjs from "@calcom/dayjs";
import { sdkActionManager, useIsEmbed } from "@calcom/embed-core/embed-iframe";
import { Price } from "@calcom/features/bookings/components/event-meta/Price";
import { getPayIcon } from "@calcom/features/bookings/components/event-meta/getPayIcon";
import { APP_NAME, WEBSITE_URL } from "@calcom/lib/constants";
import getPaymentAppData from "@calcom/lib/getPaymentAppData";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import useTheme from "@calcom/lib/hooks/useTheme";
import { getIs24hClockFromLocalStorage, isBrowserLocale24h } from "@calcom/lib/timeFormat";
import { localStorage } from "@calcom/lib/webstorage";
import { CreditCard } from "@calcom/ui/components/icon";
import type { PaymentPageProps } from "../pages/payment";
@@ -31,6 +32,13 @@ const PaypalPaymentComponent = dynamic(
}
);
const AlbyPaymentComponent = dynamic(
() => import("@calcom/app-store/alby/components/AlbyPaymentComponent").then((m) => m.AlbyPaymentComponent),
{
ssr: false,
}
);
const PaymentPage: FC<PaymentPageProps> = (props) => {
const { t, i18n } = useLocale();
const [is24h, setIs24h] = useState(isBrowserLocale24h());
@@ -66,6 +74,7 @@ const PaymentPage: FC<PaymentPageProps> = (props) => {
}, [isEmbed]);
const eventName = props.booking.title;
const PayIcon = getPayIcon(paymentAppData.currency);
return (
<div className="h-screen">
@@ -92,7 +101,7 @@ const PaymentPage: FC<PaymentPageProps> = (props) => {
aria-labelledby="modal-headline">
<div>
<div className="bg-success mx-auto flex h-12 w-12 items-center justify-center rounded-full">
<CreditCard className="h-8 w-8 text-green-600" />
<PayIcon className="h-8 w-8 text-green-600" />
</div>
<div className="mt-3 text-center sm:mt-5">
@@ -121,10 +130,11 @@ const PaymentPage: FC<PaymentPageProps> = (props) => {
{props.payment.paymentOption === "HOLD" ? t("no_show_fee") : t("price")}
</div>
<div className="col-span-2 mb-6 font-semibold">
{new Intl.NumberFormat(i18n.language, {
style: "currency",
currency: paymentAppData.currency,
}).format(paymentAppData.price / 100.0)}
<Price
currency={paymentAppData.currency}
price={paymentAppData.price}
displayAlternateSymbol={false}
/>
</div>
</div>
</div>
@@ -146,6 +156,9 @@ const PaymentPage: FC<PaymentPageProps> = (props) => {
{props.payment.appId === "paypal" && !props.payment.success && (
<PaypalPaymentComponent payment={props.payment} />
)}
{props.payment.appId === "alby" && !props.payment.success && (
<AlbyPaymentComponent payment={props.payment} paymentPageProps={props} />
)}
{props.payment.refunded && (
<div className="text-default mt-4 text-center dark:text-gray-300">{t("refunded")}</div>
)}
@@ -2,6 +2,8 @@ import type { Prisma } from "@prisma/client";
import { useMemo } from "react";
import type { z } from "zod";
import { Price } from "@calcom/features/bookings/components/event-meta/Price";
import { getPriceIcon } from "@calcom/features/bookings/components/event-meta/getPriceIcon";
import { classNames, parseRecurringEvent } from "@calcom/lib";
import getPaymentAppData from "@calcom/lib/getPaymentAppData";
import { useLocale } from "@calcom/lib/hooks/useLocale";
@@ -9,7 +11,7 @@ import type { baseEventTypeSelect } from "@calcom/prisma";
import { SchedulingType } from "@calcom/prisma/enums";
import type { EventTypeModel } from "@calcom/prisma/zod";
import { Badge } from "@calcom/ui";
import { Clock, Users, RefreshCw, CreditCard, Clipboard, Plus, User, Lock } from "@calcom/ui/components/icon";
import { Clock, Users, RefreshCw, Clipboard, Plus, User, Lock } from "@calcom/ui/components/icon";
export type EventTypeDescriptionProps = {
eventType: Pick<
@@ -94,11 +96,12 @@ export const EventTypeDescription = ({
)}
{paymentAppData.enabled && (
<li>
<Badge variant="gray" startIcon={CreditCard}>
{new Intl.NumberFormat(i18n.language, {
style: "currency",
currency: paymentAppData.currency,
}).format(paymentAppData.price / 100)}
<Badge variant="gray" startIcon={getPriceIcon(paymentAppData.currency)}>
<Price
currency={paymentAppData.currency}
price={paymentAppData.price}
displayAlternateSymbol={false}
/>
</Badge>
</li>
)}