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.

Optimize /cron/payouts

Steven Teyde44ac5a9985
diff --git a/apps/web/app/(ee)/api/cron/payouts/create-payout.ts b/apps/web/app/(ee)/api/cron/payouts/create-payout.ts
deleted file mode 100644
index 42db0fcc64..0000000000
--- a/apps/web/app/(ee)/api/cron/payouts/create-payout.ts
+++ /dev/null
@@ -1,221 +0,0 @@
-import { createId } from "@/lib/api/create-id";
-import { prisma } from "@dub/prisma";
-import { Prisma } from "@dub/prisma/client";
-import { endOfMonth } from "date-fns";
-
-export const createPayout = async ({
- programId,
- partnerId,
-}: {
- programId: string;
- partnerId: string;
-}) => {
- const programEnrollment = await prisma.programEnrollment.findUniqueOrThrow({
- where: {
- partnerId_programId: {
- partnerId,
- programId,
- },
- },
- select: {
- status: true,
- program: {
- select: {
- name: true,
- holdingPeriodDays: true,
- },
- },
- },
- });
-
- if (programEnrollment.status === "banned") {
- await prisma.commission.updateMany({
- where: {
- earnings: {
- gt: 0,
- },
- programId,
- partnerId,
- status: "pending",
- },
- data: {
- status: "canceled",
- },
- });
-
- console.log("Canceled commissions for banned partner.", {
- programId,
- partnerId,
- });
-
- return;
- }
-
- const { holdingPeriodDays } = programEnrollment.program;
-
- const commonWhere: Prisma.CommissionWhereInput = {
- programId,
- partnerId,
- status: "pending",
- payoutId: null,
- };
-
- const [commissions, clawbacks] = await Promise.all([
- // Find all pending commissions
- prisma.commission.findMany({
- where: {
- earnings: {
- gt: 0,
- },
- ...commonWhere,
- // If there is a holding period set:
- // we only process commissions that were created before the holding period
- // but custom commissions are always included
- ...(holdingPeriodDays > 0
- ? {
- OR: [
- {
- type: "custom",
- },
- {
- createdAt: {
- lt: new Date(
- Date.now() - holdingPeriodDays * 24 * 60 * 60 * 1000,
- ),
- },
- },
- ],
- }
- : {}),
- },
- select: {
- id: true,
- createdAt: true,
- earnings: true,
- },
- orderBy: {
- createdAt: "asc",
- },
- }),
-
- // Find all pending clawbacks
- // We don't wait for the holding period to be over for clawbacks
- prisma.commission.findMany({
- where: {
- earnings: {
- lt: 0,
- },
- ...commonWhere,
- },
- select: {
- id: true,
- createdAt: true,
- earnings: true,
- },
- orderBy: {
- createdAt: "asc",
- },
- }),
- ]);
-
- if (commissions.length === 0 && clawbacks.length === 0) {
- return;
- }
-
- console.log(
- `Found ${commissions.length} pending commissions for partner ${partnerId} in program ${programId}.`,
- );
-
- console.log(
- `Found ${clawbacks.length} pending clawbacks for partner ${partnerId} in program ${programId}.`,
- );
-
- // sort the commissions and clawbacks by createdAt
- const allCommissions = [...commissions, ...clawbacks].sort(
- (a, b) => a.createdAt.getTime() - b.createdAt.getTime(),
- );
-
- // earliest commission date
- const periodStart = allCommissions[0].createdAt;
-
- // 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
- const periodEnd = endOfMonth(
- allCommissions[allCommissions.length - 1].createdAt,
- );
-
- 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",
- },
- });
-
- // 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_" }),
- programId,
- partnerId,
- periodStart,
- periodEnd,
- description: `Dub Partners payout (${programEnrollment.program.name})`,
- },
- });
- }
-
- console.log(`Using payout ID ${payout.id}.`);
-
- // update the commissions to processed and set the payoutId
- await tx.commission.updateMany({
- where: {
- id: {
- in: allCommissions.map(({ id }) => id),
- },
- },
- data: {
- status: "processed",
- payoutId: payout.id,
- },
- });
-
- console.log(
- `Updated ${allCommissions.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,
- periodEnd,
- },
- });
- });
-};
diff --git a/apps/web/app/(ee)/api/cron/payouts/route.ts b/apps/web/app/(ee)/api/cron/payouts/route.ts
index 5044306654..5a418326f3 100644
--- a/apps/web/app/(ee)/api/cron/payouts/route.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/route.ts
@@ -1,8 +1,9 @@
+import { createId } from "@/lib/api/create-id";
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
import { prisma } from "@dub/prisma";
+import { endOfMonth } from "date-fns";
import { NextResponse } from "next/server";
-import { createPayout } from "./create-payout";
export const dynamic = "force-dynamic";
@@ -14,34 +15,218 @@ export async function GET(req: Request) {
try {
await verifyVercelSignature(req);
- const commissions = await prisma.commission.groupBy({
+ const groupedCommissions = await prisma.commission.groupBy({
by: ["programId", "partnerId"],
where: {
- earnings: {
- not: 0,
- },
status: "pending",
payoutId: null,
},
});
- if (!commissions.length) {
+ if (!groupedCommissions.length) {
return NextResponse.json({
- message: "No pending sale commissions found. Skipping...",
+ message: "No pending commissions found. Skipping...",
});
}
- // TODO: Find a batter way to handle this recursively (e.g. /api/cron/usage)
- for (const { programId, partnerId } of commissions) {
- await createPayout({
- programId,
+ console.log(
+ `Found ${groupedCommissions.length} pending commissions to process.`,
+ );
+
+ const programIdsToPartnerIds = groupedCommissions.reduce(
+ (acc, { programId, partnerId }) => {
+ acc[programId] = partnerId;
+ return acc;
+ },
+ {},
+ );
+
+ for (const programId in programIdsToPartnerIds) {
+ const program = await prisma.program.findUnique({
+ where: {
+ id: programId,
+ },
+ include: {
+ partners: {
+ where: {
+ partnerId: {
+ in: programIdsToPartnerIds[programId],
+ },
+ },
+ },
+ },
+ });
+
+ if (!program) {
+ continue;
+ }
+
+ const { name, holdingPeriodDays, partners } = program;
+
+ const bannedPartners = partners.filter(
+ (partner) => partner.status === "banned",
+ );
+ const updatedBannedCommissions = await prisma.commission.updateMany({
+ where: {
+ earnings: {
+ gt: 0,
+ },
+ programId,
+ partnerId: {
+ in: bannedPartners.map((partner) => partner.id),
+ },
+ status: "pending",
+ },
+ data: {
+ status: "canceled",
+ },
+ });
+ console.log(
+ `Updated ${updatedBannedCommissions.count} banned commissions for program ${name} to canceled`,
+ );
+
+ // Find all pending commissions
+ const pendingCommissionsForProgram = await prisma.commission.findMany({
+ where: {
+ status: "pending",
+ programId,
+ // If there is a holding period set:
+ // we only process commissions that were created before the holding period
+ // but custom commissions are always included
+ ...(holdingPeriodDays > 0
+ ? {
+ OR: [
+ {
+ type: "custom", // includes manual commissions + clawbacks
+ },
+ {
+ createdAt: {
+ lt: new Date(
+ Date.now() - holdingPeriodDays * 24 * 60 * 60 * 1000,
+ ),
+ },
+ },
+ ],
+ }
+ : {}),
+ },
+ select: {
+ id: true,
+ createdAt: true,
+ earnings: true,
+ partnerId: true,
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ });
+
+ if (pendingCommissionsForProgram.length === 0) {
+ continue;
+ }
+
+ const partnerIdsToCommissions = pendingCommissionsForProgram.reduce<
+ Record<string, typeof pendingCommissionsForProgram>
+ >((acc, commission) => {
+ if (!acc[commission.partnerId]) {
+ acc[commission.partnerId] = [];
+ }
+ acc[commission.partnerId].push(commission);
+ return acc;
+ }, {});
+
+ const partnerIdsToCommissionsArray = Object.entries(
+ partnerIdsToCommissions,
+ ).map(([partnerId, commissions]) => ({
partnerId,
+ commissions,
+ }));
+
+ const existingPendingPayouts = await prisma.payout.findMany({
+ where: {
+ programId,
+ partnerId: {
+ in: partnerIdsToCommissionsArray.map((p) => p.partnerId),
+ },
+ status: "pending",
+ },
});
+
+ for (const { partnerId, commissions } of partnerIdsToCommissionsArray) {
+ // sort the commissions by createdAt
+ const sortedCommissions = commissions.sort(
+ (a, b) => a.createdAt.getTime() - b.createdAt.getTime(),
+ );
+
+ // sum the earnings of the commissions
+ const totalEarnings = sortedCommissions.reduce(
+ (total, commission) => total + commission.earnings,
+ 0,
+ );
+
+ // earliest commission date
+ const periodStart = sortedCommissions[0].createdAt;
+
+ // 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
+ const periodEnd = endOfMonth(
+ sortedCommissions[sortedCommissions.length - 1].createdAt,
+ );
+
+ let payoutToUse = existingPendingPayouts.find(
+ (p) => p.partnerId === partnerId,
+ );
+
+ if (!payoutToUse) {
+ payoutToUse = await prisma.payout.create({
+ data: {
+ id: createId({ prefix: "po_" }),
+ programId,
+ partnerId,
+ periodStart,
+ periodEnd,
+ amount: totalEarnings,
+ description: `Dub Partners payout (${program.name})`,
+ },
+ });
+ console.log(
+ `Noe existing payout found, created new one ${payoutToUse.id} for partner ${partnerId}`,
+ );
+ }
+
+ const updatedCommissions = await prisma.commission.updateMany({
+ where: {
+ id: { in: commissions.map((c) => c.id) },
+ },
+ data: {
+ payoutId: payoutToUse.id,
+ },
+ });
+ console.log(
+ `Updated ${updatedCommissions.count} commissions to have payoutId ${payoutToUse.id}`,
+ );
+
+ // if we're reusing a pending payout, we need to update the amount
+ if (existingPendingPayouts.find((p) => p.id === payoutToUse.id)) {
+ const updatedPayout = await prisma.payout.update({
+ where: {
+ id: payoutToUse.id,
+ },
+ data: {
+ amount: {
+ increment: totalEarnings,
+ },
+ },
+ });
+ console.log(
+ `Since we're reusing payout ${payoutToUse.id}, add the new earnings of ${totalEarnings} to the payout amount, making it ${updatedPayout.amount}`,
+ );
+ }
+ }
}
return NextResponse.json({
- message: "Sale commissions payout created.",
- commissions,
+ message: "Commissions payout created.",
});
} catch (error) {
return handleAndReturnErrorResponse(error);