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 payouts usage in billing tab

Steven Tey1ab7786c19e6
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/billing/usage/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/billing/usage/route.ts
index d64594e0c9..bcd95ae174 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/billing/usage/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/usage/route.ts
@@ -1,3 +1,5 @@
+import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";
+import { getPayoutsTimeseries } from "@/lib/api/payouts/get-payouts-timeseries";
import { withWorkspace } from "@/lib/auth";
import { getWorkspaceUsage } from "@/lib/tinybird/get-workspace-usage";
import { usageQuerySchema } from "@/lib/zod/schemas/usage";
@@ -5,10 +7,35 @@ import { NextResponse } from "next/server";
export const GET = withWorkspace(
async ({ searchParams, workspace }) => {
- const params = usageQuerySchema.parse(searchParams);
+ const { resource, ...params } = usageQuerySchema.parse(searchParams);
+
+ if (resource === "payouts") {
+ const { startDate, endDate } = getStartEndDates({
+ interval: params.interval,
+ start: params.start,
+ end: params.end,
+ timezone: params.timezone,
+ });
+
+ const timeseries = await getPayoutsTimeseries({
+ workspaceId: workspace.id,
+ startDate,
+ endDate,
+ timezone: params.timezone,
+ });
+
+ return NextResponse.json(
+ timeseries.map(({ start, payouts }) => ({
+ date: start,
+ value: payouts,
+ groups: [],
+ })),
+ );
+ }
const data = await getWorkspaceUsage({
workspaceId: workspace.id,
+ resource,
...params,
});
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsx
index 662985a443..a10d6cf126 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsx
@@ -1,11 +1,14 @@
"use client";
import { clientAccessCheck } from "@/lib/client-access-check";
-import { testIds } from "@/lib/e2e/test-ids";
import { MEGA_WORKSPACE_LINKS_LIMIT } from "@/lib/constants/misc";
+import { testIds } from "@/lib/e2e/test-ids";
import useGroupsCount from "@/lib/swr/use-groups-count";
import { useLinkTagsCount } from "@/lib/swr/use-link-tags-count";
-import { useUsageTimeseries } from "@/lib/swr/use-usage-timeseries";
+import {
+ UsageResource,
+ useUsageTimeseries,
+} from "@/lib/swr/use-usage-timeseries";
import useWorkspace from "@/lib/swr/use-workspace";
import useWorkspaceUsers from "@/lib/swr/use-workspace-users";
import { useConfirmModal } from "@/ui/modals/confirm-modal";
@@ -29,6 +32,7 @@ import {
Folder5,
Globe,
Hyperlink,
+ MoneyBills2,
Tag,
Users,
Users6,
@@ -45,7 +49,7 @@ import {
} from "@dub/utils";
import NumberFlow from "@number-flow/react";
import Link from "next/link";
-import { CSSProperties, ReactNode, useMemo } from "react";
+import { ComponentProps, CSSProperties, ReactNode, useMemo } from "react";
import { toast } from "sonner";
import { UsageChart } from "./usage-chart";
@@ -80,6 +84,8 @@ export default function PlanUsage() {
trialEndsAt,
subscriptionCanceledAt,
billingCycleEndsAt,
+ defaultProgramId,
+ loading,
mutate,
} = useWorkspace();
@@ -124,16 +130,16 @@ export default function PlanUsage() {
}, [billingCycleStart, planPeriod, billingCycleEndsAt]);
const usageTabs = useMemo(() => {
- const tabs = [
+ const tabs: ComponentProps<typeof UsageTabCard>[] = [
{
- resource: "events" as const,
+ resource: "events",
icon: CursorRays,
title: "Events tracked",
usage: usage,
limit: usageLimit,
},
{
- resource: "links" as const,
+ resource: "links",
icon: Hyperlink,
title: "Links created",
usage: linksUsage,
@@ -148,8 +154,29 @@ export default function PlanUsage() {
tabs.unshift(linksTab);
}
}
+ // Reserve the payouts slot while the workspace loads to avoid layout shift
+ if (defaultProgramId || loading) {
+ tabs.splice(1, 0, {
+ resource: "payouts",
+ icon: MoneyBills2,
+ title: "Payouts sent",
+ usage: payoutsUsage,
+ limit: payoutsLimit,
+ unit: "$",
+ });
+ }
return tabs;
- }, [usage, usageLimit, linksUsage, linksLimit, totalLinks]);
+ }, [
+ usage,
+ usageLimit,
+ linksUsage,
+ linksLimit,
+ totalLinks,
+ defaultProgramId,
+ loading,
+ payoutsUsage,
+ payoutsLimit,
+ ]);
// Display the payout fee in a readable format
const payoutFeeDisplay = useMemo((): ReactNode => {
@@ -377,7 +404,12 @@ export default function PlanUsage() {
</div>
<div className="grid grid-cols-[minmax(0,1fr)] divide-y divide-neutral-200 border-t border-neutral-200">
<div>
- <div className="grid gap-4 p-6 pb-0 sm:grid-cols-2 md:p-8 md:pb-0 lg:gap-6">
+ <div
+ className={cn(
+ "grid gap-4 p-6 pb-0 sm:grid-cols-2 md:p-8 md:pb-0 lg:gap-6",
+ usageTabs.length > 2 && "lg:grid-cols-3",
+ )}
+ >
{usageTabs.map((tab) => (
<UsageTabCard key={tab.resource} {...tab} />
))}
@@ -466,7 +498,7 @@ function UsageTabCard({
unit,
requiresUpgrade,
}: {
- resource: "links" | "events";
+ resource: UsageResource;
icon: Icon;
title: string;
usage?: number;
@@ -477,19 +509,16 @@ function UsageTabCard({
const { queryParams, searchParamsObj } = useRouterStuff();
const { slug, plan } = useWorkspace();
- const { ManageUsageModal, setShowManageUsageModal } = useManageUsageModal({
- type: resource,
- });
+ const isPayouts = resource === "payouts";
const hasActiveFilters = useMemo(() => {
return !!(
- searchParamsObj.folderId ||
- searchParamsObj.domain ||
+ (!isPayouts && (searchParamsObj.folderId || searchParamsObj.domain)) ||
searchParamsObj.interval ||
searchParamsObj.start ||
searchParamsObj.end
);
- }, [searchParamsObj]);
+ }, [searchParamsObj, isPayouts]);
const { usage: usageTimeseries, activeResource } = useUsageTimeseries({
resource: hasActiveFilters ? resource : undefined,
@@ -500,20 +529,11 @@ function UsageTabCard({
return acc;
}, 0);
- const [usage, limit] =
- unit === "$" && usageProp !== undefined && limitProp !== undefined
- ? [
- (hasActiveFilters && filteredUsage !== undefined
- ? filteredUsage
- : usageProp) / 100,
- limitProp / 100,
- ]
- : [
- hasActiveFilters && filteredUsage !== undefined
- ? filteredUsage
- : usageProp,
- limitProp,
- ];
+ const rawUsage =
+ hasActiveFilters && filteredUsage !== undefined ? filteredUsage : usageProp;
+ const divisor = unit === "$" ? 100 : 1;
+ const usage = rawUsage !== undefined ? rawUsage / divisor : undefined;
+ const limit = limitProp !== undefined ? limitProp / divisor : undefined;
const loading = usage === undefined || limit === undefined;
const unlimited = limitProp !== undefined && limitProp >= INFINITY_NUMBER;
@@ -524,7 +544,6 @@ function UsageTabCard({
return (
<div className="relative">
- <ManageUsageModal />
<button
className={cn(
"w-full rounded-lg border border-neutral-300 bg-white px-4 py-3 text-left transition-colors duration-75",
@@ -565,7 +584,7 @@ function UsageTabCard({
</Tooltip>
)}
</div>
- <div className="mt-1.5">
+ <div className="mt-1.5 flex h-6 items-center">
{!loading ? (
<NumberFlow
value={usage}
@@ -585,7 +604,7 @@ function UsageTabCard({
}
/>
) : (
- <div className="h-5 w-16 animate-pulse rounded-md bg-neutral-200" />
+ <div className="h-6 w-16 animate-pulse rounded-md bg-neutral-200" />
)}
</div>
<AnimatedSizeContainer height>
@@ -635,20 +654,39 @@ function UsageTabCard({
)}
</AnimatedSizeContainer>
</button>
- {["links", "events"].includes(resource) && plan !== "enterprise" && (
- <div className="absolute right-3 top-3">
- <Button
- onClick={() => setShowManageUsageModal(true)}
- text={warning ? "Upgrade" : "Manage"}
- variant={warning ? "primary" : "secondary"}
- className="h-6 px-1.5 text-xs"
- />
- </div>
+ {resource !== "payouts" && plan !== "enterprise" && (
+ <ManageUsageButton type={resource} warning={warning} />
)}
</div>
);
}
+function ManageUsageButton({
+ type,
+ warning,
+}: {
+ type: "links" | "events";
+ warning: boolean;
+}) {
+ const { ManageUsageModal, setShowManageUsageModal } = useManageUsageModal({
+ type,
+ });
+
+ return (
+ <>
+ <ManageUsageModal />
+ <div className="absolute right-3 top-3">
+ <Button
+ onClick={() => setShowManageUsageModal(true)}
+ text={warning ? "Upgrade" : "Manage"}
+ variant={warning ? "primary" : "secondary"}
+ className="h-6 px-1.5 text-xs"
+ />
+ </div>
+ </>
+ );
+}
+
function UsageCategory(data: {
title: string;
icon: Icon;
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/usage-chart.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/usage-chart.tsx
index 0d31082fb8..6351a7d0a8 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/usage-chart.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/usage-chart.tsx
@@ -1,7 +1,10 @@
import { formatDateTooltip } from "@/lib/analytics/format-date-tooltip";
import useDomains from "@/lib/swr/use-domains";
import useFolders from "@/lib/swr/use-folders";
-import { useUsageTimeseries } from "@/lib/swr/use-usage-timeseries";
+import {
+ UsageResource,
+ useUsageTimeseries,
+} from "@/lib/swr/use-usage-timeseries";
import { BarList } from "@/ui/analytics/bar-list";
import { FolderIcon } from "@/ui/folders/folder-icon";
import SimpleDateRangePicker from "@/ui/shared/simple-date-range-picker";
@@ -16,8 +19,19 @@ import {
useRouterStuff,
} from "@dub/ui";
import { Bars, TimeSeriesChart, XAxis, YAxis } from "@dub/ui/charts";
-import { CursorRays, Folder, Globe2, Hyperlink } from "@dub/ui/icons";
-import { cn, GOOGLE_FAVICON_URL, nFormatter } from "@dub/utils";
+import {
+ CursorRays,
+ Folder,
+ Globe2,
+ Hyperlink,
+ MoneyBills2,
+} from "@dub/ui/icons";
+import {
+ cn,
+ currencyFormatter,
+ GOOGLE_FAVICON_URL,
+ nFormatter,
+} from "@dub/utils";
import NumberFlow, { NumberFlowGroup } from "@number-flow/react";
import {
ComponentProps,
@@ -42,11 +56,15 @@ const BAR_COLORS = [
"text-pink-500",
];
-const RESOURCES = ["links", "events"] as const;
const resourceEmptyStates: Record<
- (typeof RESOURCES)[number],
+ UsageResource,
ComponentProps<typeof EmptyState>
> = {
+ payouts: {
+ icon: MoneyBills2,
+ title: "Payouts Sent",
+ description: "No payouts have been sent in the selected date range.",
+ },
links: {
icon: Hyperlink,
title: "Links Created",
@@ -73,6 +91,25 @@ export function UsageChart() {
groupBy,
} = useUsageTimeseries();
+ const isPayouts = activeResource === "payouts";
+
+ const formatValue = useCallback(
+ (value: number) =>
+ isPayouts
+ ? currencyFormatter(value, { trailingZeroDisplay: "stripIfInteger" })
+ : nFormatter(value, { full: true }),
+ [isPayouts],
+ );
+
+ // Payouts are always bucketed by month
+ const formatDate = useCallback(
+ (date: Date) =>
+ isPayouts
+ ? date.toLocaleDateString("en-US", { month: "short", year: "numeric" })
+ : formatDateTooltip(date, { interval, start, end }),
+ [isPayouts, interval, start, end],
+ );
+
// Get filter values from URL params
const folderId = searchParamsObj.folderId;
const domain = searchParamsObj.domain;
@@ -319,33 +356,37 @@ export function UsageChart() {
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-2 px-4 md:flex-row md:items-center md:justify-between md:px-0">
<div className="flex w-full flex-col gap-2 md:w-fit md:flex-row md:items-center">
- <Filter.Select
- className="h-9 w-full md:w-fit"
- filters={filters}
- activeFilters={activeFilters}
- onSelect={onSelect}
- onRemove={onRemove}
- />
+ {!isPayouts && (
+ <Filter.Select
+ className="h-9 w-full md:w-fit"
+ filters={filters}
+ activeFilters={activeFilters}
+ onSelect={onSelect}
+ onRemove={onRemove}
+ />
+ )}
<SimpleDateRangePicker
presets={["7d", "30d", "90d", "1y", "mtd", "qtd", "ytd"]}
values={{ start, end, interval }}
className="h-9 w-full md:w-fit"
/>
</div>
- <ToggleGroup
- options={[
- { value: "domain", label: "Domain" },
- { value: "folderId", label: "Folder" },
- ]}
- selected={groupBy}
- selectAction={(id) => queryParams({ set: { groupBy: id } })}
- className="w-full rounded-lg border-transparent bg-neutral-100 p-0.5 md:w-fit"
- optionClassName="flex-1 justify-center text-xs text-neutral-800 data-[selected=true]:text-neutral-800 px-3 sm:px-5 py-2 leading-none"
- indicatorClassName="bg-white border-neutral-200 rounded-md"
- />
+ {!isPayouts && (
+ <ToggleGroup
+ options={[
+ { value: "domain", label: "Domain" },
+ { value: "folderId", label: "Folder" },
+ ]}
+ selected={groupBy}
+ selectAction={(id) => queryParams({ set: { groupBy: id } })}
+ className="w-full rounded-lg border-transparent bg-neutral-100 p-0.5 md:w-fit"
+ optionClassName="flex-1 justify-center text-xs text-neutral-800 data-[selected=true]:text-neutral-800 px-3 sm:px-5 py-2 leading-none"
+ indicatorClassName="bg-white border-neutral-200 rounded-md"
+ />
+ )}
</div>
<AnimatedSizeContainer height>
- {activeFilters.length > 0 && (
+ {!isPayouts && activeFilters.length > 0 && (
<Filter.List
filters={filters}
activeFilters={activeFilters}
@@ -378,7 +419,7 @@ export function UsageChart() {
id: "usage",
valueAccessor: (d) => d.values.usage,
colorClassName: "text-violet-500",
- isActive: false,
+ isActive: isPayouts,
},
...(usage?.[0]?.groups?.map((group) => ({
id: group.id,
@@ -399,10 +440,10 @@ export function UsageChart() {
<>
<div className="flex items-center justify-between gap-4 px-4 py-3 text-xs">
<span className="text-content-emphasis font-semibold">
- {formatDateTooltip(d.date, { interval, start, end })}
+ {formatDate(d.date)}
</span>
<span className="text-content-default font-medium">
- {nFormatter(d.values.usage, { full: true })}
+ {formatValue(d.values.usage)}
</span>
</div>
{Boolean(topGroups?.length) && (
@@ -441,13 +482,13 @@ export function UsageChart() {
);
}}
>
- <XAxis
- highlightLast={false}
- tickFormat={(date) =>
- formatDateTooltip(date, { interval, start, end })
+ <XAxis highlightLast={false} tickFormat={formatDate} />
+ <YAxis
+ showGridLines
+ tickFormat={(value) =>
+ isPayouts ? `$${nFormatter(value / 100)}` : nFormatter(value)
}
/>
- <YAxis showGridLines tickFormat={nFormatter} />
<Bars />
</TimeSeriesChart>
)
@@ -520,7 +561,7 @@ export function UsageChart() {
);
})}
</>
- ) : loading ? (
+ ) : loading && !isPayouts ? (
[...Array(3)].map((_, idx) => (
<div
key={idx}
diff --git a/apps/web/lib/api/payouts/get-payouts-timeseries.ts b/apps/web/lib/api/payouts/get-payouts-timeseries.ts
new file mode 100644
index 0000000000..2aa13c413c
--- /dev/null
+++ b/apps/web/lib/api/payouts/get-payouts-timeseries.ts
@@ -0,0 +1,64 @@
+import { sqlGranularityMap } from "@/lib/planetscale/granularity";
+import { prisma } from "@/lib/prisma";
+import { TZDate } from "@date-fns/tz";
+import { format } from "date-fns";
+
+interface PayoutsTimeseries {
+ start: string;
+ payouts: number;
+}
+
+// Mirrors how `payoutsUsage` is tracked: incremented when a payout invoice is
+// created (processing) and decremented if the charge fails
+export async function getPayoutsTimeseries({
+ workspaceId,
+ startDate,
+ endDate,
+ timezone,
+}: {
+ workspaceId: string;
+ startDate: Date;
+ endDate: Date;
+ timezone: string;
+}) {
+ const { dateFormat, dateIncrement, startFunction, formatString } =
+ sqlGranularityMap.month;
+
+ const payouts = await prisma.$queryRaw<PayoutsTimeseries[]>`
+ SELECT
+ DATE_FORMAT(CONVERT_TZ(createdAt, "UTC", ${timezone || "UTC"}), ${dateFormat}) AS start,
+ SUM(amount) AS payouts
+ FROM Invoice
+ WHERE
+ workspaceId = ${workspaceId}
+ AND type = "partnerPayout"
+ AND status IN ("processing", "completed")
+ AND createdAt >= ${startDate}
+ AND createdAt < ${endDate}
+ GROUP BY start
+ ORDER BY start ASC;`;
+
+ const tzStartDate = new TZDate(startDate, timezone || "UTC");
+ const tzEndDate = new TZDate(endDate, timezone || "UTC");
+
+ let currentDate = startFunction(tzStartDate);
+
+ const payoutsLookup = Object.fromEntries(
+ payouts.map((item) => [item.start, Number(item.payouts)]),
+ );
+
+ const timeseries: PayoutsTimeseries[] = [];
+
+ while (currentDate < tzEndDate) {
+ const periodKey = format(currentDate, formatString);
+
+ timeseries.push({
+ start: currentDate.toISOString(),
+ payouts: payoutsLookup[periodKey] ?? 0,
+ });
+
+ currentDate = dateIncrement(currentDate);
+ }
+
+ return timeseries;
+}
diff --git a/apps/web/lib/swr/use-usage-timeseries.ts b/apps/web/lib/swr/use-usage-timeseries.ts
index e0e3d3f6d9..8fcc9d2692 100644
--- a/apps/web/lib/swr/use-usage-timeseries.ts
+++ b/apps/web/lib/swr/use-usage-timeseries.ts
@@ -6,15 +6,19 @@ import useSWR from "swr";
import { MEGA_WORKSPACE_LINKS_LIMIT } from "../constants/misc";
import useWorkspace from "./use-workspace";
+export type UsageResource = "links" | "events" | "payouts";
+
export function useUsageTimeseries({
resource: definedResource,
-}: { resource?: "links" | "events" } = {}) {
+}: { resource?: UsageResource } = {}) {
const {
id: workspaceId,
billingCycleStart,
billingCycleEndsAt,
planPeriod,
totalLinks,
+ defaultProgramId,
+ loading: workspaceLoading,
} = useWorkspace();
const { start: firstDay, end: lastDay } = getBillingPeriodBounds({
@@ -25,7 +29,15 @@ export function useUsageTimeseries({
const searchParams = useSearchParams();
- const defaultActiveTab = useMemo(() => {
+ const availableResources = useMemo<UsageResource[]>(
+ () =>
+ defaultProgramId || workspaceLoading
+ ? ["links", "events", "payouts"]
+ : ["links", "events"],
+ [defaultProgramId, workspaceLoading],
+ );
+
+ const defaultActiveTab = useMemo((): UsageResource => {
if (totalLinks && totalLinks > MEGA_WORKSPACE_LINKS_LIMIT) {
return "links";
}
@@ -34,11 +46,14 @@ export function useUsageTimeseries({
const activeResource = useMemo(() => {
const tab = searchParams.get("tab");
- if (tab && ["links", "events"].includes(tab)) {
- return tab as "links" | "events";
+ if (tab && availableResources.includes(tab as UsageResource)) {
+ return tab as UsageResource;
}
return defaultActiveTab;
- }, [searchParams, defaultActiveTab]);
+ }, [searchParams, availableResources, defaultActiveTab]);
+
+ const resource = definedResource || activeResource;
+ const isLinkResource = resource !== "payouts";
// Get filter parameters from URL
const folderId = searchParams.get("folderId");
@@ -77,7 +92,7 @@ export function useUsageTimeseries({
>(
workspaceId &&
`/api/workspaces/${workspaceId}/billing/usage?${new URLSearchParams({
- resource: definedResource || activeResource,
+ resource,
...(start &&
end && {
start: startOfDay(new Date(start)).toISOString(),
@@ -85,10 +100,12 @@ export function useUsageTimeseries({
}),
...(interval && { interval }),
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
- ...(folderId && { folderId }),
- ...(domain && { domain }),
- ...(groupBy && {
- groupBy: groupBy === "folderId" ? "folder_id" : "domain",
+ ...(isLinkResource && {
+ ...(folderId && { folderId }),
+ ...(domain && { domain }),
+ ...(groupBy && {
+ groupBy: groupBy === "folderId" ? "folder_id" : "domain",
+ }),
}),
}).toString()}`,
fetcher,
diff --git a/apps/web/lib/zod/schemas/usage.ts b/apps/web/lib/zod/schemas/usage.ts
index cff0876a9a..242ae3bb4a 100644
--- a/apps/web/lib/zod/schemas/usage.ts
+++ b/apps/web/lib/zod/schemas/usage.ts
@@ -2,7 +2,7 @@ import { DATE_RANGE_INTERVAL_PRESETS } from "@/lib/analytics/constants";
import * as z from "zod/v4";
export const usageQuerySchema = z.object({
- resource: z.enum(["links", "events", "revenue"]),
+ resource: z.enum(["links", "events", "payouts"]),
folderId: z.string().optional(),
domain: z.string().optional(),
groupBy: z.enum(["folder_id", "domain"]).optional(),