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.

Integrate submission bounties with social stats (#3448)

Kiran Kbf696d642837
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
index e738f9ffa2..e537d8d106 100644
--- a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
@@ -1,19 +1,24 @@
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
-import { generatePerformanceBountyName } from "@/lib/api/bounties/generate-performance-bounty-name";
-import { getBountyWithDetails } from "@/lib/api/bounties/get-bounty-with-details";
-import { PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES } from "@/lib/api/bounties/performance-bounty-scope-attributes";
-import { validateBounty } from "@/lib/api/bounties/validate-bounty";
import { DubApiError } from "@/lib/api/errors";
import { throwIfInvalidGroupIds } from "@/lib/api/groups/throw-if-invalid-group-ids";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
+import { generatePerformanceBountyName } from "@/lib/bounty/api/generate-performance-bounty-name";
+import { getBountyWithDetails } from "@/lib/bounty/api/get-bounty-with-details";
+import { PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES } from "@/lib/bounty/api/performance-bounty-scope-attributes";
+import { validateBounty } from "@/lib/bounty/api/validate-bounty";
+import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { WorkflowCondition } from "@/lib/types";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
-import { BountySchema, updateBountySchema } from "@/lib/zod/schemas/bounties";
+import {
+ BountySchema,
+ submissionRequirementsSchema,
+ updateBountySchema,
+} from "@/lib/zod/schemas/bounties";
import { prisma } from "@dub/prisma";
import { PartnerGroup, Prisma } from "@dub/prisma/client";
-import { arrayEqual } from "@dub/utils";
+import { arrayEqual, deepEqual } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
@@ -85,11 +90,23 @@ export const PATCH = withWorkspace(
startsAt,
endsAt,
submissionsOpenAt,
+ submissionRequirements,
rewardAmount,
rewardDescription,
performanceScope: bounty.performanceScope,
});
+ if (
+ submissionRequirements !== undefined &&
+ submissionRequirements?.socialMetrics &&
+ !getPlanCapabilities(workspace.plan).canUseBountySocialMetrics
+ ) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Social metrics criteria require Advanced plan or above.",
+ });
+ }
+
// TODO:
// When we do archive, make sure it disables the workflow
@@ -126,6 +143,31 @@ export const PATCH = withWorkspace(
}
}
+ // Prevent update if `submissionRequirements.socialMetrics` differs from the current value if there are existing submissions
+ if (submissionRequirements) {
+ const submissionCount = bounty._count.submissions;
+
+ const currentSocialMetrics = bounty.submissionRequirements
+ ? (submissionRequirementsSchema.parse(bounty.submissionRequirements)
+ .socialMetrics ?? {})
+ : {};
+
+ const incomingSocialMetrics =
+ submissionRequirementsSchema.parse(submissionRequirements)
+ .socialMetrics ?? {};
+
+ if (
+ !deepEqual(currentSocialMetrics, incomingSocialMetrics) &&
+ submissionCount > 0
+ ) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "You cannot change the social metrics criteria because the bounty has submissions.",
+ });
+ }
+ }
+
// Bounty name
let bountyName = name;
@@ -148,7 +190,8 @@ export const PATCH = withWorkspace(
endsAt,
submissionsOpenAt:
bounty.type === "submission" ? submissionsOpenAt : null,
- rewardAmount,
+ rewardAmount:
+ rewardAmount !== undefined ? rewardAmount : bounty.rewardAmount,
rewardDescription,
...(bounty.type === "submission" &&
submissionRequirements !== undefined && {
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
index 5d0d82cb8a..56f52c3635 100644
--- 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
@@ -1,8 +1,8 @@
-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 { approveBountySubmission } from "@/lib/bounty/api/approve-bounty-submission";
+import { getBountyOrThrow } from "@/lib/bounty/api/get-bounty-or-throw";
import { approveBountySubmissionBodySchema } from "@/lib/zod/schemas/bounties";
import { NextResponse } from "next/server";
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
index 2111ea9bd1..fc9512e4e8 100644
--- 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
@@ -1,8 +1,8 @@
-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 { getBountyOrThrow } from "@/lib/bounty/api/get-bounty-or-throw";
+import { rejectBountySubmission } from "@/lib/bounty/api/reject-bounty-submission";
import { rejectBountySubmissionBodySchema } from "@/lib/zod/schemas/bounties";
import { NextResponse } from "next/server";
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 c50645c936..bde9833b4c 100644
--- a/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts
@@ -1,6 +1,6 @@
-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 { getBountyOrThrow } from "@/lib/bounty/api/get-bounty-or-throw";
import {
BountySubmissionExtendedSchema,
getBountySubmissionsQuerySchema,
@@ -14,7 +14,7 @@ export const GET = withWorkspace(
const { bountyId } = params;
const programId = getDefaultProgramIdOrThrow(workspace);
- const bounty = await getBountyOrThrow({
+ await getBountyOrThrow({
bountyId,
programId,
include: {
@@ -47,8 +47,7 @@ export const GET = withWorkspace(
programEnrollment: true,
},
orderBy: {
- [sortBy === "completedAt" ? "completedAt" : "performanceCount"]:
- sortOrder,
+ [sortBy]: sortOrder,
},
skip: (page - 1) * pageSize,
take: pageSize,
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/sync-social-metrics/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/sync-social-metrics/route.ts
new file mode 100644
index 0000000000..ebc6c786f2
--- /dev/null
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/sync-social-metrics/route.ts
@@ -0,0 +1,205 @@
+import { DubApiError } from "@/lib/api/errors";
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withWorkspace } from "@/lib/auth";
+import { getBountyOrThrow } from "@/lib/bounty/api/get-bounty-or-throw";
+import { getSocialMetricsUpdates } from "@/lib/bounty/api/get-social-metrics-updates";
+import { resolveBountyDetails } from "@/lib/bounty/utils";
+import { qstash } from "@/lib/cron";
+import { sendEmail } from "@dub/email";
+import BountyCompleted from "@dub/email/templates/bounty-completed";
+import { prisma } from "@dub/prisma";
+import { Prisma } from "@dub/prisma/client";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { NextResponse } from "next/server";
+import * as z from "zod/v4";
+
+const inputSchema = z.object({
+ submissionId: z
+ .string()
+ .optional()
+ .describe(
+ "The ID of the submission to sync social metrics for. If not provided, all submissions will be synced.",
+ ),
+});
+
+// POST /api/bounties/[bountyId]/sync-social-metrics - sync social metrics for a bounty
+export const POST = withWorkspace(
+ async ({ workspace, params, req }) => {
+ const { bountyId } = params;
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ const { submissionId } = inputSchema.parse(await parseRequestBody(req));
+
+ const bounty = await getBountyOrThrow({
+ bountyId,
+ programId,
+ include: submissionId
+ ? {
+ program: {
+ select: {
+ name: true,
+ slug: true,
+ supportEmail: true,
+ },
+ },
+ submissions: {
+ where: {
+ id: submissionId,
+ },
+ select: {
+ id: true,
+ urls: true,
+ status: true,
+ partner: true,
+ },
+ },
+ }
+ : undefined,
+ });
+
+ const bountyInfo = resolveBountyDetails(bounty);
+
+ if (!bountyInfo?.socialMetrics) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This bounty does not have social metrics requirements.",
+ });
+ }
+
+ const submission = submissionId ? bounty.submissions?.[0] : undefined;
+
+ if (submissionId) {
+ if (!submission) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Submission ${submissionId} not found.`,
+ });
+ }
+
+ if (submission.status === "approved") {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Social metrics can't be synced for an approved submission.",
+ });
+ }
+ }
+
+ const now = new Date();
+
+ if (bounty.startsAt && bounty.startsAt > now) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Social metrics can only be synced after the bounty starts.",
+ });
+ }
+
+ if (bounty.endsAt && bounty.endsAt < now) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Social metrics can't be synced after the bounty ends.",
+ });
+ }
+
+ // Do the sync in a background job if no submissionId is provided
+ if (!submissionId) {
+ const response = await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/sync-social-metrics`,
+ method: "POST",
+ body: {
+ bountyId,
+ },
+ });
+
+ if (!response.messageId) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Could not sync social metrics for this bounty now.",
+ });
+ }
+
+ return NextResponse.json({});
+ }
+
+ // Otherwise, do the sync for the specific submission
+ const toUpdate = await getSocialMetricsUpdates({
+ bounty,
+ submissions: bounty.submissions![0],
+ });
+
+ if (toUpdate.length > 0) {
+ const update = toUpdate.find((s) => s.id === submissionId);
+
+ if (!update) {
+ return NextResponse.json({});
+ }
+
+ const { socialMetricCount, socialMetricsLastSyncedAt } = update;
+ const submission = bounty.submissions![0];
+
+ const updateData: Prisma.BountySubmissionUpdateInput = {
+ socialMetricCount,
+ socialMetricsLastSyncedAt,
+ };
+
+ const hasMetCriteria =
+ socialMetricCount != null &&
+ bountyInfo.socialMetrics?.minCount != null &&
+ socialMetricCount >= bountyInfo.socialMetrics.minCount;
+
+ const shouldTransitionToSubmitted =
+ submission.status === "draft" && hasMetCriteria;
+
+ if (shouldTransitionToSubmitted) {
+ updateData.status = "submitted";
+ updateData.completedAt = new Date();
+ }
+
+ await prisma.bountySubmission.update({
+ where: {
+ id: submissionId,
+ },
+ data: {
+ ...updateData,
+ },
+ });
+
+ const { partner } = submission;
+
+ if (shouldTransitionToSubmitted && partner.email) {
+ await sendEmail({
+ subject: "Bounty completed!",
+ to: partner.email,
+ variant: "notifications",
+ replyTo: bounty.program.supportEmail || "noreply",
+ react: BountyCompleted({
+ email: partner.email,
+ bounty: {
+ name: bounty.name,
+ type: bounty.type,
+ },
+ program: {
+ name: bounty.program.name,
+ slug: bounty.program.slug,
+ },
+ }),
+ headers: {
+ "Idempotency-Key": `bounty-completed-${submissionId}`,
+ },
+ });
+ }
+ }
+
+ return NextResponse.json({});
+ },
+ {
+ requiredPlan: [
+ "business",
+ "business plus",
+ "business extra",
+ "business max",
+ "advanced",
+ "enterprise",
+ ],
+ },
+);
diff --git a/apps/web/app/(ee)/api/bounties/route.ts b/apps/web/app/(ee)/api/bounties/route.ts
index 063210227d..24fadb19fa 100644
--- a/apps/web/app/(ee)/api/bounties/route.ts
+++ b/apps/web/app/(ee)/api/bounties/route.ts
@@ -1,6 +1,4 @@
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
-import { generatePerformanceBountyName } from "@/lib/api/bounties/generate-performance-bounty-name";
-import { validateBounty } from "@/lib/api/bounties/validate-bounty";
import { createId } from "@/lib/api/create-id";
import { DubApiError } from "@/lib/api/errors";
import { throwIfInvalidGroupIds } from "@/lib/api/groups/throw-if-invalid-group-ids";
@@ -8,6 +6,8 @@ import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-progr
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
+import { generatePerformanceBountyName } from "@/lib/bounty/api/generate-performance-bounty-name";
+import { validateBounty } from "@/lib/bounty/api/validate-bounty";
import { qstash } from "@/lib/cron";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { WorkflowAction } from "@/lib/types";
@@ -156,6 +156,8 @@ export const POST = withWorkspace(
async ({ workspace, req, session }) => {
const programId = getDefaultProgramIdOrThrow(workspace);
+ const parsedBody = createBountySchema.parse(await parseRequestBody(req));
+
let {
name,
description,
@@ -170,20 +172,22 @@ export const POST = withWorkspace(
performanceCondition,
performanceScope,
sendNotificationEmails,
- } = createBountySchema.parse(await parseRequestBody(req));
+ } = parsedBody;
// Use current date as default if startsAt is not provided
startsAt = startsAt || new Date();
- validateBounty({
- type,
- startsAt,
- endsAt,
- submissionsOpenAt,
- rewardAmount,
- rewardDescription,
- performanceScope,
- });
+ validateBounty(parsedBody);
+
+ const { canUseBountySocialMetrics, canSendEmailCampaigns } =
+ getPlanCapabilities(workspace.plan);
+
+ if (submissionRequirements?.socialMetrics && !canUseBountySocialMetrics) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Social metrics criteria require Advanced plan or above.",
+ });
+ }
const partnerGroups = await throwIfInvalidGroupIds({
programId,
@@ -240,7 +244,7 @@ export const POST = withWorkspace(
name: bountyName,
description,
type,
- startsAt: startsAt!, // Can remove the ! when we're on a newer TS version (currently 5.4.4)
+ startsAt,
endsAt,
submissionsOpenAt: type === "submission" ? submissionsOpenAt : null,
rewardAmount,
@@ -276,8 +280,6 @@ export const POST = withWorkspace(
const shouldScheduleDraftSubmissions =
bounty.type === "performance" && bounty.performanceScope === "lifetime";
- const { canSendEmailCampaigns } = getPlanCapabilities(workspace.plan);
-
waitUntil(
Promise.allSettled([
recordAuditLog({
diff --git a/apps/web/app/(ee)/api/cron/bounties/queue-sync-social-metrics/route.ts b/apps/web/app/(ee)/api/cron/bounties/queue-sync-social-metrics/route.ts
new file mode 100644
index 0000000000..7a753cb32a
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/bounties/queue-sync-social-metrics/route.ts
@@ -0,0 +1,59 @@
+import { enqueueBatchJobs } from "@/lib/cron/enqueue-batch-jobs";
+import { withCron } from "@/lib/cron/with-cron";
+import { prisma } from "@dub/prisma";
+import { Prisma } from "@dub/prisma/client";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { logAndRespond } from "../../utils";
+
+export const dynamic = "force-dynamic";
+
+// GET /api/cron/bounties/queue-sync-social-metrics - queue social metrics sync for bounties
+export const GET = withCron(async () => {
+ const now = new Date();
+
+ const bounties = await prisma.bounty.findMany({
+ where: {
+ type: "submission",
+ startsAt: {
+ lte: now,
+ },
+ OR: [
+ {
+ endsAt: null,
+ },
+ {
+ endsAt: {
+ gt: now,
+ },
+ },
+ ],
+ submissionRequirements: {
+ path: "$.socialMetrics",
+ not: Prisma.JsonNull,
+ },
+ },
+ select: {
+ id: true,
+ submissionRequirements: true,
+ },
+ });
+
+ if (bounties.length === 0) {
+ return logAndRespond("No bounties to sync social metrics for.");
+ }
+
+ await enqueueBatchJobs(
+ bounties.map((bounty) => ({
+ queueName: "sync-bounty-social-metrics",
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/sync-social-metrics`,
+ deduplicationId: bounty.id,
+ body: {
+ bountyId: bounty.id,
+ },
+ })),
+ );
+
+ return logAndRespond(
+ `Queued ${bounties.length} bounties to sync social metrics.`,
+ );
+});
diff --git a/apps/web/app/(ee)/api/cron/bounties/sync-social-metrics/route.ts b/apps/web/app/(ee)/api/cron/bounties/sync-social-metrics/route.ts
new file mode 100644
index 0000000000..73a49bc11f
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/bounties/sync-social-metrics/route.ts
@@ -0,0 +1,211 @@
+import { getSocialMetricsUpdates } from "@/lib/bounty/api/get-social-metrics-updates";
+import { resolveBountyDetails } from "@/lib/bounty/utils";
+import { qstash } from "@/lib/cron";
+import { withCron } from "@/lib/cron/with-cron";
+import { sendBatchEmail } from "@dub/email";
+import BountyCompleted from "@dub/email/templates/bounty-completed";
+import { prisma } from "@dub/prisma";
+import { Partner, Prisma } from "@dub/prisma/client";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import * as z from "zod/v4";
+import { logAndRespond } from "../../utils";
+
+export const dynamic = "force-dynamic";
+
+const bodySchema = z.object({
+ bountyId: z.string(),
+ startingAfter: z
+ .string()
+ .optional()
+ .describe("The ID of the submission to start processing from."),
+});
+
+const SUBMISSION_BATCH_SIZE = 50;
+
+// POST /api/cron/bounties/sync-social-metrics - sync social metrics for a bounty
+export const POST = withCron(async ({ rawBody }) => {
+ const { bountyId, startingAfter } = bodySchema.parse(JSON.parse(rawBody));
+
+ const bounty = await prisma.bounty.findUnique({
+ where: {
+ id: bountyId,
+ },
+ include: {
+ program: true,
+ },
+ });
+
+ if (!bounty) {
+ return logAndRespond(`Bounty ${bountyId} not found. Skipping...`);
+ }
+
+ const now = new Date();
+
+ if (bounty.startsAt && bounty.startsAt > now) {
+ return logAndRespond(`Bounty ${bountyId} has not started yet. Skipping...`);
+ }
+
+ if (bounty.endsAt && bounty.endsAt < now) {
+ return logAndRespond(`Bounty ${bountyId} has ended. Skipping...`);
+ }
+
+ const bountyInfo = resolveBountyDetails(bounty);
+
+ if (!bountyInfo?.hasSocialMetrics) {
+ return logAndRespond(
+ `Bounty ${bountyId} has no social metrics requirements. Skipping...`,
+ );
+ }
+
+ const submissions = await prisma.bountySubmission.findMany({
+ where: {
+ bountyId,
+ status: {
+ // We only want to process submissions that are not rejected or approved.
+ notIn: ["rejected", "approved"],
+ },
+ },
+ select: {
+ id: true,
+ urls: true,
+ socialMetricCount: true,
+ status: true,
+ partner: {
+ select: {
+ email: true,
+ },
+ },
+ },
+ orderBy: {
+ id: "asc",
+ },
+ ...(startingAfter && {
+ skip: 1,
+ cursor: {
+ id: startingAfter,
+ },
+ }),
+ take: SUBMISSION_BATCH_SIZE,
+ });
+
+ if (submissions.length === 0) {
+ return logAndRespond(
+ `No submissions found for bounty ${bountyId}. Skipping...`,
+ );
+ }
+
+ const newMetrics = await getSocialMetricsUpdates({
+ bounty,
+ submissions,
+ });
+
+ const minCount = bountyInfo.socialMetrics?.minCount;
+
+ if (!minCount) {
+ return logAndRespond(
+ `Bounty ${bountyId} has no minimum social metrics count. Skipping...`,
+ );
+ }
+
+ const submissionById = new Map(submissions.map((s) => [s.id, s]));
+
+ const updates: Prisma.PrismaPromise<unknown>[] = [];
+ const notifications: Pick<Partner, "email">[] = [];
+
+ for (const {
+ id,
+ socialMetricCount,
+ socialMetricsLastSyncedAt,
+ } of newMetrics) {
+ const submission = submissionById.get(id);
+
+ if (!submission) {
+ continue;
+ }
+
+ const hasMetCriteria =
+ socialMetricCount != null && socialMetricCount >= minCount;
+
+ const shouldTransitionToSubmitted =
+ submission.status === "draft" && hasMetCriteria;
+
+ const updateData: Prisma.BountySubmissionUpdateInput = {
+ socialMetricCount,
+ socialMetricsLastSyncedAt,
+ };
+
+ if (shouldTransitionToSubmitted) {
+ updateData.status = "submitted";
+ updateData.completedAt = now;
+
+ if (submission.partner?.email) {
+ notifications.push({
+ email: submission.partner.email,
+ });
+ }
+ }
+
+ updates.push(
+ prisma.bountySubmission.update({
+ where: {
+ id,
+ },
+ data: updateData,
+ }),
+ );
+ }
+
+ await prisma.$transaction(updates);
+
+ if (notifications.length > 0 && bounty.program) {
+ await sendBatchEmail(
+ notifications.map(({ email }) => ({
+ subject: "Bounty completed!",
+ to: email!,
+ variant: "notifications",
+ replyTo: bounty.program.supportEmail || "noreply",
+ react: BountyCompleted({
+ email: email!,
+ bounty: {
+ name: bounty.name,
+ type: bounty.type,
+ },
+ program: {
+ name: bounty.program.name,
+ slug: bounty.program.slug,
+ },
+ }),
+ })),
+ );
+ }
+
+ if (submissions.length === SUBMISSION_BATCH_SIZE) {
+ const startingAfter = submissions[submissions.length - 1].id;
+
+ await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/sync-social-metrics`,
+ method: "POST",
+ body: {
+ bountyId,
+ startingAfter,
+ },
+ });
+
+ return logAndRespond(
+ `Synced ${updates.length} submissions for bounty ${bountyId}. Queued next batch (startingAfter: ${startingAfter}).`,
+ );
+ }
+
+ await prisma.bounty.update({
+ where: {
+ id: bountyId,
+ },
+ data: {
+ socialMetricsLastSyncedAt: new Date(),
+ },
+ });
+
+ return logAndRespond(
+ `Synced ${updates.length} submission(s) for bounty ${bountyId}.`,
+ );
+});
diff --git a/apps/web/app/(ee)/api/cron/partner-platforms/route.ts b/apps/web/app/(ee)/api/cron/partner-platforms/route.ts
index 51314ea2e0..5ffeee63c4 100644
--- a/apps/web/app/(ee)/api/cron/partner-platforms/route.ts
+++ b/apps/web/app/(ee)/api/cron/partner-platforms/route.ts
@@ -1,7 +1,7 @@
import {
AccountNotFoundError,
- fetchSocialProfile,
-} from "@/lib/api/scrape-creators/fetch-social-profile";
+ getSocialProfile,
+} from "@/lib/api/scrape-creators/get-social-profile";
import { qstash } from "@/lib/cron";
import { withCron } from "@/lib/cron/with-cron";
import { prisma } from "@dub/prisma";
@@ -83,7 +83,7 @@ export const POST = withCron(async ({ rawBody }) => {
}
try {
- const socialProfile = await fetchSocialProfile({
+ const socialProfile = await getSocialProfile({
platform: verifiedProfile.type,
handle: verifiedProfile.identifier,
});
@@ -91,6 +91,7 @@ export const POST = withCron(async ({ rawBody }) => {
const newStats = {
subscribers: socialProfile.subscribers,
posts: socialProfile.posts,
+ avatarUrl: socialProfile.avatarUrl,
};
await prisma.partnerPlatform.update({
diff --git a/apps/web/app/(ee)/api/cron/partner-platforms/youtube/route.ts b/apps/web/app/(ee)/api/cron/partner-platforms/youtube/route.ts
index b1f731f88d..32610a068e 100644
--- a/apps/web/app/(ee)/api/cron/partner-platforms/youtube/route.ts
+++ b/apps/web/app/(ee)/api/cron/partner-platforms/youtube/route.ts
@@ -12,6 +12,21 @@ const youtubeChannelSchema = z.object({
subscriberCount: z.string().transform((val) => parseInt(val, 10)),
viewCount: z.string().transform((val) => parseInt(val, 10)),
}),
+ snippet: z
+ .object({
+ thumbnails: z
+ .object({
+ default: z
+ .object({
+ url: z.string(),
+ width: z.number().optional(),
+ height: z.number().optional(),
+ })
+ .optional(),
+ })
+ .optional(),
+ })
+ .optional(),
});
export const dynamic = "force-dynamic";
@@ -77,16 +92,11 @@ export const POST = withCron(async () => {
continue;
}
- const currentStats = {
- subscribers: partnerPlatform.subscribers,
- posts: partnerPlatform.posts,
- views: partnerPlatform.views,
- };
-
const newStats = {
subscribers: channel.statistics.subscriberCount,
posts: channel.statistics.videoCount,
views: channel.statistics.viewCount,
+ avatarUrl: channel.snippet?.thumbnails?.default?.url,
};
await prisma.partnerPlatform.update({
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/social-content-stats/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/social-content-stats/route.ts
new file mode 100644
index 0000000000..e21566b7e1
--- /dev/null
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/social-content-stats/route.ts
@@ -0,0 +1,60 @@
+import { DubApiError } from "@/lib/api/errors";
+import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { getSocialContent } from "@/lib/api/scrape-creators/get-social-content";
+import { withPartnerProfile } from "@/lib/auth/partner";
+import { getBountyOrThrow } from "@/lib/bounty/api/get-bounty-or-throw";
+import { resolveBountyDetails } from "@/lib/bounty/utils";
+import { ratelimit } from "@/lib/upstash";
+import { NextResponse } from "next/server";
+import * as z from "zod/v4";
+
+const searchParamsSchema = z.object({
+ url: z.url("Social media URL is required."),
+});
+
+// GET /api/partner-profile/programs/[programId]/bounties/[bountyId]/social-content-stats
+export const GET = withPartnerProfile(
+ async ({ partner, params, searchParams }) => {
+ const { programId, bountyId } = params;
+
+ const { url } = searchParamsSchema.parse(searchParams);
+
+ const { success } = await ratelimit(10, "1 h").limit(
+ `partner-profile:social-content-stats:${partner.id}`,
+ );
+
+ if (!success) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message: "You've been rate limited. Please try again later.",
+ });
+ }
+
+ const programEnrollment = await getProgramEnrollmentOrThrow({
+ partnerId: partner.id,
+ programId,
+ include: {},
+ });
+
+ const bounty = await getBountyOrThrow({
+ bountyId,
+ programId: programEnrollment.programId,
+ });
+
+ const bountyInfo = resolveBountyDetails(bounty);
+
+ if (!bountyInfo?.socialMetrics) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This bounty does not have social content requirements.",
+ });
+ }
+
+ const content = await getSocialContent({
+ platform: bountyInfo.socialMetrics.platform,
+ url,
+ });
+
+ return NextResponse.json(content);
+ },
+);
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 f3a17fd081..e0950bf998 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
@@ -59,6 +59,16 @@ export const GET = withPartnerProfile(
where: {
partnerId: partner.id,
},
+ include: {
+ commission: {
+ select: {
+ id: true,
+ earnings: true,
+ status: true,
+ createdAt: true,
+ },
+ },
+ },
},
},
});
diff --git a/apps/web/app/(ee)/api/partners/platforms/callback/route.ts b/apps/web/app/(ee)/api/partners/platforms/callback/route.ts
index 0fbd7bbd25..d7a97e44c2 100644
--- a/apps/web/app/(ee)/api/partners/platforms/callback/route.ts
+++ b/apps/web/app/(ee)/api/partners/platforms/callback/route.ts
@@ -1,5 +1,5 @@
import { PARTNER_PLATFORMS_PROVIDERS } from "@/lib/api/partner-profile/partner-platforms-providers";
-import { fetchSocialProfile } from "@/lib/api/scrape-creators/fetch-social-profile";
+import { getSocialProfile } from "@/lib/api/scrape-creators/get-social-profile";
import { getSession } from "@/lib/auth/utils";
import { redis } from "@/lib/upstash/redis";
import { prisma } from "@dub/prisma";
@@ -149,16 +149,19 @@ export async function GET(req: Request) {
return NextResponse.redirect(redirectUrl);
}
- // Sync social stats for platforms
- let socialStats: Pick<PartnerPlatform, "subscribers" | "posts" | "views"> = {
+ let socialStats: Pick<
+ PartnerPlatform,
+ "subscribers" | "posts" | "views" | "avatarUrl"
+ > = {
subscribers: BigInt(0),
posts: BigInt(0),
views: BigInt(0),
+ avatarUrl: null,
};
if (["tiktok", "twitter"].includes(platform)) {
try {
- const socialProfile = await fetchSocialProfile({
+ const socialProfile = await getSocialProfile({
platform,
handle: partnerPlatform.identifier,
});
@@ -167,6 +170,7 @@ export async function GET(req: Request) {
subscribers: socialProfile.subscribers,
posts: socialProfile.posts,
views: socialProfile.views,
+ avatarUrl: socialProfile.avatarUrl,
};
} catch (error) {
console.error(
@@ -186,7 +190,10 @@ export async function GET(req: Request) {
data: {
verifiedAt: new Date(),
...(metadata && { metadata }),
- ...socialStats,
+ subscribers: socialStats.subscribers,
+ posts: socialStats.posts,
+ views: socialStats.views,
+ avatarUrl: socialStats.avatarUrl,
},
});
diff --git a/apps/web/app/(ee)/api/workflows/partner-approved/route.ts b/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
index a7a9778b65..e3b8b29fd1 100644
--- a/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
+++ b/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
@@ -1,9 +1,9 @@
-import { triggerDraftBountySubmissionCreation } from "@/lib/api/bounties/trigger-draft-bounty-submissions";
import { createDiscountCode } from "@/lib/api/discounts/create-discount-code";
import { createPartnerDefaultLinks } from "@/lib/api/partners/create-partner-default-links";
import { getPartnerInviteRewardsAndBounties } from "@/lib/api/partners/get-partner-invite-rewards-and-bounties";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
+import { triggerDraftBountySubmissionCreation } from "@/lib/bounty/api/trigger-draft-bounty-submissions";
import { createWorkflowLogger } from "@/lib/cron/qstash-workflow-logger";
import { polyfillSocialMediaFields } from "@/lib/social-utils";
import { PlanProps } from "@/lib/types";
diff --git a/apps/web/app/(ee)/partners.dub.co/(auth-login-register)/(generic)/layout.tsx b/apps/web/app/(ee)/partners.dub.co/(auth-login-register)/(generic)/layout.tsx
index f9b9fdbb48..90c9727e47 100644
--- a/apps/web/app/(ee)/partners.dub.co/(auth-login-register)/(generic)/layout.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(auth-login-register)/(generic)/layout.tsx
@@ -64,7 +64,7 @@ export default async function PartnerAuthLayout(props: {
redirect("/register");
}
return (
- <div className="relative grid min-h-screen min-h-[100dvh] grid-cols-1 min-[900px]:grid-cols-[440px_minmax(0,1fr)] lg:grid-cols-[595px_minmax(0,1fr)]">
+ <div className="relative grid min-h-[100dvh] min-h-screen grid-cols-1 min-[900px]:grid-cols-[440px_minmax(0,1fr)] lg:grid-cols-[595px_minmax(0,1fr)]">
<PartnerBanner program={program} />
<SidePanel program={program} />
@@ -105,7 +105,7 @@ export default async function PartnerAuthLayout(props: {
</div>
))}
</div>
- <div className="relative flex min-h-screen min-h-[100dvh] w-full justify-center">
+ <div className="relative flex min-h-[100dvh] min-h-screen w-full justify-center">
<Logo className="min-[900px]:hidden" />
{props.children}
</div>
diff --git a/apps/web/app/(ee)/partners.dub.co/(auth-other)/layout.tsx b/apps/web/app/(ee)/partners.dub.co/(auth-other)/layout.tsx
index 354850465d..cebba3d15e 100644
--- a/apps/web/app/(ee)/partners.dub.co/(auth-other)/layout.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(auth-other)/layout.tsx
@@ -45,7 +45,7 @@ export default function PartnerAuthLayout({
</div>
))}
</div>
- <div className="relative flex min-h-screen min-h-[100dvh] w-full justify-center">
+ <div className="relative flex min-h-[100dvh] min-h-screen w-full justify-center">
<Logo />
{children}
</div>
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/partner-bounty-card.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/partner-bounty-card.tsx
index 919153ccb3..5870906d0d 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/partner-bounty-card.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/partner-bounty-card.tsx
@@ -1,11 +1,11 @@
-import { getBountyRewardDescription } from "@/lib/partners/get-bounty-reward-description";
import { PartnerBountyProps } from "@/lib/types";
import { BountyPerformance } from "@/ui/partners/bounties/bounty-performance";
+import { BountyRewardDescription } from "@/ui/partners/bounties/bounty-reward-description";
import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
import { useClaimBountyModal } from "@/ui/partners/bounties/claim-bounty-modal";
+import { usePartnerBountySubmissionDetailsSheet } from "@/ui/partners/bounties/partner-bounty-submission-details-sheet";
import {
DynamicTooltipWrapper,
- Gift,
StatusBadge,
TimestampTooltip,
TooltipContent,
@@ -16,16 +16,38 @@ import { useParams } from "next/navigation";
export function PartnerBountyCard({ bounty }: { bounty: PartnerBountyProps }) {
const { programSlug } = useParams();
+
const { claimBountyModal, setShowClaimBountyModal } = useClaimBountyModal({
bounty,
});
+ const {
+ partnerBountySubmissionDetailsSheet,
+ setPartnerBountySubmissionDetailsSheetOpen,
+ } = usePartnerBountySubmissionDetailsSheet(bounty);
+
const expiredBounty =
bounty.endsAt && new Date(bounty.endsAt) < new Date() ? true : false;
+ const handleCardClick = () => {
+ if (expiredBounty) {
+ return;
+ }
+
+ const shouldOpenSheet =
+ bounty.submission && bounty.submission.status !== "draft";
+
+ if (shouldOpenSheet) {
+ setPartnerBountySubmissionDetailsSheetOpen(true);
+ } else {
+ setShowClaimBountyModal(true);
+ }
+ };
+
return (
<>
{claimBountyModal}
+ {partnerBountySubmissionDetailsSheet}
<DynamicTooltipWrapper
tooltipProps={
expiredBounty
@@ -43,7 +65,7 @@ export function PartnerBountyCard({ bounty }: { bounty: PartnerBountyProps }) {
>
<button
type="button"
- onClick={() => setShowClaimBountyModal(true)}
+ onClick={handleCardClick}
disabled={expiredBounty}
className={cn(
"border-border-subtle group relative flex w-full cursor-pointer flex-col gap-2.5 overflow-hidden rounded-xl border bg-white p-3 text-left",
@@ -93,12 +115,11 @@ export function PartnerBountyCard({ bounty }: { bounty: PartnerBountyProps }) {
</span>
</div>
- {getBountyRewardDescription(bounty) && (
- <div className="text-content-subtle flex items-center gap-2 text-sm font-medium">
- <Gift className="size-3.5" />
- <span>{getBountyRewardDescription(bounty)}</span>
- </div>
- )}
+ <BountyRewardDescription
+ bounty={bounty}
+ onTooltipClick={(e) => e.stopPropagation()}
+ className="font-medium"
+ />
</div>
<div className="flex grow flex-col justify-end px-2 pb-1">
@@ -143,6 +164,7 @@ function renderSubmissionStatus({
bounty.endsAt && new Date(bounty.endsAt) < new Date() ? true : false;
const { submission } = bounty;
+
// When there is no submission, we show the performance or claim bounty button
if (!submission) {
return bounty.type === "performance" ? (
diff --git a/apps/web/app/(ee)/partners.dub.co/(onboarding)/layout.tsx b/apps/web/app/(ee)/partners.dub.co/(onboarding)/layout.tsx
index 909ffab40f..ec0d571b1c 100644
--- a/apps/web/app/(ee)/partners.dub.co/(onboarding)/layout.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(onboarding)/layout.tsx
@@ -48,7 +48,7 @@ export default function PartnerOnboardingLayout({
))}
</div>
- <div className="relative flex min-h-screen min-h-[100dvh] w-full flex-col items-center justify-between">
+ <div className="relative flex min-h-[100dvh] min-h-screen w-full flex-col items-center justify-between">
<div className="grow basis-0">
<div className="pt-4">
<Link href="https://dub.co/home" target="_blank" className="block">
diff --git a/apps/web/app/app.dub.co/(auth)/layout.tsx b/apps/web/app/app.dub.co/(auth)/layout.tsx
index ee1c14417a..d3d14d8ab1 100644
--- a/apps/web/app/app.dub.co/(auth)/layout.tsx
+++ b/apps/web/app/app.dub.co/(auth)/layout.tsx
@@ -9,7 +9,7 @@ export default function AuthLayout({ children }: { children: ReactNode }) {
<>
<Toolbar />
- <div className="relative grid min-h-screen min-h-[100dvh] grid-cols-1 min-[900px]:grid-cols-[minmax(0,1fr)_440px] lg:grid-cols-[minmax(0,1fr)_595px]">
+ <div className="relative grid min-h-[100dvh] min-h-screen grid-cols-1 min-[900px]:grid-cols-[minmax(0,1fr)_440px] lg:grid-cols-[minmax(0,1fr)_595px]">
{/* Left: Main auth content */}
<div className="relative">
<div className="absolute inset-0 isolate overflow-hidden bg-white">
@@ -49,7 +49,7 @@ export default function AuthLayout({ children }: { children: ReactNode }) {
))}
</div>
- <div className="relative flex min-h-screen min-h-[100dvh] w-full justify-center">
+ <div className="relative flex min-h-[100dvh] min-h-screen w-full justify-center">
<a
href="https://dub.co"
target="_blank"
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx
index 37ba8467c2..fafd66e152 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx
@@ -1,6 +1,5 @@
"use client";
-import { getBountyRewardDescription } from "@/lib/partners/get-bounty-reward-description";
import useBounty from "@/lib/swr/use-bounty";
import {
SubmissionsCountByStatus,
@@ -9,10 +8,11 @@ import {
import useGroups from "@/lib/swr/use-groups";
import { usePartnersCountByGroupIds } from "@/lib/swr/use-partners-count-by-groupids";
import useWorkspace from "@/lib/swr/use-workspace";
+import { BountyRewardDescription } from "@/ui/partners/bounties/bounty-reward-description";
import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
import { GroupColorCircle } from "@/ui/partners/groups/group-color-circle";
import { ScrollableTooltipContent, Tooltip } from "@dub/ui";
-import { Calendar6, Gift, Users, Users6 } from "@dub/ui/icons";
+import { Calendar6, Users, Users6 } from "@dub/ui/icons";
import { formatDate, nFormatter, pluralize } from "@dub/utils";
import { useMemo } from "react";
import { BountyActionButton } from "../bounty-action-button";
@@ -87,14 +87,7 @@ export function BountyInfo() {
</span>
</div>
- {getBountyRewardDescription(bounty) && (
- <div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
- <Gift className="size-4 shrink-0" />
- <span className="text-ellipsis">
- {getBountyRewardDescription(bounty)}
- </span>
- </div>
- )}
+ <BountyRewardDescription bounty={bounty} className="font-regular" />
<div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
<Users className="size-4 shrink-0" />
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submission-details-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submission-details-sheet.tsx
index 18bafd4418..a325682be7 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submission-details-sheet.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submission-details-sheet.tsx
@@ -1,14 +1,21 @@
"use client";
-import { approveBountySubmissionAction } from "@/lib/actions/partners/approve-bounty-submission";
-import { REJECT_BOUNTY_SUBMISSION_REASONS } from "@/lib/constants/bounties";
+import { BOUNTY_SUBMISSION_STATUS_BADGES } from "@/lib/bounty/bounty-submission-status-badges";
+import { REJECT_BOUNTY_SUBMISSION_REASONS } from "@/lib/bounty/constants";
+import {
+ calculateSocialMetricsRewardAmount,
+ getBountyRewardCriteriaTexts,
+ resolveBountyDetails,
+} from "@/lib/bounty/utils";
import { mutatePrefix } from "@/lib/swr/mutate";
+import { useApiMutation } from "@/lib/swr/use-api-mutation";
import useBounty from "@/lib/swr/use-bounty";
import useWorkspace from "@/lib/swr/use-workspace";
import { BountySubmissionProps } from "@/lib/types";
-import { useConfirmModal } from "@/ui/modals/confirm-modal";
-import { PartnerInfoSection } from "@/ui/partners/partner-info-section";
-import { useRejectBountySubmissionModal } from "@/ui/partners/reject-bounty-submission-modal";
+import { useConfirmApproveBountySubmissionModal } from "@/ui/modals/confirm-approve-bounty-submission-modal";
+import { BountySocialContentPreview } from "@/ui/partners/bounties/bounty-social-content-preview";
+import { BountySocialMetricsRewardsTable } from "@/ui/partners/bounties/bounty-social-metrics-rewards-table";
+import { useRejectBountySubmissionModal } from "@/ui/partners/bounties/reject-bounty-submission-modal";
import { ButtonLink } from "@/ui/placeholders/button-link";
import { AmountInput } from "@/ui/shared/amount-input";
import { X } from "@/ui/shared/icons";
@@ -17,17 +24,25 @@ import {
ChevronLeft,
ChevronRight,
CopyButton,
+ DynamicTooltipWrapper,
Sheet,
StatusBadge,
+ Tooltip,
useKeyboardShortcut,
useRouterStuff,
} from "@dub/ui";
-import { currencyFormatter, formatDate, getPrettyUrl } from "@dub/utils";
+import { CircleHalfDottedClock } from "@dub/ui/icons";
+import {
+ cn,
+ currencyFormatter,
+ formatDate,
+ getPrettyUrl,
+ OG_AVATAR_URL,
+ timeAgo,
+} from "@dub/utils";
import Linkify from "linkify-react";
-import { useAction } from "next-safe-action/hooks";
-import { Dispatch, SetStateAction, useMemo, useState } from "react";
+import { Dispatch, SetStateAction, useCallback, useMemo, useState } from "react";
import { toast } from "sonner";
-import { BOUNTY_SUBMISSION_STATUS_BADGES } from "./bounty-submission-status-badges";
type BountySubmissionDetailsSheetProps = {
submission: BountySubmissionProps;
@@ -48,43 +63,33 @@ function BountySubmissionDetailsSheetContent({
const { setShowRejectModal, RejectBountySubmissionModal } =
useRejectBountySubmissionModal(submission, onNext);
- const [rewardAmount, setRewardAmount] = useState<number | null>(null);
-
const {
- executeAsync: approveBountySubmission,
- isPending: isApprovingBountySubmission,
- } = useAction(approveBountySubmissionAction, {
- onSuccess: () => {
- toast.success("Bounty submission approved successfully!");
- onNext ? onNext() : setIsOpen(false);
- mutatePrefix(`/api/bounties/${bounty?.id}/submissions`);
- },
- onError({ error }) {
- toast.error(error.serverError);
- },
+ openConfirmApproveBountySubmissionModal,
+ ConfirmApproveBountySubmissionModal,
+ } = useConfirmApproveBountySubmissionModal({
+ onApproveSuccess: () => (onNext ? onNext() : setIsOpen(false)),
});
- const {
- setShowConfirmModal: setShowApproveBountySubmissionModal,
- confirmModal: approveBountySubmissionModal,
- } = useConfirmModal({
- title: "Approve Bounty Submission",
- description: "Are you sure you want to approve this bounty submission?",
- confirmText: "Approve",
- confirmShortcut: "a",
- confirmShortcutOptions: { sheet: true, modal: true },
- onConfirm: async () => {
- if (!workspaceId || !submission?.id) {
- return;
- }
+ const [rewardAmount, setRewardAmount] = useState<number | null>(null);
- await approveBountySubmission({
- workspaceId,
- submissionId: submission.id,
- rewardAmount: rewardAmount ? rewardAmount * 100 : null,
- });
- },
- });
+ const { isSubmitting: isRefreshingSocialMetrics, makeRequest } =
+ useApiMutation();
+
+ const refreshSubmissionSocialMetrics = useCallback(() => {
+ if (!bounty?.id || !submission?.id) return;
+
+ makeRequest(`/api/bounties/${bounty.id}/sync-social-metrics`, {
+ method: "POST",
+ body: { submissionId: submission.id },
+ onSuccess: async () => {
+ await mutatePrefix(`/api/bounties/${bounty.id}/submissions`);
+ toast.success("Social content stats updated successfully.");
+ },
+ onError: (error) => {
+ toast.error(error);
+ },
+ });
+ }, [bounty?.id, submission?.id, makeRequest]);
// right arrow key onNext
useKeyboardShortcut(
@@ -112,7 +117,11 @@ function BountySubmissionDetailsSheetContent({
"a",
() => {
if (isValidForm && submission.status !== "draft") {
- setShowApproveBountySubmissionModal(true);
+ openConfirmApproveBountySubmissionModal(
+ submission,
+ bounty ?? null,
+ rewardAmount,
+ );
}
},
{ sheet: true },
@@ -140,10 +149,16 @@ function BountySubmissionDetailsSheetContent({
return true;
}, [bounty, rewardAmount]);
- if (!submission || !submission.partner) {
+ if (!submission || !submission.partner || !bounty) {
return null;
}
+ const bountyInfo = resolveBountyDetails(bounty);
+ const criteriaTexts = bounty ? getBountyRewardCriteriaTexts(bounty) : [];
+
+ const hasSocialContent =
+ bountyInfo?.hasSocialMetrics && (submission.urls?.length ?? 0) > 0;
+
return (
<div className="flex h-full flex-col">
<div className="sticky top-0 z-10 border-b border-neutral-200 bg-white">
@@ -182,29 +197,42 @@ function BountySubmissionDetailsSheetContent({
</div>
<div className="flex grow flex-col">
- <div className="border-b border-neutral-200 bg-neutral-50 p-6">
- <PartnerInfoSection
- partner={submission.partner}
- showPartnerStatus={false}
- >
+ <div className="px-6 pt-6">
+ <div className="flex items-center gap-4 rounded-xl bg-neutral-100 px-4 py-3">
+ <img
+ src={
+ submission.partner.image ||
+ `${OG_AVATAR_URL}${submission.partner.id}`
+ }
+ alt={submission.partner.name}
+ className="size-10 shrink-0 rounded-full"
+ />
+ <div className="min-w-0 flex-1">
+ <div className="text-base font-semibold text-neutral-800">
+ {submission.partner.name}
+ </div>
+ <div className="text-sm font-medium text-neutral-500">
+ {submission.partner.email}
+ </div>
+ </div>
<ButtonLink
href={`/${workspaceSlug}/program/partners/${submission.partner.id}`}
variant="secondary"
- className="h-8 w-fit px-3 py-2 text-sm font-medium"
+ className="h-8 shrink-0 px-3 text-sm font-medium"
target="_blank"
>
- View profile
+ View
</ButtonLink>
- </PartnerInfoSection>
+ </div>
</div>
- <div className="flex grow flex-col gap-8 overflow-y-auto p-6">
+ <div className="flex grow flex-col gap-6 overflow-y-auto p-6">
<div>
<h2 className="text-base font-semibold text-neutral-900">
- Bounty details
+ Details
</h2>
- <div className="mt-4 max-w-md space-y-3">
+ <div className="mt-3 max-w-md space-y-2">
{[
{
label: "Status",
@@ -231,6 +259,34 @@ function BountySubmissionDetailsSheetContent({
})
: "-",
},
+ ...(bountyInfo?.socialMetrics
+ ? [
+ {
+ label: "Criteria",
+ value:
+ criteriaTexts.length > 1 ? (
+ <DynamicTooltipWrapper
+ tooltipProps={{
+ // remove first item from criteriaTexts
+ content: criteriaTexts.slice(1).join("\n"),
+ align: "end",
+ }}
+ >
+ <div
+ className={cn(
+ "w-fit text-sm font-medium text-neutral-800",
+ "cursor-help underline decoration-dotted underline-offset-2",
+ )}
+ >
+ {`${bountyInfo.socialMetrics.minCount} ${bountyInfo.socialMetrics.metric}`}
+ </div>
+ </DynamicTooltipWrapper>
+ ) : (
+ `${bountyInfo.socialMetrics.minCount} ${bountyInfo.socialMetrics.metric}`
+ ),
+ },
+ ]
+ : []),
...(submission.status === "rejected"
? [
{
@@ -245,9 +301,32 @@ function BountySubmissionDetailsSheetContent({
: [
{
label: "Reward",
- value: submission.commission?.earnings
- ? currencyFormatter(submission.commission.earnings)
- : "-",
+ value: (() => {
+ if (submission.commission?.earnings != null) {
+ return currencyFormatter(
+ submission.commission.earnings,
+ );
+ }
+ const estimatedEarnings =
+ calculateSocialMetricsRewardAmount({
+ bounty,
+ submission,
+ });
+ if (
+ estimatedEarnings != null &&
+ estimatedEarnings > 0
+ ) {
+ return (
+ <Tooltip content="Estimated earnings based on reached reward tiers">
+ <div className="hover:text-content-emphasis text-content-muted flex w-fit cursor-help items-center gap-1 underline decoration-dotted underline-offset-2">
+ <CircleHalfDottedClock className="size-3.5 shrink-0" />{" "}
+ {currencyFormatter(estimatedEarnings)}
+ </div>
+ </Tooltip>
+ );
+ }
+ return "-";
+ })(),
},
]),
].map((item, index) => (
@@ -284,11 +363,46 @@ function BountySubmissionDetailsSheetContent({
{bounty?.type === "submission" && (
<div>
- <h2 className="text-base font-semibold text-neutral-900">
- Bounty submission
- </h2>
+ <div className="flex items-center justify-between gap-4">
+ <h2 className="text-base font-semibold text-neutral-900">
+ Submission
+ </h2>
+ {hasSocialContent && submission.status !== "approved" && (
+ <div className="flex shrink-0 items-center gap-3">
+ {submission.socialMetricsLastSyncedAt ? (
+ <span className="whitespace-nowrap text-xs font-medium text-neutral-500">
+ Last sync{" "}
+ {timeAgo(submission.socialMetricsLastSyncedAt, {
+ withAgo: true,
+ })}
+ </span>
+ ) : null}
+ <Button
+ variant="secondary"
+ text="Refresh"
+ loading={isRefreshingSocialMetrics}
+ onClick={refreshSubmissionSocialMetrics}
+ className="h-8 rounded-lg px-3"
+ />
+ </div>
+ )}
+ </div>
+
+ <div className="mt-3 flex flex-col gap-6">
+ {hasSocialContent && (
+ <BountySocialContentPreview
+ bounty={bounty}
+ submission={submission}
+ />
+ )}
+
+ {bountyInfo?.hasSocialMetrics && bounty && (
+ <BountySocialMetricsRewardsTable
+ bounty={bounty}
+ submission={submission}
+ />
+ )}
- <div className="mt-6 flex flex-col gap-6">
{Boolean(submission.files?.length) && (
<div>
<h2 className="text-content-emphasis text-sm font-medium">
@@ -315,7 +429,7 @@ function BountySubmissionDetailsSheetContent({
</div>
)}
- {Boolean(submission.urls?.length) && (
+ {Boolean(submission.urls?.length) && !hasSocialContent && (
<div>
<h2 className="text-content-emphasis text-sm font-medium">
URLs
@@ -416,19 +530,23 @@ function BountySubmissionDetailsSheetContent({
: undefined
}
disabled={
- isApprovingBountySubmission ||
submission.status === "draft"
}
onClick={() => setShowRejectModal(true)}
/>
<Button
- type="submit"
+ type="button"
variant="primary"
text="Approve"
shortcut="A"
- loading={isApprovingBountySubmission}
- onClick={() => setShowApproveBountySubmissionModal(true)}
+ onClick={() =>
+ openConfirmApproveBountySubmissionModal(
+ submission,
+ bounty ?? null,
+ rewardAmount,
+ )
+ }
disabledTooltip={
submission.status === "draft"
? "Bounty submission is in progress."
@@ -444,7 +562,7 @@ function BountySubmissionDetailsSheetContent({
</div>
<RejectBountySubmissionModal />
- {approveBountySubmissionModal}
+ {ConfirmApproveBountySubmissionModal}
</div>
);
}
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 cb801792a8..4722f6e681 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
@@ -1,7 +1,11 @@
"use client";
-import { PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES } from "@/lib/api/bounties/performance-bounty-scope-attributes";
import { isCurrencyAttribute } from "@/lib/api/workflows/utils";
+import { PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES } from "@/lib/bounty/api/performance-bounty-scope-attributes";
+import { BOUNTY_SUBMISSION_STATUS_BADGES } from "@/lib/bounty/bounty-submission-status-badges";
+import { resolveBountyDetails } from "@/lib/bounty/utils";
+import { mutatePrefix } from "@/lib/swr/mutate";
+import { useApiMutation } from "@/lib/swr/use-api-mutation";
import useBounty from "@/lib/swr/use-bounty";
import {
SubmissionsCountByStatus,
@@ -16,6 +20,7 @@ import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
import { UserRowItem } from "@/ui/users/user-row-item";
import {
AnimatedSizeContainer,
+ Button,
Filter,
ProgressCircle,
StatusBadge,
@@ -32,14 +37,15 @@ import {
fetcher,
formatDate,
nFormatter,
+ timeAgo,
} from "@dub/utils";
import { Row } from "@tanstack/react-table";
import { useParams } from "next/navigation";
-import { useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { toast } from "sonner";
import useSWR from "swr";
import { BountySubmissionDetailsSheet } from "./bounty-submission-details-sheet";
import { BountySubmissionRowMenu } from "./bounty-submission-row-menu";
-import { BOUNTY_SUBMISSION_STATUS_BADGES } from "./bounty-submission-status-badges";
import { useBountySubmissionFilters } from "./use-bounty-submission-filters";
export function BountySubmissionsTable() {
@@ -62,10 +68,17 @@ export function BountySubmissionsTable() {
columns.push("performanceMetrics");
}
+ if (
+ bounty.type === "submission" &&
+ bounty.submissionRequirements?.socialMetrics
+ ) {
+ columns.push("socialMetrics");
+ }
+
return columns;
}, [bounty]);
- // Performance based bounty columns
+ const bountyInfo = resolveBountyDetails(bounty);
const performanceCondition = bounty?.performanceCondition;
const metricColumnLabel = performanceCondition?.attribute
@@ -77,6 +90,13 @@ export function BountySubmissionsTable() {
if (bounty?.type === "performance") return "performanceCount";
+ if (
+ bounty?.type === "submission" &&
+ bounty?.submissionRequirements?.socialMetrics
+ ) {
+ return "socialMetricCount";
+ }
+
return "completedAt";
}, [searchParams, bounty]);
@@ -122,6 +142,24 @@ export function BountySubmissionsTable() {
| { open: true; submission: BountySubmissionProps }
>({ open: false, submission: null });
+ const { isSubmitting: isRefreshingStats, makeRequest } = useApiMutation();
+
+ const refreshStats = useCallback(() => {
+ if (!bountyId) return;
+
+ makeRequest(`/api/bounties/${bountyId}/sync-social-metrics`, {
+ method: "POST",
+ body: {},
+ onSuccess: async () => {
+ toast.success("Stats sync in progress. Updates will appear shortly.");
+ await mutatePrefix(`/api/bounties/${bountyId}`);
+ },
+ onError: (error) => {
+ toast.error(error);
+ },
+ });
+ }, [bountyId, makeRequest]);
+
// Open the details sheet if submissionId is set in params
useEffect(() => {
const submissionId = searchParams.get("submissionId");
@@ -281,6 +319,32 @@ export function BountySubmissionsTable() {
]
: []),
+ ...(showColumns.includes("socialMetrics") &&
+ bountyInfo?.socialPlatform &&
+ bountyInfo?.socialMetrics
+ ? [
+ {
+ id: "socialMetricCount",
+ header: `${bountyInfo.socialPlatform.label} ${capitalize(bountyInfo.socialMetrics.metric)}`,
+ cell: ({ row }: { row: Row<BountySubmissionProps> }) => {
+ const value = row.original.socialMetricCount ?? 0;
+ const minCount = bountyInfo.socialMetrics?.minCount ?? 0;
+ const target = Math.max(minCount, 1);
+ const progress = Math.min(1, value / target);
+
+ return (
+ <div className="flex items-center gap-2">
+ <ProgressCircle progress={progress} />
+ <span className="min-w-0 text-sm font-medium leading-5 text-neutral-600">
+ {nFormatter(value, { full: true })}
+ </span>
+ </div>
+ );
+ },
+ },
+ ]
+ : []),
+
...(showColumns.includes("reviewedAt")
? [
{
@@ -318,6 +382,7 @@ export function BountySubmissionsTable() {
showColumns,
metricColumnLabel,
performanceCondition,
+ bountyInfo,
workspaceId,
],
);
@@ -341,6 +406,7 @@ export function BountySubmissionsTable() {
sortableColumns: [
"completedAt",
...(bounty?.type === "performance" ? ["performanceCount"] : []),
+ ...(showColumns.includes("socialMetrics") ? ["socialMetricCount"] : []),
],
sortBy,
sortOrder,
@@ -386,15 +452,36 @@ export function BountySubmissionsTable() {
<div className="flex flex-col gap-6">
<div>
- <Filter.Select
- className="w-full md:w-fit"
- filters={filters}
- activeFilters={activeFilters}
- onSelect={onSelect}
- onRemove={onRemove}
- onSearchChange={setSearch}
- onSelectedFilterChange={setSelectedFilter}
- />
+ <div className="flex w-full items-center justify-between gap-4">
+ <Filter.Select
+ className="w-full md:w-fit"
+ filters={filters}
+ activeFilters={activeFilters}
+ onSelect={onSelect}
+ onRemove={onRemove}
+ onSearchChange={setSearch}
+ onSelectedFilterChange={setSelectedFilter}
+ />
+ {bountyInfo?.hasSocialMetrics && (submissions?.length ?? 0) > 0 && (
+ <div className="flex shrink-0 items-center gap-3">
+ {bounty?.socialMetricsLastSyncedAt ? (
+ <span className="whitespace-nowrap text-xs font-medium text-neutral-500">
+ Last sync{" "}
+ {timeAgo(bounty.socialMetricsLastSyncedAt, {
+ withAgo: true,
+ })}
+ </span>
+ ) : null}
+ <Button
+ variant="secondary"
+ text="Refresh stats"
+ loading={isRefreshingStats}
+ onClick={refreshStats}
+ className="h-8 rounded-lg px-3"
+ />
+ </div>
+ )}
+ </div>
<AnimatedSizeContainer height>
<div>
{activeFilters.length > 0 && (
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/use-bounty-submission-filters.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/use-bounty-submission-filters.tsx
index 166615a607..440868f94e 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/use-bounty-submission-filters.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/use-bounty-submission-filters.tsx
@@ -1,3 +1,4 @@
+import { BOUNTY_SUBMISSION_STATUS_BADGES } from "@/lib/bounty/bounty-submission-status-badges";
import {
SubmissionsCountByStatus,
useBountySubmissionsCount,
@@ -12,7 +13,6 @@ import { Users, Users6 } from "@dub/ui/icons";
import { cn, nFormatter, OG_AVATAR_URL } from "@dub/utils";
import { useCallback, useMemo, useState } from "react";
import { useDebounce } from "use-debounce";
-import { BOUNTY_SUBMISSION_STATUS_BADGES } from "./bounty-submission-status-badges";
export function useBountySubmissionFilters({
bounty,
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx
deleted file mode 100644
index 34211e1ef7..0000000000
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx
+++ /dev/null
@@ -1,1238 +0,0 @@
-import { generatePerformanceBountyName } from "@/lib/api/bounties/generate-performance-bounty-name";
-import { isCurrencyAttribute } from "@/lib/api/workflows/utils";
-import {
- BOUNTY_DEFAULT_SUBMISSION_URLS,
- BOUNTY_DESCRIPTION_MAX_LENGTH,
- BOUNTY_MAX_SUBMISSION_FILES,
- BOUNTY_MAX_SUBMISSION_URLS,
-} from "@/lib/constants/bounties";
-import { mutatePrefix } from "@/lib/swr/mutate";
-import { useApiMutation } from "@/lib/swr/use-api-mutation";
-import useProgram from "@/lib/swr/use-program";
-import useWorkspace from "@/lib/swr/use-workspace";
-import { BountyProps } from "@/lib/types";
-import {
- bountyPerformanceConditionSchema,
- createBountySchema,
-} from "@/lib/zod/schemas/bounties";
-import { BountyLogic } from "@/ui/partners/bounties/bounty-logic";
-import { GroupsMultiSelect } from "@/ui/partners/groups/groups-multi-select";
-import {
- ProgramSheetAccordion,
- ProgramSheetAccordionContent,
- ProgramSheetAccordionItem,
- ProgramSheetAccordionTrigger,
-} from "@/ui/partners/program-sheet-accordion";
-import { AmountInput } from "@/ui/shared/amount-input";
-import { X } from "@/ui/shared/icons";
-import { MaxCharactersCounter } from "@/ui/shared/max-characters-counter";
-import {
- AnimatedSizeContainer,
- Button,
- CardSelector,
- CardSelectorOption,
- NumberStepper,
- RichTextArea,
- RichTextProvider,
- RichTextToolbar,
- Sheet,
- SmartDateTimePicker,
- Switch,
- ToggleGroup,
- useRouterStuff,
-} from "@dub/ui";
-import { cn, formatDate } from "@dub/utils";
-import { Dispatch, SetStateAction, useMemo, useState } from "react";
-import {
- Controller,
- FormProvider,
- useForm,
- useFormContext,
-} from "react-hook-form";
-import { toast } from "sonner";
-import * as z from "zod/v4";
-import { useConfirmCreateBountyModal } from "./confirm-create-bounty-modal";
-
-type BountySheetProps = {
- setIsOpen: Dispatch<SetStateAction<boolean>>;
- bounty?: BountyProps;
-};
-
-type FormData = z.infer<typeof createBountySchema>;
-
-export const useAddEditBountyForm = () => useFormContext<FormData>();
-
-const BOUNTY_TYPES: CardSelectorOption[] = [
- {
- key: "performance",
- label: "Performance-based",
- description: "Reward for reaching milestones",
- },
- {
- key: "submission",
- label: "Submission",
- description: "Reward for task completion",
- },
-];
-
-// Only valid for submission bounties
-const REWARD_TYPES = [
- {
- value: "flat",
- label: "Flat rate",
- },
- {
- value: "custom",
- label: "Custom",
- },
-];
-
-const ACCORDION_ITEMS = [
- "bounty-type",
- "bounty-details",
- "submission-requirements",
- "groups",
-];
-
-type RewardType = "flat" | "custom";
-
-// Helper to check required fields
-const isEmpty = (value: any) =>
- value === undefined || value === null || value === "";
-
-function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {
- const { program } = useProgram();
- const { id: workspaceId } = useWorkspace();
- const { makeRequest, isSubmitting } = useApiMutation<BountyProps>();
-
- const [hasStartDate, setHasStartDate] = useState(!!bounty?.startsAt);
- const [hasEndDate, setHasEndDate] = useState(!!bounty?.endsAt);
- const [openAccordions, setOpenAccordions] = useState(ACCORDION_ITEMS);
- const originalSubmissionWindow = useMemo(() => {
- return bounty?.submissionsOpenAt && bounty?.endsAt
- ? Math.ceil(
- (new Date(bounty.endsAt).getTime() -
- new Date(bounty.submissionsOpenAt).getTime()) /
- (1000 * 60 * 60 * 24),
- )
- : null;
- }, [bounty]);
- const [submissionWindow, setSubmissionWindow] = useState<number | null>(
- originalSubmissionWindow,
- );
-
- const [requireImage, setRequireImage] = useState(
- () => !!bounty?.submissionRequirements?.image,
- );
-
- const [requireUrl, setRequireUrl] = useState(
- () => !!bounty?.submissionRequirements?.url,
- );
-
- const [imageMax, setImageMax] = useState<number | undefined>(() => {
- return bounty?.submissionRequirements?.image?.max;
- });
-
- const [urlMax, setUrlMax] = useState<number | undefined>(() => {
- return bounty?.submissionRequirements?.url?.max;
- });
-
- const [urlDomains, setUrlDomains] = useState<string[]>(() => {
- return bounty?.submissionRequirements?.url?.domains || [];
- });
-
- const [rewardType, setRewardType] = useState<RewardType>(
- bounty ? (bounty.rewardAmount ? "flat" : "custom") : "flat",
- );
-
- const form = useForm<FormData>({
- defaultValues: {
- name: bounty?.name || undefined,
- description: bounty?.description || undefined,
- startsAt: bounty?.startsAt || undefined,
- endsAt: bounty?.endsAt || undefined,
- submissionsOpenAt: bounty?.submissionsOpenAt || undefined,
- rewardAmount: bounty?.rewardAmount
- ? bounty.rewardAmount / 100
- : undefined,
- rewardDescription: bounty?.rewardDescription || undefined,
- type: bounty?.type || "performance",
- submissionRequirements: bounty?.submissionRequirements || null,
- groupIds: bounty?.groups?.map(({ id }) => id) || null,
- performanceCondition: bounty?.performanceCondition
- ? {
- ...bounty.performanceCondition,
- value: isCurrencyAttribute(bounty.performanceCondition.attribute)
- ? bounty.performanceCondition.value / 100
- : bounty.performanceCondition.value,
- }
- : {
- operator: "gte",
- },
- performanceScope: bounty?.performanceScope ?? "new",
- },
- });
-
- const {
- handleSubmit,
- watch,
- setValue,
- control,
- register,
- formState: { errors, isDirty },
- } = form;
-
- const [
- startsAt,
- endsAt,
- rewardAmount,
- rewardDescription,
- type,
- name,
- description,
- performanceCondition,
- groupIds,
- ] = watch([
- "startsAt",
- "endsAt",
- "rewardAmount",
- "rewardDescription",
- "type",
- "name",
- "description",
- "performanceCondition",
- "groupIds",
- ]);
-
- // Helper functions to update form values
- const handleStartDateToggle = (checked: boolean) => {
- setHasStartDate(checked);
- if (!checked) {
- setValue("startsAt", null, { shouldDirty: true, shouldValidate: true });
- }
- };
-
- const handleEndDateToggle = (checked: boolean) => {
- setHasEndDate(checked);
- if (!checked) {
- setValue("endsAt", null, { shouldDirty: true, shouldValidate: true });
- setSubmissionWindow(null);
- setValue("submissionsOpenAt", null, { shouldDirty: true });
- }
- };
-
- // Update submissionsOpenAt when endsAt or submissionWindow changes
- const handleEndDateChange = (date: Date | null) => {
- setValue("endsAt", date, {
- shouldDirty: true,
- shouldValidate: true,
- });
- if (date && submissionWindow) {
- const submissionsOpenAt = new Date(date);
- submissionsOpenAt.setDate(submissionsOpenAt.getDate() - submissionWindow);
- setValue("submissionsOpenAt", submissionsOpenAt, { shouldDirty: true });
- }
- };
-
- const handleSubmissionWindowToggle = (checked: boolean) => {
- if (checked) {
- setSubmissionWindow(originalSubmissionWindow || 2);
- if (bounty?.submissionsOpenAt) {
- setValue("submissionsOpenAt", bounty.submissionsOpenAt);
- }
- } else {
- setSubmissionWindow(null);
- setValue("submissionsOpenAt", null, { shouldDirty: true });
- }
- };
-
- const handleSubmissionWindowChange = (value: number) => {
- setSubmissionWindow(value);
- if (endsAt) {
- const submissionsOpenAt = new Date(endsAt);
- submissionsOpenAt.setDate(submissionsOpenAt.getDate() - value);
- setValue("submissionsOpenAt", submissionsOpenAt, { shouldDirty: true });
- }
- };
-
- const updateSubmissionRequirements = (
- imageRequired: boolean,
- urlRequired: boolean,
- imageMaxCount?: number,
- urlMaxCount?: number,
- urlDomainsList?: string[],
- ) => {
- const requirements: {
- image?: { max?: number };
- url?: { max?: number; domains?: string[] };
- } = {};
-
- if (imageRequired) {
- requirements.image = {};
- if (imageMaxCount !== undefined) {
- requirements.image.max = imageMaxCount;
- }
- }
-
- if (urlRequired) {
- requirements.url = {};
- if (urlMaxCount !== undefined) {
- requirements.url.max = urlMaxCount;
- }
- if (urlDomainsList && urlDomainsList.length > 0) {
- requirements.url.domains = urlDomainsList;
- }
- }
-
- setValue(
- "submissionRequirements",
- Object.keys(requirements).length > 0 ? requirements : null,
- { shouldDirty: true },
- );
- };
-
- const handleRequireImageToggle = (checked: boolean) => {
- setRequireImage(checked);
- if (!checked) {
- setImageMax(undefined);
- }
- updateSubmissionRequirements(
- checked,
- requireUrl,
- checked ? imageMax : undefined,
- urlMax,
- urlDomains,
- );
- };
-
- const handleRequireUrlToggle = (checked: boolean) => {
- setRequireUrl(checked);
- if (!checked) {
- setUrlMax(undefined);
- setUrlDomains([]);
- }
- updateSubmissionRequirements(
- requireImage,
- checked,
- imageMax,
- checked ? urlMax : undefined,
- checked ? urlDomains : undefined,
- );
- };
-
- const handleImageMaxChange = (value: number) => {
- setImageMax(value);
- updateSubmissionRequirements(
- requireImage,
- requireUrl,
- value,
- urlMax,
- urlDomains,
- );
- };
-
- const handleUrlMaxChange = (value: number) => {
- setUrlMax(value);
- updateSubmissionRequirements(
- requireImage,
- requireUrl,
- imageMax,
- value,
- urlDomains,
- );
- };
-
- const handleAddDomain = (domain: string) => {
- const trimmedDomain = domain.trim().toLowerCase();
- if (trimmedDomain && !urlDomains.includes(trimmedDomain)) {
- const newDomains = [...urlDomains, trimmedDomain];
- setUrlDomains(newDomains);
- updateSubmissionRequirements(
- requireImage,
- requireUrl,
- imageMax,
- urlMax,
- newDomains,
- );
- }
- };
-
- const handleRemoveDomain = (domain: string) => {
- const newDomains = urlDomains.filter((d) => d !== domain);
- setUrlDomains(newDomains);
- updateSubmissionRequirements(
- requireImage,
- requireUrl,
- imageMax,
- urlMax,
- newDomains,
- );
- };
-
- // Comprehensive validation logic
- const validationError = useMemo(() => {
- const now = new Date();
-
- // Date validations
- if (startsAt && startsAt !== bounty?.startsAt) {
- const startDate = new Date(startsAt);
- if (startDate < now) {
- return "Please choose a start date that is in the future.";
- }
- }
-
- const effectiveStartDate = startsAt ? new Date(startsAt) : now;
-
- if (endsAt) {
- const endDate = new Date(endsAt);
-
- if (endDate <= effectiveStartDate) {
- return `Please choose an end date that is after the start date (${formatDate(effectiveStartDate)}).`;
- }
-
- // Ensure end date is at least 1 hour from start
- const minEndDate = new Date(
- effectiveStartDate.getTime() + 60 * 60 * 1000,
- );
- if (endDate < minEndDate) {
- return "End date must be at least 1 hour after the start date.";
- }
- }
-
- // Submission window validations
- if (submissionWindow !== null) {
- if (!endsAt) {
- return "An end date is required to determine when the submission window opens.";
- }
-
- if (submissionWindow < 1 || submissionWindow > 30) {
- return "Submission window must be between 1 and 30 days.";
- }
-
- // Check if submission window doesn't push submissionsOpenAt before start date
- const calculatedSubmissionsOpenAt = new Date(endsAt);
- calculatedSubmissionsOpenAt.setDate(
- calculatedSubmissionsOpenAt.getDate() - submissionWindow,
- );
-
- if (calculatedSubmissionsOpenAt <= effectiveStartDate) {
- return "Submission window is too long. It would open before the bounty starts.";
- }
- }
-
- // Type-specific validations
- if (type === "submission") {
- if (!name?.trim()) {
- return "Name is required for submission bounties.";
- }
-
- if (name && name.length > 100) {
- return "Name must be 100 characters or less.";
- }
-
- if (rewardType === "flat") {
- if (isEmpty(rewardAmount)) {
- return "Reward amount is required for flat rate rewards.";
- }
- if (rewardAmount !== null && rewardAmount <= 0) {
- return "Reward amount must be greater than 0.";
- }
- if (rewardAmount !== null && rewardAmount > 1000000) {
- return "Reward amount cannot exceed $1,000,000.";
- }
- }
-
- if (rewardType === "custom") {
- if (!rewardDescription?.trim()) {
- return "Reward description is required for custom rewards.";
- }
- if (rewardDescription && rewardDescription.length > 100) {
- return "Reward description must be 100 characters or less.";
- }
- }
- }
-
- if (type === "performance") {
- const condition = performanceCondition;
-
- if (!condition?.attribute) {
- return "Performance attribute is required.";
- }
-
- if (!condition?.operator) {
- return "Performance operator is required.";
- }
-
- if (isEmpty(condition?.value)) {
- return "Performance value is required.";
- }
-
- if (condition?.value !== null && condition.value < 0) {
- return "Performance value must be greater than or equal to 0.";
- }
-
- if (isEmpty(rewardAmount)) {
- return "Reward amount is required for performance bounties.";
- }
-
- if (rewardAmount !== null && rewardAmount <= 0) {
- return "Reward amount must be greater than 0.";
- }
-
- if (rewardAmount !== null && rewardAmount > 1000000) {
- return "Reward amount cannot exceed $1,000,000.";
- }
- }
-
- // Description validation
- if (description && description.length > BOUNTY_DESCRIPTION_MAX_LENGTH) {
- return `Description must be ${BOUNTY_DESCRIPTION_MAX_LENGTH} characters or less.`;
- }
-
- return null;
- }, [
- bounty,
- startsAt,
- endsAt,
- rewardAmount,
- rewardDescription,
- submissionWindow,
- rewardType,
- type,
- name,
- description,
- performanceCondition?.attribute,
- performanceCondition?.operator,
- performanceCondition?.value,
- ]);
-
- const { setShowConfirmCreateBountyModal, confirmCreateBountyModal } =
- useConfirmCreateBountyModal({
- bounty: !validationError
- ? {
- type,
- name:
- type === "performance" && performanceCondition
- ? generatePerformanceBountyName({
- rewardAmount: rewardAmount ? rewardAmount * 100 : 0,
- condition: isCurrencyAttribute(
- performanceCondition?.attribute,
- )
- ? {
- ...performanceCondition,
- value: performanceCondition?.value * 100,
- }
- : performanceCondition,
- })
- : name || "New bounty",
- startsAt: startsAt || new Date(),
- endsAt: endsAt || null,
- rewardAmount: rewardAmount ? rewardAmount * 100 : null,
- rewardDescription: rewardDescription || null,
- groups: groupIds?.map((id) => ({ id })) || [],
- }
- : undefined,
- onConfirm: async ({ sendNotificationEmails }) => {
- await performSubmit({ sendNotificationEmails });
- },
- });
-
- // Handle actual form submission (called after confirmation)
- const performSubmit = async ({
- sendNotificationEmails,
- }: { sendNotificationEmails?: boolean } = {}) => {
- if (!workspaceId) return;
-
- const data = form.getValues();
-
- data.rewardAmount = data.rewardAmount ? data.rewardAmount * 100 : null;
-
- // Parse performance logic
- if (data.type === "performance") {
- const result = bountyPerformanceConditionSchema.safeParse(
- data.performanceCondition,
- );
-
- if (!result.success) {
- toast.error(
- "Invalid performance logic. Please fix the errors and try again.",
- );
- return;
- }
-
- let { data: condition } = result;
-
- // Format the value to be in cents if it's a currency attribute
- condition = {
- ...condition,
- value: isCurrencyAttribute(condition.attribute)
- ? condition.value * 100
- : condition.value,
- };
-
- data.performanceCondition = condition;
- data.rewardDescription = null;
- data.submissionsOpenAt = null;
- } else if (type === "submission") {
- data.performanceCondition = null;
-
- if (rewardType === "custom") {
- data.rewardAmount = null;
- } else if (rewardType === "flat") {
- data.rewardDescription = null;
- }
- }
-
- await makeRequest(bounty ? `/api/bounties/${bounty.id}` : "/api/bounties", {
- method: bounty ? "PATCH" : "POST",
- body: { ...data, sendNotificationEmails },
- onSuccess: () => {
- mutatePrefix("/api/bounties");
- setIsOpen(false);
- toast.success(`Bounty ${bounty ? "updated" : "created"} successfully!`);
- },
- });
- };
-
- // Handle form submission (shows confirmation modal for creation only)
- const onSubmit = handleSubmit(async () => {
- if (bounty) {
- // For updates, submit directly without confirmation
- await performSubmit();
- } else {
- // For creation, show confirmation modal
- setShowConfirmCreateBountyModal(true);
- }
- });
-
- return (
- <form onSubmit={onSubmit} className="flex h-full flex-col">
- <div className="sticky top-0 z-10 border-b border-neutral-200 bg-white">
- <div className="flex h-16 items-center justify-between px-6 py-4">
- <Sheet.Title className="text-lg font-semibold">
- {bounty ? "Update" : "Create"} bounty
- </Sheet.Title>
- <Sheet.Close asChild>
- <Button
- variant="outline"
- icon={<X className="size-5" />}
- className="h-auto w-fit p-1"
- />
- </Sheet.Close>
- </div>
- </div>
-
- <FormProvider {...form}>
- <div className="flex-1 overflow-y-auto">
- <div className="p-6">
- <ProgramSheetAccordion
- type="multiple"
- value={openAccordions}
- onValueChange={setOpenAccordions}
- className="space-y-6"
- >
- {!bounty && ( // cannot change type for existing bounties
- <ProgramSheetAccordionItem value="bounty-type">
- <ProgramSheetAccordionTrigger>
- Bounty type
- </ProgramSheetAccordionTrigger>
- <ProgramSheetAccordionContent>
- <div className="space-y-4">
- <p className="text-content-default text-sm">
- Set how the bounty will be completed
- </p>
- <CardSelector
- options={BOUNTY_TYPES}
- value={watch("type")}
- onChange={(value: FormData["type"]) =>
- setValue("type", value)
- }
- name="bounty-type"
- />
- </div>
- </ProgramSheetAccordionContent>
- </ProgramSheetAccordionItem>
- )}
-
- <ProgramSheetAccordionItem value="bounty-details">
- <ProgramSheetAccordionTrigger>
- Bounty details
- </ProgramSheetAccordionTrigger>
- <ProgramSheetAccordionContent>
- <div className="space-y-6">
- <p className="text-content-default text-sm">
- Set the schedule, reward, and additional details.
- </p>
-
- <AnimatedSizeContainer
- height
- transition={{ ease: "easeInOut", duration: 0.2 }}
- style={{
- height: hasStartDate ? "auto" : "0px",
- overflow: "hidden",
- }}
- >
- <div className="flex items-center gap-4">
- <Switch
- fn={handleStartDateToggle}
- checked={hasStartDate}
- trackDimensions="w-8 h-4"
- thumbDimensions="w-3 h-3"
- thumbTranslate="translate-x-4"
- disabled={Boolean(bounty?.startsAt)}
- />
- <div className="flex flex-col gap-1">
- <h3 className="text-sm font-medium text-neutral-700">
- Start date
- </h3>
- </div>
- </div>
-
- {hasStartDate && (
- <div className="mt-3 p-px">
- <Controller
- control={control}
- name="startsAt"
- render={({ field }) => (
- <SmartDateTimePicker
- value={field.value}
- onChange={(date) =>
- field.onChange(date ?? undefined)
- }
- placeholder='E.g. "2024-03-01", "Last Thursday", "2 hours ago"'
- />
- )}
- />
- {errors.startsAt && "test"}
- </div>
- )}
- </AnimatedSizeContainer>
-
- <AnimatedSizeContainer
- height
- transition={{ ease: "easeInOut", duration: 0.2 }}
- style={{
- height: hasEndDate ? "auto" : "0px",
- overflow: "hidden",
- }}
- >
- <div className="flex items-center gap-4">
- <Switch
- fn={handleEndDateToggle}
- checked={hasEndDate}
- trackDimensions="w-8 h-4"
- thumbDimensions="w-3 h-3"
- thumbTranslate="translate-x-4"
- />
- <div className="flex flex-col gap-1">
- <h3 className="text-sm font-medium text-neutral-700">
- End date
- </h3>
- </div>
- </div>
-
- {hasEndDate && (
- <div className="mt-3 p-px">
- <Controller
- control={control}
- name="endsAt"
- render={({ field }) => (
- <SmartDateTimePicker
- value={field.value}
- onChange={(date) =>
- handleEndDateChange(date ?? null)
- }
- placeholder='E.g. "in 3 months"'
- />
- )}
- />
- </div>
- )}
- </AnimatedSizeContainer>
-
- {type === "submission" && (
- <>
- <AnimatedSizeContainer
- height
- transition={{ ease: "easeInOut", duration: 0.2 }}
- style={{
- height: submissionWindow ? "auto" : "0px",
- overflow: "hidden",
- }}
- >
- <div className="flex items-center gap-4">
- <Switch
- fn={handleSubmissionWindowToggle}
- checked={submissionWindow !== null}
- trackDimensions="w-8 h-4"
- thumbDimensions="w-3 h-3"
- thumbTranslate="translate-x-4"
- disabled={!Boolean(endsAt)}
- />
- <div className="flex flex-col gap-1">
- <h3 className="text-sm font-medium text-neutral-700">
- Submission window
- </h3>
- </div>
- </div>
-
- {submissionWindow !== null && (
- <div className="mt-3 p-px">
- <NumberStepper
- value={submissionWindow ?? 2}
- onChange={handleSubmissionWindowChange}
- min={1} // Min 1 day
- max={30} // Max 30 days
- step={1}
- className="w-full"
- />
- <p className="mt-2 text-xs text-neutral-500">
- Submissions open {submissionWindow} days before
- the end date. Drafts can be saved until then.
- </p>
- </div>
- )}
- </AnimatedSizeContainer>
-
- <div>
- <label
- htmlFor="name"
- className="text-sm font-medium text-neutral-800"
- >
- Name
- </label>
- <div className="mt-2">
- <input
- id="name"
- type="text"
- maxLength={100}
- className={cn(
- "block w-full rounded-md border-neutral-300 px-3 py-2 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
- errors.name &&
- "border-red-600 focus:border-red-500 focus:ring-red-600",
- )}
- placeholder={`Create a YouTube video about${program?.name ? ` ${program.name}` : ""}...`}
- {...register("name", {
- setValueAs: (value) =>
- value === "" ? null : value,
- })}
- />
- <div className="mt-1 text-left">
- <span className="text-xs text-neutral-400">
- {name?.length || 0}/100
- </span>
- </div>
- </div>
- </div>
-
- <ToggleGroup
- className="mt-2 flex w-full items-center gap-1 rounded-md border border-neutral-200 bg-neutral-100 p-1"
- optionClassName="h-8 flex items-center justify-center rounded-md flex-1 text-sm"
- indicatorClassName="bg-white border-none rounded-md"
- options={REWARD_TYPES}
- selected={rewardType}
- selectAction={(id: RewardType) => setRewardType(id)}
- />
- </>
- )}
-
- {(rewardType === "flat" || type === "performance") && (
- <div>
- <label
- htmlFor="rewardAmount"
- className="text-sm font-medium text-neutral-800"
- >
- Reward
- </label>
- <div className="mt-2">
- <Controller
- name="rewardAmount"
- control={control}
- rules={{
- required: true,
- min: 0,
- }}
- render={({ field }) => (
- <AmountInput
- {...field}
- id="rewardAmount"
- amountType="flat"
- placeholder="200"
- error={errors.rewardAmount?.message}
- value={
- field.value == null || isNaN(field.value)
- ? ""
- : field.value
- }
- onChange={(e) => {
- const val = e.target.value;
-
- field.onChange(
- val === "" ? null : parseFloat(val),
- );
- }}
- />
- )}
- />
- </div>
- </div>
- )}
-
- {rewardType === "custom" && type === "submission" && (
- <div>
- <label
- htmlFor="rewardDescription"
- className="text-sm font-medium text-neutral-800"
- >
- Reward
- </label>
- <div className="mt-2">
- <input
- id="rewardDescription"
- type="text"
- maxLength={100}
- className={cn(
- "block w-full rounded-md border-neutral-300 px-3 py-2 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
- errors.rewardDescription &&
- "border-red-600 focus:border-red-500 focus:ring-red-600",
- )}
- placeholder="Earn an additional 10% if you hit your revenue goal"
- {...register("rewardDescription", {
- setValueAs: (value) =>
- value === "" ? null : value,
- })}
- />
- <div className="mt-1 text-left">
- <span className="text-xs text-neutral-400">
- {rewardDescription?.length || 0}/100
- </span>
- </div>
- </div>
- </div>
- )}
-
- {type === "performance" && (
- <div>
- <span className="text-sm font-medium text-neutral-800">
- Logic
- </span>
- <BountyLogic className="mt-2" />
- </div>
- )}
-
- <div>
- <label className="text-sm font-medium text-neutral-800">
- Details
- <span className="ml-1 font-normal text-neutral-500">
- (optional)
- </span>
- </label>
- <div className="mt-2">
- <Controller
- control={control}
- name="description"
- render={({ field }) => (
- <RichTextProvider
- features={["bold", "italic", "links"]}
- markdown
- placeholder="Provide any bounty requirements to the partner"
- editorClassName="block max-h-48 overflow-auto scrollbar-hide w-full resize-none border-none p-3 text-base sm:text-sm"
- initialValue={field.value}
- onChange={(editor) =>
- field.onChange(
- (editor as any).getMarkdown() || null,
- )
- }
- >
- <div
- className={cn(
- "overflow-hidden rounded-md border border-neutral-300 focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500",
- errors.description &&
- "border-red-600 focus-within:border-red-500 focus-within:ring-red-600",
- )}
- >
- <div className="flex flex-col">
- <RichTextArea />
- <RichTextToolbar className="px-1 pb-1" />
- </div>
- </div>
- </RichTextProvider>
- )}
- />
-
- <div className="mt-1 text-left">
- <MaxCharactersCounter
- name="description"
- control={control}
- maxLength={BOUNTY_DESCRIPTION_MAX_LENGTH}
- spaced
- className="text-content-muted"
- />
- </div>
- </div>
- </div>
-
- {rewardType === "custom" && (
- <div className="gap-4 rounded-lg bg-orange-50 px-4 py-2.5 text-center">
- <span className="text-sm font-medium text-orange-800">
- When reviewing these submissions, a custom reward
- amount will be required to approve.
- </span>
- </div>
- )}
- </div>
- </ProgramSheetAccordionContent>
- </ProgramSheetAccordionItem>
-
- {type === "submission" && (
- <ProgramSheetAccordionItem value="submission-requirements">
- <ProgramSheetAccordionTrigger>
- Submission requirements
- </ProgramSheetAccordionTrigger>
- <ProgramSheetAccordionContent>
- <div className="space-y-6">
- <p className="text-content-default text-sm">
- Set how partners should submit proof of their work. By
- default an open text field is provided.
- </p>
-
- <div className="space-y-6">
- <div className="space-y-4">
- <div className="flex items-center gap-4">
- <Switch
- fn={handleRequireImageToggle}
- checked={requireImage}
- trackDimensions="w-8 h-4"
- thumbDimensions="w-3 h-3"
- thumbTranslate="translate-x-4"
- />
- <div className="flex flex-col gap-1">
- <h3 className="text-sm font-medium text-neutral-700">
- Require at least one image
- </h3>
- </div>
- </div>
-
- {requireImage && (
- <div className="space-y-3 rounded-lg border border-neutral-200 bg-neutral-50/50 p-4">
- <label className="text-sm font-medium text-neutral-700">
- Maximum images
- <span className="ml-1 font-normal text-neutral-500">
- (optional)
- </span>
- </label>
- <NumberStepper
- value={imageMax ?? BOUNTY_MAX_SUBMISSION_FILES}
- onChange={handleImageMaxChange}
- min={1}
- max={BOUNTY_MAX_SUBMISSION_FILES}
- step={1}
- className="h-9 w-full [&>div]:h-9"
- />
- <p className="text-xs text-neutral-500">
- Set a maximum number of images partners can
- submit
- </p>
- </div>
- )}
-
- <div className="flex items-center gap-4">
- <Switch
- fn={handleRequireUrlToggle}
- checked={requireUrl}
- trackDimensions="w-8 h-4"
- thumbDimensions="w-3 h-3"
- thumbTranslate="translate-x-4"
- />
- <div className="flex flex-col gap-1">
- <h3 className="text-sm font-medium text-neutral-700">
- Require at least one URL
- </h3>
- </div>
- </div>
-
- {requireUrl && (
- <div className="space-y-4">
- <div className="space-y-3 rounded-lg border border-neutral-200 bg-neutral-50/50 p-4">
- <label className="text-sm font-medium text-neutral-700">
- Maximum URLs
- <span className="ml-1 font-normal text-neutral-500">
- (optional)
- </span>
- </label>
- <NumberStepper
- value={
- urlMax ?? BOUNTY_DEFAULT_SUBMISSION_URLS
- }
- onChange={handleUrlMaxChange}
- min={1}
- max={BOUNTY_MAX_SUBMISSION_URLS}
- step={1}
- className="h-9 w-full [&>div]:h-9"
- />
- <p className="text-xs text-neutral-500">
- Set a maximum number of URLs partners can
- submit
- </p>
- </div>
-
- <div className="space-y-3 rounded-lg border border-neutral-200 bg-neutral-50/50 p-4">
- <label className="text-sm font-medium text-neutral-700">
- Allowed domains
- <span className="ml-1 font-normal text-neutral-500">
- (optional)
- </span>
- </label>
- <div className="flex gap-2">
- <input
- type="text"
- placeholder="e.g. x.com"
- className={cn(
- "block h-9 flex-1 rounded-md border-neutral-300 px-3 py-1.5 text-sm text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500",
- )}
- onKeyDown={(e) => {
- if (e.key === "Enter") {
- e.preventDefault();
- const input = e.currentTarget;
- handleAddDomain(input.value);
- input.value = "";
- }
- }}
- />
- <Button
- type="button"
- variant="secondary"
- text="Add"
- className="h-9 w-fit px-3"
- onClick={(e) => {
- const input = e.currentTarget
- .previousElementSibling as HTMLInputElement;
- if (input) {
- handleAddDomain(input.value);
- input.value = "";
- }
- }}
- />
- </div>
- {urlDomains.length > 0 && (
- <div className="mt-2 flex flex-wrap gap-2">
- {urlDomains.map((domain) => (
- <div
- key={domain}
- className="flex items-center gap-1.5 rounded-md bg-neutral-100 px-2.5 py-1.5 text-sm text-neutral-700"
- >
- <span>{domain}</span>
- <button
- type="button"
- onClick={() =>
- handleRemoveDomain(domain)
- }
- className="text-neutral-400 hover:text-neutral-600"
- >
- <X className="size-3.5" />
- </button>
- </div>
- ))}
- </div>
- )}
- <p className="text-xs text-neutral-500">
- Restrict URLs to specific domains. Partners
- can submit URLs from these domains or their
- subdomains.
- </p>
- </div>
- </div>
- )}
- </div>
- </div>
- </div>
- </ProgramSheetAccordionContent>
- </ProgramSheetAccordionItem>
- )}
-
- <ProgramSheetAccordionItem value="groups">
- <ProgramSheetAccordionTrigger>
- Groups
- </ProgramSheetAccordionTrigger>
- <ProgramSheetAccordionContent>
- <Controller
- control={control}
- name="groupIds"
- render={({ field }) => (
- <GroupsMultiSelect
- selectedGroupIds={field.value}
- setSelectedGroupIds={(ids) => field.onChange(ids)}
- />
- )}
- />
- </ProgramSheetAccordionContent>
- </ProgramSheetAccordionItem>
- </ProgramSheetAccordion>
- </div>
- </div>
-
- <div className="sticky bottom-0 z-10 border-t border-neutral-200 bg-white">
- <div className="flex items-center justify-end gap-2 p-5">
- <Button
- type="button"
- variant="secondary"
- onClick={() => setIsOpen(false)}
- text="Cancel"
- className="w-fit"
- disabled={isSubmitting}
- />
-
- <Button
- type="submit"
- variant="primary"
- text={bounty ? "Update bounty" : "Create bounty"}
- className="w-fit"
- loading={isSubmitting}
- disabled={Boolean(validationError) || (bounty && !isDirty)}
- disabledTooltip={
- validationError ||
- (bounty && !isDirty ? "No changes to save" : undefined)
- }
- />
- </div>
- </div>
- </FormProvider>
- {!bounty && confirmCreateBountyModal}
- </form>
- );
-}
-
-export function BountySheet({
- isOpen,
- nested,
- ...rest
-}: BountySheetProps & {
- isOpen: boolean;
- nested?: boolean;
-}) {
- const { queryParams } = useRouterStuff();
-
- return (
- <Sheet
- open={isOpen}
- onOpenChange={rest.setIsOpen}
- onClose={() => queryParams({ del: "bountyId", scroll: false })}
- nested={nested}
- >
- <BountySheetContent {...rest} />
- </Sheet>
- );
-}
-
-export function useBountySheet(
- props: { nested?: boolean } & Omit<BountySheetProps, "setIsOpen"> = {},
-) {
- const [isOpen, setIsOpen] = useState(false);
-
- return {
- BountySheet: (
- <BountySheet setIsOpen={setIsOpen} isOpen={isOpen} {...props} />
- ),
- setShowCreateBountySheet: setIsOpen,
- };
-}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/add-edit-bounty-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/add-edit-bounty-sheet.tsx
new file mode 100644
index 0000000000..0f5be34cac
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/add-edit-bounty-sheet.tsx
@@ -0,0 +1,507 @@
+import { BOUNTY_DESCRIPTION_MAX_LENGTH } from "@/lib/bounty/constants";
+import { getPlanCapabilities } from "@/lib/plan-capabilities";
+import useProgram from "@/lib/swr/use-program";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { BountyProps, CreateBountyInput } from "@/lib/types";
+import { GroupsMultiSelect } from "@/ui/partners/groups/groups-multi-select";
+import {
+ ProgramSheetAccordion,
+ ProgramSheetAccordionContent,
+ ProgramSheetAccordionItem,
+ ProgramSheetAccordionTrigger,
+} from "@/ui/partners/program-sheet-accordion";
+import { X } from "@/ui/shared/icons";
+import { MaxCharactersCounter } from "@/ui/shared/max-characters-counter";
+import {
+ AnimatedSizeContainer,
+ Button,
+ CardSelector,
+ CardSelectorOption,
+ NumberStepper,
+ RichTextArea,
+ RichTextProvider,
+ RichTextToolbar,
+ Sheet,
+ SmartDateTimePicker,
+ Switch,
+ TooltipContent,
+ useRouterStuff,
+} from "@dub/ui";
+import { cn } from "@dub/utils";
+import { Dispatch, SetStateAction, useState } from "react";
+import { Controller, FormProvider } from "react-hook-form";
+import { BountyCriteria } from "./bounty-criteria";
+import { useAddEditBountyForm } from "./use-add-edit-bounty-form";
+
+interface BountySheetProps {
+ setIsOpen: Dispatch<SetStateAction<boolean>>;
+ bounty?: BountyProps;
+}
+
+const BOUNTY_TYPES: CardSelectorOption[] = [
+ {
+ key: "performance",
+ label: "Performance",
+ description: "Reward for reaching milestones",
+ },
+ {
+ key: "submission",
+ label: "Submission",
+ description: "Reward for task completion",
+ },
+];
+
+function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {
+ const { program } = useProgram();
+ const { plan, slug: workspaceSlug } = useWorkspace();
+
+ const {
+ form,
+ openAccordions,
+ setOpenAccordions,
+ hasStartDate,
+ handleStartDateToggle,
+ hasEndDate,
+ handleEndDateToggle,
+ handleEndDateChange,
+ submissionWindow,
+ handleSubmissionWindowToggle,
+ handleSubmissionWindowChange,
+ type,
+ name,
+ control,
+ register,
+ setValue,
+ watch,
+ errors,
+ isDirty,
+ validationError,
+ confirmCreateBountyModal,
+ onSubmit,
+ isSubmitting,
+ } = useAddEditBountyForm({ bounty, setIsOpen });
+
+ const submissionRequirements = watch("submissionRequirements");
+ const hasSocialMetrics =
+ submissionRequirements &&
+ typeof submissionRequirements === "object" &&
+ "socialMetrics" in submissionRequirements;
+ const canUseBountySocialMetrics =
+ getPlanCapabilities(plan).canUseBountySocialMetrics;
+ const showBountySocialMetricsUpsell =
+ hasSocialMetrics && !canUseBountySocialMetrics;
+
+ return (
+ <form onSubmit={onSubmit} className="flex h-full flex-col">
+ <div className="sticky top-0 z-10 border-b border-neutral-200 bg-white">
+ <div className="flex h-16 items-center justify-between px-6 py-4">
+ <Sheet.Title className="text-lg font-semibold">
+ {bounty ? "Update" : "Create"} bounty
+ </Sheet.Title>
+ <Sheet.Close asChild>
+ <Button
+ variant="outline"
+ icon={<X className="size-5" />}
+ className="h-auto w-fit p-1"
+ />
+ </Sheet.Close>
+ </div>
+ </div>
+
+ <FormProvider {...form}>
+ <div className="flex-1 overflow-y-auto">
+ <div className="p-6">
+ <ProgramSheetAccordion
+ type="multiple"
+ value={openAccordions}
+ onValueChange={setOpenAccordions}
+ className="space-y-6"
+ >
+ {!bounty && ( // cannot change type for existing bounties
+ <ProgramSheetAccordionItem value="bounty-type">
+ <ProgramSheetAccordionTrigger>
+ Type
+ </ProgramSheetAccordionTrigger>
+ <ProgramSheetAccordionContent>
+ <div className="space-y-4">
+ <p className="text-content-default text-sm">
+ Set how the bounty will be completed
+ </p>
+ <CardSelector
+ options={BOUNTY_TYPES}
+ value={watch("type")}
+ onChange={(value: CreateBountyInput["type"]) =>
+ setValue("type", value)
+ }
+ name="bounty-type"
+ />
+ </div>
+ </ProgramSheetAccordionContent>
+ </ProgramSheetAccordionItem>
+ )}
+
+ <ProgramSheetAccordionItem value="bounty-details">
+ <ProgramSheetAccordionTrigger>
+ Details
+ </ProgramSheetAccordionTrigger>
+ <ProgramSheetAccordionContent>
+ <div className="space-y-6">
+ <p className="text-content-default text-sm">
+ Set the schedule, reward and additional details.
+ </p>
+
+ <AnimatedSizeContainer
+ height
+ transition={{ ease: "easeInOut", duration: 0.2 }}
+ style={{
+ height: hasStartDate ? "auto" : "0px",
+ overflow: "hidden",
+ }}
+ >
+ <div className="flex items-center gap-4">
+ <Switch
+ fn={handleStartDateToggle}
+ checked={hasStartDate}
+ trackDimensions="w-8 h-4"
+ thumbDimensions="w-3 h-3"
+ thumbTranslate="translate-x-4"
+ disabled={Boolean(bounty?.startsAt)}
+ />
+ <div className="flex flex-col gap-1">
+ <h3 className="text-sm font-medium text-neutral-700">
+ Start date
+ </h3>
+ </div>
+ </div>
+
+ {hasStartDate && (
+ <div className="mt-3 p-px">
+ <Controller
+ control={control}
+ name="startsAt"
+ render={({ field }) => (
+ <SmartDateTimePicker
+ value={field.value}
+ onChange={(date) =>
+ field.onChange(date ?? undefined)
+ }
+ placeholder='E.g. "2026-02-28", "Last Thursday", "2 hours ago"'
+ />
+ )}
+ />
+ </div>
+ )}
+ </AnimatedSizeContainer>
+
+ {type === "performance" && (
+ <AnimatedSizeContainer
+ height
+ transition={{ ease: "easeInOut", duration: 0.2 }}
+ style={{
+ height: hasEndDate ? "auto" : "0px",
+ overflow: "hidden",
+ }}
+ >
+ <div className="flex items-center gap-4">
+ <Switch
+ fn={handleEndDateToggle}
+ checked={hasEndDate}
+ trackDimensions="w-8 h-4"
+ thumbDimensions="w-3 h-3"
+ thumbTranslate="translate-x-4"
+ disabled={Boolean(bounty?.endsAt)}
+ />
+ <div className="flex flex-col gap-1">
+ <h3 className="text-sm font-medium text-neutral-700">
+ End date
+ </h3>
+ </div>
+ </div>
+
+ {hasEndDate && (
+ <div className="mt-3 p-px">
+ <Controller
+ control={control}
+ name="endsAt"
+ render={({ field }) => (
+ <SmartDateTimePicker
+ value={field.value}
+ onChange={(date) =>
+ handleEndDateChange(date ?? null)
+ }
+ placeholder='E.g. "2026-12-01", "Next Thursday", "After 10 days"'
+ />
+ )}
+ />
+ </div>
+ )}
+ </AnimatedSizeContainer>
+ )}
+
+ {type === "submission" && (
+ <AnimatedSizeContainer
+ height
+ transition={{ ease: "easeInOut", duration: 0.2 }}
+ style={{
+ height: hasEndDate ? "auto" : "0px",
+ overflow: "hidden",
+ }}
+ >
+ <div className="flex items-center gap-4">
+ <Switch
+ fn={handleEndDateToggle}
+ checked={hasEndDate}
+ trackDimensions="w-8 h-4"
+ thumbDimensions="w-3 h-3"
+ thumbTranslate="translate-x-4"
+ disabled={Boolean(bounty?.endsAt)}
+ />
+ <div className="flex flex-col gap-1">
+ <h3 className="text-sm font-medium text-neutral-700">
+ End date
+ </h3>
+ </div>
+ </div>
+
+ {hasEndDate && (
+ <div className="mt-3 p-px">
+ <Controller
+ control={control}
+ name="endsAt"
+ render={({ field }) => (
+ <SmartDateTimePicker
+ value={field.value}
+ onChange={(date) =>
+ handleEndDateChange(date ?? null)
+ }
+ placeholder='E.g. "2026-12-01", "Next Thursday", "After 10 days"'
+ />
+ )}
+ />
+ </div>
+ )}
+ </AnimatedSizeContainer>
+ )}
+
+ {type === "submission" && (
+ <>
+ <div className="flex items-center gap-4">
+ <Switch
+ fn={handleSubmissionWindowToggle}
+ checked={submissionWindow != null}
+ trackDimensions="w-8 h-4"
+ thumbDimensions="w-3 h-3"
+ thumbTranslate="translate-x-4"
+ disabled={!hasEndDate}
+ />
+ <div className="flex flex-col gap-1">
+ <h3 className="text-sm font-medium text-neutral-700">
+ Submission window
+ </h3>
+ </div>
+ </div>
+
+ {submissionWindow != null && (
+ <div className="mt-3 space-y-2">
+ <NumberStepper
+ value={submissionWindow}
+ onChange={handleSubmissionWindowChange}
+ min={2}
+ max={14}
+ step={1}
+ className="w-full"
+ />
+ <p className="text-sm text-neutral-500">
+ Submissions open {submissionWindow} days before
+ the end date. Drafts can be saved until then.
+ </p>
+ </div>
+ )}
+ </>
+ )}
+
+ {type === "submission" && (
+ <>
+ <div>
+ <label
+ htmlFor="name"
+ className="text-sm font-medium text-neutral-800"
+ >
+ Name
+ </label>
+ <div className="mt-2">
+ <input
+ id="name"
+ type="text"
+ maxLength={100}
+ className={cn(
+ "block w-full rounded-md border-neutral-300 px-3 py-2 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
+ errors.name &&
+ "border-red-600 focus:border-red-500 focus:ring-red-600",
+ )}
+ placeholder={`Create a YouTube video about${program?.name ? ` ${program.name}` : ""}...`}
+ {...register("name", {
+ setValueAs: (value) =>
+ value === "" ? null : value,
+ })}
+ />
+ <div className="mt-1 text-left">
+ <span className="text-xs text-neutral-400">
+ {name?.length || 0}/100
+ </span>
+ </div>
+ </div>
+ </div>
+ </>
+ )}
+
+ <div>
+ <label className="text-sm font-medium text-neutral-800">
+ Description
+ <span className="ml-1 font-normal text-neutral-500">
+ (optional)
+ </span>
+ </label>
+ <div className="mt-2">
+ <Controller
+ control={control}
+ name="description"
+ render={({ field }) => (
+ <RichTextProvider
+ features={["bold", "italic", "links"]}
+ markdown
+ placeholder="Provide any bounty requirements to the partner"
+ editorClassName="block max-h-48 overflow-auto scrollbar-hide w-full resize-none border-none p-3 text-base sm:text-sm"
+ initialValue={field.value}
+ onChange={(editor: any) =>
+ field.onChange(editor.getMarkdown() || null)
+ }
+ >
+ <div
+ className={cn(
+ "overflow-hidden rounded-md border border-neutral-300 focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500",
+ errors.description &&
+ "border-red-600 focus-within:border-red-500 focus-within:ring-red-600",
+ )}
+ >
+ <div className="flex flex-col">
+ <RichTextArea />
+ <RichTextToolbar className="px-1 pb-1" />
+ </div>
+ </div>
+ </RichTextProvider>
+ )}
+ />
+
+ <div className="mt-1 text-left">
+ <MaxCharactersCounter
+ name="description"
+ control={control}
+ maxLength={BOUNTY_DESCRIPTION_MAX_LENGTH}
+ spaced
+ className="text-content-muted"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ </ProgramSheetAccordionContent>
+ </ProgramSheetAccordionItem>
+
+ <BountyCriteria />
+
+ <ProgramSheetAccordionItem value="groups">
+ <ProgramSheetAccordionTrigger>
+ Groups
+ </ProgramSheetAccordionTrigger>
+ <ProgramSheetAccordionContent>
+ <Controller
+ control={control}
+ name="groupIds"
+ render={({ field }) => (
+ <GroupsMultiSelect
+ selectedGroupIds={field.value}
+ setSelectedGroupIds={(ids) => field.onChange(ids)}
+ />
+ )}
+ />
+ </ProgramSheetAccordionContent>
+ </ProgramSheetAccordionItem>
+ </ProgramSheetAccordion>
+ </div>
+ </div>
+
+ <div className="sticky bottom-0 z-10 border-t border-neutral-200 bg-white">
+ <div className="flex items-center justify-end gap-2 p-5">
+ <Button
+ type="button"
+ variant="secondary"
+ onClick={() => setIsOpen(false)}
+ text="Cancel"
+ className="h-9 w-fit"
+ disabled={isSubmitting}
+ />
+
+ <Button
+ type="submit"
+ variant="primary"
+ text={bounty ? "Update bounty" : "Create bounty"}
+ className="h-9 w-fit"
+ loading={isSubmitting}
+ disabled={Boolean(validationError) || (bounty && !isDirty)}
+ disabledTooltip={
+ showBountySocialMetricsUpsell ? (
+ <TooltipContent
+ title="[Social metrics bounties](https://dub.co/help/article/program-bounties#social-metrics-bounties) are only available on the Advanced plan and above."
+ cta="Upgrade to Advanced"
+ href={`/${workspaceSlug}/upgrade?showPartnersUpgradeModal=true`}
+ target="_blank"
+ />
+ ) : (
+ validationError ||
+ (bounty && !isDirty ? "No changes to save" : undefined)
+ )
+ }
+ />
+ </div>
+ </div>
+ </FormProvider>
+ {!bounty && confirmCreateBountyModal}
+ </form>
+ );
+}
+
+export function BountySheet({
+ isOpen,
+ nested,
+ ...rest
+}: BountySheetProps & {
+ isOpen: boolean;
+ nested?: boolean;
+}) {
+ const { queryParams } = useRouterStuff();
+
+ return (
+ <Sheet
+ open={isOpen}
+ onOpenChange={rest.setIsOpen}
+ onClose={() => queryParams({ del: "bountyId", scroll: false })}
+ nested={nested}
+ >
+ <BountySheetContent {...rest} />
+ </Sheet>
+ );
+}
+
+export function useBountySheet(
+ props: { nested?: boolean } & Omit<BountySheetProps, "setIsOpen"> = {},
+) {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return {
+ BountySheet: (
+ <BountySheet setIsOpen={setIsOpen} isOpen={isOpen} {...props} />
+ ),
+ setShowCreateBountySheet: setIsOpen,
+ };
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-amount-input.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-amount-input.tsx
new file mode 100644
index 0000000000..5e93f1eb36
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-amount-input.tsx
@@ -0,0 +1,68 @@
+"use client";
+
+import { isCurrencyAttribute } from "@/lib/api/workflows/utils";
+import { handleMoneyInputChange, handleMoneyKeyDown } from "@/lib/form-utils";
+import { InlineBadgePopoverContext } from "@/ui/shared/inline-badge-popover";
+import { cn } from "@dub/utils";
+import { useContext } from "react";
+import { useBountyFormContext } from "./bounty-form-context";
+
+interface BountyAmountInputProps {
+ name: "rewardAmount" | "performanceCondition.value";
+ emptyValue?: null | undefined;
+}
+
+export function BountyAmountInput({
+ name,
+ emptyValue = null,
+}: BountyAmountInputProps) {
+ const { watch, register } = useBountyFormContext();
+ const { setIsOpen } = useContext(InlineBadgePopoverContext);
+
+ const attribute =
+ name === "performanceCondition.value"
+ ? watch("performanceCondition.attribute")
+ : null;
+ const isCurrency =
+ name === "rewardAmount"
+ ? true
+ : attribute
+ ? isCurrencyAttribute(attribute)
+ : false;
+
+ return (
+ <div className="relative rounded-md shadow-sm">
+ {isCurrency && (
+ <span className="absolute inset-y-0 left-0 flex items-center pl-1.5 text-sm text-neutral-400">
+ $
+ </span>
+ )}
+ <input
+ className={cn(
+ "block w-full rounded-md border-neutral-300 px-1.5 py-1 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:w-32 sm:text-sm",
+ isCurrency ? "pl-4 pr-12" : "pr-7",
+ )}
+ {...register(name, {
+ required: true,
+ setValueAs: (value: string) => (value === "" ? emptyValue : +value),
+ min: 0,
+ onChange: handleMoneyInputChange,
+ })}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ setIsOpen(false);
+ return;
+ }
+
+ handleMoneyKeyDown(e);
+ }}
+ />
+ {isCurrency && (
+ <span className="absolute inset-y-0 right-0 flex items-center pr-1.5 text-sm text-neutral-400">
+ USD
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-criteria-manual-submission.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-criteria-manual-submission.tsx
new file mode 100644
index 0000000000..47ab33ad16
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-criteria-manual-submission.tsx
@@ -0,0 +1,416 @@
+"use client";
+
+import {
+ BOUNTY_DEFAULT_SUBMISSION_URLS,
+ BOUNTY_MAX_SUBMISSION_FILES,
+ BOUNTY_MAX_SUBMISSION_URLS,
+} from "@/lib/bounty/constants";
+import { RewardIconSquare } from "@/ui/partners/rewards/reward-icon-square";
+import { X } from "@/ui/shared/icons";
+import {
+ InlineBadgePopover,
+ InlineBadgePopoverInput,
+ InlineBadgePopoverMenu,
+} from "@/ui/shared/inline-badge-popover";
+import { Button, ImageIcon, NumberStepper, Switch } from "@dub/ui";
+import { cn, currencyFormatter } from "@dub/utils";
+import { Controller } from "react-hook-form";
+import { BountyAmountInput } from "./bounty-amount-input";
+import { useBountyFormContext } from "./bounty-form-context";
+
+const REWARD_TYPES = [
+ {
+ value: "flat",
+ label: "flat rate",
+ },
+ {
+ value: "custom",
+ label: "custom",
+ },
+] as const;
+
+type RewardType = (typeof REWARD_TYPES)[number]["value"];
+
+const REWARD_TYPE_COPY: Record<
+ RewardType,
+ { label: string; connectorCopy: string }
+> = {
+ flat: { label: "flat rate", connectorCopy: "of " },
+ custom: { label: "custom amount", connectorCopy: "shown as " },
+};
+
+const REWARD_VALID_BUTTON_CLASS =
+ "!bg-blue-50 !text-blue-700 hover:!bg-blue-100";
+const REWARD_INVALID_BUTTON_CLASS =
+ "!bg-orange-50 !text-orange-500 hover:!bg-orange-100";
+
+export function BountyCriteriaManualSubmission() {
+ const { watch, setValue } = useBountyFormContext();
+
+ const [submissionRequirements, rewardType = "flat"] = watch([
+ "submissionRequirements",
+ "rewardType",
+ ]);
+
+ const requireImage = !!submissionRequirements?.image;
+ const requireUrl = !!submissionRequirements?.url;
+ const imageMax = submissionRequirements?.image?.max;
+ const urlMax = submissionRequirements?.url?.max;
+ const urlDomains = submissionRequirements?.url?.domains ?? [];
+
+ const updateSubmissionRequirements = (
+ imageRequired: boolean,
+ urlRequired: boolean,
+ imageMaxCount?: number,
+ urlMaxCount?: number,
+ urlDomainsList?: string[],
+ ) => {
+ const requirements: {
+ image?: { max?: number };
+ url?: { max?: number; domains?: string[] };
+ } = {};
+
+ if (imageRequired) {
+ requirements.image = {};
+
+ if (imageMaxCount !== undefined) {
+ requirements.image.max = imageMaxCount;
+ }
+ }
+
+ if (urlRequired) {
+ requirements.url = {};
+
+ if (urlMaxCount !== undefined) {
+ requirements.url.max = urlMaxCount;
+ }
+
+ if (urlDomainsList && urlDomainsList.length > 0) {
+ requirements.url.domains = urlDomainsList;
+ }
+ }
+
+ setValue(
+ "submissionRequirements",
+ Object.keys(requirements).length > 0 ? requirements : null,
+ { shouldDirty: true },
+ );
+ };
+
+ const handleRequireImageToggle = (checked: boolean) => {
+ updateSubmissionRequirements(
+ checked,
+ requireUrl,
+ checked ? imageMax : undefined,
+ urlMax,
+ urlDomains,
+ );
+ };
+
+ const handleRequireUrlToggle = (checked: boolean) => {
+ updateSubmissionRequirements(
+ requireImage,
+ checked,
+ imageMax,
+ checked ? urlMax : undefined,
+ checked ? urlDomains : undefined,
+ );
+ };
+
+ const handleImageMaxChange = (value: number) => {
+ updateSubmissionRequirements(
+ requireImage,
+ requireUrl,
+ value,
+ urlMax,
+ urlDomains,
+ );
+ };
+
+ const handleUrlMaxChange = (value: number) => {
+ updateSubmissionRequirements(
+ requireImage,
+ requireUrl,
+ imageMax,
+ value,
+ urlDomains,
+ );
+ };
+
+ const handleAddDomain = (domain: string) => {
+ const trimmedDomain = domain.trim().toLowerCase();
+
+ if (trimmedDomain && !urlDomains.includes(trimmedDomain)) {
+ const newDomains = [...urlDomains, trimmedDomain];
+
+ updateSubmissionRequirements(
+ requireImage,
+ requireUrl,
+ imageMax,
+ urlMax,
+ newDomains,
+ );
+ }
+ };
+
+ const handleRemoveDomain = (domain: string) => {
+ const newDomains = urlDomains.filter((d) => d !== domain);
+
+ updateSubmissionRequirements(
+ requireImage,
+ requireUrl,
+ imageMax,
+ urlMax,
+ newDomains,
+ );
+ };
+
+ return (
+ <>
+ <div className="space-y-4">
+ <div className="flex items-center gap-4">
+ <Switch
+ fn={handleRequireImageToggle}
+ checked={requireImage}
+ trackDimensions="w-8 h-4"
+ thumbDimensions="w-3 h-3"
+ thumbTranslate="translate-x-4"
+ />
+ <span className="text-sm font-medium text-neutral-700">
+ Require at least one image
+ </span>
+ </div>
+
+ <div className="flex items-center gap-4">
+ <Switch
+ fn={handleRequireUrlToggle}
+ checked={requireUrl}
+ trackDimensions="w-8 h-4"
+ thumbDimensions="w-3 h-3"
+ thumbTranslate="translate-x-4"
+ />
+ <span className="text-sm font-medium text-neutral-700">
+ Require at least one URL
+ </span>
+ </div>
+ </div>
+
+ {(requireImage || requireUrl) && (
+ <div className="space-y-4">
+ {requireImage && (
+ <div className="space-y-3 rounded-lg border border-neutral-200 bg-neutral-50/50 p-4">
+ <label className="text-sm font-medium text-neutral-700">
+ Maximum images
+ <span className="ml-1 font-normal text-neutral-500">
+ (optional)
+ </span>
+ </label>
+ <NumberStepper
+ value={imageMax ?? BOUNTY_MAX_SUBMISSION_FILES}
+ onChange={handleImageMaxChange}
+ min={1}
+ max={BOUNTY_MAX_SUBMISSION_FILES}
+ step={1}
+ className="h-9 w-full [&>div]:h-9"
+ />
+ <p className="text-xs text-neutral-500">
+ Set a maximum number of images partners can submit
+ </p>
+ </div>
+ )}
+
+ {requireUrl && (
+ <div className="space-y-4">
+ <div className="space-y-3 rounded-lg border border-neutral-200 bg-neutral-50/50 p-4">
+ <label className="text-sm font-medium text-neutral-700">
+ Maximum URLs
+ <span className="ml-1 font-normal text-neutral-500">
+ (optional)
+ </span>
+ </label>
+ <NumberStepper
+ value={urlMax ?? BOUNTY_DEFAULT_SUBMISSION_URLS}
+ onChange={handleUrlMaxChange}
+ min={1}
+ max={BOUNTY_MAX_SUBMISSION_URLS}
+ step={1}
+ className="h-9 w-full [&>div]:h-9"
+ />
+ <p className="text-xs text-neutral-500">
+ Set a maximum number of URLs partners can submit
+ </p>
+ </div>
+
+ <div className="space-y-3 rounded-lg border border-neutral-200 bg-neutral-50/50 p-4">
+ <label className="text-sm font-medium text-neutral-700">
+ Allowed domains
+ <span className="ml-1 font-normal text-neutral-500">
+ (optional)
+ </span>
+ </label>
+ <div className="flex gap-2">
+ <input
+ type="text"
+ placeholder="e.g. x.com"
+ className={cn(
+ "block h-9 flex-1 rounded-md border-neutral-300 px-3 py-1.5 text-sm text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500",
+ )}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ const input = e.currentTarget;
+ handleAddDomain(input.value);
+ input.value = "";
+ }
+ }}
+ />
+ <Button
+ type="button"
+ variant="secondary"
+ text="Add"
+ className="h-9 w-fit px-3"
+ onClick={(e) => {
+ const input = e.currentTarget
+ .previousElementSibling as HTMLInputElement;
+ if (input) {
+ handleAddDomain(input.value);
+ input.value = "";
+ }
+ }}
+ />
+ </div>
+
+ {urlDomains.length > 0 && (
+ <div className="mt-2 flex flex-wrap gap-2">
+ {urlDomains.map((domain) => (
+ <div
+ key={domain}
+ className="flex items-center gap-1.5 rounded-md bg-neutral-100 px-2.5 py-1.5 text-sm text-neutral-700"
+ >
+ <span>{domain}</span>
+ <button
+ type="button"
+ onClick={() => handleRemoveDomain(domain)}
+ className="text-neutral-400 hover:text-neutral-600"
+ >
+ <X className="size-3.5" />
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+
+ <p className="text-xs text-neutral-500">
+ Restrict URLs to specific domains. Partners can submit URLs
+ from these domains or their subdomains.
+ </p>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+
+ <div className="rounded-lg border border-neutral-200 bg-neutral-50/50 p-2.5 shadow-sm">
+ <div className="flex items-center gap-2.5">
+ <RewardIconSquare icon={ImageIcon} />
+ <span className="text-content-default text-sm leading-relaxed">
+ On approval, pay a{" "}
+ <RewardTypeBadge
+ value={rewardType}
+ onSelect={(v) => setValue("rewardType", v)}
+ />{" "}
+ {REWARD_TYPE_COPY[rewardType].connectorCopy}
+ <RewardValueBadge rewardType={rewardType} />
+ </span>
+ </div>
+ </div>
+ </>
+ );
+}
+
+function RewardTypeBadge({
+ value,
+ onSelect,
+}: {
+ value: RewardType;
+ onSelect: (v: RewardType) => void;
+}) {
+ return (
+ <InlineBadgePopover
+ text={REWARD_TYPE_COPY[value].label}
+ buttonClassName={REWARD_VALID_BUTTON_CLASS}
+ >
+ <InlineBadgePopoverMenu
+ items={REWARD_TYPES.map(({ value: v, label }) => ({
+ value: v,
+ text: label,
+ }))}
+ selectedValue={value}
+ onSelect={(v) => onSelect(v)}
+ />
+ </InlineBadgePopover>
+ );
+}
+
+function RewardValueBadge({ rewardType }: { rewardType: RewardType }) {
+ const { control, watch } = useBountyFormContext();
+
+ const [rewardAmount, rewardDescription] = watch([
+ "rewardAmount",
+ "rewardDescription",
+ ]);
+
+ if (rewardType === "flat") {
+ const invalid =
+ rewardAmount == null || isNaN(rewardAmount) || rewardAmount < 0;
+ const displayText =
+ rewardAmount != null && !isNaN(rewardAmount)
+ ? currencyFormatter(rewardAmount * 100, {
+ trailingZeroDisplay: "stripIfInteger",
+ })
+ : "amount";
+
+ return (
+ <InlineBadgePopover
+ text={displayText}
+ invalid={invalid}
+ buttonClassName={
+ invalid ? REWARD_INVALID_BUTTON_CLASS : REWARD_VALID_BUTTON_CLASS
+ }
+ >
+ <BountyAmountInput name="rewardAmount" />
+ </InlineBadgePopover>
+ );
+ }
+
+ const invalid = !rewardDescription?.trim();
+ const displayText = rewardDescription?.trim() || "reward description";
+
+ return (
+ <InlineBadgePopover
+ text={displayText}
+ invalid={invalid}
+ buttonClassName={
+ invalid ? REWARD_INVALID_BUTTON_CLASS : REWARD_VALID_BUTTON_CLASS
+ }
+ >
+ <Controller
+ control={control}
+ name="rewardDescription"
+ rules={{ maxLength: 100 }}
+ render={({ field }) => (
+ <InlineBadgePopoverInput
+ {...field}
+ value={field.value ?? ""}
+ onChange={(e) => {
+ const val = (e.target as HTMLInputElement).value;
+ field.onChange(val === "" ? null : val);
+ }}
+ placeholder="Earn an additional 10% if you hit your revenue goal"
+ maxLength={100}
+ />
+ )}
+ />
+ </InlineBadgePopover>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-criteria-social-metrics.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-criteria-social-metrics.tsx
new file mode 100644
index 0000000000..8681ab4878
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-criteria-social-metrics.tsx
@@ -0,0 +1,512 @@
+"use client";
+
+import {
+ BOUNTY_SOCIAL_PLATFORM_METRICS_MAP,
+ BOUNTY_SOCIAL_PLATFORMS,
+} from "@/lib/bounty/constants";
+import type { BountySocialMetricsIncrementalBonus } from "@/lib/types";
+import { RewardIconSquare } from "@/ui/partners/rewards/reward-icon-square";
+import { X } from "@/ui/shared/icons";
+import {
+ InlineBadgePopover,
+ InlineBadgePopoverContext,
+ InlineBadgePopoverInput,
+ InlineBadgePopoverMenu,
+} from "@/ui/shared/inline-badge-popover";
+import {
+ ArrowTurnRight2,
+ Button,
+ Megaphone,
+ MoneyBills2,
+ Refresh2,
+ Tooltip,
+} from "@dub/ui";
+import { currencyFormatter } from "@dub/utils";
+import { nFormatter } from "@dub/utils/src";
+import { HelpCircle } from "lucide-react";
+import { useContext } from "react";
+import { BountyAmountInput } from "./bounty-amount-input";
+import {
+ CreateBountyInputExtended,
+ useBountyFormContext,
+} from "./bounty-form-context";
+
+interface SocialMetricsVariableBonusProps {
+ variableBonus: BountySocialMetricsIncrementalBonus;
+ metricLabel: string;
+ onUpdate: (updates: Partial<BountySocialMetricsIncrementalBonus>) => void;
+ onRemove: () => void;
+}
+
+export function BountyCriteriaSocialMetrics() {
+ const { watch, setValue } = useBountyFormContext();
+
+ const [submissionRequirements, rewardAmount] = watch([
+ "submissionRequirements",
+ "rewardAmount",
+ ]);
+
+ const socialMetrics = submissionRequirements?.socialMetrics;
+ const hasChannel = socialMetrics?.platform != null;
+ const hasMinCount =
+ socialMetrics?.minCount != null && socialMetrics.minCount > 0;
+ const hasMetric = socialMetrics?.metric != null;
+ const incrementalBonus = socialMetrics?.incrementalBonus;
+
+ const updateRequirements = (
+ data: CreateBountyInputExtended["submissionRequirements"],
+ ) => {
+ setValue(
+ "submissionRequirements",
+ {
+ ...submissionRequirements,
+ ...data,
+ },
+ {
+ shouldDirty: true,
+ },
+ );
+ };
+
+ const channelLabel = hasChannel
+ ? BOUNTY_SOCIAL_PLATFORMS.find((c) => c.value === socialMetrics.platform)
+ ?.label ?? socialMetrics.platform
+ : "channel";
+
+ const metricLabel = hasMetric
+ ? BOUNTY_SOCIAL_PLATFORM_METRICS_MAP[socialMetrics.platform]?.find(
+ (m) => m.value === socialMetrics.metric,
+ )?.label ?? socialMetrics.metric
+ : "metric";
+
+ const metricPlatformForMenu = socialMetrics?.platform ?? "youtube";
+
+ return (
+ <div className="flex flex-col gap-0">
+ <div className="border-border-subtle rounded-xl border bg-white shadow-sm">
+ <div className="flex items-center gap-2.5 p-2.5">
+ <div className="flex size-7 shrink-0 items-center justify-center rounded-md bg-neutral-100">
+ <Megaphone className="size-4 text-neutral-800" />
+ </div>
+ <span className="text-content-emphasis text-sm font-medium leading-relaxed">
+ If their post on{" "}
+ <InlineBadgePopover
+ text={channelLabel}
+ invalid={!hasChannel}
+ buttonClassName={
+ hasChannel
+ ? "!bg-blue-50 !text-blue-700 hover:!bg-blue-100"
+ : "!bg-orange-50 !text-orange-500 hover:!bg-orange-100"
+ }
+ >
+ <InlineBadgePopoverMenu
+ items={BOUNTY_SOCIAL_PLATFORMS.map((c) => ({
+ value: c.value,
+ text: c.label,
+ }))}
+ selectedValue={socialMetrics?.platform}
+ onSelect={(value) => {
+ const platformMetrics =
+ BOUNTY_SOCIAL_PLATFORM_METRICS_MAP[value];
+
+ const metric =
+ socialMetrics?.metric &&
+ platformMetrics?.some(
+ (m) => m.value === socialMetrics.metric,
+ )
+ ? socialMetrics.metric
+ : platformMetrics?.[0]?.value ?? "views";
+
+ updateRequirements({
+ socialMetrics: {
+ ...socialMetrics,
+ platform: value,
+ metric,
+ },
+ });
+ }}
+ />
+ </InlineBadgePopover>{" "}
+ has at least{" "}
+ <InlineBadgePopover
+ text={
+ hasMinCount
+ ? String(nFormatter(socialMetrics!.minCount, { full: true }))
+ : "metrics"
+ }
+ invalid={!hasMinCount}
+ buttonClassName={
+ hasMinCount
+ ? "!bg-blue-50 !text-blue-700 hover:!bg-blue-100"
+ : "!bg-orange-50 !text-orange-500 hover:!bg-orange-100"
+ }
+ >
+ <InlineBadgePopoverInput
+ type="number"
+ min={0}
+ value={
+ socialMetrics?.minCount == null ||
+ socialMetrics?.minCount === 0
+ ? ""
+ : String(socialMetrics.minCount)
+ }
+ onChange={(e) => {
+ const raw = (e.target as HTMLInputElement).value;
+
+ if (raw === "") {
+ updateRequirements({
+ socialMetrics: {
+ ...socialMetrics,
+ platform: socialMetrics?.platform ?? "youtube",
+ metric: socialMetrics?.metric ?? "views",
+ minCount: 0,
+ },
+ });
+ return;
+ }
+
+ const num = parseInt(raw, 10);
+
+ updateRequirements({
+ socialMetrics: {
+ ...socialMetrics,
+ platform: socialMetrics?.platform ?? "youtube",
+ metric: socialMetrics?.metric ?? "views",
+ minCount: Number.isNaN(num) ? 0 : Math.max(0, num),
+ },
+ });
+ }}
+ placeholder="metrics"
+ />
+ </InlineBadgePopover>{" "}
+ <InlineBadgePopover
+ text={metricLabel}
+ invalid={!hasMetric}
+ buttonClassName={
+ hasMetric
+ ? "!bg-blue-50 !text-blue-700 hover:!bg-blue-100"
+ : "!bg-orange-50 !text-orange-500 hover:!bg-orange-100"
+ }
+ >
+ <InlineBadgePopoverMenu
+ items={
+ BOUNTY_SOCIAL_PLATFORM_METRICS_MAP[
+ metricPlatformForMenu
+ ]?.map((m) => ({ value: m.value, text: m.label })) ?? []
+ }
+ selectedValue={socialMetrics?.metric}
+ onSelect={(v) =>
+ updateRequirements({
+ socialMetrics: {
+ ...socialMetrics,
+ platform: socialMetrics?.platform ?? "youtube",
+ metric: v,
+ },
+ })
+ }
+ />
+ </InlineBadgePopover>
+ </span>
+ </div>
+ </div>
+
+ <div className="bg-border-subtle ml-6 h-4 w-px shrink-0" />
+
+ <div className="border-border-subtle rounded-xl border bg-white shadow-sm">
+ <div className="flex items-center gap-2.5 p-2.5">
+ <RewardIconSquare icon={MoneyBills2} />
+ <span className="text-content-emphasis text-sm font-medium leading-relaxed">
+ Then pay{" "}
+ <InlineBadgePopover
+ text={
+ rewardAmount != null && !isNaN(rewardAmount)
+ ? currencyFormatter(rewardAmount * 100, {
+ trailingZeroDisplay: "stripIfInteger",
+ })
+ : "$0"
+ }
+ invalid={
+ rewardAmount == null || isNaN(rewardAmount) || rewardAmount < 0
+ }
+ buttonClassName={
+ rewardAmount != null &&
+ !isNaN(rewardAmount) &&
+ rewardAmount >= 0
+ ? "!bg-blue-50 !text-blue-700 hover:!bg-blue-100"
+ : "!bg-orange-50 !text-orange-500 hover:!bg-orange-100"
+ }
+ >
+ <BountyAmountInput name="rewardAmount" />
+ </InlineBadgePopover>
+ </span>
+ </div>
+ </div>
+
+ {socialMetrics && !incrementalBonus && (
+ <div className="border-bg-subtle mt-4 rounded-xl border bg-neutral-100 p-2.5">
+ <Button
+ text="Add variable bonus"
+ onClick={() =>
+ updateRequirements({
+ socialMetrics: {
+ ...socialMetrics,
+ incrementalBonus: {},
+ },
+ })
+ }
+ variant="secondary"
+ icon={<ArrowTurnRight2 className="size-4 text-neutral-900" />}
+ className="h-8 rounded-lg"
+ />
+ </div>
+ )}
+
+ {incrementalBonus && (
+ <SocialMetricsIncrementalBonus
+ variableBonus={incrementalBonus}
+ metricLabel={metricLabel}
+ onUpdate={(updates) =>
+ updateRequirements({
+ socialMetrics: {
+ ...socialMetrics,
+ incrementalBonus: {
+ ...incrementalBonus,
+ ...updates,
+ },
+ },
+ })
+ }
+ onRemove={() =>
+ updateRequirements({
+ socialMetrics: {
+ ...socialMetrics,
+ incrementalBonus: undefined,
+ },
+ })
+ }
+ />
+ )}
+ </div>
+ );
+}
+
+function SocialMetricsIncrementalBonus({
+ variableBonus,
+ metricLabel,
+ onUpdate,
+ onRemove,
+}: SocialMetricsVariableBonusProps) {
+ return (
+ <div className="border-border-subtle mt-4 overflow-hidden rounded-xl border bg-neutral-100 p-2.5 pt-0 shadow-sm">
+ <div className="flex items-center justify-between py-2.5">
+ <div className="flex items-center gap-2 px-2">
+ <ArrowTurnRight2 className="size-4 text-neutral-800" />
+ <span className="text-sm font-medium text-neutral-800">
+ Variable bonus
+ </span>
+ <Tooltip
+ content="Partners earn the base payout when they hit the threshold, plus an extra amount for each additional increment up to the cap."
+ side="top"
+ >
+ <div className="text-neutral-400 hover:text-neutral-600">
+ <HelpCircle className="size-3.5" />
+ </div>
+ </Tooltip>
+ </div>
+
+ <button
+ type="button"
+ onClick={onRemove}
+ className="ml-auto text-neutral-400 hover:text-neutral-600"
+ aria-label="Remove variable bonus"
+ >
+ <X className="size-4" />
+ </button>
+ </div>
+
+ <div className="flex flex-col gap-0 rounded-xl border border-neutral-200 bg-white px-2.5 py-3">
+ <div className="border-border-subtle rounded-xl border bg-white shadow-sm">
+ <div className="flex items-center gap-2.5 p-2.5">
+ <div className="flex size-7 shrink-0 items-center justify-center rounded-md bg-neutral-100">
+ <Megaphone className="size-4 text-neutral-800" />
+ </div>
+ <span className="text-content-emphasis text-sm font-medium leading-relaxed">
+ For each additional{" "}
+ <InlineBadgePopover
+ text={
+ variableBonus.incrementCount != null &&
+ variableBonus.incrementCount >= 1
+ ? String(
+ nFormatter(variableBonus.incrementCount, {
+ full: true,
+ }),
+ )
+ : "amount"
+ }
+ invalid={
+ variableBonus.incrementCount == null ||
+ variableBonus.incrementCount < 1
+ }
+ buttonClassName={
+ variableBonus.incrementCount != null &&
+ variableBonus.incrementCount >= 1
+ ? "!bg-blue-50 !text-blue-700 hover:!bg-blue-100"
+ : "!bg-orange-50 !text-orange-500 hover:!bg-orange-100"
+ }
+ >
+ <InlineBadgePopoverInput
+ type="number"
+ min={1}
+ value={
+ variableBonus.incrementCount != null
+ ? String(variableBonus.incrementCount)
+ : ""
+ }
+ onChange={(e) => {
+ const raw = (e.target as HTMLInputElement).value;
+ const num = raw === "" ? undefined : parseInt(raw, 10);
+ onUpdate({
+ incrementCount:
+ num === undefined || Number.isNaN(num)
+ ? undefined
+ : Math.max(1, num),
+ });
+ }}
+ placeholder="amount"
+ />
+ </InlineBadgePopover>{" "}
+ {metricLabel}
+ </span>
+ </div>
+ </div>
+ <div className="bg-border-subtle ml-6 h-4 w-px shrink-0" />
+ <div className="border-border-subtle rounded-xl border bg-white shadow-sm">
+ <div className="flex items-center gap-2.5 p-2.5">
+ <RewardIconSquare icon={MoneyBills2} />
+ <span className="text-content-emphasis text-sm font-medium leading-relaxed">
+ Pay{" "}
+ <InlineBadgePopover
+ text={
+ variableBonus.bonusPerIncrement != null &&
+ !isNaN(variableBonus.bonusPerIncrement) &&
+ variableBonus.bonusPerIncrement >= 0
+ ? currencyFormatter(variableBonus.bonusPerIncrement * 100, {
+ trailingZeroDisplay: "stripIfInteger",
+ })
+ : "amount"
+ }
+ invalid={
+ variableBonus.bonusPerIncrement == null ||
+ isNaN(variableBonus.bonusPerIncrement) ||
+ variableBonus.bonusPerIncrement < 0
+ }
+ buttonClassName={
+ variableBonus.bonusPerIncrement != null &&
+ !isNaN(variableBonus.bonusPerIncrement) &&
+ variableBonus.bonusPerIncrement >= 0
+ ? "!bg-blue-50 !text-blue-700 hover:!bg-blue-100"
+ : "!bg-orange-50 !text-orange-500 hover:!bg-orange-100"
+ }
+ >
+ <VariableBonusAmountInput
+ value={variableBonus.bonusPerIncrement}
+ onChange={(v) => onUpdate({ bonusPerIncrement: v })}
+ />
+ </InlineBadgePopover>
+ </span>
+ </div>
+ </div>
+ <div className="bg-border-subtle ml-6 h-4 w-px shrink-0" />
+ <div className="border-border-subtle rounded-xl border bg-white shadow-sm">
+ <div className="flex items-center gap-2.5 p-2.5">
+ <div className="flex size-7 shrink-0 items-center justify-center rounded-md bg-neutral-100">
+ <Refresh2 className="size-4 text-neutral-800" />
+ </div>
+ <span className="text-content-emphasis text-sm font-medium leading-relaxed">
+ Up to{" "}
+ <InlineBadgePopover
+ text={
+ variableBonus.maxCount != null && variableBonus.maxCount >= 1
+ ? String(nFormatter(variableBonus.maxCount, { full: true }))
+ : "amount"
+ }
+ invalid={
+ variableBonus.maxCount == null || variableBonus.maxCount < 1
+ }
+ buttonClassName={
+ variableBonus.maxCount != null && variableBonus.maxCount >= 1
+ ? "!bg-blue-50 !text-blue-700 hover:!bg-blue-100"
+ : "!bg-orange-50 !text-orange-500 hover:!bg-orange-100"
+ }
+ >
+ <InlineBadgePopoverInput
+ type="number"
+ min={1}
+ value={
+ variableBonus.maxCount != null
+ ? String(variableBonus.maxCount)
+ : ""
+ }
+ onChange={(e) => {
+ const raw = (e.target as HTMLInputElement).value;
+ const num = raw === "" ? undefined : parseInt(raw, 10);
+ onUpdate({
+ maxCount:
+ num === undefined || Number.isNaN(num)
+ ? undefined
+ : Math.max(1, num),
+ });
+ }}
+ placeholder="amount"
+ />
+ </InlineBadgePopover>{" "}
+ {metricLabel}
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function VariableBonusAmountInput({
+ value,
+ onChange,
+}: {
+ value?: number;
+ onChange: (value: number | undefined) => void;
+}) {
+ const { setIsOpen } = useContext(InlineBadgePopoverContext);
+ return (
+ <div className="relative rounded-md shadow-sm">
+ <span className="absolute inset-y-0 left-0 flex items-center pl-1.5 text-sm text-neutral-400">
+ $
+ </span>
+ <input
+ className="block w-full rounded-md border-neutral-300 px-1.5 py-1 pl-4 pr-12 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:w-32 sm:text-sm"
+ type="number"
+ min={0}
+ step={0.01}
+ value={value != null && !isNaN(value) && value >= 0 ? value : ""}
+ onChange={(e) => {
+ const raw = (e.target as HTMLInputElement).value;
+ const num = raw === "" ? undefined : parseFloat(raw);
+ onChange(
+ num === undefined || Number.isNaN(num)
+ ? undefined
+ : Math.max(0, num),
+ );
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ setIsOpen?.(false);
+ }
+ }}
+ />
+ <span className="absolute inset-y-0 right-0 flex items-center pr-1.5 text-sm text-neutral-400">
+ USD
+ </span>
+ </div>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-criteria.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-criteria.tsx
new file mode 100644
index 0000000000..92e0701a14
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-criteria.tsx
@@ -0,0 +1,246 @@
+"use client";
+
+import { getPlanCapabilities } from "@/lib/plan-capabilities";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { usePartnersUpgradeModal } from "@/ui/partners/partners-upgrade-modal";
+import {
+ ProgramSheetAccordionContent,
+ ProgramSheetAccordionItem,
+ ProgramSheetAccordionTrigger,
+} from "@/ui/partners/program-sheet-accordion";
+import { RewardIconSquare } from "@/ui/partners/rewards/reward-icon-square";
+import { InlineBadgePopover } from "@/ui/shared/inline-badge-popover";
+import { MoneyBills2, ToggleGroup } from "@dub/ui";
+import { cn, currencyFormatter } from "@dub/utils";
+import { useMemo } from "react";
+import { BountyAmountInput } from "./bounty-amount-input";
+import { BountyCriteriaManualSubmission } from "./bounty-criteria-manual-submission";
+import { BountyCriteriaSocialMetrics } from "./bounty-criteria-social-metrics";
+import { useBountyFormContext } from "./bounty-form-context";
+import { BountyLogic } from "./bounty-logic";
+
+const BOUNTY_SUBMISSION_TYPES = [
+ {
+ value: "manualSubmission",
+ label: "Manual submission",
+ },
+ {
+ value: "socialMetrics",
+ label: "Social metrics",
+ },
+] as const;
+
+type BountySubmissionType = (typeof BOUNTY_SUBMISSION_TYPES)[number]["value"];
+
+export function BountyCriteria() {
+ const { plan } = useWorkspace();
+ const { partnersUpgradeModal, setShowPartnersUpgradeModal } =
+ usePartnersUpgradeModal();
+
+ const canUseBountySocialMetrics =
+ getPlanCapabilities(plan).canUseBountySocialMetrics;
+
+ const { watch, setValue } = useBountyFormContext();
+
+ const [
+ type,
+ rewardAmount,
+ submissionRequirements,
+ rewardType = "flat",
+ submissionCriteriaType = "manualSubmission",
+ ] = watch([
+ "type",
+ "rewardAmount",
+ "submissionRequirements",
+ "rewardType",
+ "submissionCriteriaType",
+ ]);
+
+ const requireImage = !!submissionRequirements?.image;
+ const requireUrl = !!submissionRequirements?.url;
+ const imageMax = submissionRequirements?.image?.max;
+ const urlMax = submissionRequirements?.url?.max;
+ const urlDomains = submissionRequirements?.url?.domains ?? [];
+
+ const updateSubmissionRequirements = (
+ imageRequired: boolean,
+ urlRequired: boolean,
+ imageMaxCount?: number,
+ urlMaxCount?: number,
+ urlDomainsList?: string[],
+ ) => {
+ const requirements: {
+ image?: { max?: number };
+ url?: { max?: number; domains?: string[] };
+ } = {};
+
+ if (imageRequired) {
+ requirements.image = {};
+
+ if (imageMaxCount !== undefined) {
+ requirements.image.max = imageMaxCount;
+ }
+ }
+
+ if (urlRequired) {
+ requirements.url = {};
+
+ if (urlMaxCount !== undefined) {
+ requirements.url.max = urlMaxCount;
+ }
+
+ if (urlDomainsList && urlDomainsList.length > 0) {
+ requirements.url.domains = urlDomainsList;
+ }
+ }
+
+ setValue(
+ "submissionRequirements",
+ Object.keys(requirements).length > 0 ? requirements : null,
+ { shouldDirty: true },
+ );
+ };
+
+ const showPerformanceContent = type === "performance";
+ const showSubmissionContent = type === "submission";
+
+ const showWhenThenCards =
+ (rewardType === "flat" || type === "performance") &&
+ (type === "performance" ||
+ (type === "submission" && rewardType === "flat"));
+
+ const submissionTypeOptions = useMemo(
+ () => [
+ {
+ value: "manualSubmission",
+ label: "Manual submission",
+ },
+ {
+ value: "socialMetrics",
+ label: !canUseBountySocialMetrics ? (
+ <span className="flex shrink-0 items-center gap-2 whitespace-nowrap">
+ Social metrics
+ <span
+ className={cn(
+ "rounded-sm px-1.5 py-1 text-[0.625rem] uppercase leading-none",
+ "bg-violet-50 text-violet-600",
+ )}
+ >
+ UPGRADE REQUIRED
+ </span>
+ </span>
+ ) : (
+ "Social metrics"
+ ),
+ },
+ ],
+ [canUseBountySocialMetrics],
+ );
+
+ return (
+ <ProgramSheetAccordionItem value="bounty-criteria">
+ <ProgramSheetAccordionTrigger>Criteria</ProgramSheetAccordionTrigger>
+ <ProgramSheetAccordionContent>
+ <div className="space-y-6">
+ {showSubmissionContent && (
+ <>
+ {partnersUpgradeModal}
+ <p className="text-content-default text-sm leading-relaxed">
+ Set how partners claim bounties and how they&apos;re verified.
+ By default an open text field is provided.
+ </p>
+ <ToggleGroup
+ className="flex w-full items-center gap-1 rounded-md border border-neutral-200 bg-neutral-100 p-1"
+ optionClassName="h-8 flex flex-1 items-center justify-center gap-2 rounded-md text-sm whitespace-nowrap"
+ indicatorClassName="bg-white border border-neutral-200 rounded-md shadow-sm"
+ options={submissionTypeOptions}
+ selected={submissionCriteriaType}
+ selectAction={(id: BountySubmissionType) => {
+ setValue("submissionCriteriaType", id);
+
+ if (id === "socialMetrics") {
+ setValue(
+ "submissionRequirements",
+ {
+ socialMetrics: submissionRequirements?.socialMetrics,
+ },
+ {
+ shouldDirty: true,
+ },
+ );
+ } else {
+ updateSubmissionRequirements(
+ requireImage,
+ requireUrl,
+ imageMax,
+ urlMax,
+ urlDomains,
+ );
+ }
+ }}
+ />
+
+ {submissionCriteriaType === "manualSubmission" && (
+ <BountyCriteriaManualSubmission />
+ )}
+
+ {submissionCriteriaType === "socialMetrics" && (
+ <BountyCriteriaSocialMetrics />
+ )}
+ </>
+ )}
+
+ {showPerformanceContent && showWhenThenCards && (
+ <div className="flex flex-col gap-0">
+ <div className="border-border-subtle rounded-xl border bg-white shadow-sm">
+ <div className="flex items-center gap-2.5 p-2.5">
+ <BountyLogic />
+ </div>
+ </div>
+
+ <div className="bg-border-subtle ml-6 h-4 w-px shrink-0" />
+
+ <div className="border-border-subtle rounded-xl border bg-white shadow-sm">
+ <div className="flex items-center gap-2.5 p-2.5">
+ <RewardIconSquare icon={MoneyBills2} />
+ <span className="text-content-emphasis text-sm font-medium leading-relaxed">
+ Then pay{" "}
+ <InlineBadgePopover
+ text={
+ rewardAmount != null &&
+ !isNaN(rewardAmount) &&
+ rewardAmount >= 0
+ ? currencyFormatter(rewardAmount * 100, {
+ trailingZeroDisplay: "stripIfInteger",
+ })
+ : "amount"
+ }
+ invalid={
+ rewardAmount == null ||
+ isNaN(rewardAmount) ||
+ rewardAmount < 0
+ }
+ >
+ <BountyAmountInput name="rewardAmount" />
+ </InlineBadgePopover>
+ </span>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {rewardType === "custom" &&
+ showSubmissionContent &&
+ submissionCriteriaType === "manualSubmission" && (
+ <div className="rounded-lg bg-orange-50 px-4 py-2 text-center">
+ <span className="text-sm font-medium leading-5 text-orange-900">
+ When reviewing these submissions, a custom reward amount will
+ be required to approve.
+ </span>
+ </div>
+ )}
+ </div>
+ </ProgramSheetAccordionContent>
+ </ProgramSheetAccordionItem>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-form-context.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-form-context.tsx
new file mode 100644
index 0000000000..0472975d4f
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-form-context.tsx
@@ -0,0 +1,12 @@
+"use client";
+
+import { CreateBountyInput } from "@/lib/types";
+import { useFormContext } from "react-hook-form";
+
+export type CreateBountyInputExtended = CreateBountyInput & {
+ rewardType?: "flat" | "custom";
+ submissionCriteriaType?: "manualSubmission" | "socialMetrics";
+};
+
+export const useBountyFormContext = () =>
+ useFormContext<CreateBountyInputExtended>();
diff --git a/apps/web/ui/partners/bounties/bounty-logic.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-logic.tsx
similarity index 57%
rename from apps/web/ui/partners/bounties/bounty-logic.tsx
rename to apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-logic.tsx
index c8b1b83569..7e6f4fbdb7 100644
--- a/apps/web/ui/partners/bounties/bounty-logic.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-logic.tsx
@@ -1,20 +1,20 @@
-import { PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES } from "@/lib/api/bounties/performance-bounty-scope-attributes";
+"use client";
+
import { isCurrencyAttribute } from "@/lib/api/workflows/utils";
-import { handleMoneyInputChange, handleMoneyKeyDown } from "@/lib/form-utils";
+import { PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES } from "@/lib/bounty/api/performance-bounty-scope-attributes";
import { WORKFLOW_ATTRIBUTES } from "@/lib/zod/schemas/workflows";
import {
InlineBadgePopover,
- InlineBadgePopoverContext,
InlineBadgePopoverMenu,
} from "@/ui/shared/inline-badge-popover";
import { Trophy } from "@dub/ui/icons";
-import { cn, currencyFormatter } from "@dub/utils";
-import { useAddEditBountyForm } from "app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet";
-import { useContext } from "react";
+import { cn, currencyFormatter, nFormatter } from "@dub/utils";
import { Controller } from "react-hook-form";
+import { BountyAmountInput } from "./bounty-amount-input";
+import { useBountyFormContext } from "./bounty-form-context";
export function BountyLogic({ className }: { className?: string }) {
- const { control, watch } = useAddEditBountyForm();
+ const { control, watch } = useBountyFormContext();
const [attribute, value] = watch([
"performanceCondition.attribute",
@@ -22,12 +22,7 @@ export function BountyLogic({ className }: { className?: string }) {
]);
return (
- <div
- className={cn(
- "flex w-full items-center gap-1.5 rounded-md border border-neutral-300 px-3 py-2",
- className,
- )}
- >
+ <div className={cn("flex w-full items-center gap-1.5", className)}>
<div className="flex size-7 shrink-0 items-center justify-center rounded-md bg-neutral-100">
<Trophy className="size-4 text-neutral-800" />
</div>
@@ -88,16 +83,18 @@ export function BountyLogic({ className }: { className?: string }) {
text={
value
? isCurrencyAttribute(attribute)
- ? // value is in dollars, so we need to convert to cents
- currencyFormatter(value * 100, {
+ ? currencyFormatter(value * 100, {
trailingZeroDisplay: "stripIfInteger",
})
- : value
+ : nFormatter(value, { full: true })
: "amount"
}
invalid={!value}
>
- <ValueInput />
+ <BountyAmountInput
+ name="performanceCondition.value"
+ emptyValue={undefined}
+ />
</InlineBadgePopover>
</>
)}
@@ -105,47 +102,3 @@ export function BountyLogic({ className }: { className?: string }) {
</div>
);
}
-
-function ValueInput() {
- const { watch, register } = useAddEditBountyForm();
- const { setIsOpen } = useContext(InlineBadgePopoverContext);
-
- const attribute = watch("performanceCondition.attribute");
- const isCurrency = isCurrencyAttribute(attribute);
-
- return (
- <div className="relative rounded-md shadow-sm">
- {isCurrency && (
- <span className="absolute inset-y-0 left-0 flex items-center pl-1.5 text-sm text-neutral-400">
- $
- </span>
- )}
- <input
- className={cn(
- "block w-full rounded-md border-neutral-300 px-1.5 py-1 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:w-32 sm:text-sm",
- isCurrency ? "pl-4 pr-12" : "pr-7",
- )}
- {...register("performanceCondition.value", {
- required: true,
- setValueAs: (value: string) => (value === "" ? undefined : +value),
- min: 0,
- onChange: handleMoneyInputChange,
- })}
- onKeyDown={(e) => {
- if (e.key === "Enter") {
- e.preventDefault();
- setIsOpen(false);
- return;
- }
-
- handleMoneyKeyDown(e);
- }}
- />
- {isCurrency && (
- <span className="absolute inset-y-0 right-0 flex items-center pr-1.5 text-sm text-neutral-400">
- USD
- </span>
- )}
- </div>
- );
-}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/confirm-create-bounty-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/confirm-create-bounty-modal.tsx
similarity index 98%
rename from apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/confirm-create-bounty-modal.tsx
rename to apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/confirm-create-bounty-modal.tsx
index 3fed6e92ca..25bc0b792e 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/confirm-create-bounty-modal.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/confirm-create-bounty-modal.tsx
@@ -1,4 +1,4 @@
-import { getBountyRewardDescription } from "@/lib/partners/get-bounty-reward-description";
+import { getBountyRewardDescription } from "@/lib/bounty/get-bounty-reward-description";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import useGroups from "@/lib/swr/use-groups";
import { usePartnersCountByGroupIds } from "@/lib/swr/use-partners-count-by-groupids";
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/use-add-edit-bounty-form.ts b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/use-add-edit-bounty-form.ts
new file mode 100644
index 0000000000..ecade1f501
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/use-add-edit-bounty-form.ts
@@ -0,0 +1,496 @@
+"use client";
+
+import { isCurrencyAttribute } from "@/lib/api/workflows/utils";
+import { generatePerformanceBountyName } from "@/lib/bounty/api/generate-performance-bounty-name";
+import { BOUNTY_DESCRIPTION_MAX_LENGTH } from "@/lib/bounty/constants";
+import { mutatePrefix } from "@/lib/swr/mutate";
+import { useApiMutation } from "@/lib/swr/use-api-mutation";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { BountyProps } from "@/lib/types";
+import { bountyPerformanceConditionSchema } from "@/lib/zod/schemas/bounties";
+import { formatDate } from "@dub/utils";
+import { Dispatch, SetStateAction, useMemo, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { CreateBountyInputExtended } from "./bounty-form-context";
+import { useConfirmCreateBountyModal } from "./confirm-create-bounty-modal";
+
+const ACCORDION_ITEMS = [
+ "bounty-type",
+ "bounty-details",
+ "bounty-criteria",
+ "groups",
+];
+
+const isEmpty = (value: unknown) =>
+ value === undefined || value === null || value === "";
+
+export function useAddEditBountyForm({
+ bounty,
+ setIsOpen,
+}: {
+ bounty?: BountyProps;
+ setIsOpen: Dispatch<SetStateAction<boolean>>;
+}) {
+ const { id: workspaceId } = useWorkspace();
+ const { makeRequest, isSubmitting } = useApiMutation<BountyProps>();
+
+ const [hasStartDate, setHasStartDate] = useState(!!bounty?.startsAt);
+ const [hasEndDate, setHasEndDate] = useState(!!bounty?.endsAt);
+ const [openAccordions, setOpenAccordions] = useState(ACCORDION_ITEMS);
+
+ const [submissionWindow, setSubmissionWindow] = useState<number | null>(
+ () => {
+ if (!bounty?.submissionsOpenAt || !bounty?.endsAt) return null;
+ const days = Math.ceil(
+ (new Date(bounty.endsAt).getTime() -
+ new Date(bounty.submissionsOpenAt).getTime()) /
+ (1000 * 60 * 60 * 24),
+ );
+ return days >= 2 && days <= 14 ? days : null;
+ },
+ );
+
+ const initialSubmissionRequirements = (() => {
+ const raw = bounty?.submissionRequirements;
+ const bonus = raw?.socialMetrics?.incrementalBonus;
+
+ if (raw && bonus && typeof bonus.bonusPerIncrement === "number") {
+ return {
+ ...raw,
+ socialMetrics: {
+ ...raw.socialMetrics!,
+ incrementalBonus: {
+ ...bonus,
+ bonusPerIncrement: bonus.bonusPerIncrement / 100,
+ },
+ },
+ };
+ }
+ return raw ?? null;
+ })();
+
+ const form = useForm<CreateBountyInputExtended>({
+ defaultValues: {
+ name: bounty?.name || undefined,
+ description: bounty?.description || undefined,
+ startsAt: bounty?.startsAt || undefined,
+ endsAt: bounty?.endsAt || undefined,
+ submissionsOpenAt: bounty?.submissionsOpenAt || undefined,
+ rewardAmount: bounty?.rewardAmount
+ ? bounty.rewardAmount / 100
+ : undefined,
+ rewardDescription: bounty?.rewardDescription || undefined,
+ type: bounty?.type || "performance",
+ submissionRequirements: initialSubmissionRequirements,
+ groupIds: bounty?.groups?.map(({ id }) => id) || null,
+ performanceCondition: bounty?.performanceCondition
+ ? {
+ ...bounty.performanceCondition,
+ value: isCurrencyAttribute(bounty.performanceCondition.attribute)
+ ? bounty.performanceCondition.value / 100
+ : bounty.performanceCondition.value,
+ }
+ : {
+ operator: "gte",
+ },
+ performanceScope: bounty?.performanceScope ?? "new",
+ rewardType: bounty ? (bounty.rewardAmount ? "flat" : "custom") : "flat",
+ submissionCriteriaType:
+ bounty?.submissionRequirements &&
+ typeof bounty.submissionRequirements === "object" &&
+ "socialMetrics" in bounty.submissionRequirements
+ ? "socialMetrics"
+ : "manualSubmission",
+ },
+ shouldUnregister: false,
+ });
+
+ const {
+ handleSubmit,
+ watch,
+ setValue,
+ control,
+ register,
+ formState: { errors, isDirty },
+ } = form;
+
+ const [
+ startsAt,
+ endsAt,
+ rewardAmount,
+ rewardDescription,
+ type,
+ name,
+ description,
+ performanceCondition,
+ groupIds,
+ rewardType,
+ submissionRequirements,
+ ] = watch([
+ "startsAt",
+ "endsAt",
+ "rewardAmount",
+ "rewardDescription",
+ "type",
+ "name",
+ "description",
+ "performanceCondition",
+ "groupIds",
+ "rewardType",
+ "submissionRequirements",
+ ]);
+
+ const handleStartDateToggle = (checked: boolean) => {
+ setHasStartDate(checked);
+ if (!checked) {
+ setValue("startsAt", null, { shouldDirty: true, shouldValidate: true });
+ }
+ };
+
+ const handleEndDateToggle = (checked: boolean) => {
+ setHasEndDate(checked);
+ if (!checked) {
+ setValue("endsAt", null, { shouldDirty: true, shouldValidate: true });
+ setSubmissionWindow(null);
+ setValue("submissionsOpenAt", null, { shouldDirty: true });
+ }
+ };
+
+ const handleEndDateChange = (date: Date | null) => {
+ setValue("endsAt", date, {
+ shouldDirty: true,
+ shouldValidate: true,
+ });
+ if (date && submissionWindow != null) {
+ const submissionsOpenAt = new Date(date);
+ submissionsOpenAt.setDate(submissionsOpenAt.getDate() - submissionWindow);
+ setValue("submissionsOpenAt", submissionsOpenAt, {
+ shouldDirty: true,
+ shouldValidate: true,
+ });
+ }
+ };
+
+ const getInitialSubmissionWindow = () => {
+ if (!bounty?.submissionsOpenAt || !bounty?.endsAt) return null;
+ const days = Math.ceil(
+ (new Date(bounty.endsAt).getTime() -
+ new Date(bounty.submissionsOpenAt).getTime()) /
+ (1000 * 60 * 60 * 24),
+ );
+ return days >= 2 && days <= 14 ? days : null;
+ };
+
+ const handleSubmissionWindowToggle = (checked: boolean) => {
+ if (checked) {
+ const val = getInitialSubmissionWindow() ?? 2;
+ setSubmissionWindow(val);
+ if (endsAt) {
+ const submissionsOpenAt = new Date(endsAt);
+ submissionsOpenAt.setDate(submissionsOpenAt.getDate() - val);
+ setValue("submissionsOpenAt", submissionsOpenAt, {
+ shouldDirty: true,
+ shouldValidate: true,
+ });
+ }
+ } else {
+ setSubmissionWindow(null);
+ setValue("submissionsOpenAt", null, { shouldDirty: true });
+ }
+ };
+
+ const handleSubmissionWindowChange = (value: number) => {
+ setSubmissionWindow(value);
+ if (endsAt) {
+ const submissionsOpenAt = new Date(endsAt);
+ submissionsOpenAt.setDate(submissionsOpenAt.getDate() - value);
+ setValue("submissionsOpenAt", submissionsOpenAt, {
+ shouldDirty: true,
+ shouldValidate: true,
+ });
+ }
+ };
+
+ const validationError = useMemo(() => {
+ const now = new Date();
+
+ if (startsAt && startsAt !== bounty?.startsAt) {
+ const startDate = new Date(startsAt);
+ if (startDate < now) {
+ return "Please choose a start date that is in the future.";
+ }
+ }
+
+ const effectiveStartDate = startsAt ? new Date(startsAt) : now;
+
+ if (endsAt) {
+ const endDate = new Date(endsAt);
+
+ if (endDate <= effectiveStartDate) {
+ return `Please choose an end date that is after the start date (${formatDate(effectiveStartDate)}).`;
+ }
+
+ const minEndDate = new Date(
+ effectiveStartDate.getTime() + 60 * 60 * 1000,
+ );
+ if (endDate < minEndDate) {
+ return "End date must be at least 1 hour after the start date.";
+ }
+ }
+
+ if (type === "submission" && submissionWindow != null) {
+ if (!endsAt) {
+ return "An end date is required to determine when the submission window opens.";
+ }
+ if (submissionWindow < 2 || submissionWindow > 14) {
+ return "Submission window must be between 2 and 14 days.";
+ }
+ const calculatedSubmissionsOpenAt = new Date(endsAt);
+ calculatedSubmissionsOpenAt.setDate(
+ calculatedSubmissionsOpenAt.getDate() - submissionWindow,
+ );
+ if (calculatedSubmissionsOpenAt < effectiveStartDate) {
+ return "Submission window is too long. It would open before the bounty starts.";
+ }
+ }
+
+ if (type === "submission") {
+ if (!name?.trim()) {
+ return "Name is required for submission bounties.";
+ }
+
+ if (name && name.length > 100) {
+ return "Name must be 100 characters or less.";
+ }
+
+ if ((rewardType ?? "flat") === "flat") {
+ if (isEmpty(rewardAmount)) {
+ return "Reward amount is required for flat rate rewards.";
+ }
+ if (rewardAmount !== null && rewardAmount <= 0) {
+ return "Reward amount must be greater than 0.";
+ }
+ if (rewardAmount !== null && rewardAmount > 1000000) {
+ return "Reward amount cannot exceed $1,000,000.";
+ }
+ }
+
+ if ((rewardType ?? "flat") === "custom") {
+ const isSocialMetrics =
+ submissionRequirements &&
+ typeof submissionRequirements === "object" &&
+ "socialMetrics" in submissionRequirements;
+ if (!isSocialMetrics) {
+ if (!rewardDescription?.trim()) {
+ return "Reward description is required for custom rewards.";
+ }
+ if (rewardDescription && rewardDescription.length > 100) {
+ return "Reward description must be 100 characters or less.";
+ }
+ }
+ }
+ }
+
+ if (type === "performance") {
+ const condition = performanceCondition;
+
+ if (!condition?.attribute) {
+ return "Performance attribute is required.";
+ }
+
+ if (!condition?.operator) {
+ return "Performance operator is required.";
+ }
+
+ if (isEmpty(condition?.value)) {
+ return "Performance value is required.";
+ }
+
+ if (condition?.value !== null && condition.value < 0) {
+ return "Performance value must be greater than or equal to 0.";
+ }
+
+ if (isEmpty(rewardAmount)) {
+ return "Reward amount is required for performance bounties.";
+ }
+
+ if (rewardAmount !== null && rewardAmount <= 0) {
+ return "Reward amount must be greater than 0.";
+ }
+
+ if (rewardAmount !== null && rewardAmount > 1000000) {
+ return "Reward amount cannot exceed $1,000,000.";
+ }
+ }
+
+ if (description && description.length > BOUNTY_DESCRIPTION_MAX_LENGTH) {
+ return `Description must be ${BOUNTY_DESCRIPTION_MAX_LENGTH} characters or less.`;
+ }
+
+ return null;
+ }, [
+ bounty,
+ startsAt,
+ endsAt,
+ submissionWindow,
+ rewardAmount,
+ rewardDescription,
+ rewardType,
+ type,
+ name,
+ description,
+ performanceCondition?.attribute,
+ performanceCondition?.operator,
+ performanceCondition?.value,
+ submissionRequirements,
+ ]);
+
+ const performSubmit = async ({
+ sendNotificationEmails,
+ }: { sendNotificationEmails?: boolean } = {}) => {
+ if (!workspaceId) return;
+
+ const {
+ rewardType: formRewardType,
+ submissionCriteriaType: _submissionCriteriaType,
+ ...data
+ } = form.getValues();
+
+ const rawRewardAmount = data.rewardAmount;
+ const numAmount =
+ typeof rawRewardAmount === "number" && !Number.isNaN(rawRewardAmount)
+ ? rawRewardAmount
+ : null;
+ data.rewardAmount =
+ numAmount != null && numAmount > 0 ? numAmount * 100 : null;
+
+ if (data.type === "performance") {
+ const result = bountyPerformanceConditionSchema.safeParse(
+ data.performanceCondition,
+ );
+
+ if (!result.success) {
+ toast.error(
+ "Invalid performance logic. Please fix the errors and try again.",
+ );
+ return;
+ }
+
+ let { data: condition } = result;
+
+ condition = {
+ ...condition,
+ value: isCurrencyAttribute(condition.attribute)
+ ? condition.value * 100
+ : condition.value,
+ };
+
+ data.performanceCondition = condition;
+ data.rewardDescription = null;
+ data.submissionsOpenAt = null;
+ } else if (data.type === "submission") {
+ data.performanceCondition = null;
+ data.submissionFrequency = undefined;
+ data.maxSubmissions = undefined;
+
+ if ((formRewardType ?? "flat") === "custom") {
+ data.rewardAmount = null;
+ } else if ((formRewardType ?? "flat") === "flat") {
+ data.rewardDescription = null;
+ }
+
+ const incBonus =
+ data.submissionRequirements?.socialMetrics?.incrementalBonus;
+ if (incBonus && typeof incBonus.bonusPerIncrement === "number") {
+ data.submissionRequirements = {
+ ...data.submissionRequirements!,
+ socialMetrics: {
+ ...data.submissionRequirements!.socialMetrics!,
+ incrementalBonus: {
+ ...incBonus,
+ bonusPerIncrement: incBonus.bonusPerIncrement * 100,
+ },
+ },
+ };
+ }
+ }
+
+ await makeRequest(bounty ? `/api/bounties/${bounty.id}` : "/api/bounties", {
+ method: bounty ? "PATCH" : "POST",
+ body: { ...data, sendNotificationEmails },
+ onSuccess: () => {
+ mutatePrefix("/api/bounties");
+ setIsOpen(false);
+ toast.success(`Bounty ${bounty ? "updated" : "created"} successfully!`);
+ },
+ });
+ };
+
+ const { setShowConfirmCreateBountyModal, confirmCreateBountyModal } =
+ useConfirmCreateBountyModal({
+ bounty: !validationError
+ ? {
+ type,
+ name:
+ type === "performance" && performanceCondition
+ ? generatePerformanceBountyName({
+ rewardAmount: rewardAmount ? rewardAmount * 100 : 0,
+ condition: isCurrencyAttribute(
+ performanceCondition?.attribute,
+ )
+ ? {
+ ...performanceCondition,
+ value: performanceCondition?.value * 100,
+ }
+ : performanceCondition,
+ })
+ : name || "New bounty",
+ startsAt: startsAt || new Date(),
+ endsAt: endsAt || null,
+ rewardAmount: rewardAmount ? rewardAmount * 100 : null,
+ rewardDescription: rewardDescription || null,
+ groups: groupIds?.map((id) => ({ id })) || [],
+ }
+ : undefined,
+ onConfirm: async ({ sendNotificationEmails }) => {
+ await performSubmit({ sendNotificationEmails });
+ },
+ });
+
+ const onSubmit = handleSubmit(async () => {
+ if (bounty) {
+ await performSubmit();
+ } else {
+ setShowConfirmCreateBountyModal(true);
+ }
+ });
+
+ return {
+ form,
+ hasStartDate,
+ setHasStartDate,
+ hasEndDate,
+ handleEndDateToggle,
+ openAccordions,
+ setOpenAccordions,
+ type,
+ name,
+ control,
+ register,
+ setValue,
+ watch,
+ errors,
+ isDirty,
+ handleStartDateToggle,
+ handleEndDateChange,
+ submissionWindow,
+ handleSubmissionWindowToggle,
+ handleSubmissionWindowChange,
+ validationError,
+ confirmCreateBountyModal,
+ setShowConfirmCreateBountyModal,
+ onSubmit,
+ isSubmitting,
+ };
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-action-button.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-action-button.tsx
index 32977cf40a..43f9b23964 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-action-button.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-action-button.tsx
@@ -14,7 +14,7 @@ import { PenWriting, Trash } from "@dub/ui/icons";
import { Command } from "cmdk";
import { useMemo, useState } from "react";
import { toast } from "sonner";
-import { useBountySheet } from "./add-edit-bounty-sheet";
+import { useBountySheet } from "./add-edit-bounty/add-edit-bounty-sheet";
interface BountyActionButtonProps {
bounty: BountyProps;
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx
index ac8e13b30e..4b09f0f695 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx
@@ -1,12 +1,12 @@
-import { getBountyRewardDescription } from "@/lib/partners/get-bounty-reward-description";
import useGroups from "@/lib/swr/use-groups";
import { usePartnersCountByGroupIds } from "@/lib/swr/use-partners-count-by-groupids";
import useWorkspace from "@/lib/swr/use-workspace";
import { BountyListProps } from "@/lib/types";
+import { BountyRewardDescription } from "@/ui/partners/bounties/bounty-reward-description";
import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
import { GroupColorCircle } from "@/ui/partners/groups/group-color-circle";
import { DynamicTooltipWrapper, ScrollableTooltipContent } from "@dub/ui";
-import { Calendar6, Gift, Users, Users6 } from "@dub/ui/icons";
+import { Calendar6, Users, Users6 } from "@dub/ui/icons";
import { formatDate, nFormatter, pluralize } from "@dub/utils";
import Link from "next/link";
import { useMemo } from "react";
@@ -71,12 +71,11 @@ export function BountyCard({ bounty }: { bounty: BountyListProps }) {
</span>
</div>
- {getBountyRewardDescription(bounty) && (
- <div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
- <Gift className="size-3.5" />
- <span>{getBountyRewardDescription(bounty)}</span>
- </div>
- )}
+ <BountyRewardDescription
+ bounty={bounty}
+ className="font-regular"
+ onTooltipClick={(e) => e.preventDefault()}
+ />
<div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
<Users className="size-3.5" />
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-list.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-list.tsx
index b5f9379ba0..fef19200bd 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-list.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-list.tsx
@@ -7,7 +7,7 @@ import { Button } from "@dub/ui";
import { fetcher } from "@dub/utils";
import { Trophy } from "lucide-react";
import useSWR from "swr";
-import { useBountySheet } from "./add-edit-bounty-sheet";
+import { useBountySheet } from "./add-edit-bounty/add-edit-bounty-sheet";
import { BountyCard, BountyCardSkeleton } from "./bounty-card";
export function BountyList() {
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/create-bounty-button.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/create-bounty-button.tsx
index 69dd77cea0..06ab7c6c9f 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/create-bounty-button.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/create-bounty-button.tsx
@@ -1,7 +1,7 @@
"use client";
import { Button, useKeyboardShortcut, useMediaQuery } from "@dub/ui";
-import { useBountySheet } from "./add-edit-bounty-sheet";
+import { useBountySheet } from "./add-edit-bounty/add-edit-bounty-sheet";
export function CreateBountyButton() {
const { isMobile } = useMediaQuery();
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/layout.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/layout.tsx
index 14fced625d..f59e3cb16d 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/layout.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/layout.tsx
@@ -43,7 +43,7 @@ export default function Layout({ children }: PropsWithChildren) {
))}
</div>
- <div className="relative flex min-h-screen min-h-[100dvh] w-full flex-col items-center justify-between">
+ <div className="relative flex min-h-[100dvh] min-h-screen w-full flex-col items-center justify-between">
<div className="grow basis-0">
<div className="pt-4">
<Link href="https://dub.co/home" target="_blank" className="block">
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/welcome/page.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/welcome/page.tsx
index c04befbb72..6d6227be31 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/welcome/page.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/welcome/page.tsx
@@ -9,7 +9,7 @@ export default function Welcome() {
<>
<TrackSignup />
<NewBackground showAnimation showGradient={false} />
- <div className="relative flex min-h-screen min-h-[100dvh] flex-col items-center justify-center">
+ <div className="relative flex min-h-[100dvh] min-h-screen flex-col items-center justify-center">
<div className="flex max-w-sm flex-col items-center px-4 py-16 text-center">
<div className="animate-slide-up-fade relative flex w-auto items-center justify-center px-6 py-2 [--offset:20px] [animation-duration:1.3s] [animation-fill-mode:both]">
<Gradient className="opacity-10 mix-blend-overlay" />
diff --git a/apps/web/lib/actions/partners/approve-bounty-submission.ts b/apps/web/lib/actions/partners/approve-bounty-submission.ts
index 2f597f3356..207064a629 100644
--- a/apps/web/lib/actions/partners/approve-bounty-submission.ts
+++ b/apps/web/lib/actions/partners/approve-bounty-submission.ts
@@ -1,7 +1,7 @@
"use server";
-import { approveBountySubmission } from "@/lib/api/bounties/approve-bounty-submission";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { approveBountySubmission } from "@/lib/bounty/api/approve-bounty-submission";
import { approveBountySubmissionBodySchema } from "@/lib/zod/schemas/bounties";
import * as z from "zod/v4";
import { authActionClient } from "../safe-action";
diff --git a/apps/web/lib/actions/partners/create-bounty-submission.ts b/apps/web/lib/actions/partners/create-bounty-submission.ts
index 56a12da678..a1a02026db 100644
--- a/apps/web/lib/actions/partners/create-bounty-submission.ts
+++ b/apps/web/lib/actions/partners/create-bounty-submission.ts
@@ -3,47 +3,28 @@
import { createId } from "@/lib/api/create-id";
import { getWorkspaceUsers } from "@/lib/api/get-workspace-users";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { getSocialContent } from "@/lib/api/scrape-creators/get-social-content";
+import { BOUNTY_MAX_SUBMISSION_URLS } from "@/lib/bounty/constants";
import {
- BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH,
- BOUNTY_MAX_SUBMISSION_FILES,
- BOUNTY_MAX_SUBMISSION_URLS,
-} from "@/lib/constants/bounties";
+ getPlatformFromSocialUrl,
+ resolveBountyDetails,
+} from "@/lib/bounty/utils";
import {
- BountySubmissionFileSchema,
+ createBountySubmissionInputSchema,
submissionRequirementsSchema,
} from "@/lib/zod/schemas/bounties";
import { sendBatchEmail, sendEmail } from "@dub/email";
import NewBountySubmission from "@dub/email/templates/bounty-new-submission";
import BountySubmitted from "@dub/email/templates/bounty-submitted";
import { prisma } from "@dub/prisma";
-import { BountySubmission, WorkspaceRole } from "@dub/prisma/client";
+import { BountySubmission, Prisma, WorkspaceRole } from "@dub/prisma/client";
import { getDomainWithoutWWW } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
-import { formatDistanceToNow } from "date-fns";
-import * as z from "zod/v4";
+import { formatDistanceToNow, isBefore } from "date-fns";
import { authPartnerActionClient } from "../safe-action";
-const schema = z.object({
- programId: z.string(),
- bountyId: z.string(),
- files: z
- .array(BountySubmissionFileSchema)
- .max(BOUNTY_MAX_SUBMISSION_FILES)
- .default([]),
- urls: z.array(z.url()).max(BOUNTY_MAX_SUBMISSION_URLS).default([]),
- description: z
- .string()
- .trim()
- .max(BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH)
- .optional(),
- isDraft: z
- .boolean()
- .default(false)
- .describe("Whether to create a draft submission or a final submission."),
-});
-
export const createBountySubmissionAction = authPartnerActionClient
- .inputSchema(schema)
+ .inputSchema(createBountySubmissionInputSchema)
.action(async ({ ctx, parsedInput }) => {
const { partner } = ctx;
const { programId, bountyId, files, urls, description, isDraft } =
@@ -137,6 +118,14 @@ export const createBountySubmissionAction = authPartnerActionClient
);
}
+ const bountyInfo = resolveBountyDetails(bounty);
+
+ if (bountyInfo?.hasSocialMetrics && isDraft) {
+ throw new Error(
+ "Draft submissions are not allowed for social metrics bounties.",
+ );
+ }
+
// Validate the submission requirements
const submissionRequirements = bounty.submissionRequirements
? submissionRequirementsSchema.parse(bounty.submissionRequirements)
@@ -146,6 +135,11 @@ export const createBountySubmissionAction = authPartnerActionClient
const requireUrl = !!submissionRequirements?.url;
const urlRequirement = submissionRequirements?.url || null;
const imageRequirement = submissionRequirements?.image || null;
+ const storedUrls = [...urls].slice(0, BOUNTY_MAX_SUBMISSION_URLS);
+
+ let submissionData: Partial<Prisma.BountySubmissionUncheckedCreateInput> = {
+ status: isDraft ? "draft" : "submitted",
+ };
if (!isDraft) {
if (requireImage && files.length === 0) {
@@ -200,8 +194,126 @@ export const createBountySubmissionAction = authPartnerActionClient
`You can submit at most ${imageRequirement.max} image${imageRequirement.max === 1 ? "" : "s"}.`,
);
}
+
+ submissionData = {
+ ...submissionData,
+ completedAt: new Date(),
+ };
+ }
+
+ // Validate social content requirements
+ if (bountyInfo?.socialMetrics) {
+ const contentUrl = storedUrls[0];
+
+ if (!bountyInfo?.socialPlatform) {
+ throw new Error("Invalid bounty platform.");
+ }
+
+ const platform = bountyInfo.socialPlatform;
+
+ if (!contentUrl) {
+ throw new Error(
+ `You must provide a ${platform.label} URL to submit this bounty.`,
+ );
+ }
+
+ const urlPlatform = getPlatformFromSocialUrl(contentUrl);
+
+ if (urlPlatform !== platform.value) {
+ throw new Error(
+ `This link must be a ${platform.label} link. You submitted a link from another platform.`,
+ );
+ }
+
+ const partnerPlatform = await prisma.partnerPlatform.findUnique({
+ where: {
+ partnerId_type: {
+ partnerId: partner.id,
+ type: platform.value,
+ },
+ },
+ select: {
+ identifier: true,
+ verifiedAt: true,
+ },
+ });
+
+ if (!partnerPlatform) {
+ throw new Error(
+ `You must connect your ${platform.label} account to your profile before submitting this bounty.`,
+ );
+ }
+
+ if (!partnerPlatform.verifiedAt) {
+ throw new Error(
+ `You must verify your ${platform.label} account before submitting this bounty.`,
+ );
+ }
+
+ const socialContent = await getSocialContent({
+ platform: platform.value,
+ url: storedUrls[0],
+ });
+
+ if (!socialContent.handle || !socialContent.publishedAt) {
+ throw new Error(
+ "We were unable to verify this content. Please review the submission and try again.",
+ );
+ }
+
+ if (
+ socialContent.handle.toLowerCase() !==
+ partnerPlatform.identifier.toLowerCase()
+ ) {
+ throw new Error(
+ `The content was not published from your connected ${platform.label} account.`,
+ );
+ }
+
+ if (
+ socialContent.publishedAt &&
+ bounty.startsAt &&
+ isBefore(socialContent.publishedAt, bounty.startsAt)
+ ) {
+ throw new Error(
+ `This content was published before the bounty started. Please submit content posted after the start date.`,
+ );
+ }
+
+ submissionData = {
+ ...submissionData,
+ status: "draft",
+ completedAt: null,
+ };
+
+ const metricValue = socialContent[bountyInfo.socialMetrics.metric];
+
+ if (typeof metricValue === "number" && Number.isInteger(metricValue)) {
+ submissionData = {
+ ...submissionData,
+ urls: [contentUrl],
+ socialMetricCount: metricValue,
+ socialMetricsLastSyncedAt: new Date(),
+ };
+
+ if (
+ metricValue &&
+ bountyInfo.socialMetrics.minCount &&
+ metricValue >= bountyInfo.socialMetrics.minCount
+ ) {
+ submissionData.status = "submitted";
+ submissionData.completedAt = new Date();
+ }
+ }
}
+ submissionData = {
+ ...submissionData,
+ ...(requireImage && { files }),
+ ...(!bountyInfo?.hasSocialMetrics && requireUrl && { urls }),
+ ...(description && { description }),
+ };
+
// If there is an existing submission, update it
if (submission) {
submission = await prisma.bountySubmission.update({
@@ -209,11 +321,7 @@ export const createBountySubmissionAction = authPartnerActionClient
id: submission.id,
},
data: {
- description,
- ...(requireImage && { files }),
- ...(requireUrl && { urls }),
- status: isDraft ? "draft" : "submitted",
- ...(isDraft ? {} : { completedAt: new Date() }),
+ ...submissionData,
},
});
}
@@ -221,15 +329,11 @@ export const createBountySubmissionAction = authPartnerActionClient
else {
submission = await prisma.bountySubmission.create({
data: {
+ ...submissionData,
id: createId({ prefix: "bnty_sub_" }),
programId: bounty.programId,
bountyId: bounty.id,
partnerId: partner.id,
- description,
- ...(requireImage && { files }),
- ...(requireUrl && { urls }),
- status: isDraft ? "draft" : "submitted",
- ...(isDraft ? {} : { completedAt: new Date() }),
},
});
}
@@ -296,8 +400,4 @@ export const createBountySubmissionAction = authPartnerActionClient
}
})(),
);
-
- return {
- success: true,
- };
});
diff --git a/apps/web/lib/actions/partners/reject-bounty-submission.ts b/apps/web/lib/actions/partners/reject-bounty-submission.ts
index 0fe264e0cb..fe5665ed01 100644
--- a/apps/web/lib/actions/partners/reject-bounty-submission.ts
+++ b/apps/web/lib/actions/partners/reject-bounty-submission.ts
@@ -1,7 +1,7 @@
"use server";
-import { rejectBountySubmission } from "@/lib/api/bounties/reject-bounty-submission";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { rejectBountySubmission } from "@/lib/bounty/api/reject-bounty-submission";
import { rejectBountySubmissionBodySchema } from "@/lib/zod/schemas/bounties";
import * as z from "zod/v4";
import { authActionClient } from "../safe-action";
diff --git a/apps/web/lib/actions/partners/verify-social-account-by-code.ts b/apps/web/lib/actions/partners/verify-social-account-by-code.ts
index 0e1ac9e215..fc130f2958 100644
--- a/apps/web/lib/actions/partners/verify-social-account-by-code.ts
+++ b/apps/web/lib/actions/partners/verify-social-account-by-code.ts
@@ -1,6 +1,6 @@
"use server";
-import { fetchSocialProfile } from "@/lib/api/scrape-creators/fetch-social-profile";
+import { getSocialProfile } from "@/lib/api/scrape-creators/get-social-profile";
import { ratelimit } from "@/lib/upstash";
import { redis } from "@/lib/upstash/redis";
import { prisma } from "@dub/prisma";
@@ -74,7 +74,7 @@ export const verifySocialAccountByCodeAction = authPartnerActionClient
// Verifies that a verification code exists in the account's profile bio/description.
// Fetches the account profile and checks if the provided code appears in any of the
// profile text fields (description, about, bio, summary).
- const socialProfile = await fetchSocialProfile({
+ const socialProfile = await getSocialProfile({
platform,
handle,
});
@@ -110,6 +110,7 @@ export const verifySocialAccountByCodeAction = authPartnerActionClient
subscribers: socialProfile.subscribers,
posts: socialProfile.posts,
views: socialProfile.views,
+ avatarUrl: socialProfile.avatarUrl,
},
});
diff --git a/apps/web/lib/api/error-codes.ts b/apps/web/lib/api/error-codes.ts
index 939baf74f8..cdbf24c617 100644
--- a/apps/web/lib/api/error-codes.ts
+++ b/apps/web/lib/api/error-codes.ts
@@ -15,5 +15,8 @@ export const ErrorCodes = {
} as const;
export const ErrorCode = z.enum(
- Object.keys(ErrorCodes) as [string, ...string[]],
+ Object.keys(ErrorCodes) as [
+ keyof typeof ErrorCodes,
+ ...(keyof typeof ErrorCodes)[],
+ ],
);
diff --git a/apps/web/lib/api/groups/move-partners-to-group.ts b/apps/web/lib/api/groups/move-partners-to-group.ts
index 5c7905a107..5828bf1a56 100644
--- a/apps/web/lib/api/groups/move-partners-to-group.ts
+++ b/apps/web/lib/api/groups/move-partners-to-group.ts
@@ -1,3 +1,4 @@
+import { triggerDraftBountySubmissionCreation } from "@/lib/bounty/api/trigger-draft-bounty-submissions";
import { qstash } from "@/lib/cron";
import { recordLink } from "@/lib/tinybird";
import { prisma } from "@dub/prisma";
@@ -9,7 +10,6 @@ import {
trackActivityLog,
TrackActivityLogInput,
} from "../activity-log/track-activity-log";
-import { triggerDraftBountySubmissionCreation } from "../bounties/trigger-draft-bounty-submissions";
import { getWorkspaceUsers } from "../get-workspace-users";
import { includeProgramEnrollment } from "../links/include-program-enrollment";
import { includeTags } from "../links/include-tags";
diff --git a/apps/web/lib/api/scrape-creators/client.ts b/apps/web/lib/api/scrape-creators/client.ts
index 72cf0b75f2..7f4820af4d 100644
--- a/apps/web/lib/api/scrape-creators/client.ts
+++ b/apps/web/lib/api/scrape-creators/client.ts
@@ -1,7 +1,7 @@
import { createFetch, createSchema } from "@better-fetch/fetch";
import { PlatformType } from "@dub/prisma/client";
import * as z from "zod/v4";
-import { profileResponseSchema } from "./schema";
+import { socialContentSchema, socialProfileSchema } from "./schema";
export const scrapeCreatorsFetch = createFetch({
baseURL: "https://api.scrapecreators.com",
@@ -15,6 +15,7 @@ export const scrapeCreatorsFetch = createFetch({
},
schema: createSchema(
{
+ // Fetch social profile
"/v1/:platform/:handleType": {
method: "get",
params: z.object({
@@ -24,20 +25,34 @@ export const scrapeCreatorsFetch = createFetch({
query: z.object({
handle: z.string(),
}),
- output: profileResponseSchema,
+ output: socialProfileSchema,
},
+
+ // Fetch social content
+ "/:version/:platform/:contentType": {
+ method: "get",
+ params: z.object({
+ version: z.enum(["v1", "v2"]),
+ platform: z.enum(PlatformType),
+ contentType: z.enum(["post", "video", "tweet"]),
+ }),
+ query: z.object({
+ url: z.string(),
+ }),
+ output: socialContentSchema,
+ },
+ },
+ {
+ strict: true,
},
- { strict: true },
),
onError: ({ error }) => {
console.error("[ScrapeCreators] Error", error);
},
// onResponse: async ({ response }) => {
- // if (process.env.NODE_ENV === "development") {
- // console.log(
- // "[ScrapeCreators] Response",
- // prettyPrint(await response.clone().json()),
- // );
- // }
+ // console.log(
+ // "[ScrapeCreators] Response",
+ // prettyPrint(await response.clone().json()),
+ // );
// },
});
diff --git a/apps/web/lib/api/scrape-creators/get-social-content.ts b/apps/web/lib/api/scrape-creators/get-social-content.ts
new file mode 100644
index 0000000000..afbab85229
--- /dev/null
+++ b/apps/web/lib/api/scrape-creators/get-social-content.ts
@@ -0,0 +1,213 @@
+import { BOUNTY_SOCIAL_PLATFORM_VALUES } from "@/lib/bounty/constants";
+import { SocialContent } from "@/lib/types";
+import { redis } from "@/lib/upstash";
+import { PlatformType } from "@dub/prisma/client";
+import { hashStringSHA256, isValidUrl } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
+import { scrapeCreatorsFetch } from "./client";
+
+const CACHE_KEY_PREFIX = "socialContentCache";
+const CACHE_TTL = 60 * 60;
+
+interface GetSocialContentStatsParams {
+ platform: PlatformType;
+ url: string;
+}
+
+const PLATFORM_CONTENT_TYPE: Record<
+ Exclude<PlatformType, "website" | "linkedin">,
+ "post" | "video" | "tweet"
+> = {
+ youtube: "video",
+ instagram: "post",
+ twitter: "tweet",
+ tiktok: "video",
+};
+
+const EMPTY_SOCIAL_CONTENT: SocialContent = {
+ publishedAt: null,
+ platformId: null,
+ handle: null,
+ likes: 0,
+ views: 0,
+ title: null,
+ description: null,
+ thumbnailUrl: null,
+};
+
+export async function getSocialContent({
+ platform,
+ url,
+}: GetSocialContentStatsParams): Promise<SocialContent> {
+ url = url?.trim();
+
+ // Invalid URL
+ if (!url || !isValidUrl(url)) {
+ return EMPTY_SOCIAL_CONTENT;
+ }
+
+ url = normalizeUrl(url);
+
+ // Check cache first
+ const urlHash = await hashStringSHA256(url);
+ const cacheKey = `${CACHE_KEY_PREFIX}:${urlHash}`;
+
+ const cachedResult = await redis.get<SocialContent>(cacheKey);
+
+ if (cachedResult) {
+ return cachedResult;
+ }
+
+ const contentType = PLATFORM_CONTENT_TYPE[platform];
+ const version = platform === "tiktok" ? "v2" : "v1";
+
+ const { data, error } = await scrapeCreatorsFetch(
+ "/:version/:platform/:contentType",
+ {
+ params: {
+ version,
+ platform,
+ contentType,
+ },
+ query: {
+ url,
+ },
+ },
+ );
+
+ if (error) {
+ return EMPTY_SOCIAL_CONTENT;
+ }
+
+ let result: SocialContent;
+
+ switch (data.platform) {
+ case "youtube": {
+ result = {
+ publishedAt: new Date(data.publishDateText),
+ handle: data.channel.handle,
+ platformId: data.channel.id,
+ views: data.viewCountInt,
+ likes: data.likeCountInt,
+ title: data.title ?? null,
+ description: data.description ?? null,
+ thumbnailUrl: data.thumbnailUrl ?? null,
+ };
+ break;
+ }
+
+ case "instagram": {
+ const thumbnailUrl = data.display_url ?? data.thumbnail_src ?? null;
+ const carouselEdges = data.edge_sidecar_to_children?.edges ?? [];
+
+ const thumbnailUrls =
+ carouselEdges.length > 0
+ ? carouselEdges
+ .map(
+ (edge: {
+ node: { display_url?: string; thumbnail_src?: string };
+ }) => edge.node.display_url ?? edge.node.thumbnail_src ?? "",
+ )
+ .filter(Boolean)
+ : undefined;
+
+ let mediaType: "image" | "video" | "carousel" | undefined;
+
+ if (data.__typename === "GraphVideo") {
+ mediaType = "video";
+ } else if (
+ data.__typename === "GraphSidecar" ||
+ (thumbnailUrls !== undefined && thumbnailUrls.length > 0)
+ ) {
+ mediaType = "carousel";
+ } else if (data.__typename === "GraphImage") {
+ mediaType = "image";
+ } else if (thumbnailUrls === undefined && data.video_view_count > 0) {
+ mediaType = "video";
+ }
+
+ result = {
+ publishedAt: new Date(data.taken_at_timestamp * 1000),
+ handle: data.owner.username,
+ platformId: null,
+ views: data.video_view_count,
+ likes: data.edge_media_preview_like.count,
+ title: null,
+ description: data.edge_media_to_caption?.edges?.[0]?.node?.text ?? null,
+ thumbnailUrl,
+ mediaType,
+ thumbnailUrls,
+ };
+ break;
+ }
+
+ case "twitter": {
+ result = {
+ publishedAt: new Date(data.legacy.created_at),
+ handle: data.core.user_results.result.core.screen_name,
+ platformId: null,
+ views: data.views.count,
+ likes: data.legacy.favorite_count,
+ title: null,
+ description: data.legacy.full_text ?? null,
+ thumbnailUrl: null,
+ };
+ break;
+ }
+
+ case "tiktok": {
+ result = {
+ publishedAt: new Date(data.create_time_utc),
+ handle: data.author.unique_id,
+ platformId: null,
+ views: data.statistics.play_count,
+ likes: data.statistics.digg_count,
+ title: null,
+ description: data.desc ?? null,
+ thumbnailUrl: data.video?.cover?.url_list?.[0] ?? null,
+ };
+ break;
+ }
+
+ default:
+ result = {
+ publishedAt: null,
+ handle: null,
+ platformId: null,
+ views: 0,
+ likes: 0,
+ title: null,
+ description: null,
+ thumbnailUrl: null,
+ };
+ }
+
+ if (BOUNTY_SOCIAL_PLATFORM_VALUES.includes(data.platform)) {
+ waitUntil(redis.set(cacheKey, result, { ex: CACHE_TTL }));
+ }
+
+ return result;
+}
+
+function normalizeUrl(raw: string) {
+ const url = new URL(raw);
+
+ // Lowercase hostname
+ url.hostname = url.hostname.toLowerCase();
+
+ // Remove tracking params
+ [
+ "utm_source",
+ "utm_medium",
+ "utm_campaign",
+ "si",
+ "feature",
+ "igshid",
+ "t",
+ ].forEach((p) => url.searchParams.delete(p));
+
+ // Remove trailing slash
+ url.pathname = url.pathname.replace(/\/$/, "");
+
+ return url.toString();
+}
diff --git a/apps/web/lib/api/scrape-creators/fetch-social-profile.ts b/apps/web/lib/api/scrape-creators/get-social-profile.ts
similarity index 81%
rename from apps/web/lib/api/scrape-creators/fetch-social-profile.ts
rename to apps/web/lib/api/scrape-creators/get-social-profile.ts
index bcb42560eb..1ea893b383 100644
--- a/apps/web/lib/api/scrape-creators/fetch-social-profile.ts
+++ b/apps/web/lib/api/scrape-creators/get-social-profile.ts
@@ -1,18 +1,18 @@
import { PartnerPlatform, PlatformType } from "@dub/prisma/client";
import { scrapeCreatorsFetch } from "./client";
-type FetchSocialProfileParams = {
- platform: PlatformType;
- handle: string;
-};
-
type SocialProfile = Pick<
PartnerPlatform,
- "platformId" | "subscribers" | "posts" | "views"
+ "platformId" | "subscribers" | "posts" | "views" | "avatarUrl"
> & {
description: string | null;
};
+interface GetSocialProfileParams {
+ platform: PlatformType;
+ handle: string;
+}
+
export class AccountNotFoundError extends Error {
constructor(message: string) {
super(message);
@@ -20,10 +20,10 @@ export class AccountNotFoundError extends Error {
}
}
-export async function fetchSocialProfile({
+export async function getSocialProfile({
platform,
handle,
-}: FetchSocialProfileParams) {
+}: GetSocialProfileParams) {
const { data, error } = await scrapeCreatorsFetch(
"/v1/:platform/:handleType",
{
@@ -56,15 +56,21 @@ export async function fetchSocialProfile({
subscribers: BigInt(0),
posts: BigInt(0),
views: BigInt(0),
+ avatarUrl: null,
};
switch (data.platform) {
case "youtube": {
+ const largestAvatar = data.avatar.image.sources.sort(
+ (a, b) => b.width - a.width,
+ )[0];
+
socialProfile.description = data.description;
socialProfile.platformId = data.channelId;
socialProfile.subscribers = BigInt(data.subscriberCount);
socialProfile.posts = BigInt(data.videoCount);
socialProfile.views = BigInt(data.viewCount);
+ socialProfile.avatarUrl = largestAvatar?.url ?? null;
break;
}
@@ -74,6 +80,7 @@ export async function fetchSocialProfile({
socialProfile.posts = BigInt(
data.data.user.edge_owner_to_timeline_media.count,
);
+ socialProfile.avatarUrl = data.data.user.profile_pic_url;
break;
}
@@ -82,6 +89,7 @@ export async function fetchSocialProfile({
socialProfile.platformId = data.user.id;
socialProfile.subscribers = BigInt(data.stats.followerCount);
socialProfile.posts = BigInt(data.stats.videoCount);
+ socialProfile.avatarUrl = data.user.avatarThumb;
break;
}
@@ -90,6 +98,7 @@ export async function fetchSocialProfile({
socialProfile.platformId = data.rest_id;
socialProfile.subscribers = BigInt(data.legacy.followers_count);
socialProfile.posts = BigInt(data.legacy.statuses_count);
+ socialProfile.avatarUrl = data.avatar.image_url;
break;
}
}
diff --git a/apps/web/lib/api/scrape-creators/schema.ts b/apps/web/lib/api/scrape-creators/schema.ts
index 3a1ff9378a..355d8f107f 100644
--- a/apps/web/lib/api/scrape-creators/schema.ts
+++ b/apps/web/lib/api/scrape-creators/schema.ts
@@ -1,38 +1,52 @@
import * as z from "zod/v4";
-export const profileResponseSchema = z.preprocess(
- (data: unknown) => {
+export const socialProfileSchema = z.preprocess(
+ (data: any) => {
if (typeof data === "object" && data !== null) {
// Check for "account doesn't exist" response
if (
"message" in data &&
- typeof (data as any).message === "string" &&
- ((data as any).message.toLowerCase().includes("doesn't exist") ||
- (data as any).message.toLowerCase().includes("does not exist") ||
- (data as any).message.toLowerCase().includes("not found"))
+ typeof data.message === "string" &&
+ (data.message.toLowerCase().includes("doesn't exist") ||
+ data.message.toLowerCase().includes("does not exist") ||
+ data.message.toLowerCase().includes("not found"))
) {
- return { platform: "account_not_found", ...data };
+ return {
+ ...data,
+ platform: "account_not_found",
+ };
}
+ // YouTube detection
if ("description" in data && "channelId" in data) {
- return { platform: "youtube", ...data };
+ return {
+ ...data,
+ platform: "youtube",
+ };
}
- if (
- "data" in data &&
- typeof (data as any).data === "object" &&
- (data as any).data?.user
- ) {
- return { platform: "instagram", ...data };
+ // Instagram detection
+ if ("data" in data && typeof data.data === "object" && data.data?.user) {
+ return {
+ ...data,
+ platform: "instagram",
+ };
}
+ // TikTok detection
if ("user" in data && "stats" in data) {
- return { platform: "tiktok", ...data };
+ return {
+ ...data,
+ platform: "tiktok",
+ };
}
// Twitter detection: check for rest_id and legacy fields (more reliable than is_blue_verified)
if ("rest_id" in data && "legacy" in data) {
- return { platform: "twitter", ...data };
+ return {
+ ...data,
+ platform: "twitter",
+ };
}
}
@@ -62,6 +76,17 @@ export const profileResponseSchema = z.preprocess(
.number()
.nullish()
.transform((val) => val ?? 0),
+ avatar: z.object({
+ image: z.object({
+ sources: z.array(
+ z.object({
+ url: z.url(),
+ width: z.number(),
+ height: z.number(),
+ }),
+ ),
+ }),
+ }),
}),
z.object({
@@ -81,6 +106,7 @@ export const profileResponseSchema = z.preprocess(
.nullish()
.transform((val) => val ?? 0),
}),
+ profile_pic_url: z.url().nullish().default(null),
}),
}),
}),
@@ -91,6 +117,7 @@ export const profileResponseSchema = z.preprocess(
id: z.string(),
signature: z.string(),
uniqueId: z.string(),
+ avatarThumb: z.url().nullish().default(null),
}),
stats: z.object({
followerCount: z
@@ -122,8 +149,167 @@ export const profileResponseSchema = z.preprocess(
.nullish()
.transform((val) => val ?? 0),
}),
+ avatar: z.object({
+ image_url: z.url().nullish().default(null),
+ }),
}),
]),
);
-export type ProfileResponse = z.infer<typeof profileResponseSchema>;
+export const socialContentSchema = z.preprocess(
+ (data: any) => {
+ if (typeof data === "object" && data !== null) {
+ // YouTube detection
+ if ("viewCountInt" in data && "likeCountInt" in data) {
+ return {
+ ...data,
+ platform: "youtube",
+ };
+ }
+
+ // Instagram detection
+ if ("data" in data && "xdt_shortcode_media" in data.data) {
+ return {
+ ...data.data.xdt_shortcode_media,
+ platform: "instagram",
+ };
+ }
+
+ // Twitter detection
+ if ("__typename" in data && data.__typename === "Tweet") {
+ return {
+ ...data,
+ platform: "twitter",
+ };
+ }
+
+ // TikTok detection
+ if ("aweme_detail" in data) {
+ return {
+ ...data.aweme_detail,
+ platform: "tiktok",
+ };
+ }
+ }
+
+ return data;
+ },
+ z.discriminatedUnion("platform", [
+ z.object({
+ platform: z.literal("youtube"),
+ publishDateText: z.string(),
+ channel: z.object({
+ id: z.string(),
+ handle: z.string(),
+ }),
+ viewCountInt: z
+ .number()
+ .nullable()
+ .transform((val) => val ?? 0),
+ likeCountInt: z
+ .number()
+ .nullable()
+ .transform((val) => val ?? 0),
+ title: z.string().nullish(),
+ description: z.string().nullish(),
+ thumbnailUrl: z.string().nullish(),
+ }),
+
+ z.object({
+ platform: z.literal("instagram"),
+ taken_at_timestamp: z.number(),
+ owner: z.object({
+ username: z.string(),
+ }),
+ video_view_count: z
+ .number()
+ .nullish()
+ .transform((val) => val ?? 0),
+ edge_media_preview_like: z.object({
+ count: z
+ .number()
+ .nullable()
+ .transform((val) => val ?? 0),
+ }),
+ edge_media_to_caption: z
+ .object({
+ edges: z.array(
+ z.object({
+ node: z.object({ text: z.string() }),
+ }),
+ ),
+ })
+ .optional(),
+ display_url: z.string().optional(),
+ thumbnail_src: z.string().optional(),
+ __typename: z.string().optional(),
+ edge_sidecar_to_children: z
+ .object({
+ edges: z.array(
+ z.object({
+ node: z.object({
+ display_url: z.string().optional(),
+ thumbnail_src: z.string().optional(),
+ }),
+ }),
+ ),
+ })
+ .optional(),
+ }),
+
+ z.object({
+ platform: z.literal("twitter"),
+ core: z.object({
+ user_results: z.object({
+ result: z.object({
+ core: z.object({
+ screen_name: z.string(),
+ }),
+ }),
+ }),
+ }),
+ views: z.object({
+ count: z
+ .string()
+ .nullable()
+ .transform((val) => (val == null ? 0 : Number(val))),
+ }),
+ legacy: z.object({
+ created_at: z.string(),
+ favorite_count: z
+ .number()
+ .nullable()
+ .transform((val) => val ?? 0),
+ full_text: z.string().optional(),
+ }),
+ }),
+
+ z.object({
+ platform: z.literal("tiktok"),
+ create_time_utc: z.string(),
+ author: z.object({
+ unique_id: z.string(),
+ }),
+ statistics: z.object({
+ play_count: z
+ .number()
+ .nullable()
+ .transform((val) => val ?? 0),
+ digg_count: z
+ .number()
+ .nullable()
+ .transform((val) => val ?? 0),
+ }),
+ desc: z.string().optional(),
+ video: z
+ .object({
+ cover: z
+ .object({
+ url_list: z.array(z.string()),
+ })
+ .optional(),
+ })
+ .optional(),
+ }),
+ ]),
+);
diff --git a/apps/web/lib/api/bounties/approve-bounty-submission.ts b/apps/web/lib/bounty/api/approve-bounty-submission.ts
similarity index 88%
rename from apps/web/lib/api/bounties/approve-bounty-submission.ts
rename to apps/web/lib/bounty/api/approve-bounty-submission.ts
index 2f74c72667..95198e1b73 100644
--- a/apps/web/lib/api/bounties/approve-bounty-submission.ts
+++ b/apps/web/lib/bounty/api/approve-bounty-submission.ts
@@ -1,4 +1,10 @@
+import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
+import { DubApiError } from "@/lib/api/errors";
import { Session } from "@/lib/auth";
+import {
+ calculateSocialMetricsRewardAmount,
+ resolveBountyDetails,
+} from "@/lib/bounty/utils";
import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
import {
approveBountySubmissionBodySchema,
@@ -9,8 +15,6 @@ 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> {
@@ -36,11 +40,13 @@ export async function approveBountySubmission({
partnerId: true,
bountyId: true,
status: true,
+ socialMetricCount: true,
bounty: {
select: {
name: true,
type: true,
rewardAmount: true,
+ submissionRequirements: true,
},
},
},
@@ -82,7 +88,18 @@ export async function approveBountySubmission({
}
const bounty = submission.bounty;
- const finalRewardAmount = bounty.rewardAmount ?? rewardAmount;
+ const bountyInfo = resolveBountyDetails(bounty);
+
+ let finalRewardAmount = bounty.rewardAmount ?? rewardAmount;
+
+ if (bountyInfo?.hasSocialMetrics) {
+ const socialRewardAmount = calculateSocialMetricsRewardAmount({
+ bounty,
+ submission,
+ });
+
+ finalRewardAmount = socialRewardAmount;
+ }
if (!finalRewardAmount) {
throw new DubApiError({
diff --git a/apps/web/lib/api/bounties/generate-performance-bounty-name.ts b/apps/web/lib/bounty/api/generate-performance-bounty-name.ts
similarity index 93%
rename from apps/web/lib/api/bounties/generate-performance-bounty-name.ts
rename to apps/web/lib/bounty/api/generate-performance-bounty-name.ts
index 9a420bd3f5..803770f6eb 100644
--- a/apps/web/lib/api/bounties/generate-performance-bounty-name.ts
+++ b/apps/web/lib/bounty/api/generate-performance-bounty-name.ts
@@ -1,6 +1,6 @@
+import { isCurrencyAttribute } from "@/lib/api/workflows/utils";
import { BountyPerformanceCondition } from "@/lib/types";
import { currencyFormatter, nFormatter } from "@dub/utils";
-import { isCurrencyAttribute } from "../workflows/utils";
import { PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES } from "./performance-bounty-scope-attributes";
export const generatePerformanceBountyName = ({
diff --git a/apps/web/lib/api/bounties/get-bounties-by-groups.ts b/apps/web/lib/bounty/api/get-bounties-by-groups.ts
similarity index 100%
rename from apps/web/lib/api/bounties/get-bounties-by-groups.ts
rename to apps/web/lib/bounty/api/get-bounties-by-groups.ts
diff --git a/apps/web/lib/api/bounties/get-bounty-or-throw.ts b/apps/web/lib/bounty/api/get-bounty-or-throw.ts
similarity index 94%
rename from apps/web/lib/api/bounties/get-bounty-or-throw.ts
rename to apps/web/lib/bounty/api/get-bounty-or-throw.ts
index de944cb09c..8a29175b14 100644
--- a/apps/web/lib/api/bounties/get-bounty-or-throw.ts
+++ b/apps/web/lib/bounty/api/get-bounty-or-throw.ts
@@ -1,6 +1,6 @@
+import { DubApiError } from "@/lib/api/errors";
import { prisma } from "@dub/prisma";
import { Prisma } from "@dub/prisma/client";
-import { DubApiError } from "../errors";
interface GetBountyOrThrowParams<T extends Prisma.BountyInclude = {}> {
programId: string;
diff --git a/apps/web/lib/api/bounties/get-bounty-with-details.ts b/apps/web/lib/bounty/api/get-bounty-with-details.ts
similarity index 84%
rename from apps/web/lib/api/bounties/get-bounty-with-details.ts
rename to apps/web/lib/bounty/api/get-bounty-with-details.ts
index f156b4f9ba..cfd5ee3729 100644
--- a/apps/web/lib/api/bounties/get-bounty-with-details.ts
+++ b/apps/web/lib/bounty/api/get-bounty-with-details.ts
@@ -1,5 +1,5 @@
+import { DubApiError } from "@/lib/api/errors";
import { prisma } from "@dub/prisma";
-import { DubApiError } from "../errors";
export const getBountyWithDetails = async ({
bountyId,
@@ -17,9 +17,12 @@ export const getBountyWithDetails = async ({
b.startsAt,
b.endsAt,
b.submissionsOpenAt,
+ b.submissionFrequency,
+ b.maxSubmissions,
b.rewardAmount,
b.rewardDescription,
b.submissionRequirements,
+ b.socialMetricsLastSyncedAt,
b.performanceScope,
wf.triggerConditions,
@@ -61,9 +64,12 @@ export const getBountyWithDetails = async ({
startsAt: bounty.startsAt,
endsAt: bounty.endsAt,
submissionsOpenAt: bounty.submissionsOpenAt,
+ submissionFrequency: bounty.submissionFrequency,
+ maxSubmissions: bounty.maxSubmissions,
rewardAmount: bounty.rewardAmount,
rewardDescription: bounty.rewardDescription,
submissionRequirements: bounty.submissionRequirements,
+ socialMetricsLastSyncedAt: bounty.socialMetricsLastSyncedAt ?? null,
performanceScope,
performanceCondition,
groups: bounty.groups.filter((group) => group !== null) ?? [],
diff --git a/apps/web/lib/bounty/api/get-social-metrics-updates.ts b/apps/web/lib/bounty/api/get-social-metrics-updates.ts
new file mode 100644
index 0000000000..dc8be280a2
--- /dev/null
+++ b/apps/web/lib/bounty/api/get-social-metrics-updates.ts
@@ -0,0 +1,95 @@
+import { getSocialContent } from "@/lib/api/scrape-creators/get-social-content";
+import { resolveBountyDetails } from "@/lib/bounty/utils";
+import { Bounty, BountySubmission } from "@dub/prisma/client";
+
+export type SocialMetricsUpdate = Pick<
+ BountySubmission,
+ "id" | "socialMetricCount" | "socialMetricsLastSyncedAt"
+>;
+
+const submissionWithUrl = (submission: { id: string; urls: unknown }) => {
+ const first =
+ Array.isArray(submission.urls) && submission.urls.length > 0
+ ? submission.urls[0]
+ : null;
+
+ const url =
+ typeof first === "string" && first.trim().length > 0 ? first.trim() : null;
+
+ return {
+ submissionId: submission.id,
+ url,
+ };
+};
+
+export async function getSocialMetricsUpdates({
+ bounty,
+ submissions,
+}: {
+ bounty: Pick<Bounty, "submissionRequirements">;
+ submissions: { id: string; urls: unknown } | { id: string; urls: unknown }[];
+}): Promise<SocialMetricsUpdate[]> {
+ const bountyInfo = resolveBountyDetails(bounty);
+ const socialPlatform = bountyInfo?.socialPlatform;
+ const socialMetrics = bountyInfo?.socialMetrics;
+
+ if (
+ !bountyInfo?.hasSocialMetrics ||
+ !socialPlatform?.value ||
+ !socialMetrics
+ ) {
+ return [];
+ }
+
+ const list = Array.isArray(submissions) ? submissions : [submissions];
+ const toProcess = list.map(submissionWithUrl).filter((s) => s.url !== null);
+
+ if (toProcess.length === 0) {
+ return [];
+ }
+
+ const results = await Promise.allSettled(
+ toProcess.map((s) =>
+ getSocialContent({
+ platform: socialPlatform.value,
+ url: s.url!,
+ }),
+ ),
+ );
+
+ const submissionById = new Map(list.map((s) => [s.id, s]));
+ const updates: SocialMetricsUpdate[] = [];
+
+ for (let i = 0; i < results.length; i++) {
+ const result = results[i];
+
+ if (result.status !== "fulfilled") {
+ continue;
+ }
+
+ const submission = submissionById.get(toProcess[i].submissionId);
+
+ if (!submission) {
+ continue;
+ }
+
+ const socialContent = result.value;
+ const socialMetricCount = socialContent[socialMetrics.metric];
+
+ if (
+ socialMetricCount === null ||
+ socialMetricCount === undefined ||
+ !Number.isInteger(socialMetricCount)
+ ) {
+ continue;
+ }
+
+ updates.push({
+ id: submission.id,
+ socialMetricCount,
+ socialMetricsLastSyncedAt: new Date(),
+ });
+ }
+
+ return updates;
+}
diff --git a/apps/web/lib/api/bounties/performance-bounty-scope-attributes.ts b/apps/web/lib/bounty/api/performance-bounty-scope-attributes.ts
similarity index 100%
rename from apps/web/lib/api/bounties/performance-bounty-scope-attributes.ts
rename to apps/web/lib/bounty/api/performance-bounty-scope-attributes.ts
diff --git a/apps/web/lib/api/bounties/reject-bounty-submission.ts b/apps/web/lib/bounty/api/reject-bounty-submission.ts
similarity index 95%
rename from apps/web/lib/api/bounties/reject-bounty-submission.ts
rename to apps/web/lib/bounty/api/reject-bounty-submission.ts
index 916b5d071c..b1f34f6c50 100644
--- a/apps/web/lib/api/bounties/reject-bounty-submission.ts
+++ b/apps/web/lib/bounty/api/reject-bounty-submission.ts
@@ -1,5 +1,7 @@
+import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
+import { DubApiError } from "@/lib/api/errors";
import { Session } from "@/lib/auth";
-import { REJECT_BOUNTY_SUBMISSION_REASONS } from "@/lib/constants/bounties";
+import { REJECT_BOUNTY_SUBMISSION_REASONS } from "@/lib/bounty/constants";
import {
BountySubmissionSchema,
rejectBountySubmissionBodySchema,
@@ -9,8 +11,6 @@ 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> {
diff --git a/apps/web/lib/api/bounties/trigger-draft-bounty-submissions.ts b/apps/web/lib/bounty/api/trigger-draft-bounty-submissions.ts
similarity index 100%
rename from apps/web/lib/api/bounties/trigger-draft-bounty-submissions.ts
rename to apps/web/lib/bounty/api/trigger-draft-bounty-submissions.ts
diff --git a/apps/web/lib/api/bounties/validate-bounty.ts b/apps/web/lib/bounty/api/validate-bounty.ts
similarity index 77%
rename from apps/web/lib/api/bounties/validate-bounty.ts
rename to apps/web/lib/bounty/api/validate-bounty.ts
index 217fd4c892..ecea4ee8a2 100644
--- a/apps/web/lib/api/bounties/validate-bounty.ts
+++ b/apps/web/lib/bounty/api/validate-bounty.ts
@@ -1,16 +1,17 @@
-import { createBountySchema } from "@/lib/zod/schemas/bounties";
-import * as z from "zod/v4";
-import { DubApiError } from "../errors";
+import { DubApiError } from "@/lib/api/errors";
+import { CreateBountyInput } from "@/lib/types";
export function validateBounty({
type,
startsAt,
endsAt,
submissionsOpenAt,
+ submissionFrequency,
+ maxSubmissions,
rewardAmount,
rewardDescription,
performanceScope,
-}: Partial<z.infer<typeof createBountySchema>>) {
+}: Partial<CreateBountyInput>) {
startsAt = startsAt || new Date();
if (endsAt && endsAt < startsAt) {
@@ -53,7 +54,9 @@ export function validateBounty({
code: "bad_request",
message: "Reward amount is required for performance bounties.",
});
- } else if (!rewardDescription) {
+ }
+
+ if (!rewardDescription) {
throw new DubApiError({
code: "bad_request",
message:
@@ -62,17 +65,20 @@ export function validateBounty({
}
}
- if (rewardAmount && rewardAmount < 0) {
- throw new DubApiError({
- code: "bad_request",
- message: "Reward amount cannot be negative.",
- });
- }
-
if (!performanceScope && type === "performance") {
throw new DubApiError({
code: "bad_request",
message: "performanceScope must be set for performance bounties.",
});
}
+
+ // submission bounty checks
+ if (type === "submission") {
+ if (submissionFrequency && maxSubmissions == null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "maxSubmissions is required when submissionFrequency is set.",
+ });
+ }
+ }
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submission-status-badges.ts b/apps/web/lib/bounty/bounty-submission-status-badges.ts
similarity index 100%
rename from apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submission-status-badges.ts
rename to apps/web/lib/bounty/bounty-submission-status-badges.ts
diff --git a/apps/web/lib/bounty/constants.ts b/apps/web/lib/bounty/constants.ts
new file mode 100644
index 0000000000..29b778414f
--- /dev/null
+++ b/apps/web/lib/bounty/constants.ts
@@ -0,0 +1,70 @@
+export const BOUNTY_DESCRIPTION_MAX_LENGTH = 5000;
+
+export const BOUNTY_MAX_SUBMISSION_FILES = 4;
+
+export const BOUNTY_DEFAULT_SUBMISSION_URLS = 10;
+
+export const BOUNTY_MAX_SUBMISSION_URLS = 100;
+
+export const BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH = 1000;
+
+export const BOUNTY_MAX_SUBMISSION_REJECTION_NOTE_LENGTH = 5000;
+
+export const BOUNTY_SUBMISSION_REQUIREMENTS = ["image", "url"] as const;
+
+export const REJECT_BOUNTY_SUBMISSION_REASONS = {
+ invalidProof: "Invalid proof",
+ duplicateSubmission: "Duplicate submission",
+ outOfTimeWindow: "Out of time window",
+ didNotMeetCriteria: "Did not meet criteria",
+ other: "Other",
+} as const;
+
+export const BOUNTY_SOCIAL_PLATFORMS = [
+ {
+ value: "youtube",
+ label: "YouTube",
+ postType: "video",
+ metrics: ["views", "likes"],
+ placeholder: "https://www.youtube.com/watch?v=",
+ },
+ {
+ value: "tiktok",
+ label: "TikTok",
+ postType: "video",
+ metrics: ["views", "likes"],
+ placeholder: "https://www.tiktok.com/@username/video/",
+ },
+ {
+ value: "instagram",
+ label: "Instagram",
+ postType: "photo",
+ metrics: ["likes", "views"],
+ placeholder: "https://www.instagram.com/username/reel/",
+ },
+ {
+ value: "twitter",
+ label: "X/Twitter",
+ postType: "tweet",
+ metrics: ["likes", "views"],
+ placeholder: "https://x.com/username/status/",
+ },
+] as const;
+
+export const BOUNTY_SOCIAL_PLATFORM_VALUES = BOUNTY_SOCIAL_PLATFORMS.map(
+ (p) => p.value,
+);
+
+export const BOUNTY_SOCIAL_PLATFORM_METRICS = BOUNTY_SOCIAL_PLATFORMS.map(
+ (p) => p.metrics,
+).flat();
+
+export const BOUNTY_SOCIAL_PLATFORM_METRICS_MAP = Object.fromEntries(
+ BOUNTY_SOCIAL_PLATFORMS.map((p) => [
+ p.value,
+ p.metrics.map((m) => ({
+ value: m,
+ label: m,
+ })),
+ ]),
+);
diff --git a/apps/web/lib/partners/get-bounty-reward-description.ts b/apps/web/lib/bounty/get-bounty-reward-description.ts
similarity index 100%
rename from apps/web/lib/partners/get-bounty-reward-description.ts
rename to apps/web/lib/bounty/get-bounty-reward-description.ts
diff --git a/apps/web/lib/bounty/utils.ts b/apps/web/lib/bounty/utils.ts
new file mode 100644
index 0000000000..120bc6e0fc
--- /dev/null
+++ b/apps/web/lib/bounty/utils.ts
@@ -0,0 +1,329 @@
+import {
+ BountySubmissionFrequency,
+ PlatformType,
+ Prisma,
+} from "@dub/prisma/client";
+import { currencyFormatter, isValidUrl, nFormatter } from "@dub/utils";
+import { addDays, addMonths, addWeeks } from "date-fns";
+import {
+ BountySocialPlatform,
+ BountySubmissionProps,
+ PartnerBountyProps,
+} from "../types";
+import { bountySocialContentRequirementsSchema } from "../zod/schemas/bounties";
+import { BOUNTY_SOCIAL_PLATFORMS } from "./constants";
+
+export function getNextBountySubmissionEligibleAt({
+ submissionFrequency,
+ lastSubmissionAt,
+}: {
+ submissionFrequency: BountySubmissionFrequency;
+ lastSubmissionAt: Date;
+}): Date {
+ switch (submissionFrequency) {
+ case "day":
+ return addDays(lastSubmissionAt, 1);
+ case "week":
+ return addWeeks(lastSubmissionAt, 1);
+ case "month":
+ return addMonths(lastSubmissionAt, 1);
+ default:
+ throw new Error("Invalid submission frequency");
+ }
+}
+
+const SOCIAL_URL_HOST_TO_PLATFORM: Record<string, PlatformType> = {
+ "youtube.com": "youtube",
+ "m.youtube.com": "youtube",
+ "youtu.be": "youtube",
+ "tiktok.com": "tiktok",
+ "m.tiktok.com": "tiktok",
+ "vm.tiktok.com": "tiktok",
+ "instagram.com": "instagram",
+ "m.instagram.com": "instagram",
+ "twitter.com": "twitter",
+ "x.com": "twitter",
+};
+
+export function getPlatformFromSocialUrl(url: string): PlatformType | null {
+ const trimmed = url?.trim();
+
+ if (!trimmed || !isValidUrl(trimmed)) {
+ return null;
+ }
+
+ try {
+ const parsed = new URL(trimmed);
+ const host = parsed.hostname.replace(/^www\./, "");
+
+ return SOCIAL_URL_HOST_TO_PLATFORM[host] ?? null;
+ } catch {
+ return null;
+ }
+}
+
+export function getSocialContentEmbedUrl({
+ platform,
+ url,
+}: {
+ platform: BountySocialPlatform;
+ url: string;
+}) {
+ try {
+ const parsed = new URL(url);
+ const host = parsed.hostname.replace(/^www\./, "");
+
+ if (platform === "youtube") {
+ if (host === "youtu.be") {
+ const id = parsed.pathname.slice(1).split("?")[0];
+ return id ? `https://www.youtube.com/embed/${id}` : null;
+ }
+
+ if (host === "youtube.com" || host === "m.youtube.com") {
+ const v = parsed.searchParams.get("v");
+
+ if (v) {
+ return `https://www.youtube.com/embed/${v}`;
+ }
+
+ const shortsMatch = parsed.pathname.match(/\/shorts\/([^/?#]+)/);
+
+ if (shortsMatch?.[1]) {
+ return `https://www.youtube.com/embed/${shortsMatch[1]}`;
+ }
+
+ return null;
+ }
+ }
+
+ if (platform === "instagram") {
+ if (host === "instagram.com" || host === "m.instagram.com") {
+ const pathMatch =
+ parsed.pathname.match(/\/p\/([^/]+)/) ??
+ parsed.pathname.match(/\/reel\/([^/]+)/);
+ const shortcode = pathMatch?.[1];
+
+ if (!shortcode) {
+ return null;
+ }
+
+ const isReel = parsed.pathname.includes("/reel/");
+
+ return isReel
+ ? `https://www.instagram.com/reel/${shortcode}/embed/`
+ : `https://www.instagram.com/p/${shortcode}/embed/`;
+ }
+ }
+
+ if (platform === "tiktok") {
+ if (
+ host === "tiktok.com" ||
+ host === "m.tiktok.com" ||
+ host === "vm.tiktok.com"
+ ) {
+ const match = parsed.pathname.match(/\/video\/(\d+)/);
+ const videoId = match?.[1];
+
+ return videoId ? `https://www.tiktok.com/embed/v2/${videoId}` : null;
+ }
+ }
+
+ if (platform === "twitter") {
+ if (host === "twitter.com" || host === "x.com") {
+ const statusMatch = parsed.pathname.match(/\/status\/(\d+)/);
+ const tweetId = statusMatch?.[1];
+ return tweetId
+ ? `https://platform.twitter.com/embed/Tweet.html?id=${tweetId}`
+ : null;
+ }
+ }
+
+ return null;
+ } catch {
+ return null;
+ }
+}
+
+export function getBountySubmissionRequirementTexts(
+ bounty: PartnerBountyProps,
+): string[] {
+ const bountyInfo = resolveBountyDetails(bounty);
+
+ if (!bountyInfo?.hasSocialMetrics || !bountyInfo.socialPlatform) {
+ return [];
+ }
+
+ return [
+ `Submit a ${bountyInfo.socialPlatform.label} link from your connected account`,
+ "The content shared is posted after this bounty started",
+ ];
+}
+
+export function getBountyRewardCriteriaTexts(
+ bounty: PartnerBountyProps | Parameters<typeof resolveBountyDetails>[0],
+): string[] {
+ const bountyInfo = resolveBountyDetails(bounty);
+
+ if (
+ !bountyInfo?.socialMetrics ||
+ !bountyInfo.socialPlatform ||
+ !bountyInfo.rewardAmount
+ ) {
+ return [];
+ }
+
+ const formattedAmount = currencyFormatter(bountyInfo.rewardAmount, {
+ trailingZeroDisplay: "stripIfInteger",
+ });
+
+ const socialPlatform = bountyInfo.socialPlatform;
+ const { minCount, metric, incrementalBonus } = bountyInfo.socialMetrics;
+
+ const texts: string[] = [
+ `Get ${nFormatter(minCount ?? 0, { full: true })} ${metric} on your ${socialPlatform.label} content, earn ${formattedAmount}`,
+ ];
+
+ if (incrementalBonus) {
+ const { incrementCount, bonusPerIncrement, maxCount } = incrementalBonus;
+
+ if (incrementCount && bonusPerIncrement && maxCount) {
+ const formattedBonus = currencyFormatter(bonusPerIncrement, {
+ trailingZeroDisplay: "stripIfInteger",
+ });
+
+ texts.push(
+ `For each additional ${nFormatter(incrementCount, { full: true })} ${metric} on your ${socialPlatform.label} content, earn ${formattedBonus} – up to ${nFormatter(maxCount, { full: true })} ${metric}`,
+ );
+ }
+ }
+
+ return texts;
+}
+
+interface BountyInfoInput {
+ submissionRequirements: Prisma.JsonValue;
+ rewardAmount?: number | undefined | null;
+}
+
+export function resolveBountyDetails(
+ bounty: BountyInfoInput | undefined | null,
+) {
+ if (!bounty) {
+ return null;
+ }
+
+ // Social metrics requirements
+ const submissionRequirements = bounty.submissionRequirements as {
+ socialMetrics?: unknown | Prisma.JsonValue | undefined | null;
+ };
+
+ const parsedSocialMetrics = bountySocialContentRequirementsSchema
+ .optional()
+ .safeParse(submissionRequirements?.socialMetrics);
+
+ const socialMetrics = parsedSocialMetrics.success
+ ? parsedSocialMetrics.data
+ : null;
+
+ // Identify the social platform
+ const socialPlatform = BOUNTY_SOCIAL_PLATFORMS.find(
+ ({ value }) => value === socialMetrics?.platform,
+ );
+
+ return {
+ ...bounty,
+ socialPlatform,
+ socialMetrics,
+ hasSocialMetrics: socialMetrics != null,
+ };
+}
+
+export interface SocialMetricsRewardTier {
+ threshold: number;
+ rewardAmount: number;
+ status: "met" | "unmet";
+}
+
+export function getSocialMetricsRewardTiers({
+ bounty,
+ submission,
+}: {
+ bounty: BountyInfoInput | undefined | null;
+ submission: Pick<BountySubmissionProps, "socialMetricCount">;
+}): SocialMetricsRewardTier[] {
+ const bountyInfo = resolveBountyDetails(bounty);
+ const socialMetrics = bountyInfo?.socialMetrics;
+ const rewardAmount = bounty?.rewardAmount ?? 0;
+ const socialMetricCount = submission.socialMetricCount ?? 0;
+
+ if (!socialMetrics?.metric || !socialMetrics.minCount || rewardAmount <= 0) {
+ return [];
+ }
+
+ const { minCount, incrementalBonus } = socialMetrics;
+
+ // Base tier
+ const tiers: SocialMetricsRewardTier[] = [
+ {
+ threshold: minCount,
+ rewardAmount,
+ status: socialMetricCount >= minCount ? "met" : "unmet",
+ },
+ ];
+
+ if (tiers[0].status === "unmet") {
+ return tiers;
+ }
+
+ // Incremental bonus tiers
+ if (incrementalBonus) {
+ const { incrementCount, bonusPerIncrement, maxCount } = incrementalBonus;
+
+ const hasValidIncrementalBonus =
+ incrementCount != null &&
+ bonusPerIncrement != null &&
+ maxCount != null &&
+ incrementCount > 0;
+
+ if (hasValidIncrementalBonus) {
+ for (
+ let t = minCount + incrementCount;
+ t <= maxCount;
+ t += incrementCount
+ ) {
+ const status = socialMetricCount >= t ? "met" : "unmet";
+
+ tiers.push({
+ threshold: t,
+ rewardAmount: bonusPerIncrement,
+ status,
+ });
+
+ // Stop after first unmet
+ if (status === "unmet") {
+ break;
+ }
+ }
+ }
+ }
+
+ return tiers;
+}
+
+export function calculateSocialMetricsRewardAmount({
+ bounty,
+ submission,
+}: {
+ bounty: BountyInfoInput | undefined | null;
+ submission: Pick<BountySubmissionProps, "socialMetricCount">;
+}) {
+ const tiers = getSocialMetricsRewardTiers({ bounty, submission });
+
+ if (tiers.length === 0 || submission.socialMetricCount == null) {
+ return null;
+ }
+
+ return tiers
+ .filter((tier) => tier.status === "met")
+ .reduce((sum, tier) => sum + tier.rewardAmount, 0);
+}
diff --git a/apps/web/lib/constants/bounties.ts b/apps/web/lib/constants/bounties.ts
deleted file mode 100644
index 4b4c6dc7ab..0000000000
--- a/apps/web/lib/constants/bounties.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-export const BOUNTY_DESCRIPTION_MAX_LENGTH = 5000;
-
-export const BOUNTY_MAX_SUBMISSION_FILES = 4;
-
-export const BOUNTY_DEFAULT_SUBMISSION_URLS = 10;
-export const BOUNTY_MAX_SUBMISSION_URLS = 100;
-
-export const BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH = 1000;
-
-export const BOUNTY_MAX_SUBMISSION_REJECTION_NOTE_LENGTH = 5000;
-
-export const BOUNTY_SUBMISSION_REQUIREMENTS = ["image", "url"] as const;
-
-export const REJECT_BOUNTY_SUBMISSION_REASONS = {
- invalidProof: "Invalid proof",
- duplicateSubmission: "Duplicate submission",
- outOfTimeWindow: "Out of time window",
- didNotMeetCriteria: "Did not meet criteria",
- other: "Other",
-} as const;
diff --git a/apps/web/lib/cron/enqueue-batch-jobs.ts b/apps/web/lib/cron/enqueue-batch-jobs.ts
index a765e7d057..6bb58e50f6 100644
--- a/apps/web/lib/cron/enqueue-batch-jobs.ts
+++ b/apps/web/lib/cron/enqueue-batch-jobs.ts
@@ -3,7 +3,11 @@ import type { PublishBatchRequest } from "@upstash/qstash";
import { qstash } from ".";
type EnqueueBatchJobsProps = PublishBatchRequest<unknown> & {
- queueName: "ban-partner" | "send-partner-summary" | "create-discount-code";
+ queueName:
+ | "ban-partner"
+ | "send-partner-summary"
+ | "create-discount-code"
+ | "sync-bounty-social-metrics";
};
// Generic helper to enqueue a batch of QStash jobs.
diff --git a/apps/web/lib/integrations/slack/transform.ts b/apps/web/lib/integrations/slack/transform.ts
index 08af89c55d..24de8d2138 100644
--- a/apps/web/lib/integrations/slack/transform.ts
+++ b/apps/web/lib/integrations/slack/transform.ts
@@ -1,5 +1,5 @@
import { isFirstConversion } from "@/lib/analytics/is-first-conversion";
-import { getBountyRewardDescription } from "@/lib/partners/get-bounty-reward-description";
+import { getBountyRewardDescription } from "@/lib/bounty/get-bounty-reward-description";
import { APP_DOMAIN, COUNTRIES, currencyFormatter, truncate } from "@dub/utils";
import { LinkWebhookEvent } from "dub/models/components";
import * as z from "zod/v4";
diff --git a/apps/web/lib/plan-capabilities.ts b/apps/web/lib/plan-capabilities.ts
index 1044ec1ba1..96d6b9922f 100644
--- a/apps/web/lib/plan-capabilities.ts
+++ b/apps/web/lib/plan-capabilities.ts
@@ -19,5 +19,7 @@ export const getPlanCapabilities = (
canDiscoverPartners: !!plan && ["enterprise", "advanced"].includes(plan),
canManageFraudEvents: !!plan && ["enterprise", "advanced"].includes(plan),
canUseGroupMoveRule: !!plan && ["enterprise", "advanced"].includes(plan),
+ canUseBountySocialMetrics:
+ !!plan && ["enterprise", "advanced"].includes(plan),
};
};
diff --git a/apps/web/lib/social-utils.ts b/apps/web/lib/social-utils.ts
index 6862ff4cc4..4a04788f18 100644
--- a/apps/web/lib/social-utils.ts
+++ b/apps/web/lib/social-utils.ts
@@ -27,7 +27,7 @@ export const SOCIAL_PLATFORM_CONFIGS: Record<
],
allowedChars: /[^\w]/g,
maxLength: 15,
- name: "Twitter",
+ name: "X/Twitter",
},
linkedin: {
patterns: [/^(?:.*\.)?linkedin\.com\/(?:in\/)?([^\/\?]+)/i],
diff --git a/apps/web/lib/swr/use-partner-profile.ts b/apps/web/lib/swr/use-partner-profile.ts
index c3e9aa53be..96c4511c4d 100644
--- a/apps/web/lib/swr/use-partner-profile.ts
+++ b/apps/web/lib/swr/use-partner-profile.ts
@@ -29,8 +29,15 @@ export default function usePartnerProfile() {
},
);
+ const platformsVerified = partner?.platforms?.length
+ ? Object.fromEntries(
+ partner.platforms.map((p) => [p.type, p.verifiedAt != null]),
+ )
+ : undefined;
+
return {
partner,
+ platformsVerified,
payoutMethod: partner?.country
? PAYPAL_SUPPORTED_COUNTRIES.includes(partner.country)
? "paypal"
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 31f1f08afc..cd9f26f094 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -30,7 +30,10 @@ import {
import * as z from "zod/v4";
import { RESOURCE_COLORS } from "../ui/colors";
import { PAID_TRAFFIC_PLATFORMS } from "./api/fraud/constants";
-import { BOUNTY_SUBMISSION_REQUIREMENTS } from "./constants/bounties";
+import {
+ BOUNTY_SOCIAL_PLATFORMS,
+ BOUNTY_SUBMISSION_REQUIREMENTS,
+} from "./bounty/constants";
import {
FOLDER_PERMISSIONS,
FOLDER_WORKSPACE_ACCESS,
@@ -49,8 +52,12 @@ import {
BountyListSchema,
bountyPerformanceConditionSchema,
BountySchema,
+ bountySocialContentIncrementalBonusSchema,
BountySubmissionExtendedSchema,
+ createBountySchema,
getBountySubmissionsQuerySchema,
+ socialContentOutputSchema,
+ submissionRequirementsSchema,
} from "./zod/schemas/bounties";
import {
CampaignListSchema,
@@ -662,12 +669,19 @@ export type BountySubmissionProps = z.infer<
export type BountySubmissionRequirement =
(typeof BOUNTY_SUBMISSION_REQUIREMENTS)[number];
+export type SocialMetricsChannel =
+ (typeof BOUNTY_SOCIAL_PLATFORMS)[number]["value"];
+
export type WorkflowCondition = z.infer<typeof workflowConditionSchema>;
export type BountyPerformanceCondition = z.infer<
typeof bountyPerformanceConditionSchema
>;
+export type BountySocialMetricsIncrementalBonus = z.infer<
+ typeof bountySocialContentIncrementalBonusSchema
+>;
+
export type CampaignTriggerCondition = z.infer<
typeof campaignTriggerConditionSchema
>;
@@ -830,6 +844,19 @@ export type ChangeSet = Record<string, FieldDiff>;
export type ActivityLog = z.infer<typeof activityLogSchema>;
+export type CreateBountyInput = z.infer<typeof createBountySchema>;
+
+export type SocialContent = z.infer<typeof socialContentOutputSchema>;
+
+export type SubmissionRequirements = z.infer<
+ typeof submissionRequirementsSchema
+>;
+
+export type BountySocialPlatform =
+ (typeof BOUNTY_SOCIAL_PLATFORMS)[number]["value"];
+
+export type BountySocialPlatformMetric =
+ (typeof BOUNTY_SOCIAL_PLATFORMS)[number]["metrics"][number];
export type PostbackProps = z.infer<typeof postbackSchema>;
export type PostbackEventProps = z.infer<typeof postbackEventInputSchemaTB>;
diff --git a/apps/web/lib/zod/schemas/bounties.ts b/apps/web/lib/zod/schemas/bounties.ts
index ac5c86a11e..cc4c3c63ec 100644
--- a/apps/web/lib/zod/schemas/bounties.ts
+++ b/apps/web/lib/zod/schemas/bounties.ts
@@ -1,9 +1,15 @@
import {
BOUNTY_DESCRIPTION_MAX_LENGTH,
+ BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH,
+ BOUNTY_MAX_SUBMISSION_FILES,
BOUNTY_MAX_SUBMISSION_REJECTION_NOTE_LENGTH,
-} from "@/lib/constants/bounties";
+ BOUNTY_MAX_SUBMISSION_URLS,
+ BOUNTY_SOCIAL_PLATFORM_METRICS,
+ BOUNTY_SOCIAL_PLATFORM_VALUES,
+} from "@/lib/bounty/constants";
import {
BountyPerformanceScope,
+ BountySubmissionFrequency,
BountySubmissionRejectionReason,
BountySubmissionStatus,
BountyType,
@@ -23,7 +29,44 @@ export const bountyPerformanceConditionSchema = z.object({
value: z.number(),
});
-// Object format with image and url keys
+// Eg: for each additional 1000 views, earn $1, up to $100
+export const bountySocialContentIncrementalBonusSchema = z
+ .object({
+ incrementCount: z.number().int().positive().optional(),
+ bonusPerIncrement: z.number().min(0).optional(),
+ maxCount: z.number().int().positive().optional(),
+ })
+ .refine(
+ ({ incrementCount, maxCount }) => {
+ if (
+ incrementCount != null &&
+ maxCount != null &&
+ !Number.isNaN(incrementCount) &&
+ !Number.isNaN(maxCount)
+ ) {
+ return maxCount >= incrementCount;
+ }
+
+ return true;
+ },
+ {
+ message: "Cap must be at least the increment count",
+ path: ["maxCount"],
+ },
+ );
+
+export const bountySocialContentRequirementsSchema = z.object({
+ platform: z.enum(BOUNTY_SOCIAL_PLATFORM_VALUES),
+ metric: z.enum(BOUNTY_SOCIAL_PLATFORM_METRICS),
+ minCount: z
+ .number()
+ .int()
+ .positive()
+ .optional()
+ .describe("Minimum metric required for eligibility"),
+ incrementalBonus: bountySocialContentIncrementalBonusSchema.optional(),
+});
+
export const submissionRequirementsSchema = z.object({
image: z
.object({
@@ -36,13 +79,9 @@ export const submissionRequirementsSchema = z.object({
domains: z.array(z.string()).optional(),
})
.optional(),
+ socialMetrics: bountySocialContentRequirementsSchema.optional(),
});
-// Type exports for TypeScript
-export type SubmissionRequirements = z.infer<
- typeof submissionRequirementsSchema
->;
-
export const createBountySchema = z.object({
name: z
.string()
@@ -61,8 +100,16 @@ export const createBountySchema = z.object({
startsAt: parseDateSchema.nullish(),
endsAt: parseDateSchema.nullish(),
submissionsOpenAt: parseDateSchema.nullish(),
+ submissionFrequency: z.enum(BountySubmissionFrequency).nullish(),
+ maxSubmissions: z
+ .number()
+ .int()
+ .min(2, "Total submissions allowed must be at least 2")
+ .max(10)
+ .nullish(),
rewardAmount: z
.number()
+ .positive()
.min(1, "Reward amount must be greater than 1")
.nullable(),
rewardDescription: z
@@ -101,6 +148,8 @@ export const BountySchema = z.object({
startsAt: z.date(),
endsAt: z.date().nullable(),
submissionsOpenAt: z.date().nullable(),
+ // submissionFrequency: z.enum(BountySubmissionFrequency).nullable(),
+ // maxSubmissions: z.number().nullable(),
rewardAmount: z.number().nullable(),
rewardDescription: z.string().nullable(),
performanceCondition: bountyPerformanceConditionSchema
@@ -108,6 +157,7 @@ export const BountySchema = z.object({
.default(null),
performanceScope: z.enum(BountyPerformanceScope).nullable(),
submissionRequirements: submissionRequirementsSchema.nullable().default(null),
+ socialMetricsLastSyncedAt: z.date().nullable().optional(),
groups: z.array(GroupSchema.pick({ id: true })),
});
@@ -151,6 +201,14 @@ export const BountySubmissionSchema = z.object({
.number()
.nullable()
.meta({ description: "The performance count of the submission" }),
+ socialMetricCount: z.number().int().nullable().meta({
+ description:
+ "The social metric count (views or likes) for the social content",
+ }),
+ socialMetricsLastSyncedAt: z.date().nullable().optional().meta({
+ description:
+ "The date and time the submission's social metrics were last synced",
+ }),
createdAt: z
.date()
.meta({ description: "The date and time the submission was created" }),
@@ -232,7 +290,7 @@ export const getBountySubmissionsQuerySchema = z
description: "The ID of the partner to list submissions for.",
}),
sortBy: z
- .enum(["completedAt", "performanceCount"])
+ .enum(["completedAt", "performanceCount", "socialMetricCount"])
.default("completedAt")
.meta({
description: "The field to sort the submissions by.",
@@ -242,3 +300,35 @@ export const getBountySubmissionsQuerySchema = z
}),
})
.extend(getPaginationQuerySchema({ pageSize: 100 }));
+
+export const socialContentOutputSchema = z.object({
+ likes: z.number(),
+ views: z.number(),
+ handle: z.string().nullable(),
+ platformId: z.string().nullable(),
+ publishedAt: z.date().nullable(),
+ title: z.string().nullable().optional(),
+ description: z.string().nullable().optional(),
+ thumbnailUrl: z.string().nullable().optional(),
+ mediaType: z.enum(["image", "video", "carousel"]).optional(),
+ thumbnailUrls: z.array(z.string()).optional(),
+});
+
+export const createBountySubmissionInputSchema = z.object({
+ programId: z.string(),
+ bountyId: z.string(),
+ files: z
+ .array(BountySubmissionFileSchema)
+ .max(BOUNTY_MAX_SUBMISSION_FILES)
+ .default([]),
+ urls: z.array(z.url()).max(BOUNTY_MAX_SUBMISSION_URLS).default([]),
+ description: z
+ .string()
+ .trim()
+ .max(BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH)
+ .optional(),
+ isDraft: z
+ .boolean()
+ .default(false)
+ .describe("Whether to create a draft submission or a final submission."),
+});
diff --git a/apps/web/lib/zod/schemas/partner-profile.ts b/apps/web/lib/zod/schemas/partner-profile.ts
index 802c465314..7d8ca9f038 100644
--- a/apps/web/lib/zod/schemas/partner-profile.ts
+++ b/apps/web/lib/zod/schemas/partner-profile.ts
@@ -148,7 +148,16 @@ export const partnerNotificationTypes = z.enum([
export const PartnerBountySchema = BountySchema.omit({
groups: true,
}).extend({
- submission: BountySubmissionSchema.nullable(),
+ submission: BountySubmissionSchema.extend({
+ commission: PartnerEarningsSchema.pick({
+ id: true,
+ earnings: true,
+ status: true,
+ createdAt: true,
+ })
+ .nullable()
+ .default(null),
+ }).nullable(),
performanceCondition: bountyPerformanceConditionSchema
.nullable()
.default(null),
diff --git a/apps/web/lib/zod/schemas/partners.ts b/apps/web/lib/zod/schemas/partners.ts
index e9f84cafba..82ac0027ab 100644
--- a/apps/web/lib/zod/schemas/partners.ts
+++ b/apps/web/lib/zod/schemas/partners.ts
@@ -72,7 +72,7 @@ export const exportPartnerColumns = [
{ id: "netRevenue", label: "Net Revenue", default: false, numeric: true },
{ id: "website", label: "Website", default: false },
{ id: "youtube", label: "YouTube", default: false },
- { id: "twitter", label: "Twitter", default: false },
+ { id: "twitter", label: "X/Twitter", default: false },
{ id: "linkedin", label: "LinkedIn", default: false },
{ id: "instagram", label: "Instagram", default: false },
{ id: "tiktok", label: "TikTok", default: false },
@@ -100,7 +100,7 @@ export const exportApplicationColumns = [
{ id: "description", label: "Description" },
{ id: "website", label: "Website" },
{ id: "youtube", label: "YouTube" },
- { id: "twitter", label: "Twitter" },
+ { id: "twitter", label: "X/Twitter" },
{ id: "linkedin", label: "LinkedIn" },
{ id: "instagram", label: "Instagram" },
{ id: "tiktok", label: "TikTok" },
@@ -213,6 +213,7 @@ export const partnerPlatformSchema = z.object({
identifier: z.string(),
verifiedAt: z.date().nullable(),
platformId: z.string().nullable(),
+ avatarUrl: z.string().nullish(),
subscribers: z.bigint().default(BigInt(0)),
posts: z.bigint().default(BigInt(0)),
views: z.bigint().default(BigInt(0)),
diff --git a/apps/web/tests/workflows/utils/verify-bounty-submission.ts b/apps/web/tests/workflows/utils/verify-bounty-submission.ts
index ec3fa5f495..4812f4d05c 100644
--- a/apps/web/tests/workflows/utils/verify-bounty-submission.ts
+++ b/apps/web/tests/workflows/utils/verify-bounty-submission.ts
@@ -62,6 +62,6 @@ export const verifyBountySubmission = async ({
throw new Error(
`Bounty submission did not reach status "${expectedStatus}" within ${TIMEOUT_MS / 1000} seconds. ` +
- `bountyId: ${bountyId}, partnerId: ${partnerId}. ${lastState}`,
+ `bountyId: ${bountyId}, partnerId: ${partnerId}. ${lastState}`,
);
};
diff --git a/apps/web/ui/layout/auth-layout.tsx b/apps/web/ui/layout/auth-layout.tsx
index 529c891fae..40a2bbe840 100644
--- a/apps/web/ui/layout/auth-layout.tsx
+++ b/apps/web/ui/layout/auth-layout.tsx
@@ -13,7 +13,7 @@ export const AuthLayout = ({
return (
<div
className={cn(
- "flex min-h-screen min-h-[100dvh] w-full flex-col items-center justify-between",
+ "flex min-h-[100dvh] w-full flex-col items-center justify-between",
className,
)}
>
diff --git a/apps/web/ui/modals/confirm-approve-bounty-submission-modal.tsx b/apps/web/ui/modals/confirm-approve-bounty-submission-modal.tsx
new file mode 100644
index 0000000000..c1f874504b
--- /dev/null
+++ b/apps/web/ui/modals/confirm-approve-bounty-submission-modal.tsx
@@ -0,0 +1,199 @@
+"use client";
+
+import { approveBountySubmissionAction } from "@/lib/actions/partners/approve-bounty-submission";
+import {
+ calculateSocialMetricsRewardAmount,
+ resolveBountyDetails,
+} from "@/lib/bounty/utils";
+import { mutatePrefix } from "@/lib/swr/mutate";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { BountyProps, BountySubmissionProps } from "@/lib/types";
+import { Button, Modal } from "@dub/ui";
+import { currencyFormatter, OG_AVATAR_URL } from "@dub/utils";
+import { useAction } from "next-safe-action/hooks";
+import { useMemo, useState } from "react";
+import { toast } from "sonner";
+
+type ConfirmApproveBountySubmissionModalProps = {
+ showModal: boolean;
+ setShowModal: (showModal: boolean) => void;
+ submission: BountySubmissionProps;
+ bounty: BountyProps | null;
+ rewardAmount: number | null;
+ onApproveSuccess?: () => void;
+};
+
+function ConfirmApproveBountySubmissionModal({
+ showModal,
+ setShowModal,
+ submission,
+ bounty,
+ rewardAmount,
+ onApproveSuccess,
+}: ConfirmApproveBountySubmissionModalProps) {
+ const { id: workspaceId } = useWorkspace();
+
+ const { executeAsync: approveBountySubmission, isPending } = useAction(
+ approveBountySubmissionAction,
+ {
+ onSuccess: async () => {
+ setShowModal(false);
+ toast.success("Bounty submission approved successfully!");
+ if (bounty?.id) {
+ await mutatePrefix(`/api/bounties/${bounty.id}/submissions`);
+ }
+ onApproveSuccess?.();
+ },
+ onError({ error }) {
+ toast.error(error.serverError);
+ },
+ },
+ );
+
+ const commissionAmountCents = useMemo(() => {
+ const bountyInfo = bounty ? resolveBountyDetails(bounty) : null;
+ if (bountyInfo?.hasSocialMetrics && bounty) {
+ return calculateSocialMetricsRewardAmount({ bounty, submission });
+ }
+ if (bounty?.rewardAmount != null) {
+ return bounty.rewardAmount;
+ }
+ if (rewardAmount != null) {
+ return rewardAmount * 100;
+ }
+ return null;
+ }, [bounty, submission, rewardAmount]);
+
+ const handleApprove = async () => {
+ if (!workspaceId || !submission?.id) return;
+ await approveBountySubmission({
+ workspaceId,
+ submissionId: submission.id,
+ rewardAmount: rewardAmount != null ? rewardAmount * 100 : null,
+ });
+ };
+
+ return (
+ <Modal showModal={showModal} setShowModal={setShowModal}>
+ <div className="space-y-2 border-b border-neutral-200 px-4 py-4 sm:px-6">
+ <h3 className="text-content-emphasis text-lg font-medium">
+ Approve bounty submission
+ </h3>
+ <p className="text-content-subtle text-sm">
+ This will create a{" "}
+ <span className="font-semibold text-neutral-900">
+ {currencyFormatter(commissionAmountCents ?? 0, {
+ trailingZeroDisplay: "stripIfInteger",
+ })}
+ </span>{" "}
+ commission for{" "}
+ <span className="font-semibold text-neutral-900">
+ {submission.partner.name}
+ </span>
+ .
+ </p>
+ </div>
+
+ <div className="flex flex-col">
+ <div className="flex flex-col gap-4 px-4 py-6 text-left sm:px-6">
+ <div className="relative overflow-hidden rounded-lg border border-neutral-200 bg-white p-5">
+ <div
+ className="pointer-events-none absolute inset-0 bg-neutral-50"
+ style={{
+ backgroundImage:
+ "radial-gradient(circle, #d4d4d4 1px, transparent 1px)",
+ backgroundSize: "16px 16px",
+ }}
+ />
+ <div className="relative flex items-center justify-between gap-4">
+ <div className="flex min-w-0 flex-1 items-center gap-4">
+ <img
+ src={
+ submission.partner.image ||
+ `${OG_AVATAR_URL}${submission.partner.id}`
+ }
+ alt={submission.partner.name}
+ className="size-10 shrink-0 rounded-full"
+ />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-base font-semibold text-neutral-800">
+ {submission.partner.name}
+ </div>
+ <div className="truncate text-sm font-medium text-neutral-500">
+ {submission.partner.email}
+ </div>
+ </div>
+ </div>
+ <div className="shrink-0 text-right">
+ <span className="text-content-emphasis text-xl font-semibold">
+ {currencyFormatter(commissionAmountCents ?? 0)}
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div className="flex items-center justify-end border-t border-neutral-200 px-4 py-4 sm:px-6">
+ <div className="flex gap-2">
+ <Button
+ type="button"
+ variant="secondary"
+ text="Cancel"
+ className="h-8 w-fit"
+ onClick={() => setShowModal(false)}
+ disabled={isPending}
+ />
+ <Button
+ type="button"
+ variant="primary"
+ text="Approve"
+ className="h-8 w-fit"
+ loading={isPending}
+ onClick={handleApprove}
+ />
+ </div>
+ </div>
+ </div>
+ </Modal>
+ );
+}
+
+export function useConfirmApproveBountySubmissionModal(options?: {
+ onApproveSuccess?: () => void;
+}) {
+ const [state, setState] = useState<{
+ submission: BountySubmissionProps;
+ bounty: BountyProps | null;
+ rewardAmount: number | null;
+ } | null>(null);
+
+ function openConfirmApproveBountySubmissionModal(
+ submission: BountySubmissionProps,
+ bounty: BountyProps | null,
+ rewardAmount: number | null,
+ ) {
+ setState({ submission, bounty, rewardAmount });
+ }
+
+ function closeConfirmApproveBountySubmissionModal() {
+ setState(null);
+ }
+
+ return {
+ openConfirmApproveBountySubmissionModal,
+ closeConfirmApproveBountySubmissionModal,
+ ConfirmApproveBountySubmissionModal: state ? (
+ <ConfirmApproveBountySubmissionModal
+ submission={state.submission}
+ bounty={state.bounty}
+ rewardAmount={state.rewardAmount}
+ showModal
+ setShowModal={(show) => {
+ if (!show) closeConfirmApproveBountySubmissionModal();
+ }}
+ onApproveSuccess={options?.onApproveSuccess}
+ />
+ ) : null,
+ isConfirmApproveBountySubmissionModalOpen: state !== null,
+ };
+}
diff --git a/apps/web/ui/modals/confirm-referral-status-change-modal.tsx b/apps/web/ui/modals/confirm-referral-status-change-modal.tsx
index 4545778aa9..8aa9f64fb7 100644
--- a/apps/web/ui/modals/confirm-referral-status-change-modal.tsx
+++ b/apps/web/ui/modals/confirm-referral-status-change-modal.tsx
@@ -364,10 +364,10 @@ export function useConfirmReferralStatusChangeModal(options?: {
options?.onClose?.();
}
- function ConfirmReferralStatusChangeModalWrapper() {
- if (!state) return null;
-
- return (
+ return {
+ openConfirmReferralStatusChangeModal,
+ closeConfirmReferralStatusChangeModal,
+ ConfirmReferralStatusChangeModal: state ? (
<ConfirmReferralStatusChangeModal
referral={state.referral}
newStatus={state.newStatus}
@@ -376,13 +376,7 @@ export function useConfirmReferralStatusChangeModal(options?: {
if (!show) closeConfirmReferralStatusChangeModal();
}}
/>
- );
- }
-
- return {
- openConfirmReferralStatusChangeModal,
- closeConfirmReferralStatusChangeModal,
- ConfirmReferralStatusChangeModal: ConfirmReferralStatusChangeModalWrapper,
+ ) : null,
isConfirmReferralStatusChangeModalOpen: state !== null,
};
}
diff --git a/apps/web/ui/oauth-apps/add-edit-app-form.tsx b/apps/web/ui/oauth-apps/add-edit-app-form.tsx
index ce2cfd6651..2581a26067 100644
--- a/apps/web/ui/oauth-apps/add-edit-app-form.tsx
+++ b/apps/web/ui/oauth-apps/add-edit-app-form.tsx
@@ -352,7 +352,7 @@ export default function AddOAuthAppForm({
>
<div
className={cn(
- "border-border-subtle overflow-hidden rounded-md border border-neutral-300 shadow-sm focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500",
+ "border-border-subtle overflow-hidden rounded-md border shadow-sm focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500",
!canManageApp && "cursor-not-allowed bg-neutral-50",
)}
>
diff --git a/apps/web/ui/partners/bounties/bounty-description.tsx b/apps/web/ui/partners/bounties/bounty-description.tsx
new file mode 100644
index 0000000000..ca2771945a
--- /dev/null
+++ b/apps/web/ui/partners/bounties/bounty-description.tsx
@@ -0,0 +1,90 @@
+import {
+ getBountyRewardCriteriaTexts,
+ getBountySubmissionRequirementTexts,
+} from "@/lib/bounty/utils";
+import { PartnerBountyProps } from "@/lib/types";
+import { Markdown } from "@/ui/shared/markdown";
+import { Check2, PROSE_STYLES } from "@dub/ui";
+import { cn } from "@dub/utils";
+
+export function bountyHasDetails(bounty: PartnerBountyProps): boolean {
+ const submissionTexts = getBountySubmissionRequirementTexts(bounty);
+ const rewardTexts = getBountyRewardCriteriaTexts(bounty);
+ const hasDescription = Boolean(bounty.description?.trim());
+ const hasSubmissionRequirements = submissionTexts.length > 0;
+ const hasRewardCriteria = rewardTexts.length > 0;
+ return hasDescription || hasSubmissionRequirements || hasRewardCriteria;
+}
+
+export function BountyDescription({
+ bounty,
+ hideHeading = false,
+}: {
+ bounty: PartnerBountyProps;
+ hideHeading?: boolean;
+}) {
+ const submissionTexts = getBountySubmissionRequirementTexts(bounty);
+ const rewardTexts = getBountyRewardCriteriaTexts(bounty);
+
+ const hasDescription = Boolean(bounty.description?.trim());
+ const hasSubmissionRequirements = submissionTexts.length > 0;
+ const hasRewardCriteria = rewardTexts.length > 0;
+
+ if (!hasDescription && !hasSubmissionRequirements && !hasRewardCriteria) {
+ return null;
+ }
+
+ return (
+ <div className="flex flex-col space-y-3 text-sm">
+ {hasDescription && (
+ <div>
+ {!hideHeading && (
+ <span className="text-content-emphasis font-semibold">Details</span>
+ )}
+ <Markdown
+ className={cn(
+ PROSE_STYLES.default,
+ "text-content-subtle text-sm font-medium leading-5",
+ )}
+ >
+ {bounty.description!.trim()}
+ </Markdown>
+ </div>
+ )}
+
+ {hasSubmissionRequirements && (
+ <div>
+ <span className="text-content-emphasis font-semibold">
+ Submission requirements
+ </span>
+
+ <div className="text-content-subtle mt-2 text-sm font-medium leading-5">
+ {submissionTexts.map((text) => (
+ <div className="flex items-center gap-1.5" key={text}>
+ <Check2 className="size-3 text-green-600" />
+ <span>{text}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {hasRewardCriteria && (
+ <div>
+ <span className="text-content-emphasis font-semibold">
+ Reward criteria
+ </span>
+
+ <div className="text-content-subtle mt-2 text-sm font-medium leading-5">
+ {rewardTexts.map((text) => (
+ <div className="flex items-center gap-1.5" key={text}>
+ <Check2 className="size-3 text-green-600" />
+ <span>{text}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/ui/partners/bounties/bounty-incremental-bonus-tooltip.tsx b/apps/web/ui/partners/bounties/bounty-incremental-bonus-tooltip.tsx
new file mode 100644
index 0000000000..3e9d290419
--- /dev/null
+++ b/apps/web/ui/partners/bounties/bounty-incremental-bonus-tooltip.tsx
@@ -0,0 +1,56 @@
+import { PartnerBountyProps } from "@/lib/types";
+import { InfoTooltip } from "@dub/ui";
+import { currencyFormatter, nFormatter } from "@dub/utils";
+
+export function BountyIncrementalBonusTooltip({
+ bounty,
+ onTooltipClick,
+}: {
+ bounty: Pick<PartnerBountyProps, "submissionRequirements">;
+ onTooltipClick?: (e: React.MouseEvent) => void;
+}) {
+ const description = getBountyIncrementalBonusDescription(bounty);
+
+ if (!description) {
+ return null;
+ }
+
+ return (
+ <span
+ className="inline-flex shrink-0 align-middle"
+ onClick={onTooltipClick}
+ >
+ <InfoTooltip content={description} />
+ </span>
+ );
+}
+
+function getBountyIncrementalBonusDescription(
+ bounty: Pick<PartnerBountyProps, "submissionRequirements">,
+): string | null {
+ const socialMetrics = bounty.submissionRequirements?.socialMetrics;
+ const variableBonus = socialMetrics?.incrementalBonus;
+
+ if (!socialMetrics?.metric || !variableBonus) {
+ return null;
+ }
+
+ const { incrementCount, bonusPerIncrement, maxCount } = variableBonus;
+
+ if (
+ incrementCount == null ||
+ bonusPerIncrement == null ||
+ maxCount == null ||
+ incrementCount < 1 ||
+ maxCount < 1
+ ) {
+ return null;
+ }
+
+ const formattedBonus = currencyFormatter(bonusPerIncrement, {
+ trailingZeroDisplay: "stripIfInteger",
+ });
+
+ // Eg: For each additional 1000 views, earn $1, up to 10000 views
+ return `For each additional ${nFormatter(incrementCount, { full: true })} ${socialMetrics.metric} earn ${formattedBonus}, up to ${nFormatter(maxCount, { full: true })} ${socialMetrics.metric}`;
+}
diff --git a/apps/web/ui/partners/bounties/bounty-performance.tsx b/apps/web/ui/partners/bounties/bounty-performance.tsx
index 0e63e83bad..e22b88ab7e 100644
--- a/apps/web/ui/partners/bounties/bounty-performance.tsx
+++ b/apps/web/ui/partners/bounties/bounty-performance.tsx
@@ -1,5 +1,5 @@
-import { PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES } from "@/lib/api/bounties/performance-bounty-scope-attributes";
import { isCurrencyAttribute } from "@/lib/api/workflows/utils";
+import { PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES } from "@/lib/bounty/api/performance-bounty-scope-attributes";
import { PartnerBountyProps } from "@/lib/types";
import { cn, currencyFormatter, nFormatter } from "@dub/utils";
diff --git a/apps/web/ui/partners/bounties/bounty-reward-description.tsx b/apps/web/ui/partners/bounties/bounty-reward-description.tsx
new file mode 100644
index 0000000000..d4032b9c7b
--- /dev/null
+++ b/apps/web/ui/partners/bounties/bounty-reward-description.tsx
@@ -0,0 +1,43 @@
+import { getBountyRewardDescription } from "@/lib/bounty/get-bounty-reward-description";
+import { BountyProps } from "@/lib/types";
+import { Gift } from "@dub/ui";
+import { cn } from "@dub/utils";
+import { BountyIncrementalBonusTooltip } from "./bounty-incremental-bonus-tooltip";
+
+export function BountyRewardDescription({
+ bounty,
+ className,
+ onTooltipClick,
+}: {
+ bounty: Pick<
+ BountyProps,
+ "rewardAmount" | "rewardDescription" | "submissionRequirements"
+ >;
+ className?: string;
+ onTooltipClick?: (e: React.MouseEvent) => void; // Prevent the tooltip from being clicked when the reward description is clicked
+}) {
+ const description = getBountyRewardDescription(bounty);
+
+ if (!description) {
+ return null;
+ }
+
+ return (
+ <div
+ className={cn(
+ "text-content-subtle flex items-center gap-1 text-sm",
+ className,
+ )}
+ >
+ <div className="flex items-center gap-2">
+ <Gift className="size-3.5 shrink-0" />
+ <span>{description}</span>
+ </div>
+
+ <BountyIncrementalBonusTooltip
+ bounty={bounty}
+ onTooltipClick={onTooltipClick}
+ />
+ </div>
+ );
+}
diff --git a/apps/web/ui/partners/bounties/bounty-social-content-preview.tsx b/apps/web/ui/partners/bounties/bounty-social-content-preview.tsx
new file mode 100644
index 0000000000..ab087340f9
--- /dev/null
+++ b/apps/web/ui/partners/bounties/bounty-social-content-preview.tsx
@@ -0,0 +1,108 @@
+"use client";
+
+import {
+ getSocialContentEmbedUrl,
+ resolveBountyDetails,
+} from "@/lib/bounty/utils";
+import {
+ BountySocialPlatform,
+ BountySubmissionProps,
+ PartnerBountyProps,
+} from "@/lib/types";
+import { cn } from "@dub/utils";
+import { useState } from "react";
+
+interface BountySocialContentPreviewProps {
+ bounty: Pick<PartnerBountyProps, "id" | "submissionRequirements">;
+ submission: Pick<BountySubmissionProps, "urls"> | null | undefined;
+}
+
+function getSocialContentEmbedAspectRatio({
+ platform,
+ url,
+}: {
+ platform: BountySocialPlatform;
+ url: string;
+}): string {
+ try {
+ const parsed = new URL(url);
+ const pathname = parsed.pathname;
+
+ if (platform === "youtube") {
+ return pathname.includes("/shorts/") ? "aspect-[9/16]" : "aspect-video";
+ }
+
+ if (platform === "tiktok") {
+ return "aspect-[9/16]";
+ }
+
+ if (platform === "instagram") {
+ return pathname.includes("/reel/") ? "aspect-[9/16]" : "aspect-square";
+ }
+
+ if (platform === "twitter") {
+ return "aspect-square";
+ }
+
+ return "aspect-video";
+ } catch {
+ return "aspect-video";
+ }
+}
+
+export function BountySocialContentPreview({
+ bounty,
+ submission,
+}: BountySocialContentPreviewProps) {
+ const [loaded, setLoaded] = useState(false);
+
+ const bountyInfo = resolveBountyDetails(bounty);
+
+ const url = submission?.urls?.[0] ?? "";
+ const platform = bountyInfo?.socialPlatform;
+
+ if (!url || !platform) {
+ return null;
+ }
+
+ const embedUrl = getSocialContentEmbedUrl({
+ platform: platform.value,
+ url,
+ });
+
+ if (!embedUrl) {
+ return null;
+ }
+
+ const aspectClass = getSocialContentEmbedAspectRatio({
+ platform: platform.value,
+ url,
+ });
+
+ return (
+ <div className="overflow-hidden rounded-xl border border-neutral-200 bg-white p-2">
+ <div
+ className={cn(
+ "relative mx-auto flex max-h-[700px] w-full items-center justify-center overflow-hidden rounded-lg",
+ aspectClass,
+ )}
+ >
+ {!loaded && (
+ <div className="absolute inset-0 z-10 flex items-center justify-center bg-neutral-100">
+ <div className="h-8 w-8 animate-spin rounded-full border-2 border-neutral-300 border-t-neutral-600" />
+ </div>
+ )}
+ <iframe
+ src={embedUrl}
+ title={`${platform.label} content preview`}
+ aria-label={`${platform.label} content preview`}
+ className={cn("absolute inset-0 size-full", !loaded && "opacity-0")}
+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
+ allowFullScreen
+ loading="lazy"
+ onLoad={() => setLoaded(true)}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/ui/partners/bounties/bounty-social-content.tsx b/apps/web/ui/partners/bounties/bounty-social-content.tsx
new file mode 100644
index 0000000000..2fd8ed526a
--- /dev/null
+++ b/apps/web/ui/partners/bounties/bounty-social-content.tsx
@@ -0,0 +1,249 @@
+"use client";
+
+import { resolveBountyDetails } from "@/lib/bounty/utils";
+import usePartnerProfile from "@/lib/swr/use-partner-profile";
+import { PartnerBountyProps, SocialContent } from "@/lib/types";
+import { useClaimBountyContext } from "@/ui/partners/bounties/claim-bounty-context";
+import { useClaimBountyForm } from "@/ui/partners/bounties/use-claim-bounty-form";
+import { useSocialContent } from "@/ui/partners/bounties/use-social-content";
+import { ButtonLink } from "@/ui/placeholders/button-link";
+import { CircleCheckFill, LoadingSpinner } from "@dub/ui";
+import { cn, formatDate } from "@dub/utils";
+import { isBefore } from "date-fns";
+import { AlertTriangle } from "lucide-react";
+import Link from "next/link";
+import { useEffect, useId, useState } from "react";
+
+function socialContentRequirementChecks({
+ content,
+ bounty,
+ partnerPlatform,
+}: {
+ content: SocialContent | null | undefined;
+ bounty: PartnerBountyProps;
+ partnerPlatform: { identifier: string; verifiedAt: Date | null } | undefined;
+}) {
+ const isPostedFromYourAccount =
+ !!content &&
+ !!partnerPlatform &&
+ !!partnerPlatform.verifiedAt &&
+ partnerPlatform.identifier.toLowerCase() === content.handle?.toLowerCase();
+
+ const isAfterStartDate =
+ !!content?.publishedAt &&
+ !!bounty.startsAt &&
+ !isBefore(content.publishedAt, bounty.startsAt);
+
+ return {
+ isPostedFromYourAccount,
+ isAfterStartDate,
+ };
+}
+
+function SocialContentRequirementChecks({
+ content,
+ bounty,
+}: {
+ content: SocialContent | null;
+ bounty: PartnerBountyProps;
+}) {
+ const { partner } = usePartnerProfile();
+
+ const bountyInfo = resolveBountyDetails(bounty);
+ const socialPlatform = bountyInfo?.socialPlatform;
+
+ const partnerPlatform = partner?.platforms?.find(
+ (p) => p.type === socialPlatform?.value,
+ );
+
+ const { isPostedFromYourAccount, isAfterStartDate } =
+ socialContentRequirementChecks({
+ content,
+ bounty,
+ partnerPlatform,
+ });
+
+ return (
+ <ul className="mt-2 flex flex-wrap items-center gap-3">
+ <li
+ className={cn(
+ "flex items-center gap-1 text-xs font-medium transition-colors",
+ isPostedFromYourAccount ? "text-green-600" : "text-neutral-400",
+ )}
+ >
+ <CircleCheckFill
+ className={cn(
+ "size-2.5 transition-opacity",
+ isPostedFromYourAccount ? "text-green-600" : "text-neutral-200",
+ )}
+ />
+ <span>Posted from your account</span>
+ </li>
+
+ <li
+ className={cn(
+ "flex items-center gap-1 text-xs font-medium transition-colors",
+ isAfterStartDate ? "text-green-600" : "text-neutral-400",
+ )}
+ >
+ <CircleCheckFill
+ className={cn(
+ "size-2.5 transition-opacity",
+ isAfterStartDate ? "text-green-600" : "text-neutral-200",
+ )}
+ />
+ <span>{`Posted after ${formatDate(bounty.startsAt, { month: "short", day: "numeric", year: "numeric" })}`}</span>
+ </li>
+ </ul>
+ );
+}
+
+export function SocialContentUrlField({
+ bounty,
+}: {
+ bounty: PartnerBountyProps;
+}) {
+ const { partner } = usePartnerProfile();
+ const { setSocialContentRequirementsMet } = useClaimBountyContext();
+
+ const { watch, setValue, getValues, setSocialContentVerifying } =
+ useClaimBountyForm();
+
+ const [urlToCheck, setUrlToCheck] = useState<string>("");
+ const inputId = useId();
+
+ const contentUrl = watch("urls")?.[0] ?? "";
+
+ useEffect(() => {
+ if (contentUrl === "") {
+ setUrlToCheck("");
+ }
+ }, [contentUrl]);
+
+ const { data, error, isValidating } = useSocialContent({
+ bountyId: bounty.id,
+ url: urlToCheck,
+ });
+
+ useEffect(() => {
+ setSocialContentVerifying(isValidating);
+ return () => setSocialContentVerifying(false);
+ }, [isValidating, setSocialContentVerifying]);
+
+ const bountyInfo = resolveBountyDetails(bounty);
+ const partnerPlatform = partner?.platforms?.find(
+ (p) => p.type === bountyInfo?.socialPlatform?.value,
+ );
+
+ useEffect(() => {
+ const checks = socialContentRequirementChecks({
+ content: data,
+ bounty,
+ partnerPlatform,
+ });
+
+ setSocialContentRequirementsMet(
+ checks.isPostedFromYourAccount && checks.isAfterStartDate,
+ );
+
+ return () => setSocialContentRequirementsMet(true);
+ }, [data, bounty, partnerPlatform, setSocialContentRequirementsMet]);
+
+ const showIcon = isValidating || (error && urlToCheck);
+
+ if (!bountyInfo?.socialPlatform) {
+ return null;
+ }
+
+ const handleChange = (value: string) => {
+ const prev = getValues("urls") ?? [];
+ setValue("urls", [value, ...prev.slice(1)], { shouldDirty: true });
+ };
+
+ const handleBlur = () => {
+ const trimmed = contentUrl.trim();
+ const prev = getValues("urls") ?? [];
+ setValue("urls", [trimmed, ...prev.slice(1)], { shouldDirty: true });
+ setUrlToCheck(trimmed);
+ };
+
+ return (
+ <div>
+ <label htmlFor={inputId} className="block">
+ <span className="text-sm font-medium text-neutral-900">
+ {`${bountyInfo?.socialPlatform.label} URL`}
+ </span>
+ </label>
+ <div className="relative mt-2">
+ <input
+ id={inputId}
+ type="text"
+ inputMode="url"
+ autoComplete="url"
+ placeholder={bountyInfo?.socialPlatform.placeholder}
+ value={contentUrl}
+ onChange={(e) => handleChange(e.target.value)}
+ onBlur={handleBlur}
+ className={cn(
+ "block h-10 w-full rounded-md border-neutral-300 px-3 py-2 pr-10 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
+ error &&
+ urlToCheck &&
+ "border-red-500 focus:border-red-500 focus:ring-red-500",
+ )}
+ />
+
+ {showIcon && (
+ <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
+ {isValidating ? (
+ <LoadingSpinner className="size-4 shrink-0 text-neutral-400" />
+ ) : error && urlToCheck ? (
+ <AlertTriangle
+ className="size-4 shrink-0 text-red-500"
+ fill="#ef4444"
+ />
+ ) : null}
+ </div>
+ )}
+ </div>
+ <SocialContentRequirementChecks content={data} bounty={bounty} />
+ </div>
+ );
+}
+
+export function SocialAccountNotVerifiedWarning({
+ bounty,
+}: {
+ bounty: PartnerBountyProps;
+}) {
+ const bountyInfo = resolveBountyDetails(bounty);
+
+ if (!bountyInfo?.socialPlatform) {
+ return null;
+ }
+
+ return (
+ <div className="flex flex-col gap-2 rounded-lg bg-orange-50 p-2 text-center">
+ <div className="px-2 text-sm font-medium text-orange-900">
+ {`A verified ${bountyInfo.socialPlatform.label} account must be connected to your Dub partner profile to claim this bounty.`}
+
+ <Link
+ href="https://dub.co/help/article/receiving-payouts"
+ target="_blank"
+ className="ml-1 underline underline-offset-2"
+ >
+ Learn more
+ </Link>
+ </div>
+
+ <ButtonLink
+ variant="primary"
+ href="/profile"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="h-7 w-full justify-center rounded-lg"
+ >
+ View profile
+ </ButtonLink>
+ </div>
+ );
+}
diff --git a/apps/web/ui/partners/bounties/bounty-social-metrics-rewards-table.tsx b/apps/web/ui/partners/bounties/bounty-social-metrics-rewards-table.tsx
new file mode 100644
index 0000000000..23788c148c
--- /dev/null
+++ b/apps/web/ui/partners/bounties/bounty-social-metrics-rewards-table.tsx
@@ -0,0 +1,138 @@
+"use client";
+
+import {
+ getSocialMetricsRewardTiers,
+ resolveBountyDetails,
+ SocialMetricsRewardTier,
+} from "@/lib/bounty/utils";
+import { BountySubmissionProps, PartnerBountyProps } from "@/lib/types";
+import { StatusBadge, Table, useTable } from "@dub/ui";
+import { capitalize, currencyFormatter } from "@dub/utils";
+import { ColumnDef } from "@tanstack/react-table";
+import { useMemo } from "react";
+
+const displayStatusMap = {
+ approved: {
+ label: "Approved",
+ variant: "success",
+ },
+ pending: {
+ label: "Pending approval",
+ variant: "new",
+ },
+ inProgress: {
+ label: "In progress",
+ variant: "pending",
+ },
+};
+
+function getDisplayStatus(
+ tier: SocialMetricsRewardTier,
+ submission: Pick<
+ BountySubmissionProps,
+ "socialMetricCount" | "commission" | "status"
+ >,
+) {
+ if (tier.status === "unmet") {
+ return "inProgress";
+ }
+
+ if (
+ submission.status === "approved" &&
+ submission.commission != null &&
+ submission.commission.earnings != null
+ ) {
+ return "approved";
+ }
+
+ return "pending";
+}
+
+export function BountySocialMetricsRewardsTable({
+ bounty,
+ submission,
+ titleText = "Rewards",
+}: {
+ bounty: Pick<
+ PartnerBountyProps,
+ "id" | "submissionRequirements" | "rewardAmount"
+ >;
+ submission: Pick<
+ BountySubmissionProps,
+ "socialMetricCount" | "commission" | "status"
+ >;
+ titleText?: string;
+}) {
+ const tiers = getSocialMetricsRewardTiers({
+ bounty,
+ submission,
+ });
+
+ const bountyInfo = resolveBountyDetails(bounty);
+ const metricLabel = bountyInfo?.socialMetrics?.metric ?? "Count";
+
+ const columns = useMemo<ColumnDef<SocialMetricsRewardTier>[]>(
+ () => [
+ {
+ id: "threshold",
+ header: capitalize(metricLabel)!,
+ minSize: 100,
+ size: 120,
+ cell: ({ row: { original } }) => (
+ <span className="font-medium text-neutral-800">
+ {original.threshold.toLocaleString()}
+ </span>
+ ),
+ },
+ {
+ id: "reward",
+ header: "Reward",
+ minSize: 100,
+ size: 120,
+ cell: ({ row: { original } }) =>
+ currencyFormatter(original.rewardAmount, {
+ trailingZeroDisplay: "stripIfInteger",
+ }),
+ },
+ {
+ id: "status",
+ header: "Status",
+ minSize: 120,
+ size: 140,
+ cell: ({ row: { original } }) => {
+ const status =
+ displayStatusMap[getDisplayStatus(original, submission)];
+
+ return (
+ <StatusBadge variant={status.variant}>{status.label}</StatusBadge>
+ );
+ },
+ },
+ ],
+ [metricLabel, submission],
+ );
+
+ const table = useTable({
+ data: tiers,
+ columns,
+ getRowId: (row) => String(row.threshold),
+ resourceName: () => "reward tier",
+ scrollWrapperClassName: "min-h-0",
+ thClassName: "border-l-0",
+ tdClassName: "border-l-0",
+ className: "[&_tbody_tr:last-child_td]:border-b-0",
+ });
+
+ if (tiers.length === 0) {
+ return null;
+ }
+
+ return (
+ <div>
+ <h2 className="text-base font-semibold text-neutral-900">{titleText}</h2>
+ <div className="mt-3">
+ <Table {...table} />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/ui/partners/bounties/claim-bounty-context.tsx b/apps/web/ui/partners/bounties/claim-bounty-context.tsx
new file mode 100644
index 0000000000..3cca9dddd6
--- /dev/null
+++ b/apps/web/ui/partners/bounties/claim-bounty-context.tsx
@@ -0,0 +1,55 @@
+"use client";
+
+import {
+ createContext,
+ Dispatch,
+ SetStateAction,
+ useContext,
+ useState,
+} from "react";
+
+export type ClaimBountyContextValue = {
+ socialContentVerifying: boolean;
+ setSocialContentVerifying: Dispatch<SetStateAction<boolean>>;
+ socialContentRequirementsMet: boolean;
+ setSocialContentRequirementsMet: Dispatch<SetStateAction<boolean>>;
+};
+
+const ClaimBountyContext = createContext<ClaimBountyContextValue | undefined>(
+ undefined,
+);
+
+export function ClaimBountyProvider({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ const [socialContentVerifying, setSocialContentVerifying] = useState(false);
+ const [socialContentRequirementsMet, setSocialContentRequirementsMet] =
+ useState(true);
+
+ return (
+ <ClaimBountyContext.Provider
+ value={{
+ socialContentVerifying,
+ setSocialContentVerifying,
+ socialContentRequirementsMet,
+ setSocialContentRequirementsMet,
+ }}
+ >
+ {children}
+ </ClaimBountyContext.Provider>
+ );
+}
+
+export function useClaimBountyContext() {
+ const context = useContext(ClaimBountyContext);
+
+ if (!context) {
+ throw new Error(
+ "useClaimBountyContext must be used within ClaimBountyProvider",
+ );
+ }
+
+ return context;
+}
diff --git a/apps/web/ui/partners/bounties/claim-bounty-modal.tsx b/apps/web/ui/partners/bounties/claim-bounty-modal.tsx
index d9de8a5983..897d9a9725 100644
--- a/apps/web/ui/partners/bounties/claim-bounty-modal.tsx
+++ b/apps/web/ui/partners/bounties/claim-bounty-modal.tsx
@@ -5,23 +5,21 @@ import {
BOUNTY_MAX_SUBMISSION_FILES,
BOUNTY_MAX_SUBMISSION_URLS,
REJECT_BOUNTY_SUBMISSION_REASONS,
-} from "@/lib/constants/bounties";
-import { getBountyRewardDescription } from "@/lib/partners/get-bounty-reward-description";
+} from "@/lib/bounty/constants";
+import { resolveBountyDetails } from "@/lib/bounty/utils";
import { mutatePrefix } from "@/lib/swr/mutate";
+import usePartnerProfile from "@/lib/swr/use-partner-profile";
import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
import { PartnerBountyProps } from "@/lib/types";
import { useConfirmModal } from "@/ui/modals/confirm-modal";
import { X } from "@/ui/shared/icons";
-import { Markdown } from "@/ui/shared/markdown";
import {
AnimatedSizeContainer,
Button,
Calendar6,
FileUpload,
- Gift,
LoadingSpinner,
Modal,
- PROSE_STYLES,
StatusBadge,
Trash,
buttonVariants,
@@ -34,11 +32,23 @@ import { motion } from "motion/react";
import { useAction } from "next-safe-action/hooks";
import Link from "next/link";
import { Dispatch, SetStateAction, useState } from "react";
+import { FormProvider, useForm } from "react-hook-form";
import ReactTextareaAutosize from "react-textarea-autosize";
import { toast } from "sonner";
import { v4 as uuid } from "uuid";
+import { BountyDescription, bountyHasDetails } from "./bounty-description";
import { BountyPerformance } from "./bounty-performance";
+import { BountyRewardDescription } from "./bounty-reward-description";
+import {
+ SocialAccountNotVerifiedWarning,
+ SocialContentUrlField,
+} from "./bounty-social-content";
import { BountyThumbnailImage } from "./bounty-thumbnail-image";
+import {
+ ClaimBountyProvider,
+ useClaimBountyContext,
+} from "./claim-bounty-context";
+import { CreateBountySubmissionInput } from "./use-claim-bounty-form";
type ClaimBountyModalProps = {
setShowModal: Dispatch<SetStateAction<boolean>>;
@@ -52,19 +62,20 @@ interface FileInput {
uploading: boolean;
}
-interface Url {
- id: string;
- url: string;
-}
-
function ClaimBountyModalContent({ bounty }: ClaimBountyModalProps) {
const { submission } = bounty;
-
const { programEnrollment } = useProgramEnrollment();
+ const { platformsVerified } = usePartnerProfile();
const [success, setSuccess] = useState(false);
const [isFormOpen, setIsFormOpen] = useState(false);
const [isDraft, setIsDraft] = useState<boolean | null>(null);
+ const { socialContentVerifying, socialContentRequirementsMet } =
+ useClaimBountyContext();
+
+ const bountyInfo = resolveBountyDetails(bounty);
+ const socialPlatform = bountyInfo?.socialPlatform;
+ const isSocialMetricsBounty = bountyInfo?.hasSocialMetrics ?? false;
// Initialize form state with existing draft submission data
const [description, setDescription] = useState(submission?.description || "");
@@ -82,33 +93,60 @@ function ClaimBountyModalContent({ bounty }: ClaimBountyModalProps) {
return [];
});
- const [urls, setUrls] = useState<Url[]>(() => {
+ const initialUrls = (() => {
if (submission?.urls && submission.urls.length > 0) {
- return submission.urls.map((url) => ({
- id: uuid(),
- url: url,
- }));
+ return socialPlatform
+ ? [submission.urls[0] ?? "", ...submission.urls.slice(1)]
+ : [...submission.urls];
}
- return [{ id: uuid(), url: "" }];
+ return [""];
+ })();
+
+ const claimForm = useForm<CreateBountySubmissionInput>({
+ defaultValues: {
+ urls: initialUrls,
+ },
});
const { executeAsync: uploadFile } = useAction(
uploadBountySubmissionFileAction,
);
+ const { executeAsync: createSubmission } = useAction(
+ createBountySubmissionAction,
+ {
+ onSuccess: async () => {
+ toast.success(isDraft ? "Bounty progress saved." : "Bounty submitted.");
+ setSuccess(true);
+ await mutatePrefix(
+ `/api/partner-profile/programs/${programEnrollment?.program.slug}/bounties`,
+ );
+ },
+ onError: ({ error }) => {
+ toast.error(
+ error.serverError || "Failed to create submission. Please try again.",
+ );
+ setIsDraft(null);
+ },
+ },
+ );
+
+ // Handle file upload
const handleUpload = async (file: File) => {
if (!programEnrollment) return;
setFiles((prev) => [...prev, { id: uuid(), file, uploading: true }]);
- // TODO: Partners upload URL
const result = await uploadFile({
programId: programEnrollment.programId,
bountyId: bounty.id,
});
- if (!result?.data) throw new Error("Failed to get signed upload URL");
+ if (!result?.data) {
+ toast.error("Failed to get signed upload URL.");
+ return;
+ }
const { signedUrl, destinationUrl } = result.data;
@@ -128,6 +166,7 @@ function ClaimBountyModalContent({ bounty }: ClaimBountyModalProps) {
}
toast.success(`${file.name} uploaded!`);
+
setFiles((prev) =>
prev.map((f) =>
f.file === file ? { ...f, uploading: false, url: destinationUrl } : f,
@@ -135,10 +174,6 @@ function ClaimBountyModalContent({ bounty }: ClaimBountyModalProps) {
);
};
- const { executeAsync: createSubmission } = useAction(
- createBountySubmissionAction,
- );
-
const imageRequired = !!bounty.submissionRequirements?.image;
const urlRequired = !!bounty.submissionRequirements?.url;
const fileUploading = files.some(({ uploading }) => uploading);
@@ -169,10 +204,12 @@ function ClaimBountyModalContent({ bounty }: ClaimBountyModalProps) {
Are you sure you want to submit this bounty? Once submitted, you won't
be able to make any further changes.
</p>
- <p>
- If you need to make changes later, you can save your progress as a
- draft instead.
- </p>
+ {!isSocialMetricsBounty && (
+ <p>
+ If you need to make changes later, you can save your progress as a
+ draft instead.
+ </p>
+ )}
</div>
),
confirmText: "Confirm submission",
@@ -186,47 +223,39 @@ function ClaimBountyModalContent({ bounty }: ClaimBountyModalProps) {
setIsDraft(isDraft);
const finalFiles = files
- .filter(({ url }) => url)
+ .filter((f): f is FileInput & { url: string } => !!f.url)
.map(({ file, url }) => ({
- url: url!,
+ url,
fileName: file?.name || "File",
size: file?.size || 0,
}));
- const finalUrls = urls.map(({ url }) => url).filter(Boolean);
+ const formUrls = (claimForm.getValues("urls") ?? []).filter(Boolean);
try {
- // Check the submission requirements are met for non-draft submissions
if (!isDraft) {
setShowConfirmModal(false);
if (imageRequired && finalFiles.length === 0) {
throw new Error("You must upload at least one image.");
}
- if (urlRequired && finalUrls.length === 0) {
+ if (socialPlatform && !formUrls[0]?.trim()) {
+ throw new Error(`You must provide the ${socialPlatform.label} link.`);
+ }
+
+ if (urlRequired && formUrls.length === 0) {
throw new Error("You must provide at least one URL.");
}
}
- const result = await createSubmission({
+ await createSubmission({
programId: programEnrollment.programId,
bountyId: bounty.id,
files: finalFiles,
- urls: finalUrls,
+ urls: formUrls,
description,
...(isDraft && { isDraft }),
});
-
- if (!result?.data?.success) {
- throw new Error(result?.serverError);
- }
-
- toast.success(isDraft ? "Bounty progress saved." : "Bounty submitted.");
-
- setSuccess(true);
- await mutatePrefix(
- `/api/partner-profile/programs/${programEnrollment.program.slug}/bounties`,
- );
} catch (error) {
toast.error(
error instanceof Error
@@ -240,464 +269,535 @@ function ClaimBountyModalContent({ bounty }: ClaimBountyModalProps) {
return (
<>
{confirmModal}
- <form
- onSubmit={async (e) => {
- e.preventDefault();
- if (!programEnrollment) return;
-
- // Determine which button was clicked
- const submitter = (e.nativeEvent as SubmitEvent)
- .submitter as HTMLButtonElement;
-
- const isDraft = submitter?.name === "draft";
-
- if (isDraft) {
- // Handle draft save directly
- await handleSubmission({ isDraft: true });
- } else {
- // Show confirmation modal for final submission
- setShowConfirmModal(true);
- }
- }}
- >
- <div className="scrollbar-hide max-h-[calc(100dvh-150px)] overflow-y-auto">
- <div className="flex h-[132px] items-center justify-center bg-neutral-100 py-3">
- <div className="relative size-full">
- <BountyThumbnailImage bounty={bounty} />
+ <FormProvider {...claimForm}>
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+ if (!programEnrollment) return;
+
+ // Determine which button was clicked
+ const submitter = (e.nativeEvent as SubmitEvent)
+ .submitter as HTMLButtonElement;
+
+ const isDraft =
+ submitter?.name === "draft" && !isSocialMetricsBounty;
+
+ if (isDraft) {
+ // Handle draft save directly
+ await handleSubmission({ isDraft: true });
+ } else {
+ // Show confirmation modal for final submission
+ setShowConfirmModal(true);
+ }
+ }}
+ >
+ <div className="scrollbar-hide max-h-[calc(100dvh-150px)] overflow-y-auto">
+ <div className="flex h-[132px] items-center justify-center bg-neutral-100 py-3">
+ <div className="relative size-full">
+ <BountyThumbnailImage bounty={bounty} />
+ </div>
</div>
- </div>
- <AnimatedSizeContainer
- height={isFormOpen}
- transition={{ duration: 0.15, ease: "easeInOut" }}
- >
- {success ? (
- <div className="mx-auto flex max-w-sm flex-col items-center gap-1 p-6 text-center max-sm:px-4">
- {isDraft ? (
- <>
- <span className="text-content-emphasis text-base font-semibold">
- Progress saved successfully.
- </span>
- <p className="text-content-subtle text-balance text-sm font-medium">
- You can continue working on your submission later.
- </p>
- </>
- ) : (
- <>
- <span className="text-content-emphasis text-base font-semibold">
- Congratulations! You've successfully submitted your
- bounty.
- </span>
- <p className="text-content-subtle text-balance text-sm font-medium">
- We'll let you know when your bounty has been reviewed.
- </p>
- </>
- )}
- </div>
- ) : (
- <>
- <div className="flex flex-col gap-1 p-6 max-sm:px-4">
- <span className="text-content-emphasis truncate text-sm font-semibold">
- {bounty.name}
- </span>
-
- <div className="text-content-subtle flex items-center gap-2 text-sm font-medium">
- <Calendar6 className="size-3.5" />
- <span>
- {bounty.endsAt ? (
- <>
- Ends {formatDate(bounty.endsAt, { month: "short" })}
- </>
- ) : (
- "No end date"
- )}
+ <AnimatedSizeContainer
+ height={isFormOpen}
+ transition={{ duration: 0.15, ease: "easeInOut" }}
+ >
+ {success ? (
+ <div className="mx-auto flex max-w-sm flex-col items-center gap-1 p-6 text-center max-sm:px-4">
+ {isDraft ? (
+ <>
+ <span className="text-content-emphasis text-base font-semibold">
+ Progress saved successfully.
+ </span>
+ <p className="text-content-subtle text-balance text-sm font-medium">
+ You can continue working on your submission later.
+ </p>
+ </>
+ ) : (
+ <>
+ <span className="text-content-emphasis text-base font-semibold">
+ Congratulations! You've successfully submitted your
+ bounty.
+ </span>
+ <p className="text-content-subtle text-balance text-sm font-medium">
+ We'll let you know when your bounty has been reviewed.
+ </p>
+ </>
+ )}
+ </div>
+ ) : (
+ <>
+ <div className="flex flex-col gap-1 p-6 max-sm:px-4">
+ <span className="text-content-emphasis truncate text-sm font-semibold">
+ {bounty.name}
</span>
- </div>
- {getBountyRewardDescription(bounty) && (
<div className="text-content-subtle flex items-center gap-2 text-sm font-medium">
- <Gift className="size-3.5" />
- <span>{getBountyRewardDescription(bounty)}</span>
+ <Calendar6 className="size-3.5" />
+ <span>
+ {bounty.endsAt ? (
+ <>
+ Ends {formatDate(bounty.endsAt, { month: "short" })}
+ </>
+ ) : (
+ "No end date"
+ )}
+ </span>
+ </div>
+
+ <BountyRewardDescription
+ bounty={bounty}
+ className="font-medium"
+ />
+
+ {submission ? (
+ <div className="grid gap-2">
+ <div className="flex items-center gap-2">
+ {submission.status === "approved" && (
+ <Link
+ href={`/programs/${programEnrollment?.program.slug}/earnings?type=custom`}
+ target="_blank"
+ className={cn(
+ buttonVariants({ variant: "primary" }),
+ "flex h-7 w-fit items-center whitespace-nowrap rounded-lg border px-2.5 text-sm",
+ )}
+ >
+ View earnings
+ </Link>
+ )}
+ {submission.status !== "draft" && (
+ <StatusBadge
+ className="rounded-lg py-1.5"
+ variant={
+ submission.status === "submitted"
+ ? "new"
+ : submission.status === "approved"
+ ? "success"
+ : "error"
+ }
+ icon={
+ submission.status === "approved"
+ ? undefined
+ : null
+ }
+ >
+ {submission.status === "submitted" ? (
+ <>
+ Pending Review |{" "}
+ {bounty.type === "performance"
+ ? "Completed"
+ : "Submitted"}{" "}
+ {submission.completedAt &&
+ formatDate(submission.completedAt, {
+ month: "short",
+ })}
+ </>
+ ) : submission.status === "approved" ? (
+ <>
+ Confirmed{" "}
+ {submission.reviewedAt &&
+ formatDate(submission.reviewedAt, {
+ month: "short",
+ })}
+ </>
+ ) : (
+ "Rejected"
+ )}
+ </StatusBadge>
+ )}
+ </div>
+
+ {/* Rejection details for rejected submissions */}
+ {submission.status === "rejected" && (
+ <div className="mt-3 flex flex-col gap-2 rounded-lg border border-red-200 bg-red-50 p-4">
+ <div className="flex gap-1">
+ <span className="text-sm font-medium text-red-900">
+ Rejection reason:
+ </span>
+ <span className="text-sm text-red-800">
+ {submission.rejectionReason &&
+ REJECT_BOUNTY_SUBMISSION_REASONS[
+ submission.rejectionReason as keyof typeof REJECT_BOUNTY_SUBMISSION_REASONS
+ ]}
+ </span>
+ </div>
+ {submission.rejectionNote && (
+ <div className="mt-1">
+ <span className="text-sm font-medium text-red-900">
+ Note:
+ </span>
+ <Linkify
+ as="p"
+ options={{
+ target: "_blank",
+ rel: "noopener noreferrer nofollow",
+ format: (href) => getPrettyUrl(href),
+ className:
+ "underline underline-offset-4 text-red-400 hover:text-red-700",
+ }}
+ className="mt-1 whitespace-pre-wrap text-sm text-red-800"
+ >
+ {submission.rejectionNote}
+ </Linkify>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ ) : (
+ bounty.type === "performance" && (
+ <div className="mt-5">
+ <BountyPerformance bounty={bounty} />
+ </div>
+ )
+ )}
+ </div>
+
+ {bountyHasDetails(bounty) && (
+ <div className="border-border-subtle border-t p-6 max-sm:px-4">
+ <BountyDescription bounty={bounty} />
</div>
)}
- {submission ? (
- <div className="mt-3 grid gap-2">
- <div className="flex items-center gap-2">
- {submission.status === "approved" && (
- <Link
- href={`/programs/${programEnrollment?.program.slug}/earnings?type=custom`}
- target="_blank"
+ {/* Form */}
+ <motion.div
+ initial={false}
+ animate={{ height: isFormOpen ? "auto" : 0 }}
+ transition={{ duration: 0.15 }}
+ className={cn(
+ "overflow-hidden transition-opacity",
+ !isFormOpen && "opacity-0",
+ )}
+ >
+ <div className="border-border-subtle flex flex-col gap-5 border-t p-6 max-sm:px-4">
+ {imageRequired && (
+ <div>
+ <div className="flex items-center space-x-2">
+ <h2 className="text-sm font-medium text-neutral-900">
+ Files
+ {imageRequired && " (at least 1 required)"}
+ </h2>
+ </div>
+ <div
className={cn(
- buttonVariants({ variant: "primary" }),
- "flex h-7 w-fit items-center whitespace-nowrap rounded-lg border px-2.5 text-sm",
+ "mt-2 flex h-12 items-center gap-2 transition-[height]",
+ files.length === 0 && "h-24",
)}
>
- View earnings
- </Link>
- )}
- {submission.status !== "draft" && (
- <StatusBadge
- className="rounded-lg py-1.5"
- variant={
- submission.status === "submitted"
- ? "new"
- : submission.status === "approved"
- ? "success"
- : "error"
- }
- icon={
- submission.status === "approved"
- ? undefined
- : null
- }
- >
- {submission.status === "submitted" ? (
- <>
- Pending Review |{" "}
- {bounty.type === "performance"
- ? "Completed"
- : "Submitted"}{" "}
- {submission.completedAt &&
- formatDate(submission.completedAt, {
- month: "short",
- })}
- </>
- ) : submission.status === "approved" ? (
- <>
- Confirmed{" "}
- {submission.reviewedAt &&
- formatDate(submission.reviewedAt, {
- month: "short",
- })}
- </>
- ) : (
- "Rejected"
- )}
- </StatusBadge>
- )}
- </div>
+ {files.map((file, idx) => (
+ <div
+ key={file.id}
+ className="border-border-subtle group relative flex aspect-square h-full items-center justify-center rounded-md border bg-white"
+ >
+ {file.uploading ? (
+ <LoadingSpinner className="size-4" />
+ ) : (
+ <div className="relative size-full overflow-hidden rounded-md">
+ <img
+ src={file.url}
+ alt={
+ file.file?.name ||
+ `Bounty attachment ${idx + 1}`
+ }
+ />
+ </div>
+ )}
+ <span className="sr-only">
+ {file.file?.name || `File ${idx + 1}`}
+ </span>
+ <button
+ type="button"
+ className={cn(
+ "absolute right-0 top-0 flex size-[1.125rem] -translate-y-1/2 translate-x-1/2 items-center justify-center",
+ "rounded-full border border-neutral-200 bg-white shadow-sm hover:bg-neutral-50 active:scale-95",
+ "scale-50 opacity-0 transition-[background-color,transform,opacity] group-hover:scale-100 group-hover:opacity-100",
+ )}
+ onClick={() => {
+ setFiles((prev) =>
+ prev.filter((s) => s.id !== file.id),
+ );
+ }}
+ >
+ <X className="size-2.5 text-neutral-400" />
+ </button>
+ </div>
+ ))}
+
+ <FileUpload
+ accept="images"
+ className={cn(
+ "border-border-subtle h-full w-auto rounded-md border",
+ files.length > 0
+ ? "aspect-square"
+ : "aspect-[unset] w-full",
+ )}
+ iconClassName="size-5 shrink-0"
+ variant="plain"
+ content={
+ files.length > 0
+ ? null
+ : "JPG or PNG, max size of 5MB"
+ }
+ onChange={async ({ file }) =>
+ await handleUpload(file)
+ }
+ disabled={files.length >= maxFiles}
+ maxFileSizeMB={5}
+ />
+ </div>
+ </div>
+ )}
- {/* Rejection details for rejected submissions */}
- {submission.status === "rejected" && (
- <div className="mt-3 flex flex-col gap-2 rounded-lg border border-red-200 bg-red-50 p-4">
- <div className="flex gap-1">
- <span className="text-sm font-medium text-red-900">
- Rejection reason:
- </span>
- <span className="text-sm text-red-800">
- {submission.rejectionReason &&
- REJECT_BOUNTY_SUBMISSION_REASONS[
- submission.rejectionReason as keyof typeof REJECT_BOUNTY_SUBMISSION_REASONS
- ]}
+ {urlRequired && (
+ <div>
+ <div className="flex items-center justify-between">
+ <h2 className="text-sm font-medium text-neutral-900">
+ URLs
+ {urlRequired && " (at least 1 required)"}
+ </h2>
+ <span className="text-xs font-medium text-neutral-500">
+ {
+ (claimForm.watch("urls") ?? []).filter(Boolean)
+ .length
+ }{" "}
+ / {maxUrls}
</span>
</div>
- {submission.rejectionNote && (
- <div className="mt-1">
- <span className="text-sm font-medium text-red-900">
- Note:
- </span>
- <Linkify
- as="p"
- options={{
- target: "_blank",
- rel: "noopener noreferrer nofollow",
- format: (href) => getPrettyUrl(href),
- className:
- "underline underline-offset-4 text-red-400 hover:text-red-700",
- }}
- className="mt-1 whitespace-pre-wrap text-sm text-red-800"
- >
- {submission.rejectionNote}
- </Linkify>
- </div>
- )}
+ <div className={cn("mt-2 flex flex-col gap-2")}>
+ {(() => {
+ const formUrls = claimForm.watch("urls") ?? [];
+ const displayUrls = socialPlatform
+ ? formUrls.slice(1)
+ : formUrls;
+ const rows =
+ displayUrls.length > 0 ? displayUrls : [""];
+ return (
+ <>
+ {rows.map((url, i) => (
+ <div
+ key={i}
+ className="flex items-center gap-2"
+ >
+ <input
+ type="url"
+ placeholder={placeholderUrl}
+ value={url}
+ onChange={(e) => {
+ const prev =
+ claimForm.getValues("urls") ?? [];
+ const idx = socialPlatform
+ ? i + 1
+ : i;
+ const next =
+ prev.length > idx
+ ? [...prev]
+ : [
+ ...prev,
+ ...Array(
+ idx - prev.length + 1,
+ ).fill(""),
+ ];
+ next[idx] = e.target.value;
+ claimForm.setValue("urls", next);
+ }}
+ className="block h-10 w-full rounded-md border-neutral-300 px-3 py-2 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
+ />
+ {rows.length > 1 && (
+ <Button
+ variant="outline"
+ icon={<Trash className="size-4" />}
+ className="w-10 shrink-0 bg-red-50 p-0 text-red-700 hover:bg-red-100"
+ onClick={() => {
+ const prev =
+ claimForm.getValues("urls") ?? [];
+ const idx = socialPlatform
+ ? i + 1
+ : i;
+ claimForm.setValue(
+ "urls",
+ prev.filter((_, j) => j !== idx),
+ );
+ }}
+ />
+ )}
+ </div>
+ ))}
+ {(claimForm.watch("urls") ?? []).length <
+ maxUrls && (
+ <Button
+ variant="secondary"
+ text="Add URL"
+ className="h-8 rounded-lg"
+ onClick={() => {
+ claimForm.setValue("urls", [
+ ...(claimForm.getValues("urls") ??
+ []),
+ "",
+ ]);
+ }}
+ />
+ )}
+ </>
+ );
+ })()}
+ {bounty.submissionRequirements?.url?.domains &&
+ bounty.submissionRequirements.url.domains.length >
+ 0 && (
+ <p className="text-xs text-neutral-400">
+ Allowed domains:{" "}
+ {bounty.submissionRequirements.url.domains.join(
+ ", ",
+ )}
+ </p>
+ )}
+ </div>
</div>
)}
- </div>
- ) : (
- bounty.type === "performance" && (
- <div className="mt-5">
- <BountyPerformance bounty={bounty} />
- </div>
- )
- )}
- </div>
- {bounty.description && (
- <div className="border-border-subtle flex flex-col gap-2 border-t p-6 text-sm max-sm:px-4">
- <span className="text-content-emphasis font-semibold">
- Details
- </span>
- <Markdown className={PROSE_STYLES.default}>
- {bounty.description}
- </Markdown>
- </div>
- )}
+ {socialPlatform && (
+ <SocialContentUrlField bounty={bounty} />
+ )}
- {/* Form */}
- <motion.div
- initial={false}
- animate={{ height: isFormOpen ? "auto" : 0 }}
- transition={{ duration: 0.15 }}
- className={cn(
- "overflow-hidden transition-opacity",
- !isFormOpen && "opacity-0",
- )}
- >
- <div className="border-border-subtle flex flex-col gap-5 border-t p-6 max-sm:px-4">
- {/* Files */}
- {imageRequired && (
<div>
<label
- htmlFor="slug"
+ htmlFor="bounty-submission-description"
className="flex items-center space-x-2"
>
- <h2 className="text-sm font-medium text-neutral-900">
- Files
- {imageRequired && " (at least 1 required)"}
- </h2>
+ <span className="text-sm font-medium text-neutral-900">
+ Provide any additional details (optional)
+ </span>
</label>
- <div
+ <ReactTextareaAutosize
+ id="bounty-submission-description"
className={cn(
- "mt-2 flex h-12 items-center gap-2 transition-[height]",
- files.length === 0 && "h-24",
+ "mt-2 block w-full resize-none rounded-md focus:outline-none sm:text-sm",
+ "border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:ring-neutral-500",
)}
- >
- {files.map((file, idx) => (
- <div
- key={file.id}
- className="border-border-subtle group relative flex aspect-square h-full items-center justify-center rounded-md border bg-white"
- >
- {file.uploading ? (
- <LoadingSpinner className="size-4" />
- ) : (
- <div className="relative size-full overflow-hidden rounded-md">
- <img src={file.url} alt="object-cover" />
- </div>
- )}
- <span className="sr-only">
- {file.file?.name || `File ${idx + 1}`}
- </span>
- <button
- type="button"
- className={cn(
- "absolute right-0 top-0 flex size-[1.125rem] -translate-y-1/2 translate-x-1/2 items-center justify-center",
- "rounded-full border border-neutral-200 bg-white shadow-sm hover:bg-neutral-50 active:scale-95",
- "scale-50 opacity-0 transition-[background-color,transform,opacity] group-hover:scale-100 group-hover:opacity-100",
- )}
- onClick={() => {
- setFiles((prev) =>
- prev.filter((s) => s.id !== file.id),
- );
- }}
- >
- <X className="size-2.5 text-neutral-400" />
- </button>
- </div>
- ))}
-
- <FileUpload
- accept="images"
- className={cn(
- "border-border-subtle h-full w-auto rounded-md border",
- files.length > 0
- ? "aspect-square"
- : "aspect-[unset] w-full",
- )}
- iconClassName="size-5 shrink-0"
- variant="plain"
- content={
- files.length > 0
- ? null
- : "JPG or PNG, max size of 5MB"
+ minRows={2}
+ maxLength={BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH}
+ value={description}
+ onChange={(e) => {
+ const value = e.target.value;
+ if (
+ value.length <=
+ BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH
+ ) {
+ setDescription(value);
}
- onChange={async ({ file }) =>
- await handleUpload(file)
- }
- disabled={files.length >= maxFiles}
- maxFileSizeMB={5}
- />
- </div>
- </div>
- )}
-
- {/* URLs */}
- {urlRequired && (
- <div>
- <label
- htmlFor="slug"
- className="flex items-center justify-between"
- >
- <h2 className="text-sm font-medium text-neutral-900">
- URLs
- {urlRequired && " (at least 1 required)"}
- </h2>
- <span className="text-xs font-medium text-neutral-500">
- {urls.filter((u) => u.url).length} / {maxUrls}
+ }}
+ />
+ <div className="mt-1 text-left">
+ <span className="text-xs text-neutral-500">
+ {BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH -
+ description.length}{" "}
+ / {BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH}
</span>
- </label>
- <div className={cn("mt-2 flex flex-col gap-2")}>
- {urls.map(({ id, url }, idx) => (
- <div key={id} className="flex items-center gap-2">
- <input
- type="url"
- placeholder={placeholderUrl}
- value={url}
- onChange={(e) =>
- setUrls((prev) =>
- prev.map((u) =>
- u.id === id
- ? { ...u, url: e.target.value }
- : u,
- ),
- )
- }
- className="block h-10 w-full rounded-md border-neutral-300 px-3 py-2 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
- />
- {urls.length > 1 && (
- <Button
- variant="outline"
- icon={<Trash className="size-4" />}
- className="w-10 shrink-0 bg-red-50 p-0 text-red-700 hover:bg-red-100"
- onClick={() =>
- setUrls((prev) =>
- prev.filter((s) => s.id !== id),
- )
- }
- />
- )}
- </div>
- ))}
- {urls.length < maxUrls && (
- <Button
- variant="secondary"
- text="Add URL"
- className="h-8 rounded-lg"
- onClick={() =>
- setUrls((prev) => [
- ...prev,
- { id: uuid(), url: "" },
- ])
- }
- />
- )}
- {bounty.submissionRequirements?.url?.domains &&
- bounty.submissionRequirements.url.domains.length >
- 0 && (
- <p className="text-xs text-neutral-400">
- Allowed domains:{" "}
- {bounty.submissionRequirements.url.domains.join(
- ", ",
- )}
- </p>
- )}
</div>
</div>
- )}
+ </div>
+ </motion.div>
+ </>
+ )}
+ </AnimatedSizeContainer>
+ </div>
- {/* Description */}
- <div>
- <label
- htmlFor="slug"
- className="flex items-center space-x-2"
- >
- <h2 className="text-sm font-medium text-neutral-900">
- How did you complete this bounty?
- </h2>
- </label>
- <ReactTextareaAutosize
- className={cn(
- "mt-2 block w-full resize-none rounded-md focus:outline-none sm:text-sm",
- "border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:ring-neutral-500",
- )}
- minRows={2}
- maxLength={BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH}
- value={description}
- onChange={(e) => {
- const value = e.target.value;
- if (
- value.length <=
- BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH
- ) {
- setDescription(value);
+ {/* Action buttons - outside scrollable area */}
+ {bounty.type !== "performance" &&
+ (!submission || submission.status === "draft") &&
+ !success && (
+ <div className="border-t border-neutral-200 bg-white p-4">
+ {isFormOpen ? (
+ <div className="flex items-center justify-between">
+ <Button
+ type="button"
+ variant="outline"
+ text="Cancel"
+ className="h-9 w-fit rounded-lg px-3"
+ onClick={() => {
+ claimForm.reset({ urls: initialUrls });
+ setDescription(submission?.description || "");
+ setFiles(
+ submission?.files && submission.files.length > 0
+ ? submission.files.map((file) => ({
+ id: uuid(),
+ url: file.url,
+ uploading: false,
+ file: undefined,
+ }))
+ : [],
+ );
+ setIsFormOpen(false);
+ }}
+ />
+ <div className="flex gap-2">
+ {!isSocialMetricsBounty && (
+ <Button
+ variant="secondary"
+ text="Save progress"
+ className="h-9 rounded-lg px-3"
+ type="submit"
+ name="draft" // for submitter.name detection above
+ loading={isDraft === true}
+ disabled={
+ fileUploading ||
+ isDraft === false ||
+ socialContentVerifying ||
+ (!!socialPlatform && !socialContentRequirementsMet)
}
- }}
+ />
+ )}
+ <Button
+ variant="primary"
+ text="Submit"
+ className="h-9 rounded-lg px-3"
+ type="submit"
+ name="submit" // for submitter.name detection above
+ loading={isDraft === false}
+ disabled={
+ fileUploading ||
+ isDraft === true ||
+ socialContentVerifying ||
+ (!!socialPlatform && !socialContentRequirementsMet)
+ }
+ disabledTooltip={
+ !hasSubmissionsOpen
+ ? `Submissions are not open yet. They will open on ${formatDate(
+ bounty.submissionsOpenAt!,
+ {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ timeZone: "UTC",
+ },
+ )}.${isSocialMetricsBounty ? "" : " In the meantime, you can save your progress as a draft."}`
+ : socialPlatform && !socialContentRequirementsMet
+ ? "Post must be from your verified account and after the bounty start date."
+ : undefined
+ }
/>
- <div className="mt-1 text-left">
- <span className="text-xs text-neutral-500">
- {BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH -
- description.length}{" "}
- / {BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH}
- </span>
- </div>
</div>
</div>
- </motion.div>
- </>
+ ) : (
+ <>
+ {socialPlatform &&
+ !platformsVerified?.[socialPlatform.value] ? (
+ <SocialAccountNotVerifiedWarning bounty={bounty} />
+ ) : (
+ <Button
+ variant="primary"
+ text={
+ submission ? "Continue submission" : "Claim bounty"
+ }
+ className="w-full rounded-lg"
+ onClick={() => setIsFormOpen(true)}
+ />
+ )}
+ </>
+ )}
+ </div>
)}
- </AnimatedSizeContainer>
- </div>
-
- {/* Action buttons - outside scrollable area */}
- {bounty.type !== "performance" &&
- (!submission || submission.status === "draft") &&
- !success && (
- <div className="border-t border-neutral-200 bg-white p-4">
- {isFormOpen ? (
- <div className="flex items-center justify-between">
- <Button
- type="button"
- variant="outline"
- text="Cancel"
- className="h-9 w-fit rounded-lg px-3"
- onClick={() => setIsFormOpen(false)}
- />
- <div className="flex gap-2">
- <Button
- variant="secondary"
- text="Save progress"
- className="h-9 rounded-lg px-3"
- type="submit"
- name="draft" // for submitter.name detection above
- loading={isDraft === true}
- disabled={fileUploading || isDraft === false}
- />
- <Button
- variant="primary"
- text="Submit"
- className="h-9 rounded-lg px-3"
- type="submit"
- name="submit" // for submitter.name detection above
- loading={isDraft === false}
- disabled={fileUploading || isDraft === true}
- disabledTooltip={
- !hasSubmissionsOpen
- ? `Submissions are not open yet. They will open on ${formatDate(
- bounty.submissionsOpenAt!,
- {
- month: "short",
- day: "numeric",
- year: "numeric",
- timeZone: "UTC",
- },
- )}. In the meantime, you can save your progress as a draft.`
- : undefined
- }
- />
- </div>
- </div>
- ) : (
- <Button
- variant="primary"
- text={submission ? "Continue submission" : "Claim bounty"}
- className="w-full rounded-lg"
- onClick={() => setIsFormOpen(true)}
- />
- )}
- </div>
- )}
- </form>
+ </form>
+ </FormProvider>
</>
);
}
@@ -716,7 +816,9 @@ export function ClaimBountyModal({
setShowModal={rest.setShowModal}
onClose={() => queryParams({ del: "bountyId", scroll: false })}
>
- <ClaimBountyModalContent {...rest} />
+ <ClaimBountyProvider>
+ <ClaimBountyModalContent {...rest} />
+ </ClaimBountyProvider>
</Modal>
);
}
diff --git a/apps/web/ui/partners/bounties/partner-bounty-submission-details-sheet.tsx b/apps/web/ui/partners/bounties/partner-bounty-submission-details-sheet.tsx
new file mode 100644
index 0000000000..b23951fac5
--- /dev/null
+++ b/apps/web/ui/partners/bounties/partner-bounty-submission-details-sheet.tsx
@@ -0,0 +1,225 @@
+"use client";
+
+import { BOUNTY_SUBMISSION_STATUS_BADGES } from "@/lib/bounty/bounty-submission-status-badges";
+import { REJECT_BOUNTY_SUBMISSION_REASONS } from "@/lib/bounty/constants";
+import { resolveBountyDetails } from "@/lib/bounty/utils";
+import { BountySubmissionProps, PartnerBountyProps } from "@/lib/types";
+import {
+ BountyDescription,
+ bountyHasDetails,
+} from "@/ui/partners/bounties/bounty-description";
+import { BountyRewardDescription } from "@/ui/partners/bounties/bounty-reward-description";
+import { BountySocialContentPreview } from "@/ui/partners/bounties/bounty-social-content-preview";
+import { BountySocialMetricsRewardsTable } from "@/ui/partners/bounties/bounty-social-metrics-rewards-table";
+import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
+import { ButtonLink } from "@/ui/placeholders/button-link";
+import { X } from "@/ui/shared/icons";
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+ Button,
+ Sheet,
+ StatusBadge,
+} from "@dub/ui";
+import { Calendar6 } from "@dub/ui/icons";
+import { formatDate, getPrettyUrl } from "@dub/utils";
+import Linkify from "linkify-react";
+import { useParams } from "next/navigation";
+import { Dispatch, SetStateAction, useState } from "react";
+
+interface PartnerBountySubmissionDetailsSheetProps {
+ bounty: PartnerBountyProps;
+ isOpen: boolean;
+ setIsOpen: Dispatch<SetStateAction<boolean>>;
+}
+
+function PartnerBountySubmissionDetailsSheetContent({
+ bounty,
+}: Omit<PartnerBountySubmissionDetailsSheetProps, "isOpen" | "setIsOpen">) {
+ const { programSlug } = useParams();
+
+ const submission = bounty.submission! as BountySubmissionProps;
+ const bountyInfo = resolveBountyDetails(bounty);
+
+ const hasSocialContent =
+ bountyInfo?.hasSocialMetrics && (submission.urls?.length ?? 0) > 0;
+
+ const statusBadge = BOUNTY_SUBMISSION_STATUS_BADGES[submission.status];
+
+ const statusDate =
+ submission.status === "approved"
+ ? submission.reviewedAt
+ : submission.status === "submitted"
+ ? submission.completedAt
+ : submission.status === "rejected"
+ ? submission.reviewedAt
+ : null;
+ const statusLabelWithDate =
+ statusDate != null
+ ? `${statusBadge.label} ${formatDate(statusDate, { month: "short", day: "numeric", year: "numeric" })}`
+ : statusBadge.label;
+
+ return (
+ <div className="relative flex size-full flex-col">
+ <Sheet.Close asChild>
+ <Button
+ variant="outline"
+ icon={<X className="size-5" />}
+ className="absolute right-4 top-4 z-10 h-auto w-fit p-1"
+ />
+ </Sheet.Close>
+ <div className="scrollbar-hide flex min-h-0 flex-1 flex-col overflow-y-auto">
+ {/* Thumbnail header (matches claim-bounty-modal) */}
+ <div className="flex h-[132px] shrink-0 items-center justify-center bg-neutral-100 py-3">
+ <div className="relative size-full">
+ <BountyThumbnailImage bounty={bounty} />
+ </div>
+ </div>
+
+ <div className="flex min-h-0 flex-1 flex-col divide-y divide-neutral-200">
+ {/* Bounty title, ends at, earn, status */}
+ <div className="flex flex-col gap-1 p-5">
+ <Sheet.Title className="text-content-emphasis truncate text-sm font-semibold">
+ {bounty.name ?? "Bounty"}
+ </Sheet.Title>
+ <div className="text-content-subtle flex items-center gap-2 text-sm font-medium">
+ <Calendar6 className="size-3.5 shrink-0" />
+ {bounty.endsAt
+ ? `Ends ${formatDate(bounty.endsAt, { month: "short", day: "numeric", year: "numeric" })}`
+ : "No end date"}
+ </div>
+ <BountyRewardDescription bounty={bounty} className="font-medium" />
+ <StatusBadge
+ variant={statusBadge.variant}
+ icon={statusBadge.icon}
+ className="w-fit rounded-lg py-1.5"
+ >
+ {statusLabelWithDate}
+ </StatusBadge>
+ </div>
+
+ {/* Details accordion (only when there is content; open by default to match design) */}
+ {bountyHasDetails(bounty) && (
+ <Accordion type="single" collapsible className="w-full p-5">
+ <AccordionItem
+ value="details"
+ className="border-none bg-transparent py-0"
+ >
+ <AccordionTrigger className="!text-base font-semibold text-neutral-900">
+ Details
+ </AccordionTrigger>
+ <AccordionContent>
+ <BountyDescription bounty={bounty} hideHeading />
+ </AccordionContent>
+ </AccordionItem>
+ </Accordion>
+ )}
+
+ {submission.status === "rejected" && (
+ <div className="p-5">
+ {submission.rejectionNote && (
+ <div className="rounded-lg border border-red-200 bg-red-50 p-4">
+ <Linkify
+ as="p"
+ options={{
+ target: "_blank",
+ rel: "noopener noreferrer nofollow",
+ format: (href) => getPrettyUrl(href),
+ className:
+ "underline underline-offset-4 text-red-400 hover:text-red-700",
+ }}
+ className="mt-1 whitespace-pre-wrap text-sm text-red-800"
+ >
+ {submission.rejectionNote}
+ </Linkify>
+ </div>
+ )}
+
+ {submission.rejectionReason && (
+ <p className="text-content-subtle text-sm">
+ <span className="font-medium text-neutral-700">
+ Rejection reason:{" "}
+ </span>
+ {REJECT_BOUNTY_SUBMISSION_REASONS[submission.rejectionReason]}
+ </p>
+ )}
+ </div>
+ )}
+
+ {/* Submission section */}
+ {bounty?.type === "submission" && hasSocialContent && (
+ <div className="p-5">
+ <h2 className="text-base font-semibold text-neutral-900">
+ Submission
+ </h2>
+ <div className="mt-3">
+ <BountySocialContentPreview
+ bounty={bounty}
+ submission={submission}
+ />
+ </div>
+ </div>
+ )}
+
+ {bounty?.type === "submission" &&
+ bountyInfo?.hasSocialMetrics &&
+ bounty && (
+ <div className="p-5">
+ <BountySocialMetricsRewardsTable
+ bounty={bounty}
+ submission={submission}
+ titleText="Earnings"
+ />
+ </div>
+ )}
+
+ {submission.status === "approved" && (
+ <div className="mt-auto p-5 pt-2">
+ <ButtonLink
+ href={`/programs/${programSlug}/earnings?type=custom`}
+ target="_blank"
+ variant="secondary"
+ className="mt-3 w-full justify-center text-sm font-medium"
+ >
+ View earnings
+ </ButtonLink>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export function PartnerBountySubmissionDetailsSheet({
+ bounty,
+ isOpen,
+ ...rest
+}: PartnerBountySubmissionDetailsSheetProps) {
+ return (
+ <Sheet open={isOpen} onOpenChange={rest.setIsOpen}>
+ <PartnerBountySubmissionDetailsSheetContent bounty={bounty} {...rest} />
+ </Sheet>
+ );
+}
+
+export function usePartnerBountySubmissionDetailsSheet(
+ bounty: PartnerBountyProps | null,
+) {
+ const [isOpen, setIsOpen] = useState(false);
+ const canOpen = bounty?.submission && bounty.submission.status !== "draft";
+
+ return {
+ partnerBountySubmissionDetailsSheet:
+ canOpen && bounty ? (
+ <PartnerBountySubmissionDetailsSheet
+ bounty={bounty}
+ isOpen={isOpen}
+ setIsOpen={setIsOpen}
+ />
+ ) : null,
+ setPartnerBountySubmissionDetailsSheetOpen: setIsOpen,
+ };
+}
diff --git a/apps/web/ui/partners/reject-bounty-submission-modal.tsx b/apps/web/ui/partners/bounties/reject-bounty-submission-modal.tsx
similarity index 99%
rename from apps/web/ui/partners/reject-bounty-submission-modal.tsx
rename to apps/web/ui/partners/bounties/reject-bounty-submission-modal.tsx
index 5c99fcb346..1c940c7fe8 100644
--- a/apps/web/ui/partners/reject-bounty-submission-modal.tsx
+++ b/apps/web/ui/partners/bounties/reject-bounty-submission-modal.tsx
@@ -2,7 +2,7 @@ import { rejectBountySubmissionAction } from "@/lib/actions/partners/reject-boun
import {
BOUNTY_MAX_SUBMISSION_REJECTION_NOTE_LENGTH,
REJECT_BOUNTY_SUBMISSION_REASONS,
-} from "@/lib/constants/bounties";
+} from "@/lib/bounty/constants";
import { mutatePrefix } from "@/lib/swr/mutate";
import useBounty from "@/lib/swr/use-bounty";
import useWorkspace from "@/lib/swr/use-workspace";
diff --git a/apps/web/ui/partners/bounties/use-claim-bounty-form.ts b/apps/web/ui/partners/bounties/use-claim-bounty-form.ts
new file mode 100644
index 0000000000..21d819f780
--- /dev/null
+++ b/apps/web/ui/partners/bounties/use-claim-bounty-form.ts
@@ -0,0 +1,20 @@
+"use client";
+
+import { createBountySubmissionInputSchema } from "@/lib/zod/schemas/bounties";
+import { useFormContext } from "react-hook-form";
+import * as z from "zod/v4";
+import { useClaimBountyContext } from "./claim-bounty-context";
+
+export type CreateBountySubmissionInput = z.infer<
+ typeof createBountySubmissionInputSchema
+>;
+
+export function useClaimBountyForm() {
+ const form = useFormContext<CreateBountySubmissionInput>();
+ const claim = useClaimBountyContext();
+
+ return {
+ ...form,
+ ...claim,
+ };
+}
diff --git a/apps/web/ui/partners/bounties/use-social-content.ts b/apps/web/ui/partners/bounties/use-social-content.ts
new file mode 100644
index 0000000000..ccac915f67
--- /dev/null
+++ b/apps/web/ui/partners/bounties/use-social-content.ts
@@ -0,0 +1,32 @@
+import { SocialContent } from "@/lib/types";
+import { fetcher } from "@dub/utils";
+import { useParams } from "next/navigation";
+import useSWR from "swr";
+
+interface UseSocialContentParams {
+ bountyId: string;
+ url: string;
+}
+
+export function useSocialContent({ bountyId, url }: UseSocialContentParams) {
+ const { programSlug } = useParams<{ programSlug?: string }>();
+
+ const searchParams = new URLSearchParams({ url });
+
+ const { data, error, isValidating, mutate } = useSWR<SocialContent>(
+ programSlug && bountyId && url
+ ? `/api/partner-profile/programs/${programSlug}/bounties/${bountyId}/social-content-stats?${searchParams.toString()}`
+ : null,
+ fetcher,
+ {
+ revalidateOnFocus: false,
+ },
+ );
+
+ return {
+ data: data ?? null,
+ error,
+ isValidating,
+ mutate,
+ };
+}
diff --git a/apps/web/ui/partners/groups/design/application-form/fields/long-text-field.tsx b/apps/web/ui/partners/groups/design/application-form/fields/long-text-field.tsx
index 635966dc9b..25eed46acd 100644
--- a/apps/web/ui/partners/groups/design/application-form/fields/long-text-field.tsx
+++ b/apps/web/ui/partners/groups/design/application-form/fields/long-text-field.tsx
@@ -27,7 +27,7 @@ export function LongTextField({
<FormControl label={field.label} required={field.required} dir="auto">
<textarea
className={cn(
- "mt-2 block w-full rounded-md text-base md:text-sm focus:outline-none",
+ "mt-2 block w-full rounded-md text-base focus:outline-none md:text-sm",
error
? "border-red-400 pr-10 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500"
: "border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-[var(--brand)] focus:ring-[var(--brand)]",
diff --git a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
index 25fb525d84..b2f4e763be 100644
--- a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
+++ b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
@@ -602,7 +602,7 @@ function RewardSheetContent({
disabledTooltip={
showAdvancedUpsell ? (
<TooltipContent
- title="Advanced reward structures are only available on the Advanced plan and above."
+ title="[Advanced reward structures](https://dub.co/help/article/partner-rewards#adding-reward-conditions) are only available on the Advanced plan and above."
cta="Upgrade to Advanced"
href={`/${workspaceSlug}/upgrade?showPartnersUpgradeModal=true`}
target="_blank"
diff --git a/apps/web/ui/partners/rewards/rewards-logic.tsx b/apps/web/ui/partners/rewards/rewards-logic.tsx
index 8eb65dc669..b549ec04ac 100644
--- a/apps/web/ui/partners/rewards/rewards-logic.tsx
+++ b/apps/web/ui/partners/rewards/rewards-logic.tsx
@@ -1,6 +1,7 @@
"use client";
import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
+import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { REFERRAL_ENABLED_PROGRAM_IDS } from "@/lib/referrals/constants";
import useProgram from "@/lib/swr/use-program";
import useWorkspace from "@/lib/swr/use-workspace";
@@ -94,7 +95,23 @@ export function RewardsLogic({
<Button
className="h-8 rounded-lg"
icon={<ArrowTurnRight2 className="size-4" />}
- text="Add condition"
+ text={
+ <div className="flex items-center gap-2">
+ <span>Add condition</span>
+ {!getPlanCapabilities(plan).canUseAdvancedRewardLogic && (
+ <div
+ className={cn(
+ "rounded-sm px-1.5 py-1 text-[0.625rem] uppercase leading-none",
+ isDefaultReward
+ ? "bg-violet-500/50 text-violet-200"
+ : "bg-violet-50 text-violet-600",
+ )}
+ >
+ Upgrade required
+ </div>
+ )}
+ </div>
+ }
onClick={() => {
const type = getValues("type");
diff --git a/apps/web/ui/referrals/partner-referral-sheet.tsx b/apps/web/ui/referrals/partner-referral-sheet.tsx
index e5c12e31ca..e8831b8e53 100644
--- a/apps/web/ui/referrals/partner-referral-sheet.tsx
+++ b/apps/web/ui/referrals/partner-referral-sheet.tsx
@@ -86,7 +86,7 @@ function ReferralSheetContent({
return (
<>
- <ConfirmReferralStatusChangeModal />
+ {ConfirmReferralStatusChangeModal}
<div className="flex size-full flex-col">
<div className="flex h-16 shrink-0 items-center justify-between border-b border-neutral-200 px-6 py-4">
<Sheet.Title className="text-lg font-semibold">
diff --git a/apps/web/ui/referrals/referral-lead-details.tsx b/apps/web/ui/referrals/referral-lead-details.tsx
index 2fee9b388f..5017730b74 100644
--- a/apps/web/ui/referrals/referral-lead-details.tsx
+++ b/apps/web/ui/referrals/referral-lead-details.tsx
@@ -44,7 +44,7 @@ export function ReferralLeadDetails({
return (
<>
{isInteractive && <EditReferralModal />}
- {isInteractive && !isControlled && <ConfirmReferralStatusChangeModal />}
+ {isInteractive && !isControlled && ConfirmReferralStatusChangeModal}
<div className="border-border-subtle overflow-hidden rounded-xl border bg-white">
<div className="flex items-start justify-between px-4 pt-4">
<div className="relative w-fit shrink-0">
diff --git a/apps/web/ui/webhooks/webhook-event-details-sheet.tsx b/apps/web/ui/webhooks/webhook-event-details-sheet.tsx
index 2c629ec149..41f42086ad 100644
--- a/apps/web/ui/webhooks/webhook-event-details-sheet.tsx
+++ b/apps/web/ui/webhooks/webhook-event-details-sheet.tsx
@@ -72,9 +72,7 @@ function WebhookEventDetailsSheetContent({
</Sheet.Close>
</div>
<div className="group flex items-center gap-2">
- <p className="font-mono text-sm text-neutral-500">
- {event.event_id}
- </p>
+ <p className="font-mono text-sm text-neutral-500">{event.event_id}</p>
<ButtonTooltip
tooltipProps={{
content: "Copy event ID",
diff --git a/apps/web/vercel.json b/apps/web/vercel.json
index 2293e47fa4..77584bd042 100644
--- a/apps/web/vercel.json
+++ b/apps/web/vercel.json
@@ -51,6 +51,10 @@
{
"path": "/api/cron/payouts/reminders/program-owners",
"schedule": "0 13 25-31,1-5 * *"
+ },
+ {
+ "path": "/api/cron/bounties/queue-sync-social-metrics",
+ "schedule": "0 * * * *"
}
],
"functions": {
diff --git a/packages/prisma/client.ts b/packages/prisma/client.ts
index d771c2cb20..141719a72e 100644
--- a/packages/prisma/client.ts
+++ b/packages/prisma/client.ts
@@ -2,6 +2,7 @@ export * from "@prisma/client";
export {
BountyPerformanceScope,
+ BountySubmissionFrequency,
BountySubmissionRejectionReason,
BountySubmissionStatus,
BountyType,
diff --git a/packages/prisma/schema/bounty.prisma b/packages/prisma/schema/bounty.prisma
index 0d5f5df827..5f49b42563 100644
--- a/packages/prisma/schema/bounty.prisma
+++ b/packages/prisma/schema/bounty.prisma
@@ -23,23 +23,32 @@ enum BountySubmissionRejectionReason {
other
}
+enum BountySubmissionFrequency {
+ day
+ week
+ month
+}
+
model Bounty {
- id String @id @default(cuid())
- programId String
- workflowId String? @unique
- name String
- description String? @db.Text
- type BountyType
- startsAt DateTime
- endsAt DateTime?
- submissionsOpenAt DateTime?
- rewardAmount Int?
- rewardDescription String?
- performanceScope BountyPerformanceScope?
- submissionRequirements Json?
- archivedAt DateTime?
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ id String @id @default(cuid())
+ programId String
+ workflowId String? @unique
+ name String
+ description String? @db.Text
+ type BountyType
+ startsAt DateTime
+ endsAt DateTime?
+ submissionsOpenAt DateTime?
+ submissionFrequency BountySubmissionFrequency?
+ maxSubmissions Int @default(1)
+ rewardAmount Int?
+ rewardDescription String?
+ performanceScope BountyPerformanceScope?
+ submissionRequirements Json?
+ socialMetricsLastSyncedAt DateTime?
+ archivedAt DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
submissions BountySubmission[]
groups BountyGroup[]
@@ -63,23 +72,25 @@ model BountyGroup {
}
model BountySubmission {
- id String @id @default(cuid())
- programId String
- partnerId String
- bountyId String
- performanceCount Int?
- commissionId String? @unique
- userId String?
- description String? @db.Text
- status BountySubmissionStatus @default(draft)
- rejectionReason BountySubmissionRejectionReason?
- rejectionNote String? @db.Text
- files Json?
- urls Json?
- completedAt DateTime?
- reviewedAt DateTime?
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ id String @id @default(cuid())
+ programId String
+ partnerId String
+ bountyId String
+ performanceCount Int?
+ socialMetricCount Int?
+ commissionId String? @unique
+ userId String?
+ description String? @db.Text
+ status BountySubmissionStatus @default(draft)
+ rejectionReason BountySubmissionRejectionReason?
+ rejectionNote String? @db.Text
+ files Json?
+ urls Json?
+ socialMetricsLastSyncedAt DateTime?
+ completedAt DateTime?
+ reviewedAt DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
bounty Bounty @relation(fields: [bountyId], references: [id], onDelete: Cascade)
partner Partner @relation(fields: [partnerId], references: [id], onDelete: Cascade)
diff --git a/packages/prisma/schema/platform.prisma b/packages/prisma/schema/platform.prisma
index e9f56d0430..7903a43a91 100644
--- a/packages/prisma/schema/platform.prisma
+++ b/packages/prisma/schema/platform.prisma
@@ -13,6 +13,7 @@ model PartnerPlatform {
type PlatformType
identifier String // The unique identifier for the platform (e.g., username for social platforms, domain for websites)
platformId String? // Platform-specific immutable ID (e.g., YouTube channel ID)
+ avatarUrl String? @db.Text
subscribers BigInt @default(0) // Subscribers/followers for social platforms, also for newsletter subscribers
posts BigInt @default(0)
views BigInt @default(0) // Video views for YouTube, impressions for social platforms, pageviews for websites