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.

Show the earnings of all programs in the partner earnings chart and table

Rafi1d6a079ce18a
diff --git a/apps/web/lib/swr/use-program-enrollment.ts b/apps/web/lib/swr/use-program-enrollment.ts
index 3a74f38876..7329b91f76 100644
--- a/apps/web/lib/swr/use-program-enrollment.ts
+++ b/apps/web/lib/swr/use-program-enrollment.ts
@@ -41,12 +41,22 @@ export default function useProgramEnrollment({
return {
programEnrollment,
showDetailedAnalytics:
- programEnrollment &&
- (!LARGE_PROGRAM_IDS.includes(programEnrollment.programId) ||
- (programEnrollment.status === "approved" &&
- programEnrollment.totalCommissions >=
- LARGE_PROGRAM_MIN_TOTAL_COMMISSIONS_CENTS)),
+ programEnrollment && getShowDetailedAnalytics(programEnrollment),
error,
loading: status === "loading" || isLoading,
};
}
+
+export function getShowDetailedAnalytics(
+ programEnrollment: Pick<
+ ProgramEnrollmentProps,
+ "programId" | "status" | "totalCommissions"
+ >,
+) {
+ return (
+ !LARGE_PROGRAM_IDS.includes(programEnrollment.programId) ||
+ (programEnrollment.status === "approved" &&
+ programEnrollment.totalCommissions >=
+ LARGE_PROGRAM_MIN_TOTAL_COMMISSIONS_CENTS)
+ );
+}
diff --git a/apps/web/ui/partners/earnings/earnings-composite-chart.tsx b/apps/web/ui/partners/earnings/earnings-composite-chart.tsx
index be3f814554..15dc72cbde 100644
--- a/apps/web/ui/partners/earnings/earnings-composite-chart.tsx
+++ b/apps/web/ui/partners/earnings/earnings-composite-chart.tsx
@@ -1,7 +1,6 @@
"use client";
import { formatDateTooltip } from "@/lib/analytics/format-date-tooltip";
-import usePartnerLinks from "@/lib/swr/use-partner-links";
import {
usePartnerProfileEarningsCount,
usePartnerProfileEarningsTimeseries,
@@ -9,11 +8,13 @@ import {
import { LinkIcon } from "@/ui/links/link-icon";
import { CommissionTypeIcon } from "@/ui/partners/comission-type-icon";
import { CommissionStatusBadges } from "@/ui/partners/commission-status-badges";
+import { ProgramLogo } from "@/ui/partners/program-logo";
import SimpleDateRangePicker from "@/ui/shared/simple-date-range-picker";
import { Filter, LoadingSpinner, ToggleGroup, useRouterStuff } from "@dub/ui";
import { Areas, TimeSeriesChart, XAxis, YAxis } from "@dub/ui/charts";
import {
CircleDotted,
+ GridIcon,
Hyperlink,
MoneyBill2,
Sliders,
@@ -23,12 +24,12 @@ import {
capitalize,
cn,
currencyFormatter,
- getPrettyUrl,
linkConstructor,
nFormatter,
} from "@dub/utils";
import NumberFlow from "@number-flow/react";
import { CommissionType } from "@prisma/client";
+import { useParams } from "next/navigation";
import { Fragment, useMemo, useState } from "react";
import { usePartnerEarningsFilters } from "./use-partner-earnings-filters";
@@ -51,23 +52,48 @@ const EVENT_TYPE_LINE_COLORS = {
const MAX_LINES = LINE_COLORS.length;
+type EarningsGroupBy = "type" | "linkId" | "programId";
+
+// a row of GET /api/partner-profile/earnings/count, grouped by link or by program
+type EarningsCountGroup = {
+ id: string;
+ domain?: string;
+ key?: string;
+ name?: string;
+ logo?: string | null;
+};
+
export function EarningsCompositeChart() {
+ const { programSlug } = useParams<{ programSlug?: string }>();
const { queryParams, searchParamsObj } = useRouterStuff();
const filters = usePartnerEarningsFilters();
const { start, end, interval } = filters;
- const { groupBy = "type" } = searchParamsObj as {
- groupBy?: "linkId" | "type";
+ // the All programs page has no programSlug, and groups by program by default
+ const { groupBy = programSlug ? "type" : "programId" } = searchParamsObj as {
+ groupBy?: EarningsGroupBy;
};
- const { links } = usePartnerLinks();
-
const { data } = usePartnerProfileEarningsTimeseries({
...filters,
groupBy,
});
+ // the names of the links and programs in the tooltip
+ const { data: groups } = usePartnerProfileEarningsCount<EarningsCountGroup[]>(
+ {
+ ...filters,
+ groupBy: groupBy === "type" ? undefined : groupBy,
+ enabled: groupBy !== "type",
+ },
+ );
+
+ const groupsById = useMemo(
+ () => new Map(groups?.map((group) => [group.id, group])),
+ [groups],
+ );
+
const total = useMemo(
() => data?.reduce((acc, { earnings }) => acc + earnings, 0),
[data],
@@ -120,7 +146,7 @@ export function EarningsCompositeChart() {
<div className="flex flex-col gap-4">
<EarningsTableControls />
<div className="rounded-lg border border-neutral-200 p-6">
- <div className="flex w-full items-center justify-between">
+ <div className="flex w-full flex-wrap items-center justify-between gap-3">
<div className="flex flex-col gap-1">
<span className="text-sm text-neutral-500">Total Earnings</span>
<div className="mt-1">
@@ -164,6 +190,19 @@ export function EarningsCompositeChart() {
),
value: "linkId",
},
+ ...(programSlug
+ ? []
+ : [
+ {
+ label: (
+ <div className="flex items-center gap-1.5 text-neutral-600">
+ <GridIcon className="size-4" />
+ <span className="text-sm">Program</span>
+ </div>
+ ),
+ value: "programId",
+ },
+ ]),
]}
selected={groupBy}
selectAction={(option) => {
@@ -196,7 +235,7 @@ export function EarningsCompositeChart() {
</div>
<div className="grid max-w-64 grid-cols-[minmax(0,1fr),min-content] gap-x-6 gap-y-2 px-4 py-3 text-xs">
{series.map(({ id, colorClassName, valueAccessor }) => {
- const link = links?.find((link) => link.id === id);
+ const group = groupsById.get(id);
return (
<Fragment key={id}>
<div className="flex items-center gap-2">
@@ -206,10 +245,27 @@ export function EarningsCompositeChart() {
"size-2 shrink-0 rounded-sm bg-current opacity-50 shadow-[inset_0_0_0_1px_#0003]",
)}
/>
+ {groupBy === "programId" && group?.name && (
+ <ProgramLogo
+ program={{
+ name: group.name,
+ logo: group.logo ?? null,
+ }}
+ className="size-3.5"
+ />
+ )}
<span className="min-w-0 truncate font-medium text-neutral-700">
- {link?.shortLink
- ? getPrettyUrl(link.shortLink)
- : capitalize(id)}
+ {groupBy === "programId" && group?.name
+ ? group.name
+ : groupBy === "linkId" &&
+ group?.domain &&
+ group?.key
+ ? linkConstructor({
+ domain: group.domain,
+ key: group.key,
+ pretty: true,
+ })
+ : capitalize(id)}
</span>
</div>
<p className="text-right text-neutral-500">
@@ -250,10 +306,23 @@ export function EarningsCompositeChart() {
}
function EarningsTableControls() {
+ const { programSlug } = useParams<{ programSlug?: string }>();
const { queryParams, searchParamsObj } = useRouterStuff();
const earningsFilters = usePartnerEarningsFilters();
const [selectedFilter, setSelectedFilter] = useState<string | null>(null);
+ const { data: programs } = usePartnerProfileEarningsCount<
+ { id: string; name?: string; logo?: string | null; _count: number }[]
+ >({
+ ...earningsFilters,
+ groupBy: "programId",
+ enabled:
+ !programSlug &&
+ (selectedFilter === "programId" || searchParamsObj.programId
+ ? true
+ : false),
+ });
+
const { data: links } = usePartnerProfileEarningsCount<
{ id: string; domain: string; key: string; url: string; _count: number }[]
>({
@@ -285,6 +354,27 @@ function EarningsTableControls() {
const filters = useMemo(
() => [
+ ...(programSlug
+ ? []
+ : [
+ {
+ key: "programId",
+ icon: GridIcon,
+ label: "Program",
+ options:
+ programs?.map(({ id, name, logo, _count }) => ({
+ value: id,
+ label: name ?? id,
+ icon: (
+ <ProgramLogo
+ program={{ name: name ?? id, logo: logo ?? null }}
+ className="size-4"
+ />
+ ),
+ right: nFormatter(_count, { full: true }),
+ })) ?? null,
+ },
+ ]),
{
key: "type",
icon: Sliders,
@@ -346,19 +436,23 @@ function EarningsTableControls() {
}) ?? null,
},
],
- [links, customers, statuses],
+ [programSlug, programs, links, customers, statuses],
);
const activeFilters = useMemo(() => {
- const { type, linkId, customerId, status, payoutId } = searchParamsObj;
+ const { programId, type, linkId, customerId, status, payoutId } =
+ searchParamsObj;
return [
+ ...(programId && !programSlug
+ ? [{ key: "programId", value: programId }]
+ : []),
...(type ? [{ key: "type", value: type }] : []),
...(linkId ? [{ key: "linkId", value: linkId }] : []),
...(customerId ? [{ key: "customerId", value: customerId }] : []),
...(status ? [{ key: "status", value: status }] : []),
...(payoutId ? [{ key: "payoutId", value: payoutId }] : []),
];
- }, [searchParamsObj]);
+ }, [searchParamsObj, programSlug]);
const onSelect = (key: string, value: any) =>
queryParams({
@@ -375,7 +469,15 @@ function EarningsTableControls() {
const onRemoveAll = () =>
queryParams({
- del: ["linkId", "customerId", "status", "payoutId", "page"],
+ del: [
+ "programId",
+ "type",
+ "linkId",
+ "customerId",
+ "status",
+ "payoutId",
+ "page",
+ ],
});
return (
diff --git a/apps/web/ui/partners/earnings/earnings-table.tsx b/apps/web/ui/partners/earnings/earnings-table.tsx
index e536f6e6a7..84eeaf0683 100644
--- a/apps/web/ui/partners/earnings/earnings-table.tsx
+++ b/apps/web/ui/partners/earnings/earnings-table.tsx
@@ -6,11 +6,15 @@ import {
usePartnerProfileEarnings,
usePartnerProfileEarningsCount,
} from "@/lib/swr/use-partner-profile-earnings";
-import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
+import useProgramEnrollment, {
+ getShowDetailedAnalytics,
+} from "@/lib/swr/use-program-enrollment";
+import useProgramEnrollments from "@/lib/swr/use-program-enrollments";
import { PartnerProfileEarningsResponse } from "@/lib/types";
import { CustomerRowItem } from "@/ui/customers/customer-row-item";
import { CommissionStatusBadges } from "@/ui/partners/commission-status-badges";
import { CommissionTypeBadge } from "@/ui/partners/commission-type-badge";
+import { ProgramLogo } from "@/ui/partners/program-logo";
import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
import { CountryFlag } from "@/ui/shared/country-flag";
import { FilterButtonTableRow } from "@/ui/shared/filter-button-table-row";
@@ -36,7 +40,9 @@ import {
} from "@dub/utils";
import { CommissionType } from "@prisma/client";
import { Cell } from "@tanstack/react-table";
+import Link from "next/link";
import { useParams } from "next/navigation";
+import { useMemo } from "react";
import { usePartnerEarningsFilters } from "./use-partner-earnings-filters";
type ColumnMeta = {
@@ -45,10 +51,29 @@ type ColumnMeta = {
) => Record<string, any>;
};
+// the earnings of one program, or of all programs on the All programs page (no programSlug)
export function EarningsTablePartner({ limit }: { limit?: number }) {
- const { programSlug } = useParams();
+ const { programSlug } = useParams<{ programSlug?: string }>();
const { partner } = usePartnerProfile();
const { programEnrollment, showDetailedAnalytics } = useProgramEnrollment();
+
+ // the enrollment of each row's program, for the All programs page
+ const { programEnrollments } = useProgramEnrollments();
+ const programEnrollmentsById = useMemo(
+ () =>
+ new Map(
+ programEnrollments?.map((enrollment) => [
+ enrollment.programId,
+ enrollment,
+ ]),
+ ),
+ [programEnrollments],
+ );
+
+ const getRowProgramEnrollment = (row: PartnerProfileEarningsResponse) =>
+ programSlug
+ ? programEnrollment
+ : programEnrollmentsById.get(row.program.id);
const { queryParams, searchParamsObj } = useRouterStuff();
const filters = usePartnerEarningsFilters();
@@ -77,11 +102,41 @@ export function EarningsTablePartner({ limit }: { limit?: number }) {
sortOrder,
});
+ const emptyStateDescription = programSlug
+ ? "No earnings have been made for this program yet."
+ : "No earnings have been made yet.";
+
const { table, ...tableProps } = useTable({
data: earnings || [],
loading: isLoading,
error: error ? "Failed to fetch earnings." : undefined,
columns: [
+ ...(programSlug
+ ? []
+ : [
+ {
+ id: "program",
+ header: "Program",
+ minSize: 160,
+ meta: {
+ filterParams: ({ row }) => ({
+ programId: row.original.program.id,
+ }),
+ },
+ cell: ({ row }) => (
+ <Link
+ href={`/programs/${row.original.program.slug}`}
+ className="flex min-w-0 items-center gap-2 hover:underline"
+ >
+ <ProgramLogo
+ program={row.original.program}
+ className="size-4"
+ />
+ <span className="truncate">{row.original.program.name}</span>
+ </Link>
+ ),
+ },
+ ]),
{
id: "createdAt",
header: "Date",
@@ -125,7 +180,7 @@ export function EarningsTablePartner({ limit }: { limit?: number }) {
: row.original.type === CommissionType.referral && partner?.username
? {
apexDomain: "dub.co",
- shortLink: `https://partners.dub.co/${programSlug}/apply?via=${partner.username}`,
+ shortLink: `https://partners.dub.co/${row.original.program.slug}/apply?via=${partner.username}`,
}
: null;
@@ -155,20 +210,27 @@ export function EarningsTablePartner({ limit }: { limit?: number }) {
id: "customer",
header: "Customer",
minSize: 250,
- cell: ({ row }) =>
- row.original.customer ? (
+ cell: ({ row }) => {
+ const rowProgramEnrollment = getRowProgramEnrollment(row.original);
+ const showCustomerLink = programSlug
+ ? showDetailedAnalytics
+ : rowProgramEnrollment &&
+ getShowDetailedAnalytics(rowProgramEnrollment);
+
+ return row.original.customer ? (
<CustomerRowItem
customer={row.original.customer}
href={
- showDetailedAnalytics
- ? `/programs/${programSlug}/customers/${row.original.customer.id}`
+ showCustomerLink
+ ? `/programs/${row.original.program.slug}/customers/${row.original.customer.id}`
: undefined
}
className="px-4 py-2.5"
/>
) : (
<p className="px-4 py-2.5">-</p>
- ),
+ );
+ },
meta: {
filterParams: ({ row }) =>
row.original.customer
@@ -178,7 +240,9 @@ export function EarningsTablePartner({ limit }: { limit?: number }) {
: null,
},
},
- ...(programEnrollment?.rewards?.some((r) => r.event === "sale")
+ // the All programs page always shows the sale amount
+ ...(!programSlug ||
+ programEnrollment?.rewards?.some((r) => r.event === "sale")
? [
{
id: "amount",
@@ -262,14 +326,20 @@ export function EarningsTablePartner({ limit }: { limit?: number }) {
header: "Status",
cell: ({ row }) => {
const badge = CommissionStatusBadges[row.original.status];
+ const rowProgramEnrollment = getRowProgramEnrollment(row.original);
return (
<StatusBadge
icon={null}
variant={badge.variant}
tooltip={badge.tooltip({
- program: programEnrollment?.program,
- group: programEnrollment?.group ?? undefined,
+ // without the enrollment (for example a deactivated program), the
+ // tooltip still links to the program, without its minimum payout
+ program: rowProgramEnrollment?.program ?? {
+ ...row.original.program,
+ minPayoutAmount: 0,
+ },
+ group: rowProgramEnrollment?.group ?? undefined,
commission: row.original,
variant: "partner",
})}
@@ -310,7 +380,7 @@ export function EarningsTablePartner({ limit }: { limit?: number }) {
emptyState: (
<AnimatedEmptyState
title="No earnings found"
- description="No earnings have been made for this program yet."
+ description={emptyStateDescription}
cardContent={() => (
<>
<CircleDollar className="size-4 text-neutral-700" />
@@ -331,7 +401,7 @@ export function EarningsTablePartner({ limit }: { limit?: number }) {
) : (
<AnimatedEmptyState
title="No earnings found"
- description="No earnings have been made for this program yet."
+ description={emptyStateDescription}
cardContent={() => (
<>
<CircleDollar className="size-4 text-neutral-700" />
diff --git a/apps/web/ui/partners/earnings/use-partner-earnings-filters.ts b/apps/web/ui/partners/earnings/use-partner-earnings-filters.ts
index 002e04b28f..2a11cb2dcf 100644
--- a/apps/web/ui/partners/earnings/use-partner-earnings-filters.ts
+++ b/apps/web/ui/partners/earnings/use-partner-earnings-filters.ts
@@ -6,23 +6,38 @@ import { useMemo } from "react";
// the program, filters and date range of the partner Earnings pages, from the URL
export function usePartnerEarningsFilters() {
- const { programSlug } = useParams<{ programSlug: string }>();
+ const { programSlug } = useParams<{ programSlug?: string }>();
const { searchParamsObj } = useRouterStuff();
const dateRange = usePartnerDateRange();
- const { type, linkId, customerId, status, payoutId } =
- searchParamsObj as Omit<PartnerProfileEarningsFilters, "programIdOrSlug">;
+ const { programId, type, linkId, customerId, status, payoutId } =
+ searchParamsObj as Omit<
+ PartnerProfileEarningsFilters,
+ "programIdOrSlug"
+ > & {
+ programId?: string;
+ };
return useMemo(
() => ({
...dateRange,
- programIdOrSlug: programSlug,
+ // on the All programs page, the Program filter sets programId
+ programIdOrSlug: programSlug ?? programId,
type,
linkId,
customerId,
status,
payoutId,
}),
- [dateRange, programSlug, type, linkId, customerId, status, payoutId],
+ [
+ dateRange,
+ programSlug,
+ programId,
+ type,
+ linkId,
+ customerId,
+ status,
+ payoutId,
+ ],
);
}