diff --git a/packages/lib/ee/LICENSE.md b/packages/lib/ee/LICENSE.md new file mode 100644 index 000000000..eabda6db2 --- /dev/null +++ b/packages/lib/ee/LICENSE.md @@ -0,0 +1 @@ + diff --git a/packages/lib/ee/stripe/create-customer.ts b/packages/lib/ee/stripe/create-customer.ts new file mode 100644 index 000000000..585fbdb22 --- /dev/null +++ b/packages/lib/ee/stripe/create-customer.ts @@ -0,0 +1,32 @@ +import { prisma } from '@documenso/prisma'; +import { User } from '@documenso/prisma/client'; + +import { stripe } from '../../server-only/stripe'; +import { getSubscriptionByUserId } from '../../server-only/subscription/get-subscription-by-user-id'; + +export type CreateCustomerOptions = { + user: User; +}; + +export const createCustomer = async ({ user }: CreateCustomerOptions) => { + const existingSubscription = await getSubscriptionByUserId({ userId: user.id }); + + if (existingSubscription) { + throw new Error('User already has a subscription'); + } + + const customer = await stripe.customers.create({ + name: user.name ?? undefined, + email: user.email, + metadata: { + userId: user.id, + }, + }); + + return await prisma.subscription.create({ + data: { + userId: user.id, + customerId: customer.id, + }, + }); +}; diff --git a/packages/lib/ee/stripe/get-portal-session.ts b/packages/lib/ee/stripe/get-portal-session.ts new file mode 100644 index 000000000..91ecc63ab --- /dev/null +++ b/packages/lib/ee/stripe/get-portal-session.ts @@ -0,0 +1,19 @@ +'use server'; + +import { stripe } from '../../server-only/stripe'; + +export type GetPortalSessionOptions = { + customerId: string; + returnUrl: string; +}; + +export const getPortalSession = async ({ customerId, returnUrl }: GetPortalSessionOptions) => { + 'use server'; + + const session = await stripe.billingPortal.sessions.create({ + customer: customerId, + return_url: returnUrl, + }); + + return session.url; +}; diff --git a/packages/lib/package.json b/packages/lib/package.json index 0d04f6c93..dafac9527 100644 --- a/packages/lib/package.json +++ b/packages/lib/package.json @@ -3,7 +3,7 @@ "version": "1.0.0", "main": "./index.ts", "types": "./index.ts", - "license": "MIT", + "license": "SEE LICENSE IN LICENSE.md", "files": [ "client-only/", "server-only/", diff --git a/packages/lib/server-only/subscription/get-subscription-by-user-id.ts b/packages/lib/server-only/subscription/get-subscription-by-user-id.ts new file mode 100644 index 000000000..19932669a --- /dev/null +++ b/packages/lib/server-only/subscription/get-subscription-by-user-id.ts @@ -0,0 +1,15 @@ +'use server'; + +import { prisma } from '@documenso/prisma'; + +export type GetSubscriptionByUserIdOptions = { + userId: number; +}; + +export const getSubscriptionByUserId = ({ userId }: GetSubscriptionByUserIdOptions) => { + return prisma.subscription.findFirst({ + where: { + userId, + }, + }); +};