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.

Align relative bounty timing across PATCH, queries, cron, and webhooks.

Kiran K30d83d6c350d
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
index d06dc099ac..822b657e4e 100644
--- a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
@@ -85,6 +85,18 @@ export const PATCH = withWorkspace(
const nextStartMode =
startMode !== undefined ? startMode : bounty.startMode;
+ // Absolute end dates are cleared when switching to relative (unless the
+ // client explicitly sends endsAt) or when setting endsAfterDays.
+ let endsAtUpdate: { endsAt?: Date | null } = {};
+
+ if (endsAt !== undefined) {
+ endsAtUpdate = { endsAt };
+ } else if (endsAfterDays != null) {
+ endsAtUpdate = { endsAt: null };
+ } else if (nextStartMode === "relative" && bounty.endsAt != null) {
+ endsAtUpdate = { endsAt: null };
+ }
+
validateBounty({
type: bounty.type,
// Relative bounties never store startsAt; coerce so mode switches don't
@@ -95,7 +107,8 @@ export const PATCH = withWorkspace(
: startsAt !== undefined
? startsAt
: bounty.startsAt,
- endsAt: endsAt !== undefined ? endsAt : bounty.endsAt,
+ endsAt:
+ endsAtUpdate.endsAt !== undefined ? endsAtUpdate.endsAt : bounty.endsAt,
startMode: nextStartMode,
endsAfterDays:
endsAfterDays !== undefined
@@ -225,7 +238,7 @@ export const PATCH = withWorkspace(
name: bountyName ?? undefined,
description,
...startsAtUpdate,
- ...(endsAt !== undefined && { endsAt }),
+ ...endsAtUpdate,
...(startMode !== undefined && { startMode }),
...(endsAfterDays !== undefined
? { endsAfterDays }
diff --git a/apps/web/app/(ee)/api/cron/bounties/queue-sync-social-metrics/route.ts b/apps/web/app/(ee)/api/cron/bounties/queue-sync-social-metrics/route.ts
index 5ca507dcf2..2a79591fb9 100644
--- a/apps/web/app/(ee)/api/cron/bounties/queue-sync-social-metrics/route.ts
+++ b/apps/web/app/(ee)/api/cron/bounties/queue-sync-social-metrics/route.ts
@@ -1,7 +1,8 @@
+import { buildBountyActivePeriodWhere } from "@/lib/bounty/api/bounty-availability";
import { enqueueBatchJobs } from "@/lib/cron/enqueue-batch-jobs";
import { withCron } from "@/lib/cron/with-cron";
import { prisma } from "@/lib/prisma";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { APP_DOMAIN_WITH_NGROK, chunk } from "@dub/utils";
import { Prisma } from "@prisma/client";
import { logAndRespond } from "../../utils";
@@ -9,32 +10,17 @@ export const dynamic = "force-dynamic";
// GET /api/cron/bounties/queue-sync-social-metrics - queue social metrics sync for bounties
export const GET = withCron(async () => {
- const now = new Date();
-
const bounties = await prisma.bounty.findMany({
where: {
type: "submission",
- startsAt: {
- lte: now,
- },
- OR: [
- {
- endsAt: null,
- },
- {
- endsAt: {
- gt: now,
- },
- },
- ],
submissionRequirements: {
path: "$.socialMetrics",
not: Prisma.JsonNull,
},
+ ...buildBountyActivePeriodWhere(),
},
select: {
id: true,
- submissionRequirements: true,
},
});
@@ -42,16 +28,20 @@ export const GET = withCron(async () => {
return logAndRespond("No bounties to sync social metrics for.");
}
- await enqueueBatchJobs(
- bounties.map((bounty) => ({
- queueName: "sync-bounty-social-metrics",
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/sync-social-metrics`,
- deduplicationId: bounty.id,
- body: {
- bountyId: bounty.id,
- },
- })),
- );
+ const chunks = chunk(bounties, 100);
+
+ for (const chunk of chunks) {
+ await enqueueBatchJobs(
+ chunk.map((bounty) => ({
+ queueName: "sync-bounty-social-metrics",
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/sync-social-metrics`,
+ deduplicationId: bounty.id,
+ body: {
+ bountyId: bounty.id,
+ },
+ })),
+ );
+ }
return logAndRespond(
`Queued ${bounties.length} bounties to sync social metrics.`,
diff --git a/apps/web/app/(ee)/api/cron/bounties/sync-social-metrics/route.ts b/apps/web/app/(ee)/api/cron/bounties/sync-social-metrics/route.ts
index 6a64fd6325..31f8e274fd 100644
--- a/apps/web/app/(ee)/api/cron/bounties/sync-social-metrics/route.ts
+++ b/apps/web/app/(ee)/api/cron/bounties/sync-social-metrics/route.ts
@@ -1,4 +1,6 @@
+import { getEffectiveBountyPeriod } from "@/lib/bounty/api/bounty-availability";
import { getSocialMetricsUpdates } from "@/lib/bounty/api/get-social-metrics-updates";
+import { isBountyExpired } from "@/lib/bounty/bounty-period";
import { resolveBountyDetails } from "@/lib/bounty/utils";
import { qstash } from "@/lib/cron";
import { withCron } from "@/lib/cron/with-cron";
@@ -6,7 +8,7 @@ import { prisma } from "@/lib/prisma";
import { sendBatchEmail } from "@dub/email";
import BountyCompleted from "@dub/email/templates/bounty-completed";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
-import { Partner, Prisma } from "@prisma/client";
+import { BountySubmissionStatus, Partner, Prisma } from "@prisma/client";
import * as z from "zod/v4";
import { logAndRespond } from "../../utils";
@@ -31,7 +33,13 @@ export const POST = withCron(async ({ rawBody }) => {
id: bountyId,
},
include: {
- program: true,
+ program: {
+ select: {
+ name: true,
+ slug: true,
+ supportEmail: true,
+ },
+ },
},
});
@@ -39,16 +47,6 @@ export const POST = withCron(async ({ rawBody }) => {
return logAndRespond(`Bounty ${bountyId} not found. Skipping...`);
}
- const now = new Date();
-
- if (bounty.startsAt && bounty.startsAt > now) {
- return logAndRespond(`Bounty ${bountyId} has not started yet. Skipping...`);
- }
-
- if (bounty.endsAt && bounty.endsAt < now) {
- return logAndRespond(`Bounty ${bountyId} has ended. Skipping...`);
- }
-
const bountyInfo = resolveBountyDetails(bounty);
if (!bountyInfo?.hasSocialMetrics) {
@@ -62,7 +60,10 @@ export const POST = withCron(async ({ rawBody }) => {
bountyId,
status: {
// We only want to process submissions that are not rejected or approved.
- notIn: ["rejected", "approved"],
+ notIn: [
+ BountySubmissionStatus.rejected,
+ BountySubmissionStatus.approved,
+ ],
},
},
select: {
@@ -75,6 +76,12 @@ export const POST = withCron(async ({ rawBody }) => {
email: true,
},
},
+ programEnrollment: {
+ select: {
+ groupJoinedAt: true,
+ createdAt: true,
+ },
+ },
},
orderBy: {
id: "asc",
@@ -119,7 +126,16 @@ export const POST = withCron(async ({ rawBody }) => {
} of newMetrics) {
const submission = submissionById.get(id);
- if (!submission) {
+ if (!submission || !submission.programEnrollment) {
+ continue;
+ }
+
+ const { endsAt } = getEffectiveBountyPeriod({
+ programEnrollment: submission.programEnrollment,
+ bounty,
+ });
+
+ if (isBountyExpired(endsAt)) {
continue;
}
@@ -136,7 +152,7 @@ export const POST = withCron(async ({ rawBody }) => {
if (shouldTransitionToSubmitted) {
updateData.status = "submitted";
- updateData.completedAt = now;
+ updateData.completedAt = new Date();
if (submission.partner?.email) {
notifications.push({
@@ -157,7 +173,7 @@ export const POST = withCron(async ({ rawBody }) => {
await prisma.$transaction(updates);
- if (notifications.length > 0 && bounty.program) {
+ if (notifications.length > 0) {
await sendBatchEmail(
notifications.map(({ email }) => ({
subject: "Bounty completed!",
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
index 372381bc17..1108e29ce7 100644
--- 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
@@ -321,6 +321,14 @@ export function BountyDuration({
initialPresets.customEndsAfterDays,
);
+ const [endDateLocked] = useState(
+ () => isEditing && (value.endsAt != null || value.endsAfterDays != null),
+ );
+
+ const endOptions = endDateLocked
+ ? END_OPTIONS.filter((option) => option.value !== "never")
+ : END_OPTIONS;
+
useEffect(() => {
const presets = parsePresetsFromValue(value, isEditing);
setStartPreset(presets.startPreset);
@@ -426,7 +434,7 @@ export function BountyDuration({
<span className="inline-flex items-center gap-0.5">
<InlineBadgePopover text={endLabel} buttonClassName="mx-0.5">
<InlineBadgePopoverMenu
- items={END_OPTIONS.map((option) => ({
+ items={endOptions.map((option) => ({
value: option.value,
text: option.label,
}))}
@@ -434,6 +442,10 @@ export function BountyDuration({
customEndsAfterDays != null ? undefined : endPreset
}
onSelect={(preset) => {
+ if (endDateLocked && preset === "never") {
+ return;
+ }
+
setEndPreset(preset);
setCustomEndsAfterDays(null);
diff --git a/apps/web/lib/bounty/api/bounty-availability.ts b/apps/web/lib/bounty/api/bounty-availability.ts
index d81345b8d7..aa617d75c3 100644
--- a/apps/web/lib/bounty/api/bounty-availability.ts
+++ b/apps/web/lib/bounty/api/bounty-availability.ts
@@ -1,6 +1,7 @@
import {
Bounty,
BountyGroup,
+ BountyStartMode,
BountySubmission,
Prisma,
Program,
@@ -34,6 +35,32 @@ export function buildBountyEligibilityWhere(
};
}
+export function buildBountyActivePeriodWhere(): Prisma.BountyWhereInput[] {
+ const now = new Date();
+
+ return [
+ {
+ startMode: BountyStartMode.relative,
+ },
+ {
+ startMode: BountyStartMode.absolute,
+ startsAt: {
+ lte: now,
+ },
+ OR: [
+ {
+ endsAt: null,
+ },
+ {
+ endsAt: {
+ gte: now,
+ },
+ },
+ ],
+ },
+ ];
+}
+
export const bountyEligibilityIncludes = {
groups: {
select: {
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 93d129f239..18d9c54764 100644
--- a/apps/web/lib/bounty/api/get-bounties-for-partner.ts
+++ b/apps/web/lib/bounty/api/get-bounties-for-partner.ts
@@ -7,6 +7,7 @@ import { PartnerBountySchema } from "@/lib/zod/schemas/partner-profile";
import { Program, ProgramEnrollment } from "@prisma/client";
import * as z from "zod/v4";
import {
+ buildBountyActivePeriodWhere,
buildBountyEligibilityWhere,
getEffectiveBountyPeriod,
} from "./bounty-availability";
@@ -39,29 +40,7 @@ export async function getBountiesForPartner({
archivedAt: null,
...buildBountyEligibilityWhere(partnerGroupId),
OR: [
- // Relative bounties start when a partner joins (no startsAt filter).
- {
- startMode: "relative",
- },
-
- // Absolute bounties must have started and not expired.
- {
- startMode: "absolute",
- startsAt: {
- lt: now,
- },
- OR: [
- {
- endsAt: null,
- },
- {
- endsAt: {
- gt: now,
- },
- },
- ],
- },
-
+ ...buildBountyActivePeriodWhere(),
// Bounties the partner has a submission on stay visible
{
submissions: {
diff --git a/apps/web/lib/webhook/sample-events/bounty-created.json b/apps/web/lib/webhook/sample-events/bounty-created.json
index eb772cfae8..dd9f943f5e 100644
--- a/apps/web/lib/webhook/sample-events/bounty-created.json
+++ b/apps/web/lib/webhook/sample-events/bounty-created.json
@@ -5,6 +5,8 @@
"type": "submission",
"startsAt": "2025-08-01T17:34:00.000Z",
"endsAt": "2025-09-01T17:34:00.000Z",
+ "startMode": "absolute",
+ "endsAfterDays": null,
"submissionsOpenAt": null,
"submissionFrequency": null,
"maxSubmissions": 1,
diff --git a/apps/web/lib/webhook/sample-events/bounty-updated.json b/apps/web/lib/webhook/sample-events/bounty-updated.json
index 0d5605ac89..109d1a74cf 100644
--- a/apps/web/lib/webhook/sample-events/bounty-updated.json
+++ b/apps/web/lib/webhook/sample-events/bounty-updated.json
@@ -5,6 +5,8 @@
"type": "submission",
"startsAt": "2025-08-01T17:34:00.000Z",
"endsAt": "2025-09-01T17:34:00.000Z",
+ "startMode": "absolute",
+ "endsAfterDays": null,
"submissionsOpenAt": null,
"submissionFrequency": null,
"maxSubmissions": 1,
diff --git a/apps/web/tests/webhooks/index.test.ts b/apps/web/tests/webhooks/index.test.ts
index 39864ea072..863522a25f 100644
--- a/apps/web/tests/webhooks/index.test.ts
+++ b/apps/web/tests/webhooks/index.test.ts
@@ -55,8 +55,18 @@ const commissionWebhookEventSchemaExtended = CommissionWebhookSchema.extend({
});
const bountyWebhookEventSchemaExtended = BountySchema.extend({
- startsAt: z.string().transform((str) => new Date(str)),
- endsAt: z.string().transform((str) => (str ? new Date(str) : null)),
+ startsAt: z
+ .string()
+ .nullable()
+ .transform((str) => (str ? new Date(str) : null)),
+ endsAt: z
+ .string()
+ .nullable()
+ .transform((str) => (str ? new Date(str) : null)),
+ submissionsOpenAt: z
+ .string()
+ .nullable()
+ .transform((str) => (str ? new Date(str) : null)),
});
const payoutWebhookEventSchemaExtended = payoutWebhookEventSchema.extend({