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 partner bounty submission query with filters

Kiran K69fed8f359f0
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts
index 0d296e93ad..f5f197b387 100644
--- a/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts
@@ -1,9 +1,13 @@
+import { getPartnersWithBountySubmission } from "@/lib/api/bounties/get-partners-with-bounty-submission";
import { DubApiError } from "@/lib/api/errors";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { withWorkspace } from "@/lib/auth";
-import { BountySubmissionExtendedSchema } from "@/lib/zod/schemas/bounties";
+import {
+ BountySubmissionExtendedSchema,
+ getBountySubmissionsQuerySchema,
+} from "@/lib/zod/schemas/bounties";
import { prisma } from "@dub/prisma";
-import { Bounty, BountyGroup, BountyType } from "@dub/prisma/client";
+import { Bounty, BountyType } from "@dub/prisma/client";
import { NextResponse } from "next/server";
import { z } from "zod";
@@ -11,33 +15,44 @@ import { z } from "zod";
// Add filter, pagination
// GET /api/bounties/[bountyId]/submissions - get all submissions for a bounty
-export const GET = withWorkspace(async ({ workspace, params }) => {
- const { bountyId } = params;
- const programId = getDefaultProgramIdOrThrow(workspace);
+export const GET = withWorkspace(
+ async ({ workspace, params, searchParams }) => {
+ const { bountyId } = params;
+ const programId = getDefaultProgramIdOrThrow(workspace);
- const bounty = await prisma.bounty.findUniqueOrThrow({
- where: {
- id: bountyId,
- },
- include: {
- groups: true,
- },
- });
-
- if (bounty.programId !== programId) {
- throw new DubApiError({
- code: "not_found",
- message: `Bounty ${bountyId} not found.`,
+ const bounty = await prisma.bounty.findUniqueOrThrow({
+ where: {
+ id: bountyId,
+ },
+ include: {
+ groups: true,
+ },
});
- }
- const results =
- bounty.type === BountyType.submission
- ? await getSubmissions(bounty)
- : await getActivePartners(bounty);
+ if (bounty.programId !== programId) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Bounty ${bountyId} not found.`,
+ });
+ }
- return NextResponse.json(z.array(BountySubmissionExtendedSchema).parse(results));
-});
+ const filters = getBountySubmissionsQuerySchema.parse(searchParams);
+
+ const results =
+ bounty.type === BountyType.submission
+ ? await getSubmissions(bounty)
+ : await getPartnersWithBountySubmission({
+ ...filters,
+ programId: bounty.programId,
+ bountyId: bounty.id,
+ groupIds: bounty.groups.map(({ groupId }) => groupId),
+ });
+
+ return NextResponse.json(
+ z.array(BountySubmissionExtendedSchema).parse(results),
+ );
+ },
+);
// Get the submissions for a bounty of the type `submission`
async function getSubmissions(bounty: Pick<Bounty, "id">) {
@@ -73,69 +88,3 @@ async function getSubmissions(bounty: Pick<Bounty, "id">) {
return results;
}
-
-// Get active partners regardless of progress for `performance` bounties
-async function getActivePartners(bounty: Bounty & { groups: BountyGroup[] }) {
- // TODO:
- // Sort the list by the performance attribute
-
-
- const programEnrollments = await prisma.programEnrollment.findMany({
- where: {
- programId: bounty.programId,
- ...(bounty.groups.length > 0
- ? {
- groupId: {
- in: bounty.groups.map(({ groupId }) => groupId),
- },
- }
- : {}),
- status: {
- in: ["approved", "invited"],
- },
- },
- include: {
- links: true,
- partner: true,
- bountySubmissions: {
- where: {
- bountyId: bounty.id,
- },
- include: {
- user: true,
- commission: true,
- },
- },
- },
- });
-
- const results = programEnrollments.map(
- ({ links, partner, bountySubmissions, ...programEnrollment }) => {
- const { leads, conversions, saleAmount } = links?.reduce(
- (acc, link) => {
- return {
- leads: acc.leads + link.leads,
- conversions: acc.conversions + link.conversions,
- saleAmount: acc.saleAmount + link.saleAmount,
- };
- },
- { leads: 0, conversions: 0, saleAmount: 0 },
- );
-
- return {
- partner: {
- ...partner,
- ...programEnrollment,
- leads,
- conversions,
- saleAmount,
- },
- submission: bountySubmissions[0] ?? null,
- commission: bountySubmissions[0]?.commission ?? null,
- user: bountySubmissions[0]?.user ?? null,
- };
- },
- );
-
- return results;
-}
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/route.ts
index 3c8ff9ba2c..d8b87f0ca0 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/route.ts
@@ -38,8 +38,6 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {
},
});
- console.log(bounties)
-
return NextResponse.json(
z.array(BountyWithSubmissionsSchema).parse(bounties),
);
diff --git a/apps/web/lib/api/bounties/get-partners-with-bounty-submission.ts b/apps/web/lib/api/bounties/get-partners-with-bounty-submission.ts
new file mode 100644
index 0000000000..cc7802ba49
--- /dev/null
+++ b/apps/web/lib/api/bounties/get-partners-with-bounty-submission.ts
@@ -0,0 +1,110 @@
+import { getBountySubmissionsQuerySchema } from "@/lib/zod/schemas/bounties";
+import { prisma } from "@dub/prisma";
+import { Prisma } from "@prisma/client";
+import { z } from "zod";
+
+const sortColumnsMap = {
+ createdAt: "pe.createdAt",
+ leads: "totalLeads",
+ conversions: "totalConversions",
+ saleAmount: "totalSaleAmount",
+ commissions: "totalCommissions",
+};
+
+type SubmissionFilters = z.infer<typeof getBountySubmissionsQuerySchema> & {
+ programId: string;
+ bountyId: string;
+ groupIds: string[];
+};
+
+export async function getPartnersWithBountySubmission({
+ page,
+ pageSize,
+ sortBy,
+ sortOrder,
+ programId,
+ bountyId,
+ groupIds,
+}: SubmissionFilters) {
+ const rows: any[] = await prisma.$queryRaw`
+ SELECT
+ p.*,
+ bs.*,
+ pe.partnerId,
+ pe.groupId,
+ pe.status,
+ bs.id as bountySubmissionId,
+ bs.status as bountySubmissionStatus,
+ bs.createdAt as bountySubmissionCreatedAt,
+ bs.updatedAt as bountySubmissionUpdatedAt,
+ pe.totalCommissions,
+ COALESCE(metrics.totalLeads, 0) as totalLeads,
+ COALESCE(metrics.totalConversions, 0) as totalConversions,
+ COALESCE(metrics.totalSaleAmount, 0) as totalSaleAmount,
+ c.id as commissionId,
+ c.amount as commissionAmount,
+ c.earnings as commissionEarnings,
+ c.status as commissionStatus
+ FROM
+ ProgramEnrollment pe
+ INNER JOIN Partner p ON p.id = pe.partnerId
+ LEFT JOIN BountySubmission bs ON bs.partnerId = p.id AND bs.bountyId = ${bountyId}
+ LEFT JOIN Commission c ON c.id = bs.commissionId
+ LEFT JOIN (
+ SELECT
+ partnerId,
+ SUM(leads) as totalLeads,
+ SUM(conversions) as totalConversions,
+ SUM(saleAmount) as totalSaleAmount
+ FROM Link
+ WHERE programId = ${programId} AND partnerId IS NOT NULL
+ GROUP BY partnerId
+ ) metrics ON metrics.partnerId = pe.partnerId
+ WHERE
+ pe.programId = ${programId}
+ ${groupIds && groupIds.length > 0 ? Prisma.sql`AND pe.groupId IN (${Prisma.join(groupIds)})` : Prisma.sql``}
+ GROUP BY
+ p.id, pe.partnerId, pe.groupId, pe.totalCommissions, pe.status, bountySubmissionId, bountySubmissionStatus, bountySubmissionCreatedAt, bountySubmissionUpdatedAt, metrics.totalLeads, metrics.totalConversions, metrics.totalSaleAmount
+ ORDER BY ${Prisma.raw(sortColumnsMap[sortBy])} ${Prisma.raw(sortOrder)}
+ LIMIT ${pageSize} OFFSET ${(page - 1) * pageSize}`;
+
+ // return partners;
+
+ return rows.map((row) => {
+ const partner = {
+ ...row,
+ id: row.partnerId,
+ leads: Number(row.totalLeads),
+ conversions: Number(row.totalConversions),
+ saleAmount: Number(row.totalSaleAmount),
+ totalCommissions: Number(row.totalCommissions),
+ };
+
+ const submission = {
+ id: row.bountySubmissionId,
+ description: row.description,
+ urls: row.urls,
+ files: row.files,
+ status: row.status,
+ createdAt: row.bountySubmissionCreatedAt,
+ updatedAt: row.bountySubmissionUpdatedAt,
+ reviewedAt: row.reviewedAt,
+ rejectionReason: row.rejectionReason,
+ rejectionNote: row.rejectionNote,
+ };
+
+ const commission = {
+ id: row.commissionId,
+ amount: row.commissionAmount,
+ earnings: row.commissionEarnings,
+ status: row.commissionStatus,
+ };
+
+ return {
+ partner,
+ submission: submission.id ? submission : null,
+ commission: commission.id ? commission : null,
+ user: null,
+ };
+ });
+}
diff --git a/apps/web/lib/zod/schemas/bounties.ts b/apps/web/lib/zod/schemas/bounties.ts
index 90fd5426bb..94f8c44752 100644
--- a/apps/web/lib/zod/schemas/bounties.ts
+++ b/apps/web/lib/zod/schemas/bounties.ts
@@ -7,7 +7,7 @@ import { z } from "zod";
import { CommissionSchema } from "./commissions";
import { GroupSchema } from "./groups";
import { booleanQuerySchema, getPaginationQuerySchema } from "./misc";
-import { EnrolledPartnerSchema } from "./partners";
+import { EnrolledPartnerSchema, PARTNERS_MAX_PAGE_SIZE } from "./partners";
import { UserSchema } from "./users";
import { parseDateSchema } from "./utils";
import { workflowConditionSchema } from "./workflows";
@@ -151,3 +151,12 @@ export const REJECT_BOUNTY_SUBMISSION_REASONS = {
didNotMeetCriteria: "Did not meet criteria",
other: "Other",
} as const;
+
+export const getBountySubmissionsQuerySchema = z
+ .object({
+ sortBy: z
+ .enum(["createdAt", "leads", "conversions", "saleAmount", "commissions"])
+ .default("createdAt"),
+ sortOrder: z.enum(["asc", "desc"]).default("desc"),
+ })
+ .merge(getPaginationQuerySchema({ pageSize: PARTNERS_MAX_PAGE_SIZE }));