The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Enhance folder and link sync process for Stripe subscription changes
Kiran K797c68d215ef
diff --git a/apps/web/app/api/cron/links/sync-tinybird/route.ts b/apps/web/app/api/cron/links/sync-tinybird/route.tsindex e10ec35028..31bf7ceb55 100644--- a/apps/web/app/api/cron/links/sync-tinybird/route.ts+++ b/apps/web/app/api/cron/links/sync-tinybird/route.ts@@ -40,10 +40,16 @@ export async function POST(req: Request) {const countOfLinks = folder._count.links;if (countOfLinks === 0) {- return new Response("No links found in the folder. Skipping...");+ await prisma.folder.delete({+ where: {+ id: folderId,+ },+ });++ return new Response("No more links to process. Deleting folder...");}- await prisma.$transaction(+ const processedLinks = await prisma.$transaction(async (tx) => {const links = await tx.link.findMany({where: {@@ -59,10 +65,15 @@ export async function POST(req: Request) {orderBy: {id: "asc",},- take: 500,+ take: 1,});- await recordLink(links);+ await recordLink(+ links.map((link) => ({+ ...link,+ folderId: null,+ })),+ );await tx.link.updateMany({where: {@@ -74,6 +85,8 @@ export async function POST(req: Request) {folderId: null,},});++ return links;},{timeout: 10000,@@ -85,7 +98,9 @@ export async function POST(req: Request) {delay: 2,});- return new Response(`Processed ${countOfLinks} links in the folder.`);+ return new Response(+ `Processed ${processedLinks.length} links in the folder.`,+ );} catch (error) {return handleAndReturnErrorResponse(error);}diff --git a/apps/web/app/api/folders/[folderId]/route.ts b/apps/web/app/api/folders/[folderId]/route.tsindex 1fbb4a5bf6..717afc4924 100644--- a/apps/web/app/api/folders/[folderId]/route.ts+++ b/apps/web/app/api/folders/[folderId]/route.ts@@ -106,7 +106,7 @@ export const DELETE = withWorkspace(async ({ params, workspace, session }) => {const { folderId } = params;- await verifyFolderAccess({+ const folder = await verifyFolderAccess({workspace,userId: session.user.id,folderId,diff --git a/apps/web/app/api/stripe/webhook/customer-subscription-deleted.ts b/apps/web/app/api/stripe/webhook/customer-subscription-deleted.tsindex 020346e412..06f8b2a2d9 100644--- a/apps/web/app/api/stripe/webhook/customer-subscription-deleted.ts+++ b/apps/web/app/api/stripe/webhook/customer-subscription-deleted.ts@@ -1,3 +1,4 @@+import { scheduleLinkSync } from "@/lib/api/links/utils/sync-links";import { recordLink } from "@/lib/tinybird";import { redis } from "@/lib/upstash";import { webhookCache } from "@/lib/webhook/cache";@@ -22,6 +23,7 @@ export async function customerSubscriptionDeleted(event: Stripe.Event) {id: true,slug: true,domains: true,+ foldersUsage: true,links: {where: {key: "_root",@@ -65,7 +67,6 @@ export async function customerSubscriptionDeleted(event: Stripe.Event) {}const workspaceLinks = workspace.links;-const workspaceUsers = workspace.users.map(({ user }) => user);const pipeline = redis.pipeline();@@ -177,13 +178,6 @@ export async function customerSubscriptionDeleted(event: Stripe.Event) {webhookEnabled: false,},}),-- // Remove all folders for the workspace- prisma.folder.deleteMany({- where: {- projectId: workspace.id,- },- }),]);// Update the webhooks cache@@ -201,4 +195,35 @@ export async function customerSubscriptionDeleted(event: Stripe.Event) {});await webhookCache.mset(webhooks);++ if (workspace.foldersUsage > 0) {+ const folders = await prisma.folder.findMany({+ where: {+ projectId: workspace.id,+ },+ select: {+ id: true,+ },+ });++ await prisma.project.update({+ where: {+ id: workspace.id,+ },+ data: {+ foldersUsage: {+ decrement: folders.length,+ },+ },+ });++ await Promise.all(+ folders.map(({ id }) =>+ scheduleLinkSync({+ folderId: id,+ delay: 5,+ }),+ ),+ );+ }}diff --git a/apps/web/app/api/stripe/webhook/customer-subscription-updated.ts b/apps/web/app/api/stripe/webhook/customer-subscription-updated.tsindex 7a2ff4460f..b3f64d0e99 100644--- a/apps/web/app/api/stripe/webhook/customer-subscription-updated.ts+++ b/apps/web/app/api/stripe/webhook/customer-subscription-updated.ts@@ -1,3 +1,4 @@+import { scheduleLinkSync } from "@/lib/api/links/utils/sync-links";import { webhookCache } from "@/lib/webhook/cache";import { prisma } from "@dub/prisma";import { getPlanFromPriceId, log } from "@dub/utils";@@ -29,6 +30,7 @@ export async function customerSubscriptionUpdated(event: Stripe.Event) {id: true,plan: true,paymentFailedAt: true,+ foldersUsage: true,users: {select: {user: {@@ -61,7 +63,7 @@ export async function customerSubscriptionUpdated(event: Stripe.Event) {const newPlan = plan.name.toLowerCase();const shouldDisableWebhooks = newPlan === "free" || newPlan === "pro";- const shouldDeleteFolders = newPlan === "free";+ const shouldDeleteFolders = newPlan === "free" && workspace.foldersUsage > 0;// If a workspace upgrades/downgrades their subscription, update their usage limit in the database.if (workspace.plan !== newPlan) {@@ -136,14 +138,34 @@ export async function customerSubscriptionUpdated(event: Stripe.Event) {// Delete the folders if the new plan is free// For downgrade from Business → Pro, it should be fine since we're accounting that to make sure all folders get write access.if (shouldDeleteFolders) {- await prisma.folder.deleteMany({+ const folders = await prisma.folder.findMany({where: {projectId: workspace.id,},+ select: {+ id: true,+ },+ });++ await prisma.project.update({+ where: {+ id: workspace.id,+ },+ data: {+ foldersUsage: {+ decrement: folders.length,+ },+ },});- // TODO- // call recordLink to update the Links in TB+ await Promise.all(+ folders.map(({ id }) =>+ scheduleLinkSync({+ folderId: id,+ delay: 5,+ }),+ ),+ );}} else if (workspace.paymentFailedAt) {await prisma.project.update({