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.

display sales and earnings

Kiran Kb12a15643106
diff --git a/apps/web/app/api/events/client/route.ts b/apps/web/app/api/events/client/route.ts
index 0a771e2642..4ecdb848b7 100644
--- a/apps/web/app/api/events/client/route.ts
+++ b/apps/web/app/api/events/client/route.ts
@@ -1,17 +1,40 @@
import { getEvents } from "@/lib/analytics/get-events";
+import { calculateEarnings } from "@/lib/api/sales/commission";
import { withAuth } from "@/lib/referrals/auth";
import { eventsQuerySchema } from "@/lib/zod/schemas/analytics";
import { NextResponse } from "next/server";
// GET /api/events/client - get events for the current link
-export const GET = withAuth(async ({ searchParams, workspace, link }) => {
- const parsedParams = eventsQuerySchema.parse(searchParams);
+export const GET = withAuth(async ({ searchParams, program, link }) => {
+ const parsedParams = eventsQuerySchema
+ .omit({
+ linkId: true,
+ externalId: true,
+ domain: true,
+ root: true,
+ key: true,
+ tagId: true,
+ })
+ .parse(searchParams);
const response = await getEvents({
...parsedParams,
linkId: link.id,
- workspaceId: workspace.id,
+ obfuscateData: true,
});
- return NextResponse.json(response);
+ return NextResponse.json(
+ response.map((item: any) => {
+ return {
+ ...item,
+ ...(parsedParams.event === "sales" && {
+ earnings: calculateEarnings({
+ program,
+ sales: item.sales ?? 0,
+ saleAmount: item.sale?.amount ?? 0,
+ }),
+ }),
+ };
+ }),
+ );
});
diff --git a/apps/web/app/app.dub.co/embed/context.tsx b/apps/web/app/app.dub.co/embed/context.tsx
new file mode 100644
index 0000000000..6e3ebfd46b
--- /dev/null
+++ b/apps/web/app/app.dub.co/embed/context.tsx
@@ -0,0 +1,11 @@
+"use client";
+
+import { IntervalOptions } from "@/lib/analytics/types";
+import { createContext } from "react";
+
+export const ProgramOverviewContext = createContext<{
+ start?: Date;
+ end?: Date;
+ interval?: IntervalOptions;
+ color?: string;
+}>({});
diff --git a/apps/web/app/app.dub.co/embed/earnings-chart.tsx b/apps/web/app/app.dub.co/embed/earnings-chart.tsx
new file mode 100644
index 0000000000..b66be6e5a1
--- /dev/null
+++ b/apps/web/app/app.dub.co/embed/earnings-chart.tsx
@@ -0,0 +1,144 @@
+"use client";
+
+import Areas from "@/ui/charts/areas";
+import { ChartContext } from "@/ui/charts/chart-context";
+import TimeSeriesChart from "@/ui/charts/time-series-chart";
+import XAxis from "@/ui/charts/x-axis";
+import YAxis from "@/ui/charts/y-axis";
+import SimpleDateRangePicker from "@/ui/shared/simple-date-range-picker";
+import { LoadingSpinner } from "@dub/ui/src/icons";
+import { cn, currencyFormatter, formatDate } from "@dub/utils";
+import { LinearGradient } from "@visx/gradient";
+import { useContext, useId, useMemo } from "react";
+import { ProgramOverviewContext } from "./context";
+import useReferralAnalytics from "./use-referral-analytics";
+
+export function EarningsChart() {
+ const id = useId();
+ const { start, end, interval, color } = useContext(ProgramOverviewContext);
+
+ const { data: { earnings: total } = {} } = useReferralAnalytics({
+ interval,
+ start,
+ end,
+ });
+
+ const { data: timeseries, error } = useReferralAnalytics({
+ groupBy: "timeseries",
+ interval,
+ start,
+ end,
+ });
+
+ const data = useMemo(
+ () =>
+ timeseries?.map(({ start, earnings }) => ({
+ date: new Date(start),
+ values: { earnings: earnings / 100 },
+ })),
+ [timeseries],
+ );
+
+ return (
+ <div>
+ <div className="flex flex-col-reverse items-start justify-between gap-4 md:flex-row">
+ <div>
+ <span className="block text-sm text-neutral-500">Earnings</span>
+ <div className="mt-1.5">
+ {total !== undefined ? (
+ <span className="text-2xl leading-none text-neutral-800">
+ {currencyFormatter(total / 100, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ })}
+ </span>
+ ) : (
+ <div className="h-7 w-24 animate-pulse rounded-md bg-neutral-200" />
+ )}
+ </div>
+ </div>
+ <div className="w-full md:w-auto">
+ <SimpleDateRangePicker className="h-8 w-full md:w-fit" />
+ </div>
+ </div>
+ <div className="relative mt-4 h-64 w-full">
+ {data ? (
+ <TimeSeriesChart
+ data={data}
+ series={[
+ {
+ id: "earnings",
+ valueAccessor: (d) => d.values.earnings,
+ colorClassName: color ? `text-[${color}]` : "text-violet-500",
+ isActive: true,
+ },
+ ]}
+ tooltipClassName="p-0"
+ tooltipContent={(d) => {
+ return (
+ <>
+ <p className="border-b border-gray-200 px-4 py-3 text-sm text-gray-900">
+ {formatDate(d.date)}
+ </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={cn(
+ "h-2 w-2 rounded-sm shadow-[inset_0_0_0_1px_#0003]",
+ color ? `bg-[${color}]` : "bg-violet-500",
+ )}
+ />
+ <p className="capitalize text-gray-600">Earnings</p>
+ </div>
+ <p className="text-right font-medium text-gray-900">
+ {currencyFormatter(d.values.earnings, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ })}
+ </p>
+ </div>
+ </>
+ );
+ }}
+ >
+ <ChartContext.Consumer>
+ {(context) => (
+ <LinearGradient
+ id={`${id}-color-gradient`}
+ from={color || "#7D3AEC"}
+ to={color || "#DA2778"}
+ x1={0}
+ x2={context?.width ?? 1}
+ gradientUnits="userSpaceOnUse"
+ />
+ )}
+ </ChartContext.Consumer>
+
+ <XAxis />
+ <YAxis showGridLines />
+ <Areas
+ seriesStyles={[
+ {
+ id: "earnings",
+ areaFill: `url(#${id}-color-gradient)`,
+ lineStroke: `url(#${id}-color-gradient)`,
+ lineClassName: `text-[${color}]`,
+ },
+ ]}
+ />
+ </TimeSeriesChart>
+ ) : (
+ <div className="flex size-full items-center justify-center">
+ {error ? (
+ <span className="text-sm text-neutral-500">
+ Failed to load earnings data.
+ </span>
+ ) : (
+ <LoadingSpinner />
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/app/app.dub.co/embed/page-client.tsx b/apps/web/app/app.dub.co/embed/page-client.tsx
index 0ca8f0f67d..64f6cd43e4 100644
--- a/apps/web/app/app.dub.co/embed/page-client.tsx
+++ b/apps/web/app/app.dub.co/embed/page-client.tsx
@@ -1,14 +1,7 @@
"use client";
import { IntervalOptions } from "@/lib/analytics/types";
-import Areas from "@/ui/charts/areas";
-import { ChartContext } from "@/ui/charts/chart-context";
-import TimeSeriesChart from "@/ui/charts/time-series-chart";
-import XAxis from "@/ui/charts/x-axis";
-import YAxis from "@/ui/charts/y-axis";
import { ProgramCommissionDescription } from "@/ui/partners/program-commission-description";
-import SimpleDateRangePicker from "@/ui/shared/simple-date-range-picker";
-import { MiniAreaChart } from "@dub/blocks";
import {
Button,
Check2,
@@ -16,28 +9,15 @@ import {
useCopyToClipboard,
useRouterStuff,
} from "@dub/ui";
-import { Copy, LoadingSpinner, MoneyBill2 } from "@dub/ui/src/icons";
-import {
- cn,
- currencyFormatter,
- formatDate,
- getPrettyUrl,
- nFormatter,
-} from "@dub/utils";
-import { LinearGradient } from "@visx/gradient";
-import { createContext, useContext, useId, useMemo } from "react";
+import { Copy, MoneyBill2 } from "@dub/ui/src/icons";
+import { getPrettyUrl } from "@dub/utils";
+import { ProgramOverviewContext } from "./context";
+import { EarningsChart } from "./earnings-chart";
import { HeroBackground } from "./hero-background";
-import useReferralAnalytics from "./use-referral-analytics";
+import { SaleTable } from "./sale-table";
+import { StatCard } from "./stat-card";
import { useReferralLink } from "./use-referral-link";
import { useReferralProgram } from "./use-referral-program";
-// import { SaleTablePartner } from "./sales/sale-table";
-
-const ProgramOverviewContext = createContext<{
- start?: Date;
- end?: Date;
- interval?: IntervalOptions;
- color?: string;
-}>({});
export function ReferralsEmbedPageClient() {
const { program } = useReferralProgram();
@@ -124,198 +104,11 @@ export function ReferralsEmbedPageClient() {
Recent sales
</h2>
</div>
- <div className="mt-4">{/* <SaleTablePartner limit={10} /> */}</div>
+ <div className="mt-4">
+ <SaleTable limit={10} />
+ </div>
</div>
</ProgramOverviewContext.Provider>
</MaxWidthWrapper>
);
}
-
-function EarningsChart() {
- const id = useId();
- const { start, end, interval, color } = useContext(ProgramOverviewContext);
-
- const { data: { earnings: total } = {} } = useReferralAnalytics({
- interval,
- start,
- end,
- });
-
- const { data: timeseries, error } = useReferralAnalytics({
- groupBy: "timeseries",
- interval,
- start,
- end,
- });
-
- const data = useMemo(
- () =>
- timeseries?.map(({ start, earnings }) => ({
- date: new Date(start),
- values: { earnings: earnings / 100 },
- })),
- [timeseries],
- );
-
- return (
- <div>
- <div className="flex flex-col-reverse items-start justify-between gap-4 md:flex-row">
- <div>
- <span className="block text-sm text-neutral-500">Earnings</span>
- <div className="mt-1.5">
- {total !== undefined ? (
- <span className="text-2xl leading-none text-neutral-800">
- {currencyFormatter(total / 100, {
- minimumFractionDigits: 2,
- maximumFractionDigits: 2,
- })}
- </span>
- ) : (
- <div className="h-7 w-24 animate-pulse rounded-md bg-neutral-200" />
- )}
- </div>
- </div>
- <div className="w-full md:w-auto">
- <SimpleDateRangePicker className="h-8 w-full md:w-fit" />
- </div>
- </div>
- <div className="relative mt-4 h-64 w-full">
- {data ? (
- <TimeSeriesChart
- data={data}
- series={[
- {
- id: "earnings",
- valueAccessor: (d) => d.values.earnings,
- colorClassName: color ? `text-[${color}]` : "text-violet-500",
- isActive: true,
- },
- ]}
- tooltipClassName="p-0"
- tooltipContent={(d) => {
- return (
- <>
- <p className="border-b border-gray-200 px-4 py-3 text-sm text-gray-900">
- {formatDate(d.date)}
- </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={cn(
- "h-2 w-2 rounded-sm shadow-[inset_0_0_0_1px_#0003]",
- color ? `bg-[${color}]` : "bg-violet-500",
- )}
- />
- <p className="capitalize text-gray-600">Earnings</p>
- </div>
- <p className="text-right font-medium text-gray-900">
- {currencyFormatter(d.values.earnings, {
- minimumFractionDigits: 2,
- maximumFractionDigits: 2,
- })}
- </p>
- </div>
- </>
- );
- }}
- >
- <ChartContext.Consumer>
- {(context) => (
- <LinearGradient
- id={`${id}-color-gradient`}
- from={color || "#7D3AEC"}
- to={color || "#DA2778"}
- x1={0}
- x2={context?.width ?? 1}
- gradientUnits="userSpaceOnUse"
- />
- )}
- </ChartContext.Consumer>
-
- <XAxis />
- <YAxis showGridLines />
- <Areas
- seriesStyles={[
- {
- id: "earnings",
- areaFill: `url(#${id}-color-gradient)`,
- lineStroke: `url(#${id}-color-gradient)`,
- lineClassName: `text-[${color}]`,
- },
- ]}
- />
- </TimeSeriesChart>
- ) : (
- <div className="flex size-full items-center justify-center">
- {error ? (
- <span className="text-sm text-neutral-500">
- Failed to load earnings data.
- </span>
- ) : (
- <LoadingSpinner />
- )}
- </div>
- )}
- </div>
- </div>
- );
-}
-
-function StatCard({
- title,
- event,
-}: {
- title: string;
- event: "clicks" | "leads" | "sales";
-}) {
- const { start, end, interval, color } = useContext(ProgramOverviewContext);
-
- const { data: total } = useReferralAnalytics({
- interval,
- start,
- end,
- });
-
- const { data: timeseries, error } = useReferralAnalytics({
- groupBy: "timeseries",
- interval,
- start,
- end,
- event,
- });
-
- return (
- <div className="hover:drop-shadow-card-hover block rounded-md border border-neutral-300 bg-white p-5 transition-[filter]">
- <span className="block text-sm text-neutral-500">{title}</span>
- {total !== undefined ? (
- <span className="block text-2xl text-neutral-800">
- {nFormatter(total[event])}
- </span>
- ) : (
- <div className="h-8 w-16 animate-pulse rounded-md bg-neutral-200" />
- )}
- <div className="mt-2 h-16 w-full">
- {timeseries ? (
- <MiniAreaChart
- data={timeseries.map((d) => ({
- date: new Date(d.start),
- value: d[event],
- }))}
- curve={false}
- color={color}
- />
- ) : (
- <div className="flex size-full items-center justify-center">
- {error ? (
- <span className="text-sm text-neutral-500">
- Failed to load data.
- </span>
- ) : (
- <LoadingSpinner />
- )}
- </div>
- )}
- </div>
- </div>
- );
-}
diff --git a/apps/web/app/app.dub.co/embed/sale-table.tsx b/apps/web/app/app.dub.co/embed/sale-table.tsx
new file mode 100644
index 0000000000..f9afb3e6d0
--- /dev/null
+++ b/apps/web/app/app.dub.co/embed/sale-table.tsx
@@ -0,0 +1,151 @@
+"use client";
+
+import { IntervalOptions } from "@/lib/analytics/types";
+import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
+import SimpleDateRangePicker from "@/ui/shared/simple-date-range-picker";
+import { Table, usePagination, useRouterStuff, useTable } from "@dub/ui";
+import { CircleDollar } from "@dub/ui/src/icons";
+import { currencyFormatter, formatDate } from "@dub/utils";
+import useReferralAnalytics from "./use-referral-analytics";
+import useReferralEvents from "./use-referral-events";
+
+export function SaleTable({ limit }: { limit?: number }) {
+ const { queryParams, searchParamsObj } = useRouterStuff();
+
+ const {
+ start,
+ end,
+ interval,
+ sortBy = "timestamp",
+ order = "desc",
+ } = searchParamsObj as {
+ start?: string;
+ end?: string;
+ interval?: IntervalOptions;
+ sortBy?: "timestamp";
+ order?: "asc" | "desc";
+ };
+
+ const { data: { sales: totalSaleEvents } = {} } = useReferralAnalytics({
+ interval,
+ start: start ? new Date(start) : undefined,
+ end: end ? new Date(end) : undefined,
+ });
+
+ const {
+ data: saleEvents,
+ loading,
+ error,
+ } = useReferralEvents({
+ event: "sales",
+ interval: interval as any,
+ start: start ? new Date(start) : undefined,
+ end: end ? new Date(end) : undefined,
+ order,
+ sortBy,
+ });
+
+ const { pagination, setPagination } = usePagination(limit);
+
+ const { table, ...tableProps } = useTable({
+ data: saleEvents?.slice(0, limit) || [],
+ loading,
+ error: error ? "Failed to fetch sales events." : undefined,
+ columns: [
+ {
+ id: "timestamp",
+ header: "Date",
+ accessorKey: "timestamp",
+ cell: ({ row }) => {
+ return formatDate(row.original.timestamp, { month: "short" });
+ },
+ },
+ {
+ id: "customer",
+ header: "Customer",
+ accessorKey: "customer",
+ cell: ({ row }) => {
+ return row.original.customer.email;
+ },
+ },
+ {
+ id: "saleAmount",
+ header: "Sale Amount",
+ accessorKey: "sale",
+ cell: ({ row }) => {
+ return currencyFormatter(row.original.sale.amount / 100, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ });
+ },
+ },
+ {
+ id: "earnings",
+ header: "Earnings",
+ accessorKey: "earnings",
+ cell: ({ row }) => {
+ return currencyFormatter(row.original.earnings / 100, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ });
+ },
+ },
+ ],
+ ...(!limit && {
+ pagination,
+ onPaginationChange: setPagination,
+ sortableColumns: ["timestamp"],
+ sortBy,
+ sortOrder: order,
+ onSortChange: ({ sortBy, sortOrder }) =>
+ queryParams({
+ set: {
+ ...(sortBy && { sort: sortBy }),
+ ...(sortOrder && { order: sortOrder }),
+ },
+ }),
+ }),
+ rowCount: totalSaleEvents,
+ emptyState: (
+ <AnimatedEmptyState
+ title="No sales found"
+ description="No sales have been made for this program yet."
+ cardContent={() => (
+ <>
+ <CircleDollar className="size-4 text-neutral-700" />
+ <div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />
+ </>
+ )}
+ />
+ ),
+ resourceName: (plural) => `sale${plural ? "s" : ""}`,
+ });
+
+ return (
+ <div className="flex flex-col gap-3">
+ {!limit && (
+ <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
+ <SimpleDateRangePicker className="w-full sm:min-w-[200px] md:w-fit" />
+ </div>
+ )}
+ {loading || saleEvents?.length ? (
+ <Table
+ {...tableProps}
+ table={table}
+ containerClassName="border-neutral-300"
+ />
+ ) : (
+ <AnimatedEmptyState
+ title="No sales found"
+ description="No sales have been made for this program yet."
+ cardContent={() => (
+ <>
+ <CircleDollar className="size-4 text-neutral-700" />
+ <div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />
+ </>
+ )}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/app/app.dub.co/embed/stat-card.tsx b/apps/web/app/app.dub.co/embed/stat-card.tsx
new file mode 100644
index 0000000000..184a685255
--- /dev/null
+++ b/apps/web/app/app.dub.co/embed/stat-card.tsx
@@ -0,0 +1,67 @@
+"use client";
+
+import { MiniAreaChart } from "@dub/blocks";
+import { LoadingSpinner } from "@dub/ui/src/icons";
+import { nFormatter } from "@dub/utils";
+import { useContext } from "react";
+import { ProgramOverviewContext } from "./context";
+import useReferralAnalytics from "./use-referral-analytics";
+
+export function StatCard({
+ title,
+ event,
+}: {
+ title: string;
+ event: "clicks" | "leads" | "sales";
+}) {
+ const { start, end, interval, color } = useContext(ProgramOverviewContext);
+
+ const { data: total } = useReferralAnalytics({
+ interval,
+ start,
+ end,
+ });
+
+ const { data: timeseries, error } = useReferralAnalytics({
+ groupBy: "timeseries",
+ interval,
+ start,
+ end,
+ event,
+ });
+
+ return (
+ <div className="hover:drop-shadow-card-hover block rounded-md border border-neutral-300 bg-white p-5 transition-[filter]">
+ <span className="block text-sm text-neutral-500">{title}</span>
+ {total !== undefined ? (
+ <span className="block text-2xl text-neutral-800">
+ {nFormatter(total[event])}
+ </span>
+ ) : (
+ <div className="h-8 w-16 animate-pulse rounded-md bg-neutral-200" />
+ )}
+ <div className="mt-2 h-16 w-full">
+ {timeseries ? (
+ <MiniAreaChart
+ data={timeseries.map((d) => ({
+ date: new Date(d.start),
+ value: d[event],
+ }))}
+ curve={false}
+ color={color}
+ />
+ ) : (
+ <div className="flex size-full items-center justify-center">
+ {error ? (
+ <span className="text-sm text-neutral-500">
+ Failed to load data.
+ </span>
+ ) : (
+ <LoadingSpinner />
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/app/app.dub.co/embed/use-referral-analytics.ts b/apps/web/app/app.dub.co/embed/use-referral-analytics.ts
index eb32a6cd84..da20e38c06 100644
--- a/apps/web/app/app.dub.co/embed/use-referral-analytics.ts
+++ b/apps/web/app/app.dub.co/embed/use-referral-analytics.ts
@@ -15,7 +15,7 @@ export default function useReferralAnalytics(params?: PartnerAnalyticsFilters) {
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
});
- const { data, error, isLoading } = useSWR<any>(
+ const { data, error } = useSWR<any>(
`/api/analytics/client?${searchParams.toString()}`,
fetcher,
{
@@ -26,6 +26,6 @@ export default function useReferralAnalytics(params?: PartnerAnalyticsFilters) {
return {
data,
error,
- isLoading,
+ loading: !data && !error,
};
}
diff --git a/apps/web/app/app.dub.co/embed/use-referral-events.ts b/apps/web/app/app.dub.co/embed/use-referral-events.ts
new file mode 100644
index 0000000000..9d695a43df
--- /dev/null
+++ b/apps/web/app/app.dub.co/embed/use-referral-events.ts
@@ -0,0 +1,29 @@
+import { PartnerEventsFilters } from "@/lib/analytics/types";
+import { fetcher } from "@dub/utils";
+import useSWR from "swr";
+
+export default function useReferralEvents(params?: PartnerEventsFilters) {
+ const searchParams = new URLSearchParams({
+ event: params?.event ?? "sales",
+ ...(params?.start && params?.end
+ ? {
+ start: params.start.toISOString(),
+ end: params.end.toISOString(),
+ }
+ : { interval: params?.interval ?? "30d" }),
+ });
+
+ const { data, error } = useSWR<any>(
+ `/api/events/client?${searchParams.toString()}`,
+ fetcher,
+ {
+ dedupingInterval: 60000,
+ },
+ );
+
+ return {
+ data,
+ error,
+ loading: !data && !error,
+ };
+}