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.

Add the earnings chart to the All programs Overview page

Rafidb9f58588d87
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/earnings-chart.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/earnings-chart.tsx
new file mode 100644
index 0000000000..d2ff922f1e
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/earnings-chart.tsx
@@ -0,0 +1,207 @@
+"use client";
+
+import { formatDateTooltip } from "@/lib/analytics/format-date-tooltip";
+import { usePartnerProfileEarningsTimeseries } from "@/lib/swr/use-partner-profile-earnings-timeseries";
+import useProgramEnrollments from "@/lib/swr/use-program-enrollments";
+import { buttonVariants } from "@dub/ui";
+import {
+ Areas,
+ ChartContext,
+ TimeSeriesChart,
+ XAxis,
+ YAxis,
+} from "@dub/ui/charts";
+import { LoadingSpinner } from "@dub/ui/icons";
+import { cn, currencyFormatter, nFormatter } from "@dub/utils";
+import NumberFlow from "@number-flow/react";
+import { LinearGradient } from "@visx/gradient";
+import { useRouter } from "next/navigation";
+import { useId, useMemo } from "react";
+import { ProgramLogo } from "./overview-card";
+import { useOverviewDateRange } from "./use-overview-date-range";
+
+const MAX_TOOLTIP_PROGRAMS = 5;
+
+export function EarningsChart() {
+ const id = useId();
+ const router = useRouter();
+ const { start, end, interval } = useOverviewDateRange();
+
+ const { data: timeseries, error } = usePartnerProfileEarningsTimeseries({
+ groupBy: "programId",
+ interval,
+ start,
+ end,
+ });
+
+ const { programEnrollments } = useProgramEnrollments();
+
+ const programs = useMemo(
+ () =>
+ new Map(
+ programEnrollments?.map(({ program }) => [program.id, program]) ?? [],
+ ),
+ [programEnrollments],
+ );
+
+ const total = useMemo(
+ () => timeseries?.reduce((acc, { earnings }) => acc + earnings, 0),
+ [timeseries],
+ );
+
+ const data = useMemo(
+ () =>
+ timeseries?.map(({ start, earnings, data }) => ({
+ date: new Date(start),
+ values: { main: earnings, programs: data ?? {} },
+ })),
+ [timeseries],
+ );
+
+ return (
+ <div className="flex flex-col rounded-xl border border-neutral-200 bg-white lg:h-[460px]">
+ <div className="px-5 py-4">
+ <h2 className="pt-0.5 text-base font-semibold leading-6 text-neutral-800">
+ Earnings
+ </h2>
+ {total !== undefined ? (
+ <NumberFlow
+ className="text-lg font-medium leading-7 text-neutral-600"
+ value={total / 100}
+ format={{
+ style: "currency",
+ currency: "USD",
+ // @ts-ignore - trailingZeroDisplay is a valid option but TS is outdated
+ trailingZeroDisplay: "stripIfInteger",
+ }}
+ />
+ ) : (
+ <div className="mt-0.5 h-7 w-24 animate-pulse rounded-md bg-neutral-200" />
+ )}
+ </div>
+ <div className="relative h-72 w-full px-5 pb-3 lg:h-auto lg:min-h-0 lg:flex-1">
+ {error ? (
+ <div className="flex size-full items-center justify-center">
+ <span className="text-sm text-neutral-500">
+ Failed to load earnings data.
+ </span>
+ </div>
+ ) : !data ? (
+ <div className="flex size-full items-center justify-center">
+ <LoadingSpinner />
+ </div>
+ ) : total === 0 ? (
+ <div className="flex size-full items-center justify-center">
+ <span className="text-sm text-neutral-500">
+ No earnings in this date range
+ </span>
+ </div>
+ ) : (
+ <TimeSeriesChart
+ data={data}
+ series={[
+ {
+ id: "main",
+ valueAccessor: (d) => d.values.main,
+ colorClassName: "text-[#DA2778]",
+ isActive: true,
+ },
+ ]}
+ onXValueClick={() => router.push("/programs")}
+ tooltipClassName="w-[200px] overflow-hidden p-0 shadow-md"
+ tooltipContent={(d) => {
+ const programEarnings = Object.entries(
+ d.values.programs as Record<string, number>,
+ )
+ .filter(([, earnings]) => earnings !== 0)
+ .sort(([, a], [, b]) => b - a)
+ .slice(0, MAX_TOOLTIP_PROGRAMS);
+
+ return (
+ <div className="text-[11px] leading-[1.1]">
+ <div className="border-b border-neutral-200 p-3 font-semibold text-neutral-900">
+ {formatDateTooltip(d.date, { interval, start, end })}
+ </div>
+ <div className="flex flex-col gap-3 p-3">
+ {programEarnings.length > 0 ? (
+ <div className="flex flex-col gap-2">
+ {programEarnings.map(([programId, earnings]) => {
+ const program = programs.get(programId);
+
+ return (
+ <div
+ key={programId}
+ className="flex items-center justify-between gap-2"
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ {program && (
+ <ProgramLogo
+ program={program}
+ className="size-3.5"
+ />
+ )}
+ <span className="truncate font-medium text-neutral-700">
+ {program?.name ?? programId}
+ </span>
+ </div>
+ <span className="shrink-0 text-neutral-500">
+ {currencyFormatter(earnings)}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ ) : (
+ <span className="text-neutral-500">No earnings</span>
+ )}
+ <div
+ className={cn(
+ buttonVariants({ variant: "secondary" }),
+ "flex h-6 items-center justify-center rounded-lg border text-sm font-medium",
+ )}
+ >
+ View all programs
+ </div>
+ </div>
+ </div>
+ );
+ }}
+ >
+ <ChartContext.Consumer>
+ {(context) => (
+ <LinearGradient
+ id={`${id}-color-gradient`}
+ from="#7D3AEC"
+ to="#DA2778"
+ x1={0}
+ x2={context?.width ?? 1}
+ gradientUnits="userSpaceOnUse"
+ />
+ )}
+ </ChartContext.Consumer>
+ <XAxis
+ showAxisLine={false}
+ tickFormat={(date) =>
+ formatDateTooltip(date, { interval, start, end })
+ }
+ />
+ <YAxis
+ showGridLines
+ tickFormat={(value) => `$${nFormatter(value / 100)}`}
+ />
+ <Areas
+ seriesStyles={[
+ {
+ id: "main",
+ areaFill: `url(#${id}-color-gradient)`,
+ lineStroke: `url(#${id}-color-gradient)`,
+ lineClassName: "text-[#DA2778]",
+ },
+ ]}
+ />
+ </TimeSeriesChart>
+ )}
+ </div>
+ </div>
+ );
+}
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 0a45e8974c..cba9ac3c35 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
@@ -1,5 +1,5 @@
import { buttonVariants } from "@dub/ui";
-import { cn } from "@dub/utils";
+import { cn, OG_AVATAR_URL } from "@dub/utils";
import Link from "next/link";
import { Fragment, ReactNode } from "react";
@@ -114,5 +114,25 @@ export function OverviewCardMessage({
);
}
+export function ProgramLogo({
+ program,
+ className,
+}: {
+ program: { name: string; logo: string | null };
+ className?: string;
+}) {
+ return (
+ <img
+ src={program.logo || `${OG_AVATAR_URL}${program.name}`}
+ alt={program.name}
+ referrerPolicy="no-referrer"
+ className={cn(
+ "size-5 shrink-0 rounded-full border border-black/10",
+ className,
+ )}
+ />
+ );
+}
+
export const OVERVIEW_CARD_ROW_CLASSNAME =
"flex items-center gap-2.5 rounded-lg px-3 py-2.5";
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/page-client.tsx
index f29020117c..d48606e5d5 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/page-client.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/overview/page-client.tsx
@@ -3,6 +3,7 @@
import { DUB_PARTNERS_ANALYTICS_INTERVAL } from "@/lib/analytics/constants";
import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
import SimpleDateRangePicker from "@/ui/shared/simple-date-range-picker";
+import { EarningsChart } from "./earnings-chart";
export function PartnerOverviewPageClient() {
return (
@@ -14,6 +15,7 @@ export function PartnerOverviewPageClient() {
/>
<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 flex-col gap-3" />
</div>
</div>
diff --git a/apps/web/lib/swr/use-partner-profile-earnings-timeseries.ts b/apps/web/lib/swr/use-partner-profile-earnings-timeseries.ts
new file mode 100644
index 0000000000..44cc19bc6f
--- /dev/null
+++ b/apps/web/lib/swr/use-partner-profile-earnings-timeseries.ts
@@ -0,0 +1,56 @@
+import { fetcher } from "@dub/utils";
+import { useSession } from "next-auth/react";
+import useSWR from "swr";
+import * as z from "zod/v4";
+import { DUB_PARTNERS_ANALYTICS_INTERVAL } from "../analytics/constants";
+import { partnerProfileEarningsTimeseriesQuerySchema } from "../zod/schemas/partner-profile";
+
+export type PartnerProfileEarningsTimeseries = {
+ start: string;
+ earnings: number;
+ groupBy?: string;
+ data?: Record<string, number>;
+}[];
+
+export function usePartnerProfileEarningsTimeseries({
+ groupBy,
+ programIdOrSlug,
+ interval,
+ start,
+ end,
+ enabled = true,
+}: Pick<
+ z.input<typeof partnerProfileEarningsTimeseriesQuerySchema>,
+ "groupBy" | "programIdOrSlug" | "interval"
+> & {
+ start?: Date;
+ end?: Date;
+ enabled?: boolean;
+}) {
+ const { data: session } = useSession();
+ const partnerId = session?.user?.["defaultPartnerId"];
+
+ const { data, error } = useSWR<PartnerProfileEarningsTimeseries>(
+ enabled &&
+ partnerId &&
+ `/api/partner-profile/earnings/timeseries?${new URLSearchParams({
+ ...(groupBy && { groupBy }),
+ ...(programIdOrSlug && { programIdOrSlug }),
+ ...(start && end
+ ? { start: start.toISOString(), end: end.toISOString() }
+ : { interval: interval ?? DUB_PARTNERS_ANALYTICS_INTERVAL }),
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ })}`,
+ fetcher,
+ {
+ dedupingInterval: 60000,
+ keepPreviousData: true,
+ },
+ );
+
+ return {
+ data,
+ error,
+ loading: !data && !error,
+ };
+}