diff --git a/ee/apps/billing/routes/stripe.ts b/ee/apps/billing/routes/stripe.ts index 3887f10f..ade0adb1 100644 --- a/ee/apps/billing/routes/stripe.ts +++ b/ee/apps/billing/routes/stripe.ts @@ -31,6 +31,7 @@ stripeApi.post('/webhooks', async (c) => { orgId, price, active: stripeEvent.data.object.status === 'active', + deleteEvent: stripeEvent.type === 'customer.subscription.deleted', stripeCustomerId: stripeEvent.data.object.customer as string, stripeSubscriptionId: stripeEvent.data.object.id }); @@ -77,26 +78,30 @@ type BillingRecordParams = { stripeCustomerId: string; stripeSubscriptionId: string; active: boolean; + deleteEvent: boolean; }; export const createOrUpdateBillingRecords = async ({ active, + deleteEvent, stripeCustomerId, orgId, price, stripeSubscriptionId }: BillingRecordParams) => { + // If the subscription is canceled and the event is a delete event, we need to delete the orgBilling record + if (!active) { + if (deleteEvent) { + await db.delete(orgBilling).where(eq(orgBilling.orgId, orgId)); + } + return; + } + const existingRecord = await db.query.orgBilling.findFirst({ where: eq(orgBilling.orgId, orgId), columns: { id: true } }); - // If the subscription is canceled, we need to delete the orgBilling record - if (!active) { - await db.delete(orgBilling).where(eq(orgBilling.orgId, orgId)); - return; - } - const [plan, period] = price; const values = { orgId, diff --git a/ee/apps/billing/scripts/sync-stripe-db.ts b/ee/apps/billing/scripts/sync-stripe-db.ts index 8a2bd200..2fdf73a7 100644 --- a/ee/apps/billing/scripts/sync-stripe-db.ts +++ b/ee/apps/billing/scripts/sync-stripe-db.ts @@ -116,7 +116,8 @@ for (const entry of orgBillingEntries) { price, stripeCustomerId: subscription.customer as string, stripeSubscriptionId: subscription.id, - active: subscription.status === 'active' + active: subscription.status === 'active', + deleteEvent: false }); } }