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.

Top programs admin tab

Steven Tey92fdd9c9150d
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/commissions/client.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/commissions/client.tsx
index 68e1d131b5..d65c5686a7 100644
--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/commissions/client.tsx
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/commissions/client.tsx
@@ -29,12 +29,7 @@ type Tab = {
export default function CommissionsPageClient() {
const { queryParams, getQueryString, searchParamsObj } = useRouterStuff();
- const {
- tab: selectedTab = "commissions",
- interval,
- start,
- end,
- } = searchParamsObj;
+ const { interval, start, end } = searchParamsObj;
const { data: { programs, timeseries } = {}, isLoading } = useSWR<{
programs: {
@@ -42,12 +37,10 @@ export default function CommissionsPageClient() {
name: string;
logo: string;
commissions: number;
- revenue: number;
}[];
timeseries: {
start: Date;
commissions: number;
- revenue: number;
}[];
}>(
`/api/admin/commissions${getQueryString({
@@ -65,21 +58,16 @@ export default function CommissionsPageClient() {
label: "Commissions",
colorClassName: "text-teal-500 bg-teal-500/50 border-teal-500",
},
- {
- id: "revenue",
- label: "Revenue",
- colorClassName: "text-purple-500 bg-purple-500/50 border-purple-500",
- },
];
- const tab = tabs.find(({ id }) => id === selectedTab) ?? tabs[0];
+ const tab = tabs[0];
+ const selectedTab = tab.id;
const chartData =
- timeseries?.map(({ start, commissions, revenue }) => ({
+ timeseries?.map(({ start, commissions }) => ({
date: start ? new Date(start) : new Date(),
values: {
commissions: commissions || 0,
- revenue: revenue || 0,
},
})) ?? null;
@@ -90,8 +78,6 @@ export default function CommissionsPageClient() {
(acc, { commissions }) => acc + (commissions || 0),
0,
) ?? 0,
- revenue:
- timeseries?.reduce((acc, { revenue }) => acc + (revenue || 0), 0) ?? 0,
};
}, [timeseries]);
@@ -149,16 +135,6 @@ export default function CommissionsPageClient() {
maximumFractionDigits: 2,
}),
},
- {
- id: "revenue",
- header: "Revenue",
- accessorKey: "revenue",
- cell: ({ row }) =>
- currencyFormatter(row.original.revenue / 100, {
- minimumFractionDigits: 2,
- maximumFractionDigits: 2,
- }),
- },
],
pagination,
onPaginationChange: setPagination,
@@ -236,12 +212,6 @@ export default function CommissionsPageClient() {
isActive: selectedTab === "commissions",
colorClassName: tab.colorClassName,
},
- {
- id: "revenue",
- valueAccessor: (d) => d.values.revenue,
- isActive: selectedTab === "revenue",
- colorClassName: tab.colorClassName,
- },
]}
tooltipClassName="p-0"
tooltipContent={(d) => (
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/layout-nav-client.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/layout-nav-client.tsx
index 99c3aaee66..0560f7b73d 100644
--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/layout-nav-client.tsx
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/layout-nav-client.tsx
@@ -23,6 +23,10 @@ const tabs = [
href: "/commissions",
label: "Commissions",
},
+ {
+ href: "/revenue",
+ label: "Revenue",
+ },
{
href: "/payouts",
label: "Payouts",
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/revenue/client.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/revenue/client.tsx
new file mode 100644
index 0000000000..e42b744a9f
--- /dev/null
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/revenue/client.tsx
@@ -0,0 +1,199 @@
+"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 { useMemo } from "react";
+import useSWR from "swr";
+
+type Tab = {
+ id: string;
+ label: string;
+ colorClassName: string;
+};
+
+export default function RevenuePageClient() {
+ const { queryParams, getQueryString, searchParamsObj } = useRouterStuff();
+
+ const { data: { programs } = {}, isLoading } = useSWR<{
+ programs: {
+ id: string;
+ name: string;
+ logo: string;
+ partners: number;
+ sales: number;
+ saleAmount: number;
+ }[];
+ }>(
+ `/api/admin/revenue${getQueryString({
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ })}`,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ const tabs: Tab[] = [
+ {
+ id: "revenue",
+ label: "Revenue",
+ colorClassName: "text-purple-500 bg-purple-500/50 border-purple-500",
+ },
+ ];
+
+ const tab = tabs[0];
+ const selectedTab = tab.id;
+
+ const totals = useMemo(() => {
+ return {
+ revenue:
+ programs?.reduce((acc, { saleAmount }) => acc + (saleAmount || 0), 0) ??
+ 0,
+ };
+ }, [programs]);
+
+ 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: "Partners",
+ accessorKey: "partners",
+ cell: ({ row }) => nFormatter(row.original.partners, { full: true }),
+ },
+ {
+ id: "sales",
+ header: "Sales",
+ accessorKey: "sales",
+ cell: ({ row }) => nFormatter(row.original.sales, { full: true }),
+ },
+ {
+ id: "revenue",
+ header: "Revenue",
+ accessorKey: "revenue",
+ cell: ({ row }) =>
+ currencyFormatter(row.original.saleAmount / 100, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ }),
+ },
+ ],
+ pagination,
+ onPaginationChange: setPagination,
+ resourceName: (plural) => `program${plural ? "s" : ""}`,
+ rowCount: programs?.length ?? 0,
+ loading: isLoading,
+ });
+
+ 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="scrollbar-hide grid w-full grid-cols-2 divide-x overflow-y-hidden sm:grid-cols-3">
+ {tabs.map(({ id, label, colorClassName }) => {
+ return (
+ <button
+ key={id}
+ onClick={() => {
+ queryParams({
+ set: { tab: id },
+ });
+ }}
+ className={cn(
+ "border-box relative block h-full w-full flex-none px-4 py-3 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 sm:first:rounded-tl-xl",
+ )}
+ >
+ {/* Active tab indicator */}
+ <div
+ className={cn(
+ "absolute bottom-0 left-0 h-0.5 w-full bg-black transition-transform duration-100",
+ selectedTab !== id && "translate-y-[3px]",
+ )}
+ />
+ <div className="flex items-center gap-2.5 text-sm text-neutral-600">
+ <div
+ className={cn(
+ "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">
+ {(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>
+ </button>
+ );
+ })}
+ </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
new file mode 100644
index 0000000000..0d1dffc677
--- /dev/null
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/revenue/page.tsx
@@ -0,0 +1,10 @@
+import { Suspense } from "react";
+import RevenuePageClient from "./client";
+
+export default async function RevenuePage() {
+ return (
+ <Suspense>
+ <RevenuePageClient />
+ </Suspense>
+ );
+}
diff --git a/apps/web/app/(ee)/api/admin/commissions/utils.ts b/apps/web/app/(ee)/api/admin/commissions/get-commissions-timeseries.ts
similarity index 58%
rename from apps/web/app/(ee)/api/admin/commissions/utils.ts
rename to apps/web/app/(ee)/api/admin/commissions/get-commissions-timeseries.ts
index 3538ed4ffb..ab08439f40 100644
--- a/apps/web/app/(ee)/api/admin/commissions/utils.ts
+++ b/apps/web/app/(ee)/api/admin/commissions/get-commissions-timeseries.ts
@@ -3,61 +3,9 @@ import { prisma } from "@dub/prisma";
import { ACME_PROGRAM_ID } from "@dub/utils";
import { DateTime } from "luxon";
-export async function getTopProgramsByCommissions({
- startDate,
- endDate,
-}: {
- startDate: Date;
- endDate: Date;
-}) {
- const programCommissions = await prisma.commission.groupBy({
- by: ["programId"],
- _sum: {
- earnings: true,
- amount: true,
- },
- where: {
- earnings: {
- gt: 0,
- },
- programId: {
- not: ACME_PROGRAM_ID,
- },
- createdAt: {
- gte: startDate,
- lte: endDate,
- },
- },
- orderBy: {
- _sum: {
- earnings: "desc",
- },
- },
- });
-
- const topPrograms = await prisma.program.findMany({
- where: {
- id: {
- in: programCommissions.map(({ programId }) => programId),
- },
- },
- });
-
- const topProgramsWithCommissions = programCommissions.map(
- ({ programId, _sum }) => ({
- ...topPrograms.find((program) => program.id === programId),
- commissions: _sum.earnings || 0,
- revenue: _sum.amount || 0,
- }),
- );
-
- return topProgramsWithCommissions;
-}
-
interface Commission {
start: string;
commissions: number;
- revenue: number;
}
export async function getCommissionsTimeseries({
@@ -77,8 +25,7 @@ export async function getCommissionsTimeseries({
const commissions = await prisma.$queryRaw<Commission[]>`
SELECT
DATE_FORMAT(CONVERT_TZ(createdAt, "UTC", ${timezone || "UTC"}), ${dateFormat}) AS start,
- SUM(earnings) AS commissions,
- SUM(amount) AS revenue
+ SUM(earnings) AS commissions
FROM Commission
WHERE
earnings > 0
@@ -97,7 +44,6 @@ export async function getCommissionsTimeseries({
item.start,
{
commissions: Number(item.commissions),
- revenue: Number(item.revenue),
},
]),
);
@@ -111,7 +57,6 @@ export async function getCommissionsTimeseries({
start: currentDate.toISO(),
...(commissionsLookup[periodKey] || {
commissions: 0,
- revenue: 0,
}),
});
diff --git a/apps/web/app/(ee)/api/admin/commissions/get-top-program-by-commissions.ts b/apps/web/app/(ee)/api/admin/commissions/get-top-program-by-commissions.ts
new file mode 100644
index 0000000000..dbd93c391d
--- /dev/null
+++ b/apps/web/app/(ee)/api/admin/commissions/get-top-program-by-commissions.ts
@@ -0,0 +1,51 @@
+import { prisma } from "@dub/prisma";
+import { ACME_PROGRAM_ID } from "@dub/utils";
+
+export async function getTopProgramsByCommissions({
+ startDate,
+ endDate,
+}: {
+ startDate: Date;
+ endDate: Date;
+}) {
+ const programCommissions = await prisma.commission.groupBy({
+ by: ["programId"],
+ _sum: {
+ earnings: true,
+ },
+ where: {
+ earnings: {
+ gt: 0,
+ },
+ programId: {
+ not: ACME_PROGRAM_ID,
+ },
+ createdAt: {
+ gte: startDate,
+ lte: endDate,
+ },
+ },
+ orderBy: {
+ _sum: {
+ earnings: "desc",
+ },
+ },
+ });
+
+ const topPrograms = await prisma.program.findMany({
+ where: {
+ id: {
+ in: programCommissions.map(({ programId }) => programId),
+ },
+ },
+ });
+
+ const topProgramsWithCommissions = programCommissions.map(
+ ({ programId, _sum }) => ({
+ ...topPrograms.find((program) => program.id === programId),
+ commissions: _sum.earnings || 0,
+ }),
+ );
+
+ return topProgramsWithCommissions;
+}
diff --git a/apps/web/app/(ee)/api/admin/commissions/route.ts b/apps/web/app/(ee)/api/admin/commissions/route.ts
index 3d85a85009..78cc26740f 100644
--- a/apps/web/app/(ee)/api/admin/commissions/route.ts
+++ b/apps/web/app/(ee)/api/admin/commissions/route.ts
@@ -3,7 +3,8 @@ import { withAdmin } from "@/lib/auth";
import { THE_BEGINNING_OF_TIME } from "@dub/utils";
import { endOfDay, startOfDay } from "date-fns";
import { NextResponse } from "next/server";
-import { getCommissionsTimeseries, getTopProgramsByCommissions } from "./utils";
+import { getCommissionsTimeseries } from "./get-commissions-timeseries";
+import { getTopProgramsByCommissions } from "./get-top-program-by-commissions";
export const GET = withAdmin(async ({ searchParams }) => {
const { interval = "mtd", start, end, timezone = "UTC" } = searchParams;
diff --git a/apps/web/app/(ee)/api/admin/revenue/get-top-programs-by-sales.ts b/apps/web/app/(ee)/api/admin/revenue/get-top-programs-by-sales.ts
new file mode 100644
index 0000000000..68065ed2b5
--- /dev/null
+++ b/apps/web/app/(ee)/api/admin/revenue/get-top-programs-by-sales.ts
@@ -0,0 +1,60 @@
+import { tb } from "@/lib/tinybird";
+import z from "@/lib/zod";
+import { prisma } from "@dub/prisma";
+import { ACME_PROGRAM_ID } from "@dub/utils";
+
+export async function getTopProgramsBySales({
+ startDate,
+ endDate,
+}: {
+ startDate: Date;
+ endDate: Date;
+}) {
+ const pipe = tb.buildPipe({
+ pipe: "v2_top_programs",
+ parameters: z.any(),
+ data: z.any(),
+ });
+
+ const response = await pipe({
+ eventType: "sales",
+ start: startDate.toISOString().replace("T", " ").replace("Z", ""),
+ end: endDate.toISOString().replace("T", " ").replace("Z", ""),
+ });
+
+ const topProgramsData = response.data as {
+ programId: string;
+ }[];
+
+ const programs = await prisma.program.findMany({
+ where: {
+ id: {
+ in: topProgramsData.map((item) => item.programId),
+ not: ACME_PROGRAM_ID,
+ },
+ },
+ select: {
+ id: true,
+ name: true,
+ logo: true,
+ _count: {
+ select: {
+ partners: true,
+ },
+ },
+ },
+ });
+
+ return topProgramsData
+ .map((item) => {
+ const program = programs.find((program) => program.id === item.programId);
+ if (!program) return null;
+ const { _count, ...rest } = program;
+ return {
+ ...rest,
+ ...item,
+ partners: _count.partners,
+ };
+ })
+ .filter(Boolean);
+}
diff --git a/apps/web/app/(ee)/api/admin/revenue/route.ts b/apps/web/app/(ee)/api/admin/revenue/route.ts
new file mode 100644
index 0000000000..7bd6934e34
--- /dev/null
+++ b/apps/web/app/(ee)/api/admin/revenue/route.ts
@@ -0,0 +1,26 @@
+import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";
+import { withAdmin } from "@/lib/auth";
+import { THE_BEGINNING_OF_TIME } 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: THE_BEGINNING_OF_TIME,
+ });
+
+ const programs = await getTopProgramsBySales({
+ startDate,
+ endDate,
+ });
+
+ return NextResponse.json({
+ programs,
+ });
+});
diff --git a/apps/web/lib/analytics/get-analytics.ts b/apps/web/lib/analytics/get-analytics.ts
index 43cb4f7b54..c3ca94f3d6 100644
--- a/apps/web/lib/analytics/get-analytics.ts
+++ b/apps/web/lib/analytics/get-analytics.ts
@@ -15,14 +15,6 @@ import {
import { AnalyticsFilters } from "./types";
import { getStartEndDates } from "./utils/get-start-end-dates";
-// Determine the pipe name based on the groupBy parameter
-const determinePipeName = (groupBy: AnalyticsFilters["groupBy"]) => {
- if (UTM_TAGS_PLURAL_LIST.includes(groupBy)) {
- return "v2_utms";
- }
- return `v2_${groupBy}`;
-};
-
// Fetch data for /api/analytics
export const getAnalytics = async (params: AnalyticsFilters) => {
let {
@@ -102,7 +94,7 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
// Create a Tinybird pipe
const pipe = tb.buildPipe({
- pipe: determinePipeName(groupBy),
+ pipe: UTM_TAGS_PLURAL_LIST.includes(groupBy) ? "v2_utms" : `v2_${groupBy}`,
parameters: analyticsFilterTB,
data:
groupBy === "top_links" ||