2023-10-15 20:26:32 +11:00
|
|
|
import { match } from 'ts-pattern';
|
|
|
|
|
|
2023-12-14 15:22:54 +11:00
|
|
|
import type { Stripe } from '@documenso/lib/server-only/stripe';
|
2023-10-15 20:26:32 +11:00
|
|
|
import { prisma } from '@documenso/prisma';
|
|
|
|
|
import { SubscriptionStatus } from '@documenso/prisma/client';
|
|
|
|
|
|
|
|
|
|
export type OnSubscriptionUpdatedOptions = {
|
|
|
|
|
userId: number;
|
|
|
|
|
subscription: Stripe.Subscription;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const onSubscriptionUpdated = async ({
|
|
|
|
|
userId,
|
|
|
|
|
subscription,
|
|
|
|
|
}: OnSubscriptionUpdatedOptions) => {
|
|
|
|
|
const status = match(subscription.status)
|
|
|
|
|
.with('active', () => SubscriptionStatus.ACTIVE)
|
|
|
|
|
.with('past_due', () => SubscriptionStatus.PAST_DUE)
|
|
|
|
|
.otherwise(() => SubscriptionStatus.INACTIVE);
|
|
|
|
|
|
|
|
|
|
await prisma.subscription.upsert({
|
|
|
|
|
where: {
|
2023-12-14 15:22:54 +11:00
|
|
|
planId: subscription.id,
|
2023-10-15 20:26:32 +11:00
|
|
|
},
|
|
|
|
|
create: {
|
|
|
|
|
status: status,
|
|
|
|
|
planId: subscription.id,
|
|
|
|
|
priceId: subscription.items.data[0].price.id,
|
|
|
|
|
periodEnd: new Date(subscription.current_period_end * 1000),
|
|
|
|
|
userId,
|
2023-12-14 15:22:54 +11:00
|
|
|
cancelAtPeriodEnd: subscription.cancel_at_period_end,
|
2023-10-15 20:26:32 +11:00
|
|
|
},
|
|
|
|
|
update: {
|
|
|
|
|
status: status,
|
|
|
|
|
planId: subscription.id,
|
|
|
|
|
priceId: subscription.items.data[0].price.id,
|
|
|
|
|
periodEnd: new Date(subscription.current_period_end * 1000),
|
2023-12-14 15:22:54 +11:00
|
|
|
cancelAtPeriodEnd: subscription.cancel_at_period_end,
|
2023-10-15 20:26:32 +11:00
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
};
|