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.

recalculate lifetime bounties

Pedro Ladeira9530c40295ad
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
index 922486ecda..aef35da2f0 100644
--- a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
@@ -9,7 +9,9 @@ import { withWorkspace } from "@/lib/auth";
import { generatePerformanceBountyName } from "@/lib/bounty/api/generate-performance-bounty-name";
import { getBountyWithDetails } from "@/lib/bounty/api/get-bounty-with-details";
import { PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES } from "@/lib/bounty/api/performance-bounty-scope-attributes";
+import { shouldUpsertDraftSubmissionsOnReopen } from "@/lib/bounty/api/upsert-draft-bounty-submissions";
import { validateBounty } from "@/lib/bounty/api/validate-bounty";
+import { qstash } from "@/lib/cron";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { prisma } from "@/lib/prisma";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
@@ -18,7 +20,7 @@ import {
submissionRequirementsSchema,
updateBountySchema,
} from "@/lib/zod/schemas/bounties";
-import { arrayEqual, deepEqual } from "@dub/utils";
+import { APP_DOMAIN_WITH_NGROK, arrayEqual, deepEqual } from "@dub/utils";
import { PartnerGroup, Prisma } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
@@ -250,6 +252,15 @@ export const PATCH = withWorkspace(
performanceCondition: data.workflow?.triggerConditions?.[0],
});
+ const shouldUpsertDraftSubmissions = shouldUpsertDraftSubmissionsOnReopen({
+ type: bounty.type,
+ performanceScope: bounty.performanceScope,
+ previousEndsAt: bounty.endsAt,
+ startsAt: data.startsAt,
+ endsAt: data.endsAt,
+ archivedAt: data.archivedAt,
+ });
+
waitUntil(
Promise.allSettled([
recordAuditLog({
@@ -272,6 +283,14 @@ export const PATCH = withWorkspace(
trigger: "bounty.updated",
data: updatedBounty,
}),
+
+ shouldUpsertDraftSubmissions &&
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/upsert-draft-submissions`,
+ body: {
+ bountyId: bounty.id,
+ },
+ }),
]),
);
diff --git a/apps/web/app/(ee)/api/bounties/route.ts b/apps/web/app/(ee)/api/bounties/route.ts
index e995e591a0..eb42e0a8a0 100644
--- a/apps/web/app/(ee)/api/bounties/route.ts
+++ b/apps/web/app/(ee)/api/bounties/route.ts
@@ -321,7 +321,7 @@ export const POST = withWorkspace(
shouldScheduleDraftSubmissions &&
qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/create-draft-submissions`,
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/upsert-draft-submissions`,
body: {
bountyId: bounty.id,
},
diff --git a/apps/web/app/(ee)/api/cron/bounties/create-draft-submissions/route.ts b/apps/web/app/(ee)/api/cron/bounties/upsert-draft-submissions/route.ts
similarity index 63%
rename from apps/web/app/(ee)/api/cron/bounties/create-draft-submissions/route.ts
rename to apps/web/app/(ee)/api/cron/bounties/upsert-draft-submissions/route.ts
index ff0234134c..19d525e85d 100644
--- a/apps/web/app/(ee)/api/cron/bounties/create-draft-submissions/route.ts
+++ b/apps/web/app/(ee)/api/cron/bounties/upsert-draft-submissions/route.ts
@@ -1,13 +1,14 @@
-import { createId } from "@/lib/api/create-id";
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { awardBountyConditionSchema } from "@/lib/api/workflows/award-bounty/schema";
-import { evaluateWorkflowConditions } from "@/lib/api/workflows/evaluate-workflow-conditions";
+import {
+ PartnerLifetimeStats,
+ planDraftBountySubmissionUpserts,
+} from "@/lib/bounty/api/upsert-draft-bounty-submissions";
import { qstash } from "@/lib/cron";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
import { aggregatePartnerLinksStats } from "@/lib/partners/aggregate-partner-links-stats";
import { prisma } from "@/lib/prisma";
import { APP_DOMAIN_WITH_NGROK, log, toCentsNumber } from "@dub/utils";
-import { Prisma } from "@prisma/client";
import { differenceInMinutes } from "date-fns";
import * as z from "zod/v4";
import { logAndRespond } from "../../utils";
@@ -22,8 +23,8 @@ const schema = z.object({
const MAX_PAGE_SIZE = 100;
-// POST /api/cron/bounties/create-draft-submissions
-// Create draft bounty submissions for performance bounties with lifetime performance scope
+// POST /api/cron/bounties/upsert-draft-submissions
+// Create or update draft/submitted bounty submissions for lifetime performance bounties
export async function POST(req: Request) {
try {
const rawBody = await req.text();
@@ -137,57 +138,74 @@ export async function POST(req: Request) {
.parse(bounty.workflow.triggerConditions)[0];
// Partners with their link metrics
- const partners = programEnrollments.map((programEnrollment) => {
- return {
- id: programEnrollment.partnerId,
- ...aggregatePartnerLinksStats(programEnrollment.links),
- totalCommissions: toCentsNumber(programEnrollment.totalCommissions),
- };
+ const partners: PartnerLifetimeStats[] = programEnrollments.map(
+ (programEnrollment) => {
+ return {
+ id: programEnrollment.partnerId,
+ ...aggregatePartnerLinksStats(programEnrollment.links),
+ totalCommissions: toCentsNumber(programEnrollment.totalCommissions),
+ };
+ },
+ );
+
+ const existingSubmissions = await prisma.bountySubmission.findMany({
+ where: {
+ bountyId: bounty.id,
+ partnerId: {
+ in: partners.map((partner) => partner.id),
+ },
+ periodNumber: 1,
+ },
+ select: {
+ id: true,
+ partnerId: true,
+ status: true,
+ },
});
- const bountySubmissionsToCreate: Prisma.BountySubmissionCreateManyInput[] =
- partners
- // only create submissions for partners that have at least 1 performanceCount
- .filter((partner) => partner[condition.attribute] > 0)
- .map((partner) => {
- const performanceCount = partner[condition.attribute];
-
- const conditionMet = evaluateWorkflowConditions({
- conditions: [condition],
- attributes: {
- [condition.attribute]: performanceCount,
- },
- });
-
- return {
- id: createId({ prefix: "bnty_sub_" }),
- programId: bounty.programId,
- partnerId: partner.id,
- bountyId: bounty.id,
- performanceCount,
- // If the condition is met, automatically submit the submission
- ...(conditionMet && {
- status: "submitted",
- completedAt: new Date(),
- }),
- };
- });
-
- console.table(bountySubmissionsToCreate);
-
- // Create bounty submissions
- const createdBountySubmissions = await prisma.bountySubmission.createMany({
- data: bountySubmissionsToCreate,
- skipDuplicates: true,
+ const { toCreate, toUpdate } = planDraftBountySubmissionUpserts({
+ partners,
+ existingSubmissions,
+ condition,
+ programId: bounty.programId,
+ bountyId: bounty.id,
});
+ console.table(toCreate);
+ console.table(toUpdate);
+
+ const [createdBountySubmissions] = await Promise.all([
+ toCreate.length > 0
+ ? prisma.bountySubmission.createMany({
+ data: toCreate,
+ skipDuplicates: true,
+ })
+ : Promise.resolve({ count: 0 }),
+ toUpdate.length > 0
+ ? prisma.$transaction(
+ toUpdate.map((update) =>
+ prisma.bountySubmission.update({
+ where: { id: update.id },
+ data: {
+ performanceCount: update.performanceCount,
+ ...(update.promoteToSubmitted && {
+ status: "submitted",
+ completedAt: new Date(),
+ }),
+ },
+ }),
+ ),
+ )
+ : Promise.resolve([]),
+ ]);
+
console.log(
- `Created ${createdBountySubmissions.count} bounty submissions for bounty ${bountyId}.`,
+ `Upserted bounty submissions for bounty ${bountyId}: created ${createdBountySubmissions.count}, updated ${toUpdate.length}.`,
);
if (programEnrollments.length === MAX_PAGE_SIZE) {
const response = await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/create-draft-submissions`,
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/upsert-draft-submissions`,
body: {
bountyId,
partnerIds,
@@ -201,11 +219,11 @@ export async function POST(req: Request) {
}
return logAndRespond(
- `Finished creating submissions for ${createdBountySubmissions.count} partners for bounty ${bountyId}.`,
+ `Finished upserting submissions for bounty ${bountyId}: created ${createdBountySubmissions.count}, updated ${toUpdate.length}.`,
);
} catch (error) {
await log({
- message: "New bounties submissions cron failed. Error: " + error.message,
+ message: "Upsert bounty submissions cron failed. Error: " + error.message,
type: "errors",
});
diff --git a/apps/web/lib/bounty/api/trigger-draft-bounty-submissions.ts b/apps/web/lib/bounty/api/trigger-draft-bounty-submissions.ts
index 068653dd8e..f93700e613 100644
--- a/apps/web/lib/bounty/api/trigger-draft-bounty-submissions.ts
+++ b/apps/web/lib/bounty/api/trigger-draft-bounty-submissions.ts
@@ -81,7 +81,7 @@ export async function triggerDraftBountySubmissionCreation({
await Promise.allSettled(
eligibleBounties.map((bounty) =>
qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/create-draft-submissions`,
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/upsert-draft-submissions`,
body: {
bountyId: bounty.id,
partnerIds: groupPartnerIds,
diff --git a/apps/web/lib/bounty/api/upsert-draft-bounty-submissions.ts b/apps/web/lib/bounty/api/upsert-draft-bounty-submissions.ts
new file mode 100644
index 0000000000..12ce51cbe9
--- /dev/null
+++ b/apps/web/lib/bounty/api/upsert-draft-bounty-submissions.ts
@@ -0,0 +1,134 @@
+import { createId } from "@/lib/api/create-id";
+import { awardBountyConditionSchema } from "@/lib/api/workflows/award-bounty/schema";
+import { evaluateWorkflowConditions } from "@/lib/api/workflows/evaluate-workflow-conditions";
+import {
+ BountyPerformanceScope,
+ BountySubmissionStatus,
+ BountyType,
+ Prisma,
+} from "@prisma/client";
+import * as z from "zod/v4";
+
+type AwardBountyCondition = z.infer<typeof awardBountyConditionSchema>;
+
+export type PartnerLifetimeStats = {
+ id: string;
+ totalLeads: number;
+ totalConversions: number;
+ totalSaleAmount: number;
+ totalCommissions: number;
+};
+
+export type ExistingBountySubmission = {
+ id: string;
+ partnerId: string;
+ status: BountySubmissionStatus;
+};
+
+export type DraftBountySubmissionUpdate = {
+ id: string;
+ performanceCount: number;
+ promoteToSubmitted: boolean;
+};
+
+export function shouldUpsertDraftSubmissionsOnReopen({
+ type,
+ performanceScope,
+ previousEndsAt,
+ startsAt,
+ endsAt,
+ archivedAt,
+ now = new Date(),
+}: {
+ type: BountyType;
+ performanceScope: BountyPerformanceScope | null;
+ previousEndsAt: Date | null;
+ startsAt: Date;
+ endsAt: Date | null;
+ archivedAt: Date | null;
+ now?: Date;
+}): boolean {
+ if (type !== "performance") return false;
+ if (performanceScope !== "lifetime") return false;
+
+ const wasExpired = previousEndsAt != null && previousEndsAt < now;
+ const nowActive =
+ startsAt <= now && (endsAt == null || endsAt > now) && !archivedAt;
+
+ return wasExpired && nowActive;
+}
+
+export function planDraftBountySubmissionUpserts({
+ partners,
+ existingSubmissions,
+ condition,
+ programId,
+ bountyId,
+}: {
+ partners: PartnerLifetimeStats[];
+ existingSubmissions: ExistingBountySubmission[];
+ condition: AwardBountyCondition;
+ programId: string;
+ bountyId: string;
+}): {
+ toCreate: Prisma.BountySubmissionCreateManyInput[];
+ toUpdate: DraftBountySubmissionUpdate[];
+} {
+ const existingByPartnerId = new Map(
+ existingSubmissions.map((submission) => [submission.partnerId, submission]),
+ );
+
+ const toCreate: Prisma.BountySubmissionCreateManyInput[] = [];
+ const toUpdate: DraftBountySubmissionUpdate[] = [];
+
+ for (const partner of partners) {
+ const performanceCount = partner[condition.attribute];
+
+ if (performanceCount <= 0) {
+ continue;
+ }
+
+ const conditionMet = evaluateWorkflowConditions({
+ conditions: [condition],
+ attributes: {
+ [condition.attribute]: performanceCount,
+ },
+ });
+
+ const existing = existingByPartnerId.get(partner.id);
+
+ if (!existing) {
+ toCreate.push({
+ id: createId({ prefix: "bnty_sub_" }),
+ programId,
+ partnerId: partner.id,
+ bountyId,
+ performanceCount,
+ ...(conditionMet && {
+ status: "submitted",
+ completedAt: new Date(),
+ }),
+ });
+ continue;
+ }
+
+ if (existing.status === "draft") {
+ toUpdate.push({
+ id: existing.id,
+ performanceCount,
+ promoteToSubmitted: conditionMet,
+ });
+ continue;
+ }
+
+ if (existing.status === "submitted") {
+ toUpdate.push({
+ id: existing.id,
+ performanceCount,
+ promoteToSubmitted: false,
+ });
+ }
+ }
+
+ return { toCreate, toUpdate };
+}
diff --git a/apps/web/tests/bounties/upsert-draft-bounty-submissions.test.ts b/apps/web/tests/bounties/upsert-draft-bounty-submissions.test.ts
new file mode 100644
index 0000000000..b4141e5ec0
--- /dev/null
+++ b/apps/web/tests/bounties/upsert-draft-bounty-submissions.test.ts
@@ -0,0 +1,284 @@
+import {
+ planDraftBountySubmissionUpserts,
+ shouldUpsertDraftSubmissionsOnReopen,
+} from "@/lib/bounty/api/upsert-draft-bounty-submissions";
+import { BountySubmissionStatus } from "@prisma/client";
+import { describe, expect, it } from "vitest";
+
+const NOW = new Date("2025-06-01T12:00:00.000Z");
+const PROGRAM_ID = "prog_test";
+const BOUNTY_ID = "bnty_test";
+
+const condition = {
+ attribute: "totalSaleAmount" as const,
+ operator: "gte" as const,
+ value: 10_000,
+};
+
+function makePartner(
+ overrides: Partial<{
+ id: string;
+ totalLeads: number;
+ totalConversions: number;
+ totalSaleAmount: number;
+ totalCommissions: number;
+ }> = {},
+) {
+ return {
+ id: "pn_1",
+ totalLeads: 0,
+ totalConversions: 0,
+ totalSaleAmount: 5_000,
+ totalCommissions: 0,
+ ...overrides,
+ };
+}
+
+function makeSubmission(
+ overrides: Partial<{
+ id: string;
+ partnerId: string;
+ status: BountySubmissionStatus;
+ }> = {},
+) {
+ return {
+ id: "bnty_sub_1",
+ partnerId: "pn_1",
+ status: "draft" as BountySubmissionStatus,
+ ...overrides,
+ };
+}
+
+describe("shouldUpsertDraftSubmissionsOnReopen", () => {
+ it("returns true when a lifetime performance bounty was expired and is now active", () => {
+ expect(
+ shouldUpsertDraftSubmissionsOnReopen({
+ type: "performance",
+ performanceScope: "lifetime",
+ previousEndsAt: new Date("2025-05-01T00:00:00.000Z"),
+ startsAt: new Date("2025-01-01T00:00:00.000Z"),
+ endsAt: new Date("2025-12-01T00:00:00.000Z"),
+ archivedAt: null,
+ now: NOW,
+ }),
+ ).toBe(true);
+ });
+
+ it("returns true when endsAt is cleared after expiry", () => {
+ expect(
+ shouldUpsertDraftSubmissionsOnReopen({
+ type: "performance",
+ performanceScope: "lifetime",
+ previousEndsAt: new Date("2025-05-01T00:00:00.000Z"),
+ startsAt: new Date("2025-01-01T00:00:00.000Z"),
+ endsAt: null,
+ archivedAt: null,
+ now: NOW,
+ }),
+ ).toBe(true);
+ });
+
+ it("returns false for new-scope performance bounties", () => {
+ expect(
+ shouldUpsertDraftSubmissionsOnReopen({
+ type: "performance",
+ performanceScope: "new",
+ previousEndsAt: new Date("2025-05-01T00:00:00.000Z"),
+ startsAt: new Date("2025-01-01T00:00:00.000Z"),
+ endsAt: new Date("2025-12-01T00:00:00.000Z"),
+ archivedAt: null,
+ now: NOW,
+ }),
+ ).toBe(false);
+ });
+
+ it("returns false when the bounty was not previously expired", () => {
+ expect(
+ shouldUpsertDraftSubmissionsOnReopen({
+ type: "performance",
+ performanceScope: "lifetime",
+ previousEndsAt: new Date("2025-12-01T00:00:00.000Z"),
+ startsAt: new Date("2025-01-01T00:00:00.000Z"),
+ endsAt: new Date("2026-01-01T00:00:00.000Z"),
+ archivedAt: null,
+ now: NOW,
+ }),
+ ).toBe(false);
+ });
+
+ it("returns false when the bounty is still expired after the update", () => {
+ expect(
+ shouldUpsertDraftSubmissionsOnReopen({
+ type: "performance",
+ performanceScope: "lifetime",
+ previousEndsAt: new Date("2025-04-01T00:00:00.000Z"),
+ startsAt: new Date("2025-01-01T00:00:00.000Z"),
+ endsAt: new Date("2025-05-01T00:00:00.000Z"),
+ archivedAt: null,
+ now: NOW,
+ }),
+ ).toBe(false);
+ });
+
+ it("returns false for archived bounties", () => {
+ expect(
+ shouldUpsertDraftSubmissionsOnReopen({
+ type: "performance",
+ performanceScope: "lifetime",
+ previousEndsAt: new Date("2025-05-01T00:00:00.000Z"),
+ startsAt: new Date("2025-01-01T00:00:00.000Z"),
+ endsAt: null,
+ archivedAt: new Date("2025-05-15T00:00:00.000Z"),
+ now: NOW,
+ }),
+ ).toBe(false);
+ });
+
+ it("returns false for submission bounties", () => {
+ expect(
+ shouldUpsertDraftSubmissionsOnReopen({
+ type: "submission",
+ performanceScope: null,
+ previousEndsAt: new Date("2025-05-01T00:00:00.000Z"),
+ startsAt: new Date("2025-01-01T00:00:00.000Z"),
+ endsAt: new Date("2025-12-01T00:00:00.000Z"),
+ archivedAt: null,
+ now: NOW,
+ }),
+ ).toBe(false);
+ });
+});
+
+describe("planDraftBountySubmissionUpserts", () => {
+ it("creates a submission for partners without an existing row", () => {
+ const { toCreate, toUpdate } = planDraftBountySubmissionUpserts({
+ partners: [makePartner({ totalSaleAmount: 5_000 })],
+ existingSubmissions: [],
+ condition,
+ programId: PROGRAM_ID,
+ bountyId: BOUNTY_ID,
+ });
+
+ expect(toUpdate).toHaveLength(0);
+ expect(toCreate).toHaveLength(1);
+ expect(toCreate[0]).toMatchObject({
+ programId: PROGRAM_ID,
+ partnerId: "pn_1",
+ bountyId: BOUNTY_ID,
+ performanceCount: 5_000,
+ });
+ expect(toCreate[0].status).toBeUndefined();
+ });
+
+ it("auto-submits newly created submissions that meet the condition", () => {
+ const { toCreate } = planDraftBountySubmissionUpserts({
+ partners: [makePartner({ totalSaleAmount: 15_000 })],
+ existingSubmissions: [],
+ condition,
+ programId: PROGRAM_ID,
+ bountyId: BOUNTY_ID,
+ });
+
+ expect(toCreate).toHaveLength(1);
+ expect(toCreate[0]).toMatchObject({
+ performanceCount: 15_000,
+ status: "submitted",
+ completedAt: expect.any(Date),
+ });
+ });
+
+ it("refreshes a draft submission performanceCount", () => {
+ const { toCreate, toUpdate } = planDraftBountySubmissionUpserts({
+ partners: [makePartner({ totalSaleAmount: 8_000 })],
+ existingSubmissions: [makeSubmission({ status: "draft" })],
+ condition,
+ programId: PROGRAM_ID,
+ bountyId: BOUNTY_ID,
+ });
+
+ expect(toCreate).toHaveLength(0);
+ expect(toUpdate).toEqual([
+ {
+ id: "bnty_sub_1",
+ performanceCount: 8_000,
+ promoteToSubmitted: false,
+ },
+ ]);
+ });
+
+ it("promotes a draft to submitted when the refreshed count meets the condition", () => {
+ const { toUpdate } = planDraftBountySubmissionUpserts({
+ partners: [makePartner({ totalSaleAmount: 12_000 })],
+ existingSubmissions: [makeSubmission({ status: "draft" })],
+ condition,
+ programId: PROGRAM_ID,
+ bountyId: BOUNTY_ID,
+ });
+
+ expect(toUpdate).toEqual([
+ {
+ id: "bnty_sub_1",
+ performanceCount: 12_000,
+ promoteToSubmitted: true,
+ },
+ ]);
+ });
+
+ it("refreshes submitted performanceCount without changing status", () => {
+ const { toUpdate } = planDraftBountySubmissionUpserts({
+ partners: [makePartner({ totalSaleAmount: 20_000 })],
+ existingSubmissions: [makeSubmission({ status: "submitted" })],
+ condition,
+ programId: PROGRAM_ID,
+ bountyId: BOUNTY_ID,
+ });
+
+ expect(toUpdate).toEqual([
+ {
+ id: "bnty_sub_1",
+ performanceCount: 20_000,
+ promoteToSubmitted: false,
+ },
+ ]);
+ });
+
+ it("skips approved and rejected submissions", () => {
+ const { toCreate, toUpdate } = planDraftBountySubmissionUpserts({
+ partners: [
+ makePartner({ id: "pn_approved", totalSaleAmount: 20_000 }),
+ makePartner({ id: "pn_rejected", totalSaleAmount: 20_000 }),
+ ],
+ existingSubmissions: [
+ makeSubmission({
+ id: "bnty_sub_approved",
+ partnerId: "pn_approved",
+ status: "approved",
+ }),
+ makeSubmission({
+ id: "bnty_sub_rejected",
+ partnerId: "pn_rejected",
+ status: "rejected",
+ }),
+ ],
+ condition,
+ programId: PROGRAM_ID,
+ bountyId: BOUNTY_ID,
+ });
+
+ expect(toCreate).toHaveLength(0);
+ expect(toUpdate).toHaveLength(0);
+ });
+
+ it("skips partners with zero performanceCount", () => {
+ const { toCreate, toUpdate } = planDraftBountySubmissionUpserts({
+ partners: [makePartner({ totalSaleAmount: 0 })],
+ existingSubmissions: [],
+ condition,
+ programId: PROGRAM_ID,
+ bountyId: BOUNTY_ID,
+ });
+
+ expect(toCreate).toHaveLength(0);
+ expect(toUpdate).toHaveLength(0);
+ });
+});