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.

wip new UI for embed

Kiran Kf2a80b1af560
diff --git a/apps/web/app/api/analytics/client/route.ts b/apps/web/app/api/analytics/client/route.ts
index 357d4f4a86..59f01701ff 100644
--- a/apps/web/app/api/analytics/client/route.ts
+++ b/apps/web/app/api/analytics/client/route.ts
@@ -1,17 +1,50 @@
import { getAnalytics } from "@/lib/analytics/get-analytics";
+import { calculateEarnings } from "@/lib/api/sales/commission";
import { withAuth } from "@/lib/referrals/auth";
import { analyticsQuerySchema } from "@/lib/zod/schemas/analytics";
import { NextResponse } from "next/server";
// GET /api/analytics/client - get analytics for the current link
-export const GET = withAuth(async ({ workspace, link, searchParams }) => {
- const parsedParams = analyticsQuerySchema.parse(searchParams);
+export const GET = withAuth(async ({ link, searchParams, program }) => {
+ const parsedParams = analyticsQuerySchema
+ .pick({
+ event: true,
+ start: true,
+ end: true,
+ interval: true,
+ groupBy: true,
+ timezone: true,
+ })
+ .parse(searchParams);
const response = await getAnalytics({
...parsedParams,
- workspaceId: workspace.id,
linkId: link.id,
});
- return NextResponse.json(response);
+ let data;
+
+ if (response instanceof Array) {
+ data = response.map((item) => {
+ return {
+ ...item,
+ earnings: calculateEarnings({
+ program,
+ sales: item.sales ?? 0,
+ saleAmount: item.saleAmount ?? 0,
+ }),
+ };
+ });
+ } else {
+ data = {
+ ...response,
+ earnings: calculateEarnings({
+ program,
+ sales: response.sales,
+ saleAmount: response.saleAmount,
+ }),
+ };
+ }
+
+ return NextResponse.json(data);
});
diff --git a/apps/web/app/api/referrals/link/route.ts b/apps/web/app/api/referrals/link/route.ts
new file mode 100644
index 0000000000..3a3ae10206
--- /dev/null
+++ b/apps/web/app/api/referrals/link/route.ts
@@ -0,0 +1,7 @@
+import { withAuth } from "@/lib/referrals/auth";
+import { NextResponse } from "next/server";
+
+// GET /api/referrals/link - get the link for the given affiliate
+export const GET = withAuth(async ({ link }) => {
+ return NextResponse.json(link);
+});
diff --git a/apps/web/app/api/referrals/program/route.ts b/apps/web/app/api/referrals/program/route.ts
new file mode 100644
index 0000000000..a18da727ac
--- /dev/null
+++ b/apps/web/app/api/referrals/program/route.ts
@@ -0,0 +1,7 @@
+import { withAuth } from "@/lib/referrals/auth";
+import { NextResponse } from "next/server";
+
+// GET /api/referrals/program - get the program for the given affiliate
+export const GET = withAuth(async ({ program }) => {
+ return NextResponse.json(program);
+});
diff --git a/apps/web/app/api/referrals/tokens/route.ts b/apps/web/app/api/referrals/tokens/route.ts
index 0a2412b24d..4174a1c621 100644
--- a/apps/web/app/api/referrals/tokens/route.ts
+++ b/apps/web/app/api/referrals/tokens/route.ts
@@ -1,6 +1,6 @@
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
-import { createReferralPublicToken } from "@/lib/referrals/token";
+import { createReferralPublicToken } from "@/lib/referrals/create-referral-token";
import {
createReferralTokenSchema,
referralTokenSchema,
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/referrals-token/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/referrals-token/route.ts
index 17561d9086..90e7f27ee7 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/referrals-token/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/referrals-token/route.ts
@@ -1,6 +1,6 @@
import { DubApiError } from "@/lib/api/errors";
import { withWorkspace } from "@/lib/auth";
-import { createReferralPublicToken } from "@/lib/referrals/token";
+import { createReferralPublicToken } from "@/lib/referrals/create-referral-token";
import { referralTokenSchema } from "@/lib/zod/schemas/referrals";
import { NextResponse } from "next/server";
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/generate-button.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/generate-button.tsx
deleted file mode 100644
index cc3c746ead..0000000000
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/generate-button.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-"use client";
-
-import { generateReferralLink } from "@/lib/actions/generate-referral-link";
-import useWorkspace from "@/lib/swr/use-workspace";
-import { Button } from "@dub/ui";
-import { useAction } from "next-safe-action/hooks";
-import { useRouter } from "next/navigation";
-import { toast } from "sonner";
-
-export function GenerateButton() {
- const router = useRouter();
- const { id: workspaceId } = useWorkspace();
-
- const { executeAsync, isExecuting, hasSucceeded } = useAction(
- generateReferralLink,
- {
- onSuccess: () => {
- router.refresh();
- toast.success("Referral link generated.");
- },
- onError: ({ error }) => {
- toast.error(error.serverError?.serverError);
- },
- },
- );
-
- return (
- <Button
- text="Activate Referral Link"
- className="h-9 w-auto rounded-lg"
- onClick={() => executeAsync({ workspaceId: workspaceId! })}
- loading={isExecuting || hasSucceeded}
- />
- );
-}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/hero-background.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/hero-background.tsx
deleted file mode 100644
index 8f33439724..0000000000
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/hero-background.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import { Logo } from "@dub/ui";
-import Image from "next/image";
-
-const heroGradient =
- "conic-gradient(from 45deg at 65% 70%, #855AFC 0deg, #3A8BFD 72deg, #00FFF9 144deg, #5CFF80 197.89deg, #EAB308 260.96deg, #FF0000 360deg)";
-
-export function HeroBackground() {
- return (
- <div className="pointer-events-none absolute inset-0 [mask-image:radial-gradient(100%_100%_at_top_right,black,transparent)] max-[350px]:opacity-50 sm:[mask-image:linear-gradient(to_right,transparent_50%,black_70%)]">
- <div className="absolute -right-[60px] top-[40px] isolate w-[600px] -translate-y-1/2 overflow-hidden bg-white sm:-right-[60px] sm:top-1/2 sm:w-[1200px] md:right-0">
- <div
- className="absolute -inset-[50%] opacity-15 blur-[100px]"
- style={{
- backgroundImage: heroGradient,
- }}
- />
- <Image
- src="https://assets.dub.co/misc/referrals-hero-background.svg"
- alt="Refer and earn"
- width={1200}
- height={630}
- className="relative"
- />
- <div
- className="absolute -inset-[50%] mix-blend-soft-light blur-[100px]"
- style={{
- backgroundImage: heroGradient,
- }}
- />
- <Logo className="absolute right-[9.9%] top-[49.9%] size-10 -translate-x-1/2 -translate-y-1/2 overflow-hidden rounded-full bg-white sm:size-20 sm:drop-shadow-lg" />
- </div>
- </div>
- );
-}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/invite-button.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/invite-button.tsx
deleted file mode 100644
index e4d56e9063..0000000000
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/invite-button.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-"use client";
-
-import { useInviteReferralModal } from "@/ui/modals/invite-referral-modal";
-import { Button } from "@dub/ui";
-import { Mail } from "lucide-react";
-
-const subject = "Create a free account on Dub!";
-const body = (url: string) =>
- `Use my referral link to get started with Dub: ${url}`;
-
-export function InviteButton() {
- const { InviteReferralModal, setShowInviteReferralModal } =
- useInviteReferralModal();
-
- return (
- <>
- <InviteReferralModal />
- <Button
- text="Invite via email"
- icon={<Mail className="size-4" />}
- className="h-9 rounded-lg"
- onClick={() => setShowInviteReferralModal(true)}
- />
- </>
- );
-}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page-client.tsx
index e9fcafd60f..8782824043 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page-client.tsx
@@ -1,19 +1,10 @@
"use client";
-import {
- REFERRAL_CLICKS_QUOTA_BONUS,
- REFERRAL_CLICKS_QUOTA_BONUS_MAX,
- REFERRAL_REVENUE_SHARE,
-} from "@/lib/referrals/constants";
import useWorkspace from "@/lib/swr/use-workspace";
import { ReferralsEmbed } from "@dub/blocks";
-import { Check, Wordmark } from "@dub/ui";
-import { nFormatter } from "@dub/utils";
import { redirect } from "next/navigation";
-import { Suspense, useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
-import { HeroBackground } from "./hero-background";
-import ReferralLink, { ReferralLinkSkeleton } from "./referral-link";
export default function ReferralsPageClient() {
const { slug, flags } = useWorkspace();
@@ -45,71 +36,8 @@ export default function ReferralsPageClient() {
}
if (!publicToken) {
- return <ReferralLinkSkeleton />;
+ return <div>Loading...</div>;
}
- return (
- <div>
- <div className="relative">
- <div className="relative overflow-hidden rounded-xl border border-gray-200 p-4 sm:p-9">
- <Suspense>
- <HeroBackground />
- </Suspense>
-
- <div className="relative">
- <h1 className="text-xl font-semibold text-black sm:text-2xl">
- Refer and earn
- </h1>
-
- {/* Benefits */}
- <div className="mt-6 flex flex-col gap-6">
- {[
- {
- title: `${nFormatter(REFERRAL_REVENUE_SHARE * 100)}% recurring revenue`,
- description: "per paying customer (up to 1 year)",
- },
- {
- title: `${nFormatter(REFERRAL_CLICKS_QUOTA_BONUS)} extra clicks quota per month`,
- description: `per signup (up to ${nFormatter(REFERRAL_CLICKS_QUOTA_BONUS_MAX, { full: true })} total)`,
- },
- ].map(({ title, description }) => (
- <div className="flex items-center gap-3">
- <div className="flex size-9 items-center justify-center rounded-full border border-gray-200 bg-gradient-to-t from-gray-100 to-white">
- <div className="rounded-full bg-green-500 p-0.5">
- <Check className="size-3.5 text-white" />
- </div>
- </div>
- <div>
- <p className="text-base font-medium text-gray-800">
- {title}
- </p>
- <p className="text-xs text-gray-500">{description}</p>
- </div>
- </div>
- ))}
- </div>
-
- {/* Referral link + invite button or empty/error states */}
- <Suspense fallback={<ReferralLinkSkeleton />}>
- <ReferralLink slug={slug!} />
- </Suspense>
- </div>
- </div>
-
- {/* Powered by Dub Conversions */}
- <a
- href="https://d.to/conversions"
- target="_blank"
- className="mt-2 flex items-center justify-center gap-2 rounded-lg border-gray-100 bg-white p-2 transition-colors hover:border-gray-200 active:bg-gray-50 md:absolute md:bottom-3 md:right-3 md:mt-0 md:translate-x-0 md:border md:drop-shadow-sm"
- >
- <Wordmark className="h-4" />
- <p className="text-xs text-gray-800">
- Powered by <span className="font-medium">Dub Conversions</span>
- </p>
- </a>
- </div>
- {/* Embed Dub */}
- <ReferralsEmbed publicToken={publicToken} />
- </div>
- );
+ return <ReferralsEmbed publicToken={publicToken} />;
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/referral-link.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/referral-link.tsx
deleted file mode 100644
index 7be3b58c09..0000000000
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/referral-link.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { getReferralLink } from "@/lib/actions/get-referral-link";
-import { CopyButton } from "@dub/ui";
-import { getPrettyUrl } from "@dub/utils";
-import { GenerateButton } from "./generate-button";
-import { InviteButton } from "./invite-button";
-
-export default async function ReferralLink({ slug }: { slug: string }) {
- const { shortLink } = (await getReferralLink(slug)) || {};
-
- return (
- <div className="mt-8">
- {shortLink ? (
- <div className="grid gap-1.5">
- <p className="text-xs text-gray-500">Referral Link</p>
- <div className="grid grid-cols-1 gap-x-2 gap-y-2 sm:max-w-sm sm:grid-cols-[1fr_auto] xl:max-w-md">
- <div className="flex h-9 items-center justify-between gap-x-2 rounded-lg border border-gray-300 bg-white py-1.5 pl-4 pr-2">
- <p className="text-sm text-gray-500">{getPrettyUrl(shortLink)}</p>
- <CopyButton
- value={shortLink}
- variant="neutral"
- className="p-1.5 text-gray-500"
- />
- </div>
- <InviteButton />
- </div>
- </div>
- ) : (
- <GenerateButton />
- )}
- </div>
- );
-}
-
-export function ReferralLinkSkeleton() {
- return <div className="mt-8 h-9 w-40 animate-pulse rounded-lg bg-gray-200" />;
-}
diff --git a/apps/web/app/app.dub.co/embed/event-tabs.tsx b/apps/web/app/app.dub.co/embed/event-tabs.tsx
deleted file mode 100644
index 1079bba6fc..0000000000
--- a/apps/web/app/app.dub.co/embed/event-tabs.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-"use client";
-
-import { useRouterStuff } from "@dub/ui";
-import { ToggleGroup } from "@dub/ui/src/toggle-group";
-
-export function EventTabs() {
- const { queryParams, searchParams } = useRouterStuff();
-
- return (
- <ToggleGroup
- options={[
- { value: "clicks", label: "Clicks" },
- { value: "leads", label: "Leads" },
- { value: "sales", label: "Sales" },
- ]}
- selected={searchParams.get("event") ?? "clicks"}
- selectAction={(event) => queryParams({ set: { event }, del: "page" })}
- />
- );
-}
diff --git a/apps/web/app/app.dub.co/embed/events.tsx b/apps/web/app/app.dub.co/embed/events.tsx
deleted file mode 100644
index db66962232..0000000000
--- a/apps/web/app/app.dub.co/embed/events.tsx
+++ /dev/null
@@ -1,167 +0,0 @@
-"use client";
-
-import { EventType } from "@/lib/analytics/types";
-import { REFERRAL_REVENUE_SHARE } from "@/lib/referrals/constants";
-import { EventList, EventListSkeleton, useEvents } from "@dub/blocks";
-import {
- CaretUpFill,
- ChartActivity2,
- CursorRays,
- Globe,
- InvoiceDollar,
- UserCheck,
-} from "@dub/ui/src/icons";
-import { capitalize, COUNTRIES, currencyFormatter, timeAgo } from "@dub/utils";
-import { ClickEvent, LeadEvent, SaleEvent } from "dub/models/components";
-
-interface EventsProps {
- event: EventType;
- page: string;
-}
-
-const iconMap: Record<EventType, React.ElementType> = {
- clicks: CursorRays,
- leads: UserCheck,
- sales: InvoiceDollar,
-};
-
-const saleText = {
- "Subscription creation": "upgraded their account",
- "Subscription paid": "paid their subscription",
- "Plan upgraded": "upgraded their plan",
- default: "made a payment",
-};
-
-export const Events = ({ event, page }: EventsProps) => {
- const { events, isLoading } = useEvents({
- event,
- interval: "all",
- page,
- });
-
- if (isLoading || !events) {
- return <EventListSkeleton />;
- }
-
- const Icon = iconMap[event];
-
- return (
- <div className="relative">
- <EventList
- events={events.map((e: any) => {
- const content = {
- clicks: <ClickDescription event={e as ClickEvent} />,
- leads: <LeadDescription event={e as LeadEvent} />,
- sales: <SaleDescription event={e as SaleEvent} />,
- }[event];
-
- return {
- icon: <Icon className="size-4.5" />,
- content,
- right: e.timestamp ? (
- <div className="whitespace-nowrap">
- {timeAgo(new Date(e.timestamp), { withAgo: true })}
- </div>
- ) : null,
- };
- })}
- totalEvents={events?.length || 0}
- emptyState={{
- icon: ChartActivity2,
- title: `${capitalize(event)} Activity`,
- description: `No referral ${event} have been recorded yet.`,
- learnMore: "https://d.to/conversions",
- }}
- />
-
- {/* {demo && (
- <div className="absolute inset-0 bg-gradient-to-b from-[#fff3] to-white"></div>
- )} */}
- </div>
- );
-};
-
-const ClickDescription = ({ event }: { event: ClickEvent }) => {
- return (
- <>
- Someone from{" "}
- <div className="mx-1 inline-block">
- {event.country ? (
- <img
- alt={event.country}
- src={`https://flag.vercel.app/m/${event.country}.svg`}
- className="-mt-px inline-block h-3 w-4"
- />
- ) : (
- <Globe className="inline-block size-3 text-gray-700" />
- )}{" "}
- <span className="font-semibold text-gray-700">
- {event.country ? COUNTRIES[event.country] : "Planet Earth"}
- </span>{" "}
- </div>
- clicked on your link
- </>
- );
-};
-
-const LeadDescription = ({ event }: { event: LeadEvent }) => {
- return (
- <>
- Someone from{" "}
- <div className="mx-1 inline-block">
- {event.country ? (
- <img
- alt={event.country}
- src={`https://flag.vercel.app/m/${event.country}.svg`}
- className="-mt-px inline-block h-3 w-4"
- />
- ) : (
- <Globe className="inline-block size-3 text-gray-700" />
- )}{" "}
- <span className="font-semibold text-gray-700">
- {event.country ? COUNTRIES[event.country] : "Planet Earth"}
- </span>{" "}
- </div>
- signed up for an account
- </>
- );
-};
-
-const SaleDescription = ({ event }: { event: SaleEvent }) => {
- return (
- <div className="flex items-center justify-between gap-3">
- <div>
- Someone from{" "}
- <div className="mx-1 inline-block">
- {event.country ? (
- <img
- alt={event.country}
- src={`https://flag.vercel.app/m/${event.country}.svg`}
- className="-mt-px inline-block h-3 w-4"
- />
- ) : (
- <Globe className="inline-block size-3 text-gray-700" />
- )}{" "}
- <span className="font-semibold text-gray-700">
- {event.country ? COUNTRIES[event.country] : "Planet Earth"}
- </span>{" "}
- </div>
- {saleText[event.eventName] || saleText.default}
- </div>
- {event.saleAmount && event.saleAmount > 0 && (
- <span className="flex items-center gap-1 whitespace-nowrap font-medium text-gray-700 sm:pr-8 md:pr-12 lg:pr-20">
- {event.eventName === "Plan upgraded" && (
- <CaretUpFill className="size-3 text-green-600" />
- )}
- {currencyFormatter(
- Math.floor(event.saleAmount * REFERRAL_REVENUE_SHARE) / 100,
- {
- maximumFractionDigits: 2,
- },
- )}{" "}
- earned
- </span>
- )}
- </div>
- );
-};
diff --git a/apps/web/app/app.dub.co/embed/hero-background.tsx b/apps/web/app/app.dub.co/embed/hero-background.tsx
new file mode 100644
index 0000000000..17bfe4e5b7
--- /dev/null
+++ b/apps/web/app/app.dub.co/embed/hero-background.tsx
@@ -0,0 +1,49 @@
+import { BlurImage } from "@dub/ui";
+import Image from "next/image";
+
+export function HeroBackground({
+ logo,
+ color,
+}: {
+ logo?: string | null;
+ color?: string | null;
+}) {
+ const heroGradient = color
+ ? `conic-gradient(from 45deg at 65% 70%, ${color} 0deg, ${color} 72deg, ${color} 144deg, ${color} 197.89deg, ${color} 260.96deg, ${color} 360deg)`
+ : "conic-gradient(from 45deg at 65% 70%, #855AFC 0deg, #3A8BFD 72deg, #00FFF9 144deg, #5CFF80 197.89deg, #EAB308 260.96deg, #FF0000 360deg)";
+
+ return (
+ <div className="animate-fade-in pointer-events-none absolute inset-0 overflow-hidden [mask-image:radial-gradient(100%_100%_at_top_right,black,transparent)] max-[350px]:opacity-50 sm:[mask-image:linear-gradient(to_right,transparent_50%,black_70%)]">
+ <div className="absolute -right-[60px] top-[40px] isolate w-[600px] -translate-y-1/2 overflow-hidden bg-white sm:-right-[60px] sm:top-1/2 sm:w-[1200px] md:right-0">
+ <div
+ className="absolute -inset-[50%] opacity-15 blur-[100px]"
+ style={{
+ backgroundImage: heroGradient,
+ }}
+ />
+ <Image
+ src="https://assets.dub.co/misc/referrals-hero-background.svg"
+ alt="Refer and earn"
+ width={1200}
+ height={630}
+ className="relative"
+ />
+ <div
+ className="absolute -inset-[50%] mix-blend-soft-light blur-[100px]"
+ style={{
+ backgroundImage: heroGradient,
+ }}
+ />
+ {logo && (
+ <BlurImage
+ src={logo}
+ alt="Program Logo"
+ width={1200}
+ height={1200}
+ className="absolute right-[9.9%] top-[49.9%] size-10 -translate-x-1/2 -translate-y-1/2 overflow-hidden rounded-full bg-white sm:size-20 sm:drop-shadow-lg"
+ />
+ )}
+ </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
new file mode 100644
index 0000000000..0ca8f0f67d
--- /dev/null
+++ b/apps/web/app/app.dub.co/embed/page-client.tsx
@@ -0,0 +1,321 @@
+"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,
+ MaxWidthWrapper,
+ 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 { HeroBackground } from "./hero-background";
+import useReferralAnalytics from "./use-referral-analytics";
+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();
+ const [copied, copyToClipboard] = useCopyToClipboard();
+ const { getQueryString, searchParamsObj } = useRouterStuff();
+ const { link, isLoading: isLoadingLink } = useReferralLink();
+
+ const {
+ start,
+ end,
+ interval = "30d",
+ } = searchParamsObj as {
+ start?: string;
+ end?: string;
+ interval?: IntervalOptions;
+ };
+
+ const color = "#8B5CF6"; // TODO: Read this from a program attribute
+
+ return (
+ <MaxWidthWrapper className="pb-10">
+ <div className="relative flex flex-col rounded-lg border border-neutral-300 bg-gradient-to-r from-neutral-50 p-4 md:p-6">
+ {program && <HeroBackground logo={program?.logo} color={color} />}
+ <span className="flex items-center gap-2 text-sm text-neutral-500">
+ <MoneyBill2 className="size-4" />
+ Refer and earn
+ </span>
+ <div className="relative mt-24 text-lg text-neutral-900 sm:max-w-[50%]">
+ {program ? (
+ <ProgramCommissionDescription program={program} />
+ ) : (
+ <div className="mb-7 h-7 w-full animate-pulse rounded-md bg-neutral-200" />
+ )}
+ </div>
+ <span className="mb-1.5 mt-6 block text-sm text-neutral-800">
+ Referral link
+ </span>
+ <div className="xs:flex-row relative flex flex-col items-center gap-2">
+ {!isLoadingLink && link ? (
+ <input
+ type="text"
+ readOnly
+ value={getPrettyUrl(link.shortLink)}
+ className="xs:w-auto h-10 w-full rounded-md border border-neutral-300 px-3 text-sm focus:border-gray-500 focus:outline-none focus:ring-gray-500 lg:min-w-64 xl:min-w-72"
+ />
+ ) : (
+ <div className="h-10 w-16 animate-pulse rounded-md bg-neutral-200 lg:w-72" />
+ )}
+ <Button
+ icon={
+ copied ? (
+ <Check2 className="size-4" />
+ ) : (
+ <Copy className="size-4" />
+ )
+ }
+ text={copied ? "Copied link" : "Copy link"}
+ className="xs:w-fit"
+ onClick={() => copyToClipboard(getPrettyUrl(link?.shortLink))}
+ />
+ </div>
+ </div>
+ <ProgramOverviewContext.Provider
+ value={{
+ start: start ? new Date(start) : undefined,
+ end: end ? new Date(end) : undefined,
+ interval,
+ color,
+ }}
+ >
+ <div className="mt-6 rounded-lg border border-neutral-300">
+ <div className="p-4 md:p-6 md:pb-4">
+ <EarningsChart />
+ </div>
+ </div>
+ <div className="mt-6 grid grid-cols-[minmax(0,1fr)] gap-4 sm:grid-cols-3">
+ <StatCard title="Clicks" event="clicks" />
+ <StatCard title="Leads" event="leads" />
+ <StatCard title="Sales" event="sales" />
+ </div>
+ <div className="mt-6">
+ <div className="flex items-center justify-between">
+ <h2 className="text-base font-medium text-neutral-900">
+ Recent sales
+ </h2>
+ </div>
+ <div className="mt-4">{/* <SaleTablePartner 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/page.tsx b/apps/web/app/app.dub.co/embed/page.tsx
index 0bccef43b8..450571379e 100644
--- a/apps/web/app/app.dub.co/embed/page.tsx
+++ b/apps/web/app/app.dub.co/embed/page.tsx
@@ -1,16 +1,9 @@
-import { EventType } from "@/lib/analytics/types";
-import { Referrals } from "./referrals";
-
-export default async function EmbedPage({
- searchParams,
-}: {
- searchParams: { token: string; event?: EventType; page?: string };
-}) {
- const { token, event, page } = searchParams;
+import { ReferralsEmbedPageClient } from "./page-client";
+export default async function ReferralsEmbedPage() {
return (
<>
- <Referrals event={event} page={page} publicToken={token} />
+ <ReferralsEmbedPageClient />
</>
);
}
diff --git a/apps/web/app/app.dub.co/embed/placeholders.tsx b/apps/web/app/app.dub.co/embed/placeholders.tsx
deleted file mode 100644
index 5ebaa1a852..0000000000
--- a/apps/web/app/app.dub.co/embed/placeholders.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-import { randomValue } from "@dub/utils";
-import { subDays } from "date-fns";
-
-export const placeholderEvents = {
- clicks: [...Array(10)].map(
- (_, idx) =>
- ({
- timestamp: subDays(new Date(), idx).toISOString(),
- click_id: "1",
- link_id: "1",
- domain: "refer.dub.co",
- key: "",
- url: "https://dub.co",
- country: randomValue(["US", "GB", "CA", "AU", "DE", "FR", "ES", "IT"]),
- }) as any,
- ),
-
- leads: [...Array(10)].map(
- (_, idx) =>
- ({
- timestamp: subDays(new Date(), idx).toISOString(),
- click_id: "1",
- link_id: "1",
- domain: "refer.dub.co",
- key: "",
- url: "https://dub.co",
- country: randomValue(["US", "GB", "CA", "AU", "DE", "FR", "ES", "IT"]),
- }) as any,
- ),
-
- sales: [...Array(10)].map(
- (_, idx) =>
- ({
- timestamp: subDays(new Date(), idx).toISOString(),
- click_id: "1",
- link_id: "1",
- domain: "refer.dub.co",
- key: "",
- url: "https://dub.co",
- country: randomValue(["US", "GB", "CA", "AU", "DE", "FR", "ES", "IT"]),
- event_name: [
- "Subscription creation",
- "Subscription paid",
- "Plan upgraded",
- ][idx % 3],
- // TODO update to saleAmount
- amount: [1100, 4900, 2400][idx % 3],
- }) as any,
- ),
-};
diff --git a/apps/web/app/app.dub.co/embed/referrals.tsx b/apps/web/app/app.dub.co/embed/referrals.tsx
deleted file mode 100644
index 7eefb96e19..0000000000
--- a/apps/web/app/app.dub.co/embed/referrals.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-"use client";
-
-import { EventType } from "@/lib/analytics/types";
-import { DubProvider } from "@dub/blocks";
-import { EventTabs } from "./event-tabs";
-import { Events } from "./events";
-import { Stats } from "./stats";
-
-interface ReferralsProps {
- event: EventType | undefined;
- page: string | undefined;
- publicToken: string | undefined | null;
-}
-
-export const Referrals = ({ event, page, publicToken }: ReferralsProps) => {
- if (!publicToken) {
- return (
- <div className="flex h-64 flex-col items-center justify-center text-center">
- <h2 className="mb-2 text-2xl font-semibold text-gray-800">
- Unavailable
- </h2>
- <p className="text-gray-600">The embed public token is not found.</p>
- </div>
- );
- }
-
- return (
- <DubProvider publicToken={publicToken}>
- <div className="mt-8">
- <Stats />
- </div>
-
- <div className="mt-12">
- <div className="mb-5 flex flex-wrap items-end justify-between gap-4">
- <h2 className="text-xl font-semibold text-gray-800">Activity</h2>
- <EventTabs />
- </div>
- <Events event={event || "clicks"} page={page || "1"} />
- </div>
- </DubProvider>
- );
-};
diff --git a/apps/web/app/app.dub.co/embed/stats.tsx b/apps/web/app/app.dub.co/embed/stats.tsx
deleted file mode 100644
index 7e0d548ea1..0000000000
--- a/apps/web/app/app.dub.co/embed/stats.tsx
+++ /dev/null
@@ -1,94 +0,0 @@
-"use client";
-
-import {
- REFERRAL_CLICKS_QUOTA_BONUS,
- REFERRAL_CLICKS_QUOTA_BONUS_MAX,
- REFERRAL_REVENUE_SHARE,
-} from "@/lib/referrals/constants";
-import {
- Gauge,
- MiniAreaChart,
- StatsCard,
- StatsCardSkeleton,
- useAnalytics,
-} from "@dub/blocks";
-import { CountingNumbers } from "@dub/ui";
-import { User } from "@dub/ui/src/icons";
-import { AnalyticsCount, AnalyticsTimeseries } from "dub/models/components";
-
-interface StatsInnerProps {
- totalEvents: AnalyticsCount;
- sales: AnalyticsTimeseries[];
-}
-
-export const Stats = () => {
- const { analytics: sales, isLoading: isLoadingSales } = useAnalytics({
- event: "sales",
- interval: "90d",
- groupBy: "timeseries",
- });
-
- const { analytics: totalEvents, isLoading: isLoadingTotalEvents } =
- useAnalytics({
- event: "composite",
- interval: "all_unfiltered",
- groupBy: "count",
- });
-
- const loading = isLoadingSales || isLoadingTotalEvents;
-
- return (
- <div className="grid grid-cols-1 gap-x-4 gap-y-4 md:grid-cols-2 lg:gap-x-6">
- {loading ? (
- [...Array(2)].map(() => <StatsCardSkeleton />)
- ) : (
- <StatsInner
- totalEvents={totalEvents as AnalyticsCount}
- sales={sales as AnalyticsTimeseries[]}
- />
- )}
- </div>
- );
-};
-
-const StatsInner = ({ totalEvents, sales }: StatsInnerProps) => {
- const totalLeads = Math.min(totalEvents.leads ?? 0, 32);
- const totalSales = totalEvents.saleAmount ?? 0;
-
- const clicksQuotaBonus = Math.min(
- totalLeads * REFERRAL_CLICKS_QUOTA_BONUS,
- REFERRAL_CLICKS_QUOTA_BONUS_MAX,
- );
-
- const salesData = sales.map((sale) => ({
- date: new Date(sale.start),
- value: sale.saleAmount ?? 0,
- }));
-
- return (
- <>
- <StatsCard
- label="Affiliate Earnings"
- graphic={<MiniAreaChart data={salesData} />}
- >
- <CountingNumbers prefix="$" variant="full">
- {(totalSales / 100) * REFERRAL_REVENUE_SHARE}
- </CountingNumbers>
- </StatsCard>
-
- <StatsCard
- label="Clicks Quota Earned"
- graphic={
- <Gauge value={clicksQuotaBonus} max={REFERRAL_CLICKS_QUOTA_BONUS_MAX}>
- <div className="flex items-end gap-1 text-xs font-medium text-gray-500">
- <User className="size-4" />
- <CountingNumbers>{totalLeads}</CountingNumbers>
- </div>
- </Gauge>
- }
- >
- <CountingNumbers variant="full">{clicksQuotaBonus}</CountingNumbers>
- </StatsCard>
- </>
- );
-};
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
new file mode 100644
index 0000000000..eb32a6cd84
--- /dev/null
+++ b/apps/web/app/app.dub.co/embed/use-referral-analytics.ts
@@ -0,0 +1,31 @@
+import { PartnerAnalyticsFilters } from "@/lib/analytics/types";
+import { fetcher } from "@dub/utils";
+import useSWR from "swr";
+
+export default function useReferralAnalytics(params?: PartnerAnalyticsFilters) {
+ const searchParams = new URLSearchParams({
+ event: params?.event ?? "composite",
+ ...(params?.start && params?.end
+ ? {
+ start: params.start.toISOString(),
+ end: params.end.toISOString(),
+ }
+ : { interval: params?.interval ?? "all_unfiltered" }),
+ groupBy: params?.groupBy ?? "count",
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ });
+
+ const { data, error, isLoading } = useSWR<any>(
+ `/api/analytics/client?${searchParams.toString()}`,
+ fetcher,
+ {
+ dedupingInterval: 60000,
+ },
+ );
+
+ return {
+ data,
+ error,
+ isLoading,
+ };
+}
diff --git a/apps/web/app/app.dub.co/embed/use-referral-link.ts b/apps/web/app/app.dub.co/embed/use-referral-link.ts
new file mode 100644
index 0000000000..902d02cbaa
--- /dev/null
+++ b/apps/web/app/app.dub.co/embed/use-referral-link.ts
@@ -0,0 +1,17 @@
+import { fetcher } from "@dub/utils";
+import { Link } from "@prisma/client";
+import useSWR from "swr";
+
+export const useReferralLink = () => {
+ const {
+ data: link,
+ error,
+ isLoading,
+ } = useSWR<Link>(`/api/referrals/link`, fetcher);
+
+ return {
+ link,
+ error,
+ isLoading,
+ };
+};
diff --git a/apps/web/app/app.dub.co/embed/use-referral-program.ts b/apps/web/app/app.dub.co/embed/use-referral-program.ts
new file mode 100644
index 0000000000..7a3dd39acf
--- /dev/null
+++ b/apps/web/app/app.dub.co/embed/use-referral-program.ts
@@ -0,0 +1,17 @@
+import { fetcher } from "@dub/utils";
+import { Program } from "@prisma/client";
+import useSWR from "swr";
+
+export const useReferralProgram = () => {
+ const {
+ data: program,
+ error,
+ isLoading,
+ } = useSWR<Program>(`/api/referrals/program`, fetcher);
+
+ return {
+ program,
+ error,
+ isLoading,
+ };
+};
diff --git a/apps/web/lib/actions/generate-referral-link.ts b/apps/web/lib/actions/generate-referral-link.ts
deleted file mode 100644
index e192c45721..0000000000
--- a/apps/web/lib/actions/generate-referral-link.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-"use server";
-
-import { linkConstructor } from "@dub/utils";
-import { z } from "zod";
-import { dub } from "../dub";
-import { prisma } from "../prisma";
-import { authActionClient } from "./safe-action";
-
-// Generate a referral link for a workspace
-export const generateReferralLink = authActionClient
- .schema(
- z.object({
- workspaceId: z.string(),
- }),
- )
- .action(async ({ ctx }) => {
- const { workspace } = ctx;
-
- try {
- const createdLink = await dub.links.create({
- domain: "refer.dub.co",
- key: workspace.slug,
- url: "https://dub.co",
- externalId: `ws_${workspace.id}`,
- tagIds: ["cm000srqx0004o6ldehod07zc"],
- trackConversion: true,
- identifier: workspace.slug,
- });
-
- await prisma.project.update({
- where: {
- id: workspace.id,
- },
- data: {
- referralLinkId: createdLink.id,
- },
- });
-
- return {
- url: linkConstructor({
- domain: createdLink.domain,
- key: createdLink.key,
- }),
- };
- } catch (e) {
- console.error("Failed to activate referral link.", e);
- }
-
- throw new Error("Failed to activate referral link.");
- });
diff --git a/apps/web/lib/referrals/auth.ts b/apps/web/lib/referrals/auth.ts
index cd1b89dbc4..dfb0254b34 100644
--- a/apps/web/lib/referrals/auth.ts
+++ b/apps/web/lib/referrals/auth.ts
@@ -2,7 +2,7 @@ import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { prisma } from "@/lib/prisma";
import { ratelimit } from "@/lib/upstash";
import { getSearchParams } from "@dub/utils";
-import { Link, Project } from "@prisma/client";
+import { Link, Program, Project } from "@prisma/client";
import { AxiomRequest, withAxiom } from "next-axiom";
import { cookies } from "next/headers";
import { EMBED_PUBLIC_TOKEN_COOKIE_NAME } from "./constants";
@@ -14,12 +14,14 @@ interface WithAuthHandler {
searchParams,
workspace,
link,
+ program,
}: {
req: Request;
params: Record<string, string>;
searchParams: Record<string, string>;
workspace: Project;
link: Link;
+ program: Program;
}): Promise<Response>;
}
@@ -107,12 +109,19 @@ export const withAuth = (handler: WithAuthHandler) => {
},
});
+ const program = await prisma.program.findFirstOrThrow({
+ where: {
+ workspaceId: workspace.id,
+ },
+ });
+
return await handler({
req,
params,
searchParams,
workspace,
link,
+ program,
});
} catch (error) {
req.log.error(error);
diff --git a/apps/web/lib/referrals/token.ts b/apps/web/lib/referrals/create-referral-token.ts
similarity index 100%
rename from apps/web/lib/referrals/token.ts
rename to apps/web/lib/referrals/create-referral-token.ts