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.

add /api/cron/payouts/confirm

Kiran K74c72fd265b5
diff --git a/apps/web/app/(ee)/api/cron/payouts/confirm/confirm-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/confirm/confirm-payouts.ts
new file mode 100644
index 0000000000..d942f5e951
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/payouts/confirm/confirm-payouts.ts
@@ -0,0 +1,171 @@
+import { createId } from "@/lib/api/create-id";
+import { PAYOUT_FEES } from "@/lib/partners/constants";
+import { stripe } from "@/lib/stripe";
+import { sendEmail } from "@dub/email";
+import PartnerPayoutConfirmed from "@dub/email/templates/partner-payout-confirmed";
+import { prisma } from "@dub/prisma";
+import { Program, Project } from "@prisma/client";
+import { waitUntil } from "@vercel/functions";
+
+const allowedPaymentMethods = ["us_bank_account", "card", "link"];
+
+export async function confirmPayouts({
+ workspace,
+ program,
+ userId,
+ paymentMethodId,
+ excludeCurrentMonth,
+}: {
+ workspace: Pick<Project, "id" | "stripeId" | "plan" | "invoicePrefix">;
+ program: Pick<Program, "id" | "name" | "logo" | "minPayoutAmount">;
+ userId: string;
+ paymentMethodId: string;
+ excludeCurrentMonth: boolean;
+}) {
+ const now = new Date();
+ const currentMonthStart = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1),
+ );
+
+ const paymentMethod = await stripe.paymentMethods.retrieve(paymentMethodId);
+
+ const payouts = await prisma.payout.findMany({
+ where: {
+ programId: program.id,
+ status: "pending",
+ invoiceId: null,
+ amount: {
+ gte: program.minPayoutAmount,
+ },
+ partner: {
+ payoutsEnabledAt: {
+ not: null,
+ },
+ },
+ ...(excludeCurrentMonth && {
+ OR: [
+ {
+ periodStart: null,
+ periodEnd: null,
+ },
+ {
+ periodEnd: {
+ lte: currentMonthStart,
+ },
+ },
+ ],
+ }),
+ },
+ select: {
+ id: true,
+ amount: true,
+ periodStart: true,
+ periodEnd: true,
+ partner: {
+ select: {
+ email: true,
+ },
+ },
+ },
+ });
+
+ if (!payouts.length) {
+ return;
+ }
+
+ // Create the invoice for the payouts
+ const newInvoice = await prisma.$transaction(async (tx) => {
+ const amount = payouts.reduce((total, payout) => total + payout.amount, 0);
+
+ const fee =
+ amount *
+ PAYOUT_FEES[workspace.plan?.split(" ")[0] ?? "business"][
+ paymentMethod.type === "us_bank_account" ? "ach" : "card"
+ ];
+
+ const total = amount + fee;
+
+ // Generate the next invoice number
+ const totalInvoices = await tx.invoice.count({
+ where: {
+ workspaceId: workspace.id,
+ },
+ });
+ const paddedNumber = String(totalInvoices + 1).padStart(4, "0");
+ const invoiceNumber = `${workspace.invoicePrefix}-${paddedNumber}`;
+
+ const invoice = await tx.invoice.create({
+ data: {
+ id: createId({ prefix: "inv_" }),
+ number: invoiceNumber,
+ programId: program.id,
+ workspaceId: workspace.id,
+ amount,
+ fee,
+ total,
+ },
+ });
+
+ if (!invoice) {
+ throw new Error("Failed to create payout invoice.");
+ }
+
+ await stripe.paymentIntents.create({
+ amount: invoice.total,
+ customer: workspace.stripeId!,
+ payment_method_types: allowedPaymentMethods,
+ payment_method: paymentMethod.id,
+ currency: "usd",
+ confirmation_method: "automatic",
+ confirm: true,
+ transfer_group: invoice.id,
+ statement_descriptor: "Dub Partners",
+ description: `Dub Partners payout invoice (${invoice.id})`,
+ });
+
+ await tx.payout.updateMany({
+ where: {
+ id: {
+ in: payouts.map((p) => p.id),
+ },
+ },
+ data: {
+ invoiceId: invoice.id,
+ status: "processing",
+ userId,
+ },
+ });
+
+ return invoice;
+ });
+
+ waitUntil(
+ (async () => {
+ // Send emails to all the partners involved in the payouts if the payout method is ACH
+ // ACH takes 4 business days to process
+ if (newInvoice && paymentMethod.type === "us_bank_account") {
+ await Promise.all(
+ payouts
+ .filter((payout) => payout.partner.email)
+ .map((payout) =>
+ sendEmail({
+ subject: "You've got money coming your way!",
+ email: payout.partner.email!,
+ react: PartnerPayoutConfirmed({
+ email: payout.partner.email!,
+ program,
+ payout: {
+ id: payout.id,
+ amount: payout.amount,
+ startDate: payout.periodStart,
+ endDate: payout.periodEnd,
+ },
+ }),
+ variant: "notifications",
+ }),
+ ),
+ );
+ }
+ })(),
+ );
+}
diff --git a/apps/web/app/(ee)/api/cron/payouts/confirm/route.ts b/apps/web/app/(ee)/api/cron/payouts/confirm/route.ts
new file mode 100644
index 0000000000..ebd788d64f
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/payouts/confirm/route.ts
@@ -0,0 +1,65 @@
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { prisma } from "@dub/prisma";
+import { log } from "@dub/utils";
+import z from "zod";
+import { confirmPayouts } from "./confirm-payouts";
+import { splitPayouts } from "./split-payouts";
+
+export const dynamic = "force-dynamic";
+
+const confirmPayoutsSchema = z.object({
+ workspaceId: z.string(),
+ userId: z.string(),
+ paymentMethodId: z.string(),
+ excludeCurrentMonth: z.boolean().optional().default(false),
+});
+
+// POST /api/cron/payouts/confirm
+// This route is used to confirm payouts for a given invoice
+export async function POST(req: Request) {
+ try {
+ const rawBody = await req.text();
+
+ await verifyQstashSignature({ req, rawBody });
+
+ const { workspaceId, userId, paymentMethodId, excludeCurrentMonth } =
+ confirmPayoutsSchema.parse(JSON.parse(rawBody));
+
+ const workspace = await prisma.project.findUniqueOrThrow({
+ where: {
+ id: workspaceId,
+ },
+ });
+
+ const program = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: getDefaultProgramIdOrThrow(workspace),
+ },
+ });
+
+ if (excludeCurrentMonth) {
+ await splitPayouts({
+ program,
+ });
+ }
+
+ await confirmPayouts({
+ workspace,
+ program,
+ userId,
+ paymentMethodId,
+ excludeCurrentMonth,
+ });
+
+ return new Response(`Payouts confirmed for program ${program.name}.`);
+ } catch (error) {
+ await log({
+ message: `Error confirming payouts for program: ${error.message}`,
+ type: "cron",
+ });
+
+ return handleAndReturnErrorResponse(error);
+ }
+}
diff --git a/apps/web/app/(ee)/api/cron/payouts/confirm/split-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/confirm/split-payouts.ts
new file mode 100644
index 0000000000..f7475c9766
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/payouts/confirm/split-payouts.ts
@@ -0,0 +1,119 @@
+import { createId } from "@/lib/api/create-id";
+import { prisma } from "@dub/prisma";
+import { Program } from "@prisma/client";
+
+// If the user wants to exclude the current month, we need to split the payouts
+// 1 - one for everything up until the end of the previous month
+// 2 - everything else in the current month will be left as pending (and excluded from the payout)
+export async function splitPayouts({
+ program,
+}: {
+ program: Pick<Program, "id" | "minPayoutAmount">;
+}) {
+ const payouts = await prisma.payout.findMany({
+ where: {
+ programId: program.id,
+ status: "pending",
+ invoiceId: null,
+ amount: {
+ gte: program.minPayoutAmount,
+ },
+ partner: {
+ payoutsEnabledAt: {
+ not: null,
+ },
+ },
+ periodStart: {
+ not: null, // exclude the manual payouts
+ },
+ },
+ include: {
+ commissions: true,
+ },
+ });
+
+ if (payouts.length === 0) {
+ return;
+ }
+
+ const now = new Date();
+ const currentMonthStart = new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1),
+ );
+
+ for (const payout of payouts) {
+ const previousCommissions = payout.commissions
+ .filter((commission) => {
+ return commission.createdAt < currentMonthStart;
+ })
+ .sort((a, b) => {
+ return a.createdAt.getTime() - b.createdAt.getTime();
+ });
+
+ const currentCommissions = payout.commissions
+ .filter((commission) => {
+ return commission.createdAt >= currentMonthStart;
+ })
+ .sort((a, b) => {
+ return a.createdAt.getTime() - b.createdAt.getTime();
+ });
+
+ const previousCommissionsCount = previousCommissions.length;
+ const currentCommissionsCount = currentCommissions.length;
+
+ if (previousCommissionsCount > 0) {
+ const periodEnd =
+ previousCommissions[previousCommissionsCount - 1].createdAt;
+
+ await prisma.payout.update({
+ where: {
+ id: payout.id,
+ },
+ data: {
+ periodEnd: new Date(
+ periodEnd.getFullYear(),
+ periodEnd.getMonth() + 1,
+ ),
+ amount: previousCommissions.reduce(
+ (total, commission) => total + commission.earnings,
+ 0,
+ ),
+ },
+ });
+ }
+
+ if (previousCommissionsCount > 0 && currentCommissionsCount > 0) {
+ const periodEnd =
+ currentCommissions[currentCommissions.length - 1].createdAt;
+
+ const currentMonthPayout = await prisma.payout.create({
+ data: {
+ id: createId({ prefix: "po_" }),
+ programId: program.id,
+ partnerId: payout.partnerId,
+ periodStart: currentCommissions[0].createdAt,
+ periodEnd: new Date(
+ periodEnd.getFullYear(),
+ periodEnd.getMonth() + 1,
+ ),
+ amount: currentCommissions.reduce(
+ (total, commission) => total + commission.earnings,
+ 0,
+ ),
+ description: "Dub Partners payout",
+ },
+ });
+
+ await prisma.commission.updateMany({
+ where: {
+ id: {
+ in: currentCommissions.map((commission) => commission.id),
+ },
+ },
+ data: {
+ payoutId: currentMonthPayout.id,
+ },
+ });
+ }
+ }
+}
diff --git a/apps/web/lib/actions/partners/confirm-payouts.ts b/apps/web/lib/actions/partners/confirm-payouts.ts
index fd5d467bf2..27eac10462 100644
--- a/apps/web/lib/actions/partners/confirm-payouts.ts
+++ b/apps/web/lib/actions/partners/confirm-payouts.ts
@@ -1,14 +1,9 @@
"use server";
-import { createId } from "@/lib/api/create-id";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
-import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
-import { PAYOUT_FEES } from "@/lib/partners/constants";
+import { qstash } from "@/lib/cron";
import { stripe } from "@/lib/stripe";
-import { sendEmail } from "@dub/email";
-import PartnerPayoutConfirmed from "@dub/email/templates/partner-payout-confirmed";
-import { prisma } from "@dub/prisma";
-import { waitUntil } from "@vercel/functions";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import z from "zod";
import { authActionClient } from "../safe-action";
@@ -20,9 +15,6 @@ const confirmPayoutsSchema = z.object({
const allowedPaymentMethods = ["us_bank_account", "card", "link"];
-// TODO:
-// Move this to a background job
-
// Confirm payouts
export const confirmPayoutsAction = authActionClient
.schema(confirmPayoutsSchema)
@@ -30,18 +22,12 @@ export const confirmPayoutsAction = authActionClient
const { workspace, user } = ctx;
const { paymentMethodId, excludeCurrentMonth } = parsedInput;
- const programId = getDefaultProgramIdOrThrow(workspace);
-
- const { minPayoutAmount } = await getProgramOrThrow({
- workspaceId: workspace.id,
- programId,
- });
+ getDefaultProgramIdOrThrow(workspace);
if (!workspace.stripeId) {
throw new Error("Workspace does not have a valid Stripe ID.");
}
- // Check the payout method is valid
const paymentMethod = await stripe.paymentMethods.retrieve(paymentMethodId);
if (paymentMethod.customer !== workspace.stripeId) {
@@ -54,284 +40,19 @@ export const confirmPayoutsAction = authActionClient
);
}
- // If the user wants to exclude the current month, we need to split the payouts
- // 1 - one for everything up until the end of the previous month
- // 2 - everything else in the current month will be left as pending (and excluded from the payout)
- if (excludeCurrentMonth) {
- await splitPayouts({
- programId,
- minPayoutAmount,
- });
- }
-
- const now = new Date();
- const currentMonthStart = new Date(
- Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1),
- );
-
- const payouts = await prisma.payout.findMany({
- where: {
- programId,
- status: "pending",
- invoiceId: null,
- amount: {
- gte: minPayoutAmount,
- },
- partner: {
- payoutsEnabledAt: {
- not: null,
- },
- },
- ...(excludeCurrentMonth && {
- OR: [
- {
- periodStart: null,
- periodEnd: null,
- },
- {
- periodEnd: {
- lte: currentMonthStart,
- },
- },
- ],
- }),
- },
- select: {
- id: true,
- amount: true,
- periodStart: true,
- periodEnd: true,
- partner: {
- select: {
- email: true,
- },
- },
- program: {
- select: {
- id: true,
- name: true,
- logo: true,
- },
- },
+ const qstashResponse = await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/confirm`,
+ body: {
+ workspaceId: workspace.id,
+ userId: user.id,
+ paymentMethodId,
+ excludeCurrentMonth,
},
});
- if (!payouts.length) {
- throw new Error("No pending payouts found.");
+ if (qstashResponse.messageId) {
+ console.log(`Message sent to Qstash with id ${qstashResponse.messageId}`);
+ } else {
+ console.error("Error sending message to Qstash", qstashResponse);
}
-
- // Create the invoice for the payouts
- const newInvoice = await prisma.$transaction(async (tx) => {
- const amount = payouts.reduce(
- (total, payout) => total + payout.amount,
- 0,
- );
-
- const fee =
- amount *
- PAYOUT_FEES[workspace.plan?.split(" ")[0] ?? "business"][
- paymentMethod.type === "us_bank_account" ? "ach" : "card"
- ];
-
- const total = amount + fee;
-
- // Generate the next invoice number
- const totalInvoices = await tx.invoice.count({
- where: {
- workspaceId: workspace.id,
- },
- });
- const paddedNumber = String(totalInvoices + 1).padStart(4, "0");
- const invoiceNumber = `${workspace.invoicePrefix}-${paddedNumber}`;
-
- const invoice = await tx.invoice.create({
- data: {
- id: createId({ prefix: "inv_" }),
- number: invoiceNumber,
- programId,
- workspaceId: workspace.id,
- amount,
- fee,
- total,
- },
- });
-
- if (!invoice) {
- throw new Error("Failed to create payout invoice.");
- }
-
- // await stripe.paymentIntents.create({
- // amount: invoice.total,
- // customer: workspace.stripeId!,
- // payment_method_types: allowedPaymentMethods,
- // payment_method: paymentMethod.id,
- // currency: "usd",
- // confirmation_method: "automatic",
- // confirm: true,
- // transfer_group: invoice.id,
- // statement_descriptor: "Dub Partners",
- // description: `Dub Partners payout invoice (${invoice.id})`,
- // });
-
- await tx.payout.updateMany({
- where: {
- id: {
- in: payouts.map((p) => p.id),
- },
- },
- data: {
- invoiceId: invoice.id,
- status: "processing",
- userId: user.id,
- },
- });
-
- return invoice;
- });
-
- waitUntil(
- (async () => {
- // Send emails to all the partners involved in the payouts if the payout method is ACH
- // ACH takes 4 business days to process
- if (newInvoice && paymentMethod.type === "us_bank_account") {
- await Promise.all(
- payouts
- .filter((payout) => payout.partner.email)
- .map((payout) =>
- sendEmail({
- subject: "You've got money coming your way!",
- email: payout.partner.email!,
- react: PartnerPayoutConfirmed({
- email: payout.partner.email!,
- program: payout.program,
- payout: {
- id: payout.id,
- amount: payout.amount,
- startDate: payout.periodStart,
- endDate: payout.periodEnd,
- },
- }),
- variant: "notifications",
- }),
- ),
- );
- }
- })(),
- );
});
-
-const splitPayouts = async ({
- programId,
- minPayoutAmount,
-}: {
- programId: string;
- minPayoutAmount: number;
-}) => {
- const payouts = await prisma.payout.findMany({
- where: {
- programId,
- status: "pending",
- invoiceId: null,
- amount: {
- gte: minPayoutAmount,
- },
- partner: {
- payoutsEnabledAt: {
- not: null,
- },
- },
- // exclude the manual payouts
- periodStart: {
- not: null,
- },
- },
- include: {
- commissions: true,
- },
- });
-
- if (payouts.length === 0) {
- return;
- }
-
- const now = new Date();
- const currentMonthStart = new Date(
- Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1),
- );
-
- for (const payout of payouts) {
- const previousCommissions = payout.commissions
- .filter((commission) => {
- return commission.createdAt < currentMonthStart;
- })
- .sort((a, b) => {
- return a.createdAt.getTime() - b.createdAt.getTime();
- });
-
- const currentCommissions = payout.commissions
- .filter((commission) => {
- return commission.createdAt >= currentMonthStart;
- })
- .sort((a, b) => {
- return a.createdAt.getTime() - b.createdAt.getTime();
- });
-
- const previousCommissionsCount = previousCommissions.length;
- const currentCommissionsCount = currentCommissions.length;
-
- if (previousCommissionsCount > 0) {
- const periodEnd =
- previousCommissions[previousCommissionsCount - 1].createdAt;
-
- await prisma.payout.update({
- where: {
- id: payout.id,
- },
- data: {
- periodEnd: new Date(
- periodEnd.getFullYear(),
- periodEnd.getMonth() + 1,
- ),
- amount: previousCommissions.reduce(
- (total, commission) => total + commission.earnings,
- 0,
- ),
- },
- });
- }
-
- if (previousCommissionsCount > 0 && currentCommissionsCount > 0) {
- const periodEnd =
- currentCommissions[currentCommissions.length - 1].createdAt;
-
- const currentMonthPayout = await prisma.payout.create({
- data: {
- id: createId({ prefix: "po_" }),
- programId,
- partnerId: payout.partnerId,
- periodStart: currentCommissions[0].createdAt,
- periodEnd: new Date(
- periodEnd.getFullYear(),
- periodEnd.getMonth() + 1,
- ),
- amount: currentCommissions.reduce(
- (total, commission) => total + commission.earnings,
- 0,
- ),
- description: "Dub Partners payout",
- },
- });
-
- await prisma.commission.updateMany({
- where: {
- id: {
- in: currentCommissions.map((commission) => commission.id),
- },
- },
- data: {
- payoutId: currentMonthPayout.id,
- },
- });
- }
- }
-};