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 events table

Tim Wilsoncff6191a4f42
diff --git a/apps/web/app/api/partners/[partnerId]/programs/[programId]/events/route.ts b/apps/web/app/api/partners/[partnerId]/programs/[programId]/events/route.ts
index b1b2fef88a..71b7fd80fd 100644
--- a/apps/web/app/api/partners/[partnerId]/programs/[programId]/events/route.ts
+++ b/apps/web/app/api/partners/[partnerId]/programs/[programId]/events/route.ts
@@ -12,13 +12,13 @@ export const GET = withPartner(async ({ partner, params, searchParams }) => {
});
const parsedParams = eventsQuerySchema
- .pick({
- event: true,
- interval: true,
- page: true,
- limit: true,
- order: true,
- sortBy: true,
+ .omit({
+ linkId: true,
+ externalId: true,
+ domain: true,
+ root: true,
+ key: true,
+ tagId: true,
})
.parse(searchParams);
@@ -38,7 +38,9 @@ export const GET = withPartner(async ({ partner, params, searchParams }) => {
response.map((item) => {
return {
...item,
- earnings: getEarnings(item),
+ ...(parsedParams.event === "sales" && {
+ earnings: getEarnings(item),
+ }),
};
}),
);
diff --git a/apps/web/app/partners.dub.co/(dashboard)/[partnerId]/[programId]/events/page-client.tsx b/apps/web/app/partners.dub.co/(dashboard)/[partnerId]/[programId]/events/page-client.tsx
index 52da7b6dae..b224db67c5 100644
--- a/apps/web/app/partners.dub.co/(dashboard)/[partnerId]/[programId]/events/page-client.tsx
+++ b/apps/web/app/partners.dub.co/(dashboard)/[partnerId]/[programId]/events/page-client.tsx
@@ -1,28 +1,417 @@
"use client";
-import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
-import { MaxWidthWrapper } from "@dub/ui";
-import { CursorRays, InvoiceDollar, UserCheck } from "@dub/ui/src/icons";
-
-const emptyStateIcons = [CursorRays, UserCheck, InvoiceDollar];
+import {
+ INTERVAL_DATA,
+ INTERVAL_DISPLAYS,
+ TRIGGER_DISPLAY,
+ VALID_ANALYTICS_FILTERS,
+} from "@/lib/analytics/constants";
+import AnalyticsProvider, {
+ AnalyticsContext,
+} from "@/ui/analytics/analytics-provider";
+import ContinentIcon from "@/ui/analytics/continent-icon";
+import DeviceIcon from "@/ui/analytics/device-icon";
+import EventsTable from "@/ui/analytics/events/events-table";
+import EventsTabs from "@/ui/analytics/events/events-tabs";
+import RefererIcon from "@/ui/analytics/referer-icon";
+import { useAnalyticsFilterOption } from "@/ui/analytics/utils";
+import {
+ DateRangePicker,
+ Filter,
+ LinkLogo,
+ MaxWidthWrapper,
+ useRouterStuff,
+} from "@dub/ui";
+import {
+ Cube,
+ CursorRays,
+ FlagWavy,
+ LinkBroken,
+ MapPosition,
+ MobilePhone,
+ OfficeBuilding,
+ QRCode,
+ ReferredVia,
+ Window,
+} from "@dub/ui/src/icons";
+import {
+ capitalize,
+ cn,
+ CONTINENTS,
+ COUNTRIES,
+ getApexDomain,
+ nFormatter,
+} from "@dub/utils";
+import { useParams } from "next/navigation";
+import {
+ ComponentProps,
+ useCallback,
+ useContext,
+ useMemo,
+ useState,
+} from "react";
export function EventsPageClient() {
+ const { partnerId, programId } = useParams() as {
+ partnerId: string;
+ programId: string;
+ };
+
return (
<MaxWidthWrapper>
- <AnimatedEmptyState
- title="Events"
- description="View a real-time event stream for your referral activity"
- cardContent={(idx) => {
- const Icon = emptyStateIcons[idx % emptyStateIcons.length];
- return (
- <>
- <Icon className="size-4 text-neutral-700" />
- <div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />
- </>
- );
- }}
- pillContent="Coming soon"
- />
+ <AnalyticsProvider
+ partnerId={partnerId}
+ programId={programId}
+ defaultInterval="30d"
+ >
+ <div className="pb-10">
+ <EventsFilters />
+ <div className="mx-auto mt-3 flex max-w-screen-xl flex-col gap-3">
+ <EventsTabs conversionEnabled />
+ <EventsTableContainer />
+ </div>
+ </div>
+ </AnalyticsProvider>
</MaxWidthWrapper>
);
}
+
+function EventsTableContainer() {
+ const { selectedTab } = useContext(AnalyticsContext);
+
+ return <EventsTable key={selectedTab} partners />;
+}
+
+function EventsFilters() {
+ const { queryParams, searchParamsObj } = useRouterStuff();
+ const { start, end, interval } = useContext(AnalyticsContext);
+
+ const [requestedFilters, setRequestedFilters] = useState<string[]>([]);
+
+ const activeFilters = useMemo(() => {
+ const {
+ continent,
+ country,
+ city,
+ device,
+ browser,
+ os,
+ trigger,
+ referer,
+ refererUrl,
+ url,
+ } = searchParamsObj;
+ return [
+ ...(continent ? [{ key: "continent", value: continent }] : []),
+ ...(country ? [{ key: "country", value: country }] : []),
+ ...(city ? [{ key: "city", value: city }] : []),
+ ...(device ? [{ key: "device", value: device }] : []),
+ ...(browser ? [{ key: "browser", value: browser }] : []),
+ ...(os ? [{ key: "os", value: os }] : []),
+ ...(trigger ? [{ key: "trigger", value: trigger }] : []),
+ ...(referer ? [{ key: "referer", value: referer }] : []),
+ ...(refererUrl ? [{ key: "refererUrl", value: refererUrl }] : []),
+ ...(url ? [{ key: "url", value: url }] : []),
+ ];
+ }, [searchParamsObj]);
+
+ const isRequested = useCallback(
+ (key: string) =>
+ requestedFilters.includes(key) ||
+ activeFilters.some((af) => af.key === key),
+ [requestedFilters, activeFilters],
+ );
+
+ const countries = useAnalyticsFilterOption("countries", {
+ cacheOnly: !isRequested("country"),
+ });
+ const cities = useAnalyticsFilterOption("cities", {
+ cacheOnly: !isRequested("city"),
+ });
+ const continents = useAnalyticsFilterOption("continents", {
+ cacheOnly: !isRequested("continent"),
+ });
+ const devices = useAnalyticsFilterOption("devices", {
+ cacheOnly: !isRequested("device"),
+ });
+ const browsers = useAnalyticsFilterOption("browsers", {
+ cacheOnly: !isRequested("browser"),
+ });
+ const os = useAnalyticsFilterOption("os", {
+ cacheOnly: !isRequested("os"),
+ });
+ const triggers = useAnalyticsFilterOption("triggers", {
+ cacheOnly: !isRequested("trigger"),
+ });
+ const referers = useAnalyticsFilterOption("referers", {
+ cacheOnly: !isRequested("referer"),
+ });
+ const refererUrls = useAnalyticsFilterOption("referer_urls", {
+ cacheOnly: !isRequested("refererUrl"),
+ });
+ const urls = useAnalyticsFilterOption("top_urls", {
+ cacheOnly: !isRequested("url"),
+ });
+
+ const filters: ComponentProps<typeof Filter.Select>["filters"] = useMemo(
+ () => [
+ {
+ key: "trigger",
+ icon: CursorRays,
+ label: "Trigger",
+ options:
+ triggers?.map(({ trigger, count }) => ({
+ value: trigger,
+ label: TRIGGER_DISPLAY[trigger],
+ icon: trigger === "qr" ? QRCode : CursorRays,
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ {
+ 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:
+ countries?.map(({ country, count }) => ({
+ value: country,
+ label: COUNTRIES[country],
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "city",
+ icon: OfficeBuilding,
+ label: "City",
+ options:
+ cities?.map(({ city, country, count }) => ({
+ value: city,
+ label: city,
+ icon: (
+ <img
+ alt={country}
+ src={`https://flag.vercel.app/m/${country}.svg`}
+ className="h-2.5 w-4"
+ />
+ ),
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "continent",
+ icon: MapPosition,
+ label: "Continent",
+ getOptionIcon: (value) => (
+ <ContinentIcon display={value} className="size-2.5" />
+ ),
+ getOptionLabel: (value) => CONTINENTS[value],
+ options:
+ continents?.map(({ continent, count }) => ({
+ value: continent,
+ label: CONTINENTS[continent],
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "device",
+ icon: MobilePhone,
+ label: "Device",
+ getOptionIcon: (value) => (
+ <DeviceIcon
+ display={capitalize(value) ?? value}
+ tab="devices"
+ className="h-4 w-4"
+ />
+ ),
+ options:
+ devices?.map(({ device, count }) => ({
+ value: device,
+ label: device,
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "browser",
+ icon: Window,
+ label: "Browser",
+ getOptionIcon: (value) => (
+ <DeviceIcon display={value} tab="browsers" className="h-4 w-4" />
+ ),
+ options:
+ browsers?.map(({ browser, count }) => ({
+ value: browser,
+ label: browser,
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "os",
+ icon: Cube,
+ label: "OS",
+ getOptionIcon: (value) => (
+ <DeviceIcon display={value} tab="os" className="h-4 w-4" />
+ ),
+ options:
+ os?.map(({ os, count }) => ({
+ value: os,
+ label: os,
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "referer",
+ icon: ReferredVia,
+ label: "Referer",
+ getOptionIcon: (value, props) => (
+ <RefererIcon display={value} className="h-4 w-4" />
+ ),
+ options:
+ referers?.map(({ referer, count }) => ({
+ value: referer,
+ label: referer,
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "refererUrl",
+ icon: ReferredVia,
+ label: "Referrer URL",
+ getOptionIcon: (value, props) => (
+ <RefererIcon display={value} className="h-4 w-4" />
+ ),
+ options:
+ refererUrls?.map(({ refererUrl, count }) => ({
+ value: refererUrl,
+ label: refererUrl,
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "url",
+ icon: LinkBroken,
+ label: "Destination URL",
+ getOptionIcon: (_, props) => (
+ <LinkLogo
+ apexDomain={getApexDomain(props.option?.value)}
+ className="size-4 sm:size-4"
+ />
+ ),
+ options:
+ urls?.map(({ url, count }) => ({
+ value: url,
+ label: url.replace(/^https?:\/\//, "").replace(/\/$/, ""),
+ right: nFormatter(count, { full: true }),
+ })) ?? null,
+ },
+ ],
+ [countries, cities, devices, browsers, os, referers, refererUrls, urls],
+ );
+
+ return (
+ <div>
+ <div className="flex items-center gap-2">
+ <Filter.Select
+ className="w-full md:w-fit"
+ filters={filters}
+ activeFilters={activeFilters}
+ onSelect={async (key, value) => {
+ queryParams({
+ set: {
+ [key]: value,
+ },
+ del: "page",
+ });
+ }}
+ onRemove={(key) =>
+ queryParams({
+ del: key === "link" ? ["domain", "key"] : key,
+ })
+ }
+ onOpenFilter={(key) =>
+ setRequestedFilters((rf) => (rf.includes(key) ? rf : [...rf, key]))
+ }
+ />
+ <DateRangePicker
+ className="w-full sm:min-w-[200px] md:w-fit"
+ align="start"
+ value={
+ start && end
+ ? {
+ from: start,
+ to: end,
+ }
+ : undefined
+ }
+ presetId={!start || !end ? interval ?? "24h" : undefined}
+ onChange={(range, preset) => {
+ if (preset) {
+ queryParams({
+ del: ["start", "end"],
+ set: {
+ interval: preset.id,
+ },
+ scroll: false,
+ });
+
+ return;
+ }
+
+ // Regular range
+ if (!range || !range.from || !range.to) return;
+
+ queryParams({
+ del: "interval",
+ set: {
+ start: range.from.toISOString(),
+ end: range.to.toISOString(),
+ },
+ scroll: false,
+ });
+ }}
+ presets={INTERVAL_DISPLAYS.map(({ display, value, shortcut }) => {
+ const start = INTERVAL_DATA[value].startDate;
+ const end = new Date();
+
+ return {
+ id: value,
+ label: display,
+ dateRange: {
+ from: start,
+ to: end,
+ },
+ shortcut,
+ };
+ })}
+ />
+ </div>
+ <div className={cn(activeFilters.length && "mt-3")}>
+ <Filter.List
+ filters={filters}
+ activeFilters={activeFilters}
+ onRemove={(key) =>
+ queryParams({
+ del: key === "link" ? ["domain", "key", "url"] : key,
+ scroll: false,
+ })
+ }
+ onRemoveAll={() =>
+ queryParams({
+ // Reset all filters except for date range
+ del: VALID_ANALYTICS_FILTERS.concat(["page"]).filter(
+ (f) => !["interval", "start", "end"].includes(f),
+ ),
+ scroll: false,
+ })
+ }
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/app/partners.dub.co/(dashboard)/[partnerId]/[programId]/page-client.tsx b/apps/web/app/partners.dub.co/(dashboard)/[partnerId]/[programId]/page-client.tsx
index 23a25d9029..5daa63c458 100644
--- a/apps/web/app/partners.dub.co/(dashboard)/[partnerId]/[programId]/page-client.tsx
+++ b/apps/web/app/partners.dub.co/(dashboard)/[partnerId]/[programId]/page-client.tsx
@@ -31,6 +31,8 @@ import {
} from "@dub/utils";
import { LinearGradient } from "@visx/gradient";
import { endOfDay, startOfDay, subDays } from "date-fns";
+import Link from "next/link";
+import { useParams } from "next/navigation";
import { createContext, useContext, useId, useMemo } from "react";
const ProgramOverviewContext = createContext<{
@@ -310,6 +312,7 @@ function StatCard({
title: string;
event: "clicks" | "leads" | "sales";
}) {
+ const { partnerId, programId } = useParams();
const { start, end, interval } = useContext(ProgramOverviewContext);
const { data: total } = usePartnerAnalytics({
@@ -326,7 +329,10 @@ function StatCard({
});
return (
- <div className="rounded-md border border-neutral-300 p-5">
+ <Link
+ href={`/${partnerId}/${programId}/events?event=${event}`}
+ 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">
@@ -356,7 +362,7 @@ function StatCard({
</div>
)}
</div>
- </div>
+ </Link>
);
}
diff --git a/apps/web/lib/zod/schemas/sales.ts b/apps/web/lib/zod/schemas/sales.ts
index c6eab66ff7..b56a8f1062 100644
--- a/apps/web/lib/zod/schemas/sales.ts
+++ b/apps/web/lib/zod/schemas/sales.ts
@@ -143,6 +143,7 @@ export const saleEventResponseObfuscatedSchema = saleEventResponseSchema
.pick({
click: true,
timestamp: true,
+ eventName: true,
})
.extend({
link: LinkSchema.pick({
diff --git a/apps/web/ui/analytics/analytics-provider.tsx b/apps/web/ui/analytics/analytics-provider.tsx
index 645f3692d9..2412866eae 100644
--- a/apps/web/ui/analytics/analytics-provider.tsx
+++ b/apps/web/ui/analytics/analytics-provider.tsx
@@ -39,6 +39,7 @@ export interface dashboardProps {
export const AnalyticsContext = createContext<{
basePath: string;
baseApiPath: string;
+ eventsApiPath?: string;
selectedTab: EventType;
view: AnalyticsView;
domain?: string;
@@ -54,11 +55,14 @@ export const AnalyticsContext = createContext<{
};
adminPage?: boolean;
demoPage?: boolean;
+ partnerId?: string;
+ programId?: string;
requiresUpgrade?: boolean;
dashboardProps?: dashboardProps;
}>({
basePath: "",
baseApiPath: "",
+ eventsApiPath: "",
selectedTab: "clicks",
view: "default",
domain: "",
@@ -67,6 +71,8 @@ export const AnalyticsContext = createContext<{
end: new Date(),
adminPage: false,
demoPage: false,
+ partnerId: undefined,
+ programId: undefined,
requiresUpgrade: false,
dashboardProps: undefined,
});
@@ -74,11 +80,17 @@ export const AnalyticsContext = createContext<{
export default function AnalyticsProvider({
adminPage,
demoPage,
+ partnerId,
+ programId,
dashboardProps,
+ defaultInterval = "24h",
children,
}: PropsWithChildren<{
adminPage?: boolean;
demoPage?: boolean;
+ partnerId?: string;
+ programId?: string;
+ defaultInterval?: string;
dashboardProps?: dashboardProps;
}>) {
const searchParams = useSearchParams();
@@ -117,7 +129,7 @@ export default function AnalyticsProvider({
// Only set interval if start and end are not provided
const interval =
- start || end ? undefined : searchParams?.get("interval") ?? "24h";
+ start || end ? undefined : searchParams?.get("interval") ?? defaultInterval;
const selectedTab: EventType = useMemo(() => {
if (!!adminPage && !!demoPage && !conversionEnabled && !showConversions)
@@ -141,7 +153,7 @@ export default function AnalyticsProvider({
? searchParams.get("root") === "true"
: undefined;
- const { basePath, domain, baseApiPath } = useMemo(() => {
+ const { basePath, domain, baseApiPath, eventsApiPath } = useMemo(() => {
if (adminPage) {
return {
basePath: `/analytics`,
@@ -158,6 +170,14 @@ export default function AnalyticsProvider({
return {
basePath: `/${slug}/analytics`,
baseApiPath: `/api/analytics`,
+ eventsApiPath: `/api/events`,
+ domain: domainSlug,
+ };
+ } else if (partnerId && programId) {
+ return {
+ basePath: `/api/partners/${partnerId}/programs/${programId}/analytics`,
+ baseApiPath: `/api/partners/${partnerId}/programs/${programId}/analytics`,
+ eventsApiPath: `/api/partners/${partnerId}/programs/${programId}/events`,
domain: domainSlug,
};
} else {
@@ -176,6 +196,8 @@ export default function AnalyticsProvider({
dashboardProps?.domain,
domainSlug,
key,
+ partnerId,
+ programId,
selectedTab,
]);
@@ -248,6 +270,7 @@ export default function AnalyticsProvider({
basePath, // basePath for the page (e.g. /[slug]/analytics, /share/[dashboardId])
baseApiPath, // baseApiPath for analytics API endpoints (e.g. /api/analytics)
selectedTab, // selected event tab (clicks, leads, sales)
+ eventsApiPath, // eventsApiPath for events API endpoints (e.g. /api/events)
view,
queryString,
domain: domain || undefined, // domain for the link (e.g. dub.sh, stey.me, etc.)
diff --git a/apps/web/ui/analytics/events/events-table.tsx b/apps/web/ui/analytics/events/events-table.tsx
index 9fa2583846..93a83d4924 100644
--- a/apps/web/ui/analytics/events/events-table.tsx
+++ b/apps/web/ui/analytics/events/events-table.tsx
@@ -2,7 +2,6 @@
import { editQueryString } from "@/lib/analytics/utils";
import { generateRandomName } from "@/lib/names";
-import useWorkspace from "@/lib/swr/use-workspace";
import { clickEventResponseSchema } from "@/lib/zod/schemas/clicks";
import { leadEventResponseSchema } from "@/lib/zod/schemas/leads";
import { saleEventResponseSchema } from "@/lib/zod/schemas/sales";
@@ -23,7 +22,6 @@ import {
FilterBars,
Globe,
Magnifier,
- Menu3,
QRCode,
} from "@dub/ui/src/icons";
import {
@@ -38,7 +36,7 @@ import {
import { Cell, ColumnDef } from "@tanstack/react-table";
import { Link2 } from "lucide-react";
import Link from "next/link";
-import { useContext, useEffect, useMemo } from "react";
+import { ReactNode, useContext, useEffect, useMemo } from "react";
import useSWR from "swr";
import z from "zod";
import { AnalyticsContext } from "../analytics-provider";
@@ -48,7 +46,7 @@ import EditColumnsButton from "./edit-columns-button";
import { EventsContext } from "./events-provider";
import { exampleData } from "./example-data";
import { RowMenuButton } from "./row-menu-button";
-import { eventColumns, useColumnVisibility } from "./use-column-visibility";
+import { getEventColumns, useColumnVisibility } from "./use-column-visibility";
export type EventDatum =
| z.infer<typeof clickEventResponseSchema>
@@ -83,12 +81,26 @@ const FilterButton = ({ set }: { set: Record<string, any> }) => {
);
};
-export default function EventsTable() {
- const { slug, plan, conversionEnabled } = useWorkspace();
+export default function EventsTable({
+ requiresUpgrade,
+ upgradeOverlay,
+ partners = false,
+}: {
+ requiresUpgrade?: boolean;
+ upgradeOverlay?: ReactNode;
+ partners?: boolean;
+}) {
const { searchParams, queryParams } = useRouterStuff();
const { setExportQueryString } = useContext(EventsContext);
- const { selectedTab: tab } = useContext(AnalyticsContext);
- const { columnVisibility, setColumnVisibility } = useColumnVisibility();
+ const {
+ selectedTab: tab,
+ queryString: originalQueryString,
+ eventsApiPath,
+ totalEvents,
+ } = useContext(AnalyticsContext);
+ const { columnVisibility, setColumnVisibility } = useColumnVisibility({
+ partners,
+ });
const sortBy = searchParams.get("sort") || "timestamp";
const order = searchParams.get("order") === "asc" ? "asc" : "desc";
@@ -140,35 +152,39 @@ export default function EventsTable() {
</span>
) || <span className="text-gray-400">-</span>,
},
- {
- id: "link",
- header: "Link",
- accessorKey: "link",
- minSize: 250,
- maxSize: 200,
- meta: {
- filterParams: ({ getValue }) => ({
- domain: getValue().domain,
- key: getValue().key,
- }),
- },
- cell: ({ getValue }) => (
- <div className="flex items-center gap-3">
- <LinkLogo
- apexDomain={getApexDomain(getValue().url)}
- className="size-4 shrink-0 sm:size-4"
- />
- <CopyText
- value={getValue().shortLink}
- successMessage="Copied link to clipboard!"
- >
- <span className="truncate" title={getValue().shortLink}>
- {getPrettyUrl(getValue().shortLink)}
- </span>
- </CopyText>
- </div>
- ),
- },
+ ...(!partners
+ ? [
+ {
+ id: "link",
+ header: "Link",
+ accessorKey: "link",
+ minSize: 250,
+ maxSize: 200,
+ meta: {
+ filterParams: ({ getValue }) => ({
+ domain: getValue().domain,
+ key: getValue().key,
+ }),
+ },
+ cell: ({ getValue }) => (
+ <div className="flex items-center gap-3">
+ <LinkLogo
+ apexDomain={getApexDomain(getValue().url)}
+ className="size-4 shrink-0 sm:size-4"
+ />
+ <CopyText
+ value={getValue().shortLink}
+ successMessage="Copied link to clipboard!"
+ >
+ <span className="truncate" title={getValue().shortLink}>
+ {getPrettyUrl(getValue().shortLink)}
+ </span>
+ </CopyText>
+ </div>
+ ),
+ },
+ ]
+ : []),
{
id: "customer",
header: "Customer",
@@ -411,18 +427,22 @@ export default function EventsTable() {
),
},
// Sale invoice ID
- {
- id: "invoiceId",
- header: "Invoice ID",
- accessorKey: "sale.invoiceId",
- maxSize: 200,
- cell: ({ getValue }) =>
- (
- <span className="truncate" title={getValue()}>
- {getValue()}
- </span>
- ) || <span className="text-gray-400">-</span>,
- },
+ ...(!partners
+ ? [
+ {
+ id: "invoiceId",
+ header: "Invoice ID",
+ accessorKey: "sale.invoiceId",
+ maxSize: 200,
+ cell: ({ getValue }) =>
+ (
+ <span className="truncate" title={getValue()}>
+ {getValue()}
+ </span>
+ ) || <span className="text-gray-400">-</span>,
+ },
+ ]
+ : []),
// Date
{
id: "timestamp",
@@ -464,15 +484,15 @@ export default function EventsTable() {
header: ({ table }) => <EditColumnsButton table={table} />,
cell: ({ row }) => <RowMenuButton row={row} />,
},
- ].filter((c) => c.id === "menu" || eventColumns[tab].all.includes(c.id)),
+ ].filter(
+ (c) =>
+ c.id === "menu" || getEventColumns(partners)[tab].all.includes(c.id),
+ ),
[tab],
);
const { pagination, setPagination } = usePagination();
- const { queryString: originalQueryString, totalEvents } =
- useContext(AnalyticsContext);
-
const queryString = useMemo(
() =>
editQueryString(originalQueryString, {
@@ -502,11 +522,8 @@ export default function EventsTable() {
[setExportQueryString, queryString, columnVisibility, tab],
);
- const needsHigherPlan =
- (plan === "free" || plan === "pro") && !conversionEnabled;
-
const { data, isLoading, error } = useSWR<EventDatum[]>(
- !needsHigherPlan && `/api/events?${queryString}`,
+ !requiresUpgrade && `${eventsApiPath || "/api/events"}?${queryString}`,
fetcher,
{
keepPreviousData: true,
@@ -514,13 +531,13 @@ export default function EventsTable() {
);
const { table, ...tableProps } = useTable({
- data: (data ?? (needsHigherPlan ? exampleData[tab] : [])) as EventDatum[],
+ data: (data ?? (requiresUpgrade ? exampleData[tab] : [])) as EventDatum[],
loading: isLoading,
- error: error && !needsHigherPlan ? "Failed to fetch events." : undefined,
+ error: error && !requiresUpgrade ? "Failed to fetch events." : undefined,
columns,
pagination,
onPaginationChange: setPagination,
- rowCount: needsHigherPlan ? 0 : totalEvents?.[tab] ?? 0,
+ rowCount: requiresUpgrade ? 0 : totalEvents?.[tab] ?? 0,
columnVisibility: columnVisibility[tab],
onColumnVisibilityChange: (args) => setColumnVisibility(tab, args),
sortableColumns: ["timestamp"],
@@ -557,19 +574,12 @@ export default function EventsTable() {
<Table
{...tableProps}
table={table}
- scrollWrapperClassName={needsHigherPlan ? "overflow-x-hidden" : undefined}
+ scrollWrapperClassName={requiresUpgrade ? "overflow-x-hidden" : undefined}
>
- {needsHigherPlan && (
+ {requiresUpgrade && (
<>
<div className="absolute inset-0 flex touch-pan-y items-center justify-center bg-gradient-to-t from-[#fff_70%] to-[#fff6]">
- <EmptyState
- icon={Menu3}
- title="Real-time Events Stream"
- description={`Want more data on your link ${tab === "clicks" ? "clicks & QR code scans" : tab}? Upgrade to our Business Plan to get a detailed, real-time stream of events in your workspace.`}
- learnMore="https://d.to/events"
- buttonText="Upgrade to Business"
- buttonLink={`/${slug}/upgrade`}
- />
+ {upgradeOverlay}
</div>
<div className="h-[400px]" />
</>
diff --git a/apps/web/ui/analytics/events/events-tabs.tsx b/apps/web/ui/analytics/events/events-tabs.tsx
index 2d8f24ad8e..c0da547aa1 100644
--- a/apps/web/ui/analytics/events/events-tabs.tsx
+++ b/apps/web/ui/analytics/events/events-tabs.tsx
@@ -1,6 +1,5 @@
import { AnalyticsResponseOptions } from "@/lib/analytics/types";
import { editQueryString } from "@/lib/analytics/utils";
-import useWorkspace from "@/lib/swr/use-workspace";
import { MiniAreaChart } from "@dub/blocks";
import { CountingNumbers, useMediaQuery, useRouterStuff } from "@dub/ui";
import { capitalize, cn, fetcher } from "@dub/utils";
@@ -17,14 +16,17 @@ type TimeseriesData = {
saleAmount: number;
}[];
-export default function EventsTabs() {
+export default function EventsTabs({
+ conversionEnabled,
+}: {
+ conversionEnabled?: boolean;
+}) {
const { searchParams, queryParams } = useRouterStuff();
const { isMobile } = useMediaQuery();
const tab = searchParams.get("event") || "clicks";
const { demoPage } = useContext(AnalyticsContext);
- const { conversionEnabled } = useWorkspace();
const { baseApiPath, queryString, requiresUpgrade } =
useContext(AnalyticsContext);
diff --git a/apps/web/ui/analytics/events/index.tsx b/apps/web/ui/analytics/events/index.tsx
index 6dbba971f0..6d33b9341d 100644
--- a/apps/web/ui/analytics/events/index.tsx
+++ b/apps/web/ui/analytics/events/index.tsx
@@ -1,7 +1,10 @@
"use client";
-import { useRouterStuff } from "@dub/ui";
-import AnalyticsProvider from "../analytics-provider";
+import useWorkspace from "@/lib/swr/use-workspace";
+import EmptyState from "@/ui/shared/empty-state";
+import { Menu3 } from "@dub/ui/src/icons";
+import { useContext } from "react";
+import AnalyticsProvider, { AnalyticsContext } from "../analytics-provider";
import Toggle from "../toggle";
import EventsTable from "./events-table";
import EventsTabs from "./events-tabs";
@@ -17,18 +20,42 @@ export default function AnalyticsEvents({
adminPage?: boolean;
demoPage?: boolean;
}) {
- const { searchParams } = useRouterStuff();
- const event = searchParams.get("event");
+ const { conversionEnabled } = useWorkspace();
return (
<AnalyticsProvider {...{ staticDomain, staticUrl, adminPage, demoPage }}>
<div className="pb-10">
<Toggle page="events" />
<div className="mx-auto flex max-w-screen-xl flex-col gap-3 px-3 lg:px-10">
- <EventsTabs />
- <EventsTable key={event} />
+ <EventsTabs conversionEnabled={conversionEnabled} />
+ <EventsTableContainer />
</div>
</div>
</AnalyticsProvider>
);
}
+
+function EventsTableContainer() {
+ const { selectedTab } = useContext(AnalyticsContext);
+ const { plan, slug, conversionEnabled } = useWorkspace();
+
+ const requiresUpgrade =
+ (plan === "free" || plan === "pro") && !conversionEnabled;
+
+ return (
+ <EventsTable
+ key={selectedTab}
+ requiresUpgrade={requiresUpgrade}
+ upgradeOverlay={
+ <EmptyState
+ icon={Menu3}
+ title="Real-time Events Stream"
+ description={`Want more data on your link ${selectedTab === "clicks" ? "clicks & QR code scans" : selectedTab}? Upgrade to our Business Plan to get a detailed, real-time stream of events in your workspace.`}
+ learnMore="https://d.to/events"
+ buttonText="Upgrade to Business"
+ buttonLink={`/${slug}/upgrade`}
+ />
+ }
+ />
+ );
+}
diff --git a/apps/web/ui/analytics/events/use-column-visibility.ts b/apps/web/ui/analytics/events/use-column-visibility.ts
index bdb4738a83..d2a4ee9df6 100644
--- a/apps/web/ui/analytics/events/use-column-visibility.ts
+++ b/apps/web/ui/analytics/events/use-column-visibility.ts
@@ -2,14 +2,15 @@ import { EventType } from "@/lib/analytics/types";
import { useLocalStorage } from "@dub/ui";
import { VisibilityState } from "@tanstack/react-table";
-export const eventColumns: Record<
- EventType,
- { all: string[]; defaultVisible: string[] }
-> = {
+export const getEventColumns: (
+ partners?: boolean,
+) => Record<EventType, { all: string[]; defaultVisible: string[] }> = (
+ partners,
+) => ({
clicks: {
all: [
"trigger",
- "link",
+ ...(!partners ? ["link"] : []),
"continent",
"country",
"city",
@@ -21,12 +22,19 @@ export const eventColumns: Record<
"ip",
"timestamp",
],
- defaultVisible: ["trigger", "link", "country", "device", "timestamp"],
+ defaultVisible: [
+ "trigger",
+ ...(!partners ? ["link"] : []),
+ "country",
+ "device",
+ ...(partners ? ["refererUrl"] : []),
+ "timestamp",
+ ],
},
leads: {
all: [
"event",
- "link",
+ ...(!partners ? ["link"] : []),
"customer",
"continent",
"country",
@@ -41,7 +49,7 @@ export const eventColumns: Record<
],
defaultVisible: [
"event",
- "link",
+ ...(!partners ? ["link"] : []),
"customer",
"country",
"device",
@@ -52,8 +60,7 @@ export const eventColumns: Record<
all: [
"event",
"customer",
- "invoiceId",
- "link",
+ ...(!partners ? ["link", "invoiceId"] : []),
"continent",
"country",
"city",
@@ -68,30 +75,33 @@ export const eventColumns: Record<
],
defaultVisible: [
"event",
- "link",
+ ...(!partners ? ["link"] : []),
"customer",
"country",
"saleAmount",
"timestamp",
],
},
-};
+});
-const getDefaultColumnVisibility = (tab: EventType) =>
- Object.fromEntries(
- eventColumns[tab].all.map((id) => [
- id,
- eventColumns[tab].defaultVisible.includes(id),
- ]),
+const getDefaultColumnVisibility = (tab: EventType, partners?: boolean) => {
+ const columns = getEventColumns(partners)[tab];
+ return Object.fromEntries(
+ columns.all.map((id) => [id, columns.defaultVisible.includes(id)]),
);
+};
-export function useColumnVisibility() {
+export function useColumnVisibility({
+ partners,
+}: {
+ partners?: boolean;
+} = {}) {
const [columnVisibility, setColumnVisibility] = useLocalStorage<
Record<EventType, VisibilityState>
>("events-columns", {
- clicks: getDefaultColumnVisibility("clicks"),
- leads: getDefaultColumnVisibility("leads"),
- sales: getDefaultColumnVisibility("sales"),
+ clicks: getDefaultColumnVisibility("clicks", partners),
+ leads: getDefaultColumnVisibility("leads", partners),
+ sales: getDefaultColumnVisibility("sales", partners),
});
return {
diff --git a/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx b/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx
index 7ca1ab79ef..02e7853326 100644
--- a/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx
+++ b/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx
@@ -194,7 +194,6 @@ function ProgramInfo() {
const copyTimeout = useRef<NodeJS.Timeout | null>(null);
const { data: analytics, loading } = usePartnerAnalytics();
- console.log(analytics);
const items = [
{