📄 Add Commercial License for ee folder (#1532)
This commit is contained in:
@@ -1,11 +1,7 @@
|
||||
import prisma from '@typebot.io/lib/prisma'
|
||||
import { authenticatedProcedure } from '@/helpers/server/trpc'
|
||||
import { TRPCError } from '@trpc/server'
|
||||
import { Plan } from '@typebot.io/prisma'
|
||||
import Stripe from 'stripe'
|
||||
import { z } from 'zod'
|
||||
import { isAdminWriteWorkspaceForbidden } from '@/features/workspace/helpers/isAdminWriteWorkspaceForbidden'
|
||||
import { env } from '@typebot.io/env'
|
||||
import { createCheckoutSession as createCheckoutSessionHandler } from '@typebot.io/billing/api/createCheckoutSession'
|
||||
|
||||
export const createCheckoutSession = authenticatedProcedure
|
||||
.meta({
|
||||
@@ -38,130 +34,6 @@ export const createCheckoutSession = authenticatedProcedure
|
||||
checkoutUrl: z.string(),
|
||||
})
|
||||
)
|
||||
.mutation(
|
||||
async ({
|
||||
input: { vat, email, company, workspaceId, currency, plan, returnUrl },
|
||||
ctx: { user },
|
||||
}) => {
|
||||
if (!env.STRIPE_SECRET_KEY)
|
||||
throw new TRPCError({
|
||||
code: 'INTERNAL_SERVER_ERROR',
|
||||
message: 'Stripe environment variables are missing',
|
||||
})
|
||||
const workspace = await prisma.workspace.findFirst({
|
||||
where: {
|
||||
id: workspaceId,
|
||||
},
|
||||
select: {
|
||||
stripeId: true,
|
||||
members: {
|
||||
select: {
|
||||
userId: true,
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!workspace || isAdminWriteWorkspaceForbidden(workspace, user))
|
||||
throw new TRPCError({
|
||||
code: 'NOT_FOUND',
|
||||
message: 'Workspace not found',
|
||||
})
|
||||
if (workspace.stripeId)
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: 'Customer already exists, use updateSubscription endpoint.',
|
||||
})
|
||||
|
||||
const stripe = new Stripe(env.STRIPE_SECRET_KEY, {
|
||||
apiVersion: '2022-11-15',
|
||||
})
|
||||
|
||||
await prisma.user.updateMany({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: {
|
||||
company,
|
||||
},
|
||||
})
|
||||
|
||||
const customer = await stripe.customers.create({
|
||||
email,
|
||||
name: company,
|
||||
metadata: { workspaceId },
|
||||
tax_id_data: vat
|
||||
? [vat as Stripe.CustomerCreateParams.TaxIdDatum]
|
||||
: undefined,
|
||||
})
|
||||
|
||||
const checkoutUrl = await createCheckoutSessionUrl(stripe)({
|
||||
customerId: customer.id,
|
||||
userId: user.id,
|
||||
workspaceId,
|
||||
currency,
|
||||
plan,
|
||||
returnUrl,
|
||||
})
|
||||
|
||||
if (!checkoutUrl)
|
||||
throw new TRPCError({
|
||||
code: 'INTERNAL_SERVER_ERROR',
|
||||
message: 'Stripe checkout session creation failed',
|
||||
})
|
||||
|
||||
return {
|
||||
checkoutUrl,
|
||||
}
|
||||
}
|
||||
.mutation(async ({ input, ctx: { user } }) =>
|
||||
createCheckoutSessionHandler({ ...input, user })
|
||||
)
|
||||
|
||||
type Props = {
|
||||
customerId: string
|
||||
workspaceId: string
|
||||
currency: 'usd' | 'eur'
|
||||
plan: 'STARTER' | 'PRO'
|
||||
returnUrl: string
|
||||
userId: string
|
||||
}
|
||||
|
||||
export const createCheckoutSessionUrl =
|
||||
(stripe: Stripe) =>
|
||||
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`,
|
||||
allow_promotion_codes: true,
|
||||
customer: customerId,
|
||||
customer_update: {
|
||||
address: 'auto',
|
||||
name: 'never',
|
||||
},
|
||||
mode: 'subscription',
|
||||
metadata: {
|
||||
workspaceId,
|
||||
plan,
|
||||
},
|
||||
currency,
|
||||
billing_address_collection: 'required',
|
||||
automatic_tax: { enabled: true },
|
||||
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
|
||||
}
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
import prisma from '@typebot.io/lib/prisma'
|
||||
import { authenticatedProcedure } from '@/helpers/server/trpc'
|
||||
import { TRPCError } from '@trpc/server'
|
||||
import { Plan } from '@typebot.io/prisma'
|
||||
import Stripe from 'stripe'
|
||||
import { z } from 'zod'
|
||||
import { isAdminWriteWorkspaceForbidden } from '@/features/workspace/helpers/isAdminWriteWorkspaceForbidden'
|
||||
import { env } from '@typebot.io/env'
|
||||
import { createCustomCheckoutSession as createCustomCheckoutSessionHandler } from '@typebot.io/billing/api/createCustomCheckoutSession'
|
||||
|
||||
export const createCustomCheckoutSession = authenticatedProcedure
|
||||
.meta({
|
||||
@@ -30,154 +25,9 @@ export const createCustomCheckoutSession = authenticatedProcedure
|
||||
checkoutUrl: z.string(),
|
||||
})
|
||||
)
|
||||
.mutation(
|
||||
async ({ input: { email, workspaceId, returnUrl }, ctx: { user } }) => {
|
||||
if (!env.STRIPE_SECRET_KEY)
|
||||
throw new TRPCError({
|
||||
code: 'INTERNAL_SERVER_ERROR',
|
||||
message: 'Stripe environment variables are missing',
|
||||
})
|
||||
const workspace = await prisma.workspace.findFirst({
|
||||
where: {
|
||||
id: workspaceId,
|
||||
},
|
||||
select: {
|
||||
stripeId: true,
|
||||
claimableCustomPlan: true,
|
||||
name: true,
|
||||
members: {
|
||||
select: {
|
||||
userId: true,
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if (
|
||||
!workspace?.claimableCustomPlan ||
|
||||
workspace.claimableCustomPlan.claimedAt ||
|
||||
isAdminWriteWorkspaceForbidden(workspace, user)
|
||||
)
|
||||
throw new TRPCError({
|
||||
code: 'NOT_FOUND',
|
||||
message: 'Custom plan not found',
|
||||
})
|
||||
const stripe = new Stripe(env.STRIPE_SECRET_KEY, {
|
||||
apiVersion: '2022-11-15',
|
||||
})
|
||||
|
||||
const vat =
|
||||
workspace.claimableCustomPlan.vatValue &&
|
||||
workspace.claimableCustomPlan.vatType
|
||||
? ({
|
||||
type: workspace.claimableCustomPlan.vatType,
|
||||
value: workspace.claimableCustomPlan.vatValue,
|
||||
} as Stripe.CustomerCreateParams.TaxIdDatum)
|
||||
: undefined
|
||||
|
||||
const customer = workspace.stripeId
|
||||
? await stripe.customers.retrieve(workspace.stripeId)
|
||||
: await stripe.customers.create({
|
||||
email,
|
||||
name: workspace.claimableCustomPlan.companyName ?? workspace.name,
|
||||
metadata: { workspaceId },
|
||||
tax_id_data: vat ? [vat] : undefined,
|
||||
})
|
||||
|
||||
const session = await stripe.checkout.sessions.create({
|
||||
success_url: `${returnUrl}?stripe=${Plan.CUSTOM}&success=true`,
|
||||
cancel_url: `${returnUrl}?stripe=cancel`,
|
||||
allow_promotion_codes: true,
|
||||
customer: customer.id,
|
||||
customer_update: {
|
||||
address: 'auto',
|
||||
name: 'never',
|
||||
},
|
||||
mode: 'subscription',
|
||||
metadata: {
|
||||
claimableCustomPlanId: workspace.claimableCustomPlan.id,
|
||||
},
|
||||
currency: workspace.claimableCustomPlan.currency,
|
||||
billing_address_collection: 'required',
|
||||
automatic_tax: { enabled: true },
|
||||
line_items: [
|
||||
{
|
||||
price_data: {
|
||||
currency: workspace.claimableCustomPlan.currency,
|
||||
tax_behavior: 'exclusive',
|
||||
recurring: {
|
||||
interval: workspace.claimableCustomPlan.isYearly
|
||||
? 'year'
|
||||
: 'month',
|
||||
},
|
||||
product_data: {
|
||||
name: workspace.claimableCustomPlan.name,
|
||||
description:
|
||||
workspace.claimableCustomPlan.description ?? undefined,
|
||||
},
|
||||
unit_amount: workspace.claimableCustomPlan.price * 100,
|
||||
},
|
||||
quantity: 1,
|
||||
},
|
||||
{
|
||||
price_data: {
|
||||
currency: workspace.claimableCustomPlan.currency,
|
||||
tax_behavior: 'exclusive',
|
||||
recurring: {
|
||||
interval: workspace.claimableCustomPlan.isYearly
|
||||
? 'year'
|
||||
: 'month',
|
||||
},
|
||||
product_data: {
|
||||
name: 'Included chats per month',
|
||||
},
|
||||
unit_amount: 0,
|
||||
},
|
||||
quantity: workspace.claimableCustomPlan.chatsLimit,
|
||||
},
|
||||
{
|
||||
price_data: {
|
||||
currency: workspace.claimableCustomPlan.currency,
|
||||
tax_behavior: 'exclusive',
|
||||
recurring: {
|
||||
interval: workspace.claimableCustomPlan.isYearly
|
||||
? 'year'
|
||||
: 'month',
|
||||
},
|
||||
product_data: {
|
||||
name: 'Included storage per month',
|
||||
},
|
||||
unit_amount: 0,
|
||||
},
|
||||
quantity: workspace.claimableCustomPlan.storageLimit,
|
||||
},
|
||||
{
|
||||
price_data: {
|
||||
currency: workspace.claimableCustomPlan.currency,
|
||||
tax_behavior: 'exclusive',
|
||||
recurring: {
|
||||
interval: workspace.claimableCustomPlan.isYearly
|
||||
? 'year'
|
||||
: 'month',
|
||||
},
|
||||
product_data: {
|
||||
name: 'Included seats',
|
||||
},
|
||||
unit_amount: 0,
|
||||
},
|
||||
quantity: workspace.claimableCustomPlan.seatsLimit,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
if (!session.url)
|
||||
throw new TRPCError({
|
||||
code: 'INTERNAL_SERVER_ERROR',
|
||||
message: 'Stripe checkout session creation failed',
|
||||
})
|
||||
|
||||
return {
|
||||
checkoutUrl: session.url,
|
||||
}
|
||||
}
|
||||
.mutation(async ({ input, ctx: { user } }) =>
|
||||
createCustomCheckoutSessionHandler({
|
||||
...input,
|
||||
user,
|
||||
})
|
||||
)
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import prisma from '@typebot.io/lib/prisma'
|
||||
import { authenticatedProcedure } from '@/helpers/server/trpc'
|
||||
import { TRPCError } from '@trpc/server'
|
||||
import Stripe from 'stripe'
|
||||
import { z } from 'zod'
|
||||
import { isAdminWriteWorkspaceForbidden } from '@/features/workspace/helpers/isAdminWriteWorkspaceForbidden'
|
||||
import { env } from '@typebot.io/env'
|
||||
import { getBillingPortalUrl as getBillingPortalUrlHandler } from '@typebot.io/billing/api/getBillingPortalUrl'
|
||||
|
||||
export const getBillingPortalUrl = authenticatedProcedure
|
||||
.meta({
|
||||
@@ -26,39 +22,6 @@ export const getBillingPortalUrl = authenticatedProcedure
|
||||
billingPortalUrl: z.string(),
|
||||
})
|
||||
)
|
||||
.query(async ({ input: { workspaceId }, ctx: { user } }) => {
|
||||
if (!env.STRIPE_SECRET_KEY)
|
||||
throw new TRPCError({
|
||||
code: 'INTERNAL_SERVER_ERROR',
|
||||
message: 'STRIPE_SECRET_KEY var is missing',
|
||||
})
|
||||
const workspace = await prisma.workspace.findFirst({
|
||||
where: {
|
||||
id: workspaceId,
|
||||
},
|
||||
select: {
|
||||
stripeId: true,
|
||||
members: {
|
||||
select: {
|
||||
userId: true,
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!workspace?.stripeId || isAdminWriteWorkspaceForbidden(workspace, user))
|
||||
throw new TRPCError({
|
||||
code: 'NOT_FOUND',
|
||||
message: 'Workspace not found',
|
||||
})
|
||||
const stripe = new Stripe(env.STRIPE_SECRET_KEY, {
|
||||
apiVersion: '2022-11-15',
|
||||
})
|
||||
const portalSession = await stripe.billingPortal.sessions.create({
|
||||
customer: workspace.stripeId,
|
||||
return_url: `${env.NEXTAUTH_URL}/typebots`,
|
||||
})
|
||||
return {
|
||||
billingPortalUrl: portalSession.url,
|
||||
}
|
||||
})
|
||||
.query(async ({ input: { workspaceId }, ctx: { user } }) =>
|
||||
getBillingPortalUrlHandler({ workspaceId, user })
|
||||
)
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import prisma from '@typebot.io/lib/prisma'
|
||||
import { authenticatedProcedure } from '@/helpers/server/trpc'
|
||||
import { TRPCError } from '@trpc/server'
|
||||
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 { env } from '@typebot.io/env'
|
||||
import { getSubscription as getSubscriptionHandler } from '@typebot.io/billing/api/getSubscription'
|
||||
|
||||
export const getSubscription = authenticatedProcedure
|
||||
.meta({
|
||||
@@ -27,65 +23,6 @@ export const getSubscription = authenticatedProcedure
|
||||
subscription: subscriptionSchema.or(z.null().openapi({ type: 'string' })),
|
||||
})
|
||||
)
|
||||
.query(async ({ input: { workspaceId }, ctx: { user } }) => {
|
||||
if (!env.STRIPE_SECRET_KEY)
|
||||
throw new TRPCError({
|
||||
code: 'INTERNAL_SERVER_ERROR',
|
||||
message: 'Stripe environment variables are missing',
|
||||
})
|
||||
const workspace = await prisma.workspace.findFirst({
|
||||
where: {
|
||||
id: workspaceId,
|
||||
},
|
||||
select: {
|
||||
stripeId: true,
|
||||
members: {
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!workspace || isReadWorkspaceFobidden(workspace, user))
|
||||
throw new TRPCError({
|
||||
code: 'NOT_FOUND',
|
||||
message: 'Workspace not found',
|
||||
})
|
||||
if (!workspace?.stripeId)
|
||||
return {
|
||||
subscription: null,
|
||||
}
|
||||
const stripe = new Stripe(env.STRIPE_SECRET_KEY, {
|
||||
apiVersion: '2022-11-15',
|
||||
})
|
||||
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)
|
||||
return {
|
||||
subscription: null,
|
||||
}
|
||||
|
||||
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
|
||||
),
|
||||
currency: currentSubscription.currency as 'usd' | 'eur',
|
||||
cancelDate: currentSubscription.cancel_at
|
||||
? new Date(currentSubscription.cancel_at * 1000)
|
||||
: undefined,
|
||||
},
|
||||
}
|
||||
})
|
||||
.query(async ({ input: { workspaceId }, ctx: { user } }) =>
|
||||
getSubscriptionHandler({ workspaceId, user })
|
||||
)
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import prisma from '@typebot.io/lib/prisma'
|
||||
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'
|
||||
import { getUsage as getUsageHandler } from '@typebot.io/billing/api/getUsage'
|
||||
|
||||
export const getUsage = authenticatedProcedure
|
||||
.meta({
|
||||
@@ -26,87 +22,6 @@ export const getUsage = authenticatedProcedure
|
||||
})
|
||||
)
|
||||
.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,
|
||||
},
|
||||
},
|
||||
typebots: {
|
||||
select: { id: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!workspace || isReadWorkspaceFobidden(workspace, user))
|
||||
throw new TRPCError({
|
||||
code: 'NOT_FOUND',
|
||||
message: 'Workspace not found',
|
||||
})
|
||||
|
||||
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 }
|
||||
}
|
||||
|
||||
const stripe = new Stripe(env.STRIPE_SECRET_KEY, {
|
||||
apiVersion: '2022-11-15',
|
||||
})
|
||||
|
||||
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: new Date(currentSubscription.current_period_start * 1000),
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
totalChatsUsed,
|
||||
resetsAt: new Date(currentSubscription.current_period_end * 1000),
|
||||
}
|
||||
})
|
||||
.query(async ({ input: { workspaceId }, ctx: { user } }) =>
|
||||
getUsageHandler({ workspaceId, user })
|
||||
)
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
import prisma from '@typebot.io/lib/prisma'
|
||||
import { authenticatedProcedure } from '@/helpers/server/trpc'
|
||||
import { TRPCError } from '@trpc/server'
|
||||
import Stripe from 'stripe'
|
||||
import { isDefined } from '@typebot.io/lib'
|
||||
import { z } from 'zod'
|
||||
import { invoiceSchema } from '@typebot.io/schemas/features/billing/invoice'
|
||||
import { isAdminWriteWorkspaceForbidden } from '@/features/workspace/helpers/isAdminWriteWorkspaceForbidden'
|
||||
import { env } from '@typebot.io/env'
|
||||
import { listInvoices as listInvoicesHandler } from '@typebot.io/billing/api/listInvoices'
|
||||
|
||||
export const listInvoices = authenticatedProcedure
|
||||
.meta({
|
||||
@@ -32,49 +27,6 @@ export const listInvoices = authenticatedProcedure
|
||||
invoices: z.array(invoiceSchema),
|
||||
})
|
||||
)
|
||||
.query(async ({ input: { workspaceId }, ctx: { user } }) => {
|
||||
if (!env.STRIPE_SECRET_KEY)
|
||||
throw new TRPCError({
|
||||
code: 'INTERNAL_SERVER_ERROR',
|
||||
message: 'STRIPE_SECRET_KEY var is missing',
|
||||
})
|
||||
const workspace = await prisma.workspace.findFirst({
|
||||
where: {
|
||||
id: workspaceId,
|
||||
},
|
||||
select: {
|
||||
stripeId: true,
|
||||
members: {
|
||||
select: {
|
||||
userId: true,
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!workspace?.stripeId || isAdminWriteWorkspaceForbidden(workspace, user))
|
||||
throw new TRPCError({
|
||||
code: 'NOT_FOUND',
|
||||
message: 'Workspace not found',
|
||||
})
|
||||
const stripe = new Stripe(env.STRIPE_SECRET_KEY, {
|
||||
apiVersion: '2022-11-15',
|
||||
})
|
||||
const invoices = await stripe.invoices.list({
|
||||
customer: workspace.stripeId,
|
||||
limit: 50,
|
||||
})
|
||||
return {
|
||||
invoices: invoices.data
|
||||
.filter(
|
||||
(invoice) => isDefined(invoice.invoice_pdf) && isDefined(invoice.id)
|
||||
)
|
||||
.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,
|
||||
})),
|
||||
}
|
||||
})
|
||||
.query(async ({ input: { workspaceId }, ctx: { user } }) =>
|
||||
listInvoicesHandler({ workspaceId, user })
|
||||
)
|
||||
|
||||
@@ -1,14 +1,8 @@
|
||||
import prisma from '@typebot.io/lib/prisma'
|
||||
import { authenticatedProcedure } from '@/helpers/server/trpc'
|
||||
import { TRPCError } from '@trpc/server'
|
||||
import { Plan } from '@typebot.io/prisma'
|
||||
import { workspaceSchema } from '@typebot.io/schemas'
|
||||
import Stripe from 'stripe'
|
||||
import { z } from 'zod'
|
||||
import { createCheckoutSessionUrl } from './createCheckoutSession'
|
||||
import { isAdminWriteWorkspaceForbidden } from '@/features/workspace/helpers/isAdminWriteWorkspaceForbidden'
|
||||
import { env } from '@typebot.io/env'
|
||||
import { trackEvents } from '@typebot.io/telemetry/trackEvents'
|
||||
import { updateSubscription as updateSubscriptionHandler } from '@typebot.io/billing/api/updateSubscription'
|
||||
|
||||
export const updateSubscription = authenticatedProcedure
|
||||
.meta({
|
||||
@@ -34,140 +28,9 @@ export const updateSubscription = authenticatedProcedure
|
||||
checkoutUrl: z.string().nullish(),
|
||||
})
|
||||
)
|
||||
.mutation(
|
||||
async ({
|
||||
input: { workspaceId, plan, currency, returnUrl },
|
||||
ctx: { user },
|
||||
}) => {
|
||||
if (!env.STRIPE_SECRET_KEY)
|
||||
throw new TRPCError({
|
||||
code: 'INTERNAL_SERVER_ERROR',
|
||||
message: 'Stripe environment variables are missing',
|
||||
})
|
||||
const workspace = await prisma.workspace.findFirst({
|
||||
where: {
|
||||
id: workspaceId,
|
||||
},
|
||||
select: {
|
||||
isPastDue: true,
|
||||
stripeId: true,
|
||||
members: {
|
||||
select: {
|
||||
userId: true,
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if (workspace?.isPastDue)
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message:
|
||||
'You have unpaid invoices. Please head over your billing portal to pay it.',
|
||||
})
|
||||
if (
|
||||
!workspace?.stripeId ||
|
||||
isAdminWriteWorkspaceForbidden(workspace, user)
|
||||
)
|
||||
throw new TRPCError({
|
||||
code: 'NOT_FOUND',
|
||||
message: 'Workspace not found',
|
||||
})
|
||||
|
||||
const stripe = new Stripe(env.STRIPE_SECRET_KEY, {
|
||||
apiVersion: '2022-11-15',
|
||||
})
|
||||
const { data } = await stripe.subscriptions.list({
|
||||
customer: workspace.stripeId,
|
||||
limit: 1,
|
||||
status: 'active',
|
||||
})
|
||||
const subscription = data[0] as Stripe.Subscription | undefined
|
||||
const currentPlanItemId = subscription?.items.data.find((item) =>
|
||||
[env.STRIPE_STARTER_PRICE_ID, env.STRIPE_PRO_PRICE_ID].includes(
|
||||
item.price.id
|
||||
)
|
||||
)?.id
|
||||
const currentUsageItemId = subscription?.items.data.find(
|
||||
(item) =>
|
||||
item.price.id === env.STRIPE_STARTER_CHATS_PRICE_ID ||
|
||||
item.price.id === env.STRIPE_PRO_CHATS_PRICE_ID
|
||||
)?.id
|
||||
|
||||
const items = [
|
||||
{
|
||||
id: currentPlanItemId,
|
||||
price:
|
||||
plan === Plan.STARTER
|
||||
? env.STRIPE_STARTER_PRICE_ID
|
||||
: env.STRIPE_PRO_PRICE_ID,
|
||||
quantity: 1,
|
||||
},
|
||||
{
|
||||
id: currentUsageItemId,
|
||||
price:
|
||||
plan === Plan.STARTER
|
||||
? env.STRIPE_STARTER_CHATS_PRICE_ID
|
||||
: env.STRIPE_PRO_CHATS_PRICE_ID,
|
||||
},
|
||||
]
|
||||
|
||||
if (subscription) {
|
||||
if (plan === 'STARTER') {
|
||||
const totalChatsUsed = await prisma.result.count({
|
||||
where: {
|
||||
typebot: { workspaceId },
|
||||
hasStarted: true,
|
||||
createdAt: {
|
||||
gte: new Date(subscription.current_period_start * 1000),
|
||||
},
|
||||
},
|
||||
})
|
||||
if (totalChatsUsed >= 4000) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message:
|
||||
"You have collected more than 4000 chats during this billing cycle. You can't downgrade to the Starter.",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
await stripe.subscriptions.update(subscription.id, {
|
||||
items,
|
||||
proration_behavior: 'always_invoice',
|
||||
})
|
||||
} else {
|
||||
const checkoutUrl = await createCheckoutSessionUrl(stripe)({
|
||||
customerId: workspace.stripeId,
|
||||
userId: user.id,
|
||||
workspaceId,
|
||||
currency,
|
||||
plan,
|
||||
returnUrl,
|
||||
})
|
||||
|
||||
return { checkoutUrl }
|
||||
}
|
||||
|
||||
const updatedWorkspace = await prisma.workspace.update({
|
||||
where: { id: workspaceId },
|
||||
data: {
|
||||
plan,
|
||||
isQuarantined: false,
|
||||
},
|
||||
})
|
||||
|
||||
await trackEvents([
|
||||
{
|
||||
name: 'Subscription updated',
|
||||
workspaceId,
|
||||
userId: user.id,
|
||||
data: {
|
||||
plan,
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
return { workspace: updatedWorkspace }
|
||||
}
|
||||
.mutation(async ({ input, ctx: { user } }) =>
|
||||
updateSubscriptionHandler({
|
||||
...input,
|
||||
user,
|
||||
})
|
||||
)
|
||||
|
||||
@@ -11,7 +11,7 @@ import { StarterPlanPricingCard } from './StarterPlanPricingCard'
|
||||
import { ProPlanPricingCard } from './ProPlanPricingCard'
|
||||
import { useTranslate } from '@tolgee/react'
|
||||
import { StripeClimateLogo } from './StripeClimateLogo'
|
||||
import { guessIfUserIsEuropean } from '@typebot.io/billing/guessIfUserIsEuropean'
|
||||
import { guessIfUserIsEuropean } from '@typebot.io/billing/helpers/guessIfUserIsEuropean'
|
||||
import { WorkspaceInApp } from '@/features/workspace/WorkspaceProvider'
|
||||
|
||||
type Props = {
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
} from '@chakra-ui/react'
|
||||
import { useTranslate } from '@tolgee/react'
|
||||
import { proChatTiers } from '@typebot.io/billing/constants'
|
||||
import { formatPrice } from '@typebot.io/billing/formatPrice'
|
||||
import { formatPrice } from '@typebot.io/billing/helpers/formatPrice'
|
||||
|
||||
type Props = {
|
||||
isOpen: boolean
|
||||
|
||||
@@ -17,8 +17,8 @@ import {
|
||||
import { useRouter } from 'next/router'
|
||||
import React, { FormEvent, useState } from 'react'
|
||||
import { isDefined } from '@typebot.io/lib'
|
||||
import { taxIdTypes } from '../taxIdTypes'
|
||||
import { useTranslate } from '@tolgee/react'
|
||||
import { taxIdTypes } from '@typebot.io/billing/taxIdTypes'
|
||||
|
||||
export type PreCheckoutModalProps = {
|
||||
selectedSubscription:
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
import { Plan } from '@typebot.io/prisma'
|
||||
import { FeaturesList } from './FeaturesList'
|
||||
import { MoreInfoTooltip } from '@/components/MoreInfoTooltip'
|
||||
import { formatPrice } from '@typebot.io/billing/formatPrice'
|
||||
import { formatPrice } from '@typebot.io/billing/helpers/formatPrice'
|
||||
import { ChatsProTiersModal } from './ChatsProTiersModal'
|
||||
import { prices } from '@typebot.io/billing/constants'
|
||||
import { T, useTranslate } from '@tolgee/react'
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
import { Plan } from '@typebot.io/prisma'
|
||||
import { FeaturesList } from './FeaturesList'
|
||||
import { MoreInfoTooltip } from '@/components/MoreInfoTooltip'
|
||||
import { formatPrice } from '@typebot.io/billing/formatPrice'
|
||||
import { formatPrice } from '@typebot.io/billing/helpers/formatPrice'
|
||||
import { prices } from '@typebot.io/billing/constants'
|
||||
import { T, useTranslate } from '@tolgee/react'
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import { AlertIcon } from '@/components/icons'
|
||||
import { WorkspaceInApp } from '@/features/workspace/WorkspaceProvider'
|
||||
import { parseNumberWithCommas } from '@typebot.io/lib'
|
||||
import { defaultQueryOptions, trpc } from '@/lib/trpc'
|
||||
import { getChatsLimit } from '@typebot.io/billing/getChatsLimit'
|
||||
import { getChatsLimit } from '@typebot.io/billing/helpers/getChatsLimit'
|
||||
import { useTranslate } from '@tolgee/react'
|
||||
|
||||
type Props = {
|
||||
|
||||
@@ -1,555 +0,0 @@
|
||||
export const taxIdTypes = [
|
||||
{
|
||||
type: 'ae_trn',
|
||||
code: 'AE TRN',
|
||||
name: 'United Arab Emirates',
|
||||
emoji: '🇦🇪',
|
||||
placeholder: '123456789012345',
|
||||
},
|
||||
{
|
||||
type: 'au_abn',
|
||||
code: 'AU ABN',
|
||||
name: 'Australia',
|
||||
emoji: '🇦🇺',
|
||||
placeholder: '123456789012',
|
||||
},
|
||||
{
|
||||
type: 'au_arn',
|
||||
code: 'AU ARN',
|
||||
name: 'Australia',
|
||||
emoji: '🇦🇺',
|
||||
placeholder: '123456789012',
|
||||
},
|
||||
{
|
||||
type: 'bg_uic',
|
||||
code: 'BG UIC',
|
||||
name: 'Bulgaria',
|
||||
emoji: '🇧🇬',
|
||||
placeholder: 'BG123456789',
|
||||
},
|
||||
{
|
||||
type: 'br_cnpj',
|
||||
code: 'BR CNPJ',
|
||||
name: 'Brazil',
|
||||
emoji: '🇧🇷',
|
||||
placeholder: '12.345.678/0001-23',
|
||||
},
|
||||
{
|
||||
type: 'br_cpf',
|
||||
code: 'BR CPF',
|
||||
name: 'Brazil',
|
||||
emoji: '🇧🇷',
|
||||
placeholder: '123.456.789-01',
|
||||
},
|
||||
{
|
||||
type: 'ca_bn',
|
||||
code: 'CA BN',
|
||||
name: 'Canada',
|
||||
emoji: '🇨🇦',
|
||||
placeholder: '123456789',
|
||||
},
|
||||
{
|
||||
type: 'ca_gst_hst',
|
||||
code: 'CA GST/HST',
|
||||
name: 'Canada',
|
||||
emoji: '🇨🇦',
|
||||
placeholder: '123456789',
|
||||
},
|
||||
{
|
||||
type: 'ca_pst_bc',
|
||||
code: 'CA PST-BC',
|
||||
name: 'Canada',
|
||||
emoji: '🇨🇦',
|
||||
placeholder: '123456789',
|
||||
},
|
||||
{
|
||||
type: 'ca_pst_mb',
|
||||
code: 'CA PST-MB',
|
||||
name: 'Canada',
|
||||
emoji: '🇨🇦',
|
||||
placeholder: '123456789',
|
||||
},
|
||||
{
|
||||
type: 'ca_pst_sk',
|
||||
code: 'CA PST-SK',
|
||||
name: 'Canada',
|
||||
emoji: '🇨🇦',
|
||||
placeholder: '123456789',
|
||||
},
|
||||
{
|
||||
type: 'ca_qst',
|
||||
code: 'CA QST',
|
||||
name: 'Canada',
|
||||
emoji: '🇨🇦',
|
||||
placeholder: '123456789',
|
||||
},
|
||||
{
|
||||
type: 'ch_vat',
|
||||
code: 'CH VAT',
|
||||
name: 'Switzerland',
|
||||
emoji: '🇨🇭',
|
||||
placeholder: 'CHE-123.456.789 MWST',
|
||||
},
|
||||
{
|
||||
type: 'cl_tin',
|
||||
code: 'CL TIN',
|
||||
name: 'Chile',
|
||||
emoji: '🇨🇱',
|
||||
placeholder: '12345678-9',
|
||||
},
|
||||
{
|
||||
type: 'eg_tin',
|
||||
code: 'EG TIN',
|
||||
name: 'Egypt',
|
||||
emoji: '🇪🇬',
|
||||
placeholder: '123456789012',
|
||||
},
|
||||
{
|
||||
type: 'es_cif',
|
||||
code: 'ES CIF',
|
||||
name: 'Spain',
|
||||
emoji: '🇪🇸',
|
||||
placeholder: 'A12345678',
|
||||
},
|
||||
{
|
||||
type: 'eu_oss_vat',
|
||||
code: 'EU OSS VAT',
|
||||
name: 'European Union',
|
||||
emoji: '🇪🇺',
|
||||
placeholder: 'XX123456789',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'AT VAT',
|
||||
name: 'Austria',
|
||||
emoji: '🇦🇹',
|
||||
placeholder: 'ATU12345678',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'DE VAT',
|
||||
name: 'Germany',
|
||||
emoji: '🇩🇪',
|
||||
placeholder: 'DE123456789',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'BE VAT',
|
||||
name: 'Belgium',
|
||||
emoji: '🇧🇪',
|
||||
placeholder: 'BE0123456789',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'BG VAT',
|
||||
name: 'Bulgaria',
|
||||
emoji: '🇧🇬',
|
||||
placeholder: 'BG123456789',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'CY VAT',
|
||||
name: 'Cyprus',
|
||||
emoji: '🇨🇾',
|
||||
placeholder: 'CY12345678L',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'DK VAT',
|
||||
name: 'Denmark',
|
||||
emoji: '🇩🇰',
|
||||
placeholder: 'DK12345678',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'EE VAT',
|
||||
name: 'Estonia',
|
||||
emoji: '🇪🇪',
|
||||
placeholder: 'EE123456789',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'GR VAT',
|
||||
name: 'Greece',
|
||||
emoji: '🇬🇷',
|
||||
placeholder: 'EL123456789',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'ES VAT',
|
||||
name: 'Spain',
|
||||
emoji: '🇪🇸',
|
||||
placeholder: 'ESX12345678',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'FI VAT',
|
||||
name: 'Finland',
|
||||
emoji: '🇫🇮',
|
||||
placeholder: 'FI12345678',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'FR VAT',
|
||||
name: 'France',
|
||||
emoji: '🇫🇷',
|
||||
placeholder: 'FRXX123456789',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'HR VAT',
|
||||
name: 'Croatia',
|
||||
emoji: '🇭🇷',
|
||||
placeholder: 'HR12345678901',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'IE VAT',
|
||||
name: 'Ireland',
|
||||
emoji: '🇮🇪',
|
||||
placeholder: 'IE1X12345X',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'IT VAT',
|
||||
name: 'Italy',
|
||||
emoji: '🇮🇹',
|
||||
placeholder: 'IT12345678901',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'LT VAT',
|
||||
name: 'Lithuania',
|
||||
emoji: '🇱🇹',
|
||||
placeholder: 'LT123456789',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'LU VAT',
|
||||
name: 'Luxembourg',
|
||||
emoji: '🇱🇺',
|
||||
placeholder: 'LU12345678',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'LV VAT',
|
||||
name: 'Latvia',
|
||||
emoji: '🇱🇻',
|
||||
placeholder: 'LV12345678901',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'MT VAT',
|
||||
name: 'Malta',
|
||||
emoji: '🇲🇹',
|
||||
placeholder: 'MT12345678',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'NL VAT',
|
||||
name: 'Netherlands',
|
||||
emoji: '🇳🇱',
|
||||
placeholder: 'NL123456789B01',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'PL VAT',
|
||||
name: 'Poland',
|
||||
emoji: '🇵🇱',
|
||||
placeholder: 'PL1234567890',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'PT VAT',
|
||||
name: 'Portugal',
|
||||
emoji: '🇵🇹',
|
||||
placeholder: 'PT123456789',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'RO VAT',
|
||||
name: 'Romania',
|
||||
emoji: '🇷🇴',
|
||||
placeholder: 'RO1234567891',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'SE VAT',
|
||||
name: 'Sweden',
|
||||
emoji: '🇸🇪',
|
||||
placeholder: 'SE123456789101',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'SI VAT',
|
||||
name: 'Slovenia',
|
||||
emoji: '🇸🇮',
|
||||
placeholder: 'SI12345678',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'SK VAT',
|
||||
name: 'Slovakia',
|
||||
emoji: '🇸🇰',
|
||||
placeholder: 'SK1234567890',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'XI VAT',
|
||||
name: 'Northern Ireland',
|
||||
emoji: '🇮🇪',
|
||||
placeholder: 'XI123456789',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'GE VAT',
|
||||
name: 'Georgia',
|
||||
emoji: '🇬🇪',
|
||||
placeholder: 'GE123456789',
|
||||
},
|
||||
{
|
||||
type: 'eu_vat',
|
||||
code: 'CZ VAT',
|
||||
name: 'Czech Republic',
|
||||
emoji: '🇨🇿',
|
||||
placeholder: 'CZ12345678',
|
||||
},
|
||||
{
|
||||
type: 'gb_vat',
|
||||
code: 'GB VAT',
|
||||
name: 'United Kingdom',
|
||||
emoji: '🇬🇧',
|
||||
placeholder: 'GB123456789',
|
||||
},
|
||||
{
|
||||
type: 'ge_vat',
|
||||
code: 'GE VAT',
|
||||
name: 'Georgia',
|
||||
emoji: '🇬🇪',
|
||||
placeholder: 'GE123456789',
|
||||
},
|
||||
{
|
||||
type: 'hk_br',
|
||||
code: 'HK BR',
|
||||
name: 'Hong Kong',
|
||||
emoji: '🇭🇰',
|
||||
placeholder: '12345678',
|
||||
},
|
||||
{
|
||||
type: 'hu_tin',
|
||||
code: 'HU TIN',
|
||||
name: 'Hungary',
|
||||
emoji: '🇭🇺',
|
||||
placeholder: '13804079-2-13',
|
||||
},
|
||||
{
|
||||
type: 'hu_vat',
|
||||
code: 'HU VAT',
|
||||
name: 'Hungary',
|
||||
emoji: '🇭🇺',
|
||||
placeholder: 'HU12345678',
|
||||
},
|
||||
{
|
||||
type: 'id_npwp',
|
||||
code: 'ID NPWP',
|
||||
name: 'Indonesia',
|
||||
emoji: '🇮🇩',
|
||||
placeholder: '123.456.7-8910.000',
|
||||
},
|
||||
{
|
||||
type: 'il_vat',
|
||||
code: 'IL VAT',
|
||||
name: 'Israel',
|
||||
emoji: '🇮🇱',
|
||||
placeholder: '123456789',
|
||||
},
|
||||
{
|
||||
type: 'in_gst',
|
||||
code: 'IN GST',
|
||||
name: 'India',
|
||||
emoji: '🇮🇳',
|
||||
placeholder: '12ABCDE1234F1Z5',
|
||||
},
|
||||
{
|
||||
type: 'is_vat',
|
||||
code: 'IS VAT',
|
||||
name: 'Iceland',
|
||||
emoji: '🇮🇸',
|
||||
placeholder: '123456-7890',
|
||||
},
|
||||
{
|
||||
type: 'jp_cn',
|
||||
code: 'JP CN',
|
||||
name: 'Japan',
|
||||
emoji: '🇯🇵',
|
||||
placeholder: '123456789012',
|
||||
},
|
||||
{
|
||||
type: 'jp_rn',
|
||||
code: 'JP RN',
|
||||
name: 'Japan',
|
||||
emoji: '🇯🇵',
|
||||
placeholder: '123456789012',
|
||||
},
|
||||
{
|
||||
type: 'jp_trn',
|
||||
code: 'JP TRN',
|
||||
name: 'Japan',
|
||||
emoji: '🇯🇵',
|
||||
placeholder: '123456789012',
|
||||
},
|
||||
{
|
||||
type: 'ke_pin',
|
||||
code: 'KE PIN',
|
||||
name: 'Kenya',
|
||||
emoji: '🇰🇪',
|
||||
placeholder: '12345678A',
|
||||
},
|
||||
{
|
||||
type: 'kr_brn',
|
||||
code: 'KR BRN',
|
||||
name: 'South Korea',
|
||||
emoji: '🇰🇷',
|
||||
placeholder: '1234567890',
|
||||
},
|
||||
{
|
||||
type: 'li_uid',
|
||||
code: 'LI UID',
|
||||
name: 'Liechtenstein',
|
||||
emoji: '🇱🇮',
|
||||
placeholder: 'CHE-123.456.789',
|
||||
},
|
||||
{
|
||||
type: 'mx_rfc',
|
||||
code: 'MX RFC',
|
||||
name: 'Mexico',
|
||||
emoji: '🇲🇽',
|
||||
placeholder: 'XAXX010101000',
|
||||
},
|
||||
{
|
||||
type: 'my_frp',
|
||||
code: 'MY FRP',
|
||||
name: 'Malaysia',
|
||||
emoji: '🇲🇾',
|
||||
placeholder: '123456789012',
|
||||
},
|
||||
{
|
||||
type: 'my_itn',
|
||||
code: 'MY ITN',
|
||||
name: 'Malaysia',
|
||||
emoji: '🇲🇾',
|
||||
placeholder: '123456789012',
|
||||
},
|
||||
{
|
||||
type: 'my_sst',
|
||||
code: 'MY SST',
|
||||
name: 'Malaysia',
|
||||
emoji: '🇲🇾',
|
||||
placeholder: '123456789012',
|
||||
},
|
||||
{
|
||||
type: 'no_vat',
|
||||
code: 'NO VAT',
|
||||
name: 'Norway',
|
||||
emoji: '🇳🇴',
|
||||
placeholder: '123456789',
|
||||
},
|
||||
{
|
||||
type: 'nz_gst',
|
||||
code: 'NZ GST',
|
||||
name: 'New Zealand',
|
||||
emoji: '🇳🇿',
|
||||
placeholder: '123456789',
|
||||
},
|
||||
{
|
||||
type: 'ph_tin',
|
||||
code: 'PH TIN',
|
||||
name: 'Philippines',
|
||||
emoji: '🇵🇭',
|
||||
placeholder: '123-456-789-012',
|
||||
},
|
||||
{
|
||||
type: 'ru_inn',
|
||||
code: 'RU INN',
|
||||
name: 'Russia',
|
||||
emoji: '🇷🇺',
|
||||
placeholder: '123456789012',
|
||||
},
|
||||
{
|
||||
type: 'ru_kpp',
|
||||
code: 'RU KPP',
|
||||
name: 'Russia',
|
||||
emoji: '🇷🇺',
|
||||
placeholder: '123456789',
|
||||
},
|
||||
{
|
||||
type: 'sa_vat',
|
||||
code: 'SA VAT',
|
||||
name: 'Saudi Arabia',
|
||||
emoji: '🇸🇦',
|
||||
placeholder: '123456789012',
|
||||
},
|
||||
{
|
||||
type: 'sg_gst',
|
||||
code: 'SG GST',
|
||||
name: 'Singapore',
|
||||
emoji: '🇸🇬',
|
||||
placeholder: '123456789',
|
||||
},
|
||||
{
|
||||
type: 'sg_uen',
|
||||
code: 'SG UEN',
|
||||
name: 'Singapore',
|
||||
emoji: '🇸🇬',
|
||||
placeholder: '123456789',
|
||||
},
|
||||
{
|
||||
type: 'si_tin',
|
||||
code: 'SI TIN',
|
||||
name: 'Slovenia',
|
||||
emoji: '🇸🇮',
|
||||
placeholder: '12345678',
|
||||
},
|
||||
{
|
||||
type: 'th_vat',
|
||||
code: 'TH VAT',
|
||||
name: 'Thailand',
|
||||
emoji: '🇹🇭',
|
||||
placeholder: '1234567890123',
|
||||
},
|
||||
{
|
||||
type: 'tr_tin',
|
||||
code: 'TR TIN',
|
||||
name: 'Turkey',
|
||||
emoji: '🇹🇷',
|
||||
placeholder: '1234567890',
|
||||
},
|
||||
{
|
||||
type: 'tw_vat',
|
||||
code: 'TW VAT',
|
||||
name: 'Taiwan',
|
||||
emoji: '🇹🇼',
|
||||
placeholder: '12345678',
|
||||
},
|
||||
{
|
||||
type: 'ua_vat',
|
||||
code: 'UA VAT',
|
||||
name: 'Ukraine',
|
||||
emoji: '🇺🇦',
|
||||
placeholder: '12345678',
|
||||
},
|
||||
{
|
||||
type: 'us_ein',
|
||||
code: 'US EIN',
|
||||
name: 'United States',
|
||||
emoji: '🇺🇸',
|
||||
placeholder: '12-3456789',
|
||||
},
|
||||
{
|
||||
type: 'za_vat',
|
||||
code: 'ZA VAT',
|
||||
name: 'South Africa',
|
||||
emoji: '🇿🇦',
|
||||
placeholder: '1234567890',
|
||||
},
|
||||
]
|
||||
@@ -14,7 +14,7 @@ import { FolderContent } from '@/features/folders/components/FolderContent'
|
||||
import { TypebotDndProvider } from '@/features/folders/TypebotDndProvider'
|
||||
import { ParentModalProvider } from '@/features/graph/providers/ParentModalProvider'
|
||||
import { trpc } from '@/lib/trpc'
|
||||
import { guessIfUserIsEuropean } from '@typebot.io/billing/guessIfUserIsEuropean'
|
||||
import { guessIfUserIsEuropean } from '@typebot.io/billing/helpers/guessIfUserIsEuropean'
|
||||
import { useTranslate } from '@tolgee/react'
|
||||
|
||||
export const DashboardPage = () => {
|
||||
|
||||
@@ -19,7 +19,7 @@ import { updateInvitationQuery } from '../queries/updateInvitationQuery'
|
||||
import { updateMemberQuery } from '../queries/updateMemberQuery'
|
||||
import { Member } from '../types'
|
||||
import { useWorkspace } from '../WorkspaceProvider'
|
||||
import { getSeatsLimit } from '@typebot.io/billing/getSeatsLimit'
|
||||
import { getSeatsLimit } from '@typebot.io/billing/helpers/getSeatsLimit'
|
||||
import { useTranslate } from '@tolgee/react'
|
||||
|
||||
export const MembersList = () => {
|
||||
|
||||
@@ -1,346 +1,15 @@
|
||||
import { NextApiRequest, NextApiResponse } from 'next'
|
||||
import { methodNotAllowed } from '@typebot.io/lib/api'
|
||||
import Stripe from 'stripe'
|
||||
import Cors from 'micro-cors'
|
||||
import { buffer } from 'micro'
|
||||
import prisma from '@typebot.io/lib/prisma'
|
||||
import { Plan, WorkspaceRole } from '@typebot.io/prisma'
|
||||
import { RequestHandler } from 'next/dist/server/next'
|
||||
import { Settings } from '@typebot.io/schemas'
|
||||
import { env } from '@typebot.io/env'
|
||||
import { prices } from '@typebot.io/billing/constants'
|
||||
import { trackEvents } from '@typebot.io/telemetry/trackEvents'
|
||||
|
||||
if (!env.STRIPE_SECRET_KEY || !env.STRIPE_WEBHOOK_SECRET)
|
||||
throw new Error('STRIPE_SECRET_KEY or STRIPE_WEBHOOK_SECRET missing')
|
||||
const stripe = new Stripe(env.STRIPE_SECRET_KEY, {
|
||||
apiVersion: '2022-11-15',
|
||||
})
|
||||
import { webhookHandler } from '@typebot.io/billing/api/webhookHandler'
|
||||
|
||||
const cors = Cors({
|
||||
allowMethods: ['POST', 'HEAD'],
|
||||
})
|
||||
|
||||
const webhookSecret = env.STRIPE_WEBHOOK_SECRET as string
|
||||
|
||||
export const config = {
|
||||
api: {
|
||||
bodyParser: false,
|
||||
},
|
||||
}
|
||||
|
||||
const webhookHandler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
if (req.method === 'POST') {
|
||||
const buf = await buffer(req)
|
||||
const sig = req.headers['stripe-signature']
|
||||
|
||||
if (!sig) return res.status(400).send(`stripe-signature is missing`)
|
||||
try {
|
||||
const event = stripe.webhooks.constructEvent(
|
||||
buf.toString(),
|
||||
sig.toString(),
|
||||
webhookSecret
|
||||
)
|
||||
switch (event.type) {
|
||||
case 'checkout.session.completed': {
|
||||
const session = event.data.object as Stripe.Checkout.Session
|
||||
const metadata = session.metadata as unknown as
|
||||
| {
|
||||
plan: 'STARTER' | 'PRO'
|
||||
workspaceId: string
|
||||
userId: string
|
||||
}
|
||||
| { claimableCustomPlanId: string; userId: string }
|
||||
if ('plan' in metadata) {
|
||||
const { workspaceId, plan } = metadata
|
||||
if (!workspaceId || !plan)
|
||||
return res
|
||||
.status(500)
|
||||
.send({ message: `Couldn't retrieve valid metadata` })
|
||||
|
||||
const workspace = await prisma.workspace.update({
|
||||
where: { id: workspaceId },
|
||||
data: {
|
||||
plan,
|
||||
stripeId: session.customer as string,
|
||||
isQuarantined: false,
|
||||
},
|
||||
include: {
|
||||
members: {
|
||||
select: { userId: true },
|
||||
where: {
|
||||
role: WorkspaceRole.ADMIN,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await trackEvents(
|
||||
workspace.members.map((m) => ({
|
||||
name: 'Subscription updated',
|
||||
workspaceId,
|
||||
userId: m.userId,
|
||||
data: {
|
||||
plan,
|
||||
},
|
||||
}))
|
||||
)
|
||||
} else {
|
||||
const { claimableCustomPlanId, userId } = metadata
|
||||
if (!claimableCustomPlanId)
|
||||
return res
|
||||
.status(500)
|
||||
.send({ message: `Couldn't retrieve valid metadata` })
|
||||
const { workspaceId, chatsLimit, seatsLimit, storageLimit } =
|
||||
await prisma.claimableCustomPlan.update({
|
||||
where: { id: claimableCustomPlanId },
|
||||
data: { claimedAt: new Date() },
|
||||
})
|
||||
|
||||
await prisma.workspace.updateMany({
|
||||
where: { id: workspaceId },
|
||||
data: {
|
||||
plan: Plan.CUSTOM,
|
||||
stripeId: session.customer as string,
|
||||
customChatsLimit: chatsLimit,
|
||||
customStorageLimit: storageLimit,
|
||||
customSeatsLimit: seatsLimit,
|
||||
},
|
||||
})
|
||||
|
||||
await trackEvents([
|
||||
{
|
||||
name: 'Subscription updated',
|
||||
workspaceId,
|
||||
userId,
|
||||
data: {
|
||||
plan: Plan.CUSTOM,
|
||||
},
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
return res.status(200).send({ message: 'workspace upgraded in DB' })
|
||||
}
|
||||
case 'customer.subscription.updated': {
|
||||
const subscription = event.data.object as Stripe.Subscription
|
||||
if (subscription.status !== 'past_due')
|
||||
return res.send({ message: 'Not past_due, skipping.' })
|
||||
const existingWorkspace = await prisma.workspace.findFirst({
|
||||
where: {
|
||||
stripeId: subscription.customer as string,
|
||||
},
|
||||
select: {
|
||||
isPastDue: true,
|
||||
id: true,
|
||||
members: {
|
||||
select: { userId: true, role: true },
|
||||
where: { role: WorkspaceRole.ADMIN },
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!existingWorkspace) throw new Error('Workspace not found')
|
||||
if (existingWorkspace?.isPastDue)
|
||||
return res.send({
|
||||
message: 'Workspace already past due, skipping.',
|
||||
})
|
||||
await prisma.workspace.updateMany({
|
||||
where: {
|
||||
id: existingWorkspace.id,
|
||||
},
|
||||
data: {
|
||||
isPastDue: true,
|
||||
},
|
||||
})
|
||||
await trackEvents(
|
||||
existingWorkspace.members.map((m) => ({
|
||||
name: 'Workspace past due',
|
||||
workspaceId: existingWorkspace.id,
|
||||
userId: m.userId,
|
||||
}))
|
||||
)
|
||||
return res.send({ message: 'Workspace set to past due.' })
|
||||
}
|
||||
case 'invoice.paid': {
|
||||
const invoice = event.data.object as Stripe.Invoice
|
||||
const workspace = await prisma.workspace.findFirst({
|
||||
where: {
|
||||
stripeId: invoice.customer as string,
|
||||
},
|
||||
select: {
|
||||
isPastDue: true,
|
||||
},
|
||||
})
|
||||
if (!workspace?.isPastDue)
|
||||
return res.send({ message: 'Workspace not past_due, skipping.' })
|
||||
const outstandingInvoices = await stripe.invoices.list({
|
||||
customer: invoice.customer as string,
|
||||
status: 'open',
|
||||
})
|
||||
const outstandingInvoicesWithAdditionalUsageCosts =
|
||||
outstandingInvoices.data.filter(
|
||||
(invoice) => invoice.amount_due > prices['PRO'] * 100
|
||||
)
|
||||
if (outstandingInvoicesWithAdditionalUsageCosts.length > 0)
|
||||
return res.send({
|
||||
message: 'Workspace has outstanding invoices, skipping.',
|
||||
})
|
||||
const updatedWorkspace = await prisma.workspace.update({
|
||||
where: {
|
||||
stripeId: invoice.customer as string,
|
||||
},
|
||||
data: {
|
||||
isPastDue: false,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
members: {
|
||||
select: { userId: true },
|
||||
where: {
|
||||
role: WorkspaceRole.ADMIN,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
await trackEvents(
|
||||
updatedWorkspace.members.map((m) => ({
|
||||
name: 'Workspace past due status removed',
|
||||
workspaceId: updatedWorkspace.id,
|
||||
userId: m.userId,
|
||||
}))
|
||||
)
|
||||
return res.send({ message: 'Workspace was regulated' })
|
||||
}
|
||||
case 'customer.subscription.deleted': {
|
||||
const subscription = event.data.object as Stripe.Subscription
|
||||
const { data } = await stripe.subscriptions.list({
|
||||
customer: subscription.customer as string,
|
||||
limit: 1,
|
||||
status: 'active',
|
||||
})
|
||||
const existingSubscription = data[0] as
|
||||
| Stripe.Subscription
|
||||
| undefined
|
||||
if (existingSubscription)
|
||||
return res.send({
|
||||
message:
|
||||
'An active subscription still exists. Skipping downgrade.',
|
||||
})
|
||||
const outstandingInvoices = await stripe.invoices.list({
|
||||
customer: subscription.customer as string,
|
||||
status: 'open',
|
||||
})
|
||||
const outstandingInvoicesWithAdditionalUsageCosts =
|
||||
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,
|
||||
},
|
||||
data: {
|
||||
plan: Plan.FREE,
|
||||
customChatsLimit: null,
|
||||
customStorageLimit: null,
|
||||
customSeatsLimit: null,
|
||||
isPastDue: outstandingInvoicesWithAdditionalUsageCosts.length > 0,
|
||||
},
|
||||
include: {
|
||||
members: {
|
||||
select: { userId: true },
|
||||
where: {
|
||||
role: WorkspaceRole.ADMIN,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await trackEvents(
|
||||
workspace.members.map((m) => ({
|
||||
name: 'Subscription updated',
|
||||
workspaceId: workspace.id,
|
||||
userId: m.userId,
|
||||
data: {
|
||||
plan: Plan.FREE,
|
||||
},
|
||||
}))
|
||||
)
|
||||
|
||||
const typebots = await prisma.typebot.findMany({
|
||||
where: {
|
||||
workspaceId: workspace.id,
|
||||
isArchived: { not: true },
|
||||
},
|
||||
include: { publishedTypebot: true },
|
||||
})
|
||||
for (const typebot of typebots) {
|
||||
const settings = typebot.settings as Settings
|
||||
if (settings.general?.isBrandingEnabled) continue
|
||||
await prisma.typebot.updateMany({
|
||||
where: { id: typebot.id },
|
||||
data: {
|
||||
settings: {
|
||||
...settings,
|
||||
general: {
|
||||
...settings.general,
|
||||
isBrandingEnabled: true,
|
||||
},
|
||||
whatsApp: settings.whatsApp
|
||||
? {
|
||||
...settings.whatsApp,
|
||||
isEnabled: false,
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
},
|
||||
})
|
||||
const publishedTypebotSettings = typebot.publishedTypebot
|
||||
?.settings as Settings | null
|
||||
if (
|
||||
!publishedTypebotSettings ||
|
||||
publishedTypebotSettings?.general?.isBrandingEnabled
|
||||
)
|
||||
continue
|
||||
await prisma.publicTypebot.updateMany({
|
||||
where: { id: typebot.id },
|
||||
data: {
|
||||
settings: {
|
||||
...publishedTypebotSettings,
|
||||
general: {
|
||||
...publishedTypebotSettings.general,
|
||||
isBrandingEnabled: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
return res.send({ message: 'workspace downgraded in DB' })
|
||||
}
|
||||
default: {
|
||||
return res.status(304).send({ message: 'event not handled' })
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
if (err instanceof Error) {
|
||||
console.error(err)
|
||||
return res.status(400).send(`Webhook Error: ${err.message}`)
|
||||
}
|
||||
return res.status(500).send(`Error occured: ${err}`)
|
||||
}
|
||||
}
|
||||
return methodNotAllowed(res)
|
||||
}
|
||||
|
||||
export default cors(webhookHandler as RequestHandler)
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from '@typebot.io/lib/api'
|
||||
import { getAuthenticatedUser } from '@/features/auth/helpers/getAuthenticatedUser'
|
||||
import { sendWorkspaceMemberInvitationEmail } from '@typebot.io/emails'
|
||||
import { getSeatsLimit } from '@typebot.io/billing/getSeatsLimit'
|
||||
import { getSeatsLimit } from '@typebot.io/billing/helpers/getSeatsLimit'
|
||||
import { env } from '@typebot.io/env'
|
||||
|
||||
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
|
||||
Reference in New Issue
Block a user