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.

Embed Bounties Tab (#3583)

Pedro Ladeiraba2bfc653361
diff --git a/apps/web/app/(ee)/api/embed/referrals/analytics/route.ts b/apps/web/app/(ee)/api/embed/referrals/analytics/route.ts
index a216817e63..98d274db6e 100644
--- a/apps/web/app/(ee)/api/embed/referrals/analytics/route.ts
+++ b/apps/web/app/(ee)/api/embed/referrals/analytics/route.ts
@@ -1,21 +1,33 @@
import { getAnalytics } from "@/lib/analytics/get-analytics";
import { withReferralsEmbedToken } from "@/lib/embed/referrals/auth";
+import { partnerProfileAnalyticsQuerySchema } from "@/lib/zod/schemas/partner-profile";
import { parseFilterValue } from "@dub/utils";
import { NextResponse } from "next/server";
-// GET /api/embed/referrals/analytics – get timeseries analytics for a partner
-export const GET = withReferralsEmbedToken(async ({ links, program }) => {
- if (links.length === 0) {
- return NextResponse.json([]);
- }
+const querySchema = partnerProfileAnalyticsQuerySchema.pick({
+ event: true,
+ start: true,
+ end: true,
+ groupBy: true,
+ saleType: true,
+ interval: true,
+});
- const analytics = await getAnalytics({
- event: "composite",
- groupBy: "timeseries",
- interval: "1y",
- linkId: parseFilterValue(links.map((link) => link.id)),
- dataAvailableFrom: program.startedAt ?? program.createdAt,
- });
+// GET /api/embed/referrals/analytics – get analytics for a partner
+export const GET = withReferralsEmbedToken(
+ async ({ links, program, searchParams }) => {
+ if (links.length === 0) {
+ return NextResponse.json([]);
+ }
- return NextResponse.json(analytics);
-});
+ const parsedQuery = querySchema.parse(searchParams);
+
+ const analytics = await getAnalytics({
+ ...parsedQuery,
+ linkId: parseFilterValue(links.map((link) => link.id)),
+ dataAvailableFrom: program.startedAt ?? program.createdAt,
+ });
+
+ return NextResponse.json(analytics);
+ },
+);
diff --git a/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/social-content-stats/route.ts b/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/social-content-stats/route.ts
new file mode 100644
index 0000000000..4065dc05e7
--- /dev/null
+++ b/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/social-content-stats/route.ts
@@ -0,0 +1,91 @@
+import { DubApiError } from "@/lib/api/errors";
+import { getSocialContent } from "@/lib/api/scrape-creators/get-social-content";
+import { getBountyOrThrow } from "@/lib/bounty/api/get-bounty-or-throw";
+import { resolveBountyDetails } from "@/lib/bounty/utils";
+import { withReferralsEmbedToken } from "@/lib/embed/referrals/auth";
+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/embed/referrals/bounties/[bountyId]/social-content-stats
+export const GET = withReferralsEmbedToken(
+ async ({ programEnrollment, searchParams, params }) => {
+ const { bountyId } = params;
+ const { url } = searchParamsSchema.parse(searchParams);
+
+ const { success } = await ratelimit(10, "1 h").limit(
+ `partner-profile:social-content-stats:${programEnrollment.partnerId}`,
+ );
+
+ if (!success) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message: "You've been rate limited. Please try again later.",
+ });
+ }
+
+ const bounty = await getBountyOrThrow({
+ bountyId,
+ programId: programEnrollment.programId,
+ include: {
+ groups: true,
+ },
+ });
+
+ if (bounty.groups.length > 0) {
+ const isInGroup = bounty.groups.some(
+ ({ groupId }) => groupId === programEnrollment.groupId,
+ );
+
+ if (!isInGroup) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "You are not allowed to access this bounty.",
+ });
+ }
+ }
+
+ const now = new Date();
+
+ if (bounty.startsAt && bounty.startsAt > now) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This bounty is not yet available.",
+ });
+ }
+
+ if (bounty.endsAt && bounty.endsAt < now) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This bounty is no longer available.",
+ });
+ }
+
+ if (bounty.archivedAt) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This bounty is archived.",
+ });
+ }
+
+ 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/embed/referrals/bounties/[bountyId]/upload/route.ts b/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/upload/route.ts
new file mode 100644
index 0000000000..f3955af166
--- /dev/null
+++ b/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/upload/route.ts
@@ -0,0 +1,33 @@
+import { getBountySubmissionUploadUrl } from "@/lib/bounty/api/get-bounty-submission-upload-url";
+import { withReferralsEmbedToken } from "@/lib/embed/referrals/auth";
+import { NextResponse } from "next/server";
+import * as z from "zod/v4";
+
+const bodySchema = z.object({
+ fileName: z.string().trim().min(1),
+ contentType: z.string().trim().min(1),
+ contentLength: z.number().int().positive(),
+});
+
+// POST /api/embed/referrals/bounties/[bountyId]/upload – get a signed R2 upload URL for a bounty submission
+export const POST = withReferralsEmbedToken(
+ async ({ req, programEnrollment, params }) => {
+ const { bountyId } = params;
+ const { fileName, contentType, contentLength } = bodySchema.parse(
+ await req.json(),
+ );
+
+ const { signedUrl, destinationUrl } = await getBountySubmissionUploadUrl({
+ bountyId,
+ fileName,
+ contentType,
+ contentLength,
+ programEnrollment,
+ });
+
+ return NextResponse.json({
+ signedUrl,
+ destinationUrl,
+ });
+ },
+);
diff --git a/apps/web/app/(ee)/api/embed/referrals/earnings/route.ts b/apps/web/app/(ee)/api/embed/referrals/earnings/route.ts
index 819d4a6bb8..208e3ce307 100644
--- a/apps/web/app/(ee)/api/embed/referrals/earnings/route.ts
+++ b/apps/web/app/(ee)/api/embed/referrals/earnings/route.ts
@@ -1,66 +1,77 @@
-import { obfuscateCustomerEmail } from "@/lib/api/partner-profile/obfuscate-customer-email";
-import { REFERRALS_EMBED_EARNINGS_LIMIT } from "@/lib/constants/misc";
+import { getEarningsForPartner } from "@/lib/api/partner-profile/get-earnings-for-partner";
import { withReferralsEmbedToken } from "@/lib/embed/referrals/auth";
-import { generateRandomName } from "@/lib/names";
-import { PartnerEarningsSchema } from "@/lib/zod/schemas/partner-profile";
+import { getPartnerEarningsQuerySchema } from "@/lib/zod/schemas/partner-profile";
import { prisma } from "@dub/prisma";
import { NextResponse } from "next/server";
import * as z from "zod/v4";
+const querySchema = getPartnerEarningsQuerySchema
+ .pick({
+ start: true,
+ end: true,
+ page: true,
+ pageSize: true,
+ interval: true,
+ timezone: true,
+ })
+ .extend({
+ withTotal: z
+ .string()
+ .optional()
+ .transform((v) => v?.toLowerCase() === "true")
+ .default(false),
+ });
+
// GET /api/embed/referrals/earnings – get commissions for a partner from an embed token
export const GET = withReferralsEmbedToken(
async ({ programEnrollment, searchParams }) => {
- const { page } = z
- .object({ page: z.coerce.number().optional().default(1) })
- .parse(searchParams);
+ const { withTotal, start, end, pageSize, page, interval, timezone } =
+ querySchema.parse(searchParams);
- const earnings = await prisma.commission.findMany({
- where: {
- earnings: {
- gt: 0,
- },
+ const [earnings, total] = await Promise.all([
+ getEarningsForPartner({
+ page,
+ pageSize,
+ start,
+ end,
+ interval,
+ timezone,
+ sortBy: "createdAt",
+ sortOrder: "desc",
programId: programEnrollment.programId,
partnerId: programEnrollment.partnerId,
- },
- include: {
- customer: {
- select: {
- id: true,
- email: true,
- name: true,
- },
- },
- link: {
- select: {
- id: true,
- shortLink: true,
- url: true,
- },
- },
- },
- take: REFERRALS_EMBED_EARNINGS_LIMIT,
- skip: (page - 1) * REFERRALS_EMBED_EARNINGS_LIMIT,
- orderBy: {
- createdAt: "desc",
- },
- });
+ customerDataSharingEnabledAt:
+ programEnrollment.customerDataSharingEnabledAt,
+ }),
+
+ withTotal
+ ? prisma.commission.count({
+ where: {
+ earnings: {
+ not: 0,
+ },
+ programId: programEnrollment.programId,
+ partnerId: programEnrollment.partnerId,
+ ...(start || end
+ ? {
+ createdAt: {
+ ...(start && { gte: start }),
+ ...(end && { lte: end }),
+ },
+ }
+ : {}),
+ },
+ })
+ : Promise.resolve(null),
+ ]);
+
+ if (withTotal) {
+ return NextResponse.json({
+ data: earnings,
+ total,
+ });
+ }
- return NextResponse.json(
- z.array(PartnerEarningsSchema).parse(
- earnings.map((e) => ({
- ...e,
- customer: e.customer
- ? {
- ...e.customer,
- email: e.customer.email
- ? programEnrollment.customerDataSharingEnabledAt
- ? e.customer.email
- : obfuscateCustomerEmail(e.customer.email)
- : e.customer.name || generateRandomName(),
- }
- : null,
- })),
- ),
- );
+ return NextResponse.json(earnings);
},
);
diff --git a/apps/web/app/(ee)/api/embed/referrals/earnings/timeseries/route.ts b/apps/web/app/(ee)/api/embed/referrals/earnings/timeseries/route.ts
new file mode 100644
index 0000000000..fb058cb254
--- /dev/null
+++ b/apps/web/app/(ee)/api/embed/referrals/earnings/timeseries/route.ts
@@ -0,0 +1,19 @@
+import { getPartnerEarningsTimeseries } from "@/lib/api/partner-profile/get-partner-earnings-timeseries";
+import { withReferralsEmbedToken } from "@/lib/embed/referrals/auth";
+import { getPartnerEarningsTimeseriesSchema } from "@/lib/zod/schemas/partner-profile";
+import { NextResponse } from "next/server";
+
+// GET /api/embed/referrals/earnings/timeseries - get earnings timeseries for a partner from an embed token
+export const GET = withReferralsEmbedToken(
+ async ({ programEnrollment, searchParams }) => {
+ const filters = getPartnerEarningsTimeseriesSchema.parse(searchParams);
+
+ const timeseries = await getPartnerEarningsTimeseries({
+ partnerId: programEnrollment.partnerId,
+ programId: programEnrollment.programId,
+ filters,
+ });
+
+ return NextResponse.json(timeseries);
+ },
+);
diff --git a/apps/web/app/(ee)/api/embed/referrals/events/route.ts b/apps/web/app/(ee)/api/embed/referrals/events/route.ts
new file mode 100644
index 0000000000..85b601018d
--- /dev/null
+++ b/apps/web/app/(ee)/api/embed/referrals/events/route.ts
@@ -0,0 +1,75 @@
+import { getEvents } from "@/lib/analytics/get-events";
+import { obfuscateCustomerEmail } from "@/lib/api/partner-profile/obfuscate-customer-email";
+import { withReferralsEmbedToken } from "@/lib/embed/referrals/auth";
+import { generateRandomName } from "@/lib/names";
+import {
+ partnerProfileEventsQuerySchema,
+ PartnerProfileLinkSchema,
+} from "@/lib/zod/schemas/partner-profile";
+import { parseFilterValue } from "@dub/utils";
+import { NextResponse } from "next/server";
+import * as z from "zod/v4";
+
+const querySchema = partnerProfileEventsQuerySchema.pick({
+ event: true,
+ start: true,
+ end: true,
+ saleType: true,
+ limit: true,
+ page: true,
+ sortBy: true,
+});
+
+// GET /api/embed/referrals/events – get paginated events for a partner
+export const GET = withReferralsEmbedToken(
+ async ({ links, program, programEnrollment, searchParams }) => {
+ if (links.length === 0) {
+ return NextResponse.json([]);
+ }
+
+ const parsedQuery = querySchema.parse(searchParams);
+
+ const events = await getEvents({
+ ...parsedQuery,
+ workspaceId: program.workspaceId,
+ linkId: parseFilterValue(links.map((link) => link.id)),
+ dataAvailableFrom: program.startedAt ?? program.createdAt,
+ });
+
+ const { customerDataSharingEnabledAt } = programEnrollment;
+
+ const response = events.map((event) => {
+ // don't return ip address for partner profile
+ // @ts-ignore – ip is deprecated but present in the data
+ const { ip, click, customer, ...eventRest } = event;
+ const { ip: _, ...clickRest } = click;
+
+ return {
+ ...eventRest,
+ click: clickRest,
+ link: event?.link ? PartnerProfileLinkSchema.parse(event.link) : null,
+ ...(customer && {
+ customer: z
+ .object({
+ id: z.string(),
+ email: z.string(),
+ ...(customerDataSharingEnabledAt && { name: z.string() }),
+ })
+ .parse({
+ ...customer,
+ email: customer.email
+ ? customerDataSharingEnabledAt
+ ? customer.email
+ : obfuscateCustomerEmail(customer.email)
+ : customer.name || generateRandomName(),
+ ...(customerDataSharingEnabledAt && {
+ name: customer.name || generateRandomName(),
+ }),
+ }),
+ }),
+ };
+ });
+
+ return NextResponse.json(response);
+ },
+);
diff --git a/apps/web/app/(ee)/api/embed/referrals/leaderboard/route.ts b/apps/web/app/(ee)/api/embed/referrals/leaderboard/route.ts
index 10db3525a2..ef5211e6aa 100644
--- a/apps/web/app/(ee)/api/embed/referrals/leaderboard/route.ts
+++ b/apps/web/app/(ee)/api/embed/referrals/leaderboard/route.ts
@@ -24,8 +24,6 @@ export const GET = withReferralsEmbedToken(async ({ program }) => {
const response = partners.map((partner) => ({
id: partner.id,
- name: generateRandomName(partner.id),
- image: `${OG_AVATAR_URL}${partner.id}`,
totalCommissions: Number(partner.totalCommissions),
}));
diff --git a/apps/web/app/(ee)/api/embed/referrals/submissions/route.ts b/apps/web/app/(ee)/api/embed/referrals/submissions/route.ts
new file mode 100644
index 0000000000..1ba4bd3606
--- /dev/null
+++ b/apps/web/app/(ee)/api/embed/referrals/submissions/route.ts
@@ -0,0 +1,57 @@
+import { parseRequestBody } from "@/lib/api/utils";
+import { BountySubmissionHandler } from "@/lib/bounty/api/create-bounty-submission";
+import { withReferralsEmbedToken } from "@/lib/embed/referrals/auth";
+import { createBountySubmissionInputSchema } from "@/lib/zod/schemas/bounties";
+import { prisma } from "@dub/prisma";
+import { NextResponse } from "next/server";
+
+// POST /api/embed/referrals/submissions – submit a bounty via embed token
+export const POST = withReferralsEmbedToken(
+ async ({ req, programEnrollment }) => {
+ const parsedInput = createBountySubmissionInputSchema
+ .omit({ programId: true })
+ .superRefine((data, ctx) => {
+ data.urls.forEach((value, index) => {
+ try {
+ const protocol = new URL(value).protocol;
+ if (protocol !== "http:" && protocol !== "https:") {
+ ctx.addIssue({
+ code: "custom",
+ path: ["urls", index],
+ message: "URL must use http or https.",
+ });
+ }
+ } catch {
+ ctx.addIssue({
+ code: "custom",
+ path: ["urls", index],
+ message: "Invalid URL.",
+ });
+ }
+ });
+ })
+ .parse(await parseRequestBody(req));
+
+ const partner = await prisma.partner.findUniqueOrThrow({
+ where: {
+ id: programEnrollment.partnerId,
+ },
+ select: {
+ id: true,
+ name: true,
+ image: true,
+ email: true,
+ },
+ });
+
+ const submissionHandler = new BountySubmissionHandler({
+ ...parsedInput,
+ programId: programEnrollment.programId,
+ partner,
+ });
+
+ const submission = await submissionHandler.submit();
+
+ return NextResponse.json(submission);
+ },
+);
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 e0950bf998..c9622f3ed0 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
@@ -1,90 +1,20 @@
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
import { withPartnerProfile } from "@/lib/auth/partner";
-import { aggregatePartnerLinksStats } from "@/lib/partners/aggregate-partner-links-stats";
-import { PartnerBountySchema } from "@/lib/zod/schemas/partner-profile";
-import { prisma } from "@dub/prisma";
+import { getBountiesForPartner } from "@/lib/bounty/api/get-bounties-for-partner";
import { NextResponse } from "next/server";
-import * as z from "zod/v4";
// GET /api/partner-profile/programs/[programId]/bounties – get available bounties for an enrolled program
-export const GET = withPartnerProfile(
- async ({ partner, params, searchParams }) => {
- const { program, totalCommissions, groupId, links } =
- await getProgramEnrollmentOrThrow({
- partnerId: partner.id,
- programId: params.programId,
- include: {
- program: true,
- links: true,
- },
- });
+export const GET = withPartnerProfile(async ({ partner, params }) => {
+ const programEnrollment = await getProgramEnrollmentOrThrow({
+ partnerId: partner.id,
+ programId: params.programId,
+ include: {
+ program: true,
+ links: true,
+ },
+ });
- const now = new Date();
- const partnerGroupId = groupId || program.defaultGroupId;
+ const bounties = await getBountiesForPartner(programEnrollment);
- const bounties = await prisma.bounty.findMany({
- where: {
- programId: program.id,
- startsAt: {
- lte: now,
- },
- // If bounty has no groups, it's available to all partners
- // If bounty has groups, only partners in those groups can see it
- AND: [
- {
- OR: [
- {
- groups: {
- none: {},
- },
- },
- {
- groups: {
- some: {
- groupId: partnerGroupId,
- },
- },
- },
- ],
- },
- ],
- },
- include: {
- workflow: {
- select: {
- triggerConditions: true,
- },
- },
- submissions: {
- where: {
- partnerId: partner.id,
- },
- include: {
- commission: {
- select: {
- id: true,
- earnings: true,
- status: true,
- createdAt: true,
- },
- },
- },
- },
- },
- });
-
- return NextResponse.json(
- z.array(PartnerBountySchema).parse(
- bounties.map((bounty) => ({
- ...bounty,
- submission: bounty.submissions?.[0] || null,
- performanceCondition: bounty.workflow?.triggerConditions?.[0] || null,
- partner: {
- ...aggregatePartnerLinksStats(links),
- totalCommissions,
- },
- })),
- ),
- );
- },
-);
+ return NextResponse.json(bounties);
+});
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/earnings/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/earnings/route.ts
index 30d94badaf..ab10116d8a 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/earnings/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/earnings/route.ts
@@ -1,103 +1,28 @@
-import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";
-import { obfuscateCustomerEmail } from "@/lib/api/partner-profile/obfuscate-customer-email";
+import { getEarningsForPartner } from "@/lib/api/partner-profile/get-earnings-for-partner";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
import { withPartnerProfile } from "@/lib/auth/partner";
-import { generateRandomName } from "@/lib/names";
-import {
- PartnerEarningsSchema,
- getPartnerEarningsQuerySchema,
-} from "@/lib/zod/schemas/partner-profile";
-import { prisma } from "@dub/prisma";
+import { getPartnerEarningsQuerySchema } from "@/lib/zod/schemas/partner-profile";
import { NextResponse } from "next/server";
-import * as z from "zod/v4";
// GET /api/partner-profile/programs/[programId]/earnings – get earnings for a partner in a program enrollment
export const GET = withPartnerProfile(
async ({ partner, params, searchParams }) => {
- const { program, customerDataSharingEnabledAt } =
+ const { programId, partnerId, customerDataSharingEnabledAt } =
await getProgramEnrollmentOrThrow({
partnerId: partner.id,
programId: params.programId,
- include: {
- program: true,
- },
+ include: {},
});
- const {
- page = 1,
- pageSize,
- type,
- status,
- sortBy,
- sortOrder,
- linkId,
- customerId,
- payoutId,
- interval,
- start,
- end,
- timezone,
- } = getPartnerEarningsQuerySchema.parse(searchParams);
+ const parsedQuery = getPartnerEarningsQuerySchema.parse(searchParams);
- const { startDate, endDate } = getStartEndDates({
- interval,
- start,
- end,
- timezone,
+ const earnings = await getEarningsForPartner({
+ ...parsedQuery,
+ programId,
+ partnerId,
+ customerDataSharingEnabledAt,
});
- const earnings = await prisma.commission.findMany({
- where: {
- earnings: {
- not: 0,
- },
- programId: program.id,
- partnerId: partner.id,
- status,
- type,
- linkId,
- customerId,
- payoutId,
- createdAt: {
- gte: startDate,
- lte: endDate,
- },
- },
- include: {
- customer: true,
- link: {
- select: {
- id: true,
- shortLink: true,
- url: true,
- },
- },
- },
- skip: (page - 1) * pageSize,
- take: pageSize,
- orderBy: { [sortBy]: sortOrder },
- });
-
- const data = z.array(PartnerEarningsSchema).parse(
- earnings.map((e) => {
- // fallback to a random name if the customer doesn't have an email
- const customerEmail =
- e.customer?.email || e.customer?.name || generateRandomName();
- return {
- ...e,
- customer: e.customer
- ? {
- ...e.customer,
- email: customerDataSharingEnabledAt
- ? customerEmail
- : obfuscateCustomerEmail(customerEmail),
- country: e.customer?.country,
- }
- : null,
- };
- }),
- );
-
- return NextResponse.json(data);
+ return NextResponse.json(earnings);
},
);
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/activity.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/activity.tsx
index 1c1ec7b1c3..76eac63bd6 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/activity.tsx
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/activity.tsx
@@ -5,25 +5,27 @@ import { AnalyticsTimeseries } from "dub/models/components";
import { SVGProps, useId } from "react";
import useSWR from "swr";
import { useEmbedToken } from "../../embed/use-embed-token";
+import { useReferralsEmbedData } from "./page-client";
+
+export function ReferralsEmbedActivity() {
+ const {
+ group: { brandColor: color },
+ stats: { clicks, leads, sales, saleAmount },
+ } = useReferralsEmbedData();
-export function ReferralsEmbedActivity({
- clicks,
- leads,
- sales,
- saleAmount,
- color,
-}: {
- clicks: number;
- leads: number;
- sales: number;
- saleAmount: number;
- color?: string | null;
-}) {
const token = useEmbedToken();
const isEmpty = clicks === 0 && leads === 0 && sales === 0;
+
+ const analyticsSearchParams = new URLSearchParams({
+ event: "composite",
+ groupBy: "timeseries",
+ interval: "1y",
+ });
+
const { data: analytics } = useSWR<AnalyticsTimeseries[]>(
- !isEmpty && "/api/embed/referrals/analytics",
+ !isEmpty &&
+ `/api/embed/referrals/analytics?${analyticsSearchParams.toString()}`,
(url) =>
fetcher(url, {
headers: {
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/add-edit-link.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/add-edit-link.tsx
index 54d4b5a308..eece679f6e 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/add-edit-link.tsx
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/add-edit-link.tsx
@@ -1,7 +1,6 @@
import { mutateSuffix } from "@/lib/swr/mutate";
-import { PartnerGroupAdditionalLink, PartnerGroupProps } from "@/lib/types";
+import { PartnerGroupAdditionalLink } from "@/lib/types";
import { Lock } from "@/ui/shared/icons";
-import { Program } from "@dub/prisma/client";
import {
Button,
Combobox,
@@ -22,26 +21,21 @@ import { useEffect, useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { useDebounce } from "use-debounce";
import { useEmbedToken } from "../use-embed-token";
+import { useReferralsEmbedData } from "./page-client";
import { ReferralsEmbedLink } from "./types";
-interface Props {
- program: Pick<Program, "domain" | "url">;
- group: Pick<PartnerGroupProps, "id" | "additionalLinks" | "maxPartnerLinks">;
- link?: ReferralsEmbedLink | null;
- onCancel: () => void;
-}
-
interface FormData {
pathname: string;
key: string;
}
export function ReferralsEmbedCreateUpdateLink({
- program,
- group,
link,
onCancel,
-}: Props) {
+}: {
+ link: ReferralsEmbedLink | null;
+ onCancel: () => void;
+}) {
const token = useEmbedToken();
const { isMobile } = useMediaQuery();
const [, copyToClipboard] = useCopyToClipboard();
@@ -50,6 +44,8 @@ export function ReferralsEmbedCreateUpdateLink({
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [isExactMode, setIsExactMode] = useState(false);
+ const { program, group } = useReferralsEmbedData();
+
const shortLinkDomain = program.domain || "";
const additionalLinks: PartnerGroupAdditionalLink[] =
group.additionalLinks ?? [];
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/detail.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/detail.tsx
new file mode 100644
index 0000000000..f42733cf8b
--- /dev/null
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/detail.tsx
@@ -0,0 +1,217 @@
+"use client";
+
+import {
+ PartnerBountyProps,
+ PartnerBountySubmission,
+ ProgramEnrollmentProps,
+} from "@/lib/types";
+import { BountyDescription } from "@/ui/partners/bounties/bounty-description";
+import {
+ PerformanceBountyProgress,
+ SubmissionBountyProgress,
+} from "@/ui/partners/bounties/bounty-performance";
+import { BountyRewardCriteria } from "@/ui/partners/bounties/bounty-reward-criteria";
+import { BountyRewardDescription } from "@/ui/partners/bounties/bounty-reward-description";
+import { BountyStatusBadge } from "@/ui/partners/bounties/bounty-status-badge";
+import { BountySubmissionRequirements } from "@/ui/partners/bounties/bounty-submission-requirements";
+import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
+import { PlatformType } from "@dub/prisma/client";
+import { ChevronRight, Trophy } from "@dub/ui";
+import { useState } from "react";
+import {
+ BountyEndDate,
+ BountyRewardsTable,
+} from "../../../../partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/bounty-card";
+import { EmbedBountyPerformanceSection } from "./performance-section";
+import { EmbedBountySubmissionDetail } from "./submission-detail";
+import { EmbedBountySubmissionForm } from "./submission-form";
+import { EmbedBountySubmissionsTable } from "./submissions-table";
+
+export type EmbedBountyView =
+ | { mode: "detail" }
+ | { mode: "submission-form"; periodNumber: number }
+ | { mode: "submission-view"; periodNumber: number };
+
+export function EmbedBountyDetail({
+ bounty: initialBounty,
+ partnerPlatforms,
+ programEnrollment,
+ view,
+ setView,
+ onBack,
+ onBountyUpdate,
+}: {
+ bounty: PartnerBountyProps;
+ partnerPlatforms: Array<{
+ type: PlatformType;
+ identifier: string;
+ verifiedAt: Date | null;
+ }>;
+ programEnrollment: Pick<ProgramEnrollmentProps, "createdAt">;
+ view: EmbedBountyView;
+ setView: (v: EmbedBountyView) => void;
+ onBack: () => void;
+ onBountyUpdate?: (bounty: PartnerBountyProps) => void;
+}) {
+ const [bounty, setBounty] = useState<PartnerBountyProps>(initialBounty);
+
+ const hasRewards = bounty.submissions.some((s) => s.commission != null);
+
+ const handleSubmissionSuccess = (newSubmission: PartnerBountySubmission) => {
+ const normalized: PartnerBountySubmission = {
+ ...newSubmission,
+ commission: newSubmission.commission ?? null,
+ };
+ setBounty((prev) => {
+ const existing = prev.submissions.find(
+ (s) => s.periodNumber === normalized.periodNumber,
+ );
+ const updatedSubmissions = existing
+ ? prev.submissions.map((s) =>
+ s.periodNumber === normalized.periodNumber ? normalized : s,
+ )
+ : [...prev.submissions, normalized];
+ const updated = { ...prev, submissions: updatedSubmissions };
+
+ onBountyUpdate?.(updated);
+ return updated;
+ });
+ setView({
+ mode: "submission-view",
+ periodNumber: newSubmission.periodNumber,
+ });
+ };
+
+ const existingSubmission =
+ view.mode === "submission-form"
+ ? bounty.submissions.find((s) => s.periodNumber === view.periodNumber) ??
+ null
+ : null;
+
+ const viewSubmission =
+ view.mode === "submission-view"
+ ? bounty.submissions.find((s) => s.periodNumber === view.periodNumber)
+ : undefined;
+
+ if (view.mode === "submission-form") {
+ return (
+ <EmbedBountySubmissionForm
+ bounty={bounty}
+ partnerPlatforms={partnerPlatforms}
+ periodNumber={
+ (view as { mode: "submission-form"; periodNumber: number })
+ .periodNumber
+ }
+ existingSubmission={existingSubmission}
+ onCancel={() => setView({ mode: "detail" })}
+ onBackToRoot={onBack}
+ onSuccess={handleSubmissionSuccess}
+ />
+ );
+ }
+
+ if (view.mode === "submission-view" && viewSubmission) {
+ return (
+ <EmbedBountySubmissionDetail
+ bounty={bounty}
+ submission={viewSubmission}
+ periodNumber={
+ (view as { mode: "submission-view"; periodNumber: number })
+ .periodNumber
+ }
+ onBack={() => setView({ mode: "detail" })}
+ onBackToRoot={onBack}
+ />
+ );
+ }
+
+ return (
+ <div className="border-border-subtle bg-bg-default overflow-hidden rounded-xl border">
+ <div className="flex items-center gap-1.5 px-4 py-2">
+ <button
+ type="button"
+ aria-label="Back to bounties"
+ title="Back to bounties"
+ onClick={onBack}
+ className="bg-bg-subtle flex size-8 shrink-0 items-center justify-center rounded-lg transition-[transform,background-color] duration-150 hover:bg-bg-emphasis active:scale-95"
+ >
+ <Trophy className="size-4" />
+ </button>
+ <ChevronRight className="text-content-muted size-2.5 shrink-0 [&_*]:stroke-2" />
+ <span className="text-content-emphasis text-sm font-semibold">
+ Bounty details
+ </span>
+ </div>
+
+ <div className="border-border-subtle border-t" />
+
+ <div className="lg:divide-border-subtle grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_minmax(0,400px)] lg:divide-x">
+ <div className="flex flex-col gap-6 p-5">
+ <div className="flex flex-col gap-3">
+ <h2 className="text-content-emphasis text-sm font-semibold">
+ Progress
+ </h2>
+ <div className="border-border-subtle bg-bg-default flex w-full flex-col gap-4 rounded-xl border px-5 pb-4 pt-6">
+ {bounty.type === "performance" ? (
+ <PerformanceBountyProgress
+ bounty={bounty}
+ labelClassName="text-sm"
+ />
+ ) : (
+ <SubmissionBountyProgress
+ bounty={bounty}
+ labelClassName="text-sm"
+ />
+ )}
+ </div>
+ </div>
+
+ {bounty.type === "performance" ? (
+ <EmbedBountyPerformanceSection
+ bounty={bounty}
+ programEnrollment={programEnrollment}
+ />
+ ) : (
+ <EmbedBountySubmissionsTable
+ bounty={bounty}
+ onSubmit={(periodNumber) =>
+ setView({ mode: "submission-form", periodNumber })
+ }
+ onView={(periodNumber) =>
+ setView({ mode: "submission-view", periodNumber })
+ }
+ />
+ )}
+
+ <div className="flex flex-col gap-6 text-sm">
+ <BountySubmissionRequirements bounty={bounty} />
+ <BountyRewardCriteria bounty={bounty} />
+ <BountyDescription bounty={bounty} />
+ </div>
+ </div>
+
+ <div className="border-border-subtle flex flex-col gap-4 border-t p-5 lg:border-t-0">
+ <div className="bg-bg-subtle relative flex h-[132px] items-center justify-center overflow-hidden rounded-lg">
+ <div className="relative size-full">
+ <BountyThumbnailImage bounty={bounty} />
+ </div>
+ <BountyStatusBadge bounty={bounty} />
+ </div>
+
+ <div className="flex flex-col gap-1">
+ <h3 className="text-content-emphasis text-sm font-semibold">
+ {bounty.name}
+ </h3>
+
+ <BountyEndDate bounty={bounty} />
+ <BountyRewardDescription bounty={bounty} className="font-medium" />
+ </div>
+
+ {hasRewards && (
+ <BountyRewardsTable bounty={bounty} className="border-t pt-4" />
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/index.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/index.tsx
new file mode 100644
index 0000000000..dcf2dbd6d1
--- /dev/null
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/index.tsx
@@ -0,0 +1,104 @@
+"use client";
+
+import { PartnerBountyProps } from "@/lib/types";
+import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
+import { TAB_ITEM_ANIMATION_SETTINGS } from "@dub/ui";
+import { Trophy } from "@dub/ui/icons";
+import { AnimatePresence, motion } from "motion/react";
+import { useState } from "react";
+import {
+ BountyEndDate,
+ PartnerBountyCard,
+} from "../../../../partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/bounty-card";
+import { useReferralsEmbedData } from "../page-client";
+import { EmbedBountyDetail, EmbedBountyView } from "./detail";
+
+export function ReferralsEmbedBounties() {
+ const {
+ bounties: initialBounties,
+ partnerPlatforms,
+ programEnrollment,
+ } = useReferralsEmbedData();
+
+ const [bounties, setBounties] =
+ useState<PartnerBountyProps[]>(initialBounties);
+ const [selectedBounty, setSelectedBounty] =
+ useState<PartnerBountyProps | null>(null);
+ const [view, setView] = useState<EmbedBountyView>({ mode: "detail" });
+
+ const animKey = selectedBounty
+ ? view.mode === "detail"
+ ? `detail-${selectedBounty.id}`
+ : view.mode === "submission-form"
+ ? `sf-${selectedBounty.id}-${view.periodNumber}`
+ : `sv-${selectedBounty.id}-${view.periodNumber}`
+ : bounties.length === 0
+ ? "empty"
+ : "list";
+
+ const handleSelectBounty = (bounty: PartnerBountyProps) => {
+ setView({ mode: "detail" });
+ setSelectedBounty(bounty);
+ };
+
+ const handleBack = () => {
+ setView({ mode: "detail" });
+ setSelectedBounty(null);
+ };
+
+ const handleBountyUpdate = (updatedBounty: PartnerBountyProps) => {
+ setSelectedBounty(updatedBounty);
+ setBounties((prev) =>
+ prev.map((b) => (b.id === updatedBounty.id ? updatedBounty : b)),
+ );
+ };
+
+ return (
+ <AnimatePresence mode="wait">
+ <motion.div key={animKey} {...TAB_ITEM_ANIMATION_SETTINGS}>
+ {selectedBounty ? (
+ <EmbedBountyDetail
+ bounty={selectedBounty}
+ partnerPlatforms={partnerPlatforms}
+ programEnrollment={programEnrollment}
+ view={view}
+ setView={setView}
+ onBack={handleBack}
+ onBountyUpdate={handleBountyUpdate}
+ />
+ ) : bounties.length === 0 ? (
+ <AnimatedEmptyState
+ title="No bounties available"
+ description="This program isn't offering any bounties at the moment."
+ cardContent={(idx) => {
+ const Icon = [Trophy, Trophy][idx % 2];
+ return (
+ <>
+ <Icon className="text-content-default size-4" />
+ <div className="bg-bg-emphasis h-2.5 w-24 min-w-0 rounded-sm" />
+ </>
+ );
+ }}
+ />
+ ) : (
+ <div
+ className="grid gap-4"
+ style={{
+ gridTemplateColumns: "repeat(auto-fill, minmax(317px, 1fr))",
+ }}
+ >
+ {bounties.map((bounty) => (
+ <PartnerBountyCard
+ key={bounty.id}
+ bounty={bounty}
+ onClick={() => handleSelectBounty(bounty)}
+ />
+ ))}
+ </div>
+ )}
+ </motion.div>
+ </AnimatePresence>
+ );
+}
+
+export { BountyEndDate };
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/performance-section.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/performance-section.tsx
new file mode 100644
index 0000000000..dcf41526f3
--- /dev/null
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/performance-section.tsx
@@ -0,0 +1,688 @@
+"use client";
+
+import { formatDateTooltip } from "@/lib/analytics/format-date-tooltip";
+import { isCurrencyAttribute } from "@/lib/api/workflows/utils";
+import { PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES } from "@/lib/bounty/api/performance-bounty-scope-attributes";
+import {
+ LeadEvent,
+ PartnerBountyProps,
+ ProgramEnrollmentProps,
+ SaleEvent,
+} from "@/lib/types";
+import { CustomerRowItem } from "@/ui/customers/customer-row-item";
+import {
+ CopyText,
+ LinkLogo,
+ LoadingSpinner,
+ Table,
+ TimestampTooltip,
+ useTable,
+ useTablePagination,
+} from "@dub/ui";
+import { Areas, TimeSeriesChart, XAxis } from "@dub/ui/charts";
+import {
+ cn,
+ currencyFormatter,
+ fetcher,
+ formatDateTimeSmart,
+ getApexDomain,
+ getPrettyUrl,
+ nFormatter,
+} from "@dub/utils";
+import { ColumnDef } from "@tanstack/react-table";
+import { useMemo, useState } from "react";
+import useSWR from "swr";
+import { useEmbedToken } from "../../use-embed-token";
+
+type PerformanceAttribute = keyof typeof PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES;
+
+interface PerformanceRow {
+ id: string;
+ date: string | Date;
+ customer: {
+ id: string;
+ email?: string | null;
+ name?: string | null;
+ avatar?: string | null;
+ } | null;
+ link: {
+ id: string;
+ shortLink: string;
+ url: string;
+ } | null;
+ amount?: number;
+}
+
+const ATTRIBUTE_TO_TABLE_TITLE: Record<PerformanceAttribute, string> = {
+ totalLeads: "Leads generated",
+ totalConversions: "Conversions",
+ totalSaleAmount: "Revenue generated",
+ totalCommissions: "Commissions earned",
+};
+
+const ATTRIBUTE_TO_EVENT_PARAMS: Partial<
+ Record<
+ PerformanceAttribute,
+ { event: "leads" | "sales"; saleType?: "new" | "recurring" }
+ >
+> = {
+ totalLeads: { event: "leads" },
+ totalConversions: { event: "leads", saleType: "new" },
+ totalSaleAmount: { event: "sales" },
+};
+
+const ATTRIBUTE_TO_ANALYTICS_FIELD: Partial<
+ Record<PerformanceAttribute, "leads" | "sales" | "saleAmount">
+> = {
+ totalLeads: "leads",
+ totalConversions: "leads",
+ totalSaleAmount: "sales",
+};
+
+const ATTRIBUTE_TO_CHART_FIELD: Partial<
+ Record<PerformanceAttribute, "leads" | "sales" | "saleAmount">
+> = {
+ totalLeads: "leads",
+ totalConversions: "leads",
+ totalSaleAmount: "saleAmount",
+};
+
+const PAGE_SIZE = 10;
+
+export function EmbedBountyPerformanceSection({
+ bounty,
+ programEnrollment,
+}: {
+ bounty: PartnerBountyProps;
+ programEnrollment: Pick<ProgramEnrollmentProps, "createdAt">;
+}) {
+ return (
+ <div className="flex flex-col gap-6">
+ <div className="flex flex-col gap-3">
+ <h2 className="text-content-emphasis text-sm font-semibold">
+ Performance
+ </h2>
+ <div className="border-border-subtle bg-bg-default rounded-xl border p-5">
+ <EmbedBountyPerformanceChart
+ bounty={bounty}
+ programEnrollment={programEnrollment}
+ />
+ </div>
+ </div>
+ <EmbedBountyPerformanceTable
+ bounty={bounty}
+ programEnrollment={programEnrollment}
+ />
+ </div>
+ );
+}
+
+function EmbedBountyPerformanceChart({
+ bounty,
+ programEnrollment,
+}: {
+ bounty: PartnerBountyProps;
+ programEnrollment: Pick<ProgramEnrollmentProps, "createdAt">;
+}) {
+ const token = useEmbedToken();
+ const attribute = bounty.performanceCondition?.attribute as
+ | PerformanceAttribute
+ | undefined;
+ const isCurrency = attribute ? isCurrencyAttribute(attribute) : false;
+ const isCommissions = attribute === "totalCommissions";
+
+ const startDate = useMemo(
+ () =>
+ bounty.performanceScope === "new"
+ ? new Date(bounty.startsAt)
+ : new Date(programEnrollment.createdAt ?? bounty.startsAt),
+ [bounty.performanceScope, bounty.startsAt, programEnrollment.createdAt],
+ );
+ const endDate = useMemo(
+ () => (bounty.endsAt ? new Date(bounty.endsAt) : new Date()),
+ [bounty.endsAt],
+ );
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+ const authFetcher = (url: string) =>
+ fetcher(url, { headers: { Authorization: `Bearer ${token}` } });
+
+ const analyticsUrl = useMemo(() => {
+ const eventParam = attribute
+ ? ATTRIBUTE_TO_EVENT_PARAMS[attribute]
+ : undefined;
+ const params = new URLSearchParams({
+ event: "composite",
+ groupBy: "timeseries",
+ start: startDate.toISOString(),
+ end: endDate.toISOString(),
+ ...(eventParam?.saleType && { saleType: eventParam.saleType }),
+ });
+ return `/api/embed/referrals/analytics?${params.toString()}`;
+ }, [startDate, endDate, attribute]);
+
+ const earningsTimeseriesUrl = useMemo(() => {
+ const params = new URLSearchParams({
+ start: startDate.toISOString(),
+ end: endDate.toISOString(),
+ timezone,
+ });
+ return `/api/embed/referrals/earnings/timeseries?${params.toString()}`;
+ }, [startDate, endDate, timezone]);
+
+ const { data: analyticsTimeseries, error: analyticsError } = useSWR<any[]>(
+ isCommissions ? null : analyticsUrl,
+ authFetcher,
+ { keepPreviousData: true },
+ );
+
+ const { data: earningsTimeseries, error: earningsError } = useSWR<
+ { start: string; earnings: number }[]
+ >(isCommissions ? earningsTimeseriesUrl : null, authFetcher, {
+ keepPreviousData: true,
+ revalidateOnFocus: false,
+ });
+
+ const data = useMemo(() => {
+ if (isCommissions) {
+ if (!earningsTimeseries) {
+ return undefined;
+ }
+
+ if (!Array.isArray(earningsTimeseries)) {
+ return [];
+ }
+
+ return earningsTimeseries.map(({ start, earnings }) => ({
+ date: new Date(start),
+ values: { main: earnings },
+ }));
+ }
+
+ if (!analyticsTimeseries) {
+ return undefined;
+ }
+
+ if (!attribute) return [];
+
+ const field = ATTRIBUTE_TO_CHART_FIELD[attribute];
+ if (!field || !Array.isArray(analyticsTimeseries)) return [];
+
+ return analyticsTimeseries.map((d: Record<string, any>) => ({
+ date: new Date(d.start),
+ values: { main: d[field] ?? 0 },
+ }));
+ }, [analyticsTimeseries, earningsTimeseries, isCommissions, attribute]);
+
+ const error = isCommissions ? earningsError : analyticsError;
+
+ const chartData = useMemo(() => {
+ if (data === undefined) return undefined;
+ if (data.length > 0) return data;
+
+ const now = new Date();
+ return Array.from({ length: 30 }, (_, i) => ({
+ date: new Date(now.getTime() - (29 - i) * 24 * 60 * 60 * 1000),
+ values: { main: 0 },
+ }));
+ }, [data]);
+
+ return (
+ <div className="h-44 w-full">
+ {chartData ? (
+ <TimeSeriesChart
+ data={chartData}
+ series={[
+ {
+ id: "main",
+ valueAccessor: (d) => d.values.main,
+ colorClassName: "text-[var(--brand,#8e51ff)]",
+ isActive: true,
+ },
+ ]}
+ tooltipContent={(d) => (
+ <div className="flex justify-between gap-6 whitespace-nowrap p-2 text-xs leading-none">
+ <span className="text-content-default font-medium">
+ {formatDateTooltip(d.date, {})}
+ </span>
+ <p className="text-content-subtle text-right">
+ {isCurrency
+ ? currencyFormatter(d.values.main)
+ : nFormatter(d.values.main)}
+ </p>
+ </div>
+ )}
+ >
+ <XAxis showAxisLine={false} />
+ <Areas />
+ </TimeSeriesChart>
+ ) : (
+ <div className="flex size-full items-center justify-center">
+ {error ? (
+ <span className="text-content-subtle text-sm">
+ Failed to load data.
+ </span>
+ ) : (
+ <LoadingSpinner />
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function EmbedBountyPerformanceTable({
+ bounty,
+ programEnrollment,
+}: {
+ bounty: PartnerBountyProps;
+ programEnrollment: Pick<ProgramEnrollmentProps, "createdAt">;
+}) {
+ const attribute = bounty.performanceCondition?.attribute as
+ | PerformanceAttribute
+ | undefined;
+
+ if (attribute === "totalCommissions") {
+ return (
+ <EmbedBountyCommissionsTable
+ bounty={bounty}
+ programEnrollment={programEnrollment}
+ />
+ );
+ }
+
+ return (
+ <EmbedBountyEventsTable
+ bounty={bounty}
+ programEnrollment={programEnrollment}
+ />
+ );
+}
+
+function EmbedBountyEventsTable({
+ bounty,
+ programEnrollment,
+}: {
+ bounty: PartnerBountyProps;
+ programEnrollment: Pick<ProgramEnrollmentProps, "createdAt">;
+}) {
+ const token = useEmbedToken();
+ const [page, setPage] = useState(1);
+
+ const { pagination, setPagination } = useTablePagination({
+ pageSize: PAGE_SIZE,
+ page,
+ onPageChange: setPage,
+ });
+
+ const attribute = bounty.performanceCondition
+ ?.attribute as PerformanceAttribute;
+ const isCurrency = attribute ? isCurrencyAttribute(attribute) : false;
+ const metricLabel = attribute
+ ? PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES[attribute].toLowerCase()
+ : "entries";
+ const tableTitle = attribute
+ ? ATTRIBUTE_TO_TABLE_TITLE[attribute]
+ : "Performance";
+
+ const eventParams = attribute
+ ? ATTRIBUTE_TO_EVENT_PARAMS[attribute]
+ : undefined;
+
+ const startDate = useMemo(
+ () =>
+ bounty.performanceScope === "new"
+ ? new Date(bounty.startsAt)
+ : new Date(programEnrollment.createdAt ?? bounty.startsAt),
+ [bounty.performanceScope, bounty.startsAt, programEnrollment.createdAt],
+ );
+ const endDate = useMemo(
+ () => (bounty.endsAt ? new Date(bounty.endsAt) : new Date()),
+ [bounty.endsAt],
+ );
+
+ const eventsUrl = useMemo(() => {
+ if (!eventParams) return null;
+ const params = new URLSearchParams({
+ event: eventParams.event,
+ start: startDate.toISOString(),
+ end: endDate.toISOString(),
+ limit: String(PAGE_SIZE),
+ page: String(page),
+ ...(eventParams.saleType && { saleType: eventParams.saleType }),
+ });
+ return `/api/embed/referrals/events?${params.toString()}`;
+ }, [eventParams, startDate, endDate, page]);
+
+ const countUrl = useMemo(() => {
+ if (!eventParams || !attribute) return null;
+ const analyticsField = ATTRIBUTE_TO_ANALYTICS_FIELD[attribute];
+ if (!analyticsField) return null;
+ const params = new URLSearchParams({
+ event: "composite",
+ groupBy: "count",
+ start: startDate.toISOString(),
+ end: endDate.toISOString(),
+ ...(eventParams.saleType && { saleType: eventParams.saleType }),
+ });
+ return `/api/embed/referrals/analytics?${params.toString()}`;
+ }, [eventParams, attribute, startDate, endDate]);
+
+ const authFetcher = (url: string) =>
+ fetcher(url, { headers: { Authorization: `Bearer ${token}` } });
+
+ const {
+ data: events,
+ isValidating: isLoading,
+ error,
+ } = useSWR<(LeadEvent | SaleEvent)[]>(eventsUrl, authFetcher, {
+ keepPreviousData: true,
+ });
+
+ const { data: analyticsCount } = useSWR<Record<string, number>>(
+ countUrl,
+ authFetcher,
+ { keepPreviousData: true },
+ );
+
+ const rows = useMemo<PerformanceRow[]>(() => {
+ if (!events) return [];
+ return events.map((event) => ({
+ id: event.eventId,
+ date: event.timestamp,
+ customer: event.customer ?? null,
+ link: event.link ?? null,
+ ...(attribute === "totalSaleAmount" && {
+ amount:
+ ("sale" in event ? event.sale?.amount : undefined) ??
+ ("saleAmount" in event ? event.saleAmount : 0),
+ }),
+ }));
+ }, [events, attribute]);
+
+ const analyticsField = attribute
+ ? ATTRIBUTE_TO_ANALYTICS_FIELD[attribute]
+ : undefined;
+ const eventsCount =
+ analyticsField && analyticsCount ? analyticsCount[analyticsField] : 0;
+
+ const columns = useMemo<ColumnDef<PerformanceRow, any>[]>(() => {
+ const base: ColumnDef<PerformanceRow, any>[] = [
+ {
+ id: "date",
+ header: "Date",
+ accessorKey: "date",
+ minSize: 140,
+ cell: ({ row }) => (
+ <TimestampTooltip
+ timestamp={row.original.date}
+ side="right"
+ rows={["local"]}
+ >
+ <span>{formatDateTimeSmart(row.original.date)}</span>
+ </TimestampTooltip>
+ ),
+ },
+ {
+ id: "customer",
+ header: "Customer",
+ minSize: 220,
+ cell: ({ row }) =>
+ row.original.customer ? (
+ <CustomerRowItem
+ customer={row.original.customer}
+ className="px-4 py-2.5"
+ />
+ ) : (
+ <p className="px-4 py-2.5">-</p>
+ ),
+ },
+ {
+ id: "link",
+ header: "Link",
+ accessorKey: "link",
+ size: 200,
+ cell: ({ row }) =>
+ row.original.link ? (
+ <div className="flex items-center gap-3">
+ <LinkLogo
+ apexDomain={getApexDomain(row.original.link.url)}
+ className="size-4 shrink-0 sm:size-4"
+ />
+ <CopyText
+ value={row.original.link.shortLink}
+ successMessage="Copied link to clipboard!"
+ className="truncate"
+ >
+ <span
+ className="text-content-default truncate"
+ title={row.original.link.shortLink}
+ >
+ {getPrettyUrl(row.original.link.shortLink)}
+ </span>
+ </CopyText>
+ </div>
+ ) : (
+ "-"
+ ),
+ },
+ ];
+
+ if (isCurrency) {
+ base.push({
+ id: "amount",
+ header: "Amount",
+ accessorKey: "amount",
+ cell: ({ row }) => currencyFormatter(row.original.amount ?? 0),
+ });
+ }
+
+ return base;
+ }, [isCurrency]);
+
+ const { table, ...tableProps } = useTable({
+ data: rows,
+ loading: isLoading,
+ error: error ? "Failed to fetch data." : undefined,
+ columns,
+ pagination,
+ onPaginationChange: setPagination,
+ rowCount: eventsCount,
+ thClassName: "border-l-transparent",
+ tdClassName: (columnId: string) =>
+ cn("border-l-transparent", columnId === "customer" && "p-0"),
+ resourceName: () => metricLabel,
+ emptyState: (
+ <div className="text-content-subtle text-sm">
+ No {metricLabel} recorded yet
+ </div>
+ ),
+ emptyWrapperClassName: "h-48",
+ });
+
+ return (
+ <div className="flex flex-col gap-3">
+ <h2 className="text-content-emphasis text-sm font-semibold leading-7 tracking-[-0.36px]">
+ {tableTitle}
+ </h2>
+ <Table
+ {...tableProps}
+ table={table}
+ containerClassName="border-border-subtle"
+ scrollWrapperClassName="min-h-[315px]"
+ />
+ </div>
+ );
+}
+
+function EmbedBountyCommissionsTable({
+ bounty,
+ programEnrollment,
+}: {
+ bounty: PartnerBountyProps;
+ programEnrollment: Pick<ProgramEnrollmentProps, "createdAt">;
+}) {
+ const token = useEmbedToken();
+ const [page, setPage] = useState(1);
+
+ const { pagination, setPagination } = useTablePagination({
+ pageSize: PAGE_SIZE,
+ page,
+ onPageChange: setPage,
+ });
+
+ const startDate = useMemo(
+ () =>
+ bounty.performanceScope === "new"
+ ? new Date(bounty.startsAt)
+ : new Date(programEnrollment.createdAt ?? bounty.startsAt),
+ [bounty.performanceScope, bounty.startsAt, programEnrollment.createdAt],
+ );
+ const endDate = useMemo(
+ () => (bounty.endsAt ? new Date(bounty.endsAt) : new Date()),
+ [bounty.endsAt],
+ );
+
+ const authFetcher = (url: string) =>
+ fetcher(url, { headers: { Authorization: `Bearer ${token}` } });
+
+ const earningsUrl = useMemo(() => {
+ const params = new URLSearchParams({
+ start: startDate.toISOString(),
+ end: endDate.toISOString(),
+ page: String(page),
+ pageSize: String(PAGE_SIZE),
+ withTotal: "true",
+ });
+ return `/api/embed/referrals/earnings?${params.toString()}`;
+ }, [startDate, endDate, page]);
+
+ const {
+ data: earningsResponse,
+ isLoading,
+ error,
+ } = useSWR<{
+ data: {
+ id: string;
+ createdAt: string;
+ earnings: number;
+ customer: { id: string; email: string } | null;
+ link: { id: string; shortLink: string; url: string } | null;
+ }[];
+ total: number;
+ }>(earningsUrl, authFetcher, {
+ keepPreviousData: true,
+ revalidateOnFocus: false,
+ });
+
+ const rows = useMemo<PerformanceRow[]>(
+ () =>
+ earningsResponse?.data.map((e) => ({
+ id: e.id,
+ date: e.createdAt,
+ customer: e.customer,
+ link: e.link ?? null,
+ amount: e.earnings,
+ })) ?? [],
+ [earningsResponse],
+ );
+
+ const columns = useMemo<ColumnDef<PerformanceRow, any>[]>(
+ () => [
+ {
+ id: "date",
+ header: "Date",
+ accessorKey: "date",
+ minSize: 140,
+ cell: ({ row }) => (
+ <TimestampTooltip
+ timestamp={row.original.date}
+ side="right"
+ rows={["local"]}
+ >
+ <span>{formatDateTimeSmart(row.original.date)}</span>
+ </TimestampTooltip>
+ ),
+ },
+ {
+ id: "customer",
+ header: "Customer",
+ minSize: 220,
+ cell: ({ row }) =>
+ row.original.customer ? (
+ <CustomerRowItem
+ customer={row.original.customer}
+ className="px-4 py-2.5"
+ />
+ ) : (
+ <p className="px-4 py-2.5">-</p>
+ ),
+ },
+ {
+ id: "link",
+ header: "Link",
+ size: 200,
+ cell: ({ row }) =>
+ row.original.link ? (
+ <div className="flex items-center gap-3">
+ <LinkLogo
+ apexDomain={getApexDomain(row.original.link.url)}
+ className="size-4 shrink-0 sm:size-4"
+ />
+ <CopyText
+ value={row.original.link.shortLink}
+ successMessage="Copied link to clipboard!"
+ className="truncate"
+ >
+ <span className="truncate" title={row.original.link.shortLink}>
+ {getPrettyUrl(row.original.link.shortLink)}
+ </span>
+ </CopyText>
+ </div>
+ ) : (
+ "-"
+ ),
+ },
+ {
+ id: "earnings",
+ header: "Earnings",
+ accessorKey: "amount",
+ cell: ({ row }) => currencyFormatter(row.original.amount ?? 0),
+ },
+ ],
+ [],
+ );
+
+ const { table, ...tableProps } = useTable({
+ data: rows,
+ loading: isLoading,
+ error: error ? "Failed to fetch data." : undefined,
+ columns,
+ pagination,
+ onPaginationChange: setPagination,
+ rowCount: earningsResponse?.total ?? 0,
+ thClassName: "border-l-transparent",
+ tdClassName: (columnId: string) =>
+ cn("border-l-transparent", columnId === "customer" && "p-0"),
+ resourceName: () => "commissions",
+ emptyState: (
+ <div className="text-content-subtle text-sm">
+ No commissions recorded yet
+ </div>
+ ),
+ emptyWrapperClassName: "h-48",
+ });
+
+ return (
+ <div className="flex flex-col gap-3">
+ <h2 className="text-content-emphasis text-sm font-semibold leading-7 tracking-[-0.36px]">
+ Commissions earned
+ </h2>
+ <Table
+ {...tableProps}
+ table={table}
+ containerClassName="border-border-subtle"
+ scrollWrapperClassName="min-h-[315px]"
+ />
+ </div>
+ );
+}
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submission-detail.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submission-detail.tsx
new file mode 100644
index 0000000000..d09de02a10
--- /dev/null
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submission-detail.tsx
@@ -0,0 +1,293 @@
+"use client";
+
+import { REJECT_BOUNTY_SUBMISSION_REASONS } from "@/lib/bounty/constants";
+import { getPeriodLabel } from "@/lib/bounty/periods";
+import { BOUNTY_SUBMISSION_STATUS_BADGES } from "@/lib/bounty/submission-status";
+import { resolveBountyDetails } from "@/lib/bounty/utils";
+import { PartnerBountyProps, PartnerBountySubmission } from "@/lib/types";
+import { BountySocialMetricsRewardsTable } from "@/ui/partners/bounties/bounty-social-metrics-rewards-table";
+import {
+ SocialContentPreview,
+ SubmissionRewardTable,
+} from "@/ui/partners/bounties/bounty-submission-details-sheet";
+import { ChevronRight, CopyButton, StatusBadge, Trophy } from "@dub/ui";
+import { formatDate } from "@dub/utils";
+import { Fragment } from "react";
+import { toast } from "sonner";
+
+export function EmbedBountySubmissionDetail({
+ bounty,
+ submission,
+ periodNumber,
+ onBack,
+ onBackToRoot,
+}: {
+ bounty: PartnerBountyProps;
+ submission: PartnerBountySubmission;
+ periodNumber: number;
+ onBack: () => void;
+ onBackToRoot: () => void;
+}) {
+ const title =
+ bounty.maxSubmissions > 1
+ ? `Submission (${getPeriodLabel(bounty.submissionFrequency, periodNumber - 1)})`
+ : "Submission";
+
+ return (
+ <div className="border-border-subtle bg-bg-default overflow-hidden rounded-xl border">
+ <div className="flex items-center gap-1.5 px-4 py-2">
+ <button
+ type="button"
+ aria-label="Back to bounties"
+ title="Back to bounties"
+ onClick={onBackToRoot}
+ className="bg-bg-subtle flex size-8 shrink-0 items-center justify-center rounded-lg transition-[transform,background-color] duration-150 hover:bg-bg-emphasis active:scale-95"
+ >
+ <Trophy className="size-4" />
+ </button>
+ <ChevronRight className="text-content-muted size-2.5 shrink-0 [&_*]:stroke-2" />
+ <button
+ type="button"
+ aria-label="Back to bounty details"
+ title="Back to bounty details"
+ onClick={onBack}
+ className="text-content-default hover:text-content-emphasis shrink-0 text-sm font-medium transition-colors"
+ >
+ Bounty details
+ </button>
+ <ChevronRight className="text-content-muted size-2.5 shrink-0 [&_*]:stroke-2" />
+ <span className="text-content-emphasis min-w-0 truncate text-sm font-semibold">
+ {title}
+ </span>
+ </div>
+
+ <div className="border-border-subtle border-t" />
+
+ <div className="divide-border-subtle grid grid-cols-1 divide-y lg:grid-cols-[minmax(0,1fr)_minmax(0,400px)] lg:divide-x lg:divide-y-0">
+ <SubmissionLeftColumn bounty={bounty} submission={submission} />
+ <SubmissionRightColumn bounty={bounty} submission={submission} />
+ </div>
+ </div>
+ );
+}
+
+function SubmissionLeftColumn({
+ bounty,
+ submission,
+}: {
+ bounty: PartnerBountyProps;
+ submission: PartnerBountySubmission;
+}) {
+ const bountyInfo = resolveBountyDetails(bounty);
+
+ return (
+ <div className="flex flex-col gap-5 p-5">
+ <SocialContentPreview bounty={bounty} submission={submission} />
+
+ {bountyInfo?.hasSocialMetrics ? null : (
+ <SubmissionRewardTable submission={submission} />
+ )}
+
+ {(Boolean(submission.files?.length) ||
+ (Boolean(submission.urls?.length) && !bountyInfo?.hasSocialMetrics) ||
+ submission.description) && (
+ <div className="flex flex-col gap-4">
+ {!bountyInfo?.hasSocialMetrics && (
+ <h2 className="text-content-emphasis text-base font-semibold">
+ Submitted content
+ </h2>
+ )}
+
+ {Boolean(submission.files?.length) && (
+ <div>
+ <h3 className="text-content-default text-sm font-medium">
+ Images
+ </h3>
+ <div className="mt-2 flex flex-wrap gap-3">
+ {submission.files!.map((file, idx) => (
+ <a
+ key={idx}
+ className="border-border-subtle hover:border-border-default bg-bg-default group relative flex size-14 items-center justify-center rounded-md border"
+ target="_blank"
+ href={file.url}
+ rel="noopener noreferrer"
+ >
+ <div className="relative size-full overflow-hidden rounded-md">
+ <img
+ src={file.url}
+ alt={file.fileName || `File ${idx + 1}`}
+ className="object-cover"
+ />
+ </div>
+ <span className="sr-only">
+ {file.fileName || `File ${idx + 1}`}
+ </span>
+ </a>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {Boolean(submission.urls?.length) &&
+ !bountyInfo?.hasSocialMetrics && (
+ <div>
+ <h3 className="text-content-default text-sm font-medium">
+ URLs
+ </h3>
+ <div className="mt-2 flex flex-col gap-2">
+ {submission.urls?.map((url, idx) => (
+ <div
+ className="relative"
+ key={`${submission.id}-${idx}-${url}`}
+ >
+ <div className="border-border-subtle block w-full rounded-lg border px-3 py-2 pl-10 pr-12">
+ <a
+ href={url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-content-emphasis block cursor-alias truncate text-sm font-normal decoration-dotted underline-offset-2 hover:underline"
+ >
+ {url}
+ </a>
+ </div>
+ <div className="absolute inset-y-0 left-0 flex items-center pl-2.5">
+ <div className="bg-bg-subtle text-content-subtle flex size-6 items-center justify-center rounded-full text-xs font-medium">
+ {idx + 1}
+ </div>
+ </div>
+ <div className="absolute inset-y-0 right-0 flex items-center pr-2.5">
+ <CopyButton
+ value={url}
+ onCopy={() =>
+ toast.success("URL copied to clipboard!")
+ }
+ />
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {submission.description && (
+ <div>
+ <h3 className="text-content-default text-sm font-medium">
+ Provide any additional details (optional)
+ </h3>
+ <p className="text-content-subtle mt-2 whitespace-pre-wrap text-sm">
+ {submission.description}
+ </p>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function SubmissionRightColumn({
+ bounty,
+ submission,
+}: {
+ bounty: PartnerBountyProps;
+ submission: PartnerBountySubmission;
+}) {
+ const bountyInfo = resolveBountyDetails(bounty);
+ const statusBadge = BOUNTY_SUBMISSION_STATUS_BADGES[submission.status];
+ const submittedDate = submission.completedAt ?? submission.createdAt;
+
+ const textValue = (text: string) => (
+ <span className="text-content-emphasis text-sm font-medium">{text}</span>
+ );
+
+ const details: { label: string; value: React.ReactNode }[] = [];
+
+ if (statusBadge) {
+ details.push({
+ label: "Status",
+ value: (
+ <StatusBadge
+ variant={statusBadge.variant}
+ icon={statusBadge.icon}
+ className="w-fit rounded-lg py-1"
+ >
+ {submission.status === "submitted"
+ ? "Pending review"
+ : statusBadge.label}
+ </StatusBadge>
+ ),
+ });
+ }
+
+ if (submittedDate) {
+ details.push({
+ label: "Submitted",
+ value: textValue(
+ formatDate(submittedDate, {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ }),
+ ),
+ });
+ }
+
+ if (submission.reviewedAt) {
+ details.push({
+ label: "Reviewed",
+ value: textValue(
+ formatDate(submission.reviewedAt, {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ }),
+ ),
+ });
+ }
+
+ if (submission.rejectionReason) {
+ details.push({
+ label: "Rejection reason",
+ value: textValue(
+ REJECT_BOUNTY_SUBMISSION_REASONS[submission.rejectionReason] ??
+ submission.rejectionReason,
+ ),
+ });
+ }
+
+ return (
+ <div className="flex flex-col gap-5 p-5">
+ <div>
+ <h2 className="text-content-emphasis text-base font-semibold">
+ Details
+ </h2>
+ <div className="mt-3 grid grid-cols-2 items-center gap-x-14 gap-y-1">
+ {details.map(({ label, value }) => (
+ <Fragment key={label}>
+ <span className="text-content-subtle text-sm font-medium">
+ {label}
+ </span>
+ <div>{value}</div>
+ </Fragment>
+ ))}
+ </div>
+ </div>
+
+ {submission.rejectionNote && (
+ <div className="bg-bg-attention rounded-lg p-4">
+ <p className="text-content-attention whitespace-pre-wrap text-sm leading-6">
+ {submission.rejectionNote}
+ </p>
+ </div>
+ )}
+
+ {bountyInfo?.hasSocialMetrics &&
+ ["draft", "submitted"].includes(submission.status) && (
+ <BountySocialMetricsRewardsTable
+ bounty={bounty}
+ submission={submission}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submission-fields.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submission-fields.tsx
new file mode 100644
index 0000000000..c7113915bf
--- /dev/null
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submission-fields.tsx
@@ -0,0 +1,462 @@
+"use client";
+
+import {
+ BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH,
+ BOUNTY_MAX_SUBMISSION_FILES,
+ BOUNTY_MAX_SUBMISSION_URLS,
+} from "@/lib/bounty/constants";
+import { resolveBountyDetails } from "@/lib/bounty/utils";
+import { PartnerBountyProps, PartnerPlatformProps } from "@/lib/types";
+import { evaluateSocialContentRequirements } from "@/ui/partners/bounties/evaluate-social-content-requirements";
+import { X } from "@/ui/shared/icons";
+import {
+ Button,
+ CircleCheckFill,
+ FileUpload,
+ Label,
+ LoadingSpinner,
+ Trash,
+} from "@dub/ui";
+import { cn, formatDate } from "@dub/utils";
+import { AlertTriangle } from "lucide-react";
+import { useEffect, useId, useState } from "react";
+import ReactTextareaAutosize from "react-textarea-autosize";
+import { toast } from "sonner";
+import { v4 as uuid } from "uuid";
+import { useEmbedSocialContent } from "./use-embed-social-content";
+
+const inputClassName =
+ "block h-10 w-full rounded-md px-3 py-2 sm:text-sm " +
+ "border-border-default bg-bg-default text-content-emphasis " +
+ "placeholder:text-content-muted " +
+ "focus:border-border-emphasis focus:outline-none focus:ring-border-emphasis";
+
+export interface FileInput {
+ id: string;
+ file?: File;
+ url?: string;
+ uploading: boolean;
+ originalFileName?: string;
+ originalFileSize?: number;
+}
+
+export function EmbedImagesField({
+ bounty,
+ files,
+ setFiles,
+ onUploadingChange,
+ token,
+}: {
+ bounty: PartnerBountyProps;
+ files: FileInput[];
+ setFiles: React.Dispatch<React.SetStateAction<FileInput[]>>;
+ onUploadingChange: (uploading: boolean) => void;
+ token: string;
+}) {
+ const imageMax = bounty.submissionRequirements?.image?.max;
+ const maxFiles = imageMax ?? BOUNTY_MAX_SUBMISSION_FILES;
+ const formatRequirementText = (max?: number | null) =>
+ max != null && max > 1 ? ` (1 required, max of ${max})` : " (1 required)";
+
+ const handleUpload = async (file: File) => {
+ const newFile: FileInput = { id: uuid(), file, uploading: true };
+
+ setFiles((prev) => {
+ const updated = [...prev, newFile];
+ onUploadingChange(true);
+ return updated;
+ });
+
+ try {
+ const uploadUrlRes = await fetch(
+ `/api/embed/referrals/bounties/${bounty.id}/upload`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${token}`,
+ },
+ body: JSON.stringify({
+ fileName: file.name,
+ contentType: file.type,
+ contentLength: file.size,
+ }),
+ },
+ );
+
+ if (!uploadUrlRes.ok) {
+ toast.error("Failed to get signed upload URL.");
+ setFiles((prev) => {
+ const updated = prev.filter((f) => f.id !== newFile.id);
+ onUploadingChange(updated.some((f) => f.uploading));
+ return updated;
+ });
+ return;
+ }
+
+ const { signedUrl, destinationUrl } = await uploadUrlRes.json();
+
+ const uploadResponse = await fetch(signedUrl, {
+ method: "PUT",
+ body: file,
+ headers: {
+ "Content-Type": file.type,
+ "Content-Length": file.size.toString(),
+ },
+ });
+
+ if (!uploadResponse.ok) {
+ toast.error("Failed to upload screenshot.");
+ setFiles((prev) => {
+ const updated = prev.filter((f) => f.id !== newFile.id);
+ onUploadingChange(updated.some((f) => f.uploading));
+ return updated;
+ });
+ return;
+ }
+
+ toast.success(`${file.name} uploaded!`);
+ setFiles((prev) => {
+ const updated = prev.map((f) =>
+ f.id === newFile.id
+ ? { ...f, uploading: false, url: destinationUrl }
+ : f,
+ );
+ onUploadingChange(updated.some((f) => f.uploading));
+ return updated;
+ });
+ } catch {
+ toast.error(
+ "An unexpected error occurred while uploading. Please try again.",
+ );
+ setFiles((prev) => {
+ const updated = prev.filter((f) => f.id !== newFile.id);
+ onUploadingChange(updated.some((f) => f.uploading));
+ return updated;
+ });
+ }
+ };
+
+ return (
+ <div>
+ <Label>Images{formatRequirementText(imageMax)}</Label>
+ <div
+ className={cn(
+ "mt-2 flex h-12 items-center gap-2 transition-[height]",
+ files.length === 0 && "h-[104px]",
+ )}
+ >
+ {files.map((file, idx) => (
+ <div
+ key={file.id}
+ className="border-border-subtle bg-bg-default group relative flex aspect-square h-full items-center justify-center rounded-md border"
+ >
+ {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"
+ aria-label={`Remove ${file.file?.name ?? file.originalFileName ?? "file"}`}
+ className={cn(
+ "absolute right-0 top-0 flex size-[1.125rem] -translate-y-1/2 translate-x-1/2 items-center justify-center",
+ "border-border-subtle bg-bg-default hover:bg-bg-muted rounded-full border shadow-sm active:scale-95",
+ "scale-50 opacity-0 transition-[background-color,transform,opacity] group-hover:scale-100 group-hover:opacity-100",
+ )}
+ onClick={() => {
+ setFiles((prev) => {
+ const next = prev.filter((f) => f.id !== file.id);
+ onUploadingChange(next.some((f) => f.uploading));
+ return next;
+ });
+ }}
+ >
+ <X className="text-content-muted size-2.5" />
+ </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 : "SVG, JPG, PNG or WEBP\nMax size 5MB"
+ }
+ onChange={async ({ file }) => await handleUpload(file)}
+ disabled={files.length >= maxFiles}
+ maxFileSizeMB={5}
+ />
+ </div>
+ </div>
+ );
+}
+
+export function EmbedSocialUrlField({
+ bounty,
+ value,
+ onChange,
+ partnerPlatform,
+ onVerifyingChange,
+ onRequirementsMetChange,
+}: {
+ bounty: PartnerBountyProps;
+ value: string;
+ onChange: (v: string) => void;
+ partnerPlatform?: Pick<PartnerPlatformProps, "identifier" | "verifiedAt">;
+ onVerifyingChange: (value: boolean) => void;
+ onRequirementsMetChange: (value: boolean) => void;
+}) {
+ const bountyInfo = resolveBountyDetails(bounty);
+ const socialPlatform = bountyInfo?.socialPlatform;
+ const inputId = useId();
+ const [urlToCheck, setUrlToCheck] = useState("");
+
+ useEffect(() => {
+ setUrlToCheck("");
+ onRequirementsMetChange(false);
+ }, [value, onRequirementsMetChange]);
+
+ const { data, error, isValidating } = useEmbedSocialContent({
+ bountyId: bounty.id,
+ url: urlToCheck,
+ });
+
+ useEffect(() => {
+ onVerifyingChange(isValidating);
+ return () => onVerifyingChange(false);
+ }, [isValidating, onVerifyingChange]);
+
+ if (!socialPlatform) return null;
+
+ const { isPostedFromYourAccount, isAfterStartDate } =
+ evaluateSocialContentRequirements({
+ content: data,
+ bounty: {
+ startsAt: new Date(bounty.startsAt),
+ },
+ partnerPlatform: {
+ identifier: partnerPlatform?.identifier ?? "",
+ verifiedAt: partnerPlatform?.verifiedAt
+ ? new Date(partnerPlatform.verifiedAt)
+ : null,
+ },
+ });
+
+ useEffect(() => {
+ onRequirementsMetChange(isPostedFromYourAccount && isAfterStartDate);
+ return () => onRequirementsMetChange(true);
+ }, [isAfterStartDate, isPostedFromYourAccount, onRequirementsMetChange]);
+
+ const showIcon = isValidating || (!!error && !!urlToCheck);
+
+ return (
+ <div>
+ <label htmlFor={inputId} className="block">
+ <span className="text-content-emphasis text-sm font-medium">
+ {`${socialPlatform.label} URL`}
+ </span>
+ </label>
+ <div className="relative mt-2">
+ <input
+ id={inputId}
+ type="text"
+ inputMode="url"
+ autoComplete="url"
+ placeholder={socialPlatform.placeholder}
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ onBlur={(e) => {
+ const trimmed = e.target.value.trim();
+ onChange(trimmed);
+ setUrlToCheck(trimmed);
+ }}
+ className={cn(
+ `${inputClassName} pr-10`,
+ error &&
+ urlToCheck &&
+ "border-border-error focus:border-border-error focus:ring-border-error",
+ )}
+ />
+
+ {showIcon && (
+ <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
+ {isValidating ? (
+ <LoadingSpinner className="text-content-muted size-4 shrink-0" />
+ ) : error && urlToCheck ? (
+ <AlertTriangle
+ className="text-content-error size-4 shrink-0"
+ fill="rgb(var(--content-error))"
+ />
+ ) : null}
+ </div>
+ )}
+ </div>
+ <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-content-success"
+ : "text-content-muted",
+ )}
+ >
+ <CircleCheckFill
+ className={cn(
+ "size-2.5 transition-opacity",
+ isPostedFromYourAccount
+ ? "text-content-success"
+ : "text-content-muted",
+ )}
+ />
+ <span>Posted from your account</span>
+ </li>
+ {bounty.startsAt && (
+ <li
+ className={cn(
+ "flex items-center gap-1 text-xs font-medium transition-colors",
+ isAfterStartDate ? "text-content-success" : "text-content-muted",
+ )}
+ >
+ <CircleCheckFill
+ className={cn(
+ "size-2.5 transition-opacity",
+ isAfterStartDate
+ ? "text-content-success"
+ : "text-content-muted",
+ )}
+ />
+ <span>{`Posted after ${formatDate(bounty.startsAt, { month: "short", day: "numeric", year: "numeric" })}`}</span>
+ </li>
+ )}
+ </ul>
+ </div>
+ );
+}
+
+export function EmbedUrlsField({
+ bounty,
+ urls,
+ setUrls,
+}: {
+ bounty: PartnerBountyProps;
+ urls: string[];
+ setUrls: React.Dispatch<React.SetStateAction<string[]>>;
+}) {
+ const urlMax = bounty.submissionRequirements?.url?.max;
+ const maxUrls = urlMax ?? BOUNTY_MAX_SUBMISSION_URLS;
+ const formatRequirementText = (max?: number | null) =>
+ max != null && max > 1 ? ` (1 required, max of ${max})` : " (1 required)";
+ const firstDomain = bounty.submissionRequirements?.url?.domains?.[0];
+ const placeholderUrl = firstDomain ? `https://${firstDomain}` : "https://";
+ const rows = urls.length > 0 ? urls : [""];
+
+ return (
+ <div>
+ <div className="flex items-center justify-between">
+ <Label>URL{formatRequirementText(urlMax)}</Label>
+ <span className="text-content-subtle text-xs font-medium">
+ {urls.filter(Boolean).length} / {maxUrls}
+ </span>
+ </div>
+ <div className="mt-2 flex flex-col gap-2">
+ {rows.map((url, i) => (
+ <div key={i} className="flex items-center gap-2">
+ <input
+ type="url"
+ placeholder={placeholderUrl}
+ value={url}
+ onChange={(e) => {
+ setUrls((prev) => {
+ const next =
+ prev.length > i
+ ? [...prev]
+ : [...prev, ...Array(i - prev.length + 1).fill("")];
+ next[i] = e.target.value;
+ return next;
+ });
+ }}
+ className={inputClassName}
+ />
+ <Button
+ variant="outline"
+ icon={<Trash className="size-4" />}
+ aria-label={`Remove URL ${i + 1}`}
+ className="bg-bg-error text-content-error hover:bg-bg-error/80 w-10 shrink-0 p-0"
+ onClick={() => setUrls((prev) => prev.filter((_, j) => j !== i))}
+ />
+ </div>
+ ))}
+
+ {urls.length < maxUrls && (
+ <Button
+ variant="secondary"
+ text="Add URL"
+ className="h-8 rounded-lg"
+ onClick={() => setUrls((prev) => [...prev, ""])}
+ />
+ )}
+
+ {bounty.submissionRequirements?.url?.domains &&
+ bounty.submissionRequirements.url.domains.length > 0 && (
+ <p className="text-content-muted text-xs">
+ Allowed domains:{" "}
+ {bounty.submissionRequirements.url.domains.join(", ")}
+ </p>
+ )}
+ </div>
+ </div>
+ );
+}
+
+export function EmbedDescriptionField({
+ value,
+ onChange,
+}: {
+ value: string;
+ onChange: (v: string) => void;
+}) {
+ return (
+ <div>
+ <Label htmlFor="embed-submission-description">
+ Provide any additional details (optional)
+ </Label>
+ <ReactTextareaAutosize
+ id="embed-submission-description"
+ className={cn(
+ "mt-2 block w-full resize-none rounded-md focus:outline-none sm:text-sm",
+ "border-border-default bg-bg-default text-content-emphasis",
+ "placeholder:text-content-muted focus:border-border-emphasis focus:ring-border-emphasis",
+ )}
+ minRows={3}
+ maxLength={BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH}
+ value={value}
+ onChange={(e) => {
+ if (
+ e.target.value.length <= BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH
+ ) {
+ onChange(e.target.value);
+ }
+ }}
+ />
+ <div className="mt-1 text-left">
+ <span className="text-content-subtle text-xs">
+ {value.length} / {BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH}
+ </span>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submission-form.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submission-form.tsx
new file mode 100644
index 0000000000..dd75c3e2b3
--- /dev/null
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submission-form.tsx
@@ -0,0 +1,328 @@
+"use client";
+
+import { getPeriodLabel } from "@/lib/bounty/periods";
+import { resolveBountyDetails } from "@/lib/bounty/utils";
+import { PartnerBountyProps, PartnerBountySubmission } from "@/lib/types";
+import { SocialAccountNotVerifiedWarning } from "@/ui/partners/bounties/bounty-social-content";
+import { PlatformType } from "@dub/prisma/client";
+import { Button, ChevronRight, Popover, Trophy } from "@dub/ui";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { toast } from "sonner";
+import { v4 as uuid } from "uuid";
+import { useEmbedToken } from "../../use-embed-token";
+import {
+ EmbedDescriptionField,
+ EmbedImagesField,
+ EmbedSocialUrlField,
+ EmbedUrlsField,
+ type FileInput,
+} from "./submission-fields";
+
+export function SubmissionCardHeader({
+ title,
+ onBack,
+ onBackToRoot,
+ rightContent,
+}: {
+ title: string;
+ onBack: () => void;
+ onBackToRoot: () => void;
+ rightContent: React.ReactNode;
+}) {
+ return (
+ <>
+ <div className="flex items-center justify-between px-4 py-2">
+ <div className="flex min-w-0 items-center gap-1.5">
+ <button
+ type="button"
+ aria-label="Back to bounties"
+ title="Back to bounties"
+ onClick={onBackToRoot}
+ className="bg-bg-subtle hover:bg-bg-emphasis flex size-8 shrink-0 items-center justify-center rounded-lg transition-[transform,background-color] duration-150 active:scale-95"
+ >
+ <Trophy className="size-4" />
+ </button>
+ <ChevronRight className="text-content-muted size-2.5 shrink-0 [&_*]:stroke-2" />
+ <button
+ type="button"
+ aria-label="Back to bounty details"
+ title="Back to bounty details"
+ onClick={onBack}
+ className="text-content-default hover:text-content-emphasis shrink-0 text-sm font-medium transition-colors"
+ >
+ Bounty details
+ </button>
+ <ChevronRight className="text-content-muted size-2.5 shrink-0 [&_*]:stroke-2" />
+ <span className="text-content-emphasis min-w-0 truncate text-sm font-semibold">
+ {title}
+ </span>
+ </div>
+ <div className="flex items-center gap-2">{rightContent}</div>
+ </div>
+ <div className="border-border-subtle border-t" />
+ </>
+ );
+}
+
+export function EmbedBountySubmissionForm({
+ bounty,
+ partnerPlatforms,
+ periodNumber,
+ existingSubmission,
+ onCancel,
+ onBackToRoot,
+ onSuccess,
+}: {
+ bounty: PartnerBountyProps;
+ partnerPlatforms: Array<{
+ type: PlatformType;
+ identifier: string;
+ verifiedAt: Date | null;
+ }>;
+ periodNumber: number;
+ existingSubmission?: PartnerBountySubmission | null;
+ onCancel: () => void;
+ onBackToRoot: () => void;
+ onSuccess: (submission: PartnerBountySubmission) => void;
+}) {
+ const router = useRouter();
+ const token = useEmbedToken();
+ const bountyInfo = resolveBountyDetails(bounty);
+ const isSocialMetricsBounty = bountyInfo?.hasSocialMetrics ?? false;
+ const partnerPlatform = bountyInfo?.socialPlatform
+ ? partnerPlatforms.find((p) => p.type === bountyInfo.socialPlatform?.value)
+ : undefined;
+ const imageRequired = !!bounty.submissionRequirements?.image;
+ const urlRequired =
+ !!bounty.submissionRequirements?.url && !isSocialMetricsBounty;
+
+ const [files, setFiles] = useState<FileInput[]>(() =>
+ (existingSubmission?.files ?? []).map((f) => ({
+ id: uuid(),
+ url: f.url,
+ uploading: false,
+ originalFileName: f.fileName,
+ originalFileSize: f.size,
+ })),
+ );
+ const [urls, setUrls] = useState<string[]>(() => {
+ if (existingSubmission?.urls?.length) return existingSubmission.urls;
+ return isSocialMetricsBounty ? [""] : [""];
+ });
+ const [description, setDescription] = useState(
+ existingSubmission?.description ?? "",
+ );
+
+ const [fileUploading, setFileUploading] = useState(false);
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const [isDraftSaving, setIsDraftSaving] = useState(false);
+ const [socialContentVerifying, setSocialContentVerifying] = useState(false);
+ const [socialContentRequirementsMet, setSocialContentRequirementsMet] =
+ useState(true);
+ const [confirmSubmitOpen, setConfirmSubmitOpen] = useState(false);
+
+ const submissionsOpenAt = bounty.submissionsOpenAt
+ ? new Date(bounty.submissionsOpenAt)
+ : null;
+ const submissionsNotOpenYet =
+ submissionsOpenAt !== null && submissionsOpenAt > new Date();
+
+ const isBusy =
+ fileUploading ||
+ isSubmitting ||
+ isDraftSaving ||
+ (isSocialMetricsBounty &&
+ (socialContentVerifying || !socialContentRequirementsMet));
+ const isDisabled = submissionsNotOpenYet || isBusy;
+
+ const title =
+ bounty.maxSubmissions > 1
+ ? `Submission (${getPeriodLabel(bounty.submissionFrequency, periodNumber - 1)})`
+ : "Submission";
+
+ const handleSubmit = async (isDraft: boolean) => {
+ if (!token || isSubmitting || isDraftSaving || isDisabled) return;
+
+ const completedFiles = files
+ .filter((f): f is FileInput & { url: string } => !f.uploading && !!f.url)
+ .map((f) => ({
+ url: f.url,
+ fileName: f.file?.name ?? f.originalFileName ?? "File",
+ size: f.file?.size ?? f.originalFileSize ?? 0,
+ }));
+
+ const submissionUrls = isSocialMetricsBounty
+ ? urls.slice(0, 1).filter(Boolean)
+ : urls.filter(Boolean);
+
+ if (!isDraft) {
+ if (imageRequired && completedFiles.length === 0) {
+ toast.error("You must upload at least one image.");
+ return;
+ }
+
+ if (urlRequired && submissionUrls.length === 0) {
+ toast.error("You must provide at least one URL.");
+ return;
+ }
+ }
+
+ isDraft ? setIsDraftSaving(true) : setIsSubmitting(true);
+
+ try {
+ const res = await fetch("/api/embed/referrals/submissions", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${token}`,
+ },
+ body: JSON.stringify({
+ bountyId: bounty.id,
+ files: completedFiles,
+ urls: submissionUrls,
+ description: description || undefined,
+ isDraft,
+ periodNumber,
+ }),
+ });
+
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({}));
+ toast.error(err?.error?.message ?? "Failed to submit bounty.");
+ return;
+ }
+
+ const submission = await res.json();
+ toast.success(isDraft ? "Progress saved!" : "Bounty submitted!");
+ onSuccess(submission);
+ router.refresh();
+ } catch {
+ toast.error("An unexpected error occurred. Please try again.");
+ } finally {
+ setIsSubmitting(false);
+ setIsDraftSaving(false);
+ }
+ };
+
+ return (
+ <div className="border-border-subtle bg-bg-default overflow-hidden rounded-xl border">
+ <SubmissionCardHeader
+ title={title}
+ onBack={onCancel}
+ onBackToRoot={onBackToRoot}
+ rightContent={
+ <>
+ {!isSocialMetricsBounty && (
+ <Button
+ type="button"
+ text={isDraftSaving ? "Saving..." : "Save progress"}
+ variant="secondary"
+ loading={isDraftSaving}
+ onClick={() => handleSubmit(true)}
+ disabled={isDisabled}
+ className="h-8 rounded-lg px-3"
+ />
+ )}
+
+ <Popover
+ openPopover={confirmSubmitOpen}
+ setOpenPopover={setConfirmSubmitOpen}
+ side="bottom"
+ align="end"
+ forceDropdown
+ content={
+ <div className="max-w-sm p-3">
+ <p className="text-sm font-medium text-neutral-800">
+ Confirm submission
+ </p>
+ <p className="mt-0.5 text-xs text-neutral-500">
+ Are you sure you want to submit this bounty? Once submitted,
+ you won't be able to make any further changes.
+ </p>
+ <div className="mt-3 flex items-center justify-end gap-1.5">
+ <Button
+ variant="secondary"
+ text="Cancel"
+ onClick={() => setConfirmSubmitOpen(false)}
+ className="h-7 w-fit rounded-lg px-3"
+ />
+ <Button
+ variant="primary"
+ text="Confirm submission"
+ loading={isSubmitting}
+ onClick={() => handleSubmit(false)}
+ className="h-7 w-fit rounded-lg px-3"
+ />
+ </div>
+ </div>
+ }
+ >
+ <Button
+ text={isSubmitting ? "Submitting..." : "Submit"}
+ loading={isSubmitting}
+ onClick={() => {
+ if (!isDisabled) {
+ setConfirmSubmitOpen(true);
+ }
+ }}
+ disabled={isDisabled}
+ className="h-8 rounded-lg px-3"
+ />
+ </Popover>
+ </>
+ }
+ />
+
+ <div className="flex flex-col gap-5 p-5">
+ {submissionsNotOpenYet && submissionsOpenAt && (
+ <div className="bg-bg-attention text-content-attention rounded-lg p-2 text-center text-sm font-medium">
+ Submissions open{" "}
+ {submissionsOpenAt.toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ })}{" "}
+ at{" "}
+ {submissionsOpenAt.toLocaleTimeString("en-US", {
+ hour: "numeric",
+ hour12: true,
+ })}
+ </div>
+ )}
+
+ {imageRequired && (
+ <EmbedImagesField
+ bounty={bounty}
+ files={files}
+ setFiles={setFiles}
+ onUploadingChange={setFileUploading}
+ token={token ?? ""}
+ />
+ )}
+
+ {isSocialMetricsBounty && bountyInfo?.socialPlatform ? (
+ <>
+ {!partnerPlatform?.verifiedAt && (
+ <SocialAccountNotVerifiedWarning bounty={bounty} />
+ )}
+ <EmbedSocialUrlField
+ bounty={bounty}
+ value={urls[0] ?? ""}
+ onChange={(v) => setUrls([v])}
+ partnerPlatform={partnerPlatform}
+ onVerifyingChange={setSocialContentVerifying}
+ onRequirementsMetChange={setSocialContentRequirementsMet}
+ />
+ </>
+ ) : (
+ urlRequired && (
+ <EmbedUrlsField bounty={bounty} urls={urls} setUrls={setUrls} />
+ )
+ )}
+
+ <EmbedDescriptionField value={description} onChange={setDescription} />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submissions-table.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submissions-table.tsx
new file mode 100644
index 0000000000..52d19bfaa8
--- /dev/null
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submissions-table.tsx
@@ -0,0 +1,172 @@
+"use client";
+
+import {
+ type SubmissionPeriod,
+ getSubmissionPeriods,
+} from "@/lib/bounty/periods";
+import { BOUNTY_SUBMISSION_STATUS_BADGES } from "@/lib/bounty/submission-status";
+import { PartnerBountyProps, PartnerBountySubmission } from "@/lib/types";
+import { Button, StatusBadge, Table, useTable } from "@dub/ui";
+import { ColumnDef } from "@tanstack/react-table";
+import { useMemo } from "react";
+
+export function EmbedBountySubmissionsTable({
+ bounty,
+ onSubmit,
+ onView,
+}: {
+ bounty: PartnerBountyProps;
+ onSubmit: (periodNumber: number) => void;
+ onView: (periodNumber: number) => void;
+}) {
+ const periods = getSubmissionPeriods({
+ startsAt: bounty.startsAt,
+ endsAt: bounty.endsAt,
+ submissionFrequency: bounty.submissionFrequency,
+ maxSubmissions: bounty.maxSubmissions,
+ submissions: bounty.submissions ?? [],
+ });
+
+ const showSubmissionColumn = bounty.maxSubmissions > 1;
+
+ const columns = useMemo<
+ ColumnDef<SubmissionPeriod<PartnerBountySubmission>>[]
+ >(
+ () => [
+ ...(showSubmissionColumn
+ ? [
+ {
+ id: "submission",
+ header: "Submission",
+ minSize: 200,
+ cell: ({
+ row: { original },
+ }: {
+ row: {
+ original: SubmissionPeriod<PartnerBountySubmission>;
+ };
+ }) => {
+ const config = BOUNTY_SUBMISSION_STATUS_BADGES[original.status];
+ const label =
+ original.status === "submitted"
+ ? "Pending review"
+ : config?.label;
+ return (
+ <div className="flex items-center gap-3">
+ <span className="text-content-subtle min-w-[52px] text-sm font-medium leading-5 tracking-[-0.28px]">
+ {original.label}
+ </span>
+ {config && (
+ <span className="sm:hidden">
+ <StatusBadge
+ variant={config.variant}
+ icon={config.icon}
+ >
+ {label}
+ </StatusBadge>
+ </span>
+ )}
+ </div>
+ );
+ },
+ } satisfies ColumnDef<SubmissionPeriod<PartnerBountySubmission>>,
+ ]
+ : []),
+ {
+ id: "status",
+ header: "Status",
+ minSize: 120,
+ size: 160,
+ cell: ({ row: { original } }) => {
+ const config = BOUNTY_SUBMISSION_STATUS_BADGES[original.status];
+ if (!config) return null;
+ const label =
+ original.status === "submitted" ? "Pending review" : config.label;
+ return (
+ <StatusBadge variant={config.variant} icon={config.icon}>
+ {label}
+ </StatusBadge>
+ );
+ },
+ },
+ {
+ id: "action",
+ header: "",
+ minSize: 98,
+ size: 98,
+ cell: ({ row: { original } }) => {
+ const { status, periodNumber } = original;
+ const isExpired =
+ bounty.endsAt !== null && new Date(bounty.endsAt) < new Date();
+ const isActionable =
+ status === "notSubmitted" ||
+ (status === "draft" &&
+ !bounty.submissionRequirements?.socialMetrics);
+
+ let buttonText = "Submit";
+ if (status === "draft") {
+ if (bounty.submissionRequirements?.socialMetrics) {
+ buttonText = "View";
+ } else {
+ buttonText = "Continue";
+ }
+ } else if (["submitted", "approved", "rejected"].includes(status)) {
+ buttonText = "View";
+ }
+
+ const isDisabled =
+ status === "notOpen" || (isExpired && isActionable);
+ const isPrimary = isActionable && !isExpired;
+
+ let disabledTooltip: string | undefined;
+ if (status === "notOpen") {
+ disabledTooltip = `Opens ${original.startDate.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })} at ${original.startDate.toLocaleTimeString("en-US", { hour: "numeric", hour12: true })}`;
+ } else if (isExpired && isActionable) {
+ disabledTooltip = "This bounty has expired";
+ }
+
+ return (
+ <div className="flex justify-end">
+ <Button
+ variant={isPrimary ? "primary" : "secondary"}
+ disabled={isDisabled}
+ className="h-7 w-fit rounded-lg px-2.5 py-2"
+ text={buttonText}
+ onClick={() => {
+ if (isActionable) {
+ onSubmit(periodNumber);
+ } else {
+ onView(periodNumber);
+ }
+ }}
+ disabledTooltip={disabledTooltip}
+ />
+ </div>
+ );
+ },
+ },
+ ],
+ [bounty, showSubmissionColumn, onSubmit, onView],
+ );
+
+ const { table, ...tableProps } = useTable({
+ data: periods,
+ columns,
+ getRowId: (row) => String(row.periodNumber),
+ resourceName: () => "submission period",
+ scrollWrapperClassName: "min-h-0",
+ thClassName: () => "border-l-0 border-r-0",
+ tdClassName: () => "border-l-0 border-r-0",
+ className: "[&_tbody_tr:last-child_td]:border-b-0",
+ containerClassName: "border-border-subtle",
+ });
+
+ return (
+ <div className="flex flex-col gap-3">
+ <h2 className="text-content-emphasis text-sm font-semibold">
+ Submissions
+ </h2>
+ <Table {...tableProps} table={table} />
+ </div>
+ );
+}
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/use-embed-social-content.ts b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/use-embed-social-content.ts
new file mode 100644
index 0000000000..73cc6726e1
--- /dev/null
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/use-embed-social-content.ts
@@ -0,0 +1,47 @@
+"use client";
+
+import { SocialContent } from "@/lib/types";
+import { fetcher } from "@dub/utils";
+import useSWR from "swr";
+import { useEmbedToken } from "../../use-embed-token";
+
+interface UseEmbedSocialContentParams {
+ bountyId: string;
+ url: string;
+}
+
+export function useEmbedSocialContent({
+ bountyId,
+ url,
+}: UseEmbedSocialContentParams) {
+ const token = useEmbedToken();
+
+ const searchParams = new URLSearchParams({
+ url,
+ });
+
+ const { data, error, isValidating, mutate } = useSWR<SocialContent>(
+ token && bountyId && url
+ ? [
+ `/api/embed/referrals/bounties/${bountyId}/social-content-stats?${searchParams.toString()}`,
+ token,
+ ]
+ : null,
+ ([requestUrl, authToken]) =>
+ fetcher(requestUrl, {
+ headers: {
+ Authorization: `Bearer ${authToken}`,
+ },
+ }),
+ {
+ revalidateOnFocus: false,
+ },
+ );
+
+ return {
+ data: data ?? null,
+ error,
+ isValidating,
+ mutate,
+ };
+}
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/earnings-summary.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/earnings-summary.tsx
index e59524eeb3..2fc0442027 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/earnings-summary.tsx
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/earnings-summary.tsx
@@ -1,15 +1,10 @@
import { Button, InfoTooltip } from "@dub/ui";
import { currencyFormatter } from "@dub/utils";
+import { useReferralsEmbedData } from "./page-client";
+
+export function ReferralsEmbedEarningsSummary() {
+ const { program, partner, earnings } = useReferralsEmbedData();
-export function ReferralsEmbedEarningsSummary({
- earnings,
- programSlug,
- partnerEmail,
-}: {
- earnings: { upcoming: number; paid: number };
- programSlug: string;
- partnerEmail: string | null;
-}) {
return (
<div className="border-border-subtle bg-bg-default flex flex-col justify-between gap-4 rounded-lg border p-4">
<div className="flex items-center justify-between">
@@ -18,8 +13,8 @@ export function ReferralsEmbedEarningsSummary({
<InfoTooltip content="Summary of your commission earnings from your referrals." />
</div>
<a
- href={`https://partners.dub.co/${programSlug}/register${
- partnerEmail ? `?email=${partnerEmail}` : ""
+ href={`https://partners.dub.co/${program.slug}/register${
+ partner.email ? `?email=${partner.email}` : ""
}`}
target="_blank"
>
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/earnings.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/earnings.tsx
index b452acc17e..bc51fae969 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/earnings.tsx
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/earnings.tsx
@@ -18,15 +18,19 @@ import {
import { motion } from "motion/react";
import useSWR from "swr";
import { useEmbedToken } from "../../embed/use-embed-token";
+import { useReferralsEmbedData } from "./page-client";
-export function ReferralsEmbedEarnings({ salesCount }: { salesCount: number }) {
+export function ReferralsEmbedEarnings() {
const token = useEmbedToken();
+ const {
+ earnings: { totalCount: earningsCount },
+ } = useReferralsEmbedData();
const { pagination, setPagination } = usePagination(
REFERRALS_EMBED_EARNINGS_LIMIT,
);
const { data: earnings, isLoading } = useSWR<PartnerEarningsResponse[]>(
- `/api/embed/referrals/earnings?page=${pagination.pageIndex}`,
+ `/api/embed/referrals/earnings?page=${pagination.pageIndex}&pageSize=${pagination.pageSize}&interval=all`,
(url) =>
fetcher(url, {
headers: {
@@ -88,7 +92,7 @@ export function ReferralsEmbedEarnings({ salesCount }: { salesCount: number }) {
],
pagination,
onPaginationChange: setPagination,
- rowCount: salesCount,
+ rowCount: earningsCount,
emptyState: (
<div className="flex w-full flex-col items-center justify-center gap-2">
<Gift className="text-content-muted size-6" />
@@ -100,7 +104,7 @@ export function ReferralsEmbedEarnings({ salesCount }: { salesCount: number }) {
),
thClassName: "border-l-0",
tdClassName: "border-l-0",
- resourceName: (plural) => `sale${plural ? "s" : ""}`,
+ resourceName: (plural) => `commission${plural ? "s" : ""}`,
});
return (
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/faq.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/faq.tsx
index 148fe73bef..dfbe104f96 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/faq.tsx
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/faq.tsx
@@ -1,8 +1,6 @@
import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
-import { RewardProps } from "@/lib/types";
import { programEmbedSchema } from "@/lib/zod/schemas/program-embed";
import { BlockMarkdown } from "@/ui/partners/lander/blocks/block-markdown";
-import { Program } from "@dub/prisma/client";
import {
Accordion,
AccordionContent,
@@ -11,14 +9,12 @@ import {
TAB_ITEM_ANIMATION_SETTINGS,
} from "@dub/ui";
import { motion } from "motion/react";
+import { useReferralsEmbedData } from "./page-client";
+
+export function ReferralsEmbedFAQ() {
+ const { program, rewards } = useReferralsEmbedData();
+ const reward = rewards[0];
-export function ReferralsEmbedFAQ({
- program,
- reward,
-}: {
- program: Program;
- reward: RewardProps | null;
-}) {
const rewardDescription = reward
? `For each new customer you refer, you'll earn a ${constructRewardAmount(reward)} commission on their subscription${
reward.maxDuration === null
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/leaderboard.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/leaderboard.tsx
index 4b2a1fb60d..1e8a626fc4 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/leaderboard.tsx
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/leaderboard.tsx
@@ -1,4 +1,6 @@
+import { generateRandomName } from "@/lib/names";
import { LeaderboardPartnerSchema } from "@/lib/zod/schemas/partners";
+import { PartnerAvatar } from "@/ui/partners/partner-avatar";
import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
import {
Crown,
@@ -65,14 +67,10 @@ export function ReferralsEmbedLeaderboard() {
cell: ({ row }) => {
return (
<div className="flex items-center gap-2">
- <img
- src={row.original.image}
- alt={row.original.name}
- className="size-5 rounded-full"
- />
+ <PartnerAvatar partner={row.original} className="size-5" />
<Tooltip content="For privacy reasons, the name of the partner is anonymized.">
<span className="cursor-help text-sm font-medium decoration-dotted underline-offset-2 hover:underline">
- {row.original.name}
+ {generateRandomName(row.original.id)}
</span>
</Tooltip>
</div>
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/links-list.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/links-list.tsx
index 8857257d63..7e0dbd2246 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/links-list.tsx
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/links-list.tsx
@@ -1,7 +1,5 @@
import { constructPartnerLink } from "@/lib/partners/construct-partner-link";
-import { PartnerGroupProps } from "@/lib/types";
import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
-import { Program } from "@dub/prisma/client";
import {
Button,
CopyButton,
@@ -22,27 +20,17 @@ import { motion } from "motion/react";
import { useEffect, useState } from "react";
import useSWR from "swr";
import { useEmbedToken } from "../use-embed-token";
+import { useReferralsEmbedData } from "./page-client";
import { ReferralsEmbedLink } from "./types";
interface Props {
- program: Pick<Program, "name">;
- links: ReferralsEmbedLink[];
- group: Pick<
- PartnerGroupProps,
- "id" | "additionalLinks" | "maxPartnerLinks" | "linkStructure"
- >;
onCreateLink: () => void;
onEditLink: (link: ReferralsEmbedLink) => void;
}
-export function ReferralsEmbedLinksList({
- program,
- links,
- group,
- onCreateLink,
- onEditLink,
-}: Props) {
+export function ReferralsEmbedLinksList({ onCreateLink, onEditLink }: Props) {
const token = useEmbedToken();
+ const { links, program, group } = useReferralsEmbedData();
const [partnerLinks, setPartnerLinks] = useState<ReferralsEmbedLink[]>(links);
const { data: refreshedLinks, isLoading } = useSWR<ReferralsEmbedLink[]>(
@@ -85,7 +73,7 @@ export function ReferralsEmbedLinksList({
return (
<div className="flex min-w-0 items-center gap-2">
- <div className="border-border-subtle has-[:hover]:bg-bg-muted rounded-md border bg-white transition-colors dark:bg-black">
+ <div className="border-border-subtle has-[:hover]:bg-bg-muted bg-bg-default rounded-md border transition-colors">
<CopyButton
value={partnerLink}
variant="neutral"
@@ -188,7 +176,7 @@ export function ReferralsEmbedLinksList({
text="Create link"
variant="primary"
onClick={onCreateLink}
- className="bg-bg-inverted h-9 rounded-md hover:bg-neutral-800"
+ className="bg-bg-inverted text-content-inverted h-9 rounded-md hover:opacity-80"
/>
}
/>
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/links.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/links.tsx
index 6c1c7f827d..4a80d079e5 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/links.tsx
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/links.tsx
@@ -1,20 +1,9 @@
-import { PartnerGroupProps } from "@/lib/types";
-import { Program } from "@dub/prisma/client";
import { useState } from "react";
import { ReferralsEmbedCreateUpdateLink } from "./add-edit-link";
import { ReferralsEmbedLinksList } from "./links-list";
import { ReferralsEmbedLink } from "./types";
-interface Props {
- links: ReferralsEmbedLink[];
- program: Pick<Program, "domain" | "url" | "name">;
- group: Pick<
- PartnerGroupProps,
- "id" | "additionalLinks" | "maxPartnerLinks" | "linkStructure"
- >;
-}
-
-export function ReferralsEmbedLinks({ links, program, group }: Props) {
+export function ReferralsEmbedLinks() {
const [createLink, setCreateLink] = useState(false);
const [link, setLink] = useState<ReferralsEmbedLink | null>(null);
@@ -22,9 +11,7 @@ export function ReferralsEmbedLinks({ links, program, group }: Props) {
<div className="flex flex-col space-y-6">
{createLink ? (
<ReferralsEmbedCreateUpdateLink
- program={program}
link={link}
- group={group}
onCancel={() => {
setCreateLink(false);
setLink(null);
@@ -32,9 +19,6 @@ export function ReferralsEmbedLinks({ links, program, group }: Props) {
/>
) : (
<ReferralsEmbedLinksList
- program={program}
- links={links}
- group={group}
onCreateLink={() => setCreateLink(true)}
onEditLink={(link) => {
setLink(link);
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/page-client.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/page-client.tsx
index 43fa5b2720..44aaa27db9 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/page-client.tsx
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/page-client.tsx
@@ -2,14 +2,20 @@
import { constructPartnerLink } from "@/lib/partners/construct-partner-link";
import { QueryLinkStructureHelpText } from "@/lib/partners/query-link-structure-help-text";
-import { DiscountProps, PartnerGroupProps, RewardProps } from "@/lib/types";
+import {
+ DiscountProps,
+ PartnerBountyProps,
+ PartnerGroupProps,
+ ProgramEnrollmentProps,
+ RewardProps,
+} from "@/lib/types";
import { programEmbedSchema } from "@/lib/zod/schemas/program-embed";
import { programResourcesSchema } from "@/lib/zod/schemas/program-resources";
import { HeroBackground } from "@/ui/partners/hero-background";
import { ProgramRewardList } from "@/ui/partners/program-reward-list";
import { ProgramRewardTerms } from "@/ui/partners/program-reward-terms";
import { ThreeDots } from "@/ui/shared/icons";
-import { Partner, Program } from "@dub/prisma/client";
+import { Partner, PlatformType, Program } from "@dub/prisma/client";
import {
Button,
Check,
@@ -26,8 +32,17 @@ import { ArrowTurnRight2 } from "@dub/ui/icons";
import { cn, getApexDomain, getPrettyUrl } from "@dub/utils";
import { ChevronDown } from "lucide-react";
import { AnimatePresence } from "motion/react";
-import { useEffect, useMemo, useState } from "react";
+import {
+ createContext,
+ CSSProperties,
+ ReactNode,
+ useContext,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
import { ReferralsEmbedActivity } from "./activity";
+import { ReferralsEmbedBounties } from "./bounties";
import { ReferralsEmbedEarnings } from "./earnings";
import { ReferralsEmbedEarningsSummary } from "./earnings-summary";
import { ReferralsEmbedFAQ } from "./faq";
@@ -39,26 +54,43 @@ import { ThemeOptions } from "./theme-options";
import { ReferralsReferralsEmbedToken } from "./token";
import { ReferralsEmbedLink } from "./types";
-export function ReferralsEmbedPageClient({
- program,
- partner,
- links,
- rewards,
- discount,
- earnings,
- stats,
- group,
- themeOptions,
- dynamicHeight,
-}: {
- program: Program;
+type ReferralsEmbedData = {
+ program: Pick<
+ Program,
+ | "id"
+ | "name"
+ | "slug"
+ | "domain"
+ | "minPayoutAmount"
+ | "termsUrl"
+ | "embedData"
+ | "resources"
+ >;
+ programEnrollment: Pick<ProgramEnrollmentProps, "createdAt">;
partner: Pick<Partner, "id" | "name" | "email">;
+ partnerPlatforms: Array<{
+ type: PlatformType;
+ identifier: string;
+ verifiedAt: Date | null;
+ }>;
+ group: Pick<
+ PartnerGroupProps,
+ | "id"
+ | "logo"
+ | "wordmark"
+ | "brandColor"
+ | "additionalLinks"
+ | "maxPartnerLinks"
+ | "linkStructure"
+ | "holdingPeriodDays"
+ >;
links: ReferralsEmbedLink[];
rewards: RewardProps[];
discount?: DiscountProps | null;
earnings: {
upcoming: number;
paid: number;
+ totalCount: number;
};
stats: {
clicks: number;
@@ -66,20 +98,59 @@ export function ReferralsEmbedPageClient({
sales: number;
saleAmount: number;
};
- group: Pick<
- PartnerGroupProps,
- | "id"
- | "logo"
- | "wordmark"
- | "brandColor"
- | "additionalLinks"
- | "maxPartnerLinks"
- | "linkStructure"
- | "holdingPeriodDays"
- >;
+ bounties: PartnerBountyProps[];
+};
+
+type ReferralsEmbedPageClientProps = ReferralsEmbedData & {
themeOptions: ThemeOptions;
dynamicHeight: boolean;
+};
+
+const ReferralsEmbedDataContext = createContext<ReferralsEmbedData | null>(
+ null,
+);
+
+export function useReferralsEmbedData() {
+ const context = useContext(ReferralsEmbedDataContext);
+
+ if (!context) {
+ throw new Error(
+ "useReferralsEmbedData must be used within ReferralsEmbedDataProvider",
+ );
+ }
+
+ return context;
+}
+
+function ReferralsEmbedDataProvider({
+ children,
+ value,
+}: {
+ children: ReactNode;
+ value: ReferralsEmbedData;
}) {
+ return (
+ <ReferralsEmbedDataContext.Provider value={value}>
+ {children}
+ </ReferralsEmbedDataContext.Provider>
+ );
+}
+
+export function ReferralsEmbedPageClient({
+ program,
+ partner,
+ partnerPlatforms,
+ links,
+ rewards,
+ discount,
+ earnings,
+ stats,
+ programEnrollment,
+ group,
+ bounties,
+ themeOptions,
+ dynamicHeight,
+}: ReferralsEmbedPageClientProps) {
const resources = programResourcesSchema.parse(
program.resources ?? { logos: [], colors: [], files: [] },
);
@@ -97,9 +168,12 @@ export function ReferralsEmbedPageClient({
true,
);
+ const activeBountiesCount = bounties.length;
+
const tabs = useMemo(
() => [
...(showQuickstart ? ["Quickstart"] : []),
+ ...(activeBountiesCount > 0 ? ["Bounties"] : []),
"Earnings",
...(group.additionalLinks.length > 0 ? ["Links"] : []),
...(programEmbedData?.leaderboard?.mode === "disabled"
@@ -108,7 +182,13 @@ export function ReferralsEmbedPageClient({
"FAQ",
...(hasResources ? ["Resources"] : []),
],
- [showQuickstart, group.additionalLinks, programEmbedData, hasResources],
+ [
+ showQuickstart,
+ activeBountiesCount,
+ group.additionalLinks,
+ programEmbedData,
+ hasResources,
+ ],
);
const [selectedTab, setSelectedTab] = useState(tabs[0]);
@@ -117,146 +197,166 @@ export function ReferralsEmbedPageClient({
if (!tabs.includes(selectedTab)) setSelectedTab(tabs[0]);
}, [tabs, selectedTab]);
+ const embedData = useMemo(
+ () => ({
+ program,
+ partner,
+ partnerPlatforms,
+ links,
+ rewards,
+ discount,
+ earnings,
+ stats,
+ programEnrollment,
+ group,
+ bounties,
+ }),
+ [
+ program,
+ partner,
+ partnerPlatforms,
+ links,
+ rewards,
+ discount,
+ earnings,
+ stats,
+ programEnrollment,
+ group,
+ bounties,
+ ],
+ );
+
return (
- <div
- style={{ backgroundColor: themeOptions.backgroundColor || "transparent" }}
- className={cn("flex flex-col", !dynamicHeight && "min-h-screen")}
- >
- <div className="relative z-0 p-5">
- <div className="border-border-default relative flex flex-col overflow-hidden rounded-lg border p-4 md:p-6">
- <HeroBackground logo={group.logo} color={group.brandColor} embed />
-
- <ReferralLinkDisplay
- links={links}
- group={group}
- onSelectTab={setSelectedTab}
- />
+ <ReferralsEmbedDataProvider value={embedData}>
+ <div
+ style={
+ {
+ backgroundColor: themeOptions.backgroundColor || "transparent",
+ "--brand": group.brandColor || "#2563eb",
+ } as CSSProperties
+ }
+ className={cn("flex flex-col", !dynamicHeight && "min-h-screen")}
+ >
+ <div className="relative z-0 p-5">
+ <div className="border-border-default relative flex flex-col overflow-hidden rounded-lg border p-4 md:p-6">
+ <HeroBackground logo={group.logo} color={group.brandColor} embed />
- <div className="mt-12 sm:max-w-[50%]">
- <div className="flex items-end justify-between">
- <span className="text-content-emphasis text-base font-semibold leading-none">
- Rewards
- </span>
- {program.termsUrl && (
+ <ReferralLinkDisplay onSelectTab={setSelectedTab} />
+
+ <div className="mt-12 sm:max-w-[50%]">
+ <div className="flex items-end justify-between">
+ <span className="text-content-emphasis text-base font-semibold leading-none">
+ Rewards
+ </span>
+ {program.termsUrl && (
+ <a
+ href={program.termsUrl}
+ target="_blank"
+ className="text-content-subtle text-xs font-medium leading-none underline-offset-2 hover:underline"
+ >
+ View terms ↗
+ </a>
+ )}
+ </div>
+ <div className="text-content-emphasis relative mt-4 text-lg">
+ <ProgramRewardList rewards={rewards} discount={discount} />
+ <ProgramRewardTerms
+ minPayoutAmount={program.minPayoutAmount}
+ holdingPeriodDays={group.holdingPeriodDays ?? 0}
+ />
+ </div>
+ </div>
+ {!programEmbedData?.hidePoweredByBadge && (
+ <div className="mt-4 flex justify-center md:absolute md:bottom-3 md:right-3 md:mt-0">
<a
- href={program.termsUrl}
+ href="https://dub.co/partners"
target="_blank"
- className="text-content-subtle text-xs font-medium leading-none underline-offset-2 hover:underline"
+ className="hover:text-content-default text-content-subtle bg-bg-default border-border-subtle flex w-fit items-center gap-1.5 rounded-md border px-2 py-1 transition-colors duration-75"
>
- View terms ↗
+ <p className="whitespace-nowrap text-xs font-medium leading-none">
+ Powered by
+ </p>
+ <Wordmark className="text-content-emphasis h-3.5" />
</a>
- )}
- </div>
- <div className="text-content-emphasis relative mt-4 text-lg">
- <ProgramRewardList rewards={rewards} discount={discount} />
- <ProgramRewardTerms
- minPayoutAmount={program.minPayoutAmount}
- holdingPeriodDays={group.holdingPeriodDays ?? 0}
- />
- </div>
+ </div>
+ )}
</div>
- {!programEmbedData?.hidePoweredByBadge && (
- <div className="mt-4 flex justify-center md:absolute md:bottom-3 md:right-3 md:mt-0">
- <a
- href="https://dub.co/partners"
- target="_blank"
- className="hover:text-content-default text-content-subtle bg-bg-default border-border-subtle flex w-fit items-center gap-1.5 rounded-md border px-2 py-1 transition-colors duration-75"
- >
- <p className="whitespace-nowrap text-xs font-medium leading-none">
- Powered by
- </p>
- <Wordmark className="text-content-emphasis h-3.5" />
- </a>
- </div>
- )}
- </div>
- <div className="mt-4 grid gap-2 sm:h-32 sm:grid-cols-3">
- <ReferralsEmbedActivity color={group.brandColor} {...stats} />
- <ReferralsEmbedEarningsSummary
- earnings={earnings}
- programSlug={program.slug}
- partnerEmail={partner.email}
- />
- </div>
- <div className="mt-4">
- <div className="border-border-subtle flex items-center border-b">
- <TabSelect
- options={tabs.map((tab) => ({
- id: tab,
- label: tab,
- }))}
- selected={selectedTab}
- onSelect={(option) => {
- setSelectedTab(option);
- }}
- className="scrollbar-hide min-w-0 grow overflow-x-auto"
- />
-
- <div className="shrink">
- <Menu
- showQuickstart={showQuickstart}
- setShowQuickstart={(show) => {
- setShowQuickstart(show);
- if (show) setSelectedTab("Quickstart");
+ <div className="mt-4 grid gap-2 sm:h-32 sm:grid-cols-3">
+ <ReferralsEmbedActivity />
+ <ReferralsEmbedEarningsSummary />
+ </div>
+ <div className="mt-4">
+ <div className="border-border-subtle flex items-center border-b">
+ <TabSelect
+ options={tabs.map((tab) => ({
+ id: tab,
+ label:
+ tab === "Bounties" ? (
+ <span className="flex items-center gap-2">
+ Bounties
+ <span
+ className={cn(
+ "flex h-5 items-center rounded-md px-1.5 text-xs font-medium",
+ "bg-[var(--brand)] text-white",
+ )}
+ >
+ {activeBountiesCount}
+ </span>
+ </span>
+ ) : (
+ tab
+ ),
+ }))}
+ selected={selectedTab}
+ onSelect={(option) => {
+ setSelectedTab(option);
}}
+ className="scrollbar-hide min-w-0 grow overflow-x-auto"
/>
- </div>
- </div>
- <div className="my-4">
- <AnimatePresence mode="wait">
- {selectedTab === "Quickstart" ? (
- <ReferralsEmbedQuickstart
- program={program}
- group={group}
- links={links}
- earnings={earnings}
- hasResources={hasResources}
- setSelectedTab={setSelectedTab}
- />
- ) : selectedTab === "Earnings" ? (
- <ReferralsEmbedEarnings salesCount={stats.sales} />
- ) : selectedTab === "Links" ? (
- <ReferralsEmbedLinks
- program={program}
- links={links}
- group={group}
+
+ <div className="shrink">
+ <Menu
+ showQuickstart={showQuickstart}
+ setShowQuickstart={(show) => {
+ setShowQuickstart(show);
+ if (show) setSelectedTab("Quickstart");
+ }}
/>
- ) : selectedTab === "Leaderboard" &&
- programEmbedData?.leaderboard?.mode !== "disabled" ? (
- <ReferralsEmbedLeaderboard />
- ) : selectedTab === "FAQ" ? (
- <ReferralsEmbedFAQ program={program} reward={rewards[0]} />
- ) : selectedTab === "Resources" ? (
- <ReferralsEmbedResources resources={resources} />
- ) : null}
- </AnimatePresence>
+ </div>
+ </div>
+ <div className="my-4">
+ <AnimatePresence mode="wait">
+ {selectedTab === "Quickstart" ? (
+ <ReferralsEmbedQuickstart
+ hasResources={hasResources}
+ setSelectedTab={setSelectedTab}
+ />
+ ) : selectedTab === "Bounties" ? (
+ <ReferralsEmbedBounties />
+ ) : selectedTab === "Earnings" ? (
+ <ReferralsEmbedEarnings />
+ ) : selectedTab === "Links" ? (
+ <ReferralsEmbedLinks />
+ ) : selectedTab === "Leaderboard" &&
+ programEmbedData?.leaderboard?.mode !== "disabled" ? (
+ <ReferralsEmbedLeaderboard />
+ ) : selectedTab === "FAQ" ? (
+ <ReferralsEmbedFAQ />
+ ) : selectedTab === "Resources" ? (
+ <ReferralsEmbedResources resources={resources} />
+ ) : null}
+ </AnimatePresence>
+ </div>
</div>
+ <ReferralsReferralsEmbedToken />
</div>
- <ReferralsReferralsEmbedToken />
</div>
- </div>
+ </ReferralsEmbedDataProvider>
);
}
-function ReferralLinkDisplay({
- links,
- group,
- onSelectTab,
-}: {
- links: ReferralsEmbedLink[];
- group: Pick<
- PartnerGroupProps,
- | "id"
- | "logo"
- | "wordmark"
- | "brandColor"
- | "additionalLinks"
- | "maxPartnerLinks"
- | "linkStructure"
- | "holdingPeriodDays"
- >;
- onSelectTab: (tab: string) => void;
-}) {
+function ReferralLinkDisplay({ onSelectTab }) {
+ const { links, group } = useReferralsEmbedData();
const [copied, copyToClipboard] = useCopyToClipboard();
const [selectedLinkId, setSelectedLinkId] = useState<string | null>(
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/page.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/page.tsx
index 7be2d75d03..1352fd3e2a 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/page.tsx
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/page.tsx
@@ -66,7 +66,7 @@ function EmbedInlineLoading({ themeOptions }: { themeOptions: ThemeOptions }) {
<div className="p-5">
<div className="border-border-default relative flex flex-col overflow-hidden rounded-lg border p-4 md:p-6">
<HeroBackground color="#737373" />
- <span className="text-base font-semibold text-neutral-800">
+ <span className="text-content-emphasis text-base font-semibold">
Referral link
</span>
<div className="xs:flex-row relative mt-3 flex flex-col items-center gap-2">
@@ -78,7 +78,7 @@ function EmbedInlineLoading({ themeOptions }: { themeOptions: ThemeOptions }) {
disabled
/>
</div>
- <span className="mt-12 text-base font-semibold text-neutral-800">
+ <span className="text-content-emphasis mt-12 text-base font-semibold">
Rewards
</span>
<div className="bg-bg-default border-border-subtle mt-2 h-20 w-[28rem] rounded-md border" />
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/quickstart.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/quickstart.tsx
index f3439e0569..d8c78d3c62 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/quickstart.tsx
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/quickstart.tsx
@@ -1,6 +1,4 @@
import { constructPartnerLink } from "@/lib/partners/construct-partner-link";
-import { PartnerGroupProps } from "@/lib/types";
-import { Program } from "@dub/prisma/client";
import {
Button,
Carousel,
@@ -15,31 +13,22 @@ import {
} from "@dub/ui";
import { cn, DUB_LOGO } from "@dub/utils";
import { motion } from "motion/react";
-import { ReferralsEmbedLink } from "./types";
+import { useReferralsEmbedData } from "./page-client";
-const BUTTON_CLASSNAME = "h-9 rounded-lg bg-bg-inverted hover:bg-neutral-800";
+const BUTTON_CLASSNAME =
+ "bg-bg-inverted text-content-inverted h-9 rounded-lg hover:opacity-80";
export function ReferralsEmbedQuickstart({
- program,
- group,
- links,
- earnings,
hasResources,
setSelectedTab,
}: {
- program: Program;
- group: Pick<PartnerGroupProps, "logo" | "linkStructure">;
- links: ReferralsEmbedLink[];
- earnings: {
- upcoming: number;
- paid: number;
- };
hasResources: boolean;
setSelectedTab: (tab: "Links" | "Resources") => void;
}) {
+ const { program, group, links, earnings } = useReferralsEmbedData();
+
const [copied, copyToClipboard] = useCopyToClipboard();
const { isMobile } = useMediaQuery();
-
const payoutsDisabled = earnings.upcoming === 0 && earnings.paid === 0;
const items = [
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/resources.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/resources.tsx
index 98ec5b860b..cf64052941 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/resources.tsx
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/resources.tsx
@@ -51,7 +51,7 @@ export function ReferralsEmbedResources({
key={link.id}
resourceType="link"
icon={
- <div className="flex size-full items-center justify-center bg-neutral-50">
+ <div className="bg-bg-subtle flex size-full items-center justify-center">
<img
src={`${GOOGLE_FAVICON_URL}${getApexDomain(link.url)}`}
alt={link.name}
@@ -94,8 +94,8 @@ export function ReferralsEmbedResources({
key={file.id}
resourceType="file"
icon={
- <div className="flex size-full items-center justify-center bg-neutral-50">
- <FileContent className="size-4 text-neutral-800" />
+ <div className="bg-bg-subtle flex size-full items-center justify-center">
+ <FileContent className="text-content-emphasis size-4" />
</div>
}
title={file.name || "File"}
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/utils.ts b/apps/web/app/(ee)/app.dub.co/embed/referrals/utils.ts
index cadd8d79ad..f39942ff9a 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/utils.ts
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/utils.ts
@@ -1,5 +1,6 @@
import { serializeReward } from "@/lib/api/partners/serialize-reward";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { getBountiesForPartner } from "@/lib/bounty/api/get-bounties-for-partner";
import { referralsEmbedToken } from "@/lib/embed/referrals/token-class";
import { aggregatePartnerLinksStats } from "@/lib/partners/aggregate-partner-links-stats";
import { PartnerGroupAdditionalLink } from "@/lib/types";
@@ -16,18 +17,61 @@ export const getReferralsEmbedData = async (token: string) => {
notFound();
}
+ const now = new Date();
const programEnrollment = await getProgramEnrollmentOrThrow({
partnerId,
programId,
include: {
- partner: true,
- program: true,
+ partner: {
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ platforms: {
+ select: {
+ type: true,
+ identifier: true,
+ verifiedAt: true,
+ },
+ },
+ },
+ },
+ program: {
+ select: {
+ id: true,
+ name: true,
+ slug: true,
+ domain: true,
+ defaultGroupId: true,
+ minPayoutAmount: true,
+ termsUrl: true,
+ embedData: true,
+ resources: true,
+ _count: {
+ select: {
+ bounties: {
+ where: {
+ startsAt: {
+ lte: now,
+ },
+ OR: [{ endsAt: null }, { endsAt: { gte: now } }],
+ },
+ },
+ },
+ },
+ },
+ },
links: true,
partnerGroup: true,
discount: true,
clickReward: true,
leadReward: true,
saleReward: true,
+ _count: {
+ select: {
+ commissions: true,
+ },
+ },
},
});
@@ -35,20 +79,6 @@ export const getReferralsEmbedData = async (token: string) => {
notFound();
}
- const commissions = await prisma.commission.groupBy({
- by: ["status"],
- _sum: {
- earnings: true,
- },
- where: {
- earnings: {
- gt: 0,
- },
- programId,
- partnerId,
- },
- });
-
const {
program,
partner,
@@ -63,6 +93,26 @@ export const getReferralsEmbedData = async (token: string) => {
const { totalClicks, totalLeads, totalSales, totalSaleAmount } =
aggregatePartnerLinksStats(links);
+ const [commissions, bounties] = await Promise.all([
+ prisma.commission.groupBy({
+ by: ["status"],
+ _sum: {
+ earnings: true,
+ },
+ where: {
+ earnings: {
+ gt: 0,
+ },
+ programId,
+ partnerId,
+ },
+ }),
+
+ program._count.bounties > 0
+ ? getBountiesForPartner(programEnrollment)
+ : Promise.resolve([]),
+ ]);
+
return {
program,
partner: {
@@ -70,6 +120,7 @@ export const getReferralsEmbedData = async (token: string) => {
name: partner.name,
email: partner.email,
},
+ partnerPlatforms: partner.platforms,
links: z.array(ReferralsEmbedLinkSchema).parse(links),
rewards: [clickReward, leadReward, saleReward]
.filter((r): r is Reward => r !== null)
@@ -83,6 +134,7 @@ export const getReferralsEmbedData = async (token: string) => {
return acc;
}, 0),
paid: commissions.find((c) => c.status === "paid")?._sum.earnings ?? 0,
+ totalCount: programEnrollment._count.commissions,
},
stats: {
clicks: totalClicks,
@@ -90,6 +142,9 @@ export const getReferralsEmbedData = async (token: string) => {
sales: totalSales,
saleAmount: totalSaleAmount,
},
+ programEnrollment: {
+ createdAt: programEnrollment.createdAt,
+ },
group: {
id: group.id,
logo: group.logo,
@@ -100,5 +155,6 @@ export const getReferralsEmbedData = async (token: string) => {
linkStructure: group.linkStructure,
holdingPeriodDays: group.holdingPeriodDays,
},
+ bounties,
};
};
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/[bountyId]/bounty-submissions-table.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/[bountyId]/bounty-submissions-table.tsx
index c49fdee735..bbeef8f9ed 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/[bountyId]/bounty-submissions-table.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/[bountyId]/bounty-submissions-table.tsx
@@ -5,7 +5,7 @@ import {
getSubmissionPeriods,
} from "@/lib/bounty/periods";
import { BOUNTY_SUBMISSION_STATUS_BADGES } from "@/lib/bounty/submission-status";
-import { PartnerBountyProps } from "@/lib/types";
+import { PartnerBountyProps, PartnerBountySubmission } from "@/lib/types";
import { useBountySubmissionDetailsSheet } from "@/ui/partners/bounties/bounty-submission-details-sheet";
import { useClaimBountySheet } from "@/ui/partners/bounties/claim-bounty-sheet";
import { Button, StatusBadge, Table, useTable } from "@dub/ui";
@@ -13,8 +13,6 @@ import { cn, formatDate } from "@dub/utils";
import { ColumnDef } from "@tanstack/react-table";
import { useMemo } from "react";
-type PartnerBountySubmission = PartnerBountyProps["submissions"][number];
-
export function BountySubmissionsTable({
bounty,
}: {
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/bounty-card.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/bounty-card.tsx
index d48dbdbf7c..17ddba859c 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/bounty-card.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/bounty-card.tsx
@@ -16,38 +16,33 @@ import {
formatDateTimeSmart,
} from "@dub/utils";
import Link from "next/link";
-import { useParams, useRouter } from "next/navigation";
+import { useParams } from "next/navigation";
export function PartnerBountyCard({
bounty,
showFullTitle = false,
hideFooter = false,
showRewards = false,
+ href,
+ onClick,
}: {
bounty: PartnerBountyProps;
showFullTitle?: boolean;
hideFooter?: boolean;
showRewards?: boolean;
+ href?: string;
+ onClick?: () => void;
}) {
const { programSlug } = useParams();
- const router = useRouter();
-
+ const As = href ? Link : "div";
return (
- <div
- role="link"
- tabIndex={0}
- onClick={() =>
- router.push(`/programs/${programSlug}/bounties/${bounty.id}`)
- }
- onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
- router.push(`/programs/${programSlug}/bounties/${bounty.id}`);
- }
- }}
- className="border-border-subtle group relative flex w-full cursor-pointer flex-col overflow-hidden rounded-xl border bg-white text-left"
+ <As
+ href={href ?? "#"}
+ onClick={onClick}
+ className="border-border-subtle hover:border-border-default bg-bg-default group relative flex w-full cursor-pointer flex-col overflow-hidden rounded-xl border text-left transition-all hover:shadow-lg"
>
<div className="p-3 pb-0">
- <div className="relative flex h-[124px] items-center justify-center rounded-lg bg-neutral-100">
+ <div className="bg-bg-subtle relative flex h-[124px] items-center justify-center rounded-lg">
<div className="relative size-full">
<BountyThumbnailImage bounty={bounty} />
</div>
@@ -76,7 +71,7 @@ export function PartnerBountyCard({
</div>
{!hideFooter && (
- <div className="border-t border-neutral-200 px-5 py-4">
+ <div className="border-border-subtle border-t px-5 py-4">
{bounty.type === "performance" ? (
<PerformanceBountyProgress bounty={bounty} />
) : (
@@ -85,15 +80,15 @@ export function PartnerBountyCard({
</div>
)}
- {showRewards && bounty.submissions.some((s) => s.commission !== null) && (
- <div className="@3xl/page:block hidden border-t border-neutral-200 p-4">
+ {showRewards && bounty.submissions.some((s) => s.commission != null) && (
+ <div className="@3xl/page:block border-border-subtle hidden border-t p-4">
<BountyRewardsTable
bounty={bounty}
programSlug={programSlug as string}
/>
</div>
)}
- </div>
+ </As>
);
}
@@ -103,11 +98,11 @@ export function BountyRewardsTable({
className,
}: {
bounty: PartnerBountyProps;
- programSlug: string;
+ programSlug?: string;
className?: string;
}) {
const rewards = bounty.submissions
- .filter((s) => s.commission !== null)
+ .filter((s) => s.commission != null)
.map((s) => s.commission!);
const { table, ...tableProps } = useTable({
@@ -148,24 +143,24 @@ export function BountyRewardsTable({
return (
<div className={cn("relative flex flex-col gap-4", className)}>
<div className="flex items-center justify-between">
- <h3 className="@3xl/page:text-sm text-lg font-semibold text-neutral-900">
- Rewards
- </h3>
- <Link
- href={`/programs/${programSlug}/earnings?type=custom`}
- onClick={(e) => e.stopPropagation()}
- className={cn(
- buttonVariants({ variant: "secondary" }),
- "border-border-subtle flex h-6 items-center rounded-md border px-2 text-xs",
- )}
- >
- View all
- </Link>
+ <h3 className="text-content-emphasis text-sm font-semibold">Rewards</h3>
+ {programSlug && (
+ <Link
+ href={`/programs/${programSlug}/earnings?type=custom`}
+ onClick={(e) => e.stopPropagation()}
+ className={cn(
+ buttonVariants({ variant: "secondary" }),
+ "border-border-subtle flex h-6 items-center rounded-md border px-2 text-xs",
+ )}
+ >
+ View all
+ </Link>
+ )}
</div>
<Table
{...tableProps}
table={table}
- containerClassName="border-neutral-200"
+ containerClassName="border-border-subtle"
scrollWrapperClassName="min-h-0"
className="[&_tbody_tr:last-child_td]:border-b-0"
/>
@@ -173,7 +168,7 @@ export function BountyRewardsTable({
);
}
-function BountyEndDate({ bounty }: { bounty: PartnerBountyProps }) {
+export function BountyEndDate({ bounty }: { bounty: PartnerBountyProps }) {
const isExpired =
bounty.endsAt && new Date(bounty.endsAt) < new Date() ? true : false;
@@ -204,14 +199,14 @@ function BountyEndDate({ bounty }: { bounty: PartnerBountyProps }) {
export const PartnerBountyCardSkeleton = () => {
return (
- <div className="border-border-subtle rounded-xl border bg-white p-5">
+ <div className="border-border-subtle bg-bg-default rounded-xl border p-5">
<div className="flex flex-col gap-5">
- <div className="flex h-[132px] animate-pulse items-center justify-center rounded-lg bg-neutral-100 px-32 py-4" />
+ <div className="bg-bg-subtle flex h-[132px] animate-pulse items-center justify-center rounded-lg px-32 py-4" />
<div className="flex flex-col gap-1.5">
- <div className="h-5 w-48 animate-pulse rounded-md bg-neutral-200" />
+ <div className="bg-bg-emphasis h-5 w-48 animate-pulse rounded-md" />
<div className="flex h-5 items-center space-x-2">
- <div className="size-4 animate-pulse rounded bg-neutral-200" />
- <div className="h-4 w-32 animate-pulse rounded bg-neutral-200" />
+ <div className="bg-bg-emphasis size-4 animate-pulse rounded" />
+ <div className="bg-bg-emphasis h-4 w-32 animate-pulse rounded" />
</div>
</div>
</div>
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/page-client.tsx
index 8957114646..00f7da6fe7 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/page-client.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/page-client.tsx
@@ -5,6 +5,7 @@ import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
import { Heart, Trophy } from "@dub/ui/icons";
import { cn } from "@dub/utils";
+import { useParams } from "next/navigation";
import { useMemo, useState } from "react";
import { PartnerBountyCard, PartnerBountyCardSkeleton } from "./bounty-card";
@@ -20,9 +21,9 @@ const tabs = [
] as const;
export function BountiesPageClient() {
+ const { programSlug } = useParams();
const [activeTab, setActiveTab] = useState<"active" | "expired">("active");
const { bounties, bountiesCount, isLoading } = usePartnerProgramBounties();
-
// Filter bounties based on active tab
const filteredBounties = useMemo(() => {
if (!bounties) return [];
@@ -76,7 +77,11 @@ export function BountiesPageClient() {
<div className="grid grid-cols-1 gap-6 md:grid-cols-2 xl:grid-cols-3">
{filteredBounties?.length
? filteredBounties?.map((bounty) => (
- <PartnerBountyCard key={bounty.id} bounty={bounty} />
+ <PartnerBountyCard
+ key={bounty.id}
+ bounty={bounty}
+ href={`/programs/${programSlug}/bounties/${bounty.id}`}
+ />
))
: Array.from({ length: 3 }, (_, index) => (
<PartnerBountyCardSkeleton key={index} />
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/analytics-partners-table.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/analytics-partners-table.tsx
index c570edb1c4..89adaceab8 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/analytics-partners-table.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/analytics/analytics-partners-table.tsx
@@ -198,7 +198,7 @@ export function AnalyticsPartnersTable() {
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 8 }}
transition={{ ease: "easeOut", duration: 0.15 }}
- className="absolute bottom-0 left-0 z-20 flex h-16 w-full items-end bg-gradient-to-t from-white to-white/0"
+ className="absolute bottom-1 left-0 z-20 flex h-16 w-full items-end bg-gradient-to-t from-white to-white/0"
>
<div className="flex w-full items-center justify-center gap-2 pb-2.5">
{stagedPartnerIds !== null && stagedPartnerIds.length > 0 && (
diff --git a/apps/web/lib/actions/partners/create-bounty-submission.ts b/apps/web/lib/actions/partners/create-bounty-submission.ts
index 978e1af91e..5e5d91da67 100644
--- a/apps/web/lib/actions/partners/create-bounty-submission.ts
+++ b/apps/web/lib/actions/partners/create-bounty-submission.ts
@@ -9,10 +9,10 @@ export const createBountySubmissionAction = authPartnerActionClient
.action(async ({ ctx, parsedInput }) => {
const { partner } = ctx;
- const handler = new BountySubmissionHandler({
+ const submissionHandler = new BountySubmissionHandler({
...parsedInput,
partner,
});
- await handler.submit();
+ await submissionHandler.submit();
});
diff --git a/apps/web/lib/actions/partners/upload-bounty-submission-file.ts b/apps/web/lib/actions/partners/upload-bounty-submission-file.ts
index e7ba7530a3..05b1b83621 100644
--- a/apps/web/lib/actions/partners/upload-bounty-submission-file.ts
+++ b/apps/web/lib/actions/partners/upload-bounty-submission-file.ts
@@ -1,123 +1,41 @@
"use server";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
-import { storage } from "@/lib/storage";
-import { ratelimit } from "@/lib/upstash";
-import { submissionRequirementsSchema } from "@/lib/zod/schemas/bounties";
-import { prisma } from "@dub/prisma";
-import { nanoid, R2_URL } from "@dub/utils";
+import { getBountySubmissionUploadUrl } from "@/lib/bounty/api/get-bounty-submission-upload-url";
import * as z from "zod/v4";
import { authPartnerActionClient } from "../safe-action";
const schema = z.object({
programId: z.string(),
bountyId: z.string(),
+ fileName: z.string().trim().min(1),
+ contentType: z.string().trim().min(1),
+ contentLength: z.number().int().positive(),
});
-const MAX_ATTEMPTS = 25;
-const CACHE_KEY_PREFIX = "bounty:submission:file:upload";
-
export const uploadBountySubmissionFileAction = authPartnerActionClient
.inputSchema(schema)
.action(async ({ ctx, parsedInput }) => {
const { partner } = ctx;
- const { programId, bountyId } = parsedInput;
-
- const { success } = await ratelimit(MAX_ATTEMPTS, "24 h").limit(
- `${CACHE_KEY_PREFIX}:${bountyId}:${partner.id}`,
- );
-
- if (!success) {
- throw new Error(
- "You've reached the maximum number of attempts to upload a file for this bounty.",
- );
- }
-
- const [programEnrollment, bounty] = await Promise.all([
- getProgramEnrollmentOrThrow({
- partnerId: partner.id,
- programId,
- include: {},
- }),
-
- prisma.bounty.findUniqueOrThrow({
- where: {
- id: bountyId,
- },
- include: {
- groups: true,
- submissions: {
- where: {
- partnerId: partner.id,
- },
- },
- },
- }),
- ]);
-
- if (!["approved", "pending"].includes(programEnrollment.status)) {
- throw new Error(
- "You are not allowed to submit a bounty for this program.",
- );
- }
-
- if (bounty.programId !== programId) {
- throw new Error("This bounty is not for this program.");
- }
-
- if (bounty.groups.length > 0) {
- const isInGroup = bounty.groups.find(
- ({ groupId }) => groupId === programEnrollment.groupId,
- );
-
- if (!isInGroup) {
- throw new Error("You are not allowed to submit this bounty.");
- }
- }
-
- // Validate the bounty dates
- const now = new Date();
-
- if (bounty.startsAt && bounty.startsAt > now) {
- throw new Error("This bounty is not yet available.");
- }
-
- if (bounty.endsAt && bounty.endsAt < now) {
- throw new Error("This bounty is no longer available.");
- }
-
- if (bounty.archivedAt) {
- throw new Error("This bounty is archived.");
- }
-
- if (bounty.type === "performance") {
- throw new Error("You are not allowed to submit a performance bounty.");
- }
-
- // Validate the submission requirements
- const submissionRequirements = submissionRequirementsSchema.parse(
- bounty.submissionRequirements,
- );
-
- const requireImage = !!submissionRequirements?.image;
-
- if (!requireImage) {
- throw new Error(
- "The submission requirements for this bounty do not allow for file uploads.",
- );
- }
-
- try {
- const key = `programs/${bounty.programId}/bounties/${bounty.id}/submissions/${partner.id}/${nanoid(7)}`;
- const signedUrl = await storage.getSignedUploadUrl({
- key,
- });
-
- return {
- signedUrl,
- destinationUrl: `${R2_URL}/${key}`,
- };
- } catch (e) {
- throw new Error("Failed to get signed URL for upload.");
- }
+ const { programId, bountyId, fileName, contentType, contentLength } =
+ parsedInput;
+
+ const programEnrollment = await getProgramEnrollmentOrThrow({
+ partnerId: partner.id,
+ programId,
+ include: {},
+ });
+
+ const { signedUrl, destinationUrl } = await getBountySubmissionUploadUrl({
+ bountyId,
+ fileName,
+ contentType,
+ contentLength,
+ programEnrollment,
+ });
+
+ return {
+ signedUrl,
+ destinationUrl,
+ };
});
diff --git a/apps/web/lib/api/partner-profile/get-earnings-for-partner.ts b/apps/web/lib/api/partner-profile/get-earnings-for-partner.ts
new file mode 100644
index 0000000000..88b4b3c8ac
--- /dev/null
+++ b/apps/web/lib/api/partner-profile/get-earnings-for-partner.ts
@@ -0,0 +1,100 @@
+import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";
+import { generateRandomName } from "@/lib/names";
+import {
+ getPartnerEarningsQuerySchema,
+ PartnerEarningsSchema,
+} from "@/lib/zod/schemas/partner-profile";
+import { prisma } from "@dub/prisma";
+import * as z from "zod/v4";
+import { obfuscateCustomerEmail } from "./obfuscate-customer-email";
+
+interface GetEarningsForPartnerParams
+ extends z.infer<typeof getPartnerEarningsQuerySchema> {
+ programId: string;
+ partnerId: string;
+ customerDataSharingEnabledAt: Date | null;
+}
+
+export async function getEarningsForPartner(
+ params: GetEarningsForPartnerParams,
+) {
+ const {
+ page = 1,
+ pageSize,
+ type,
+ status,
+ sortBy,
+ sortOrder,
+ linkId,
+ customerId,
+ payoutId,
+ interval,
+ start,
+ end,
+ timezone,
+ programId,
+ partnerId,
+ customerDataSharingEnabledAt,
+ } = params;
+
+ const { startDate, endDate } = getStartEndDates({
+ interval,
+ start,
+ end,
+ timezone,
+ });
+
+ const earnings = await prisma.commission.findMany({
+ where: {
+ earnings: {
+ not: 0,
+ },
+ programId,
+ partnerId,
+ status,
+ type,
+ linkId,
+ customerId,
+ payoutId,
+ createdAt: {
+ gte: startDate,
+ lte: endDate,
+ },
+ },
+ include: {
+ customer: true,
+ link: {
+ select: {
+ id: true,
+ shortLink: true,
+ url: true,
+ },
+ },
+ },
+ skip: (page - 1) * pageSize,
+ take: pageSize,
+ orderBy: {
+ [sortBy]: sortOrder,
+ },
+ });
+
+ return z.array(PartnerEarningsSchema).parse(
+ earnings.map((e) => {
+ // fallback to a random name if the customer doesn't have an email
+ const customerEmail =
+ e.customer?.email || e.customer?.name || generateRandomName();
+ return {
+ ...e,
+ customer: e.customer
+ ? {
+ ...e.customer,
+ email: customerDataSharingEnabledAt
+ ? customerEmail
+ : obfuscateCustomerEmail(customerEmail),
+ country: e.customer?.country,
+ }
+ : null,
+ };
+ }),
+ );
+}
diff --git a/apps/web/lib/bounty/api/create-bounty-submission.ts b/apps/web/lib/bounty/api/create-bounty-submission.ts
index dd0f226373..94cf3b3ace 100644
--- a/apps/web/lib/bounty/api/create-bounty-submission.ts
+++ b/apps/web/lib/bounty/api/create-bounty-submission.ts
@@ -1,4 +1,5 @@
import { createId } from "@/lib/api/create-id";
+import { DubApiError } from "@/lib/api/errors";
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";
@@ -131,14 +132,20 @@ export class BountySubmissionHandler {
// Multi-submission WITHOUT frequency — all periods open
if (!this.bounty.submissionFrequency) {
if (!this.periodNumber) {
- throw new Error("Period number is required for this bounty.");
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Period number is required for this bounty.",
+ });
}
if (
this.periodNumber < 1 ||
this.periodNumber > this.bounty.maxSubmissions
) {
- throw new Error("Invalid submission period number.");
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Invalid submission period number.",
+ });
}
this.finalPeriodNumber = this.periodNumber;
@@ -159,14 +166,20 @@ export class BountySubmissionHandler {
periodNumber = this.periodNumber;
} else {
if (!currentPeriod) {
- throw new Error("No active submission period for this bounty.");
+ throw new DubApiError({
+ code: "bad_request",
+ message: "No active submission period for this bounty.",
+ });
}
periodNumber = currentPeriod;
}
if (periodNumber < 1 || periodNumber > this.bounty.maxSubmissions) {
- throw new Error("Invalid submission period number.");
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Invalid submission period number.",
+ });
}
// Validate the period has started
@@ -177,11 +190,17 @@ export class BountySubmissionHandler {
});
if (new Date() < periodStart) {
- throw new Error("This submission period hasn't started yet.");
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This submission period hasn't started yet.",
+ });
}
if (currentPeriod && periodNumber < currentPeriod) {
- throw new Error("This submission period has already closed.");
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This submission period has already closed.",
+ });
}
this.finalPeriodNumber = periodNumber;
@@ -190,13 +209,17 @@ export class BountySubmissionHandler {
// Validate the eligibility of the submission
private validateEligibility() {
if (!["approved", "pending"].includes(this.programEnrollment.status)) {
- throw new Error(
- "You are not allowed to submit a bounty for this program.",
- );
+ throw new DubApiError({
+ code: "forbidden",
+ message: "You are not allowed to submit a bounty for this program.",
+ });
}
if (this.bounty.programId !== this.programId) {
- throw new Error("This bounty is not for this program.");
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This bounty is not for this program.",
+ });
}
// Check existing submission for this period
@@ -212,18 +235,20 @@ export class BountySubmissionHandler {
existingSubmission.status === "approved" ||
existingSubmission.status === "rejected"
) {
- throw new Error(
- `You already have a ${existingSubmission.status} submission for this period.`,
- );
+ throw new DubApiError({
+ code: "conflict",
+ message: `You already have a ${existingSubmission.status} submission for this period.`,
+ });
}
if (
existingSubmission.status !== "draft" &&
!bountyInfo?.hasSocialMetrics
) {
- throw new Error(
- `You already have a ${existingSubmission.status} submission for this period.`,
- );
+ throw new DubApiError({
+ code: "conflict",
+ message: `You already have a ${existingSubmission.status} submission for this period.`,
+ });
}
}
@@ -234,7 +259,10 @@ export class BountySubmissionHandler {
);
if (!isInGroup) {
- throw new Error("You are not allowed to submit this bounty.");
+ throw new DubApiError({
+ code: "forbidden",
+ message: "You are not allowed to submit this bounty.",
+ });
}
}
@@ -242,19 +270,31 @@ export class BountySubmissionHandler {
const now = new Date();
if (this.bounty.startsAt && this.bounty.startsAt > now) {
- throw new Error("This bounty is not yet available.");
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This bounty is not yet available.",
+ });
}
if (this.bounty.endsAt && this.bounty.endsAt < now) {
- throw new Error("This bounty is no longer available.");
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This bounty is no longer available.",
+ });
}
if (this.bounty.archivedAt) {
- throw new Error("This bounty is archived.");
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This bounty is archived.",
+ });
}
if (this.bounty.type === "performance") {
- throw new Error("You are not allowed to submit a performance bounty.");
+ throw new DubApiError({
+ code: "forbidden",
+ message: "You are not allowed to submit a performance bounty.",
+ });
}
if (
@@ -266,15 +306,18 @@ export class BountySubmissionHandler {
addSuffix: true,
});
- throw new Error(
- `Submissions are not open yet. You can submit ${waitTime}.`,
- );
+ throw new DubApiError({
+ code: "bad_request",
+ message: `Submissions are not open yet. You can submit ${waitTime}.`,
+ });
}
if (bountyInfo?.hasSocialMetrics && this.isDraft) {
- throw new Error(
- "Draft submissions are not allowed for social metrics bounties.",
- );
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "Draft submissions are not allowed for social metrics bounties.",
+ });
}
}
@@ -295,27 +338,35 @@ export class BountySubmissionHandler {
if (!this.isDraft) {
if (requireImage && this.files.length === 0) {
- throw new Error("You must submit an image.");
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: "You must submit an image.",
+ });
}
if (requireUrl && this.urls.length === 0) {
- throw new Error("You must submit a URL.");
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: "You must submit a URL.",
+ });
}
this.validateUrlDomains(urlRequirement);
// Validate max count for URLs
if (urlRequirement?.max && this.urls.length > urlRequirement.max) {
- throw new Error(
- `You can submit at most ${urlRequirement.max} URL${urlRequirement.max === 1 ? "" : "s"}.`,
- );
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: `You can submit at most ${urlRequirement.max} URL${urlRequirement.max === 1 ? "" : "s"}.`,
+ });
}
// Validate max count for images
if (imageRequirement?.max && this.files.length > imageRequirement.max) {
- throw new Error(
- `You can submit at most ${imageRequirement.max} image${imageRequirement.max === 1 ? "" : "s"}.`,
- );
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: `You can submit at most ${imageRequirement.max} image${imageRequirement.max === 1 ? "" : "s"}.`,
+ });
}
this.submissionData = {
@@ -364,9 +415,10 @@ export class BountySubmissionHandler {
if (invalidUrls.length > 0) {
const domainsList = allowedDomains.join(", ");
- throw new Error(
- `All URLs must be from one of the following domains: ${domainsList}. Please check your submission.`,
- );
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: `All URLs must be from one of the following domains: ${domainsList}. Please check your submission.`,
+ });
}
}
@@ -381,23 +433,28 @@ export class BountySubmissionHandler {
const contentUrl = this.urls[0];
if (!bountyInfo.socialPlatform) {
- throw new Error("Invalid bounty platform.");
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Invalid bounty platform.",
+ });
}
const platform = bountyInfo.socialPlatform;
if (!contentUrl) {
- throw new Error(
- `You must provide a ${platform.label} URL to submit this bounty.`,
- );
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: `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.`,
- );
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: `This link must be a ${platform.label} link. You submitted a link from another platform.`,
+ });
}
const partnerPlatform = await prisma.partnerPlatform.findUnique({
@@ -414,15 +471,17 @@ export class BountySubmissionHandler {
});
if (!partnerPlatform) {
- throw new Error(
- `You must connect your ${platform.label} account to your profile before submitting this bounty.`,
- );
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: `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.`,
- );
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: `You must verify your ${platform.label} account before submitting this bounty.`,
+ });
}
const socialContent = await getSocialContent({
@@ -431,18 +490,21 @@ export class BountySubmissionHandler {
});
if (!socialContent.handle || !socialContent.publishedAt) {
- throw new Error(
- "We were unable to verify this content. Please review the submission and try again.",
- );
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message:
+ "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.`,
- );
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: `The content was not published from your connected ${platform.label} account.`,
+ });
}
if (
@@ -450,9 +512,11 @@ export class BountySubmissionHandler {
this.bounty.startsAt &&
isBefore(socialContent.publishedAt, this.bounty.startsAt)
) {
- throw new Error(
- `This content was published before the bounty started. Please submit content posted after the start date.`,
- );
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message:
+ "This content was published before the bounty started. Please submit content posted after the start date.",
+ });
}
this.submissionData = {
diff --git a/apps/web/lib/bounty/api/get-bounties-for-partner.ts b/apps/web/lib/bounty/api/get-bounties-for-partner.ts
new file mode 100644
index 0000000000..77bc71df9e
--- /dev/null
+++ b/apps/web/lib/bounty/api/get-bounties-for-partner.ts
@@ -0,0 +1,91 @@
+import {
+ aggregatePartnerLinksStats,
+ PartnerLink,
+} from "@/lib/partners/aggregate-partner-links-stats";
+import { PartnerBountySchema } from "@/lib/zod/schemas/partner-profile";
+import { prisma } from "@dub/prisma";
+import { Program, ProgramEnrollment } from "@dub/prisma/client";
+import * as z from "zod/v4";
+
+type GetBountiesForPartnerParams = Pick<
+ ProgramEnrollment,
+ "groupId" | "partnerId" | "totalCommissions"
+> & {
+ links: PartnerLink[];
+ program: Pick<Program, "id" | "defaultGroupId">;
+};
+
+export async function getBountiesForPartner(
+ params: GetBountiesForPartnerParams,
+) {
+ const { groupId, partnerId, totalCommissions, program, links } = params;
+
+ const now = new Date();
+
+ const bounties = await prisma.bounty.findMany({
+ where: {
+ programId: program.id,
+ startsAt: {
+ lte: now,
+ },
+ // If bounty has no groups, it's available to all partners
+ // If bounty has groups, only partners in those groups can see it
+ AND: [
+ {
+ OR: [
+ {
+ groups: {
+ none: {},
+ },
+ },
+ {
+ groups: {
+ some: {
+ groupId: groupId || program.defaultGroupId,
+ },
+ },
+ },
+ ],
+ },
+ {
+ OR: [{ endsAt: null }, { endsAt: { gte: now } }],
+ },
+ ],
+ },
+ include: {
+ workflow: {
+ select: {
+ triggerConditions: true,
+ },
+ },
+ submissions: {
+ where: {
+ partnerId,
+ },
+ include: {
+ commission: {
+ select: {
+ id: true,
+ earnings: true,
+ status: true,
+ createdAt: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ const partnerLinkStats = aggregatePartnerLinksStats(links);
+
+ return z.array(PartnerBountySchema).parse(
+ bounties.map((bounty) => ({
+ ...bounty,
+ performanceCondition: bounty.workflow?.triggerConditions?.[0] || null,
+ partner: {
+ ...partnerLinkStats,
+ totalCommissions,
+ },
+ })),
+ );
+}
diff --git a/apps/web/lib/bounty/api/get-bounty-submission-upload-url.ts b/apps/web/lib/bounty/api/get-bounty-submission-upload-url.ts
new file mode 100644
index 0000000000..246c634443
--- /dev/null
+++ b/apps/web/lib/bounty/api/get-bounty-submission-upload-url.ts
@@ -0,0 +1,180 @@
+import { DubApiError } from "@/lib/api/errors";
+import { storage } from "@/lib/storage";
+import { ratelimit } from "@/lib/upstash";
+import { submissionRequirementsSchema } from "@/lib/zod/schemas/bounties";
+import { prisma } from "@dub/prisma";
+import { ProgramEnrollment } from "@dub/prisma/client";
+import { nanoid, R2_URL } from "@dub/utils";
+
+const MAX_ATTEMPTS = 25;
+const CACHE_KEY_PREFIX = "bounty:submission:file:upload";
+
+type GetBountySubmissionUploadUrlParams = {
+ bountyId: string;
+ fileName: string;
+ contentType: string;
+ contentLength: number;
+ programEnrollment: Pick<
+ ProgramEnrollment,
+ "programId" | "partnerId" | "groupId"
+ >;
+};
+
+const MAX_UPLOAD_SIZE_BYTES = 5 * 1024 * 1024;
+const ALLOWED_IMAGE_CONTENT_TYPES = new Set([
+ "image/jpeg",
+ "image/png",
+ "image/webp",
+ "image/svg+xml",
+]);
+
+export async function getBountySubmissionUploadUrl({
+ bountyId,
+ fileName,
+ contentType,
+ contentLength,
+ programEnrollment,
+}: GetBountySubmissionUploadUrlParams) {
+ const { programId, partnerId } = programEnrollment;
+
+ if (!fileName.trim()) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: "File name is required.",
+ });
+ }
+
+ if (!ALLOWED_IMAGE_CONTENT_TYPES.has(contentType)) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: "Unsupported file type. Please upload SVG, JPG, PNG, or WEBP.",
+ });
+ }
+
+ if (
+ !Number.isInteger(contentLength) ||
+ contentLength <= 0 ||
+ contentLength > MAX_UPLOAD_SIZE_BYTES
+ ) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: "File size exceeds maximum of 5MB.",
+ });
+ }
+
+ const { success } = await ratelimit(MAX_ATTEMPTS, "24 h").limit(
+ `${CACHE_KEY_PREFIX}:${bountyId}:${partnerId}`,
+ );
+
+ if (!success) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message:
+ "You've reached the maximum number of attempts to upload a file for this bounty.",
+ });
+ }
+
+ const bounty = await prisma.bounty.findUniqueOrThrow({
+ where: {
+ id: bountyId,
+ },
+ select: {
+ programId: true,
+ type: true,
+ startsAt: true,
+ endsAt: true,
+ archivedAt: true,
+ submissionRequirements: true,
+ groups: {
+ select: {
+ groupId: true,
+ },
+ },
+ },
+ });
+
+ if (bounty.programId !== programId) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "This bounty is not for this program.",
+ });
+ }
+
+ if (bounty.groups.length > 0) {
+ const isInGroup = bounty.groups.find(
+ ({ groupId }) => groupId === programEnrollment.groupId,
+ );
+
+ if (!isInGroup) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "You are not allowed to submit this bounty.",
+ });
+ }
+ }
+
+ // Validate the bounty dates
+ const now = new Date();
+
+ if (bounty.startsAt && bounty.startsAt > now) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "This bounty is not yet available.",
+ });
+ }
+
+ if (bounty.endsAt && bounty.endsAt < now) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "This bounty is no longer available.",
+ });
+ }
+
+ if (bounty.archivedAt) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "This bounty is archived.",
+ });
+ }
+
+ if (bounty.type === "performance") {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "You are not allowed to submit a performance bounty.",
+ });
+ }
+
+ // Validate the submission requirements
+ const submissionRequirements = submissionRequirementsSchema.parse(
+ bounty.submissionRequirements,
+ );
+
+ const requireImage = !!submissionRequirements?.image;
+
+ if (!requireImage) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message:
+ "The submission requirements for this bounty do not allow for file uploads.",
+ });
+ }
+
+ try {
+ const key = `programs/${programId}/bounties/${bountyId}/submissions/${partnerId}/${nanoid(7)}`;
+ const signedUrl = await storage.getSignedUploadUrl({
+ key,
+ contentLength,
+ contentType,
+ });
+
+ return {
+ signedUrl,
+ destinationUrl: `${R2_URL}/${key}`,
+ };
+ } catch (e) {
+ throw new DubApiError({
+ code: "internal_server_error",
+ message: "Failed to get signed URL for upload.",
+ });
+ }
+}
diff --git a/apps/web/lib/bounty/api/get-group-bounty-summaries.ts b/apps/web/lib/bounty/api/get-group-bounty-summaries.ts
index 1fdfc5b614..4b20ec3b84 100644
--- a/apps/web/lib/bounty/api/get-group-bounty-summaries.ts
+++ b/apps/web/lib/bounty/api/get-group-bounty-summaries.ts
@@ -1,12 +1,6 @@
import { prisma } from "@dub/prisma";
import { BountyType } from "@dub/prisma/client";
-export type GroupBountySummary = {
- id: string;
- name: string;
- type: BountyType;
-};
-
type BountyEligibilityCandidate = {
id: string;
name: string | null;
diff --git a/apps/web/lib/partners/aggregate-partner-links-stats.ts b/apps/web/lib/partners/aggregate-partner-links-stats.ts
index db79bdd0b7..fe2f6d3d7c 100644
--- a/apps/web/lib/partners/aggregate-partner-links-stats.ts
+++ b/apps/web/lib/partners/aggregate-partner-links-stats.ts
@@ -1,13 +1,14 @@
import { toCentsNumber } from "@dub/utils";
import { LinkProps } from "../types";
-export function aggregatePartnerLinksStats(
- links?:
- | (Pick<LinkProps, "clicks" | "leads" | "conversions" | "sales"> & {
- saleAmount: number | bigint;
- })[]
- | null,
-) {
+export type PartnerLink = Pick<
+ LinkProps,
+ "clicks" | "leads" | "conversions" | "sales"
+> & {
+ saleAmount: number | bigint;
+};
+
+export function aggregatePartnerLinksStats(links?: PartnerLink[] | null) {
if (!links || links.length === 0) {
return {
totalClicks: 0,
diff --git a/apps/web/lib/storage.ts b/apps/web/lib/storage.ts
index aa7591d690..b136a91991 100644
--- a/apps/web/lib/storage.ts
+++ b/apps/web/lib/storage.ts
@@ -143,15 +143,24 @@ class StorageClient {
bucket?: BucketType;
expiresIn?: number;
contentLength?: number;
+ contentType?: string;
}) {
+ const headers: Record<string, string> = {};
+
+ if (opts.contentLength) {
+ headers["Content-Length"] = String(opts.contentLength);
+ }
+
+ if (opts.contentType) {
+ headers["Content-Type"] = opts.contentType;
+ }
+
return await this.getSignedUrl({
key: opts.key,
method: "PUT",
bucket: opts.bucket || "public",
expiresIn: opts.expiresIn || 600,
- headers: opts.contentLength
- ? { "Content-Length": String(opts.contentLength) }
- : undefined,
+ headers: Object.keys(headers).length > 0 ? headers : undefined,
});
}
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 4114737a19..4009dbd879 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -1,5 +1,6 @@
import {
PartnerBountySchema,
+ partnerBountySubmissionSchema,
PartnerEarningsSchema,
partnerPayoutMethodSchema,
PartnerProfileCustomerSchema,
@@ -887,3 +888,7 @@ export type CommissionDetail = z.infer<typeof CommissionDetailSchema>;
export type NullableOptional<T> = {
[K in keyof T]?: T[K] | null;
};
+
+export type PartnerBountySubmission = z.infer<
+ typeof partnerBountySubmissionSchema
+>;
diff --git a/apps/web/lib/zod/schemas/partner-profile.ts b/apps/web/lib/zod/schemas/partner-profile.ts
index 738f804de9..2cdd58ee61 100644
--- a/apps/web/lib/zod/schemas/partner-profile.ts
+++ b/apps/web/lib/zod/schemas/partner-profile.ts
@@ -57,6 +57,7 @@ export const getPartnerEarningsQuerySchema = getCommissionsQuerySchema
.extend({
interval: z
.enum(DATE_RANGE_INTERVAL_PRESETS)
+ .optional()
.default(DUB_PARTNERS_ANALYTICS_INTERVAL),
timezone: z.string().optional(),
type: z.enum(CommissionType).optional(),
diff --git a/apps/web/lib/zod/schemas/partners.ts b/apps/web/lib/zod/schemas/partners.ts
index 43bf4ec8fa..928b1f8202 100644
--- a/apps/web/lib/zod/schemas/partners.ts
+++ b/apps/web/lib/zod/schemas/partners.ts
@@ -513,8 +513,6 @@ export const WebhookPartnerSchema = PartnerSchema.pick({
export const LeaderboardPartnerSchema = z.object({
id: z.string(),
- name: z.string(),
- image: z.string(),
totalCommissions: centsSchemaWithDefault,
});
diff --git a/apps/web/ui/partners/bounties/bounty-description.tsx b/apps/web/ui/partners/bounties/bounty-description.tsx
index b4a6e28875..82d51ff91e 100644
--- a/apps/web/ui/partners/bounties/bounty-description.tsx
+++ b/apps/web/ui/partners/bounties/bounty-description.tsx
@@ -12,7 +12,7 @@ export function BountyDescription({ bounty }: { bounty: PartnerBountyProps }) {
return (
<div>
- <h3 className="text-content-emphasis text-lg font-semibold">
+ <h3 className="text-content-emphasis text-sm font-semibold">
Bounty details
</h3>
@@ -20,7 +20,7 @@ export function BountyDescription({ bounty }: { bounty: PartnerBountyProps }) {
<Markdown
className={cn(
PROSE_STYLES.default,
- "text-sm font-normal text-neutral-600",
+ "text-content-subtle text-sm font-normal",
)}
>
{description}
diff --git a/apps/web/ui/partners/bounties/bounty-progress-bar-row.tsx b/apps/web/ui/partners/bounties/bounty-progress-bar-row.tsx
index 9151f7f1ba..7bab3aa575 100644
--- a/apps/web/ui/partners/bounties/bounty-progress-bar-row.tsx
+++ b/apps/web/ui/partners/bounties/bounty-progress-bar-row.tsx
@@ -3,7 +3,9 @@ import { ReactNode } from "react";
export function EmphasisNumber({ children }: { children: ReactNode }) {
return (
- <span className="text-content-emphasis font-semibold">{children}</span>
+ <span className="text-content-emphasis text-sm font-semibold">
+ {children}
+ </span>
);
}
@@ -28,7 +30,7 @@ export function BountyProgressBarRow({
wrapperClassName ?? "gap-2",
)}
>
- <div className="h-1 w-full overflow-hidden rounded-full bg-neutral-200">
+ <div className="bg-bg-emphasis h-1 w-full overflow-hidden rounded-full">
<div
className={cn(
"h-full rounded-full",
diff --git a/apps/web/ui/partners/bounties/bounty-reward-criteria.tsx b/apps/web/ui/partners/bounties/bounty-reward-criteria.tsx
index 94c2dd38b3..c58e1b8e57 100644
--- a/apps/web/ui/partners/bounties/bounty-reward-criteria.tsx
+++ b/apps/web/ui/partners/bounties/bounty-reward-criteria.tsx
@@ -57,7 +57,7 @@ export function BountyRewardCriteria({
return (
<div>
- <h3 className="text-content-emphasis text-lg font-semibold">
+ <h3 className="text-content-emphasis text-sm font-semibold">
Reward criteria
</h3>
@@ -65,7 +65,9 @@ export function BountyRewardCriteria({
{rewardTexts.map((text) => (
<div className="flex items-center gap-1.5" key={text}>
<Check2 className="size-3 shrink-0 text-green-600" />
- <span className="text-sm font-normal text-neutral-600">{text}</span>
+ <span className="text-content-subtle text-sm font-normal">
+ {text}
+ </span>
</div>
))}
</div>
diff --git a/apps/web/ui/partners/bounties/bounty-reward-description.tsx b/apps/web/ui/partners/bounties/bounty-reward-description.tsx
index 9222f2c1e8..4fbd39295d 100644
--- a/apps/web/ui/partners/bounties/bounty-reward-description.tsx
+++ b/apps/web/ui/partners/bounties/bounty-reward-description.tsx
@@ -31,7 +31,7 @@ export function BountyRewardDescription({
>
<div className="flex items-center gap-2">
<Gift className="size-3.5 shrink-0" />
- <span>{description}</span>
+ <span className="max-w-[240px] truncate">{description}</span>
</div>
<BountyIncrementalBonusTooltip
diff --git a/apps/web/ui/partners/bounties/bounty-social-content.tsx b/apps/web/ui/partners/bounties/bounty-social-content.tsx
index 2fd8ed526a..6a84281d39 100644
--- a/apps/web/ui/partners/bounties/bounty-social-content.tsx
+++ b/apps/web/ui/partners/bounties/bounty-social-content.tsx
@@ -6,39 +6,12 @@ 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 { Button, CircleCheckFill, LoadingSpinner } from "@dub/ui";
import { cn, formatDate } from "@dub/utils";
-import { isBefore } from "date-fns";
+import { useReferralsEmbedData } from "app/(ee)/app.dub.co/embed/referrals/page-client";
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,
- };
-}
+import { evaluateSocialContentRequirements } from "./evaluate-social-content-requirements";
function SocialContentRequirementChecks({
content,
@@ -57,7 +30,7 @@ function SocialContentRequirementChecks({
);
const { isPostedFromYourAccount, isAfterStartDate } =
- socialContentRequirementChecks({
+ evaluateSocialContentRequirements({
content,
bounty,
partnerPlatform,
@@ -136,7 +109,7 @@ export function SocialContentUrlField({
);
useEffect(() => {
- const checks = socialContentRequirementChecks({
+ const checks = evaluateSocialContentRequirements({
content: data,
bounty,
partnerPlatform,
@@ -217,33 +190,32 @@ export function SocialAccountNotVerifiedWarning({
}) {
const bountyInfo = resolveBountyDetails(bounty);
+ const { program, partner } = useReferralsEmbedData();
+
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">
+ <div className="bg-bg-attention flex flex-col items-center justify-between gap-2 rounded-lg p-2 text-center sm:flex-row">
+ <div className="text-content-attention px-2 text-sm font-medium">
{`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"
+ <a
+ href="https://dub.co/help/article/partner-profile#website-and-socials"
target="_blank"
className="ml-1 underline underline-offset-2"
>
Learn more
- </Link>
+ </a>
</div>
- <ButtonLink
- variant="primary"
- href="/profile"
+ <a
+ href={`https://partners.dub.co/${program.slug}/register?email=${partner.email}`}
target="_blank"
- rel="noopener noreferrer"
- className="h-7 w-full justify-center rounded-lg"
>
- View profile
- </ButtonLink>
+ <Button text="Update profile" className="h-7 w-full px-3 sm:w-fit" />
+ </a>
</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
index 906c0c6f67..880a0b964b 100644
--- a/apps/web/ui/partners/bounties/bounty-social-metrics-rewards-table.tsx
+++ b/apps/web/ui/partners/bounties/bounty-social-metrics-rewards-table.tsx
@@ -95,7 +95,7 @@ export function BountySocialMetricsRewardsTable({
minSize: 100,
size: 120,
cell: ({ row: { original } }) => (
- <span className="font-medium text-neutral-800">
+ <span className="text-content-default font-medium">
{original.threshold.toLocaleString()}
</span>
),
@@ -145,7 +145,9 @@ export function BountySocialMetricsRewardsTable({
return (
<div>
- <h2 className="text-base font-semibold text-neutral-900">{titleText}</h2>
+ <h2 className="text-content-emphasis text-base font-semibold">
+ {titleText}
+ </h2>
<div className="mt-3">
<Table {...table} />
</div>
diff --git a/apps/web/ui/partners/bounties/bounty-status-badge.tsx b/apps/web/ui/partners/bounties/bounty-status-badge.tsx
index 9e8651916f..46c849dbc2 100644
--- a/apps/web/ui/partners/bounties/bounty-status-badge.tsx
+++ b/apps/web/ui/partners/bounties/bounty-status-badge.tsx
@@ -96,7 +96,7 @@ export function BountyStatusBadge({ bounty }: { bounty: PartnerBountyProps }) {
<StatusBadge
variant="error"
icon={null}
- className="bg-red-100 text-xs font-semibold text-red-700"
+ className="bg-bg-error text-content-error text-xs font-semibold"
>
Expired {endsAtFormatted}
</StatusBadge>
@@ -106,7 +106,7 @@ export function BountyStatusBadge({ bounty }: { bounty: PartnerBountyProps }) {
<StatusBadge
variant="warning"
icon={null}
- className="bg-amber-100 text-xs font-semibold text-amber-700"
+ className="bg-bg-attention text-content-attention text-xs font-semibold"
>
Expiring soon {endsAtFormatted}
</StatusBadge>
@@ -116,7 +116,7 @@ export function BountyStatusBadge({ bounty }: { bounty: PartnerBountyProps }) {
<StatusBadge
variant="success"
icon={null}
- className="bg-green-100 text-xs font-semibold text-green-700"
+ className="bg-bg-success text-content-success text-xs font-semibold"
>
Completed {completedAtFormatted}
</StatusBadge>
@@ -126,7 +126,7 @@ export function BountyStatusBadge({ bounty }: { bounty: PartnerBountyProps }) {
<StatusBadge
variant="new"
icon={null}
- className="bg-blue-100 text-xs font-semibold text-blue-700"
+ className="bg-bg-info text-content-info text-xs font-semibold"
>
New
</StatusBadge>
diff --git a/apps/web/ui/partners/bounties/bounty-submission-details-sheet.tsx b/apps/web/ui/partners/bounties/bounty-submission-details-sheet.tsx
index d0e0528daf..8ba7fcea22 100644
--- a/apps/web/ui/partners/bounties/bounty-submission-details-sheet.tsx
+++ b/apps/web/ui/partners/bounties/bounty-submission-details-sheet.tsx
@@ -4,7 +4,7 @@ import { REJECT_BOUNTY_SUBMISSION_REASONS } from "@/lib/bounty/constants";
import { getPeriodLabel } from "@/lib/bounty/periods";
import { BOUNTY_SUBMISSION_STATUS_BADGES } from "@/lib/bounty/submission-status";
import { resolveBountyDetails } from "@/lib/bounty/utils";
-import { PartnerBountyProps } from "@/lib/types";
+import { PartnerBountyProps, PartnerBountySubmission } from "@/lib/types";
import { CommissionStatusBadges } from "@/ui/partners/commission-status-badges";
import { X } from "@/ui/shared/icons";
import {
@@ -33,8 +33,6 @@ import { EmphasisNumber } from "./bounty-progress-bar-row";
import { BountySocialContentPreview } from "./bounty-social-content-preview";
import { BountySocialMetricsRewardsTable } from "./bounty-social-metrics-rewards-table";
-type PartnerBountySubmission = PartnerBountyProps["submissions"][number];
-
interface BountySubmissionDetailsSheetProps {
bounty: PartnerBountyProps;
submission: PartnerBountySubmission;
@@ -44,7 +42,7 @@ interface BountySubmissionDetailsSheetProps {
onPrevious?: () => void;
}
-function SocialContentPreview({
+export function SocialContentPreview({
bounty,
submission,
}: {
@@ -72,21 +70,21 @@ function SocialContentPreview({
return (
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between">
- <h2 className="text-base font-semibold text-neutral-800">
+ <h2 className="text-content-emphasis text-base font-semibold">
Submitted content
</h2>
{lastSyncedAt && (
- <span className="text-xs font-medium text-neutral-400">
+ <span className="text-content-subtle text-xs font-medium">
Last sync{" "}
{formatDistanceToNow(new Date(lastSyncedAt), { addSuffix: true })}
</span>
)}
</div>
- <div className="rounded-xl border border-neutral-200 bg-neutral-50">
+ <div className="border-border-default bg-bg-subtle rounded-xl border">
{/* Progress section */}
<div className="flex flex-col gap-3 px-4 pb-3 pt-4">
- <div className="h-1 w-full rounded-full bg-neutral-200">
+ <div className="bg-bg-emphasis h-1 w-full rounded-full">
<div
className={cn(
"h-full rounded-full",
@@ -98,7 +96,7 @@ function SocialContentPreview({
<div className="flex items-center gap-2">
<PlatformIcon className="size-4 shrink-0" />
- <p className="text-sm font-medium text-neutral-600">
+ <p className="text-content-subtle text-sm font-medium">
<EmphasisNumber>
{nFormatter(socialMetricCount, { full: true })}
</EmphasisNumber>
@@ -305,7 +303,7 @@ function SubmissionDetailsView({
);
}
-function SubmissionRewardTable({
+export function SubmissionRewardTable({
submission,
}: {
submission: PartnerBountySubmission;
@@ -364,12 +362,12 @@ function SubmissionRewardTable({
return (
<div>
- <h2 className="text-base font-semibold text-neutral-800">Rewards</h2>
+ <h2 className="text-content-emphasis text-base font-semibold">Rewards</h2>
<div className="mt-2">
<Table
{...tableProps}
table={table}
- containerClassName="border-neutral-200"
+ containerClassName="border-border-default"
scrollWrapperClassName="min-h-0"
className="[&_tbody_tr:last-child_td]:border-b-0"
/>
diff --git a/apps/web/ui/partners/bounties/bounty-submission-requirements.tsx b/apps/web/ui/partners/bounties/bounty-submission-requirements.tsx
index 6d4107a8dc..576937333b 100644
--- a/apps/web/ui/partners/bounties/bounty-submission-requirements.tsx
+++ b/apps/web/ui/partners/bounties/bounty-submission-requirements.tsx
@@ -50,7 +50,7 @@ export function BountySubmissionRequirements({
return (
<div>
- <h3 className="text-content-emphasis text-lg font-semibold">
+ <h3 className="text-content-emphasis text-sm font-semibold">
Submission requirements
</h3>
@@ -58,7 +58,9 @@ export function BountySubmissionRequirements({
{submissionTexts.map((text) => (
<div className="flex items-center gap-1.5" key={text}>
<Check2 className="size-3 shrink-0 text-green-600" />
- <span className="text-sm font-normal text-neutral-600">{text}</span>
+ <span className="text-content-subtle text-sm font-normal">
+ {text}
+ </span>
</div>
))}
</div>
diff --git a/apps/web/ui/partners/bounties/claim-bounty-sheet.tsx b/apps/web/ui/partners/bounties/claim-bounty-sheet.tsx
index 27aa683002..73a86d2b65 100644
--- a/apps/web/ui/partners/bounties/claim-bounty-sheet.tsx
+++ b/apps/web/ui/partners/bounties/claim-bounty-sheet.tsx
@@ -95,6 +95,9 @@ function ImagesField({
const result = await uploadFile({
programId: programEnrollment.programId,
bountyId: bounty.id,
+ fileName: file.name,
+ contentType: file.type,
+ contentLength: file.size,
});
if (!result?.data) {
diff --git a/apps/web/ui/partners/bounties/evaluate-social-content-requirements.ts b/apps/web/ui/partners/bounties/evaluate-social-content-requirements.ts
new file mode 100644
index 0000000000..b7424be304
--- /dev/null
+++ b/apps/web/ui/partners/bounties/evaluate-social-content-requirements.ts
@@ -0,0 +1,32 @@
+import {
+ PartnerBountyProps,
+ PartnerPlatformProps,
+ SocialContent,
+} from "@/lib/types";
+import { isBefore } from "date-fns/isBefore";
+
+export function evaluateSocialContentRequirements({
+ content,
+ bounty,
+ partnerPlatform,
+}: {
+ content?: SocialContent | null;
+ bounty: Pick<PartnerBountyProps, "startsAt">;
+ partnerPlatform?: Pick<PartnerPlatformProps, "identifier" | "verifiedAt">;
+}) {
+ 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,
+ };
+}
diff --git a/apps/web/ui/partners/program-reward-terms.tsx b/apps/web/ui/partners/program-reward-terms.tsx
index e60e42506c..7ed352c8e7 100644
--- a/apps/web/ui/partners/program-reward-terms.tsx
+++ b/apps/web/ui/partners/program-reward-terms.tsx
@@ -1,4 +1,5 @@
import { currencyFormatter } from "@dub/utils";
+import { Fragment } from "react";
export function ProgramRewardTerms({
minPayoutAmount,
@@ -35,7 +36,7 @@ export function ProgramRewardTerms({
return (
<div className="border-border-subtle text-content-subtle -mt-1 flex items-center gap-1 rounded-b-md rounded-t-none border border-t-0 p-1.5 pl-2.5 pt-2.5 text-xs">
{items.map((item, index) => (
- <>
+ <Fragment key={item.label}>
<span key={item.label}>
<span className="text-content-emphasis font-semibold">
{item.value}
@@ -50,7 +51,7 @@ export function ProgramRewardTerms({
</a>
</span>
{index < items.length - 1 && "•"}
- </>
+ </Fragment>
))}
</div>
);
diff --git a/packages/email/src/templates/broadcasts/dub-product-update-mar26.tsx b/packages/email/src/templates/broadcasts/dub-product-update-mar26.tsx
index 8ab5ec32f2..381c9f72dc 100644
--- a/packages/email/src/templates/broadcasts/dub-product-update-mar26.tsx
+++ b/packages/email/src/templates/broadcasts/dub-product-update-mar26.tsx
@@ -402,8 +402,7 @@ export default function DubProductUpdateMar26({
• Bounties, Commissions, and Payouts APIs
<br />
• “Paid” and “Canceled” columns on customer tables
- <br />
- • Group reward update logs for auditability
+ <br />• Group reward update logs for auditability
</Text>
<Section className="mt-4 text-center">
<Link
diff --git a/packages/ui/src/charts/time-series-chart.tsx b/packages/ui/src/charts/time-series-chart.tsx
index b0628c71ec..e1429ec747 100644
--- a/packages/ui/src/charts/time-series-chart.tsx
+++ b/packages/ui/src/charts/time-series-chart.tsx
@@ -180,7 +180,7 @@ function TimeSeriesChartInner<T extends Datum>({
width={xScale.bandwidth() * (1 + xScale.padding() * 2)}
y={0}
height={height}
- fill="black"
+ className="fill-[rgb(var(--content-emphasis))]"
fillOpacity={0.05}
/>
</>
@@ -191,7 +191,7 @@ function TimeSeriesChartInner<T extends Datum>({
x2={xScale(tooltipData.date)}
y1={height}
y2={0}
- stroke="black"
+ className="stroke-[rgb(var(--content-emphasis))]"
strokeOpacity={0.5}
strokeWidth={1}
/>
@@ -244,7 +244,7 @@ function TimeSeriesChartInner<T extends Datum>({
>
<div
className={cn(
- "pointer-events-none rounded-lg border border-neutral-200 bg-white px-4 py-2 text-base shadow-sm",
+ "border-border-default bg-bg-default pointer-events-none rounded-lg border px-4 py-2 text-base shadow-sm",
tooltipClassName,
)}
>
diff --git a/packages/ui/src/status-badge.tsx b/packages/ui/src/status-badge.tsx
index e81d536c11..273f7d5f56 100644
--- a/packages/ui/src/status-badge.tsx
+++ b/packages/ui/src/status-badge.tsx
@@ -16,11 +16,11 @@ const statusBadgeVariants = cva(
variants: {
variant: {
neutral: "bg-neutral-500/[.15] text-neutral-600",
- new: "bg-blue-500/[.15] text-blue-600",
- success: "bg-green-500/[.15] text-green-600",
- pending: "bg-orange-500/[.15] text-orange-600",
- warning: "bg-yellow-500/[.15] text-yellow-600",
- error: "bg-red-500/[.15] text-red-600",
+ new: "bg-bg-info text-content-info",
+ success: "bg-bg-success text-content-success",
+ pending: "bg-bg-attention text-content-attention",
+ warning: "bg-bg-attention text-content-attention",
+ error: "bg-bg-error text-content-error",
},
size: {
sm: "px-1.5 py-0.5",
diff --git a/packages/ui/src/tab-select.tsx b/packages/ui/src/tab-select.tsx
index 5e41e4ac9b..69e4555e76 100644
--- a/packages/ui/src/tab-select.tsx
+++ b/packages/ui/src/tab-select.tsx
@@ -2,7 +2,7 @@ import { cn } from "@dub/utils";
import { cva, VariantProps } from "class-variance-authority";
import { LayoutGroup, motion } from "motion/react";
import Link from "next/link";
-import { Dispatch, SetStateAction, useId } from "react";
+import { Dispatch, ReactNode, SetStateAction, useId } from "react";
import { ArrowUpRight } from "./icons";
const tabSelectButtonVariants = cva("p-4 transition-colors duration-75", {
@@ -38,7 +38,7 @@ export function TabSelect<T extends string>({
onSelect,
className,
}: VariantProps<typeof tabSelectButtonVariants> & {
- options: { id: T; label: string; href?: string; target?: string }[];
+ options: { id: T; label: ReactNode; href?: string; target?: string }[];
selected: string | null;
onSelect?: Dispatch<SetStateAction<T>> | ((id: T) => void);
className?: string;
diff --git a/packages/ui/src/table/table.tsx b/packages/ui/src/table/table.tsx
index af229431a6..c0fd1b3ea8 100644
--- a/packages/ui/src/table/table.tsx
+++ b/packages/ui/src/table/table.tsx
@@ -851,9 +851,10 @@ export function Table<T>({
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
- className="bg-bg-default/50 absolute inset-0 h-full"
+ className="bg-bg-default/50 absolute inset-0 h-full rounded-xl"
>
- <div className="flex h-[75vh] w-full items-center justify-center">
+ {/* here we're using min(75%,75vh) to ensure proper placement on full height vs partial height tables */}
+ <div className="flex h-[min(75%,75vh)] w-full items-center justify-center">
<LoadingSpinner />
</div>
</motion.div>
diff --git a/packages/ui/src/tooltip.tsx b/packages/ui/src/tooltip.tsx
index 595db4aac4..69af90ca6d 100644
--- a/packages/ui/src/tooltip.tsx
+++ b/packages/ui/src/tooltip.tsx
@@ -99,7 +99,7 @@ export function Tooltip({
<TooltipPrimitive.Content
sideOffset={8}
side={side}
- className="animate-slide-up-fade pointer-events-auto z-[99] items-center overflow-hidden rounded-xl border border-neutral-200 bg-white shadow-sm"
+ className="animate-slide-up-fade border-border-default bg-bg-default pointer-events-auto z-[99] items-center overflow-hidden rounded-xl border shadow-sm"
collisionPadding={0}
{...rest}
>