feat: make billing better (#203)

This commit is contained in:
KM Koushik
2025-08-25 22:35:21 +10:00
committed by GitHub
parent 8ce5e4b2dd
commit 3f9094e95d
25 changed files with 956 additions and 360 deletions

View File

@@ -47,7 +47,11 @@ export async function createCheckoutSessionForTeam(teamId: number) {
customerId = customer.id;
}
if (!env.STRIPE_BASIC_PRICE_ID || !customerId) {
if (
!env.STRIPE_BASIC_PRICE_ID ||
!env.STRIPE_BASIC_USAGE_PRICE_ID ||
!customerId
) {
throw new Error("Stripe prices are not set");
}
@@ -57,6 +61,10 @@ export async function createCheckoutSessionForTeam(teamId: number) {
line_items: [
{
price: env.STRIPE_BASIC_PRICE_ID,
quantity: 1,
},
{
price: env.STRIPE_BASIC_USAGE_PRICE_ID,
},
],
success_url: `${env.NEXTAUTH_URL}/payments?success=true&session_id={CHECKOUT_SESSION_ID}`,
@@ -70,8 +78,13 @@ export async function createCheckoutSessionForTeam(teamId: number) {
return session;
}
function getPlanFromPriceId(priceId: string) {
if (priceId === env.STRIPE_BASIC_PRICE_ID) {
function getPlanFromPriceIds(priceIds: string[]) {
if (
(env.STRIPE_BASIC_PRICE_ID &&
priceIds.includes(env.STRIPE_BASIC_PRICE_ID)) ||
(env.STRIPE_LEGACY_BASIC_PRICE_ID &&
priceIds.includes(env.STRIPE_LEGACY_BASIC_PRICE_ID))
) {
return "BASIC";
}
@@ -129,11 +142,16 @@ export async function syncStripeData(customerId: string) {
return;
}
const priceIds = subscription.items.data
.map((item) => item.price?.id)
.filter((id): id is string => Boolean(id));
await db.subscription.upsert({
where: { id: subscription.id },
update: {
status: subscription.status,
priceId: subscription.items.data[0]?.price?.id || "",
priceIds: priceIds,
currentPeriodEnd: new Date(
subscription.items.data[0]?.current_period_end * 1000
),
@@ -150,6 +168,7 @@ export async function syncStripeData(customerId: string) {
id: subscription.id,
status: subscription.status,
priceId: subscription.items.data[0]?.price?.id || "",
priceIds: priceIds,
currentPeriodEnd: new Date(
subscription.items.data[0]?.current_period_end * 1000
),
@@ -167,7 +186,7 @@ export async function syncStripeData(customerId: string) {
await db.team.update({
where: { id: team.id },
data: {
plan: getPlanFromPriceId(subscription.items.data[0]?.price?.id || ""),
plan: getPlanFromPriceIds(priceIds),
isActive: subscription.status === "active",
},
});