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.

Support filtering by multiple tags in analytics/events

Steven Teya678581fb2f5
diff --git a/apps/web/app/api/tags/route.ts b/apps/web/app/api/tags/route.ts
index 888e6ce240..d1fd0689a0 100644
--- a/apps/web/app/api/tags/route.ts
+++ b/apps/web/app/api/tags/route.ts
@@ -5,7 +5,7 @@ import { prisma } from "@/lib/prisma";
import {
TagSchema,
createTagBodySchema,
- getTagsQuerySchema,
+ getTagsQuerySchemaExtended,
} from "@/lib/zod/schemas/tags";
import { COLORS_LIST, randomBadgeColor } from "@/ui/links/tag-badge";
import { NextResponse } from "next/server";
@@ -13,8 +13,8 @@ import { NextResponse } from "next/server";
// GET /api/tags - get all tags for a workspace
export const GET = withWorkspace(
async ({ workspace, headers, searchParams }) => {
- const { search, ids, page, pageSize } =
- getTagsQuerySchema.parse(searchParams);
+ const { search, ids, page, pageSize, includeLinksCount } =
+ getTagsQuerySchemaExtended.parse(searchParams);
const tags = await prisma.tag.findMany({
where: {
@@ -34,6 +34,13 @@ export const GET = withWorkspace(
id: true,
name: true,
color: true,
+ ...(includeLinksCount && {
+ _count: {
+ select: {
+ links: true,
+ },
+ },
+ }),
},
orderBy: {
name: "asc",
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/page-client.tsx
index f5198804fc..d427e3348b 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/page-client.tsx
@@ -20,6 +20,7 @@ import {
Tooltip,
TooltipContent,
useMediaQuery,
+ useRouterStuff,
} from "@dub/ui";
import { Download, Globe, TableIcon, Tag } from "@dub/ui/src/icons";
import { useSession } from "next-auth/react";
@@ -71,6 +72,8 @@ function WorkspaceLinks() {
} = useLinkFilters();
const { isValidating } = useLinks();
+ const { getQueryString } = useRouterStuff();
+ const { isMobile } = useMediaQuery();
return (
<>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/library/tags/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/library/tags/page-client.tsx
index 6baa8bbd3f..41f6feceae 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/library/tags/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/library/tags/page-client.tsx
@@ -1,6 +1,5 @@
"use client";
-import useLinksCount from "@/lib/swr/use-links-count";
import useTags from "@/lib/swr/use-tags";
import useTagsCount from "@/lib/swr/use-tags-count";
import useWorkspace from "@/lib/swr/use-workspace";
@@ -38,20 +37,15 @@ export default function WorkspaceTagsClient() {
const { pagination, setPagination } = usePagination(TAGS_MAX_PAGE_SIZE);
const { tags, loading } = useTags({
- query: { search: search ?? "", page: pagination.pageIndex },
+ query: {
+ search: search ?? "",
+ page: pagination.pageIndex,
+ },
+ includeLinksCount: true,
});
const { data: tagsCount } = useTagsCount({
query: { search: search ?? "" },
});
- const { data: tagLinksCount } = useLinksCount<
- {
- tagId: string;
- _count: number;
- }[]
- >({
- groupBy: "tagId",
- showArchived: true,
- });
// Whether the initial tags have already loaded, for some loading states like the search box
const [initiallyLoaded, setInitiallyLoaded] = useState(false);
@@ -95,13 +89,7 @@ export default function WorkspaceTagsClient() {
>
<CardList variant="compact" loading={loading}>
{tags?.length
- ? tags.map((tag) => (
- <TagCard
- key={tag.id}
- tag={tag}
- tagsCount={tagLinksCount}
- />
- ))
+ ? tags.map((tag) => <TagCard key={tag.id} tag={tag} />)
: Array.from({ length: 6 }).map((_, idx) => (
<TagCardPlaceholder key={idx} />
))}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/library/tags/tag-card.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/library/tags/tag-card.tsx
index 4f179272fd..5036ed4278 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/library/tags/tag-card.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/library/tags/tag-card.tsx
@@ -27,14 +27,12 @@ import { TagsListContext } from "./page-client";
export function TagCard({
tag,
- tagsCount,
}: {
- tag: TagProps;
- tagsCount?: { tagId: string; _count: number }[];
+ tag: TagProps & { _count?: { links: number } };
}) {
const { id, slug } = useWorkspace();
- const linksCount = tagsCount?.find(({ tagId }) => tagId === tag.id)?._count;
+ const linksCount = tag._count?.links;
const { openMenuTagId, setOpenMenuTagId } = useContext(TagsListContext);
const openPopover = openMenuTagId === tag.id;
@@ -111,7 +109,7 @@ export function TagCard({
</div>
<div className="flex items-center gap-5 sm:gap-8 md:gap-12">
- {tagsCount !== undefined && (
+ {linksCount !== undefined && (
<Link
href={`/${slug}?tagIds=${tag.id}`}
className="whitespace-nowrap rounded-md border border-gray-200 bg-gray-50 px-2 py-0.5 text-sm text-gray-800 transition-colors hover:bg-gray-100"
diff --git a/apps/web/lib/analytics/get-analytics.ts b/apps/web/lib/analytics/get-analytics.ts
index 97b8e30280..1ad41fe49c 100644
--- a/apps/web/lib/analytics/get-analytics.ts
+++ b/apps/web/lib/analytics/get-analytics.ts
@@ -1,5 +1,6 @@
import { tb } from "@/lib/tinybird";
import { getDaysDifference, linkConstructor, punyEncode } from "@dub/utils";
+import { combineTagIds } from "../api/links";
import { conn } from "../planetscale";
import { prismaEdge } from "../prisma/edge";
import { tbDemo } from "../tinybird/demo-client";
@@ -26,6 +27,8 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
isDeprecatedClicksEndpoint = false,
} = params;
+ const tagIds = combineTagIds(params);
+
// get all-time clicks count if:
// 1. type is count
// 2. linkId is defined
@@ -86,7 +89,7 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
// Create a Tinybird pipe
const pipe = (isDemo ? tbDemo : tb).buildPipe({
- pipe: `v1_${groupBy}`,
+ pipe: `${groupBy === "top_links" ? "v2" : "v1"}_${groupBy}`,
parameters: analyticsFilterTB,
data: groupBy === "top_links" ? z.any() : analyticsResponse[groupBy],
});
@@ -96,6 +99,7 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
eventType: event,
workspaceId,
qr,
+ tagIds,
start: start.toISOString().replace("T", " ").replace("Z", ""),
end: end.toISOString().replace("T", " ").replace("Z", ""),
granularity,
diff --git a/apps/web/lib/swr/use-tags.ts b/apps/web/lib/swr/use-tags.ts
index 1e0d0dc24f..1cc4f57957 100644
--- a/apps/web/lib/swr/use-tags.ts
+++ b/apps/web/lib/swr/use-tags.ts
@@ -10,13 +10,22 @@ const partialQuerySchema = getTagsQuerySchema.partial();
export default function useTags({
query,
enabled = true,
-}: { query?: z.infer<typeof partialQuerySchema>; enabled?: boolean } = {}) {
+ includeLinksCount = false,
+}: {
+ query?: z.infer<typeof partialQuerySchema>;
+ enabled?: boolean;
+ includeLinksCount?: boolean;
+} = {}) {
const { id } = useWorkspace();
const { data: tags, isValidating } = useSWR<TagProps[]>(
id &&
enabled &&
- `/api/tags?${new URLSearchParams({ workspaceId: id, ...query } as Record<string, any>).toString()}`,
+ `/api/tags?${new URLSearchParams({
+ workspaceId: id,
+ ...query,
+ includeLinksCount,
+ } as Record<string, any>).toString()}`,
fetcher,
{
dedupingInterval: 60000,
diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.ts
index 2d41fe20e5..7056f9ba82 100644
--- a/apps/web/lib/zod/schemas/analytics.ts
+++ b/apps/web/lib/zod/schemas/analytics.ts
@@ -161,7 +161,15 @@ export const analyticsQuerySchema = z.object({
tagId: z
.string()
.optional()
- .describe("The tag ID to retrieve analytics for."),
+ .describe(
+ "Deprecated. Use `tagIds` instead. The tag ID to retrieve analytics for.",
+ )
+ .openapi({ deprecated: true }),
+ tagIds: z
+ .union([z.string(), z.array(z.string())])
+ .transform((v) => (Array.isArray(v) ? v : v.split(",")))
+ .optional()
+ .describe("The tag IDs to retrieve analytics for."),
qr: booleanQuerySchema
.optional()
.describe(
@@ -208,7 +216,7 @@ export const analyticsFilterTB = z
os: true,
referer: true,
refererUrl: true,
- tagId: true,
+ tagIds: true,
url: true,
}),
);
diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.ts
index db091c7c5c..7b450e4c02 100644
--- a/apps/web/lib/zod/schemas/links.ts
+++ b/apps/web/lib/zod/schemas/links.ts
@@ -35,7 +35,7 @@ const LinksQuerySchema = z.object({
.string()
.optional()
.describe(
- "The tag ID to filter the links by. This field is deprecated – use `tagIds` instead.",
+ "Deprecated. Use `tagIds` instead. The tag ID to filter the links by.",
)
.openapi({ deprecated: true }),
tagIds: z
diff --git a/apps/web/lib/zod/schemas/tags.ts b/apps/web/lib/zod/schemas/tags.ts
index 6a7dde3aa6..4d596afdff 100644
--- a/apps/web/lib/zod/schemas/tags.ts
+++ b/apps/web/lib/zod/schemas/tags.ts
@@ -1,6 +1,6 @@
import { tagColors } from "@/lib/types";
import z from "@/lib/zod";
-import { getPaginationQuerySchema } from "./misc";
+import { booleanQuerySchema, getPaginationQuerySchema } from "./misc";
export const TAGS_MAX_PAGE_SIZE = 100;
@@ -18,6 +18,13 @@ export const getTagsQuerySchema = z
})
.merge(getPaginationQuerySchema({ pageSize: TAGS_MAX_PAGE_SIZE }));
+export const getTagsQuerySchemaExtended = getTagsQuerySchema.merge(
+ z.object({
+ // Only Dub UI uses the following query parameters
+ includeLinksCount: booleanQuerySchema.default("false"),
+ }),
+);
+
export const getTagsCountQuerySchema = getTagsQuerySchema.omit({
ids: true,
page: true,
diff --git a/apps/web/ui/layout/sidebar/app-sidebar-nav.tsx b/apps/web/ui/layout/sidebar/app-sidebar-nav.tsx
index 79f118796b..63c644c08c 100644
--- a/apps/web/ui/layout/sidebar/app-sidebar-nav.tsx
+++ b/apps/web/ui/layout/sidebar/app-sidebar-nav.tsx
@@ -2,6 +2,7 @@
import useWorkspace from "@/lib/swr/use-workspace";
import { BetaFeatures } from "@/lib/types";
+import { useRouterStuff } from "@dub/ui";
import {
Books2,
CircleInfo,
@@ -29,10 +30,11 @@ import { WorkspaceDropdown } from "./workspace-dropdown";
const NAV_AREAS: SidebarNavAreas<{
slug: string;
+ queryString: string;
flags?: Record<BetaFeatures, boolean>;
}> = {
// Top-level
- default: ({ slug }) => ({
+ default: ({ slug, queryString }) => ({
showSwitcher: true,
showNews: true,
direction: "left",
@@ -48,12 +50,12 @@ const NAV_AREAS: SidebarNavAreas<{
{
name: "Analytics",
icon: LinesY,
- href: `/${slug}/analytics`,
+ href: `/${slug}/analytics${queryString}`,
},
{
name: "Events",
icon: CursorRays,
- href: `/${slug}/events`,
+ href: `/${slug}/events${queryString}`,
},
{
name: "Settings",
@@ -192,6 +194,7 @@ export function AppSidebarNav({
const { slug } = useParams() as { slug?: string };
const pathname = usePathname();
const { flags } = useWorkspace();
+ const { getQueryString } = useRouterStuff();
const currentArea = useMemo(() => {
return pathname.startsWith("/account/settings")
@@ -205,7 +208,7 @@ export function AppSidebarNav({
<SidebarNav
areas={NAV_AREAS}
currentArea={currentArea}
- data={{ slug: slug || "", flags }}
+ data={{ slug: slug || "", queryString: getQueryString(), flags }}
toolContent={toolContent}
newsContent={newsContent}
switcher={<WorkspaceDropdown />}
diff --git a/apps/web/ui/layout/sidebar/sidebar-nav.tsx b/apps/web/ui/layout/sidebar/sidebar-nav.tsx
index c66015811f..b883c67f66 100644
--- a/apps/web/ui/layout/sidebar/sidebar-nav.tsx
+++ b/apps/web/ui/layout/sidebar/sidebar-nav.tsx
@@ -139,7 +139,10 @@ function NavItem({ item }: { item: NavItemType }) {
const pathname = usePathname();
const isActive = useMemo(() => {
- return exact ? pathname === href : pathname.startsWith(href);
+ const hrefWithoutQuery = href.split("?")[0];
+ return exact
+ ? pathname === hrefWithoutQuery
+ : pathname.startsWith(hrefWithoutQuery);
}, [pathname, href, exact]);
return (