The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
add /trigger-withdrawal cron
Steven Teyaf990b0d1abf
diff --git a/apps/web/app/api/cron/cleanup/route.ts b/apps/web/app/api/cron/cleanup/route.tsindex 80f884e05f..8512a43b33 100644--- a/apps/web/app/api/cron/cleanup/route.ts+++ b/apps/web/app/api/cron/cleanup/route.ts@@ -11,8 +11,10 @@ export const dynamic = "force-dynamic";const E2E_USER_ID = "clxz1q7c7000hbqx5ckv4r82h";const E2E_WORKSPACE_ID = "clrei1gld0002vs9mzn93p8ik";-// Cron to remove links and domains created during the E2E test.-// Run every 6 hours (0 */6 * * *)+/***+ This route is used to remove links and domains created during the E2E test.+ Runs every 6 hours (0 * / 6 * * *)+*/export async function GET(req: Request) {try {await verifyVercelSignature(req);diff --git a/apps/web/app/api/cron/links/delete/route.ts b/apps/web/app/api/cron/links/delete/route.tsindex eb31ea2080..b42c5d376a 100644--- a/apps/web/app/api/cron/links/delete/route.ts+++ b/apps/web/app/api/cron/links/delete/route.ts@@ -5,6 +5,10 @@ import { prisma } from "@dub/prisma";export const dynamic = "force-dynamic";+/*+ This route is used to delete demo links that are not claimed+ It is called by QStash 30 minutes after a demo link is created+*/export async function POST(req: Request) {try {const body = await req.json();diff --git a/apps/web/app/api/cron/payouts/route.ts b/apps/web/app/api/cron/payouts/route.tsdeleted file mode 100644index 42f31c8a78..0000000000--- a/apps/web/app/api/cron/payouts/route.ts+++ /dev/null@@ -1,18 +0,0 @@-import { handleAndReturnErrorResponse } from "@/lib/api/errors";-import { verifyVercelSignature } from "@/lib/cron/verify-vercel";-import { NextResponse } from "next/server";-import { processMonthlyPartnerPayouts } from "./utils";--export const dynamic = "force-dynamic";--export async function GET(req: Request) {- try {- await verifyVercelSignature(req);-- await processMonthlyPartnerPayouts();-- return NextResponse.json({ message: "Payouts calculated" });- } catch (error) {- return handleAndReturnErrorResponse(error);- }-}diff --git a/apps/web/app/api/cron/payouts/utils.ts b/apps/web/app/api/cron/payouts/utils.tsdeleted file mode 100644index 69576baa2f..0000000000--- a/apps/web/app/api/cron/payouts/utils.ts+++ /dev/null@@ -1,40 +0,0 @@-import { createSalesPayout } from "@/lib/partners/create-sales-payout";-import { prisma } from "@dub/prisma";--// Payout are calcuated at the end of the month-export const processMonthlyPartnerPayouts = async () => {- const partners = await prisma.programEnrollment.findMany({- where: {- status: "approved",- },- });-- if (!partners.length) {- return;- }-- const currentDate = new Date();-- const periodStart = new Date(- currentDate.getFullYear(),- currentDate.getMonth(),- 1,- );-- const periodEnd = new Date(- currentDate.getFullYear(),- currentDate.getMonth() + 1,- 0,- );-- // TODO:- // We need a batter way to handle this recursively- for (const { programId, partnerId } of partners) {- await createSalesPayout({- programId,- partnerId,- periodStart,- periodEnd,- });- }-};diff --git a/apps/web/app/api/cron/process-payouts/route.ts b/apps/web/app/api/cron/process-payouts/route.tsnew file mode 100644index 0000000000..e830e49242--- /dev/null+++ b/apps/web/app/api/cron/process-payouts/route.ts@@ -0,0 +1,58 @@+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { verifyVercelSignature } from "@/lib/cron/verify-vercel";+import { createSalesPayout } from "@/lib/partners/create-sales-payout";+import { prisma } from "@dub/prisma";+import { NextResponse } from "next/server";++export const dynamic = "force-dynamic";++/*+ This route is used to calculate payouts for partners.+ Runs once every hour (0 * * * *)+*/+export async function GET(req: Request) {+ try {+ await verifyVercelSignature(req);++ const partners = await prisma.programEnrollment.findMany({+ where: {+ status: "approved",+ },+ });++ if (!partners.length) {+ return;+ }++ const currentDate = new Date();++ const periodStart = new Date(+ currentDate.getFullYear(),+ currentDate.getMonth(),+ 1,+ );++ const periodEnd = new Date(+ currentDate.getFullYear(),+ currentDate.getMonth() + 1,+ 0,+ );++ // TODO:+ // We need a batter way to handle this recursively+ for (const { programId, partnerId } of partners) {+ await createSalesPayout({+ programId,+ partnerId,+ periodStart,+ periodEnd,+ });+ }++ return NextResponse.json({+ message: `Calculated payouts for ${partners.length} partners`,+ });+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/app/api/cron/trigger-withdrawal/route.ts b/apps/web/app/api/cron/trigger-withdrawal/route.tsnew file mode 100644index 0000000000..c2ed5da268--- /dev/null+++ b/apps/web/app/api/cron/trigger-withdrawal/route.ts@@ -0,0 +1,62 @@+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { verifyVercelSignature } from "@/lib/cron/verify-vercel";+import { stripe } from "@/lib/stripe";+import { prisma } from "@dub/prisma";+import { NextResponse } from "next/server";++export const dynamic = "force-dynamic";++/*+ This route is used to trigger withdrawal from Stripe (since we're using manual payouts)+ Runs twice a day at midnight and noon UTC (0 0 * * * and 0 12 * * *)+*/+export async function GET(req: Request) {+ try {+ await verifyVercelSignature(req);++ const [currentBalance, pendingPayouts] = await Promise.all([+ stripe.balance.retrieve(),+ prisma.payout.findMany({+ where: {+ status: "processing",+ },+ }),+ ]);++ let reservedBalance = 50000; // keep at least $500 in the account++ if (pendingPayouts.length) {+ const totalPendingPayouts = pendingPayouts.reduce(+ (acc, payout) => acc + payout.amount,+ 0,+ );++ // add the pending payouts to the reserved balance (to make sure we have enough balance+ // to pay out partners when chargeSucceeded webhook is triggered)+ reservedBalance += totalPendingPayouts;+ }++ if (reservedBalance > currentBalance.available[0].amount) {+ return NextResponse.json({+ message: "Insufficient balance to trigger withdrawal, skipping...",+ });+ }++ const balanceToWithdraw =+ currentBalance.available[0].amount - reservedBalance;++ const createPayout = await stripe.payouts.create({+ amount: balanceToWithdraw,+ currency: "usd",+ });++ return NextResponse.json({+ currentBalance,+ reservedBalance,+ balanceToWithdraw,+ createPayout,+ });+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/app/api/cron/usage/route.ts b/apps/web/app/api/cron/usage/route.tsindex 5cd3a55c14..c022ccd5d0 100644--- a/apps/web/app/api/cron/usage/route.ts+++ b/apps/web/app/api/cron/usage/route.ts@@ -5,9 +5,10 @@ import { log } from "@dub/utils";import { NextResponse } from "next/server";import { updateUsage } from "./utils";-// Cron to update the usage stats of each workspace.-// Runs once every day at noon UTC (0 12 * * *)-+/*+ This route is used to update the usage stats of each workspace.+ Runs once every day at noon UTC (0 12 * * *)+*/export const dynamic = "force-dynamic";async function handler(req: Request) {diff --git a/apps/web/vercel.json b/apps/web/vercel.jsonindex 8f9ffe21e6..6d88127727 100644--- a/apps/web/vercel.json+++ b/apps/web/vercel.json@@ -17,8 +17,12 @@"schedule": "0 12 * * 1"},{- "path": "/api/cron/cleanup-expired-public-tokens",- "schedule": "0 12 * * *"+ "path": "/api/cron/process-payouts",+ "schedule": "0 * * * *"+ },+ {+ "path": "/api/cron/trigger-withdrawal",+ "schedule": "0 0,12 * * *"}],"functions": {