Files
sign/packages/ee/server-only/stripe/webhook/on-subscription-updated.ts

42 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-10-15 20:26:32 +11:00
import { match } from 'ts-pattern';
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: {
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,
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),
cancelAtPeriodEnd: subscription.cancel_at_period_end,
2023-10-15 20:26:32 +11:00
},
});
};