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 status tabs, search and a table view to the partner Programs page

Rafidb7db144a2cc
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/page-client.tsx
index 7e052bda6e..ce061ad10a 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/page-client.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/page-client.tsx
@@ -1,64 +1,183 @@
"use client";
import useProgramEnrollments from "@/lib/swr/use-program-enrollments";
+import useProgramEnrollmentsCount from "@/lib/swr/use-program-enrollments-count";
import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
import { ProgramCard, ProgramCardSkeleton } from "@/ui/partners/program-card";
+import { ProgramInviteCard } from "@/ui/partners/program-invite-card";
import { ProgramMarketplaceBanner } from "@/ui/program-marketplace/program-marketplace-banner";
+import { SearchBoxPersisted } from "@/ui/shared/search-box";
+import { formatTabBadgeCount, SheetTabs } from "@/ui/shared/sheet-tabs";
import { SimpleEmptyState } from "@/ui/shared/simple-empty-state";
-import { HexadecagonStar } from "@dub/ui/icons";
+import { ToggleGroup, useLocalStorage, useRouterStuff } from "@dub/ui";
+import { GridIcon, HexadecagonStar, TableRows2 } from "@dub/ui/icons";
import { useId } from "react";
+import { PROGRAM_TABS, ProgramTab } from "./program-tabs";
+import { ProgramsTable } from "./programs-table";
+
+type ProgramsView = "grid" | "table";
+
+const INACTIVE_TAB = PROGRAM_TABS.find(({ id }) => id === "inactive")!;
export function PartnersDashboardPageClient() {
- const { programEnrollments: allProgramEnrollments, isLoading } =
- useProgramEnrollments({
- includeRewardsDiscounts: true,
- });
-
- const programEnrollments = allProgramEnrollments?.filter(
- (programEnrollment) =>
- !["invited", "declined"].includes(programEnrollment.status),
+ const { searchParams, queryParams } = useRouterStuff();
+
+ const [view, setView] = useLocalStorage<ProgramsView>(
+ "partner-programs-view",
+ "grid",
+ );
+
+ const tab =
+ PROGRAM_TABS.find(({ id }) => id === searchParams.get("tab")) ??
+ PROGRAM_TABS[0];
+ const search = searchParams.get("search") || undefined;
+
+ const { count } = useProgramEnrollmentsCount({
+ status: tab.statuses.join(","),
+ search,
+ });
+
+ const { count: invitationsCount } = useProgramEnrollmentsCount({
+ status: "invited",
+ });
+
+ const { count: inactiveCount } = useProgramEnrollmentsCount({
+ status: INACTIVE_TAB.statuses.join(","),
+ });
+
+ // the Inactive tab shows only when the partner has an inactive program
+ const tabs = PROGRAM_TABS.filter(
+ ({ id }) => id !== "inactive" || inactiveCount || tab.id === "inactive",
);
return (
- <PageWidthWrapper className="pb-10">
+ <PageWidthWrapper className="flex flex-col gap-4 pb-10">
<ProgramMarketplaceBanner />
- {programEnrollments?.length == 0 ? (
- <SimpleEmptyState
- title="No programs"
- description="When you've joined or applied for a program it will appear here."
- graphic={
- <div className="border-border-subtle flex flex-col gap-4 rounded-xl border p-3 shadow-[0_4px_12px_#0001]">
- <HexadecagonStar className="text-content-default size-6" />
- <div className="flex flex-col gap-2">
- <div className="bg-bg-emphasis h-2.5 w-8 rounded" />
- <div className="bg-bg-emphasis h-2.5 w-16 rounded" />
- </div>
- <div className="bg-bg-subtle border-subtle grid w-40 max-w-full grid-cols-2 items-center gap-5 rounded-lg border p-2">
- <div className="flex flex-col gap-2">
- <div className="bg-bg-emphasis h-2.5 w-9 rounded" />
- <div className="bg-bg-inverted h-2.5 w-12 rounded" />
- </div>
- <EmptyStateChart />
- </div>
- </div>
+ <div className="flex items-center justify-between gap-3">
+ <SearchBoxPersisted
+ placeholder="Search programs"
+ inputClassName="md:w-[16rem]"
+ />
+ <ToggleGroup
+ className="bg-bg-muted h-10 shrink-0 gap-0 rounded-lg p-0"
+ optionClassName="h-full rounded-md px-2.5 py-0"
+ indicatorClassName="bg-bg-default -left-px -top-px h-[calc(100%+2px)] w-[calc(100%+2px)]"
+ options={[
+ {
+ value: "grid",
+ label: <GridIcon className="size-4" />,
+ },
+ {
+ value: "table",
+ label: <TableRows2 className="size-4" />,
+ },
+ ]}
+ selected={view}
+ selectAction={(option) => setView(option as ProgramsView)}
+ />
+ </div>
+
+ <div className="border-border-subtle overflow-clip rounded-xl border bg-neutral-100">
+ <SheetTabs
+ tabs={tabs.map(({ id, label, icon }) => ({
+ id,
+ label,
+ icon,
+ badge:
+ id === "invitations"
+ ? formatTabBadgeCount(invitationsCount)
+ : undefined,
+ }))}
+ currentTabId={tab.id}
+ setCurrentTabId={(id) =>
+ queryParams({
+ set: { tab: id },
+ del: ["page"],
+ })
}
/>
- ) : (
- <div className="@md/page:grid-cols-2 @3xl/page:grid-cols-3 grid gap-4">
- {isLoading
- ? Array.from({ length: 3 }).map((_, idx) => (
- <ProgramCardSkeleton key={idx} />
- ))
- : programEnrollments?.map((programEnrollment, idx) => (
- <ProgramCard key={idx} programEnrollment={programEnrollment} />
- ))}
+ <div className="border-border-subtle -mx-px -mb-px overflow-clip rounded-xl border bg-white">
+ {count === 0 ? (
+ <ProgramsEmptyState tab={tab} search={search} />
+ ) : view === "table" ? (
+ <ProgramsTable tab={tab} search={search} />
+ ) : (
+ <ProgramsGrid tab={tab} search={search} />
+ )}
</div>
- )}
+ </div>
</PageWidthWrapper>
);
}
+function ProgramsGrid({ tab, search }: { tab: ProgramTab; search?: string }) {
+ const { programEnrollments, isLoading } = useProgramEnrollments({
+ includeRewardsDiscounts: true,
+ status: tab.statuses.join(","),
+ search,
+ });
+
+ return (
+ <div className="@md/page:grid-cols-2 @3xl/page:grid-cols-3 grid gap-4 p-4">
+ {isLoading || !programEnrollments
+ ? Array.from({ length: 3 }).map((_, idx) => (
+ <ProgramCardSkeleton key={idx} />
+ ))
+ : programEnrollments.map((programEnrollment) =>
+ tab.id === "invitations" ? (
+ <ProgramInviteCard
+ key={programEnrollment.programId}
+ programEnrollment={programEnrollment}
+ />
+ ) : (
+ <ProgramCard
+ key={programEnrollment.programId}
+ programEnrollment={programEnrollment}
+ />
+ ),
+ )}
+ </div>
+ );
+}
+
+function ProgramsEmptyState({
+ tab,
+ search,
+}: {
+ tab: ProgramTab;
+ search?: string;
+}) {
+ return (
+ <div className="py-10">
+ <SimpleEmptyState
+ title={search ? "No programs found" : tab.emptyState.title}
+ description={
+ search
+ ? `No ${tab.resourceName}s match "${search}". Try a different search.`
+ : tab.emptyState.description
+ }
+ graphic={
+ <div className="border-border-subtle flex flex-col gap-4 rounded-xl border p-3 shadow-[0_4px_12px_#0001]">
+ <HexadecagonStar className="text-content-default size-6" />
+ <div className="flex flex-col gap-2">
+ <div className="bg-bg-emphasis h-2.5 w-8 rounded" />
+ <div className="bg-bg-emphasis h-2.5 w-16 rounded" />
+ </div>
+ <div className="bg-bg-subtle border-subtle grid w-40 max-w-full grid-cols-2 items-center gap-5 rounded-lg border p-2">
+ <div className="flex flex-col gap-2">
+ <div className="bg-bg-emphasis h-2.5 w-9 rounded" />
+ <div className="bg-bg-inverted h-2.5 w-12 rounded" />
+ </div>
+ <EmptyStateChart />
+ </div>
+ </div>
+ }
+ />
+ </div>
+ );
+}
+
function EmptyStateChart() {
const id = useId();
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/program-tabs.ts b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/program-tabs.ts
new file mode 100644
index 0000000000..5cc32ddd60
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/program-tabs.ts
@@ -0,0 +1,71 @@
+import {
+ CircleHalfDottedClock,
+ CircleXmark,
+ GridIcon,
+ UserCheck,
+} from "@dub/ui/icons";
+import { ProgramEnrollmentStatus } from "@prisma/client";
+
+export const PROGRAM_TABS = [
+ {
+ id: "active",
+ label: "Active",
+ icon: GridIcon,
+ statuses: ["approved"],
+ resourceName: "active program",
+ emptyState: {
+ title: "No programs",
+ description:
+ "When you've joined a program it will appear here. Find more programs in the marketplace.",
+ },
+ },
+ {
+ id: "invitations",
+ label: "Invitations",
+ icon: UserCheck,
+ statuses: ["invited"],
+ resourceName: "invitation",
+ emptyState: {
+ title: "No program invitations",
+ description:
+ "When a program sends you an invitation to join them, they will appear here.",
+ },
+ },
+ {
+ id: "applications",
+ label: "Applications",
+ icon: CircleHalfDottedClock,
+ statuses: ["pending", "rejected"],
+ resourceName: "application",
+ emptyState: {
+ title: "No applications",
+ description:
+ "When you've applied to a program, your application will appear here.",
+ },
+ },
+ {
+ id: "inactive",
+ label: "Inactive",
+ icon: CircleXmark,
+ statuses: ["banned", "deactivated", "archived"],
+ resourceName: "inactive program",
+ emptyState: {
+ title: "No inactive programs",
+ description:
+ "Programs that banned, deactivated or archived your partnership appear here.",
+ },
+ },
+] as const satisfies {
+ id: string;
+ label: string;
+ icon: typeof GridIcon;
+ statuses: ProgramEnrollmentStatus[];
+ resourceName: string;
+ emptyState: { title: string; description: string };
+}[];
+
+export type ProgramTab = (typeof PROGRAM_TABS)[number];
+
+export type ProgramTabId = ProgramTab["id"];
+
+export const PROGRAMS_TABLE_PAGE_SIZE = 10;
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/programs-table.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/programs-table.tsx
new file mode 100644
index 0000000000..80c64981d5
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/programs-table.tsx
@@ -0,0 +1,332 @@
+"use client";
+
+import { constructPartnerLink } from "@/lib/partners/construct-partner-link";
+import { usePartnerProfileEarningsTimeseries } from "@/lib/swr/use-partner-profile-earnings";
+import useProgramEnrollments from "@/lib/swr/use-program-enrollments";
+import useProgramEnrollmentsCount from "@/lib/swr/use-program-enrollments-count";
+import { ProgramEnrollmentProps } from "@/lib/types";
+import { PartnerStatusBadges } from "@/ui/partners/partner-status-badges";
+import { ProgramInviteActions } from "@/ui/partners/program-invite-actions";
+import { ProgramRewardDescription } from "@/ui/partners/program-reward-description";
+import {
+ BlurImage,
+ MiniAreaChart,
+ StatusBadge,
+ Table,
+ Tooltip,
+ useCopyToClipboard,
+ usePagination,
+ useRouterStuff,
+ useTable,
+} from "@dub/ui";
+import { ChartLine, Check, Copy, Link4 } from "@dub/ui/icons";
+import {
+ cn,
+ currencyFormatter,
+ formatDate,
+ getPrettyUrl,
+ OG_AVATAR_URL,
+} from "@dub/utils";
+import { ColumnDef } from "@tanstack/react-table";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useMemo } from "react";
+import { PROGRAMS_TABLE_PAGE_SIZE, ProgramTab } from "./program-tabs";
+
+type ProgramColumn = ColumnDef<ProgramEnrollmentProps>;
+
+export function ProgramsTable({
+ tab,
+ search,
+}: {
+ tab: ProgramTab;
+ search?: string;
+}) {
+ const router = useRouter();
+ const { searchParams, queryParams } = useRouterStuff();
+ const { pagination, setPagination } = usePagination(PROGRAMS_TABLE_PAGE_SIZE);
+
+ const sortBy = searchParams.get("sortBy") === "name" ? "name" : undefined;
+ const sortOrder = searchParams.get("sortOrder") === "asc" ? "asc" : "desc";
+
+ const status = tab.statuses.join(",");
+
+ const { programEnrollments, isLoading, error } = useProgramEnrollments({
+ includeRewardsDiscounts: tab.id === "invitations",
+ status,
+ search,
+ ...(sortBy && { sortBy }),
+ sortOrder,
+ page: pagination.pageIndex,
+ pageSize: pagination.pageSize,
+ });
+
+ const { count, error: countError } = useProgramEnrollmentsCount({
+ status,
+ search,
+ });
+
+ const columns = useMemo(() => getColumns(tab), [tab]);
+
+ const { table, ...tableProps } = useTable({
+ data: programEnrollments || [],
+ columns,
+ onRowClick: (row, e) => {
+ const url = getProgramUrl(tab, row.original);
+
+ if (e.metaKey || e.ctrlKey) window.open(url, "_blank");
+ else router.push(url);
+ },
+ onRowAuxClick: (row) => window.open(getProgramUrl(tab, row.original)),
+ pagination,
+ onPaginationChange: setPagination,
+ sortableColumns: ["name", "totalCommissions"],
+ sortBy: sortBy ?? "totalCommissions",
+ sortOrder,
+ onSortChange: ({ sortBy, sortOrder }) =>
+ queryParams({
+ set: {
+ ...(sortBy && { sortBy }),
+ ...(sortOrder && { sortOrder }),
+ },
+ del: "page",
+ }),
+ containerClassName: "border-none",
+ thClassName: "border-l-0",
+ tdClassName: "border-l-0",
+ resourceName: (plural) => `${tab.resourceName}${plural ? "s" : ""}`,
+ rowCount: count ?? 0,
+ loading: isLoading,
+ error: error || countError ? "Failed to load programs" : undefined,
+ });
+
+ return <Table {...tableProps} table={table} />;
+}
+
+function getProgramUrl(tab: ProgramTab, { program }: ProgramEnrollmentProps) {
+ return tab.id === "invitations"
+ ? `/programs/${program.slug}/invite`
+ : `/programs/${program.slug}`;
+}
+
+function getColumns(tab: ProgramTab): ProgramColumn[] {
+ const programColumn: ProgramColumn = {
+ id: "name",
+ header: "Program",
+ size: 200,
+ minSize: 160,
+ cell: ({ row }) => <ProgramName program={row.original.program} />,
+ };
+
+ const earningsColumn: ProgramColumn = {
+ id: "totalCommissions",
+ header: "Earnings",
+ size: 120,
+ cell: ({ row }) => currencyFormatter(row.original.totalCommissions),
+ };
+
+ switch (tab.id) {
+ case "active":
+ return [
+ programColumn,
+ {
+ id: "link",
+ header: "Links",
+ minSize: 200,
+ cell: ({ row }) => (
+ <ProgramLinkChip programEnrollment={row.original} />
+ ),
+ },
+ {
+ id: "activity",
+ header: "Activity",
+ size: 180,
+ cell: ({ row }) => (
+ <ProgramActivity programEnrollment={row.original} />
+ ),
+ },
+ earningsColumn,
+ ];
+ case "invitations":
+ return [
+ programColumn,
+ {
+ id: "createdAt",
+ header: "Invited date",
+ size: 140,
+ cell: ({ row }) =>
+ formatDate(row.original.createdAt, { month: "short" }),
+ },
+ {
+ id: "rewards",
+ header: "Rewards",
+ minSize: 160,
+ cell: ({ row }) => (
+ <span className="truncate">
+ <ProgramRewardDescription
+ reward={row.original.rewards?.[0]}
+ amountClassName="font-normal"
+ periodClassName="font-normal"
+ />
+ </span>
+ ),
+ },
+ {
+ id: "actions",
+ header: "",
+ size: 210,
+ minSize: 210,
+ cell: ({ row }) => (
+ <ProgramInviteActions
+ programEnrollment={row.original}
+ className="ml-auto flex w-fit"
+ buttonClassName="h-7 w-auto whitespace-nowrap px-2.5 text-xs"
+ />
+ ),
+ },
+ ];
+ case "applications":
+ return [
+ programColumn,
+ {
+ id: "createdAt",
+ header: "Application date",
+ size: 160,
+ cell: ({ row }) =>
+ formatDate(row.original.createdAt, { month: "short" }),
+ },
+ {
+ id: "status",
+ header: "Status",
+ size: 160,
+ cell: ({ row }) => (
+ <EnrollmentStatusBadge status={row.original.status} />
+ ),
+ },
+ ];
+ case "inactive":
+ return [
+ programColumn,
+ {
+ id: "status",
+ header: "Status",
+ size: 160,
+ cell: ({ row }) => (
+ <EnrollmentStatusBadge status={row.original.status} />
+ ),
+ },
+ earningsColumn,
+ ];
+ }
+}
+
+function ProgramName({
+ program,
+}: {
+ program: ProgramEnrollmentProps["program"];
+}) {
+ return (
+ <div className="flex min-w-0 items-center gap-2">
+ <BlurImage
+ width={40}
+ height={40}
+ src={program.logo || `${OG_AVATAR_URL}${program.name}`}
+ alt={program.name}
+ className="size-5 shrink-0 rounded-full border border-black/10"
+ />
+ <span className="truncate font-medium text-neutral-800">
+ {program.name}
+ </span>
+ </div>
+ );
+}
+
+function EnrollmentStatusBadge({
+ status,
+}: {
+ status: ProgramEnrollmentProps["status"];
+}) {
+ const badge = PartnerStatusBadges[status];
+
+ return (
+ <StatusBadge variant={badge.variant} icon={null}>
+ {badge.label}
+ </StatusBadge>
+ );
+}
+
+// the partner's default link: click to copy, or open its analytics
+function ProgramLinkChip({
+ programEnrollment,
+}: {
+ programEnrollment: ProgramEnrollmentProps;
+}) {
+ const { program, group } = programEnrollment;
+ const link = programEnrollment.links?.[0];
+ const [copied, copyToClipboard] = useCopyToClipboard();
+
+ if (!link) {
+ return <span className="text-neutral-400">No link</span>;
+ }
+
+ const partnerLink = constructPartnerLink({ group, link });
+
+ return (
+ <div className="group/chip flex w-fit max-w-full items-center gap-1 rounded-md px-1.5 py-0.5 transition-colors hover:bg-neutral-100">
+ <button
+ type="button"
+ className="flex min-w-0 items-center gap-1.5 text-neutral-700"
+ onClick={(e) => {
+ e.stopPropagation();
+ copyToClipboard(partnerLink);
+ }}
+ >
+ <Link4 className="size-3.5 shrink-0" />
+ <span className="truncate">{getPrettyUrl(partnerLink)}</span>
+ {copied ? (
+ <Check className="size-3.5 shrink-0" />
+ ) : (
+ <Copy className="size-3.5 shrink-0 opacity-0 transition-opacity group-hover/chip:opacity-100" />
+ )}
+ </button>
+ <Tooltip content="View analytics">
+ <Link
+ href={`/programs/${program.slug}/analytics?linkId=${link.id}`}
+ onClick={(e) => e.stopPropagation()}
+ className={cn(
+ "shrink-0 rounded p-0.5 text-neutral-500 opacity-0 transition-opacity hover:text-neutral-800 group-hover/chip:opacity-100",
+ )}
+ >
+ <ChartLine className="size-3.5" />
+ </Link>
+ </Tooltip>
+ </div>
+ );
+}
+
+function ProgramActivity({
+ programEnrollment,
+}: {
+ programEnrollment: ProgramEnrollmentProps;
+}) {
+ // one request for every program on the page (SWR dedupes it across rows)
+ const { data: timeseries } = usePartnerProfileEarningsTimeseries({
+ groupBy: "programId",
+ interval: "1y",
+ });
+
+ const data = useMemo(
+ () =>
+ timeseries?.map(({ start, data }) => ({
+ date: new Date(start),
+ value: data?.[programEnrollment.programId] ?? 0,
+ })),
+ [timeseries, programEnrollment.programId],
+ );
+
+ return (
+ <div className="h-6 w-36">
+ {data && <MiniAreaChart data={data} padding={{ top: 2, bottom: 2 }} />}
+ </div>
+ );
+}