Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add tabs, a list view and an All programs page to partner Bounties (#4684)

Rafiec2b1529c049
diff --git a/apps/web/app/(ee)/api/partner-profile/bounties/route.ts b/apps/web/app/(ee)/api/partner-profile/bounties/route.ts
new file mode 100644
index 0000000000..6add9e5e93
--- /dev/null
+++ b/apps/web/app/(ee)/api/partner-profile/bounties/route.ts
@@ -0,0 +1,61 @@
+import { getProgramEnrollmentsWhere } from "@/lib/api/partner-profile/get-program-enrollments-where";
+import { withPartnerProfile } from "@/lib/auth/partner";
+import { programEnrollmentEligibilityIncludes } from "@/lib/bounty/api/bounty-availability";
+import { getBountiesForPartnerEnrollments } from "@/lib/bounty/api/get-bounties-for-partner";
+import { aggregatePartnerLinksStats } from "@/lib/partners/aggregate-partner-links-stats";
+import { getPartnerLinksStatsByProgram } from "@/lib/partners/get-partner-links-stats-by-program";
+import { prisma } from "@/lib/prisma";
+import { PartnerProfileBountySchema } from "@/lib/zod/schemas/partner-profile";
+import { ACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";
+import { NextResponse } from "next/server";
+import * as z from "zod/v4";
+
+// GET /api/partner-profile/bounties – get available bounties for all active program enrollments
+export const GET = withPartnerProfile(async ({ partner }) => {
+ const [programEnrollments, linksStatsByProgram] = await Promise.all([
+ prisma.programEnrollment.findMany({
+ where: getProgramEnrollmentsWhere({
+ partnerId: partner.id,
+ // archived partners can still submit bounties
+ status: ACTIVE_ENROLLMENT_STATUSES,
+ }),
+ include: {
+ program: {
+ select: {
+ id: true,
+ name: true,
+ slug: true,
+ logo: true,
+ defaultGroupId: true,
+ },
+ },
+ ...programEnrollmentEligibilityIncludes,
+ },
+ }),
+ // summed in the database, because a partner can have many links in each program
+ getPartnerLinksStatsByProgram({ partnerId: partner.id }),
+ ]);
+
+ const bounties = await getBountiesForPartnerEnrollments({
+ partnerId: partner.id,
+ programEnrollments: programEnrollments.map((programEnrollment) => ({
+ ...programEnrollment,
+ partnerLinksStats:
+ linksStatsByProgram.get(programEnrollment.programId) ??
+ aggregatePartnerLinksStats([]),
+ })),
+ });
+
+ const programsById = new Map(
+ programEnrollments.map(({ program }) => [program.id, program]),
+ );
+
+ return NextResponse.json(
+ z.array(PartnerProfileBountySchema).parse(
+ bounties.map((bounty) => ({
+ ...bounty,
+ program: programsById.get(bounty.programId),
+ })),
+ ),
+ );
+});
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
index 3e22ab9c27..b86306c8a6 100644
--- 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
@@ -4,10 +4,14 @@ import { withPartnerProfile } from "@/lib/auth/partner";
import {
bountyEligibilityIncludes,
canPartnerSeeBounty,
- getEffectiveBountyPeriod,
+ programEnrollmentEligibilityIncludes,
} from "@/lib/bounty/api/bounty-availability";
+import { toPartnerBounty } from "@/lib/bounty/api/get-bounties-for-partner";
import { getBountyOrThrow } from "@/lib/bounty/api/get-bounty-or-throw";
-import { aggregatePartnerLinksStats } from "@/lib/partners/aggregate-partner-links-stats";
+import {
+ aggregatePartnerLinksStats,
+ partnerLinkStatsSelect,
+} from "@/lib/partners/aggregate-partner-links-stats";
import { PartnerBountySchema } from "@/lib/zod/schemas/partner-profile";
import { NextResponse } from "next/server";
@@ -27,19 +31,9 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {
},
},
links: {
- select: {
- clicks: true,
- leads: true,
- conversions: true,
- sales: true,
- saleAmount: true,
- },
- },
- programPartnerTags: {
- select: {
- partnerTagId: true,
- },
+ select: partnerLinkStatsSelect,
},
+ ...programEnrollmentEligibilityIncludes,
},
});
@@ -88,23 +82,13 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {
});
}
- const { startsAt, endsAt } = getEffectiveBountyPeriod({
- programEnrollment,
- bounty,
- });
-
- const { groups, partnerTags, ...bountyWithoutGroups } = bounty;
-
return NextResponse.json(
- PartnerBountySchema.parse({
- ...bountyWithoutGroups,
- startsAt,
- endsAt,
- performanceCondition: bounty.workflow?.triggerConditions?.[0] || null,
- partner: {
- ...aggregatePartnerLinksStats(links),
- totalCommissions: programEnrollment.totalCommissions,
- },
- }),
+ PartnerBountySchema.parse(
+ toPartnerBounty({
+ bounty,
+ programEnrollment,
+ partnerLinksStats: aggregatePartnerLinksStats(links),
+ }),
+ ),
);
});
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/social-content-stats/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/social-content-stats/route.ts
index 0a73e5dcd2..6b20c35c7b 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/social-content-stats/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/social-content-stats/route.ts
@@ -5,6 +5,7 @@ import { withPartnerProfile } from "@/lib/auth/partner";
import {
bountyEligibilityIncludes,
canPartnerSubmitBounty,
+ programEnrollmentEligibilityIncludes,
} from "@/lib/bounty/api/bounty-availability";
import { getBountyOrThrow } from "@/lib/bounty/api/get-bounty-or-throw";
import { resolveBountyDetails } from "@/lib/bounty/utils";
@@ -39,11 +40,7 @@ export const GET = withPartnerProfile(
defaultGroupId: true,
},
},
- programPartnerTags: {
- select: {
- partnerTagId: true,
- },
- },
+ ...programEnrollmentEligibilityIncludes,
},
});
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/route.ts
index 03fadc4089..a3f3f51b7d 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/route.ts
@@ -1,6 +1,8 @@
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
import { withPartnerProfile } from "@/lib/auth/partner";
+import { programEnrollmentEligibilityIncludes } from "@/lib/bounty/api/bounty-availability";
import { getBountiesForPartner } from "@/lib/bounty/api/get-bounties-for-partner";
+import { partnerLinkStatsSelect } from "@/lib/partners/aggregate-partner-links-stats";
import { NextResponse } from "next/server";
// GET /api/partner-profile/programs/[programId]/bounties – get available bounties for an enrolled program
@@ -16,19 +18,9 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {
},
},
links: {
- select: {
- clicks: true,
- leads: true,
- conversions: true,
- sales: true,
- saleAmount: true,
- },
- },
- programPartnerTags: {
- select: {
- partnerTagId: true,
- },
+ select: partnerLinkStatsSelect,
},
+ ...programEnrollmentEligibilityIncludes,
},
});
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/detail.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/detail.tsx
index b4a708db89..30c2562ed2 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/detail.tsx
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/detail.tsx
@@ -15,13 +15,13 @@ import { BountyRewardDescription } from "@/ui/partners/bounties/bounty-reward-de
import { BountyStatusBadge } from "@/ui/partners/bounties/bounty-status-badge";
import { BountySubmissionRequirements } from "@/ui/partners/bounties/bounty-submission-requirements";
import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
-import { ChevronRight, Trophy } from "@dub/ui";
-import { PlatformType } from "@prisma/client";
-import { useState } from "react";
import {
BountyEndDate,
BountyRewardsTable,
-} from "../../../../partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/bounty-card";
+} from "@/ui/partners/bounties/partner-bounty-card";
+import { ChevronRight, Trophy } from "@dub/ui";
+import { PlatformType } from "@prisma/client";
+import { useState } from "react";
import { EmbedBountySubmissionDetail } from "./submission-detail";
import { EmbedBountySubmissionForm } from "./submission-form";
import { EmbedBountySubmissionsTable } from "./submissions-table";
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/index.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/index.tsx
index dcf2dbd6d1..bdf270f6b1 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/index.tsx
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/index.tsx
@@ -1,15 +1,15 @@
"use client";
import { PartnerBountyProps } from "@/lib/types";
+import {
+ BountyEndDate,
+ PartnerBountyCard,
+} from "@/ui/partners/bounties/partner-bounty-card";
import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
import { TAB_ITEM_ANIMATION_SETTINGS } from "@dub/ui";
import { Trophy } from "@dub/ui/icons";
import { AnimatePresence, motion } from "motion/react";
import { useState } from "react";
-import {
- BountyEndDate,
- PartnerBountyCard,
-} from "../../../../partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/bounty-card";
import { useReferralsEmbedData } from "../page-client";
import { EmbedBountyDetail, EmbedBountyView } from "./detail";
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submissions-table.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submissions-table.tsx
index 2ae845320a..92808ff7ff 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submissions-table.tsx
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submissions-table.tsx
@@ -1,6 +1,7 @@
"use client";
import { BountySubmissionStatusBadges } from "@/lib/bounty/bounty-submission-status-badges";
+import { isPartnerBountyExpired } from "@/lib/bounty/partner-bounty-tabs";
import {
type SubmissionPeriod,
getSubmissionPeriods,
@@ -100,8 +101,7 @@ export function EmbedBountySubmissionsTable({
},
cell: ({ row: { original } }) => {
const { status, periodNumber } = original;
- const isExpired =
- bounty.endsAt !== null && new Date(bounty.endsAt) < new Date();
+ const isExpired = isPartnerBountyExpired(bounty);
const isActionable =
status === "notSubmitted" ||
(status === "draft" &&
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/bounties/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/bounties/page.tsx
new file mode 100644
index 0000000000..d0920212ce
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/bounties/page.tsx
@@ -0,0 +1,26 @@
+"use client";
+
+import { usePartnerProfileBounties } from "@/lib/swr/use-partner-profile-bounties";
+import { PageContent } from "@/ui/layout/page-content";
+import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
+import { PartnerBountiesView } from "@/ui/partners/bounties/partner-bounties-view";
+
+export default function PartnerBountiesPage() {
+ const { bounties, bountiesCount, isLoading } = usePartnerProfileBounties();
+
+ return (
+ <PageContent title="Bounties">
+ <PageWidthWrapper className="pb-10">
+ <PartnerBountiesView
+ bounties={bounties}
+ bountiesCount={bountiesCount}
+ isLoading={isLoading}
+ getHref={(bounty) =>
+ `/programs/${bounty.program.slug}/bounties/${bounty.id}`
+ }
+ showProgram
+ />
+ </PageWidthWrapper>
+ </PageContent>
+ );
+}
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/[bountyId]/bounty-submissions-table.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/[bountyId]/bounty-submissions-table.tsx
index eae29e419d..faafc0fcec 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/[bountyId]/bounty-submissions-table.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/[bountyId]/bounty-submissions-table.tsx
@@ -1,6 +1,7 @@
"use client";
import { BountySubmissionStatusBadges } from "@/lib/bounty/bounty-submission-status-badges";
+import { isPartnerBountyExpired } from "@/lib/bounty/partner-bounty-tabs";
import {
type SubmissionPeriod,
getSubmissionPeriods,
@@ -145,8 +146,7 @@ export function BountySubmissionsTable({
cell: ({ row: { original } }) => {
const { status } = original;
const bountyInfo = resolveBountyDetails(bounty);
- const isExpired =
- bounty.endsAt !== null && new Date(bounty.endsAt) < new Date();
+ const isExpired = isPartnerBountyExpired(bounty);
const isActionable = bountyInfo?.hasSocialMetrics
? status === "notSubmitted"
: status === "notSubmitted" || status === "draft";
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
index d9e4c5ee47..e37181728e 100644
--- 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
@@ -10,15 +10,15 @@ import {
} 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";
+} from "@/ui/partners/bounties/partner-bounty-card";
+import { ChevronRight, Trophy } from "@dub/ui";
+import { cn, truncate } from "@dub/utils";
+import Link from "next/link";
+import { redirect, useParams } from "next/navigation";
import { BountySubmissionsTable } from "./bounty-submissions-table";
export default function PartnerBountyPage() {
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/page.tsx
index 7258e9378a..3c80dce64e 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/page.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/page.tsx
@@ -3,120 +3,22 @@
import { usePartnerProgramBounties } from "@/lib/swr/use-partner-program-bounties";
import { PageContent } from "@/ui/layout/page-content";
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 { PartnerBountiesView } from "@/ui/partners/bounties/partner-bounties-view";
import { useParams } from "next/navigation";
-import { useMemo, useState } from "react";
-import { PartnerBountyCard, PartnerBountyCardSkeleton } from "./bounty-card";
-
-const tabs = [
- {
- label: "Active",
- id: "active",
- },
- {
- label: "Expired",
- id: "expired",
- },
-] as const;
export default function PartnerProgramBountiesPage() {
const { programSlug } = useParams();
- const [activeTab, setActiveTab] = useState<"active" | "expired">("active");
const { bounties, bountiesCount, isLoading } = usePartnerProgramBounties();
- // Filter bounties based on active tab
- const filteredBounties = useMemo(() => {
- if (!bounties) return [];
-
- const now = new Date();
- return bounties.filter((bounty) => {
- const isExpired = bounty.endsAt && new Date(bounty.endsAt) <= now;
-
- if (activeTab === "active") {
- return !isExpired;
- } else {
- return isExpired;
- }
- });
- }, [bounties, activeTab]);
return (
<PageContent title="Bounties">
<PageWidthWrapper className="pb-10">
- <div className="mb-4 grid grid-cols-2 gap-2">
- {tabs.map((tab) => {
- const isActive = activeTab === tab.id;
-
- return (
- <button
- key={tab.id}
- type="button"
- className={cn(
- "border-border-subtle flex flex-col gap-1 rounded-lg border p-4 text-left transition-colors duration-100",
- isActive
- ? "border-black ring-1 ring-black"
- : "hover:bg-bg-muted",
- )}
- onClick={() => setActiveTab(tab.id)}
- >
- <span className="text-content-default text-xs font-semibold">
- {tab.label}
- </span>
- {bounties ? (
- <span className="text-content-emphasis text-base font-semibold">
- {bountiesCount[tab.id].toLocaleString()}
- </span>
- ) : (
- <div className="h-6 w-12 animate-pulse rounded-md bg-neutral-200" />
- )}
- </button>
- );
- })}
- </div>
-
- {filteredBounties?.length !== 0 || isLoading ? (
- <div className="grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3">
- {filteredBounties?.length
- ? filteredBounties?.map((bounty) => (
- <PartnerBountyCard
- key={bounty.id}
- bounty={bounty}
- href={`/programs/${programSlug}/bounties/${bounty.id}`}
- />
- ))
- : Array.from({ length: 3 }, (_, index) => (
- <PartnerBountyCardSkeleton key={index} />
- ))}
- </div>
- ) : (
- <AnimatedEmptyState
- title="No bounties to collect"
- description={
- <>
- This program isn't offering any bounties at the moment.{" "}
- <a
- href="https://dub.co/help/article/program-bounties"
- target="_blank"
- rel="noopener noreferrer"
- className="hover:text-content-default underline sm:whitespace-nowrap"
- >
- Learn more about bounties
- </a>
- .
- </>
- }
- cardContent={(idx) => {
- const Icon = [Trophy, Heart][idx % 2];
- return (
- <>
- <Icon className="size-4 text-neutral-700" />
- <div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />
- </>
- );
- }}
- />
- )}
+ <PartnerBountiesView
+ bounties={bounties}
+ bountiesCount={bountiesCount}
+ isLoading={isLoading}
+ getHref={(bounty) => `/programs/${programSlug}/bounties/${bounty.id}`}
+ />
</PageWidthWrapper>
</PageContent>
);
diff --git a/apps/web/lib/bounty/api/bounty-availability.ts b/apps/web/lib/bounty/api/bounty-availability.ts
index 02b259d48f..8c8cb689ad 100644
--- a/apps/web/lib/bounty/api/bounty-availability.ts
+++ b/apps/web/lib/bounty/api/bounty-availability.ts
@@ -141,6 +141,15 @@ export const bountyEligibilityIncludes = {
},
} satisfies Prisma.BountyInclude;
+// the program enrollment relations that the bounty eligibility checks need
+export const programEnrollmentEligibilityIncludes = {
+ programPartnerTags: {
+ select: {
+ partnerTagId: true,
+ },
+ },
+} satisfies Prisma.ProgramEnrollmentInclude;
+
export function getEffectiveBountyPeriod({
programEnrollment,
bounty,
diff --git a/apps/web/lib/bounty/api/get-bounties-for-partner.ts b/apps/web/lib/bounty/api/get-bounties-for-partner.ts
index a8e1083b44..c57c9f3ae7 100644
--- a/apps/web/lib/bounty/api/get-bounties-for-partner.ts
+++ b/apps/web/lib/bounty/api/get-bounties-for-partner.ts
@@ -1,11 +1,17 @@
import {
aggregatePartnerLinksStats,
PartnerLink,
+ PartnerLinksStats,
} from "@/lib/partners/aggregate-partner-links-stats";
import { prisma } from "@/lib/prisma";
import { PartnerBountySchema } from "@/lib/zod/schemas/partner-profile";
import { pluck } from "@dub/utils";
-import { Program, ProgramEnrollment, ProgramPartnerTag } from "@prisma/client";
+import {
+ Program,
+ ProgramEnrollment,
+ ProgramPartnerTag,
+ Workflow,
+} from "@prisma/client";
import * as z from "zod/v4";
import {
bountyEligibilityIncludes,
@@ -15,29 +21,58 @@ import {
getEffectiveBountyPeriod,
} from "./bounty-availability";
-type GetBountiesForPartnerParams = Pick<
+type PartnerBountyEnrollment = Pick<
ProgramEnrollment,
- "groupId" | "partnerId" | "totalCommissions" | "createdAt" | "status"
+ "groupId" | "totalCommissions" | "createdAt" | "status"
> & {
- links: PartnerLink[];
program: Pick<Program, "id" | "defaultGroupId">;
programPartnerTags: Pick<ProgramPartnerTag, "partnerTagId">[];
};
export async function getBountiesForPartner({
- program,
links,
- programPartnerTags,
+ partnerId,
...programEnrollment
-}: GetBountiesForPartnerParams) {
- const { groupId, partnerId, totalCommissions, createdAt } = programEnrollment;
+}: PartnerBountyEnrollment &
+ Pick<ProgramEnrollment, "partnerId"> & {
+ links: PartnerLink[];
+ }) {
+ const bounties = await getBountiesForPartnerEnrollments({
+ partnerId,
+ programEnrollments: [
+ {
+ ...programEnrollment,
+ partnerLinksStats: aggregatePartnerLinksStats(links),
+ },
+ ],
+ });
- const partnerGroupId = groupId || program.defaultGroupId;
- const partnerTagIds = pluck(programPartnerTags, "partnerTagId");
+ return z.array(PartnerBountySchema).parse(bounties);
+}
+// the bounties a partner can see across their program enrollments, in one query.
+// Each bounty keeps its programId, so callers can match it to its program
+export async function getBountiesForPartnerEnrollments({
+ partnerId,
+ programEnrollments,
+}: {
+ partnerId: string;
+ programEnrollments: (PartnerBountyEnrollment & {
+ partnerLinksStats: PartnerLinksStats;
+ })[];
+}) {
+ if (programEnrollments.length === 0) {
+ return [];
+ }
+
+ // one filter for all enrollments, so the query size does not grow with the number of programs.
+ // Groups and tags belong to one program, so the union matches almost the same bounties, and
+ // canPartnerSeeBounty below checks each bounty against its own enrollment
const bounties = await prisma.bounty.findMany({
where: {
- programId: program.id,
+ programId: {
+ in: programEnrollments.map(({ program }) => program.id),
+ },
archivedAt: null,
OR: [
{
@@ -50,8 +85,13 @@ export async function getBountiesForPartner({
{
AND: [
buildBountyEligibilityWhere({
- groupId: partnerGroupId,
- partnerTagIds,
+ groupId: programEnrollments.map(
+ ({ program, groupId }) => groupId || program.defaultGroupId,
+ ),
+ partnerTagIds: programEnrollments.flatMap(
+ ({ programPartnerTags }) =>
+ pluck(programPartnerTags, "partnerTagId"),
+ ),
}),
buildBountyActivePeriodWhere(),
],
@@ -86,41 +126,64 @@ export async function getBountiesForPartner({
},
});
- const partnerLinkStats = aggregatePartnerLinksStats(links);
-
- const visibleBounties = bounties.filter((bounty) =>
- canPartnerSeeBounty({
- program,
- bounty,
- programEnrollment: {
- ...programEnrollment,
- programPartnerTags,
- },
- }),
+ const enrollmentsByProgramId = new Map(
+ programEnrollments.map((programEnrollment) => [
+ programEnrollment.program.id,
+ programEnrollment,
+ ]),
);
- return z.array(PartnerBountySchema).parse(
- visibleBounties.map((bounty) => {
- const performanceCondition =
- bounty.workflow?.triggerConditions?.[0] || null;
+ return bounties.flatMap((bounty) => {
+ const programEnrollment = enrollmentsByProgramId.get(bounty.programId);
- const { startsAt, endsAt } = getEffectiveBountyPeriod({
- programEnrollment: {
- createdAt,
- },
+ if (
+ !programEnrollment ||
+ !canPartnerSeeBounty({
+ program: programEnrollment.program,
bounty,
- });
+ programEnrollment,
+ })
+ ) {
+ return [];
+ }
- return {
- ...bounty,
- startsAt,
- endsAt,
- performanceCondition,
- partner: {
- ...partnerLinkStats,
- totalCommissions,
- },
- };
- }),
- );
+ return [
+ toPartnerBounty({
+ bounty,
+ programEnrollment,
+ partnerLinksStats: programEnrollment.partnerLinksStats,
+ }),
+ ];
+ });
+}
+
+// adds the partner's bounty period, performance condition and stats to a bounty
+export function toPartnerBounty<
+ T extends Parameters<typeof getEffectiveBountyPeriod>[0]["bounty"] & {
+ workflow: Pick<Workflow, "triggerConditions"> | null;
+ },
+>({
+ bounty,
+ programEnrollment,
+ partnerLinksStats,
+}: {
+ bounty: T;
+ programEnrollment: Pick<ProgramEnrollment, "createdAt" | "totalCommissions">;
+ partnerLinksStats: PartnerLinksStats;
+}) {
+ const { startsAt, endsAt } = getEffectiveBountyPeriod({
+ programEnrollment,
+ bounty,
+ });
+
+ return {
+ ...bounty,
+ startsAt,
+ endsAt,
+ performanceCondition: bounty.workflow?.triggerConditions?.[0] || null,
+ partner: {
+ ...partnerLinksStats,
+ totalCommissions: programEnrollment.totalCommissions,
+ },
+ };
}
diff --git a/apps/web/lib/bounty/partner-bounty-tabs.ts b/apps/web/lib/bounty/partner-bounty-tabs.ts
new file mode 100644
index 0000000000..771973738f
--- /dev/null
+++ b/apps/web/lib/bounty/partner-bounty-tabs.ts
@@ -0,0 +1,60 @@
+import { PartnerBountyProps } from "@/lib/types";
+
+export const PARTNER_BOUNTY_TABS = ["active", "completed", "expired"] as const;
+
+export type PartnerBountyTab = (typeof PARTNER_BOUNTY_TABS)[number];
+
+// the partner reached the goal: the performance target, or the maximum number of submissions (drafts do not count)
+function isPartnerBountyCompleted(
+ bounty: Pick<
+ PartnerBountyProps,
+ "type" | "submissions" | "performanceCondition" | "maxSubmissions"
+ >,
+) {
+ if (bounty.type === "performance") {
+ // a performance bounty without a condition has no target to reach, but a target of 0 is valid
+ return (
+ bounty.performanceCondition != null &&
+ (bounty.submissions?.[0]?.performanceCount ?? 0) >=
+ bounty.performanceCondition.value
+ );
+ }
+
+ return (
+ (bounty.submissions?.filter((s) => s.status !== "draft").length ?? 0) >=
+ (bounty.maxSubmissions ?? 1)
+ );
+}
+
+export function isPartnerBountyExpired(
+ bounty: Pick<PartnerBountyProps, "endsAt">,
+) {
+ return !!bounty.endsAt && new Date(bounty.endsAt) < new Date();
+}
+
+// a completed bounty stays in Completed after it ends, so Expired only has bounties the partner did not complete
+export function getPartnerBountyTab(
+ bounty: PartnerBountyProps,
+): PartnerBountyTab {
+ if (isPartnerBountyCompleted(bounty)) {
+ return "completed";
+ }
+
+ return isPartnerBountyExpired(bounty) ? "expired" : "active";
+}
+
+export function countPartnerBountiesByTab(
+ bounties: PartnerBountyProps[] | undefined,
+) {
+ const counts: Record<PartnerBountyTab, number> = {
+ active: 0,
+ completed: 0,
+ expired: 0,
+ };
+
+ for (const bounty of bounties ?? []) {
+ counts[getPartnerBountyTab(bounty)]++;
+ }
+
+ return counts;
+}
diff --git a/apps/web/lib/bounty/rewards.ts b/apps/web/lib/bounty/rewards.ts
index 021253987f..02e35d9f58 100644
--- a/apps/web/lib/bounty/rewards.ts
+++ b/apps/web/lib/bounty/rewards.ts
@@ -2,12 +2,15 @@ import { currencyFormatter } from "@dub/utils";
import { BountyProps } from "../types";
import { resolveBountyDetails } from "./utils";
-export function getBountyRewardDescription(
- bounty: Pick<
- BountyProps,
- "rewardAmount" | "rewardDescription" | "submissionRequirements"
- >,
-) {
+type BountyRewardFields = Pick<
+ BountyProps,
+ "rewardAmount" | "rewardDescription" | "submissionRequirements"
+>;
+
+// the reward in cents, and whether it is a maximum (bounties with an incremental bonus pay up to that amount)
+export function getBountyRewardAmount(
+ bounty: BountyRewardFields,
+): { amount: number; isMaximum: boolean } | null {
const bountyInfo = resolveBountyDetails({
rewardAmount: bounty.rewardAmount,
submissionRequirements: bounty.submissionRequirements,
@@ -36,20 +39,38 @@ export function getBountyRewardDescription(
const earningsCapCents = baseRewardCents + incrementalCapCents;
if (earningsCapCents > 0) {
- const formattedEarningsCap = currencyFormatter(earningsCapCents, {
- trailingZeroDisplay: "stripIfInteger",
- });
-
- return `Earn up to ${formattedEarningsCap}`;
+ return { amount: earningsCapCents, isMaximum: true };
}
}
if (bounty.rewardAmount) {
- const formattedAmount = currencyFormatter(bounty.rewardAmount, {
- trailingZeroDisplay: "stripIfInteger",
- });
+ return { amount: bounty.rewardAmount, isMaximum: false };
+ }
+
+ return null;
+}
+
+// "$50" or "Up to $300", and with a prefix, "Earn $50" or "Earn up to $300"
+export function formatBountyRewardAmount(
+ reward: { amount: number; isMaximum: boolean },
+ { prefix }: { prefix?: string } = {},
+) {
+ const formattedAmount = currencyFormatter(reward.amount, {
+ trailingZeroDisplay: "stripIfInteger",
+ });
+
+ const text = [prefix, reward.isMaximum && "up to", formattedAmount]
+ .filter(Boolean)
+ .join(" ");
+
+ return text.charAt(0).toUpperCase() + text.slice(1);
+}
+
+export function getBountyRewardDescription(bounty: BountyRewardFields) {
+ const reward = getBountyRewardAmount(bounty);
- return `Earn ${formattedAmount}`;
+ if (reward) {
+ return formatBountyRewardAmount(reward, { prefix: "Earn" });
}
if (bounty.rewardDescription) {
diff --git a/apps/web/lib/middleware/partners.ts b/apps/web/lib/middleware/partners.ts
index d7a29ea0ad..47af8f8b4d 100644
--- a/apps/web/lib/middleware/partners.ts
+++ b/apps/web/lib/middleware/partners.ts
@@ -14,6 +14,7 @@ const AUTHENTICATED_PATHS = [
"/overview",
"/programs",
"/marketplace",
+ "/bounties",
"/onboarding",
"/settings",
"/profile",
diff --git a/apps/web/lib/partners/aggregate-partner-links-stats.ts b/apps/web/lib/partners/aggregate-partner-links-stats.ts
index fe2f6d3d7c..99e162f059 100644
--- a/apps/web/lib/partners/aggregate-partner-links-stats.ts
+++ b/apps/web/lib/partners/aggregate-partner-links-stats.ts
@@ -1,4 +1,5 @@
import { toCentsNumber } from "@dub/utils";
+import { Prisma } from "@prisma/client";
import { LinkProps } from "../types";
export type PartnerLink = Pick<
@@ -8,6 +9,17 @@ export type PartnerLink = Pick<
saleAmount: number | bigint;
};
+export type PartnerLinksStats = ReturnType<typeof aggregatePartnerLinksStats>;
+
+// the link fields that aggregatePartnerLinksStats needs
+export const partnerLinkStatsSelect = {
+ clicks: true,
+ leads: true,
+ conversions: true,
+ sales: true,
+ saleAmount: true,
+} satisfies Prisma.LinkSelect;
+
export function aggregatePartnerLinksStats(links?: PartnerLink[] | null) {
if (!links || links.length === 0) {
return {
diff --git a/apps/web/lib/partners/get-partner-links-stats-by-program.ts b/apps/web/lib/partners/get-partner-links-stats-by-program.ts
new file mode 100644
index 0000000000..f84a3752a5
--- /dev/null
+++ b/apps/web/lib/partners/get-partner-links-stats-by-program.ts
@@ -0,0 +1,38 @@
+import { prisma } from "@/lib/prisma";
+import { toCentsNumber } from "@dub/utils";
+import {
+ PartnerLinksStats,
+ partnerLinkStatsSelect,
+} from "./aggregate-partner-links-stats";
+
+// the link stats of a partner in each of their programs, summed in the database
+// instead of loading every link. Programs without links are not in the map
+export async function getPartnerLinksStatsByProgram({
+ partnerId,
+}: {
+ partnerId: string;
+}) {
+ const stats = await prisma.link.groupBy({
+ by: ["programId"],
+ where: {
+ partnerId,
+ programId: {
+ not: null,
+ },
+ },
+ _sum: partnerLinkStatsSelect,
+ });
+
+ return new Map<string, PartnerLinksStats>(
+ stats.map(({ programId, _sum }) => [
+ programId!,
+ {
+ totalClicks: _sum.clicks ?? 0,
+ totalLeads: _sum.leads ?? 0,
+ totalConversions: _sum.conversions ?? 0,
+ totalSales: _sum.sales ?? 0,
+ totalSaleAmount: toCentsNumber(_sum.saleAmount),
+ },
+ ]),
+ );
+}
diff --git a/apps/web/lib/swr/use-partner-profile-bounties.ts b/apps/web/lib/swr/use-partner-profile-bounties.ts
new file mode 100644
index 0000000000..d9d494f4e1
--- /dev/null
+++ b/apps/web/lib/swr/use-partner-profile-bounties.ts
@@ -0,0 +1,37 @@
+import { fetcher } from "@dub/utils";
+import { useMemo } from "react";
+import useSWR from "swr";
+import { countPartnerBountiesByTab } from "../bounty/partner-bounty-tabs";
+import { PartnerProfileBountyProps } from "../types";
+
+// the partner bounties of all active programs
+export function usePartnerProfileBounties({
+ enabled = true,
+}: {
+ enabled?: boolean;
+} = {}) {
+ const {
+ data: bounties,
+ isLoading,
+ error,
+ } = useSWR<PartnerProfileBountyProps[]>(
+ enabled && "/api/partner-profile/bounties",
+ fetcher,
+ {
+ dedupingInterval: 60000,
+ keepPreviousData: true,
+ },
+ );
+
+ const bountiesCount = useMemo(
+ () => countPartnerBountiesByTab(bounties),
+ [bounties],
+ );
+
+ return {
+ bounties,
+ bountiesCount,
+ 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 631b57bc85..d24c4d2b25 100644
--- a/apps/web/lib/swr/use-partner-program-bounties.ts
+++ b/apps/web/lib/swr/use-partner-program-bounties.ts
@@ -2,6 +2,7 @@ import { fetcher } from "@dub/utils";
import { useParams } from "next/navigation";
import { useMemo } from "react";
import useSWR from "swr";
+import { countPartnerBountiesByTab } from "../bounty/partner-bounty-tabs";
import { PartnerBountyProps } from "../types";
export function usePartnerProgramBounties({
@@ -26,17 +27,10 @@ export function usePartnerProgramBounties({
},
);
- const bountiesCount = useMemo(() => {
- if (!bounties) return { active: 0, expired: 0 };
- return bounties.reduce(
- (counts, bounty) => {
- const isExpired = bounty.endsAt && new Date(bounty.endsAt) < new Date();
- counts[isExpired ? "expired" : "active"]++;
- return counts;
- },
- { active: 0, expired: 0 },
- );
- }, [bounties]);
+ const bountiesCount = useMemo(
+ () => countPartnerBountiesByTab(bounties),
+ [bounties],
+ );
return {
bounties,
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 588a9a0702..d348a7df1b 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -4,14 +4,15 @@ import {
partnerBountySubmissionSchema,
PartnerEarningsSchema,
partnerPayoutMethodSchema,
+ PartnerProfileBountySchema,
PartnerProfileCustomerSchema,
+ partnerProfileEarningsAnalyticsQuerySchema,
PartnerProfileEarningsSchema,
PartnerProfileLinkSchema,
PartnerProfileProgramEnrollmentSchema,
PartnerProfileTopLinkEarningsSchema,
PartnerProfileTopProgramEarningsSchema,
PartnerProfileTypeEarningsSchema,
- partnerProfileEarningsAnalyticsQuerySchema,
partnerSubmittedLeadsCountByStatusSchema,
partnerUserSchema,
} from "@/lib/zod/schemas/partner-profile";
@@ -754,6 +755,10 @@ export type GroupBountySummaryProps = z.infer<typeof GroupBountySummarySchema>;
export type PartnerBountyProps = z.infer<typeof PartnerBountySchema>;
+export type PartnerProfileBountyProps = z.infer<
+ typeof PartnerProfileBountySchema
+>;
+
export type BountySubmissionProps = z.infer<
typeof BountySubmissionExtendedSchema
>;
diff --git a/apps/web/lib/zod/schemas/partner-profile.ts b/apps/web/lib/zod/schemas/partner-profile.ts
index b681cab2e5..b2f684f652 100644
--- a/apps/web/lib/zod/schemas/partner-profile.ts
+++ b/apps/web/lib/zod/schemas/partner-profile.ts
@@ -319,6 +319,11 @@ export const PartnerBountySchema = BountySchema.omit({
}),
});
+// used in GET /partner-profile/bounties, which lists the bounties of all programs
+export const PartnerProfileBountySchema = PartnerBountySchema.extend({
+ program: PartnerProfileEarningsProgramSchema,
+});
+
export const invitePartnerUserSchema = z.object({
email: z.email({ error: "Please enter a valid email." }),
role: z.enum(PartnerRole),
diff --git a/apps/web/playwright/api/partner-profile/bounties.spec.ts b/apps/web/playwright/api/partner-profile/bounties.spec.ts
new file mode 100644
index 0000000000..bc48daad77
--- /dev/null
+++ b/apps/web/playwright/api/partner-profile/bounties.spec.ts
@@ -0,0 +1,289 @@
+import { createId } from "@/lib/api/create-id";
+import { hashToken } from "@/lib/auth/hash-token";
+import { prisma } from "@/lib/prisma";
+import { nanoid } from "@dub/utils";
+import { expect } from "@playwright/test";
+import { ProgramEnrollmentStatus } from "@prisma/client";
+import { createBearerApiClient, test } from "../fixtures";
+import { createPartner, deletePartner } from "../partners/helpers";
+
+type PartnerProfileBounty = {
+ id: string;
+ partner: { totalClicks: number; totalSaleAmount: number };
+ program: { id: string; name: string; slug: string };
+};
+
+const day = 24 * 60 * 60 * 1000;
+
+test.describe("GET /partner-profile/bounties", () => {
+ let partnerId: string | undefined;
+ let userId: string | undefined;
+ let token: string;
+
+ // each program is in its own workspace
+ const suffix = nanoid(8).toLowerCase();
+ const programs = [
+ { name: "Approved", status: "approved" },
+ { name: "Archived", status: "archived" },
+ { name: "Banned", status: "banned" },
+ // an approved enrollment in a deactivated program
+ { name: "Deactivated", status: "approved", deactivatedAt: new Date() },
+ ].map((program, i) => ({
+ ...program,
+ name: `PWB ${suffix} ${program.name}`,
+ status: program.status as ProgramEnrollmentStatus,
+ id: createId({ prefix: "prog_" }),
+ workspaceId: createId({ prefix: "ws_" }),
+ defaultGroupId: createId({ prefix: "grp_" }),
+ slug: `pw-bounties-${suffix}-${i}`,
+ }));
+
+ const [approved, archived, banned, deactivated] = programs;
+
+ const bountyId = () => createId({ prefix: "bnty_" });
+ const bounties = {
+ approved: bountyId(),
+ archivedBounty: bountyId(),
+ // an ended bounty stays visible because the partner has a submission on it
+ endedWithSubmission: bountyId(),
+ archivedEnrollment: bountyId(),
+ // limited to the partner's group, and to another group of the same program
+ partnerGroup: bountyId(),
+ otherGroup: bountyId(),
+ banned: bountyId(),
+ deactivated: bountyId(),
+ };
+
+ test.beforeAll(async ({ api }) => {
+ const { data: partner } = await createPartner(api);
+ partnerId = partner.id;
+
+ token = `dub_pw_${nanoid(24)}`;
+ const user = await prisma.user.create({
+ data: {
+ id: createId({ prefix: "user_" }),
+ email: partner.email,
+ emailVerified: new Date(),
+ defaultPartnerId: partner.id,
+ partners: {
+ create: {
+ partnerId: partner.id,
+ role: "owner",
+ },
+ },
+ tokens: {
+ create: {
+ name: "Playwright partner profile bounties",
+ hashedKey: await hashToken(token),
+ partialKey: `${token.slice(0, 3)}...${token.slice(-4)}`,
+ },
+ },
+ },
+ });
+ userId = user.id;
+
+ for (const program of programs) {
+ await prisma.project.create({
+ data: {
+ id: program.workspaceId,
+ name: program.name,
+ slug: program.slug,
+ billingCycleStart: 1,
+ },
+ });
+ await prisma.program.create({
+ data: {
+ id: program.id,
+ workspaceId: program.workspaceId,
+ name: program.name,
+ slug: program.slug,
+ defaultFolderId: createId({ prefix: "fold_" }),
+ defaultGroupId: program.defaultGroupId,
+ deactivatedAt: program.deactivatedAt,
+ },
+ });
+ await prisma.programEnrollment.create({
+ data: {
+ id: createId({ prefix: "pge_" }),
+ partnerId: partner.id,
+ programId: program.id,
+ status: program.status,
+ },
+ });
+ }
+
+ const activeBounty = (id: string, programId: string) => ({
+ id,
+ programId,
+ name: `PWB ${suffix} bounty`,
+ type: "submission" as const,
+ startsAt: new Date(Date.now() - day),
+ });
+
+ await prisma.bounty.createMany({
+ data: [
+ activeBounty(bounties.approved, approved.id),
+ {
+ ...activeBounty(bounties.archivedBounty, approved.id),
+ archivedAt: new Date(),
+ },
+ {
+ ...activeBounty(bounties.endedWithSubmission, approved.id),
+ startsAt: new Date(Date.now() - 10 * day),
+ endsAt: new Date(Date.now() - day),
+ },
+ activeBounty(bounties.archivedEnrollment, archived.id),
+ activeBounty(bounties.partnerGroup, approved.id),
+ activeBounty(bounties.otherGroup, approved.id),
+ activeBounty(bounties.banned, banned.id),
+ activeBounty(bounties.deactivated, deactivated.id),
+ ],
+ });
+
+ // the partner has no groupId, so they are in the program's default group
+ await prisma.bountyGroup.createMany({
+ data: [
+ { bountyId: bounties.partnerGroup, groupId: approved.defaultGroupId },
+ {
+ bountyId: bounties.otherGroup,
+ groupId: createId({ prefix: "grp_" }),
+ },
+ ],
+ });
+
+ await prisma.bountySubmission.create({
+ data: {
+ id: createId({ prefix: "bnty_sub_" }),
+ programId: approved.id,
+ partnerId: partner.id,
+ bountyId: bounties.endedWithSubmission,
+ },
+ });
+
+ // two links in the approved program, so the route sums their stats
+ await prisma.link.createMany({
+ data: [
+ { clicks: 3, saleAmount: 1000 },
+ { clicks: 4, saleAmount: 2500 },
+ ].map((stats) => {
+ const key = `pwb-${nanoid(8).toLowerCase()}`;
+
+ return {
+ ...stats,
+ id: createId({ prefix: "link_" }),
+ domain: "dub.sh",
+ key,
+ url: "https://dub.co",
+ shortLink: `https://dub.sh/${key}`,
+ projectId: approved.workspaceId,
+ programId: approved.id,
+ partnerId: partner.id,
+ };
+ }),
+ });
+ });
+
+ test.afterAll(async () => {
+ if (userId) await prisma.user.delete({ where: { id: userId } });
+ // deletePartner also deletes the partner's links
+ await deletePartner(partnerId);
+ // Prisma's emulated relations break these deletes, so use raw SQL like deletePartner
+ for (const program of programs) {
+ await prisma.$executeRaw`DELETE FROM BountySubmission WHERE programId = ${program.id}`;
+ await prisma.$executeRaw`DELETE FROM BountyGroup WHERE bountyId IN (SELECT id FROM Bounty WHERE programId = ${program.id})`;
+ await prisma.$executeRaw`DELETE FROM Bounty WHERE programId = ${program.id}`;
+ await prisma.$executeRaw`DELETE FROM Program WHERE id = ${program.id}`;
+ await prisma.$executeRaw`DELETE FROM Project WHERE id = ${program.workspaceId}`;
+ }
+ });
+
+ const withPartnerApi = async (
+ playwright: Parameters<typeof createBearerApiClient>[0]["playwright"],
+ run: (
+ partnerApi: Awaited<ReturnType<typeof createBearerApiClient>>["api"],
+ ) => Promise<void>,
+ ) => {
+ const { api: partnerApi, dispose } = await createBearerApiClient({
+ playwright,
+ token,
+ });
+ try {
+ await run(partnerApi);
+ } finally {
+ await dispose();
+ }
+ };
+
+ // only the bounties of this test, because the partner is also in the test workspace program
+ const testBounties = (data: PartnerProfileBounty[]) =>
+ data.filter((bounty) => Object.values(bounties).includes(bounty.id));
+
+ test("returns the bounties of approved and archived enrollments", async ({
+ playwright,
+ }) => {
+ await withPartnerApi(playwright, async (partnerApi) => {
+ const { status, data } = await partnerApi.get<PartnerProfileBounty[]>(
+ "/api/partner-profile/bounties",
+ );
+
+ expect(status).toEqual(200);
+ // no archived bounty, no bounty of another group, and no bounty of a banned enrollment or a deactivated program
+ expect(
+ testBounties(data)
+ .map(({ id }) => id)
+ .sort(),
+ ).toEqual(
+ [
+ bounties.approved,
+ bounties.endedWithSubmission,
+ bounties.archivedEnrollment,
+ bounties.partnerGroup,
+ ].sort(),
+ );
+ });
+ });
+
+ test("returns the program of each bounty", async ({ playwright }) => {
+ await withPartnerApi(playwright, async (partnerApi) => {
+ const { data } = await partnerApi.get<PartnerProfileBounty[]>(
+ "/api/partner-profile/bounties",
+ );
+
+ const bounty = data.find(({ id }) => id === bounties.archivedEnrollment);
+
+ expect(bounty?.program).toEqual({
+ id: archived.id,
+ name: archived.name,
+ slug: archived.slug,
+ logo: null,
+ });
+ });
+ });
+
+ test("sums the partner's link stats like the program bounties route", async ({
+ playwright,
+ }) => {
+ await withPartnerApi(playwright, async (partnerApi) => {
+ const { data: allPrograms } = await partnerApi.get<
+ PartnerProfileBounty[]
+ >("/api/partner-profile/bounties");
+ const { data: oneProgram } = await partnerApi.get<PartnerProfileBounty[]>(
+ `/api/partner-profile/programs/${approved.id}/bounties`,
+ );
+
+ const stats = (data: PartnerProfileBounty[]) =>
+ data.find(({ id }) => id === bounties.approved)?.partner;
+
+ expect(stats(allPrograms)).toMatchObject({
+ totalClicks: 7,
+ totalSaleAmount: 3500,
+ });
+ expect(stats(oneProgram)).toEqual(stats(allPrograms));
+ // a program without links gets zero stats
+ expect(
+ allPrograms.find(({ id }) => id === bounties.archivedEnrollment)
+ ?.partner,
+ ).toMatchObject({ totalClicks: 0, totalSaleAmount: 0 });
+ });
+ });
+});
diff --git a/apps/web/tests/bounties/partner-bounty-tabs.test.ts b/apps/web/tests/bounties/partner-bounty-tabs.test.ts
new file mode 100644
index 0000000000..82045c88d0
--- /dev/null
+++ b/apps/web/tests/bounties/partner-bounty-tabs.test.ts
@@ -0,0 +1,130 @@
+import {
+ countPartnerBountiesByTab,
+ getPartnerBountyTab,
+} from "@/lib/bounty/partner-bounty-tabs";
+import { PartnerBountyProps } from "@/lib/types";
+import { describe, expect, it } from "vitest";
+
+const day = 24 * 60 * 60 * 1000;
+
+const bounty = (
+ overrides: Partial<PartnerBountyProps> & {
+ submissionStatuses?: string[];
+ performanceCount?: number;
+ } = {},
+) => {
+ const { submissionStatuses = [], performanceCount, ...rest } = overrides;
+
+ return {
+ type: "submission",
+ endsAt: null,
+ maxSubmissions: 1,
+ performanceCondition: null,
+ submissions: submissionStatuses.map((status) => ({
+ status,
+ performanceCount: performanceCount ?? null,
+ })),
+ ...rest,
+ } as unknown as PartnerBountyProps;
+};
+
+describe("getPartnerBountyTab", () => {
+ it("puts a bounty without enough submissions in Active", () => {
+ expect(getPartnerBountyTab(bounty({ maxSubmissions: 2 }))).toBe("active");
+ });
+
+ it("does not count draft submissions", () => {
+ expect(getPartnerBountyTab(bounty({ submissionStatuses: ["draft"] }))).toBe(
+ "active",
+ );
+ });
+
+ it("puts a bounty with the maximum number of submissions in Completed", () => {
+ expect(
+ getPartnerBountyTab(bounty({ submissionStatuses: ["submitted"] })),
+ ).toBe("completed");
+ });
+
+ it("puts a performance bounty that reached its target in Completed", () => {
+ const performanceBounty = (performanceCount: number) =>
+ bounty({
+ type: "performance",
+ performanceCondition: {
+ attribute: "totalSaleAmount",
+ operator: "gte",
+ value: 100_000,
+ },
+ submissionStatuses: ["draft"],
+ performanceCount,
+ });
+
+ expect(getPartnerBountyTab(performanceBounty(50_000))).toBe("active");
+ expect(getPartnerBountyTab(performanceBounty(100_000))).toBe("completed");
+ });
+
+ it("keeps a performance bounty without a condition out of Completed", () => {
+ expect(
+ getPartnerBountyTab(
+ bounty({
+ type: "performance",
+ submissionStatuses: ["draft"],
+ performanceCount: 0,
+ }),
+ ),
+ ).toBe("active");
+ });
+
+ it("puts a performance bounty with a zero target in Completed", () => {
+ expect(
+ getPartnerBountyTab(
+ bounty({
+ type: "performance",
+ performanceCondition: {
+ attribute: "totalLeads",
+ operator: "gte",
+ value: 0,
+ },
+ submissionStatuses: ["draft"],
+ performanceCount: 0,
+ }),
+ ),
+ ).toBe("completed");
+ });
+
+ it("keeps a completed bounty in Completed after it ends", () => {
+ expect(
+ getPartnerBountyTab(
+ bounty({
+ endsAt: new Date(Date.now() - day),
+ submissionStatuses: ["approved"],
+ }),
+ ),
+ ).toBe("completed");
+ });
+
+ it("puts an ended bounty that the partner did not complete in Expired", () => {
+ expect(
+ getPartnerBountyTab(bounty({ endsAt: new Date(Date.now() - day) })),
+ ).toBe("expired");
+ });
+});
+
+describe("countPartnerBountiesByTab", () => {
+ it("counts every tab, with 0 for an empty or missing list", () => {
+ const empty = { active: 0, completed: 0, expired: 0 };
+
+ expect(countPartnerBountiesByTab(undefined)).toEqual(empty);
+ expect(countPartnerBountiesByTab([])).toEqual(empty);
+ });
+
+ it("counts each bounty in its tab", () => {
+ expect(
+ countPartnerBountiesByTab([
+ bounty(),
+ bounty({ maxSubmissions: 2, submissionStatuses: ["submitted"] }),
+ bounty({ submissionStatuses: ["approved"] }),
+ bounty({ endsAt: new Date(Date.now() - day) }),
+ ]),
+ ).toEqual({ active: 2, completed: 1, expired: 1 });
+ });
+});
diff --git a/apps/web/tests/bounties/rewards.test.ts b/apps/web/tests/bounties/rewards.test.ts
new file mode 100644
index 0000000000..7da89b6574
--- /dev/null
+++ b/apps/web/tests/bounties/rewards.test.ts
@@ -0,0 +1,87 @@
+import {
+ formatBountyRewardAmount,
+ getBountyRewardAmount,
+ getBountyRewardDescription,
+} from "@/lib/bounty/rewards";
+import { describe, expect, it } from "vitest";
+
+const fixedBounty = {
+ rewardAmount: 5_000,
+ rewardDescription: null,
+ submissionRequirements: null,
+};
+
+// $250 base, plus $10 for each 1,000 views between 1,000 and 6,000 views
+const bonusBounty = {
+ rewardAmount: 25_000,
+ rewardDescription: null,
+ submissionRequirements: {
+ socialMetrics: {
+ platform: "youtube" as const,
+ metric: "views" as const,
+ minCount: 1000,
+ incrementalBonus: {
+ incrementCount: 1000,
+ bonusPerIncrement: 1000,
+ maxCount: 6000,
+ },
+ },
+ },
+};
+
+const customBounty = {
+ rewardAmount: null,
+ rewardDescription: "A free product",
+ submissionRequirements: null,
+};
+
+describe("getBountyRewardAmount", () => {
+ it("returns the fixed reward", () => {
+ expect(getBountyRewardAmount(fixedBounty)).toEqual({
+ amount: 5_000,
+ isMaximum: false,
+ });
+ });
+
+ it("returns the cap of a bounty with an incremental bonus as a maximum", () => {
+ expect(getBountyRewardAmount(bonusBounty)).toEqual({
+ amount: 30_000,
+ isMaximum: true,
+ });
+ });
+
+ it("returns null for a bounty without an amount", () => {
+ expect(getBountyRewardAmount(customBounty)).toBeNull();
+ });
+});
+
+describe("formatBountyRewardAmount", () => {
+ it("formats a fixed amount", () => {
+ expect(formatBountyRewardAmount({ amount: 5_000, isMaximum: false })).toBe(
+ "$50",
+ );
+ });
+
+ it("formats a maximum amount", () => {
+ expect(formatBountyRewardAmount({ amount: 30_000, isMaximum: true })).toBe(
+ "Up to $300",
+ );
+ });
+
+ it("adds the prefix", () => {
+ expect(
+ formatBountyRewardAmount(
+ { amount: 30_000, isMaximum: true },
+ { prefix: "Earn" },
+ ),
+ ).toBe("Earn up to $300");
+ });
+});
+
+describe("getBountyRewardDescription", () => {
+ it("describes each kind of reward", () => {
+ expect(getBountyRewardDescription(fixedBounty)).toBe("Earn $50");
+ expect(getBountyRewardDescription(bonusBounty)).toBe("Earn up to $300");
+ expect(getBountyRewardDescription(customBounty)).toBe("A free product");
+ });
+});
diff --git a/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx b/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx
index 436618c215..bb3a39d1ae 100644
--- a/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx
+++ b/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx
@@ -3,12 +3,14 @@
import { useProgramMessagesCount } from "@/lib/messages/hooks/use-program-messages-count";
import { getGroupSubmittedLeadForm } from "@/lib/submitted-leads/get-group-submitted-lead-form";
import usePartnerProfile from "@/lib/swr/use-partner-profile";
+import { usePartnerProfileBounties } from "@/lib/swr/use-partner-profile-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 { MarketplaceSidebarFilters } from "@/ui/program-marketplace/marketplace-sidebar-filters";
import { ProgramMarketplaceCard } from "@/ui/program-marketplace/program-marketplace-card";
import { isMarketplaceFilterSidebarPath } from "@/ui/program-marketplace/utils/urls";
+import { formatTabBadgeCount } from "@/ui/shared/sheet-tabs";
import { type Icon, useMediaQuery, useRouterStuff } from "@dub/ui";
import {
Bell,
@@ -57,6 +59,7 @@ type SidebarNavData = {
invitationsCount?: number;
unreadMessagesCount?: number;
programBountiesCount?: number;
+ allBountiesCount?: number;
showDetailedAnalytics?: boolean;
postbacksEnabled?: boolean;
hasReferralReward?: boolean;
@@ -75,7 +78,7 @@ const NAV_GROUPS: SidebarNavGroups<SidebarNavData> = ({
icon: GridIcon,
// the middleware sends "/" to /overview or /programs, depending on the partner's programs
href: "/",
- active: ["/overview", "/programs", "/marketplace"].some((p) =>
+ active: ["/overview", "/programs", "/marketplace", "/bounties"].some((p) =>
pathname.startsWith(p),
),
},
@@ -107,9 +110,11 @@ const NAV_GROUPS: SidebarNavGroups<SidebarNavData> = ({
const PROGRAMS_CONTENT = ({
invitationsCount,
+ allBountiesCount,
}: {
invitationsCount?: number;
-}): { items: NavItemType[] }[] => [
+ allBountiesCount?: number;
+}): { name?: string; items: NavItemType[] }[] => [
{
items: [
{
@@ -132,21 +137,34 @@ const PROGRAMS_CONTENT = ({
},
],
},
+ {
+ name: "Engage",
+ items: [
+ {
+ name: "Bounties",
+ icon: Trophy,
+ href: "/bounties",
+ badge: formatTabBadgeCount(allBountiesCount),
+ },
+ ],
+ },
];
const NAV_AREAS: SidebarNavAreas<SidebarNavData> = {
// Top-level
- programs: ({ invitationsCount }) => ({
+ programs: ({ invitationsCount, allBountiesCount }) => ({
title: <PartnerProgramDropdown />,
- content: PROGRAMS_CONTENT({ invitationsCount }),
+ content: PROGRAMS_CONTENT({ invitationsCount, allBountiesCount }),
direction: "left",
}),
- marketplace: ({ isMobile, invitationsCount }) => ({
+ marketplace: ({ isMobile, invitationsCount, allBountiesCount }) => ({
title: <PartnerProgramDropdown />,
- content: isMobile
- ? PROGRAMS_CONTENT({ invitationsCount })
- : <MarketplaceSidebarFilters />,
+ content: isMobile ? (
+ PROGRAMS_CONTENT({ invitationsCount, allBountiesCount })
+ ) : (
+ <MarketplaceSidebarFilters />
+ ),
direction: "right",
}),
@@ -270,10 +288,7 @@ const NAV_AREAS: SidebarNavAreas<SidebarNavData> = {
name: "Bounties",
icon: Trophy,
href: `/programs/${programSlug}/bounties` as `/${string}`,
- badge:
- programBountiesCount && programBountiesCount > 99
- ? "99+"
- : programBountiesCount || undefined,
+ badge: formatTabBadgeCount(programBountiesCount),
locked: isUnapproved,
},
...(submittedLeadsEnabled
@@ -399,6 +414,12 @@ export function PartnersSidebarNav({
const { isMobile } = useMediaQuery();
+ // only load the bounties of all programs where the sidebar shows them
+ const { bountiesCount: allBountiesCount } = usePartnerProfileBounties({
+ enabled:
+ currentArea === "programs" || (currentArea === "marketplace" && isMobile),
+ });
+
const { partner } = usePartnerProfile();
const referralsActive =
@@ -441,6 +462,7 @@ export function PartnersSidebarNav({
invitationsCount,
unreadMessagesCount,
programBountiesCount: bountiesCount.active,
+ allBountiesCount: allBountiesCount.active,
showDetailedAnalytics,
postbacksEnabled: partner?.featureFlags?.postbacks,
hasReferralReward: !!programEnrollment?.referralRewardId,
diff --git a/apps/web/ui/partners/bounties/bounty-performance.tsx b/apps/web/ui/partners/bounties/bounty-performance.tsx
index 9c019003df..85f14aace8 100644
--- a/apps/web/ui/partners/bounties/bounty-performance.tsx
+++ b/apps/web/ui/partners/bounties/bounty-performance.tsx
@@ -11,10 +11,12 @@ export function PerformanceBountyProgress({
bounty,
labelClassName,
wrapperClassName,
+ hideBar,
}: {
bounty: PartnerBountyProps;
labelClassName?: string;
wrapperClassName?: string;
+ hideBar?: boolean;
}) {
const performanceCondition = bounty.performanceCondition;
@@ -47,6 +49,7 @@ export function PerformanceBountyProgress({
progress={percent}
labelClassName={labelClassName}
wrapperClassName={wrapperClassName}
+ hideBar={hideBar}
>
<EmphasisNumber>{formattedValue}</EmphasisNumber> of{" "}
<EmphasisNumber>{formattedTarget}</EmphasisNumber> {metricLabel} generated
@@ -59,11 +62,13 @@ export function SubmissionBountyProgress({
labelClassName,
wrapperClassName,
className,
+ hideBar,
}: {
bounty: PartnerBountyProps;
labelClassName?: string;
wrapperClassName?: string;
className?: string;
+ hideBar?: boolean;
}) {
const submittedCount = bounty.submissions.filter(
({ status }) => status !== "draft",
@@ -83,6 +88,7 @@ export function SubmissionBountyProgress({
progress={submittedPercent}
labelClassName={labelClassName}
wrapperClassName={wrapperClassName}
+ hideBar={hideBar}
>
<EmphasisNumber>{submittedCount}</EmphasisNumber> of{" "}
<EmphasisNumber>{maxSubmissions}</EmphasisNumber> submitted
@@ -91,6 +97,7 @@ export function SubmissionBountyProgress({
progress={approvedPercent}
labelClassName={labelClassName}
wrapperClassName={wrapperClassName}
+ hideBar={hideBar}
>
<EmphasisNumber>{approvedCount}</EmphasisNumber> approved
</BountyProgressBarRow>
diff --git a/apps/web/ui/partners/bounties/bounty-progress-bar-row.tsx b/apps/web/ui/partners/bounties/bounty-progress-bar-row.tsx
index 7bab3aa575..7ddcf32b21 100644
--- a/apps/web/ui/partners/bounties/bounty-progress-bar-row.tsx
+++ b/apps/web/ui/partners/bounties/bounty-progress-bar-row.tsx
@@ -14,11 +14,13 @@ export function BountyProgressBarRow({
children,
labelClassName,
wrapperClassName,
+ hideBar = false,
}: {
progress: number;
children: ReactNode;
labelClassName?: string;
wrapperClassName?: string;
+ hideBar?: boolean;
}) {
const percent = Math.min(Math.max(progress, 0), 100);
const isComplete = percent >= 100;
@@ -30,15 +32,17 @@ export function BountyProgressBarRow({
wrapperClassName ?? "gap-2",
)}
>
- <div className="bg-bg-emphasis h-1 w-full overflow-hidden rounded-full">
- <div
- className={cn(
- "h-full rounded-full",
- isComplete ? "bg-green-600" : "bg-amber-600",
- )}
- style={{ width: `${percent}%` }}
- />
- </div>
+ {!hideBar && (
+ <div className="bg-bg-emphasis h-1 w-full overflow-hidden rounded-full">
+ <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",
diff --git a/apps/web/ui/partners/bounties/bounty-status-badge.tsx b/apps/web/ui/partners/bounties/bounty-status-badge.tsx
index f8d32630f3..2444c6e024 100644
--- a/apps/web/ui/partners/bounties/bounty-status-badge.tsx
+++ b/apps/web/ui/partners/bounties/bounty-status-badge.tsx
@@ -1,3 +1,4 @@
+import { getPartnerBountyTab } from "@/lib/bounty/partner-bounty-tabs";
import { PartnerBountyProps } from "@/lib/types";
import { StatusBadge } from "@dub/ui";
import { formatDate } from "@dub/utils";
@@ -24,9 +25,24 @@ function getBountyBadgeState(
? formatDate(bounty.endsAt, { month: "short" })
: null;
- const isExpired = endsAt !== null && endsAt < now;
+ const tab = getPartnerBountyTab(bounty);
+
+ if (tab === "completed") {
+ const lastSubmission = bounty.submissions?.[0];
+ const isPendingReview =
+ bounty.type === "performance" && lastSubmission?.status === "submitted";
- if (isExpired) {
+ return {
+ status: "completed",
+ endsAtFormatted,
+ completedAtFormatted: formatDate(lastSubmission?.completedAt ?? now, {
+ month: "short",
+ }),
+ isPendingReview,
+ };
+ }
+
+ if (tab === "expired") {
return {
status: "expired",
endsAtFormatted,
@@ -49,28 +65,6 @@ function getBountyBadgeState(
};
}
- 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];
- const isPendingReview =
- bounty.type === "performance" && lastSubmission?.status === "submitted";
-
- return {
- status: "completed",
- endsAtFormatted,
- completedAtFormatted: formatDate(lastSubmission?.completedAt ?? now, {
- month: "short",
- }),
- isPendingReview,
- };
- }
-
const daysSinceStart = differenceInDays(now, startsAt);
const isNew = daysSinceStart <= NEW_BOUNTY_DAYS;
diff --git a/apps/web/ui/partners/bounties/partner-bounties-table.tsx b/apps/web/ui/partners/bounties/partner-bounties-table.tsx
new file mode 100644
index 0000000000..83e97d5f7c
--- /dev/null
+++ b/apps/web/ui/partners/bounties/partner-bounties-table.tsx
@@ -0,0 +1,229 @@
+"use client";
+
+import {
+ formatBountyRewardAmount,
+ getBountyRewardAmount,
+} from "@/lib/bounty/rewards";
+import { PartnerBountyProps, ProgramProps } from "@/lib/types";
+import { Table, useTable, useTablePagination } from "@dub/ui";
+import { formatDate } from "@dub/utils";
+import { ColumnDef } from "@tanstack/react-table";
+import { useRouter } from "next/navigation";
+import { useMemo, useState } from "react";
+import { ProgramLogo } from "../program-logo";
+import { BountyIncrementalBonusTooltip } from "./bounty-incremental-bonus-tooltip";
+import {
+ PerformanceBountyProgress,
+ SubmissionBountyProgress,
+} from "./bounty-performance";
+import { BountyThumbnailImage } from "./bounty-thumbnail-image";
+
+const PAGE_SIZE = 10;
+
+// the program is only set on the bounties of all programs
+export type PartnerBountyRow = PartnerBountyProps & {
+ program?: Pick<ProgramProps, "name" | "logo">;
+};
+
+type SortBy = "program" | "endsAt" | "rewardAmount";
+
+// sort values: bounties without an end date expire last, and bounties without an amount earn least
+const SORT_VALUES: Record<
+ SortBy,
+ (bounty: PartnerBountyRow) => number | string
+> = {
+ program: (bounty) => bounty.program?.name ?? "",
+ endsAt: (bounty) =>
+ bounty.endsAt ? new Date(bounty.endsAt).getTime() : Infinity,
+ rewardAmount: (bounty) => getBountyRewardAmount(bounty)?.amount ?? 0,
+};
+
+function compareSortValues(a: number | string, b: number | string) {
+ if (typeof a === "string" || typeof b === "string") {
+ return String(a).localeCompare(String(b));
+ }
+
+ const diff = a - b;
+ // two bounties without an end date give Infinity - Infinity
+ return Number.isNaN(diff) ? 0 : diff;
+}
+
+const PROGRAM_COLUMN: ColumnDef<PartnerBountyRow> = {
+ id: "program",
+ header: "Program",
+ minSize: 160,
+ cell: ({ row }) =>
+ row.original.program ? (
+ <div className="flex min-w-0 items-center gap-2">
+ <ProgramLogo program={row.original.program} />
+ <span className="truncate font-medium text-neutral-800">
+ {row.original.program.name}
+ </span>
+ </div>
+ ) : (
+ "-"
+ ),
+};
+
+const COLUMNS: ColumnDef<PartnerBountyRow>[] = [
+ {
+ id: "name",
+ header: "Bounty",
+ minSize: 240,
+ cell: ({ row }) => (
+ <div className="flex min-w-0 items-center gap-2">
+ <div className="bg-bg-subtle flex size-6 shrink-0 items-center justify-center rounded-md p-1">
+ <BountyThumbnailImage bounty={row.original} />
+ </div>
+ <span className="truncate font-medium text-neutral-800">
+ {row.original.name}
+ </span>
+ </div>
+ ),
+ },
+ {
+ id: "endsAt",
+ header: "Expires",
+ size: 140,
+ cell: ({ row }) =>
+ row.original.endsAt
+ ? formatDate(row.original.endsAt, { month: "short" })
+ : "-",
+ },
+ {
+ id: "progress",
+ header: "Progress",
+ minSize: 240,
+ cell: ({ row }) =>
+ row.original.type === "performance" ? (
+ <PerformanceBountyProgress bounty={row.original} hideBar />
+ ) : (
+ <SubmissionBountyProgress
+ bounty={row.original}
+ className="flex-row"
+ hideBar
+ />
+ ),
+ },
+ {
+ id: "rewardAmount",
+ header: "Earnings",
+ size: 160,
+ cell: ({ row }) => <BountyEarnings bounty={row.original} />,
+ },
+];
+
+// the compact list view of the partner bounties. The page loads every bounty, so the table sorts and pages them here
+export function PartnerBountiesTable<T extends PartnerBountyRow>({
+ bounties,
+ isLoading,
+ getHref,
+ resourceName,
+ showProgram = false,
+}: {
+ bounties?: T[];
+ isLoading?: boolean;
+ getHref: (bounty: T) => string;
+ resourceName: (plural: boolean) => string;
+ showProgram?: boolean;
+}) {
+ const router = useRouter();
+
+ const [sort, setSort] = useState<{
+ sortBy: SortBy;
+ sortOrder: "asc" | "desc";
+ }>({ sortBy: "endsAt", sortOrder: "asc" });
+
+ const { pagination, setPagination } = useTablePagination({
+ pageSize: PAGE_SIZE,
+ page: 1,
+ });
+
+ // compute each sort value once per bounty, not once per comparison
+ const sortedBounties = useMemo(() => {
+ const getValue = SORT_VALUES[sort.sortBy];
+ const direction = sort.sortOrder === "asc" ? 1 : -1;
+
+ return (bounties ?? [])
+ .map((bounty) => ({ bounty, value: getValue(bounty) }))
+ .sort((a, b) => compareSortValues(a.value, b.value) * direction)
+ .map(({ bounty }) => bounty);
+ }, [bounties, sort]);
+
+ const pageBounties = useMemo(
+ () =>
+ sortedBounties.slice(
+ (pagination.pageIndex - 1) * pagination.pageSize,
+ pagination.pageIndex * pagination.pageSize,
+ ),
+ [sortedBounties, pagination],
+ );
+
+ const columns = useMemo(
+ () =>
+ (showProgram ? [PROGRAM_COLUMN, ...COLUMNS] : COLUMNS) as ColumnDef<T>[],
+ [showProgram],
+ );
+
+ const { table, ...tableProps } = useTable({
+ data: pageBounties,
+ columns,
+ onRowClick: (row, e) => {
+ const href = getHref(row.original);
+
+ if (e.metaKey || e.ctrlKey) window.open(href, "_blank");
+ else router.push(href);
+ },
+ onRowAuxClick: (row) => window.open(getHref(row.original)),
+ pagination,
+ onPaginationChange: setPagination,
+ sortableColumns: [
+ ...(showProgram ? ["program"] : []),
+ "endsAt",
+ "rewardAmount",
+ ],
+ sortBy: sort.sortBy,
+ sortOrder: sort.sortOrder,
+ onSortChange: ({ sortBy, sortOrder }) => {
+ setSort((current) => {
+ const newSortBy = (sortBy as SortBy | undefined) ?? current.sortBy;
+
+ return {
+ sortBy: newSortBy,
+ // the table starts a new column at desc, but names read better A to Z on the first click
+ sortOrder:
+ newSortBy === "program" && current.sortBy !== "program"
+ ? "asc"
+ : sortOrder ?? current.sortOrder,
+ };
+ });
+ setPagination((current) => ({ ...current, pageIndex: 1 }));
+ },
+ containerClassName: "border-none",
+ thClassName: "border-l-0",
+ tdClassName: "border-l-0",
+ resourceName,
+ rowCount: bounties?.length ?? 0,
+ loading: isLoading,
+ });
+
+ return <Table {...tableProps} table={table} />;
+}
+
+function BountyEarnings({ bounty }: { bounty: PartnerBountyProps }) {
+ const reward = getBountyRewardAmount(bounty);
+
+ const label = reward
+ ? formatBountyRewardAmount(reward)
+ : bounty.rewardDescription || "-";
+
+ return (
+ <div className="flex min-w-0 items-center gap-1">
+ <span className="truncate">{label}</span>
+ <BountyIncrementalBonusTooltip
+ bounty={bounty}
+ onTooltipClick={(e) => e.stopPropagation()}
+ />
+ </div>
+ );
+}
diff --git a/apps/web/ui/partners/bounties/partner-bounties-view.tsx b/apps/web/ui/partners/bounties/partner-bounties-view.tsx
new file mode 100644
index 0000000000..7ab1e1f3ba
--- /dev/null
+++ b/apps/web/ui/partners/bounties/partner-bounties-view.tsx
@@ -0,0 +1,186 @@
+"use client";
+
+import {
+ getPartnerBountyTab,
+ PARTNER_BOUNTY_TABS,
+ PartnerBountyTab,
+} from "@/lib/bounty/partner-bounty-tabs";
+import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
+import { formatTabBadgeCount, SheetTabs } from "@/ui/shared/sheet-tabs";
+import { ToggleGroup, useLocalStorage, useRouterStuff } from "@dub/ui";
+import { GridIcon, Heart, TableRows2, Trophy } from "@dub/ui/icons";
+import { useMemo } from "react";
+import {
+ PartnerBountiesTable,
+ PartnerBountyRow,
+} from "./partner-bounties-table";
+import {
+ PartnerBountyCard,
+ PartnerBountyCardSkeleton,
+} from "./partner-bounty-card";
+import { PARTNER_BOUNTY_TAB_CONFIG } from "./partner-bounty-tab-config";
+
+type BountiesView = "grid" | "table";
+
+// without a saved view, the page starts on the table for partners with more
+// active bounties than this, the same rule as the Programs page
+const BOUNTIES_TABLE_VIEW_THRESHOLD = 6;
+
+// the bounty tabs with the grid and list views, for one program or for all programs
+export function PartnerBountiesView<T extends PartnerBountyRow>({
+ bounties,
+ bountiesCount,
+ isLoading,
+ getHref,
+ showProgram = false,
+}: {
+ bounties?: T[];
+ bountiesCount: Record<PartnerBountyTab, number>;
+ isLoading?: boolean;
+ getHref: (bounty: T) => string;
+ showProgram?: boolean;
+}) {
+ const { searchParams, queryParams } = useRouterStuff();
+
+ // null until the partner chooses a view with the toggle
+ const [savedView, setView] = useLocalStorage<BountiesView | null>(
+ "partner-bounties-view",
+ null,
+ );
+
+ const view: BountiesView =
+ savedView ??
+ (bountiesCount.active > BOUNTIES_TABLE_VIEW_THRESHOLD ? "table" : "grid");
+
+ const tab =
+ PARTNER_BOUNTY_TABS.find((id) => id === searchParams.get("tab")) ??
+ "active";
+
+ const tabBounties = useMemo(
+ () => bounties?.filter((bounty) => getPartnerBountyTab(bounty) === tab),
+ [bounties, tab],
+ );
+
+ return (
+ <div className="border-border-subtle overflow-clip rounded-xl border bg-neutral-100">
+ <SheetTabs
+ tabs={PARTNER_BOUNTY_TABS.map((id) => {
+ const config = PARTNER_BOUNTY_TAB_CONFIG[id];
+
+ return {
+ id,
+ label: config.label,
+ badge: config.showCount
+ ? formatTabBadgeCount(bountiesCount[id])
+ : undefined,
+ badgeClassName: config.badgeClassName,
+ };
+ })}
+ currentTabId={tab}
+ setCurrentTabId={(id) => queryParams({ set: { tab: id } })}
+ right={
+ <ToggleGroup
+ className="bg-bg-muted shrink-0 gap-0 rounded-lg p-0"
+ optionClassName="h-7 rounded-md px-1.5 py-0"
+ indicatorClassName="bg-bg-default -left-px -top-px h-[calc(100%+2px)] w-[calc(100%+2px)]"
+ options={[
+ {
+ value: "grid",
+ label: <GridIcon className="size-4" />,
+ },
+ {
+ value: "table",
+ label: <TableRows2 className="size-4" />,
+ },
+ ]}
+ selected={view}
+ selectAction={(option) => setView(option as BountiesView)}
+ />
+ }
+ />
+ <div className="border-border-subtle -mx-px -mb-px overflow-clip rounded-xl border bg-white">
+ {tabBounties?.length === 0 ? (
+ <BountiesEmptyState tab={tab} allPrograms={showProgram} />
+ ) : view === "table" ? (
+ <PartnerBountiesTable
+ key={tab}
+ bounties={tabBounties}
+ isLoading={isLoading}
+ getHref={getHref}
+ showProgram={showProgram}
+ resourceName={(plural) =>
+ PARTNER_BOUNTY_TAB_CONFIG[tab].resourceName[
+ plural ? "plural" : "singular"
+ ]
+ }
+ />
+ ) : (
+ <div className="grid grid-cols-1 gap-5 p-4 md:grid-cols-2 xl:grid-cols-3">
+ {tabBounties
+ ? tabBounties.map((bounty) => (
+ <PartnerBountyCard
+ key={bounty.id}
+ bounty={bounty}
+ href={getHref(bounty)}
+ program={showProgram ? bounty.program : undefined}
+ />
+ ))
+ : Array.from({ length: 3 }, (_, index) => (
+ <PartnerBountyCardSkeleton key={index} />
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function BountiesEmptyState({
+ tab,
+ allPrograms,
+}: {
+ tab: PartnerBountyTab;
+ allPrograms: boolean;
+}) {
+ const { title, showLearnMore, ...emptyState } =
+ PARTNER_BOUNTY_TAB_CONFIG[tab].emptyState;
+
+ const description =
+ (allPrograms && emptyState.allProgramsDescription) ||
+ emptyState.description;
+
+ return (
+ <div className="py-10">
+ <AnimatedEmptyState
+ title={title}
+ description={
+ showLearnMore ? (
+ <>
+ {description}{" "}
+ <a
+ href="https://dub.co/help/article/program-bounties"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="hover:text-content-default underline sm:whitespace-nowrap"
+ >
+ Learn more about bounties
+ </a>
+ .
+ </>
+ ) : (
+ description
+ )
+ }
+ cardContent={(idx) => {
+ const Icon = [Trophy, Heart][idx % 2];
+ return (
+ <>
+ <Icon className="size-4 text-neutral-700" />
+ <div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />
+ </>
+ );
+ }}
+ />
+ </div>
+ );
+}
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/bounty-card.tsx b/apps/web/ui/partners/bounties/partner-bounty-card.tsx
similarity index 83%
rename from apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/bounty-card.tsx
rename to apps/web/ui/partners/bounties/partner-bounty-card.tsx
index f360857363..9c2454906e 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/bounties/bounty-card.tsx
+++ b/apps/web/ui/partners/bounties/partner-bounty-card.tsx
@@ -1,12 +1,7 @@
-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 { isPartnerBountyExpired } from "@/lib/bounty/partner-bounty-tabs";
+import { PartnerBountyProps, ProgramProps } from "@/lib/types";
import { CommissionStatusBadges } from "@/ui/partners/commission-status-badges";
+import { ProgramLogo } from "@/ui/partners/program-logo";
import { buttonVariants, Table, TimestampTooltip, useTable } from "@dub/ui";
import { Calendar6 } from "@dub/ui/icons";
import {
@@ -17,6 +12,13 @@ import {
} from "@dub/utils";
import Link from "next/link";
import { useParams } from "next/navigation";
+import {
+ PerformanceBountyProgress,
+ SubmissionBountyProgress,
+} from "./bounty-performance";
+import { BountyRewardDescription } from "./bounty-reward-description";
+import { BountyStatusBadge } from "./bounty-status-badge";
+import { BountyThumbnailImage } from "./bounty-thumbnail-image";
export function PartnerBountyCard({
bounty,
@@ -25,6 +27,7 @@ export function PartnerBountyCard({
showRewards = false,
href,
onClick,
+ program,
}: {
bounty: PartnerBountyProps;
showFullTitle?: boolean;
@@ -32,6 +35,8 @@ export function PartnerBountyCard({
showRewards?: boolean;
href?: string;
onClick?: () => void;
+ // shown under the reward on the bounties of all programs
+ program?: Pick<ProgramProps, "name" | "logo">;
}) {
const { programSlug } = useParams();
const As = href ? Link : "div";
@@ -72,6 +77,13 @@ export function PartnerBountyCard({
onTooltipClick={(e) => e.stopPropagation()}
className="font-medium"
/>
+
+ {program && (
+ <div className="text-content-subtle mt-1 flex min-w-0 items-center gap-1.5 text-xs font-medium">
+ <ProgramLogo program={program} className="size-4" />
+ <span className="truncate">{program.name}</span>
+ </div>
+ )}
</div>
{!hideFooter && (
@@ -86,13 +98,13 @@ export function PartnerBountyCard({
{showRewards &&
bounty.submissions.some((s) => s.commissions.length > 0) && (
- <div className="@3xl/page:block border-border-subtle hidden border-t p-4">
- <BountyRewardsTable
- bounty={bounty}
- programSlug={programSlug as string}
- />
- </div>
- )}
+ <div className="@3xl/page:block border-border-subtle hidden border-t p-4">
+ <BountyRewardsTable
+ bounty={bounty}
+ programSlug={programSlug as string}
+ />
+ </div>
+ )}
</As>
);
}
@@ -172,8 +184,7 @@ export function BountyRewardsTable({
}
export function BountyEndDate({ bounty }: { bounty: PartnerBountyProps }) {
- const isExpired =
- bounty.endsAt && new Date(bounty.endsAt) < new Date() ? true : false;
+ const isExpired = isPartnerBountyExpired(bounty);
return (
<div className="text-content-subtle flex items-center gap-2 text-sm font-medium">
diff --git a/apps/web/ui/partners/bounties/partner-bounty-tab-config.ts b/apps/web/ui/partners/bounties/partner-bounty-tab-config.ts
new file mode 100644
index 0000000000..3140f4fcc8
--- /dev/null
+++ b/apps/web/ui/partners/bounties/partner-bounty-tab-config.ts
@@ -0,0 +1,58 @@
+import { PartnerBountyTab } from "@/lib/bounty/partner-bounty-tabs";
+
+interface PartnerBountyTabConfig {
+ label: string;
+ showCount: boolean;
+ badgeClassName?: string;
+ resourceName: { singular: string; plural: string };
+ emptyState: {
+ title: string;
+ description: string;
+ // the description on the bounties page of all programs, when it differs
+ allProgramsDescription?: string;
+ showLearnMore: boolean;
+ };
+}
+
+export const PARTNER_BOUNTY_TAB_CONFIG: Record<
+ PartnerBountyTab,
+ PartnerBountyTabConfig
+> = {
+ active: {
+ label: "Active",
+ showCount: true,
+ resourceName: { singular: "active bounty", plural: "active bounties" },
+ emptyState: {
+ title: "No bounties to collect",
+ description: "This program isn't offering any bounties at the moment.",
+ allProgramsDescription:
+ "Your programs aren't offering any bounties at the moment.",
+ showLearnMore: true,
+ },
+ },
+ completed: {
+ label: "Completed",
+ showCount: true,
+ badgeClassName: "bg-green-600",
+ resourceName: {
+ singular: "completed bounty",
+ plural: "completed bounties",
+ },
+ emptyState: {
+ title: "No completed bounties",
+ description: "Bounties you complete appear here.",
+ showLearnMore: false,
+ },
+ },
+ expired: {
+ label: "Expired",
+ // no count for Expired, as in the design
+ showCount: false,
+ resourceName: { singular: "expired bounty", plural: "expired bounties" },
+ emptyState: {
+ title: "No expired bounties",
+ description: "Bounties that ended before you completed them appear here.",
+ showLearnMore: false,
+ },
+ },
+};
diff --git a/apps/web/ui/shared/sheet-tabs.tsx b/apps/web/ui/shared/sheet-tabs.tsx
index 6e74a2850c..f7480eeee9 100644
--- a/apps/web/ui/shared/sheet-tabs.tsx
+++ b/apps/web/ui/shared/sheet-tabs.tsx
@@ -1,22 +1,25 @@
import { cn } from "@dub/utils";
import { LayoutGroup, motion } from "motion/react";
-import { ComponentType, SVGProps, useId } from "react";
+import { ComponentType, ReactNode, SVGProps, useId } from "react";
export type SheetTab = {
id: string;
label: string;
- icon: ComponentType<SVGProps<SVGSVGElement>>;
+ icon?: ComponentType<SVGProps<SVGSVGElement>>;
badge?: string | number;
+ badgeClassName?: string;
};
export function SheetTabs({
tabs,
currentTabId,
setCurrentTabId,
+ right,
}: {
tabs: SheetTab[];
currentTabId: string;
setCurrentTabId: (id: string) => void;
+ right?: ReactNode;
}) {
const layoutGroupId = useId();
@@ -24,7 +27,7 @@ export function SheetTabs({
<div className="scrollbar-hide relative z-0 flex items-center justify-between gap-1 overflow-x-auto p-2">
<LayoutGroup id={layoutGroupId}>
<div className="relative z-0 inline-flex items-center gap-1">
- {tabs.map(({ id, label, icon: Icon, badge }) => {
+ {tabs.map(({ id, label, icon: Icon, badge, badgeClassName }) => {
const isSelected = id === currentTabId;
return (
<button
@@ -39,10 +42,15 @@ export function SheetTabs({
badge && "pr-1",
)}
>
- <Icon className="size-4" />
+ {Icon && <Icon className="size-4" />}
<span>{label}</span>
{badge && (
- <span className="rounded-md bg-blue-600 px-2 py-0.5 text-xs font-semibold text-white">
+ <span
+ className={cn(
+ "rounded-md bg-blue-600 px-2 py-0.5 text-xs font-semibold text-white",
+ badgeClassName,
+ )}
+ >
{badge}
</span>
)}
@@ -60,6 +68,7 @@ export function SheetTabs({
})}
</div>
</LayoutGroup>
+ {right}
</div>
);
}
diff --git a/packages/utils/src/constants/reserved-slugs.ts b/packages/utils/src/constants/reserved-slugs.ts
index adf3ad241d..3524583d9e 100644
--- a/packages/utils/src/constants/reserved-slugs.ts
+++ b/packages/utils/src/constants/reserved-slugs.ts
@@ -67,4 +67,5 @@ export const RESERVED_SLUGS = [
"marketplace",
"fraud",
"overview",
+ "bounties",
];