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 overview chart

Tim Wilson67de06fb1c90
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/analytics-chart.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/analytics-chart.tsx
index 8f789a1bcc..38e85cb6a6 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/analytics-chart.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/analytics-chart.tsx
@@ -1,38 +1,20 @@
-import { formatDateTooltip } from "@/lib/analytics/format-date-tooltip";
import { editQueryString } from "@/lib/analytics/utils";
import { AnalyticsFunnelChart } from "@/ui/analytics/analytics-funnel-chart";
import { AnalyticsContext } from "@/ui/analytics/analytics-provider";
import { AnalyticsTabs } from "@/ui/analytics/analytics-tabs";
import { ChartViewSwitcher } from "@/ui/analytics/chart-view-switcher";
import { useRouterStuff } from "@dub/ui";
-import {
- Areas,
- ChartContext,
- TimeSeriesChart,
- XAxis,
- YAxis,
-} from "@dub/ui/charts";
import { LoadingSpinner } from "@dub/ui/icons";
-import { capitalize, currencyFormatter, fetcher, nFormatter } from "@dub/utils";
-import { LinearGradient } from "@visx/gradient";
-import { useContext, useId, useMemo } from "react";
+import { fetcher } from "@dub/utils";
+import { useContext, useMemo } from "react";
import useSWR from "swr";
+import { AnalyticsTimeseriesChart } from "./analytics-timeseries-chart";
export function AnalyticsChart() {
- const id = useId();
-
const { queryParams } = useRouterStuff();
- const {
- start,
- end,
- interval,
- selectedTab,
- saleUnit,
- view,
- totalEvents,
- queryString,
- } = useContext(AnalyticsContext);
+ const { selectedTab, saleUnit, view, totalEvents, queryString } =
+ useContext(AnalyticsContext);
const { data, error } = useSWR<
{
@@ -102,72 +84,7 @@ export function AnalyticsChart() {
<>
{view === "timeseries" ? (
<div className="relative size-full p-6 pt-10">
- <TimeSeriesChart
- key={`${start?.toString()}-${end?.toString()}-${interval ?? ""}-${selectedTab}-${saleUnit}`}
- data={chartData || []}
- series={[
- {
- id: "amount",
- valueAccessor: (d) => d.values.amount,
- colorClassName: "text-[#8B5CF6]",
- isActive: true,
- },
- ]}
- tooltipClassName="p-0"
- tooltipContent={(d) => {
- return (
- <>
- <p className="border-b border-neutral-200 px-4 py-3 text-sm text-neutral-900">
- {formatDateTooltip(d.date, { interval, start, end })}
- </p>
- <div className="grid grid-cols-2 gap-x-6 gap-y-2 px-4 py-3 text-sm">
- <div className="flex items-center gap-2">
- <div className="h-2 w-2 rounded-sm bg-violet-500 shadow-[inset_0_0_0_1px_#0003]" />
- <p className="capitalize text-neutral-600">
- {capitalize(selectedTab)}
- </p>
- </div>
- <p className="text-right font-medium text-neutral-900">
- {selectedTab === "sales" &&
- saleUnit === "saleAmount"
- ? currencyFormatter(d.values.amount, {
- minimumFractionDigits: 2,
- maximumFractionDigits: 2,
- })
- : nFormatter(d.values.amount)}
- </p>
- </div>
- </>
- );
- }}
- >
- <ChartContext.Consumer>
- {(context) => (
- <LinearGradient
- id={`${id}-color-gradient`}
- from="#7D3AEC"
- to="#DA2778"
- x1={0}
- x2={context?.width ?? 1}
- gradientUnits="userSpaceOnUse"
- />
- )}
- </ChartContext.Consumer>
- <XAxis
- tickFormat={(date) =>
- formatDateTooltip(date, { interval, start, end })
- }
- />
- <YAxis
- showGridLines
- tickFormat={
- selectedTab === "sales" && saleUnit === "saleAmount"
- ? currencyFormatter
- : nFormatter
- }
- />
- <Areas />
- </TimeSeriesChart>
+ <AnalyticsTimeseriesChart data={chartData} />
</div>
) : (
<AnalyticsFunnelChart />
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/analytics-timeseries-chart.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/analytics-timeseries-chart.tsx
new file mode 100644
index 0000000000..e5922c9300
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/analytics-timeseries-chart.tsx
@@ -0,0 +1,95 @@
+import { formatDateTooltip } from "@/lib/analytics/format-date-tooltip";
+import { AnalyticsContext } from "@/ui/analytics/analytics-provider";
+import {
+ Areas,
+ ChartContext,
+ TimeSeriesChart,
+ XAxis,
+ YAxis,
+} from "@dub/ui/charts";
+import { capitalize, currencyFormatter, nFormatter } from "@dub/utils";
+import { LinearGradient } from "@visx/gradient";
+import { useContext, useId } from "react";
+
+export function AnalyticsTimeseriesChart({
+ data,
+}: {
+ data?: {
+ date: Date;
+ values: {
+ amount: number;
+ };
+ }[];
+}) {
+ const id = useId();
+
+ const { start, end, interval, selectedTab, saleUnit } =
+ useContext(AnalyticsContext);
+
+ return (
+ <TimeSeriesChart
+ key={`${start?.toString()}-${end?.toString()}-${interval ?? ""}-${selectedTab}-${saleUnit}`}
+ data={data || []}
+ series={[
+ {
+ id: "amount",
+ valueAccessor: (d) => d.values.amount,
+ colorClassName: "text-[#8B5CF6]",
+ isActive: true,
+ },
+ ]}
+ tooltipClassName="p-0"
+ tooltipContent={(d) => {
+ return (
+ <>
+ <p className="border-b border-neutral-200 px-4 py-3 text-sm text-neutral-900">
+ {formatDateTooltip(d.date, { interval, start, end })}
+ </p>
+ <div className="grid grid-cols-2 gap-x-6 gap-y-2 px-4 py-3 text-sm">
+ <div className="flex items-center gap-2">
+ <div className="h-2 w-2 rounded-sm bg-violet-500 shadow-[inset_0_0_0_1px_#0003]" />
+ <p className="capitalize text-neutral-600">
+ {capitalize(selectedTab)}
+ </p>
+ </div>
+ <p className="text-right font-medium text-neutral-900">
+ {selectedTab === "sales" && saleUnit === "saleAmount"
+ ? currencyFormatter(d.values.amount, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ })
+ : nFormatter(d.values.amount)}
+ </p>
+ </div>
+ </>
+ );
+ }}
+ >
+ <ChartContext.Consumer>
+ {(context) => (
+ <LinearGradient
+ id={`${id}-color-gradient`}
+ from="#7D3AEC"
+ to="#DA2778"
+ x1={0}
+ x2={context?.width ?? 1}
+ gradientUnits="userSpaceOnUse"
+ />
+ )}
+ </ChartContext.Consumer>
+ <XAxis
+ tickFormat={(date) => formatDateTooltip(date, { interval, start, end })}
+ maxTicks={2}
+ />
+ <YAxis
+ showGridLines
+ tickFormat={
+ selectedTab === "sales" && saleUnit === "saleAmount"
+ ? currencyFormatter
+ : nFormatter
+ }
+ />
+ <Areas />
+ </TimeSeriesChart>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/overview-chart.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/overview-chart.tsx
index 1b21de59e8..d887ad4fcd 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/overview-chart.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/overview-chart.tsx
@@ -1,215 +1,107 @@
-import { DUB_PARTNERS_ANALYTICS_INTERVAL } from "@/lib/analytics/constants";
-import { formatDateTooltip } from "@/lib/analytics/format-date-tooltip";
-import { IntervalOptions } from "@/lib/analytics/types";
-import useCommissionsTimeseries from "@/lib/swr/use-commissions-timeseries";
-import useWorkspace from "@/lib/swr/use-workspace";
-import SimpleDateRangePicker from "@/ui/shared/simple-date-range-picker";
-import { Combobox, useRouterStuff } from "@dub/ui";
-import {
- Areas,
- ChartContext,
- TimeSeriesChart,
- XAxis,
- YAxis,
-} from "@dub/ui/charts";
-import { LoadingSpinner } from "@dub/ui/icons";
-import { currencyFormatter, fetcher } from "@dub/utils";
+import { editQueryString } from "@/lib/analytics/utils";
+import { AnalyticsContext } from "@/ui/analytics/analytics-provider";
+import { Combobox, LoadingSpinner, useRouterStuff } from "@dub/ui";
+import { fetcher } from "@dub/utils";
import NumberFlow from "@number-flow/react";
-import { LinearGradient } from "@visx/gradient";
-import { useId, useMemo, useState } from "react";
+import { useContext, useMemo } from "react";
import useSWR from "swr";
+import { AnalyticsTimeseriesChart } from "./analytics/analytics-timeseries-chart";
const chartOptions = [
- { value: "revenue", label: "Revenue" },
- { value: "commissions", label: "Commissions" },
+ { value: "sales", label: "Revenue", currency: true },
+ { value: "leads", label: "Leads" },
+ { value: "clicks", label: "Clicks" },
];
-type ViewType = "revenue" | "commissions";
-
export function OverviewChart() {
- const id = useId();
- const { id: workspaceId, defaultProgramId } = useWorkspace();
- const { searchParamsObj } = useRouterStuff();
- const [viewType, setViewType] = useState<ViewType>("revenue");
-
- const {
- start,
- end,
- interval = DUB_PARTNERS_ANALYTICS_INTERVAL,
- } = searchParamsObj as {
- start?: string;
- end?: string;
- interval?: IntervalOptions;
- };
+ const { queryParams } = useRouterStuff();
+ const { selectedTab, saleUnit, queryString, totalEvents } =
+ useContext(AnalyticsContext);
- const { data: revenue, error: revenueError } = useSWR<
+ const { data, error, isLoading } = useSWR<
{
- start: string;
+ start: Date;
+ clicks: number;
+ leads: number;
sales: number;
saleAmount: number;
}[]
>(
- workspaceId && defaultProgramId && viewType === "revenue"
- ? `/api/analytics?${new URLSearchParams({
- workspaceId,
- programId: defaultProgramId,
- event: "sales",
- groupBy: "timeseries",
- interval,
- ...(start && { start }),
- ...(end && { end }),
- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
- } as Record<string, string>).toString()}`
- : null,
+ `/api/analytics?${editQueryString(queryString, {
+ event: "composite",
+ groupBy: "timeseries",
+ })}`,
fetcher,
- {
- keepPreviousData: true,
- },
);
- const { data: commissions, error: commissionsError } =
- useCommissionsTimeseries({
- event: "sales",
- groupBy: "timeseries",
- interval,
- start: start ? new Date(start) : undefined,
- end: end ? new Date(end) : undefined,
- enabled: viewType === "commissions",
- });
-
- const data = useMemo(() => {
- const sourceData = viewType === "revenue" ? revenue : commissions;
-
- return sourceData?.map((item) => ({
- date: new Date(item.start),
- values: {
- amount:
- (viewType === "revenue" ? item.saleAmount : item.earnings) / 100,
- },
- }));
- }, [revenue, commissions, viewType]);
-
- const total = useMemo(() => {
- return data?.reduce((acc, curr) => acc + curr.values.amount, 0);
- }, [data]);
-
- const dataLoading = !data && !revenueError && !commissionsError;
- const error = revenueError || commissionsError;
+ const chartData = useMemo(
+ () =>
+ data?.map((d) => ({
+ date: new Date(d.start),
+ values: {
+ amount:
+ selectedTab === "sales" && saleUnit === "saleAmount"
+ ? d.saleAmount / 100
+ : d[selectedTab],
+ },
+ })),
+ [data, selectedTab, saleUnit],
+ );
return (
- <div>
- <div>
- <div className="flex justify-between gap-2">
- <Combobox
- selected={
- chartOptions.find((opt) => opt.value === viewType) || null
+ <div className="flex size-full flex-col gap-6">
+ <div className="flex flex-col">
+ <Combobox
+ selected={
+ chartOptions.find((opt) => opt.value === selectedTab) || null
+ }
+ setSelected={(option) =>
+ option && queryParams({ set: { event: option.value } })
+ }
+ options={chartOptions.slice()}
+ optionClassName="w-36"
+ caret={true}
+ hideSearch={true}
+ buttonProps={{
+ variant: "outline",
+ className: "h-7 w-fit px-2 -ml-2 -mt-1.5",
+ }}
+ />
+ {totalEvents ? (
+ <NumberFlow
+ value={
+ selectedTab === "sales" && saleUnit === "saleAmount"
+ ? totalEvents.saleAmount / 100
+ : totalEvents[selectedTab]
}
- setSelected={(option) =>
- option && setViewType(option.value as ViewType)
+ className="text-content-emphasis block text-3xl font-medium"
+ format={
+ selectedTab === "sales" && saleUnit === "saleAmount"
+ ? {
+ style: "currency",
+ currency: "USD",
+ trailingZeroDisplay: "stripIfInteger",
+ }
+ : {
+ notation:
+ totalEvents[selectedTab] > 999999
+ ? "compact"
+ : "standard",
+ }
}
- options={chartOptions}
- optionClassName="w-36"
- caret={true}
- hideSearch={true}
- buttonProps={{
- variant: "outline",
- className: "h-9 w-fit",
- }}
/>
-
- <SimpleDateRangePicker className="h-9 w-fit px-2" />
- </div>
-
- <div className="flex flex-col gap-1 px-4">
- {total === undefined ? (
- <div className="h-11 w-24 animate-pulse rounded-md bg-neutral-200" />
- ) : (
- <NumberFlow
- value={total}
- className="text-3xl text-neutral-800"
- format={{
- style: "currency",
- currency: "USD",
- }}
- />
- )}
- </div>
+ ) : (
+ <div className="mb-1 mt-px h-10 w-24 animate-pulse rounded-md bg-neutral-200" />
+ )}
</div>
- <div className="relative mt-4 h-72 md:h-96">
- {dataLoading ? (
+
+ <div className="relative min-h-0 grow">
+ {isLoading ? (
<div className="flex size-full items-center justify-center">
<LoadingSpinner />
</div>
- ) : error ? (
- <div className="flex size-full items-center justify-center text-sm text-neutral-500">
- Failed to load data
- </div>
) : (
- <TimeSeriesChart
- key={`${start?.toString}-${end?.toString()}-${interval?.toString()}-${viewType}`}
- data={data || []}
- series={[
- {
- id: "amount",
- valueAccessor: (d) => d.values.amount,
- colorClassName: "text-[#8B5CF6]",
- isActive: true,
- },
- ]}
- tooltipClassName="p-0"
- tooltipContent={(d) => {
- return (
- <>
- <p className="border-b border-neutral-200 px-4 py-3 text-sm text-neutral-900">
- {formatDateTooltip(d.date, { interval, start, end })}
- </p>
- <div className="grid grid-cols-2 gap-x-6 gap-y-2 px-4 py-3 text-sm">
- <div className="flex items-center gap-2">
- <div className="h-2 w-2 rounded-sm bg-violet-500 shadow-[inset_0_0_0_1px_#0003]" />
- <p className="capitalize text-neutral-600">
- {viewType === "revenue" ? "Revenue" : "Commissions"}
- </p>
- </div>
- <p className="text-right font-medium text-neutral-900">
- {currencyFormatter(d.values.amount, {
- minimumFractionDigits: 2,
- maximumFractionDigits: 2,
- })}
- </p>
- </div>
- </>
- );
- }}
- >
- <ChartContext.Consumer>
- {(context) => (
- <LinearGradient
- id={`${id}-color-gradient`}
- from="#7D3AEC"
- to="#DA2778"
- x1={0}
- x2={context?.width ?? 1}
- gradientUnits="userSpaceOnUse"
- />
- )}
- </ChartContext.Consumer>
- <XAxis
- tickFormat={(date) =>
- formatDateTooltip(date, { interval, start, end })
- }
- />
- <YAxis showGridLines tickFormat={currencyFormatter} />
- <Areas
- seriesStyles={[
- {
- id: "saleAmount",
- areaFill: `url(#${id}-color-gradient)`,
- lineStroke: `url(#${id}-color-gradient)`,
- lineClassName: "text-violet-500",
- },
- ]}
- />
- </TimeSeriesChart>
+ <AnalyticsTimeseriesChart data={chartData} />
)}
</div>
</div>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/page-client.tsx
index 7a7712e9ec..37f601b110 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/page-client.tsx
@@ -1,58 +1,96 @@
"use client";
import { DUB_PARTNERS_ANALYTICS_INTERVAL } from "@/lib/analytics/constants";
+import { AnalyticsResponseOptions } from "@/lib/analytics/types";
+import { editQueryString } from "@/lib/analytics/utils";
import useProgram from "@/lib/swr/use-program";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { AnalyticsContext } from "@/ui/analytics/analytics-provider";
import SimpleDateRangePicker from "@/ui/shared/simple-date-range-picker";
import { useRouterStuff } from "@dub/ui";
-import { IntervalOptions } from "date-fns";
-import { useParams } from "next/navigation";
-import { ContextType, createContext, useMemo } from "react";
-
-export const ProgramOverviewContext = createContext<{
- start?: string;
- end?: string;
- interval?: IntervalOptions;
-}>({});
+import { fetcher } from "@dub/utils";
+import { useMemo } from "react";
+import useSWR from "swr";
+import { OverviewChart } from "./overview-chart";
export default function ProgramOverviewPageClient() {
const { program } = useProgram();
- const { slug } = useParams();
- const { getQueryString } = useRouterStuff();
-
const { searchParamsObj } = useRouterStuff();
- const { start, end, interval } = useMemo(
- () =>
- ({
- interval: DUB_PARTNERS_ANALYTICS_INTERVAL,
- ...searchParamsObj,
- }) as ContextType<typeof ProgramOverviewContext>,
- [searchParamsObj],
+ const { defaultProgramId, id: workspaceId } = useWorkspace();
+
+ const { start, end, interval, selectedTab } = useMemo(() => {
+ const { event, ...rest } = searchParamsObj;
+ return {
+ interval: DUB_PARTNERS_ANALYTICS_INTERVAL,
+ selectedTab: event || "sales",
+ ...rest,
+ } as Record<string, any>;
+ }, [searchParamsObj]);
+
+ const queryString = new URLSearchParams({
+ programId: defaultProgramId ?? "",
+ workspaceId: workspaceId ?? "",
+ ...(start &&
+ end && {
+ start: new Date(start).toISOString(),
+ end: new Date(end).toISOString(),
+ }),
+ ...(interval && { interval: interval.toString() }),
+ }).toString();
+
+ const { data: totalEvents } = useSWR<{
+ [key in AnalyticsResponseOptions]: number;
+ }>(
+ `/api/analytics?${editQueryString(queryString, {
+ event: "composite",
+ })}`,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
);
return (
<div className="@container flex flex-col gap-6">
<SimpleDateRangePicker align="start" className="w-fit" />
- <div className="@4xl:grid-cols-[minmax(0,1fr)_400px] grid grid-cols-1 gap-6 rounded-2xl bg-neutral-100 p-4">
- {/* Chart */}
- <div className="border-border-subtle @4xl:h-full h-96 rounded-[0.625rem] border bg-white"></div>
+ <AnalyticsContext.Provider
+ value={{
+ basePath: "",
+ baseApiPath: "/api/analytics",
+ selectedTab,
+ saleUnit: "saleAmount",
+ view: "timeseries",
+ queryString,
+ start: start ? new Date(start) : undefined,
+ end: end ? new Date(end) : undefined,
+ interval: interval as string | undefined,
+ totalEvents,
+ }}
+ >
+ <div className="@4xl:grid-cols-[minmax(0,1fr)_400px] grid grid-cols-1 gap-6 rounded-2xl bg-neutral-100 p-4">
+ {/* Chart */}
+ <div className="border-border-subtle @4xl:h-full h-96 rounded-[0.625rem] border bg-white p-6">
+ <OverviewChart />
+ </div>
- <div className="@4xl:grid-cols-1 grid grid-cols-2 gap-6">
- {/* Tasks */}
- <div className="border-border-subtle h-48 rounded-[0.625rem] border bg-white"></div>
+ <div className="@4xl:grid-cols-1 @2xl:grid-cols-2 grid grid-cols-1 gap-6">
+ {/* Tasks */}
+ <div className="border-border-subtle h-48 rounded-[0.625rem] border bg-white"></div>
- {/* Program links */}
- <div className="border-border-subtle h-48 rounded-[0.625rem] border bg-white"></div>
+ {/* Program links */}
+ <div className="border-border-subtle h-48 rounded-[0.625rem] border bg-white"></div>
+ </div>
+ </div>
+ <div className="@2xl:grid-cols-2 @4xl:grid-cols-3 grid grid-cols-1 gap-6">
+ {[...Array(6)].map((_, idx) => (
+ <div
+ key={idx}
+ className="border-border-subtle h-64 rounded-[0.625rem] border bg-white"
+ ></div>
+ ))}
</div>
- </div>
- <div className="@2xl:grid-cols-2 @4xl:grid-cols-3 grid grid-cols-1 gap-6">
- {[...Array(6)].map((_, idx) => (
- <div
- key={idx}
- className="border-border-subtle h-64 rounded-[0.625rem] border bg-white"
- ></div>
- ))}
- </div>
+ </AnalyticsContext.Provider>
{/* <div className="mt-6 grid grid-cols-1 gap-6 md:grid-cols-2">
<TopPartners />
<PendingPayouts />