Files
sign/apps/web/src/app/(dashboard)/settings/billing/create-checkout.action.ts

41 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-10-13 23:33:40 +11:00
'use server';
import { getCheckoutSession } from '@documenso/ee/server-only/stripe/get-checkout-session';
import { getStripeCustomerByUser } from '@documenso/ee/server-only/stripe/get-customer';
2023-10-13 23:33:40 +11:00
import { getPortalSession } from '@documenso/ee/server-only/stripe/get-portal-session';
import { NEXT_PUBLIC_WEBAPP_URL } from '@documenso/lib/constants/app';
2023-11-16 07:35:45 +05:30
import { getRequiredServerComponentSession } from '@documenso/lib/next-auth/get-server-component-session';
import { getSubscriptionsByUserId } from '@documenso/lib/server-only/subscription/get-subscriptions-by-user-id';
2023-10-13 23:33:40 +11:00
export type CreateCheckoutOptions = {
priceId: string;
};
export const createCheckout = async ({ priceId }: CreateCheckoutOptions) => {
const session = await getRequiredServerComponentSession();
2023-10-13 23:33:40 +11:00
const { user, stripeCustomer } = await getStripeCustomerByUser(session.user);
2023-10-13 23:33:40 +11:00
const existingSubscriptions = await getSubscriptionsByUserId({ userId: user.id });
2023-10-13 23:33:40 +11:00
const foundSubscription = existingSubscriptions.find(
(subscription) =>
subscription.priceId === priceId &&
subscription.periodEnd &&
subscription.periodEnd >= new Date(),
);
2023-10-13 23:33:40 +11:00
if (foundSubscription) {
2023-10-13 23:33:40 +11:00
return getPortalSession({
customerId: stripeCustomer.id,
returnUrl: `${NEXT_PUBLIC_WEBAPP_URL()}/settings/billing`,
2023-10-13 23:33:40 +11:00
});
}
return getCheckoutSession({
customerId: stripeCustomer.id,
priceId,
returnUrl: `${NEXT_PUBLIC_WEBAPP_URL()}/settings/billing`,
2023-10-13 23:33:40 +11:00
});
};