The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
WIP table
Tim Wilson72c53ab3a835
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/page-client.tsxnew file mode 100644index 0000000000..459a68b801--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/page-client.tsx@@ -0,0 +1,9 @@+import { CustomerTable } from "@/ui/customers/customer-table/customer-table";++export function CustomersPageClient() {+ return (+ <div className="mt-3">+ <CustomerTable />+ </div>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/page.tsxindex 249b3b71f4..8e6609c511 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/page.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/page.tsx@@ -1,10 +1,13 @@import { PageContent } from "@/ui/layout/page-content";import { MaxWidthWrapper } from "@dub/ui";+import { CustomersPageClient } from "./page-client";export default function CustomersPage() {return (<PageContent title="Customers">- <MaxWidthWrapper>WIP</MaxWidthWrapper>+ <MaxWidthWrapper>+ <CustomersPageClient />+ </MaxWidthWrapper></PageContent>);}diff --git a/apps/web/ui/customers/customer-row-item.tsx b/apps/web/ui/customers/customer-row-item.tsxindex 8c00ae7d22..9533e85995 100644--- a/apps/web/ui/customers/customer-row-item.tsx+++ b/apps/web/ui/customers/customer-row-item.tsx@@ -2,6 +2,7 @@ import { generateRandomName } from "@/lib/names";import { ChartActivity2 } from "@dub/ui";import { cn, OG_AVATAR_URL } from "@dub/utils";import Link from "next/link";+import React, { ComponentProps } from "react";export function CustomerRowItem({customer,@@ -14,17 +15,18 @@ export function CustomerRowItem({name?: string | null;avatar?: string | null;};- href: string;+ href?: string;className?: string;}) {const display = customer.email || customer.name || generateRandomName();return (- <Link- href={href}- target="_blank"+ <Wrapper+ element={href ? Link : "div"}+ {...(href ? { href, target: "_blank" } : {})}className={cn(- "group flex cursor-alias items-center justify-between gap-2 decoration-dotted hover:underline",+ "group flex items-center justify-between gap-2",+ href && "cursor-alias decoration-dotted hover:underline",className,)}>@@ -36,7 +38,16 @@ export function CustomerRowItem({/><span className="truncate">{display}</span></div>- <ChartActivity2 className="size-3.5 shrink-0 transition-all group-hover:-translate-x-3 group-hover:opacity-0" />- </Link>+ {href && (+ <ChartActivity2 className="size-3.5 shrink-0 transition-all group-hover:-translate-x-3 group-hover:opacity-0" />+ )}+ </Wrapper>);}++const Wrapper = <T extends React.ElementType>({+ element: T,+ ...props+}: {+ element: T;+} & ComponentProps<T>) => <T {...props} />;diff --git a/apps/web/ui/customers/customer-table/customer-table.tsx b/apps/web/ui/customers/customer-table/customer-table.tsxnew file mode 100644index 0000000000..60adecb939--- /dev/null+++ b/apps/web/ui/customers/customer-table/customer-table.tsx@@ -0,0 +1,282 @@+"use client";++import useCustomersCount from "@/lib/swr/use-customers-count";+import useWorkspace from "@/lib/swr/use-workspace";+import { CustomerProps } from "@/lib/types";+import EditColumnsButton from "@/ui/analytics/events/edit-columns-button";+import { CustomerRowItem } from "@/ui/customers/customer-row-item";+import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";+import { SearchBoxPersisted } from "@/ui/shared/search-box";+import {+ AnimatedSizeContainer,+ Button,+ CopyText,+ Filter,+ LinkLogo,+ Popover,+ Table,+ usePagination,+ useRouterStuff,+ useTable,+} from "@dub/ui";+import { Dots, Users } from "@dub/ui/icons";+import { COUNTRIES, fetcher, formatDate, getPrettyUrl } from "@dub/utils";+import { Row } from "@tanstack/react-table";+import { Command } from "cmdk";+import { useParams, useRouter } from "next/navigation";+import { useState } from "react";+import useSWR from "swr";+import { customersColumns, useColumnVisibility } from "./use-column-visibility";+import { useCustomerFilters } from "./use-customer-filters";++export function CustomerTable() {+ const { id: workspaceId } = useWorkspace();+ const { queryParams, searchParams, getQueryString } = useRouterStuff();++ const sortBy = searchParams.get("sortBy") || "saleAmount";+ const sortOrder = searchParams.get("sortOrder") === "asc" ? "asc" : "desc";++ const {+ filters,+ activeFilters,+ onSelect,+ onRemove,+ onRemoveAll,+ isFiltered,+ } = useCustomerFilters({ sortBy, sortOrder });++ const { data: customersCount, error: countError } = useCustomersCount();++ const {+ data: customers,+ error,+ isLoading,+ } = useSWR<CustomerProps[]>(+ `/api/customers${getQueryString({+ workspaceId,+ includeExpandedFields: "true",+ })}`,+ fetcher,+ {+ keepPreviousData: true,+ },+ );++ console.log(customers);++ const { columnVisibility, setColumnVisibility } = useColumnVisibility();+ const { pagination, setPagination } = usePagination();++ const { table, ...tableProps } = useTable({+ data: customers || [],+ columns: [+ {+ id: "customer",+ header: "Customer",+ enableHiding: false,+ minSize: 250,+ cell: ({ row }) => {+ return <CustomerRowItem customer={row.original} />;+ },+ },+ {+ id: "createdAt",+ header: "Created date",+ accessorFn: (d) => formatDate(d.createdAt, { month: "short" }),+ },+ {+ id: "link",+ header: "Referral link",+ accessorKey: "link",+ meta: {+ filterParams: ({ getValue }) => ({+ linkId: getValue().id,+ }),+ },+ cell: ({ row }) =>+ row.original.link ? (+ <div className="flex items-center gap-3">+ <LinkLogo+ apexDomain={row.original.link.domain}+ className="size-4 shrink-0 sm:size-4"+ />+ <CopyText+ value={row.original.link.shortLink}+ successMessage="Copied link to clipboard!"+ className="truncate"+ >+ <span className="truncate" title={row.original.link.shortLink}>+ {getPrettyUrl(row.original.link.shortLink)}+ </span>+ </CopyText>+ </div>+ ) : (+ "-"+ ),+ size: 250,+ },+ {+ id: "externalId",+ header: "External ID",+ accessorKey: "externalId",+ cell: ({ row }) =>+ row.original.externalId ? (+ <CopyText+ value={row.original.externalId}+ successMessage="Copied external ID to clipboard!"+ className="truncate"+ >+ {row.original.externalId}+ </CopyText>+ ) : (+ "-"+ ),+ },+ {+ id: "country",+ header: "Country",+ minSize: 150,+ cell: ({ row }) => {+ const country = row.original.country;+ return (+ <div className="flex items-center gap-2">+ {country && (+ <img+ alt={`${country} flag`}+ src={`https://hatscripts.github.io/circle-flags/flags/${country.toLowerCase()}.svg`}+ className="size-4 shrink-0"+ />+ )}+ <span className="min-w-0 truncate">+ {(country ? COUNTRIES[country] : null) ?? "-"}+ </span>+ </div>+ );+ },+ },+ // Menu+ {+ id: "menu",+ enableHiding: false,+ minSize: 43,+ size: 43,+ maxSize: 43,+ header: () => <EditColumnsButton table={table} />,+ cell: ({ row }) => (+ <RowMenuButton row={row} workspaceId={workspaceId!} />+ ),+ },+ ].filter((c) => c.id === "menu" || customersColumns.all.includes(c.id)),+ onRowClick: (row) => {},+ pagination,+ onPaginationChange: setPagination,+ columnVisibility,+ onColumnVisibilityChange: setColumnVisibility,+ sortableColumns: ["createdAt"],+ sortBy,+ sortOrder,+ onSortChange: ({ sortBy, sortOrder }) =>+ queryParams({+ set: {+ ...(sortBy && { sortBy }),+ ...(sortOrder && { sortOrder }),+ },+ del: "page",+ scroll: false,+ }),+ thClassName: "border-l-0",+ tdClassName: "border-l-0",+ resourceName: (p) => `customer${p ? "s" : ""}`,+ rowCount: customersCount || 0,+ loading: isLoading,+ error: error || countError ? "Failed to load customers" : undefined,+ });++ return (+ <div className="flex flex-col gap-3">+ <div>+ <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">+ <Filter.Select+ className="w-full md:w-fit"+ filters={filters}+ activeFilters={activeFilters}+ onSelect={onSelect}+ onRemove={onRemove}+ />+ <SearchBoxPersisted+ placeholder="Search..."+ inputClassName="md:w-72"+ />+ </div>+ <AnimatedSizeContainer height>+ <div>+ {activeFilters.length > 0 && (+ <div className="pt-3">+ <Filter.List+ filters={filters}+ activeFilters={activeFilters}+ onRemove={onRemove}+ onRemoveAll={onRemoveAll}+ />+ </div>+ )}+ </div>+ </AnimatedSizeContainer>+ </div>+ {customers?.length !== 0 ? (+ <Table {...tableProps} table={table} />+ ) : (+ <AnimatedEmptyState+ title="No customers found"+ description={+ isFiltered+ ? "No customers found for the selected filters."+ : "No customers have been added to this program yet."+ }+ cardContent={() => (+ <>+ <Users className="size-4 text-neutral-700" />+ <div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />+ </>+ )}+ />+ )}+ </div>+ );+}++function RowMenuButton({+ row,+ workspaceId,+}: {+ row: Row<CustomerProps>;+ workspaceId: string;+}) {+ const router = useRouter();+ const { slug } = useParams();+ const [isOpen, setIsOpen] = useState(false);++ return (+ <>+ <Popover+ openPopover={isOpen}+ setOpenPopover={setIsOpen}+ content={+ <Command tabIndex={0} loop className="focus:outline-none">+ <Command.List className="flex w-screen flex-col gap-1 p-1.5 text-sm focus-visible:outline-none sm:w-auto sm:min-w-[130px]">+ {/* TODO: Add menu items */}+ </Command.List>+ </Command>+ }+ align="end"+ >+ <Button+ type="button"+ className="h-8 whitespace-nowrap px-2"+ variant="outline"+ icon={<Dots className="h-4 w-4 shrink-0" />}+ />+ </Popover>+ </>+ );+}diff --git a/apps/web/ui/customers/customer-table/use-column-visibility.ts b/apps/web/ui/customers/customer-table/use-column-visibility.tsnew file mode 100644index 0000000000..8a0ed59cc0--- /dev/null+++ b/apps/web/ui/customers/customer-table/use-column-visibility.ts@@ -0,0 +1,32 @@+import { useLocalStorage } from "@dub/ui";+import { VisibilityState } from "@tanstack/react-table";++export const customersColumns = {+ all: ["customer", "createdAt", "ltv", "link", "externalId", "country"],+ defaultVisible: [+ "customer",+ "createdAt",+ "ltv",+ "link",+ "externalId",+ "country",+ ],+};++export function useColumnVisibility() {+ const [columnVisibility, setColumnVisibility] =+ useLocalStorage<VisibilityState>(+ "customers-table-columns",+ Object.fromEntries(+ customersColumns.all.map((id) => [+ id,+ customersColumns.defaultVisible.includes(id),+ ]),+ ),+ );++ return {+ columnVisibility,+ setColumnVisibility,+ };+}diff --git a/apps/web/ui/customers/customer-table/use-customer-filters.tsx b/apps/web/ui/customers/customer-table/use-customer-filters.tsxnew file mode 100644index 0000000000..d7c0f982d0--- /dev/null+++ b/apps/web/ui/customers/customer-table/use-customer-filters.tsx@@ -0,0 +1,98 @@+import useWorkspace from "@/lib/swr/use-workspace";+import { useRouterStuff } from "@dub/ui";+import { FlagWavy } from "@dub/ui/icons";+import { COUNTRIES, nFormatter } from "@dub/utils";+import { useMemo } from "react";++export function useCustomerFilters(extraSearchParams: Record<string, string>) {+ const { searchParamsObj, queryParams } = useRouterStuff();+ const { id: workspaceId } = useWorkspace();++ // const { data: countriesCount } = useCustomersCount<+ // | {+ // country: string;+ // _count: number;+ // }[]+ // | undefined+ // >({+ // groupBy: "country",+ // });++ const countriesCount = [];++ const filters = useMemo(+ () => [+ {+ key: "country",+ icon: FlagWavy,+ label: "Country",+ getOptionIcon: (value) => (+ <img+ alt={value}+ src={`https://flag.vercel.app/m/${value}.svg`}+ className="h-2.5 w-4"+ />+ ),+ getOptionLabel: (value) => COUNTRIES[value],+ options:+ countriesCount+ ?.filter(({ country }) => COUNTRIES[country])+ .map(({ country, _count }) => ({+ value: country,+ label: COUNTRIES[country],+ right: nFormatter(_count, { full: true }),+ })) ?? [],+ },+ ],+ [countriesCount],+ );++ const activeFilters = useMemo(() => {+ const { country } = searchParamsObj;++ return [...(country ? [{ key: "country", value: country }] : [])];+ }, [searchParamsObj]);++ const onSelect = (key: string, value: any) =>+ queryParams({+ set: {+ [key]: value,+ },+ del: "page",+ });++ const onRemove = (key: string, value: any) =>+ queryParams({+ del: [key, "page"],+ });++ const onRemoveAll = () =>+ queryParams({+ del: ["country", "search"],+ });++ const searchQuery = useMemo(+ () =>+ new URLSearchParams({+ ...Object.fromEntries(+ activeFilters.map(({ key, value }) => [key, value]),+ ),+ ...(searchParamsObj.search && { search: searchParamsObj.search }),+ workspaceId: workspaceId || "",+ ...extraSearchParams,+ }).toString(),+ [activeFilters, workspaceId, extraSearchParams],+ );++ const isFiltered = activeFilters.length > 0 || searchParamsObj.search;++ return {+ filters,+ activeFilters,+ onSelect,+ onRemove,+ onRemoveAll,+ searchQuery,+ isFiltered,+ };+}