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.

Refactor payout email notifications and update payout model schema

Kiran K8c35d66f9f83
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.ts
index 9c8dd391d6..cef8ddce75 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
@@ -149,16 +149,17 @@ export async function sendStripePayouts({ payload }: { payload: Payload }) {
},
}),
- partner.email &&
- sendEmail({
- variant: "notifications",
- subject: "You've been paid!",
- email: partner.email,
- react: PartnerPayoutSent({
+ partner.email
+ ? sendEmail({
+ variant: "notifications",
+ subject: "You've been paid!",
email: partner.email,
- payoutAmount: totalAmount,
- }),
- }),
+ react: PartnerPayoutSent({
+ email: partner.email,
+ payoutAmount: totalAmount,
+ }),
+ })
+ : Promise.resolve(),
]);
// sleep for 250ms
diff --git a/apps/web/app/(ee)/api/stripe/connect/webhook/balance-available.ts b/apps/web/app/(ee)/api/stripe/connect/webhook/balance-available.ts
index b09052ecea..ed5e74cfed 100644
--- a/apps/web/app/(ee)/api/stripe/connect/webhook/balance-available.ts
+++ b/apps/web/app/(ee)/api/stripe/connect/webhook/balance-available.ts
@@ -1,14 +1,8 @@
-import { ZERO_DECIMAL_CURRENCIES } from "@/lib/analytics/convert-currency";
-import {
- BELOW_MIN_WITHDRAWAL_FEE_CENTS,
- MIN_WITHDRAWAL_AMOUNT_CENTS,
-} from "@/lib/partners/constants";
import { stripe } from "@/lib/stripe";
-import { redis } from "@/lib/upstash";
import { sendEmail } from "@dub/email";
import PartnerPayoutWithdrawalInitiated from "@dub/email/templates/partner-payout-withdrawal-initiated";
import { prisma } from "@dub/prisma";
-import { currencyFormatter, log } from "@dub/utils";
+import { currencyFormatter } from "@dub/utils";
import Stripe from "stripe";
export async function balanceAvailable(event: Stripe.Event) {
@@ -46,43 +40,8 @@ export async function balanceAvailable(event: Stripe.Event) {
}
const { amount, currency } = balance.available[0];
-
let availableBalance = amount;
- let convertedUsdAmount = amount;
-
- if (currency !== "usd") {
- const fxRates = await redis.hget("fxRates:usd", currency.toUpperCase());
-
- if (!fxRates) {
- console.error(
- `Failed to get exchange rate from Redis for ${currency}. Skipping...`,
- );
- return;
- }
-
- convertedUsdAmount = availableBalance / Number(fxRates);
-
- const isZeroDecimalCurrency = ZERO_DECIMAL_CURRENCIES.includes(
- currency.toUpperCase(),
- );
- if (isZeroDecimalCurrency) {
- convertedUsdAmount = convertedUsdAmount * 100;
- }
-
- // round to nearest integer to avoid errors with Stripe
- convertedUsdAmount = Math.round(convertedUsdAmount);
- }
-
- // Check minimum withdrawal amount
- if (convertedUsdAmount < partner.minWithdrawalAmount) {
- console.log(
- `The available balance (${currencyFormatter(convertedUsdAmount / 100, { maximumFractionDigits: 2 })}) for partner ${partner.email} (${stripeAccount}) is less than their minimum withdrawal amount (${currencyFormatter(partner.minWithdrawalAmount / 100, { maximumFractionDigits: 2 })})`,
- );
- return;
- }
-
- // Subtract the pending/in-transit payouts from the available balance
const { data: stripePayouts } = await stripe.payouts.list(
{
status: "pending",
@@ -92,6 +51,7 @@ export async function balanceAvailable(event: Stripe.Event) {
},
);
+ // Subtract the pending/in-transit payouts from the available balance
if (stripePayouts.length > 0) {
const pendingOrInTransitPayouts = stripePayouts.filter(
({ status }) => status === "pending" || status === "in_transit",
@@ -112,68 +72,6 @@ export async function balanceAvailable(event: Stripe.Event) {
return;
}
- let withdrawalFee = 0;
-
- const transfers = await stripe.transfers.list({
- destination: stripeAccount,
- limit: 100,
- });
-
- // 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;
-
- if (transfers.data.length === 0) {
- console.error(
- `No transfers found for partner ${partner.email} (${stripeAccount}). Skipping...`,
- );
- return;
- }
-
- // Find the latest transfer that's large enough to cover the withdrawal fee
- const suitableTransfer = transfers.data
- .filter((transfer) => transfer.amount >= withdrawalFee)
- .sort((a, b) => b.created - a.created)[0];
-
- // This should never happen, but just in case
- if (!suitableTransfer) {
- const errorMessage = `Error processing withdrawal for partner ${partner.email} (${stripeAccount}): No transfer found with amount >= withdrawal fee (${currencyFormatter(withdrawalFee / 100)}). Available transfers: ${transfers.data
- .map((t) => currencyFormatter(t.amount / 100))
- .join(", ")}. Skipping...`;
- console.error(errorMessage);
- await log({
- message: errorMessage,
- type: "errors",
- mention: true,
- });
- return;
- }
-
- // Charge the withdrawal fee to the partner's account
- await stripe.transfers.createReversal(suitableTransfer.id, {
- amount: withdrawalFee,
- description: "Dub Partners withdrawal fee",
- });
-
- // If the withdrawal fee was charged, we need to fetch the partner's updated balance
- const updatedBalance = await stripe.balance.retrieve({
- stripeAccount,
- });
-
- if (
- updatedBalance.available.length === 0 ||
- updatedBalance.available[0].amount === 0
- ) {
- // this should never happen, but just in case
- console.log(
- `No available balance found after withdrawal fee for partner ${partner.email} (${stripeAccount}). Skipping...`,
- );
- return;
- }
-
- availableBalance = updatedBalance.available[0].amount;
- }
-
if (["huf", "twd"].includes(currency)) {
// For HUF and TWD, Stripe requires payout amounts to be evenly divisible by 100
// We need to round down to the nearest 100 units
@@ -192,7 +90,15 @@ export async function balanceAvailable(event: Stripe.Event) {
},
);
- // Find the Dub payouts associated with this Stripe payout
+ console.log(
+ `Stripe payout created for partner ${partner.email} (${stripeAccount}): ${payout.id} (${currencyFormatter(payout.amount / 100, { maximumFractionDigits: 2, currency })})`,
+ );
+
+ const transfers = await stripe.transfers.list({
+ destination: stripeAccount,
+ limit: 100,
+ });
+
await prisma.payout.updateMany({
where: {
status: "sent",
@@ -206,18 +112,14 @@ export async function balanceAvailable(event: Stripe.Event) {
},
});
- console.log(
- `Stripe payout created for partner ${partner.email} (${stripeAccount}): ${payout.id} (${currencyFormatter(payout.amount / 100, { maximumFractionDigits: 2, currency })})`,
- );
-
if (partner.email) {
- await sendEmail({
+ sendEmail({
variant: "notifications",
subject: "Your funds are on their way to your bank",
email: partner.email,
react: PartnerPayoutWithdrawalInitiated({
email: partner.email,
- payoutAmount: availableBalance,
+ amount: payout.amount,
}),
});
}
diff --git a/packages/email/src/templates/partner-payout-withdrawal-initiated.tsx b/packages/email/src/templates/partner-payout-withdrawal-initiated.tsx
index 9ffe82afaf..4054518a0c 100644
--- a/packages/email/src/templates/partner-payout-withdrawal-initiated.tsx
+++ b/packages/email/src/templates/partner-payout-withdrawal-initiated.tsx
@@ -17,12 +17,12 @@ import { Footer } from "../components/footer";
// Send this email after initiating a Stripe payout to the partner
export default function PartnerPayoutWithdrawalInitiated({
email = "[email protected]",
- payoutAmount = 490,
+ amount = 45590,
}: {
email: string;
- payoutAmount: number;
+ amount: number;
}) {
- const payoutAmountFormatted = currencyFormatter(payoutAmount / 100, {
+ const amountInDollars = currencyFormatter(amount / 100, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
@@ -45,7 +45,7 @@ export default function PartnerPayoutWithdrawalInitiated({
<Text className="text-sm leading-6 text-neutral-600">
Good news!{" "}
<span className="font-semibold text-neutral-800">
- {payoutAmountFormatted}
+ {amountInDollars}
</span>{" "}
is being transferred to your bank account.
</Text>
diff --git a/packages/prisma/schema/payout.prisma b/packages/prisma/schema/payout.prisma
index fda335ddf0..1aa2b5bc99 100644
--- a/packages/prisma/schema/payout.prisma
+++ b/packages/prisma/schema/payout.prisma
@@ -21,7 +21,7 @@ model Payout {
periodStart DateTime?
periodEnd DateTime?
paypalTransferId String? @unique
- stripeTransferId String? @unique
+ stripeTransferId String?
stripePayoutId String?
failureReason String? @db.Text
createdAt DateTime @default(now())