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.

improve domain validation

Steven Teycc80219e7ea9
diff --git a/apps/web/app/(ee)/api/cron/domains/delete/route.ts b/apps/web/app/(ee)/api/cron/domains/delete/route.ts
index 1992c40edc..0831f2ab48 100644
--- a/apps/web/app/(ee)/api/cron/domains/delete/route.ts
+++ b/apps/web/app/(ee)/api/cron/domains/delete/route.ts
@@ -10,6 +10,7 @@ import { recordLink } from "@/lib/tinybird/record-link";
import { prisma } from "@dub/prisma";
import { R2_URL } from "@dub/utils";
import * as z from "zod/v4";
+import { logAndRespond } from "../../utils";
export const dynamic = "force-dynamic";
@@ -32,7 +33,7 @@ export async function POST(req: Request) {
});
if (!domainRecord) {
- return new Response(`Domain ${domain} not found. Skipping...`);
+ return logAndRespond(`Domain ${domain} not found. Skipping...`);
}
const links = await prisma.link.findMany({
@@ -51,55 +52,55 @@ export async function POST(req: Request) {
console.log(`Found ${links.length} links to delete`);
- if (links.length === 0) {
- return new Response("No more links to delete. Exiting...");
- }
-
- const response = await Promise.allSettled([
- // Remove the link from Redis
- linkCache.deleteMany(links),
-
- // Record link in Tinybird
- recordLink(links, { deleted: true }),
-
- // Remove image from R2 storage if it exists
- links
- .filter((link) => link.image?.startsWith(`${R2_URL}/images/${link.id}`))
- .map((link) =>
- limiter.schedule(() =>
- storage.delete({ key: link.image!.replace(`${R2_URL}/`, "") }),
+ if (links.length > 0) {
+ const response = await Promise.allSettled([
+ // Remove the link from Redis
+ linkCache.deleteMany(links),
+
+ // Record link in Tinybird
+ recordLink(links, { deleted: true }),
+
+ // Remove image from R2 storage if it exists
+ links
+ .filter((link) =>
+ link.image?.startsWith(`${R2_URL}/images/${link.id}`),
+ )
+ .map((link) =>
+ limiter.schedule(() =>
+ storage.delete({ key: link.image!.replace(`${R2_URL}/`, "") }),
+ ),
),
- ),
-
- // Remove the link from MySQL
- prisma.link.deleteMany({
- where: {
- id: { in: links.map((link) => link.id) },
- },
- }),
- // Update the project's total links count
- links[0].projectId &&
- prisma.project.update({
+ // Remove the link from MySQL
+ prisma.link.deleteMany({
where: {
- id: links[0].projectId,
- },
- data: {
- totalLinks: { decrement: links.length },
+ id: { in: links.map((link) => link.id) },
},
}),
- ]);
-
- console.log(response);
- response.forEach((promise) => {
- if (promise.status === "rejected") {
- console.error("deleteDomainAndLinks", {
- reason: promise.reason,
- domain,
- });
- }
- });
+ // Update the project's total links count
+ links[0].projectId &&
+ prisma.project.update({
+ where: {
+ id: links[0].projectId,
+ },
+ data: {
+ totalLinks: { decrement: links.length },
+ },
+ }),
+ ]);
+
+ console.log(response);
+
+ response.forEach((promise) => {
+ if (promise.status === "rejected") {
+ console.error("deleteDomainAndLinks", {
+ reason: promise.reason,
+ domain,
+ });
+ }
+ });
+ }
const remainingLinks = await prisma.link.count({
where: {
@@ -107,14 +108,14 @@ export async function POST(req: Request) {
},
});
- console.log("remainingLinks", remainingLinks);
+ console.log(`Found ${remainingLinks} remaining links for ${domain}.`);
if (remainingLinks > 0) {
await queueDomainDeletion({
domain,
delay: 2,
});
- return new Response(
+ return logAndRespond(
`Deleted ${links.length} links, ${remainingLinks} remaining. Starting next batch...`,
);
}
@@ -130,7 +131,7 @@ export async function POST(req: Request) {
storage.delete({ key: domainRecord.logo.replace(`${R2_URL}/`, "") }),
]);
- return new Response(
+ return logAndRespond(
`Deleted ${links.length} links, no more links remaining. Domain deleted.`,
);
} catch (error) {
diff --git a/apps/web/app/api/domains/[domain]/validate/route.ts b/apps/web/app/api/domains/[domain]/validate/route.ts
index 98a4e578a6..629706460e 100644
--- a/apps/web/app/api/domains/[domain]/validate/route.ts
+++ b/apps/web/app/api/domains/[domain]/validate/route.ts
@@ -14,6 +14,12 @@ export const GET = withSession(async ({ params }) => {
status: "invalid",
});
}
+ if (domain.startsWith("www.")) {
+ return NextResponse.json({
+ status: "invalid",
+ message: "Custom domain cannot start with www.",
+ });
+ }
const dubLinkError = validateDubLinkSubdomain(domain);
if (dubLinkError) {
return NextResponse.json({
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/[payoutId]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/[payoutId]/page-client.tsx
deleted file mode 100644
index a0ac81e61f..0000000000
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/[payoutId]/page-client.tsx
+++ /dev/null
@@ -1,553 +0,0 @@
-"use client";
-
-import { clientAccessCheck } from "@/lib/client-access-check";
-import { getPlanCapabilities } from "@/lib/plan-capabilities";
-import { useFraudGroupCount } from "@/lib/swr/use-fraud-groups-count";
-import { usePayout } from "@/lib/swr/use-payout";
-import useWorkspace from "@/lib/swr/use-workspace";
-import {
- CommissionResponse,
- FraudGroupCountByPartner,
- PayoutResponse,
-} from "@/lib/types";
-import { CustomerAvatar } from "@/ui/customers/customer-avatar";
-import { PageContent } from "@/ui/layout/page-content";
-import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
-import { ActivityEvent } from "@/ui/partners/activity-event";
-import { CommissionTypeIcon } from "@/ui/partners/comission-type-icon";
-import { CommissionRowMenu } from "@/ui/partners/commission-row-menu";
-import { CommissionTypeBadge } from "@/ui/partners/commission-type-badge";
-import { PartnerAvatar } from "@/ui/partners/partner-avatar";
-import { PayoutStatusBadges } from "@/ui/partners/payout-status-badges";
-import { ConditionalLink } from "@/ui/shared/conditional-link";
-import { UserAvatar } from "@/ui/users/user-avatar";
-import { PayoutStatus } from "@dub/prisma/client";
-import {
- Button,
- ChevronRight,
- CircleArrowRight,
- CopyText,
- MoneyBills2,
- StatusBadge,
- Table,
- TimestampTooltip,
- Tooltip,
- useKeyboardShortcut,
- usePagination,
- useTable,
-} from "@dub/ui";
-import {
- APP_DOMAIN,
- cn,
- currencyFormatter,
- fetcher,
- formatDateTime,
- formatDateTimeSmart,
- pluralize,
-} from "@dub/utils";
-import { formatPeriod } from "@dub/utils/src/functions/datetime";
-import Link from "next/link";
-import { redirect, useRouter } from "next/navigation";
-import { useMemo } from "react";
-import useSWR from "swr";
-
-type PayoutActivityItem = {
- status: keyof typeof PayoutStatusBadges;
- timestamp: string | Date | null;
- user?: PayoutResponse["user"];
-};
-
-export function PayoutDetailsPageClient() {
- const { slug, id: workspaceId } = useWorkspace();
- const { payout, loading, error } = usePayout();
- const router = useRouter();
-
- if (error?.status === 404) {
- redirect(`/${slug}/program/payouts`);
- }
-
- return (
- <PageContent
- title={
- loading ? (
- <div className="h-7 w-40 animate-pulse rounded-md bg-neutral-200" />
- ) : (
- <div className="flex items-center gap-1">
- <Link
- href={`/${slug}/program/payouts`}
- aria-label="Back to payouts"
- title="Back to payouts"
- className="bg-bg-subtle hover:bg-bg-emphasis flex size-8 shrink-0 items-center justify-center rounded-lg transition-[transform,background-color] duration-150 active:scale-95"
- >
- <MoneyBills2 className="size-4" />
- </Link>
- <div className="flex items-center gap-1.5">
- <ChevronRight className="text-content-subtle size-2.5 shrink-0 [&_*]:stroke-2" />
- <div className="flex items-center gap-2">
- {payout?.partner && (
- <PartnerAvatar
- partner={payout.partner}
- className="size-5 shrink-0"
- />
- )}
- <span className="text-lg font-semibold leading-7 text-neutral-900">
- {payout?.partner?.name ?? "Payout details"}
- </span>
- </div>
- </div>
- </div>
- )
- }
- controls={<PayoutConfirmButton />}
- >
- <PageWidthWrapper className="pb-10">
- {payout ? (
- <PayoutDetailsContent
- payout={payout}
- workspaceId={workspaceId!}
- slug={slug!}
- router={router}
- />
- ) : loading ? (
- <PayoutDetailsskeleton />
- ) : error ? (
- <div className="flex flex-col items-center justify-center gap-2 py-16 text-center">
- <p className="text-sm font-medium text-neutral-700">
- Failed to load payout
- </p>
- <p className="text-sm text-neutral-500">{error.message}</p>
- </div>
- ) : null}
- </PageWidthWrapper>
- </PageContent>
- );
-}
-
-function PayoutDetailsContent({
- payout,
- workspaceId,
- slug,
- router,
-}: {
- payout: NonNullable<ReturnType<typeof usePayout>["payout"]>;
- workspaceId: string;
- slug: string;
- router: ReturnType<typeof useRouter>;
-}) {
- const { pagination, setPagination } = usePagination(10);
-
- const {
- data: commissions,
- isLoading,
- error,
- } = useSWR<CommissionResponse[]>(
- `/api/commissions?${new URLSearchParams({
- workspaceId,
- payoutId: payout.id,
- interval: "all",
- page: String(pagination.pageIndex),
- pageSize: String(pagination.pageSize),
- })}`,
- fetcher,
- { keepPreviousData: true },
- );
-
- const { data: commissionsCount } = useSWR<{ all: { count: number } }>(
- `/api/commissions/count?${new URLSearchParams({
- workspaceId,
- payoutId: payout.id,
- interval: "all",
- })}`,
- fetcher,
- );
-
- const invoiceData = useMemo(() => {
- const statusBadge = PayoutStatusBadges[payout.status];
-
- return {
- Partner: (
- <ConditionalLink
- href={`/${slug}/program/partners/${payout.partner.id}`}
- className="flex min-w-0 items-center gap-1.5 text-neutral-500"
- >
- <PartnerAvatar
- partner={payout.partner}
- className="mt-px size-5 shrink-0"
- />
- <span className="truncate leading-5">{payout.partner.name}</span>
- </ConditionalLink>
- ),
-
- Period: formatPeriod({
- periodStart: payout.periodStart ? new Date(payout.periodStart) : null,
- periodEnd: payout.periodEnd ? new Date(payout.periodEnd) : null,
- }),
-
- Status: (
- <StatusBadge variant={statusBadge.variant} icon={statusBadge.icon}>
- {statusBadge.label}
- </StatusBadge>
- ),
-
- Initiated: payout.initiatedAt ? (
- <TimestampTooltip
- timestamp={payout.initiatedAt}
- side="left"
- rows={["local", "utc"]}
- >
- <span className="hover:text-content-emphasis underline decoration-dotted underline-offset-2">
- {formatDateTimeSmart(payout.initiatedAt)}
- </span>
- </TimestampTooltip>
- ) : (
- "-"
- ),
-
- Paid: payout.paidAt ? (
- <TimestampTooltip
- timestamp={payout.paidAt}
- side="left"
- rows={["local", "utc"]}
- >
- <span className="hover:text-content-emphasis underline decoration-dotted underline-offset-2">
- {formatDateTimeSmart(payout.paidAt)}
- </span>
- </TimestampTooltip>
- ) : (
- "-"
- ),
-
- Amount: (
- <div className="flex items-center gap-2">
- {currencyFormatter(payout.amount)}
-
- {payout.mode === "external" && (
- <Tooltip
- content={
- payout.status === PayoutStatus.pending
- ? `This payout will be made externally through the partner's account after approval.`
- : `This payout was made externally through the partner's account.`
- }
- >
- <CircleArrowRight className="size-3.5 shrink-0 text-neutral-500" />
- </Tooltip>
- )}
- </div>
- ),
-
- ...(payout.invoiceId &&
- payout.mode === "internal" &&
- payout.status !== "failed" && {
- Invoice: (
- <ConditionalLink
- href={`${APP_DOMAIN}/invoices/${payout.invoiceId}`}
- target="_blank"
- className="max-w-xs truncate"
- >
- {payout.invoiceId}
- </ConditionalLink>
- ),
- }),
-
- ...(payout.description && {
- Description: payout.description,
- }),
-
- ...(payout.traceId && {
- "Trace ID": (
- <CopyText
- value={payout.traceId}
- className="block w-full truncate text-left font-mono text-xs text-neutral-500"
- >
- {payout.traceId}
- </CopyText>
- ),
- }),
- };
- }, [payout, slug]);
-
- const activityItems = useMemo(() => {
- const items: PayoutActivityItem[] = [
- { status: "pending", timestamp: payout.createdAt },
- ];
-
- if (payout.initiatedAt) {
- items.push({
- status: "processed",
- timestamp: payout.initiatedAt,
- user: payout.user,
- });
- }
-
- const terminalStatuses = [
- "completed",
- "sent",
- "failed",
- "canceled",
- "hold",
- ] as const;
- const terminalStatus = terminalStatuses.find((s) => s === payout.status);
-
- if (terminalStatus) {
- const timestamp = payout.paidAt ?? payout.updatedAt ?? null;
- items.push({ status: terminalStatus, timestamp });
- }
-
- return items.reverse();
- }, [payout]);
-
- const commissionsTable = useTable({
- data:
- commissions?.filter(
- ({ status }) => !["duplicate", "fraud"].includes(status),
- ) || [],
- columns: [
- {
- header: "Details",
- minSize: 300,
- size: 9999,
- cell: ({ row }) => (
- <div className="flex items-center gap-2">
- {["click", "custom"].includes(row.original.type) ||
- !row.original.customer ? (
- <div className="flex size-6 items-center justify-center rounded-full bg-neutral-100">
- <CommissionTypeIcon
- type={row.original.type}
- className="size-4"
- />
- </div>
- ) : (
- <CustomerAvatar
- customer={row.original.customer}
- className="size-6"
- />
- )}
-
- <div className="flex flex-col">
- {row.original.customer ? (
- <Link
- href={`/${slug}/program/customers/${row.original.customer.id}`}
- onClick={(e) => e.stopPropagation()}
- className="max-w-xs truncate text-sm text-neutral-700 hover:underline"
- >
- {row.original.customer.email || row.original.customer.name}
- </Link>
- ) : (
- <span className="max-w-xs truncate text-sm text-neutral-700">
- {row.original.type === "click"
- ? `${row.original.quantity} ${pluralize("click", row.original.quantity)}`
- : "Custom commission"}
- </span>
- )}
- <span className="text-xs text-neutral-500">
- {formatDateTime(row.original.createdAt)}
- </span>
- </div>
- </div>
- ),
- },
- {
- id: "type",
- header: "Type",
- minSize: 150,
- size: 150,
- maxSize: 150,
- cell: ({ row }) => (
- <CommissionTypeBadge type={row.original.type ?? "sale"} />
- ),
- },
- {
- id: "total",
- header: "Total",
- minSize: 120,
- size: 120,
- maxSize: 120,
- cell: ({ row }) => currencyFormatter(row.original.earnings),
- },
- {
- id: "menu",
- enableHiding: false,
- minSize: 48,
- size: 48,
- cell: ({ row }) => <CommissionRowMenu row={row} />,
- },
- ],
- columnPinning: { right: ["menu"] },
- onRowClick: (row, e) => {
- const url = `/${slug}/program/commissions/${row.original.id}`;
- if (e.metaKey || e.ctrlKey) window.open(url, "_blank");
- else router.push(url);
- },
- onRowAuxClick: (row) =>
- window.open(`/${slug}/program/commissions/${row.original.id}`, "_blank"),
- rowProps: (row) => ({
- onPointerEnter: () =>
- router.prefetch(`/${slug}/program/commissions/${row.original.id}`),
- }),
- thClassName: (id) =>
- cn(id === "menu" && "[&>div]:justify-end", "border-l-0"),
- tdClassName: (id) => cn(id === "menu" && "text-right", "border-l-0"),
- className: "[&_tr:last-child>td]:border-b-transparent",
- scrollWrapperClassName: "min-h-[40px]",
- resourceName: (p) => `commission${p ? "s" : ""}`,
- pagination,
- paginationAllRowsHref: `/${slug}/program/commissions?payoutId=${payout.id}&interval=all`,
- onPaginationChange: setPagination,
- rowCount: commissionsCount?.all?.count ?? commissions?.length ?? 0,
- loading: isLoading,
- error: error ? "Failed to load commissions" : undefined,
- } as any);
-
- return (
- <div className="flex flex-col gap-6 lg:flex-row">
- <div className="order-last min-w-0 flex-1 lg:order-first">
- <Table {...commissionsTable} />
-
- <div className="mt-6">
- <h3 className="mb-4 text-base font-medium text-neutral-900">
- Activity
- </h3>
- <div className="flex flex-col">
- {activityItems.map((item, index) => {
- const badge = PayoutStatusBadges[item.status];
-
- return (
- <ActivityEvent
- key={index}
- icon={badge.icon}
- timestamp={item.timestamp}
- isLast={index === activityItems.length - 1}
- >
- <span className="text-sm text-neutral-700">Payout</span>
- <StatusBadge variant={badge.variant} icon={null}>
- {badge.label}
- </StatusBadge>
- {item.user && (
- <>
- <span className="text-sm text-neutral-500">by</span>
- <div className="flex h-6 items-center gap-2 rounded-lg bg-neutral-100 px-2 py-1">
- <UserAvatar user={item.user} className="size-4" />
- <span className="text-[13px] text-sm text-neutral-700">
- {item.user.name}
- </span>
- </div>
- </>
- )}
- </ActivityEvent>
- );
- })}
- </div>
- </div>
- </div>
-
- <div className="order-first w-full shrink-0 lg:order-last lg:w-[360px]">
- <div className="rounded-xl border border-neutral-200 bg-white p-4">
- <h3 className="text-content-emphasis mb-2 text-base font-semibold">
- Invoice details
- </h3>
- <div className="flex flex-col gap-1">
- {Object.entries(invoiceData).map(([key, value]) => (
- <div
- key={key}
- className="flex items-center gap-4 rounded-md py-1"
- >
- <div className="w-20 shrink-0 text-xs font-medium text-neutral-700">
- {key}
- </div>
- <div className="flex min-w-0 flex-1 items-center text-xs font-medium text-neutral-500">
- {value}
- </div>
- </div>
- ))}
- </div>
- </div>
- </div>
- </div>
- );
-}
-
-function PayoutDetailsskeleton() {
- return (
- <div className="flex flex-col gap-6 lg:flex-row">
- <div className="order-last min-w-0 flex-1 lg:order-first">
- <div className="h-64 animate-pulse rounded-xl border border-neutral-200 bg-neutral-100" />
- <div className="mt-6 h-32 animate-pulse rounded-xl border border-neutral-200 bg-neutral-100" />
- </div>
- <div className="order-first w-full shrink-0 lg:order-last lg:w-[360px]">
- <div className="h-80 animate-pulse rounded-xl border border-neutral-200 bg-neutral-100" />
- </div>
- </div>
- );
-}
-
-function PayoutConfirmButton() {
- const { slug, role, plan } = useWorkspace();
- const { payout } = usePayout();
- const router = useRouter();
-
- const { canManageFraudEvents } = getPlanCapabilities(plan);
-
- const { fraudGroupCount } = useFraudGroupCount<FraudGroupCountByPartner[]>({
- ignoreParams: true,
- enabled: !!payout?.partner?.id,
- query: {
- groupBy: "partnerId",
- status: "pending",
- ...(payout?.partner?.id && { partnerId: payout.partner.id }),
- },
- });
-
- const hasHold =
- payout?.status === "pending" &&
- canManageFraudEvents &&
- (fraudGroupCount?.length ?? 0) > 0;
-
- const { error: _permissionsError } = clientAccessCheck({
- action: "payouts.write",
- role,
- });
-
- const permissionsError =
- typeof _permissionsError === "string" ? _permissionsError : null;
-
- useKeyboardShortcut(
- "c",
- () =>
- router.push(
- `/${slug}/program/payouts?confirmPayouts=true&selectedPayoutId=${payout?.id}`,
- ),
- {
- enabled:
- !hasHold &&
- !!payout?.id &&
- !!payout.partner.payoutsEnabledAt &&
- !permissionsError,
- },
- );
-
- if (payout?.status !== "pending") {
- return null;
- }
-
- return (
- <div className="flex items-center gap-2">
- <Button
- text="Confirm payout"
- className="h-8 px-3 sm:h-9"
- shortcut="C"
- disabledTooltip={
- hasHold
- ? `This partner's payouts are on hold due to [unresolved fraud events](${APP_DOMAIN}/${slug}/program/fraud?partnerId=${payout.partner.id}). They cannot be paid out until resolved.`
- : !payout.partner.payoutsEnabledAt
- ? "This partner has not [connected a bank account](https://dub.co/help/article/receiving-payouts) to receive payouts yet, which means they won't be able to receive payouts from your program."
- : permissionsError || undefined
- }
- onClick={() => {
- router.push(
- `/${slug}/program/payouts?confirmPayouts=true&selectedPayoutId=${payout.id}`,
- );
- }}
- />
- </div>
- );
-}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/[payoutId]/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/[payoutId]/page.tsx
index 4e165296c9..bcecd41071 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/[payoutId]/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/[payoutId]/page.tsx
@@ -1,5 +1,553 @@
-import { PayoutDetailsPageClient } from "./page-client";
+"use client";
+
+import { clientAccessCheck } from "@/lib/client-access-check";
+import { getPlanCapabilities } from "@/lib/plan-capabilities";
+import { useFraudGroupCount } from "@/lib/swr/use-fraud-groups-count";
+import { usePayout } from "@/lib/swr/use-payout";
+import useWorkspace from "@/lib/swr/use-workspace";
+import {
+ CommissionResponse,
+ FraudGroupCountByPartner,
+ PayoutResponse,
+} from "@/lib/types";
+import { CustomerAvatar } from "@/ui/customers/customer-avatar";
+import { PageContent } from "@/ui/layout/page-content";
+import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
+import { ActivityEvent } from "@/ui/partners/activity-event";
+import { CommissionTypeIcon } from "@/ui/partners/comission-type-icon";
+import { CommissionRowMenu } from "@/ui/partners/commission-row-menu";
+import { CommissionTypeBadge } from "@/ui/partners/commission-type-badge";
+import { PartnerAvatar } from "@/ui/partners/partner-avatar";
+import { PayoutStatusBadges } from "@/ui/partners/payout-status-badges";
+import { ConditionalLink } from "@/ui/shared/conditional-link";
+import { UserAvatar } from "@/ui/users/user-avatar";
+import { PayoutStatus } from "@dub/prisma/client";
+import {
+ Button,
+ ChevronRight,
+ CircleArrowRight,
+ CopyText,
+ MoneyBills2,
+ StatusBadge,
+ Table,
+ TimestampTooltip,
+ Tooltip,
+ useKeyboardShortcut,
+ usePagination,
+ useTable,
+} from "@dub/ui";
+import {
+ APP_DOMAIN,
+ cn,
+ currencyFormatter,
+ fetcher,
+ formatDateTime,
+ formatDateTimeSmart,
+ pluralize,
+} from "@dub/utils";
+import { formatPeriod } from "@dub/utils/src/functions/datetime";
+import Link from "next/link";
+import { redirect, useRouter } from "next/navigation";
+import { useMemo } from "react";
+import useSWR from "swr";
+
+type PayoutActivityItem = {
+ status: keyof typeof PayoutStatusBadges;
+ timestamp: string | Date | null;
+ user?: PayoutResponse["user"];
+};
export default function PayoutDetailsPage() {
- return <PayoutDetailsPageClient />;
+ const { slug, id: workspaceId } = useWorkspace();
+ const { payout, loading, error } = usePayout();
+ const router = useRouter();
+
+ if (error?.status === 404) {
+ redirect(`/${slug}/program/payouts`);
+ }
+
+ return (
+ <PageContent
+ title={
+ loading ? (
+ <div className="h-7 w-40 animate-pulse rounded-md bg-neutral-200" />
+ ) : (
+ <div className="flex items-center gap-1">
+ <Link
+ href={`/${slug}/program/payouts?status=pending`}
+ aria-label="Back to payouts"
+ title="Back to payouts"
+ className="bg-bg-subtle hover:bg-bg-emphasis flex size-8 shrink-0 items-center justify-center rounded-lg transition-[transform,background-color] duration-150 active:scale-95"
+ >
+ <MoneyBills2 className="size-4" />
+ </Link>
+ <div className="flex items-center gap-1.5">
+ <ChevronRight className="text-content-subtle size-2.5 shrink-0 [&_*]:stroke-2" />
+ <div className="flex items-center gap-2">
+ {payout?.partner && (
+ <PartnerAvatar
+ partner={payout.partner}
+ className="size-5 shrink-0"
+ />
+ )}
+ <span className="text-lg font-semibold leading-7 text-neutral-900">
+ {payout?.partner?.name ?? "Payout details"}
+ </span>
+ </div>
+ </div>
+ </div>
+ )
+ }
+ controls={<PayoutConfirmButton />}
+ >
+ <PageWidthWrapper className="pb-10">
+ {payout ? (
+ <PayoutDetailsContent
+ payout={payout}
+ workspaceId={workspaceId!}
+ slug={slug!}
+ router={router}
+ />
+ ) : loading ? (
+ <PayoutDetailsskeleton />
+ ) : error ? (
+ <div className="flex flex-col items-center justify-center gap-2 py-16 text-center">
+ <p className="text-sm font-medium text-neutral-700">
+ Failed to load payout
+ </p>
+ <p className="text-sm text-neutral-500">{error.message}</p>
+ </div>
+ ) : null}
+ </PageWidthWrapper>
+ </PageContent>
+ );
+}
+
+function PayoutDetailsContent({
+ payout,
+ workspaceId,
+ slug,
+ router,
+}: {
+ payout: NonNullable<ReturnType<typeof usePayout>["payout"]>;
+ workspaceId: string;
+ slug: string;
+ router: ReturnType<typeof useRouter>;
+}) {
+ const { pagination, setPagination } = usePagination(10);
+
+ const {
+ data: commissions,
+ isLoading,
+ error,
+ } = useSWR<CommissionResponse[]>(
+ `/api/commissions?${new URLSearchParams({
+ workspaceId,
+ payoutId: payout.id,
+ interval: "all",
+ page: String(pagination.pageIndex),
+ pageSize: String(pagination.pageSize),
+ })}`,
+ fetcher,
+ { keepPreviousData: true },
+ );
+
+ const { data: commissionsCount } = useSWR<{ all: { count: number } }>(
+ `/api/commissions/count?${new URLSearchParams({
+ workspaceId,
+ payoutId: payout.id,
+ interval: "all",
+ })}`,
+ fetcher,
+ );
+
+ const invoiceData = useMemo(() => {
+ const statusBadge = PayoutStatusBadges[payout.status];
+
+ return {
+ Partner: (
+ <ConditionalLink
+ href={`/${slug}/program/partners/${payout.partner.id}`}
+ className="flex min-w-0 items-center gap-1.5 text-neutral-500"
+ >
+ <PartnerAvatar
+ partner={payout.partner}
+ className="mt-px size-5 shrink-0"
+ />
+ <span className="truncate leading-5">{payout.partner.name}</span>
+ </ConditionalLink>
+ ),
+
+ Period: formatPeriod({
+ periodStart: payout.periodStart ? new Date(payout.periodStart) : null,
+ periodEnd: payout.periodEnd ? new Date(payout.periodEnd) : null,
+ }),
+
+ Status: (
+ <StatusBadge variant={statusBadge.variant} icon={statusBadge.icon}>
+ {statusBadge.label}
+ </StatusBadge>
+ ),
+
+ Initiated: payout.initiatedAt ? (
+ <TimestampTooltip
+ timestamp={payout.initiatedAt}
+ side="left"
+ rows={["local", "utc"]}
+ >
+ <span className="hover:text-content-emphasis underline decoration-dotted underline-offset-2">
+ {formatDateTimeSmart(payout.initiatedAt)}
+ </span>
+ </TimestampTooltip>
+ ) : (
+ "-"
+ ),
+
+ Paid: payout.paidAt ? (
+ <TimestampTooltip
+ timestamp={payout.paidAt}
+ side="left"
+ rows={["local", "utc"]}
+ >
+ <span className="hover:text-content-emphasis underline decoration-dotted underline-offset-2">
+ {formatDateTimeSmart(payout.paidAt)}
+ </span>
+ </TimestampTooltip>
+ ) : (
+ "-"
+ ),
+
+ Amount: (
+ <div className="flex items-center gap-2">
+ {currencyFormatter(payout.amount)}
+
+ {payout.mode === "external" && (
+ <Tooltip
+ content={
+ payout.status === PayoutStatus.pending
+ ? `This payout will be made externally through the partner's account after approval.`
+ : `This payout was made externally through the partner's account.`
+ }
+ >
+ <CircleArrowRight className="size-3.5 shrink-0 text-neutral-500" />
+ </Tooltip>
+ )}
+ </div>
+ ),
+
+ ...(payout.invoiceId &&
+ payout.mode === "internal" &&
+ payout.status !== "failed" && {
+ Invoice: (
+ <ConditionalLink
+ href={`${APP_DOMAIN}/invoices/${payout.invoiceId}`}
+ target="_blank"
+ className="max-w-xs truncate"
+ >
+ {payout.invoiceId}
+ </ConditionalLink>
+ ),
+ }),
+
+ ...(payout.description && {
+ Description: payout.description,
+ }),
+
+ ...(payout.traceId && {
+ "Trace ID": (
+ <CopyText
+ value={payout.traceId}
+ className="block w-full truncate text-left font-mono text-xs text-neutral-500"
+ >
+ {payout.traceId}
+ </CopyText>
+ ),
+ }),
+ };
+ }, [payout, slug]);
+
+ const activityItems = useMemo(() => {
+ const items: PayoutActivityItem[] = [
+ { status: "pending", timestamp: payout.createdAt },
+ ];
+
+ if (payout.initiatedAt) {
+ items.push({
+ status: "processed",
+ timestamp: payout.initiatedAt,
+ user: payout.user,
+ });
+ }
+
+ const terminalStatuses = [
+ "completed",
+ "sent",
+ "failed",
+ "canceled",
+ "hold",
+ ] as const;
+ const terminalStatus = terminalStatuses.find((s) => s === payout.status);
+
+ if (terminalStatus) {
+ const timestamp = payout.paidAt ?? payout.updatedAt ?? null;
+ items.push({ status: terminalStatus, timestamp });
+ }
+
+ return items.reverse();
+ }, [payout]);
+
+ const commissionsTable = useTable({
+ data:
+ commissions?.filter(
+ ({ status }) => !["duplicate", "fraud"].includes(status),
+ ) || [],
+ columns: [
+ {
+ header: "Details",
+ minSize: 300,
+ size: 9999,
+ cell: ({ row }) => (
+ <div className="flex items-center gap-2">
+ {["click", "custom"].includes(row.original.type) ||
+ !row.original.customer ? (
+ <div className="flex size-6 items-center justify-center rounded-full bg-neutral-100">
+ <CommissionTypeIcon
+ type={row.original.type}
+ className="size-4"
+ />
+ </div>
+ ) : (
+ <CustomerAvatar
+ customer={row.original.customer}
+ className="size-6"
+ />
+ )}
+
+ <div className="flex flex-col">
+ {row.original.customer ? (
+ <Link
+ href={`/${slug}/program/customers/${row.original.customer.id}`}
+ onClick={(e) => e.stopPropagation()}
+ className="max-w-xs truncate text-sm text-neutral-700 hover:underline"
+ >
+ {row.original.customer.email || row.original.customer.name}
+ </Link>
+ ) : (
+ <span className="max-w-xs truncate text-sm text-neutral-700">
+ {row.original.type === "click"
+ ? `${row.original.quantity} ${pluralize("click", row.original.quantity)}`
+ : "Custom commission"}
+ </span>
+ )}
+ <span className="text-xs text-neutral-500">
+ {formatDateTime(row.original.createdAt)}
+ </span>
+ </div>
+ </div>
+ ),
+ },
+ {
+ id: "type",
+ header: "Type",
+ minSize: 150,
+ size: 150,
+ maxSize: 150,
+ cell: ({ row }) => (
+ <CommissionTypeBadge type={row.original.type ?? "sale"} />
+ ),
+ },
+ {
+ id: "total",
+ header: "Total",
+ minSize: 120,
+ size: 120,
+ maxSize: 120,
+ cell: ({ row }) => currencyFormatter(row.original.earnings),
+ },
+ {
+ id: "menu",
+ enableHiding: false,
+ minSize: 48,
+ size: 48,
+ cell: ({ row }) => <CommissionRowMenu row={row} />,
+ },
+ ],
+ columnPinning: { right: ["menu"] },
+ onRowClick: (row, e) => {
+ const url = `/${slug}/program/commissions/${row.original.id}`;
+ if (e.metaKey || e.ctrlKey) window.open(url, "_blank");
+ else router.push(url);
+ },
+ onRowAuxClick: (row) =>
+ window.open(`/${slug}/program/commissions/${row.original.id}`, "_blank"),
+ rowProps: (row) => ({
+ onPointerEnter: () =>
+ router.prefetch(`/${slug}/program/commissions/${row.original.id}`),
+ }),
+ thClassName: (id) =>
+ cn(id === "menu" && "[&>div]:justify-end", "border-l-0"),
+ tdClassName: (id) => cn(id === "menu" && "text-right", "border-l-0"),
+ className: "[&_tr:last-child>td]:border-b-transparent",
+ scrollWrapperClassName: "min-h-[40px]",
+ resourceName: (p) => `commission${p ? "s" : ""}`,
+ pagination,
+ paginationAllRowsHref: `/${slug}/program/commissions?payoutId=${payout.id}&interval=all`,
+ onPaginationChange: setPagination,
+ rowCount: commissionsCount?.all?.count ?? commissions?.length ?? 0,
+ loading: isLoading,
+ error: error ? "Failed to load commissions" : undefined,
+ } as any);
+
+ return (
+ <div className="flex flex-col gap-6 lg:flex-row">
+ <div className="order-last min-w-0 flex-1 lg:order-first">
+ <Table {...commissionsTable} />
+
+ <div className="mt-6">
+ <h3 className="mb-4 text-base font-medium text-neutral-900">
+ Activity
+ </h3>
+ <div className="flex flex-col">
+ {activityItems.map((item, index) => {
+ const badge = PayoutStatusBadges[item.status];
+
+ return (
+ <ActivityEvent
+ key={index}
+ icon={badge.icon}
+ timestamp={item.timestamp}
+ isLast={index === activityItems.length - 1}
+ >
+ <span className="text-sm text-neutral-700">Payout</span>
+ <StatusBadge variant={badge.variant} icon={null}>
+ {badge.label}
+ </StatusBadge>
+ {item.user && (
+ <>
+ <span className="text-sm text-neutral-500">by</span>
+ <div className="flex h-6 items-center gap-2 rounded-lg bg-neutral-100 px-2 py-1">
+ <UserAvatar user={item.user} className="size-4" />
+ <span className="text-[13px] text-sm text-neutral-700">
+ {item.user.name}
+ </span>
+ </div>
+ </>
+ )}
+ </ActivityEvent>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+
+ <div className="order-first w-full shrink-0 lg:order-last lg:w-[360px]">
+ <div className="rounded-xl border border-neutral-200 bg-white p-4">
+ <h3 className="text-content-emphasis mb-2 text-base font-semibold">
+ Invoice details
+ </h3>
+ <div className="flex flex-col gap-1">
+ {Object.entries(invoiceData).map(([key, value]) => (
+ <div
+ key={key}
+ className="flex items-center gap-4 rounded-md py-1"
+ >
+ <div className="w-20 shrink-0 text-xs font-medium text-neutral-700">
+ {key}
+ </div>
+ <div className="flex min-w-0 flex-1 items-center text-xs font-medium text-neutral-500">
+ {value}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function PayoutDetailsskeleton() {
+ return (
+ <div className="flex flex-col gap-6 lg:flex-row">
+ <div className="order-last min-w-0 flex-1 lg:order-first">
+ <div className="h-64 animate-pulse rounded-xl border border-neutral-200 bg-neutral-100" />
+ <div className="mt-6 h-32 animate-pulse rounded-xl border border-neutral-200 bg-neutral-100" />
+ </div>
+ <div className="order-first w-full shrink-0 lg:order-last lg:w-[360px]">
+ <div className="h-80 animate-pulse rounded-xl border border-neutral-200 bg-neutral-100" />
+ </div>
+ </div>
+ );
+}
+
+function PayoutConfirmButton() {
+ const { slug, role, plan } = useWorkspace();
+ const { payout } = usePayout();
+ const router = useRouter();
+
+ const { canManageFraudEvents } = getPlanCapabilities(plan);
+
+ const { fraudGroupCount } = useFraudGroupCount<FraudGroupCountByPartner[]>({
+ ignoreParams: true,
+ enabled: !!payout?.partner?.id,
+ query: {
+ groupBy: "partnerId",
+ status: "pending",
+ ...(payout?.partner?.id && { partnerId: payout.partner.id }),
+ },
+ });
+
+ const hasHold =
+ payout?.status === "pending" &&
+ canManageFraudEvents &&
+ (fraudGroupCount?.length ?? 0) > 0;
+
+ const { error: _permissionsError } = clientAccessCheck({
+ action: "payouts.write",
+ role,
+ });
+
+ const permissionsError =
+ typeof _permissionsError === "string" ? _permissionsError : null;
+
+ useKeyboardShortcut(
+ "c",
+ () =>
+ router.push(
+ `/${slug}/program/payouts?confirmPayouts=true&selectedPayoutId=${payout?.id}`,
+ ),
+ {
+ enabled:
+ !hasHold &&
+ !!payout?.id &&
+ !!payout.partner.payoutsEnabledAt &&
+ !permissionsError,
+ },
+ );
+
+ if (payout?.status !== "pending") {
+ return null;
+ }
+
+ return (
+ <div className="flex items-center gap-2">
+ <Button
+ text="Confirm payout"
+ className="h-8 px-3 sm:h-9"
+ shortcut="C"
+ disabledTooltip={
+ hasHold
+ ? `This partner's payouts are on hold due to [unresolved fraud events](${APP_DOMAIN}/${slug}/program/fraud?partnerId=${payout.partner.id}). They cannot be paid out until resolved.`
+ : !payout.partner.payoutsEnabledAt
+ ? "This partner has not [connected a bank account](https://dub.co/help/article/receiving-payouts) to receive payouts yet, which means they won't be able to receive payouts from your program."
+ : permissionsError || undefined
+ }
+ onClick={() => {
+ router.push(
+ `/${slug}/program/payouts?confirmPayouts=true&selectedPayoutId=${payout.id}`,
+ );
+ }}
+ />
+ </div>
+ );
}
diff --git a/apps/web/lib/api/domains/utils.ts b/apps/web/lib/api/domains/utils.ts
index 7a2bf30e5f..378e3479e8 100644
--- a/apps/web/lib/api/domains/utils.ts
+++ b/apps/web/lib/api/domains/utils.ts
@@ -12,6 +12,12 @@ export const validateDomain = async (
if (!isValidDomain(domain)) {
return { error: "Invalid domain", code: "unprocessable_entity" };
}
+ if (domain.startsWith("www.")) {
+ return {
+ error: "Custom domain cannot start with www.",
+ code: "unprocessable_entity",
+ };
+ }
const dubLinkError = validateDubLinkSubdomain(domain);
if (dubLinkError) {
return dubLinkError;