feat/payment-service-6438-cal-767 (#6677)
* WIP paymentService * Changes for payment Service * Fix for stripe payment flow * Remove logs/comments * Refactored refund for stripe app * Move stripe handlePayment to own lib * Move stripe delete payments to paymentService * lint fix * Change handleRefundError as generic function * remove log * remove logs * remove logs * Return stripe default export to lib/server * Fixing types * Fix types * Upgrades typescript * Update yarn lock * Typings * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) * Hotfix: ping,riverside,whereby and around not showing up in list (#6712) (#6713) * Adds deployment settings to DB (#6706) * WIP * Adds DeploymentTheme * Add missing migrations * Adds client extensions for deployment * Cleanup * Revert "lint fix" This reverts commit e1a2e4a357e58e6673c47399888ae2e00d1351a6. * Add validation * Revert changes removed in force push * Removing abstract class and just leaving interface implementation * Fix types for handlePayments * Fix payment test appStore import * Fix stripe metadata in event type * Move migration to separate PR * Revert "Move migration to separate PR" This reverts commit 48aa64e0724a522d3cc2fefaaaee5792ee9cd9e6. * Update packages/prisma/migrations/20230125175109_remove_type_from_payment_and_add_app_relationship/migration.sql Co-authored-by: Omar López <[email protected]> --------- Co-authored-by: zomars <[email protected]> Co-authored-by: Hariom Balhara <[email protected]>
This commit is contained in:
30 files changed
+761
-273
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
BookingStatus,
|
||||
MembershipRole,
|
||||
Prisma,
|
||||
PrismaPromise,
|
||||
WebhookTriggerEvents,
|
||||
@@ -8,10 +9,10 @@ import {
|
||||
} from "@prisma/client";
|
||||
import { NextApiRequest } from "next";
|
||||
|
||||
import appStore from "@calcom/app-store";
|
||||
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
|
||||
import { FAKE_DAILY_CREDENTIAL } from "@calcom/app-store/dailyvideo/lib/VideoApiAdapter";
|
||||
import { DailyLocationType } from "@calcom/app-store/locations";
|
||||
import { refund } from "@calcom/app-store/stripepayment/lib/server";
|
||||
import { cancelScheduledJobs } from "@calcom/app-store/zapier/lib/nodeScheduler";
|
||||
import { deleteMeeting } from "@calcom/core/videoClient";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
@@ -23,6 +24,7 @@ import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";
|
||||
import sendPayload, { EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
|
||||
import { isPrismaObjOrUndefined, parseRecurringEvent } from "@calcom/lib";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { handleRefundError } from "@calcom/lib/payment/handleRefundError";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import prisma, { bookingMinimalSelect } from "@calcom/prisma";
|
||||
import { schemaBookingCancelParams } from "@calcom/prisma/zod-utils";
|
||||
@@ -65,6 +67,8 @@ async function handler(req: NextApiRequest & { userId?: number }) {
|
||||
paid: true,
|
||||
eventType: {
|
||||
select: {
|
||||
owner: true,
|
||||
teamId: true,
|
||||
recurringEvent: true,
|
||||
title: true,
|
||||
description: true,
|
||||
@@ -377,7 +381,76 @@ async function handler(req: NextApiRequest & { userId?: number }) {
|
||||
uid: bookingToDelete.uid ?? "",
|
||||
destinationCalendar: bookingToDelete?.destinationCalendar || bookingToDelete?.user.destinationCalendar,
|
||||
};
|
||||
await refund(bookingToDelete, evt);
|
||||
|
||||
const successPayment = bookingToDelete.payment.find((payment) => payment.success);
|
||||
if (!successPayment) {
|
||||
throw new Error("Cannot reject a booking without a successful payment");
|
||||
}
|
||||
|
||||
let eventTypeOwnerId;
|
||||
if (bookingToDelete.eventType?.owner) {
|
||||
eventTypeOwnerId = bookingToDelete.eventType.owner.id;
|
||||
} else if (bookingToDelete.eventType?.teamId) {
|
||||
const teamOwner = await prisma.membership.findFirst({
|
||||
where: {
|
||||
teamId: bookingToDelete.eventType.teamId,
|
||||
role: MembershipRole.OWNER,
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
eventTypeOwnerId = teamOwner?.userId;
|
||||
}
|
||||
|
||||
if (!eventTypeOwnerId) {
|
||||
throw new Error("Event Type owner not found for obtaining payment app credentials");
|
||||
}
|
||||
|
||||
const paymentAppCredentials = await prisma.credential.findMany({
|
||||
where: {
|
||||
userId: eventTypeOwnerId,
|
||||
appId: successPayment.appId,
|
||||
},
|
||||
select: {
|
||||
key: true,
|
||||
appId: true,
|
||||
app: {
|
||||
select: {
|
||||
categories: true,
|
||||
dirName: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const paymentAppCredential = paymentAppCredentials.find((credential) => {
|
||||
return credential.appId === successPayment.appId;
|
||||
});
|
||||
|
||||
if (!paymentAppCredential) {
|
||||
throw new Error("Payment app credentials not found");
|
||||
}
|
||||
|
||||
// Posible to refactor TODO:
|
||||
const paymentApp = appStore[paymentAppCredential?.app?.dirName as keyof typeof appStore];
|
||||
if (!(paymentApp && "lib" in paymentApp && "PaymentService" in paymentApp.lib)) {
|
||||
console.warn(`payment App service of type ${paymentApp} is not implemented`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const PaymentService = paymentApp.lib.PaymentService;
|
||||
const paymentInstance = new PaymentService(paymentAppCredential);
|
||||
try {
|
||||
await paymentInstance.refund(successPayment.id);
|
||||
} catch (error) {
|
||||
await handleRefundError({
|
||||
event: evt,
|
||||
reason: error?.toString() || "unknown",
|
||||
paymentId: successPayment.externalId,
|
||||
});
|
||||
}
|
||||
|
||||
await prisma.booking.update({
|
||||
where: {
|
||||
id: bookingToDelete.id,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
App,
|
||||
BookingStatus,
|
||||
Credential,
|
||||
EventTypeCustomInput,
|
||||
@@ -18,8 +19,7 @@ import { metadata as GoogleMeetMetadata } from "@calcom/app-store/googlevideo/_m
|
||||
import { getLocationValueForDB, LocationObject } from "@calcom/app-store/locations";
|
||||
import { MeetLocationType } from "@calcom/app-store/locations";
|
||||
import { handleEthSignature } from "@calcom/app-store/rainbow/utils/ethereum";
|
||||
import { handlePayment } from "@calcom/app-store/stripepayment/lib/server";
|
||||
import { getEventTypeAppData } from "@calcom/app-store/utils";
|
||||
import { EventTypeAppsList, getEventTypeAppData } from "@calcom/app-store/utils";
|
||||
import { cancelScheduledJobs, scheduleTrigger } from "@calcom/app-store/zapier/lib/nodeScheduler";
|
||||
import EventManager from "@calcom/core/EventManager";
|
||||
import { getEventName } from "@calcom/core/event";
|
||||
@@ -37,10 +37,11 @@ import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";
|
||||
import { isPrismaObjOrUndefined, parseRecurringEvent } from "@calcom/lib";
|
||||
import { getDefaultEvent, getGroupName, getUsernameList } from "@calcom/lib/defaultEvents";
|
||||
import { getErrorFromUnknown } from "@calcom/lib/errors";
|
||||
import getStripeAppData from "@calcom/lib/getStripeAppData";
|
||||
import getPaymentAppData from "@calcom/lib/getPaymentAppData";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import isOutOfBounds, { BookingDateInPastError } from "@calcom/lib/isOutOfBounds";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { handlePayment } from "@calcom/lib/payment/handlePayment";
|
||||
import { checkBookingLimits, getLuckyUser } from "@calcom/lib/server";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { updateWebUser as syncServicesUpdateWebUser } from "@calcom/lib/sync/SyncServiceManager";
|
||||
@@ -63,6 +64,15 @@ const log = logger.getChildLogger({ prefix: ["[api] book:user"] });
|
||||
type User = Prisma.UserGetPayload<typeof userSelect>;
|
||||
type BufferedBusyTimes = BufferedBusyTime[];
|
||||
|
||||
interface IEventTypePaymentCredentialType {
|
||||
appId: EventTypeAppsList;
|
||||
app: {
|
||||
categories: App["categories"];
|
||||
dirName: string;
|
||||
};
|
||||
key: Prisma.JsonValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refreshes a Credential with fresh data from the database.
|
||||
*
|
||||
@@ -324,7 +334,7 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
|
||||
|
||||
if (!eventType) throw new HttpError({ statusCode: 404, message: "eventType.notFound" });
|
||||
|
||||
const stripeAppData = getStripeAppData(eventType);
|
||||
const paymentAppData = getPaymentAppData(eventType);
|
||||
|
||||
// Check if required custom inputs exist
|
||||
handleCustomInputs(eventType.customInputs as EventTypeCustomInput[], reqBody.customInputs);
|
||||
@@ -634,18 +644,48 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
|
||||
const eventManager = new EventManager({ ...organizerUser, credentials });
|
||||
await eventManager.updateCalendarAttendees(evt, booking);
|
||||
|
||||
if (!Number.isNaN(stripeAppData.price) && stripeAppData.price > 0 && !!booking) {
|
||||
const [firstStripeCredential] = organizerUser.credentials.filter(
|
||||
(cred) => cred.type == "stripe_payment"
|
||||
if (!Number.isNaN(paymentAppData.price) && paymentAppData.price > 0 && !!booking) {
|
||||
const credentialPaymentAppCategories = await prisma.credential.findMany({
|
||||
where: {
|
||||
userId: organizerUser.id,
|
||||
app: {
|
||||
categories: {
|
||||
hasSome: ["payment"],
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
key: true,
|
||||
appId: true,
|
||||
app: {
|
||||
select: {
|
||||
categories: true,
|
||||
dirName: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const eventTypePaymentAppCredential = credentialPaymentAppCategories.find((credential) => {
|
||||
return credential.appId === paymentAppData.appId;
|
||||
});
|
||||
|
||||
if (!eventTypePaymentAppCredential) {
|
||||
throw new HttpError({ statusCode: 400, message: "Missing payment credentials" });
|
||||
}
|
||||
if (!eventTypePaymentAppCredential?.appId) {
|
||||
throw new HttpError({ statusCode: 400, message: "Missing payment app id" });
|
||||
}
|
||||
|
||||
const payment = await handlePayment(
|
||||
evt,
|
||||
eventType,
|
||||
eventTypePaymentAppCredential as IEventTypePaymentCredentialType,
|
||||
booking
|
||||
);
|
||||
|
||||
if (!firstStripeCredential)
|
||||
throw new HttpError({ statusCode: 400, message: "Missing payment credentials" });
|
||||
|
||||
const payment = await handlePayment(evt, eventType, firstStripeCredential, booking);
|
||||
|
||||
req.statusCode = 201;
|
||||
return { ...booking, message: "Payment required", paymentUid: payment.uid };
|
||||
return { ...booking, message: "Payment required", paymentUid: payment?.uid };
|
||||
}
|
||||
|
||||
req.statusCode = 201;
|
||||
@@ -713,7 +753,7 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
|
||||
// Otherwise, an owner rescheduling should be always accepted.
|
||||
// Before comparing make sure that userId is set, otherwise undefined === undefined
|
||||
const userReschedulingIsOwner = userId && originalRescheduledBooking?.user?.id === userId;
|
||||
const isConfirmedByDefault = (!requiresConfirmation && !stripeAppData.price) || userReschedulingIsOwner;
|
||||
const isConfirmedByDefault = (!requiresConfirmation && !paymentAppData.price) || userReschedulingIsOwner;
|
||||
|
||||
async function createBooking() {
|
||||
if (originalRescheduledBooking) {
|
||||
@@ -807,7 +847,7 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof stripeAppData.price === "number" && stripeAppData.price > 0) {
|
||||
if (typeof paymentAppData.price === "number" && paymentAppData.price > 0) {
|
||||
/* Validate if there is any stripe_payment credential for this user */
|
||||
/* note: removes custom error message about stripe */
|
||||
await prisma.credential.findFirstOrThrow({
|
||||
@@ -939,7 +979,7 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
|
||||
}
|
||||
// If it's not a reschedule, doesn't require confirmation and there's no price,
|
||||
// Create a booking
|
||||
} else if (!requiresConfirmation && !stripeAppData.price) {
|
||||
} else if (!requiresConfirmation && !paymentAppData.price) {
|
||||
// Use EventManager to conditionally use all needed integrations.
|
||||
const createManager = await eventManager.create(evt);
|
||||
|
||||
@@ -1019,21 +1059,51 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
|
||||
}
|
||||
|
||||
if (
|
||||
!Number.isNaN(stripeAppData.price) &&
|
||||
stripeAppData.price > 0 &&
|
||||
!Number.isNaN(paymentAppData.price) &&
|
||||
paymentAppData.price > 0 &&
|
||||
!originalRescheduledBooking?.paid &&
|
||||
!!booking
|
||||
) {
|
||||
const [firstStripeCredential] = organizerUser.credentials.filter((cred) => cred.type == "stripe_payment");
|
||||
// Load credentials.app.categories
|
||||
const credentialPaymentAppCategories = await prisma.credential.findMany({
|
||||
where: {
|
||||
userId: organizerUser.id,
|
||||
app: {
|
||||
categories: {
|
||||
hasSome: ["payment"],
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
key: true,
|
||||
appId: true,
|
||||
app: {
|
||||
select: {
|
||||
categories: true,
|
||||
dirName: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const eventTypePaymentAppCredential = credentialPaymentAppCategories.find((credential) => {
|
||||
return credential.appId === paymentAppData.appId;
|
||||
});
|
||||
|
||||
if (!firstStripeCredential)
|
||||
if (!eventTypePaymentAppCredential) {
|
||||
throw new HttpError({ statusCode: 400, message: "Missing payment credentials" });
|
||||
}
|
||||
|
||||
// Convert type of eventTypePaymentAppCredential to appId: EventTypeAppList
|
||||
if (!booking.user) booking.user = organizerUser;
|
||||
const payment = await handlePayment(evt, eventType, firstStripeCredential, booking);
|
||||
const payment = await handlePayment(
|
||||
evt,
|
||||
eventType,
|
||||
eventTypePaymentAppCredential as IEventTypePaymentCredentialType,
|
||||
booking
|
||||
);
|
||||
|
||||
req.statusCode = 201;
|
||||
return { ...booking, message: "Payment required", paymentUid: payment.uid };
|
||||
return { ...booking, message: "Payment required", paymentUid: payment?.uid };
|
||||
}
|
||||
|
||||
log.debug(`Booking ${organizerUser.username} completed`);
|
||||
@@ -1082,7 +1152,7 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
|
||||
eventTitle: eventType.title,
|
||||
eventDescription: eventType.description,
|
||||
requiresConfirmation: requiresConfirmation || null,
|
||||
price: stripeAppData.price,
|
||||
price: paymentAppData.price,
|
||||
currency: eventType.currency,
|
||||
length: eventType.length,
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useRouter } from "next/router";
|
||||
import { stringify } from "querystring";
|
||||
import { SyntheticEvent, useEffect, useState } from "react";
|
||||
|
||||
import { PaymentData } from "@calcom/app-store/stripepayment/lib/server";
|
||||
import { StripePaymentData } from "@calcom/app-store/stripepayment/lib/server";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Button } from "@calcom/ui";
|
||||
|
||||
@@ -29,7 +29,7 @@ const CARD_OPTIONS: stripejs.StripeCardElementOptions = {
|
||||
|
||||
type Props = {
|
||||
payment: {
|
||||
data: PaymentData;
|
||||
data: StripePaymentData;
|
||||
};
|
||||
eventType: { id: number };
|
||||
user: { username: string | null };
|
||||
|
||||
@@ -6,10 +6,11 @@ import { FormattedNumber, IntlProvider } from "react-intl";
|
||||
|
||||
import { getSuccessPageLocationMessage } from "@calcom/app-store/locations";
|
||||
import getStripe from "@calcom/app-store/stripepayment/lib/client";
|
||||
import { StripePaymentData } from "@calcom/app-store/stripepayment/lib/server";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { sdkActionManager, useIsEmbed } from "@calcom/embed-core/embed-iframe";
|
||||
import { APP_NAME, WEBSITE_URL } from "@calcom/lib/constants";
|
||||
import getStripeAppData from "@calcom/lib/getStripeAppData";
|
||||
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";
|
||||
@@ -26,7 +27,7 @@ const PaymentPage: FC<PaymentPageProps> = (props) => {
|
||||
const [timezone, setTimezone] = useState<string | null>(null);
|
||||
useTheme(props.profile.theme);
|
||||
const isEmbed = useIsEmbed();
|
||||
const stripeAppData = getStripeAppData(props.eventType);
|
||||
const paymentAppData = getPaymentAppData(props.eventType);
|
||||
useEffect(() => {
|
||||
let embedIframeWidth = 0;
|
||||
const _timezone = localStorage.getItem("timeOption.preferredTimeZone") || dayjs.tz.guess();
|
||||
@@ -110,9 +111,9 @@ const PaymentPage: FC<PaymentPageProps> = (props) => {
|
||||
<div className="col-span-2 mb-6">
|
||||
<IntlProvider locale="en">
|
||||
<FormattedNumber
|
||||
value={stripeAppData.price / 100.0}
|
||||
value={paymentAppData.price / 100.0}
|
||||
style="currency"
|
||||
currency={stripeAppData.currency.toUpperCase()}
|
||||
currency={paymentAppData?.currency?.toUpperCase()}
|
||||
/>
|
||||
</IntlProvider>
|
||||
</div>
|
||||
@@ -123,8 +124,9 @@ const PaymentPage: FC<PaymentPageProps> = (props) => {
|
||||
{props.payment.success && !props.payment.refunded && (
|
||||
<div className="mt-4 text-center text-gray-700 dark:text-gray-300">{t("paid")}</div>
|
||||
)}
|
||||
{!props.payment.success && (
|
||||
<Elements stripe={getStripe(props.payment.data.stripe_publishable_key)}>
|
||||
{props.payment.appId === "stripe" && !props.payment.success && (
|
||||
<Elements
|
||||
stripe={getStripe((props.payment.data as StripePaymentData).stripe_publishable_key)}>
|
||||
<PaymentComponent
|
||||
payment={props.payment}
|
||||
eventType={props.eventType}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { GetServerSidePropsContext } from "next";
|
||||
import { z } from "zod";
|
||||
|
||||
import { PaymentData } from "@calcom/app-store/stripepayment/lib/server";
|
||||
import { StripePaymentData } 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";
|
||||
@@ -28,6 +28,7 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
|
||||
uid: true,
|
||||
refunded: true,
|
||||
bookingId: true,
|
||||
appId: true,
|
||||
booking: {
|
||||
select: {
|
||||
id: true,
|
||||
@@ -81,7 +82,7 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
|
||||
const { data, booking: _booking, ...restPayment } = rawPayment;
|
||||
const payment = {
|
||||
...restPayment,
|
||||
data: data as unknown as PaymentData,
|
||||
data: data as unknown as StripePaymentData,
|
||||
};
|
||||
|
||||
if (!_booking) return { notFound: true };
|
||||
|
||||
@@ -4,7 +4,7 @@ import { FormattedNumber, IntlProvider } from "react-intl";
|
||||
import { z } from "zod";
|
||||
|
||||
import { classNames, parseRecurringEvent } from "@calcom/lib";
|
||||
import getStripeAppData from "@calcom/lib/getStripeAppData";
|
||||
import getPaymentAppData from "@calcom/lib/getPaymentAppData";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { baseEventTypeSelect } from "@calcom/prisma";
|
||||
import { EventTypeModel } from "@calcom/prisma/zod";
|
||||
@@ -29,7 +29,7 @@ export const EventTypeDescription = ({ eventType, className }: EventTypeDescript
|
||||
[eventType.recurringEvent]
|
||||
);
|
||||
|
||||
const stripeAppData = getStripeAppData(eventType);
|
||||
const stripeAppData = getPaymentAppData(eventType);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -80,7 +80,7 @@ export const EventTypeDescription = ({ eventType, className }: EventTypeDescript
|
||||
<FormattedNumber
|
||||
value={stripeAppData.price / 100.0}
|
||||
style="currency"
|
||||
currency={stripeAppData.currency.toUpperCase()}
|
||||
currency={stripeAppData?.currency?.toUpperCase()}
|
||||
/>
|
||||
</IntlProvider>
|
||||
</Badge>
|
||||
|
||||
Reference in new issue
Block a user