Skip to content

Commit

Permalink
馃悰 (billing) Fix webhook calls when workspace was deleted
Browse files Browse the repository at this point in the history
  • Loading branch information
baptisteArno committed Feb 13, 2024
1 parent 63dc2e0 commit 191aeb0
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export const OnboardingPage = () => {
if (isOtherCategory)
setOnboardingReplies((prev) => ({
...prev,
categories: prev.onboardingCategories
onboardingCategories: prev.onboardingCategories
? [...prev.onboardingCategories, answer.message]
: [answer.message],
}))
Expand Down
19 changes: 18 additions & 1 deletion apps/builder/src/features/workspace/api/deleteWorkspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import { authenticatedProcedure } from '@/helpers/server/trpc'
import { z } from 'zod'
import { isAdminWriteWorkspaceForbidden } from '../helpers/isAdminWriteWorkspaceForbidden'
import { TRPCError } from '@trpc/server'
import { isNotEmpty } from '@typebot.io/lib/utils'
import Stripe from 'stripe'
import { env } from '@typebot.io/env'

export const deleteWorkspace = authenticatedProcedure
.meta({
Expand Down Expand Up @@ -38,9 +41,23 @@ export const deleteWorkspace = authenticatedProcedure
throw new TRPCError({ code: 'NOT_FOUND', message: 'No workspaces found' })

await prisma.workspace.deleteMany({
where: { members: { some: { userId: user.id } }, id: workspaceId },
where: { id: workspaceId },
})

if (isNotEmpty(workspace.stripeId) && env.STRIPE_SECRET_KEY) {
const stripe = new Stripe(env.STRIPE_SECRET_KEY, {
apiVersion: '2022-11-15',
})

const subscriptions = await stripe.subscriptions.list({
customer: workspace.stripeId,
})

for (const subscription of subscriptions.data) {
await stripe.subscriptions.cancel(subscription.id)
}
}

return {
message: 'Workspace deleted',
}
Expand Down
11 changes: 11 additions & 0 deletions apps/builder/src/pages/api/stripe/webhook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,17 @@ const webhookHandler = async (req: NextApiRequest, res: NextApiResponse) => {
outstandingInvoices.data.filter(
(invoice) => invoice.amount_due > prices['PRO'] * 100
)

const workspaceExist =
(await prisma.workspace.count({
where: {
stripeId: subscription.customer as string,
},
})) > 0

if (!workspaceExist)
return res.send({ message: 'Workspace not found, skipping...' })

const workspace = await prisma.workspace.update({
where: {
stripeId: subscription.customer as string,
Expand Down

0 comments on commit 191aeb0

Please sign in to comment.