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 the partner Overview and Programs pages (#4682)

Rafic3332c054ed2
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/route.ts
index b4ccf97e9a..d2a5406a1a 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/route.ts
@@ -1,3 +1,4 @@
+import { getProgramEnrollmentInactiveDates } from "@/lib/api/partner-profile/get-program-enrollment-inactive-dates";
import { getProgramEnrollmentsWhere } from "@/lib/api/partner-profile/get-program-enrollments-where";
import { withPartnerProfile } from "@/lib/auth/partner";
import { prisma } from "@/lib/prisma";
@@ -42,6 +43,7 @@ const PROGRAM_SELECT = {
export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
const {
includeRewardsDiscounts,
+ includeInactiveDates,
status,
search,
sortBy,
@@ -105,9 +107,16 @@ export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
}),
});
+ const inactiveDates = await getProgramEnrollmentInactiveDates({
+ partnerId: partner.id,
+ programEnrollments,
+ includeStatusLogs: includeInactiveDates ?? false,
+ });
+
const response = programEnrollments.map((enrollment) => {
return {
...enrollment,
+ inactiveAt: inactiveDates.get(enrollment.programId) ?? null,
rewards: includeRewardsDiscounts
? [
enrollment.clickReward,
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/overview-card.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/overview-card.tsx
index 7e06bab23a..0ccea56b39 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/overview-card.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/overview-card.tsx
@@ -59,7 +59,7 @@ export function OverviewCardList<T>({
}: {
items?: T[];
rowCount: number;
- renderItem: (item: T) => ReactNode;
+ renderItem: (item: T, index: number) => ReactNode;
getKey: (item: T) => string;
error?: unknown;
emptyState: { icon: ReactNode; title: string };
@@ -95,7 +95,7 @@ export function OverviewCardList<T>({
<div className="h-px bg-neutral-100" />
</div>
)}
- {renderItem(item)}
+ {renderItem(item, idx)}
</Fragment>
))}
</div>
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/page.tsx
index 1066b70900..1464f508ec 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/page.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/page.tsx
@@ -15,30 +15,37 @@ import { TopProgramsCard } from "./top-programs-card";
export default function PartnerOverviewPage() {
return (
<PageContent title="Overview">
- <PageWidthWrapper className="flex flex-col gap-4 pb-10">
- <SimpleDateRangePicker
- className="w-full sm:w-fit"
- align="start"
- defaultInterval={DUB_PARTNERS_ANALYTICS_INTERVAL}
- />
- <div className="rounded-2xl bg-neutral-50 p-4">
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-[minmax(0,1fr)_397px]">
- <EarningsChart />
- <div className="flex h-full flex-col gap-3">
- <div
- data-testid={testIds.partnerOverview.recentPayouts}
- className="flex min-h-0 flex-1 flex-col"
- >
- <PayoutsCard className="h-full min-h-0 flex-1" />
+ <PageWidthWrapper className="pb-10">
+ {/* below a 64rem page width, the wrappers are `contents`, so that every card is a cell of this grid and `order` moves Recent payouts, Tasks and Top links below Recent earnings */}
+ <div className="@3xl/page:grid-cols-2 @5xl/page:grid-cols-1 grid grid-cols-1 gap-4">
+ <div className="col-span-full">
+ <SimpleDateRangePicker
+ className="w-full sm:w-fit"
+ align="start"
+ defaultInterval={DUB_PARTNERS_ANALYTICS_INTERVAL}
+ />
+ </div>
+ <div className="@5xl/page:block @5xl/page:rounded-2xl @5xl/page:bg-neutral-50 @5xl/page:p-4 contents">
+ <div className="@5xl/page:grid @5xl/page:grid-cols-[minmax(0,1fr)_397px] @5xl/page:gap-4 contents">
+ <div className="@5xl/page:contents col-span-full rounded-2xl bg-neutral-50 p-4">
+ <EarningsChart />
+ </div>
+ <div className="@5xl/page:flex @5xl/page:h-full @5xl/page:flex-col @5xl/page:gap-3 contents">
+ <div
+ data-testid={testIds.partnerOverview.recentPayouts}
+ className="order-1 flex min-h-0 flex-1 flex-col"
+ >
+ <PayoutsCard className="h-full min-h-0 flex-1" />
+ </div>
+ <TasksCard className="order-1" />
</div>
- <TasksCard />
</div>
</div>
- </div>
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
- <TopProgramsCard />
- <RecentEarningsCard />
- <TopLinksCard />
+ <div className="@5xl/page:grid @5xl/page:grid-cols-3 @5xl/page:gap-4 contents">
+ <TopProgramsCard />
+ <RecentEarningsCard />
+ <TopLinksCard className="order-1" />
+ </div>
</div>
</PageWidthWrapper>
</PageContent>
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/tasks-card.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/tasks-card.tsx
index bd5fd81384..8a732b9dcc 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/tasks-card.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/tasks-card.tsx
@@ -9,7 +9,7 @@ import { cn, nFormatter } from "@dub/utils";
import Link from "next/link";
import { OverviewCard } from "./overview-card";
-export function TasksCard() {
+export function TasksCard({ className }: { className?: string }) {
const { isMobile } = useMediaQuery();
const { count: unreadMessagesCount } = useProgramMessagesCount({
@@ -36,7 +36,6 @@ export function TasksCard() {
];
// only on mobile: hide the card when no action is needed
- // so that Recent payouts fills the column
const incompleteTasks = tasks.filter(
(task): task is typeof task & { count: number } => !!task.count,
);
@@ -45,7 +44,11 @@ export function TasksCard() {
}
return (
- <OverviewCard title="Tasks" testId={testIds.partnerOverview.tasks}>
+ <OverviewCard
+ title="Tasks"
+ className={className}
+ testId={testIds.partnerOverview.tasks}
+ >
<div className="flex flex-col px-2 pb-2">
{tasks.map((task) => (
<TaskRow key={task.href} {...task} />
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/top-links-card.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/top-links-card.tsx
index bb294973fd..31fb744cf0 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/top-links-card.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/top-links-card.tsx
@@ -13,7 +13,7 @@ import {
} from "./overview-card";
import { useOverviewDateRange } from "./use-overview-date-range";
-export function TopLinksCard() {
+export function TopLinksCard({ className }: { className?: string }) {
const { start, end, interval } = useOverviewDateRange();
const { data: links, error } = usePartnerProfileEarningsAnalytics({
@@ -27,7 +27,7 @@ export function TopLinksCard() {
return (
<OverviewCard
title="Top links by earnings"
- className="rounded-2xl"
+ className={cn("rounded-2xl", className)}
testId={testIds.partnerOverview.topLinks}
>
<OverviewCardList
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/top-programs-card.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/top-programs-card.tsx
index 832560f9c3..8265b873d4 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/top-programs-card.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/top-programs-card.tsx
@@ -3,7 +3,7 @@
import { testIds } from "@/lib/e2e/test-ids";
import { ProgramLogo } from "@/ui/partners/program-logo";
import { GridIcon } from "@dub/ui/icons";
-import { cn, currencyFormatter } from "@dub/utils";
+import { cn, currencyFormatter, formatPercentage } from "@dub/utils";
import Link from "next/link";
import {
OVERVIEW_CARD_ROW_CLASSNAME,
@@ -18,6 +18,17 @@ export function TopProgramsCard() {
const { data, error } = useTopProgramEarnings();
const programs = data?.slice(0, ROW_COUNT);
+ // the share of positive earnings, so that the shares add up to 100%.
+ // A net total can be lower than one program's earnings when other programs have clawbacks
+ const positiveTotal = data?.reduce(
+ (sum, program) => sum + Math.max(program.earnings, 0),
+ 0,
+ );
+
+ // the bars are relative to the top program, so its bar fills the name column.
+ // the rows are sorted by earnings, so no other bar is wider.
+ const topEarnings = programs?.[0]?.earnings ?? 0;
+
return (
<OverviewCard
title="Top programs by earnings"
@@ -34,7 +45,7 @@ export function TopProgramsCard() {
icon: <GridIcon className="size-4" />,
title: "No earnings in this date range",
}}
- renderItem={(program) => (
+ renderItem={(program, index) => (
<Link
href={`/programs/${program.slug}`}
className={cn(
@@ -42,13 +53,33 @@ export function TopProgramsCard() {
"transition-colors duration-100 hover:bg-neutral-50 active:bg-neutral-100",
)}
>
- <ProgramLogo program={program} />
- <span className="text-content-emphasis min-w-0 grow truncate text-xs font-semibold">
- {program.name}
- </span>
+ <div className="relative flex min-w-0 grow items-center gap-2.5">
+ {topEarnings > 0 && (
+ <div
+ className={cn(
+ "absolute -left-3 top-1/2 h-8 -translate-y-1/2 rounded-lg bg-neutral-100",
+ index === 0 &&
+ "bg-gradient-to-r from-[#ededed] to-neutral-100",
+ )}
+ style={{
+ width: `calc(${(Math.max(program.earnings, 0) / topEarnings) * 100}% + 12px)`,
+ }}
+ />
+ )}
+ <ProgramLogo program={program} className="relative" />
+ <span className="text-content-emphasis relative min-w-0 grow truncate text-xs font-semibold">
+ {program.name}
+ </span>
+ </div>
<span className="shrink-0 text-xs font-medium text-neutral-500">
{currencyFormatter(program.earnings)}
</span>
+ <span className="w-10 shrink-0 text-right text-xs font-medium text-neutral-600">
+ {/* clawbacks can make a program's earnings negative, so it has no share */}
+ {positiveTotal && program.earnings > 0
+ ? `${formatPercentage((program.earnings / positiveTotal) * 100, { digits: 1 })}%`
+ : null}
+ </span>
</Link>
)}
/>
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/programs-table.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/programs-table.tsx
index 379c260de5..536e9af0eb 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/programs-table.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/programs-table.tsx
@@ -3,7 +3,7 @@
import { constructPartnerLink } from "@/lib/partners/construct-partner-link";
import { usePartnerProgramActivity } from "@/lib/swr/use-partner-profile-earnings";
import useProgramEnrollments from "@/lib/swr/use-program-enrollments";
-import { ProgramEnrollmentProps } from "@/lib/types";
+import { PartnerProfileProgramEnrollmentProps } from "@/lib/types";
import { PartnerStatusBadges } from "@/ui/partners/partner-status-badges";
import { ProgramInviteActions } from "@/ui/partners/program-invite-actions";
import { ProgramLogo } from "@/ui/partners/program-logo";
@@ -26,7 +26,7 @@ import { useRouter } from "next/navigation";
import { useMemo } from "react";
import { PROGRAMS_TABLE_PAGE_SIZE, ProgramTab } from "./program-tabs";
-type ProgramColumn = ColumnDef<ProgramEnrollmentProps>;
+type ProgramColumn = ColumnDef<PartnerProfileProgramEnrollmentProps>;
export function ProgramsTable({
tab,
@@ -51,6 +51,7 @@ export function ProgramsTable({
const { programEnrollments, isLoading, error } = useProgramEnrollments({
includeRewardsDiscounts: tab.id === "invitations",
+ includeInactiveDates: tab.id === "inactive",
status,
search,
...(sortBy && { sortBy }),
@@ -101,7 +102,10 @@ export function ProgramsTable({
return <Table {...tableProps} table={table} />;
}
-function getProgramUrl(tab: ProgramTab, { program }: ProgramEnrollmentProps) {
+function getProgramUrl(
+ tab: ProgramTab,
+ { program }: PartnerProfileProgramEnrollmentProps,
+) {
return tab.id === "invitations"
? `/programs/${program.slug}/invite`
: `/programs/${program.slug}`;
@@ -206,12 +210,20 @@ function getColumns(tab: ProgramTab): ProgramColumn[] {
return [
programColumn,
{
- id: "status",
- header: "Status",
+ id: "reason",
+ header: "Reason",
size: 160,
- cell: ({ row }) => (
- <EnrollmentStatusBadge status={row.original.status} />
- ),
+ cell: ({ row }) => PartnerStatusBadges[row.original.status].label,
+ },
+ {
+ id: "inactiveAt",
+ header: "Inactive date",
+ size: 160,
+ // older deactivations and archives have no date
+ cell: ({ row }) =>
+ row.original.inactiveAt
+ ? formatDate(row.original.inactiveAt, { month: "short" })
+ : "-",
},
earningsColumn,
];
@@ -221,7 +233,7 @@ function getColumns(tab: ProgramTab): ProgramColumn[] {
function ProgramName({
program,
}: {
- program: ProgramEnrollmentProps["program"];
+ program: PartnerProfileProgramEnrollmentProps["program"];
}) {
return (
<div className="flex min-w-0 items-center gap-2">
@@ -236,7 +248,7 @@ function ProgramName({
function EnrollmentStatusBadge({
status,
}: {
- status: ProgramEnrollmentProps["status"];
+ status: PartnerProfileProgramEnrollmentProps["status"];
}) {
const badge = PartnerStatusBadges[status];
@@ -250,7 +262,7 @@ function EnrollmentStatusBadge({
function ProgramLinkChip({
programEnrollment,
}: {
- programEnrollment: ProgramEnrollmentProps;
+ programEnrollment: PartnerProfileProgramEnrollmentProps;
}) {
const { group } = programEnrollment;
const link = programEnrollment.links?.[0];
@@ -291,7 +303,7 @@ function ProgramLinkChip({
function ProgramActivity({
programEnrollment,
}: {
- programEnrollment: ProgramEnrollmentProps;
+ programEnrollment: PartnerProfileProgramEnrollmentProps;
}) {
const data = usePartnerProgramActivity(programEnrollment.programId);
diff --git a/apps/web/lib/api/partner-profile/get-program-enrollment-inactive-dates.ts b/apps/web/lib/api/partner-profile/get-program-enrollment-inactive-dates.ts
new file mode 100644
index 0000000000..7a89df9b1e
--- /dev/null
+++ b/apps/web/lib/api/partner-profile/get-program-enrollment-inactive-dates.ts
@@ -0,0 +1,93 @@
+import { prisma } from "@/lib/prisma";
+import { ProgramEnrollmentStatus } from "@prisma/client";
+
+const STATUS_LOG_ACTIONS = {
+ deactivated: "partner.deactivated",
+ archived: "partner.archived",
+} as const;
+
+// When each enrollment became inactive, by program ID.
+// A ban has bannedAt. Deactivations and archives have no date column, so the date comes from the
+// latest activity log of that status, which exists only for changes made since activity logs were added.
+// The log lookup is a query, so callers turn it on only when they show these dates.
+export async function getProgramEnrollmentInactiveDates({
+ partnerId,
+ programEnrollments,
+ includeStatusLogs,
+}: {
+ partnerId: string;
+ includeStatusLogs: boolean;
+ programEnrollments: {
+ programId: string;
+ status: ProgramEnrollmentStatus;
+ bannedAt: Date | null;
+ }[];
+}) {
+ const inactiveDates = new Map<string, Date>();
+
+ for (const { programId, status, bannedAt } of programEnrollments) {
+ if (status === "banned" && bannedAt) {
+ inactiveDates.set(programId, bannedAt);
+ }
+ }
+
+ if (!includeStatusLogs) {
+ return inactiveDates;
+ }
+
+ const loggedEnrollments = programEnrollments.filter(
+ (
+ enrollment,
+ ): enrollment is typeof enrollment & {
+ status: keyof typeof STATUS_LOG_ACTIONS;
+ } => enrollment.status in STATUS_LOG_ACTIONS,
+ );
+
+ if (loggedEnrollments.length === 0) {
+ return inactiveDates;
+ }
+
+ const statusLogs = await prisma.activityLog.findMany({
+ where: {
+ resourceType: "partner",
+ resourceId: partnerId,
+ programId: {
+ in: loggedEnrollments.map(({ programId }) => programId),
+ },
+ action: {
+ in: Object.values(STATUS_LOG_ACTIONS),
+ },
+ },
+ select: {
+ programId: true,
+ action: true,
+ createdAt: true,
+ },
+ orderBy: {
+ createdAt: "desc",
+ },
+ });
+
+ // the logs are newest first, so the first log per program and action is the latest change
+ const latestLogDates = new Map<string, Date>();
+
+ for (const { programId, action, createdAt } of statusLogs) {
+ const key = `${programId}:${action}`;
+
+ if (!latestLogDates.has(key)) {
+ latestLogDates.set(key, createdAt);
+ }
+ }
+
+ for (const { programId, status } of loggedEnrollments) {
+ const loggedAt = latestLogDates.get(
+ `${programId}:${STATUS_LOG_ACTIONS[status]}`,
+ );
+
+ if (loggedAt) {
+ inactiveDates.set(programId, loggedAt);
+ }
+ }
+
+ return inactiveDates;
+}
diff --git a/apps/web/lib/swr/use-program-enrollments.ts b/apps/web/lib/swr/use-program-enrollments.ts
index a2a34cfc57..94eaf97f75 100644
--- a/apps/web/lib/swr/use-program-enrollments.ts
+++ b/apps/web/lib/swr/use-program-enrollments.ts
@@ -5,12 +5,16 @@ import * as z from "zod/v4";
import { PartnerProfileProgramEnrollmentProps } from "../types";
import { partnerProfileProgramsQuerySchema } from "../zod/schemas/partner-profile";
-export default function useProgramEnrollments(
- query: Omit<
- z.input<typeof partnerProfileProgramsQuerySchema>,
- "includeRewardsDiscounts"
- > & { includeRewardsDiscounts?: boolean } = {},
-) {
+export default function useProgramEnrollments({
+ includeInactiveDates,
+ ...query
+}: Omit<
+ z.input<typeof partnerProfileProgramsQuerySchema>,
+ "includeRewardsDiscounts" | "includeInactiveDates"
+> & {
+ includeRewardsDiscounts?: boolean;
+ includeInactiveDates?: boolean;
+} = {}) {
const { data: session } = useSession();
const partnerId = session?.user?.["defaultPartnerId"];
@@ -22,7 +26,11 @@ export default function useProgramEnrollments(
partnerId &&
`/api/partner-profile/programs?${new URLSearchParams(
Object.fromEntries(
- Object.entries(query)
+ Object.entries({
+ ...query,
+ // sent only when true, so other callers share the same request
+ includeInactiveDates: includeInactiveDates || undefined,
+ })
.filter(([, value]) => value !== undefined)
.map(([key, value]) => [key, String(value)]),
),
diff --git a/apps/web/lib/zod/schemas/partner-profile.ts b/apps/web/lib/zod/schemas/partner-profile.ts
index 9f93a8d4c9..b681cab2e5 100644
--- a/apps/web/lib/zod/schemas/partner-profile.ts
+++ b/apps/web/lib/zod/schemas/partner-profile.ts
@@ -239,10 +239,18 @@ export const partnerProfileEventsQuerySchema = eventsQuerySchema.omit({
export const PartnerProfileProgramEnrollmentSchema =
ProgramEnrollmentSchema.extend({
reapplicationTimeframe: z.enum(ReapplicationTimeframe).nullish(),
+ inactiveAt: z
+ .date()
+ .nullish()
+ .describe(
+ "When the program banned, deactivated or archived the partner. For deactivated and archived enrollments, only set when `includeInactiveDates=true`. Null for other statuses, and when the date is not known.",
+ ),
});
export const partnerProfileProgramsQuerySchema = z.object({
includeRewardsDiscounts: booleanQuerySchema.optional(),
+ // looks up when deactivated and archived enrollments became inactive
+ includeInactiveDates: booleanQuerySchema.optional(),
// one status or a comma-separated list, for example "pending,rejected"
status: z
.string()
diff --git a/apps/web/playwright/api/partner-profile/programs.spec.ts b/apps/web/playwright/api/partner-profile/programs.spec.ts
index f5e99b9bff..9fc51e6662 100644
--- a/apps/web/playwright/api/partner-profile/programs.spec.ts
+++ b/apps/web/playwright/api/partner-profile/programs.spec.ts
@@ -11,6 +11,7 @@ type PartnerProfileProgram = {
status: ProgramEnrollmentStatus;
totalCommissions: number;
program: { id: string; name: string };
+ inactiveAt?: string | null;
};
type StatusCount = { status: ProgramEnrollmentStatus; _count: number };
@@ -134,6 +135,11 @@ test.describe("GET /partner-profile/programs", () => {
const programIds = (data: PartnerProfileProgram[]) =>
data.map((enrollment) => enrollment.program.id);
+ const inactiveDates = (data: PartnerProfileProgram[]) =>
+ Object.fromEntries(
+ data.map((enrollment) => [enrollment.program.id, enrollment.inactiveAt]),
+ );
+
test("returns every enrollment by default, without deactivated programs", async ({
playwright,
program,
@@ -214,6 +220,82 @@ test.describe("GET /partner-profile/programs", () => {
});
});
+ test("returns the inactive date from bannedAt, and from the latest status log only with includeInactiveDates", async ({
+ playwright,
+ }) => {
+ const bannedAt = new Date("2026-09-01T12:00:00.000Z");
+ const deactivatedAt = new Date("2026-09-14T12:00:00.000Z");
+
+ // alpha is banned, beta is deactivated with a log, and gamma is archived without a log
+ await prisma.programEnrollment.update({
+ where: {
+ partnerId_programId: { partnerId: partnerId!, programId: alpha.id },
+ },
+ data: { status: "banned", bannedAt },
+ });
+ await prisma.programEnrollment.update({
+ where: {
+ partnerId_programId: { partnerId: partnerId!, programId: beta.id },
+ },
+ data: { status: "deactivated" },
+ });
+ await prisma.programEnrollment.update({
+ where: {
+ partnerId_programId: { partnerId: partnerId!, programId: gamma.id },
+ },
+ data: { status: "archived" },
+ });
+ const activityLog = await prisma.activityLog.create({
+ data: {
+ workspaceId: beta.workspaceId,
+ programId: beta.id,
+ resourceType: "partner",
+ resourceId: partnerId!,
+ action: "partner.deactivated",
+ createdAt: deactivatedAt,
+ },
+ });
+
+ try {
+ await withPartnerApi(playwright, async (partnerApi) => {
+ const path =
+ "/api/partner-profile/programs?status=banned,deactivated,archived";
+
+ const { status, data } = await partnerApi.get<PartnerProfileProgram[]>(
+ `${path}&includeInactiveDates=true`,
+ );
+
+ expect(status).toEqual(200);
+ expect(inactiveDates(data)).toEqual({
+ [alpha.id]: bannedAt.toISOString(),
+ [beta.id]: deactivatedAt.toISOString(),
+ [gamma.id]: null,
+ });
+
+ // without includeInactiveDates, the route skips the activity log lookup
+ const { data: withoutLogs } =
+ await partnerApi.get<PartnerProfileProgram[]>(path);
+ const withoutLogsInactiveAt = inactiveDates(withoutLogs);
+
+ expect(withoutLogsInactiveAt[alpha.id]).toEqual(bannedAt.toISOString());
+ expect(withoutLogsInactiveAt[beta.id]).toBeNull();
+ });
+ } finally {
+ await prisma.activityLog.delete({ where: { id: activityLog.id } });
+ for (const program of [alpha, beta, gamma]) {
+ await prisma.programEnrollment.update({
+ where: {
+ partnerId_programId: {
+ partnerId: partnerId!,
+ programId: program.id,
+ },
+ },
+ data: { status: program.status, bannedAt: null },
+ });
+ }
+ }
+ });
+
test("rejects an unknown status", async ({ playwright }) => {
await withPartnerApi(playwright, async (partnerApi) => {
const { status } = await partnerApi.get(
diff --git a/apps/web/playwright/partners/overview.spec.ts b/apps/web/playwright/partners/overview.spec.ts
index 05993e7dec..aec5879512 100644
--- a/apps/web/playwright/partners/overview.spec.ts
+++ b/apps/web/playwright/partners/overview.spec.ts
@@ -2,7 +2,7 @@ import { createId } from "@/lib/api/create-id";
import { testIds } from "@/lib/e2e/test-ids";
import { prisma } from "@/lib/prisma";
import { nanoid } from "@dub/utils";
-import { expect, test } from "@playwright/test";
+import { expect, Page, test } from "@playwright/test";
import { deletePartner } from "../api/partners/helpers";
import { TEST_WORKSPACE } from "../api/setup-test-workspace";
import { env } from "../env";
@@ -17,9 +17,29 @@ test.use({
},
});
-const DESKTOP_VIEWPORT = { width: 1280, height: 720 };
+// wide enough for the desktop Overview layout, which needs a 64rem page next to the sidebar
+const DESKTOP_VIEWPORT = { width: 1440, height: 900 };
const MOBILE_VIEWPORT = { width: 390, height: 844 };
+// reads every card position at once, so that a card that is still loading cannot move between two reads
+async function getCardPositions(page: Page, cardTestIds: string[]) {
+ for (const testId of cardTestIds) {
+ await expect(page.getByTestId(testId)).toBeVisible();
+ }
+ await page.waitForLoadState("networkidle");
+
+ return page.evaluate(
+ (ids) =>
+ ids.map((id) => {
+ const { top, left } = document
+ .querySelector(`[data-testid="${id}"]`)!
+ .getBoundingClientRect();
+ return { top, left };
+ }),
+ cardTestIds,
+ );
+}
+
test.describe("Partner All programs Overview", () => {
test("renders every Overview card", async ({ page }) => {
await logIn(page, env.E2E_PARTNER_EMAIL, env.E2E_PARTNER_PASSWORD);
@@ -33,6 +53,36 @@ test.describe("Partner All programs Overview", () => {
}
});
+ test("stacks Recent payouts after Recent earnings on mobile, and next to the chart on desktop", async ({
+ page,
+ }) => {
+ await logIn(page, env.E2E_PARTNER_EMAIL, env.E2E_PARTNER_PASSWORD);
+ await page.setViewportSize(MOBILE_VIEWPORT);
+ await page.goto("/overview");
+
+ const { earnings, topPrograms, recentEarnings, recentPayouts, topLinks } =
+ testIds.partnerOverview;
+
+ const mobileTops = (
+ await getCardPositions(page, [
+ earnings,
+ topPrograms,
+ recentEarnings,
+ recentPayouts,
+ topLinks,
+ ])
+ ).map(({ top }) => top);
+ expect(mobileTops).toEqual([...mobileTops].sort((a, b) => a - b));
+
+ await page.setViewportSize(DESKTOP_VIEWPORT);
+ const [earningsBox, payoutsBox] = await getCardPositions(page, [
+ earnings,
+ recentPayouts,
+ ]);
+ expect(payoutsBox.top).toBe(earningsBox.top);
+ expect(payoutsBox.left).toBeGreaterThan(earningsBox.left);
+ });
+
test("always shows Tasks on desktop, and on mobile only when an action is needed", async ({
page,
}) => {
@@ -77,6 +127,17 @@ test.describe("Partner All programs Overview", () => {
await page.setViewportSize(MOBILE_VIEWPORT);
await expect(tasks).toBeVisible();
+ // on mobile, Tasks comes after Recent payouts and before Top links
+ const [payoutsTop, tasksTop, topLinksTop] = (
+ await getCardPositions(page, [
+ testIds.partnerOverview.recentPayouts,
+ testIds.partnerOverview.tasks,
+ testIds.partnerOverview.topLinks,
+ ])
+ ).map(({ top }) => top);
+ expect(tasksTop).toBeGreaterThan(payoutsTop);
+ expect(tasksTop).toBeLessThan(topLinksTop);
+
await prisma.programEnrollment.update({
where: { id: enrollment.id },
data: { status: "approved" },
diff --git a/apps/web/playwright/partners/programs.spec.ts b/apps/web/playwright/partners/programs.spec.ts
index 8ed2d2f3e1..8ac2476452 100644
--- a/apps/web/playwright/partners/programs.spec.ts
+++ b/apps/web/playwright/partners/programs.spec.ts
@@ -44,6 +44,14 @@ test.describe("Partner Programs page", () => {
await logIn(page, email, password);
+ // the Marketplace filter counts must not load on this page
+ const marketplaceCountRequests: string[] = [];
+ page.on("request", (request) => {
+ if (request.url().includes("/api/network/programs/count")) {
+ marketplaceCountRequests.push(request.url());
+ }
+ });
+
// the old Invitations page redirects to the Invitations tab
await page.goto("/programs/invitations");
await expect(page).toHaveURL("/programs?tab=invitations");
@@ -80,6 +88,8 @@ test.describe("Partner Programs page", () => {
// a search with no match shows the empty state
await page.goto("/programs?tab=active&search=no-such-program");
await expect(page.getByText("No programs found")).toBeVisible();
+
+ expect(marketplaceCountRequests).toEqual([]);
} finally {
if (userId) await prisma.user.delete({ where: { id: userId } });
await deletePartner(partnerId);
diff --git a/apps/web/tests/misc/format-percentage.test.ts b/apps/web/tests/misc/format-percentage.test.ts
new file mode 100644
index 0000000000..45a04408d0
--- /dev/null
+++ b/apps/web/tests/misc/format-percentage.test.ts
@@ -0,0 +1,20 @@
+import { formatPercentage } from "@dub/utils";
+import { describe, expect, it } from "vitest";
+
+describe("formatPercentage", () => {
+ it("rounds to the given decimals and drops trailing zeros", () => {
+ expect(formatPercentage(45.25)).toBe("45.25");
+ expect(formatPercentage(45.25, { digits: 1 })).toBe("45.3");
+ expect(formatPercentage(28)).toBe("28");
+ expect(formatPercentage(100)).toBe("100");
+ });
+
+ it("shows a value too small to round as less than the smallest step", () => {
+ expect(formatPercentage(0.004)).toBe("< 0.01");
+ expect(formatPercentage(0.04, { digits: 1 })).toBe("< 0.1");
+ });
+
+ it("shows zero as 0", () => {
+ expect(formatPercentage(0)).toBe("0");
+ });
+});
diff --git a/apps/web/ui/partners/overview/blocks/conversion-block.tsx b/apps/web/ui/partners/overview/blocks/conversion-block.tsx
index 40e26aa338..86d247afab 100644
--- a/apps/web/ui/partners/overview/blocks/conversion-block.tsx
+++ b/apps/web/ui/partners/overview/blocks/conversion-block.tsx
@@ -3,7 +3,7 @@ import useWorkspace from "@/lib/swr/use-workspace";
import { AnalyticsContext } from "@/ui/analytics/analytics-provider";
import { LoadingSpinner, useRouterStuff } from "@dub/ui";
import { FunnelChart } from "@dub/ui/charts";
-import { nFormatter } from "@dub/utils";
+import { formatPercentage } from "@dub/utils";
import { useContext, useMemo } from "react";
import { ExceededEventsLimit } from "../exceeded-events-limit";
import { ProgramOverviewBlock } from "../program-overview-block";
@@ -109,9 +109,3 @@ export function ConversionBlock() {
</ProgramOverviewBlock>
);
}
-
-const formatPercentage = (value: number) => {
- return value > 0 && value < 0.01
- ? "< 0.01"
- : nFormatter(value, { digits: 2 });
-};
diff --git a/apps/web/ui/partners/overview/blocks/sale-type-block.tsx b/apps/web/ui/partners/overview/blocks/sale-type-block.tsx
index 0942fdadf6..884124828d 100644
--- a/apps/web/ui/partners/overview/blocks/sale-type-block.tsx
+++ b/apps/web/ui/partners/overview/blocks/sale-type-block.tsx
@@ -3,7 +3,7 @@ import { editQueryString } from "@/lib/analytics/utils";
import useWorkspace from "@/lib/swr/use-workspace";
import { AnalyticsContext } from "@/ui/analytics/analytics-provider";
import { LoadingSpinner, useRouterStuff } from "@dub/ui";
-import { cn, fetcher, nFormatter } from "@dub/utils";
+import { cn, fetcher, formatPercentage, nFormatter } from "@dub/utils";
import Link from "next/link";
import { useContext, useMemo, useState } from "react";
import useSWR from "swr";
@@ -173,9 +173,3 @@ export function SaleTypeBlock() {
</ProgramOverviewBlock>
);
}
-
-const formatPercentage = (value: number) => {
- return value > 0 && value < 0.01
- ? "< 0.01"
- : nFormatter(value, { digits: 2 });
-};
diff --git a/apps/web/ui/program-marketplace/marketplace-sidebar-filters.tsx b/apps/web/ui/program-marketplace/marketplace-sidebar-filters.tsx
index 56455742e8..4d0d8ce849 100644
--- a/apps/web/ui/program-marketplace/marketplace-sidebar-filters.tsx
+++ b/apps/web/ui/program-marketplace/marketplace-sidebar-filters.tsx
@@ -3,9 +3,14 @@
import { ChevronLeft, Filter, useKeyboardShortcut } from "@dub/ui";
import { cn } from "@dub/utils";
import Link from "next/link";
+import { usePathname } from "next/navigation";
import { useProgramNetworkFilters } from "./use-program-network-filters";
+import { isMarketplaceFilterSidebarPath } from "./utils/urls";
export function MarketplaceSidebarFilters() {
+ const pathname = usePathname();
+
+ // the sidebar keeps these filters mounted on every page, so only load the counts where they show
const {
filters,
activeFilters,
@@ -13,7 +18,9 @@ export function MarketplaceSidebarFilters() {
onRemove,
onRemoveAll,
isFiltered,
- } = useProgramNetworkFilters();
+ } = useProgramNetworkFilters({
+ enabled: isMarketplaceFilterSidebarPath(pathname),
+ });
useKeyboardShortcut("Escape", onRemoveAll, {
enabled: isFiltered,
diff --git a/apps/web/ui/program-marketplace/use-program-network-filters.tsx b/apps/web/ui/program-marketplace/use-program-network-filters.tsx
index 2745ff3219..df637c617c 100644
--- a/apps/web/ui/program-marketplace/use-program-network-filters.tsx
+++ b/apps/web/ui/program-marketplace/use-program-network-filters.tsx
@@ -20,7 +20,9 @@ import {
getPreservedMarketplaceSearchParams,
} from "./utils/urls";
-export function useProgramNetworkFilters() {
+export function useProgramNetworkFilters({
+ enabled = true,
+}: { enabled?: boolean } = {}) {
const router = useRouter();
const pathname = usePathname();
const { searchParamsObj, queryParams } = useRouterStuff();
@@ -38,6 +40,7 @@ export function useProgramNetworkFilters() {
groupBy: "category",
},
excludeParams: ["category"],
+ enabled,
});
const { data: rewardTypesCount } = useNetworkProgramsCount<
@@ -51,6 +54,7 @@ export function useProgramNetworkFilters() {
groupBy: "rewardType",
},
excludeParams: ["rewardType"],
+ enabled,
});
const { data: statusCount } = useNetworkProgramsCount<
@@ -64,6 +68,7 @@ export function useProgramNetworkFilters() {
groupBy: "status",
},
excludeParams: ["status"],
+ enabled,
});
const filters = useMemo(
diff --git a/packages/ui/src/charts/funnel-chart.tsx b/packages/ui/src/charts/funnel-chart.tsx
index af0e8417f1..c84a3a1ec6 100644
--- a/packages/ui/src/charts/funnel-chart.tsx
+++ b/packages/ui/src/charts/funnel-chart.tsx
@@ -1,4 +1,9 @@
-import { cn, currencyFormatter, nFormatter } from "@dub/utils";
+import {
+ cn,
+ currencyFormatter,
+ formatPercentage,
+ nFormatter,
+} from "@dub/utils";
import { curveBasis } from "@visx/curve";
import { ParentSize } from "@visx/responsive";
import { scaleLinear } from "@visx/scale";
@@ -268,12 +273,6 @@ function PersistentPercentage({
);
}
-const formatPercentage = (value: number) => {
- return value > 0 && value < 0.01
- ? "< 0.01"
- : nFormatter(value, { digits: 2 });
-};
-
const interpolate = (from: number, to: number) => [
{ x: 0, y: from },
{ x: 0.3, y: from },
diff --git a/packages/utils/src/functions/format-percentage.ts b/packages/utils/src/functions/format-percentage.ts
new file mode 100644
index 0000000000..1416227d30
--- /dev/null
+++ b/packages/utils/src/functions/format-percentage.ts
@@ -0,0 +1,14 @@
+import { nFormatter } from "./nformatter";
+
+// formats a percentage (0 to 100) with up to `digits` decimals, without the % sign
+// a value too small to show (for example 0.004 with 2 digits) reads "< 0.01" instead of "0"
+export function formatPercentage(
+ value: number,
+ { digits = 2 }: { digits?: number } = {},
+) {
+ const smallest = 10 ** -digits;
+
+ return value > 0 && value < smallest
+ ? `< ${smallest}`
+ : nFormatter(value, { digits });
+}
diff --git a/packages/utils/src/functions/index.ts b/packages/utils/src/functions/index.ts
index 24f815dc7d..da12d72437 100644
--- a/packages/utils/src/functions/index.ts
+++ b/packages/utils/src/functions/index.ts
@@ -15,6 +15,7 @@ export * from "./fetch-with-retry";
export * from "./fetch-with-timeout";
export * from "./fetcher";
export * from "./format-file-size";
+export * from "./format-percentage";
export * from "./group-by";
export * from "./hash-string";
export * from "./is-click-on-interactive-child";