mirror of
https://github.com/lukevella/rallly.git
synced 2025-06-03 11:11:48 +02:00
♻️ Make user required in subscription model (#1585)
This commit is contained in:
parent
01758f81ae
commit
aebea5a41c
5 changed files with 87 additions and 92 deletions
|
@ -24,26 +24,60 @@ export async function onCustomerSubscriptionCreated(event: Stripe.Event) {
|
|||
throw new Error("Missing user ID");
|
||||
}
|
||||
|
||||
// Create and update user
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: res.data.userId,
|
||||
},
|
||||
data: {
|
||||
subscription: {
|
||||
create: {
|
||||
id: subscription.id,
|
||||
active: isActive,
|
||||
priceId,
|
||||
currency,
|
||||
interval,
|
||||
amount,
|
||||
status: subscription.status,
|
||||
createdAt: toDate(subscription.created),
|
||||
periodStart: toDate(subscription.current_period_start),
|
||||
periodEnd: toDate(subscription.current_period_end),
|
||||
const userId = res.data.userId;
|
||||
|
||||
// Check if user already has a subscription
|
||||
const existingUser = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
include: { subscription: true },
|
||||
});
|
||||
|
||||
if (!existingUser) {
|
||||
throw new Error(`User with ID ${userId} not found`);
|
||||
}
|
||||
|
||||
// If user already has a subscription, update it or replace it
|
||||
if (existingUser.subscription) {
|
||||
// Update the existing subscription with new data
|
||||
await prisma.subscription.update({
|
||||
where: { id: existingUser.subscription.id },
|
||||
data: {
|
||||
id: subscription.id,
|
||||
active: isActive,
|
||||
priceId,
|
||||
currency,
|
||||
interval,
|
||||
amount,
|
||||
status: subscription.status,
|
||||
createdAt: toDate(subscription.created),
|
||||
periodStart: toDate(subscription.current_period_start),
|
||||
periodEnd: toDate(subscription.current_period_end),
|
||||
cancelAtPeriodEnd: subscription.cancel_at_period_end,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// Create a new subscription for the user
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
data: {
|
||||
subscription: {
|
||||
create: {
|
||||
id: subscription.id,
|
||||
active: isActive,
|
||||
priceId,
|
||||
currency,
|
||||
interval,
|
||||
amount,
|
||||
status: subscription.status,
|
||||
createdAt: toDate(subscription.created),
|
||||
periodStart: toDate(subscription.current_period_start),
|
||||
periodEnd: toDate(subscription.current_period_end),
|
||||
cancelAtPeriodEnd: subscription.cancel_at_period_end,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue