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.

improve design

Steven Tey64dc8a9846e8
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/user-info.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/user-info.tsx
index 9bb9830b8c..7e08e8cc5b 100644
--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/user-info.tsx
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/user-info.tsx
@@ -1,7 +1,25 @@
"use client";
+
import { PartnerStatusBadges } from "@/ui/partners/partner-status-badges";
-import { Badge, Copy, StatusBadge, Tick, useCopyToClipboard } from "@dub/ui";
-import { capitalize, currencyFormatter, nFormatter } from "@dub/utils";
+import {
+ Badge,
+ Copy,
+ CopyButton,
+ StatusBadge,
+ Tick,
+ useCopyToClipboard,
+} from "@dub/ui";
+import { ArrowUpRight2 } from "@dub/ui/icons";
+import {
+ APP_DOMAIN,
+ capitalize,
+ currencyFormatter,
+ formatDate,
+ getPrettyUrl,
+ isSafeLinkHref,
+ isWorkspaceBillingTrialActive,
+ nFormatter,
+} from "@dub/utils";
import { toast } from "sonner";
export interface UserInfoProps {
@@ -11,10 +29,16 @@ export interface UserInfoProps {
name: string;
slug: string;
plan: string;
- clicks: number;
+ planPeriod: string | null;
+ trialEndsAt: string | Date | null;
+ events: number;
links: number;
- totalClicks: number;
- totalLinks: number;
+ statsInterval: "30d" | "all";
+ program: {
+ url: string;
+ partners: number;
+ commissions: number;
+ } | null;
}[];
programs: {
id: string;
@@ -33,24 +57,17 @@ export interface UserInfoProps {
};
}
-const workspaceItems = [
- { id: "clicks", label: "Clicks" },
- { id: "links", label: "Links" },
- { id: "totalClicks", label: "Total Clicks" },
- { id: "totalLinks", label: "Total Links" },
-];
-
const programItems = [
- { id: "totalClicks", label: "Total Clicks" },
- { id: "totalLeads", label: "Total Leads" },
- { id: "totalConversions", label: "Total Conversions" },
- { id: "totalSaleAmount", label: "Total Sales", isCurrency: true },
- { id: "totalCommissions", label: "Total Commissions", isCurrency: true },
-];
+ { id: "totalClicks", label: "Clicks" },
+ { id: "totalLeads", label: "Leads" },
+ { id: "totalConversions", label: "Conversions" },
+ { id: "totalSaleAmount", label: "Sales", isCurrency: true },
+ { id: "totalCommissions", label: "Commissions", isCurrency: true },
+] as const;
export default function UserInfo({ data }: { data: UserInfoProps }) {
return (
- <div className="grid gap-4">
+ <div className="grid gap-5">
<LoginLinkCopyButton text={data.email} url={data.email} />
<LoginLinkCopyButton
text="app.dub.co login link"
@@ -62,104 +79,240 @@ export default function UserInfo({ data }: { data: UserInfoProps }) {
/>
{data.workspaces.length > 0 && (
- <div>
- <h3 className="mb-2 text-sm font-semibold text-neutral-900">
+ <section>
+ <h3 className="mb-2.5 text-sm font-semibold text-neutral-900">
Workspaces
</h3>
- <div className="grid grid-cols-2 gap-4">
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
{data.workspaces.map((workspace) => (
- <div
- key={workspace.slug}
- className="flex flex-col space-y-2 rounded-lg border border-neutral-200 p-2"
- >
- <div className="flex items-center space-x-2">
- <p className="font-semibold">{workspace.name}</p>
- <Badge className="lowercase">{workspace.slug}</Badge>
- </div>
- <div className="flex justify-between text-sm">
- <span className="font-medium text-neutral-700">ID</span>
- <span className="text-neutral-500">{workspace.id}</span>
- </div>
- <div className="flex justify-between text-sm">
- <span className="font-medium text-neutral-700">Plan</span>
- <span className="text-neutral-500">
- {capitalize(workspace.plan)}
- </span>
- </div>
- {workspaceItems.map((item) => (
- <div key={item.id} className="flex justify-between text-sm">
- <span className="font-medium text-neutral-700">
- {item.label}
- </span>
- <span className="text-neutral-500">
- {nFormatter(workspace[item.id], { full: true })}
- </span>
- </div>
- ))}
- </div>
+ <WorkspaceCard key={workspace.id} workspace={workspace} />
))}
</div>
- </div>
- )}
-
- {data.workspaces.length > 0 && data.programs.length > 0 && (
- <div className="my-2 border-b border-neutral-200" />
+ </section>
)}
{data.programs.length > 0 && (
- <div>
- <h3 className="mb-2 text-sm font-semibold text-neutral-900">
- Programs
+ <section>
+ <h3 className="mb-2.5 text-sm font-semibold text-neutral-900">
+ Partner programs
</h3>
- <div className="grid grid-cols-2 gap-4">
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
{data.programs.map((program) => (
- <div
- key={program.id}
- className="flex flex-col space-y-2 rounded-lg border border-neutral-200 p-2"
- >
- <div className="flex items-center space-x-2">
- <p className="font-semibold">{program.name}</p>
- <Badge className="lowercase">{program.slug}</Badge>
- </div>
- <div className="flex justify-between text-sm">
- <span className="font-medium text-neutral-700">ID</span>
- <span className="text-neutral-500">{program.id}</span>
- </div>
- <div className="flex justify-between text-sm">
- <span className="font-medium text-neutral-700">Status</span>
- <StatusBadge
- variant={PartnerStatusBadges[program.status].variant}
- >
- {PartnerStatusBadges[program.status].label}
- </StatusBadge>
- </div>
- {programItems.map((item) => (
- <div key={item.id} className="flex justify-between text-sm">
- <span className="font-medium text-neutral-700">
- {item.label}
- </span>
- <span className="text-neutral-500">
- {item.isCurrency
- ? currencyFormatter(program[item.id])
- : nFormatter(program[item.id], { full: true })}
- </span>
- </div>
- ))}
- </div>
+ <ProgramCard key={program.id} program={program} />
))}
</div>
+ </section>
+ )}
+ </div>
+ );
+}
+
+function WorkspaceCard({
+ workspace,
+}: {
+ workspace: UserInfoProps["workspaces"][number];
+}) {
+ const trialActive = isWorkspaceBillingTrialActive(workspace.trialEndsAt);
+ const planLabel = workspace.planPeriod
+ ? `${capitalize(workspace.plan)} (${workspace.planPeriod})`
+ : capitalize(workspace.plan);
+ const statsLabel =
+ workspace.statsInterval === "30d" ? "Last 30 days" : "All-time";
+ const programUrl = workspace.program
+ ? getPrettyUrl(workspace.program.url)
+ : null;
+
+ return (
+ <div className="flex min-w-0 flex-col overflow-hidden rounded-xl border border-neutral-200 bg-white">
+ <div className="flex items-start justify-between gap-2 px-3.5 py-3">
+ <div className="min-w-0">
+ <a
+ href={`${APP_DOMAIN}/${workspace.slug}`}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="group flex items-center gap-1 font-semibold text-neutral-900"
+ >
+ <span className="truncate">{workspace.name}</span>
+ <ArrowUpRight2 className="size-3.5 shrink-0 text-neutral-400 transition-colors group-hover:text-neutral-700" />
+ </a>
+ <p className="mt-0.5 truncate text-xs text-neutral-500">
+ {workspace.slug}
+ </p>
+ </div>
+ <div className="flex shrink-0 flex-col items-end gap-1">
+ <Badge variant="gray">{planLabel}</Badge>
+ {trialActive && workspace.trialEndsAt && (
+ <Badge variant="amber">
+ Trial ends {formatDate(workspace.trialEndsAt, { month: "short" })}
+ </Badge>
+ )}
+ </div>
+ </div>
+
+ <div className="grid grid-cols-2 gap-px border-y border-neutral-100 bg-neutral-100">
+ <StatTile
+ label="Events"
+ value={nFormatter(workspace.events, { full: true })}
+ hint={statsLabel}
+ />
+ <StatTile
+ label="Links"
+ value={nFormatter(workspace.links, { full: true })}
+ hint={statsLabel}
+ />
+ </div>
+
+ <MetaRow label="ID" value={workspace.id} copyValue={workspace.id} mono />
+
+ {workspace.program && (
+ <div className="space-y-0.5 border-t border-neutral-100 bg-neutral-50/80 py-1">
+ <MetaRow
+ label="Program URL"
+ value={programUrl || "—"}
+ href={
+ workspace.program.url && isSafeLinkHref(workspace.program.url)
+ ? workspace.program.url
+ : undefined
+ }
+ />
+ <MetaRow
+ label="Partners"
+ value={nFormatter(workspace.program.partners, { full: true })}
+ />
+ <MetaRow
+ label="Commissions (30d)"
+ value={currencyFormatter(workspace.program.commissions)}
+ />
</div>
)}
</div>
);
}
+function ProgramCard({
+ program,
+}: {
+ program: UserInfoProps["programs"][number];
+}) {
+ const status = PartnerStatusBadges[program.status];
+
+ return (
+ <div className="flex min-w-0 flex-col overflow-hidden rounded-xl border border-neutral-200 bg-white">
+ <div className="flex items-start justify-between gap-2 px-3.5 py-3">
+ <div className="min-w-0">
+ <p className="truncate font-semibold text-neutral-900">
+ {program.name}
+ </p>
+ <p className="mt-0.5 truncate text-xs text-neutral-500">
+ {program.slug}
+ </p>
+ </div>
+ {status && (
+ <StatusBadge variant={status.variant}>{status.label}</StatusBadge>
+ )}
+ </div>
+
+ <div className="grid grid-cols-2 gap-px border-y border-neutral-100 bg-neutral-100">
+ {programItems.slice(0, 2).map((item) => (
+ <StatTile
+ key={item.id}
+ label={item.label}
+ value={
+ "isCurrency" in item && item.isCurrency
+ ? currencyFormatter(program[item.id])
+ : nFormatter(program[item.id], { full: true })
+ }
+ />
+ ))}
+ </div>
+
+ <div className="py-1">
+ <MetaRow label="ID" value={program.id} copyValue={program.id} mono />
+ {programItems.slice(2).map((item) => (
+ <MetaRow
+ key={item.id}
+ label={item.label}
+ value={
+ "isCurrency" in item && item.isCurrency
+ ? currencyFormatter(program[item.id])
+ : nFormatter(program[item.id], { full: true })
+ }
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function StatTile({
+ label,
+ value,
+ hint,
+}: {
+ label: string;
+ value: string;
+ hint?: string;
+}) {
+ return (
+ <div className="bg-white px-3.5 py-2.5">
+ <p className="text-[11px] font-medium uppercase tracking-wide text-neutral-400">
+ {label}
+ </p>
+ <p className="mt-0.5 text-lg font-semibold tabular-nums tracking-tight text-neutral-900">
+ {value}
+ </p>
+ {hint && <p className="text-[11px] text-neutral-400">{hint}</p>}
+ </div>
+ );
+}
+
+function MetaRow({
+ label,
+ value,
+ copyValue,
+ href,
+ mono,
+}: {
+ label: string;
+ value: string;
+ copyValue?: string;
+ href?: string;
+ mono?: boolean;
+}) {
+ return (
+ <div className="flex items-center justify-between gap-2 px-3.5 py-1.5">
+ <span className="shrink-0 text-xs font-medium text-neutral-500">
+ {label}
+ </span>
+ <span className="flex min-w-0 items-center justify-end gap-0.5">
+ {href ? (
+ <a
+ href={href}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="truncate text-xs text-neutral-700 underline decoration-neutral-300 underline-offset-2 hover:text-neutral-900"
+ >
+ {value}
+ </a>
+ ) : (
+ <span
+ className={`truncate text-xs text-neutral-700 ${mono ? "font-mono" : ""}`}
+ >
+ {value}
+ </span>
+ )}
+ {copyValue && <CopyButton value={copyValue} className="shrink-0" />}
+ </span>
+ </div>
+ );
+}
+
const LoginLinkCopyButton = ({ text, url }: { text: string; url: string }) => {
const [copied, copyToClipboard] = useCopyToClipboard();
return (
- <div className="flex w-full items-center space-x-3">
- <div className="w-full rounded-md border border-neutral-300 px-4 py-2 text-sm text-neutral-900">
+ <div className="flex w-full items-center space-x-2">
+ <div className="w-full rounded-lg border border-neutral-200 bg-neutral-50 px-3.5 py-2 text-sm text-neutral-900">
{text}
</div>
<button
@@ -169,13 +322,9 @@ const LoginLinkCopyButton = ({ text, url }: { text: string; url: string }) => {
success: "Copied to clipboard",
})
}
- className="rounded-md border border-neutral-300 p-2"
+ className="rounded-lg border border-neutral-200 p-2 text-neutral-500 transition-colors hover:bg-neutral-50 hover:text-neutral-800"
>
- {copied ? (
- <Tick className="h-5 w-5 text-neutral-500" />
- ) : (
- <Copy className="h-5 w-5 text-neutral-500" />
- )}
+ {copied ? <Tick className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
</button>
</div>
);
diff --git a/apps/web/app/(ee)/api/admin/impersonate/route.ts b/apps/web/app/(ee)/api/admin/impersonate/route.ts
index b61065cbcb..28a1ca2655 100644
--- a/apps/web/app/(ee)/api/admin/impersonate/route.ts
+++ b/apps/web/app/(ee)/api/admin/impersonate/route.ts
@@ -1,6 +1,9 @@
+import { getAnalytics } from "@/lib/analytics/get-analytics";
+import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";
import { normalizeDomainInput } from "@/lib/api/domains/normalize-domain-input";
import { hashToken, withAdmin } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
+import { getWorkspaceUsage } from "@/lib/tinybird/get-workspace-usage";
import { emailSchema } from "@/lib/zod/schemas/auth";
import {
APP_DOMAIN,
@@ -23,10 +26,19 @@ const userSelect = {
name: true,
slug: true,
plan: true,
- usage: true,
- linksUsage: true,
+ planPeriod: true,
+ trialEndsAt: true,
+ defaultProgramId: true,
+ partnersUsage: true,
totalClicks: true,
totalLinks: true,
+ programs: {
+ select: {
+ id: true,
+ slug: true,
+ url: true,
+ },
+ },
},
},
},
@@ -172,13 +184,9 @@ export const POST = withAdmin(async ({ req }) => {
const data = {
email: response.email,
- workspaces: response.projects.map(({ project }) => ({
- ...project,
- clicks: project.usage,
- links: project.linksUsage,
- totalClicks: project.totalClicks,
- totalLinks: project.totalLinks,
- })),
+ workspaces: await serializeWorkspaces(
+ response.projects.map(({ project }) => project),
+ ),
programs:
response.partners.length > 0
? response.partners[0].partner.programs.map(({ program, ...rest }) => ({
@@ -192,6 +200,126 @@ export const POST = withAdmin(async ({ req }) => {
return NextResponse.json(data);
});
+type ImpersonateProject = Prisma.UserGetPayload<{
+ select: typeof userSelect;
+}>["projects"][number]["project"];
+
+async function serializeWorkspaces(projects: ImpersonateProject[]) {
+ const useLast30DaysStats = projects.length <= 2;
+ const programIds = projects
+ .map((project) => project.defaultProgramId)
+ .filter((id): id is string => Boolean(id));
+
+ const { startDate } = getStartEndDates({ interval: "30d" });
+
+ const [statsByWorkspaceId, commissionsByProgramId] = await Promise.all([
+ useLast30DaysStats
+ ? getLast30DayWorkspaceStats(projects)
+ : Promise.resolve(new Map<string, { clicks: number; links: number }>()),
+ programIds.length > 0
+ ? prisma.commission
+ .groupBy({
+ by: ["programId"],
+ where: {
+ programId: {
+ in: programIds,
+ },
+ status: {
+ in: ["pending", "processed", "paid"],
+ },
+ createdAt: {
+ gte: startDate,
+ },
+ },
+ _sum: {
+ earnings: true,
+ },
+ })
+ .then(
+ (rows) =>
+ new Map(
+ rows.map((row) => [row.programId, row._sum.earnings ?? 0]),
+ ),
+ )
+ : Promise.resolve(new Map<string, number>()),
+ ]);
+
+ return projects.map((project) => {
+ const stats = statsByWorkspaceId.get(project.id);
+ const program = project.defaultProgramId
+ ? project.programs.find((item) => item.id === project.defaultProgramId) ??
+ project.programs[0]
+ : null;
+
+ return {
+ id: project.id,
+ name: project.name,
+ slug: project.slug,
+ plan: project.plan,
+ planPeriod: project.planPeriod,
+ trialEndsAt: project.trialEndsAt,
+ events: stats?.clicks ?? project.totalClicks,
+ links: stats?.links ?? project.totalLinks,
+ statsInterval: useLast30DaysStats ? ("30d" as const) : ("all" as const),
+ program: program
+ ? {
+ url: program.url ?? `${PARTNERS_DOMAIN}/${program.slug}`,
+ partners: project.partnersUsage,
+ commissions: commissionsByProgramId.get(program.id) ?? 0,
+ }
+ : null,
+ };
+ });
+}
+
+async function getLast30DayWorkspaceStats(projects: ImpersonateProject[]) {
+ const entries = await Promise.all(
+ projects.map(async (project) => {
+ try {
+ const [analytics, linksUsage] = await Promise.all([
+ getAnalytics({
+ workspaceId: project.id,
+ event: "clicks",
+ groupBy: "count",
+ interval: "30d",
+ }),
+ getWorkspaceUsage({
+ workspaceId: project.id,
+ resource: "links",
+ interval: "30d",
+ }),
+ ]);
+
+ const clicks =
+ analytics &&
+ typeof analytics === "object" &&
+ "clicks" in analytics &&
+ typeof analytics.clicks === "number"
+ ? analytics.clicks
+ : project.totalClicks;
+
+ const links = linksUsage.reduce(
+ (acc, curr) => acc + (curr.value ?? 0),
+ 0,
+ );
+
+ return [project.id, { clicks, links }] as const;
+ } catch (error) {
+ console.error(
+ `Failed to fetch 30d stats for workspace ${project.slug}:`,
+ error,
+ );
+ return [
+ project.id,
+ { clicks: project.totalClicks, links: project.totalLinks },
+ ] as const;
+ }
+ }),
+ );
+
+ return new Map(entries);
+}
+
async function findUser(identifier: ImpersonateIdentifier) {
if (identifier.type === "email") {
const userEmails = [identifier.email];