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.

Support dynamic bounty periods based on partner enrollment dates.

Kiran K811f6a1d9c88
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
index 53520faca3..d06dc099ac 100644
--- a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
@@ -4,7 +4,7 @@ import { throwIfInvalidGroupIds } from "@/lib/api/groups/throw-if-invalid-group-
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
-import { bountyEligibilityIncludes } from "@/lib/bounty/api/bounty-eligibility";
+import { bountyEligibilityIncludes } from "@/lib/bounty/api/bounty-availability";
import { generatePerformanceBountyName } from "@/lib/bounty/api/generate-performance-bounty-name";
import { getBountyOrThrow } from "@/lib/bounty/api/get-bounty-or-throw";
import { getBountyWithDetails } from "@/lib/bounty/api/get-bounty-with-details";
diff --git a/apps/web/app/(ee)/api/bounties/route.ts b/apps/web/app/(ee)/api/bounties/route.ts
index b7e7aa2a00..88bfe2e456 100644
--- a/apps/web/app/(ee)/api/bounties/route.ts
+++ b/apps/web/app/(ee)/api/bounties/route.ts
@@ -10,7 +10,7 @@ import {
bountyEligibilityIncludes,
buildBountyEligibilityWhere,
getEffectiveBountyPeriod,
-} from "@/lib/bounty/api/bounty-eligibility";
+} from "@/lib/bounty/api/bounty-availability";
import { generatePerformanceBountyName } from "@/lib/bounty/api/generate-performance-bounty-name";
import { validateBounty } from "@/lib/bounty/api/validate-bounty";
import { qstash } from "@/lib/cron";
@@ -63,9 +63,7 @@ export const GET = withWorkspace(
where: {
programId,
...(programEnrollment && {
- ...buildBountyEligibilityWhere({
- groupId: partnerGroupId,
- }),
+ ...buildBountyEligibilityWhere(partnerGroupId),
}),
},
include: {
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 5ff1989bd6..bebc88a9dd 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
@@ -1,11 +1,16 @@
import { DubApiError } from "@/lib/api/errors";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
import { withPartnerProfile } from "@/lib/auth/partner";
+import { getEffectiveBountyPeriod } from "@/lib/bounty/api/bounty-availability";
+import { getBountyOrThrow } from "@/lib/bounty/api/get-bounty-or-throw";
+import { isBountyExpired, isBountyStarted } from "@/lib/bounty/bounty-period";
import { aggregatePartnerLinksStats } from "@/lib/partners/aggregate-partner-links-stats";
-import { prisma } from "@/lib/prisma";
import { PartnerBountySchema } from "@/lib/zod/schemas/partner-profile";
import { NextResponse } from "next/server";
+// TODO:
+// Allow partners to see a bounty if they have a submission
+
// 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;
@@ -20,11 +25,9 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {
},
});
- const bounty = await prisma.bounty.findUnique({
- where: {
- id: bountyId,
- programId: program.id,
- },
+ const bounty = await getBountyOrThrow({
+ programId,
+ bountyId,
include: {
workflow: {
select: {
@@ -50,27 +53,25 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {
},
});
- if (!bounty) {
- 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 (bounty.startsAt > new Date()) {
+ if (!partnerCanSeeBounty) {
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));
+ const { startsAt, endsAt } = getEffectiveBountyPeriod({
+ programEnrollment,
+ bounty,
+ });
- if (!partnerCanSeeBounty) {
+ if (!isBountyStarted(startsAt) || isBountyExpired(endsAt)) {
throw new DubApiError({
code: "not_found",
message: "Bounty not found.",
@@ -82,6 +83,8 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {
return NextResponse.json(
PartnerBountySchema.parse({
...bountyWithoutGroups,
+ startsAt,
+ endsAt,
performanceCondition: bounty.workflow?.triggerConditions?.[0] || null,
partner: {
...aggregatePartnerLinksStats(links),
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts b/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts
index d5502ff8e2..840b6083a0 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts
@@ -17,7 +17,6 @@ export const getReferralsEmbedData = async (token: string) => {
notFound();
}
- const now = new Date();
const programEnrollment = await getProgramEnrollmentOrThrow({
partnerId,
programId,
@@ -51,18 +50,6 @@ export const getReferralsEmbedData = async (token: string) => {
termsUrl: true,
embedData: true,
resources: true,
- _count: {
- select: {
- bounties: {
- where: {
- startsAt: {
- lte: now,
- },
- OR: [{ endsAt: null }, { endsAt: { gte: now } }],
- },
- },
- },
- },
},
},
links: true,
@@ -112,9 +99,7 @@ export const getReferralsEmbedData = async (token: string) => {
},
}),
- program._count.bounties > 0
- ? getBountiesForPartner(programEnrollment)
- : Promise.resolve([]),
+ getBountiesForPartner(programEnrollment),
]);
return {
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx
index b334839fcf..c22bfdd196 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx
@@ -1,19 +1,14 @@
"use client";
+import { getProgramBountyMeta } from "@/lib/bounty/bounty-period";
import useBounty from "@/lib/swr/use-bounty";
-import {
- SubmissionsCountByStatus,
- useBountySubmissionsCount,
-} from "@/lib/swr/use-bounty-submissions-count";
import useGroups from "@/lib/swr/use-groups";
-import { usePartnersCountByGroupIds } from "@/lib/swr/use-partners-count-by-groupids";
import useWorkspace from "@/lib/swr/use-workspace";
import { BountyRewardDescription } from "@/ui/partners/bounties/bounty-reward-description";
import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
import { GroupColorCircle } from "@/ui/partners/groups/group-color-circle";
import { ScrollableTooltipContent, Tooltip } from "@dub/ui";
import { Calendar6, Users, Users6 } from "@dub/ui/icons";
-import { formatDate, nFormatter, pluralize } from "@dub/utils";
import { useMemo } from "react";
import { BountyActionButton } from "../bounty-action-button";
@@ -21,28 +16,6 @@ export function BountyInfo() {
const { bounty, loading } = useBounty();
const { isOwner } = useWorkspace();
- const { submissionsCount } = useBountySubmissionsCount<
- SubmissionsCountByStatus[]
- >({
- ignoreParams: true,
- enabled: Boolean(bounty),
- });
-
- const totalSubmissions = useMemo(() => {
- return submissionsCount
- ?.filter((s) => s.status === "submitted" || s.status === "approved")
- ?.reduce((acc, curr) => acc + curr.count, 0);
- }, [submissionsCount]);
-
- const readyForReviewSubmissions = useMemo(() => {
- return submissionsCount?.find((s) => s.status === "submitted")?.count ?? 0;
- }, [submissionsCount]);
-
- const { totalPartners, loading: totalPartnersForBountyLoading } =
- usePartnersCountByGroupIds({
- groupIds: bounty?.groups?.map((group) => group.id) ?? [],
- });
-
const { groups } = useGroups();
const eligibleGroups = useMemo(() => {
@@ -62,6 +35,8 @@ export function BountyInfo() {
return null;
}
+ const { dateRangeLabel, partnerAudienceLabel } = getProgramBountyMeta(bounty);
+
return (
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:gap-6">
<div className="relative flex h-[100px] w-full items-center justify-center rounded-lg bg-neutral-100 p-4 sm:h-[128px] sm:w-[100px] sm:shrink-0">
@@ -80,63 +55,14 @@ export function BountyInfo() {
<div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
<Calendar6 className="size-4 shrink-0" />
- <span>
- {formatDate(bounty.startsAt, { month: "short" })}
- {" → "}
- {bounty.endsAt
- ? formatDate(bounty.endsAt, { month: "short" })
- : "No end date"}
- </span>
+ <span>{dateRangeLabel}</span>
</div>
<BountyRewardDescription bounty={bounty} className="font-regular" />
<div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
<Users className="size-4 shrink-0" />
- <div>
- {totalPartnersForBountyLoading ? (
- <span className="inline-block h-4 w-8 animate-pulse rounded bg-neutral-200 align-middle" />
- ) : totalPartners === 0 ? (
- <>
- <span className="text-content-default">0</span>{" "}
- {pluralize("partner", 0)}{" "}
- {bounty.type === "performance" ? "completed" : "submitted"}
- </>
- ) : totalSubmissions === totalPartners ? (
- <>
- All{" "}
- <span className="text-content-default">
- {nFormatter(totalPartners, { full: true })}
- </span>{" "}
- {pluralize("partner", totalPartners)}{" "}
- {bounty.type === "performance" ? "completed" : "submitted"}
- </>
- ) : (
- <>
- <span className="text-content-default">
- {nFormatter(totalSubmissions ?? 0, {
- full: true,
- })}
- </span>{" "}
- of{" "}
- <span className="text-content-default">
- {nFormatter(totalPartners, { full: true })}
- </span>{" "}
- {pluralize("partner", totalPartners)}{" "}
- {bounty.type === "performance" ? "completed" : "submitted"}
- </>
- )}
- {readyForReviewSubmissions > 0 && (
- <>
- {" "}
- (
- <span className="text-content-default">
- {nFormatter(readyForReviewSubmissions, { full: true })}
- </span>{" "}
- awaiting review)
- </>
- )}
- </div>
+ <span>{partnerAudienceLabel}</span>
</div>
{isOwner && (
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 c5499163d7..5d2600e9b1 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
@@ -21,7 +21,6 @@ import {
} from "@/ui/shared/inline-badge-popover";
import { MaxCharactersCounter } from "@/ui/shared/max-characters-counter";
import {
- AnimatedSizeContainer,
Button,
CalendarIcon,
CardSelector,
@@ -34,7 +33,6 @@ import {
RichTextProvider,
RichTextToolbar,
Sheet,
- SmartDateTimePicker,
Switch,
Tooltip,
TooltipContent,
@@ -45,6 +43,7 @@ import { BountySubmissionFrequency } from "@prisma/client";
import { Dispatch, SetStateAction, useState } from "react";
import { Controller, FormProvider } from "react-hook-form";
import { BountyCriteria } from "./bounty-criteria";
+import { BountyDuration } from "./bounty-duration";
import { useAddEditBountyForm } from "./use-add-edit-bounty-form";
interface BountySheetProps {
@@ -78,11 +77,12 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {
form,
openAccordions,
setOpenAccordions,
- hasStartDate,
- handleStartDateToggle,
hasEndDate,
- handleEndDateToggle,
- handleEndDateChange,
+ startsAt,
+ endsAt,
+ startMode,
+ endsAfterDays,
+ handleTimingChange,
allowedSubmissions,
handleAllowedSubmissionsChange,
maxAllowedSubmissions,
@@ -246,126 +246,16 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {
</div>
</div>
- <AnimatedSizeContainer
- height
- transition={{ ease: "easeInOut", duration: 0.2 }}
- style={{
- height: hasStartDate ? "auto" : "0px",
- overflow: "hidden",
+ <BountyDuration
+ isEditing={!!bounty}
+ value={{
+ startMode: startMode ?? "absolute",
+ startsAt: startsAt ? new Date(startsAt) : new Date(),
+ endsAt: endsAt ? new Date(endsAt) : null,
+ endsAfterDays: endsAfterDays ?? null,
}}
- >
- <div className="flex items-center gap-4">
- <Switch
- fn={handleStartDateToggle}
- checked={hasStartDate}
- trackDimensions="w-8 h-4"
- thumbDimensions="w-3 h-3"
- thumbTranslate="translate-x-4"
- disabled={Boolean(bounty?.startsAt)}
- />
- <Label>Start date</Label>
- </div>
-
- {hasStartDate && (
- <div className="mt-3 p-px">
- <Controller
- control={control}
- name="startsAt"
- render={({ field }) => (
- <SmartDateTimePicker
- value={field.value}
- onChange={(date) =>
- field.onChange(date ?? undefined)
- }
- placeholder='E.g. "2026-02-28", "Last Thursday", "2 hours ago"'
- />
- )}
- />
- </div>
- )}
- </AnimatedSizeContainer>
-
- {type === "performance" && (
- <AnimatedSizeContainer
- height
- transition={{ ease: "easeInOut", duration: 0.2 }}
- style={{
- height: hasEndDate ? "auto" : "0px",
- overflow: "hidden",
- }}
- >
- <div className="flex items-center gap-4">
- <Switch
- fn={handleEndDateToggle}
- checked={hasEndDate}
- trackDimensions="w-8 h-4"
- thumbDimensions="w-3 h-3"
- thumbTranslate="translate-x-4"
- disabled={Boolean(bounty?.endsAt)}
- />
- <Label>End date</Label>
- </div>
-
- {hasEndDate && (
- <div className="mt-3 p-px">
- <Controller
- control={control}
- name="endsAt"
- render={({ field }) => (
- <SmartDateTimePicker
- value={field.value}
- onChange={(date) =>
- handleEndDateChange(date ?? null)
- }
- placeholder='E.g. "2026-12-01", "Next Thursday", "After 10 days"'
- />
- )}
- />
- </div>
- )}
- </AnimatedSizeContainer>
- )}
-
- {type === "submission" && (
- <AnimatedSizeContainer
- height
- transition={{ ease: "easeInOut", duration: 0.2 }}
- style={{
- height: hasEndDate ? "auto" : "0px",
- overflow: "hidden",
- }}
- >
- <div className="flex items-center gap-4">
- <Switch
- fn={handleEndDateToggle}
- checked={hasEndDate}
- trackDimensions="w-8 h-4"
- thumbDimensions="w-3 h-3"
- thumbTranslate="translate-x-4"
- disabled={Boolean(bounty?.endsAt)}
- />
- <Label>End date</Label>
- </div>
-
- {hasEndDate && (
- <div className="mt-3 p-px">
- <Controller
- control={control}
- name="endsAt"
- render={({ field }) => (
- <SmartDateTimePicker
- value={field.value}
- onChange={(date) =>
- handleEndDateChange(date ?? null)
- }
- placeholder='E.g. "2026-12-01", "Next Thursday", "After 10 days"'
- />
- )}
- />
- </div>
- )}
- </AnimatedSizeContainer>
- )}
+ onChange={handleTimingChange}
+ />
{type === "submission" && (
<>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-duration.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-duration.tsx
new file mode 100644
index 0000000000..372381bc17
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-duration.tsx
@@ -0,0 +1,472 @@
+"use client";
+
+import {
+ BOUNTY_DURATION_DAYS,
+ BOUNTY_DURATION_PRESETS,
+ DurationPreset,
+ EndPreset,
+ resolveBountyTiming,
+ StartPreset,
+} from "@/lib/bounty/bounty-period";
+import {
+ InlineBadgePopover,
+ InlineBadgePopoverMenu,
+} from "@/ui/shared/inline-badge-popover";
+import { CalendarIcon, DatePicker } from "@dub/ui";
+import { formatDate } from "@dub/utils";
+import { addDays, addMonths, addWeeks } from "date-fns";
+import { useEffect, useState } from "react";
+
+type PresetOption<T extends string> = { value: T; label: string };
+type BountyTimingInput = ReturnType<typeof resolveBountyTiming>;
+type ParsedPresets = {
+ startPreset: StartPreset;
+ endPreset: EndPreset;
+ customStartsAt: Date | null;
+ customEndsAt: Date | null;
+ customEndsAfterDays: number | null;
+};
+
+const DURATION_LABELS: Record<DurationPreset, { start: string; end: string }> =
+ {
+ twoWeeks: { start: "in 2 weeks", end: "2 weeks" },
+ oneMonth: { start: "in 1 month", end: "1 month" },
+ sixMonths: { start: "in 6 months", end: "6 months" },
+ };
+
+const START_OPTIONS = [
+ { value: "today", label: "today" },
+ ...BOUNTY_DURATION_PRESETS.map((p) => ({
+ value: p,
+ label: DURATION_LABELS[p].start,
+ })),
+ { value: "onPartnerJoin", label: "when a new partner joins" },
+ { value: "custom", label: "custom" },
+] satisfies PresetOption<StartPreset>[];
+
+const END_OPTIONS = [
+ { value: "never", label: "never" },
+ ...BOUNTY_DURATION_PRESETS.map((p) => ({
+ value: p,
+ label: DURATION_LABELS[p].end,
+ })),
+ { value: "custom", label: "custom" },
+] satisfies PresetOption<EndPreset>[];
+
+const START_DURATION_DATES: Record<DurationPreset, (now: Date) => Date> = {
+ twoWeeks: (now) => addWeeks(now, 2),
+ oneMonth: (now) => addMonths(now, 1),
+ sixMonths: (now) => addMonths(now, 6),
+};
+
+const DATE_TOLERANCE_MS = 60_000;
+
+function datesAreClose(a: Date, b: Date, toleranceMs = DATE_TOLERANCE_MS) {
+ return Math.abs(a.getTime() - b.getTime()) <= toleranceMs;
+}
+
+function isSameCalendarDay(a: Date, b: Date) {
+ return (
+ a.getFullYear() === b.getFullYear() &&
+ a.getMonth() === b.getMonth() &&
+ a.getDate() === b.getDate()
+ );
+}
+
+function findDurationPresetByDays(days: number): DurationPreset | null {
+ return (
+ (Object.entries(BOUNTY_DURATION_DAYS) as [DurationPreset, number][]).find(
+ ([, durationDays]) => durationDays === days,
+ )?.[0] ?? null
+ );
+}
+
+function getPresetLabel<T extends string>(
+ preset: T,
+ options: PresetOption<T>[],
+ customDate?: Date | null,
+ fallback?: string,
+) {
+ if (preset === "custom" && customDate) {
+ return formatDate(customDate, { month: "short" });
+ }
+
+ return options.find((option) => option.value === preset)?.label ?? fallback;
+}
+
+function parsePresets(value: BountyTimingInput): ParsedPresets {
+ let startPreset: StartPreset;
+ let customStartsAt: Date | null;
+
+ if (value.startMode === "relative") {
+ startPreset = "onPartnerJoin";
+ customStartsAt = null;
+ } else {
+ const now = new Date();
+
+ if (isSameCalendarDay(value.startsAt, now)) {
+ startPreset = "today";
+ customStartsAt = null;
+ } else {
+ const matchedStartPreset = BOUNTY_DURATION_PRESETS.find((preset) =>
+ datesAreClose(value.startsAt, START_DURATION_DATES[preset](now)),
+ );
+
+ if (matchedStartPreset) {
+ startPreset = matchedStartPreset;
+ customStartsAt = null;
+ } else {
+ startPreset = "custom";
+ customStartsAt = value.startsAt;
+ }
+ }
+ }
+
+ let endPreset: EndPreset;
+ let customEndsAt: Date | null;
+
+ if (value.endsAfterDays != null) {
+ const durationPreset = findDurationPresetByDays(value.endsAfterDays);
+
+ if (durationPreset) {
+ return {
+ startPreset,
+ endPreset: durationPreset,
+ customStartsAt,
+ customEndsAt: null,
+ customEndsAfterDays: null,
+ };
+ }
+ }
+
+ if (!value.endsAt) {
+ endPreset = "never";
+ customEndsAt = null;
+ } else if (value.startMode === "absolute") {
+ const matchedEndPreset = (
+ Object.entries(BOUNTY_DURATION_DAYS) as [DurationPreset, number][]
+ ).find(([, days]) =>
+ datesAreClose(value.endsAt!, addDays(value.startsAt, days)),
+ )?.[0];
+
+ if (matchedEndPreset) {
+ endPreset = matchedEndPreset;
+ customEndsAt = null;
+ } else {
+ endPreset = "custom";
+ customEndsAt = value.endsAt;
+ }
+ } else {
+ endPreset = "custom";
+ customEndsAt = value.endsAt;
+ }
+
+ return {
+ startPreset,
+ endPreset,
+ customStartsAt,
+ customEndsAt,
+ customEndsAfterDays: null,
+ };
+}
+
+function parsePresetsForEdit(value: BountyTimingInput): ParsedPresets {
+ if (value.startMode === "relative") {
+ const startPreset: StartPreset = "onPartnerJoin";
+ const customStartsAt = null;
+
+ if (value.endsAfterDays != null) {
+ const durationPreset = findDurationPresetByDays(value.endsAfterDays);
+
+ if (durationPreset) {
+ return {
+ startPreset,
+ endPreset: durationPreset,
+ customStartsAt,
+ customEndsAt: null,
+ customEndsAfterDays: null,
+ };
+ }
+
+ return {
+ startPreset,
+ endPreset: "never",
+ customStartsAt,
+ customEndsAt: null,
+ customEndsAfterDays: value.endsAfterDays,
+ };
+ }
+
+ if (value.endsAt) {
+ return {
+ startPreset,
+ endPreset: "custom",
+ customStartsAt,
+ customEndsAt: value.endsAt,
+ customEndsAfterDays: null,
+ };
+ }
+
+ return {
+ startPreset,
+ endPreset: "never",
+ customStartsAt,
+ customEndsAt: null,
+ customEndsAfterDays: null,
+ };
+ }
+
+ const startPreset: StartPreset = "custom";
+ const customStartsAt = value.startsAt;
+
+ if (!value.endsAt) {
+ return {
+ startPreset,
+ endPreset: "never",
+ customStartsAt,
+ customEndsAt: null,
+ customEndsAfterDays: null,
+ };
+ }
+
+ return {
+ startPreset,
+ endPreset: "custom",
+ customStartsAt,
+ customEndsAt: value.endsAt,
+ customEndsAfterDays: null,
+ };
+}
+
+function parsePresetsFromValue(
+ value: BountyTimingInput,
+ isEditing: boolean,
+): ParsedPresets {
+ return isEditing ? parsePresetsForEdit(value) : parsePresets(value);
+}
+
+function CustomDatePickerIcon({
+ value,
+ onChange,
+}: {
+ value: Date | null | undefined;
+ onChange: (date: Date | null) => void;
+}) {
+ return (
+ <DatePicker
+ value={value ?? undefined}
+ onChange={(date) => {
+ if (!date) {
+ onChange(null);
+ return;
+ }
+
+ const merged = new Date(date);
+
+ if (value) {
+ merged.setHours(
+ value.getHours(),
+ value.getMinutes(),
+ value.getSeconds(),
+ value.getMilliseconds(),
+ );
+ }
+
+ onChange(merged);
+ }}
+ align="start"
+ showYearNavigation
+ trigger={() => (
+ <button
+ type="button"
+ className="inline-flex items-center rounded p-0.5 text-neutral-500 hover:bg-neutral-100 hover:text-neutral-700"
+ >
+ <CalendarIcon className="size-3.5" />
+ </button>
+ )}
+ />
+ );
+}
+
+interface BountyDurationProps {
+ value: BountyTimingInput;
+ onChange: (value: BountyTimingInput) => void;
+ isEditing?: boolean;
+}
+
+export function BountyDuration({
+ value,
+ onChange,
+ isEditing = false,
+}: BountyDurationProps) {
+ const initialPresets = parsePresetsFromValue(value, isEditing);
+
+ const [startPreset, setStartPreset] = useState<StartPreset>(
+ initialPresets.startPreset,
+ );
+
+ const [endPreset, setEndPreset] = useState<EndPreset>(
+ initialPresets.endPreset,
+ );
+
+ const [customStartsAt, setCustomStartsAt] = useState<Date | null>(
+ initialPresets.customStartsAt,
+ );
+
+ const [customEndsAt, setCustomEndsAt] = useState<Date | null>(
+ initialPresets.customEndsAt,
+ );
+
+ const [customEndsAfterDays, setCustomEndsAfterDays] = useState<number | null>(
+ initialPresets.customEndsAfterDays,
+ );
+
+ useEffect(() => {
+ const presets = parsePresetsFromValue(value, isEditing);
+ setStartPreset(presets.startPreset);
+ setEndPreset(presets.endPreset);
+ setCustomStartsAt(presets.customStartsAt);
+ setCustomEndsAt(presets.customEndsAt);
+ setCustomEndsAfterDays(presets.customEndsAfterDays);
+ }, [
+ isEditing,
+ value.startMode,
+ value.startsAt,
+ value.endsAt,
+ value.endsAfterDays,
+ ]);
+
+ const applyTiming = ({
+ nextStartPreset = startPreset,
+ nextEndPreset = endPreset,
+ nextCustomStartsAt = customStartsAt,
+ nextCustomEndsAt = customEndsAt,
+ }: {
+ nextStartPreset?: StartPreset;
+ nextEndPreset?: EndPreset;
+ nextCustomStartsAt?: Date | null;
+ nextCustomEndsAt?: Date | null;
+ } = {}) => {
+ onChange(
+ resolveBountyTiming({
+ startPreset: nextStartPreset,
+ endPreset: nextEndPreset,
+ customStartsAt: nextCustomStartsAt,
+ customEndsAt: nextCustomEndsAt,
+ }),
+ );
+ };
+
+ const startLabel = getPresetLabel(
+ startPreset,
+ START_OPTIONS,
+ customStartsAt ?? value.startsAt,
+ "today",
+ );
+
+ const endLabel =
+ customEndsAfterDays != null
+ ? `${customEndsAfterDays} days`
+ : getPresetLabel(
+ endPreset,
+ END_OPTIONS,
+ customEndsAt ?? value.endsAt,
+ "never",
+ );
+
+ const endSuffix =
+ customEndsAfterDays != null ||
+ (endPreset !== "never" && endPreset !== "custom")
+ ? value.startMode === "relative"
+ ? "after joining"
+ : "from start date"
+ : null;
+
+ return (
+ <div>
+ <div className="flex items-center gap-2.5 rounded-lg border border-neutral-200 bg-white px-3 py-2.5">
+ <CalendarIcon className="size-4 shrink-0 text-neutral-500" />
+ <span className="text-sm font-medium leading-relaxed text-neutral-800">
+ Starts{" "}
+ <span className="inline-flex items-center gap-0.5">
+ <InlineBadgePopover text={startLabel} buttonClassName="mx-0.5">
+ <InlineBadgePopoverMenu
+ items={START_OPTIONS.map((option) => ({
+ value: option.value,
+ text: option.label,
+ }))}
+ selectedValue={startPreset}
+ onSelect={(preset) => {
+ setStartPreset(preset);
+
+ if (preset === "custom") {
+ setCustomStartsAt(customStartsAt ?? value.startsAt);
+ return;
+ }
+
+ applyTiming({ nextStartPreset: preset });
+ }}
+ />
+ </InlineBadgePopover>
+ {startPreset === "custom" && (
+ <CustomDatePickerIcon
+ value={customStartsAt ?? value.startsAt}
+ onChange={(date) => {
+ const nextCustomStartsAt = date ?? null;
+ setCustomStartsAt(nextCustomStartsAt);
+ applyTiming({
+ nextStartPreset: "custom",
+ nextCustomStartsAt,
+ });
+ }}
+ />
+ )}
+ </span>{" "}
+ and ends{" "}
+ <span className="inline-flex items-center gap-0.5">
+ <InlineBadgePopover text={endLabel} buttonClassName="mx-0.5">
+ <InlineBadgePopoverMenu
+ items={END_OPTIONS.map((option) => ({
+ value: option.value,
+ text: option.label,
+ }))}
+ selectedValue={
+ customEndsAfterDays != null ? undefined : endPreset
+ }
+ onSelect={(preset) => {
+ setEndPreset(preset);
+ setCustomEndsAfterDays(null);
+
+ if (preset === "custom") {
+ setCustomEndsAt(
+ customEndsAt ??
+ value.endsAt ??
+ addWeeks(value.startsAt, 2),
+ );
+ return;
+ }
+
+ applyTiming({ nextEndPreset: preset });
+ }}
+ />
+ </InlineBadgePopover>
+ {endPreset === "custom" && (
+ <CustomDatePickerIcon
+ value={customEndsAt ?? value.endsAt}
+ onChange={(date) => {
+ const nextCustomEndsAt = date ?? null;
+ setCustomEndsAt(nextCustomEndsAt);
+ applyTiming({
+ nextEndPreset: "custom",
+ nextCustomEndsAt,
+ });
+ }}
+ />
+ )}
+ </span>
+ {endSuffix && <span> {endSuffix}</span>}
+ </span>
+ </div>
+ </div>
+ );
+}
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 5b425d1f7c..189c0b8bec 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,3 +1,4 @@
+import { getProgramBountyMeta } from "@/lib/bounty/bounty-period";
import { getBountyRewardDescription } from "@/lib/bounty/rewards";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import useGroups from "@/lib/swr/use-groups";
@@ -17,8 +18,8 @@ import {
Tooltip,
TooltipContent,
} from "@dub/ui";
-import { Users6 } from "@dub/ui/icons";
-import { formatDate, nFormatter, pluralize } from "@dub/utils";
+import { Users, Users6 } from "@dub/ui/icons";
+import { nFormatter, pluralize } from "@dub/utils";
import { cn } from "@dub/utils/src";
import { Dispatch, SetStateAction, useMemo, useState } from "react";
@@ -29,6 +30,8 @@ type ConfirmCreateBountyModalProps = {
| "name"
| "startsAt"
| "endsAt"
+ | "startMode"
+ | "endsAfterDays"
| "rewardAmount"
| "rewardDescription"
| "submissionRequirements"
@@ -79,7 +82,13 @@ function ConfirmCreateBountyModal({
}
};
- return bounty ? (
+ if (!bounty) {
+ return null;
+ }
+
+ const { dateRangeLabel, partnerAudienceLabel } = getProgramBountyMeta(bounty);
+
+ return (
<Modal
showModal={showConfirmCreateBountyModal}
setShowModal={setShowConfirmCreateBountyModal}
@@ -107,15 +116,7 @@ function ConfirmCreateBountyModal({
<div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
<Calendar6 className="size-3.5" />
- <span>
- {formatDate(bounty.startsAt, { month: "short" })}
- {bounty.endsAt && (
- <>
- {" → "}
- {formatDate(bounty.endsAt, { month: "short" })}
- </>
- )}
- </span>
+ <span>{dateRangeLabel}</span>
</div>
{!isOwner && (
@@ -127,6 +128,11 @@ function ConfirmCreateBountyModal({
</div>
)}
+ <div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
+ <Users className="size-3.5" />
+ <span>{partnerAudienceLabel}</span>
+ </div>
+
{isOwner && (
<div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
<Users6 className="size-3.5" />
@@ -236,7 +242,7 @@ function ConfirmCreateBountyModal({
/>
</div>
</Modal>
- ) : null;
+ );
}
export function useConfirmCreateBountyModal(
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 013e8ecc8f..e34639ab5b 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,6 +2,7 @@
import { isCurrencyAttribute } from "@/lib/api/workflows/utils";
import { generatePerformanceBountyName } from "@/lib/bounty/api/generate-performance-bounty-name";
+import { resolveBountyTiming } from "@/lib/bounty/bounty-period";
import {
BOUNTY_DESCRIPTION_MAX_LENGTH,
BOUNTY_MAX_SUBMISSIONS,
@@ -17,13 +18,18 @@ import {
} from "@/lib/zod/schemas/bounties";
import { formatDate } from "@dub/utils";
import { BountySubmissionFrequency } from "@prisma/client";
-import { Dispatch, SetStateAction, useEffect, useMemo, useState } from "react";
+import { addDays } from "date-fns";
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
-import {
- BountyTypeUI,
- CreateBountyInputExtended,
-} from "./bounty-form-context";
+import { BountyTypeUI, CreateBountyInputExtended } from "./bounty-form-context";
import { useConfirmCreateBountyModal } from "./confirm-create-bounty-modal";
const ACCORDION_ITEMS = [
@@ -50,6 +56,38 @@ const resolveSocialMetricsCriteria = (
const isEmpty = (value: unknown) =>
value === undefined || value === null || value === "";
+function getEffectiveEndsAt({
+ startsAt,
+ endsAt,
+ endsAfterDays,
+}: {
+ startsAt: Date;
+ endsAt: Date | null;
+ endsAfterDays: number | null;
+}) {
+ if (endsAt) {
+ return endsAt;
+ }
+
+ if (endsAfterDays != null) {
+ return addDays(startsAt, endsAfterDays);
+ }
+
+ return null;
+}
+
+function getSubmissionWindowFromBounty(bounty?: BountyProps): number | null {
+ if (!bounty?.submissionsOpenAt || !bounty?.endsAt) return null;
+
+ const days = Math.ceil(
+ (new Date(bounty.endsAt).getTime() -
+ new Date(bounty.submissionsOpenAt).getTime()) /
+ (1000 * 60 * 60 * 24),
+ );
+
+ return days >= 2 && days <= 14 ? days : null;
+}
+
export function useAddEditBountyForm({
bounty,
setIsOpen,
@@ -60,8 +98,14 @@ export function useAddEditBountyForm({
const { id: workspaceId } = useWorkspace();
const { makeRequest, isSubmitting } = useApiMutation<BountyProps>();
- const [hasStartDate, setHasStartDate] = useState(!!bounty?.startsAt);
- const [hasEndDate, setHasEndDate] = useState(!!bounty?.endsAt);
+ const defaultTiming = resolveBountyTiming({
+ startPreset: "today",
+ endPreset: "never",
+ });
+
+ const [hasEndDate, setHasEndDate] = useState(
+ !!bounty?.endsAt || !!bounty?.endsAfterDays,
+ );
const [openAccordions, setOpenAccordions] = useState(ACCORDION_ITEMS);
const [allowedSubmissions, setAllowedSubmissions] = useState<number>(
bounty?.maxSubmissions ?? 1,
@@ -71,16 +115,8 @@ export function useAddEditBountyForm({
bounty?.submissionFrequency ?? null,
);
- const [submissionWindow, setSubmissionWindow] = useState<number | null>(
- () => {
- if (!bounty?.submissionsOpenAt || !bounty?.endsAt) return null;
- const days = Math.ceil(
- (new Date(bounty.endsAt).getTime() -
- new Date(bounty.submissionsOpenAt).getTime()) /
- (1000 * 60 * 60 * 24),
- );
- return days >= 2 && days <= 14 ? days : null;
- },
+ const [submissionWindow, setSubmissionWindow] = useState<number | null>(() =>
+ getSubmissionWindowFromBounty(bounty),
);
const initialSubmissionRequirements = (() => {
@@ -106,8 +142,10 @@ export function useAddEditBountyForm({
defaultValues: {
name: bounty?.name || undefined,
description: bounty?.description || undefined,
- startsAt: bounty?.startsAt || undefined,
- endsAt: bounty?.endsAt || undefined,
+ startsAt: bounty?.startsAt || defaultTiming.startsAt,
+ endsAt: bounty?.endsAt ?? defaultTiming.endsAt,
+ startMode: bounty?.startMode ?? defaultTiming.startMode,
+ endsAfterDays: bounty?.endsAfterDays ?? defaultTiming.endsAfterDays,
submissionsOpenAt: bounty?.submissionsOpenAt || undefined,
rewardAmount: bounty?.rewardAmount
? bounty.rewardAmount / 100
@@ -154,6 +192,8 @@ export function useAddEditBountyForm({
const [
startsAt,
endsAt,
+ startMode,
+ endsAfterDays,
rewardAmount,
rewardDescription,
type,
@@ -167,6 +207,8 @@ export function useAddEditBountyForm({
] = watch([
"startsAt",
"endsAt",
+ "startMode",
+ "endsAfterDays",
"rewardAmount",
"rewardDescription",
"type",
@@ -179,50 +221,59 @@ export function useAddEditBountyForm({
"submissionRequirements",
]);
- const handleStartDateToggle = (checked: boolean) => {
- setHasStartDate(checked);
- if (!checked) {
- setValue("startsAt", null, { shouldDirty: true, shouldValidate: true });
- }
- };
+ const handleTimingChange = useCallback(
+ ({
+ startMode: nextStartMode,
+ startsAt: nextStartsAt,
+ endsAt: nextEndsAt,
+ endsAfterDays: nextEndsAfterDays,
+ }: ReturnType<typeof resolveBountyTiming>) => {
+ setValue("startMode", nextStartMode, {
+ shouldDirty: true,
+ shouldValidate: true,
+ });
- const handleEndDateToggle = (checked: boolean) => {
- setHasEndDate(checked);
- if (!checked) {
- setValue("endsAt", null, { shouldDirty: true, shouldValidate: true });
- setSubmissionWindow(null);
- setValue("submissionsOpenAt", null, { shouldDirty: true });
- }
- };
+ setValue("startsAt", nextStartsAt, {
+ shouldDirty: true,
+ shouldValidate: true,
+ });
- const handleEndDateChange = (date: Date | null) => {
- setValue("endsAt", date, {
- shouldDirty: true,
- shouldValidate: true,
- });
- if (date && submissionWindow != null) {
- const submissionsOpenAt = new Date(date);
- submissionsOpenAt.setDate(submissionsOpenAt.getDate() - submissionWindow);
- setValue("submissionsOpenAt", submissionsOpenAt, {
+ setValue("endsAt", nextEndsAt, {
shouldDirty: true,
shouldValidate: true,
});
- }
- };
- const getInitialSubmissionWindow = () => {
- if (!bounty?.submissionsOpenAt || !bounty?.endsAt) return null;
- const days = Math.ceil(
- (new Date(bounty.endsAt).getTime() -
- new Date(bounty.submissionsOpenAt).getTime()) /
- (1000 * 60 * 60 * 24),
- );
- return days >= 2 && days <= 14 ? days : null;
- };
+ setValue("endsAfterDays", nextEndsAfterDays, {
+ shouldDirty: true,
+ shouldValidate: true,
+ });
+
+ setHasEndDate(
+ Boolean(nextEndsAt) ||
+ (nextStartMode === "relative" && Boolean(nextEndsAfterDays)),
+ );
+
+ if (!nextEndsAt) {
+ setSubmissionWindow(null);
+ setValue("submissionsOpenAt", null, { shouldDirty: true });
+ } else if (submissionWindow != null) {
+ const submissionsOpenAt = new Date(nextEndsAt);
+ submissionsOpenAt.setDate(
+ submissionsOpenAt.getDate() - submissionWindow,
+ );
+
+ setValue("submissionsOpenAt", submissionsOpenAt, {
+ shouldDirty: true,
+ shouldValidate: true,
+ });
+ }
+ },
+ [setValue, submissionWindow],
+ );
const handleSubmissionWindowToggle = (checked: boolean) => {
if (checked) {
- const val = getInitialSubmissionWindow() ?? 2;
+ const val = getSubmissionWindowFromBounty(bounty) ?? 2;
setSubmissionWindow(val);
if (endsAt) {
const submissionsOpenAt = new Date(endsAt);
@@ -280,11 +331,21 @@ export function useAddEditBountyForm({
}
};
+ const effectiveEndsAt = useMemo(
+ () =>
+ getEffectiveEndsAt({
+ startsAt: startsAt ? new Date(startsAt) : new Date(),
+ endsAt: endsAt ? new Date(endsAt) : null,
+ endsAfterDays: endsAfterDays ?? null,
+ }),
+ [startsAt, endsAt, endsAfterDays],
+ );
+
const maxAllowedSubmissions = useMemo(() => {
- if (!submissionFrequency || !endsAt) return BOUNTY_MAX_SUBMISSIONS;
+ if (!submissionFrequency || !effectiveEndsAt) return BOUNTY_MAX_SUBMISSIONS;
const start = startsAt ? new Date(startsAt) : new Date();
- const end = new Date(endsAt);
+ const end = effectiveEndsAt;
let count = 0;
for (let i = 0; i < BOUNTY_MAX_SUBMISSIONS; i++) {
@@ -298,7 +359,7 @@ export function useAddEditBountyForm({
}
return count;
- }, [submissionFrequency, startsAt, endsAt]);
+ }, [submissionFrequency, startsAt, effectiveEndsAt]);
useEffect(() => {
if (allowedSubmissions > maxAllowedSubmissions) {
@@ -384,17 +445,21 @@ export function useAddEditBountyForm({
const effectiveStartDate = startsAt ? new Date(startsAt) : now;
- if (endsAt) {
- const endDate = new Date(endsAt);
+ const effectiveEndDate = endsAfterDays
+ ? addDays(effectiveStartDate, endsAfterDays)
+ : endsAt
+ ? new Date(endsAt)
+ : null;
- if (endDate <= effectiveStartDate) {
+ if (effectiveEndDate) {
+ if (effectiveEndDate <= effectiveStartDate) {
return `Please choose an end date that is after the start date (${formatDate(effectiveStartDate)}).`;
}
const minEndDate = new Date(
effectiveStartDate.getTime() + 60 * 60 * 1000,
);
- if (endDate < minEndDate) {
+ if (effectiveEndDate < minEndDate) {
return "End date must be at least 1 hour after the start date.";
}
}
@@ -459,7 +524,8 @@ export function useAddEditBountyForm({
if (!parsed.success) {
return (
- parsed.error.issues[0]?.message ?? "Invalid social metrics criteria."
+ parsed.error.issues[0]?.message ??
+ "Invalid social metrics criteria."
);
}
@@ -510,6 +576,7 @@ export function useAddEditBountyForm({
bounty,
startsAt,
endsAt,
+ endsAfterDays,
submissionWindow,
rewardAmount,
rewardDescription,
@@ -535,6 +602,11 @@ export function useAddEditBountyForm({
...data
} = form.getValues();
+ // Relative bounties start when a partner joins, so startsAt must be null
+ if (data.startMode === "relative") {
+ data.startsAt = null;
+ }
+
const rawRewardAmount = data.rewardAmount;
const numAmount =
typeof rawRewardAmount === "number" && !Number.isNaN(rawRewardAmount)
@@ -622,8 +694,10 @@ export function useAddEditBountyForm({
: performanceCondition,
})
: name || "New bounty",
- startsAt: startsAt || new Date(),
- endsAt: endsAt || null,
+ startsAt: startMode === "relative" ? null : startsAt || new Date(),
+ endsAt: startMode === "relative" ? null : effectiveEndsAt,
+ startMode: startMode ?? "absolute",
+ endsAfterDays: endsAfterDays ?? null,
rewardAmount: rewardAmount ? rewardAmount * 100 : null,
rewardDescription: rewardDescription || null,
submissionRequirements: submissionRequirements ?? null,
@@ -645,10 +719,7 @@ export function useAddEditBountyForm({
return {
form,
- hasStartDate,
- setHasStartDate,
hasEndDate,
- handleEndDateToggle,
openAccordions,
setOpenAccordions,
type,
@@ -660,8 +731,11 @@ export function useAddEditBountyForm({
watch,
errors,
isDirty,
- handleStartDateToggle,
- handleEndDateChange,
+ startsAt,
+ endsAt,
+ startMode,
+ endsAfterDays,
+ handleTimingChange,
allowedSubmissions,
handleAllowedSubmissionsChange,
maxAllowedSubmissions,
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx
index 4b09f0f695..8c81af4289 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx
@@ -1,7 +1,12 @@
+import { getProgramBountyMeta } from "@/lib/bounty/bounty-period";
import useGroups from "@/lib/swr/use-groups";
import { usePartnersCountByGroupIds } from "@/lib/swr/use-partners-count-by-groupids";
import useWorkspace from "@/lib/swr/use-workspace";
import { BountyListProps } from "@/lib/types";
+import {
+ BountyProgressBarRow,
+ EmphasisNumber,
+} from "@/ui/partners/bounties/bounty-progress-bar-row";
import { BountyRewardDescription } from "@/ui/partners/bounties/bounty-reward-description";
import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
import { GroupColorCircle } from "@/ui/partners/groups/group-color-circle";
@@ -12,7 +17,7 @@ import Link from "next/link";
import { useMemo } from "react";
export function BountyCard({ bounty }: { bounty: BountyListProps }) {
- const { slug: workspaceSlug, isOwner } = useWorkspace();
+ const { slug: workspaceSlug } = useWorkspace();
const { totalPartners, loading } = usePartnersCountByGroupIds({
groupIds: bounty.groups.map((group) => group.id),
@@ -20,6 +25,8 @@ export function BountyCard({ bounty }: { bounty: BountyListProps }) {
const { groups } = useGroups();
+ const { dateRangeLabel, partnerAudienceLabel } = getProgramBountyMeta(bounty);
+
const eligibleGroups = useMemo(() => {
if (!groups || bounty.groups.length === 0) {
return [];
@@ -29,134 +36,119 @@ export function BountyCard({ bounty }: { bounty: BountyListProps }) {
.filter((g): g is NonNullable<typeof g> => g !== undefined);
}, [groups, bounty.groups]);
+ const submissionsCount = bounty.submissionsCountData?.total ?? 0;
+ const progress =
+ totalPartners > 0 ? (submissionsCount / totalPartners) * 100 : 0;
+
return (
- <div className="border-border-subtle hover:border-border-default relative cursor-pointer rounded-xl border bg-white p-2 transition-all hover:shadow-lg">
+ <div className="border-border-subtle hover:border-border-default relative cursor-pointer rounded-xl border bg-white transition-all hover:shadow-lg">
<Link
href={`/${workspaceSlug}/program/bounties/${bounty.id}`}
- className="flex flex-col gap-3.5"
+ className="flex flex-col"
>
- <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>
+ <div className="flex flex-col gap-3.5 p-2 pb-0">
+ <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>
- <div className="absolute left-2 top-2 z-10 flex flex-col gap-1.5">
- {bounty.submissionsCountData &&
- bounty.submissionsCountData.submitted > 0 && (
- <SubmissionsCountBadge
- count={bounty.submissionsCountData.submitted}
- />
+ <div className="absolute left-2 top-2 z-10 flex flex-col gap-1.5">
+ {bounty.submissionsCountData &&
+ bounty.submissionsCountData.submitted > 0 && (
+ <SubmissionsCountBadge
+ count={bounty.submissionsCountData.submitted}
+ />
+ )}
+ {bounty.endsAt && new Date(bounty.endsAt) < new Date() && (
+ <BountyEndedBadge endsAt={bounty.endsAt} />
)}
- {bounty.endsAt && new Date(bounty.endsAt) < new Date() && (
- <BountyEndedBadge endsAt={bounty.endsAt} />
- )}
+ </div>
</div>
- </div>
- <div className="flex flex-col gap-1.5 px-2 pb-1.5">
- <h3 className="text-content-emphasis text-sm font-semibold md:truncate">
- {bounty.name}
- </h3>
-
- <div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
- <Calendar6 className="size-3.5" />
- <span>
- {formatDate(bounty.startsAt, { month: "short" })}
- {bounty.endsAt && (
- <>
- {" → "}
- {formatDate(bounty.endsAt, { month: "short" })}
- </>
- )}
- </span>
- </div>
+ <div className="flex flex-col gap-1.5 px-2 pb-3.5">
+ <h3 className="text-content-emphasis text-sm font-semibold md:truncate">
+ {bounty.name}
+ </h3>
+
+ <div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
+ <Calendar6 className="size-3.5" />
+ <span>{dateRangeLabel}</span>
+ </div>
+
+ <BountyRewardDescription
+ bounty={bounty}
+ className="font-regular"
+ onTooltipClick={(e) => e.preventDefault()}
+ />
- <BountyRewardDescription
- bounty={bounty}
- className="font-regular"
- onTooltipClick={(e) => e.preventDefault()}
- />
-
- <div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
- <Users className="size-3.5" />
- <div className="h-5">
- {loading ? (
- <span className="inline-block h-5 w-8 animate-pulse rounded bg-neutral-200 align-middle" />
- ) : totalPartners === 0 ? (
- <>
- <span className="text-content-default">0</span>{" "}
- {pluralize("partner", 0)}{" "}
- {bounty.type === "performance" ? "completed" : "submitted"}
- </>
- ) : bounty.submissionsCountData?.total === totalPartners ? (
- <>
- All{" "}
- <span className="text-content-default">
- {nFormatter(totalPartners, { full: true })}
- </span>{" "}
- {pluralize("partner", totalPartners)}{" "}
- {bounty.type === "performance" ? "completed" : "submitted"}
- </>
+ <div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
+ <Users className="size-3.5" />
+ <span>{partnerAudienceLabel}</span>
+ </div>
+
+ <div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
+ <Users6 className="size-3.5" />
+ {bounty.groups.length === 0 ? (
+ <span>All groups</span>
+ ) : eligibleGroups.length > 0 ? (
+ <DynamicTooltipWrapper
+ tooltipProps={
+ eligibleGroups.length > 1
+ ? {
+ content: (
+ <ScrollableTooltipContent>
+ {eligibleGroups.map((group) => (
+ <div
+ key={group.id}
+ className="flex items-center gap-2"
+ >
+ <GroupColorCircle group={group} />
+ <span className="font-regular text-sm text-neutral-700">
+ {group.name}
+ </span>
+ </div>
+ ))}
+ </ScrollableTooltipContent>
+ ),
+ }
+ : undefined
+ }
+ >
+ <div className="flex items-center gap-1.5">
+ <GroupColorCircle group={eligibleGroups[0]} />
+ <span className="truncate">
+ {eligibleGroups[0].name}{" "}
+ {eligibleGroups.length > 1
+ ? `+${eligibleGroups.length - 1}`
+ : ""}
+ </span>
+ </div>
+ </DynamicTooltipWrapper>
) : (
- <>
- <span className="text-content-default">
- {nFormatter(bounty.submissionsCountData?.total ?? 0, {
- full: true,
- })}
- </span>{" "}
- of{" "}
- <span className="text-content-default">
- {nFormatter(totalPartners, { full: true })}
- </span>{" "}
- {pluralize("partner", totalPartners)}{" "}
- {bounty.type === "performance" ? "completed" : "submitted"}
- </>
+ <div className="h-5 w-32 animate-pulse rounded bg-neutral-200" />
)}
</div>
</div>
+ </div>
- <div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
- <Users6 className="size-3.5" />
- {bounty.groups.length === 0 ? (
- <span>All groups</span>
- ) : eligibleGroups.length > 0 ? (
- <DynamicTooltipWrapper
- tooltipProps={
- eligibleGroups.length > 1
- ? {
- content: (
- <ScrollableTooltipContent>
- {eligibleGroups.map((group) => (
- <div
- key={group.id}
- className="flex items-center gap-2"
- >
- <GroupColorCircle group={group} />
- <span className="font-regular text-sm text-neutral-700">
- {group.name}
- </span>
- </div>
- ))}
- </ScrollableTooltipContent>
- ),
- }
- : undefined
- }
- >
- <div className="flex items-center gap-1.5">
- <GroupColorCircle group={eligibleGroups[0]} />
- <span className="truncate">
- {eligibleGroups[0].name}{" "}
- {eligibleGroups.length > 1
- ? `+${eligibleGroups.length - 1}`
- : ""}
- </span>
- </div>
- </DynamicTooltipWrapper>
- ) : (
- <div className="h-5 w-32 animate-pulse rounded bg-neutral-200" />
- )}
- </div>
+ <div className="border-border-subtle border-t px-4 py-3">
+ {loading ? (
+ <div className="flex flex-col gap-2">
+ <div className="h-1 w-full animate-pulse rounded-full bg-neutral-200" />
+ <div className="h-4 w-32 animate-pulse rounded bg-neutral-200" />
+ </div>
+ ) : (
+ <BountyProgressBarRow progress={progress}>
+ <EmphasisNumber>
+ {nFormatter(submissionsCount, { full: true })}
+ </EmphasisNumber>{" "}
+ of{" "}
+ <EmphasisNumber>
+ {nFormatter(totalPartners, { full: true })}
+ </EmphasisNumber>{" "}
+ {bounty.type === "performance" ? "completed" : "submitted"}
+ </BountyProgressBarRow>
+ )}
</div>
</Link>
</div>
@@ -181,10 +173,10 @@ function BountyEndedBadge({ endsAt }: { endsAt: Date }) {
export function BountyCardSkeleton() {
return (
- <div className="border-border-subtle rounded-xl border bg-white p-2">
- <div className="flex flex-col gap-3.5">
+ <div className="border-border-subtle rounded-xl border bg-white">
+ <div className="flex flex-col gap-3.5 p-2 pb-0">
<div className="relative flex h-[124px] animate-pulse items-center justify-center rounded-lg bg-neutral-200" />
- <div className="flex flex-col gap-1.5 px-2 pb-1.5">
+ <div className="flex flex-col gap-1.5 px-2 pb-3.5">
<div className="h-5 w-48 animate-pulse rounded bg-neutral-200" />
<div className="flex h-5 items-center gap-2">
<div className="size-3.5 shrink-0 animate-pulse rounded bg-neutral-200" />
@@ -192,7 +184,11 @@ export function BountyCardSkeleton() {
</div>
<div className="flex h-5 items-center gap-2">
<div className="size-3.5 shrink-0 animate-pulse rounded bg-neutral-200" />
- <div className="h-5 w-48 animate-pulse rounded bg-neutral-200" />
+ <div className="h-5 w-24 animate-pulse rounded bg-neutral-200" />
+ </div>
+ <div className="flex h-5 items-center gap-2">
+ <div className="size-3.5 shrink-0 animate-pulse rounded bg-neutral-200" />
+ <div className="h-5 w-28 animate-pulse rounded bg-neutral-200" />
</div>
<div className="flex h-5 items-center gap-2">
<div className="size-3.5 shrink-0 animate-pulse rounded bg-neutral-200" />
@@ -200,6 +196,12 @@ export function BountyCardSkeleton() {
</div>
</div>
</div>
+ <div className="border-border-subtle border-t px-4 py-3">
+ <div className="flex flex-col gap-2">
+ <div className="h-1 w-full animate-pulse rounded-full bg-neutral-200" />
+ <div className="h-4 w-32 animate-pulse rounded bg-neutral-200" />
+ </div>
+ </div>
</div>
);
}
diff --git a/apps/web/lib/bounty/api/bounty-eligibility.ts b/apps/web/lib/bounty/api/bounty-availability.ts
similarity index 67%
rename from apps/web/lib/bounty/api/bounty-eligibility.ts
rename to apps/web/lib/bounty/api/bounty-availability.ts
index 28b518e445..6b8b0ac6a7 100644
--- a/apps/web/lib/bounty/api/bounty-eligibility.ts
+++ b/apps/web/lib/bounty/api/bounty-availability.ts
@@ -1,11 +1,9 @@
import { Bounty, Prisma, ProgramEnrollment } from "@prisma/client";
import { addDays } from "date-fns";
-export function buildBountyEligibilityWhere({
- groupId,
-}: {
- groupId: string | undefined;
-}): Prisma.BountyWhereInput {
+export function buildBountyEligibilityWhere(
+ groupId: string | undefined,
+): Prisma.BountyWhereInput {
return {
OR: [
{
@@ -56,3 +54,23 @@ export function getEffectiveBountyPeriod({
endsAt: endsAfterDays ? addDays(bountyStartDate, endsAfterDays) : endsAt,
};
}
+
+export const canPartnerSeeBounty = ({
+ programEnrollment,
+ bounty,
+}: {
+ programEnrollment: Pick<ProgramEnrollment, "groupJoinedAt" | "createdAt">;
+ bounty: Pick<Bounty, "startsAt" | "endsAt" | "endsAfterDays" | "startMode">;
+}) => {
+ //
+};
+
+export const canPartnerSubmitToBounty = ({
+ programEnrollment,
+ bounty,
+}: {
+ programEnrollment: Pick<ProgramEnrollment, "groupJoinedAt" | "createdAt">;
+ bounty: Pick<Bounty, "startsAt" | "endsAt" | "endsAfterDays" | "startMode">;
+}) => {
+ //
+};
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 75c31aa560..e846f401ef 100644
--- a/apps/web/lib/bounty/api/get-bounties-for-partner.ts
+++ b/apps/web/lib/bounty/api/get-bounties-for-partner.ts
@@ -6,44 +6,69 @@ import { prisma } from "@/lib/prisma";
import { PartnerBountySchema } from "@/lib/zod/schemas/partner-profile";
import { Program, ProgramEnrollment } from "@prisma/client";
import * as z from "zod/v4";
+import {
+ buildBountyEligibilityWhere,
+ getEffectiveBountyPeriod,
+} from "./bounty-availability";
type GetBountiesForPartnerParams = Pick<
ProgramEnrollment,
- "groupId" | "partnerId" | "totalCommissions"
+ "groupId" | "partnerId" | "totalCommissions" | "groupJoinedAt" | "createdAt"
> & {
links: PartnerLink[];
program: Pick<Program, "id" | "defaultGroupId">;
};
-export async function getBountiesForPartner(
- params: GetBountiesForPartnerParams,
-) {
- const { groupId, partnerId, totalCommissions, program, links } = params;
-
+export async function getBountiesForPartner({
+ partnerId,
+ groupId,
+ totalCommissions,
+ createdAt,
+ groupJoinedAt,
+ program,
+ links,
+}: GetBountiesForPartnerParams) {
const now = new Date();
+ const partnerGroupId = groupId || program.defaultGroupId;
const bounties = await prisma.bounty.findMany({
where: {
programId: program.id,
- startsAt: {
- lte: now,
- },
- // If bounty has no groups, it's available to all partners
- // If bounty has groups, only partners in those groups can see it
+ archivedAt: null,
OR: [
+ // Relative bounties start when a partner joins (no startsAt filter).
{
- groups: {
- none: {},
+ startMode: "relative",
+ },
+
+ // Absolute bounties must have started and not expired.
+ {
+ startMode: "absolute",
+ startsAt: {
+ lt: now,
},
+ OR: [
+ {
+ endsAt: null,
+ },
+ {
+ endsAt: {
+ gt: now,
+ },
+ },
+ ],
},
+
+ // Bounties the partner has a submission on stay visible
{
- groups: {
+ submissions: {
some: {
- groupId: groupId || program.defaultGroupId,
+ partnerId,
},
},
},
],
+ ...buildBountyEligibilityWhere(partnerGroupId),
},
include: {
workflow: {
@@ -72,13 +97,28 @@ export async function getBountiesForPartner(
const partnerLinkStats = aggregatePartnerLinksStats(links);
return z.array(PartnerBountySchema).parse(
- bounties.map((bounty) => ({
- ...bounty,
- performanceCondition: bounty.workflow?.triggerConditions?.[0] || null,
- partner: {
- ...partnerLinkStats,
- totalCommissions,
- },
- })),
+ bounties.map((bounty) => {
+ const performanceCondition =
+ bounty.workflow?.triggerConditions?.[0] || null;
+
+ const { startsAt, endsAt } = getEffectiveBountyPeriod({
+ programEnrollment: {
+ createdAt,
+ groupJoinedAt,
+ },
+ bounty,
+ });
+
+ return {
+ ...bounty,
+ startsAt,
+ endsAt,
+ performanceCondition,
+ partner: {
+ ...partnerLinkStats,
+ totalCommissions,
+ },
+ };
+ }),
);
}
diff --git a/apps/web/lib/bounty/bounty-period.ts b/apps/web/lib/bounty/bounty-period.ts
new file mode 100644
index 0000000000..a3116f04a4
--- /dev/null
+++ b/apps/web/lib/bounty/bounty-period.ts
@@ -0,0 +1,136 @@
+import { formatDate } from "@dub/utils";
+import { BountyStartMode } from "@prisma/client";
+import { addDays, addMonths, addWeeks } from "date-fns";
+
+export const BOUNTY_DURATION_PRESETS = [
+ "twoWeeks",
+ "oneMonth",
+ "sixMonths",
+] as const;
+
+export type DurationPreset = (typeof BOUNTY_DURATION_PRESETS)[number];
+
+export const BOUNTY_DURATION_DAYS: Record<DurationPreset, number> = {
+ twoWeeks: 14,
+ oneMonth: 30,
+ sixMonths: 180,
+};
+
+const ENDS_AFTER_DAYS_LABELS: Record<number, string> = {
+ [BOUNTY_DURATION_DAYS.twoWeeks]: "2 weeks",
+ [BOUNTY_DURATION_DAYS.oneMonth]: "1 month",
+ [BOUNTY_DURATION_DAYS.sixMonths]: "6 months",
+};
+
+export type StartPreset = "today" | DurationPreset | "onPartnerJoin" | "custom";
+export type EndPreset = "never" | DurationPreset | "custom";
+
+export function resolveBountyTiming({
+ startPreset,
+ endPreset,
+ customStartsAt,
+ customEndsAt,
+}: {
+ startPreset: StartPreset;
+ endPreset: EndPreset;
+ customStartsAt?: Date | null;
+ customEndsAt?: Date | null;
+}) {
+ const now = new Date();
+
+ let startMode: BountyStartMode = "absolute";
+ let startsAt = now;
+
+ switch (startPreset) {
+ case "today":
+ startsAt = now;
+ break;
+ case "twoWeeks":
+ startsAt = addWeeks(now, 2);
+ break;
+ case "oneMonth":
+ startsAt = addMonths(now, 1);
+ break;
+ case "sixMonths":
+ startsAt = addMonths(now, 6);
+ break;
+ case "onPartnerJoin":
+ startMode = "relative";
+ startsAt = now;
+ break;
+ case "custom":
+ startsAt = customStartsAt ?? now;
+ break;
+ }
+
+ let endsAt: Date | null = null;
+ let endsAfterDays: number | null = null;
+
+ switch (endPreset) {
+ case "never":
+ break;
+ case "twoWeeks":
+ case "oneMonth":
+ case "sixMonths":
+ if (startMode === "absolute") {
+ endsAt = addDays(startsAt, BOUNTY_DURATION_DAYS[endPreset]);
+ } else {
+ endsAfterDays = BOUNTY_DURATION_DAYS[endPreset];
+ }
+ break;
+ case "custom":
+ endsAt = customEndsAt ?? null;
+ break;
+ }
+
+ return {
+ startMode,
+ startsAt,
+ endsAt,
+ endsAfterDays,
+ };
+}
+
+export function isBountyStarted(startsAt: Date) {
+ return startsAt <= new Date();
+}
+
+export function isBountyExpired(endsAt: Date | null) {
+ return endsAt !== null && endsAt <= new Date();
+}
+
+export function getProgramBountyMeta({
+ startsAt,
+ endsAt,
+ startMode,
+ endsAfterDays,
+}: {
+ startsAt: Date | null;
+ endsAt: Date | null;
+ startMode: BountyStartMode;
+ endsAfterDays: number | null;
+}) {
+ const isRelative = startMode === "relative" || !startsAt;
+
+ let dateRangeLabel: string;
+
+ if (isRelative) {
+ if (endsAfterDays != null) {
+ const durationLabel =
+ ENDS_AFTER_DAYS_LABELS[endsAfterDays] ?? `${endsAfterDays} days`;
+ dateRangeLabel = `${durationLabel} after joining`;
+ } else {
+ dateRangeLabel = "when a new partner joins";
+ }
+ } else {
+ const startLabel = formatDate(startsAt, { month: "short" });
+ dateRangeLabel = endsAt
+ ? `${startLabel} → ${formatDate(endsAt, { month: "short" })}`
+ : startLabel;
+ }
+
+ return {
+ dateRangeLabel,
+ partnerAudienceLabel: isRelative ? "New partners only" : "All partners",
+ };
+}