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 folder-based filtering to analytics and events endpoints

Kiran K7733f61d900b
diff --git a/apps/web/app/api/analytics/route.ts b/apps/web/app/api/analytics/route.ts
index eb8a4c936d..0cee3c2373 100644
--- a/apps/web/app/api/analytics/route.ts
+++ b/apps/web/app/api/analytics/route.ts
@@ -5,7 +5,9 @@ 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 { withWorkspace } from "@/lib/auth";
+import { getFolders } from "@/lib/folder/get-folders";
import { verifyFolderAccess } from "@/lib/folder/permissions";
+import { getPlanCapabilities } from "@/lib/plan-capabilities";
import {
analyticsPathParamsSchema,
analyticsQuerySchema,
@@ -62,6 +64,7 @@ export const GET = withWorkspace(
}
const folderIdToVerify = link?.folderId || folderId;
+
if (folderIdToVerify) {
await verifyFolderAccess({
workspace,
@@ -80,6 +83,24 @@ export const GET = withWorkspace(
throwError: true,
});
+ // If the request is not for a specific folder, find folders the user has access to + unsorted folder
+ let folderIds: string[] | undefined = undefined;
+
+ if (!folderIdToVerify) {
+ const { canManageFolderPermissions } = getPlanCapabilities(
+ workspace.plan,
+ );
+
+ if (canManageFolderPermissions) {
+ const folders = await getFolders({
+ workspaceId: workspace.id,
+ userId: session.user.id,
+ });
+
+ folderIds = folders.map((folder) => folder.id).concat("");
+ }
+ }
+
// Identify the request is from deprecated clicks endpoint
// (/api/analytics/clicks)
// (/api/analytics/count)
@@ -96,6 +117,7 @@ export const GET = withWorkspace(
workspaceId: workspace.id,
isDeprecatedClicksEndpoint,
dataAvailableFrom: workspace.createdAt,
+ folderIds,
});
return NextResponse.json(response);
diff --git a/apps/web/app/api/customers/[id]/activity/route.ts b/apps/web/app/api/customers/[id]/activity/route.ts
index 814c04d043..1fc7ff0585 100644
--- a/apps/web/app/api/customers/[id]/activity/route.ts
+++ b/apps/web/app/api/customers/[id]/activity/route.ts
@@ -1,6 +1,7 @@
import { getEvents } from "@/lib/analytics/get-events";
import { getCustomerOrThrow } from "@/lib/api/customers/get-customer-or-throw";
import { withWorkspace } from "@/lib/auth";
+import { verifyFolderAccess } from "@/lib/folder/permissions";
import { CustomerActivity, SaleEvent } from "@/lib/types";
import { customerActivityResponseSchema } from "@/lib/zod/schemas/customers";
import { prisma } from "@dub/prisma";
@@ -8,7 +9,7 @@ import { currencyFormatter, getPrettyUrl } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/customers/[id]/activity - get a customer's activity
-export const GET = withWorkspace(async ({ workspace, params }) => {
+export const GET = withWorkspace(async ({ workspace, params, session }) => {
const { id: customerId } = params;
const customer = await getCustomerOrThrow({
@@ -40,7 +41,7 @@ export const GET = withWorkspace(async ({ workspace, params }) => {
limit: 50,
}),
- prisma.link.findUnique({
+ prisma.link.findUniqueOrThrow({
where: {
id: customer.linkId!,
},
@@ -49,10 +50,20 @@ export const GET = withWorkspace(async ({ workspace, params }) => {
domain: true,
key: true,
shortLink: true,
+ folderId: true,
},
}),
]);
+ if (link.folderId) {
+ await verifyFolderAccess({
+ workspace,
+ userId: session.user.id,
+ folderId: link.folderId,
+ requiredPermission: "folders.read",
+ });
+ }
+
const activity: CustomerActivity[] = events.map((event: SaleEvent) => {
return {
timestamp: new Date(event.timestamp),
diff --git a/apps/web/app/api/events/route.ts b/apps/web/app/api/events/route.ts
index 0bb78fe2ce..b832e73512 100644
--- a/apps/web/app/api/events/route.ts
+++ b/apps/web/app/api/events/route.ts
@@ -4,7 +4,9 @@ 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 { withWorkspace } from "@/lib/auth";
+import { getFolders } from "@/lib/folder/get-folders";
import { verifyFolderAccess } from "@/lib/folder/permissions";
+import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { eventsQuerySchema } from "@/lib/zod/schemas/analytics";
import { Link } from "@dub/prisma/client";
import { NextResponse } from "next/server";
@@ -63,11 +65,30 @@ export const GET = withWorkspace(
throwError: true,
});
+ // If the request is not for a specific folder, find folders the user has access to + unsorted folder
+ let folderIds: string[] | undefined = undefined;
+
+ if (!folderIdToVerify) {
+ const { canManageFolderPermissions } = getPlanCapabilities(
+ workspace.plan,
+ );
+
+ if (canManageFolderPermissions) {
+ const folders = await getFolders({
+ workspaceId: workspace.id,
+ userId: session.user.id,
+ });
+
+ folderIds = folders.map((folder) => folder.id).concat("");
+ }
+ }
+
const response = await getEvents({
...parsedParams,
event,
...(link && { linkId: link.id }),
workspaceId: workspace.id,
+ folderIds,
});
return NextResponse.json(response);
diff --git a/apps/web/lib/analytics/get-analytics.ts b/apps/web/lib/analytics/get-analytics.ts
index 040822cab5..62afd1b197 100644
--- a/apps/web/lib/analytics/get-analytics.ts
+++ b/apps/web/lib/analytics/get-analytics.ts
@@ -98,8 +98,7 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
eventType: event,
workspaceId,
tagIds,
- // folderId: folderId || (workspaceId ? "" : undefined),
- folderIds: folderId ? [folderId] : undefined,
+ folderId: folderId || (workspaceId ? "" : undefined),
qr,
start: startDate.toISOString().replace("T", " ").replace("Z", ""),
end: endDate.toISOString().replace("T", " ").replace("Z", ""),
diff --git a/apps/web/lib/analytics/types.ts b/apps/web/lib/analytics/types.ts
index 1687c591aa..c100572638 100644
--- a/apps/web/lib/analytics/types.ts
+++ b/apps/web/lib/analytics/types.ts
@@ -34,6 +34,7 @@ export type AnalyticsFilters = z.infer<typeof analyticsQuerySchema> & {
dataAvailableFrom?: Date;
isDemo?: boolean;
isDeprecatedClicksEndpoint?: boolean;
+ folderIds?: string[];
};
export type EventsFilters = z.infer<typeof eventsQuerySchema> & {
@@ -41,6 +42,7 @@ export type EventsFilters = z.infer<typeof eventsQuerySchema> & {
dataAvailableFrom?: Date;
isDemo?: boolean;
customerId?: string;
+ folderIds?: string[];
};
const partnerAnalyticsSchema = analyticsQuerySchema
diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.ts
index ada7dd1621..bba156571c 100644
--- a/apps/web/lib/zod/schemas/analytics.ts
+++ b/apps/web/lib/zod/schemas/analytics.ts
@@ -282,6 +282,11 @@ export const eventsFilterTB = analyticsFilterTB
limit: z.coerce.number().default(PAGINATION_LIMIT),
order: z.enum(["asc", "desc"]).default("desc"),
sortBy: z.enum(["timestamp"]).default("timestamp"),
+ folderIds: z
+ .union([z.string(), z.array(z.string())])
+ .transform((v) => (Array.isArray(v) ? v : v.split(",")))
+ .optional()
+ .describe("The folder IDs to retrieve events for."),
}),
);