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.

Dots WIP

Tim Wilson48a9c23615f9
diff --git a/apps/web/app/api/partners/[partnerId]/payout-methods/route.ts b/apps/web/app/api/partners/[partnerId]/payout-methods/route.ts
new file mode 100644
index 0000000000..4502bbc7d7
--- /dev/null
+++ b/apps/web/app/api/partners/[partnerId]/payout-methods/route.ts
@@ -0,0 +1,17 @@
+import { withPartner } from "@/lib/auth/partner";
+import { retrieveDotsPayoutMethods } from "@/lib/dots/retrieve-dots-payout-methods";
+import { NextResponse } from "next/server";
+
+// GET /api/partners/[partnerId]/payout-methods – get Dots payout methods for a partner
+// TODO: [dots] probably need to update this to work from both the partners.dub.co and app.dub.co sides
+export const GET = withPartner(async ({ partner }) => {
+ const { dotsUserId, dotsAppId } = partner;
+
+ if (!dotsUserId || !dotsAppId) {
+ return NextResponse.json(null);
+ }
+
+ return NextResponse.json(
+ await retrieveDotsPayoutMethods({ dotsUserId, dotsAppId }),
+ );
+});
diff --git a/apps/web/app/partners.dub.co/(dashboard)/[partnerId]/settings/payouts/page-client.tsx b/apps/web/app/partners.dub.co/(dashboard)/[partnerId]/settings/payouts/page-client.tsx
new file mode 100644
index 0000000000..caf9136372
--- /dev/null
+++ b/apps/web/app/partners.dub.co/(dashboard)/[partnerId]/settings/payouts/page-client.tsx
@@ -0,0 +1,41 @@
+"use client";
+
+import { createDotsFlowAction } from "@/lib/actions/partners/create-dots-flow";
+import usePayoutMethods from "@/lib/swr/use-payout-methods";
+import { Button } from "@dub/ui";
+import { useAction } from "next-safe-action/hooks";
+import { useParams } from "next/navigation";
+import { toast } from "sonner";
+
+export function PayoutsSettingsPageClient() {
+ const { partnerId } = useParams() as { partnerId: string };
+
+ // TODO: [dots] actually list payout methods
+ const { data: payoutMethods } = usePayoutMethods({ partnerId });
+
+ const { executeAsync, isExecuting } = useAction(createDotsFlowAction, {
+ onError({ error }) {
+ toast.error(error.serverError?.serverError);
+ },
+ });
+
+ return (
+ <div>
+ <Button
+ text="Manage payout methods"
+ onClick={async () => {
+ const result = await executeAsync({ partnerId });
+ console.log(result);
+ if (!result?.data?.ok || !("link" in result?.data)) {
+ toast.error("Failed to start payout method connection flow");
+ return;
+ }
+
+ toast.success("Starting Dots flow...");
+ window.open(result.data.link, "_blank");
+ }}
+ className="w-fit"
+ />
+ </div>
+ );
+}
diff --git a/apps/web/app/partners.dub.co/(dashboard)/[partnerId]/settings/payouts/page.tsx b/apps/web/app/partners.dub.co/(dashboard)/[partnerId]/settings/payouts/page.tsx
index ac27f05a1e..4eb26f023a 100644
--- a/apps/web/app/partners.dub.co/(dashboard)/[partnerId]/settings/payouts/page.tsx
+++ b/apps/web/app/partners.dub.co/(dashboard)/[partnerId]/settings/payouts/page.tsx
@@ -1,24 +1,13 @@
import { PageContent } from "@/ui/layout/page-content";
-import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
import { MaxWidthWrapper } from "@dub/ui";
-import { GreekTemple } from "@dub/ui/src/icons";
+import { PayoutsSettingsPageClient } from "./page-client";
export default function PayoutsSettings() {
return (
- <PageContent title="Payouts">
+ <PageContent title="Payouts" description="Manage your payout methods">
<MaxWidthWrapper>
- <AnimatedEmptyState
- title="Payouts"
- description="Connect and manage your bank accounts to receive payouts"
- cardContent={
- <>
- <GreekTemple className="size-4 text-neutral-700" />
- <div className="h-2.5 w-28 min-w-0 rounded-sm bg-neutral-200" />
- </>
- }
- pillContent="Coming soon"
- />
+ <PayoutsSettingsPageClient />
</MaxWidthWrapper>
</PageContent>
);
diff --git a/apps/web/lib/actions/partners/create-dots-flow.ts b/apps/web/lib/actions/partners/create-dots-flow.ts
new file mode 100644
index 0000000000..32cda583c5
--- /dev/null
+++ b/apps/web/lib/actions/partners/create-dots-flow.ts
@@ -0,0 +1,49 @@
+"use server";
+
+import { getPartnerOrThrow } from "@/lib/api/partners/get-partner-or-throw";
+import { createDotsFlow } from "@/lib/dots/create-dots-flow";
+import { userIsInBeta } from "@/lib/edge-config";
+import z from "../../zod";
+import { authUserActionClient } from "../safe-action";
+
+const onboardPartnerSchema = z.object({
+ partnerId: z.string(),
+});
+
+// Create a Dots flow for connecting payout methods
+export const createDotsFlowAction = authUserActionClient
+ .schema(onboardPartnerSchema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { user } = ctx;
+
+ const { partner } = await getPartnerOrThrow({
+ partnerId: parsedInput.partnerId,
+ userId: user.id,
+ });
+
+ const partnersPortalEnabled = await userIsInBeta(
+ user.email,
+ "partnersPortal",
+ );
+ if (!partnersPortalEnabled) {
+ return {
+ ok: false,
+ error: "Partners portal feature flag disabled.",
+ };
+ }
+
+ try {
+ // TODO: [dots] probably need to specify the dots app ID if it ends up being different for each program enrollment
+ const response = await createDotsFlow({
+ partner,
+ steps: ["manage-payouts"],
+ });
+
+ return { ok: true, ...response };
+ } catch (e) {
+ console.error(e);
+ return {
+ ok: false,
+ };
+ }
+ });
diff --git a/apps/web/lib/dots/create-dots-flow.ts b/apps/web/lib/dots/create-dots-flow.ts
new file mode 100644
index 0000000000..b5e4e5bcc2
--- /dev/null
+++ b/apps/web/lib/dots/create-dots-flow.ts
@@ -0,0 +1,91 @@
+import { prisma } from "@/lib/prisma";
+import { Partner } from "@prisma/client";
+import z from "../zod";
+import { createDotsUser } from "./create-dots-user";
+import { DOTS_API_URL } from "./env";
+import { dotsHeaders } from "./utils";
+
+const responseSchema = z.object({
+ id: z.string(),
+ link: z.string(),
+});
+
+export const createDotsFlow = async ({
+ partner,
+ steps = ["payout"],
+}: {
+ partner: Pick<Partner, "id" | "dotsUserId" | "dotsAppId">;
+ steps?: string[];
+}) => {
+ let dotsUserId = partner.dotsUserId;
+ let dotsAppId = partner.dotsAppId;
+
+ // Create Dots user if it doesn't exist
+ if (!partner.dotsUserId) {
+ // TODO: [dots] we probably need to actually create separate Dots users for each partner <-> <-> workspace connection
+ const firstEnrolledProgramWorkspace =
+ await prisma.programEnrollment.findFirst({
+ select: {
+ program: {
+ select: {
+ workspace: {
+ select: {
+ dotsAppId: true,
+ },
+ },
+ },
+ },
+ },
+ where: {
+ partnerId: partner.id,
+ status: "approved",
+ },
+ });
+
+ dotsAppId =
+ firstEnrolledProgramWorkspace?.program.workspace.dotsAppId ?? null;
+ if (!dotsAppId) {
+ throw new Error("No eligible program enrollment found.");
+ }
+
+ // TODO: [dots] we need to gather real user info for this
+ const dotsUser = await createDotsUser({
+ dotsAppId,
+ firstName: "Test",
+ lastName: "Tester",
+ email: "[email protected]",
+ countryCode: "1",
+ phoneNumber: "4129268662",
+ });
+
+ await prisma.partner.update({
+ where: {
+ id: partner.id,
+ },
+ data: {
+ // TODO: [dots] might need to move these to the ProgramEnrollment table or somewhere between partners and workspaces
+ dotsUserId: dotsUser.id,
+ dotsAppId,
+ },
+ });
+
+ dotsUserId = dotsUser.id;
+ }
+
+ const response = await fetch(`${DOTS_API_URL}/flows`, {
+ method: "POST",
+ headers: dotsHeaders({ dotsAppId: dotsAppId ?? undefined }),
+ body: JSON.stringify({
+ steps,
+ user_id: dotsUserId,
+ }),
+ });
+
+ if (!response.ok) {
+ console.error(await response.text());
+
+ throw new Error(`Failed to create Dots flow.`);
+ }
+
+ return { ...responseSchema.parse(await response.json()), dotsAppId };
+};
diff --git a/apps/web/lib/dots/create-dots-user.ts b/apps/web/lib/dots/create-dots-user.ts
new file mode 100644
index 0000000000..a37e040c19
--- /dev/null
+++ b/apps/web/lib/dots/create-dots-user.ts
@@ -0,0 +1,44 @@
+import z from "../zod";
+import { DOTS_API_URL } from "./env";
+import { dotsHeaders } from "./utils";
+
+const responseSchema = z.object({
+ id: z.string(),
+ status: z.enum(["verified", "unverified", "disabled", "in_review"]),
+});
+
+export const createDotsUser = async ({
+ dotsAppId,
+ firstName,
+ lastName,
+ email,
+ countryCode,
+ phoneNumber,
+}: {
+ dotsAppId: string;
+ firstName: string;
+ lastName: string;
+ email: string;
+ countryCode: string;
+ phoneNumber: string;
+}) => {
+ const response = await fetch(`${DOTS_API_URL}/users`, {
+ method: "POST",
+ headers: dotsHeaders({ dotsAppId }),
+ body: JSON.stringify({
+ first_name: firstName,
+ last_name: lastName,
+ email,
+ country_code: countryCode,
+ phone_number: phoneNumber,
+ }),
+ });
+
+ if (!response.ok) {
+ console.error(await response.text());
+
+ throw new Error(`Failed to create Dots user.`);
+ }
+
+ return responseSchema.parse(await response.json());
+};
diff --git a/apps/web/lib/dots/retrieve-dots-payout-methods.ts b/apps/web/lib/dots/retrieve-dots-payout-methods.ts
new file mode 100644
index 0000000000..8f877fb5fd
--- /dev/null
+++ b/apps/web/lib/dots/retrieve-dots-payout-methods.ts
@@ -0,0 +1,28 @@
+import { DOTS_API_URL } from "./env";
+import { dotsAppSchema } from "./schemas";
+import { dotsHeaders } from "./utils";
+
+export const retrieveDotsPayoutMethods = async ({
+ dotsUserId,
+ dotsAppId,
+}: {
+ dotsUserId: string;
+ dotsAppId: string;
+}) => {
+ const response = await fetch(
+ `${DOTS_API_URL}/users/${dotsUserId}/payout-methods`,
+ {
+ method: "GET",
+ headers: dotsHeaders({ dotsAppId }),
+ },
+ );
+
+ if (!response.ok) {
+ console.error(await response.text());
+ throw new Error(
+ `Failed to retrieve payout methods for Dots user ${dotsUserId}.`,
+ );
+ }
+
+ return dotsAppSchema.parse(await response.json());
+};
diff --git a/apps/web/lib/dots/schemas.ts b/apps/web/lib/dots/schemas.ts
index e79ecc7ef0..41eeac61ca 100644
--- a/apps/web/lib/dots/schemas.ts
+++ b/apps/web/lib/dots/schemas.ts
@@ -43,3 +43,18 @@ export const dotsTransfersSchema = z.object({
data: z.array(dotsTransferSchema),
has_more: z.boolean(),
});
+
+export const dotsPayoutMethodSchema = z.object({
+ id: z.string(),
+ platform: z.enum([
+ "ach",
+ "paypal",
+ "venmo",
+ "cash_app",
+ "intl_transfer",
+ "airtm",
+ "payoneer",
+ ]),
+ mask: z.string(),
+ currency: z.string(),
+});
diff --git a/apps/web/lib/dots/send-payout.ts b/apps/web/lib/dots/send-payout.ts
new file mode 100644
index 0000000000..be6e458ee8
--- /dev/null
+++ b/apps/web/lib/dots/send-payout.ts
@@ -0,0 +1,47 @@
+import z from "../zod";
+import { DOTS_API_URL } from "./env";
+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 sendPayout = async ({
+ dotsUserId,
+ amount,
+ dotsAppId,
+}: {
+ dotsUserId: string;
+ amount: number;
+ dotsAppId: string;
+}) => {
+ const response = await fetch(`${DOTS_API_URL}/payouts/send-payout`, {
+ method: "POST",
+ headers: dotsHeaders({ dotsAppId }),
+ body: JSON.stringify({
+ user_id: dotsUserId,
+ amount,
+ }),
+ });
+
+ if (!response.ok) {
+ console.error(await response.text());
+
+ throw new Error(`Failed to create Dots user.`);
+ }
+
+ // TODO: [dots] update payout status in our DB? might also need to use webhooks for this
+
+ return responseSchema.parse(await response.json());
+};
diff --git a/apps/web/lib/dots/types.ts b/apps/web/lib/dots/types.ts
index 3aaa1c79db..ab475c957a 100644
--- a/apps/web/lib/dots/types.ts
+++ b/apps/web/lib/dots/types.ts
@@ -1,6 +1,14 @@
import { z } from "zod";
-import { dotsAppSchema, dotsTransfersSchema } from "./schemas";
+import {
+ dotsAppSchema,
+ dotsPayoutMethodSchema,
+ dotsTransfersSchema,
+} from "./schemas";
export type DotsApp = z.infer<typeof dotsAppSchema>;
export type DotsTransfers = z.infer<typeof dotsTransfersSchema>;
+
+export type DotsPayoutMethod = z.infer<typeof dotsPayoutMethodSchema>;
+
+export type DotsPayoutMethods = DotsPayoutMethod[];
diff --git a/apps/web/lib/swr/use-payout-methods.ts b/apps/web/lib/swr/use-payout-methods.ts
new file mode 100644
index 0000000000..8c22c677ab
--- /dev/null
+++ b/apps/web/lib/swr/use-payout-methods.ts
@@ -0,0 +1,20 @@
+import { fetcher } from "@dub/utils";
+import useSWR from "swr";
+import { DotsPayoutMethods } from "../dots/types";
+
+export default function usePayoutMethods({
+ partnerId,
+}: {
+ partnerId: string | null;
+}) {
+ const { data, error } = useSWR<DotsPayoutMethods>(
+ partnerId ? `/api/partners/${partnerId}/payout-methods` : null,
+ fetcher,
+ );
+
+ return {
+ data,
+ error,
+ isLoading: !data && !error,
+ };
+}
diff --git a/apps/web/lib/zod/schemas/partners.ts b/apps/web/lib/zod/schemas/partners.ts
index 11ae1e5594..1af6d3f73b 100644
--- a/apps/web/lib/zod/schemas/partners.ts
+++ b/apps/web/lib/zod/schemas/partners.ts
@@ -28,6 +28,8 @@ export const PartnerSchema = z.object({
bio: z.string().nullable(),
country: z.string().nullable(),
status: z.nativeEnum(PartnerStatus),
+ dotsUserId: z.string().nullable(),
+ dotsAppId: z.string().nullable(),
createdAt: z.date(),
updatedAt: z.date(),
});
diff --git a/apps/web/prisma/schema/partner.prisma b/apps/web/prisma/schema/partner.prisma
index 9e6dafdecf..5b42e0d068 100644
--- a/apps/web/prisma/schema/partner.prisma
+++ b/apps/web/prisma/schema/partner.prisma
@@ -19,6 +19,10 @@ model Partner {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
+ // TODO: [dots] might need to move these to the ProgramEnrollment table or somewhere between partners and workspaces
+ dotsAppId String?
+ dotsUserId String? @unique
+
programs ProgramEnrollment[]
users PartnerUser[]
invites PartnerInvite[]