The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
WIP
Tim Wilson80ef00db4726
diff --git a/apps/web/app/api/customers/count/route.ts b/apps/web/app/api/customers/count/route.tsnew file mode 100644index 0000000000..8fd9ad75b5--- /dev/null+++ b/apps/web/app/api/customers/count/route.ts@@ -0,0 +1,14 @@+import { withWorkspace } from "@/lib/auth";+import { prisma } from "@dub/prisma";+import { NextResponse } from "next/server";++// GET /api/customers/count+export const GET = withWorkspace(async ({ workspace, params }) => {+ const count = await prisma.customer.count({+ where: {+ projectId: workspace.id,+ },+ });++ return NextResponse.json(count);+});diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/[customerId]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/[customerId]/page-client.tsxindex fa8e27a455..cd8da17061 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/[customerId]/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/[customerId]/page-client.tsx@@ -2,8 +2,9 @@import useCustomer from "@/lib/swr/use-customer";import useWorkspace from "@/lib/swr/use-workspace";-import { CustomerActivityResponse } from "@/lib/types";+import { CustomerActivityResponse, SaleEvent } from "@/lib/types";import DeviceIcon from "@/ui/analytics/device-icon";+import { CustomerEarningsTable } from "@/ui/customers/customer-earnings-table";import { BackLink } from "@/ui/shared/back-link";import { CopyButton, UTM_PARAMETERS } from "@dub/ui";import {@@ -18,7 +19,7 @@ import {} from "@dub/utils";import Link from "next/link";import { notFound, useParams } from "next/navigation";-import { Fragment, HTMLProps, useMemo } from "react";+import { Fragment, HTMLProps, memo, useMemo } from "react";import useSWR from "swr";export function CustomerPageClient() {@@ -97,8 +98,8 @@ export function CustomerPageClient() {{/* Main content */}<div className="flex flex-col gap-10"><section className="flex flex-col gap-4">- <h2 className="text-lg font-semibold text-neutral-900">Sales</h2>- <div className="h-64 rounded-lg bg-neutral-100" />+ <h2 className="text-lg font-semibold text-neutral-900">Earnings</h2>+ <EarningsTable customerId={customerId} /></section><section className="flex flex-col gap-4">@@ -108,7 +109,7 @@ export function CustomerPageClient() {</div>{/* Right side details */}- <div className="-order-1 grid grid-cols-2 gap-6 overflow-hidden whitespace-nowrap text-sm text-neutral-900 lg:order-1 lg:grid-cols-1">+ <div className="-order-1 grid grid-cols-1 gap-6 overflow-hidden whitespace-nowrap text-sm text-neutral-900 min-[320px]:grid-cols-2 lg:order-1 lg:grid-cols-1"><div className="flex flex-col gap-2"><DetailHeading>Details</DetailHeading>{customer.country && (@@ -238,3 +239,34 @@ const DetailHeading = ({{...rest}></h2>);++const EarningsTable = memo(({ customerId }: { customerId: string }) => {+ const { id: workspaceId, slug } = useWorkspace();++ const { data: salesData, isLoading: isSalesLoading } = useSWR<SaleEvent[]>(+ `/api/events?event=sales&interval=all&limit=8&customerId=${customerId}&workspaceId=${workspaceId}`,+ fetcher,+ {+ keepPreviousData: true,+ },+ );++ const { data: totalSales, isLoading: isTotalSalesLoading } = useSWR<{+ sales: number;+ }>(+ `/api/analytics?event=sales&interval=all&groupBy=count&customerId=${customerId}&workspaceId=${workspaceId}`,+ fetcher,+ {+ keepPreviousData: true,+ },+ );++ return (+ <CustomerEarningsTable+ sales={salesData}+ totalSales={totalSales?.sales}+ viewAllHref={`/${slug}/events?event=sales&interval=all&customerId=${customerId}`}+ isLoading={isSalesLoading || isTotalSalesLoading}+ />+ );+});diff --git a/apps/web/lib/analytics/constants.ts b/apps/web/lib/analytics/constants.tsindex 868df62762..14b07d2756 100644--- a/apps/web/lib/analytics/constants.ts+++ b/apps/web/lib/analytics/constants.ts@@ -186,6 +186,7 @@ export const VALID_ANALYTICS_FILTERS = ["tagId","folderId","tagIds",+ "customerId","qr", // deprecated, but keeping for now for backwards compatibility"root","utm_source",diff --git a/apps/web/lib/swr/use-customers-count.ts b/apps/web/lib/swr/use-customers-count.tsnew file mode 100644index 0000000000..1e79ede093--- /dev/null+++ b/apps/web/lib/swr/use-customers-count.ts@@ -0,0 +1,17 @@+import { fetcher } from "@dub/utils";+import useSWR from "swr";+import useWorkspace from "./use-workspace";++export default function useCustomersCount() {+ const { id: workspaceId } = useWorkspace();++ const { data, error } = useSWR<number>(+ `/api/customers/count?workspaceId=${workspaceId}`,+ fetcher,+ );++ return {+ data,+ error,+ };+}diff --git a/apps/web/lib/swr/use-customers.ts b/apps/web/lib/swr/use-customers.tsnew file mode 100644index 0000000000..805a7374c4--- /dev/null+++ b/apps/web/lib/swr/use-customers.ts@@ -0,0 +1,34 @@+import { fetcher } from "@dub/utils";+import useSWR from "swr";+import { z } from "zod";+import { CustomerProps } from "../types";+import { customersQuerySchema } from "../zod/schemas/customers";+import useWorkspace from "./use-workspace";++const partialQuerySchema = customersQuerySchema.partial();++export default function useCustomers({+ query,+ enabled = true,+}: {+ query?: z.infer<typeof partialQuerySchema>;+ enabled?: boolean;+} = {}) {+ const { id: workspaceId } = useWorkspace();++ const { data: customers, error } = useSWR<CustomerProps[]>(+ enabled && workspaceId+ ? `/api/customers?${new URLSearchParams({+ workspaceId: workspaceId,+ ...query,+ } as Record<string, any>).toString()}`+ : undefined,+ fetcher,+ );++ return {+ customers,+ loading: !customers && !error,+ error,+ };+}diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.tsindex 6803408721..cd51bd6020 100644--- a/apps/web/lib/zod/schemas/analytics.ts+++ b/apps/web/lib/zod/schemas/analytics.ts@@ -101,6 +101,10 @@ export const analyticsQuerySchema = z.string().optional().describe("The ID of the partner to retrieve analytics for."),+ customerId: z+ .string()+ .optional()+ .describe("The ID of the customer to retrieve analytics for."),interval: z.enum(intervals).optional()diff --git a/apps/web/ui/analytics/analytics-provider.tsx b/apps/web/ui/analytics/analytics-provider.tsxindex 0e5a67cff4..63fcd04fb2 100644--- a/apps/web/ui/analytics/analytics-provider.tsx+++ b/apps/web/ui/analytics/analytics-provider.tsx@@ -125,6 +125,8 @@ export default function AnalyticsProvider({const folderId = searchParams?.get("folderId") ?? undefined;+ const customerId = searchParams?.get("customerId") ?? undefined;+// Default to last 24 hoursconst { start, end } = useMemo(() => {const hasRange = searchParams?.has("start") && searchParams?.has("end");@@ -283,6 +285,7 @@ export default function AnalyticsProvider({...(root && { root: root.toString() }),event: selectedTab,...(folderId && { folderId }),+ ...(customerId && { customerId }),timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,}).toString();}, [@@ -295,6 +298,7 @@ export default function AnalyticsProvider({tagIds,selectedTab,folderId,+ customerId,]);// Reset requiresUpgrade when query changesdiff --git a/apps/web/ui/analytics/toggle.tsx b/apps/web/ui/analytics/toggle.tsxindex 7c740e86c0..fdb5c6cff3 100644--- a/apps/web/ui/analytics/toggle.tsx+++ b/apps/web/ui/analytics/toggle.tsx@@ -7,6 +7,9 @@ import {} from "@/lib/analytics/constants";import { validDateRangeForPlan } from "@/lib/analytics/utils";import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";+import useCustomer from "@/lib/swr/use-customer";+import useCustomers from "@/lib/swr/use-customers";+import useCustomersCount from "@/lib/swr/use-customers-count";import useDomains from "@/lib/swr/use-domains";import useDomainsCount from "@/lib/swr/use-domains-count";import useFolder from "@/lib/swr/use-folder";@@ -16,6 +19,7 @@ import useTags from "@/lib/swr/use-tags";import useTagsCount from "@/lib/swr/use-tags-count";import useWorkspace from "@/lib/swr/use-workspace";import { LinkProps } from "@/lib/types";+import { CUSTOMERS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/customers";import { DOMAINS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/domains";import { FOLDERS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/folders";import { TAGS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/tags";@@ -51,6 +55,7 @@ import {QRCode,ReferredVia,Tag,+ User,Window,} from "@dub/ui/icons";import {@@ -59,6 +64,7 @@ import {cn,CONTINENTS,COUNTRIES,+ DICEBEAR_AVATAR_URL,DUB_DEMO_LINKS,DUB_LOGO,getApexDomain,@@ -101,6 +107,7 @@ export default function Toggle({useRouterStuff();const {+ selectedTab,domain,key,url,@@ -115,13 +122,16 @@ export default function Toggle({const scrolled = useScroll(120);- // Determine whether tags and domains should be fetched async+ // Determine whether filters should be fetched asyncconst { data: tagsCount } = useTagsCount();const { data: domainsCount } = useDomainsCount({ ignoreParams: true });const { data: foldersCount } = useFoldersCount();+ const { data: customersCount } = useCustomersCount();const tagsAsync = Boolean(tagsCount && tagsCount > TAGS_MAX_PAGE_SIZE);const domainsAsync = domainsCount && domainsCount > DOMAINS_MAX_PAGE_SIZE;const foldersAsync = foldersCount && foldersCount > FOLDERS_MAX_PAGE_SIZE;+ const customersAsync =+ customersCount && customersCount > CUSTOMERS_MAX_PAGE_SIZE;const [selectedFilter, setSelectedFilter] = useState<string | null>(null);const [search, setSearch] = useState("");@@ -138,6 +148,14 @@ export default function Toggle({foldersAsync && selectedFilter === "folderId" ? debouncedSearch : "",},});+ const { customers, loading: loadingCustomers } = useCustomers({+ query: {+ search:+ customersAsync && selectedFilter === "customerId"+ ? debouncedSearch+ : "",+ },+ });const {allDomains: domains,@@ -167,6 +185,11 @@ export default function Toggle({folderId: selectedFolderId,});+ const selectedCustomerId = searchParamsObj.customerId;+ const { data: selectedCustomer } = useCustomer({+ customerId: selectedCustomerId,+ });+const [requestedFilters, setRequestedFilters] = useState<string[]>([]);const activeFilters = useMemo(() => {@@ -349,6 +372,30 @@ export default function Toggle({: partnerPage? [LinkFilterItem]: [+ ...(["leads", "sales"].includes(selectedTab)+ ? [+ {+ key: "customerId",+ icon: User,+ label: "Customer",+ shouldFilter: !customersAsync,+ options:+ customers?.map(({ id, email, name, avatar }) => {+ return {+ value: id,+ label: email ?? name,+ icon: (+ <img+ src={avatar || `${DICEBEAR_AVATAR_URL}${id}`}+ alt={`${email} avatar`}+ className="size-4 rounded-full"+ />+ ),+ };+ }) ?? null,+ },+ ]+ : []),...(flags?.linkFolders? [{@@ -670,6 +717,7 @@ export default function Toggle({),],[+ selectedTab,dashboardProps,partnerPage,domains,@@ -679,6 +727,7 @@ export default function Toggle({selectedTags,selectedTagIds,selectedFolder,+ selectedCustomerId,countries,cities,devices,diff --git a/apps/web/ui/customers/customer-earnings-table.tsx b/apps/web/ui/customers/customer-earnings-table.tsxnew file mode 100644index 0000000000..6e4113d5d2--- /dev/null+++ b/apps/web/ui/customers/customer-earnings-table.tsx@@ -0,0 +1,134 @@+import { SaleEvent } from "@/lib/types";+import { Tooltip } from "@dub/ui";+import { currencyFormatter } from "@dub/utils";+import {+ flexRender,+ getCoreRowModel,+ useReactTable,+} from "@tanstack/react-table";+import Link from "next/link";++export function CustomerEarningsTable({+ sales,+ totalSales,+ isLoading,+ viewAllHref,+}: {+ sales?: Pick<SaleEvent, "timestamp" | "eventName" | "saleAmount">[];+ totalSales?: number;+ isLoading?: boolean;+ viewAllHref?: string;+}) {+ const table = useReactTable({+ data: sales || [],+ columns: [+ {+ header: "Date",+ accessorFn: (d) => new Date(d.timestamp),+ enableHiding: false,+ minSize: 100,+ cell: ({ getValue }) => (+ <Tooltip+ content={getValue().toLocaleTimeString("en-US", {+ year: "numeric",+ month: "short",+ day: "numeric",+ hour: "numeric",+ minute: "numeric",+ second: "numeric",+ hour12: true,+ })}+ >+ <div className="w-full truncate">+ {getValue().toLocaleTimeString("en-US", {+ month: "short",+ day: "numeric",+ hour: "numeric",+ minute: "numeric",+ hour12: true,+ })}+ </div>+ </Tooltip>+ ),+ },+ {+ header: "Event",+ accessorKey: "eventName",+ },+ {+ header: "Amount",+ accessorKey: "saleAmount",+ cell: ({ getValue }) => (+ <span>+ {currencyFormatter(getValue() / 100, {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })}+ </span>+ ),+ },+ ],+ getCoreRowModel: getCoreRowModel(),+ });++ return (+ <div className="overflow-x-auto">+ {isLoading ? (+ <div className="flex h-32 w-full animate-pulse rounded-lg border border-transparent bg-neutral-100" />+ ) : !sales?.length ? (+ <div className="border-border-subtle flex h-32 w-full items-center justify-center rounded-lg border text-xs text-neutral-500">+ {sales?.length === 0 ? "No earnings yet" : "Failed to load earnings"}+ </div>+ ) : (+ <>+ <table className="[&_tr]:border-border-subtle w-full overflow-hidden text-left text-sm [&_tr]:border-b">+ <thead>+ {table.getHeaderGroups().map((headerGroup) => (+ <tr key={headerGroup.id}>+ {headerGroup.headers.map((header) => (+ <th+ key={header.id}+ className="p-2 font-semibold text-neutral-900"+ >+ {header.isPlaceholder+ ? null+ : flexRender(+ header.column.columnDef.header,+ header.getContext(),+ )}+ </th>+ ))}+ </tr>+ ))}+ </thead>+ <tbody className="text-neutral-600">+ {table.getRowModel().rows.map((row) => (+ <tr key={row.id}>+ {row.getVisibleCells().map((cell) => (+ <td key={cell.id} className="truncate p-2">+ {flexRender(+ cell.column.columnDef.cell,+ cell.getContext(),+ )}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ {sales?.length && totalSales && viewAllHref && (+ <div className="mt-2 px-2 text-sm text-neutral-600">+ {sales.length} of{" "}+ <Link+ href={viewAllHref}+ className="font-medium text-neutral-700 hover:text-neutral-900"+ >+ {totalSales} results+ </Link>+ </div>+ )}+ </>+ )}+ </div>+ );+}diff --git a/packages/tinybird/pipes/v2_events.pipe b/packages/tinybird/pipes/v2_events.pipeindex 644781ce05..00f9808f94 100644--- a/packages/tinybird/pipes/v2_events.pipe+++ b/packages/tinybird/pipes/v2_events.pipe@@ -90,10 +90,10 @@ SQL >timestamp >= {{ DateTime(start, '2024-06-01 00:00:00') }}AND timestamp < {{ DateTime(end, '2024-06-07 00:00:00') }}{% if defined(linkId) %} AND link_id = {{ String(linkId) }}- {% elif defined(customerId) %} AND customer_id = {{ String(customerId) }}{% elif defined(workspaceId) or defined(partnerId) or defined(programId) %}AND link_id IN (SELECT link_id FROM workspace_links){% end %}+ {% if defined(customerId) %} AND customer_id = {{ String(customerId) }} {% end %}{% if defined(qr) %} AND qr = {{ Boolean(qr) }} {% end %}{% if defined(continent) %} AND continent = {{ continent }} {% end %}{% if defined(country) %} AND country = {{ country }} {% end %}@@ -131,10 +131,10 @@ SQL >timestamp >= {{ DateTime(start, '2024-06-01 00:00:00') }}AND timestamp < {{ DateTime(end, '2024-06-07 00:00:00') }}{% if defined(linkId) %} AND link_id = {{ String(linkId) }}- {% elif defined(customerId) %} AND customer_id = {{ String(customerId) }}{% elif defined(workspaceId) or defined(partnerId) or defined(programId) %}AND link_id IN (SELECT link_id FROM workspace_links){% end %}+ {% if defined(customerId) %} AND customer_id = {{ String(customerId) }} {% end %}{% if defined(qr) %} AND qr = {{ Boolean(qr) }} {% end %}{% if defined(continent) %} AND continent = {{ continent }} {% end %}{% if defined(country) %} AND country = {{ country }} {% end %}