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.

Create manual payout

Kiran K425f4f5e7092
diff --git a/apps/web/app/api/cron/payouts/utils.ts b/apps/web/app/api/cron/payouts/utils.ts
index c65207e2b0..be84042e61 100644
--- a/apps/web/app/api/cron/payouts/utils.ts
+++ b/apps/web/app/api/cron/payouts/utils.ts
@@ -1,4 +1,4 @@
-import { createId } from "@/lib/api/utils";
+import { createPartnerPayouts } from "@/lib/partners/create-payout";
import { prisma } from "@/lib/prisma";
// Payout are calcuated at the end of the month
@@ -13,94 +13,28 @@ export const processMonthlyPartnerPayouts = async () => {
return;
}
+ const currentDate = new Date();
+
+ const periodStart = new Date(
+ currentDate.getFullYear(),
+ currentDate.getMonth(),
+ 1,
+ );
+
+ const periodEnd = new Date(
+ currentDate.getFullYear(),
+ currentDate.getMonth() + 1,
+ 0,
+ );
+
// TODO:
// We need a batter way to handle this recursively
for (const { programId, partnerId } of partners) {
await createPartnerPayouts({
programId,
partnerId,
+ periodStart,
+ periodEnd,
});
}
};
-
-export const createPartnerPayouts = async ({
- programId,
- partnerId,
-}: {
- programId: string;
- partnerId: string;
-}) => {
- await prisma.$transaction(async (tx) => {
- const currentDate = new Date();
- // const periodStart = new Date(2024, 7, 1);
- // const periodEnd = new Date(2024, 10, 0);
- const periodStart = new Date(
- currentDate.getFullYear(),
- currentDate.getMonth(),
- 1,
- );
- const periodEnd = new Date(
- currentDate.getFullYear(),
- currentDate.getMonth() + 1,
- 0,
- );
-
- // Calculate the commission earned for the partner for the given program
- const sales = await tx.sale.findMany({
- where: {
- programId,
- partnerId,
- payoutId: null,
- status: "pending", // We only want to pay out sales that are pending (not refunded / fraud / duplicate)
- createdAt: {
- gte: periodStart,
- lte: periodEnd,
- },
- // Referral commissions are held for 30 days before becoming available.
- // createdAt: {
- // lte: subDays(new Date(), 30),
- // },
- },
- select: {
- id: true,
- earnings: true,
- },
- });
-
- if (!sales.length) {
- return;
- }
-
- const earningsTotal = sales.reduce(
- (total, sale) => total + sale.earnings,
- 0,
- );
-
- const amount = earningsTotal;
- const fee = amount * 0.02;
-
- // Create the payout
- const payout = await tx.payout.create({
- data: {
- id: createId({ prefix: "po_" }),
- programId,
- partnerId,
- amount,
- fee,
- total: amount + fee,
- currency: "USD",
- status: "pending",
- periodStart,
- periodEnd,
- },
- });
-
- // Update the sales records
- await tx.sale.updateMany({
- where: { id: { in: sales.map((sale) => sale.id) } },
- data: { payoutId: payout.id, status: "processed" },
- });
-
- console.info("Payout created", payout);
- });
-};
diff --git a/apps/web/app/api/partners/[partnerId]/programs/[programId]/payouts/route.ts b/apps/web/app/api/partners/[partnerId]/programs/[programId]/payouts/route.ts
index bd280931ee..4c9c4481ac 100644
--- a/apps/web/app/api/partners/[partnerId]/programs/[programId]/payouts/route.ts
+++ b/apps/web/app/api/partners/[partnerId]/programs/[programId]/payouts/route.ts
@@ -39,5 +39,13 @@ export const GET = withPartner(async ({ partner, params, searchParams }) => {
},
});
- return NextResponse.json(z.array(PartnerPayoutResponseSchema).parse(payouts));
+ return NextResponse.json(
+ z
+ .array(
+ PartnerPayoutResponseSchema.omit({
+ description: true,
+ }),
+ )
+ .parse(payouts),
+ );
});
diff --git a/apps/web/app/api/programs/[programId]/payouts/route.ts b/apps/web/app/api/programs/[programId]/payouts/route.ts
index 9ad65785d2..a2173b7f50 100644
--- a/apps/web/app/api/programs/[programId]/payouts/route.ts
+++ b/apps/web/app/api/programs/[programId]/payouts/route.ts
@@ -12,7 +12,7 @@ import z from "zod";
export const GET = withWorkspace(
async ({ workspace, params, searchParams }) => {
const { programId } = params;
- const { status, search, partnerId, sortBy, order, page, pageSize } =
+ const { status, search, partnerId, sortBy, order, page, pageSize, type } =
payoutsQuerySchema.parse(searchParams);
await getProgramOrThrow({
@@ -26,6 +26,7 @@ export const GET = withWorkspace(
...(status && { status }),
...(search && { partner: { name: { contains: search } } }),
...(partnerId && { partnerId }),
+ ...(type && { type }),
},
include: {
partner: true,
diff --git a/apps/web/app/api/track/sale/route.ts b/apps/web/app/api/track/sale/route.ts
index 4e5e50c7a7..ad9ff56dd7 100644
--- a/apps/web/app/api/track/sale/route.ts
+++ b/apps/web/app/api/track/sale/route.ts
@@ -72,6 +72,8 @@ export const POST = withWorkspaceEdge(
.omit({ timestamp: true })
.parse(leadEvent.data[0]);
+ console.log("clickData", clickData);
+
waitUntil(
(async () => {
const eventId = nanoid(16);
@@ -119,6 +121,8 @@ export const POST = withWorkspaceEdge(
}),
]);
+ console.log("link", link);
+
// for program links
if (link.programId) {
const { program, partner } =
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/payouts/create-payout-button.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/payouts/create-payout-button.tsx
new file mode 100644
index 0000000000..54840d968e
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/payouts/create-payout-button.tsx
@@ -0,0 +1,23 @@
+"use client";
+
+import { useCreatePayoutSheet } from "@/ui/partners/create-payout-sheet";
+import { Button } from "@dub/ui";
+import { Plus } from "@dub/ui/src/icons";
+
+export function CreatePayoutButton() {
+ const { createPayoutSheet, setIsOpen: setShowCreatePayoutSheet } =
+ useCreatePayoutSheet();
+
+ return (
+ <>
+ <Button
+ type="button"
+ variant="secondary"
+ onClick={() => setShowCreatePayoutSheet(true)}
+ text="Create payout"
+ icon={<Plus className="size-4" />}
+ />
+ {createPayoutSheet}
+ </>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/payouts/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/payouts/page-client.tsx
index 7ed0cfcca2..4a53510890 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/payouts/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/payouts/page-client.tsx
@@ -6,25 +6,31 @@ import { Gear } from "@dub/ui/src/icons";
import { cn } from "@dub/utils";
import Link from "next/link";
import { useParams } from "next/navigation";
+import { CreatePayoutButton } from "./create-payout-button";
import { PayoutStats } from "./payout-stats";
import { PayoutTable } from "./payout-table";
export function ProgramPayoutsPageClient() {
const { slug } = useParams() as { slug: string };
+
return (
<PageContent
title="Payouts"
titleControls={
- <Link
- href={`/${slug}/settings/payouts`}
- className={cn(
- buttonVariants({ variant: "secondary" }),
- "flex h-10 items-center gap-2 rounded-lg border px-3 text-sm",
- )}
- >
- <Gear className="size-4" />
- Settings
- </Link>
+ <div className="flex items-center gap-2">
+ <CreatePayoutButton />
+
+ <Link
+ href={`/${slug}/settings/payouts`}
+ className={cn(
+ buttonVariants({ variant: "secondary" }),
+ "flex h-10 items-center gap-2 rounded-lg border px-3 text-sm",
+ )}
+ >
+ <Gear className="size-4" />
+ Settings
+ </Link>
+ </div>
}
>
<MaxWidthWrapper>
diff --git a/apps/web/lib/actions/partners/create-manual-payout.ts b/apps/web/lib/actions/partners/create-manual-payout.ts
new file mode 100644
index 0000000000..b27f97503d
--- /dev/null
+++ b/apps/web/lib/actions/partners/create-manual-payout.ts
@@ -0,0 +1,112 @@
+"use server";
+
+import { createId } from "@/lib/api/utils";
+import { createSalesPayouts } from "@/lib/partners/create-sales-payout";
+import { processPartnerPayout } from "@/lib/partners/process-payout";
+import { prisma } from "@/lib/prisma";
+import { parseDateSchema } from "@/lib/zod/schemas/utils";
+import { Payout, PayoutType } from "@prisma/client";
+import { z } from "zod";
+import { authActionClient } from "../safe-action";
+
+const schema = z.object({
+ workspaceId: z.string(),
+ programId: z.string(),
+ partnerId: z.string(),
+ start: parseDateSchema,
+ end: parseDateSchema,
+ type: z.nativeEnum(PayoutType),
+ eventCount: z.number().default(0),
+ amount: z.number(),
+ description: z.string().max(5000).nullish(),
+ metadata: z.record(z.string(), z.number()).nullish(),
+});
+
+export const createManualPayoutAction = authActionClient
+ .schema(schema)
+ .action(async ({ parsedInput, ctx }) => {
+ const { workspace } = ctx;
+ const {
+ programId,
+ partnerId,
+ start,
+ end,
+ type,
+ amount,
+ description,
+ eventCount,
+ } = parsedInput;
+
+ if (!workspace.dotsAppId) {
+ throw new Error("Partner payouts are not enabled for this workspace.");
+ }
+
+ const result = await prisma.programEnrollment.findUniqueOrThrow({
+ where: {
+ partnerId_programId: {
+ partnerId,
+ programId,
+ },
+ },
+ select: {
+ dotsUserId: true,
+ program: true,
+ },
+ });
+
+ const { program, ...programEnrollment } = result;
+
+ if (!programEnrollment.dotsUserId) {
+ throw new Error("Partner is not properly enrolled in this program.");
+ }
+
+ let payout: Payout | undefined = undefined;
+
+ // Create a payout for clicks, leads, and custom events
+ if (["clicks", "leads", "custom"].includes(type)) {
+ const amountInCents = amount * 100;
+ const fee = amountInCents * 0.02;
+
+ payout = await prisma.payout.create({
+ data: {
+ id: createId({ prefix: "po_" }),
+ programId,
+ partnerId,
+ fee,
+ type,
+ description,
+ eventCount,
+ periodStart: start,
+ periodEnd: end,
+ amount: amountInCents,
+ total: amountInCents + fee,
+ },
+ });
+ }
+
+ // Create a payout for sales
+ if (type === "sales") {
+ payout = await createSalesPayouts({
+ programId,
+ partnerId,
+ periodStart: start,
+ periodEnd: end,
+ });
+ }
+
+ if (!payout) {
+ throw new Error("Failed to create payout. Please try again.");
+ }
+
+ const { transfer, orgTransfer } = await processPartnerPayout({
+ workspace,
+ programEnrollment,
+ program,
+ payout,
+ });
+
+ return {
+ transfer,
+ orgTransfer,
+ };
+ });
diff --git a/apps/web/lib/actions/partners/create-partner-payout.ts b/apps/web/lib/actions/partners/create-partner-payout.ts
index 8f7c4a069b..f4924df01e 100644
--- a/apps/web/lib/actions/partners/create-partner-payout.ts
+++ b/apps/web/lib/actions/partners/create-partner-payout.ts
@@ -1,15 +1,8 @@
"use server";
-import { limiter } from "@/lib/cron/limiter";
+import { processPartnerPayout } from "@/lib/partners/process-payout";
import { prisma } from "@/lib/prisma";
-import { formatDate } from "@dub/utils";
-import { waitUntil } from "@vercel/functions";
-import { sendEmail } from "emails";
-import PartnerPayoutSent from "emails/partner-payout-sent";
-import { v5 as uuidv5 } from "uuid";
import { z } from "zod";
-import { createOrgTransfer } from "../../dots/create-org-transfer";
-import { createTransfer } from "../../dots/create-transfer";
import { authActionClient } from "../safe-action";
const schema = z.object({
@@ -31,7 +24,7 @@ export const createPartnerPayoutAction = authActionClient
where: { id: payoutId },
});
- const programEnrollment = await prisma.programEnrollment.findUniqueOrThrow({
+ const result = await prisma.programEnrollment.findUniqueOrThrow({
where: {
partnerId_programId: {
partnerId: payout.partnerId,
@@ -44,83 +37,21 @@ export const createPartnerPayoutAction = authActionClient
},
});
+ const { program, ...programEnrollment } = result;
+
if (!programEnrollment.dotsUserId) {
throw new Error("Partner is not properly enrolled in this program");
}
- const transfer = await createTransfer({
- amount: payout.amount,
- dotsAppId: workspace.dotsAppId,
- dotsUserId: programEnrollment.dotsUserId,
- idempotencyKey: uuidv5(payout.id, uuidv5.URL), // pass a unique idempotency key for each payout to avoid duplicate payouts
- });
-
- // we're splitting this out of the Promise.all() to avoid a race condition
- // e.g. if the transfer fails, we shouldn't proceed with creating the org transfer
- const orgTransfer = await createOrgTransfer({
- amount: payout.fee,
- dotsAppId: workspace.dotsAppId,
+ const { transfer, orgTransfer } = await processPartnerPayout({
+ workspace,
+ programEnrollment,
+ program,
+ payout,
});
- await Promise.all([
- prisma.payout.update({
- where: { id: payoutId },
- data: { dotsTransferId: transfer.id, status: "completed" },
- }),
-
- prisma.sale.updateMany({
- where: { payoutId },
- data: { status: "paid" },
- }),
- ]);
-
- waitUntil(
- (async () => {
- const { program } = programEnrollment;
- const partnerUsers = await prisma.partnerUser.findMany({
- where: {
- partnerId: payout.partnerId,
- },
- include: {
- user: {
- select: {
- email: true,
- },
- },
- },
- });
-
- await Promise.all(
- partnerUsers.map(({ user }) =>
- limiter.schedule(() =>
- sendEmail({
- subject: "You've been paid!",
- email: user.email!,
- from: "Dub Partners <[email protected]>",
- react: PartnerPayoutSent({
- email: user.email!,
- program,
- payout: {
- id: payout.id,
- amount: payout.amount,
- startDate: formatDate(payout.periodStart, {
- year: "numeric",
- month: "short",
- day: "numeric",
- }),
- endDate: formatDate(payout.periodEnd, {
- year: "numeric",
- month: "short",
- day: "numeric",
- }),
- },
- }),
- }),
- ),
- ),
- );
- })(),
- );
-
- return { transfer, orgTransfer };
+ return {
+ transfer,
+ orgTransfer,
+ };
});
diff --git a/apps/web/lib/partners/create-sales-payout.ts b/apps/web/lib/partners/create-sales-payout.ts
new file mode 100644
index 0000000000..12ade3ab4d
--- /dev/null
+++ b/apps/web/lib/partners/create-sales-payout.ts
@@ -0,0 +1,75 @@
+import { createId } from "@/lib/api/utils";
+import { prisma } from "@/lib/prisma";
+
+// Calculate the commission earned for the partner for the given program
+export const createSalesPayouts = async ({
+ programId,
+ partnerId,
+ periodStart,
+ periodEnd,
+}: {
+ programId: string;
+ partnerId: string;
+ periodStart: Date;
+ periodEnd: Date;
+}) => {
+ return await prisma.$transaction(async (tx) => {
+ const sales = await tx.sale.findMany({
+ where: {
+ programId,
+ partnerId,
+ payoutId: null,
+ status: "pending", // We only want to pay out sales that are pending (not refunded / fraud / duplicate)
+ createdAt: {
+ gte: periodStart,
+ lte: periodEnd,
+ },
+ // Referral commissions are held for 30 days before becoming available.
+ // createdAt: {
+ // lte: subDays(new Date(), 30),
+ // },
+ },
+ select: {
+ id: true,
+ earnings: true,
+ },
+ });
+
+ if (!sales.length) {
+ return;
+ }
+
+ const earningsTotal = sales.reduce(
+ (total, sale) => total + sale.earnings,
+ 0,
+ );
+
+ const amount = earningsTotal;
+ const fee = amount * 0.02;
+
+ // Create the payout
+ const payout = await tx.payout.create({
+ data: {
+ id: createId({ prefix: "po_" }),
+ programId,
+ partnerId,
+ amount,
+ fee,
+ total: amount + fee,
+ periodStart,
+ periodEnd,
+ eventCount: sales.length,
+ },
+ });
+
+ // Update the sales records
+ await tx.sale.updateMany({
+ where: { id: { in: sales.map((sale) => sale.id) } },
+ data: { payoutId: payout.id, status: "processed" },
+ });
+
+ console.info("Payout created", payout);
+
+ return payout;
+ });
+};
diff --git a/apps/web/lib/partners/process-payout.ts b/apps/web/lib/partners/process-payout.ts
new file mode 100644
index 0000000000..89b6545f9a
--- /dev/null
+++ b/apps/web/lib/partners/process-payout.ts
@@ -0,0 +1,112 @@
+import { prisma } from "@/lib/prisma";
+import { formatDate } from "@dub/utils";
+import { Payout, Program, ProgramEnrollment, Project } from "@prisma/client";
+import { waitUntil } from "@vercel/functions";
+import { sendEmail } from "emails";
+import PartnerPayoutSent from "emails/partner-payout-sent";
+import { v5 as uuidv5 } from "uuid";
+import { limiter } from "../cron/limiter";
+import { createOrgTransfer } from "../dots/create-org-transfer";
+import { createTransfer } from "../dots/create-transfer";
+
+export const processPartnerPayout = async ({
+ workspace,
+ program,
+ programEnrollment,
+ payout,
+}: {
+ workspace: Pick<Project, "dotsAppId">;
+ program: Pick<Program, "id" | "name" | "logo">;
+ programEnrollment: Pick<ProgramEnrollment, "dotsUserId">;
+ payout: Payout;
+}) => {
+ if (!workspace.dotsAppId) {
+ throw new Error("Partner payouts are not enabled for this workspace.");
+ }
+
+ if (!programEnrollment.dotsUserId) {
+ throw new Error("Partner is not properly enrolled in this program.");
+ }
+
+ const transfer = await createTransfer({
+ amount: payout.amount,
+ dotsAppId: workspace.dotsAppId,
+ dotsUserId: programEnrollment.dotsUserId,
+ idempotencyKey: uuidv5(payout.id, uuidv5.URL),
+ });
+
+ // we're splitting this out of the Promise.all() to avoid a race condition
+ // e.g. if the transfer fails, we shouldn't proceed with creating the org transfer
+ const orgTransfer = await createOrgTransfer({
+ amount: payout.fee,
+ dotsAppId: workspace.dotsAppId,
+ });
+
+ await Promise.all([
+ prisma.payout.update({
+ where: { id: payout.id },
+ data: { dotsTransferId: transfer.id, status: "completed" },
+ }),
+
+ ...(payout.type === "sales"
+ ? [
+ prisma.sale.updateMany({
+ where: { payoutId: payout.id },
+ data: { status: "paid" },
+ }),
+ ]
+ : []),
+ ]);
+
+ waitUntil(
+ (async () => {
+ const partnerUsers = await prisma.partnerUser.findMany({
+ where: {
+ partnerId: payout.partnerId,
+ },
+ include: {
+ user: {
+ select: {
+ email: true,
+ },
+ },
+ },
+ });
+
+ await Promise.all(
+ partnerUsers.map(({ user }) =>
+ limiter.schedule(() =>
+ sendEmail({
+ subject: "You've been paid!",
+ email: user.email!,
+ from: "Dub Partners <[email protected]>",
+ react: PartnerPayoutSent({
+ email: user.email!,
+ program,
+ payout: {
+ id: payout.id,
+ amount: payout.amount,
+ startDate: formatDate(payout.periodStart, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ }),
+ endDate: formatDate(payout.periodEnd, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ }),
+ },
+ }),
+ }),
+ ),
+ ),
+ );
+ })(),
+ );
+
+ return {
+ transfer,
+ orgTransfer,
+ };
+};
diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.ts
index a4e5a6bca6..e24c4008f4 100644
--- a/apps/web/lib/tinybird/record-click.ts
+++ b/apps/web/lib/tinybird/record-click.ts
@@ -56,14 +56,14 @@ export async function recordClick({
const cacheKey = `recordClick:${linkId}:${ip}`;
- if (!skipRatelimit) {
- // by default, we deduplicate clicks from the same IP address + link ID – only record 1 click per hour
- // here, we check if the clickId is cached in Redis within the last hour
- const cachedClickId = await redis.get<string>(cacheKey);
- if (cachedClickId) {
- return null;
- }
- }
+ // if (!skipRatelimit) {
+ // // by default, we deduplicate clicks from the same IP address + link ID – only record 1 click per hour
+ // // here, we check if the clickId is cached in Redis within the last hour
+ // const cachedClickId = await redis.get<string>(cacheKey);
+ // if (cachedClickId) {
+ // return null;
+ // }
+ // }
const isQr = detectQr(req);
diff --git a/apps/web/lib/zod/schemas/partners.ts b/apps/web/lib/zod/schemas/partners.ts
index cac878022f..d31b175db5 100644
--- a/apps/web/lib/zod/schemas/partners.ts
+++ b/apps/web/lib/zod/schemas/partners.ts
@@ -3,6 +3,7 @@ import { COUNTRY_CODES } from "@dub/utils";
import {
PartnerStatus,
PayoutStatus,
+ PayoutType,
ProgramEnrollmentStatus,
SaleStatus,
} from "@prisma/client";
@@ -63,6 +64,7 @@ export const payoutsQuerySchema = z
partnerId: z.string().optional(),
order: z.enum(["asc", "desc"]).default("desc"),
sortBy: z.enum(["periodStart", "total"]).default("periodStart"),
+ type: z.nativeEnum(PayoutType).optional(),
})
.merge(getPaginationQuerySchema({ pageSize: PAYOUTS_MAX_PAGE_SIZE }));
@@ -73,9 +75,12 @@ export const PayoutSchema = z.object({
total: z.number(),
currency: z.string(),
status: z.nativeEnum(PayoutStatus),
+ type: z.nativeEnum(PayoutType),
+ description: z.string().nullish(),
periodStart: z.date(),
periodEnd: z.date(),
dotsTransferId: z.string().nullable(),
+ eventCount: z.number(),
createdAt: z.date(),
updatedAt: z.date(),
});
diff --git a/apps/web/prisma/schema/payout.prisma b/apps/web/prisma/schema/payout.prisma
index 2a7a2034ce..0557f386ad 100644
--- a/apps/web/prisma/schema/payout.prisma
+++ b/apps/web/prisma/schema/payout.prisma
@@ -4,6 +4,13 @@ enum PayoutStatus {
failed
}
+enum PayoutType {
+ clicks
+ leads
+ sales
+ custom
+}
+
model Payout {
id String @id @default(cuid())
programId String
@@ -13,8 +20,11 @@ model Payout {
total Int @default(0) // Total amount after fees (amount + fee)
currency String @default("USD")
status PayoutStatus @default(pending)
+ type PayoutType @default(sales)
+ description String?
periodStart DateTime
periodEnd DateTime
+ eventCount Int @default(0) // Number of clicks/leads/sales in this payout
dotsTransferId String? @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
diff --git a/apps/web/ui/partners/create-payout-sheet.tsx b/apps/web/ui/partners/create-payout-sheet.tsx
new file mode 100644
index 0000000000..9b4aedd21c
--- /dev/null
+++ b/apps/web/ui/partners/create-payout-sheet.tsx
@@ -0,0 +1,281 @@
+"use client";
+
+import { createManualPayoutAction } from "@/lib/actions/partners/create-manual-payout";
+import usePartners from "@/lib/swr/use-partners";
+import useProgram from "@/lib/swr/use-program";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { X } from "@/ui/shared/icons";
+import {
+ Button,
+ Combobox,
+ DateRangePicker,
+ Sheet,
+ useRouterStuff,
+} from "@dub/ui";
+import { cn } from "@dub/utils";
+import { PayoutType } from "@prisma/client";
+import { useAction } from "next-safe-action/hooks";
+import { Dispatch, SetStateAction, useId, useMemo, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { mutate } from "swr";
+
+interface CreatePayoutSheetProps {
+ setIsOpen: Dispatch<SetStateAction<boolean>>;
+}
+
+interface FormData {
+ dateRange: {
+ start: Date;
+ end: Date;
+ };
+ amount: number;
+ partnerId: string;
+ type: PayoutType;
+ description?: string;
+}
+
+function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
+ const dateRangePickerId = useId();
+ const { program } = useProgram();
+ const { data: partners } = usePartners();
+ const { id: workspaceId } = useWorkspace();
+
+ const today = new Date();
+
+ const { register, handleSubmit, watch, setValue } = useForm<FormData>({
+ defaultValues: {
+ dateRange: {
+ start: new Date(
+ today.getFullYear(),
+ today.getMonth(),
+ today.getDate() - 31,
+ ),
+ end: new Date(today.getFullYear(), today.getMonth(), today.getDate()),
+ },
+ },
+ });
+
+ const partnerId = watch("partnerId");
+ const dateRange = watch("dateRange");
+ const type = watch("type");
+ const partner = partners?.find((p) => p.id === partnerId);
+
+ const partnerOptions = useMemo(() => {
+ return partners?.map((partner) => ({
+ label: partner.name,
+ value: partner.id,
+ }));
+ }, [partners]);
+
+ // const searchParams = useMemo(() => {
+ // return partner?.link
+ // ? {
+ // workspaceId,
+ // event: "composite",
+ // start: dateRange.start.toISOString(),
+ // end: dateRange.end.toISOString(),
+ // linkId: partner?.link?.id,
+ // }
+ // : null;
+ // }, [partner?.link, dateRange.start, dateRange.end, workspaceId]);
+
+ // const { data: events } = useSWR<{
+ // [key in AnalyticsResponseOptions]: number;
+ // }>(searchParams ? `/api/analytics?${searchParams.toString()}` : null);
+
+ const { executeAsync, isExecuting } = useAction(createManualPayoutAction, {
+ onSuccess: async () => {
+ toast.success("Successfully created payout!");
+ setIsOpen(false);
+ mutate(
+ `/api/programs/${program?.id}/payouts?workspaceId=${workspaceId}&sortBy=periodStart&order=desc`,
+ );
+ },
+ onError({ error }) {
+ toast.error(error.serverError);
+ },
+ });
+
+ const onSubmit = async (data: FormData) => {
+ if (workspaceId && program) {
+ await executeAsync({
+ ...data,
+ workspaceId,
+ programId: program.id,
+ start: data.dateRange.start.toISOString(),
+ end: data.dateRange.end.toISOString(),
+ });
+ }
+ };
+
+ return (
+ <form onSubmit={handleSubmit(onSubmit)} className="flex h-full flex-col">
+ <div>
+ <div className="flex items-start justify-between border-b border-neutral-200 p-6">
+ <Sheet.Title className="text-xl font-semibold">
+ Create payout
+ </Sheet.Title>
+ <Sheet.Close asChild>
+ <Button
+ variant="outline"
+ icon={<X className="size-5" />}
+ className="h-auto w-fit p-1"
+ />
+ </Sheet.Close>
+ </div>
+ <div className="flex flex-col gap-3 p-6">
+ <div>
+ <Combobox
+ selected={
+ partnerOptions?.find((o) => o.value === partnerId) ?? null
+ }
+ setSelected={(option) => {
+ if (option) {
+ setValue("partnerId", option.value);
+ }
+ }}
+ options={partnerOptions}
+ caret={true}
+ placeholder="Select partners"
+ searchPlaceholder="Search..."
+ matchTriggerWidth
+ buttonProps={{
+ className: cn(
+ "w-full justify-start border-gray-300 px-3",
+ "data-[state=open]:ring-1 data-[state=open]:ring-gray-500 data-[state=open]:border-gray-500",
+ "focus:ring-1 focus:ring-gray-500 focus:border-gray-500 transition-none",
+ !partnerId && "text-gray-400",
+ ),
+ }}
+ />
+ </div>
+
+ <div className="flex flex-col gap-2">
+ <label
+ htmlFor={dateRangePickerId}
+ className="block text-sm font-medium text-gray-700"
+ >
+ Date Range
+ </label>
+ <DateRangePicker
+ id={dateRangePickerId}
+ onChange={(dateRange) => {
+ if (dateRange) {
+ setValue("dateRange", {
+ start: dateRange.from!,
+ end: dateRange.to!,
+ });
+ }
+ }}
+ value={{
+ from: dateRange.start,
+ to: dateRange.end,
+ }}
+ />
+ </div>
+
+ <div>
+ <label htmlFor="type" className="flex items-center space-x-2">
+ <h2 className="text-sm font-medium text-gray-900">Type</h2>
+ </label>
+ <select
+ {...register("type", { required: true })}
+ className="block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"
+ >
+ {Object.values(PayoutType).map((type) => (
+ <option key={type} value={type}>
+ {type.charAt(0).toUpperCase() + type.slice(1)}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {type !== "sales" && (
+ <div>
+ <label htmlFor="amount" className="flex items-center space-x-2">
+ <h2 className="text-sm font-medium text-gray-900">Amount</h2>
+ </label>
+ <div className="relative mt-2 rounded-md shadow-sm">
+ <input
+ {...register("amount", {
+ required: true,
+ setValueAs: (value) => Number(value),
+ })}
+ className="block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"
+ placeholder="500"
+ type="number"
+ autoComplete="off"
+ />
+ </div>
+ </div>
+ )}
+
+ <div>
+ <label
+ htmlFor="description"
+ className="flex items-center space-x-2"
+ >
+ <h2 className="text-sm font-medium text-gray-900">Description</h2>
+ </label>
+ <textarea
+ {...register("description")}
+ className="block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"
+ placeholder="A small internal note about this payout."
+ />
+ </div>
+ </div>
+ </div>
+
+ <div className="flex grow flex-col justify-end">
+ <div className="flex items-center justify-end gap-2 border-t border-neutral-200 p-5">
+ <Button
+ type="button"
+ variant="secondary"
+ onClick={() => setIsOpen(false)}
+ text="Cancel"
+ className="w-fit"
+ disabled={isExecuting}
+ />
+ <Button
+ type="submit"
+ variant="primary"
+ text="Create payout"
+ className="w-fit"
+ loading={isExecuting}
+ />
+ </div>
+ </div>
+ </form>
+ );
+}
+
+export function CreatePayoutSheet({
+ isOpen,
+ ...rest
+}: CreatePayoutSheetProps & {
+ isOpen: boolean;
+}) {
+ const { queryParams } = useRouterStuff();
+
+ return (
+ <Sheet
+ open={isOpen}
+ onOpenChange={rest.setIsOpen}
+ onClose={() => queryParams({ del: "partnerId" })}
+ >
+ <CreatePayoutSheetContent {...rest} />
+ </Sheet>
+ );
+}
+
+export function useCreatePayoutSheet() {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return {
+ createPayoutSheet: (
+ <CreatePayoutSheet setIsOpen={setIsOpen} isOpen={isOpen} />
+ ),
+ setIsOpen,
+ };
+}