The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add createStripeTransfer function
Steven Teybe4de0d9199d
diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-stripe-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-stripe-payouts.tsindex 42bde5457f..78070abf9f 100644--- a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-stripe-payouts.ts+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-stripe-payouts.ts@@ -1,13 +1,8 @@-import {- BELOW_MIN_WITHDRAWAL_FEE_CENTS,- MIN_WITHDRAWAL_AMOUNT_CENTS,-} from "@/lib/partners/constants";-import { stripe } from "@/lib/stripe";+import { createStripeTransfer } from "@/lib/partners/create-stripe-transfer";import { resend } from "@dub/email/resend";import { VARIANT_TO_FROM_MAP } from "@dub/email/resend/constants";import PartnerPayoutProcessed from "@dub/email/templates/partner-payout-processed";import { prisma } from "@dub/prisma";-import { currencyFormatter, pluralize } from "@dub/utils";import { Prisma } from "@prisma/client";export async function sendStripePayouts({ invoiceId }: { invoiceId: string }) {@@ -81,103 +76,17 @@ export async function sendStripePayouts({ invoiceId }: { invoiceId: string }) {// Process payouts for each partnerfor (const [_, partnerPayouts] of partnerPayoutsMap) {- let withdrawalFee = 0;- const partner = partnerPayouts[0].partner;-- const partnerPayoutsIds = partnerPayouts.map((p) => p.id);-- // this is usually just one payout, but we're doing this- // just in case there are multiple payouts for the same partner in the same invoice- const partnerPayoutsForCurrentInvoice = partnerPayouts.filter(- (p) => p.invoiceId === invoiceId,- );-- const totalTransferableAmount = partnerPayouts.reduce(- (acc, payout) => acc + payout.amount,- 0,- );-- // If the total transferable amount is less than the partner's minimum withdrawal amount- // we only update status for all the partner payouts for the current invoice to "processed" – no need to create a transfer for now- if (totalTransferableAmount < partner.minWithdrawalAmount) {- await prisma.payout.updateMany({- where: {- id: {- in: partnerPayoutsForCurrentInvoice.map((p) => p.id),- },- },- data: {- status: "processed",- },- });-- console.log(- `Total processed payouts (${currencyFormatter(totalTransferableAmount / 100)}) for partner ${partner.id} are below the minWithdrawalAmount (${currencyFormatter(partner.minWithdrawalAmount / 100)}), skipping...`,- );-- continue;- }-- // Decide if we need to charge a withdrawal fee for the partner- if (partner.minWithdrawalAmount < MIN_WITHDRAWAL_AMOUNT_CENTS) {- withdrawalFee = BELOW_MIN_WITHDRAWAL_FEE_CENTS;- }-- // Minus the withdrawal fee from the total amount- const finalTransferableAmount = totalTransferableAmount - withdrawalFee;-- if (finalTransferableAmount <= 0) {- continue;- }-- // Create a transfer for the partner combined payouts and update it as sent- const transfer = await stripe.transfers.create(- {- amount: finalTransferableAmount,- currency: "usd",- // here, `transfer_group` technically only used to associate the transfer with the invoice- // (even though the transfer could technically include payouts from multiple invoices)- transfer_group: invoiceId,- destination: partner.stripeConnectId!,- description: `Dub Partners payout for ${partnerPayoutsIds.join(", ")}`,- },- {- idempotencyKey: `${invoiceId}-${partner.id}`,- },- );-- console.log(- `Transfer of ${currencyFormatter(finalTransferableAmount / 100)} (${transfer.id}) created for partner ${partner.id} for ${pluralize(- "payout",- partnerPayouts.length,- )} ${partnerPayoutsIds.join(", ")}`,- );-- await Promise.allSettled([- prisma.payout.updateMany({- where: {- id: {- in: partnerPayoutsIds,- },- },- data: {- stripeTransferId: transfer.id,- status: "sent",- paidAt: new Date(),- },- }),-- prisma.commission.updateMany({- where: {- payoutId: {- in: partnerPayoutsIds,- },- },- data: {- status: "paid",- },- }),- ]);+ await createStripeTransfer({+ partner: partnerPayouts[0].partner,+ previouslyProcessedPayouts: partnerPayouts.filter(+ (p) => p.status === "processed",+ ),+ // this is usually just one payout, but we're doing this+ // just in case there are multiple payouts for the same partner in the same invoice+ currentInvoicePayouts: partnerPayouts.filter(+ (p) => p.invoiceId === invoiceId,+ ),+ });// sleep for 250msawait new Promise((resolve) => setTimeout(resolve, 250));diff --git a/apps/web/lib/actions/partners/mark-payout-paid.ts b/apps/web/lib/actions/partners/mark-payout-paid.tsdeleted file mode 100644index 407fb367d4..0000000000--- a/apps/web/lib/actions/partners/mark-payout-paid.ts+++ /dev/null@@ -1,66 +0,0 @@-"use server";--import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";-import { getPayoutOrThrow } from "@/lib/api/partners/get-payout-or-throw";-import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";-import { prisma } from "@dub/prisma";-import { waitUntil } from "@vercel/functions";-import { z } from "zod";-import { authActionClient } from "../safe-action";--const markPayoutPaidSchema = z.object({- workspaceId: z.string(),- payoutId: z.string(),-});--export const markPayoutPaidAction = authActionClient- .schema(markPayoutPaidSchema)- .action(async ({ parsedInput, ctx }) => {- const { workspace, user } = ctx;- const { payoutId } = parsedInput;-- const programId = getDefaultProgramIdOrThrow(workspace);-- const payout = await getPayoutOrThrow({- payoutId,- programId,- });-- await Promise.all([- prisma.payout.update({- where: {- id: payout.id,- },- data: {- status: "completed",- paidAt: new Date(),- },- }),-- prisma.commission.updateMany({- where: {- payoutId: payout.id,- },- data: {- status: "paid",- },- }),- ]);-- waitUntil(- recordAuditLog({- workspaceId: workspace.id,- programId,- action: "payout.marked_paid",- description: `Payout ${payout.id} marked as paid`,- actor: user,- targets: [- {- type: "payout",- id: payout.id,- metadata: payout,- },- ],- }),- );- });diff --git a/apps/web/lib/actions/partners/update-partner-withdrawal-amount.ts b/apps/web/lib/actions/partners/update-partner-withdrawal-amount.tsindex 1c8659f005..770b44d521 100644--- a/apps/web/lib/actions/partners/update-partner-withdrawal-amount.ts+++ b/apps/web/lib/actions/partners/update-partner-withdrawal-amount.ts@@ -1,6 +1,8 @@"use server";+import { createStripeTransfer } from "@/lib/partners/create-stripe-transfer";import { prisma } from "@dub/prisma";+import { waitUntil } from "@vercel/functions";import { z } from "zod";import { authPartnerActionClient } from "../safe-action";@@ -28,4 +30,25 @@ export const updatePartnerWithdrawalAmountAction = authPartnerActionClientminWithdrawalAmount: parseInt(minWithdrawalAmount),},});++ waitUntil(+ (async () => {+ if (partner.stripeConnectId && partner.payoutsEnabledAt) {+ const previouslyProcessedPayouts = await prisma.payout.findMany({+ where: {+ partnerId: partner.id,+ status: "processed",+ stripeTransferId: null,+ },+ });++ if (previouslyProcessedPayouts.length > 0) {+ await createStripeTransfer({+ partner,+ previouslyProcessedPayouts,+ });+ }+ }+ })(),+ );});diff --git a/apps/web/lib/partners/create-stripe-transfer.ts b/apps/web/lib/partners/create-stripe-transfer.tsnew file mode 100644index 0000000000..044e22a708--- /dev/null+++ b/apps/web/lib/partners/create-stripe-transfer.ts@@ -0,0 +1,122 @@+import { stripe } from "@/lib/stripe";+import { prisma } from "@dub/prisma";+import { Partner, Payout } from "@dub/prisma/client";+import { currencyFormatter, pluralize } from "@dub/utils";+import {+ BELOW_MIN_WITHDRAWAL_FEE_CENTS,+ MIN_WITHDRAWAL_AMOUNT_CENTS,+} from "./constants";++export const createStripeTransfer = async ({+ partner,+ previouslyProcessedPayouts,+ currentInvoicePayouts,+}: {+ partner: Pick<Partner, "id" | "minWithdrawalAmount" | "stripeConnectId">;+ previouslyProcessedPayouts: Pick<Payout, "id" | "amount" | "invoiceId">[];+ currentInvoicePayouts?: Pick<Payout, "id" | "amount" | "invoiceId">[];+}) => {+ let withdrawalFee = 0;++ const allPayouts = [+ ...previouslyProcessedPayouts,+ ...(currentInvoicePayouts ?? []),+ ];++ // will be used for transfer_group and idempotencyKey+ const finalPayoutInvoiceId = allPayouts[allPayouts.length - 1].invoiceId;++ // total transferable amount is the sum of all previously processed payouts (but not sent yet) and the current invoice payouts+ const totalTransferableAmount = allPayouts.reduce(+ (acc, payout) => acc + payout.amount,+ 0,+ );++ // If the total transferable amount is less than the partner's minimum withdrawal amount+ // we only update status for all the partner payouts for the current invoice (if any) to "processed" – no need to create a transfer for now+ if (totalTransferableAmount < partner.minWithdrawalAmount) {+ if (currentInvoicePayouts) {+ await prisma.payout.updateMany({+ where: {+ id: {+ in: currentInvoicePayouts.map((p) => p.id),+ },+ },+ data: {+ status: "processed",+ },+ });+ }++ console.log(+ `Total processed payouts (${currencyFormatter(totalTransferableAmount / 100)}) for partner ${partner.id} are below the minWithdrawalAmount (${currencyFormatter(partner.minWithdrawalAmount / 100)}), skipping...`,+ );++ return;+ }++ // Decide if we need to charge a withdrawal fee for the partner+ if (partner.minWithdrawalAmount < MIN_WITHDRAWAL_AMOUNT_CENTS) {+ withdrawalFee = BELOW_MIN_WITHDRAWAL_FEE_CENTS;+ }++ // Minus the withdrawal fee from the total amount+ const finalTransferableAmount = totalTransferableAmount - withdrawalFee;++ if (finalTransferableAmount <= 0) {+ console.log(+ `Final transferable amount after deducting withdrawal fee (${currencyFormatter(finalTransferableAmount / 100)}) is less than or equal to 0, skipping...`,+ );++ return;+ }++ // Create a transfer for the partner combined payouts and update it as sent+ const transfer = await stripe.transfers.create(+ {+ amount: finalTransferableAmount,+ currency: "usd",+ // here, `transfer_group` technically only used to associate the transfer with the invoice+ // (even though the transfer could technically include payouts from multiple invoices)+ transfer_group: finalPayoutInvoiceId!,+ destination: partner.stripeConnectId!,+ description: `Dub Partners payout for ${allPayouts.map((p) => p.id).join(", ")}`,+ },+ {+ idempotencyKey: `${finalPayoutInvoiceId}-${partner.id}`,+ },+ );++ console.log(+ `Transfer of ${currencyFormatter(finalTransferableAmount / 100)} (${transfer.id}) created for partner ${partner.id} for ${pluralize(+ "payout",+ allPayouts.length,+ )} ${allPayouts.map((p) => p.id).join(", ")}`,+ );++ await Promise.allSettled([+ prisma.payout.updateMany({+ where: {+ id: {+ in: allPayouts.map((p) => p.id),+ },+ },+ data: {+ stripeTransferId: transfer.id,+ status: "sent",+ paidAt: new Date(),+ },+ }),++ prisma.commission.updateMany({+ where: {+ payoutId: {+ in: allPayouts.map((p) => p.id),+ },+ },+ data: {+ status: "paid",+ },+ }),+ ]);+};diff --git a/apps/web/ui/partners/mark-payout-paid-modal.tsx b/apps/web/ui/partners/mark-payout-paid-modal.tsxdeleted file mode 100644index 960a9c14d3..0000000000--- a/apps/web/ui/partners/mark-payout-paid-modal.tsx+++ /dev/null@@ -1,113 +0,0 @@-import { markPayoutPaidAction } from "@/lib/actions/partners/mark-payout-paid";-import { mutatePrefix } from "@/lib/swr/mutate";-import useWorkspace from "@/lib/swr/use-workspace";-import { PayoutResponse } from "@/lib/types";-import { Button, Modal } from "@dub/ui";-import { useAction } from "next-safe-action/hooks";-import { useCallback, useMemo, useState } from "react";-import { toast } from "sonner";--interface MarkPayoutPaidModalProps {- showMarkPayoutPaidModal: boolean;- setShowMarkPayoutPaidModal: (show: boolean) => void;- payout: PayoutResponse;-}--function MarkPayoutPaidModal({- showMarkPayoutPaidModal,- setShowMarkPayoutPaidModal,- payout,-}: MarkPayoutPaidModalProps) {- return (- <Modal- showModal={showMarkPayoutPaidModal}- setShowModal={setShowMarkPayoutPaidModal}- >- <MarkPayoutPaidModalInner- setShowMarkPayoutPaidModal={setShowMarkPayoutPaidModal}- payout={payout}- />- </Modal>- );-}--function MarkPayoutPaidModalInner({- setShowMarkPayoutPaidModal,- payout,-}: Omit<MarkPayoutPaidModalProps, "showMarkPayoutPaidModal">) {- const { id: workspaceId, defaultProgramId } = useWorkspace();-- const { execute, isExecuting, hasSucceeded } = useAction(- markPayoutPaidAction,- {- onSuccess: () => {- toast.success("Payout updated successfully!");- setShowMarkPayoutPaidModal(false);- mutatePrefix(`/api/programs/${defaultProgramId}/payouts`);- },- onError: () => {- toast.error("Failed to update payout");- },- },- );-- return (- <>- <div className="space-y-2 border-b border-neutral-200 p-4 sm:p-6">- <h3 className="text-lg font-medium leading-none">- Mark payout as paid- </h3>- </div>-- <div className="bg-neutral-50 p-4 sm:p-6">- <p className="text-sm text-neutral-800">- Are you sure you want to manually mark this payout as paid? This- action cannot be undone.- </p>- </div>-- <div className="flex items-center justify-end gap-2 border-t border-neutral-200 bg-neutral-50 px-4 py-5 sm:px-6">- <Button- onClick={() => setShowMarkPayoutPaidModal(false)}- variant="secondary"- text="Cancel"- className="h-8 w-fit px-3"- />- <Button- onClick={() =>- execute({- workspaceId: workspaceId!,- payoutId: payout.id,- })- }- autoFocus- loading={isExecuting || hasSucceeded}- text="Mark payout as paid"- className="h-8 w-fit px-3"- />- </div>- </>- );-}--export function useMarkPayoutPaidModal(props: { payout: PayoutResponse }) {- const [showMarkPayoutPaidModal, setShowMarkPayoutPaidModal] = useState(false);-- const MarkPayoutPaidModalCallback = useCallback(() => {- return (- <MarkPayoutPaidModal- showMarkPayoutPaidModal={showMarkPayoutPaidModal}- setShowMarkPayoutPaidModal={setShowMarkPayoutPaidModal}- payout={props.payout}- />- );- }, [showMarkPayoutPaidModal, setShowMarkPayoutPaidModal, props.payout]);-- return useMemo(- () => ({- setShowMarkPayoutPaidModal,- MarkPayoutPaidModal: MarkPayoutPaidModalCallback,- }),- [setShowMarkPayoutPaidModal, MarkPayoutPaidModalCallback],- );-}