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 support for linkIds in analytics and events APIs

Kiran Kba7c3ebd97c1
diff --git a/apps/web/app/(ee)/api/cron/aggregate-clicks/route.ts b/apps/web/app/(ee)/api/cron/aggregate-clicks/route.ts
index 56bc633ef5..252387e5d3 100644
--- a/apps/web/app/(ee)/api/cron/aggregate-clicks/route.ts
+++ b/apps/web/app/(ee)/api/cron/aggregate-clicks/route.ts
@@ -3,17 +3,14 @@ import { createId } from "@/lib/api/create-id";
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { syncTotalCommissions } from "@/lib/api/partners/sync-total-commissions";
import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
+import { analyticsResponse } from "@/lib/zod/schemas/analytics-response";
import { prisma } from "@dub/prisma";
import { CommissionType } from "@dub/prisma/client";
import { NextResponse } from "next/server";
+import { z } from "zod";
export const dynamic = "force-dynamic";
-interface ClickStats {
- link_id: string;
- clicks: number;
-}
-
// This route is used aggregate clicks events on daily basis for Program links and add to the Commission table
// Runs every day at 00:00 (0 0 * * *)
// GET /api/cron/aggregate-clicks
@@ -84,18 +81,16 @@ export async function GET(req: Request) {
const linkIds = links.map(({ id }) => id);
- // TODO:
- // TB pipes need fix
- const clickStats: ClickStats[] = await getAnalytics({
- linkIds,
- start,
- end,
- groupBy: "count",
- event: "clicks",
- });
+ const clickStats: z.infer<(typeof analyticsResponse)["top_links"]>[] =
+ await getAnalytics({
+ linkIds,
+ start,
+ end,
+ groupBy: "top_links",
+ event: "clicks",
+ });
if (clickStats.length === 0) {
- console.log(`No click stats found for links ${linkIds}`);
continue;
}
@@ -105,7 +100,7 @@ export async function GET(req: Request) {
);
const commissions = clickStats.map(
- ({ link_id: linkId, clicks: quantity }) => ({
+ ({ id: linkId, clicks: quantity }) => ({
id: createId({ prefix: "cm_" }),
programId,
partnerId: linkToPartnerMap.get(linkId)!,
diff --git a/apps/web/app/(ee)/api/events/route.ts b/apps/web/app/(ee)/api/events/route.ts
index 04b0b7487d..28ebfdcc2c 100644
--- a/apps/web/app/(ee)/api/events/route.ts
+++ b/apps/web/app/(ee)/api/events/route.ts
@@ -4,9 +4,14 @@ import { validDateRangeForPlan } from "@/lib/analytics/utils";
import { getDomainOrThrow } from "@/lib/api/domains/get-domain-or-throw";
import { getLinkOrThrow } from "@/lib/api/links/get-link-or-throw";
import { throwIfClicksUsageExceeded } from "@/lib/api/links/usage-checks";
+import { checkIfLinksHaveFolders } from "@/lib/api/links/utils/check-if-links-have-folders";
import { withWorkspace } from "@/lib/auth";
-import { verifyFolderAccess } from "@/lib/folder/permissions";
+import {
+ checkFolderPermissions,
+ verifyFolderAccess,
+} from "@/lib/folder/permissions";
import { eventsQuerySchema } from "@/lib/zod/schemas/analytics";
+import { prisma } from "@dub/prisma";
import { Folder, Link } from "@dub/prisma/client";
import { NextResponse } from "next/server";
@@ -27,14 +32,17 @@ export const GET = withWorkspace(
domain,
key,
folderId,
+ linkIds,
} = parsedParams;
- let link: Link | null = null;
-
if (domain) {
await getDomainOrThrow({ workspace, domain });
}
+ let link: Link | null = null;
+ let links: Link[] = [];
+ let folderIds: string[] | undefined = undefined;
+
if (linkId || externalId || (domain && key)) {
link = await getLinkOrThrow({
workspaceId: workspace.id,
@@ -45,9 +53,56 @@ export const GET = withWorkspace(
});
}
- const folderIdToVerify = link?.folderId || folderId;
+ // if linkIds are provided
+ // 1. Check if the links are valid
+ // 2. Check if the user has access to the folders the links are in
+ if (linkIds && linkIds.length) {
+ links = await prisma.link.findMany({
+ where: {
+ id: {
+ in: linkIds,
+ },
+ programId: workspace.id,
+ },
+ });
+
+ if (checkIfLinksHaveFolders(links)) {
+ const linkFolderIds = Array.from(
+ new Set(
+ links.map((link) => link.folderId).filter(Boolean) as string[],
+ ),
+ );
+
+ const folderPermissions = await checkFolderPermissions({
+ workspaceId: workspace.id,
+ userId: session.user.id,
+ folderIds: linkFolderIds,
+ requiredPermission: "folders.read",
+ });
+
+ links = links.filter((link) => {
+ if (!link.folderId) {
+ return true;
+ }
+ const validFolder = folderPermissions.find(
+ (folder) => folder.folderId === link.folderId,
+ );
+
+ if (!validFolder?.hasPermission) {
+ return false;
+ }
+
+ (folderIds || []).push(link.folderId);
+
+ return true;
+ });
+ }
+ }
+
+ const folderIdToVerify = link?.folderId || folderId;
let selectedFolder: Pick<Folder, "id" | "type"> | null = null;
+
if (folderIdToVerify) {
selectedFolder = await verifyFolderAccess({
workspace,
@@ -66,12 +121,14 @@ export const GET = withWorkspace(
throwError: true,
});
- const folderIds = folderIdToVerify
- ? undefined
- : await getFolderIdsToFilter({
- workspace,
- userId: session.user.id,
- });
+ if (!folderIds) {
+ folderIds = folderIdToVerify
+ ? undefined
+ : await getFolderIdsToFilter({
+ workspace,
+ userId: session.user.id,
+ });
+ }
const response = await getEvents({
...parsedParams,
diff --git a/apps/web/app/api/analytics/route.ts b/apps/web/app/api/analytics/route.ts
index 07df6fed21..801021ec84 100644
--- a/apps/web/app/api/analytics/route.ts
+++ b/apps/web/app/api/analytics/route.ts
@@ -6,14 +6,19 @@ import { getDomainOrThrow } from "@/lib/api/domains/get-domain-or-throw";
import { DubApiError } from "@/lib/api/errors";
import { getLinkOrThrow } from "@/lib/api/links/get-link-or-throw";
import { throwIfClicksUsageExceeded } from "@/lib/api/links/usage-checks";
+import { checkIfLinksHaveFolders } from "@/lib/api/links/utils/check-if-links-have-folders";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { prefixWorkspaceId } from "@/lib/api/workspace-id";
import { withWorkspace } from "@/lib/auth";
-import { verifyFolderAccess } from "@/lib/folder/permissions";
+import {
+ checkFolderPermissions,
+ verifyFolderAccess,
+} from "@/lib/folder/permissions";
import {
analyticsPathParamsSchema,
analyticsQuerySchema,
} from "@/lib/zod/schemas/analytics";
+import { prisma } from "@dub/prisma";
import { Folder, Link } from "@dub/prisma/client";
import { NextResponse } from "next/server";
@@ -45,10 +50,9 @@ export const GET = withWorkspace(
key,
folderId,
programId,
+ linkIds,
} = parsedParams;
- let link: Link | null = null;
-
event = oldEvent || event;
groupBy = oldType || groupBy;
@@ -66,6 +70,10 @@ export const GET = withWorkspace(
await getDomainOrThrow({ workspace, domain });
}
+ let link: Link | null = null;
+ let links: Link[] = [];
+ let folderIds: string[] | undefined = undefined;
+
if (linkId || externalId || (domain && key)) {
link = await getLinkOrThrow({
workspaceId: workspace.id,
@@ -76,9 +84,56 @@ export const GET = withWorkspace(
});
}
- const folderIdToVerify = link?.folderId || folderId;
+ // if linkIds are provided
+ // 1. Check if the links are valid
+ // 2. Check if the user has access to the folders the links are in
+ if (linkIds && linkIds.length) {
+ links = await prisma.link.findMany({
+ where: {
+ id: {
+ in: linkIds,
+ },
+ programId: workspace.id,
+ },
+ });
+
+ if (checkIfLinksHaveFolders(links)) {
+ const linkFolderIds = Array.from(
+ new Set(
+ links.map((link) => link.folderId).filter(Boolean) as string[],
+ ),
+ );
+
+ const folderPermissions = await checkFolderPermissions({
+ workspaceId: workspace.id,
+ userId: session.user.id,
+ folderIds: linkFolderIds,
+ requiredPermission: "folders.read",
+ });
+
+ links = links.filter((link) => {
+ if (!link.folderId) {
+ return true;
+ }
+ const validFolder = folderPermissions.find(
+ (folder) => folder.folderId === link.folderId,
+ );
+
+ if (!validFolder?.hasPermission) {
+ return false;
+ }
+
+ (folderIds || []).push(link.folderId);
+
+ return true;
+ });
+ }
+ }
+
+ const folderIdToVerify = link?.folderId || folderId;
let selectedFolder: Pick<Folder, "id" | "type"> | null = null;
+
if (folderIdToVerify) {
selectedFolder = await verifyFolderAccess({
workspace,
@@ -98,13 +153,15 @@ export const GET = withWorkspace(
});
// no need to get folder ids if we are filtering by a folder or program
- const folderIds =
- folderIdToVerify || programId
- ? undefined
- : await getFolderIdsToFilter({
- workspace,
- userId: session.user.id,
- });
+ if (!folderIds) {
+ folderIds =
+ folderIdToVerify || programId
+ ? undefined
+ : await getFolderIdsToFilter({
+ workspace,
+ userId: session.user.id,
+ });
+ }
// Identify the request is from deprecated clicks endpoint
// (/api/analytics/clicks)
diff --git a/apps/web/lib/analytics/types.ts b/apps/web/lib/analytics/types.ts
index bc9d5b7098..2494a53f59 100644
--- a/apps/web/lib/analytics/types.ts
+++ b/apps/web/lib/analytics/types.ts
@@ -42,7 +42,6 @@ export type AnalyticsFilters = z.infer<typeof analyticsQuerySchema> & {
isDeprecatedClicksEndpoint?: boolean;
folderIds?: string[];
isMegaFolder?: boolean;
- linkIds?: string[];
};
export type EventsFilters = z.infer<typeof eventsQuerySchema> & {
diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.ts
index 6a9b6edad3..522bfcb972 100644
--- a/apps/web/lib/zod/schemas/analytics.ts
+++ b/apps/web/lib/zod/schemas/analytics.ts
@@ -87,6 +87,11 @@ export const analyticsQuerySchema = z
.describe(
"The unique ID of the short link on Dub to retrieve analytics for.",
),
+ linkIds: z
+ .union([z.string(), z.array(z.string())])
+ .transform((v) => (Array.isArray(v) ? v : v.split(",")))
+ .optional()
+ .describe("The link IDs to retrieve analytics for."),
externalId: z
.string()
.optional()