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 workspace.payoutMethodId, use transfer_group to identify invoice

Steven Tey9eaff1bfb0c4
diff --git a/apps/web/app/api/stripe/webhook/charge-succeeded.ts b/apps/web/app/api/stripe/webhook/charge-succeeded.ts
index c093003b6f..8795d72064 100644
--- a/apps/web/app/api/stripe/webhook/charge-succeeded.ts
+++ b/apps/web/app/api/stripe/webhook/charge-succeeded.ts
@@ -5,17 +5,21 @@ import Stripe from "stripe";
export async function chargeSucceeded(event: Stripe.Event) {
const charge = event.data.object as Stripe.Charge;
- const { id: chargeId, payment_intent: paymentIntentId } = charge;
+ const { id: chargeId, transfer_group } = charge;
- if (typeof paymentIntentId !== "string") {
- throw new Error("Invalid payment intent ID.");
+ if (!transfer_group) {
+ console.log("No transfer group found, skipping...");
+ return;
}
- console.log({ chargeId, paymentIntentId });
+ console.log({ chargeId, transfer_group });
- const invoice = await prisma.invoice.findUnique({
+ const invoice = await prisma.invoice.update({
where: {
- paymentIntentId,
+ id: transfer_group,
+ },
+ data: {
+ status: "completed",
},
include: {
payouts: {
@@ -27,9 +31,8 @@ export async function chargeSucceeded(event: Stripe.Event) {
});
if (!invoice) {
- throw new Error(
- `Invoice with payment intent ${paymentIntentId} not found.`,
- );
+ console.log(`Invoice with transfer group ${transfer_group} not found.`);
+ return;
}
console.log("Invoice found", invoice);
@@ -39,7 +42,6 @@ export async function chargeSucceeded(event: Stripe.Event) {
amount: payout.amount,
currency: "usd",
destination: payout.partner.stripeConnectId!,
- source_transaction: chargeId,
transfer_group: invoice.id,
description: "Dub Partners Payout",
});
diff --git a/apps/web/lib/actions/partners/confirm-payouts.ts b/apps/web/lib/actions/partners/confirm-payouts.ts
index 34e0480277..5db3cab829 100644
--- a/apps/web/lib/actions/partners/confirm-payouts.ts
+++ b/apps/web/lib/actions/partners/confirm-payouts.ts
@@ -5,7 +5,6 @@ import { createId } from "@/lib/api/utils";
import { MIN_PAYOUT_AMOUNT } from "@/lib/partners/constants";
import { stripe } from "@/lib/stripe";
import { prisma } from "@dub/prisma";
-import Stripe from "stripe";
import z from "zod";
import { authActionClient } from "../safe-action";
@@ -15,7 +14,6 @@ import { authActionClient } from "../safe-action";
const confirmPayoutsSchema = z.object({
workspaceId: z.string(),
programId: z.string(),
- paymentMethodId: z.string().min(1, "Please select a payment method."),
});
// Confirm payouts
@@ -23,7 +21,7 @@ export const confirmPayoutsAction = authActionClient
.schema(confirmPayoutsSchema)
.action(async ({ parsedInput, ctx }) => {
const { workspace } = ctx;
- const { programId, paymentMethodId } = parsedInput;
+ const { programId } = parsedInput;
await getProgramOrThrow({
workspaceId: workspace.id,
@@ -34,16 +32,8 @@ export const confirmPayoutsAction = authActionClient
throw new Error("Workspace does not have a valid Stripe ID.");
}
- // Doing some check to make sure the payment method is valid
- const paymentMethod = await stripe.paymentMethods.retrieve(
- paymentMethodId,
- { expand: ["customer"] },
- );
-
- const stripeCustomer = paymentMethod.customer as Stripe.Customer;
-
- if (stripeCustomer.id !== workspace.stripeId) {
- throw new Error("The payment method is not valid for this workspace.");
+ if (!workspace.payoutMethodId) {
+ throw new Error("Workspace does not have a valid payout method.");
}
const payouts = await prisma.payout.findMany({
@@ -80,7 +70,7 @@ export const confirmPayoutsAction = authActionClient
data: {
id: createId({ prefix: "inv_" }),
programId,
- paymentMethodId,
+ paymentMethodId: workspace.payoutMethodId,
amount,
fee,
total,
@@ -94,8 +84,8 @@ export const confirmPayoutsAction = authActionClient
const { id: paymentIntentId } = await stripe.paymentIntents.create({
amount: invoice.total,
customer: workspace.stripeId,
+ payment_method_types: ["us_bank_account"],
payment_method: invoice.paymentMethodId,
- payment_method_types: ["card", "us_bank_account"],
currency: "usd",
confirmation_method: "automatic",
confirm: true,
@@ -104,8 +94,6 @@ export const confirmPayoutsAction = authActionClient
description: "Dub Partners payout invoice",
});
- console.log("Payment intent created", paymentIntentId);
-
await Promise.all([
prisma.payout.updateMany({
where: {
diff --git a/apps/web/ui/partners/payout-invoice-sheet.tsx b/apps/web/ui/partners/payout-invoice-sheet.tsx
index f27e0840bb..677e7ae253 100644
--- a/apps/web/ui/partners/payout-invoice-sheet.tsx
+++ b/apps/web/ui/partners/payout-invoice-sheet.tsx
@@ -1,31 +1,13 @@
import { confirmPayoutsAction } from "@/lib/actions/partners/confirm-payouts";
import { MIN_PAYOUT_AMOUNT } from "@/lib/partners/constants";
-import usePaymentMethods from "@/lib/swr/use-payment-methods";
import usePayouts from "@/lib/swr/use-payouts";
import useWorkspace from "@/lib/swr/use-workspace";
import { X } from "@/ui/shared/icons";
-import {
- Button,
- buttonVariants,
- Gear,
- Sheet,
- Table,
- Tooltip,
- useRouterStuff,
- useTable,
-} from "@dub/ui";
+import { Button, Sheet, Table, useRouterStuff, 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,
- useEffect,
- useMemo,
- useState,
-} from "react";
+import { Dispatch, Fragment, SetStateAction, useMemo, useState } from "react";
import { toast } from "sonner";
interface PayoutInvoiceSheetProps {
@@ -39,7 +21,6 @@ interface PayoutInvoiceSheetProps {
function PayoutInvoiceSheetContent({ setIsOpen }: PayoutInvoiceSheetProps) {
const { id: workspaceId, slug } = useWorkspace();
const { programId } = useParams<{ programId: string }>();
- const [paymentMethodId, setPaymentMethodId] = useState<string | null>(null);
const {
payouts,
@@ -51,20 +32,11 @@ function PayoutInvoiceSheetContent({ setIsOpen }: PayoutInvoiceSheetProps) {
},
});
- const { paymentMethods, loading: paymentMethodsLoading } =
- usePaymentMethods();
-
- useEffect(() => {
- if (!paymentMethods.length) {
- return;
- }
-
- setPaymentMethodId(paymentMethods[0].id);
- }, [paymentMethods]);
-
const { executeAsync, isExecuting } = useAction(confirmPayoutsAction, {
onSuccess: async () => {
- toast.success("Payouts confirmed successfully! We'll process them soon.");
+ toast.success(
+ "Payouts confirmed successfully! They will be processed soon.",
+ );
setIsOpen(false);
},
onError({ error }) {
@@ -85,45 +57,28 @@ function PayoutInvoiceSheetContent({ setIsOpen }: PayoutInvoiceSheetProps) {
);
const invoiceData = useMemo(() => {
- const amount =
- pendingPayouts?.reduce((acc, payout) => acc + payout.amount, 0) || 0;
+ if (!pendingPayouts) {
+ return {
+ Amount: (
+ <div className="h-4 w-24 animate-pulse rounded-md bg-neutral-200" />
+ ),
+ Fee: (
+ <div className="h-4 w-24 animate-pulse rounded-md bg-neutral-200" />
+ ),
+ Total: (
+ <div className="h-4 w-24 animate-pulse rounded-md bg-neutral-200" />
+ ),
+ };
+ }
+
+ const amount = pendingPayouts.reduce(
+ (acc, payout) => acc + payout.amount,
+ 0,
+ );
const fee = amount * 0.02;
const total = amount + fee;
return {
- Method: (
- <div className="flex items-center gap-2">
- {paymentMethodsLoading ? (
- <div className="h-7 w-full animate-pulse rounded-md border-neutral-300 bg-neutral-100"></div>
- ) : (
- <select
- onChange={(e) => setPaymentMethodId(e.target.value)}
- defaultValue={paymentMethodId || ""}
- className="block h-8 w-full rounded-md border-neutral-300 text-neutral-900 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
- >
- {paymentMethods.map((method) => (
- <option key={method.id} value={method.id}>
- {method.type}
- </option>
- ))}
- </select>
- )}
-
- <Tooltip content="Manage payment methods">
- <Link
- href={`/${slug}/settings/billing`}
- className={cn(
- buttonVariants({ variant: "secondary" }),
- "flex h-8 items-center rounded-md border px-2 text-sm",
- )}
- target="_blank"
- >
- <Gear className="size-4" />
- </Link>
- </Tooltip>
- </div>
- ),
-
Amount: currencyFormatter(amount / 100, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
@@ -139,7 +94,7 @@ function PayoutInvoiceSheetContent({ setIsOpen }: PayoutInvoiceSheetProps) {
maximumFractionDigits: 2,
}),
};
- }, [pendingPayouts, paymentMethods, paymentMethodsLoading]);
+ }, [pendingPayouts]);
const table = useTable({
data: pendingPayouts || [],
@@ -237,15 +192,9 @@ function PayoutInvoiceSheetContent({ setIsOpen }: PayoutInvoiceSheetProps) {
return;
}
- if (!paymentMethodId) {
- toast.error("Please select a payment method.");
- return;
- }
-
await executeAsync({
workspaceId,
programId,
- paymentMethodId,
});
}}
text="Confirm payout"
diff --git a/packages/prisma/schema/invoice.prisma b/packages/prisma/schema/invoice.prisma
index 40bb3db58f..94a7d30599 100644
--- a/packages/prisma/schema/invoice.prisma
+++ b/packages/prisma/schema/invoice.prisma
@@ -1,8 +1,15 @@
+enum InvoiceStatus {
+ processing
+ completed
+ failed
+}
+
model Invoice {
id String @id @default(cuid())
programId String
paymentMethodId String // Stripe payment method ID
paymentIntentId String? @unique // Stripe payment intent ID
+ status InvoiceStatus @default(processing)
amount Int @default(0)
fee Int @default(0)
total Int @default(0)
diff --git a/packages/prisma/schema/workspace.prisma b/packages/prisma/schema/workspace.prisma
index a9025be725..e5166b283b 100644
--- a/packages/prisma/schema/workspace.prisma
+++ b/packages/prisma/schema/workspace.prisma
@@ -35,6 +35,9 @@ model Project {
updatedAt DateTime @updatedAt
usageLastChecked DateTime @default(now())
+ payoutMethodId String?
+
+ // TODO: Remove these
dotsAppId String? @unique
bankAccountName String?
partialAccountNumber String?