The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add partner earnings sums grouped by program and by link
Rafib5b17524f277
diff --git a/apps/web/app/(ee)/api/partner-profile/earnings/top/route.ts b/apps/web/app/(ee)/api/partner-profile/earnings/top/route.tsnew file mode 100644index 0000000000..874739735f--- /dev/null+++ b/apps/web/app/(ee)/api/partner-profile/earnings/top/route.ts@@ -0,0 +1,24 @@+import { getEarningsProgramId } from "@/lib/api/partner-profile/get-earnings-program-id";+import { getPartnerTopEarnings } from "@/lib/api/partner-profile/get-partner-top-earnings";+import { withPartnerProfile } from "@/lib/auth/partner";+import { partnerProfileTopEarningsQuerySchema } from "@/lib/zod/schemas/partner-profile";+import { NextResponse } from "next/server";++// GET /api/partner-profile/earnings/top - get the programs or links with the highest earnings for a partner in a date range+export const GET = withPartnerProfile(async ({ partner, searchParams }) => {+ const { programIdOrSlug, ...filters } =+ partnerProfileTopEarningsQuerySchema.parse(searchParams);++ const programId = await getEarningsProgramId({+ partnerId: partner.id,+ programIdOrSlug,+ });++ const topEarnings = await getPartnerTopEarnings({+ partnerId: partner.id,+ programId,+ filters,+ });++ return NextResponse.json(topEarnings);+});diff --git a/apps/web/lib/api/partner-profile/get-partner-top-earnings.ts b/apps/web/lib/api/partner-profile/get-partner-top-earnings.tsnew file mode 100644index 0000000000..548ad25027--- /dev/null+++ b/apps/web/lib/api/partner-profile/get-partner-top-earnings.ts@@ -0,0 +1,136 @@+import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";+import { prisma } from "@/lib/prisma";+import {+ partnerProfileTopEarningsQuerySchema,+ PartnerProfileTopLinkEarningsSchema,+ PartnerProfileTopProgramEarningsSchema,+} from "@/lib/zod/schemas/partner-profile";+import { NETWORK_PROGRAM_ID } from "@dub/utils";+import { Prisma } from "@prisma/client";+import * as z from "zod/v4";++const programSelect = {+ id: true,+ name: true,+ slug: true,+ logo: true,+} satisfies Prisma.ProgramSelect;++export async function getPartnerTopEarnings({+ partnerId,+ programId,+ filters,+}: {+ partnerId: string;+ programId?: string; // if not provided, earnings across all programs (except the network program) are summed+ filters: Omit<+ z.infer<typeof partnerProfileTopEarningsQuerySchema>,+ "programIdOrSlug"+ >;+}) {+ const { groupBy, limit, type, status, interval, start, end, timezone } =+ filters;++ const { startDate, endDate } = getStartEndDates({+ interval,+ start,+ end,+ timezone,+ });++ const where: Prisma.CommissionWhereInput = {+ earnings: {+ not: 0,+ },+ programId: programId ?? {+ not: NETWORK_PROGRAM_ID,+ },+ partnerId,+ ...(type && { type }),+ ...(status && { status }),+ createdAt: {+ gte: startDate,+ lte: endDate,+ },+ };++ if (groupBy === "programId") {+ const sums = await prisma.commission.groupBy({+ by: ["programId"],+ where,+ _sum: {+ earnings: true,+ },+ orderBy: {+ _sum: {+ earnings: "desc",+ },+ },+ take: limit,+ });++ const programs = await prisma.program.findMany({+ where: {+ id: {+ in: sums.map(({ programId }) => programId),+ },+ },+ select: programSelect,+ });++ return z.array(PartnerProfileTopProgramEarningsSchema).parse(+ sums.flatMap(({ programId, _sum }) => {+ const program = programs.find((p) => p.id === programId);+ return program ? [{ ...program, earnings: _sum.earnings ?? 0 }] : [];+ }),+ );+ }++ const sums = await prisma.commission.groupBy({+ by: ["linkId"],+ where: {+ ...where,+ linkId: {+ not: null,+ },+ },+ _sum: {+ earnings: true,+ },+ orderBy: {+ _sum: {+ earnings: "desc",+ },+ },+ take: limit,+ });++ const links = await prisma.link.findMany({+ where: {+ id: {+ in: sums+ .map(({ linkId }) => linkId)+ .filter((id): id is string => id !== null),+ },+ },+ select: {+ id: true,+ domain: true,+ key: true,+ shortLink: true,+ url: true,+ program: {+ select: programSelect,+ },+ },+ });++ return z.array(PartnerProfileTopLinkEarningsSchema).parse(+ sums.flatMap(({ linkId, _sum }) => {+ const link = links.find((l) => l.id === linkId);+ return link?.program+ ? [{ ...link, program: link.program, earnings: _sum.earnings ?? 0 }]+ : [];+ }),+ );+}diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex 5a0ec25e19..89017e73ee 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -7,6 +7,8 @@ import {PartnerProfileCustomerSchema,PartnerProfileEarningsSchema,PartnerProfileLinkSchema,+ PartnerProfileTopLinkEarningsSchema,+ PartnerProfileTopProgramEarningsSchema,partnerSubmittedLeadsCountByStatusSchema,partnerUserSchema,} from "@/lib/zod/schemas/partner-profile";@@ -516,6 +518,14 @@ export type PartnerProfileEarningsResponse = z.infer<typeof PartnerProfileEarningsSchema>;+export type PartnerProfileTopProgramEarnings = z.infer<+ typeof PartnerProfileTopProgramEarningsSchema+>;++export type PartnerProfileTopLinkEarnings = z.infer<+ typeof PartnerProfileTopLinkEarningsSchema+>;+export type CustomerProps = z.infer<typeof CustomerSchema>;export type PartnerPlatformProps = z.infer<typeof partnerPlatformSchema>;diff --git a/apps/web/lib/zod/schemas/partner-profile.ts b/apps/web/lib/zod/schemas/partner-profile.tsindex c9bf891235..9b81ed4098 100644--- a/apps/web/lib/zod/schemas/partner-profile.ts+++ b/apps/web/lib/zod/schemas/partner-profile.ts@@ -97,13 +97,15 @@ const programIdOrSlugSchema = z"The ID or slug of the program to filter earnings by. If not provided, earnings across all programs are returned.",);+const PartnerProfileEarningsProgramSchema = ProgramSchema.pick({+ id: true,+ name: true,+ slug: true,+ logo: true,+});+export const PartnerProfileEarningsSchema = PartnerEarningsSchema.extend({- program: ProgramSchema.pick({- id: true,- name: true,- slug: true,- logo: true,- }),+ program: PartnerProfileEarningsProgramSchema,});export const partnerProfileEarningsQuerySchema =@@ -127,6 +129,46 @@ export const partnerProfileEarningsTimeseriesQuerySchema =),});+export const partnerProfileTopEarningsQuerySchema =+ partnerProfileEarningsCountQuerySchema+ .pick({+ programIdOrSlug: true,+ type: true,+ status: true,+ interval: true,+ start: true,+ end: true,+ timezone: true,+ })+ .extend({+ groupBy: z+ .enum(["programId", "linkId"])+ .describe("The field to sum the earnings by."),+ limit: z.coerce+ .number()+ .int()+ .min(1)+ .max(100)+ .default(10)+ .describe("The number of groups to return, sorted by earnings."),+ });++export const PartnerProfileTopProgramEarningsSchema =+ PartnerProfileEarningsProgramSchema.extend({+ earnings: z.number(),+ });++export const PartnerProfileTopLinkEarningsSchema = LinkSchema.pick({+ id: true,+ domain: true,+ key: true,+ shortLink: true,+ url: true,+}).extend({+ program: PartnerProfileEarningsProgramSchema,+ earnings: z.number(),+});+export const PartnerProfileLinkSchema = LinkSchema.pick({id: true,domain: true,