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.

Optimize aggregate-clicks

Steven Tey50348e3633f6
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 c3fb3d6d53..3ef2f4e925 100644
--- a/apps/web/app/(ee)/api/cron/aggregate-clicks/route.ts
+++ b/apps/web/app/(ee)/api/cron/aggregate-clicks/route.ts
@@ -1,16 +1,15 @@
import { getAnalytics } from "@/lib/analytics/get-analytics";
+import { createId } from "@/lib/api/create-id";
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
-import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
+import { analyticsResponse } from "@/lib/zod/schemas/analytics-response";
import { prisma } from "@dub/prisma";
+import { CommissionType, Prisma } from "@dub/prisma/client";
import { NextResponse } from "next/server";
+import { z } from "zod";
export const dynamic = "force-dynamic";
-/**
- * TODO: Use a cron job (similar to how we do it for usage cron) to account for the future where we have a lot of links to process
- */
-
// 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
@@ -30,98 +29,112 @@ export async function GET(req: Request) {
end.setDate(end.getDate() - 1);
end.setHours(23, 59, 59, 999);
- const clickRewards = await prisma.reward.findMany({
+ const clickRewardsWithEnrollments = await prisma.reward.findMany({
where: {
event: "click",
},
include: {
- clickEnrollments: true,
+ clickEnrollments: {
+ include: {
+ links: {
+ where: {
+ clicks: {
+ gt: 0,
+ },
+ lastClicked: {
+ gte: start, // links that were clicked on after the start date
+ },
+ },
+ },
+ },
+ },
},
});
- if (!clickRewards.length) {
+ if (!clickRewardsWithEnrollments.length) {
return NextResponse.json({
message: "No programs with click rewards found. Skipping...",
});
}
- for (const { programId, clickEnrollments, ...reward } of clickRewards) {
- const partnerIds = clickEnrollments.map(({ partnerId }) => partnerId);
-
- if (!partnerIds || partnerIds.length === 0) {
- console.log("No partnerIds found for program", { programId });
- continue;
- }
+ // getting a list of click reward program enrollments (to update total commissions later)
+ const clickEnrollments = clickRewardsWithEnrollments.flatMap(
+ ({ clickEnrollments }) => clickEnrollments,
+ );
+
+ // creating a map of link id to reward (for easy lookup later)
+ const linkRewardMap = new Map(
+ clickRewardsWithEnrollments.flatMap(({ clickEnrollments, ...reward }) =>
+ clickEnrollments.flatMap(({ links }) =>
+ links.map(({ id }) => [id, reward]),
+ ),
+ ),
+ );
+
+ // getting a list of links with clicks
+ const linkWithClicks = clickRewardsWithEnrollments.flatMap(
+ ({ clickEnrollments }) => clickEnrollments.flatMap(({ links }) => links),
+ );
+
+ // getting the actual click count for the links for the previous day
+ const linkClickStats: z.infer<(typeof analyticsResponse)["top_links"]>[] =
+ await getAnalytics({
+ event: "clicks",
+ groupBy: "top_links",
+ linkIds: linkWithClicks.map(({ id }) => id),
+ start,
+ end,
+ });
- const links = await prisma.link.findMany({
- where: {
- programId,
- partnerId: {
- in: partnerIds,
- },
- clicks: {
- gt: 0,
- },
- lastClicked: {
- gte: start, // links that were clicked on after the start date
- },
- },
- select: {
- id: true,
- programId: true,
- partnerId: true,
- },
+ if (linkClickStats.length === 0) {
+ return NextResponse.json({
+ message: "No clicks found. Skipping...",
});
+ }
- if (!links.length) {
- console.log("No links found for program", { programId });
- continue;
- }
+ // creating a list of commissions to create
+ const commissionsToCreate = linkWithClicks
+ .map(({ id, programId, partnerId }) => {
+ const linkClicks =
+ linkClickStats.find(({ id: linkId }) => linkId === id)?.clicks ?? 0;
- for (const { id: linkId, programId, partnerId } of links) {
- if (!linkId || !programId || !partnerId) {
- console.log("Invalid link", { linkId, programId, partnerId });
- continue;
- }
+ const reward = linkRewardMap.get(id);
- const { clicks: quantity } = await getAnalytics({
- linkId,
- start,
- end,
- groupBy: "count",
- event: "clicks",
- });
-
- if (!quantity || quantity === 0) {
- console.log("No clicks found for link", {
- linkId,
- programId,
- partnerId,
- });
- continue;
+ if (!programId || !partnerId || linkClicks === 0 || !reward) {
+ return null;
}
- console.log("Creating commission", {
- reward,
- event: "click",
+ return {
+ id: createId({ prefix: "cm_" }),
programId,
partnerId,
- linkId,
- quantity,
- });
-
- await createPartnerCommission({
- reward,
- event: "click",
- programId,
- partnerId,
- linkId,
- quantity,
- });
- }
- }
-
- return NextResponse.json("OK");
+ linkId: id,
+ quantity: linkClicks,
+ type: CommissionType.click,
+ amount: reward.amount,
+ earnings: reward.amount * linkClicks,
+ };
+ })
+ .filter(Boolean) as Prisma.CommissionCreateManyInput[];
+
+ console.table(commissionsToCreate);
+
+ // // Create commissions
+ // await prisma.commission.createMany({
+ // data: commissionsToCreate,
+ // });
+
+ // // Sync total commissions for each partner
+ // await Promise.allSettled(
+ // clickEnrollments.map(({ partnerId, programId }) =>
+ // syncTotalCommissions({
+ // partnerId,
+ // programId,
+ // }),
+ // ),
+ // );
+
+ return NextResponse.json(commissionsToCreate);
} catch (error) {
return handleAndReturnErrorResponse(error);
}
diff --git a/apps/web/lib/analytics/types.ts b/apps/web/lib/analytics/types.ts
index 2494a53f59..a89efd9299 100644
--- a/apps/web/lib/analytics/types.ts
+++ b/apps/web/lib/analytics/types.ts
@@ -40,6 +40,7 @@ export type AnalyticsFilters = z.infer<typeof analyticsQuerySchema> & {
dataAvailableFrom?: Date;
isDemo?: boolean;
isDeprecatedClicksEndpoint?: boolean;
+ linkIds?: string[]; // TODO: remove this once it's been added to the public API
folderIds?: string[];
isMegaFolder?: boolean;
};
diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.ts
index 6a9b6edad3..2521d82d39 100644
--- a/apps/web/lib/zod/schemas/analytics.ts
+++ b/apps/web/lib/zod/schemas/analytics.ts
@@ -87,6 +87,14 @@ export const analyticsQuerySchema = z
.describe(
"The unique ID of the short link on Dub to retrieve analytics for.",
),
+ // TODO: Add this to the public API when we can properly verify linkIds ownership in /api/analytics
+ // linkIds: z
+ // .union([z.string(), z.array(z.string())])
+ // .transform((v) => (Array.isArray(v) ? v : v.split(",")))
+ // .optional()
+ // .describe(
+ // "A list of link IDs to retrieve analytics for. Takes precidence over ",
+ // ),
externalId: z
.string()
.optional()
@@ -266,6 +274,12 @@ export const analyticsFilterTB = z
.string()
.optional()
.describe("The UTM tag to group by. Defaults to `utm_source`."),
+ // TODO: remove this once it's been added to the public API
+ 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."),
folderIds: z
.union([z.string(), z.array(z.string())])
.transform((v) => (Array.isArray(v) ? v : v.split(",")))