The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Implement unified payout creation for earnings events
Kiran K3bb7658231c0
diff --git a/apps/web/app/api/cron/payouts/clicks/route.ts b/apps/web/app/api/cron/payouts/clicks/route.tsindex c1a0f8db6a..22d537b03b 100644--- a/apps/web/app/api/cron/payouts/clicks/route.ts+++ b/apps/web/app/api/cron/payouts/clicks/route.ts@@ -1,9 +1,8 @@import { handleAndReturnErrorResponse } from "@/lib/api/errors";-import { createId } from "@/lib/api/utils";import { verifyVercelSignature } from "@/lib/cron/verify-vercel";import { prisma } from "@dub/prisma";-import { Payout } from "@dub/prisma/client";import { NextResponse } from "next/server";+import { createPayout } from "../create-payout";export const dynamic = "force-dynamic";@@ -14,7 +13,7 @@ export async function GET(req: Request) {try {await verifyVercelSignature(req);- let clicks = await prisma.earnings.groupBy({+ const clicks = await prisma.earnings.groupBy({by: ["programId", "partnerId"],where: {type: "click",@@ -33,136 +32,18 @@ export async function GET(req: Request) {}for (const { programId, partnerId } of clicks) {- const payout = await createClickPayout({+ await createPayout({programId,partnerId,- });-- console.log({- programId,- payout,+ type: "click",});}return NextResponse.json({message: "Clicks payout created.",+ clicks,});} catch (error) {return handleAndReturnErrorResponse(error);}}--const createClickPayout = async ({- programId,- partnerId,-}: {- programId: string;- partnerId: string;-}) => {- const earnings = await prisma.$transaction(async (tx) => {- const earnings = await tx.earnings.findMany({- where: {- programId,- partnerId,- payoutId: null,- type: "click",- status: "pending",- },- select: {- id: true,- createdAt: true,- earnings: true,- quantity: true,- },- orderBy: {- createdAt: "asc",- },- });-- if (!earnings.length) {- return;- }-- // earliest click date- const periodStart = earnings[0].createdAt;-- // end of the month of the latest click- let periodEnd = earnings[earnings.length - 1].createdAt;- periodEnd = new Date(periodEnd.getFullYear(), periodEnd.getMonth() + 1);-- const totalQuantity = earnings.reduce(- (total, click) => total + click.quantity,- 0,- );-- const totalAmount = earnings.reduce(- (total, click) => total + click.earnings,- 0,- );-- let payout: Payout | null = null;-- // check if the partner has another pending payout- const existingPayout = await tx.payout.findFirst({- where: {- programId,- partnerId,- status: "pending",- type: "clicks",- },- });-- if (existingPayout) {- payout = await tx.payout.update({- where: {- id: existingPayout.id,- },- data: {- amount: {- increment: totalAmount,- },- quantity: {- increment: totalQuantity,- },- periodEnd,- description: existingPayout.description ?? "Dub Partners payout",- },- });- } else {- payout = await tx.payout.create({- data: {- id: createId({ prefix: "po_" }),- programId,- partnerId,- periodStart,- periodEnd,- amount: totalAmount,- quantity: totalQuantity,- description: "Dub Partners payout",- type: "clicks",- },- });- }-- console.info("Payout created", payout);-- if (!payout) {- throw new Error("Payout not created.");- }-- // update the sales records- await tx.earnings.updateMany({- where: {- id: {- in: earnings.map(({ id }) => id),- },- },- data: {- status: "processed",- payoutId: payout.id,- },- });-- return payout;- });-};diff --git a/apps/web/app/api/cron/payouts/create-payout.ts b/apps/web/app/api/cron/payouts/create-payout.tsnew file mode 100644index 0000000000..6b923099e4--- /dev/null+++ b/apps/web/app/api/cron/payouts/create-payout.ts@@ -0,0 +1,142 @@+import { createId } from "@/lib/api/utils";+import { prisma } from "@dub/prisma";+import { EventType, Payout } from "@dub/prisma/client";++export const createPayout = async ({+ programId,+ partnerId,+ type,+}: {+ programId: string;+ partnerId: string;+ type: EventType;+}) => {+ await prisma.$transaction(async (tx) => {+ const earnings = await tx.earnings.findMany({+ where: {+ programId,+ partnerId,+ payoutId: null,+ type,+ status: "pending",+ },+ select: {+ id: true,+ createdAt: true,+ earnings: true,+ quantity: true,+ },+ orderBy: {+ createdAt: "asc",+ },+ });++ if (!earnings.length) {+ console.log("No pending earnings found for processing payout.", {+ programId,+ partnerId,+ type,+ });++ return;+ }++ // get the earliest sale date+ // const periodStart = sales.reduce(+ // (min, sale) => (sale.createdAt < min ? sale.createdAt : min),+ // sales[0].createdAt,+ // );++ // earliest earnings date+ const periodStart = earnings[0].createdAt;++ // end of the month of the latest earnings date+ // e.g. if the latest sale is 2024-12-16, the periodEnd should be 2024-12-31+ let periodEnd = earnings[earnings.length - 1].createdAt;+ periodEnd = new Date(periodEnd.getFullYear(), periodEnd.getMonth() + 1);++ const totalQuantity = earnings.reduce(+ (total, { quantity }) => total + quantity,+ 0,+ );++ const totalAmount = earnings.reduce(+ (total, { earnings }) => total + earnings,+ 0,+ );++ if (totalAmount === 0) {+ console.log("Total amount is 0, skipping payout.", {+ programId,+ partnerId,+ type,+ totalQuantity,+ totalAmount,+ });++ return;+ }++ // check if the partner has another pending payout+ const existingPayout = await tx.payout.findFirst({+ where: {+ programId,+ partnerId,+ type: `${type}s`,+ status: "pending",+ },+ });++ let payout: Payout | null = null;++ if (existingPayout) {+ payout = await tx.payout.update({+ where: {+ id: existingPayout.id,+ },+ data: {+ amount: {+ increment: totalAmount,+ },+ quantity: {+ increment: totalQuantity,+ },+ periodEnd,+ description: existingPayout.description ?? "Dub Partners payout",+ },+ });+ } else {+ payout = await tx.payout.create({+ data: {+ id: createId({ prefix: "po_" }),+ programId,+ partnerId,+ periodStart,+ periodEnd,+ amount: totalAmount,+ quantity: totalQuantity,+ description: "Dub Partners payout",+ type: `${type}s`,+ },+ });+ }++ if (!payout) {+ throw new Error("Payout not created.");+ }++ await tx.earnings.updateMany({+ where: {+ id: {+ in: earnings.map(({ id }) => id),+ },+ },+ data: {+ status: "processed",+ payoutId: payout.id,+ },+ });++ console.log("Payout created", payout);+ });+};diff --git a/apps/web/app/api/cron/payouts/leads/route.ts b/apps/web/app/api/cron/payouts/leads/route.tsnew file mode 100644index 0000000000..d39c49ca02--- /dev/null+++ b/apps/web/app/api/cron/payouts/leads/route.ts@@ -0,0 +1,49 @@+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { verifyVercelSignature } from "@/lib/cron/verify-vercel";+import { prisma } from "@dub/prisma";+import { NextResponse } from "next/server";+import { createPayout } from "../create-payout";++export const dynamic = "force-dynamic";++// This route is used to calculate payouts for leads.+// Runs once every day at 00:00 (0 0 * * *)+// GET /api/cron/payouts/leads+export async function GET(req: Request) {+ try {+ await verifyVercelSignature(req);++ const leads = await prisma.earnings.groupBy({+ by: ["programId", "partnerId"],+ where: {+ type: "lead",+ status: "pending",+ payoutId: null,+ },+ _sum: {+ quantity: true,+ },+ });++ if (!leads.length) {+ return NextResponse.json({+ message: "No pending leads found. Skipping...",+ });+ }++ for (const { programId, partnerId } of leads) {+ await createPayout({+ programId,+ partnerId,+ type: "lead",+ });+ }++ return NextResponse.json({+ message: "Leads payout created.",+ leads,+ });+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/app/api/cron/payouts/sales/route.ts b/apps/web/app/api/cron/payouts/sales/route.tsindex f99c8c1351..40507507f5 100644--- a/apps/web/app/api/cron/payouts/sales/route.ts+++ b/apps/web/app/api/cron/payouts/sales/route.ts@@ -1,46 +1,49 @@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";+import { createPayout } from "../create-payout";export const dynamic = "force-dynamic";-/*- This route is used to calculate payouts for partners.- Runs once every hour (0 * * * *)-*/--// GET /cron/payouts/sales+// This route is used to calculate payouts for sales.+// Runs once every hour (0 * * * *)+// GET /api/cron/payouts/salesexport async function GET(req: Request) {try {await verifyVercelSignature(req);- const pendingSales = await prisma.sale.groupBy({+ const sales = await prisma.earnings.groupBy({by: ["programId", "partnerId"],where: {+ type: "sale",status: "pending",+ payoutId: null,},- _count: {- id: true,+ _sum: {+ quantity: true,},});- if (!pendingSales.length) {+ if (!sales.length) {return NextResponse.json({message: "No pending sales found. Skipping...",});}// TODO: Find a batter way to handle this recursively (e.g. /api/cron/usage)- for (const { programId, partnerId } of pendingSales) {- await createSalesPayout({+ for (const { programId, partnerId } of sales) {+ await createPayout({programId,partnerId,+ type: "sale",});}- return NextResponse.json(pendingSales);+ return NextResponse.json({+ message: "Sales payout created.",+ sales,+ });} catch (error) {return handleAndReturnErrorResponse(error);}diff --git a/apps/web/lib/partners/create-sales-payout.ts b/apps/web/lib/partners/create-sales-payout.tsindex 7355c54b40..fb9ccd2426 100644--- a/apps/web/lib/partners/create-sales-payout.ts+++ b/apps/web/lib/partners/create-sales-payout.ts@@ -2,6 +2,9 @@ import { createId } from "@/lib/api/utils";import { prisma } from "@dub/prisma";import { Payout } from "@dub/prisma/client";+// TODO:+// Remove this since we no longer use this+// Calculate the commission earned for the partner for the given programexport const createSalesPayout = async ({programId,