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.

wip process payout

Kiran Kf3c3bda55018
diff --git a/apps/web/app/api/cron/invoices/route.ts b/apps/web/app/api/cron/invoices/route.ts
new file mode 100644
index 0000000000..f53dc0dd9c
--- /dev/null
+++ b/apps/web/app/api/cron/invoices/route.ts
@@ -0,0 +1,26 @@
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { NextResponse } from "next/server";
+import { z } from "zod";
+import { processInvoice } from "./utils";
+
+export const dynamic = "force-dynamic";
+
+const schema = z.object({
+ invoiceId: z.string(),
+});
+
+export async function POST(req: Request) {
+ try {
+ const body = await req.json();
+ await verifyQstashSignature(req, body);
+
+ const { invoiceId } = schema.parse(body);
+
+ await processInvoice({ invoiceId });
+
+ return NextResponse.json({ message: `Invoice ${invoiceId} processed.` });
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
+}
diff --git a/apps/web/app/api/cron/invoices/utils.ts b/apps/web/app/api/cron/invoices/utils.ts
new file mode 100644
index 0000000000..c819ecf58d
--- /dev/null
+++ b/apps/web/app/api/cron/invoices/utils.ts
@@ -0,0 +1,40 @@
+import { stripe } from "@/lib/stripe";
+import { prisma } from "@dub/prisma";
+
+export const processInvoice = async ({ invoiceId }: { invoiceId: string }) => {
+ const invoice = await prisma.invoice.findUnique({
+ where: {
+ id: invoiceId,
+ },
+ });
+
+ if (!invoice) {
+ throw new Error(`Invoice ${invoiceId} not found.`);
+ }
+
+ const payouts = await prisma.payout.findMany({
+ where: {
+ invoiceId,
+ status: "pending",
+ },
+ });
+
+ if (payouts.length === 0) {
+ throw new Error(`No payouts found for invoice ${invoiceId}.`);
+ }
+
+ const result = await stripe.paymentIntents.create({
+ amount: payout.amount,
+ currency: payout.currency,
+ description: "Payout for affiliate from Dub Partners",
+ customer: partner.stripeCustomerId, // Partner's Stripe Customer ID
+ payment_method: "pm_1QV6ZKFacAXKeDpJQJa2tLc8", // Partner's Stripe Payment Method ID
+ confirm: true,
+ confirmation_method: "automatic",
+ transfer_data: {
+ destination: affiliate.connectedAccountId, // To where the payout is sent
+ },
+ application_fee_amount: 100, // 1% fee from Dub
+ });
+
+};
diff --git a/apps/web/lib/actions/partners/confirm-payouts.ts b/apps/web/lib/actions/partners/confirm-payouts.ts
index 603fdae4e2..c954e89aad 100644
--- a/apps/web/lib/actions/partners/confirm-payouts.ts
+++ b/apps/web/lib/actions/partners/confirm-payouts.ts
@@ -1,13 +1,21 @@
"use server";
import { getProgramOrThrow } from "@/lib/api/programs/get-program";
-import z from "../../zod";
+import { createId } from "@/lib/api/utils";
+import { qstash } from "@/lib/cron";
+import { prisma } from "@dub/prisma";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
+import z from "zod";
import { authActionClient } from "../safe-action";
+// TODO:
+// Fix `paymentMethodId`
+// Fix `fee`
+
const confirmPayoutsSchema = z.object({
workspaceId: z.string(),
programId: z.string(),
- // payoutIds: z.array(z.string()),
});
// Confirm payouts
@@ -17,15 +25,78 @@ export const confirmPayoutsAction = authActionClient
const { workspace } = ctx;
const { programId } = parsedInput;
- const program = await getProgramOrThrow({
+ await getProgramOrThrow({
workspaceId: workspace.id,
programId,
});
- // TODO:
- // Find the pending payouts for the program
- // Create a new invoice
- // Update the payouts with the invoice id
- // Start a Qstash workflow
- // Return the invoice id
+ const result = await prisma.$transaction(async (tx) => {
+ // Find the pending payouts for the program
+ const payouts = await tx.payout.findMany({
+ where: {
+ programId,
+ status: "pending",
+ invoiceId: null, // just to be extra safe
+ },
+ select: {
+ id: true,
+ amount: true,
+ },
+ });
+
+ if (!payouts.length) {
+ throw new Error("No pending payouts found.");
+ }
+
+ // Create the invoice for the payouts
+ const amount = payouts.reduce(
+ (total, payout) => total + payout.amount,
+ 0,
+ );
+ const fee = amount * 0.02;
+ const total = amount + fee;
+
+ const invoice = await tx.invoice.create({
+ data: {
+ id: createId({ prefix: "inv_" }),
+ programId,
+ paymentMethodId: "xxx",
+ amount,
+ fee,
+ total,
+ },
+ });
+
+ if (!invoice) {
+ throw new Error("Failed to create payout invoice.");
+ }
+
+ // Update the payouts with the invoice id
+ await tx.payout.updateMany({
+ where: {
+ id: {
+ in: payouts.map((p) => p.id),
+ },
+ },
+ data: {
+ invoiceId: invoice.id,
+ },
+ });
+
+ return invoice;
+ });
+
+ // Process the payouts in the background
+ waitUntil(
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/process-payouts`,
+ body: {
+ invoiceId: result.id,
+ },
+ }),
+ );
+
+ return {
+ invoice: result,
+ };
});
diff --git a/apps/web/lib/api/utils.ts b/apps/web/lib/api/utils.ts
index 2835b73525..d1d0ead74d 100644
--- a/apps/web/lib/api/utils.ts
+++ b/apps/web/lib/api/utils.ts
@@ -69,6 +69,7 @@ const prefixes = [
"sale_",
"pga_",
"dub_embed_",
+ "inv_",
] as const;
export const createId = ({
diff --git a/apps/web/lib/partners/create-sales-payout.ts b/apps/web/lib/partners/create-sales-payout.ts
index 9ae8ded1f4..d6a293cec5 100644
--- a/apps/web/lib/partners/create-sales-payout.ts
+++ b/apps/web/lib/partners/create-sales-payout.ts
@@ -41,13 +41,7 @@ export const createSalesPayout = async ({
return;
}
- const earningsTotal = sales.reduce(
- (total, sale) => total + sale.earnings,
- 0,
- );
-
- const amount = earningsTotal;
- const fee = amount * 0.02;
+ const amount = sales.reduce((total, sale) => total + sale.earnings, 0);
// Create the payout
const payout = await tx.payout.create({
@@ -56,8 +50,6 @@ export const createSalesPayout = async ({
programId,
partnerId,
amount,
- fee,
- total: amount + fee,
periodStart,
periodEnd,
quantity: sales.length,
diff --git a/apps/web/ui/partners/payout-invoice-sheet.tsx b/apps/web/ui/partners/payout-invoice-sheet.tsx
index 59c1ed5681..2b780867c9 100644
--- a/apps/web/ui/partners/payout-invoice-sheet.tsx
+++ b/apps/web/ui/partners/payout-invoice-sheet.tsx
@@ -1,3 +1,4 @@
+import { confirmPayoutsAction } from "@/lib/actions/partners/confirm-payouts";
import usePayouts from "@/lib/swr/use-payouts";
import useWorkspace from "@/lib/swr/use-workspace";
import { X } from "@/ui/shared/icons";
@@ -10,9 +11,11 @@ import {
useTable,
} from "@dub/ui";
import { cn, currencyFormatter, DICEBEAR_AVATAR_URL } from "@dub/utils";
+import { useAction } from "next-safe-action/hooks";
import Link from "next/link";
import { useParams } from "next/navigation";
import { Dispatch, Fragment, SetStateAction, useMemo, useState } from "react";
+import { toast } from "sonner";
import { SaleRowMenu } from "./sale-row-menu";
interface PayoutInvoiceSheetProps {
@@ -21,6 +24,8 @@ interface PayoutInvoiceSheetProps {
// TODO:
// Handle case when there are 2 payouts for the same partner
+// Fix the fee calculation
+// Fix the table menus + View all
function PayoutInvoiceSheetContent({ setIsOpen }: PayoutInvoiceSheetProps) {
const { id: workspaceId, slug } = useWorkspace();
@@ -36,10 +41,20 @@ function PayoutInvoiceSheetContent({ setIsOpen }: PayoutInvoiceSheetProps) {
},
});
+ const { executeAsync, isExecuting } = useAction(confirmPayoutsAction, {
+ onSuccess: async () => {
+ toast.success("Payouts confirmed successfully! We'll process them soon.");
+ setIsOpen(false);
+ },
+ onError({ error }) {
+ toast.error(error.serverError);
+ },
+ });
+
const invoiceData = useMemo(() => {
const amount =
payouts?.reduce((acc, payout) => acc + payout.amount, 0) || 0;
- const fee = amount * 0.02; // TODO: Fix it
+ const fee = amount * 0.02;
const total = amount + fee;
return {
@@ -173,12 +188,16 @@ function PayoutInvoiceSheetContent({ setIsOpen }: PayoutInvoiceSheetProps) {
<Button
type="button"
variant="primary"
- // loading={isExecuting}
+ loading={isExecuting}
onClick={async () => {
- // await executeAsync({
- // workspaceId: workspaceId!,
- // payoutId: payout.id,
- // });
+ if (!workspaceId || !programId) {
+ return;
+ }
+
+ await executeAsync({
+ workspaceId,
+ programId,
+ });
}}
text="Confirm payout"
className="w-fit"
diff --git a/packages/prisma/schema/payout.prisma b/packages/prisma/schema/payout.prisma
index 03007d4a08..50227fbb78 100644
--- a/packages/prisma/schema/payout.prisma
+++ b/packages/prisma/schema/payout.prisma
@@ -24,7 +24,7 @@ model Payout {
periodStart DateTime?
periodEnd DateTime?
quantity Int? // Number of clicks/leads/sales in this payout
- dotsTransferId String? @unique // TODO: Remove this
+ dotsTransferId String? @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt