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.

incorporate more admin metrics

Steven Tey25558e5e366a
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/layout.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/layout.tsx
new file mode 100644
index 0000000000..73381fbc47
--- /dev/null
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/layout.tsx
@@ -0,0 +1,22 @@
+import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
+import { Suspense } from "react";
+import { ProgramsNavTabs } from "./programs-nav-tabs";
+
+export default function AdminProgramsLayout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ return (
+ <PageWidthWrapper className="pb-12 pt-4">
+ <div className="border-border-subtle overflow-hidden rounded-xl border bg-neutral-100">
+ <Suspense>
+ <ProgramsNavTabs />
+ <div className="border-border-subtle -mx-px -mb-px space-y-4 rounded-xl border bg-white">
+ {children}
+ </div>
+ </Suspense>
+ </div>
+ </PageWidthWrapper>
+ );
+}
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/marketplace/page.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/marketplace/page.tsx
new file mode 100644
index 0000000000..bee8ff3025
--- /dev/null
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/marketplace/page.tsx
@@ -0,0 +1 @@
+export { default } from "../page";
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/programs-nav-tabs.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/programs-nav-tabs.tsx
new file mode 100644
index 0000000000..f516b8c499
--- /dev/null
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/programs-nav-tabs.tsx
@@ -0,0 +1,25 @@
+"use client";
+
+import { PageNavTabs } from "@/ui/layout/page-nav-tabs";
+import { CrownSmall, GridIcon } from "@dub/ui";
+import { useMemo } from "react";
+
+export function ProgramsNavTabs() {
+ const tabs = useMemo(
+ () => [
+ {
+ id: "marketplace",
+ label: "Marketplace",
+ icon: GridIcon,
+ },
+ {
+ id: "sales",
+ label: "Top programs by sales",
+ icon: CrownSmall,
+ },
+ ],
+ [],
+ );
+
+ return <PageNavTabs basePath="/programs" tabs={tabs} />;
+}
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/sales/page.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/sales/page.tsx
new file mode 100644
index 0000000000..d32c4e530c
--- /dev/null
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/programs/sales/page.tsx
@@ -0,0 +1,188 @@
+"use client";
+
+import SimpleDateRangePicker from "@/ui/shared/simple-date-range-picker";
+import {
+ CrownSmall,
+ Table,
+ usePagination,
+ useRouterStuff,
+ useTable,
+} from "@dub/ui";
+import { cn, currencyFormatter, fetcher, nFormatter } from "@dub/utils";
+import NumberFlow from "@number-flow/react";
+import { Suspense, useMemo } from "react";
+import useSWR from "swr";
+
+export default function ProgramSalesPage() {
+ return (
+ <Suspense>
+ <ProgramSalesPageClient />
+ </Suspense>
+ );
+}
+
+function ProgramSalesPageClient() {
+ const { getQueryString } = useRouterStuff();
+
+ const { data: { programs } = {}, isLoading } = useSWR<{
+ programs: {
+ id: string;
+ name: string;
+ logo: string;
+ partners: number;
+ sales: number;
+ saleAmount: number;
+ }[];
+ }>(`/api/admin/programs/sales${getQueryString()}`, fetcher, {
+ keepPreviousData: true,
+ });
+
+ const { pagination, setPagination } = usePagination();
+
+ const { table, ...tableProps } = useTable({
+ data: programs ?? [],
+ columns: [
+ {
+ id: "position",
+ header: "Position",
+ size: 12,
+ minSize: 12,
+ maxSize: 12,
+ cell: ({ row }) => {
+ return (
+ <div className="flex w-28 items-center justify-start gap-2 tabular-nums">
+ {row.index + 1}
+ {row.index <= 2 && (
+ <CrownSmall
+ className={cn("size-4", {
+ "text-amber-400": row.index === 0,
+ "text-neutral-400": row.index === 1,
+ "text-yellow-900": row.index === 2,
+ })}
+ />
+ )}
+ </div>
+ );
+ },
+ },
+ {
+ id: "program",
+ header: "Program",
+ cell: ({ row }) => (
+ <div className="flex items-center gap-1.5">
+ <img
+ src={row.original.logo}
+ alt={row.original.name}
+ width={20}
+ height={20}
+ className="size-4 rounded-full"
+ />
+ <span className="text-sm font-medium">{row.original.name}</span>
+ </div>
+ ),
+ },
+ {
+ id: "partners",
+ header: "Active Partners",
+ accessorKey: "partners",
+ cell: ({ row }) => nFormatter(row.original.partners, { full: true }),
+ },
+ {
+ id: "sales",
+ header: "Total Sales",
+ accessorKey: "sales",
+ cell: ({ row }) => nFormatter(row.original.sales, { full: true }),
+ },
+ {
+ id: "revenue",
+ header: "Affiliate Revenue",
+ accessorKey: "revenue",
+ cell: ({ row }) => currencyFormatter(row.original.saleAmount),
+ },
+ ],
+ pagination,
+ onPaginationChange: setPagination,
+ resourceName: (plural) => `program${plural ? "s" : ""}`,
+ rowCount: programs?.length ?? 0,
+ loading: isLoading,
+ });
+
+ const stats = useMemo(
+ () => [
+ {
+ id: "partners",
+ label: "Active Partners",
+ value: programs?.reduce(
+ (acc, { partners }) => acc + (partners || 0),
+ 0,
+ ),
+ colorClassName: "bg-blue-500",
+ },
+ {
+ id: "sales",
+ label: "Total Sales",
+ value: programs?.reduce((acc, { sales }) => acc + (sales || 0), 0),
+ colorClassName: "bg-green-500",
+ },
+ {
+ id: "revenue",
+ label: "Affiliate Revenue",
+ value: programs?.reduce(
+ (acc, { saleAmount }) => acc + (saleAmount || 0),
+ 0,
+ ),
+ colorClassName: "bg-purple-500",
+ },
+ ],
+ [programs],
+ );
+
+ return (
+ <div className="mx-auto flex w-full max-w-screen-xl flex-col space-y-6 p-6">
+ <SimpleDateRangePicker defaultInterval="mtd" className="w-fit" />
+ <div className="flex flex-col divide-y divide-neutral-200 rounded-lg border border-neutral-200 bg-white">
+ <div className="grid w-full grid-cols-1 divide-x sm:grid-cols-3">
+ {stats.map(({ id, label, value, colorClassName }) => (
+ <div key={id} className="flex-none px-4 py-3 sm:px-8 sm:py-6">
+ <div className="flex items-center gap-2.5 text-sm text-neutral-600">
+ <div
+ className={cn(
+ "h-2 w-2 rounded-sm shadow-[inset_0_0_0_1px_#00000019]",
+ colorClassName,
+ )}
+ />
+ <span>{label}</span>
+ </div>
+ <div className="mt-1 flex h-12 items-center">
+ {value !== undefined ? (
+ id === "revenue" ? (
+ <NumberFlow
+ value={value / 100}
+ className="text-xl font-medium sm:text-3xl"
+ format={{
+ style: "currency",
+ currency: "USD",
+ // @ts-ignore – trailingZeroDisplay is a valid option but TS is outdated
+ trailingZeroDisplay: "stripIfInteger",
+ }}
+ />
+ ) : (
+ <NumberFlow
+ value={value}
+ className="text-xl font-medium sm:text-3xl"
+ />
+ )
+ ) : (
+ <div className="h-10 w-24 animate-pulse rounded-md bg-neutral-200" />
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ <div className="w-full">
+ <Table {...tableProps} table={table} />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/revenue/page.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/revenue/page.tsx
index 128fef9ce5..7eed0344d9 100644
--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/revenue/page.tsx
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/revenue/page.tsx
@@ -1,18 +1,39 @@
"use client";
+import { formatDateTooltip } from "@/lib/analytics/format-date-tooltip";
+import { AnalyticsLoadingSpinner } from "@/ui/analytics/analytics-loading-spinner";
import SimpleDateRangePicker from "@/ui/shared/simple-date-range-picker";
-import {
- CrownSmall,
- Table,
- usePagination,
- useRouterStuff,
- useTable,
-} from "@dub/ui";
-import { cn, currencyFormatter, fetcher, nFormatter } from "@dub/utils";
+import { useRouterStuff } from "@dub/ui";
+import { Areas, TimeSeriesChart, XAxis, YAxis } from "@dub/ui/charts";
+import { cn, currencyFormatter, fetcher } from "@dub/utils";
import NumberFlow from "@number-flow/react";
-import { Suspense, useMemo } from "react";
+import { Fragment, Suspense, useMemo } from "react";
import useSWR from "swr";
+const revenueTabs = [
+ {
+ id: "totalRevenue",
+ label: "Total Revenue",
+ colorClassName: "text-green-500 bg-green-500/50 border-green-500",
+ },
+ {
+ id: "mrr",
+ label: "MRR",
+ colorClassName: "text-blue-500 bg-blue-500/50 border-blue-500",
+ },
+ {
+ id: "payoutFees",
+ label: "Payout Fees",
+ colorClassName: "text-orange-500 bg-orange-500/50 border-orange-500",
+ },
+] as const;
+
+type RevenueTab = (typeof revenueTabs)[number]["id"];
+
+function isRevenueTab(value: string): value is RevenueTab {
+ return revenueTabs.some((tab) => tab.id === value);
+}
+
export default function RevenuePage() {
return (
<Suspense>
@@ -22,166 +43,195 @@ export default function RevenuePage() {
}
function RevenuePageClient() {
- const { getQueryString } = useRouterStuff();
+ const { getQueryString, queryParams, searchParamsObj } = useRouterStuff();
+ const { interval, start, end, tab } = searchParamsObj;
+ const selectedTab = isRevenueTab(tab) ? tab : "totalRevenue";
+ const selectedTabConfig =
+ revenueTabs.find((revenueTab) => revenueTab.id === selectedTab) ??
+ revenueTabs[0];
- const { data: { programs } = {}, isLoading } = useSWR<{
- programs: {
- id: string;
- name: string;
- logo: string;
- partners: number;
- sales: number;
- saleAmount: number;
+ const { data: { timeseries } = {}, isLoading } = useSWR<{
+ timeseries: {
+ date: Date;
+ mrr: number;
+ payoutFees: number;
+ totalRevenue: number;
}[];
}>(`/api/admin/revenue${getQueryString()}`, fetcher, {
keepPreviousData: true,
});
- const { pagination, setPagination } = usePagination();
-
- const { table, ...tableProps } = useTable({
- data: programs ?? [],
- columns: [
- {
- id: "position",
- header: "Position",
- size: 12,
- minSize: 12,
- maxSize: 12,
- cell: ({ row }) => {
- return (
- <div className="flex w-28 items-center justify-start gap-2 tabular-nums">
- {row.index + 1}
- {row.index <= 2 && (
- <CrownSmall
- className={cn("size-4", {
- "text-amber-400": row.index === 0,
- "text-neutral-400": row.index === 1,
- "text-yellow-900": row.index === 2,
- })}
- />
- )}
- </div>
- );
- },
- },
- {
- id: "program",
- header: "Program",
- cell: ({ row }) => (
- <div className="flex items-center gap-1.5">
- <img
- src={row.original.logo}
- alt={row.original.name}
- width={20}
- height={20}
- className="size-4 rounded-full"
- />
- <span className="text-sm font-medium">{row.original.name}</span>
- </div>
- ),
- },
- {
- id: "partners",
- header: "Active Partners",
- accessorKey: "partners",
- cell: ({ row }) => nFormatter(row.original.partners, { full: true }),
- },
- {
- id: "sales",
- header: "Total Sales",
- accessorKey: "sales",
- cell: ({ row }) => nFormatter(row.original.sales, { full: true }),
- },
- {
- id: "revenue",
- header: "Affiliate Revenue",
- accessorKey: "revenue",
- cell: ({ row }) => currencyFormatter(row.original.saleAmount),
- },
- ],
- pagination,
- onPaginationChange: setPagination,
- resourceName: (plural) => `program${plural ? "s" : ""}`,
- rowCount: programs?.length ?? 0,
- loading: isLoading,
- });
+ const chartData =
+ timeseries?.map(({ date, ...values }) => ({
+ date: new Date(date),
+ values,
+ })) ?? null;
- const stats = useMemo(
- () => [
- {
- id: "partners",
- label: "Active Partners",
- value: programs?.reduce(
- (acc, { partners }) => acc + (partners || 0),
+ const totals = useMemo(
+ () => ({
+ totalRevenue:
+ timeseries?.reduce(
+ (acc, { totalRevenue }) => acc + (totalRevenue || 0),
0,
- ),
- colorClassName: "bg-blue-500",
- },
- {
- id: "sales",
- label: "Total Sales",
- value: programs?.reduce((acc, { sales }) => acc + (sales || 0), 0),
- colorClassName: "bg-green-500",
- },
- {
- id: "revenue",
- label: "Affiliate Revenue",
- value: programs?.reduce(
- (acc, { saleAmount }) => acc + (saleAmount || 0),
+ ) ?? 0,
+ mrr: timeseries?.reduce((acc, { mrr }) => acc + (mrr || 0), 0) ?? 0,
+ payoutFees:
+ timeseries?.reduce(
+ (acc, { payoutFees }) => acc + (payoutFees || 0),
0,
- ),
- colorClassName: "bg-purple-500",
- },
- ],
- [programs],
+ ) ?? 0,
+ }),
+ [timeseries],
);
return (
<div className="mx-auto flex w-full max-w-screen-xl flex-col space-y-6 p-6">
- <SimpleDateRangePicker defaultInterval="mtd" className="w-fit" />
+ <SimpleDateRangePicker
+ defaultInterval="mtd"
+ presets={["30d", "90d", "mtd", "qtd", "ytd", "1y", "all"]}
+ className="w-fit"
+ />
<div className="flex flex-col divide-y divide-neutral-200 rounded-lg border border-neutral-200 bg-white">
<div className="grid w-full grid-cols-1 divide-x sm:grid-cols-3">
- {stats.map(({ id, label, value, colorClassName }) => (
- <div key={id} className="flex-none px-4 py-3 sm:px-8 sm:py-6">
+ {revenueTabs.map(({ id, label, colorClassName }) => (
+ <button
+ key={id}
+ onClick={() =>
+ queryParams({
+ set: { tab: id },
+ })
+ }
+ className={cn(
+ "border-box relative block h-full w-full flex-none px-4 py-3 text-left sm:px-8 sm:py-6",
+ "transition-colors hover:bg-neutral-50 focus:outline-none active:bg-neutral-100",
+ "ring-inset ring-neutral-500 focus-visible:ring-1",
+ )}
+ >
+ {selectedTab === id && (
+ <div className="absolute bottom-0 left-0 h-0.5 w-full bg-black" />
+ )}
<div className="flex items-center gap-2.5 text-sm text-neutral-600">
<div
className={cn(
- "h-2 w-2 rounded-sm shadow-[inset_0_0_0_1px_#00000019]",
+ "h-2 w-2 rounded-sm bg-current shadow-[inset_0_0_0_1px_#00000019]",
colorClassName,
)}
/>
<span>{label}</span>
</div>
<div className="mt-1 flex h-12 items-center">
- {value !== undefined ? (
- id === "revenue" ? (
- <NumberFlow
- value={value / 100}
- className="text-xl font-medium sm:text-3xl"
- format={{
- style: "currency",
- currency: "USD",
- // @ts-ignore – trailingZeroDisplay is a valid option but TS is outdated
- trailingZeroDisplay: "stripIfInteger",
- }}
- />
- ) : (
- <NumberFlow
- value={value}
- className="text-xl font-medium sm:text-3xl"
- />
- )
+ {(totals[id] || totals[id] === 0) && !isLoading ? (
+ <NumberFlow
+ value={(totals[id] ?? 0) / 100}
+ className="text-xl font-medium sm:text-3xl"
+ format={{
+ style: "currency",
+ currency: "USD",
+ // @ts-ignore – trailingZeroDisplay is a valid option but TS is outdated
+ trailingZeroDisplay: "stripIfInteger",
+ }}
+ />
) : (
<div className="h-10 w-24 animate-pulse rounded-md bg-neutral-200" />
)}
</div>
- </div>
+ </button>
))}
</div>
- </div>
- <div className="w-full">
- <Table {...tableProps} table={table} />
+ <div className="p-5 sm:p-10">
+ <div className="flex h-96 w-full items-center justify-center">
+ {chartData ? (
+ chartData.length > 0 ? (
+ <TimeSeriesChart
+ data={chartData}
+ series={[
+ {
+ id: "totalRevenue",
+ valueAccessor: (d) => d.values.totalRevenue,
+ isActive: selectedTab === "totalRevenue",
+ colorClassName: revenueTabs[0].colorClassName,
+ },
+ {
+ id: "mrr",
+ valueAccessor: (d) => d.values.mrr,
+ isActive:
+ selectedTab === "mrr" || selectedTab === "totalRevenue",
+ colorClassName: revenueTabs[1].colorClassName,
+ },
+ {
+ id: "payoutFees",
+ valueAccessor: (d) => d.values.payoutFees,
+ isActive:
+ selectedTab === "payoutFees" ||
+ selectedTab === "totalRevenue",
+ colorClassName: revenueTabs[2].colorClassName,
+ },
+ ]}
+ tooltipClassName="p-0"
+ tooltipContent={(d) => {
+ const rows =
+ selectedTab === "totalRevenue"
+ ? revenueTabs
+ : revenueTabs.filter(({ id }) => id === selectedTab);
+ return (
+ <>
+ <p className="border-b border-neutral-200 px-4 py-3 text-sm text-neutral-900">
+ {formatDateTooltip(d.date, {
+ interval,
+ start,
+ end,
+ timezone: "UTC",
+ })}
+ </p>
+ <div className="grid grid-cols-2 gap-x-6 gap-y-2 px-4 py-3 text-sm">
+ {rows.map(({ id, label, colorClassName }) => (
+ <Fragment key={id}>
+ <div className="flex items-center gap-2">
+ <div
+ className={cn(
+ "h-2 w-2 rounded-sm bg-current shadow-[inset_0_0_0_1px_#0003]",
+ colorClassName,
+ )}
+ />
+ <p className="text-neutral-600">{label}</p>
+ </div>
+ <p className="text-right font-medium text-neutral-900">
+ {currencyFormatter(d.values[id])}
+ </p>
+ </Fragment>
+ ))}
+ </div>
+ </>
+ );
+ }}
+ >
+ <Areas />
+ <XAxis
+ maxTicks={5}
+ tickFormat={(date) =>
+ formatDateTooltip(date, {
+ interval,
+ start,
+ end,
+ timezone: "UTC",
+ })
+ }
+ />
+ <YAxis
+ showGridLines
+ tickFormat={(value) => currencyFormatter(value)}
+ />
+ </TimeSeriesChart>
+ ) : (
+ <div className="text-center text-sm text-neutral-600">
+ No data available.
+ </div>
+ )
+ ) : (
+ <AnalyticsLoadingSpinner />
+ )}
+ </div>
+ </div>
</div>
</div>
);
diff --git a/apps/web/app/(ee)/api/admin/payouts/get-payouts-timeseries.ts b/apps/web/app/(ee)/api/admin/payouts/get-payouts-timeseries.ts
new file mode 100644
index 0000000000..f881623140
--- /dev/null
+++ b/apps/web/app/(ee)/api/admin/payouts/get-payouts-timeseries.ts
@@ -0,0 +1,83 @@
+import { sqlGranularityMap } from "@/lib/planetscale/granularity";
+import { prisma } from "@dub/prisma";
+import { InvoiceStatus, Prisma } from "@dub/prisma/client";
+import { ACME_PROGRAM_ID } from "@dub/utils";
+import { format } from "date-fns";
+
+interface TimeseriesPoint {
+ payouts: number;
+ fees: number;
+ total: number;
+}
+
+export interface FormattedPayoutsTimeseriesPoint extends TimeseriesPoint {
+ date: Date;
+}
+
+export async function getPayoutsTimeseries({
+ programId,
+ status,
+ startDate,
+ endDate,
+ granularity,
+ timezone = "UTC",
+}: {
+ programId?: string;
+ status?: InvoiceStatus;
+ startDate: Date;
+ endDate: Date;
+ granularity: keyof typeof sqlGranularityMap;
+ timezone?: string;
+}) {
+ const { dateFormat, dateIncrement, startFunction, formatString } =
+ sqlGranularityMap[granularity];
+
+ const timeseriesData = await prisma.$queryRaw<
+ { date: Date; payouts: number; fees: number; total: number }[]
+ >`
+ SELECT
+ DATE_FORMAT(CONVERT_TZ(createdAt, "UTC", ${timezone}), ${dateFormat}) as date,
+ SUM(amount) as payouts,
+ SUM(fee) as fees,
+ SUM(total) as total
+ FROM Invoice
+ WHERE
+ ${programId ? Prisma.sql`programId = ${programId}` : Prisma.sql`programId != ${ACME_PROGRAM_ID}`}
+ AND ${status ? Prisma.sql`status = ${status}` : Prisma.sql`status != 'failed'`}
+ AND createdAt >= ${startDate}
+ AND createdAt <= ${endDate}
+ GROUP BY DATE_FORMAT(CONVERT_TZ(createdAt, "UTC", ${timezone}), ${dateFormat})
+ ORDER BY date ASC;
+ `;
+
+ const timeseriesLookup: Record<string, TimeseriesPoint> = Object.fromEntries(
+ timeseriesData.map((item) => [
+ item.date,
+ {
+ payouts: Number(item.payouts),
+ fees: Number(item.fees),
+ total: Number(item.total),
+ },
+ ]),
+ );
+
+ let currentDate = startFunction(startDate);
+ const formattedTimeseriesData: FormattedPayoutsTimeseriesPoint[] = [];
+
+ while (currentDate < endDate) {
+ const periodKey = format(currentDate, formatString);
+
+ formattedTimeseriesData.push({
+ date: currentDate,
+ ...(timeseriesLookup[periodKey] || {
+ payouts: 0,
+ fees: 0,
+ total: 0,
+ }),
+ });
+
+ currentDate = dateIncrement(currentDate);
+ }
+
+ return formattedTimeseriesData;
+}
diff --git a/apps/web/app/(ee)/api/admin/payouts/route.ts b/apps/web/app/(ee)/api/admin/payouts/route.ts
index 848a6930dd..59ee839f7b 100644
--- a/apps/web/app/(ee)/api/admin/payouts/route.ts
+++ b/apps/web/app/(ee)/api/admin/payouts/route.ts
@@ -1,23 +1,12 @@
import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";
import { withAdmin } from "@/lib/auth";
-import { sqlGranularityMap } from "@/lib/planetscale/granularity";
import { analyticsQuerySchema } from "@/lib/zod/schemas/analytics";
import { prisma } from "@dub/prisma";
-import { InvoiceStatus, Prisma } from "@dub/prisma/client";
+import { InvoiceStatus } from "@dub/prisma/client";
import { ACME_PROGRAM_ID } from "@dub/utils";
-import { format } from "date-fns";
import { NextResponse } from "next/server";
import * as z from "zod/v4";
-
-interface TimeseriesPoint {
- payouts: number;
- fees: number;
- total: number;
-}
-
-interface FormattedTimeseriesPoint extends TimeseriesPoint {
- date: Date;
-}
+import { getPayoutsTimeseries } from "./get-payouts-timeseries";
const adminPayoutsQuerySchema = z
.object({
@@ -85,27 +74,14 @@ export const GET = withAdmin(async ({ searchParams }) => {
},
});
- const { dateFormat, dateIncrement, startFunction, formatString } =
- sqlGranularityMap[granularity];
-
- // Calculate timeseries data for payouts and fees
- const timeseriesData = await prisma.$queryRaw<
- { date: Date; payouts: number; fees: number; total: number }[]
- >`
- SELECT
- DATE_FORMAT(CONVERT_TZ(createdAt, "UTC", ${timezone}), ${dateFormat}) as date,
- SUM(amount) as payouts,
- SUM(fee) as fees,
- SUM(total) as total
- FROM Invoice
- WHERE
- ${programId ? Prisma.sql`programId = ${programId}` : Prisma.sql`programId != ${ACME_PROGRAM_ID}`}
- AND ${status ? Prisma.sql`status = ${status}` : Prisma.sql`status != 'failed'`}
- AND createdAt >= ${startDate}
- AND createdAt <= ${endDate}
- GROUP BY DATE_FORMAT(CONVERT_TZ(createdAt, "UTC", ${timezone}), ${dateFormat})
- ORDER BY date ASC;
- `;
+ const timeseriesData = await getPayoutsTimeseries({
+ programId,
+ status,
+ startDate,
+ endDate,
+ granularity,
+ timezone,
+ });
const formattedInvoices = invoices.map((invoice) => ({
date: invoice.createdAt,
@@ -119,40 +95,8 @@ export const GET = withAdmin(async ({ searchParams }) => {
total: invoice.total,
}));
- // Create a lookup object for the timeseries data
- const timeseriesLookup: Record<string, TimeseriesPoint> = Object.fromEntries(
- timeseriesData.map((item) => [
- item.date,
- {
- payouts: Number(item.payouts),
- fees: Number(item.fees),
- total: Number(item.total),
- },
- ]),
- );
-
- // Backfill missing dates with 0 values
- let currentDate = startFunction(startDate);
-
- const formattedTimeseriesData: FormattedTimeseriesPoint[] = [];
-
- while (currentDate < endDate) {
- const periodKey = format(currentDate, formatString);
-
- formattedTimeseriesData.push({
- date: currentDate,
- ...(timeseriesLookup[periodKey] || {
- payouts: 0,
- fees: 0,
- total: 0,
- }),
- });
-
- currentDate = dateIncrement(currentDate);
- }
-
return NextResponse.json({
invoices: formattedInvoices,
- timeseriesData: formattedTimeseriesData,
+ timeseriesData,
});
});
diff --git a/apps/web/app/(ee)/api/admin/revenue/get-top-programs-by-sales.ts b/apps/web/app/(ee)/api/admin/programs/sales/get-top-programs-by-sales.ts
similarity index 100%
rename from apps/web/app/(ee)/api/admin/revenue/get-top-programs-by-sales.ts
rename to apps/web/app/(ee)/api/admin/programs/sales/get-top-programs-by-sales.ts
diff --git a/apps/web/app/(ee)/api/admin/programs/sales/route.ts b/apps/web/app/(ee)/api/admin/programs/sales/route.ts
new file mode 100644
index 0000000000..20564ed640
--- /dev/null
+++ b/apps/web/app/(ee)/api/admin/programs/sales/route.ts
@@ -0,0 +1,26 @@
+import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";
+import { withAdmin } from "@/lib/auth";
+import { DUB_FOUNDING_DATE } from "@dub/utils";
+import { endOfDay, startOfDay } from "date-fns";
+import { NextResponse } from "next/server";
+import { getTopProgramsBySales } from "./get-top-programs-by-sales";
+
+export const GET = withAdmin(async ({ searchParams }) => {
+ const { interval = "mtd", start, end } = searchParams;
+
+ const { startDate, endDate } = getStartEndDates({
+ interval,
+ start: start ? startOfDay(new Date(start)) : undefined,
+ end: end ? endOfDay(new Date(end)) : undefined,
+ dataAvailableFrom: DUB_FOUNDING_DATE,
+ });
+
+ const programs = await getTopProgramsBySales({
+ startDate,
+ endDate,
+ });
+
+ return NextResponse.json({
+ programs,
+ });
+});
diff --git a/apps/web/app/(ee)/api/admin/revenue/get-mrr-timeseries.ts b/apps/web/app/(ee)/api/admin/revenue/get-mrr-timeseries.ts
new file mode 100644
index 0000000000..24fb3182fd
--- /dev/null
+++ b/apps/web/app/(ee)/api/admin/revenue/get-mrr-timeseries.ts
@@ -0,0 +1,98 @@
+import { differenceInDays } from "date-fns";
+
+type RevenueGranularity = "day" | "month";
+
+type StripeMetricQueryResponse = {
+ data?: {
+ timestamp: string;
+ results: {
+ name?: string;
+ value: number;
+ }[];
+ }[];
+};
+
+type StripeErrorResponse = {
+ error?: {
+ code?: string;
+ message?: string;
+ };
+};
+
+export const getBucketKey = (
+ timestamp: string | Date,
+ granularity: RevenueGranularity,
+) => {
+ const iso =
+ typeof timestamp === "string"
+ ? new Date(timestamp).toISOString()
+ : timestamp.toISOString();
+
+ return granularity === "month" ? iso.slice(0, 7) : iso.slice(0, 10);
+};
+
+const getStripeGranularity = ({
+ granularity,
+ startDate,
+ endDate,
+}: {
+ granularity: RevenueGranularity;
+ startDate: Date;
+ endDate: Date;
+}) => {
+ if (granularity === "month") {
+ return "month";
+ }
+
+ const totalDays = differenceInDays(endDate, startDate);
+ return totalDays > 92 ? "month" : "day";
+};
+
+export async function getMrrByBucket({
+ startDate,
+ endDate,
+ granularity,
+}: {
+ startDate: Date;
+ endDate: Date;
+ granularity: RevenueGranularity;
+}) {
+ if (!process.env.STRIPE_SECRET_KEY) {
+ return new Map<string, number>();
+ }
+
+ const response = await fetch(
+ "https://api.stripe.com/v2/data/analytics/metric_query",
+ {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
+ "Content-Type": "application/json",
+ "Stripe-Version": "2026-04-22.preview",
+ },
+ body: JSON.stringify({
+ metrics: [{ name: "revenue.mrr" }],
+ starts_at: startDate.toISOString(),
+ ends_at: endDate.toISOString(),
+ granularity: getStripeGranularity({ granularity, startDate, endDate }),
+ currency: "usd",
+ }),
+ },
+ );
+
+ const responseBody = (await response.json().catch(() => ({}))) as
+ | StripeMetricQueryResponse
+ | StripeErrorResponse;
+
+ if (response.ok) {
+ const lookup = new Map<string, number>();
+ (responseBody as StripeMetricQueryResponse).data?.forEach((row) => {
+ const key = getBucketKey(row.timestamp, granularity);
+ const mrr =
+ row.results.find((result) => result.name === "revenue.mrr")?.value ?? 0;
+ lookup.set(key, (lookup.get(key) ?? 0) + mrr);
+ });
+ return lookup;
+ }
+ return new Map<string, number>();
+}
diff --git a/apps/web/app/(ee)/api/admin/revenue/route.ts b/apps/web/app/(ee)/api/admin/revenue/route.ts
index 20564ed640..ddbaac674e 100644
--- a/apps/web/app/(ee)/api/admin/revenue/route.ts
+++ b/apps/web/app/(ee)/api/admin/revenue/route.ts
@@ -1,26 +1,69 @@
import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";
import { withAdmin } from "@/lib/auth";
+import { analyticsQuerySchema } from "@/lib/zod/schemas/analytics";
import { DUB_FOUNDING_DATE } from "@dub/utils";
import { endOfDay, startOfDay } from "date-fns";
import { NextResponse } from "next/server";
-import { getTopProgramsBySales } from "./get-top-programs-by-sales";
+import * as z from "zod/v4";
+import { getPayoutsTimeseries } from "../payouts/get-payouts-timeseries";
+import { getBucketKey, getMrrByBucket } from "./get-mrr-timeseries";
+
+const adminRevenueQuerySchema = z
+ .object({})
+ .extend(
+ analyticsQuerySchema.pick({ interval: true, start: true, end: true }).shape,
+ );
export const GET = withAdmin(async ({ searchParams }) => {
- const { interval = "mtd", start, end } = searchParams;
+ const {
+ interval = "mtd",
+ start,
+ end,
+ } = adminRevenueQuerySchema.parse(searchParams);
- const { startDate, endDate } = getStartEndDates({
+ const timezone = "UTC";
+ const { startDate, endDate, granularity } = getStartEndDates({
interval,
start: start ? startOfDay(new Date(start)) : undefined,
end: end ? endOfDay(new Date(end)) : undefined,
dataAvailableFrom: DUB_FOUNDING_DATE,
+ timezone,
});
- const programs = await getTopProgramsBySales({
- startDate,
- endDate,
+ const revenueGranularity = granularity === "month" ? "month" : "day";
+
+ const [mrrLookup, payoutTimeseries] = await Promise.all([
+ getMrrByBucket({
+ startDate,
+ endDate,
+ granularity: revenueGranularity,
+ }).catch((error) => {
+ console.error(error);
+ return new Map<string, number>();
+ }),
+ getPayoutsTimeseries({
+ startDate,
+ endDate,
+ granularity: revenueGranularity,
+ timezone,
+ }),
+ ]);
+
+ console.log({ payoutTimeseries });
+
+ const timeseries = payoutTimeseries.map(({ date, fees }) => {
+ const mrr = mrrLookup.get(getBucketKey(date, revenueGranularity)) ?? 0;
+ return {
+ date,
+ mrr,
+ payoutFees: fees,
+ totalRevenue: mrr + fees,
+ };
});
+ console.log({ timeseries });
+
return NextResponse.json({
- programs,
+ timeseries,
});
});