Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

update createPayout logic

Steven Tey87a2b598b272
diff --git a/apps/web/app/(ee)/api/commissions/[commissionId]/route.ts b/apps/web/app/(ee)/api/commissions/[commissionId]/route.ts
index 16d225d368..977ef4f104 100644
--- a/apps/web/app/(ee)/api/commissions/[commissionId]/route.ts
+++ b/apps/web/app/(ee)/api/commissions/[commissionId]/route.ts
@@ -122,8 +122,7 @@ export const PATCH = withWorkspace(async ({ workspace, params, req }) => {
if (commission.status === "processed" && commission.payoutId) {
waitUntil(
prisma.$transaction(async (tx) => {
- const commissions = await tx.commission.groupBy({
- by: ["payoutId"],
+ const commissionAggregate = await tx.commission.aggregate({
where: {
payoutId: commission.payoutId,
},
@@ -132,7 +131,7 @@ export const PATCH = withWorkspace(async ({ workspace, params, req }) => {
},
});
- const newPayoutAmount = commissions[0]._sum.earnings ?? 0;
+ const newPayoutAmount = commissionAggregate._sum.earnings ?? 0;
if (newPayoutAmount === 0) {
console.log(`Deleting payout ${commission.payoutId}`);
diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts
index 4cf6c1981a..916ddb635a 100644
--- a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts
@@ -10,6 +10,8 @@ export const dynamic = "force-dynamic";
// POST /api/cron/payouts/charge-succeeded
// This route is used to process the charge-succeeded event from Stripe
+// we're intentionally offloading this to a cron job to avoid blocking the main thread
+// so that we can return a 200 to Stripe immediately
export async function POST(req: Request) {
try {
const rawBody = await req.text();
diff --git a/apps/web/app/(ee)/api/cron/payouts/confirm/route.ts b/apps/web/app/(ee)/api/cron/payouts/confirm/route.ts
index ebd788d64f..0050910a70 100644
--- a/apps/web/app/(ee)/api/cron/payouts/confirm/route.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/confirm/route.ts
@@ -18,6 +18,7 @@ const confirmPayoutsSchema = z.object({
// POST /api/cron/payouts/confirm
// This route is used to confirm payouts for a given invoice
+// we're intentionally offloading this to a cron job to avoid blocking the main thread
export async function POST(req: Request) {
try {
const rawBody = await req.text();
diff --git a/apps/web/app/(ee)/api/cron/payouts/create-payout.ts b/apps/web/app/(ee)/api/cron/payouts/create-payout.ts
index fe6ec00e5e..1d7f18fcf1 100644
--- a/apps/web/app/(ee)/api/cron/payouts/create-payout.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/create-payout.ts
@@ -1,6 +1,5 @@
import { createId } from "@/lib/api/create-id";
import { prisma } from "@dub/prisma";
-import { Payout } from "@dub/prisma/client";
export const createPayout = async ({
programId,
@@ -51,91 +50,68 @@ export const createPayout = async ({
const { holdingPeriodDays } = programEnrollment.program;
- await prisma.$transaction(async (tx) => {
- const commissions = await tx.commission.findMany({
- where: {
- earnings: {
- gt: 0,
- },
- programId,
- partnerId,
- status: "pending",
- payoutId: null,
- // Only process commissions that were created before the holding period
- ...(holdingPeriodDays > 0 && {
- createdAt: {
- lt: new Date(Date.now() - holdingPeriodDays * 24 * 60 * 60 * 1000),
- },
- }),
- },
- select: {
- id: true,
- createdAt: true,
- earnings: true,
- },
- orderBy: {
- createdAt: "asc",
+ const commissions = await prisma.commission.findMany({
+ where: {
+ earnings: {
+ gt: 0,
},
- });
+ programId,
+ partnerId,
+ status: "pending",
+ payoutId: null,
+ // Only process commissions that were created before the holding period
+ ...(holdingPeriodDays > 0 && {
+ createdAt: {
+ lt: new Date(Date.now() - holdingPeriodDays * 24 * 60 * 60 * 1000),
+ },
+ }),
+ },
+ select: {
+ id: true,
+ createdAt: true,
+ earnings: true,
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ });
- if (!commissions.length) {
- console.log("No pending commissions found for processing payout.", {
- programId,
- partnerId,
- holdingPeriodDays,
- });
+ if (commissions.length === 0) {
+ console.log(
+ `No pending commissions found for partner ${partnerId} in program ${programId}.`,
+ );
- return;
- }
+ return;
+ }
- // earliest commission date
- const periodStart = commissions[0].createdAt;
+ console.log(
+ `Found ${commissions.length} pending commissions for partner ${partnerId} in program ${programId}.`,
+ );
- // end of the month of the latest commission date
- // e.g. if the latest sale is 2024-12-16, the periodEnd should be 2024-12-31
- let periodEnd = commissions[commissions.length - 1].createdAt;
- periodEnd = new Date(periodEnd.getFullYear(), periodEnd.getMonth() + 1);
+ // earliest commission date
+ const periodStart = commissions[0].createdAt;
- const totalAmount = commissions.reduce(
- (total, { earnings }) => total + earnings,
- 0,
- );
+ // end of the month of the latest commission date
+ // e.g. if the latest sale is 2024-12-16, the periodEnd should be 2024-12-31
+ let periodEnd = commissions[commissions.length - 1].createdAt;
+ periodEnd = new Date(periodEnd.getFullYear(), periodEnd.getMonth() + 1);
- if (totalAmount === 0) {
- console.log("Total amount is 0, skipping payout.", {
- programId,
- partnerId,
- totalAmount,
- });
-
- return;
- }
-
- // check if the partner has another pending payout
- const existingPayout = await tx.payout.findFirst({
+ await prisma.$transaction(async (tx) => {
+ // check if the partner has another pending payout (take the latest entry)
+ let payout = await tx.payout.findFirst({
where: {
programId,
partnerId,
status: "pending",
},
+ orderBy: {
+ createdAt: "desc",
+ },
});
- let payout: Payout | null = null;
-
- if (existingPayout) {
- payout = await tx.payout.update({
- where: {
- id: existingPayout.id,
- },
- data: {
- amount: {
- increment: totalAmount,
- },
- periodEnd,
- description: existingPayout.description ?? "Dub Partners payout",
- },
- });
- } else {
+ // if the partner has no pending payout, create a new one
+ if (!payout) {
+ console.log("No existing payout found, creating new one.");
payout = await tx.payout.create({
data: {
id: createId({ prefix: "po_" }),
@@ -143,16 +119,14 @@ export const createPayout = async ({
partnerId,
periodStart,
periodEnd,
- amount: totalAmount,
description: "Dub Partners payout",
},
});
}
- if (!payout) {
- throw new Error("Payout not created.");
- }
+ console.log(`Payout ID to use: ${payout.id}`);
+ // update the commissions to processed and set the payoutId
await tx.commission.updateMany({
where: {
id: {
@@ -165,6 +139,34 @@ export const createPayout = async ({
},
});
- console.log("Payout created", payout);
+ console.log(
+ `Updated ${commissions.length} commissions to processed and set payoutId to ${payout.id}.`,
+ );
+
+ // get the total earnings for the commissions in the payout
+ const commissionAggregate = await tx.commission.aggregate({
+ where: {
+ payoutId: payout.id,
+ },
+ _sum: {
+ earnings: true,
+ },
+ });
+
+ const newPayoutAmount = commissionAggregate._sum.earnings ?? 0;
+
+ console.log(
+ `Updating aggregated earnings for payout ${payout.id}: ${newPayoutAmount}`,
+ );
+
+ // update the payout amount
+ await tx.payout.update({
+ where: {
+ id: payout.id,
+ },
+ data: {
+ amount: newPayoutAmount,
+ },
+ });
});
};