The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
referrals → embed
Steven Teybfb5508f3a57
diff --git a/apps/web/app/api/referrals/invite/route.ts b/apps/web/app/api/embed/invite/route.tssimilarity index 100%rename from apps/web/app/api/referrals/invite/route.tsrename to apps/web/app/api/embed/invite/route.tsdiff --git a/apps/web/app/api/referrals/sales/count/route.ts b/apps/web/app/api/embed/sales/count/route.tssimilarity index 100%rename from apps/web/app/api/referrals/sales/count/route.tsrename to apps/web/app/api/embed/sales/count/route.tsdiff --git a/apps/web/app/api/referrals/sales/route.ts b/apps/web/app/api/embed/sales/route.tssimilarity index 100%rename from apps/web/app/api/referrals/sales/route.tsrename to apps/web/app/api/embed/sales/route.tsdiff --git a/apps/web/app/api/referrals/token/route.ts b/apps/web/app/api/embed/token/route.tssimilarity index 100%rename from apps/web/app/api/referrals/token/route.tsrename to apps/web/app/api/embed/token/route.tsdiff --git a/apps/web/app/app.dub.co/embed/dashboard/page-client.tsx b/apps/web/app/app.dub.co/embed/dashboard/page-client.tsxdeleted file mode 100644index b5c12cdd3e..0000000000--- a/apps/web/app/app.dub.co/embed/dashboard/page-client.tsx+++ /dev/null@@ -1,196 +0,0 @@-"use client";--import { IntervalOptions } from "@/lib/analytics/types";-import {- EarningsChart,- ProgramOverviewContext,-} from "@/ui/partners/earnings-chart";-import { HeroBackground } from "@/ui/partners/hero-background";-import { ProgramCommissionDescription } from "@/ui/partners/program-commission-description";-import { StatCard } from "@/ui/partners/stat-card";-import {- Button,- Check2,- useCopyToClipboard,- useRouterStuff,- Wordmark,-} from "@dub/ui";-import { Copy, MoneyBill2 } from "@dub/ui/src/icons";-import { getPrettyUrl } from "@dub/utils";-import { Link, Program } from "@prisma/client";-import { useContext } from "react";-import { LinkToken } from "../token";-import useReferralAnalytics from "../use-referral-analytics";-import { SaleTable } from "./sale-table";--export function RewardDashboardPageClient({- program,- link,-}: {- program: Program;- link: Link;-}) {- const { searchParamsObj } = useRouterStuff();- const [copied, copyToClipboard] = useCopyToClipboard();-- const {- start,- end,- interval = "30d",- } = searchParamsObj as {- start?: string;- end?: string;- interval?: IntervalOptions;- };-- return (- <>- <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={program.brandColor} />- )}-- <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%]">- <ProgramCommissionDescription program={program} />- </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">- <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"- />-- <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>-- <div>- <ProgramOverviewContext.Provider- value={{- start: start ? new Date(start) : undefined,- end: end ? new Date(end) : undefined,- interval,- color: program.brandColor ?? undefined,- }}- >- <div className="mt-6 rounded-lg border border-neutral-300">- <div className="p-4 md:p-6 md:pb-4">- <EarningsChartContainer />- </div>- </div>- <div className="mt-6 grid grid-cols-[minmax(0,1fr)] gap-4 sm:grid-cols-3">- <StatCardContainer title="Clicks" event="clicks" />- <StatCardContainer title="Leads" event="leads" />- <StatCardContainer 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">- <SaleTable limit={10} />- </div>- </div>- </ProgramOverviewContext.Provider>- </div>-- <div className="flex items-center justify-center">- <a- href="https://d.to/conversions"- target="_blank"- className="mt-2 flex items-center justify-center gap-1 rounded-lg bg-white p-2 transition-colors"- >- <p className="text-sm text-gray-700">Powered by</p>- <Wordmark className="h-4" />- </a>- </div>-- <LinkToken />- </>- );-}--const EarningsChartContainer = () => {- 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,- });-- return (- <EarningsChart- timeseries={timeseries}- total={total}- color={color}- error={error}- />- );-};--function StatCardContainer({- 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 (- <StatCard- timeseries={timeseries}- total={total}- error={error}- title={title}- event={event}- color={color}- />- );-}diff --git a/apps/web/app/app.dub.co/embed/dashboard/page.tsx b/apps/web/app/app.dub.co/embed/dashboard/page.tsxdeleted file mode 100644index 5ac0dd69e1..0000000000--- a/apps/web/app/app.dub.co/embed/dashboard/page.tsx+++ /dev/null@@ -1,14 +0,0 @@-import { getLinkAndProgram } from "../utils";-import { RewardDashboardPageClient } from "./page-client";--export default async function RewardDashboardPage({- searchParams,-}: {- searchParams: { token: string };-}) {- const { token } = searchParams;-- const { link, program } = await getLinkAndProgram(token);-- return <RewardDashboardPageClient program={program} link={link} />;-}diff --git a/apps/web/app/app.dub.co/embed/dashboard/request-partner-invite-form.tsx b/apps/web/app/app.dub.co/embed/dashboard/request-partner-invite-form.tsxdeleted file mode 100644index d6ba09bf6c..0000000000--- a/apps/web/app/app.dub.co/embed/dashboard/request-partner-invite-form.tsx+++ /dev/null@@ -1,61 +0,0 @@-import { requestPartnerInviteSchema } from "@/lib/dots/schemas";-import z from "@/lib/zod";-import { Button } from "@dub/ui";-import { zodResolver } from "@hookform/resolvers/zod";-import { useForm } from "react-hook-form";-import { toast } from "sonner";-import { mutate } from "swr";--type RequestPartnerInvite = z.infer<typeof requestPartnerInviteSchema>;--export const RequestPartnerInviteForm = () => {- const {- register,- handleSubmit,- formState: { isSubmitting },- } = useForm<RequestPartnerInvite>({- resolver: zodResolver(requestPartnerInviteSchema),- });-- const onSubmit = async (data: RequestPartnerInvite) => {- const response = await fetch("/api/referrals/invite", {- method: "POST",- body: JSON.stringify(data),- });-- if (!response.ok) {- const { error } = await response.json();- toast.error(error.message);- return;- }-- mutate("/api/referrals/invite");- toast.success(- "Invite request sent successfully! Check your email for the invite link.",- );- };-- return (- <form- onSubmit={handleSubmit(onSubmit)}- className="mt-4 rounded-lg border border-neutral-300 p-5"- >- <div className="flex gap-2">- <input- {...register("email")}- className="flex-grow rounded-md border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"- autoFocus- required- placeholder="Enter your email"- />-- <Button- type="submit"- text="Request invite"- className="h-10 w-fit"- loading={isSubmitting}- />- </div>- </form>- );-};diff --git a/apps/web/app/app.dub.co/embed/dashboard/sale-table.tsx b/apps/web/app/app.dub.co/embed/dashboard/sale-table.tsxdeleted file mode 100644index 66709ed9f8..0000000000--- a/apps/web/app/app.dub.co/embed/dashboard/sale-table.tsx+++ /dev/null@@ -1,154 +0,0 @@-"use client";--import { PartnerSaleResponse } from "@/lib/types";-import { SaleStatusBadges } from "@/ui/partners/sale-status-badges";-import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";-import SimpleDateRangePicker from "@/ui/shared/simple-date-range-picker";-import {- StatusBadge,- Table,- usePagination,- useRouterStuff,- useTable,-} from "@dub/ui";-import { CircleDollar } from "@dub/ui/src/icons";-import { currencyFormatter, fetcher, formatDate } from "@dub/utils";-import useSWR from "swr";--export function SaleTable({ limit }: { limit?: number }) {- const { pagination, setPagination } = usePagination(limit);- const { queryParams, searchParamsObj, getQueryString } = useRouterStuff();-- const {- data: sales,- isLoading,- error,- } = useSWR<PartnerSaleResponse[]>(- `/api/referrals/sales${getQueryString()}`,- fetcher,- );-- const { data: salesCount } = useSWR<{ count: number }>(- `/api/referrals/sales/count${getQueryString()}`,- fetcher,- );-- const { sortBy = "timestamp", order = "desc" } = searchParamsObj as {- sortBy?: "timestamp";- order?: "asc" | "desc";- };-- const { table, ...tableProps } = useTable({- data: sales?.slice(0, limit) || [],- loading: isLoading,- error: error ? "Failed to fetch sales events." : undefined,- columns: [- {- id: "timestamp",- header: "Date",- accessorKey: "timestamp",- cell: ({ row }) => {- return formatDate(row.original.createdAt, { month: "short" });- },- },- {- id: "customer",- header: "Customer",- accessorKey: "customer",- cell: ({ row }) => {- return row.original.customer.email;- },- },- {- id: "saleAmount",- header: "Sale Amount",- accessorKey: "sale",- cell: ({ row }) => {- return currencyFormatter(row.original.amount / 100, {- minimumFractionDigits: 2,- maximumFractionDigits: 2,- });- },- },- {- id: "earnings",- header: "Earnings",- accessorKey: "earnings",- cell: ({ row }) => {- return currencyFormatter(row.original.earnings / 100, {- minimumFractionDigits: 2,- maximumFractionDigits: 2,- });- },- },- {- header: "Status",- cell: ({ row }) => {- const badge = SaleStatusBadges[row.original.status];-- return (- <StatusBadge icon={null} variant={badge.variant}>- {badge.label}- </StatusBadge>- );- },- },- ],- ...(!limit && {- pagination,- onPaginationChange: setPagination,- sortableColumns: ["timestamp"],- sortBy,- sortOrder: order,- onSortChange: ({ sortBy, sortOrder }) =>- queryParams({- set: {- ...(sortBy && { sort: sortBy }),- ...(sortOrder && { order: sortOrder }),- },- }),- }),- rowCount: salesCount?.count || 0,- emptyState: (- <AnimatedEmptyState- title="No sales found"- description="No sales have been made for this program yet."- cardContent={() => (- <>- <CircleDollar className="size-4 text-neutral-700" />- <div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />- </>- )}- />- ),- resourceName: (plural) => `sale${plural ? "s" : ""}`,- });-- return (- <div className="flex flex-col gap-3">- {!limit && (- <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">- <SimpleDateRangePicker className="w-full sm:min-w-[200px] md:w-fit" />- </div>- )}- {isLoading || sales?.length ? (- <Table- {...tableProps}- table={table}- containerClassName="border-neutral-300"- />- ) : (- <AnimatedEmptyState- title="No sales found"- description="No sales have been made for this program yet."- cardContent={() => (- <>- <CircleDollar className="size-4 text-neutral-700" />- <div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />- </>- )}- />- )}- </div>- );-}diff --git a/apps/web/app/app.dub.co/embed/token.tsx b/apps/web/app/app.dub.co/embed/token.tsxindex 79a6469940..31fc5d207b 100644--- a/apps/web/app/app.dub.co/embed/token.tsx+++ b/apps/web/app/app.dub.co/embed/token.tsx@@ -5,7 +5,7 @@ import { useEffect } from "react";import useSWR from "swr";export const LinkToken = () => {- const { error } = useSWR<{ token: number }>("/api/referrals/token", fetcher, {+ const { error } = useSWR<{ token: number }>("/api/embed/token", fetcher, {revalidateOnFocus: true,refreshInterval: 50000,});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.tsdeleted file mode 100644index da20e38c06..0000000000--- a/apps/web/app/app.dub.co/embed/use-referral-analytics.ts+++ /dev/null@@ -1,31 +0,0 @@-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 } = useSWR<any>(- `/api/analytics/client?${searchParams.toString()}`,- fetcher,- {- dedupingInterval: 60000,- },- );-- return {- data,- error,- loading: !data && !error,- };-}diff --git a/apps/web/app/app.dub.co/embed/widget/page-client.tsx b/apps/web/app/app.dub.co/embed/widget/page-client.tsxindex 0f0daa4171..4a8753af23 100644--- a/apps/web/app/app.dub.co/embed/widget/page-client.tsx+++ b/apps/web/app/app.dub.co/embed/widget/page-client.tsx@@ -46,7 +46,7 @@ export function EmbedWidgetPageClient({const [selectedTab, setSelectedTab] = useState<Tab>("invite");const { data: sales, isLoading } = useSWR<PartnerSaleResponse[]>(- "/api/referrals/sales",+ "/api/embed/sales",fetcher,);