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 relative bounty start dates on create and update

Kiran K5a02d8d3a1f3
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
index a89c393493..53520faca3 100644
--- a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
@@ -4,7 +4,9 @@ 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 { 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";
import { PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES } from "@/lib/bounty/api/performance-bounty-scope-attributes";
import { validateBounty } from "@/lib/bounty/api/validate-bounty";
@@ -54,6 +56,8 @@ export const PATCH = withWorkspace(
description,
startsAt,
endsAt,
+ startMode,
+ endsAfterDays,
submissionsOpenAt,
submissionFrequency,
maxSubmissions,
@@ -64,26 +68,41 @@ export const PATCH = withWorkspace(
groupIds,
} = updateBountySchema.parse(await parseRequestBody(req));
- const bounty = await prisma.bounty.findUniqueOrThrow({
- where: {
- id: bountyId,
- programId,
- },
+ const bounty = await getBountyOrThrow({
+ bountyId,
+ programId,
include: {
- groups: true,
workflow: true,
_count: {
select: {
submissions: true,
},
},
+ ...bountyEligibilityIncludes,
},
});
+ const nextStartMode =
+ startMode !== undefined ? startMode : bounty.startMode;
+
validateBounty({
type: bounty.type,
- startsAt,
+ // Relative bounties never store startsAt; coerce so mode switches don't
+ // fail validation against a leftover absolute startsAt.
+ startsAt:
+ nextStartMode === "relative"
+ ? null
+ : startsAt !== undefined
+ ? startsAt
+ : bounty.startsAt,
endsAt: endsAt !== undefined ? endsAt : bounty.endsAt,
+ startMode: nextStartMode,
+ endsAfterDays:
+ endsAfterDays !== undefined
+ ? endsAfterDays
+ : nextStartMode === "absolute"
+ ? null
+ : bounty.endsAfterDays,
submissionsOpenAt,
submissionFrequency:
submissionFrequency !== undefined
@@ -113,17 +132,22 @@ export const PATCH = withWorkspace(
// if groupIds is provided and is different from the current groupIds, update the groups
let updatedPartnerGroups: PartnerGroup[] | undefined = undefined;
- if (
- groupIds &&
- !arrayEqual(
- bounty.groups.map((group) => group.groupId),
- groupIds,
- )
- ) {
- updatedPartnerGroups = await throwIfInvalidGroupIds({
- programId,
- groupIds,
- });
+ let shouldUpdatePartnerGroups = false;
+
+ if (groupIds !== undefined) {
+ const currentGroupIds = bounty.groups.map((group) => group.groupId);
+ const newGroupIds = groupIds || [];
+
+ if (!arrayEqual(currentGroupIds, newGroupIds)) {
+ if (newGroupIds.length > 0) {
+ updatedPartnerGroups = await throwIfInvalidGroupIds({
+ programId,
+ groupIds: newGroupIds,
+ });
+ }
+
+ shouldUpdatePartnerGroups = true;
+ }
}
// Prevent updates if `performanceCondition.attribute` differs from the current value if there are existing submissions
@@ -179,6 +203,19 @@ export const PATCH = withWorkspace(
});
}
+ // Relative bounties start when a partner joins, so startsAt is cleared.
+ // For absolute bounties, only update startsAt when explicitly provided.
+ let startsAtUpdate: { startsAt?: Date | null } = {};
+
+ if (nextStartMode === "relative") {
+ startsAtUpdate = { startsAt: null };
+ } else if (startsAt !== undefined) {
+ startsAtUpdate = { startsAt: startsAt ?? new Date() };
+ } else if (bounty.startsAt === null) {
+ // Switching relative -> absolute without a startsAt: default to now
+ startsAtUpdate = { startsAt: new Date() };
+ }
+
const data = await prisma.$transaction(async (tx) => {
const updatedBounty = await tx.bounty.update({
where: {
@@ -187,8 +224,14 @@ export const PATCH = withWorkspace(
data: {
name: bountyName ?? undefined,
description,
- startsAt: startsAt!, // Can remove the ! when we're on a newer TS version (currently 5.4.4)
- endsAt,
+ ...startsAtUpdate,
+ ...(endsAt !== undefined && { endsAt }),
+ ...(startMode !== undefined && { startMode }),
+ ...(endsAfterDays !== undefined
+ ? { endsAfterDays }
+ : nextStartMode === "absolute" && bounty.endsAfterDays != null
+ ? { endsAfterDays: null }
+ : {}),
submissionsOpenAt:
bounty.type === "submission" ? submissionsOpenAt : null,
...(bounty.type === "submission" &&
@@ -204,18 +247,21 @@ export const PATCH = withWorkspace(
submissionRequirements !== undefined && {
submissionRequirements: submissionRequirements ?? Prisma.DbNull,
}),
- ...(updatedPartnerGroups && {
+ ...(shouldUpdatePartnerGroups && {
groups: {
deleteMany: {},
- create: updatedPartnerGroups.map((group) => ({
- groupId: group.id,
- })),
+ ...(updatedPartnerGroups &&
+ updatedPartnerGroups.length > 0 && {
+ create: updatedPartnerGroups.map((group) => ({
+ groupId: group.id,
+ })),
+ }),
},
}),
},
include: {
workflow: true,
- groups: true,
+ ...bountyEligibilityIncludes,
},
});
@@ -281,19 +327,17 @@ export const DELETE = withWorkspace(
const { bountyId } = params;
const programId = getDefaultProgramIdOrThrow(workspace);
- const bounty = await prisma.bounty.findUniqueOrThrow({
- where: {
- id: bountyId,
- programId,
- },
+ const bounty = await getBountyOrThrow({
+ bountyId,
+ programId,
include: {
- groups: true,
workflow: true,
_count: {
select: {
submissions: true,
},
},
+ ...bountyEligibilityIncludes,
},
});
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts
index f6ba6d4223..34faf5a188 100644
--- a/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/submissions/route.ts
@@ -17,9 +17,6 @@ export const GET = withWorkspace(
await getBountyOrThrow({
bountyId,
programId,
- include: {
- groups: true,
- },
});
const {
diff --git a/apps/web/app/(ee)/api/bounties/route.ts b/apps/web/app/(ee)/api/bounties/route.ts
index 873593f51f..b7e7aa2a00 100644
--- a/apps/web/app/(ee)/api/bounties/route.ts
+++ b/apps/web/app/(ee)/api/bounties/route.ts
@@ -6,6 +6,11 @@ import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-progr
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
+import {
+ bountyEligibilityIncludes,
+ buildBountyEligibilityWhere,
+ getEffectiveBountyPeriod,
+} from "@/lib/bounty/api/bounty-eligibility";
import { generatePerformanceBountyName } from "@/lib/bounty/api/generate-performance-bounty-name";
import { validateBounty } from "@/lib/bounty/api/validate-bounty";
import { qstash } from "@/lib/cron";
@@ -41,52 +46,33 @@ export const GET = withWorkspace(
partnerId,
programId,
include: {
- program: true,
+ program: {
+ select: {
+ defaultGroupId: true,
+ },
+ },
},
})
: null;
+ const partnerGroupId =
+ programEnrollment?.groupId || programEnrollment?.program.defaultGroupId;
+
const [bounties, allBountiesSubmissionsCount] = await Promise.all([
prisma.bounty.findMany({
where: {
programId,
- // Filter only bounties the specified partner is eligible for
...(programEnrollment && {
- AND: [
- // Filter out expired bounties
- {
- OR: [{ endsAt: null }, { endsAt: { gt: new Date() } }],
- },
- // Filter by partner's group eligibility
- {
- OR: [
- {
- groups: {
- none: {},
- },
- },
- {
- groups: {
- some: {
- groupId:
- programEnrollment.groupId ||
- programEnrollment.program.defaultGroupId,
- },
- },
- },
- ],
- },
- ],
+ ...buildBountyEligibilityWhere({
+ groupId: partnerGroupId,
+ }),
}),
},
include: {
- groups: {
- select: {
- groupId: true,
- },
- },
+ ...bountyEligibilityIncludes,
},
}),
+
includeSubmissionsCount
? prisma.bountySubmission.groupBy({
by: ["bountyId", "status"],
@@ -127,14 +113,35 @@ export const GET = withWorkspace(
};
};
- const data = bounties.map((bounty) => {
- return BountyListSchema.parse({
- ...bounty,
- groups: bounty.groups.map(({ groupId }) => ({ id: groupId })),
- ...(allBountiesSubmissionsCount && {
- submissionsCountData: aggregateSubmissionsCountForBounty(bounty.id),
+ // Transform the bounties to the response schema
+ const now = new Date();
+ const data = bounties.flatMap((bounty) => {
+ if (programEnrollment) {
+ const { startsAt, endsAt } = getEffectiveBountyPeriod({
+ programEnrollment,
+ bounty,
+ });
+
+ if (now < startsAt || (endsAt && now > endsAt)) {
+ return [];
+ }
+
+ bounty = {
+ ...bounty,
+ startsAt,
+ endsAt,
+ };
+ }
+
+ return [
+ BountyListSchema.parse({
+ ...bounty,
+ ...(allBountiesSubmissionsCount && {
+ submissionsCountData: aggregateSubmissionsCountForBounty(bounty.id),
+ }),
+ groups: bounty.groups.map(({ groupId }) => ({ id: groupId })),
}),
- });
+ ];
});
return NextResponse.json(data);
@@ -167,11 +174,10 @@ export const POST = withWorkspace(
performanceCondition,
performanceScope,
sendNotificationEmails,
+ startMode,
+ endsAfterDays,
} = parsedBody;
- // Use current date as default if startsAt is not provided
- startsAt = startsAt || new Date();
-
validateBounty(parsedBody);
const { canUseBountySocialMetrics, canSendEmailCampaigns } =
@@ -206,6 +212,10 @@ export const POST = withWorkspace(
});
}
+ // startsAt is only stored for absolute bounties (defaulting to now when
+ // omitted); relative bounties start when a partner joins, so it stays null.
+ startsAt = startMode === "absolute" ? startsAt || new Date() : null;
+
const bounty = await prisma.$transaction(async (tx) => {
let workflow: Workflow | null = null;
const bountyId = createId({ prefix: "bnty_" });
@@ -248,6 +258,8 @@ export const POST = withWorkspace(
rewardAmount,
rewardDescription,
performanceScope: type === "performance" ? performanceScope : null,
+ startMode,
+ endsAfterDays,
...(submissionRequirements &&
type === "submission" && {
submissionRequirements,
@@ -264,7 +276,7 @@ export const POST = withWorkspace(
},
include: {
workflow: true,
- groups: true,
+ ...bountyEligibilityIncludes,
},
});
});
@@ -276,7 +288,14 @@ export const POST = withWorkspace(
});
const shouldScheduleDraftSubmissions =
- bounty.type === "performance" && bounty.performanceScope === "lifetime";
+ bounty.type === "performance" &&
+ bounty.performanceScope === "lifetime" &&
+ bounty.startMode === "absolute";
+
+ const shouldSchedulePartnerNotifications =
+ sendNotificationEmails &&
+ canSendEmailCampaigns &&
+ bounty.startMode === "absolute";
waitUntil(
Promise.allSettled([
@@ -301,14 +320,15 @@ export const POST = withWorkspace(
data: createdBounty,
}),
- sendNotificationEmails &&
- canSendEmailCampaigns &&
+ shouldSchedulePartnerNotifications &&
qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/notify-partners`,
body: {
bountyId: bounty.id,
},
- notBefore: Math.floor(bounty.startsAt.getTime() / 1000),
+ ...(bounty.startsAt && {
+ notBefore: Math.floor(bounty.startsAt.getTime() / 1000),
+ }),
}),
shouldScheduleDraftSubmissions &&
@@ -317,7 +337,9 @@ export const POST = withWorkspace(
body: {
bountyId: bounty.id,
},
- notBefore: Math.floor(bounty.startsAt.getTime() / 1000),
+ ...(bounty.startsAt && {
+ notBefore: Math.floor(bounty.startsAt.getTime() / 1000),
+ }),
}),
]),
);
diff --git a/apps/web/lib/bounty/api/bounty-eligibility.ts b/apps/web/lib/bounty/api/bounty-eligibility.ts
new file mode 100644
index 0000000000..28b518e445
--- /dev/null
+++ b/apps/web/lib/bounty/api/bounty-eligibility.ts
@@ -0,0 +1,58 @@
+import { Bounty, Prisma, ProgramEnrollment } from "@prisma/client";
+import { addDays } from "date-fns";
+
+export function buildBountyEligibilityWhere({
+ groupId,
+}: {
+ groupId: string | undefined;
+}): Prisma.BountyWhereInput {
+ return {
+ OR: [
+ {
+ groups: {
+ none: {},
+ },
+ },
+ ...(groupId
+ ? [
+ {
+ groups: {
+ some: {
+ groupId,
+ },
+ },
+ },
+ ]
+ : []),
+ ],
+ };
+}
+
+export const bountyEligibilityIncludes = {
+ groups: {
+ select: {
+ groupId: true,
+ },
+ },
+} satisfies Prisma.BountyInclude;
+
+export function getEffectiveBountyPeriod({
+ programEnrollment,
+ bounty,
+}: {
+ programEnrollment: Pick<ProgramEnrollment, "groupJoinedAt" | "createdAt">;
+ bounty: Pick<Bounty, "startsAt" | "endsAt" | "endsAfterDays" | "startMode">;
+}) {
+ const { createdAt, groupJoinedAt } = programEnrollment;
+ const { startsAt, endsAt, endsAfterDays, startMode } = bounty;
+
+ // If startMode is absolute, use the startsAt (Assumed to be set).
+ // If startMode is relative, use the groupJoinedAt or createdAt.
+ const bountyStartDate =
+ startMode === "absolute" ? startsAt! : groupJoinedAt || createdAt;
+
+ return {
+ startsAt: bountyStartDate,
+ endsAt: endsAfterDays ? addDays(bountyStartDate, endsAfterDays) : endsAt,
+ };
+}
diff --git a/apps/web/lib/bounty/api/get-bounty-with-details.ts b/apps/web/lib/bounty/api/get-bounty-with-details.ts
index a3740ef982..e7e3f23980 100644
--- a/apps/web/lib/bounty/api/get-bounty-with-details.ts
+++ b/apps/web/lib/bounty/api/get-bounty-with-details.ts
@@ -16,6 +16,8 @@ export const getBountyWithDetails = async ({
b.type,
b.startsAt,
b.endsAt,
+ b.startMode,
+ b.endsAfterDays,
b.submissionsOpenAt,
b.submissionFrequency,
b.maxSubmissions,
@@ -63,6 +65,8 @@ export const getBountyWithDetails = async ({
type: bounty.type,
startsAt: bounty.startsAt,
endsAt: bounty.endsAt,
+ startMode: bounty.startMode,
+ endsAfterDays: bounty.endsAfterDays,
submissionsOpenAt: bounty.submissionsOpenAt,
submissionFrequency: bounty.submissionFrequency,
maxSubmissions: bounty.maxSubmissions,
diff --git a/apps/web/lib/bounty/api/validate-bounty.ts b/apps/web/lib/bounty/api/validate-bounty.ts
index 19c28f21ce..a4067bde80 100644
--- a/apps/web/lib/bounty/api/validate-bounty.ts
+++ b/apps/web/lib/bounty/api/validate-bounty.ts
@@ -5,6 +5,8 @@ export function validateBounty({
type,
startsAt,
endsAt,
+ startMode,
+ endsAfterDays,
submissionsOpenAt,
submissionFrequency,
maxSubmissions,
@@ -12,9 +14,40 @@ export function validateBounty({
rewardDescription,
performanceScope,
}: Partial<CreateBountyInput>) {
- startsAt = startsAt || new Date();
+ startMode = startMode ?? "absolute";
- if (endsAt && endsAt < startsAt) {
+ // startsAt is required when startMode is absolute and must be null when
+ // startMode is relative (relative bounties start when a partner joins).
+ if (startMode === "relative") {
+ if (startsAt != null) {
+ throw new DubApiError({
+ message:
+ "startsAt is not supported when the bounty starts when a partner joins. It must be null for relative bounties.",
+ code: "bad_request",
+ });
+ }
+ } else {
+ // Default to now when an absolute bounty doesn't specify a start date
+ startsAt = startsAt || new Date();
+ }
+
+ if (endsAt && endsAfterDays) {
+ throw new DubApiError({
+ message:
+ "Bounty cannot have both an end date (endsAt) and endsAfterDays.",
+ code: "bad_request",
+ });
+ }
+
+ if (startMode === "absolute" && endsAfterDays) {
+ throw new DubApiError({
+ message:
+ "endsAfterDays is only supported when the bounty starts when a partner joins.",
+ code: "bad_request",
+ });
+ }
+
+ if (endsAt && startsAt && endsAt < startsAt) {
throw new DubApiError({
message:
"Bounty end date (endsAt) must be on or after start date (startsAt).",
@@ -31,7 +64,7 @@ export function validateBounty({
});
}
- if (submissionsOpenAt < startsAt) {
+ if (startsAt && submissionsOpenAt < startsAt) {
throw new DubApiError({
message:
"Bounty submissions open date (submissionsOpenAt) must be on or after start date (startsAt).",
diff --git a/apps/web/lib/zod/schemas/bounties.ts b/apps/web/lib/zod/schemas/bounties.ts
index 12ea84a8b4..00b2762e6f 100644
--- a/apps/web/lib/zod/schemas/bounties.ts
+++ b/apps/web/lib/zod/schemas/bounties.ts
@@ -12,6 +12,7 @@ import {
} from "@/lib/bounty/social-content";
import {
BountyPerformanceScope,
+ BountyStartMode,
BountySubmissionFrequency,
BountySubmissionRejectionReason,
BountySubmissionStatus,
@@ -126,6 +127,8 @@ export const createBountySchema = z.object({
performanceCondition: bountyPerformanceConditionSchema.nullish(),
performanceScope: z.enum(BountyPerformanceScope).nullish(),
sendNotificationEmails: z.boolean().optional(),
+ startMode: z.enum(BountyStartMode),
+ endsAfterDays: z.number().int().positive().nullish(),
});
export const updateBountySchema = createBountySchema
@@ -148,8 +151,10 @@ export const BountySchema = z.object({
name: z.string().nullable(),
description: z.string().nullable(),
type: z.enum(BountyType),
- startsAt: z.date(),
+ startsAt: z.date().nullable(),
endsAt: z.date().nullable(),
+ startMode: z.enum(BountyStartMode),
+ endsAfterDays: z.number().nullable(),
submissionsOpenAt: z.date().nullable(),
submissionFrequency: z.enum(BountySubmissionFrequency).nullable(),
maxSubmissions: z.number(),
diff --git a/apps/web/lib/zod/schemas/partner-profile.ts b/apps/web/lib/zod/schemas/partner-profile.ts
index 303279daf9..a04b49a8da 100644
--- a/apps/web/lib/zod/schemas/partner-profile.ts
+++ b/apps/web/lib/zod/schemas/partner-profile.ts
@@ -166,6 +166,7 @@ export const PartnerBountySchema = BountySchema.omit({
groups: true,
socialMetricsLastSyncedAt: true,
}).extend({
+ startsAt: z.date(), // Always resolved to the partner's effective start date (never null)
submissions: z.array(partnerBountySubmissionSchema),
performanceCondition: bountyPerformanceConditionSchema
.nullable()
diff --git a/apps/web/prisma/schema/bounty.prisma b/apps/web/prisma/schema/bounty.prisma
index 321f46b2c3..ea6d298615 100644
--- a/apps/web/prisma/schema/bounty.prisma
+++ b/apps/web/prisma/schema/bounty.prisma
@@ -29,6 +29,11 @@ enum BountySubmissionFrequency {
month
}
+enum BountyStartMode {
+ absolute
+ relative
+}
+
model Bounty {
id String @id
programId String
@@ -36,8 +41,10 @@ model Bounty {
name String
description String? @db.Text
type BountyType
- startsAt DateTime
+ startsAt DateTime? // Set only when startMode is absolute
endsAt DateTime?
+ startMode BountyStartMode @default(absolute)
+ endsAfterDays Int? // Set only when startMode is relative
submissionsOpenAt DateTime?
submissionFrequency BountySubmissionFrequency?
maxSubmissions Int @default(1)
diff --git a/apps/web/prisma/schema/program.prisma b/apps/web/prisma/schema/program.prisma
index 7d88029486..5fff2bd916 100644
--- a/apps/web/prisma/schema/program.prisma
+++ b/apps/web/prisma/schema/program.prisma
@@ -143,6 +143,7 @@ model ProgramEnrollment {
customerDataSharingEnabledAt DateTime?
groupMoveDisabledAt DateTime?
bannedAt DateTime?
+ groupJoinedAt DateTime? // date when the partner joined their current group
bannedReason PartnerBannedReason?
reapplicationTimeframe ReapplicationTimeframe @default(standard)
riskMonitoringDisabledAt DateTime?