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 bounty submission approval and rejection endpoints (#3346)

Kiran K7ff056ea6400
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/[submissionId]/approve/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/[submissionId]/approve/route.ts
new file mode 100644
index 0000000000..19c6953127
--- /dev/null
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/[submissionId]/approve/route.ts
@@ -0,0 +1,43 @@
+import { approveBountySubmission } from "@/lib/api/bounties/approve-bounty-submission";
+import { getBountyOrThrow } from "@/lib/api/bounties/get-bounty-or-throw";
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withWorkspace } from "@/lib/auth";
+import { approveBountySubmissionBodySchema } from "@/lib/zod/schemas/bounties";
+import { NextResponse } from "next/server";
+
+// POST /api/bounties/[bountyId]/submissions/[submissionId]/approve - approve a submission
+export const POST = withWorkspace(
+ async ({ workspace, params, req, session }) => {
+ const { bountyId, submissionId } = params;
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ let body;
+ try {
+ body = await parseRequestBody(req);
+ } catch (e) {
+ // If body is empty or invalid, use empty object since body is optional
+ body = {};
+ }
+
+ const { rewardAmount } = approveBountySubmissionBodySchema.parse(body);
+
+ await getBountyOrThrow({
+ bountyId,
+ programId,
+ });
+
+ const approvedSubmission = await approveBountySubmission({
+ programId,
+ bountyId,
+ submissionId,
+ rewardAmount,
+ user: session.user,
+ });
+
+ return NextResponse.json(approvedSubmission);
+ },
+ {
+ requiredPlan: ["advanced", "enterprise"],
+ },
+);
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/[submissionId]/reject/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/[submissionId]/reject/route.ts
new file mode 100644
index 0000000000..095573f0a2
--- /dev/null
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/[submissionId]/reject/route.ts
@@ -0,0 +1,45 @@
+import { getBountyOrThrow } from "@/lib/api/bounties/get-bounty-or-throw";
+import { rejectBountySubmission } from "@/lib/api/bounties/reject-bounty-submission";
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withWorkspace } from "@/lib/auth";
+import { rejectBountySubmissionBodySchema } from "@/lib/zod/schemas/bounties";
+import { NextResponse } from "next/server";
+
+// POST /api/bounties/[bountyId]/submissions/[submissionId]/reject - reject a submission
+export const POST = withWorkspace(
+ async ({ workspace, params, req, session }) => {
+ const { bountyId, submissionId } = params;
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ let body;
+ try {
+ body = await parseRequestBody(req);
+ } catch (e) {
+ // If body is empty or invalid, use empty object since body is optional
+ body = {};
+ }
+
+ const { rejectionReason, rejectionNote } =
+ rejectBountySubmissionBodySchema.parse(body);
+
+ await getBountyOrThrow({
+ bountyId,
+ programId,
+ });
+
+ const rejectedSubmission = await rejectBountySubmission({
+ programId,
+ bountyId,
+ submissionId,
+ rejectionReason,
+ rejectionNote,
+ user: session.user,
+ });
+
+ return NextResponse.json(rejectedSubmission);
+ },
+ {
+ requiredPlan: ["advanced", "enterprise"],
+ },
+);
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/[submissionId]/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/[submissionId]/route.ts
new file mode 100644
index 0000000000..4b4d0694fd
--- /dev/null
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/[submissionId]/route.ts
@@ -0,0 +1,51 @@
+import { getBountyOrThrow } from "@/lib/api/bounties/get-bounty-or-throw";
+import { DubApiError } from "@/lib/api/errors";
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { withWorkspace } from "@/lib/auth";
+import { BountySubmissionSchema } from "@/lib/zod/schemas/bounties";
+import { prisma } from "@dub/prisma";
+import { NextResponse } from "next/server";
+
+// GET /api/bounties/[bountyId]/submissions/[submissionId] - get a single submission
+export const GET = withWorkspace(
+ async ({ workspace, params }) => {
+ const { bountyId, submissionId } = params;
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ await getBountyOrThrow({
+ bountyId,
+ programId,
+ });
+
+ const submission = await prisma.bountySubmission.findUnique({
+ where: {
+ id: submissionId,
+ },
+ include: {
+ user: true,
+ commission: true,
+ partner: true,
+ programEnrollment: true,
+ },
+ });
+
+ if (!submission) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Bounty submission ${submissionId} not found.`,
+ });
+ }
+
+ if (submission.bountyId !== bountyId) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Bounty submission ${submissionId} not found.`,
+ });
+ }
+
+ return NextResponse.json(BountySubmissionSchema.parse(submission));
+ },
+ {
+ requiredPlan: ["advanced", "enterprise"],
+ },
+);
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 6576b48e98..c50645c936 100644
--- a/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts
@@ -1,5 +1,4 @@
-import { getBountySubmissions } from "@/lib/api/bounties/get-bounty-submissions";
-import { DubApiError } from "@/lib/api/errors";
+import { getBountyOrThrow } from "@/lib/api/bounties/get-bounty-or-throw";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { withWorkspace } from "@/lib/auth";
import {
@@ -8,7 +7,6 @@ import {
} from "@/lib/zod/schemas/bounties";
import { prisma } from "@dub/prisma";
import { NextResponse } from "next/server";
-import * as z from "zod/v4";
// GET /api/bounties/[bountyId]/submissions - get all submissions for a bounty
export const GET = withWorkspace(
@@ -16,32 +14,62 @@ export const GET = withWorkspace(
const { bountyId } = params;
const programId = getDefaultProgramIdOrThrow(workspace);
- const bounty = await prisma.bounty.findUniqueOrThrow({
- where: {
- id: bountyId,
- },
+ const bounty = await getBountyOrThrow({
+ bountyId,
+ programId,
include: {
groups: true,
},
});
- if (bounty.programId !== programId) {
- throw new DubApiError({
- code: "not_found",
- message: `Bounty ${bountyId} not found.`,
- });
- }
-
- const filters = getBountySubmissionsQuerySchema.parse(searchParams);
+ const { status, groupId, partnerId, sortOrder, sortBy, page, pageSize } =
+ getBountySubmissionsQuerySchema.parse(searchParams);
- const bountySubmissions = await getBountySubmissions({
- ...filters,
- bountyId: bounty.id,
+ const submissions = await prisma.bountySubmission.findMany({
+ where: {
+ bountyId,
+ status: status ?? {
+ in: ["draft", "submitted", "approved"],
+ },
+ ...(groupId && {
+ programEnrollment: {
+ groupId,
+ },
+ }),
+ ...(partnerId && {
+ partnerId,
+ }),
+ },
+ include: {
+ user: true,
+ commission: true,
+ partner: true,
+ programEnrollment: true,
+ },
+ orderBy: {
+ [sortBy === "completedAt" ? "completedAt" : "performanceCount"]:
+ sortOrder,
+ },
+ skip: (page - 1) * pageSize,
+ take: pageSize,
});
- return NextResponse.json(
- z.array(BountySubmissionExtendedSchema).parse(bountySubmissions),
+ const bountySubmissions = submissions.map(
+ ({ partner, programEnrollment, commission, user, ...submissionData }) =>
+ BountySubmissionExtendedSchema.parse({
+ ...submissionData,
+ partner: {
+ ...partner,
+ ...(programEnrollment || {}),
+ id: partner.id,
+ status: programEnrollment?.status ?? null,
+ },
+ commission,
+ user,
+ }),
);
+
+ return NextResponse.json(bountySubmissions);
},
{
requiredPlan: [
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submissions-table.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submissions-table.tsx
index 87ba45f4fe..50781654b1 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submissions-table.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submissions-table.tsx
@@ -140,7 +140,7 @@ export function BountySubmissionsTable() {
// if the current submission is not found, return the current details sheet submission id
// and the first submission id as the previous and next submission ids
- if (currentIndex === -1) return [null, submissions[0].id];
+ if (currentIndex === -1) return [null, submissions[0]?.id ?? null];
return [
currentIndex > 0 ? submissions[currentIndex - 1].id : null,
diff --git a/apps/web/lib/actions/partners/approve-bounty-submission.ts b/apps/web/lib/actions/partners/approve-bounty-submission.ts
index 3a6c8fcdce..031701f4c7 100644
--- a/apps/web/lib/actions/partners/approve-bounty-submission.ts
+++ b/apps/web/lib/actions/partners/approve-bounty-submission.ts
@@ -1,129 +1,29 @@
"use server";
-import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
+import { approveBountySubmission } from "@/lib/api/bounties/approve-bounty-submission";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
-import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
-import { BountySubmissionSchema } from "@/lib/zod/schemas/bounties";
-import { sendEmail } from "@dub/email";
-import BountyApproved from "@dub/email/templates/bounty-approved";
-import { prisma } from "@dub/prisma";
-import { waitUntil } from "@vercel/functions";
+import { approveBountySubmissionBodySchema } from "@/lib/zod/schemas/bounties";
import * as z from "zod/v4";
import { authActionClient } from "../safe-action";
-const schema = z.object({
+const inputSchema = approveBountySubmissionBodySchema.extend({
workspaceId: z.string(),
submissionId: z.string(),
- rewardAmount: z.number().nullable(),
});
// Approve a submission for a bounty
export const approveBountySubmissionAction = authActionClient
- .inputSchema(schema)
+ .inputSchema(inputSchema)
.action(async ({ parsedInput, ctx }) => {
const { workspace, user } = ctx;
const { submissionId, rewardAmount } = parsedInput;
const programId = getDefaultProgramIdOrThrow(workspace);
- const { program, bounty, partner, ...bountySubmission } =
- await prisma.bountySubmission.findUniqueOrThrow({
- where: {
- id: submissionId,
- },
- include: {
- program: true,
- bounty: true,
- partner: true,
- },
- });
-
- if (bountySubmission.programId !== programId) {
- throw new Error("Bounty submission does not belong to this program.");
- }
-
- if (bountySubmission.status === "draft") {
- throw new Error(
- "Bounty submission is in progress and cannot be approved.",
- );
- }
-
- if (bountySubmission.status === "approved") {
- throw new Error("Bounty submission already approved.");
- }
-
- // Find the reward amount
- const finalRewardAmount = bounty.rewardAmount ?? rewardAmount;
-
- if (!finalRewardAmount) {
- throw new Error(
- "Reward amount is required to approve the bounty submission.",
- );
- }
-
- const { commission } = await createPartnerCommission({
- event: "custom",
- partnerId: bountySubmission.partnerId,
- programId: bountySubmission.programId,
- amount: finalRewardAmount,
- quantity: 1,
+ await approveBountySubmission({
+ programId,
+ submissionId,
+ rewardAmount,
user,
- description: `Commission for successfully completed "${bounty.name}" bounty.`,
});
-
- if (!commission) {
- throw new Error("Failed to create commission for the bounty submission.");
- }
-
- await prisma.bountySubmission.update({
- where: {
- id: submissionId,
- },
- data: {
- status: "approved",
- reviewedAt: new Date(),
- userId: user.id,
- rejectionNote: null,
- rejectionReason: null,
- commissionId: commission.id,
- },
- });
-
- waitUntil(
- Promise.allSettled([
- recordAuditLog({
- workspaceId: workspace.id,
- programId: program.id,
- action: "bounty_submission.approved",
- description: `Bounty submission approved for ${partner.id}`,
- actor: user,
- targets: [
- {
- type: "bounty_submission",
- id: submissionId,
- metadata: BountySubmissionSchema.parse(bountySubmission),
- },
- ],
- }),
-
- partner.email &&
- sendEmail({
- subject: "Bounty approved!",
- to: partner.email,
- variant: "notifications",
- replyTo: program.supportEmail || "noreply",
- react: BountyApproved({
- email: partner.email,
- program: {
- name: program.name,
- slug: program.slug,
- },
- bounty: {
- name: bounty.name,
- type: bounty.type,
- },
- }),
- }),
- ]),
- );
});
diff --git a/apps/web/lib/actions/partners/reject-bounty-submission.ts b/apps/web/lib/actions/partners/reject-bounty-submission.ts
index da7626910e..65e990bb0d 100644
--- a/apps/web/lib/actions/partners/reject-bounty-submission.ts
+++ b/apps/web/lib/actions/partners/reject-bounty-submission.ts
@@ -1,105 +1,30 @@
"use server";
-import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
+import { rejectBountySubmission } from "@/lib/api/bounties/reject-bounty-submission";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
-import { REJECT_BOUNTY_SUBMISSION_REASONS } from "@/lib/constants/bounties";
-import {
- BountySubmissionSchema,
- rejectBountySubmissionSchema,
-} from "@/lib/zod/schemas/bounties";
-import { sendEmail } from "@dub/email";
-import BountyRejected from "@dub/email/templates/bounty-rejected";
-import { prisma } from "@dub/prisma";
-import { waitUntil } from "@vercel/functions";
+import { rejectBountySubmissionBodySchema } from "@/lib/zod/schemas/bounties";
+import * as z from "zod/v4";
import { authActionClient } from "../safe-action";
+const inputSchema = rejectBountySubmissionBodySchema.extend({
+ workspaceId: z.string(),
+ submissionId: z.string(),
+});
+
// Reject a bounty submission
export const rejectBountySubmissionAction = authActionClient
- .inputSchema(rejectBountySubmissionSchema)
+ .inputSchema(inputSchema)
.action(async ({ parsedInput, ctx }) => {
const { workspace, user } = ctx;
const { submissionId, rejectionReason, rejectionNote } = parsedInput;
const programId = getDefaultProgramIdOrThrow(workspace);
- const { program, bounty, partner, ...bountySubmission } =
- await prisma.bountySubmission.findUniqueOrThrow({
- where: {
- id: submissionId,
- },
- include: {
- program: true,
- bounty: true,
- partner: true,
- },
- });
-
- if (bountySubmission.programId !== programId) {
- throw new Error("Bounty submission does not belong to this program.");
- }
-
- if (bountySubmission.status === "draft") {
- throw new Error(
- "Bounty submission is in progress and cannot be rejected.",
- );
- }
-
- if (bountySubmission.status === "rejected") {
- throw new Error("Bounty submission already rejected.");
- }
-
- await prisma.bountySubmission.update({
- where: {
- id: submissionId,
- },
- data: {
- status: "rejected",
- reviewedAt: new Date(),
- userId: user.id,
- rejectionReason,
- rejectionNote,
- commissionId: null,
- },
+ await rejectBountySubmission({
+ programId,
+ submissionId,
+ rejectionReason,
+ rejectionNote,
+ user,
});
-
- waitUntil(
- Promise.allSettled([
- recordAuditLog({
- workspaceId: workspace.id,
- programId: program.id,
- action: "bounty_submission.rejected",
- description: `Bounty submission rejected for ${partner.id}`,
- actor: user,
- targets: [
- {
- type: "bounty_submission",
- id: submissionId,
- metadata: BountySubmissionSchema.parse(bountySubmission),
- },
- ],
- }),
- partner.email &&
- sendEmail({
- subject: "Bounty rejected",
- to: partner.email,
- variant: "notifications",
- replyTo: program.supportEmail || "noreply",
- react: BountyRejected({
- email: partner.email,
- program: {
- name: program.name,
- slug: program.slug,
- },
- bounty: {
- name: bounty.name,
- },
- submission: {
- rejectionReason:
- REJECT_BOUNTY_SUBMISSION_REASONS[rejectionReason],
- rejectionNote,
- },
- }),
- }),
- ]),
- );
});
diff --git a/apps/web/lib/api/bounties/approve-bounty-submission.ts b/apps/web/lib/api/bounties/approve-bounty-submission.ts
new file mode 100644
index 0000000000..2f74c72667
--- /dev/null
+++ b/apps/web/lib/api/bounties/approve-bounty-submission.ts
@@ -0,0 +1,183 @@
+import { Session } from "@/lib/auth";
+import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
+import {
+ approveBountySubmissionBodySchema,
+ BountySubmissionSchema,
+} from "@/lib/zod/schemas/bounties";
+import { sendEmail } from "@dub/email";
+import BountyApproved from "@dub/email/templates/bounty-approved";
+import { prisma } from "@dub/prisma";
+import { waitUntil } from "@vercel/functions";
+import * as z from "zod/v4";
+import { recordAuditLog } from "../audit-logs/record-audit-log";
+import { DubApiError } from "../errors";
+
+interface ApproveBountySubmissionParams
+ extends z.infer<typeof approveBountySubmissionBodySchema> {
+ programId: string;
+ bountyId?: string;
+ submissionId: string;
+ user: Session["user"];
+}
+
+export async function approveBountySubmission({
+ bountyId,
+ programId,
+ submissionId,
+ rewardAmount,
+ user,
+}: ApproveBountySubmissionParams) {
+ const submission = await prisma.bountySubmission.findUnique({
+ where: {
+ id: submissionId,
+ },
+ select: {
+ programId: true,
+ partnerId: true,
+ bountyId: true,
+ status: true,
+ bounty: {
+ select: {
+ name: true,
+ type: true,
+ rewardAmount: true,
+ },
+ },
+ },
+ });
+
+ if (!submission) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Bounty submission ${submissionId} not found.`,
+ });
+ }
+
+ if (submission.programId !== programId) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Bounty submission ${submissionId} does not belong to program ${programId}.`,
+ });
+ }
+
+ if (bountyId && submission.bountyId !== bountyId) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Bounty submission ${submissionId} not found for bounty ${bountyId}.`,
+ });
+ }
+
+ if (submission.status === "draft") {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This bounty submission is in progress and cannot be approved.",
+ });
+ }
+
+ if (submission.status === "approved") {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This bounty submission has already been approved.",
+ });
+ }
+
+ const bounty = submission.bounty;
+ const finalRewardAmount = bounty.rewardAmount ?? rewardAmount;
+
+ if (!finalRewardAmount) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Reward amount is required to approve the bounty submission.",
+ });
+ }
+
+ const { commission } = await createPartnerCommission({
+ event: "custom",
+ partnerId: submission.partnerId,
+ programId: submission.programId,
+ amount: finalRewardAmount,
+ quantity: 1,
+ user,
+ description: `Commission for successfully completed "${bounty.name}" bounty.`,
+ });
+
+ if (!commission) {
+ throw new DubApiError({
+ code: "internal_server_error",
+ message: "Failed to create commission for the bounty submission.",
+ });
+ }
+
+ const approvedSubmission = await prisma.bountySubmission.update({
+ where: {
+ id: submissionId,
+ },
+ data: {
+ status: "approved",
+ reviewedAt: new Date(),
+ userId: user.id,
+ rejectionNote: null,
+ rejectionReason: null,
+ commissionId: commission.id,
+ },
+ include: {
+ partner: {
+ select: {
+ id: true,
+ email: true,
+ },
+ },
+ program: {
+ select: {
+ workspaceId: true,
+ id: true,
+ name: true,
+ slug: true,
+ supportEmail: true,
+ },
+ },
+ },
+ });
+
+ const { program, partner } = approvedSubmission;
+
+ waitUntil(
+ Promise.allSettled([
+ recordAuditLog({
+ workspaceId: program.workspaceId,
+ programId: program.id,
+ action: "bounty_submission.approved",
+ description: `Bounty submission approved for ${partner.id}`,
+ actor: user,
+ targets: [
+ {
+ type: "bounty_submission",
+ id: submissionId,
+ metadata: BountySubmissionSchema.parse(approvedSubmission),
+ },
+ ],
+ }),
+
+ partner.email &&
+ sendEmail({
+ subject: "Bounty approved!",
+ to: partner.email,
+ variant: "notifications",
+ replyTo: program.supportEmail || "noreply",
+ react: BountyApproved({
+ email: partner.email,
+ program: {
+ name: program.name,
+ slug: program.slug,
+ },
+ bounty: {
+ name: bounty.name,
+ type: bounty.type,
+ },
+ }),
+ }),
+ ]),
+ );
+
+ return BountySubmissionSchema.parse(approvedSubmission);
+}
diff --git a/apps/web/lib/api/bounties/get-bounty-or-throw.ts b/apps/web/lib/api/bounties/get-bounty-or-throw.ts
new file mode 100644
index 0000000000..de944cb09c
--- /dev/null
+++ b/apps/web/lib/api/bounties/get-bounty-or-throw.ts
@@ -0,0 +1,40 @@
+import { prisma } from "@dub/prisma";
+import { Prisma } from "@dub/prisma/client";
+import { DubApiError } from "../errors";
+
+interface GetBountyOrThrowParams<T extends Prisma.BountyInclude = {}> {
+ programId: string;
+ bountyId: string;
+ include?: T;
+}
+
+export async function getBountyOrThrow<T extends Prisma.BountyInclude = {}>({
+ programId,
+ bountyId,
+ include,
+}: GetBountyOrThrowParams<T>): Promise<
+ Prisma.BountyGetPayload<{ include: T }>
+> {
+ const bounty = await prisma.bounty.findUnique({
+ where: {
+ id: bountyId,
+ },
+ include,
+ });
+
+ if (!bounty) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Bounty ${bountyId} not found.`,
+ });
+ }
+
+ if (bounty.programId !== programId) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Bounty ${bountyId} not found.`,
+ });
+ }
+
+ return bounty as Prisma.BountyGetPayload<{ include: T }>;
+}
diff --git a/apps/web/lib/api/bounties/get-bounty-submissions.ts b/apps/web/lib/api/bounties/get-bounty-submissions.ts
deleted file mode 100644
index d8f4eff8ef..0000000000
--- a/apps/web/lib/api/bounties/get-bounty-submissions.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { BountySubmissionsQueryFilters } from "@/lib/types";
-import { prisma } from "@dub/prisma";
-
-interface GetBountySubmissionsParams extends BountySubmissionsQueryFilters {
- bountyId: string;
-}
-
-// Get list of submissions for a given bounty
-export async function getBountySubmissions({
- bountyId,
- status,
- groupId,
- partnerId,
- sortOrder,
- sortBy,
- page,
- pageSize,
-}: GetBountySubmissionsParams) {
- const submissions = await prisma.bountySubmission.findMany({
- where: {
- bountyId,
- status: status ?? {
- in: ["draft", "submitted", "approved"],
- },
- ...(groupId && {
- programEnrollment: {
- groupId,
- },
- }),
- ...(partnerId && {
- partnerId,
- }),
- },
- include: {
- user: true,
- commission: true,
- partner: true,
- programEnrollment: true,
- },
- orderBy: {
- [sortBy === "completedAt" ? "completedAt" : "performanceCount"]:
- sortOrder,
- },
- skip: (page - 1) * pageSize,
- take: pageSize,
- });
-
- return submissions.map(
- ({ partner, programEnrollment, commission, user, ...submission }) => {
- return {
- ...submission,
- partner: {
- ...partner,
- ...programEnrollment,
- id: partner.id,
- status: programEnrollment?.status,
- },
- commission,
- user,
- };
- },
- );
-}
diff --git a/apps/web/lib/api/bounties/reject-bounty-submission.ts b/apps/web/lib/api/bounties/reject-bounty-submission.ts
new file mode 100644
index 0000000000..916b5d071c
--- /dev/null
+++ b/apps/web/lib/api/bounties/reject-bounty-submission.ts
@@ -0,0 +1,168 @@
+import { Session } from "@/lib/auth";
+import { REJECT_BOUNTY_SUBMISSION_REASONS } from "@/lib/constants/bounties";
+import {
+ BountySubmissionSchema,
+ rejectBountySubmissionBodySchema,
+} from "@/lib/zod/schemas/bounties";
+import { sendEmail } from "@dub/email";
+import BountyRejected from "@dub/email/templates/bounty-rejected";
+import { prisma } from "@dub/prisma";
+import { waitUntil } from "@vercel/functions";
+import * as z from "zod/v4";
+import { recordAuditLog } from "../audit-logs/record-audit-log";
+import { DubApiError } from "../errors";
+
+interface RejectBountySubmissionParams
+ extends z.infer<typeof rejectBountySubmissionBodySchema> {
+ bountyId?: string;
+ programId: string;
+ submissionId: string;
+ user: Session["user"];
+}
+
+export async function rejectBountySubmission({
+ programId,
+ bountyId,
+ submissionId,
+ rejectionReason = "other",
+ rejectionNote,
+ user,
+}: RejectBountySubmissionParams) {
+ const submission = await prisma.bountySubmission.findUnique({
+ where: {
+ id: submissionId,
+ },
+ select: {
+ programId: true,
+ bountyId: true,
+ status: true,
+ bounty: {
+ select: {
+ name: true,
+ },
+ },
+ },
+ });
+
+ if (!submission) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Bounty submission ${submissionId} not found.`,
+ });
+ }
+
+ if (submission.programId !== programId) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Bounty submission ${submissionId} does not belong to program ${programId}.`,
+ });
+ }
+
+ if (bountyId && submission.bountyId !== bountyId) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Bounty submission ${submissionId} not found for bounty ${bountyId}.`,
+ });
+ }
+
+ if (submission.status === "draft") {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This bounty submission is in progress and cannot be rejected.",
+ });
+ }
+
+ if (submission.status === "rejected") {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This bounty submission has already been rejected.",
+ });
+ }
+
+ if (submission.status === "approved") {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "This bounty submission has already been approved and cannot be rejected.",
+ });
+ }
+
+ const bounty = submission.bounty;
+
+ const rejectedSubmission = await prisma.bountySubmission.update({
+ where: {
+ id: submissionId,
+ },
+ data: {
+ status: "rejected",
+ reviewedAt: new Date(),
+ userId: user.id,
+ rejectionReason,
+ rejectionNote,
+ commissionId: null,
+ },
+ include: {
+ partner: {
+ select: {
+ id: true,
+ email: true,
+ },
+ },
+ program: {
+ select: {
+ workspaceId: true,
+ id: true,
+ name: true,
+ slug: true,
+ supportEmail: true,
+ },
+ },
+ },
+ });
+
+ const { program, partner } = rejectedSubmission;
+
+ waitUntil(
+ Promise.allSettled([
+ recordAuditLog({
+ workspaceId: program.workspaceId,
+ programId: program.id,
+ action: "bounty_submission.rejected",
+ description: `Bounty submission rejected for ${partner.id}`,
+ actor: user,
+ targets: [
+ {
+ type: "bounty_submission",
+ id: submissionId,
+ metadata: BountySubmissionSchema.parse(rejectedSubmission),
+ },
+ ],
+ }),
+
+ partner.email &&
+ sendEmail({
+ subject: "Bounty rejected",
+ to: partner.email,
+ variant: "notifications",
+ replyTo: program.supportEmail || "noreply",
+ react: BountyRejected({
+ email: partner.email,
+ program: {
+ name: program.name,
+ slug: program.slug,
+ },
+ bounty: {
+ name: bounty.name,
+ },
+ submission: {
+ rejectionReason:
+ REJECT_BOUNTY_SUBMISSION_REASONS[rejectionReason],
+ rejectionNote,
+ },
+ }),
+ }),
+ ]),
+ );
+
+ return BountySubmissionSchema.parse(rejectedSubmission);
+}
diff --git a/apps/web/lib/openapi/bounties/approve-bounty-submission.ts b/apps/web/lib/openapi/bounties/approve-bounty-submission.ts
new file mode 100644
index 0000000000..993b4ddb80
--- /dev/null
+++ b/apps/web/lib/openapi/bounties/approve-bounty-submission.ts
@@ -0,0 +1,41 @@
+import { openApiErrorResponses } from "@/lib/openapi/responses";
+import {
+ approveBountySubmissionBodySchema,
+ BountySubmissionSchema,
+} from "@/lib/zod/schemas/bounties";
+import { ZodOpenApiOperationObject } from "zod-openapi";
+import * as z from "zod/v4";
+
+export const approveBountySubmission: ZodOpenApiOperationObject = {
+ operationId: "approveBountySubmission",
+ "x-speakeasy-name-override": "approveSubmission",
+ summary: "Approve a bounty submission",
+ description:
+ "Approve a bounty submission. Optionally specify a custom reward amount.",
+ requestParams: {
+ path: z.object({
+ bountyId: z.string(),
+ submissionId: z.string(),
+ }),
+ },
+ requestBody: {
+ content: {
+ "application/json": {
+ schema: approveBountySubmissionBodySchema.optional(),
+ },
+ },
+ },
+ responses: {
+ "200": {
+ description: "The approved bounty submission.",
+ content: {
+ "application/json": {
+ schema: BountySubmissionSchema,
+ },
+ },
+ },
+ ...openApiErrorResponses,
+ },
+ tags: ["Bounties"],
+ security: [{ token: [] }],
+};
diff --git a/apps/web/lib/openapi/bounties/get-bounty-submission.ts b/apps/web/lib/openapi/bounties/get-bounty-submission.ts
new file mode 100644
index 0000000000..2a5142cb31
--- /dev/null
+++ b/apps/web/lib/openapi/bounties/get-bounty-submission.ts
@@ -0,0 +1,30 @@
+import { openApiErrorResponses } from "@/lib/openapi/responses";
+import { BountySubmissionSchema } from "@/lib/zod/schemas/bounties";
+import { ZodOpenApiOperationObject } from "zod-openapi";
+import * as z from "zod/v4";
+
+export const getBountySubmission: ZodOpenApiOperationObject = {
+ operationId: "getBountySubmission",
+ "x-speakeasy-name-override": "getSubmission",
+ summary: "Get a bounty submission",
+ description: "Retrieve a specific bounty submission by ID.",
+ requestParams: {
+ path: z.object({
+ bountyId: z.string(),
+ submissionId: z.string(),
+ }),
+ },
+ responses: {
+ "200": {
+ description: "The bounty submission.",
+ content: {
+ "application/json": {
+ schema: BountySubmissionSchema,
+ },
+ },
+ },
+ ...openApiErrorResponses,
+ },
+ tags: ["Bounties"],
+ security: [{ token: [] }],
+};
diff --git a/apps/web/lib/openapi/bounties/index.ts b/apps/web/lib/openapi/bounties/index.ts
new file mode 100644
index 0000000000..6f3d0bb173
--- /dev/null
+++ b/apps/web/lib/openapi/bounties/index.ts
@@ -0,0 +1,20 @@
+import { ZodOpenApiPathsObject } from "zod-openapi";
+import { approveBountySubmission } from "./approve-bounty-submission";
+import { getBountySubmission } from "./get-bounty-submission";
+import { listBountySubmissions } from "./list-bounty-submissions";
+import { rejectBountySubmission } from "./reject-bounty-submission";
+
+export const bountiesPaths: ZodOpenApiPathsObject = {
+ "/bounties/{bountyId}/submissions": {
+ get: listBountySubmissions,
+ },
+ "/bounties/{bountyId}/submissions/{submissionId}": {
+ get: getBountySubmission,
+ },
+ "/bounties/{bountyId}/submissions/{submissionId}/approve": {
+ post: approveBountySubmission,
+ },
+ "/bounties/{bountyId}/submissions/{submissionId}/reject": {
+ post: rejectBountySubmission,
+ },
+};
diff --git a/apps/web/lib/openapi/bounties/list-bounty-submissions.ts b/apps/web/lib/openapi/bounties/list-bounty-submissions.ts
new file mode 100644
index 0000000000..f672abb587
--- /dev/null
+++ b/apps/web/lib/openapi/bounties/list-bounty-submissions.ts
@@ -0,0 +1,33 @@
+import { openApiErrorResponses } from "@/lib/openapi/responses";
+import {
+ BountySubmissionSchema,
+ getBountySubmissionsQuerySchema,
+} from "@/lib/zod/schemas/bounties";
+import { ZodOpenApiOperationObject } from "zod-openapi";
+import * as z from "zod/v4";
+
+export const listBountySubmissions: ZodOpenApiOperationObject = {
+ operationId: "listBountySubmissions",
+ "x-speakeasy-name-override": "listSubmissions",
+ summary: "List bounty submissions",
+ description: "List all submissions for a specific bounty.",
+ requestParams: {
+ path: z.object({
+ bountyId: z.string(),
+ }),
+ query: getBountySubmissionsQuerySchema,
+ },
+ responses: {
+ "200": {
+ description: "The list of bounty submissions.",
+ content: {
+ "application/json": {
+ schema: z.array(BountySubmissionSchema),
+ },
+ },
+ },
+ ...openApiErrorResponses,
+ },
+ tags: ["Bounties"],
+ security: [{ token: [] }],
+};
diff --git a/apps/web/lib/openapi/bounties/reject-bounty-submission.ts b/apps/web/lib/openapi/bounties/reject-bounty-submission.ts
new file mode 100644
index 0000000000..f8565559a2
--- /dev/null
+++ b/apps/web/lib/openapi/bounties/reject-bounty-submission.ts
@@ -0,0 +1,41 @@
+import { openApiErrorResponses } from "@/lib/openapi/responses";
+import {
+ BountySubmissionSchema,
+ rejectBountySubmissionBodySchema,
+} from "@/lib/zod/schemas/bounties";
+import { ZodOpenApiOperationObject } from "zod-openapi";
+import * as z from "zod/v4";
+
+export const rejectBountySubmission: ZodOpenApiOperationObject = {
+ operationId: "rejectBountySubmission",
+ "x-speakeasy-name-override": "rejectSubmission",
+ summary: "Reject a bounty submission",
+ description:
+ "Reject a bounty submission with a specified reason and optional note.",
+ requestParams: {
+ path: z.object({
+ bountyId: z.string(),
+ submissionId: z.string(),
+ }),
+ },
+ requestBody: {
+ content: {
+ "application/json": {
+ schema: rejectBountySubmissionBodySchema.optional(),
+ },
+ },
+ },
+ responses: {
+ "200": {
+ description: "The rejected bounty submission.",
+ content: {
+ "application/json": {
+ schema: BountySubmissionSchema,
+ },
+ },
+ },
+ ...openApiErrorResponses,
+ },
+ tags: ["Bounties"],
+ security: [{ token: [] }],
+};
diff --git a/apps/web/lib/openapi/index.ts b/apps/web/lib/openapi/index.ts
index 38d2c79c06..f4c0c038ee 100644
--- a/apps/web/lib/openapi/index.ts
+++ b/apps/web/lib/openapi/index.ts
@@ -6,6 +6,7 @@ import { LinkErrorSchema, LinkSchema } from "../zod/schemas/links";
import { LinkTagSchema } from "../zod/schemas/tags";
import { WorkspaceSchema } from "../zod/schemas/workspaces";
import { analyticsPath } from "./analytics";
+import { bountiesPaths } from "./bounties";
import { commissionsPaths } from "./commissions";
import { customersPaths } from "./customers";
import { domainsPaths } from "./domains";
@@ -57,6 +58,7 @@ export const document = createDocument({
...workspacesPaths,
...embedTokensPaths,
...qrCodePaths,
+ ...bountiesPaths,
},
components: {
schemas: {
diff --git a/apps/web/lib/zod/schemas/bounties.ts b/apps/web/lib/zod/schemas/bounties.ts
index e984a9eeb6..5a37ed8783 100644
--- a/apps/web/lib/zod/schemas/bounties.ts
+++ b/apps/web/lib/zod/schemas/bounties.ts
@@ -119,15 +119,17 @@ export const BountyListSchema = BountySchema.extend({
.optional(),
});
+// used in GET /bounties/{bountyId}/submissions
export const BountySubmissionSchema = z.object({
id: z.string(),
+ bountyId: z.string(),
+ partnerId: z.string(),
description: z.string().nullable(),
urls: z.array(z.string()).nullable(),
files: z.array(BountySubmissionFileSchema).nullable(),
status: z.enum(BountySubmissionStatus),
performanceCount: z.number().nullable(),
createdAt: z.date(),
- updatedAt: z.date(),
completedAt: z.date().nullable(),
reviewedAt: z.date().nullable(),
rejectionReason: z.string().nullable(),
@@ -161,23 +163,43 @@ export const BountySubmissionExtendedSchema = BountySubmissionSchema.extend({
}).nullable(),
});
-export const rejectBountySubmissionSchema = z.object({
- workspaceId: z.string(),
- submissionId: z.string(),
- rejectionReason: z.enum(BountySubmissionRejectionReason),
+export const approveBountySubmissionBodySchema = z.object({
+ rewardAmount: z.number().nullish(),
+});
+
+export const rejectBountySubmissionBodySchema = z.object({
+ rejectionReason: z.enum(BountySubmissionRejectionReason).optional().meta({
+ description: "The reason for rejecting the submission.",
+ }),
rejectionNote: z
.string()
.trim()
.max(BOUNTY_MAX_SUBMISSION_REJECTION_NOTE_LENGTH)
- .optional(),
+ .optional()
+ .meta({
+ description: "The note for rejecting the submission.",
+ }),
});
export const getBountySubmissionsQuerySchema = z
.object({
- status: z.enum(BountySubmissionStatus).optional(),
- groupId: z.string().optional(),
- partnerId: z.string().optional(),
- sortBy: z.enum(["completedAt", "performanceCount"]).default("completedAt"),
- sortOrder: z.enum(["asc", "desc"]).default("asc"),
+ status: z.enum(BountySubmissionStatus).optional().meta({
+ description: "The status of the submissions to list.",
+ }),
+ groupId: z.string().optional().meta({
+ description: "The ID of the group to list submissions for.",
+ }),
+ partnerId: z.string().optional().meta({
+ description: "The ID of the partner to list submissions for.",
+ }),
+ sortBy: z
+ .enum(["completedAt", "performanceCount"])
+ .default("completedAt")
+ .meta({
+ description: "The field to sort the submissions by.",
+ }),
+ sortOrder: z.enum(["asc", "desc"]).default("asc").meta({
+ description: "The order to sort the submissions by.",
+ }),
})
.extend(getPaginationQuerySchema({ pageSize: 100 }));
diff --git a/apps/web/ui/partners/reject-bounty-submission-modal.tsx b/apps/web/ui/partners/reject-bounty-submission-modal.tsx
index b7da4ea32f..5c99fcb346 100644
--- a/apps/web/ui/partners/reject-bounty-submission-modal.tsx
+++ b/apps/web/ui/partners/reject-bounty-submission-modal.tsx
@@ -7,7 +7,7 @@ import { mutatePrefix } from "@/lib/swr/mutate";
import useBounty from "@/lib/swr/use-bounty";
import useWorkspace from "@/lib/swr/use-workspace";
import { BountySubmissionProps } from "@/lib/types";
-import { rejectBountySubmissionSchema } from "@/lib/zod/schemas/bounties";
+import { rejectBountySubmissionBodySchema } from "@/lib/zod/schemas/bounties";
import { Button, Modal, useKeyboardShortcut } from "@dub/ui";
import { cn } from "@dub/utils";
import { useAction } from "next-safe-action/hooks";
@@ -16,11 +16,6 @@ import { useForm } from "react-hook-form";
import { toast } from "sonner";
import * as z from "zod/v4";
-type FormData = Pick<
- z.infer<typeof rejectBountySubmissionSchema>,
- "rejectionReason" | "rejectionNote"
->;
-
interface RejectBountySubmissionModalProps {
submission: BountySubmissionProps;
showModal: boolean;
@@ -42,7 +37,7 @@ const RejectBountySubmissionModal = ({
watch,
getValues,
formState: { errors },
- } = useForm<FormData>({
+ } = useForm<z.infer<typeof rejectBountySubmissionBodySchema>>({
defaultValues: {
rejectionReason: undefined,
rejectionNote: "",
@@ -73,7 +68,7 @@ const RejectBountySubmissionModal = ({
await rejectBountySubmission({
...formData,
- rejectionReason: formData.rejectionReason || "other",
+ rejectionReason: formData.rejectionReason,
workspaceId: workspace.id,
submissionId: submission.id,
});