Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

⚡ (billing) Automatic usage-based billing #924

Merged
merged 3 commits into from
Oct 17, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Send chats limit alert emails
name: Check and report chats usage

on:
schedule:
Expand All @@ -22,8 +22,9 @@ jobs:
SMTP_HOST: '${{ secrets.SMTP_HOST }}'
SMTP_PORT: '${{ secrets.SMTP_PORT }}'
NEXT_PUBLIC_SMTP_FROM: '${{ secrets.NEXT_PUBLIC_SMTP_FROM }}'
STRIPE_SECRET_KEY: '${{ secrets.STRIPE_SECRET_KEY }}'
steps:
- uses: actions/checkout@v2
- uses: pnpm/[email protected]
- run: pnpm i --frozen-lockfile
- run: pnpm turbo run sendAlertEmails
- run: pnpm turbo run checkAndReportChatsUsage
24 changes: 0 additions & 24 deletions .github/workflows/send-total-results-digest.yml

This file was deleted.

46 changes: 17 additions & 29 deletions apps/builder/src/features/billing/api/createCheckoutSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { TRPCError } from '@trpc/server'
import { Plan } from '@typebot.io/prisma'
import Stripe from 'stripe'
import { z } from 'zod'
import { parseSubscriptionItems } from '../helpers/parseSubscriptionItems'
import { isAdminWriteWorkspaceForbidden } from '@/features/workspace/helpers/isAdminWriteWorkspaceForbidden'
import { env } from '@typebot.io/env'

Expand All @@ -26,14 +25,12 @@ export const createCheckoutSession = authenticatedProcedure
currency: z.enum(['usd', 'eur']),
plan: z.enum([Plan.STARTER, Plan.PRO]),
returnUrl: z.string(),
additionalChats: z.number(),
vat: z
.object({
type: z.string(),
value: z.string(),
})
.optional(),
isYearly: z.boolean(),
})
)
.output(
Expand All @@ -43,17 +40,7 @@ export const createCheckoutSession = authenticatedProcedure
)
.mutation(
async ({
input: {
vat,
email,
company,
workspaceId,
currency,
plan,
returnUrl,
additionalChats,
isYearly,
},
input: { vat, email, company, workspaceId, currency, plan, returnUrl },
ctx: { user },
}) => {
if (!env.STRIPE_SECRET_KEY)
Expand Down Expand Up @@ -116,8 +103,6 @@ export const createCheckoutSession = authenticatedProcedure
currency,
plan,
returnUrl,
additionalChats,
isYearly,
})

if (!checkoutUrl)
Expand All @@ -138,22 +123,12 @@ type Props = {
currency: 'usd' | 'eur'
plan: 'STARTER' | 'PRO'
returnUrl: string
additionalChats: number
isYearly: boolean
userId: string
}

export const createCheckoutSessionUrl =
(stripe: Stripe) =>
async ({
customerId,
workspaceId,
currency,
plan,
returnUrl,
additionalChats,
isYearly,
}: Props) => {
async ({ customerId, workspaceId, currency, plan, returnUrl }: Props) => {
const session = await stripe.checkout.sessions.create({
success_url: `${returnUrl}?stripe=${plan}&success=true`,
cancel_url: `${returnUrl}?stripe=cancel`,
Expand All @@ -167,12 +142,25 @@ export const createCheckoutSessionUrl =
metadata: {
workspaceId,
plan,
additionalChats,
},
currency,
billing_address_collection: 'required',
automatic_tax: { enabled: true },
line_items: parseSubscriptionItems(plan, additionalChats, isYearly),
line_items: [
{
price:
plan === 'STARTER'
? env.STRIPE_STARTER_PRICE_ID
: env.STRIPE_PRO_PRICE_ID,
quantity: 1,
},
{
price:
plan === 'STARTER'
? env.STRIPE_STARTER_CHATS_PRICE_ID
: env.STRIPE_PRO_CHATS_PRICE_ID,
},
],
})

return session.url
Expand Down
17 changes: 5 additions & 12 deletions apps/builder/src/features/billing/api/getSubscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import Stripe from 'stripe'
import { z } from 'zod'
import { subscriptionSchema } from '@typebot.io/schemas/features/billing/subscription'
import { isReadWorkspaceFobidden } from '@/features/workspace/helpers/isReadWorkspaceFobidden'
import { priceIds } from '@typebot.io/lib/api/pricing'
import { env } from '@typebot.io/env'

export const getSubscription = authenticatedProcedure
Expand Down Expand Up @@ -75,24 +74,18 @@ export const getSubscription = authenticatedProcedure

return {
subscription: {
currentBillingPeriod:
subscriptionSchema.shape.currentBillingPeriod.parse({
start: new Date(currentSubscription.current_period_start),
end: new Date(currentSubscription.current_period_end),
}),
status: subscriptionSchema.shape.status.parse(
currentSubscription.status
),
isYearly: currentSubscription.items.data.some((item) => {
return (
priceIds.STARTER.chats.yearly === item.price.id ||
priceIds.PRO.chats.yearly === item.price.id
)
}),
currency: currentSubscription.currency as 'usd' | 'eur',
cancelDate: currentSubscription.cancel_at
? new Date(currentSubscription.cancel_at * 1000)
: undefined,
},
}
})

export const chatPriceIds = [priceIds.STARTER.chats.monthly]
.concat(priceIds.STARTER.chats.yearly)
.concat(priceIds.PRO.chats.monthly)
.concat(priceIds.PRO.chats.yearly)
56 changes: 52 additions & 4 deletions apps/builder/src/features/billing/api/getUsage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { authenticatedProcedure } from '@/helpers/server/trpc'
import { TRPCError } from '@trpc/server'
import { z } from 'zod'
import { isReadWorkspaceFobidden } from '@/features/workspace/helpers/isReadWorkspaceFobidden'
import { env } from '@typebot.io/env'
import Stripe from 'stripe'

export const getUsage = authenticatedProcedure
.meta({
Expand All @@ -19,13 +21,15 @@ export const getUsage = authenticatedProcedure
workspaceId: z.string(),
})
)
.output(z.object({ totalChatsUsed: z.number() }))
.output(z.object({ totalChatsUsed: z.number(), resetsAt: z.date() }))
.query(async ({ input: { workspaceId }, ctx: { user } }) => {
const workspace = await prisma.workspace.findFirst({
where: {
id: workspaceId,
},
select: {
stripeId: true,
plan: true,
members: {
select: {
userId: true,
Expand All @@ -42,19 +46,63 @@ export const getUsage = authenticatedProcedure
message: 'Workspace not found',
})

const now = new Date()
const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
if (
!env.STRIPE_SECRET_KEY ||
!workspace.stripeId ||
(workspace.plan !== 'STARTER' && workspace.plan !== 'PRO')
) {
const now = new Date()
const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)

const totalChatsUsed = await prisma.result.count({
where: {
typebotId: { in: workspace.typebots.map((typebot) => typebot.id) },
hasStarted: true,
createdAt: {
gte: firstDayOfMonth,
},
},
})

const firstDayOfNextMonth = new Date(
firstDayOfMonth.getFullYear(),
firstDayOfMonth.getMonth() + 1,
1
)
return { totalChatsUsed, resetsAt: firstDayOfNextMonth }
}
baptisteArno marked this conversation as resolved.
Show resolved Hide resolved

const stripe = new Stripe(env.STRIPE_SECRET_KEY, {
apiVersion: '2022-11-15',
})
Comment on lines +75 to +77
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Stripe client is being initialized with a hard-coded API version. It would be better to move this to a configuration file or environment variable to make it easier to update in the future.

-      apiVersion: '2022-11-15',
+      apiVersion: env.STRIPE_API_VERSION,


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

const currentSubscription = subscriptions.data
.filter((sub) => ['past_due', 'active'].includes(sub.status))
.sort((a, b) => a.created - b.created)
.shift()

if (!currentSubscription)
throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
message: `No subscription found on workspace: ${workspaceId}`,
})

const totalChatsUsed = await prisma.result.count({
where: {
typebotId: { in: workspace.typebots.map((typebot) => typebot.id) },
hasStarted: true,
createdAt: {
gte: firstDayOfMonth,
gte: new Date(currentSubscription.current_period_start * 1000),
},
},
})

return {
totalChatsUsed,
resetsAt: new Date(currentSubscription.current_period_end * 1000),
}
baptisteArno marked this conversation as resolved.
Show resolved Hide resolved
})
12 changes: 6 additions & 6 deletions apps/builder/src/features/billing/api/listInvoices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,12 @@ export const listInvoices = authenticatedProcedure
.filter(
(invoice) => isDefined(invoice.invoice_pdf) && isDefined(invoice.id)
)
.map((i) => ({
id: i.number as string,
url: i.invoice_pdf as string,
amount: i.subtotal,
currency: i.currency,
date: i.status_transitions.paid_at,
.map((invoice) => ({
id: invoice.number as string,
url: invoice.invoice_pdf as string,
amount: invoice.subtotal,
currency: invoice.currency,
date: invoice.status_transitions.paid_at,
})),
}
})
Loading