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.

createDotsWithdrawalAction

Steven Teybc58f517e22d
diff --git a/apps/web/app/api/partners/[partnerId]/dots-user/route.ts b/apps/web/app/api/partners/[partnerId]/dots-user/route.ts
index 8addccc0bf..263ffe2f7e 100644
--- a/apps/web/app/api/partners/[partnerId]/dots-user/route.ts
+++ b/apps/web/app/api/partners/[partnerId]/dots-user/route.ts
@@ -1,6 +1,7 @@
import { withPartner } from "@/lib/auth/partner";
import { DOTS_API_URL } from "@/lib/dots/env";
import { retrieveDotsFlow } from "@/lib/dots/retrieve-dots-flow";
+import { retrieveDotsUser } from "@/lib/dots/retrieve-dots-user";
import { dotsHeaders } from "@/lib/dots/utils";
import { prisma } from "@/lib/prisma";
import { redis } from "@/lib/upstash";
@@ -35,36 +36,19 @@ export const GET = withPartner(async ({ partner }) => {
return NextResponse.json({});
}
- const [info, payout_methods] = await Promise.all([
- fetch(`${DOTS_API_URL}/users/${dotsUserId}`, {
- method: "GET",
- headers: dotsHeaders({ dotsAppId: DEFAULT_DOTS_APP_ID }),
- }).then((res) => res.json()),
+ const [dotsUser, payout_methods] = await Promise.all([
+ retrieveDotsUser({ dotsUserId, partner }),
fetch(`${DOTS_API_URL}/users/${dotsUserId}/payout-methods`, {
method: "GET",
headers: dotsHeaders({ dotsAppId: DEFAULT_DOTS_APP_ID }),
}).then((res) => res.json()),
]);
- const data = {
- ...info,
- compliance: {
- ...info.compliance,
- submitted:
- partner.country === "US"
- ? info.compliance.w9.tax_id_collected
- : info.compliance.w8_ben_collected,
- },
- wallet: {
- ...info.wallet,
- pending_amount: info.wallet.amount - info.wallet.withdrawable_amount,
- withdrawable_amount: info.wallet.withdrawable_amount,
- },
+ return NextResponse.json({
+ ...dotsUser,
payout_methods: payout_methods.map((method) => ({
...method,
- default: info.default_payout_method === method.platform,
+ default: dotsUser.default_payout_method === method.platform,
})),
- };
-
- return NextResponse.json(data);
+ });
});
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/payouts/payout-stats.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/payouts/payout-stats.tsx
index a85f75f96a..3465ccc82e 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/payouts/payout-stats.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/payouts/payout-stats.tsx
@@ -1,7 +1,6 @@
"use client";
import usePayoutsCount from "@/lib/swr/use-payouts-count";
-import useWorkspace from "@/lib/swr/use-workspace";
import { PayoutStatusBadges } from "@/ui/partners/payout-status-badges";
import { ProgramStatsFilter } from "@/ui/partners/program-stats-filter";
import { MoneyBills2, useRouterStuff } from "@dub/ui";
@@ -9,7 +8,6 @@ import { useParams } from "next/navigation";
export function PayoutStats() {
const { slug, programId } = useParams();
- const { id: workspaceId } = useWorkspace();
const { queryParams } = useRouterStuff();
const { payoutsCount, error } = usePayoutsCount();
diff --git a/apps/web/lib/actions/partners/create-dots-withdrawal.ts b/apps/web/lib/actions/partners/create-dots-withdrawal.ts
index e69de29bb2..cab61b9c09 100644
--- a/apps/web/lib/actions/partners/create-dots-withdrawal.ts
+++ b/apps/web/lib/actions/partners/create-dots-withdrawal.ts
@@ -0,0 +1,37 @@
+"use server";
+
+import { createWithdrawal } from "@/lib/dots/create-withdrawal";
+import { retrieveDotsUser } from "@/lib/dots/retrieve-dots-user";
+import { dotsPayoutPlatforms } from "@/lib/dots/schemas";
+import { z } from "zod";
+import { authPartnerActionClient } from "../safe-action";
+
+const schema = z.object({
+ partnerId: z.string(),
+ platform: dotsPayoutPlatforms,
+});
+
+export const createDotsWithdrawalAction = authPartnerActionClient
+ .schema(schema)
+ .action(async ({ parsedInput, ctx }) => {
+ const { partner } = ctx;
+ const { platform } = parsedInput;
+
+ if (!partner.dotsUserId) {
+ throw new Error("Partner does not have a Dots user ID");
+ }
+
+ const dotsUser = await retrieveDotsUser({
+ dotsUserId: partner.dotsUserId,
+ partner,
+ });
+ console.log({ dotsUser });
+
+ const response = await createWithdrawal({
+ dotsUserId: partner.dotsUserId,
+ amount: dotsUser.wallet.withdrawable_amount,
+ platform,
+ });
+
+ return response;
+ });
diff --git a/apps/web/lib/actions/safe-action.ts b/apps/web/lib/actions/safe-action.ts
index 2928e24362..c9ac64abd5 100644
--- a/apps/web/lib/actions/safe-action.ts
+++ b/apps/web/lib/actions/safe-action.ts
@@ -81,3 +81,44 @@ export const authActionClient = actionClient.use(
});
},
);
+
+export const authPartnerActionClient = actionClient.use(
+ async ({ next, clientInput }) => {
+ const session = await getSession();
+
+ if (!session?.user.id) {
+ throw new Error("Unauthorized: Login required.");
+ }
+
+ // @ts-ignore
+ let partnerId = clientInput?.partnerId;
+
+ if (!partnerId) {
+ throw new Error("PartnerId is required.");
+ }
+
+ const partner = await prisma.partner.findUnique({
+ where: {
+ id: partnerId,
+ },
+ include: {
+ users: {
+ where: {
+ userId: session.user.id,
+ },
+ },
+ },
+ });
+
+ if (!partner || !partner.users) {
+ throw new Error("Partner not found.");
+ }
+
+ return next({
+ ctx: {
+ user: session.user,
+ partner,
+ },
+ });
+ },
+);
diff --git a/apps/web/lib/dots/create-payout.ts b/apps/web/lib/dots/create-withdrawal.ts
similarity index 59%
rename from apps/web/lib/dots/create-payout.ts
rename to apps/web/lib/dots/create-withdrawal.ts
index 8c2eb5b3a7..2b541606bf 100644
--- a/apps/web/lib/dots/create-payout.ts
+++ b/apps/web/lib/dots/create-withdrawal.ts
@@ -1,24 +1,9 @@
-import z from "../zod";
+import { DEFAULT_DOTS_APP_ID } from "@dub/utils";
import { DOTS_API_URL } from "./env";
import { DotsPayoutPlatform } from "./types";
import { dotsHeaders } from "./utils";
-const responseSchema = z.object({
- id: z.string(),
- status: z.enum([
- "created",
- "delivery_pending",
- "delivery_failed",
- "sent",
- "delivered",
- "claimed",
- "reversed",
- "canceled",
- "expired",
- ]),
-});
-
-export const createPayout = async ({
+export const createWithdrawal = async ({
dotsUserId,
amount,
platform,
@@ -29,7 +14,7 @@ export const createPayout = async ({
}) => {
const response = await fetch(`${DOTS_API_URL}/payouts`, {
method: "POST",
- headers: dotsHeaders(),
+ headers: dotsHeaders({ dotsAppId: DEFAULT_DOTS_APP_ID }),
body: JSON.stringify({
user_id: dotsUserId,
amount,
@@ -42,5 +27,5 @@ export const createPayout = async ({
throw new Error(`Failed to create Dots payout: ${error.message}`);
}
- return responseSchema.parse(await response.json());
+ return await response.json();
};
diff --git a/apps/web/lib/dots/retrieve-dots-app.ts b/apps/web/lib/dots/retrieve-dots-app.ts
index 48f7675b6a..75acd70bd9 100644
--- a/apps/web/lib/dots/retrieve-dots-app.ts
+++ b/apps/web/lib/dots/retrieve-dots-app.ts
@@ -9,8 +9,10 @@ export const retrieveDotsApp = async ({ dotsAppId }: { dotsAppId: string }) => {
});
if (!response.ok) {
- console.error(await response.text());
- throw new Error(`Failed to retrieve Dots app ${dotsAppId}.`);
+ const error = await response.json();
+ throw new Error(
+ `Failed to retrieve Dots app ${dotsAppId}: ${error.message}`,
+ );
}
return dotsAppSchema.parse(await response.json());
diff --git a/apps/web/lib/dots/retrieve-dots-user.ts b/apps/web/lib/dots/retrieve-dots-user.ts
new file mode 100644
index 0000000000..a71e69bd46
--- /dev/null
+++ b/apps/web/lib/dots/retrieve-dots-user.ts
@@ -0,0 +1,41 @@
+import { DEFAULT_DOTS_APP_ID } from "@dub/utils";
+import { PartnerProps } from "../types";
+import { DOTS_API_URL } from "./env";
+import { dotsHeaders } from "./utils";
+
+export const retrieveDotsUser = async ({
+ dotsUserId,
+ partner,
+}: {
+ dotsUserId: string;
+ partner: PartnerProps;
+}) => {
+ const response = await fetch(`${DOTS_API_URL}/users/${dotsUserId}`, {
+ method: "GET",
+ headers: dotsHeaders({ dotsAppId: DEFAULT_DOTS_APP_ID }),
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(
+ `Failed to retrieve Dots user ${dotsUserId}: ${error.message}`,
+ );
+ }
+
+ const data = await response.json();
+
+ return {
+ ...data,
+ compliance: {
+ ...data.compliance,
+ submitted:
+ partner.country === "US"
+ ? data.compliance.w9.tax_id_collected
+ : data.compliance.w8_ben_collected,
+ },
+ wallet: {
+ ...data.wallet,
+ pending_amount: data.wallet.amount - data.wallet.withdrawable_amount,
+ },
+ };
+};
diff --git a/apps/web/lib/dots/schemas.ts b/apps/web/lib/dots/schemas.ts
index f9409455a3..d73efbc52a 100644
--- a/apps/web/lib/dots/schemas.ts
+++ b/apps/web/lib/dots/schemas.ts
@@ -72,21 +72,3 @@ export const payoutMethodSchema = z.object({
id: z.string().optional(),
country: z.string().optional(),
});
-
-export const dotsUserSchema = z.object({
- id: z.string(),
- email: z.string(),
- phone_number: z.object({
- country_code: z.string(),
- phone_number: z.string(),
- }),
- status: z.enum(["verified", "unverified", "disabled", "in_review"]),
- verified: z.boolean(),
- wallet: z.object({
- withdrawable_amount: z.number(),
- pending_amount: z.number(),
- }),
- default_payout_method: dotsPayoutPlatforms,
- payout_methods: z.array(payoutMethodSchema),
- compliance: z.any(),
-});
diff --git a/apps/web/ui/partners/payout-withdraw-sheet.tsx b/apps/web/ui/partners/payout-withdraw-sheet.tsx
index 73c4f75c5b..a2553332bb 100644
--- a/apps/web/ui/partners/payout-withdraw-sheet.tsx
+++ b/apps/web/ui/partners/payout-withdraw-sheet.tsx
@@ -1,3 +1,5 @@
+import { createDotsWithdrawalAction } from "@/lib/actions/partners/create-dots-withdrawal";
+import { DotsPayoutPlatform } from "@/lib/dots/types";
import useDotsUser from "@/lib/swr/use-dots-user";
import usePartnerProfile from "@/lib/swr/use-partner-profile";
import { X } from "@/ui/shared/icons";
@@ -8,6 +10,8 @@ import {
DICEBEAR_AVATAR_URL,
formatDate,
} from "@dub/utils";
+import { useAction } from "next-safe-action/hooks";
+import { useParams } from "next/navigation";
import {
Dispatch,
Fragment,
@@ -17,6 +21,7 @@ import {
useState,
} from "react";
import { toast } from "sonner";
+import { mutate } from "swr";
import { DOTS_PAYOUT_PLATFORMS } from "../dots/platforms";
type PayoutWithdrawSheetProps = {
@@ -24,6 +29,7 @@ type PayoutWithdrawSheetProps = {
};
function PayoutWithdrawSheetContent({ setIsOpen }: PayoutWithdrawSheetProps) {
+ const { partnerId } = useParams() as { partnerId: string };
const { partner, error: partnerError } = usePartnerProfile();
const { dotsUser, error: dotsUserError } = useDotsUser();
@@ -63,9 +69,8 @@ function PayoutWithdrawSheetContent({ setIsOpen }: PayoutWithdrawSheetProps) {
[partner, dotsUser],
);
- const [selectedPayoutMethod, setSelectedPayoutMethod] = useState<
- string | null
- >(null);
+ const [selectedPayoutMethod, setSelectedPayoutMethod] =
+ useState<DotsPayoutPlatform | null>(null);
useEffect(() => {
if (!dotsUser?.payout_methods?.length || selectedPayoutMethod !== null)
@@ -76,6 +81,20 @@ function PayoutWithdrawSheetContent({ setIsOpen }: PayoutWithdrawSheetProps) {
);
}, [dotsUser, selectedPayoutMethod]);
+ const { executeAsync, isExecuting } = useAction(createDotsWithdrawalAction, {
+ onSuccess: async () => {
+ await Promise.all([
+ mutate(`/api/partners/${partnerId}/dots-user`),
+ mutate(`/api/partners/${partnerId}/withdrawals`),
+ ]);
+ setIsOpen(false);
+ toast.success("Successfully initiated withdrawal!");
+ },
+ onError({ error }) {
+ toast.error(error.serverError?.serverError);
+ },
+ });
+
return (
<>
<div>
@@ -161,14 +180,14 @@ function PayoutWithdrawSheetContent({ setIsOpen }: PayoutWithdrawSheetProps) {
type="button"
variant="primary"
disabled={!dotsUser?.id || !selectedPayoutMethod}
- onClick={async () => {
- if (!dotsUser?.id) {
- toast.error("Partner has no Dots user ID");
- return;
- }
- toast.info(`WIP withdraw to ${selectedPayoutMethod}`);
- setIsOpen(false);
- }}
+ onClick={() =>
+ selectedPayoutMethod &&
+ executeAsync({
+ partnerId,
+ platform: selectedPayoutMethod,
+ })
+ }
+ loading={isExecuting}
text="Confirm withdrawal"
className="w-fit"
/>
@@ -194,13 +213,13 @@ function PayoutMethodOption({
name: string;
description: string;
isDefault?: boolean;
- selectedPayoutMethod: string | null;
- setSelectedPayoutMethod: Dispatch<SetStateAction<string | null>>;
+ selectedPayoutMethod: DotsPayoutPlatform | null;
+ setSelectedPayoutMethod: Dispatch<SetStateAction<DotsPayoutPlatform | null>>;
}) {
return (
<button
type="button"
- onClick={() => setSelectedPayoutMethod(id)}
+ onClick={() => setSelectedPayoutMethod(id as DotsPayoutPlatform)}
className={cn(
"flex items-center justify-between gap-4 rounded-lg border border-neutral-200 bg-white p-4 text-left",
"transition-[background-color,border-color,box-shadow] duration-75 hover:bg-neutral-50",