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.

Bounty single page & support multiple submissions (#3521)

Kiran K2fed750219b8
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
index db452820ef..99b517d511 100644
--- a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
@@ -62,6 +62,8 @@ export const PATCH = withWorkspace(
startsAt,
endsAt,
submissionsOpenAt,
+ submissionFrequency,
+ maxSubmissions,
rewardAmount,
rewardDescription,
submissionRequirements,
@@ -88,8 +90,14 @@ export const PATCH = withWorkspace(
validateBounty({
type: bounty.type,
startsAt,
- endsAt,
+ endsAt: endsAt !== undefined ? endsAt : bounty.endsAt,
submissionsOpenAt,
+ submissionFrequency:
+ submissionFrequency !== undefined
+ ? submissionFrequency
+ : bounty.submissionFrequency,
+ maxSubmissions:
+ maxSubmissions !== undefined ? maxSubmissions : bounty.maxSubmissions,
submissionRequirements,
rewardAmount,
rewardDescription,
@@ -190,6 +198,12 @@ export const PATCH = withWorkspace(
endsAt,
submissionsOpenAt:
bounty.type === "submission" ? submissionsOpenAt : null,
+ ...(bounty.type === "submission" &&
+ submissionFrequency !== undefined && { submissionFrequency }),
+ ...(bounty.type === "submission" &&
+ maxSubmissions !== undefined && {
+ maxSubmissions: maxSubmissions ?? 1,
+ }),
rewardAmount:
rewardAmount !== undefined ? rewardAmount : bounty.rewardAmount,
rewardDescription,
diff --git a/apps/web/app/(ee)/api/bounties/route.ts b/apps/web/app/(ee)/api/bounties/route.ts
index 24fadb19fa..208cacb85b 100644
--- a/apps/web/app/(ee)/api/bounties/route.ts
+++ b/apps/web/app/(ee)/api/bounties/route.ts
@@ -167,6 +167,8 @@ export const POST = withWorkspace(
startsAt,
endsAt,
submissionsOpenAt,
+ submissionFrequency,
+ maxSubmissions,
submissionRequirements,
groupIds,
performanceCondition,
@@ -247,6 +249,9 @@ export const POST = withWorkspace(
startsAt,
endsAt,
submissionsOpenAt: type === "submission" ? submissionsOpenAt : null,
+ submissionFrequency:
+ type === "submission" ? submissionFrequency : null,
+ maxSubmissions: type === "submission" ? maxSubmissions ?? 1 : 1,
rewardAmount,
rewardDescription,
performanceScope: type === "performance" ? performanceScope : null,
diff --git a/apps/web/app/(ee)/api/cron/bounties/notify-partners/route.ts b/apps/web/app/(ee)/api/cron/bounties/notify-partners/route.ts
index f6bf324815..6224f2e9c2 100644
--- a/apps/web/app/(ee)/api/cron/bounties/notify-partners/route.ts
+++ b/apps/web/app/(ee)/api/cron/bounties/notify-partners/route.ts
@@ -150,6 +150,7 @@ export async function POST(req: Request) {
react: NewBountyAvailable({
email: partner.email!,
bounty: {
+ id: bounty.id,
name: bounty.name,
type: bounty.type,
endsAt: bounty.endsAt,
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/route.ts
new file mode 100644
index 0000000000..7173352de3
--- /dev/null
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/route.ts
@@ -0,0 +1,92 @@
+import { DubApiError } from "@/lib/api/errors";
+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 { NextResponse } from "next/server";
+
+// GET /api/partner-profile/programs/[programId]/bounties/[bountyId] – get a single bounty for an enrolled program
+export const GET = withPartnerProfile(async ({ partner, params }) => {
+ const { programId, bountyId } = params;
+
+ const { program, links, ...programEnrollment } =
+ await getProgramEnrollmentOrThrow({
+ partnerId: partner.id,
+ programId,
+ include: {
+ program: true,
+ links: true,
+ },
+ });
+
+ const bounty = await prisma.bounty.findUnique({
+ where: {
+ id: bountyId,
+ programId: program.id,
+ },
+ include: {
+ workflow: {
+ select: {
+ triggerConditions: true,
+ },
+ },
+ groups: true,
+ submissions: {
+ where: {
+ partnerId: partner.id,
+ },
+ include: {
+ commission: {
+ select: {
+ id: true,
+ earnings: true,
+ status: true,
+ createdAt: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!bounty) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Bounty not found.",
+ });
+ }
+
+ if (bounty.startsAt > new Date()) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Bounty not found.",
+ });
+ }
+
+ const partnerGroupId = programEnrollment.groupId || program.defaultGroupId;
+ const bountyGroupIds = bounty.groups.map((g) => g.groupId);
+ const partnerCanSeeBounty =
+ bountyGroupIds.length === 0 ||
+ (partnerGroupId && bountyGroupIds.includes(partnerGroupId));
+
+ if (!partnerCanSeeBounty) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Bounty not found.",
+ });
+ }
+
+ const { groups, ...bountyWithoutGroups } = bounty;
+
+ return NextResponse.json(
+ PartnerBountySchema.parse({
+ ...bountyWithoutGroups,
+ performanceCondition: bounty.workflow?.triggerConditions?.[0] || null,
+ partner: {
+ ...aggregatePartnerLinksStats(links),
+ totalCommissions: programEnrollment.totalCommissions,
+ },
+ }),
+ );
+});
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/[bountyId]/bounty-performance-section.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/[bountyId]/bounty-performance-section.tsx
new file mode 100644
index 0000000000..1bf399bf68
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/[bountyId]/bounty-performance-section.tsx
@@ -0,0 +1,706 @@
+"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 usePartnerAnalytics from "@/lib/swr/use-partner-analytics";
+import { usePartnerEarningsTimeseries } from "@/lib/swr/use-partner-earnings-timeseries";
+import {
+ LeadEvent,
+ PartnerBountyProps,
+ PartnerEarningsResponse,
+ SaleEvent,
+} from "@/lib/types";
+import { CustomerRowItem } from "@/ui/customers/customer-row-item";
+import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
+import {
+ buttonVariants,
+ CopyText,
+ LinkLogo,
+ LoadingSpinner,
+ Table,
+ TimestampTooltip,
+ useTable,
+} from "@dub/ui";
+import { Areas, TimeSeriesChart, XAxis } from "@dub/ui/charts";
+import { CircleDollar, UserPlus } from "@dub/ui/icons";
+import {
+ cn,
+ currencyFormatter,
+ fetcher,
+ formatDateTimeSmart,
+ getApexDomain,
+ getPrettyUrl,
+ nFormatter,
+} from "@dub/utils";
+import { ColumnDef } from "@tanstack/react-table";
+import Link from "next/link";
+import { useParams } from "next/navigation";
+import { useMemo, useState } from "react";
+import useSWR from "swr";
+
+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_ANALYTICS_FIELD: Partial<
+ Record<PerformanceAttribute, "leads" | "sales" | "saleAmount">
+> = {
+ totalLeads: "leads",
+ totalConversions: "sales",
+ totalSaleAmount: "saleAmount",
+};
+
+const ATTRIBUTE_TO_EVENT_PARAMS: Partial<
+ Record<PerformanceAttribute, { event: string; saleType?: string }>
+> = {
+ totalLeads: { event: "leads" },
+ totalConversions: { event: "sales", saleType: "new" },
+ totalSaleAmount: { event: "sales" },
+};
+
+const ATTRIBUTE_TO_TABLE_TITLE: Record<PerformanceAttribute, string> = {
+ totalLeads: "Leads generated",
+ totalConversions: "Conversions",
+ totalSaleAmount: "Revenue generated",
+ totalCommissions: "Commissions earned",
+};
+
+export function BountyPerformanceSection({
+ bounty,
+}: {
+ bounty: PartnerBountyProps;
+}) {
+ return (
+ <div className="flex flex-col gap-6">
+ <div className="flex flex-col gap-3">
+ <h2 className="text-content-emphasis text-lg font-semibold leading-7 tracking-[-0.36px]">
+ Performance
+ </h2>
+ <div className="border-border-subtle rounded-xl border bg-white p-5">
+ <BountyPerformanceChart bounty={bounty} />
+ </div>
+ </div>
+ <BountyPerformanceTable bounty={bounty} />
+ </div>
+ );
+}
+
+function BountyPerformanceChart({ bounty }: { bounty: PartnerBountyProps }) {
+ 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) : undefined,
+ [bounty.performanceScope, bounty.startsAt],
+ );
+ const endDate = useMemo(
+ () =>
+ bounty.performanceScope === "new"
+ ? bounty.endsAt
+ ? new Date(Math.min(new Date(bounty.endsAt).getTime(), Date.now()))
+ : new Date()
+ : undefined,
+ [bounty.performanceScope, bounty.endsAt],
+ );
+
+ const { data: analyticsTimeseries, error: analyticsError } =
+ usePartnerAnalytics({
+ groupBy: "timeseries",
+ event: "composite",
+ ...(startDate && endDate && { start: startDate, end: endDate }),
+ enabled: !isCommissions,
+ });
+
+ const { data: earningsTimeseries, error: earningsError } =
+ usePartnerEarningsTimeseries({
+ interval: "30d",
+ ...(startDate && endDate && { start: startDate, end: endDate }),
+ enabled: isCommissions,
+ });
+
+ const data = useMemo(() => {
+ if (isCommissions) {
+ if (!earningsTimeseries) {
+ return undefined;
+ }
+
+ if (!Array.isArray(earningsTimeseries)) {
+ return [];
+ }
+
+ return earningsTimeseries.map(
+ ({ start, earnings }: { start: string; earnings: number }) => ({
+ date: new Date(start),
+ values: { main: earnings },
+ }),
+ );
+ }
+
+ if (!attribute) {
+ return [];
+ }
+
+ if (!analyticsTimeseries) {
+ return undefined;
+ }
+
+ const field = ATTRIBUTE_TO_ANALYTICS_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 },
+ }));
+ }, [isCommissions, earningsTimeseries, analyticsTimeseries, 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-violet-500",
+ isActive: true,
+ },
+ ]}
+ tooltipContent={(d) => (
+ <div className="flex justify-between gap-6 whitespace-nowrap p-2 text-xs leading-none">
+ <span className="font-medium text-neutral-700">
+ {formatDateTooltip(d.date, {})}
+ </span>
+ <p className="text-right text-neutral-500">
+ {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-sm text-neutral-500">
+ Failed to load data.
+ </span>
+ ) : (
+ <LoadingSpinner />
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+const PAGE_SIZE = 5;
+
+function usePaginationState() {
+ const [page, setPage] = useState(1);
+ const pagination = useMemo(
+ () => ({ pageIndex: page - 1, pageSize: PAGE_SIZE }),
+ [page],
+ );
+
+ const onPaginationChange = (
+ updater:
+ | { pageIndex: number; pageSize: number }
+ | ((prev: { pageIndex: number; pageSize: number }) => {
+ pageIndex: number;
+ pageSize: number;
+ }),
+ ) => {
+ const next = typeof updater === "function" ? updater(pagination) : updater;
+ setPage(next.pageIndex + 1);
+ };
+
+ return { page, pagination, onPaginationChange };
+}
+
+function PerformanceTableShell({
+ title,
+ viewAllHref,
+ children,
+}: {
+ title: string;
+ viewAllHref: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center justify-between">
+ <h2 className="text-content-emphasis text-lg font-semibold leading-7 tracking-[-0.36px]">
+ {title}
+ </h2>
+ <Link
+ href={viewAllHref}
+ className={cn(
+ buttonVariants({ variant: "secondary" }),
+ "flex h-7 items-center rounded-lg border px-2 text-sm",
+ )}
+ >
+ View all
+ </Link>
+ </div>
+ {children}
+ </div>
+ );
+}
+
+function BountyPerformanceTable({ bounty }: { bounty: PartnerBountyProps }) {
+ const attribute = bounty.performanceCondition?.attribute as
+ | PerformanceAttribute
+ | undefined;
+
+ if (attribute === "totalCommissions") {
+ return <BountyPerformanceCommissionsTable bounty={bounty} />;
+ }
+
+ return <BountyPerformanceEventsTable bounty={bounty} />;
+}
+
+function BountyPerformanceEventsTable({
+ bounty,
+}: {
+ bounty: PartnerBountyProps;
+}) {
+ const { programSlug } = useParams<{ programSlug: string }>();
+ const attribute = bounty.performanceCondition?.attribute as
+ | PerformanceAttribute
+ | undefined;
+
+ 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 EmptyIcon =
+ attribute === "totalLeads" || attribute === "totalConversions"
+ ? UserPlus
+ : CircleDollar;
+
+ const eventParams = attribute
+ ? ATTRIBUTE_TO_EVENT_PARAMS[attribute]
+ : undefined;
+
+ const startDate = useMemo(
+ () =>
+ bounty.performanceScope === "new" ? new Date(bounty.startsAt) : undefined,
+ [bounty.performanceScope, bounty.startsAt],
+ );
+ const endDate = useMemo(
+ () =>
+ bounty.performanceScope === "new"
+ ? bounty.endsAt
+ ? new Date(Math.min(new Date(bounty.endsAt).getTime(), Date.now()))
+ : new Date()
+ : undefined,
+ [bounty.performanceScope, bounty.endsAt],
+ );
+
+ const { page, pagination, onPaginationChange } = usePaginationState();
+
+ const eventsUrl = useMemo(() => {
+ if (!programSlug || !eventParams) {
+ return null;
+ }
+
+ const params = new URLSearchParams({
+ event: eventParams.event,
+ limit: String(PAGE_SIZE),
+ page: String(page),
+ });
+
+ if (eventParams.saleType) {
+ params.set("saleType", eventParams.saleType);
+ }
+
+ if (startDate) {
+ params.set("start", startDate.toISOString());
+ }
+ if (endDate) {
+ params.set("end", endDate.toISOString());
+ }
+ return `/api/partner-profile/programs/${programSlug}/events?${params.toString()}`;
+ }, [programSlug, eventParams, page, startDate, endDate]);
+
+ const {
+ data: events,
+ isValidating: isLoading,
+ error,
+ } = useSWR<(LeadEvent | SaleEvent)[]>(eventsUrl, fetcher, {
+ keepPreviousData: true,
+ });
+
+ const { data: analyticsCount } = usePartnerAnalytics({
+ event: "composite",
+ groupBy: "count",
+ ...(startDate && endDate && { start: startDate, end: endDate }),
+ enabled: 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 totalCount =
+ attribute === "totalSaleAmount"
+ ? analyticsCount?.sales ?? 0
+ : analyticsField
+ ? analyticsCount?.[analyticsField] ?? 0
+ : 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="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,
+ rowCount: totalCount,
+ thClassName: "border-l-transparent",
+ tdClassName: (columnId: string) =>
+ cn("border-l-transparent", columnId === "customer" && "p-0"),
+ resourceName: () => metricLabel,
+ emptyState: (
+ <AnimatedEmptyState
+ title={`No ${metricLabel} recorded yet`}
+ description={`${tableTitle} will appear here once you start generating activity.`}
+ cardContent={() => (
+ <>
+ <EmptyIcon className="size-4 text-neutral-700" />
+ <div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />
+ </>
+ )}
+ className="border-none md:min-h-0"
+ />
+ ),
+ });
+
+ return (
+ <PerformanceTableShell
+ title={tableTitle}
+ viewAllHref={`/programs/${programSlug}/events`}
+ >
+ <Table
+ {...tableProps}
+ table={table}
+ containerClassName="border-neutral-200"
+ scrollWrapperClassName="min-h-[315px]"
+ />
+ </PerformanceTableShell>
+ );
+}
+
+function BountyPerformanceCommissionsTable({
+ bounty,
+}: {
+ bounty: PartnerBountyProps;
+}) {
+ const { programSlug } = useParams<{ programSlug: string }>();
+
+ const startDate = useMemo(
+ () =>
+ bounty.performanceScope === "new" ? new Date(bounty.startsAt) : undefined,
+ [bounty.performanceScope, bounty.startsAt],
+ );
+ const endDate = useMemo(
+ () =>
+ bounty.performanceScope === "new"
+ ? bounty.endsAt
+ ? new Date(Math.min(new Date(bounty.endsAt).getTime(), Date.now()))
+ : new Date()
+ : undefined,
+ [bounty.performanceScope, bounty.endsAt],
+ );
+
+ const { page, pagination, onPaginationChange } = usePaginationState();
+
+ const earningsUrlParams = useMemo(() => {
+ const params = new URLSearchParams({
+ pageSize: String(PAGE_SIZE),
+ page: String(page),
+ });
+ if (startDate) params.set("start", startDate.toISOString());
+ if (endDate) params.set("end", endDate.toISOString());
+ return params.toString();
+ }, [page, startDate, endDate]);
+
+ const earningsCountUrlParams = useMemo(() => {
+ const params = new URLSearchParams();
+ if (startDate) params.set("start", startDate.toISOString());
+ if (endDate) params.set("end", endDate.toISOString());
+ const qs = params.toString();
+ return qs ? `?${qs}` : "";
+ }, [startDate, endDate]);
+
+ const {
+ data: earnings,
+ isValidating: isLoading,
+ error,
+ } = useSWR<PartnerEarningsResponse[]>(
+ programSlug
+ ? `/api/partner-profile/programs/${programSlug}/earnings?${earningsUrlParams}`
+ : null,
+ fetcher,
+ { keepPreviousData: true },
+ );
+
+ const { data: earningsCount } = useSWR<{ count: number }>(
+ programSlug
+ ? `/api/partner-profile/programs/${programSlug}/earnings/count${earningsCountUrlParams}`
+ : null,
+ fetcher,
+ { keepPreviousData: true },
+ );
+
+ const rows = useMemo<PerformanceRow[]>(() => {
+ if (!earnings) {
+ return [];
+ }
+
+ return earnings.map((earning) => ({
+ id: earning.id,
+ date: earning.createdAt,
+ customer: earning.customer,
+ link: earning.link ?? null,
+ amount: earning.earnings,
+ }));
+ }, [earnings]);
+
+ 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",
+ 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="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,
+ rowCount: earningsCount?.count || 0,
+ thClassName: "border-l-transparent",
+ tdClassName: (columnId: string) =>
+ cn("border-l-transparent", columnId === "customer" && "p-0"),
+ resourceName: () => "commissions",
+ emptyState: (
+ <AnimatedEmptyState
+ title="No commissions recorded yet"
+ description="Commissions earned will appear here once you start generating activity."
+ cardContent={() => (
+ <>
+ <CircleDollar className="size-4 text-neutral-700" />
+ <div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />
+ </>
+ )}
+ className="border-none md:min-h-0"
+ />
+ ),
+ });
+
+ return (
+ <PerformanceTableShell
+ title="Commissions earned"
+ viewAllHref={`/programs/${programSlug}/earnings`}
+ >
+ <Table
+ {...tableProps}
+ table={table}
+ containerClassName="border-neutral-200"
+ scrollWrapperClassName="min-h-[315px]"
+ />
+ </PerformanceTableShell>
+ );
+}
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
new file mode 100644
index 0000000000..c49fdee735
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/[bountyId]/bounty-submissions-table.tsx
@@ -0,0 +1,235 @@
+"use client";
+
+import {
+ type SubmissionPeriod,
+ getSubmissionPeriods,
+} from "@/lib/bounty/periods";
+import { BOUNTY_SUBMISSION_STATUS_BADGES } from "@/lib/bounty/submission-status";
+import { PartnerBountyProps } 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";
+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,
+}: {
+ bounty: PartnerBountyProps;
+}) {
+ const {
+ claimBountySheet,
+ setShowClaimBountySheet,
+ setActivePeriodNumber: setClaimPeriodNumber,
+ } = useClaimBountySheet({ bounty });
+
+ const {
+ bountySubmissionDetailsSheet,
+ setShowBountySubmissionDetailsSheet,
+ setActivePeriodNumber: setViewPeriodNumber,
+ } = useBountySubmissionDetailsSheet({ bounty });
+
+ 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="min-w-[52px] text-sm font-medium leading-5 tracking-[-0.28px] text-neutral-600">
+ {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: "submitted",
+ header: "Submitted",
+ minSize: 100,
+ size: 120,
+ cell: ({ row: { original } }) => (
+ <span className="text-center text-sm font-medium leading-5 tracking-[-0.28px] text-neutral-600">
+ {original.submission?.completedAt
+ ? formatDate(original.submission.completedAt, {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ })
+ : "–"}
+ </span>
+ ),
+ },
+ {
+ id: "reviewed",
+ header: "Reviewed",
+ minSize: 100,
+ size: 120,
+ cell: ({ row: { original } }) => (
+ <span className="text-center text-sm font-medium leading-5 tracking-[-0.28px] text-neutral-600">
+ {original.submission?.reviewedAt
+ ? formatDate(original.submission.reviewedAt, {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ })
+ : "–"}
+ </span>
+ ),
+ },
+ {
+ id: "action",
+ header: "",
+ minSize: 98,
+ size: 98,
+ cell: ({ row: { original } }) => {
+ const { status } = original;
+ const isExpired =
+ bounty.endsAt !== null && new Date(bounty.endsAt) < new Date();
+ const isActionable = status === "notSubmitted" || status === "draft";
+
+ let buttonText = "Submit";
+
+ if (status === "draft") {
+ 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) {
+ setClaimPeriodNumber(original.periodNumber);
+ setShowClaimBountySheet(true);
+ } else {
+ setViewPeriodNumber(original.periodNumber);
+ setShowBountySubmissionDetailsSheet(true);
+ }
+ }}
+ disabledTooltip={disabledTooltip}
+ />
+ </div>
+ );
+ },
+ },
+ ],
+ [bounty, showSubmissionColumn],
+ );
+
+ // When there is no "submission" column (single-submission bounty), the
+ // "status" column must be visible on mobile too since nothing else shows it.
+ const MOBILE_HIDDEN = new Set(
+ showSubmissionColumn
+ ? ["status", "submitted", "reviewed"]
+ : ["submitted", "reviewed"],
+ );
+
+ const table = useTable({
+ data: periods,
+ columns,
+ getRowId: (row) => String(row.periodNumber),
+ resourceName: () => "submission period",
+ scrollWrapperClassName: "min-h-0",
+ thClassName: (columnId) =>
+ cn(
+ "border-l-0 border-r-0",
+ MOBILE_HIDDEN.has(columnId) && "hidden sm:table-cell",
+ ),
+ tdClassName: (columnId) =>
+ cn(
+ "border-l-0 border-r-0",
+ MOBILE_HIDDEN.has(columnId) && "hidden sm:table-cell",
+ ),
+ className: "[&_tbody_tr:last-child_td]:border-b-0",
+ containerClassName: "border-neutral-200",
+ });
+
+ return (
+ <>
+ {claimBountySheet}
+ {bountySubmissionDetailsSheet}
+ <div className="flex flex-col gap-3">
+ <h2 className="text-content-emphasis text-lg font-semibold leading-7 tracking-[-0.36px]">
+ Submissions
+ </h2>
+ <Table {...table} />
+ </div>
+ </>
+ );
+}
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/[bountyId]/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/[bountyId]/page-client.tsx
new file mode 100644
index 0000000000..b7e6931d69
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/[bountyId]/page-client.tsx
@@ -0,0 +1,142 @@
+"use client";
+
+import usePartnerBounty from "@/lib/swr/use-partner-bounty";
+import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
+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 { BountySubmissionRequirements } from "@/ui/partners/bounties/bounty-submission-requirements";
+import { ChevronRight, Trophy } from "@dub/ui";
+import { cn, truncate } from "@dub/utils";
+import Link from "next/link";
+import { redirect, useParams } from "next/navigation";
+import {
+ BountyRewardsTable,
+ PartnerBountyCard,
+ PartnerBountyCardSkeleton,
+} from "../bounty-card";
+import { BountyPerformanceSection } from "./bounty-performance-section";
+import { BountySubmissionsTable } from "./bounty-submissions-table";
+
+export function PartnerBountyPageClient() {
+ const { programSlug } = useParams<{ programSlug: string }>();
+ const { bounty, isLoading } = usePartnerBounty();
+
+ if (!bounty && !isLoading) {
+ redirect(`/programs/${programSlug}/bounties`);
+ }
+
+ return (
+ <PageWidthWrapper className="flex flex-col gap-6 pb-10">
+ <div className="@3xl/page:grid-cols-[minmax(440px,1fr)_minmax(0,360px)] grid grid-cols-1 gap-6">
+ <div className="@3xl/page:contents flex flex-col gap-6">
+ {isLoading ? (
+ <PartnerBountyCardSkeleton />
+ ) : bounty ? (
+ <div className="@3xl/page:col-start-2 @3xl/page:row-start-1 @3xl/page:w-[360px] @3xl/page:shrink-0 flex w-full flex-col gap-4">
+ <PartnerBountyCard
+ bounty={bounty}
+ showFullTitle
+ hideFooter
+ showRewards
+ />
+
+ <BountyRewardsTable
+ bounty={bounty}
+ programSlug={programSlug}
+ className="@3xl/page:hidden"
+ />
+ </div>
+ ) : null}
+ </div>
+
+ <div className="@3xl/page:col-start-1 @3xl/page:row-start-1 flex flex-col gap-6">
+ {isLoading ? (
+ <BountyDetailsProgressSkeleton />
+ ) : bounty ? (
+ <>
+ <div className="flex flex-col gap-3">
+ <h2 className="text-content-emphasis text-lg font-semibold leading-7 tracking-[-0.36px]">
+ Progress
+ </h2>
+ <div className="border-border-subtle flex w-full flex-col gap-4 rounded-xl border bg-white px-5 pb-4 pt-6">
+ {bounty.type === "performance" ? (
+ <PerformanceBountyProgress
+ bounty={bounty}
+ labelClassName="text-base"
+ />
+ ) : (
+ <SubmissionBountyProgress
+ bounty={bounty}
+ labelClassName="text-base"
+ />
+ )}
+ </div>
+ </div>
+
+ {bounty.type === "performance" ? (
+ <BountyPerformanceSection bounty={bounty} />
+ ) : (
+ <BountySubmissionsTable bounty={bounty} />
+ )}
+
+ <div className="flex max-w-[700px] flex-col gap-6 text-sm">
+ <BountySubmissionRequirements bounty={bounty} />
+ <BountyRewardCriteria bounty={bounty} />
+ <BountyDescription bounty={bounty} />
+ </div>
+ </>
+ ) : null}
+ </div>
+ </div>
+ </PageWidthWrapper>
+ );
+}
+
+function BountyDetailsProgressSkeleton() {
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="h-7 w-20 animate-pulse rounded-md bg-neutral-200" />
+ <div className="border-border-subtle flex flex-col gap-4 rounded-xl border bg-white px-5 pb-4 pt-6">
+ <div className="h-1 w-full animate-pulse rounded-full bg-neutral-200" />
+ <div className="flex gap-1">
+ <div className="h-6 w-8 animate-pulse rounded bg-neutral-200" />
+ <div className="h-6 w-6 animate-pulse rounded bg-neutral-200" />
+ <div className="h-6 w-24 animate-pulse rounded bg-neutral-200" />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export function PartnerBountyPageHeader() {
+ const { programSlug } = useParams<{ programSlug: string }>();
+ const { bounty } = usePartnerBounty();
+
+ return (
+ <div className="flex items-center gap-1.5">
+ <Link
+ href={`/programs/${programSlug}/bounties`}
+ aria-label="Back to bounties"
+ title="Back to bounties"
+ className={cn(
+ "bg-bg-subtle flex size-8 shrink-0 items-center justify-center rounded-lg",
+ "hover:bg-bg-emphasis transition-[transform,background-color] duration-150 active:scale-95",
+ )}
+ >
+ <Trophy className="size-4" />
+ </Link>
+ <ChevronRight className="text-content-muted size-2.5 shrink-0 [&_*]:stroke-2" />
+ <div className="min-w-0 truncate">
+ {bounty ? (
+ truncate(bounty.name, 70)
+ ) : (
+ <div className="h-6 w-48 animate-pulse rounded-md bg-neutral-200" />
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/[bountyId]/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/[bountyId]/page.tsx
new file mode 100644
index 0000000000..8cf6cab23a
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/[bountyId]/page.tsx
@@ -0,0 +1,13 @@
+import { PageContent } from "@/ui/layout/page-content";
+import {
+ PartnerBountyPageClient,
+ PartnerBountyPageHeader,
+} from "./page-client";
+
+export default function PartnerBountyPage() {
+ return (
+ <PageContent title={<PartnerBountyPageHeader />}>
+ <PartnerBountyPageClient />
+ </PageContent>
+ );
+}
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
new file mode 100644
index 0000000000..d48dbdbf7c
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/bounty-card.tsx
@@ -0,0 +1,220 @@
+import { PartnerBountyProps } from "@/lib/types";
+import {
+ PerformanceBountyProgress,
+ SubmissionBountyProgress,
+} from "@/ui/partners/bounties/bounty-performance";
+import { BountyRewardDescription } from "@/ui/partners/bounties/bounty-reward-description";
+import { BountyStatusBadge } from "@/ui/partners/bounties/bounty-status-badge";
+import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
+import { CommissionStatusBadges } from "@/ui/partners/commission-status-badges";
+import { buttonVariants, Table, TimestampTooltip, useTable } from "@dub/ui";
+import { Calendar6 } from "@dub/ui/icons";
+import {
+ cn,
+ currencyFormatter,
+ formatDate,
+ formatDateTimeSmart,
+} from "@dub/utils";
+import Link from "next/link";
+import { useParams, useRouter } from "next/navigation";
+
+export function PartnerBountyCard({
+ bounty,
+ showFullTitle = false,
+ hideFooter = false,
+ showRewards = false,
+}: {
+ bounty: PartnerBountyProps;
+ showFullTitle?: boolean;
+ hideFooter?: boolean;
+ showRewards?: boolean;
+}) {
+ const { programSlug } = useParams();
+ const router = useRouter();
+
+ 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"
+ >
+ <div className="p-3 pb-0">
+ <div className="relative flex h-[124px] items-center justify-center rounded-lg bg-neutral-100">
+ <div className="relative size-full">
+ <BountyThumbnailImage bounty={bounty} />
+ </div>
+
+ <BountyStatusBadge bounty={bounty} />
+ </div>
+ </div>
+
+ <div className="flex min-w-0 flex-col gap-1 px-5 py-4">
+ <h3
+ className={cn(
+ "text-content-emphasis text-sm font-semibold",
+ !showFullTitle && "sm:truncate",
+ )}
+ >
+ {bounty.name}
+ </h3>
+
+ <BountyEndDate bounty={bounty} />
+
+ <BountyRewardDescription
+ bounty={bounty}
+ onTooltipClick={(e) => e.stopPropagation()}
+ className="font-medium"
+ />
+ </div>
+
+ {!hideFooter && (
+ <div className="border-t border-neutral-200 px-5 py-4">
+ {bounty.type === "performance" ? (
+ <PerformanceBountyProgress bounty={bounty} />
+ ) : (
+ <SubmissionBountyProgress bounty={bounty} />
+ )}
+ </div>
+ )}
+
+ {showRewards && bounty.submissions.some((s) => s.commission !== null) && (
+ <div className="@3xl/page:block hidden border-t border-neutral-200 p-4">
+ <BountyRewardsTable
+ bounty={bounty}
+ programSlug={programSlug as string}
+ />
+ </div>
+ )}
+ </div>
+ );
+}
+
+export function BountyRewardsTable({
+ bounty,
+ programSlug,
+ className,
+}: {
+ bounty: PartnerBountyProps;
+ programSlug: string;
+ className?: string;
+}) {
+ const rewards = bounty.submissions
+ .filter((s) => s.commission !== null)
+ .map((s) => s.commission!);
+
+ const { table, ...tableProps } = useTable({
+ data: rewards,
+ columns: [
+ {
+ id: "amount",
+ header: "Amount",
+ cell: ({ row }) => currencyFormatter(row.original.earnings),
+ },
+ {
+ id: "status",
+ header: "Status",
+ cell: ({ row }) => {
+ const badge = CommissionStatusBadges[row.original.status];
+
+ return badge ? (
+ <span
+ className={cn(
+ "rounded-md px-2 py-0.5 text-xs font-semibold",
+ badge.className,
+ )}
+ >
+ {badge.label}
+ </span>
+ ) : null;
+ },
+ },
+ ],
+ thClassName: "border-l-transparent py-1.5",
+ tdClassName: "border-l-transparent py-1.5",
+ });
+
+ if (rewards.length === 0) {
+ return null;
+ }
+
+ 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>
+ </div>
+ <Table
+ {...tableProps}
+ table={table}
+ containerClassName="border-neutral-200"
+ scrollWrapperClassName="min-h-0"
+ className="[&_tbody_tr:last-child_td]:border-b-0"
+ />
+ </div>
+ );
+}
+
+function BountyEndDate({ bounty }: { bounty: PartnerBountyProps }) {
+ const isExpired =
+ bounty.endsAt && new Date(bounty.endsAt) < new Date() ? true : false;
+
+ return (
+ <div className="text-content-subtle flex items-center gap-2 text-sm font-medium">
+ <Calendar6 className="size-3.5" />
+ {bounty.endsAt ? (
+ <span>
+ {isExpired ? "Ended" : "Ends"} at{" "}
+ <TimestampTooltip
+ timestamp={bounty.endsAt}
+ side="right"
+ rows={["local", "utc"]}
+ >
+ <span className="hover:text-content-emphasis underline decoration-dotted underline-offset-2">
+ {formatDateTimeSmart(bounty.endsAt)}
+ </span>
+ </TimestampTooltip>
+ </span>
+ ) : (
+ <span>
+ {formatDate(bounty.startsAt, { month: "short" })} → No end date
+ </span>
+ )}
+ </div>
+ );
+}
+
+export const PartnerBountyCardSkeleton = () => {
+ return (
+ <div className="border-border-subtle rounded-xl border bg-white 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="flex flex-col gap-1.5">
+ <div className="h-5 w-48 animate-pulse rounded-md bg-neutral-200" />
+ <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>
+ </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 5e7788598c..8957114646 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
@@ -1,15 +1,12 @@
"use client";
-import usePartnerProgramBounties from "@/lib/swr/use-partner-program-bounties";
+import { usePartnerProgramBounties } from "@/lib/swr/use-partner-program-bounties";
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 { useMemo, useState } from "react";
-import {
- PartnerBountyCard,
- PartnerBountyCardSkeleton,
-} from "./partner-bounty-card";
+import { PartnerBountyCard, PartnerBountyCardSkeleton } from "./bounty-card";
const tabs = [
{
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/partner-bounty-card.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/partner-bounty-card.tsx
deleted file mode 100644
index a33125aae8..0000000000
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/partner-bounty-card.tsx
+++ /dev/null
@@ -1,237 +0,0 @@
-import { PartnerBountyProps } from "@/lib/types";
-import { BountyPerformance } from "@/ui/partners/bounties/bounty-performance";
-import { BountyRewardDescription } from "@/ui/partners/bounties/bounty-reward-description";
-import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
-import { useClaimBountyModal } from "@/ui/partners/bounties/claim-bounty-modal";
-import { usePartnerBountySubmissionDetailsSheet } from "@/ui/partners/bounties/partner-bounty-submission-details-sheet";
-import {
- DynamicTooltipWrapper,
- StatusBadge,
- TimestampTooltip,
- TooltipContent,
-} from "@dub/ui";
-import { Calendar6 } from "@dub/ui/icons";
-import { cn, formatDate, formatDateTimeSmart } from "@dub/utils";
-import { useParams } from "next/navigation";
-
-export function PartnerBountyCard({ bounty }: { bounty: PartnerBountyProps }) {
- const { programSlug } = useParams();
-
- const { claimBountyModal, setShowClaimBountyModal } = useClaimBountyModal({
- bounty,
- });
-
- const {
- partnerBountySubmissionDetailsSheet,
- setPartnerBountySubmissionDetailsSheetOpen,
- } = usePartnerBountySubmissionDetailsSheet(bounty);
-
- const expiredBounty =
- bounty.endsAt && new Date(bounty.endsAt) < new Date() ? true : false;
-
- const submittedBounty =
- bounty.submission &&
- (bounty.submission.status !== "draft" ||
- bounty.submissionRequirements?.socialMetrics);
-
- const handleCardClick = () => {
- if (expiredBounty) {
- return;
- }
-
- if (submittedBounty) {
- setPartnerBountySubmissionDetailsSheetOpen(true);
- } else {
- setShowClaimBountyModal(true);
- }
- };
-
- return (
- <>
- {claimBountyModal}
- {partnerBountySubmissionDetailsSheet}
- <DynamicTooltipWrapper
- tooltipProps={
- expiredBounty
- ? {
- content: (
- <TooltipContent
- title={`This bounty is no longer eligible for submission since it ended on ${formatDate(bounty.endsAt!, { month: "short" })}`}
- cta="Contact program"
- href={`/messages/${programSlug}`}
- />
- ),
- }
- : undefined
- }
- >
- <button
- type="button"
- onClick={handleCardClick}
- disabled={expiredBounty || bounty.type === "performance"}
- className={cn(
- "border-border-subtle group relative flex w-full cursor-pointer flex-col gap-2.5 overflow-hidden rounded-xl border bg-white p-3 text-left",
- expiredBounty
- ? "cursor-not-allowed"
- : bounty.type === "performance"
- ? "cursor-default"
- : "hover:border-border-default transition-all hover:shadow-lg",
- )}
- >
- <div className="relative flex h-[124px] items-center justify-center rounded-lg bg-neutral-100 py-3">
- <div className="relative size-full">
- <BountyThumbnailImage bounty={bounty} />
- </div>
-
- {expiredBounty && (
- <div className="absolute left-2 top-2 z-10">
- <div className="flex h-5 items-center gap-1 rounded-md bg-red-100 px-2 py-1 text-xs font-semibold text-red-600">
- Expired {formatDate(bounty.endsAt!, { month: "short" })}
- </div>
- </div>
- )}
- </div>
-
- <div className="flex min-w-0 flex-col gap-1.5 px-2 pb-1.5">
- <h3 className="text-content-emphasis text-sm font-semibold sm:truncate">
- {bounty.name}
- </h3>
-
- <div className="text-content-subtle flex items-center gap-2 text-sm font-medium">
- <Calendar6 className="size-3.5" />
- <span>
- {bounty.endsAt ? (
- <>
- {expiredBounty ? "Ended" : "Ends"} at{" "}
- <TimestampTooltip
- timestamp={bounty.endsAt}
- side="right"
- rows={["local", "utc"]}
- >
- <span className="hover:text-content-emphasis underline decoration-dotted underline-offset-2">
- {formatDateTimeSmart(bounty.endsAt)}
- </span>
- </TimestampTooltip>
- </>
- ) : (
- `${formatDate(bounty.startsAt, { month: "short" })} → No end date`
- )}
- </span>
- </div>
-
- <BountyRewardDescription
- bounty={bounty}
- onTooltipClick={(e) => e.stopPropagation()}
- className="font-medium"
- />
- </div>
-
- <div className="flex grow flex-col justify-end px-2 pb-1">
- {renderSubmissionStatus({
- bounty,
- setShowClaimBountyModal,
- })}
- </div>
- </button>
- </DynamicTooltipWrapper>
- </>
- );
-}
-
-export const PartnerBountyCardSkeleton = () => {
- return (
- <div className="border-border-subtle rounded-xl border bg-white 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="flex flex-col gap-1.5">
- <div className="h-5 w-48 animate-pulse rounded-md bg-neutral-200" />
-
- <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>
- </div>
- </div>
- </div>
- );
-};
-
-function renderSubmissionStatus({
- bounty,
- setShowClaimBountyModal,
-}: {
- bounty: PartnerBountyProps;
- setShowClaimBountyModal: (show: boolean) => void;
-}) {
- const expiredBounty =
- bounty.endsAt && new Date(bounty.endsAt) < new Date() ? true : false;
-
- const { submission } = bounty;
-
- // When there is no submission, we show the performance or claim bounty button
- if (!submission) {
- return bounty.type === "performance" ? (
- <BountyPerformance bounty={bounty} />
- ) : (
- <div
- className={cn(
- "flex h-7 w-fit items-center rounded-lg bg-black px-2.5 text-sm text-white",
- expiredBounty
- ? "cursor-not-allowed border border-neutral-200 bg-neutral-100 text-neutral-400"
- : "group-hover:ring-border-subtle transition-all group-hover:ring-2",
- )}
- onClick={() => setShowClaimBountyModal(true)}
- >
- Claim bounty
- </div>
- );
- }
-
- switch (submission.status) {
- case "draft":
- return bounty.type === "performance" ||
- bounty.submissionRequirements?.socialMetrics ? (
- <BountyPerformance bounty={bounty} />
- ) : (
- <div
- className={cn(
- "flex h-7 w-fit items-center rounded-lg bg-black px-2.5 text-sm text-white",
- expiredBounty
- ? "cursor-not-allowed border border-neutral-200 bg-neutral-100 text-neutral-400"
- : "group-hover:ring-border-subtle transition-all group-hover:ring-2",
- )}
- onClick={() => setShowClaimBountyModal(true)}
- >
- Continue submission
- </div>
- );
-
- case "submitted":
- return (
- <StatusBadge variant="new" icon={null}>
- Pending Review |{" "}
- {bounty.type === "performance" ? "Completed" : "Submitted"}{" "}
- {submission.completedAt &&
- formatDate(submission.completedAt, { month: "short" })}
- </StatusBadge>
- );
-
- case "rejected":
- return (
- <StatusBadge variant="error" icon={null}>
- Rejected
- </StatusBadge>
- );
-
- case "approved":
- default:
- return (
- <StatusBadge variant="success">
- Confirmed{" "}
- {submission.reviewedAt &&
- formatDate(submission.reviewedAt, { month: "short" })}
- </StatusBadge>
- );
- }
-}
diff --git a/apps/web/app/api/ai/sync-embeddings/route.ts b/apps/web/app/api/ai/sync-embeddings/route.ts
index 855c659b63..6368faab8a 100644
--- a/apps/web/app/api/ai/sync-embeddings/route.ts
+++ b/apps/web/app/api/ai/sync-embeddings/route.ts
@@ -39,7 +39,10 @@ export const POST = async (req: Request) => {
try {
const body = await req.json().catch(() => {
- throw new DubApiError({ code: "bad_request", message: "Invalid JSON body." });
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Invalid JSON body.",
+ });
});
const { url, delay } = schema.parse(body);
const normalizedUrl = new URL(url).toString();
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submission-details-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submission-details-sheet.tsx
index 8dff299c03..f4a68ab77f 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submission-details-sheet.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submission-details-sheet.tsx
@@ -1,18 +1,18 @@
"use client";
-import { BOUNTY_SUBMISSION_STATUS_BADGES } from "@/lib/bounty/bounty-submission-status-badges";
import { REJECT_BOUNTY_SUBMISSION_REASONS } from "@/lib/bounty/constants";
-import {
- calculateSocialMetricsRewardAmount,
- getBountyRewardCriteriaTexts,
- resolveBountyDetails,
-} from "@/lib/bounty/utils";
+import { calculateSocialMetricsRewardAmount } from "@/lib/bounty/rewards";
+import { BOUNTY_SUBMISSION_STATUS_BADGES } from "@/lib/bounty/submission-status";
+import { resolveBountyDetails } from "@/lib/bounty/utils";
import { mutatePrefix } from "@/lib/swr/mutate";
import { useApiMutation } from "@/lib/swr/use-api-mutation";
import useBounty from "@/lib/swr/use-bounty";
import useWorkspace from "@/lib/swr/use-workspace";
import { BountySubmissionProps } from "@/lib/types";
import { useConfirmApproveBountySubmissionModal } from "@/ui/modals/confirm-approve-bounty-submission-modal";
+import { PLATFORM_ICONS } from "@/ui/partners/bounties/bounty-platform-icons";
+import { EmphasisNumber } from "@/ui/partners/bounties/bounty-progress-bar-row";
+import { getBountyRewardCriteria } from "@/ui/partners/bounties/bounty-reward-criteria";
import { BountySocialContentPreview } from "@/ui/partners/bounties/bounty-social-content-preview";
import { BountySocialMetricsRewardsTable } from "@/ui/partners/bounties/bounty-social-metrics-rewards-table";
import { useRejectBountySubmissionModal } from "@/ui/partners/bounties/reject-bounty-submission-modal";
@@ -37,6 +37,7 @@ import {
currencyFormatter,
formatDate,
getPrettyUrl,
+ nFormatter,
OG_AVATAR_URL,
timeAgo,
} from "@dub/utils";
@@ -160,11 +161,23 @@ function BountySubmissionDetailsSheetContent({
}
const bountyInfo = resolveBountyDetails(bounty);
- const criteriaTexts = bounty ? getBountyRewardCriteriaTexts(bounty) : [];
+ const criteriaTexts = bounty ? getBountyRewardCriteria(bounty) : [];
const hasSocialContent =
bountyInfo?.hasSocialMetrics && (submission.urls?.length ?? 0) > 0;
+ const socialPlatform = bountyInfo?.socialPlatform;
+ const SocialPlatformIcon = socialPlatform
+ ? PLATFORM_ICONS[socialPlatform.value]
+ : null;
+ const socialMetricCount = submission.socialMetricCount ?? 0;
+ const socialMinCount = bountyInfo?.socialMetrics?.minCount ?? 0;
+ const socialMetricPercent =
+ socialMinCount > 0
+ ? Math.min((socialMetricCount / socialMinCount) * 100, 100)
+ : 100;
+ const socialMetricComplete = socialMetricPercent >= 100;
+
return (
<div className="flex h-full flex-col">
<div className="sticky top-0 z-10 border-b border-neutral-200 bg-white">
@@ -396,18 +409,52 @@ function BountySubmissionDetailsSheetContent({
<div className="mt-3 flex flex-col gap-6">
{hasSocialContent && (
- <BountySocialContentPreview
- bounty={bounty}
- submission={submission}
- />
+ <div className="rounded-xl border border-neutral-200 bg-neutral-50">
+ <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={cn(
+ "h-full rounded-full",
+ socialMetricComplete
+ ? "bg-green-600"
+ : "bg-amber-600",
+ )}
+ style={{ width: `${socialMetricPercent}%` }}
+ />
+ </div>
+
+ {SocialPlatformIcon && bountyInfo?.socialMetrics && (
+ <div className="flex items-center gap-2">
+ <SocialPlatformIcon className="size-4 shrink-0" />
+ <p className="text-sm font-medium text-neutral-600">
+ <EmphasisNumber>
+ {nFormatter(socialMetricCount, { full: true })}
+ </EmphasisNumber>
+ {" of "}
+ <EmphasisNumber>
+ {nFormatter(socialMinCount, { full: true })}
+ </EmphasisNumber>
+ {` ${bountyInfo.socialMetrics.metric} generated`}
+ </p>
+ </div>
+ )}
+ </div>
+ <BountySocialContentPreview
+ bounty={bounty}
+ submission={submission}
+ />
+ </div>
)}
- {bountyInfo?.hasSocialMetrics && bounty && (
- <BountySocialMetricsRewardsTable
- bounty={bounty}
- submission={submission}
- />
- )}
+ {bountyInfo?.hasSocialMetrics &&
+ ["draft", "submitted", "approved"].includes(
+ submission.status,
+ ) && (
+ <BountySocialMetricsRewardsTable
+ bounty={bounty}
+ submission={submission}
+ />
+ )}
{Boolean(submission.files?.length) && (
<div>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submissions-table.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submissions-table.tsx
index 4722f6e681..bf0896581d 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submissions-table.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submissions-table.tsx
@@ -2,7 +2,7 @@
import { isCurrencyAttribute } from "@/lib/api/workflows/utils";
import { PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES } from "@/lib/bounty/api/performance-bounty-scope-attributes";
-import { BOUNTY_SUBMISSION_STATUS_BADGES } from "@/lib/bounty/bounty-submission-status-badges";
+import { BOUNTY_SUBMISSION_STATUS_BADGES } from "@/lib/bounty/submission-status";
import { resolveBountyDetails } from "@/lib/bounty/utils";
import { mutatePrefix } from "@/lib/swr/mutate";
import { useApiMutation } from "@/lib/swr/use-api-mutation";
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/use-bounty-submission-filters.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/use-bounty-submission-filters.tsx
index 440868f94e..68f3314664 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/use-bounty-submission-filters.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/use-bounty-submission-filters.tsx
@@ -1,4 +1,4 @@
-import { BOUNTY_SUBMISSION_STATUS_BADGES } from "@/lib/bounty/bounty-submission-status-badges";
+import { BOUNTY_SUBMISSION_STATUS_BADGES } from "@/lib/bounty/submission-status";
import {
SubmissionsCountByStatus,
useBountySubmissionsCount,
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/add-edit-bounty-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/add-edit-bounty-sheet.tsx
index 0f5be34cac..ed42556068 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/add-edit-bounty-sheet.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/add-edit-bounty-sheet.tsx
@@ -1,4 +1,7 @@
-import { BOUNTY_DESCRIPTION_MAX_LENGTH } from "@/lib/bounty/constants";
+import {
+ BOUNTY_DESCRIPTION_MAX_LENGTH,
+ SUBMISSION_FREQUENCY_OPTIONS,
+} from "@/lib/bounty/constants";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import useProgram from "@/lib/swr/use-program";
import useWorkspace from "@/lib/swr/use-workspace";
@@ -10,13 +13,23 @@ import {
ProgramSheetAccordionItem,
ProgramSheetAccordionTrigger,
} from "@/ui/partners/program-sheet-accordion";
+import { RewardIconSquare } from "@/ui/partners/rewards/reward-icon-square";
import { X } from "@/ui/shared/icons";
+import {
+ InlineBadgePopover,
+ InlineBadgePopoverInput,
+} from "@/ui/shared/inline-badge-popover";
import { MaxCharactersCounter } from "@/ui/shared/max-characters-counter";
+import { BountySubmissionFrequency } from "@dub/prisma/client";
import {
AnimatedSizeContainer,
Button,
+ CalendarIcon,
CardSelector,
CardSelectorOption,
+ Combobox,
+ ComboboxOption,
+ Label,
NumberStepper,
RichTextArea,
RichTextProvider,
@@ -24,6 +37,7 @@ import {
Sheet,
SmartDateTimePicker,
Switch,
+ Tooltip,
TooltipContent,
useRouterStuff,
} from "@dub/ui";
@@ -64,9 +78,15 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {
hasEndDate,
handleEndDateToggle,
handleEndDateChange,
+ allowedSubmissions,
+ handleAllowedSubmissionsChange,
+ maxAllowedSubmissions,
submissionWindow,
handleSubmissionWindowToggle,
handleSubmissionWindowChange,
+ submissionFrequency,
+ handleSubmissionFrequencyToggle,
+ handleSubmissionFrequencyChange,
type,
name,
control,
@@ -146,9 +166,85 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {
</ProgramSheetAccordionTrigger>
<ProgramSheetAccordionContent>
<div className="space-y-6">
- <p className="text-content-default text-sm">
- Set the schedule, reward and additional details.
- </p>
+ {type === "submission" && (
+ <>
+ <div>
+ <Label htmlFor="name">Name</Label>
+ <div className="mt-2">
+ <input
+ id="name"
+ type="text"
+ maxLength={100}
+ className={cn(
+ "block w-full rounded-md border-neutral-300 px-3 py-2 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
+ errors.name &&
+ "border-red-600 focus:border-red-500 focus:ring-red-600",
+ )}
+ placeholder={`Create a YouTube video about${program?.name ? ` ${program.name}` : ""}...`}
+ {...register("name", {
+ setValueAs: (value) =>
+ value === "" ? null : value,
+ })}
+ />
+ <div className="mt-1 text-left">
+ <span className="text-xs text-neutral-400">
+ {name?.length || 0}/100
+ </span>
+ </div>
+ </div>
+ </div>
+ </>
+ )}
+
+ <div>
+ <Label>
+ Description
+ <span className="ml-1 font-normal text-neutral-500">
+ (optional)
+ </span>
+ </Label>
+ <div className="mt-2">
+ <Controller
+ control={control}
+ name="description"
+ render={({ field }) => (
+ <RichTextProvider
+ features={["bold", "italic", "links"]}
+ markdown
+ placeholder="Provide any bounty requirements to the partner"
+ editorClassName="block max-h-48 overflow-auto scrollbar-hide w-full resize-none border-none p-3 text-base sm:text-sm"
+ initialValue={field.value}
+ onChange={(editor: any) =>
+ field.onChange(editor.getMarkdown() || null)
+ }
+ >
+ <div
+ className={cn(
+ "overflow-hidden rounded-md border border-neutral-300 focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500",
+ errors.description &&
+ "border-red-600 focus-within:border-red-500 focus-within:ring-red-600",
+ )}
+ >
+ <div className="flex flex-col">
+ <RichTextArea />
+ <RichTextToolbar className="px-1 pb-1" />
+ </div>
+ </div>
+ </RichTextProvider>
+ )}
+ />
+
+ <div className="mt-1 text-left">
+ <MaxCharactersCounter
+ name="description"
+ control={control}
+ maxLength={BOUNTY_DESCRIPTION_MAX_LENGTH}
+ spaced
+ className="text-content-muted"
+ />
+ </div>
+ </div>
+ </div>
<AnimatedSizeContainer
height
@@ -167,11 +263,7 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {
thumbTranslate="translate-x-4"
disabled={Boolean(bounty?.startsAt)}
/>
- <div className="flex flex-col gap-1">
- <h3 className="text-sm font-medium text-neutral-700">
- Start date
- </h3>
- </div>
+ <Label>Start date</Label>
</div>
{hasStartDate && (
@@ -211,11 +303,7 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {
thumbTranslate="translate-x-4"
disabled={Boolean(bounty?.endsAt)}
/>
- <div className="flex flex-col gap-1">
- <h3 className="text-sm font-medium text-neutral-700">
- End date
- </h3>
- </div>
+ <Label>End date</Label>
</div>
{hasEndDate && (
@@ -256,11 +344,7 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {
thumbTranslate="translate-x-4"
disabled={Boolean(bounty?.endsAt)}
/>
- <div className="flex flex-col gap-1">
- <h3 className="text-sm font-medium text-neutral-700">
- End date
- </h3>
- </div>
+ <Label>End date</Label>
</div>
{hasEndDate && (
@@ -285,125 +369,134 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {
{type === "submission" && (
<>
- <div className="flex items-center gap-4">
- <Switch
- fn={handleSubmissionWindowToggle}
- checked={submissionWindow != null}
- trackDimensions="w-8 h-4"
- thumbDimensions="w-3 h-3"
- thumbTranslate="translate-x-4"
- disabled={!hasEndDate}
- />
- <div className="flex flex-col gap-1">
- <h3 className="text-sm font-medium text-neutral-700">
- Submission window
- </h3>
- </div>
- </div>
-
- {submissionWindow != null && (
- <div className="mt-3 space-y-2">
+ <div>
+ <Label>Allowed submissions</Label>
+ <div className="mt-2">
<NumberStepper
- value={submissionWindow}
- onChange={handleSubmissionWindowChange}
- min={2}
- max={14}
+ value={allowedSubmissions}
+ onChange={handleAllowedSubmissionsChange}
+ min={1}
+ max={maxAllowedSubmissions}
step={1}
className="w-full"
/>
- <p className="text-sm text-neutral-500">
- Submissions open {submissionWindow} days before
- the end date. Drafts can be saved until then.
- </p>
</div>
- )}
- </>
- )}
+ </div>
- {type === "submission" && (
- <>
<div>
- <label
- htmlFor="name"
- className="text-sm font-medium text-neutral-800"
+ <Tooltip
+ content={
+ !hasEndDate
+ ? "Set an end date to use submission window."
+ : allowedSubmissions > 1
+ ? "Decrease allowed submissions to 1 to use submission window."
+ : undefined
+ }
>
- Name
- </label>
- <div className="mt-2">
- <input
- id="name"
- type="text"
- maxLength={100}
+ <div
className={cn(
- "block w-full rounded-md border-neutral-300 px-3 py-2 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
- errors.name &&
- "border-red-600 focus:border-red-500 focus:ring-red-600",
+ "flex items-center gap-4 transition-opacity",
+ (!hasEndDate || allowedSubmissions > 1) &&
+ "opacity-30",
)}
- placeholder={`Create a YouTube video about${program?.name ? ` ${program.name}` : ""}...`}
- {...register("name", {
- setValueAs: (value) =>
- value === "" ? null : value,
- })}
- />
- <div className="mt-1 text-left">
- <span className="text-xs text-neutral-400">
- {name?.length || 0}/100
- </span>
+ >
+ <Switch
+ fn={handleSubmissionWindowToggle}
+ checked={submissionWindow != null}
+ trackDimensions="w-8 h-4"
+ thumbDimensions="w-3 h-3"
+ thumbTranslate="translate-x-4"
+ disabled={!hasEndDate || allowedSubmissions > 1}
+ />
+ <Label>Submission window</Label>
</div>
- </div>
- </div>
- </>
- )}
+ </Tooltip>
- <div>
- <label className="text-sm font-medium text-neutral-800">
- Description
- <span className="ml-1 font-normal text-neutral-500">
- (optional)
- </span>
- </label>
- <div className="mt-2">
- <Controller
- control={control}
- name="description"
- render={({ field }) => (
- <RichTextProvider
- features={["bold", "italic", "links"]}
- markdown
- placeholder="Provide any bounty requirements to the partner"
- editorClassName="block max-h-48 overflow-auto scrollbar-hide w-full resize-none border-none p-3 text-base sm:text-sm"
- initialValue={field.value}
- onChange={(editor: any) =>
- field.onChange(editor.getMarkdown() || null)
- }
- >
- <div
- className={cn(
- "overflow-hidden rounded-md border border-neutral-300 focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500",
- errors.description &&
- "border-red-600 focus-within:border-red-500 focus-within:ring-red-600",
- )}
- >
- <div className="flex flex-col">
- <RichTextArea />
- <RichTextToolbar className="px-1 pb-1" />
+ {submissionWindow != null && (
+ <div className="mt-3 space-y-2">
+ <div className="rounded-lg border border-neutral-200 bg-neutral-50/50 p-2.5 shadow-sm">
+ <div className="flex items-center gap-2.5">
+ <RewardIconSquare icon={CalendarIcon} />
+ <span className="text-content-default text-sm leading-relaxed">
+ Partners can submit{" "}
+ <SubmissionWindowBadge
+ value={submissionWindow}
+ onChange={handleSubmissionWindowChange}
+ />{" "}
+ days before the end date
+ </span>
</div>
</div>
- </RichTextProvider>
+ </div>
)}
- />
+ </div>
- <div className="mt-1 text-left">
- <MaxCharactersCounter
- name="description"
- control={control}
- maxLength={BOUNTY_DESCRIPTION_MAX_LENGTH}
- spaced
- className="text-content-muted"
- />
+ <div>
+ <Tooltip
+ content={
+ allowedSubmissions === 1
+ ? "Increase allowed submissions to 2 or more to use submission frequency."
+ : maxAllowedSubmissions < 2
+ ? "The selected date range is too short for submission frequency."
+ : undefined
+ }
+ >
+ <div
+ className={cn(
+ "flex items-center gap-4 transition-opacity",
+ (allowedSubmissions === 1 ||
+ maxAllowedSubmissions < 2) &&
+ "opacity-30",
+ )}
+ >
+ <Switch
+ fn={handleSubmissionFrequencyToggle}
+ checked={submissionFrequency != null}
+ trackDimensions="w-8 h-4"
+ thumbDimensions="w-3 h-3"
+ thumbTranslate="translate-x-4"
+ disabled={
+ allowedSubmissions === 1 ||
+ maxAllowedSubmissions < 2
+ }
+ />
+ <Label>Submission frequency</Label>
+ </div>
+ </Tooltip>
+
+ {submissionFrequency != null && (
+ <div className="mt-3 space-y-2">
+ <Combobox
+ selected={
+ SUBMISSION_FREQUENCY_OPTIONS.find(
+ (option) =>
+ option.value === submissionFrequency,
+ ) ?? null
+ }
+ setSelected={(option) =>
+ handleSubmissionFrequencyChange(
+ option?.value as BountySubmissionFrequency,
+ )
+ }
+ options={
+ SUBMISSION_FREQUENCY_OPTIONS as unknown as ComboboxOption<BountySubmissionFrequency>[]
+ }
+ caret
+ matchTriggerWidth
+ hideSearch
+ buttonProps={{
+ className: cn(
+ "w-full justify-start border-neutral-300 px-3",
+ "data-[state=open]:ring-1 data-[state=open]:ring-neutral-500 data-[state=open]:border-neutral-500",
+ "focus:ring-1 focus:ring-neutral-500 focus:border-neutral-500 focus:border-[var(--brand)] focus:ring-[var(--brand)] transition-none",
+ ),
+ }}
+ />
+ </div>
+ )}
</div>
- </div>
- </div>
+ </>
+ )}
</div>
</ProgramSheetAccordionContent>
</ProgramSheetAccordionItem>
@@ -471,6 +564,42 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {
);
}
+function SubmissionWindowBadge({
+ value,
+ onChange,
+}: {
+ value: number;
+ onChange: (value: number | undefined) => void;
+}) {
+ return (
+ <InlineBadgePopover
+ text={
+ value != null && !isNaN(value) ? String(value) : "Submission window"
+ }
+ invalid={value == null || isNaN(value)}
+ >
+ <InlineBadgePopoverInput
+ type="number"
+ min={1}
+ value={value == null || value === 0 ? "" : String(value)}
+ onChange={(e) => {
+ const raw = (e.target as HTMLInputElement).value;
+
+ if (raw === "") {
+ onChange(undefined);
+ return;
+ }
+
+ const num = parseInt(raw, 10);
+
+ onChange(Number.isNaN(num) ? undefined : Math.max(1, num));
+ }}
+ placeholder="days"
+ />
+ </InlineBadgePopover>
+ );
+}
+
export function BountySheet({
isOpen,
nested,
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-criteria-manual-submission.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-criteria-manual-submission.tsx
index 98352ff4a9..328cbd2bf7 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-criteria-manual-submission.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-criteria-manual-submission.tsx
@@ -207,7 +207,7 @@ export function BountyCriteriaManualSubmission() {
min={1}
max={BOUNTY_MAX_SUBMISSION_FILES}
step={1}
- className="h-9 w-full [&>div]:h-9"
+ className="w-full"
/>
<p className="text-xs text-neutral-500">
Set a maximum number of images partners can submit
@@ -255,7 +255,7 @@ export function BountyCriteriaManualSubmission() {
min={1}
max={BOUNTY_MAX_SUBMISSION_URLS}
step={1}
- className="h-9 w-full [&>div]:h-9"
+ className="w-full"
/>
<p className="text-xs text-neutral-500">
Set a maximum number of URLs partners can submit
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-criteria-social-metrics.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-criteria-social-metrics.tsx
index 8681ab4878..44253d4e06 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-criteria-social-metrics.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-criteria-social-metrics.tsx
@@ -3,7 +3,7 @@
import {
BOUNTY_SOCIAL_PLATFORM_METRICS_MAP,
BOUNTY_SOCIAL_PLATFORMS,
-} from "@/lib/bounty/constants";
+} from "@/lib/bounty/social-content";
import type { BountySocialMetricsIncrementalBonus } from "@/lib/types";
import { RewardIconSquare } from "@/ui/partners/rewards/reward-icon-square";
import { X } from "@/ui/shared/icons";
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/confirm-create-bounty-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/confirm-create-bounty-modal.tsx
index 25bc0b792e..283f25b512 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/confirm-create-bounty-modal.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/confirm-create-bounty-modal.tsx
@@ -1,4 +1,4 @@
-import { getBountyRewardDescription } from "@/lib/bounty/get-bounty-reward-description";
+import { getBountyRewardDescription } from "@/lib/bounty/rewards";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import useGroups from "@/lib/swr/use-groups";
import { usePartnersCountByGroupIds } from "@/lib/swr/use-partners-count-by-groupids";
@@ -31,6 +31,7 @@ type ConfirmCreateBountyModalProps = {
| "endsAt"
| "rewardAmount"
| "rewardDescription"
+ | "submissionRequirements"
| "groups"
>;
onConfirm: (data: { sendNotificationEmails: boolean }) => Promise<void>;
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/use-add-edit-bounty-form.ts b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/use-add-edit-bounty-form.ts
index 1a94df5f23..36520a28fc 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/use-add-edit-bounty-form.ts
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/use-add-edit-bounty-form.ts
@@ -2,14 +2,19 @@
import { isCurrencyAttribute } from "@/lib/api/workflows/utils";
import { generatePerformanceBountyName } from "@/lib/bounty/api/generate-performance-bounty-name";
-import { BOUNTY_DESCRIPTION_MAX_LENGTH } from "@/lib/bounty/constants";
+import {
+ BOUNTY_DESCRIPTION_MAX_LENGTH,
+ BOUNTY_MAX_SUBMISSIONS,
+} from "@/lib/bounty/constants";
+import { addFrequency } from "@/lib/bounty/periods";
import { mutatePrefix } from "@/lib/swr/mutate";
import { useApiMutation } from "@/lib/swr/use-api-mutation";
import useWorkspace from "@/lib/swr/use-workspace";
import { BountyProps } from "@/lib/types";
import { bountyPerformanceConditionSchema } from "@/lib/zod/schemas/bounties";
+import { BountySubmissionFrequency } from "@dub/prisma/client";
import { formatDate } from "@dub/utils";
-import { Dispatch, SetStateAction, useMemo, useState } from "react";
+import { Dispatch, SetStateAction, useEffect, useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { CreateBountyInputExtended } from "./bounty-form-context";
@@ -38,6 +43,13 @@ export function useAddEditBountyForm({
const [hasStartDate, setHasStartDate] = useState(!!bounty?.startsAt);
const [hasEndDate, setHasEndDate] = useState(!!bounty?.endsAt);
const [openAccordions, setOpenAccordions] = useState(ACCORDION_ITEMS);
+ const [allowedSubmissions, setAllowedSubmissions] = useState<number>(
+ bounty?.maxSubmissions ?? 1,
+ );
+ const [submissionFrequency, setSubmissionFrequency] =
+ useState<BountySubmissionFrequency | null>(
+ bounty?.submissionFrequency ?? null,
+ );
const [submissionWindow, setSubmissionWindow] = useState<number | null>(
() => {
@@ -200,6 +212,87 @@ export function useAddEditBountyForm({
}
};
+ const handleSubmissionFrequencyToggle = (checked: boolean) => {
+ if (checked) {
+ if (allowedSubmissions < 2) {
+ setAllowedSubmissions(2);
+ setValue("maxSubmissions", 2, { shouldDirty: true });
+ }
+
+ if (submissionWindow != null) {
+ setSubmissionWindow(null);
+ setValue("submissionsOpenAt", null, { shouldDirty: true });
+ }
+
+ setSubmissionFrequency(BountySubmissionFrequency.day);
+ setValue("submissionFrequency", BountySubmissionFrequency.day, {
+ shouldDirty: true,
+ });
+ } else {
+ setSubmissionFrequency(null);
+ setValue("submissionFrequency", null, { shouldDirty: true });
+ }
+ };
+
+ const handleSubmissionFrequencyChange = (
+ value: BountySubmissionFrequency,
+ ) => {
+ setSubmissionFrequency(value);
+ setValue("submissionFrequency", value, { shouldDirty: true });
+ };
+
+ const handleAllowedSubmissionsChange = (value: number) => {
+ setAllowedSubmissions(value);
+ setValue("maxSubmissions", value > 1 ? value : null, { shouldDirty: true });
+ if (value > 1 && submissionWindow != null) {
+ setSubmissionWindow(null);
+ setValue("submissionsOpenAt", null, { shouldDirty: true });
+ }
+ if (value === 1 && submissionFrequency != null) {
+ setSubmissionFrequency(null);
+ setValue("submissionFrequency", null, { shouldDirty: true });
+ }
+ };
+
+ const maxAllowedSubmissions = useMemo(() => {
+ if (!submissionFrequency || !endsAt) return BOUNTY_MAX_SUBMISSIONS;
+
+ const start = startsAt ? new Date(startsAt) : new Date();
+ const end = new Date(endsAt);
+
+ let count = 0;
+ for (let i = 0; i < BOUNTY_MAX_SUBMISSIONS; i++) {
+ const periodStart = addFrequency({
+ date: start,
+ frequency: submissionFrequency,
+ amount: i,
+ });
+ if (periodStart >= end) break;
+ count++;
+ }
+
+ return count;
+ }, [submissionFrequency, startsAt, endsAt]);
+
+ useEffect(() => {
+ if (allowedSubmissions > maxAllowedSubmissions) {
+ const clamped = maxAllowedSubmissions;
+ setAllowedSubmissions(clamped);
+ setValue("maxSubmissions", clamped > 1 ? clamped : null, {
+ shouldDirty: true,
+ });
+ if (clamped === 1 && submissionFrequency != null) {
+ setSubmissionFrequency(null);
+ setValue("submissionFrequency", null, { shouldDirty: true });
+ }
+ }
+ }, [
+ maxAllowedSubmissions,
+ allowedSubmissions,
+ setValue,
+ submissionFrequency,
+ ]);
+
const handleSubmissionWindowChange = (value: number) => {
setSubmissionWindow(value);
if (endsAt) {
@@ -384,8 +477,6 @@ export function useAddEditBountyForm({
data.submissionsOpenAt = null;
} else if (data.type === "submission") {
data.performanceCondition = null;
- data.submissionFrequency = undefined;
- data.maxSubmissions = undefined;
if ((formRewardType ?? "flat") === "custom") {
data.rewardAmount = null;
@@ -443,6 +534,7 @@ export function useAddEditBountyForm({
endsAt: endsAt || null,
rewardAmount: rewardAmount ? rewardAmount * 100 : null,
rewardDescription: rewardDescription || null,
+ submissionRequirements: submissionRequirements ?? null,
groups: groupIds?.map((id) => ({ id })) || [],
}
: undefined,
@@ -477,6 +569,12 @@ export function useAddEditBountyForm({
isDirty,
handleStartDateToggle,
handleEndDateChange,
+ allowedSubmissions,
+ handleAllowedSubmissionsChange,
+ maxAllowedSubmissions,
+ submissionFrequency,
+ handleSubmissionFrequencyToggle,
+ handleSubmissionFrequencyChange,
submissionWindow,
handleSubmissionWindowToggle,
handleSubmissionWindowChange,
diff --git a/apps/web/lib/actions/partners/create-bounty-submission.ts b/apps/web/lib/actions/partners/create-bounty-submission.ts
index 11af1708f4..978e1af91e 100644
--- a/apps/web/lib/actions/partners/create-bounty-submission.ts
+++ b/apps/web/lib/actions/partners/create-bounty-submission.ts
@@ -1,403 +1,18 @@
"use server";
-import { createId } from "@/lib/api/create-id";
-import { getWorkspaceUsers } from "@/lib/api/get-workspace-users";
-import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
-import { getSocialContent } from "@/lib/api/scrape-creators/get-social-content";
-import { BOUNTY_MAX_SUBMISSION_URLS } from "@/lib/bounty/constants";
-import {
- getPlatformFromSocialUrl,
- resolveBountyDetails,
-} from "@/lib/bounty/utils";
-import {
- createBountySubmissionInputSchema,
- submissionRequirementsSchema,
-} from "@/lib/zod/schemas/bounties";
-import { sendBatchEmail, sendEmail } from "@dub/email";
-import NewBountySubmission from "@dub/email/templates/bounty-new-submission";
-import BountySubmitted from "@dub/email/templates/bounty-submitted";
-import { prisma } from "@dub/prisma";
-import { BountySubmission, Prisma, WorkspaceRole } from "@dub/prisma/client";
-import { getDomainWithoutWWW } from "@dub/utils";
-import { waitUntil } from "@vercel/functions";
-import { formatDistanceToNow, isBefore } from "date-fns";
+import { BountySubmissionHandler } from "@/lib/bounty/api/create-bounty-submission";
+import { createBountySubmissionInputSchema } from "@/lib/zod/schemas/bounties";
import { authPartnerActionClient } from "../safe-action";
export const createBountySubmissionAction = authPartnerActionClient
.inputSchema(createBountySubmissionInputSchema)
.action(async ({ ctx, parsedInput }) => {
const { partner } = ctx;
- const { programId, bountyId, files, urls, description, isDraft } =
- parsedInput;
- const [programEnrollment, bounty] = await Promise.all([
- getProgramEnrollmentOrThrow({
- partnerId: partner.id,
- programId,
- include: {},
- }),
+ const handler = new BountySubmissionHandler({
+ ...parsedInput,
+ partner,
+ });
- 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.");
- }
-
- const bountyInfo = resolveBountyDetails(bounty);
- let submission: BountySubmission | null = null;
-
- if (bounty.submissions.length > 0) {
- submission = bounty.submissions[0];
-
- // if there's an existing submission, only throw an error
- // if submission is not a draft and is not for a social metrics bounty
- if (submission.status !== "draft" && !bountyInfo?.hasSocialMetrics) {
- throw new Error(
- `You already have a ${submission.status} submission for this bounty.`,
- );
- }
- }
-
- 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.");
- }
-
- if (
- !isDraft &&
- bounty.submissionsOpenAt &&
- bounty.submissionsOpenAt > now
- ) {
- const waitTime = formatDistanceToNow(bounty.submissionsOpenAt, {
- addSuffix: true,
- });
-
- throw new Error(
- `Submissions are not open yet. You can submit ${waitTime}.`,
- );
- }
-
- if (bountyInfo?.hasSocialMetrics && isDraft) {
- throw new Error(
- "Draft submissions are not allowed for social metrics bounties.",
- );
- }
-
- // Validate the submission requirements
- const submissionRequirements = bounty.submissionRequirements
- ? submissionRequirementsSchema.parse(bounty.submissionRequirements)
- : null;
-
- const requireImage = !!submissionRequirements?.image;
- const requireUrl = !!submissionRequirements?.url;
- const urlRequirement = submissionRequirements?.url || null;
- const imageRequirement = submissionRequirements?.image || null;
- const storedUrls = [...urls].slice(0, BOUNTY_MAX_SUBMISSION_URLS);
-
- let submissionData: Partial<Prisma.BountySubmissionUncheckedCreateInput> = {
- status: isDraft ? "draft" : "submitted",
- };
-
- if (!isDraft) {
- if (requireImage && files.length === 0) {
- throw new Error("You must submit an image.");
- }
-
- if (requireUrl && urls.length === 0) {
- throw new Error("You must submit a URL.");
- }
-
- // Validate URL domain restrictions
- if (
- urlRequirement?.domains &&
- urlRequirement.domains.length > 0 &&
- urls.length > 0
- ) {
- const allowedDomains = urlRequirement.domains
- .map((domain) => getDomainWithoutWWW(domain)?.toLowerCase())
- .filter((domain): domain is string => !!domain);
-
- if (allowedDomains.length > 0) {
- const invalidUrls = urls.filter((url) => {
- const urlDomain = getDomainWithoutWWW(url)?.toLowerCase();
- if (!urlDomain) return true;
- // Check if URL domain matches any allowed domain or is a subdomain
- return !allowedDomains.some(
- (allowedDomain) =>
- urlDomain === allowedDomain ||
- urlDomain.endsWith(`.${allowedDomain}`),
- );
- });
-
- 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.`,
- );
- }
- }
- }
-
- // Validate max count for URLs
- if (urlRequirement?.max && urls.length > urlRequirement.max) {
- throw new Error(
- `You can submit at most ${urlRequirement.max} URL${urlRequirement.max === 1 ? "" : "s"}.`,
- );
- }
-
- // Validate max count for images
- if (imageRequirement?.max && files.length > imageRequirement.max) {
- throw new Error(
- `You can submit at most ${imageRequirement.max} image${imageRequirement.max === 1 ? "" : "s"}.`,
- );
- }
-
- submissionData = {
- ...submissionData,
- completedAt: new Date(),
- };
- }
-
- // Validate social content requirements
- if (bountyInfo?.socialMetrics) {
- const contentUrl = storedUrls[0];
-
- if (!bountyInfo?.socialPlatform) {
- throw new Error("Invalid bounty platform.");
- }
-
- const platform = bountyInfo.socialPlatform;
-
- if (!contentUrl) {
- throw new Error(
- `You must provide a ${platform.label} URL to submit this bounty.`,
- );
- }
-
- const urlPlatform = getPlatformFromSocialUrl(contentUrl);
-
- if (urlPlatform !== platform.value) {
- throw new Error(
- `This link must be a ${platform.label} link. You submitted a link from another platform.`,
- );
- }
-
- const partnerPlatform = await prisma.partnerPlatform.findUnique({
- where: {
- partnerId_type: {
- partnerId: partner.id,
- type: platform.value,
- },
- },
- select: {
- identifier: true,
- verifiedAt: true,
- },
- });
-
- if (!partnerPlatform) {
- throw new Error(
- `You must connect your ${platform.label} account to your profile before submitting this bounty.`,
- );
- }
-
- if (!partnerPlatform.verifiedAt) {
- throw new Error(
- `You must verify your ${platform.label} account before submitting this bounty.`,
- );
- }
-
- const socialContent = await getSocialContent({
- platform: platform.value,
- url: storedUrls[0],
- });
-
- if (!socialContent.handle || !socialContent.publishedAt) {
- throw new Error(
- "We were unable to verify this content. Please review the submission and try again.",
- );
- }
-
- if (
- socialContent.handle.toLowerCase() !==
- partnerPlatform.identifier.toLowerCase()
- ) {
- throw new Error(
- `The content was not published from your connected ${platform.label} account.`,
- );
- }
-
- if (
- socialContent.publishedAt &&
- bounty.startsAt &&
- isBefore(socialContent.publishedAt, bounty.startsAt)
- ) {
- throw new Error(
- `This content was published before the bounty started. Please submit content posted after the start date.`,
- );
- }
-
- submissionData = {
- ...submissionData,
- status: "draft",
- completedAt: null,
- };
-
- const metricValue = socialContent[bountyInfo.socialMetrics.metric];
-
- if (typeof metricValue === "number" && Number.isInteger(metricValue)) {
- submissionData = {
- ...submissionData,
- urls: [contentUrl],
- socialMetricCount: metricValue,
- socialMetricsLastSyncedAt: new Date(),
- };
-
- if (
- metricValue &&
- bountyInfo.socialMetrics.minCount &&
- metricValue >= bountyInfo.socialMetrics.minCount
- ) {
- submissionData.status = "submitted";
- submissionData.completedAt = new Date();
- }
- }
- }
-
- submissionData = {
- ...submissionData,
- ...(requireImage && { files }),
- ...(!bountyInfo?.hasSocialMetrics && requireUrl && { urls }),
- ...(description && { description }),
- };
-
- // If there is an existing submission, update it
- if (submission) {
- submission = await prisma.bountySubmission.update({
- where: {
- id: submission.id,
- },
- data: {
- ...submissionData,
- },
- });
- }
- // If there is no existing submission, create a new one
- else {
- submission = await prisma.bountySubmission.create({
- data: {
- ...submissionData,
- id: createId({ prefix: "bnty_sub_" }),
- programId: bounty.programId,
- bountyId: bounty.id,
- partnerId: partner.id,
- },
- });
- }
-
- waitUntil(
- (async () => {
- if (submission.status === "draft") {
- return;
- }
-
- // Send email to the program owners
- const { users, program, ...workspace } = await getWorkspaceUsers({
- programId,
- role: WorkspaceRole.owner,
- notificationPreference: "newBountySubmitted",
- });
-
- if (users.length > 0) {
- await sendBatchEmail(
- users.map((user) => ({
- variant: "notifications",
- to: user.email,
- subject: "New bounty submission",
- react: NewBountySubmission({
- email: user.email,
- workspace: {
- slug: workspace.slug,
- },
- bounty: {
- id: bounty.id,
- name: bounty.name,
- },
- partner: {
- id: partner.id,
- name: partner.name,
- image: partner.image,
- email: partner.email!,
- },
- submission: {
- id: submission.id,
- },
- }),
- })),
- );
- }
-
- // Send email to the partner
- if (partner.email && program) {
- await sendEmail({
- subject: "Bounty submitted!",
- to: partner.email,
- replyTo: program.supportEmail || "noreply",
- react: BountySubmitted({
- email: partner.email,
- bounty: {
- name: bounty.name,
- },
- program: {
- name: program.name,
- slug: program.slug,
- },
- }),
- });
- }
- })(),
- );
+ await handler.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 06863929ab..e7ba7530a3 100644
--- a/apps/web/lib/actions/partners/upload-bounty-submission-file.ts
+++ b/apps/web/lib/actions/partners/upload-bounty-submission-file.ts
@@ -14,7 +14,7 @@ const schema = z.object({
bountyId: z.string(),
});
-const MAX_ATTEMPTS = 5;
+const MAX_ATTEMPTS = 25;
const CACHE_KEY_PREFIX = "bounty:submission:file:upload";
export const uploadBountySubmissionFileAction = authPartnerActionClient
@@ -65,17 +65,6 @@ export const uploadBountySubmissionFileAction = authPartnerActionClient
throw new Error("This bounty is not for this program.");
}
- // Validate the partner has not already created a submission for this bounty
- if (bounty.submissions.length > 0) {
- const submission = bounty.submissions[0];
-
- if (submission.status !== "draft") {
- throw new Error(
- "You have already created a submission for this bounty.",
- );
- }
- }
-
if (bounty.groups.length > 0) {
const isInGroup = bounty.groups.find(
({ groupId }) => groupId === programEnrollment.groupId,
diff --git a/apps/web/lib/api/partner-profile/get-partner-earnings-timeseries.ts b/apps/web/lib/api/partner-profile/get-partner-earnings-timeseries.ts
index 868bd3809d..c3d9152266 100644
--- a/apps/web/lib/api/partner-profile/get-partner-earnings-timeseries.ts
+++ b/apps/web/lib/api/partner-profile/get-partner-earnings-timeseries.ts
@@ -49,14 +49,7 @@ export async function getPartnerEarningsTimeseries({
const { dateFormat, dateIncrement, startFunction, formatString } =
sqlGranularityMap[granularity];
- const earnings = await prisma.$queryRaw<
- {
- start: string;
- earnings: number;
- type?: string;
- linkId?: string;
- }[]
- >`
+ const query = Prisma.sql`
SELECT
DATE_FORMAT(CONVERT_TZ(createdAt, "UTC", ${timezone || "UTC"}), ${dateFormat}) AS start,
${groupBy ? (groupBy === "type" ? Prisma.sql`type,` : Prisma.sql`linkId,`) : Prisma.sql``}
@@ -77,6 +70,15 @@ export async function getPartnerEarningsTimeseries({
ORDER BY start ASC;
`;
+ const earnings = await prisma.$queryRaw<
+ {
+ start: string;
+ earnings: number;
+ type?: string;
+ linkId?: string;
+ }[]
+ >(query);
+
const timeseries: {
start: string;
earnings: number;
diff --git a/apps/web/lib/api/scrape-creators/get-social-content.ts b/apps/web/lib/api/scrape-creators/get-social-content.ts
index bd3a1255bb..c557f2f4a6 100644
--- a/apps/web/lib/api/scrape-creators/get-social-content.ts
+++ b/apps/web/lib/api/scrape-creators/get-social-content.ts
@@ -1,4 +1,4 @@
-import { BOUNTY_SOCIAL_PLATFORM_VALUES } from "@/lib/bounty/constants";
+import { BOUNTY_SOCIAL_PLATFORM_VALUES } from "@/lib/bounty/social-content";
import { SocialContent } from "@/lib/types";
import { redis } from "@/lib/upstash";
import { PlatformType } from "@dub/prisma/client";
diff --git a/apps/web/lib/api/workflows/execute-complete-bounty-workflow.ts b/apps/web/lib/api/workflows/execute-complete-bounty-workflow.ts
index ba1de49d3b..fead14af24 100644
--- a/apps/web/lib/api/workflows/execute-complete-bounty-workflow.ts
+++ b/apps/web/lib/api/workflows/execute-complete-bounty-workflow.ts
@@ -116,13 +116,15 @@ export const executeCompleteBountyWorkflow = async ({
};
const performanceCount = finalContext[condition.attribute] ?? 0;
+ const periodNumber = 1; // Only one submission is allowed for performance based bounties
// Create or update the submission
const bountySubmission = await prisma.bountySubmission.upsert({
where: {
- bountyId_partnerId: {
+ bountyId_partnerId_periodNumber: {
bountyId,
partnerId,
+ periodNumber,
},
},
create: {
@@ -130,6 +132,7 @@ export const executeCompleteBountyWorkflow = async ({
programId: bounty.programId,
partnerId,
bountyId: bounty.id,
+ periodNumber,
status: "draft",
performanceCount,
},
diff --git a/apps/web/lib/bounty/api/approve-bounty-submission.ts b/apps/web/lib/bounty/api/approve-bounty-submission.ts
index 95198e1b73..6326c46c35 100644
--- a/apps/web/lib/bounty/api/approve-bounty-submission.ts
+++ b/apps/web/lib/bounty/api/approve-bounty-submission.ts
@@ -1,10 +1,8 @@
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
import { DubApiError } from "@/lib/api/errors";
import { Session } from "@/lib/auth";
-import {
- calculateSocialMetricsRewardAmount,
- resolveBountyDetails,
-} from "@/lib/bounty/utils";
+import { calculateSocialMetricsRewardAmount } from "@/lib/bounty/rewards";
+import { resolveBountyDetails } from "@/lib/bounty/utils";
import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
import {
approveBountySubmissionBodySchema,
diff --git a/apps/web/lib/bounty/api/create-bounty-submission.ts b/apps/web/lib/bounty/api/create-bounty-submission.ts
new file mode 100644
index 0000000000..dd0f226373
--- /dev/null
+++ b/apps/web/lib/bounty/api/create-bounty-submission.ts
@@ -0,0 +1,619 @@
+import { createId } from "@/lib/api/create-id";
+import { getWorkspaceUsers } from "@/lib/api/get-workspace-users";
+import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { getSocialContent } from "@/lib/api/scrape-creators/get-social-content";
+import { BOUNTY_MAX_SUBMISSION_URLS } from "@/lib/bounty/constants";
+import { addFrequency, getCurrentPeriodNumber } from "@/lib/bounty/periods";
+import { resolveBountyDetails } from "@/lib/bounty/utils";
+import {
+ createBountySubmissionInputSchema,
+ submissionRequirementsSchema,
+} from "@/lib/zod/schemas/bounties";
+import { sendBatchEmail, sendEmail } from "@dub/email";
+import NewBountySubmission from "@dub/email/templates/bounty-new-submission";
+import BountySubmitted from "@dub/email/templates/bounty-submitted";
+import { prisma } from "@dub/prisma";
+import {
+ BountySubmission,
+ Partner,
+ PlatformType,
+ Prisma,
+ WorkspaceRole,
+} from "@dub/prisma/client";
+import { getDomainWithoutWWW, isValidUrl } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
+import { formatDistanceToNow, isBefore } from "date-fns";
+import * as z from "zod/v4";
+import { SOCIAL_URL_HOST_TO_PLATFORM } from "../social-content";
+
+type CreateBountySubmissionParams = z.infer<
+ typeof createBountySubmissionInputSchema
+> & {
+ partner: Pick<Partner, "id" | "name" | "image" | "email">;
+};
+
+type BountyWithRelations = Prisma.BountyGetPayload<{
+ include: {
+ groups: true;
+ submissions: true;
+ };
+}>;
+
+export class BountySubmissionHandler {
+ // Input
+ private partner: CreateBountySubmissionParams["partner"];
+ private programId: string;
+ private bountyId: string;
+ private files: z.infer<typeof createBountySubmissionInputSchema>["files"];
+ private urls: string[];
+ private description?: string;
+ private isDraft: boolean;
+ private periodNumber?: number;
+
+ // Resolved state
+ private bounty: BountyWithRelations;
+ private finalPeriodNumber: number;
+ private submissions: BountySubmission[];
+ private submissionData: Partial<Prisma.BountySubmissionUncheckedCreateInput>;
+ private programEnrollment: Prisma.ProgramEnrollmentGetPayload<{
+ include: {};
+ }>;
+
+ constructor(params: CreateBountySubmissionParams) {
+ this.partner = params.partner;
+ this.programId = params.programId;
+ this.bountyId = params.bountyId;
+ this.files = params.files;
+ this.urls = params.urls;
+ this.description = params.description;
+ this.isDraft = params.isDraft;
+ this.periodNumber = params.periodNumber;
+ }
+
+ async submit(): Promise<BountySubmission> {
+ await this.fetchBountyAndEnrollment();
+
+ this.resolvePeriodNumber();
+
+ this.validateEligibility();
+
+ this.validateRequirements();
+
+ await this.validateSocialContent();
+
+ this.mergeSubmissionData();
+
+ const submission = await this.persist();
+
+ this.sendNotifications(submission);
+
+ return submission;
+ }
+
+ // Fetch the bounty and program enrollment
+ private async fetchBountyAndEnrollment() {
+ const [programEnrollment, bounty] = await Promise.all([
+ getProgramEnrollmentOrThrow({
+ partnerId: this.partner.id,
+ programId: this.programId,
+ include: {},
+ }),
+
+ prisma.bounty.findUniqueOrThrow({
+ where: {
+ id: this.bountyId,
+ },
+ include: {
+ groups: true,
+ submissions: {
+ where: {
+ partnerId: this.partner.id,
+ },
+ },
+ },
+ }),
+ ]);
+
+ this.programEnrollment = programEnrollment;
+ this.bounty = bounty;
+ this.submissions = bounty.submissions;
+ }
+
+ // Resolve the period number for the submission
+ private resolvePeriodNumber() {
+ const isMultiSubmission = this.bounty.maxSubmissions > 1;
+
+ if (!isMultiSubmission) {
+ this.finalPeriodNumber = 1;
+ return;
+ }
+
+ // Multi-submission WITHOUT frequency — all periods open
+ if (!this.bounty.submissionFrequency) {
+ if (!this.periodNumber) {
+ throw new Error("Period number is required for this bounty.");
+ }
+
+ if (
+ this.periodNumber < 1 ||
+ this.periodNumber > this.bounty.maxSubmissions
+ ) {
+ throw new Error("Invalid submission period number.");
+ }
+
+ this.finalPeriodNumber = this.periodNumber;
+ return;
+ }
+
+ // Multi-submission WITH frequency — time-gated
+ const currentPeriod = getCurrentPeriodNumber({
+ startsAt: this.bounty.startsAt,
+ endsAt: this.bounty.endsAt,
+ submissionFrequency: this.bounty.submissionFrequency,
+ maxSubmissions: this.bounty.maxSubmissions,
+ });
+
+ let periodNumber: number;
+
+ if (this.periodNumber) {
+ periodNumber = this.periodNumber;
+ } else {
+ if (!currentPeriod) {
+ throw new Error("No active submission period for this bounty.");
+ }
+
+ periodNumber = currentPeriod;
+ }
+
+ if (periodNumber < 1 || periodNumber > this.bounty.maxSubmissions) {
+ throw new Error("Invalid submission period number.");
+ }
+
+ // Validate the period has started
+ const periodStart = addFrequency({
+ date: this.bounty.startsAt,
+ frequency: this.bounty.submissionFrequency,
+ amount: periodNumber - 1,
+ });
+
+ if (new Date() < periodStart) {
+ throw new Error("This submission period hasn't started yet.");
+ }
+
+ if (currentPeriod && periodNumber < currentPeriod) {
+ throw new Error("This submission period has already closed.");
+ }
+
+ this.finalPeriodNumber = periodNumber;
+ }
+
+ // 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.",
+ );
+ }
+
+ if (this.bounty.programId !== this.programId) {
+ throw new Error("This bounty is not for this program.");
+ }
+
+ // Check existing submission for this period
+ const existingSubmission = this.submissions.find(
+ (s) => s.periodNumber === this.finalPeriodNumber,
+ );
+
+ const bountyInfo = resolveBountyDetails(this.bounty);
+
+ if (existingSubmission) {
+ if (
+ existingSubmission.reviewedAt ||
+ existingSubmission.status === "approved" ||
+ existingSubmission.status === "rejected"
+ ) {
+ throw new Error(
+ `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.`,
+ );
+ }
+ }
+
+ // Check group membership
+ if (this.bounty.groups.length > 0) {
+ const isInGroup = this.bounty.groups.find(
+ ({ groupId }) => groupId === this.programEnrollment.groupId,
+ );
+
+ if (!isInGroup) {
+ throw new Error("You are not allowed to submit this bounty.");
+ }
+ }
+
+ // Validate bounty dates and status
+ const now = new Date();
+
+ if (this.bounty.startsAt && this.bounty.startsAt > now) {
+ throw new Error("This bounty is not yet available.");
+ }
+
+ if (this.bounty.endsAt && this.bounty.endsAt < now) {
+ throw new Error("This bounty is no longer available.");
+ }
+
+ if (this.bounty.archivedAt) {
+ throw new Error("This bounty is archived.");
+ }
+
+ if (this.bounty.type === "performance") {
+ throw new Error("You are not allowed to submit a performance bounty.");
+ }
+
+ if (
+ !this.isDraft &&
+ this.bounty.submissionsOpenAt &&
+ this.bounty.submissionsOpenAt > now
+ ) {
+ const waitTime = formatDistanceToNow(this.bounty.submissionsOpenAt, {
+ addSuffix: true,
+ });
+
+ throw new Error(
+ `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.",
+ );
+ }
+ }
+
+ // Validate the requirements of the submission
+ private validateRequirements() {
+ const submissionRequirements = submissionRequirementsSchema
+ .nullable()
+ .parse(this.bounty.submissionRequirements);
+
+ const requireImage = !!submissionRequirements?.image;
+ const requireUrl = !!submissionRequirements?.url;
+ const urlRequirement = submissionRequirements?.url || null;
+ const imageRequirement = submissionRequirements?.image || null;
+
+ this.submissionData = {
+ status: this.isDraft ? "draft" : "submitted",
+ };
+
+ if (!this.isDraft) {
+ if (requireImage && this.files.length === 0) {
+ throw new Error("You must submit an image.");
+ }
+
+ if (requireUrl && this.urls.length === 0) {
+ throw new Error("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"}.`,
+ );
+ }
+
+ // 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"}.`,
+ );
+ }
+
+ this.submissionData = {
+ ...this.submissionData,
+ completedAt: new Date(),
+ };
+ }
+ }
+
+ // Validate the domains of the URLs
+ private validateUrlDomains(
+ urlRequirement: {
+ domains?: string[] | null;
+ } | null,
+ ) {
+ if (
+ !urlRequirement?.domains ||
+ urlRequirement.domains.length === 0 ||
+ this.urls.length === 0
+ ) {
+ return;
+ }
+
+ const allowedDomains = urlRequirement.domains
+ .map((domain) => getDomainWithoutWWW(domain)?.toLowerCase())
+ .filter((domain): domain is string => !!domain);
+
+ if (allowedDomains.length === 0) {
+ return;
+ }
+
+ const invalidUrls = this.urls.filter((url) => {
+ const urlDomain = getDomainWithoutWWW(url)?.toLowerCase();
+
+ if (!urlDomain) {
+ return true;
+ }
+
+ return !allowedDomains.some(
+ (allowedDomain) =>
+ urlDomain === allowedDomain ||
+ urlDomain.endsWith(`.${allowedDomain}`),
+ );
+ });
+
+ 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.`,
+ );
+ }
+ }
+
+ // Validate the social content of the submission
+ private async validateSocialContent() {
+ const bountyInfo = resolveBountyDetails(this.bounty);
+
+ if (!bountyInfo?.socialMetrics) {
+ return;
+ }
+
+ const contentUrl = this.urls[0];
+
+ if (!bountyInfo.socialPlatform) {
+ throw new Error("Invalid bounty platform.");
+ }
+
+ const platform = bountyInfo.socialPlatform;
+
+ if (!contentUrl) {
+ throw new Error(
+ `You must provide a ${platform.label} URL to submit this bounty.`,
+ );
+ }
+
+ const urlPlatform = getPlatformFromSocialUrl(contentUrl);
+
+ if (urlPlatform !== platform.value) {
+ throw new Error(
+ `This link must be a ${platform.label} link. You submitted a link from another platform.`,
+ );
+ }
+
+ const partnerPlatform = await prisma.partnerPlatform.findUnique({
+ where: {
+ partnerId_type: {
+ partnerId: this.partner.id,
+ type: platform.value,
+ },
+ },
+ select: {
+ identifier: true,
+ verifiedAt: true,
+ },
+ });
+
+ if (!partnerPlatform) {
+ throw new Error(
+ `You must connect your ${platform.label} account to your profile before submitting this bounty.`,
+ );
+ }
+
+ if (!partnerPlatform.verifiedAt) {
+ throw new Error(
+ `You must verify your ${platform.label} account before submitting this bounty.`,
+ );
+ }
+
+ const socialContent = await getSocialContent({
+ platform: platform.value,
+ url: contentUrl,
+ });
+
+ if (!socialContent.handle || !socialContent.publishedAt) {
+ throw new Error(
+ "We were unable to verify this content. Please review the submission and try again.",
+ );
+ }
+
+ if (
+ socialContent.handle.toLowerCase() !==
+ partnerPlatform.identifier.toLowerCase()
+ ) {
+ throw new Error(
+ `The content was not published from your connected ${platform.label} account.`,
+ );
+ }
+
+ if (
+ socialContent.publishedAt &&
+ 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.`,
+ );
+ }
+
+ this.submissionData = {
+ ...this.submissionData,
+ status: "draft",
+ completedAt: null,
+ };
+
+ const metricValue = socialContent[bountyInfo.socialMetrics!.metric];
+
+ if (typeof metricValue === "number" && Number.isInteger(metricValue)) {
+ this.submissionData = {
+ ...this.submissionData,
+ urls: [contentUrl],
+ socialMetricCount: metricValue,
+ socialMetricsLastSyncedAt: new Date(),
+ };
+
+ if (
+ metricValue &&
+ bountyInfo.socialMetrics!.minCount &&
+ metricValue >= bountyInfo.socialMetrics!.minCount
+ ) {
+ this.submissionData.status = "submitted";
+ this.submissionData.completedAt = new Date();
+ }
+ }
+ }
+
+ // Merge the submission data
+ private mergeSubmissionData() {
+ const bountyInfo = resolveBountyDetails(this.bounty);
+
+ const submissionRequirements = submissionRequirementsSchema
+ .nullable()
+ .parse(this.bounty.submissionRequirements);
+
+ const requireImage = !!submissionRequirements?.image;
+ const requireUrl = !!submissionRequirements?.url;
+
+ this.submissionData = {
+ ...this.submissionData,
+ ...(requireImage && { files: this.files }),
+ ...(!bountyInfo?.hasSocialMetrics &&
+ requireUrl && {
+ urls: [...this.urls].slice(0, BOUNTY_MAX_SUBMISSION_URLS),
+ }),
+ ...(this.description !== undefined && { description: this.description }),
+ };
+ }
+
+ // Persist the submission
+ private async persist(): Promise<BountySubmission> {
+ const existingSubmission = this.submissions.find(
+ (s) => s.periodNumber === this.finalPeriodNumber,
+ );
+
+ if (existingSubmission) {
+ return prisma.bountySubmission.update({
+ where: {
+ id: existingSubmission.id,
+ },
+ data: {
+ ...this.submissionData,
+ },
+ });
+ }
+
+ return prisma.bountySubmission.create({
+ data: {
+ ...this.submissionData,
+ id: createId({ prefix: "bnty_sub_" }),
+ programId: this.bounty.programId,
+ bountyId: this.bounty.id,
+ partnerId: this.partner.id,
+ periodNumber: this.finalPeriodNumber,
+ },
+ });
+ }
+
+ // Send notifications for the submission
+ private sendNotifications(submission: BountySubmission) {
+ const { partner, bounty } = this;
+ const programId = this.programId;
+
+ if (submission.status === "draft") {
+ return;
+ }
+
+ waitUntil(
+ (async () => {
+ const { users, program, ...workspace } = await getWorkspaceUsers({
+ programId,
+ role: WorkspaceRole.owner,
+ notificationPreference: "newBountySubmitted",
+ });
+
+ if (users.length > 0) {
+ await sendBatchEmail(
+ users.map((user) => ({
+ variant: "notifications" as const,
+ to: user.email,
+ subject: "New bounty submission",
+ react: NewBountySubmission({
+ email: user.email,
+ workspace: {
+ slug: workspace.slug,
+ },
+ bounty: {
+ id: bounty.id,
+ name: bounty.name,
+ },
+ partner: {
+ id: partner.id,
+ name: partner.name,
+ image: partner.image,
+ email: partner.email ?? "",
+ },
+ submission: {
+ id: submission.id,
+ },
+ }),
+ })),
+ );
+ }
+
+ if (partner.email && program) {
+ await sendEmail({
+ subject: "Bounty submitted!",
+ to: partner.email,
+ replyTo: program.supportEmail || "noreply",
+ react: BountySubmitted({
+ email: partner.email,
+ bounty: {
+ name: bounty.name,
+ },
+ program: {
+ name: program.name,
+ slug: program.slug,
+ },
+ }),
+ });
+ }
+ })(),
+ );
+ }
+}
+
+function getPlatformFromSocialUrl(url: string): PlatformType | null {
+ const trimmed = url?.trim();
+
+ if (!trimmed || !isValidUrl(trimmed)) {
+ return null;
+ }
+
+ try {
+ const parsed = new URL(trimmed);
+ const host = parsed.hostname.replace(/^www\./, "");
+
+ return SOCIAL_URL_HOST_TO_PLATFORM[host] ?? null;
+ } catch {
+ return null;
+ }
+}
diff --git a/apps/web/lib/bounty/api/get-bounty-with-details.ts b/apps/web/lib/bounty/api/get-bounty-with-details.ts
index cfd5ee3729..acb707c441 100644
--- a/apps/web/lib/bounty/api/get-bounty-with-details.ts
+++ b/apps/web/lib/bounty/api/get-bounty-with-details.ts
@@ -36,7 +36,7 @@ export const getBountyWithDetails = async ({
WHERE bountyId = b.id
),
JSON_ARRAY()
- ) AS groups
+ ) AS \`groups\`
FROM Bounty b
LEFT JOIN Workflow wf ON wf.id = b.workflowId
diff --git a/apps/web/lib/bounty/api/validate-bounty.ts b/apps/web/lib/bounty/api/validate-bounty.ts
index ecea4ee8a2..19c28f21ce 100644
--- a/apps/web/lib/bounty/api/validate-bounty.ts
+++ b/apps/web/lib/bounty/api/validate-bounty.ts
@@ -80,5 +80,12 @@ export function validateBounty({
message: "maxSubmissions is required when submissionFrequency is set.",
});
}
+
+ if (submissionFrequency && !endsAt) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "An end date is required when submissionFrequency is set.",
+ });
+ }
}
}
diff --git a/apps/web/lib/bounty/constants.ts b/apps/web/lib/bounty/constants.ts
index 29b778414f..2bc3609ec3 100644
--- a/apps/web/lib/bounty/constants.ts
+++ b/apps/web/lib/bounty/constants.ts
@@ -1,5 +1,9 @@
+import { BountySubmissionFrequency } from "@dub/prisma/client";
+
export const BOUNTY_DESCRIPTION_MAX_LENGTH = 5000;
+export const BOUNTY_MAX_SUBMISSIONS = 10;
+
export const BOUNTY_MAX_SUBMISSION_FILES = 4;
export const BOUNTY_DEFAULT_SUBMISSION_URLS = 10;
@@ -20,51 +24,8 @@ export const REJECT_BOUNTY_SUBMISSION_REASONS = {
other: "Other",
} as const;
-export const BOUNTY_SOCIAL_PLATFORMS = [
- {
- value: "youtube",
- label: "YouTube",
- postType: "video",
- metrics: ["views", "likes"],
- placeholder: "https://www.youtube.com/watch?v=",
- },
- {
- value: "tiktok",
- label: "TikTok",
- postType: "video",
- metrics: ["views", "likes"],
- placeholder: "https://www.tiktok.com/@username/video/",
- },
- {
- value: "instagram",
- label: "Instagram",
- postType: "photo",
- metrics: ["likes", "views"],
- placeholder: "https://www.instagram.com/username/reel/",
- },
- {
- value: "twitter",
- label: "X/Twitter",
- postType: "tweet",
- metrics: ["likes", "views"],
- placeholder: "https://x.com/username/status/",
- },
+export const SUBMISSION_FREQUENCY_OPTIONS = [
+ { label: "Once a day", value: BountySubmissionFrequency.day },
+ { label: "Once a week", value: BountySubmissionFrequency.week },
+ { label: "Once a month", value: BountySubmissionFrequency.month },
] as const;
-
-export const BOUNTY_SOCIAL_PLATFORM_VALUES = BOUNTY_SOCIAL_PLATFORMS.map(
- (p) => p.value,
-);
-
-export const BOUNTY_SOCIAL_PLATFORM_METRICS = BOUNTY_SOCIAL_PLATFORMS.map(
- (p) => p.metrics,
-).flat();
-
-export const BOUNTY_SOCIAL_PLATFORM_METRICS_MAP = Object.fromEntries(
- BOUNTY_SOCIAL_PLATFORMS.map((p) => [
- p.value,
- p.metrics.map((m) => ({
- value: m,
- label: m,
- })),
- ]),
-);
diff --git a/apps/web/lib/bounty/get-bounty-reward-description.ts b/apps/web/lib/bounty/get-bounty-reward-description.ts
deleted file mode 100644
index f3ccdd4f25..0000000000
--- a/apps/web/lib/bounty/get-bounty-reward-description.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { currencyFormatter } from "@dub/utils";
-import { BountyProps } from "../types";
-import { resolveBountyDetails } from "./utils";
-
-export function getBountyRewardDescription(
- bounty: Pick<BountyProps, "rewardAmount" | "rewardDescription"> & {
- submissionRequirements?: BountyProps["submissionRequirements"];
- },
-) {
- const bountyInfo = resolveBountyDetails({
- rewardAmount: bounty.rewardAmount,
- submissionRequirements: bounty.submissionRequirements ?? null,
- });
-
- const incrementalBonus = bountyInfo?.socialMetrics?.incrementalBonus;
-
- if (
- incrementalBonus?.incrementCount &&
- incrementalBonus?.bonusPerIncrement != null &&
- incrementalBonus?.maxCount
- ) {
- const baseRewardCents = bounty.rewardAmount ?? 0;
-
- const incrementalCapCents =
- Math.floor(incrementalBonus.maxCount / incrementalBonus.incrementCount) *
- incrementalBonus.bonusPerIncrement;
-
- const earningsCapCents = baseRewardCents + incrementalCapCents;
-
- if (earningsCapCents > 0) {
- const formattedEarningsCap = currencyFormatter(earningsCapCents, {
- trailingZeroDisplay: "stripIfInteger",
- });
-
- return `Earn up to ${formattedEarningsCap}`;
- }
- }
-
- if (bounty.rewardAmount) {
- const formattedAmount = currencyFormatter(bounty.rewardAmount, {
- trailingZeroDisplay: "stripIfInteger",
- });
-
- return `Earn ${formattedAmount}`;
- }
-
- if (bounty.rewardDescription) {
- return bounty.rewardDescription;
- }
-
- return "";
-}
diff --git a/apps/web/lib/bounty/periods.ts b/apps/web/lib/bounty/periods.ts
new file mode 100644
index 0000000000..1846dbf445
--- /dev/null
+++ b/apps/web/lib/bounty/periods.ts
@@ -0,0 +1,255 @@
+import { BountySubmissionFrequency } from "@dub/prisma/client";
+import { addDays, addMonths, addWeeks } from "date-fns";
+
+export type SubmissionPeriodStatus =
+ | "notSubmitted"
+ | "notOpen"
+ | "draft"
+ | "submitted"
+ | "approved"
+ | "rejected";
+
+export interface SubmissionPeriod<TSubmission = unknown> {
+ periodNumber: number;
+ label: string;
+ startDate: Date;
+ endDate: Date;
+ status: SubmissionPeriodStatus;
+ submission: TSubmission | null;
+}
+
+// Add a frequency-based duration to a date.
+export function addFrequency({
+ date,
+ frequency,
+ amount,
+}: {
+ date: Date;
+ frequency: BountySubmissionFrequency;
+ amount: number;
+}): Date {
+ switch (frequency) {
+ case "day":
+ return addDays(date, amount);
+ case "week":
+ return addWeeks(date, amount);
+ case "month":
+ return addMonths(date, amount);
+ default:
+ return addWeeks(date, amount);
+ }
+}
+
+// Get a human-readable label for a period (0-indexed input).
+export function getPeriodLabel(
+ frequency: BountySubmissionFrequency | null,
+ index: number,
+): string {
+ const n = index + 1;
+
+ if (!frequency) {
+ return `Submission ${n}`;
+ }
+
+ switch (frequency) {
+ case "day":
+ return `Day ${n}`;
+ case "week":
+ return `Week ${n}`;
+ case "month":
+ return `Month ${n}`;
+ default:
+ return `Week ${n}`;
+ }
+}
+
+/**
+ * Determine the current active period number (1-indexed) based on
+ * the bounty's startsAt, submissionFrequency, and maxSubmissions.
+ * Returns null if now is before startsAt or after all periods.
+ * For single-submission bounties, always returns 1 (if started).
+ */
+export function getCurrentPeriodNumber({
+ startsAt,
+ endsAt,
+ submissionFrequency,
+ maxSubmissions,
+}: {
+ startsAt: Date;
+ endsAt: Date | null;
+ submissionFrequency: BountySubmissionFrequency | null;
+ maxSubmissions: number;
+}): number | null {
+ const now = new Date();
+ const start = new Date(startsAt);
+
+ if (now < start) {
+ return null;
+ }
+
+ if (maxSubmissions < 2) {
+ const end = endsAt ? new Date(endsAt) : null;
+ return end && now >= end ? null : 1;
+ }
+
+ // all periods open, caller picks
+ if (!submissionFrequency) {
+ return null;
+ }
+
+ for (let i = 0; i < maxSubmissions; i++) {
+ const periodStart = addFrequency({
+ date: start,
+ frequency: submissionFrequency,
+ amount: i,
+ });
+
+ let periodEnd: Date;
+
+ if (i < maxSubmissions - 1) {
+ periodEnd = addFrequency({
+ date: start,
+ frequency: submissionFrequency,
+ amount: i + 1,
+ });
+ } else if (endsAt) {
+ periodEnd = new Date(endsAt);
+ } else {
+ periodEnd = addFrequency({
+ date: start,
+ frequency: submissionFrequency,
+ amount: i + 1,
+ });
+ }
+
+ if (now >= periodStart && now < periodEnd) {
+ return i + 1;
+ }
+ }
+
+ return null;
+}
+
+// Build the list of submission periods, matching submissions by periodNumber.
+export function getSubmissionPeriods<
+ TSubmission extends { periodNumber: number; status: string },
+>({
+ startsAt,
+ endsAt,
+ submissionFrequency,
+ maxSubmissions,
+ submissions,
+}: {
+ startsAt: Date;
+ endsAt: Date | null;
+ submissionFrequency: BountySubmissionFrequency | null;
+ maxSubmissions: number;
+ submissions: TSubmission[];
+}): SubmissionPeriod<TSubmission>[] {
+ const now = new Date();
+ const start = new Date(startsAt);
+ const end = endsAt ? new Date(endsAt) : null;
+
+ // Case 1: Single-submission bounty
+ if (maxSubmissions < 2) {
+ let status: SubmissionPeriodStatus;
+ const submission = submissions.find((s) => s.periodNumber === 1) ?? null;
+
+ if (submission) {
+ status = submission.status as SubmissionPeriodStatus;
+ } else if (now < start) {
+ status = "notOpen";
+ } else {
+ status = "notSubmitted";
+ }
+
+ return [
+ {
+ periodNumber: 1,
+ label: "Submission",
+ startDate: start,
+ endDate: end ?? start,
+ status,
+ submission,
+ },
+ ];
+ }
+
+ // Case 2: Multi-submission WITHOUT frequency — all periods open immediately
+ if (!submissionFrequency) {
+ const periods: SubmissionPeriod<TSubmission>[] = [];
+
+ for (let i = 0; i < maxSubmissions; i++) {
+ const periodNumber = i + 1;
+ const submissionForPeriod =
+ submissions.find((s) => s.periodNumber === periodNumber) ?? null;
+
+ let status: SubmissionPeriodStatus;
+
+ if (submissionForPeriod) {
+ status = submissionForPeriod.status as SubmissionPeriodStatus;
+ } else if (now < start) {
+ status = "notOpen";
+ } else {
+ status = "notSubmitted";
+ }
+
+ periods.push({
+ periodNumber,
+ label: getPeriodLabel(null, i),
+ startDate: start,
+ endDate: end ?? start,
+ status,
+ submission: submissionForPeriod,
+ });
+ }
+
+ return periods;
+ }
+
+ // Case 3: Multi-submission WITH frequency — time-gated periods
+ // All periods share the same end date (bounty end) so partners can submit
+ // for any period up until the final deadline.
+ const periods: SubmissionPeriod<TSubmission>[] = [];
+ const periodEndDate =
+ end ??
+ addFrequency({
+ date: start,
+ frequency: submissionFrequency,
+ amount: maxSubmissions,
+ });
+
+ for (let i = 0; i < maxSubmissions; i++) {
+ const periodNumber = i + 1;
+ const startDate = addFrequency({
+ date: start,
+ frequency: submissionFrequency,
+ amount: i,
+ });
+ const endDate = periodEndDate;
+
+ const submissionForPeriod =
+ submissions.find((s) => s.periodNumber === periodNumber) ?? null;
+
+ let status: SubmissionPeriodStatus;
+
+ if (submissionForPeriod) {
+ status = submissionForPeriod.status as SubmissionPeriodStatus;
+ } else if (now < startDate) {
+ status = "notOpen";
+ } else {
+ status = "notSubmitted";
+ }
+
+ periods.push({
+ periodNumber,
+ label: getPeriodLabel(submissionFrequency, i),
+ startDate,
+ endDate,
+ status,
+ submission: submissionForPeriod,
+ });
+ }
+
+ return periods;
+}
diff --git a/apps/web/lib/bounty/rewards.ts b/apps/web/lib/bounty/rewards.ts
new file mode 100644
index 0000000000..77d8dd7d1c
--- /dev/null
+++ b/apps/web/lib/bounty/rewards.ts
@@ -0,0 +1,156 @@
+import { Prisma } from "@dub/prisma/client";
+import { currencyFormatter } from "@dub/utils";
+import { BountyProps, BountySubmissionProps } from "../types";
+import { resolveBountyDetails } from "./utils";
+
+interface BountyInfoInput {
+ submissionRequirements?: Prisma.JsonValue | undefined | null;
+ rewardAmount?: number | undefined | null;
+}
+
+export interface SocialMetricsRewardTier {
+ threshold: number;
+ rewardAmount: number;
+ status: "met" | "unmet";
+}
+
+export function getSocialMetricsRewardTiers({
+ bounty,
+ submission,
+}: {
+ bounty: BountyInfoInput | undefined | null;
+ submission: Pick<BountySubmissionProps, "socialMetricCount">;
+}): SocialMetricsRewardTier[] {
+ const bountyInfo = resolveBountyDetails(bounty);
+ const socialMetrics = bountyInfo?.socialMetrics;
+ const rewardAmount = bounty?.rewardAmount ?? 0;
+ const socialMetricCount = submission.socialMetricCount ?? 0;
+
+ if (!socialMetrics?.metric || !socialMetrics.minCount || rewardAmount <= 0) {
+ return [];
+ }
+
+ const { minCount, incrementalBonus } = socialMetrics;
+
+ // Base tier
+ const tiers: SocialMetricsRewardTier[] = [
+ {
+ threshold: minCount,
+ rewardAmount,
+ status: socialMetricCount >= minCount ? "met" : "unmet",
+ },
+ ];
+
+ if (tiers[0].status === "unmet") {
+ return tiers;
+ }
+
+ // Incremental bonus tiers
+ if (incrementalBonus) {
+ const { incrementCount, bonusPerIncrement, maxCount } = incrementalBonus;
+
+ const hasValidIncrementalBonus =
+ incrementCount != null &&
+ bonusPerIncrement != null &&
+ maxCount != null &&
+ incrementCount > 0;
+
+ if (hasValidIncrementalBonus) {
+ for (
+ let t = minCount + incrementCount;
+ t <= maxCount;
+ t += incrementCount
+ ) {
+ const status = socialMetricCount >= t ? "met" : "unmet";
+
+ tiers.push({
+ threshold: t,
+ rewardAmount: bonusPerIncrement,
+ status,
+ });
+
+ // Stop after first unmet
+ if (status === "unmet") {
+ break;
+ }
+ }
+ }
+ }
+
+ return tiers;
+}
+
+export function calculateSocialMetricsRewardAmount({
+ bounty,
+ submission,
+}: {
+ bounty: BountyInfoInput | undefined | null;
+ submission: Pick<BountySubmissionProps, "socialMetricCount">;
+}) {
+ const tiers = getSocialMetricsRewardTiers({ bounty, submission });
+
+ if (tiers.length === 0 || submission.socialMetricCount == null) {
+ return null;
+ }
+
+ return tiers
+ .filter((tier) => tier.status === "met")
+ .reduce((sum, tier) => sum + tier.rewardAmount, 0);
+}
+
+export function getBountyRewardDescription(
+ bounty: Pick<
+ BountyProps,
+ "rewardAmount" | "rewardDescription" | "submissionRequirements"
+ >,
+) {
+ const bountyInfo = resolveBountyDetails({
+ rewardAmount: bounty.rewardAmount,
+ submissionRequirements: bounty.submissionRequirements,
+ });
+
+ const socialMetrics = bountyInfo?.socialMetrics;
+ const incrementalBonus = socialMetrics?.incrementalBonus;
+
+ if (
+ incrementalBonus?.incrementCount &&
+ incrementalBonus?.bonusPerIncrement != null &&
+ incrementalBonus?.maxCount
+ ) {
+ const baseRewardCents = bounty.rewardAmount ?? 0;
+ const minCount = socialMetrics?.minCount ?? 0;
+
+ const incrementalCapCents =
+ Math.max(
+ 0,
+ Math.floor(
+ (incrementalBonus.maxCount - minCount) /
+ incrementalBonus.incrementCount,
+ ),
+ ) * incrementalBonus.bonusPerIncrement;
+
+ const earningsCapCents = baseRewardCents + incrementalCapCents;
+
+ if (earningsCapCents > 0) {
+ const formattedEarningsCap = currencyFormatter(earningsCapCents, {
+ trailingZeroDisplay: "stripIfInteger",
+ });
+
+ return `Earn up to ${formattedEarningsCap}`;
+ }
+ }
+
+ if (bounty.rewardAmount) {
+ const formattedAmount = currencyFormatter(bounty.rewardAmount, {
+ trailingZeroDisplay: "stripIfInteger",
+ });
+
+ return `Earn ${formattedAmount}`;
+ }
+
+ if (bounty.rewardDescription) {
+ return bounty.rewardDescription;
+ }
+
+ return "";
+}
diff --git a/apps/web/lib/bounty/social-content.ts b/apps/web/lib/bounty/social-content.ts
new file mode 100644
index 0000000000..347e31e2b7
--- /dev/null
+++ b/apps/web/lib/bounty/social-content.ts
@@ -0,0 +1,63 @@
+import { PlatformType } from "@dub/prisma/client";
+
+export const BOUNTY_SOCIAL_PLATFORMS = [
+ {
+ value: "youtube",
+ label: "YouTube",
+ postType: "video",
+ metrics: ["views", "likes"],
+ placeholder: "https://www.youtube.com/watch?v=",
+ },
+ {
+ value: "tiktok",
+ label: "TikTok",
+ postType: "video",
+ metrics: ["views", "likes"],
+ placeholder: "https://www.tiktok.com/@username/video/",
+ },
+ {
+ value: "instagram",
+ label: "Instagram",
+ postType: "photo",
+ metrics: ["likes", "views"],
+ placeholder: "https://www.instagram.com/username/reel/",
+ },
+ {
+ value: "twitter",
+ label: "X/Twitter",
+ postType: "tweet",
+ metrics: ["likes", "views"],
+ placeholder: "https://x.com/username/status/",
+ },
+] as const;
+
+export const BOUNTY_SOCIAL_PLATFORM_VALUES = BOUNTY_SOCIAL_PLATFORMS.map(
+ (p) => p.value,
+);
+
+export const BOUNTY_SOCIAL_PLATFORM_METRICS = BOUNTY_SOCIAL_PLATFORMS.map(
+ (p) => p.metrics,
+).flat();
+
+export const BOUNTY_SOCIAL_PLATFORM_METRICS_MAP = Object.fromEntries(
+ BOUNTY_SOCIAL_PLATFORMS.map((p) => [
+ p.value,
+ p.metrics.map((m) => ({
+ value: m,
+ label: m,
+ })),
+ ]),
+);
+
+export const SOCIAL_URL_HOST_TO_PLATFORM: Record<string, PlatformType> = {
+ "youtube.com": "youtube",
+ "m.youtube.com": "youtube",
+ "youtu.be": "youtube",
+ "tiktok.com": "tiktok",
+ "m.tiktok.com": "tiktok",
+ "vm.tiktok.com": "tiktok",
+ "instagram.com": "instagram",
+ "m.instagram.com": "instagram",
+ "twitter.com": "twitter",
+ "x.com": "twitter",
+};
diff --git a/apps/web/lib/bounty/bounty-submission-status-badges.ts b/apps/web/lib/bounty/submission-status.ts
similarity index 71%
rename from apps/web/lib/bounty/bounty-submission-status-badges.ts
rename to apps/web/lib/bounty/submission-status.ts
index 66ae0a58eb..9b5144af9d 100644
--- a/apps/web/lib/bounty/bounty-submission-status-badges.ts
+++ b/apps/web/lib/bounty/submission-status.ts
@@ -1,11 +1,25 @@
import {
CircleCheck,
+ CircleDotted,
CircleHalfDottedCheck,
CircleHalfDottedClock,
CircleXmark,
+ Lock,
} from "@dub/ui/icons";
export const BOUNTY_SUBMISSION_STATUS_BADGES = {
+ notSubmitted: {
+ label: "Not submitted",
+ variant: "neutral",
+ icon: CircleDotted,
+ iconClassName: "text-neutral-700",
+ },
+ notOpen: {
+ label: "Not open",
+ variant: "neutral",
+ icon: Lock,
+ iconClassName: "text-neutral-700",
+ },
draft: {
label: "In progress",
variant: "pending",
diff --git a/apps/web/lib/bounty/utils.ts b/apps/web/lib/bounty/utils.ts
index 9385b2530b..e33714451a 100644
--- a/apps/web/lib/bounty/utils.ts
+++ b/apps/web/lib/bounty/utils.ts
@@ -1,204 +1,6 @@
-import {
- BountySubmissionFrequency,
- PlatformType,
- Prisma,
-} from "@dub/prisma/client";
-import { currencyFormatter, isValidUrl, nFormatter } from "@dub/utils";
-import { addDays, addMonths, addWeeks } from "date-fns";
-import {
- BountySocialPlatform,
- BountySubmissionProps,
- PartnerBountyProps,
-} from "../types";
+import { Prisma } from "@dub/prisma/client";
import { bountySocialContentRequirementsSchema } from "../zod/schemas/bounties";
-import { BOUNTY_SOCIAL_PLATFORMS } from "./constants";
-
-export function getNextBountySubmissionEligibleAt({
- submissionFrequency,
- lastSubmissionAt,
-}: {
- submissionFrequency: BountySubmissionFrequency;
- lastSubmissionAt: Date;
-}): Date {
- switch (submissionFrequency) {
- case "day":
- return addDays(lastSubmissionAt, 1);
- case "week":
- return addWeeks(lastSubmissionAt, 1);
- case "month":
- return addMonths(lastSubmissionAt, 1);
- default:
- throw new Error("Invalid submission frequency");
- }
-}
-
-const SOCIAL_URL_HOST_TO_PLATFORM: Record<string, PlatformType> = {
- "youtube.com": "youtube",
- "m.youtube.com": "youtube",
- "youtu.be": "youtube",
- "tiktok.com": "tiktok",
- "m.tiktok.com": "tiktok",
- "vm.tiktok.com": "tiktok",
- "instagram.com": "instagram",
- "m.instagram.com": "instagram",
- "twitter.com": "twitter",
- "x.com": "twitter",
-};
-
-export function getPlatformFromSocialUrl(url: string): PlatformType | null {
- const trimmed = url?.trim();
-
- if (!trimmed || !isValidUrl(trimmed)) {
- return null;
- }
-
- try {
- const parsed = new URL(trimmed);
- const host = parsed.hostname.replace(/^www\./, "");
-
- return SOCIAL_URL_HOST_TO_PLATFORM[host] ?? null;
- } catch {
- return null;
- }
-}
-
-export function getSocialContentEmbedUrl({
- platform,
- url,
-}: {
- platform: BountySocialPlatform;
- url: string;
-}) {
- try {
- const parsed = new URL(url);
- const host = parsed.hostname.replace(/^www\./, "");
-
- if (platform === "youtube") {
- if (host === "youtu.be") {
- const id = parsed.pathname.slice(1).split("?")[0];
- return id ? `https://www.youtube.com/embed/${id}` : null;
- }
-
- if (host === "youtube.com" || host === "m.youtube.com") {
- const v = parsed.searchParams.get("v");
-
- if (v) {
- return `https://www.youtube.com/embed/${v}`;
- }
-
- const shortsMatch = parsed.pathname.match(/\/shorts\/([^/?#]+)/);
-
- if (shortsMatch?.[1]) {
- return `https://www.youtube.com/embed/${shortsMatch[1]}`;
- }
-
- return null;
- }
- }
-
- if (platform === "instagram") {
- if (host === "instagram.com" || host === "m.instagram.com") {
- const pathMatch =
- parsed.pathname.match(/\/p\/([^/]+)/) ??
- parsed.pathname.match(/\/reel\/([^/]+)/);
- const shortcode = pathMatch?.[1];
-
- if (!shortcode) {
- return null;
- }
-
- const isReel = parsed.pathname.includes("/reel/");
-
- return isReel
- ? `https://www.instagram.com/reel/${shortcode}/embed/`
- : `https://www.instagram.com/p/${shortcode}/embed/`;
- }
- }
-
- if (platform === "tiktok") {
- if (
- host === "tiktok.com" ||
- host === "m.tiktok.com" ||
- host === "vm.tiktok.com"
- ) {
- const match = parsed.pathname.match(/\/video\/(\d+)/);
- const videoId = match?.[1];
-
- return videoId ? `https://www.tiktok.com/embed/v2/${videoId}` : null;
- }
- }
-
- if (platform === "twitter") {
- if (host === "twitter.com" || host === "x.com") {
- const statusMatch = parsed.pathname.match(/\/status\/(\d+)/);
- const tweetId = statusMatch?.[1];
- return tweetId
- ? `https://platform.twitter.com/embed/Tweet.html?id=${tweetId}`
- : null;
- }
- }
-
- return null;
- } catch {
- return null;
- }
-}
-
-export function getBountySubmissionRequirementTexts(
- bounty: PartnerBountyProps,
-): string[] {
- const bountyInfo = resolveBountyDetails(bounty);
-
- if (!bountyInfo?.hasSocialMetrics || !bountyInfo.socialPlatform) {
- return [];
- }
-
- return [
- `Submit a ${bountyInfo.socialPlatform.label} link from your connected account`,
- "The content shared is posted after this bounty started",
- ];
-}
-
-export function getBountyRewardCriteriaTexts(
- bounty: PartnerBountyProps | Parameters<typeof resolveBountyDetails>[0],
-): string[] {
- const bountyInfo = resolveBountyDetails(bounty);
-
- if (
- !bountyInfo?.socialMetrics ||
- !bountyInfo.socialPlatform ||
- !bountyInfo.rewardAmount
- ) {
- return [];
- }
-
- const formattedAmount = currencyFormatter(bountyInfo.rewardAmount, {
- trailingZeroDisplay: "stripIfInteger",
- });
-
- const socialPlatform = bountyInfo.socialPlatform;
- const { minCount, metric, incrementalBonus } = bountyInfo.socialMetrics;
-
- const texts: string[] = [
- `Get ${nFormatter(minCount ?? 0, { full: true })} ${metric} on your ${socialPlatform.label} content, earn ${formattedAmount}`,
- ];
-
- if (incrementalBonus) {
- const { incrementCount, bonusPerIncrement, maxCount } = incrementalBonus;
-
- if (incrementCount && bonusPerIncrement && maxCount) {
- const formattedBonus = currencyFormatter(bonusPerIncrement, {
- trailingZeroDisplay: "stripIfInteger",
- });
-
- texts.push(
- `For each additional ${nFormatter(incrementCount, { full: true })} ${metric} on your ${socialPlatform.label} content, earn ${formattedBonus} – up to ${nFormatter(maxCount, { full: true })} ${metric}`,
- );
- }
- }
-
- return texts;
-}
+import { BOUNTY_SOCIAL_PLATFORMS } from "./social-content";
interface BountyInfoInput {
submissionRequirements?: Prisma.JsonValue | undefined | null;
@@ -237,93 +39,3 @@ export function resolveBountyDetails(
hasSocialMetrics: socialMetrics != null,
};
}
-
-export interface SocialMetricsRewardTier {
- threshold: number;
- rewardAmount: number;
- status: "met" | "unmet";
-}
-
-export function getSocialMetricsRewardTiers({
- bounty,
- submission,
-}: {
- bounty: BountyInfoInput | undefined | null;
- submission: Pick<BountySubmissionProps, "socialMetricCount">;
-}): SocialMetricsRewardTier[] {
- const bountyInfo = resolveBountyDetails(bounty);
- const socialMetrics = bountyInfo?.socialMetrics;
- const rewardAmount = bounty?.rewardAmount ?? 0;
- const socialMetricCount = submission.socialMetricCount ?? 0;
-
- if (!socialMetrics?.metric || !socialMetrics.minCount || rewardAmount <= 0) {
- return [];
- }
-
- const { minCount, incrementalBonus } = socialMetrics;
-
- // Base tier
- const tiers: SocialMetricsRewardTier[] = [
- {
- threshold: minCount,
- rewardAmount,
- status: socialMetricCount >= minCount ? "met" : "unmet",
- },
- ];
-
- if (tiers[0].status === "unmet") {
- return tiers;
- }
-
- // Incremental bonus tiers
- if (incrementalBonus) {
- const { incrementCount, bonusPerIncrement, maxCount } = incrementalBonus;
-
- const hasValidIncrementalBonus =
- incrementCount != null &&
- bonusPerIncrement != null &&
- maxCount != null &&
- incrementCount > 0;
-
- if (hasValidIncrementalBonus) {
- for (
- let t = minCount + incrementCount;
- t <= maxCount;
- t += incrementCount
- ) {
- const status = socialMetricCount >= t ? "met" : "unmet";
-
- tiers.push({
- threshold: t,
- rewardAmount: bonusPerIncrement,
- status,
- });
-
- // Stop after first unmet
- if (status === "unmet") {
- break;
- }
- }
- }
- }
-
- return tiers;
-}
-
-export function calculateSocialMetricsRewardAmount({
- bounty,
- submission,
-}: {
- bounty: BountyInfoInput | undefined | null;
- submission: Pick<BountySubmissionProps, "socialMetricCount">;
-}) {
- const tiers = getSocialMetricsRewardTiers({ bounty, submission });
-
- if (tiers.length === 0 || submission.socialMetricCount == null) {
- return null;
- }
-
- return tiers
- .filter((tier) => tier.status === "met")
- .reduce((sum, tier) => sum + tier.rewardAmount, 0);
-}
diff --git a/apps/web/lib/integrations/slack/transform.ts b/apps/web/lib/integrations/slack/transform.ts
index 24de8d2138..d312a32439 100644
--- a/apps/web/lib/integrations/slack/transform.ts
+++ b/apps/web/lib/integrations/slack/transform.ts
@@ -1,5 +1,5 @@
import { isFirstConversion } from "@/lib/analytics/is-first-conversion";
-import { getBountyRewardDescription } from "@/lib/bounty/get-bounty-reward-description";
+import { getBountyRewardDescription } from "@/lib/bounty/rewards";
import { APP_DOMAIN, COUNTRIES, currencyFormatter, truncate } from "@dub/utils";
import { LinkWebhookEvent } from "dub/models/components";
import * as z from "zod/v4";
@@ -446,6 +446,7 @@ const bountyTemplates = ({
description,
rewardAmount,
rewardDescription,
+ submissionRequirements,
type,
startsAt,
endsAt,
@@ -459,6 +460,7 @@ const bountyTemplates = ({
const formattedReward = getBountyRewardDescription({
rewardAmount,
rewardDescription,
+ submissionRequirements,
});
const hrefToBounty = `${APP_DOMAIN}/program/bounties/${id}`;
diff --git a/apps/web/lib/swr/use-partner-bounty.ts b/apps/web/lib/swr/use-partner-bounty.ts
new file mode 100644
index 0000000000..eed9d10707
--- /dev/null
+++ b/apps/web/lib/swr/use-partner-bounty.ts
@@ -0,0 +1,38 @@
+import { fetcher } from "@dub/utils";
+import { useParams } from "next/navigation";
+import useSWR from "swr";
+import { PartnerBountyProps } from "../types";
+
+export default function usePartnerBounty({
+ bountyId,
+ enabled = true,
+}: {
+ bountyId?: string;
+ enabled?: boolean;
+} = {}) {
+ const params = useParams<{ programSlug: string; bountyId: string }>();
+ const programSlug = params?.programSlug;
+ const bountyIdParam = bountyId ?? params?.bountyId;
+
+ const {
+ data: bounty,
+ isLoading,
+ error,
+ } = useSWR<PartnerBountyProps>(
+ enabled &&
+ programSlug &&
+ bountyIdParam &&
+ `/api/partner-profile/programs/${programSlug}/bounties/${bountyIdParam}`,
+ fetcher,
+ {
+ dedupingInterval: 60000,
+ keepPreviousData: true,
+ },
+ );
+
+ return {
+ bounty,
+ isLoading,
+ error,
+ };
+}
diff --git a/apps/web/lib/swr/use-partner-program-bounties.ts b/apps/web/lib/swr/use-partner-program-bounties.ts
index 1330eadfb7..631b57bc85 100644
--- a/apps/web/lib/swr/use-partner-program-bounties.ts
+++ b/apps/web/lib/swr/use-partner-program-bounties.ts
@@ -4,7 +4,7 @@ import { useMemo } from "react";
import useSWR from "swr";
import { PartnerBountyProps } from "../types";
-export default function usePartnerProgramBounties({
+export function usePartnerProgramBounties({
enabled = true,
}: {
enabled?: boolean;
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 32670b9df3..e3ffef51e6 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -32,10 +32,8 @@ import {
import * as z from "zod/v4";
import { RESOURCE_COLORS } from "../ui/colors";
import { PAID_TRAFFIC_PLATFORMS } from "./api/fraud/constants";
-import {
- BOUNTY_SOCIAL_PLATFORMS,
- BOUNTY_SUBMISSION_REQUIREMENTS,
-} from "./bounty/constants";
+import { BOUNTY_SUBMISSION_REQUIREMENTS } from "./bounty/constants";
+import { BOUNTY_SOCIAL_PLATFORMS } from "./bounty/social-content";
import {
FOLDER_PERMISSIONS,
FOLDER_WORKSPACE_ACCESS,
diff --git a/apps/web/lib/webhook/sample-events/bounty-created.json b/apps/web/lib/webhook/sample-events/bounty-created.json
index ed16979879..eb772cfae8 100644
--- a/apps/web/lib/webhook/sample-events/bounty-created.json
+++ b/apps/web/lib/webhook/sample-events/bounty-created.json
@@ -6,6 +6,8 @@
"startsAt": "2025-08-01T17:34:00.000Z",
"endsAt": "2025-09-01T17:34:00.000Z",
"submissionsOpenAt": null,
+ "submissionFrequency": null,
+ "maxSubmissions": 1,
"rewardAmount": 50000,
"rewardDescription": null,
"submissionRequirements": {
diff --git a/apps/web/lib/webhook/sample-events/bounty-updated.json b/apps/web/lib/webhook/sample-events/bounty-updated.json
index e73fed2e8d..0d5605ac89 100644
--- a/apps/web/lib/webhook/sample-events/bounty-updated.json
+++ b/apps/web/lib/webhook/sample-events/bounty-updated.json
@@ -6,6 +6,8 @@
"startsAt": "2025-08-01T17:34:00.000Z",
"endsAt": "2025-09-01T17:34:00.000Z",
"submissionsOpenAt": null,
+ "submissionFrequency": null,
+ "maxSubmissions": 1,
"rewardAmount": 100000,
"rewardDescription": null,
"submissionRequirements": {
diff --git a/apps/web/lib/zod/schemas/bounties.ts b/apps/web/lib/zod/schemas/bounties.ts
index e21dd35dd4..fff633f196 100644
--- a/apps/web/lib/zod/schemas/bounties.ts
+++ b/apps/web/lib/zod/schemas/bounties.ts
@@ -4,9 +4,12 @@ import {
BOUNTY_MAX_SUBMISSION_FILES,
BOUNTY_MAX_SUBMISSION_REJECTION_NOTE_LENGTH,
BOUNTY_MAX_SUBMISSION_URLS,
+ BOUNTY_MAX_SUBMISSIONS,
+} from "@/lib/bounty/constants";
+import {
BOUNTY_SOCIAL_PLATFORM_METRICS,
BOUNTY_SOCIAL_PLATFORM_VALUES,
-} from "@/lib/bounty/constants";
+} from "@/lib/bounty/social-content";
import {
BountyPerformanceScope,
BountySubmissionFrequency,
@@ -105,7 +108,7 @@ export const createBountySchema = z.object({
.number()
.int()
.min(2, "Total submissions allowed must be at least 2")
- .max(10)
+ .max(BOUNTY_MAX_SUBMISSIONS)
.nullish(),
rewardAmount: z
.number()
@@ -148,8 +151,8 @@ export const BountySchema = z.object({
startsAt: z.date(),
endsAt: z.date().nullable(),
submissionsOpenAt: z.date().nullable(),
- // submissionFrequency: z.enum(BountySubmissionFrequency).nullable(),
- // maxSubmissions: z.number().nullable(),
+ submissionFrequency: z.enum(BountySubmissionFrequency).nullable(),
+ maxSubmissions: z.number(),
rewardAmount: z.number().nullable(),
rewardDescription: z.string().nullable(),
performanceCondition: bountyPerformanceConditionSchema
@@ -227,6 +230,9 @@ export const BountySubmissionSchema = z.object({
.string()
.nullable()
.meta({ description: "The note for rejecting the submission" }),
+ periodNumber: z.number().int().min(1).meta({
+ description: "The period number for this submission (1-indexed)",
+ }),
});
export const BountySubmissionExtendedSchema = BountySubmissionSchema.extend({
@@ -330,4 +336,12 @@ export const createBountySubmissionInputSchema = z.object({
.boolean()
.default(false)
.describe("Whether to create a draft submission or a final submission."),
+ periodNumber: z
+ .number()
+ .int()
+ .min(1)
+ .optional()
+ .describe(
+ "The period number to submit for. Required for multi-submission bounties.",
+ ),
});
diff --git a/apps/web/lib/zod/schemas/partner-profile.ts b/apps/web/lib/zod/schemas/partner-profile.ts
index 60816b3cd2..738f804de9 100644
--- a/apps/web/lib/zod/schemas/partner-profile.ts
+++ b/apps/web/lib/zod/schemas/partner-profile.ts
@@ -147,19 +147,22 @@ export const partnerNotificationTypes = z.enum([
"connectPayoutReminder",
]);
+export const partnerBountySubmissionSchema = BountySubmissionSchema.extend({
+ commission: PartnerEarningsSchema.pick({
+ id: true,
+ earnings: true,
+ status: true,
+ createdAt: true,
+ })
+ .nullable()
+ .default(null),
+});
+
export const PartnerBountySchema = BountySchema.omit({
groups: true,
+ socialMetricsLastSyncedAt: true,
}).extend({
- submission: BountySubmissionSchema.extend({
- commission: PartnerEarningsSchema.pick({
- id: true,
- earnings: true,
- status: true,
- createdAt: true,
- })
- .nullable()
- .default(null),
- }).nullable(),
+ submissions: z.array(partnerBountySubmissionSchema),
performanceCondition: bountyPerformanceConditionSchema
.nullable()
.default(null),
diff --git a/apps/web/tests/bounties/index.test.ts b/apps/web/tests/bounties/index.test.ts
index d6d336a30d..68832e66dc 100644
--- a/apps/web/tests/bounties/index.test.ts
+++ b/apps/web/tests/bounties/index.test.ts
@@ -1,5 +1,5 @@
import { Bounty } from "@dub/prisma/client";
-import { addDays, subDays } from "date-fns";
+import { addDays, addMonths, subDays } from "date-fns";
import { E2E_PARTNER_GROUP } from "tests/utils/resource";
import { describe, expect, onTestFinished, test } from "vitest";
import { IntegrationHarness } from "../utils/integration";
@@ -237,3 +237,324 @@ describe.sequential("/bounties/**", async () => {
});
});
});
+
+describe.sequential(
+ "/bounties - multiple submissions & frequency",
+ async () => {
+ const h = new IntegrationHarness();
+ const { http } = await h.init();
+
+ const bountyStartsAt = new Date(Date.now() + 5 * 60 * 1000);
+ const bountyEndsAt = addMonths(bountyStartsAt, 1);
+
+ const base = {
+ name: "Multi-Submission Bounty",
+ type: "submission",
+ startsAt: bountyStartsAt.toISOString(),
+ endsAt: bountyEndsAt.toISOString(),
+ rewardAmount: 1000,
+ submissionRequirements: { image: { max: 4 } },
+ groupIds: [E2E_PARTNER_GROUP.id],
+ };
+
+ let bountyId = "";
+
+ test("POST /bounties - maxSubmissions persists for submission bounty", async () => {
+ const { status, data: bounty } = await http.post<Bounty>({
+ path: "/bounties",
+ body: { ...base, maxSubmissions: 5 },
+ });
+
+ expect(status).toEqual(200);
+ expect(bounty).toMatchObject({
+ id: expect.any(String),
+ maxSubmissions: 5,
+ submissionFrequency: null,
+ });
+
+ onTestFinished(async () => {
+ await h.deleteBounty(bounty.id);
+ });
+ });
+
+ test("POST /bounties - submissionFrequency 'week' with maxSubmissions", async () => {
+ const { status, data: bounty } = await http.post<Bounty>({
+ path: "/bounties",
+ body: { ...base, maxSubmissions: 4, submissionFrequency: "week" },
+ });
+
+ expect(status).toEqual(200);
+ expect(bounty).toMatchObject({
+ maxSubmissions: 4,
+ submissionFrequency: "week",
+ });
+
+ onTestFinished(async () => {
+ await h.deleteBounty(bounty.id);
+ });
+ });
+
+ test("POST /bounties - submissionFrequency 'month' with maxSubmissions", async () => {
+ const { status, data: bounty } = await http.post<Bounty>({
+ path: "/bounties",
+ body: { ...base, maxSubmissions: 3, submissionFrequency: "month" },
+ });
+
+ expect(status).toEqual(200);
+ expect(bounty).toMatchObject({
+ maxSubmissions: 3,
+ submissionFrequency: "month",
+ });
+
+ bountyId = bounty.id;
+ });
+
+ test("POST /bounties - maxSubmissions and submissionFrequency are ignored for performance bounties", async () => {
+ const { status, data: bounty } = await http.post<Bounty>({
+ path: "/bounties",
+ body: {
+ type: "performance",
+ startsAt: bountyStartsAt.toISOString(),
+ endsAt: null,
+ rewardAmount: 1000,
+ performanceScope: "new",
+ groupIds: [E2E_PARTNER_GROUP.id],
+ performanceCondition: {
+ attribute: "totalLeads",
+ operator: "gte",
+ value: 50,
+ },
+ maxSubmissions: 5,
+ submissionFrequency: "week",
+ },
+ });
+
+ expect(status).toEqual(200);
+ expect(bounty).toMatchObject({
+ maxSubmissions: 1,
+ submissionFrequency: null,
+ });
+
+ onTestFinished(async () => {
+ await h.deleteBounty(bounty.id);
+ });
+ });
+
+ test("POST /bounties - maxSubmissions below minimum (1) is rejected", async () => {
+ const { status } = await http.post({
+ path: "/bounties",
+ body: { ...base, maxSubmissions: 1 },
+ });
+
+ expect(status).toEqual(422);
+ });
+
+ test("POST /bounties - maxSubmissions above maximum (11) is rejected", async () => {
+ const { status } = await http.post({
+ path: "/bounties",
+ body: { ...base, maxSubmissions: 11 },
+ });
+
+ expect(status).toEqual(422);
+ });
+
+ test("POST /bounties - submissionFrequency without maxSubmissions is rejected", async () => {
+ const { status, data } = await http.post({
+ path: "/bounties",
+ body: { ...base, submissionFrequency: "week" },
+ });
+
+ expect(status).toEqual(400);
+ expect(data).toMatchObject({
+ error: {
+ message:
+ "maxSubmissions is required when submissionFrequency is set.",
+ },
+ });
+ });
+
+ test("POST /bounties - submissionFrequency without endsAt is rejected", async () => {
+ const { status, data } = await http.post({
+ path: "/bounties",
+ body: {
+ ...base,
+ endsAt: null,
+ maxSubmissions: 4,
+ submissionFrequency: "week",
+ },
+ });
+
+ expect(status).toEqual(400);
+ expect(data).toMatchObject({
+ error: {
+ message: "An end date is required when submissionFrequency is set.",
+ },
+ });
+ });
+
+ test("POST /bounties - submissionsOpenAt without endsAt is rejected", async () => {
+ const submissionsOpenAt = addDays(bountyStartsAt, 5).toISOString();
+
+ const { status, data } = await http.post({
+ path: "/bounties",
+ body: { ...base, endsAt: null, submissionsOpenAt },
+ });
+
+ expect(status).toEqual(400);
+ expect(data).toMatchObject({
+ error: {
+ message:
+ "An end date is required to determine when the submission window opens.",
+ },
+ });
+ });
+
+ test("POST /bounties - submissionsOpenAt before startsAt is rejected", async () => {
+ const submissionsOpenAt = subDays(bountyStartsAt, 1).toISOString();
+
+ const { status, data } = await http.post({
+ path: "/bounties",
+ body: { ...base, submissionsOpenAt },
+ });
+
+ expect(status).toEqual(400);
+ expect(data).toMatchObject({
+ error: {
+ message:
+ "Bounty submissions open date (submissionsOpenAt) must be on or after start date (startsAt).",
+ },
+ });
+ });
+
+ test("POST /bounties - submissionsOpenAt after endsAt is rejected", async () => {
+ const submissionsOpenAt = addDays(bountyEndsAt, 1).toISOString();
+
+ const { status, data } = await http.post({
+ path: "/bounties",
+ body: { ...base, submissionsOpenAt },
+ });
+
+ expect(status).toEqual(400);
+ expect(data).toMatchObject({
+ error: {
+ message:
+ "Bounty submissions open date (submissionsOpenAt) must be on or before end date (endsAt).",
+ },
+ });
+ });
+
+ test("PATCH /bounties/{bountyId} - update maxSubmissions", async () => {
+ const { status, data: bounty } = await http.patch<Bounty>({
+ path: `/bounties/${bountyId}`,
+ body: { maxSubmissions: 6 },
+ });
+
+ expect(status).toEqual(200);
+ expect(bounty).toMatchObject({ maxSubmissions: 6 });
+ });
+
+ test("PATCH /bounties/{bountyId} - update submissionFrequency", async () => {
+ const { status, data: bounty } = await http.patch<Bounty>({
+ path: `/bounties/${bountyId}`,
+ body: { submissionFrequency: "day" },
+ });
+
+ expect(status).toEqual(200);
+ expect(bounty).toMatchObject({ submissionFrequency: "day" });
+ });
+
+ test("PATCH /bounties/{bountyId} - clear submissionFrequency to null", async () => {
+ const { status, data: bounty } = await http.patch<Bounty>({
+ path: `/bounties/${bountyId}`,
+ body: { submissionFrequency: null },
+ });
+
+ expect(status).toEqual(200);
+ expect(bounty).toMatchObject({ submissionFrequency: null });
+ });
+
+ test("PATCH /bounties/{bountyId} - clear maxSubmissions to null", async () => {
+ const { status, data: bounty } = await http.patch<Bounty>({
+ path: `/bounties/${bountyId}`,
+ body: { maxSubmissions: null },
+ });
+
+ expect(status).toEqual(200);
+ expect(bounty).toMatchObject({ maxSubmissions: 1 });
+ });
+
+ test("PATCH /bounties/{bountyId} - update submissionsOpenAt", async () => {
+ const submissionsOpenAt = addDays(bountyStartsAt, 5).toISOString();
+
+ const { status, data: bounty } = await http.patch<Bounty>({
+ path: `/bounties/${bountyId}`,
+ body: { submissionsOpenAt },
+ });
+
+ expect(status).toEqual(200);
+ expect(bounty).toMatchObject({
+ submissionsOpenAt: expect.any(String),
+ });
+ });
+
+ test("PATCH /bounties/{bountyId} - submissionFrequency requires endsAt on the bounty", async () => {
+ const { status: clearStatus } = await http.patch({
+ path: `/bounties/${bountyId}`,
+ body: { endsAt: null },
+ });
+ expect(clearStatus).toEqual(200);
+
+ const { status, data } = await http.patch({
+ path: `/bounties/${bountyId}`,
+ body: { submissionFrequency: "week", maxSubmissions: 4 },
+ });
+
+ expect(status).toEqual(400);
+ expect(data).toMatchObject({
+ error: {
+ message: "An end date is required when submissionFrequency is set.",
+ },
+ });
+ });
+
+ test("PATCH /bounties/{bountyId} - submissionsOpenAt without endsAt is rejected", async () => {
+ const submissionsOpenAt = addDays(bountyStartsAt, 5).toISOString();
+
+ const { status, data } = await http.patch({
+ path: `/bounties/${bountyId}`,
+ body: { submissionsOpenAt },
+ });
+
+ expect(status).toEqual(400);
+ expect(data).toMatchObject({
+ error: {
+ message:
+ "An end date is required to determine when the submission window opens.",
+ },
+ });
+ });
+
+ test("PATCH /bounties/{bountyId} - maxSubmissions below minimum (1) is rejected", async () => {
+ const { status } = await http.patch({
+ path: `/bounties/${bountyId}`,
+ body: { maxSubmissions: 1 },
+ });
+
+ expect(status).toEqual(422);
+ });
+
+ test("PATCH /bounties/{bountyId} - maxSubmissions above maximum (11) is rejected", async () => {
+ const { status } = await http.patch({
+ path: `/bounties/${bountyId}`,
+ body: { maxSubmissions: 11 },
+ });
+
+ expect(status).toEqual(422);
+ });
+
+ test("DELETE /bounties/{bountyId}", async () => {
+ const { status } = await http.delete({ path: `/bounties/${bountyId}` });
+ expect(status).toEqual(200);
+ });
+ },
+);
diff --git a/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx b/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx
index e11f49c4d2..c696705c84 100644
--- a/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx
+++ b/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx
@@ -1,7 +1,7 @@
"use client";
import usePartnerProfile from "@/lib/swr/use-partner-profile";
-import usePartnerProgramBounties from "@/lib/swr/use-partner-program-bounties";
+import { usePartnerProgramBounties } from "@/lib/swr/use-partner-program-bounties";
import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
import useProgramEnrollmentsCount from "@/lib/swr/use-program-enrollments-count";
import { useProgramMessagesCount } from "@/lib/swr/use-program-messages-count";
diff --git a/apps/web/ui/modals/confirm-approve-bounty-submission-modal.tsx b/apps/web/ui/modals/confirm-approve-bounty-submission-modal.tsx
index c1f874504b..86d93cc821 100644
--- a/apps/web/ui/modals/confirm-approve-bounty-submission-modal.tsx
+++ b/apps/web/ui/modals/confirm-approve-bounty-submission-modal.tsx
@@ -1,10 +1,8 @@
"use client";
import { approveBountySubmissionAction } from "@/lib/actions/partners/approve-bounty-submission";
-import {
- calculateSocialMetricsRewardAmount,
- resolveBountyDetails,
-} from "@/lib/bounty/utils";
+import { calculateSocialMetricsRewardAmount } from "@/lib/bounty/rewards";
+import { resolveBountyDetails } from "@/lib/bounty/utils";
import { mutatePrefix } from "@/lib/swr/mutate";
import useWorkspace from "@/lib/swr/use-workspace";
import { BountyProps, BountySubmissionProps } from "@/lib/types";
diff --git a/apps/web/ui/partners/bounties/bounty-description.tsx b/apps/web/ui/partners/bounties/bounty-description.tsx
index efbabc495f..b4a6e28875 100644
--- a/apps/web/ui/partners/bounties/bounty-description.tsx
+++ b/apps/web/ui/partners/bounties/bounty-description.tsx
@@ -1,90 +1,31 @@
-import {
- getBountyRewardCriteriaTexts,
- getBountySubmissionRequirementTexts,
-} from "@/lib/bounty/utils";
import { PartnerBountyProps } from "@/lib/types";
import { Markdown } from "@/ui/shared/markdown";
-import { Check2, PROSE_STYLES } from "@dub/ui";
+import { PROSE_STYLES } from "@dub/ui";
import { cn } from "@dub/utils";
-export function bountyHasDetails(bounty: PartnerBountyProps): boolean {
- const submissionTexts = getBountySubmissionRequirementTexts(bounty);
- const rewardTexts = getBountyRewardCriteriaTexts(bounty);
- const hasDescription = Boolean(bounty.description?.trim());
- const hasSubmissionRequirements = submissionTexts.length > 0;
- const hasRewardCriteria = rewardTexts.length > 0;
- return hasDescription || hasSubmissionRequirements || hasRewardCriteria;
-}
-
-export function BountyDescription({
- bounty,
- hideHeading = false,
-}: {
- bounty: PartnerBountyProps;
- hideHeading?: boolean;
-}) {
- const submissionTexts = getBountySubmissionRequirementTexts(bounty);
- const rewardTexts = getBountyRewardCriteriaTexts(bounty);
+export function BountyDescription({ bounty }: { bounty: PartnerBountyProps }) {
+ const description = bounty.description?.trim();
- const hasDescription = Boolean(bounty.description?.trim());
- const hasSubmissionRequirements = submissionTexts.length > 0;
- const hasRewardCriteria = rewardTexts.length > 0;
-
- if (!hasDescription && !hasSubmissionRequirements && !hasRewardCriteria) {
+ if (!description) {
return null;
}
return (
- <div className="flex flex-col space-y-3 text-sm">
- {hasDescription && (
- <div>
- {!hideHeading && (
- <span className="text-content-emphasis font-semibold">Details</span>
+ <div>
+ <h3 className="text-content-emphasis text-lg font-semibold">
+ Bounty details
+ </h3>
+
+ <div className="flex flex-col gap-1">
+ <Markdown
+ className={cn(
+ PROSE_STYLES.default,
+ "text-sm font-normal text-neutral-600",
)}
- <Markdown
- className={cn(
- PROSE_STYLES.default,
- "text-content-subtle text-sm font-medium leading-5",
- )}
- >
- {bounty.description!.trim()}
- </Markdown>
- </div>
- )}
-
- {hasSubmissionRequirements && (
- <div>
- <span className="text-content-emphasis font-semibold">
- Submission requirements
- </span>
-
- <div className="text-content-subtle mt-2 text-sm font-medium leading-5">
- {submissionTexts.map((text) => (
- <div className="flex items-start gap-1.5" key={text}>
- <Check2 className="mt-1 size-3 shrink-0 text-green-600" />
- <span>{text}</span>
- </div>
- ))}
- </div>
- </div>
- )}
-
- {hasRewardCriteria && (
- <div>
- <span className="text-content-emphasis font-semibold">
- Reward criteria
- </span>
-
- <div className="text-content-subtle mt-2 text-sm font-medium leading-5">
- {rewardTexts.map((text) => (
- <div className="flex items-start gap-1.5" key={text}>
- <Check2 className="mt-1 size-3 shrink-0 text-green-600" />
- <span>{text}</span>
- </div>
- ))}
- </div>
- </div>
- )}
+ >
+ {description}
+ </Markdown>
+ </div>
</div>
);
}
diff --git a/apps/web/ui/partners/bounties/bounty-performance.tsx b/apps/web/ui/partners/bounties/bounty-performance.tsx
index 66e254ed2f..9c019003df 100644
--- a/apps/web/ui/partners/bounties/bounty-performance.tsx
+++ b/apps/web/ui/partners/bounties/bounty-performance.tsx
@@ -2,102 +2,98 @@ import { isCurrencyAttribute } from "@/lib/api/workflows/utils";
import { PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES } from "@/lib/bounty/api/performance-bounty-scope-attributes";
import { PartnerBountyProps } from "@/lib/types";
import { cn, currencyFormatter, nFormatter } from "@dub/utils";
+import {
+ BountyProgressBarRow,
+ EmphasisNumber,
+} from "./bounty-progress-bar-row";
-type PerformanceDisplay = {
- value: number;
- target: number;
- formattedValue: string;
- formattedTarget: string;
- metricLabel: string;
-};
-
-function getPerformanceDisplay(
- bounty: PartnerBountyProps,
-): PerformanceDisplay | null {
+export function PerformanceBountyProgress({
+ bounty,
+ labelClassName,
+ wrapperClassName,
+}: {
+ bounty: PartnerBountyProps;
+ labelClassName?: string;
+ wrapperClassName?: string;
+}) {
const performanceCondition = bounty.performanceCondition;
- const socialMetrics = bounty.submissionRequirements?.socialMetrics;
-
- if (performanceCondition) {
- const attribute = performanceCondition.attribute;
- const target = performanceCondition.value;
- const value = bounty.submission?.performanceCount ?? 0;
- const isCurrency = isCurrencyAttribute(attribute);
- return {
- value,
- target,
- formattedValue:
- value === undefined
- ? "-"
- : isCurrency
- ? currencyFormatter(value, {
- trailingZeroDisplay: "stripIfInteger",
- })
- : nFormatter(value, { full: true }),
- formattedTarget: isCurrency
- ? currencyFormatter(target, { trailingZeroDisplay: "stripIfInteger" })
- : nFormatter(target, { full: true }),
- metricLabel:
- PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES[
- performanceCondition.attribute
- ].toLowerCase(),
- };
+ if (!performanceCondition) {
+ return null;
}
- if (socialMetrics?.metric && socialMetrics.minCount != null) {
- const target = socialMetrics.minCount;
- const value = bounty.submission?.socialMetricCount ?? 0;
+ const { attribute } = performanceCondition;
- return {
- value,
- target,
- formattedValue: nFormatter(value, { full: true }),
- formattedTarget: nFormatter(target, { full: true }),
- metricLabel: socialMetrics.metric.toLowerCase(),
- };
- }
+ // Current value
+ const value = bounty.submissions?.[0]?.performanceCount ?? 0;
+ const formattedValue = isCurrencyAttribute(attribute)
+ ? currencyFormatter(value, { trailingZeroDisplay: "stripIfInteger" })
+ : nFormatter(value, { full: true });
+
+ // Target value
+ const target = performanceCondition.value;
+ const formattedTarget = isCurrencyAttribute(attribute)
+ ? currencyFormatter(target, { trailingZeroDisplay: "stripIfInteger" })
+ : nFormatter(target, { full: true });
+
+ const metricLabel =
+ PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES[attribute].toLowerCase();
- return null;
+ const percent =
+ target > 0 ? Math.min(Math.max(value / target, 0), 1) * 100 : 0;
+
+ return (
+ <BountyProgressBarRow
+ progress={percent}
+ labelClassName={labelClassName}
+ wrapperClassName={wrapperClassName}
+ >
+ <EmphasisNumber>{formattedValue}</EmphasisNumber> of{" "}
+ <EmphasisNumber>{formattedTarget}</EmphasisNumber> {metricLabel} generated
+ </BountyProgressBarRow>
+ );
}
-export function BountyPerformance({ bounty }: { bounty: PartnerBountyProps }) {
- const display = getPerformanceDisplay(bounty);
+export function SubmissionBountyProgress({
+ bounty,
+ labelClassName,
+ wrapperClassName,
+ className,
+}: {
+ bounty: PartnerBountyProps;
+ labelClassName?: string;
+ wrapperClassName?: string;
+ className?: string;
+}) {
+ const submittedCount = bounty.submissions.filter(
+ ({ status }) => status !== "draft",
+ ).length;
- if (!display) {
- return null;
- }
+ const approvedCount = bounty.submissions.filter(
+ ({ status }) => status === "approved",
+ ).length;
- const { value, target, formattedValue, formattedTarget, metricLabel } =
- display;
- const expiredBounty =
- bounty.endsAt && new Date(bounty.endsAt) < new Date() ? true : false;
+ const maxSubmissions = bounty.maxSubmissions || 1;
+ const submittedPercent = (submittedCount / maxSubmissions) * 100;
+ const approvedPercent = (approvedCount / maxSubmissions) * 100;
return (
- <div className="flex flex-col gap-2">
- <div className="h-1.5 w-full overflow-hidden rounded-full bg-neutral-200">
- {value > 0 && target > 0 && (
- <div
- style={{
- width: Math.min(Math.max(value / target, 0), 1) * 100 + "%",
- }}
- className={cn(
- "h-full rounded-full bg-orange-600",
- expiredBounty && "bg-neutral-400",
- )}
- />
- )}
- </div>
- <span className="text-content-default text-xs font-medium">
- <strong className="text-content-emphasis font-semibold">
- {formattedValue}
- </strong>{" "}
- of{" "}
- <strong className="text-content-emphasis font-semibold">
- {formattedTarget}
- </strong>{" "}
- {metricLabel}
- {bounty.type === "performance" ? " generated" : ""}
- </span>
+ <div className={cn("flex flex-col gap-4 sm:flex-row", className)}>
+ <BountyProgressBarRow
+ progress={submittedPercent}
+ labelClassName={labelClassName}
+ wrapperClassName={wrapperClassName}
+ >
+ <EmphasisNumber>{submittedCount}</EmphasisNumber> of{" "}
+ <EmphasisNumber>{maxSubmissions}</EmphasisNumber> submitted
+ </BountyProgressBarRow>
+ <BountyProgressBarRow
+ progress={approvedPercent}
+ labelClassName={labelClassName}
+ wrapperClassName={wrapperClassName}
+ >
+ <EmphasisNumber>{approvedCount}</EmphasisNumber> approved
+ </BountyProgressBarRow>
</div>
);
}
diff --git a/apps/web/ui/partners/bounties/bounty-platform-icons.ts b/apps/web/ui/partners/bounties/bounty-platform-icons.ts
new file mode 100644
index 0000000000..f165b9dc56
--- /dev/null
+++ b/apps/web/ui/partners/bounties/bounty-platform-icons.ts
@@ -0,0 +1,13 @@
+import { BountySocialPlatform } from "@/lib/types";
+import { Instagram, TikTok, Twitter, YouTube } from "@dub/ui";
+import { ComponentType } from "react";
+
+export const PLATFORM_ICONS: Record<
+ BountySocialPlatform,
+ ComponentType<{ className?: string }>
+> = {
+ youtube: YouTube,
+ tiktok: TikTok,
+ instagram: Instagram,
+ twitter: Twitter,
+};
diff --git a/apps/web/ui/partners/bounties/bounty-progress-bar-row.tsx b/apps/web/ui/partners/bounties/bounty-progress-bar-row.tsx
new file mode 100644
index 0000000000..9151f7f1ba
--- /dev/null
+++ b/apps/web/ui/partners/bounties/bounty-progress-bar-row.tsx
@@ -0,0 +1,50 @@
+import { cn } from "@dub/utils";
+import { ReactNode } from "react";
+
+export function EmphasisNumber({ children }: { children: ReactNode }) {
+ return (
+ <span className="text-content-emphasis font-semibold">{children}</span>
+ );
+}
+
+export function BountyProgressBarRow({
+ progress,
+ children,
+ labelClassName,
+ wrapperClassName,
+}: {
+ progress: number;
+ children: ReactNode;
+ labelClassName?: string;
+ wrapperClassName?: string;
+}) {
+ const percent = Math.min(Math.max(progress, 0), 100);
+ const isComplete = percent >= 100;
+
+ return (
+ <div
+ className={cn(
+ "flex min-w-0 flex-1 flex-col",
+ wrapperClassName ?? "gap-2",
+ )}
+ >
+ <div className="h-1 w-full overflow-hidden rounded-full bg-neutral-200">
+ <div
+ className={cn(
+ "h-full rounded-full",
+ isComplete ? "bg-green-600" : "bg-amber-600",
+ )}
+ style={{ width: `${percent}%` }}
+ />
+ </div>
+ <p
+ className={cn(
+ "text-content-subtle text-xs font-medium",
+ labelClassName,
+ )}
+ >
+ {children}
+ </p>
+ </div>
+ );
+}
diff --git a/apps/web/ui/partners/bounties/bounty-reward-criteria.tsx b/apps/web/ui/partners/bounties/bounty-reward-criteria.tsx
new file mode 100644
index 0000000000..94c2dd38b3
--- /dev/null
+++ b/apps/web/ui/partners/bounties/bounty-reward-criteria.tsx
@@ -0,0 +1,74 @@
+import { resolveBountyDetails } from "@/lib/bounty/utils";
+import { PartnerBountyProps } from "@/lib/types";
+import { Check2 } from "@dub/ui";
+import { currencyFormatter, nFormatter } from "@dub/utils";
+
+export function getBountyRewardCriteria(
+ bounty: PartnerBountyProps | Parameters<typeof resolveBountyDetails>[0],
+) {
+ const bountyInfo = resolveBountyDetails(bounty);
+
+ if (
+ !bountyInfo?.socialMetrics ||
+ !bountyInfo.socialPlatform ||
+ !bountyInfo.rewardAmount
+ ) {
+ return [];
+ }
+
+ const formattedAmount = currencyFormatter(bountyInfo.rewardAmount, {
+ trailingZeroDisplay: "stripIfInteger",
+ });
+
+ const socialPlatform = bountyInfo.socialPlatform;
+ const { minCount, metric, incrementalBonus } = bountyInfo.socialMetrics;
+
+ const texts: string[] = [
+ `Get ${nFormatter(minCount ?? 0, { full: true })} ${metric} on your ${socialPlatform.label} content, earn ${formattedAmount}`,
+ ];
+
+ if (incrementalBonus) {
+ const { incrementCount, bonusPerIncrement, maxCount } = incrementalBonus;
+
+ if (incrementCount && bonusPerIncrement && maxCount) {
+ const formattedBonus = currencyFormatter(bonusPerIncrement, {
+ trailingZeroDisplay: "stripIfInteger",
+ });
+
+ texts.push(
+ `For each additional ${nFormatter(incrementCount, { full: true })} ${metric} on your ${socialPlatform.label} content, earn ${formattedBonus} – up to ${nFormatter(maxCount, { full: true })} ${metric}`,
+ );
+ }
+ }
+
+ return texts;
+}
+
+export function BountyRewardCriteria({
+ bounty,
+}: {
+ bounty: PartnerBountyProps;
+}) {
+ const rewardTexts = getBountyRewardCriteria(bounty);
+
+ if (rewardTexts.length === 0) {
+ return null;
+ }
+
+ return (
+ <div>
+ <h3 className="text-content-emphasis text-lg font-semibold">
+ Reward criteria
+ </h3>
+
+ <div className="mt-2 flex flex-col gap-1">
+ {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>
+ </div>
+ ))}
+ </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 d4032b9c7b..9222f2c1e8 100644
--- a/apps/web/ui/partners/bounties/bounty-reward-description.tsx
+++ b/apps/web/ui/partners/bounties/bounty-reward-description.tsx
@@ -1,4 +1,4 @@
-import { getBountyRewardDescription } from "@/lib/bounty/get-bounty-reward-description";
+import { getBountyRewardDescription } from "@/lib/bounty/rewards";
import { BountyProps } from "@/lib/types";
import { Gift } from "@dub/ui";
import { cn } from "@dub/utils";
diff --git a/apps/web/ui/partners/bounties/bounty-social-content-preview.tsx b/apps/web/ui/partners/bounties/bounty-social-content-preview.tsx
index ab087340f9..c4af7c0757 100644
--- a/apps/web/ui/partners/bounties/bounty-social-content-preview.tsx
+++ b/apps/web/ui/partners/bounties/bounty-social-content-preview.tsx
@@ -1,9 +1,6 @@
"use client";
-import {
- getSocialContentEmbedUrl,
- resolveBountyDetails,
-} from "@/lib/bounty/utils";
+import { resolveBountyDetails } from "@/lib/bounty/utils";
import {
BountySocialPlatform,
BountySubmissionProps,
@@ -11,19 +8,106 @@ import {
} from "@/lib/types";
import { cn } from "@dub/utils";
import { useState } from "react";
+import { PLATFORM_ICONS } from "./bounty-platform-icons";
interface BountySocialContentPreviewProps {
bounty: Pick<PartnerBountyProps, "id" | "submissionRequirements">;
submission: Pick<BountySubmissionProps, "urls"> | null | undefined;
}
+interface GetSocialContentEmbedUrlParams {
+ platform: BountySocialPlatform;
+ url: string;
+}
+
+interface GetSocialContentEmbedAspectRatioParams {
+ platform: BountySocialPlatform;
+ url: string;
+}
+
+function getSocialContentEmbedUrl({
+ platform,
+ url,
+}: GetSocialContentEmbedUrlParams) {
+ try {
+ const parsed = new URL(url);
+ const host = parsed.hostname.replace(/^www\./, "");
+
+ if (platform === "youtube") {
+ if (host === "youtu.be") {
+ const id = parsed.pathname.slice(1).split("?")[0];
+ return id ? `https://www.youtube.com/embed/${id}` : null;
+ }
+
+ if (host === "youtube.com" || host === "m.youtube.com") {
+ const v = parsed.searchParams.get("v");
+
+ if (v) {
+ return `https://www.youtube.com/embed/${v}`;
+ }
+
+ const shortsMatch = parsed.pathname.match(/\/shorts\/([^/?#]+)/);
+
+ if (shortsMatch?.[1]) {
+ return `https://www.youtube.com/embed/${shortsMatch[1]}`;
+ }
+
+ return null;
+ }
+ }
+
+ if (platform === "instagram") {
+ if (host === "instagram.com" || host === "m.instagram.com") {
+ const pathMatch =
+ parsed.pathname.match(/\/p\/([^/]+)/) ??
+ parsed.pathname.match(/\/reel\/([^/]+)/);
+ const shortcode = pathMatch?.[1];
+
+ if (!shortcode) {
+ return null;
+ }
+
+ const isReel = parsed.pathname.includes("/reel/");
+
+ return isReel
+ ? `https://www.instagram.com/reel/${shortcode}/embed/`
+ : `https://www.instagram.com/p/${shortcode}/embed/`;
+ }
+ }
+
+ if (platform === "tiktok") {
+ if (
+ host === "tiktok.com" ||
+ host === "m.tiktok.com" ||
+ host === "vm.tiktok.com"
+ ) {
+ const match = parsed.pathname.match(/\/video\/(\d+)/);
+ const videoId = match?.[1];
+
+ return videoId ? `https://www.tiktok.com/embed/v2/${videoId}` : null;
+ }
+ }
+
+ if (platform === "twitter") {
+ if (host === "twitter.com" || host === "x.com") {
+ const statusMatch = parsed.pathname.match(/\/status\/(\d+)/);
+ const tweetId = statusMatch?.[1];
+ return tweetId
+ ? `https://platform.twitter.com/embed/Tweet.html?id=${tweetId}`
+ : null;
+ }
+ }
+
+ return null;
+ } catch {
+ return null;
+ }
+}
+
function getSocialContentEmbedAspectRatio({
platform,
url,
-}: {
- platform: BountySocialPlatform;
- url: string;
-}): string {
+}: GetSocialContentEmbedAspectRatioParams) {
try {
const parsed = new URL(url);
const pathname = parsed.pathname;
@@ -79,11 +163,30 @@ export function BountySocialContentPreview({
url,
});
+ const PlatformIcon = PLATFORM_ICONS[platform.value];
+
return (
- <div className="overflow-hidden rounded-xl border border-neutral-200 bg-white p-2">
+ <div className="flex flex-col gap-2 rounded-xl border border-neutral-200 bg-white p-2">
+ {/* Channel row */}
+ {/* <div className="flex items-center gap-2 px-2 py-1">
+ <div className="flex size-6 shrink-0 items-center justify-center rounded-full bg-neutral-100">
+ <PlatformIcon className="size-3.5" />
+ </div>
+ <div className="min-w-0 flex-1" />
+ <a
+ href={url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="flex h-7 shrink-0 items-center rounded-lg border border-neutral-200 bg-white px-2.5 text-sm font-medium text-neutral-900"
+ >
+ View
+ </a>
+ </div> */}
+
+ {/* Native embed */}
<div
className={cn(
- "relative mx-auto flex max-h-[700px] w-full items-center justify-center overflow-hidden rounded-lg",
+ "relative flex max-h-[700px] w-full items-center justify-center overflow-hidden rounded-md border border-black/10",
aspectClass,
)}
>
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 23788c148c..906c0c6f67 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
@@ -2,9 +2,9 @@
import {
getSocialMetricsRewardTiers,
- resolveBountyDetails,
SocialMetricsRewardTier,
-} from "@/lib/bounty/utils";
+} from "@/lib/bounty/rewards";
+import { resolveBountyDetails } from "@/lib/bounty/utils";
import { BountySubmissionProps, PartnerBountyProps } from "@/lib/types";
import { StatusBadge, Table, useTable } from "@dub/ui";
import { capitalize, currencyFormatter } from "@dub/utils";
@@ -24,14 +24,25 @@ const displayStatusMap = {
label: "In progress",
variant: "pending",
},
+ draft: {
+ label: "Draft",
+ variant: "pending",
+ },
+ rejected: {
+ label: "Rejected",
+ variant: "error",
+ },
};
+interface SubmissionForRewards {
+ socialMetricCount: number | null;
+ commission: { earnings: number } | null;
+ status: BountySubmissionProps["status"];
+}
+
function getDisplayStatus(
tier: SocialMetricsRewardTier,
- submission: Pick<
- BountySubmissionProps,
- "socialMetricCount" | "commission" | "status"
- >,
+ submission: SubmissionForRewards,
) {
if (tier.status === "unmet") {
return "inProgress";
@@ -45,6 +56,14 @@ function getDisplayStatus(
return "approved";
}
+ if (submission.status === "draft") {
+ return "draft";
+ }
+
+ if (submission.status === "rejected") {
+ return "rejected";
+ }
+
return "pending";
}
@@ -57,10 +76,7 @@ export function BountySocialMetricsRewardsTable({
PartnerBountyProps,
"id" | "submissionRequirements" | "rewardAmount"
>;
- submission: Pick<
- BountySubmissionProps,
- "socialMetricCount" | "commission" | "status"
- >;
+ submission: SubmissionForRewards;
titleText?: string;
}) {
const tiers = getSocialMetricsRewardTiers({
@@ -86,7 +102,7 @@ export function BountySocialMetricsRewardsTable({
},
{
id: "reward",
- header: "Reward",
+ header: "Amount",
minSize: 100,
size: 120,
cell: ({ row: { original } }) =>
diff --git a/apps/web/ui/partners/bounties/bounty-status-badge.tsx b/apps/web/ui/partners/bounties/bounty-status-badge.tsx
new file mode 100644
index 0000000000..9e8651916f
--- /dev/null
+++ b/apps/web/ui/partners/bounties/bounty-status-badge.tsx
@@ -0,0 +1,136 @@
+import { PartnerBountyProps } from "@/lib/types";
+import { StatusBadge } from "@dub/ui";
+import { formatDate } from "@dub/utils";
+import { differenceInDays } from "date-fns";
+
+const NEW_BOUNTY_DAYS = 14;
+const EXPIRING_SOON_DAYS = 2;
+
+interface BountyBadgeStateResult {
+ status: "expired" | "expiring_soon" | "completed" | "new";
+ endsAtFormatted: string | null;
+ completedAtFormatted: string | null;
+}
+
+function getBountyBadgeState(
+ bounty: PartnerBountyProps,
+): BountyBadgeStateResult | null {
+ const now = new Date();
+ const endsAt = bounty.endsAt ? new Date(bounty.endsAt) : null;
+ const startsAt = new Date(bounty.startsAt);
+
+ const endsAtFormatted = bounty.endsAt
+ ? formatDate(bounty.endsAt, { month: "short" })
+ : null;
+
+ const isExpired = endsAt !== null && endsAt < now;
+
+ if (isExpired) {
+ return {
+ status: "expired",
+ endsAtFormatted,
+ completedAtFormatted: null,
+ };
+ }
+
+ const daysUntilEnd = endsAt ? differenceInDays(endsAt, now) : null;
+ const isExpiringSoon =
+ endsAt !== null &&
+ daysUntilEnd !== null &&
+ daysUntilEnd >= 0 &&
+ daysUntilEnd <= EXPIRING_SOON_DAYS;
+
+ if (isExpiringSoon) {
+ return {
+ status: "expiring_soon",
+ endsAtFormatted,
+ completedAtFormatted: null,
+ };
+ }
+
+ const isCompleted =
+ bounty.type === "performance"
+ ? (bounty.submissions?.[0]?.performanceCount ?? 0) >=
+ (bounty.performanceCondition?.value ?? 0)
+ : (bounty.submissions?.filter((s) => s.status !== "draft").length ?? 0) >=
+ (bounty.maxSubmissions ?? 1);
+
+ if (isCompleted) {
+ const lastSubmission = bounty.submissions?.[0];
+
+ return {
+ status: "completed",
+ endsAtFormatted,
+ completedAtFormatted: formatDate(lastSubmission?.completedAt ?? now, {
+ month: "short",
+ }),
+ };
+ }
+
+ const daysSinceStart = differenceInDays(now, startsAt);
+ const isNew = daysSinceStart <= NEW_BOUNTY_DAYS;
+
+ if (isNew) {
+ return {
+ status: "new",
+ endsAtFormatted,
+ completedAtFormatted: null,
+ };
+ }
+
+ return null;
+}
+
+export function BountyStatusBadge({ bounty }: { bounty: PartnerBountyProps }) {
+ const state = getBountyBadgeState(bounty);
+
+ if (!state) {
+ return null;
+ }
+
+ const { status, endsAtFormatted, completedAtFormatted } = state;
+
+ return (
+ <div className="absolute left-2 top-2 z-10">
+ {status === "expired" && endsAtFormatted && (
+ <StatusBadge
+ variant="error"
+ icon={null}
+ className="bg-red-100 text-xs font-semibold text-red-700"
+ >
+ Expired {endsAtFormatted}
+ </StatusBadge>
+ )}
+
+ {status === "expiring_soon" && endsAtFormatted && (
+ <StatusBadge
+ variant="warning"
+ icon={null}
+ className="bg-amber-100 text-xs font-semibold text-amber-700"
+ >
+ Expiring soon {endsAtFormatted}
+ </StatusBadge>
+ )}
+
+ {status === "completed" && completedAtFormatted && (
+ <StatusBadge
+ variant="success"
+ icon={null}
+ className="bg-green-100 text-xs font-semibold text-green-700"
+ >
+ Completed {completedAtFormatted}
+ </StatusBadge>
+ )}
+
+ {status === "new" && (
+ <StatusBadge
+ variant="new"
+ icon={null}
+ className="bg-blue-100 text-xs font-semibold text-blue-700"
+ >
+ New
+ </StatusBadge>
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/ui/partners/bounties/bounty-submission-details-sheet.tsx b/apps/web/ui/partners/bounties/bounty-submission-details-sheet.tsx
new file mode 100644
index 0000000000..d0e0528daf
--- /dev/null
+++ b/apps/web/ui/partners/bounties/bounty-submission-details-sheet.tsx
@@ -0,0 +1,500 @@
+"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 } from "@/lib/types";
+import { CommissionStatusBadges } from "@/ui/partners/commission-status-badges";
+import { X } from "@/ui/shared/icons";
+import {
+ Button,
+ CopyButton,
+ Sheet,
+ StatusBadge,
+ Table,
+ TimestampTooltip,
+ useKeyboardShortcut,
+ useTable,
+} from "@dub/ui";
+import { ChevronLeft, ChevronRight } from "@dub/ui/icons";
+import {
+ cn,
+ currencyFormatter,
+ formatDate,
+ formatDateTimeSmart,
+ nFormatter,
+} from "@dub/utils";
+import { formatDistanceToNow } from "date-fns";
+import { Dispatch, Fragment, ReactNode, SetStateAction, useState } from "react";
+import { toast } from "sonner";
+import { PLATFORM_ICONS } from "./bounty-platform-icons";
+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;
+ isOpen: boolean;
+ setIsOpen: Dispatch<SetStateAction<boolean>>;
+ onNext?: () => void;
+ onPrevious?: () => void;
+}
+
+function SocialContentPreview({
+ bounty,
+ submission,
+}: {
+ bounty: PartnerBountyProps;
+ submission: PartnerBountySubmission;
+}) {
+ const bountyInfo = resolveBountyDetails(bounty);
+ const { socialMetrics, socialPlatform } = bountyInfo ?? {};
+
+ const url = submission.urls?.[0] ?? "";
+
+ if (!socialMetrics || !socialPlatform || !url) {
+ return null;
+ }
+
+ const socialMetricCount = submission.socialMetricCount ?? 0;
+ const minCount = socialMetrics.minCount ?? 0;
+ const percent =
+ minCount > 0 ? Math.min((socialMetricCount / minCount) * 100, 100) : 100;
+ const isComplete = percent >= 100;
+
+ const PlatformIcon = PLATFORM_ICONS[socialPlatform.value];
+ const lastSyncedAt = submission.socialMetricsLastSyncedAt;
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center justify-between">
+ <h2 className="text-base font-semibold text-neutral-800">
+ Submitted content
+ </h2>
+ {lastSyncedAt && (
+ <span className="text-xs font-medium text-neutral-400">
+ Last sync{" "}
+ {formatDistanceToNow(new Date(lastSyncedAt), { addSuffix: true })}
+ </span>
+ )}
+ </div>
+
+ <div className="rounded-xl border border-neutral-200 bg-neutral-50">
+ {/* 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={cn(
+ "h-full rounded-full",
+ isComplete ? "bg-green-600" : "bg-amber-600",
+ )}
+ style={{ width: `${percent}%` }}
+ />
+ </div>
+
+ <div className="flex items-center gap-2">
+ <PlatformIcon className="size-4 shrink-0" />
+ <p className="text-sm font-medium text-neutral-600">
+ <EmphasisNumber>
+ {nFormatter(socialMetricCount, { full: true })}
+ </EmphasisNumber>
+ {" of "}
+ <EmphasisNumber>
+ {nFormatter(minCount, { full: true })}
+ </EmphasisNumber>
+ {` ${socialMetrics.metric} generated`}
+ </p>
+ </div>
+ </div>
+
+ <BountySocialContentPreview bounty={bounty} submission={submission} />
+ </div>
+ </div>
+ );
+}
+
+function SubmissionDetailsView({
+ 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-sm font-medium text-neutral-900">{text}</span>
+ );
+
+ const details: { label: string; value: 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="scrollbar-hide flex min-h-0 flex-1 flex-col overflow-y-auto">
+ <div className="flex flex-col gap-5 p-5">
+ <div>
+ <h2 className="text-base font-semibold text-neutral-800">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-sm font-medium text-neutral-500">
+ {label}
+ </span>
+ <div>{value}</div>
+ </Fragment>
+ ))}
+ </div>
+ </div>
+
+ {submission.rejectionNote && (
+ <div className="rounded-lg bg-orange-50 p-4">
+ <p className="whitespace-pre-wrap text-sm leading-6 text-orange-800">
+ {submission.rejectionNote}
+ </p>
+ </div>
+ )}
+
+ <SubmissionRewardTable submission={submission} />
+
+ {bountyInfo?.hasSocialMetrics &&
+ ["draft", "submitted"].includes(submission.status) && (
+ <BountySocialMetricsRewardsTable
+ bounty={bounty}
+ submission={submission}
+ />
+ )}
+
+ <SocialContentPreview bounty={bounty} submission={submission} />
+
+ {Boolean(submission.files?.length) && (
+ <div>
+ <h2 className="text-base font-semibold text-neutral-800">Images</h2>
+ <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 group relative flex size-14 items-center justify-center rounded-md border bg-white"
+ 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>
+ <h2 className="text-base font-semibold text-neutral-800">URLs</h2>
+ <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="block cursor-alias truncate text-sm font-normal text-neutral-800 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="flex size-6 items-center justify-center rounded-full bg-neutral-100 text-xs font-medium text-neutral-600">
+ {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>
+ <h2 className="text-base font-semibold text-neutral-800">
+ Provide any additional details (optional)
+ </h2>
+ <p className="mt-2 whitespace-pre-wrap text-sm text-neutral-600">
+ {submission.description}
+ </p>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function SubmissionRewardTable({
+ submission,
+}: {
+ submission: PartnerBountySubmission;
+}) {
+ const rewards = submission.commission ? [submission.commission] : [];
+
+ const { table, ...tableProps } = useTable({
+ data: rewards,
+ columns: [
+ {
+ id: "amount",
+ header: "Amount",
+ cell: ({ row }) => currencyFormatter(row.original.earnings),
+ },
+ {
+ id: "status",
+ header: "Status",
+ cell: ({ row }) => {
+ const badge = CommissionStatusBadges[row.original.status];
+
+ return badge ? (
+ <span
+ className={cn(
+ "rounded-md px-2 py-0.5 text-xs font-semibold",
+ badge.className,
+ )}
+ >
+ {badge.label}
+ </span>
+ ) : null;
+ },
+ },
+ {
+ id: "date",
+ header: "Date",
+ cell: ({ row }) => (
+ <TimestampTooltip
+ timestamp={row.original.createdAt}
+ side="right"
+ rows={["local", "utc"]}
+ >
+ <span className="hover:text-content-emphasis underline decoration-dotted underline-offset-2">
+ {formatDateTimeSmart(row.original.createdAt)}
+ </span>
+ </TimestampTooltip>
+ ),
+ },
+ ],
+ thClassName: "border-l-transparent",
+ tdClassName: "border-l-transparent",
+ });
+
+ if (rewards.length === 0) {
+ return null;
+ }
+
+ return (
+ <div>
+ <h2 className="text-base font-semibold text-neutral-800">Rewards</h2>
+ <div className="mt-2">
+ <Table
+ {...tableProps}
+ table={table}
+ containerClassName="border-neutral-200"
+ scrollWrapperClassName="min-h-0"
+ className="[&_tbody_tr:last-child_td]:border-b-0"
+ />
+ </div>
+ </div>
+ );
+}
+
+export function BountySubmissionDetailsSheet({
+ bounty,
+ submission,
+ isOpen,
+ setIsOpen,
+ onNext,
+ onPrevious,
+}: BountySubmissionDetailsSheetProps) {
+ const title =
+ bounty.maxSubmissions > 1
+ ? `Submission (${getPeriodLabel(bounty.submissionFrequency, submission.periodNumber - 1)})`
+ : "Submission";
+
+ useKeyboardShortcut(
+ "ArrowRight",
+ () => {
+ if (onNext) onNext();
+ },
+ { sheet: true },
+ );
+
+ useKeyboardShortcut(
+ "ArrowLeft",
+ () => {
+ if (onPrevious) onPrevious();
+ },
+ { sheet: true },
+ );
+
+ return (
+ <Sheet open={isOpen} onOpenChange={setIsOpen}>
+ <div className="relative flex size-full flex-col">
+ <div className="sticky top-0 z-10 flex shrink-0 items-center justify-between border-b border-neutral-200 bg-white px-5 py-4">
+ <Sheet.Title className="text-base font-semibold text-neutral-900">
+ {title}
+ </Sheet.Title>
+ <div className="flex items-center gap-4">
+ {(onNext || onPrevious) && (
+ <div className="flex items-center">
+ <Button
+ type="button"
+ disabled={!onPrevious}
+ onClick={onPrevious}
+ variant="secondary"
+ className="size-9 rounded-l-lg rounded-r-none p-0"
+ icon={<ChevronLeft className="size-3.5" />}
+ />
+ <Button
+ type="button"
+ disabled={!onNext}
+ onClick={onNext}
+ variant="secondary"
+ className="-ml-px size-9 rounded-l-none rounded-r-lg p-0"
+ icon={<ChevronRight className="size-3.5" />}
+ />
+ </div>
+ )}
+ <Sheet.Close asChild>
+ <Button
+ variant="outline"
+ icon={<X className="size-5" />}
+ className="h-auto w-fit p-1"
+ />
+ </Sheet.Close>
+ </div>
+ </div>
+ <SubmissionDetailsView bounty={bounty} submission={submission} />
+ </div>
+ </Sheet>
+ );
+}
+
+export function useBountySubmissionDetailsSheet({
+ bounty,
+}: {
+ bounty: PartnerBountyProps;
+}) {
+ const [isOpen, setIsOpen] = useState(false);
+ const [activePeriodNumber, setActivePeriodNumber] = useState<
+ number | undefined
+ >();
+
+ const submission =
+ bounty.submissions?.find(
+ (s) => s.periodNumber === (activePeriodNumber ?? 1),
+ ) ?? null;
+
+ // Navigable submissions: non-draft, sorted by periodNumber
+ const submittedPeriodNumbers = (bounty.submissions ?? [])
+ .filter((s) => s.status !== "draft")
+ .map((s) => s.periodNumber)
+ .sort((a, b) => a - b);
+
+ const currentIndex = submittedPeriodNumbers.indexOf(activePeriodNumber ?? 1);
+
+ const onPrevious =
+ currentIndex > 0
+ ? () => setActivePeriodNumber(submittedPeriodNumbers[currentIndex - 1])
+ : undefined;
+
+ const onNext =
+ currentIndex < submittedPeriodNumbers.length - 1
+ ? () => setActivePeriodNumber(submittedPeriodNumbers[currentIndex + 1])
+ : undefined;
+
+ return {
+ bountySubmissionDetailsSheet: submission ? (
+ <BountySubmissionDetailsSheet
+ bounty={bounty}
+ submission={submission}
+ isOpen={isOpen}
+ setIsOpen={setIsOpen}
+ onNext={onNext}
+ onPrevious={onPrevious}
+ />
+ ) : null,
+ setShowBountySubmissionDetailsSheet: setIsOpen,
+ setActivePeriodNumber,
+ };
+}
diff --git a/apps/web/ui/partners/bounties/bounty-submission-requirements.tsx b/apps/web/ui/partners/bounties/bounty-submission-requirements.tsx
new file mode 100644
index 0000000000..6d4107a8dc
--- /dev/null
+++ b/apps/web/ui/partners/bounties/bounty-submission-requirements.tsx
@@ -0,0 +1,67 @@
+import { resolveBountyDetails } from "@/lib/bounty/utils";
+import { PartnerBountyProps } from "@/lib/types";
+import { Check2 } from "@dub/ui";
+
+export function getBountySubmissionRequirements(bounty: PartnerBountyProps) {
+ const bountyInfo = resolveBountyDetails(bounty);
+ const requirements: string[] = [];
+
+ const reqs = bounty.submissionRequirements;
+
+ if (reqs?.image) {
+ requirements.push(
+ reqs.image.max
+ ? `Submit up to ${reqs.image.max} image${reqs.image.max === 1 ? "" : "s"}`
+ : "Submit an image",
+ );
+ }
+
+ if (reqs?.url) {
+ requirements.push(
+ reqs.url.max
+ ? `Submit up to ${reqs.url.max} URL${reqs.url.max === 1 ? "" : "s"}`
+ : "Submit a URL",
+ );
+ if (reqs.url.domains?.length) {
+ requirements.push(`URL must be from: ${reqs.url.domains.join(", ")}`);
+ }
+ }
+
+ if (bountyInfo?.hasSocialMetrics && bountyInfo.socialPlatform) {
+ requirements.push(
+ `Submit a ${bountyInfo.socialPlatform.label} link from your connected account`,
+ "The content shared is posted after this bounty started",
+ );
+ }
+
+ return requirements;
+}
+
+export function BountySubmissionRequirements({
+ bounty,
+}: {
+ bounty: PartnerBountyProps;
+}) {
+ const submissionTexts = getBountySubmissionRequirements(bounty);
+
+ if (submissionTexts.length === 0) {
+ return null;
+ }
+
+ return (
+ <div>
+ <h3 className="text-content-emphasis text-lg font-semibold">
+ Submission requirements
+ </h3>
+
+ <div className="mt-2 flex flex-col gap-1">
+ {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>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/ui/partners/bounties/claim-bounty-modal.tsx b/apps/web/ui/partners/bounties/claim-bounty-modal.tsx
deleted file mode 100644
index 6d03baaa34..0000000000
--- a/apps/web/ui/partners/bounties/claim-bounty-modal.tsx
+++ /dev/null
@@ -1,843 +0,0 @@
-import { createBountySubmissionAction } from "@/lib/actions/partners/create-bounty-submission";
-import { uploadBountySubmissionFileAction } from "@/lib/actions/partners/upload-bounty-submission-file";
-import {
- BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH,
- BOUNTY_MAX_SUBMISSION_FILES,
- BOUNTY_MAX_SUBMISSION_URLS,
- REJECT_BOUNTY_SUBMISSION_REASONS,
-} from "@/lib/bounty/constants";
-import { resolveBountyDetails } from "@/lib/bounty/utils";
-import { mutatePrefix } from "@/lib/swr/mutate";
-import usePartnerProfile from "@/lib/swr/use-partner-profile";
-import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
-import { PartnerBountyProps } from "@/lib/types";
-import { useConfirmModal } from "@/ui/modals/confirm-modal";
-import { X } from "@/ui/shared/icons";
-import {
- AnimatedSizeContainer,
- Button,
- Calendar6,
- FileUpload,
- LoadingSpinner,
- Modal,
- StatusBadge,
- Trash,
- buttonVariants,
- useRouterStuff,
-} from "@dub/ui";
-import { cn, formatDate, getPrettyUrl } from "@dub/utils";
-import { isBefore } from "date-fns";
-import Linkify from "linkify-react";
-import { motion } from "motion/react";
-import { useAction } from "next-safe-action/hooks";
-import Link from "next/link";
-import { Dispatch, SetStateAction, useState } from "react";
-import { FormProvider, useForm } from "react-hook-form";
-import ReactTextareaAutosize from "react-textarea-autosize";
-import { toast } from "sonner";
-import { v4 as uuid } from "uuid";
-import { BountyDescription, bountyHasDetails } from "./bounty-description";
-import { BountyPerformance } from "./bounty-performance";
-import { BountyRewardDescription } from "./bounty-reward-description";
-import {
- SocialAccountNotVerifiedWarning,
- SocialContentUrlField,
-} from "./bounty-social-content";
-import { BountyThumbnailImage } from "./bounty-thumbnail-image";
-import {
- ClaimBountyProvider,
- useClaimBountyContext,
-} from "./claim-bounty-context";
-import { CreateBountySubmissionInput } from "./use-claim-bounty-form";
-
-type ClaimBountyModalProps = {
- setShowModal: Dispatch<SetStateAction<boolean>>;
- bounty: PartnerBountyProps;
-};
-
-interface FileInput {
- id: string;
- file?: File;
- url?: string;
- uploading: boolean;
-}
-
-function ClaimBountyModalContent({ bounty }: ClaimBountyModalProps) {
- const { submission } = bounty;
- const { programEnrollment } = useProgramEnrollment();
- const { platformsVerified } = usePartnerProfile();
-
- const [success, setSuccess] = useState(false);
- const [isFormOpen, setIsFormOpen] = useState(false);
- const [isDraft, setIsDraft] = useState<boolean | null>(null);
- const { socialContentVerifying, socialContentRequirementsMet } =
- useClaimBountyContext();
-
- const bountyInfo = resolveBountyDetails(bounty);
- const socialPlatform = bountyInfo?.socialPlatform;
- const isSocialMetricsBounty = bountyInfo?.hasSocialMetrics ?? false;
-
- // Initialize form state with existing draft submission data
- const [description, setDescription] = useState(submission?.description || "");
-
- const [files, setFiles] = useState<FileInput[]>(() => {
- if (submission?.files && submission.files.length > 0) {
- return submission.files.map((file) => ({
- id: uuid(),
- url: file.url,
- uploading: false,
- file: undefined,
- }));
- }
-
- return [];
- });
-
- const initialUrls = (() => {
- if (submission?.urls && submission.urls.length > 0) {
- return socialPlatform
- ? [submission.urls[0] ?? "", ...submission.urls.slice(1)]
- : [...submission.urls];
- }
-
- return [""];
- })();
-
- const claimForm = useForm<CreateBountySubmissionInput>({
- defaultValues: {
- urls: initialUrls,
- },
- });
-
- const { executeAsync: uploadFile } = useAction(
- uploadBountySubmissionFileAction,
- );
-
- const { executeAsync: createSubmission } = useAction(
- createBountySubmissionAction,
- {
- onSuccess: async () => {
- toast.success(isDraft ? "Bounty progress saved." : "Bounty submitted.");
- setSuccess(true);
- await mutatePrefix(
- `/api/partner-profile/programs/${programEnrollment?.program.slug}/bounties`,
- );
- },
- onError: ({ error }) => {
- toast.error(
- error.serverError || "Failed to create submission. Please try again.",
- );
- setIsDraft(null);
- },
- },
- );
-
- // Handle file upload
- const handleUpload = async (file: File) => {
- if (!programEnrollment) return;
-
- setFiles((prev) => [...prev, { id: uuid(), file, uploading: true }]);
-
- const result = await uploadFile({
- programId: programEnrollment.programId,
- bountyId: bounty.id,
- });
-
- if (!result?.data) {
- toast.error("Failed to get signed upload URL.");
- return;
- }
-
- const { signedUrl, destinationUrl } = result.data;
-
- const uploadResponse = await fetch(signedUrl, {
- method: "PUT",
- body: file,
- headers: {
- "Content-Type": file.type,
- "Content-Length": file.size.toString(),
- },
- });
-
- if (!uploadResponse.ok) {
- const result = await uploadResponse.json();
- toast.error(result.error.message || "Failed to upload screenshot.");
- return;
- }
-
- toast.success(`${file.name} uploaded!`);
-
- setFiles((prev) =>
- prev.map((f) =>
- f.file === file ? { ...f, uploading: false, url: destinationUrl } : f,
- ),
- );
- };
-
- const imageRequired = !!bounty.submissionRequirements?.image;
- const urlRequired = !!bounty.submissionRequirements?.url;
- const fileUploading = files.some(({ uploading }) => uploading);
-
- // Get max values from bounty submission requirements, fallback to constants
- const imageMax = bounty.submissionRequirements?.image?.max;
- const maxFiles = imageMax ?? BOUNTY_MAX_SUBMISSION_FILES;
- 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)";
-
- // Get placeholder URL from domain if available
- const placeholderUrl = (() => {
- const firstDomain = bounty.submissionRequirements?.url?.domains?.[0];
- if (!firstDomain) return "https://";
- return `https://${firstDomain}`;
- })();
-
- const hasSubmissionsOpen = bounty.submissionsOpenAt
- ? isBefore(bounty.submissionsOpenAt, new Date())
- : true;
-
- // Confirmation modal for final submission
- const { confirmModal, setShowConfirmModal } = useConfirmModal({
- title: "Confirm submission",
- description: (
- <div className="space-y-2">
- <p>
- Are you sure you want to submit this bounty? Once submitted, you won't
- be able to make any further changes.
- </p>
- {!isSocialMetricsBounty && (
- <p>
- If you need to make changes later, you can save your progress as a
- draft instead.
- </p>
- )}
- </div>
- ),
- confirmText: "Confirm submission",
- onConfirm: () => handleSubmission({ isDraft: false }),
- });
-
- // Function to handle the actual submission
- const handleSubmission = async ({ isDraft }: { isDraft: boolean }) => {
- if (!programEnrollment) return;
-
- setIsDraft(isDraft);
-
- const finalFiles = files
- .filter((f): f is FileInput & { url: string } => !!f.url)
- .map(({ file, url }) => ({
- url,
- fileName: file?.name || "File",
- size: file?.size || 0,
- }));
-
- const formUrls = (claimForm.getValues("urls") ?? []).filter(Boolean);
-
- try {
- if (!isDraft) {
- setShowConfirmModal(false);
- if (imageRequired && finalFiles.length === 0) {
- throw new Error("You must upload at least one image.");
- }
-
- if (socialPlatform && !formUrls[0]?.trim()) {
- throw new Error(`You must provide the ${socialPlatform.label} link.`);
- }
-
- if (urlRequired && formUrls.length === 0) {
- throw new Error("You must provide at least one URL.");
- }
- }
-
- await createSubmission({
- programId: programEnrollment.programId,
- bountyId: bounty.id,
- files: finalFiles,
- urls: formUrls,
- description,
- ...(isDraft && { isDraft }),
- });
- } catch (error) {
- toast.error(
- error instanceof Error
- ? error.message
- : "Failed to create submission. Please try again.",
- );
- setIsDraft(null); // reset submit state on error
- }
- };
-
- return (
- <>
- {confirmModal}
- <FormProvider {...claimForm}>
- <form
- onSubmit={async (e) => {
- e.preventDefault();
- if (!programEnrollment) return;
-
- // Determine which button was clicked
- const submitter = (e.nativeEvent as SubmitEvent)
- .submitter as HTMLButtonElement;
-
- const isDraft =
- submitter?.name === "draft" && !isSocialMetricsBounty;
-
- if (isDraft) {
- // Handle draft save directly
- await handleSubmission({ isDraft: true });
- } else {
- // Show confirmation modal for final submission
- setShowConfirmModal(true);
- }
- }}
- >
- <div className="scrollbar-hide max-h-[calc(100dvh-150px)] overflow-y-auto">
- <div className="flex h-[132px] items-center justify-center bg-neutral-100 py-3">
- <div className="relative size-full">
- <BountyThumbnailImage bounty={bounty} />
- </div>
- </div>
-
- <AnimatedSizeContainer
- height={isFormOpen}
- transition={{ duration: 0.15, ease: "easeInOut" }}
- >
- {success ? (
- <div className="mx-auto flex max-w-sm flex-col items-center gap-1 p-6 text-center max-sm:px-4">
- {isDraft ? (
- <>
- <span className="text-content-emphasis text-base font-semibold">
- Progress saved successfully.
- </span>
- <p className="text-content-subtle text-balance text-sm font-medium">
- You can continue working on your submission later.
- </p>
- </>
- ) : (
- <>
- <span className="text-content-emphasis text-base font-semibold">
- Congratulations! You've successfully submitted your
- bounty.
- </span>
- <p className="text-content-subtle text-balance text-sm font-medium">
- We'll let you know when your bounty has been reviewed.
- </p>
- </>
- )}
- </div>
- ) : (
- <>
- <div className="flex flex-col gap-1 p-6 max-sm:px-4">
- <span className="text-content-emphasis truncate text-sm font-semibold">
- {bounty.name}
- </span>
-
- <div className="text-content-subtle flex items-center gap-2 text-sm font-medium">
- <Calendar6 className="size-3.5" />
- <span>
- {bounty.endsAt ? (
- <>
- Ends {formatDate(bounty.endsAt, { month: "short" })}
- </>
- ) : (
- "No end date"
- )}
- </span>
- </div>
-
- <BountyRewardDescription
- bounty={bounty}
- className="font-medium"
- />
-
- {submission ? (
- <div className="grid gap-2">
- <div className="flex items-center gap-2">
- {submission.status === "approved" && (
- <Link
- href={`/programs/${programEnrollment?.program.slug}/earnings?type=custom`}
- target="_blank"
- className={cn(
- buttonVariants({ variant: "primary" }),
- "flex h-7 w-fit items-center whitespace-nowrap rounded-lg border px-2.5 text-sm",
- )}
- >
- View earnings
- </Link>
- )}
- {submission.status !== "draft" && (
- <StatusBadge
- className="rounded-lg py-1.5"
- variant={
- submission.status === "submitted"
- ? "new"
- : submission.status === "approved"
- ? "success"
- : "error"
- }
- icon={
- submission.status === "approved"
- ? undefined
- : null
- }
- >
- {submission.status === "submitted" ? (
- <>
- Pending Review |{" "}
- {bounty.type === "performance"
- ? "Completed"
- : "Submitted"}{" "}
- {submission.completedAt &&
- formatDate(submission.completedAt, {
- month: "short",
- })}
- </>
- ) : submission.status === "approved" ? (
- <>
- Confirmed{" "}
- {submission.reviewedAt &&
- formatDate(submission.reviewedAt, {
- month: "short",
- })}
- </>
- ) : (
- "Rejected"
- )}
- </StatusBadge>
- )}
- </div>
-
- {/* Rejection details for rejected submissions */}
- {submission.status === "rejected" && (
- <div className="mt-3 flex flex-col gap-2 rounded-lg border border-red-200 bg-red-50 p-4">
- <div className="flex gap-1">
- <span className="text-sm font-medium text-red-900">
- Rejection reason:
- </span>
- <span className="text-sm text-red-800">
- {submission.rejectionReason &&
- REJECT_BOUNTY_SUBMISSION_REASONS[
- submission.rejectionReason as keyof typeof REJECT_BOUNTY_SUBMISSION_REASONS
- ]}
- </span>
- </div>
- {submission.rejectionNote && (
- <div className="mt-1">
- <span className="text-sm font-medium text-red-900">
- Note:
- </span>
- <Linkify
- as="p"
- options={{
- target: "_blank",
- rel: "noopener noreferrer nofollow",
- format: (href) => getPrettyUrl(href),
- className:
- "underline underline-offset-4 text-red-400 hover:text-red-700",
- }}
- className="mt-1 whitespace-pre-wrap text-sm text-red-800"
- >
- {submission.rejectionNote}
- </Linkify>
- </div>
- )}
- </div>
- )}
- </div>
- ) : (
- bounty.type === "performance" && (
- <div className="mt-5">
- <BountyPerformance bounty={bounty} />
- </div>
- )
- )}
- </div>
-
- {bountyHasDetails(bounty) && (
- <div className="border-border-subtle border-t p-6 max-sm:px-4">
- <BountyDescription bounty={bounty} />
- </div>
- )}
-
- {/* Form */}
- <motion.div
- initial={false}
- animate={{ height: isFormOpen ? "auto" : 0 }}
- transition={{ duration: 0.15 }}
- className={cn(
- "overflow-hidden transition-opacity",
- !isFormOpen && "opacity-0",
- )}
- >
- <div className="border-border-subtle flex flex-col gap-5 border-t p-6 max-sm:px-4">
- {imageRequired && (
- <div>
- <div className="flex items-center space-x-2">
- <h2 className="text-sm font-medium text-neutral-900">
- Images
- {imageRequired && formatRequirementText(imageMax)}
- </h2>
- </div>
- <div
- className={cn(
- "mt-2 flex h-12 items-center gap-2 transition-[height]",
- files.length === 0 && "h-24",
- )}
- >
- {files.map((file, idx) => (
- <div
- key={file.id}
- className="border-border-subtle group relative flex aspect-square h-full items-center justify-center rounded-md border bg-white"
- >
- {file.uploading ? (
- <LoadingSpinner className="size-4" />
- ) : (
- <div className="relative size-full overflow-hidden rounded-md">
- <img
- src={file.url}
- alt={
- file.file?.name ||
- `Bounty attachment ${idx + 1}`
- }
- />
- </div>
- )}
- <span className="sr-only">
- {file.file?.name || `File ${idx + 1}`}
- </span>
- <button
- type="button"
- className={cn(
- "absolute right-0 top-0 flex size-[1.125rem] -translate-y-1/2 translate-x-1/2 items-center justify-center",
- "rounded-full border border-neutral-200 bg-white shadow-sm hover:bg-neutral-50 active:scale-95",
- "scale-50 opacity-0 transition-[background-color,transform,opacity] group-hover:scale-100 group-hover:opacity-100",
- )}
- onClick={() => {
- setFiles((prev) =>
- prev.filter((s) => s.id !== file.id),
- );
- }}
- >
- <X className="size-2.5 text-neutral-400" />
- </button>
- </div>
- ))}
-
- <FileUpload
- accept="images"
- className={cn(
- "border-border-subtle h-full w-auto rounded-md border",
- files.length > 0
- ? "aspect-square"
- : "aspect-[unset] w-full",
- )}
- iconClassName="size-5 shrink-0"
- variant="plain"
- content={
- files.length > 0
- ? null
- : "JPG or PNG, max size of 5MB"
- }
- onChange={async ({ file }) =>
- await handleUpload(file)
- }
- disabled={files.length >= maxFiles}
- maxFileSizeMB={5}
- />
- </div>
- </div>
- )}
-
- {urlRequired && (
- <div>
- <div className="flex items-center justify-between">
- <h2 className="text-sm font-medium text-neutral-900">
- URLs
- {urlRequired && formatRequirementText(urlMax)}
- </h2>
- <span className="text-xs font-medium text-neutral-500">
- {
- (claimForm.watch("urls") ?? []).filter(Boolean)
- .length
- }{" "}
- / {maxUrls}
- </span>
- </div>
- <div className={cn("mt-2 flex flex-col gap-2")}>
- {(() => {
- const formUrls = claimForm.watch("urls") ?? [];
- const displayUrls = socialPlatform
- ? formUrls.slice(1)
- : formUrls;
- const rows =
- displayUrls.length > 0 ? displayUrls : [""];
- return (
- <>
- {rows.map((url, i) => (
- <div
- key={i}
- className="flex items-center gap-2"
- >
- <input
- type="url"
- placeholder={placeholderUrl}
- value={url}
- onChange={(e) => {
- const prev =
- claimForm.getValues("urls") ?? [];
- const idx = socialPlatform
- ? i + 1
- : i;
- const next =
- prev.length > idx
- ? [...prev]
- : [
- ...prev,
- ...Array(
- idx - prev.length + 1,
- ).fill(""),
- ];
- next[idx] = e.target.value;
- claimForm.setValue("urls", next);
- }}
- className="block h-10 w-full rounded-md border-neutral-300 px-3 py-2 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
- />
- {rows.length > 1 && (
- <Button
- variant="outline"
- icon={<Trash className="size-4" />}
- className="w-10 shrink-0 bg-red-50 p-0 text-red-700 hover:bg-red-100"
- onClick={() => {
- const prev =
- claimForm.getValues("urls") ?? [];
- const idx = socialPlatform
- ? i + 1
- : i;
- claimForm.setValue(
- "urls",
- prev.filter((_, j) => j !== idx),
- );
- }}
- />
- )}
- </div>
- ))}
- {(claimForm.watch("urls") ?? []).length <
- maxUrls && (
- <Button
- variant="secondary"
- text="Add URL"
- className="h-8 rounded-lg"
- onClick={() => {
- claimForm.setValue("urls", [
- ...(claimForm.getValues("urls") ??
- []),
- "",
- ]);
- }}
- />
- )}
- </>
- );
- })()}
- {bounty.submissionRequirements?.url?.domains &&
- bounty.submissionRequirements.url.domains.length >
- 0 && (
- <p className="text-xs text-neutral-400">
- Allowed domains:{" "}
- {bounty.submissionRequirements.url.domains.join(
- ", ",
- )}
- </p>
- )}
- </div>
- </div>
- )}
-
- {socialPlatform && (
- <SocialContentUrlField bounty={bounty} />
- )}
-
- <div>
- <label
- htmlFor="bounty-submission-description"
- className="flex items-center space-x-2"
- >
- <span className="text-sm font-medium text-neutral-900">
- Provide any additional details (optional)
- </span>
- </label>
- <ReactTextareaAutosize
- id="bounty-submission-description"
- className={cn(
- "mt-2 block w-full resize-none rounded-md focus:outline-none sm:text-sm",
- "border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:ring-neutral-500",
- )}
- minRows={2}
- maxLength={BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH}
- value={description}
- onChange={(e) => {
- const value = e.target.value;
- if (
- value.length <=
- BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH
- ) {
- setDescription(value);
- }
- }}
- />
- <div className="mt-1 text-left">
- <span className="text-xs text-neutral-500">
- {BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH -
- description.length}{" "}
- / {BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH}
- </span>
- </div>
- </div>
- </div>
- </motion.div>
- </>
- )}
- </AnimatedSizeContainer>
- </div>
-
- {/* Action buttons - outside scrollable area */}
- {bounty.type !== "performance" &&
- (!submission || submission.status === "draft") &&
- !success && (
- <div className="border-t border-neutral-200 bg-white p-4">
- {isFormOpen ? (
- <div className="flex items-center justify-between">
- <Button
- type="button"
- variant="outline"
- text="Cancel"
- className="h-9 w-fit rounded-lg px-3"
- onClick={() => {
- claimForm.reset({ urls: initialUrls });
- setDescription(submission?.description || "");
- setFiles(
- submission?.files && submission.files.length > 0
- ? submission.files.map((file) => ({
- id: uuid(),
- url: file.url,
- uploading: false,
- file: undefined,
- }))
- : [],
- );
- setIsFormOpen(false);
- }}
- />
- <div className="flex gap-2">
- {!isSocialMetricsBounty && (
- <Button
- variant="secondary"
- text="Save progress"
- className="h-9 rounded-lg px-3"
- type="submit"
- name="draft" // for submitter.name detection above
- loading={isDraft === true}
- disabled={
- fileUploading ||
- isDraft === false ||
- socialContentVerifying ||
- (!!socialPlatform && !socialContentRequirementsMet)
- }
- />
- )}
- <Button
- variant="primary"
- text="Submit"
- className="h-9 rounded-lg px-3"
- type="submit"
- name="submit" // for submitter.name detection above
- loading={isDraft === false}
- disabled={
- fileUploading ||
- isDraft === true ||
- socialContentVerifying ||
- (!!socialPlatform && !socialContentRequirementsMet)
- }
- disabledTooltip={
- !hasSubmissionsOpen
- ? `Submissions are not open yet. They will open on ${formatDate(
- bounty.submissionsOpenAt!,
- {
- month: "short",
- day: "numeric",
- year: "numeric",
- timeZone: "UTC",
- },
- )}.${isSocialMetricsBounty ? "" : " In the meantime, you can save your progress as a draft."}`
- : socialPlatform && !socialContentRequirementsMet
- ? "Post must be from your verified account and after the bounty start date."
- : undefined
- }
- />
- </div>
- </div>
- ) : (
- <>
- {socialPlatform &&
- !platformsVerified?.[socialPlatform.value] ? (
- <SocialAccountNotVerifiedWarning bounty={bounty} />
- ) : (
- <Button
- variant="primary"
- text={
- submission ? "Continue submission" : "Claim bounty"
- }
- className="w-full rounded-lg"
- onClick={() => setIsFormOpen(true)}
- />
- )}
- </>
- )}
- </div>
- )}
- </form>
- </FormProvider>
- </>
- );
-}
-
-export function ClaimBountyModal({
- showModal,
- ...rest
-}: ClaimBountyModalProps & {
- showModal: boolean;
-}) {
- const { queryParams } = useRouterStuff();
-
- return (
- <Modal
- showModal={showModal}
- setShowModal={rest.setShowModal}
- onClose={() => queryParams({ del: "bountyId", scroll: false })}
- >
- <ClaimBountyProvider>
- <ClaimBountyModalContent {...rest} />
- </ClaimBountyProvider>
- </Modal>
- );
-}
-
-export function useClaimBountyModal(
- props: Omit<ClaimBountyModalProps, "setShowModal">,
-) {
- const [showModal, setShowModal] = useState(false);
-
- return {
- claimBountyModal: (
- <ClaimBountyModal
- setShowModal={setShowModal}
- showModal={showModal}
- {...props}
- />
- ),
- setShowClaimBountyModal: setShowModal,
- };
-}
diff --git a/apps/web/ui/partners/bounties/claim-bounty-sheet.tsx b/apps/web/ui/partners/bounties/claim-bounty-sheet.tsx
new file mode 100644
index 0000000000..27aa683002
--- /dev/null
+++ b/apps/web/ui/partners/bounties/claim-bounty-sheet.tsx
@@ -0,0 +1,718 @@
+"use client";
+
+import { createBountySubmissionAction } from "@/lib/actions/partners/create-bounty-submission";
+import { uploadBountySubmissionFileAction } from "@/lib/actions/partners/upload-bounty-submission-file";
+import {
+ BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH,
+ BOUNTY_MAX_SUBMISSION_FILES,
+ BOUNTY_MAX_SUBMISSION_URLS,
+} from "@/lib/bounty/constants";
+import { getPeriodLabel } from "@/lib/bounty/periods";
+import { resolveBountyDetails } from "@/lib/bounty/utils";
+import { mutatePrefix } from "@/lib/swr/mutate";
+import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
+import { PartnerBountyProps } from "@/lib/types";
+import { useConfirmModal } from "@/ui/modals/confirm-modal";
+import { X } from "@/ui/shared/icons";
+import {
+ Button,
+ FileUpload,
+ Label,
+ LoadingSpinner,
+ Sheet,
+ Trash,
+} from "@dub/ui";
+import { cn } from "@dub/utils";
+import { useAction } from "next-safe-action/hooks";
+import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react";
+import { FormProvider, useForm } from "react-hook-form";
+import ReactTextareaAutosize from "react-textarea-autosize";
+import { toast } from "sonner";
+import { v4 as uuid } from "uuid";
+import { SocialContentUrlField } from "./bounty-social-content";
+import {
+ ClaimBountyProvider,
+ useClaimBountyContext,
+} from "./claim-bounty-context";
+import {
+ CreateBountySubmissionInput,
+ useClaimBountyForm,
+} from "./use-claim-bounty-form";
+
+interface FileInput {
+ id: string;
+ file?: File;
+ url?: string;
+ uploading: boolean;
+}
+
+function ImagesField({
+ bounty,
+ onUploadingChange,
+ files,
+ setFiles,
+}: {
+ bounty: PartnerBountyProps;
+ onUploadingChange: (uploading: boolean) => void;
+ files: FileInput[];
+ setFiles: Dispatch<SetStateAction<FileInput[]>>;
+}) {
+ const { programEnrollment } = useProgramEnrollment();
+ const { setValue } = useClaimBountyForm();
+
+ 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 { executeAsync: uploadFile } = useAction(
+ uploadBountySubmissionFileAction,
+ );
+
+ const syncToForm = (updated: FileInput[]) => {
+ const completed = updated
+ .filter((f): f is FileInput & { url: string } => !f.uploading && !!f.url)
+ .map((f) => ({
+ url: f.url,
+ fileName: f.file?.name ?? "File",
+ size: f.file?.size ?? 0,
+ }));
+ setValue("files", completed);
+ };
+
+ const handleUpload = async (file: File) => {
+ if (!programEnrollment) return;
+
+ const newFile: FileInput = { id: uuid(), file, uploading: true };
+
+ setFiles((prev) => {
+ const updated = [...prev, newFile];
+ onUploadingChange(true);
+ return updated;
+ });
+
+ try {
+ const result = await uploadFile({
+ programId: programEnrollment.programId,
+ bountyId: bounty.id,
+ });
+
+ if (!result?.data) {
+ 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));
+ syncToForm(updated);
+ return updated;
+ });
+ return;
+ }
+
+ const { signedUrl, destinationUrl } = result.data;
+
+ const uploadResponse = await fetch(signedUrl, {
+ method: "PUT",
+ body: file,
+ headers: {
+ "Content-Type": file.type,
+ "Content-Length": file.size.toString(),
+ },
+ });
+
+ if (!uploadResponse.ok) {
+ let errorMessage = "Failed to upload screenshot.";
+ try {
+ const res = await uploadResponse.json();
+ errorMessage = res.error?.message || errorMessage;
+ } catch {
+ // ignore JSON parse errors; use the default message
+ }
+ toast.error(errorMessage);
+ setFiles((prev) => {
+ const updated = prev.filter((f) => f.id !== newFile.id);
+ onUploadingChange(updated.some((f) => f.uploading));
+ syncToForm(updated);
+ 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));
+ syncToForm(updated);
+ 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));
+ syncToForm(updated);
+ 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 group relative flex aspect-square h-full items-center justify-center rounded-md border bg-white"
+ >
+ {file.uploading ? (
+ <LoadingSpinner className="size-4" />
+ ) : (
+ <div className="relative size-full overflow-hidden rounded-md">
+ <img
+ src={file.url}
+ alt={file.file?.name || `Bounty attachment ${idx + 1}`}
+ />
+ </div>
+ )}
+ <span className="sr-only">
+ {file.file?.name || `File ${idx + 1}`}
+ </span>
+ <button
+ type="button"
+ className={cn(
+ "absolute right-0 top-0 flex size-[1.125rem] -translate-y-1/2 translate-x-1/2 items-center justify-center",
+ "rounded-full border border-neutral-200 bg-white shadow-sm hover:bg-neutral-50 active:scale-95",
+ "scale-50 opacity-0 transition-[background-color,transform,opacity] group-hover:scale-100 group-hover:opacity-100",
+ )}
+ onClick={() => {
+ setFiles((prev) => {
+ const updated = prev.filter((f) => f.id !== file.id);
+ syncToForm(updated);
+ return updated;
+ });
+ }}
+ >
+ <X className="size-2.5 text-neutral-400" />
+ </button>
+ </div>
+ ))}
+
+ <FileUpload
+ accept="images"
+ className={cn(
+ "border-border-subtle h-full w-auto rounded-md border",
+ files.length > 0 ? "aspect-square" : "aspect-[unset] w-full",
+ )}
+ iconClassName="size-5 shrink-0"
+ variant="plain"
+ content={
+ files.length > 0 ? null : "SVG, JPG, PNG or WEBP\nMax size 5MB"
+ }
+ onChange={async ({ file }) => await handleUpload(file)}
+ disabled={files.length >= maxFiles}
+ maxFileSizeMB={5}
+ />
+ </div>
+ </div>
+ );
+}
+
+function UrlsField({ bounty }: { bounty: PartnerBountyProps }) {
+ const { watch, setValue, getValues } = useClaimBountyForm();
+
+ const bountyInfo = resolveBountyDetails(bounty);
+ const socialPlatform = bountyInfo?.socialPlatform;
+
+ 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 formUrls = watch("urls") ?? [];
+ const displayUrls = socialPlatform ? formUrls.slice(1) : formUrls;
+ const rows = displayUrls.length > 0 ? displayUrls : [""];
+
+ return (
+ <div>
+ <div className="flex items-center justify-between">
+ <Label>URL{formatRequirementText(urlMax)}</Label>
+ <span className="text-xs font-medium text-neutral-500">
+ {formUrls.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) => {
+ const prev = getValues("urls") ?? [];
+ const idx = socialPlatform ? i + 1 : i;
+ const next =
+ prev.length > idx
+ ? [...prev]
+ : [...prev, ...Array(idx - prev.length + 1).fill("")];
+ next[idx] = e.target.value;
+ setValue("urls", next);
+ }}
+ className="block h-10 w-full rounded-md border-neutral-300 px-3 py-2 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
+ />
+ <Button
+ variant="outline"
+ icon={<Trash className="size-4" />}
+ className="w-10 shrink-0 bg-red-50 p-0 text-red-700 hover:bg-red-100"
+ onClick={() => {
+ const prev = getValues("urls") ?? [];
+ const idx = socialPlatform ? i + 1 : i;
+ setValue(
+ "urls",
+ prev.filter((_, j) => j !== idx),
+ );
+ }}
+ />
+ </div>
+ ))}
+
+ {formUrls.length < maxUrls && (
+ <Button
+ variant="secondary"
+ text="Add URL"
+ className="h-8 rounded-lg"
+ onClick={() => {
+ setValue("urls", [...(getValues("urls") ?? []), ""]);
+ }}
+ />
+ )}
+
+ {bounty.submissionRequirements?.url?.domains &&
+ bounty.submissionRequirements.url.domains.length > 0 && (
+ <p className="text-xs text-neutral-400">
+ Allowed domains:{" "}
+ {bounty.submissionRequirements.url.domains.join(", ")}
+ </p>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function DescriptionField() {
+ const { watch, setValue } = useClaimBountyForm();
+ const description = watch("description") ?? "";
+
+ return (
+ <div>
+ <Label htmlFor="bounty-submission-description">
+ Provide any additional details (optional)
+ </Label>
+ <ReactTextareaAutosize
+ id="bounty-submission-description"
+ className={cn(
+ "mt-2 block w-full resize-none rounded-md focus:outline-none sm:text-sm",
+ "border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:ring-neutral-500",
+ )}
+ minRows={3}
+ maxLength={BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH}
+ value={description}
+ onChange={(e) => {
+ const value = e.target.value;
+ if (value.length <= BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH) {
+ setValue("description", value);
+ }
+ }}
+ />
+ <div className="mt-1 text-left">
+ <span className="text-xs text-neutral-500">
+ {description.length} / {BOUNTY_MAX_SUBMISSION_DESCRIPTION_LENGTH}
+ </span>
+ </div>
+ </div>
+ );
+}
+
+interface ClaimBountySheetProps {
+ bounty: PartnerBountyProps;
+ isOpen: boolean;
+ setIsOpen: Dispatch<SetStateAction<boolean>>;
+ periodNumber?: number;
+}
+
+function ClaimBountySheetContent({
+ bounty,
+ setIsOpen,
+ isOpen,
+ periodNumber,
+}: ClaimBountySheetProps) {
+ const effectivePeriodNumber = periodNumber ?? 1;
+ const submission =
+ bounty.submissions?.find((s) => s.periodNumber === effectivePeriodNumber) ??
+ null;
+ const { programEnrollment } = useProgramEnrollment();
+ const {
+ socialContentVerifying,
+ socialContentRequirementsMet,
+ setSocialContentVerifying,
+ setSocialContentRequirementsMet,
+ } = useClaimBountyContext();
+
+ const [isDraft, setIsDraft] = useState<boolean | null>(null);
+ const [fileUploading, setFileUploading] = useState(false);
+
+ const bountyInfo = resolveBountyDetails(bounty);
+ const socialPlatform = bountyInfo?.socialPlatform;
+ const isSocialMetricsBounty = bountyInfo?.hasSocialMetrics ?? false;
+
+ const initialUrls = (() => {
+ if (submission?.urls && submission.urls.length > 0) {
+ return socialPlatform
+ ? [submission.urls[0] ?? "", ...submission.urls.slice(1)]
+ : [...submission.urls];
+ }
+ return [""];
+ })();
+
+ const claimForm = useForm<CreateBountySubmissionInput>({
+ defaultValues: {
+ urls: initialUrls,
+ description: submission?.description ?? "",
+ files:
+ submission?.files?.map((f) => ({
+ url: f.url,
+ fileName: f.fileName ?? "File",
+ size: f.size ?? 0,
+ })) ?? [],
+ },
+ });
+
+ const [files, setFiles] = useState<FileInput[]>(() =>
+ (submission?.files ?? []).map((f) => ({
+ id: uuid(),
+ url: f.url,
+ uploading: false,
+ file: undefined,
+ })),
+ );
+
+ const bountyRef = useRef(bounty);
+ bountyRef.current = bounty;
+
+ useEffect(() => {
+ if (!isOpen) return;
+
+ const b = bountyRef.current;
+ const ep = periodNumber ?? 1;
+ const sub = b.submissions?.find((s) => s.periodNumber === ep) ?? null;
+ const sp = resolveBountyDetails(b)?.socialPlatform;
+
+ const urls = sub?.urls?.length
+ ? sp
+ ? [sub.urls[0] ?? "", ...sub.urls.slice(1)]
+ : [...sub.urls]
+ : [""];
+
+ const formFiles =
+ sub?.files?.map((f) => ({
+ url: f.url,
+ fileName: f.fileName ?? "File",
+ size: f.size ?? 0,
+ })) ?? [];
+
+ claimForm.reset({
+ urls,
+ description: sub?.description ?? "",
+ files: formFiles,
+ });
+
+ setFiles(
+ formFiles.map((f) => ({
+ id: uuid(),
+ url: f.url,
+ uploading: false,
+ file: undefined,
+ })),
+ );
+
+ setSocialContentVerifying(false);
+ setSocialContentRequirementsMet(true);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [isOpen, periodNumber]);
+
+ const { executeAsync: createSubmission } = useAction(
+ createBountySubmissionAction,
+ {
+ onSuccess: async ({ input }) => {
+ const isDraftSave = !!input?.isDraft;
+ toast.success(
+ isDraftSave ? "Bounty progress saved." : "Bounty submitted.",
+ );
+ await mutatePrefix(
+ `/api/partner-profile/programs/${programEnrollment?.program.slug}/bounties`,
+ );
+ setIsDraft(null);
+ if (!isDraftSave) {
+ setIsOpen(false);
+ }
+ },
+ onError: ({ error }) => {
+ toast.error(
+ error.serverError || "Failed to create submission. Please try again.",
+ );
+ setIsDraft(null);
+ },
+ },
+ );
+
+ const imageRequired = !!bounty.submissionRequirements?.image;
+ const urlRequired = !!bounty.submissionRequirements?.url;
+
+ const { confirmModal, setShowConfirmModal } = useConfirmModal({
+ title: "Confirm submission",
+ description: (
+ <div className="space-y-2">
+ <p>
+ Are you sure you want to submit this bounty? Once submitted, you won't
+ be able to make any further changes.
+ </p>
+ {!isSocialMetricsBounty && (
+ <p>
+ If you need to make changes later, you can save your progress as a
+ draft instead.
+ </p>
+ )}
+ </div>
+ ),
+ confirmText: "Confirm submission",
+ onConfirm: () => handleSubmission({ isDraft: false }),
+ });
+
+ const handleSubmission = async ({ isDraft }: { isDraft: boolean }) => {
+ if (!programEnrollment) {
+ return;
+ }
+
+ setIsDraft(isDraft);
+
+ const finalFiles = claimForm.getValues("files") ?? [];
+ const formUrls = (claimForm.getValues("urls") ?? []).filter(Boolean);
+ const description = claimForm.getValues("description") ?? "";
+
+ try {
+ if (!isDraft) {
+ setShowConfirmModal(false);
+
+ if (imageRequired && finalFiles.length === 0) {
+ throw new Error("You must upload at least one image.");
+ }
+
+ if (socialPlatform && !formUrls[0]?.trim()) {
+ throw new Error(`You must provide the ${socialPlatform.label} link.`);
+ }
+
+ if (urlRequired && formUrls.length === 0) {
+ throw new Error("You must provide at least one URL.");
+ }
+ }
+
+ await createSubmission({
+ programId: programEnrollment.programId,
+ bountyId: bounty.id,
+ files: finalFiles,
+ urls: formUrls,
+ description,
+ periodNumber: effectivePeriodNumber,
+ ...(isDraft && { isDraft }),
+ });
+ } catch (error) {
+ toast.error(
+ error.message || "Failed to create submission. Please try again.",
+ );
+ setIsDraft(null);
+ }
+ };
+
+ const submissionsOpenAt = bounty.submissionsOpenAt
+ ? new Date(bounty.submissionsOpenAt)
+ : null;
+
+ const submissionsNotOpenYet =
+ submissionsOpenAt !== null && submissionsOpenAt > new Date();
+
+ const formattedSubmissionsOpenAt =
+ submissionsOpenAt && new Date() < submissionsOpenAt
+ ? `${submissionsOpenAt.toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ })} at ${submissionsOpenAt.toLocaleTimeString("en-US", { hour: "numeric", hour12: true })}`
+ : null;
+
+ const isBusy =
+ fileUploading ||
+ isDraft === false ||
+ socialContentVerifying ||
+ (!!socialPlatform && !socialContentRequirementsMet);
+
+ const isDisabled = submissionsNotOpenYet || isBusy;
+
+ return (
+ <>
+ {confirmModal}
+ <div className="relative flex size-full flex-col">
+ {/* Sticky header */}
+ <div className="sticky top-0 z-10 flex shrink-0 items-center justify-between border-b border-neutral-200 bg-white px-5 py-4">
+ <Sheet.Title className="text-base font-semibold text-neutral-900">
+ {bounty.maxSubmissions > 1
+ ? `Submission (${getPeriodLabel(bounty.submissionFrequency, effectivePeriodNumber - 1)})`
+ : "Submission"}
+ </Sheet.Title>
+ <Sheet.Close asChild>
+ <Button
+ variant="outline"
+ icon={<X className="size-5" />}
+ className="h-auto w-fit p-1"
+ />
+ </Sheet.Close>
+ </div>
+
+ <FormProvider {...claimForm}>
+ <form
+ className="flex min-h-0 flex-1 flex-col"
+ onSubmit={async (e) => {
+ e.preventDefault();
+ if (!programEnrollment) return;
+
+ const submitter = (e.nativeEvent as SubmitEvent)
+ .submitter as HTMLButtonElement;
+
+ const isDraftSubmit =
+ submitter?.name === "draft" && !isSocialMetricsBounty;
+
+ if (isDraftSubmit) {
+ await handleSubmission({ isDraft: true });
+ } else {
+ setShowConfirmModal(true);
+ }
+ }}
+ >
+ <div className="scrollbar-hide min-h-0 flex-1 overflow-y-auto">
+ {formattedSubmissionsOpenAt && (
+ <div className="p-5 pb-0">
+ <div className="rounded-lg bg-orange-50 p-2 text-center text-sm font-medium text-orange-800">
+ Submissions open {formattedSubmissionsOpenAt}
+ </div>
+ </div>
+ )}
+
+ <div className="flex flex-col gap-5 p-5">
+ {imageRequired && (
+ <ImagesField
+ bounty={bounty}
+ onUploadingChange={setFileUploading}
+ files={files}
+ setFiles={setFiles}
+ />
+ )}
+ {urlRequired && <UrlsField bounty={bounty} />}
+ {socialPlatform && <SocialContentUrlField bounty={bounty} />}
+ <DescriptionField />
+ </div>
+ </div>
+
+ <div className="flex shrink-0 items-center justify-between gap-2 border-t border-neutral-200 bg-white p-4">
+ <Button
+ variant="outline"
+ text="Cancel"
+ className="h-10 w-fit rounded-lg"
+ type="button"
+ onClick={() => setIsOpen(false)}
+ />
+
+ <div className="flex items-center gap-2">
+ {!isSocialMetricsBounty && (
+ <Button
+ variant="secondary"
+ text="Save progress"
+ className="h-10 w-fit rounded-lg"
+ type="submit"
+ name="draft"
+ loading={isDraft === true}
+ disabled={isDisabled}
+ />
+ )}
+
+ <Button
+ variant="primary"
+ text="Submit"
+ className="h-10 w-fit rounded-lg"
+ type="submit"
+ name="submit"
+ loading={isDraft === false}
+ disabled={isDisabled}
+ />
+ </div>
+ </div>
+ </form>
+ </FormProvider>
+ </div>
+ </>
+ );
+}
+
+export function ClaimBountySheet({
+ bounty,
+ isOpen,
+ setIsOpen,
+ periodNumber,
+}: ClaimBountySheetProps) {
+ return (
+ <Sheet open={isOpen} onOpenChange={setIsOpen}>
+ <ClaimBountyProvider>
+ <ClaimBountySheetContent
+ bounty={bounty}
+ isOpen={isOpen}
+ setIsOpen={setIsOpen}
+ periodNumber={periodNumber}
+ />
+ </ClaimBountyProvider>
+ </Sheet>
+ );
+}
+
+export function useClaimBountySheet(
+ props: Omit<ClaimBountySheetProps, "isOpen" | "setIsOpen" | "periodNumber">,
+) {
+ const [isOpen, setIsOpen] = useState(false);
+ const [activePeriodNumber, setActivePeriodNumber] = useState<
+ number | undefined
+ >();
+
+ return {
+ claimBountySheet: (
+ <ClaimBountySheet
+ {...props}
+ isOpen={isOpen}
+ setIsOpen={setIsOpen}
+ periodNumber={activePeriodNumber}
+ />
+ ),
+ setShowClaimBountySheet: setIsOpen,
+ setActivePeriodNumber,
+ };
+}
diff --git a/apps/web/ui/partners/bounties/partner-bounty-submission-details-sheet.tsx b/apps/web/ui/partners/bounties/partner-bounty-submission-details-sheet.tsx
deleted file mode 100644
index 31b701ed38..0000000000
--- a/apps/web/ui/partners/bounties/partner-bounty-submission-details-sheet.tsx
+++ /dev/null
@@ -1,306 +0,0 @@
-"use client";
-
-import { BOUNTY_SUBMISSION_STATUS_BADGES } from "@/lib/bounty/bounty-submission-status-badges";
-import { REJECT_BOUNTY_SUBMISSION_REASONS } from "@/lib/bounty/constants";
-import { resolveBountyDetails } from "@/lib/bounty/utils";
-import { BountySubmissionProps, PartnerBountyProps } from "@/lib/types";
-import {
- BountyDescription,
- bountyHasDetails,
-} from "@/ui/partners/bounties/bounty-description";
-import { BountyRewardDescription } from "@/ui/partners/bounties/bounty-reward-description";
-import { BountySocialContentPreview } from "@/ui/partners/bounties/bounty-social-content-preview";
-import { BountySocialMetricsRewardsTable } from "@/ui/partners/bounties/bounty-social-metrics-rewards-table";
-import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
-import { ButtonLink } from "@/ui/placeholders/button-link";
-import { X } from "@/ui/shared/icons";
-import {
- Accordion,
- AccordionContent,
- AccordionItem,
- AccordionTrigger,
- Button,
- CopyButton,
- Sheet,
- StatusBadge,
-} from "@dub/ui";
-import { Calendar6 } from "@dub/ui/icons";
-import { formatDate, getPrettyUrl } from "@dub/utils";
-import Linkify from "linkify-react";
-import { useParams } from "next/navigation";
-import { Dispatch, SetStateAction, useState } from "react";
-import { toast } from "sonner";
-
-interface PartnerBountySubmissionDetailsSheetProps {
- bounty: PartnerBountyProps;
- isOpen: boolean;
- setIsOpen: Dispatch<SetStateAction<boolean>>;
-}
-
-function PartnerBountySubmissionDetailsSheetContent({
- bounty,
-}: Omit<PartnerBountySubmissionDetailsSheetProps, "isOpen" | "setIsOpen">) {
- const { programSlug } = useParams();
-
- const submission = bounty.submission! as BountySubmissionProps;
- const bountyInfo = resolveBountyDetails(bounty);
-
- const hasSocialContent =
- bountyInfo?.hasSocialMetrics && (submission.urls?.length ?? 0) > 0;
-
- const statusBadge = BOUNTY_SUBMISSION_STATUS_BADGES[submission.status];
-
- const statusDate =
- submission.status === "approved"
- ? submission.reviewedAt
- : submission.status === "submitted"
- ? submission.completedAt
- : submission.status === "rejected"
- ? submission.reviewedAt
- : null;
- const statusLabelWithDate =
- statusDate != null
- ? `${statusBadge.label} ${formatDate(statusDate, { month: "short", day: "numeric", year: "numeric" })}`
- : statusBadge.label;
-
- return (
- <div className="relative flex size-full flex-col">
- <Sheet.Close asChild>
- <Button
- variant="outline"
- icon={<X className="size-5" />}
- className="absolute right-4 top-4 z-10 h-auto w-fit p-1"
- />
- </Sheet.Close>
- <div className="scrollbar-hide flex min-h-0 flex-1 flex-col overflow-y-auto">
- {/* Thumbnail header (matches claim-bounty-modal) */}
- <div className="flex h-[132px] shrink-0 items-center justify-center bg-neutral-100 py-3">
- <div className="relative size-full">
- <BountyThumbnailImage bounty={bounty} />
- </div>
- </div>
-
- <div className="flex min-h-0 flex-1 flex-col divide-y divide-neutral-200">
- {/* Bounty title, ends at, earn, status */}
- <div className="flex flex-col gap-1 p-5">
- <Sheet.Title className="text-content-emphasis truncate text-sm font-semibold">
- {bounty.name ?? "Bounty"}
- </Sheet.Title>
- <div className="text-content-subtle flex items-center gap-2 text-sm font-medium">
- <Calendar6 className="size-3.5 shrink-0" />
- {bounty.endsAt
- ? `Ends ${formatDate(bounty.endsAt, { month: "short", day: "numeric", year: "numeric" })}`
- : "No end date"}
- </div>
- <BountyRewardDescription bounty={bounty} className="font-medium" />
- {statusDate && (
- <StatusBadge
- variant={statusBadge.variant}
- icon={statusBadge.icon}
- className="w-fit rounded-lg py-1.5"
- >
- {statusLabelWithDate}
- </StatusBadge>
- )}
- </div>
-
- {/* Details accordion (only when there is content; open by default to match design) */}
- {bountyHasDetails(bounty) && (
- <Accordion type="single" collapsible className="w-full p-5">
- <AccordionItem
- value="details"
- className="border-none bg-transparent py-0"
- >
- <AccordionTrigger className="!text-base font-semibold text-neutral-900">
- Details
- </AccordionTrigger>
- <AccordionContent>
- <BountyDescription bounty={bounty} hideHeading />
- </AccordionContent>
- </AccordionItem>
- </Accordion>
- )}
-
- {submission.status === "rejected" && (
- <div className="p-5">
- {submission.rejectionNote && (
- <div className="rounded-lg border border-red-200 bg-red-50 p-4">
- <Linkify
- as="p"
- options={{
- target: "_blank",
- rel: "noopener noreferrer nofollow",
- format: (href) => getPrettyUrl(href),
- className:
- "underline underline-offset-4 text-red-400 hover:text-red-700",
- }}
- className="mt-1 whitespace-pre-wrap text-sm text-red-800"
- >
- {submission.rejectionNote}
- </Linkify>
- </div>
- )}
-
- {submission.rejectionReason && (
- <p className="text-content-subtle text-sm">
- <span className="font-medium text-neutral-700">
- Rejection reason:{" "}
- </span>
- {REJECT_BOUNTY_SUBMISSION_REASONS[submission.rejectionReason]}
- </p>
- )}
- </div>
- )}
-
- {bounty?.type === "submission" &&
- bountyInfo?.hasSocialMetrics &&
- bounty && (
- <div className="p-5">
- <BountySocialMetricsRewardsTable
- bounty={bounty}
- submission={submission}
- titleText="Earnings"
- />
- </div>
- )}
-
- {/* Submission section */}
- {bounty?.type === "submission" && (
- <div className="p-5">
- <h2 className="text-base font-semibold text-neutral-900">
- Submission
- </h2>
- <div className="mt-3 flex flex-col gap-4">
- {hasSocialContent && (
- <BountySocialContentPreview
- bounty={bounty}
- submission={submission}
- />
- )}
-
- {Boolean(submission.files?.length) && (
- <div>
- <h2 className="text-content-emphasis text-sm font-medium">
- Files
- </h2>
- <div className="mt-2 flex flex-wrap gap-4">
- {submission.files!.map((file, idx) => (
- <a
- key={idx}
- className="border-border-subtle hover:border-border-default group relative flex size-14 items-center justify-center rounded-md border bg-white"
- target="_blank"
- href={file.url}
- rel="noopener noreferrer"
- >
- <div className="relative size-full overflow-hidden rounded-md">
- <img src={file.url} alt="object-cover" />
- </div>
- <span className="sr-only">
- {file.fileName || `File ${idx + 1}`}
- </span>
- </a>
- ))}
- </div>
- </div>
- )}
-
- {Boolean(submission.urls?.length) && !hasSocialContent && (
- <div>
- <h2 className="text-content-emphasis text-sm font-medium">
- URLs
- </h2>
- <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="block cursor-alias truncate text-sm font-normal text-neutral-800 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="flex size-6 items-center justify-center rounded-full bg-neutral-100 text-xs font-medium text-neutral-600">
- {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>
- <h2 className="text-content-emphasis text-sm font-medium">
- How did you complete this bounty?
- </h2>
- <span className="mt-2 whitespace-pre-wrap text-sm font-normal text-neutral-600">
- {submission.description}
- </span>
- </div>
- )}
- </div>
- </div>
- )}
-
- {submission.status === "approved" && (
- <div className="mt-auto p-5 pt-2">
- <ButtonLink
- href={`/programs/${programSlug}/earnings?type=custom`}
- target="_blank"
- variant="secondary"
- className="mt-3 w-full justify-center text-sm font-medium"
- >
- View earnings
- </ButtonLink>
- </div>
- )}
- </div>
- </div>
- </div>
- );
-}
-
-export function PartnerBountySubmissionDetailsSheet({
- bounty,
- isOpen,
- ...rest
-}: PartnerBountySubmissionDetailsSheetProps) {
- return (
- <Sheet open={isOpen} onOpenChange={rest.setIsOpen}>
- <PartnerBountySubmissionDetailsSheetContent bounty={bounty} {...rest} />
- </Sheet>
- );
-}
-
-export function usePartnerBountySubmissionDetailsSheet(
- bounty: PartnerBountyProps | null,
-) {
- const [isOpen, setIsOpen] = useState(false);
-
- return {
- partnerBountySubmissionDetailsSheet: bounty ? (
- <PartnerBountySubmissionDetailsSheet
- bounty={bounty}
- isOpen={isOpen}
- setIsOpen={setIsOpen}
- />
- ) : null,
- setPartnerBountySubmissionDetailsSheetOpen: setIsOpen,
- };
-}
diff --git a/apps/web/ui/partners/program-sheet-accordion.tsx b/apps/web/ui/partners/program-sheet-accordion.tsx
index 26fe180b55..ae631200ac 100644
--- a/apps/web/ui/partners/program-sheet-accordion.tsx
+++ b/apps/web/ui/partners/program-sheet-accordion.tsx
@@ -43,8 +43,8 @@ const ProgramSheetAccordionTrigger = React.forwardRef<
ref={ref}
className={cn(
// Completely custom trigger styling - force small text on all screen sizes, hide default icon
- "flex items-center justify-between border-b border-neutral-200 bg-neutral-50 px-4 py-3 text-sm font-semibold text-neutral-800",
- "transition-all hover:bg-neutral-100 data-[state=closed]:border-b-0 sm:text-sm",
+ "flex items-center justify-between bg-neutral-100 px-4 py-3 text-sm font-semibold text-neutral-800",
+ "transition-all hover:bg-neutral-200 data-[state=closed]:border-b-0 sm:text-sm",
"[&>svg]:size-4 [&>svg]:text-neutral-400 [&[data-state=open]>svg]:rotate-180",
className,
)}
diff --git a/packages/email/src/templates/new-bounty-available.tsx b/packages/email/src/templates/new-bounty-available.tsx
index 30970e9eef..3b40d5dd99 100644
--- a/packages/email/src/templates/new-bounty-available.tsx
+++ b/packages/email/src/templates/new-bounty-available.tsx
@@ -18,6 +18,7 @@ import { Footer } from "../components/footer";
export default function NewBountyAvailable({
bounty = {
+ id: "bty_xxx",
name: "Promote Acme at your campus and earn $500",
type: "performance",
endsAt: new Date(),
@@ -31,6 +32,7 @@ export default function NewBountyAvailable({
email = "[email protected]",
}: {
bounty: {
+ id: string;
name: string;
type: "performance" | "submission";
endsAt: Date | null;
@@ -90,7 +92,7 @@ export default function NewBountyAvailable({
<Section className="px-6 pb-6 text-center">
<Link
- href={`https://partners.dub.co/programs/${program.slug}/bounties`}
+ href={`https://partners.dub.co/programs/${program.slug}/bounties/${bounty.id}`}
className="box-border block w-full rounded-md bg-black px-2 py-4 text-center text-sm font-medium leading-none text-white no-underline"
>
View bounty
diff --git a/packages/email/src/templates/unresolved-fraud-events-summary.tsx b/packages/email/src/templates/unresolved-fraud-events-summary.tsx
index fb788cea94..2a7d7ce6f4 100644
--- a/packages/email/src/templates/unresolved-fraud-events-summary.tsx
+++ b/packages/email/src/templates/unresolved-fraud-events-summary.tsx
@@ -110,14 +110,14 @@ export default function UnresolvedFraudEventsSummary({
<Column className="px-3 py-3" valign="middle">
<Row>
<Column width="32" valign="middle">
- <Img
- src={
- group.partner.image ||
- `${OG_AVATAR_URL}${group.partner.name}`
- }
- width={32}
- height={32}
- alt={group.partner.name}
+ <Img
+ src={
+ group.partner.image ||
+ `${OG_AVATAR_URL}${group.partner.name}`
+ }
+ width={32}
+ height={32}
+ alt={group.partner.name}
className="rounded-full"
/>
</Column>
diff --git a/packages/prisma/schema/bounty.prisma b/packages/prisma/schema/bounty.prisma
index ec480bab03..1ed1a9766d 100644
--- a/packages/prisma/schema/bounty.prisma
+++ b/packages/prisma/schema/bounty.prisma
@@ -86,6 +86,7 @@ model BountySubmission {
rejectionNote String? @db.Text
files Json?
urls Json?
+ periodNumber Int @default(1)
socialMetricsLastSyncedAt DateTime?
completedAt DateTime?
reviewedAt DateTime?
@@ -99,7 +100,7 @@ model BountySubmission {
user User? @relation(fields: [userId], references: [id])
programEnrollment ProgramEnrollment? @relation(fields: [programId, partnerId], references: [programId, partnerId], onDelete: Cascade)
- @@unique([bountyId, partnerId])
+ @@unique([bountyId, partnerId, periodNumber])
@@index([programId, partnerId])
@@index(partnerId)
@@index(userId)
diff --git a/packages/ui/src/label.tsx b/packages/ui/src/label.tsx
index 9f28db402d..8412673df5 100644
--- a/packages/ui/src/label.tsx
+++ b/packages/ui/src/label.tsx
@@ -4,7 +4,7 @@ import { cva, type VariantProps } from "class-variance-authority";
import * as React from "react";
const labelVariants = cva(
- "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",
+ "text-sm font-medium leading-none text-content-emphasis peer-disabled:cursor-not-allowed peer-disabled:opacity-70",
);
const Label = React.forwardRef<
diff --git a/packages/ui/src/number-stepper.tsx b/packages/ui/src/number-stepper.tsx
index 47f6311565..82c4008209 100644
--- a/packages/ui/src/number-stepper.tsx
+++ b/packages/ui/src/number-stepper.tsx
@@ -175,7 +175,7 @@ export function NumberStepper({
role="group"
aria-disabled={disabled}
className={cn(
- "flex h-10 w-full select-none items-stretch overflow-hidden rounded-lg border border-neutral-200 bg-white",
+ "flex h-10 w-full select-none items-stretch overflow-hidden rounded-lg border border-neutral-200 bg-white p-1",
disabled && "opacity-60",
className,
)}
@@ -187,8 +187,9 @@ export function NumberStepper({
onClick={handleDecrement}
disabled={disabled || !canDecrement}
className={cn(
- "flex h-full w-24 items-center justify-center border-r border-neutral-200 text-neutral-700 transition-colors",
- !(disabled || !canDecrement) && "hover:bg-neutral-50",
+ "flex h-full w-16 items-center justify-center rounded-lg text-neutral-700 transition-colors",
+ !(disabled || !canDecrement) &&
+ "hover:bg-neutral-100 active:bg-neutral-200",
)}
>
<Minus className="block size-4" />
@@ -258,8 +259,9 @@ export function NumberStepper({
onClick={handleIncrement}
disabled={disabled || !canIncrement}
className={cn(
- "flex h-full w-24 items-center justify-center border-l border-neutral-200 text-neutral-700 transition-colors",
- !(disabled || !canIncrement) && "hover:bg-neutral-50",
+ "flex h-full w-16 items-center justify-center rounded-lg text-neutral-700 transition-colors",
+ !(disabled || !canIncrement) &&
+ "hover:bg-neutral-100 active:bg-neutral-200",
)}
>
<Plus className="block size-4" />