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.

Trigger draft bounty submissions for partners

Kiran Kb2b07deef71f
diff --git a/apps/web/app/(ee)/api/bounties/route.ts b/apps/web/app/(ee)/api/bounties/route.ts
index deede6b078..7bbe84c695 100644
--- a/apps/web/app/(ee)/api/bounties/route.ts
+++ b/apps/web/app/(ee)/api/bounties/route.ts
@@ -266,7 +266,7 @@ export const POST = withWorkspace(
shouldCreateSubmissions &&
qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/create-submissions`,
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/create-draft-submissions`,
body: {
bountyId: bounty.id,
},
diff --git a/apps/web/app/(ee)/api/cron/bounties/create-submissions/route.ts b/apps/web/app/(ee)/api/cron/bounties/create-draft-submissions/route.ts
similarity index 87%
rename from apps/web/app/(ee)/api/cron/bounties/create-submissions/route.ts
rename to apps/web/app/(ee)/api/cron/bounties/create-draft-submissions/route.ts
index 324e05029c..0ba4f3d100 100644
--- a/apps/web/app/(ee)/api/cron/bounties/create-submissions/route.ts
+++ b/apps/web/app/(ee)/api/cron/bounties/create-draft-submissions/route.ts
@@ -14,12 +14,14 @@ export const dynamic = "force-dynamic";
const schema = z.object({
bountyId: z.string(),
+ partnerIds: z.array(z.string()).optional(),
page: z.number().optional().default(0),
});
const MAX_PAGE_SIZE = 100;
// POST /api/cron/bounties/create-submissions
+// Create draft bounty submissions for performance bounties for partners
export async function POST(req: Request) {
try {
const rawBody = await req.text();
@@ -29,7 +31,7 @@ export async function POST(req: Request) {
rawBody,
});
- const { bountyId, page } = schema.parse(JSON.parse(rawBody));
+ const { bountyId, partnerIds, page } = schema.parse(JSON.parse(rawBody));
// Find bounty
const bounty = await prisma.bounty.findUnique({
@@ -61,6 +63,12 @@ export async function POST(req: Request) {
return logAndRespond(`Bounty ${bountyId} is not a performance bounty.`);
}
+ if (bounty.currentStatsOnly) {
+ return logAndRespond(
+ `Bounty ${bountyId} is limited to current stats; submission creation skipped.`,
+ );
+ }
+
if (!bounty.workflow) {
return logAndRespond(`Bounty ${bountyId} has no workflow.`);
}
@@ -77,6 +85,11 @@ export async function POST(req: Request) {
in: groupIds,
},
}),
+ ...(partnerIds && {
+ partnerId: {
+ in: partnerIds,
+ },
+ }),
status: {
in: ["approved", "invited"],
},
@@ -93,6 +106,11 @@ export async function POST(req: Request) {
saleAmount: true,
},
},
+ partner: {
+ select: {
+ name: true,
+ },
+ },
},
orderBy: {
createdAt: "asc",
@@ -107,6 +125,8 @@ export async function POST(req: Request) {
);
}
+ console.log("programEnrollments", programEnrollments);
+
// Find the workflow condition
const condition = z
.array(workflowConditionSchema)
@@ -140,6 +160,7 @@ export async function POST(req: Request) {
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/create-submissions`,
body: {
bountyId,
+ partnerIds,
page: page + 1,
},
});
diff --git a/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/partners/route.ts b/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/partners/route.ts
index ec0abfd92a..b638dbdd23 100644
--- a/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/partners/route.ts
+++ b/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/partners/route.ts
@@ -1,3 +1,4 @@
+import { triggerDraftBountySubmissionCreation } from "@/lib/api/bounties/trigger-draft-bounty-submissions";
import { DubApiError } from "@/lib/api/errors";
import { getGroupOrThrow } from "@/lib/api/groups/get-group-or-throw";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
@@ -28,6 +29,7 @@ export const POST = withWorkspace(
let { partnerIds } = addPartnersToGroupSchema.parse(
await parseRequestBody(req),
);
+
partnerIds = [...new Set(partnerIds)];
if (partnerIds.length === 0) {
@@ -55,15 +57,22 @@ export const POST = withWorkspace(
if (count > 0) {
waitUntil(
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/groups/remap-default-links`,
- body: {
+ Promise.allSettled([
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/groups/remap-default-links`,
+ body: {
+ programId,
+ groupId: group.id,
+ partnerIds,
+ userId: session.user.id,
+ },
+ }),
+
+ triggerDraftBountySubmissionCreation({
programId,
- groupId: group.id,
partnerIds,
- userId: session.user.id,
- },
- }),
+ }),
+ ]),
);
}
diff --git a/apps/web/lib/actions/partners/bulk-approve-partners.ts b/apps/web/lib/actions/partners/bulk-approve-partners.ts
index d8ff1142c0..eedc326de0 100644
--- a/apps/web/lib/actions/partners/bulk-approve-partners.ts
+++ b/apps/web/lib/actions/partners/bulk-approve-partners.ts
@@ -1,6 +1,7 @@
"use server";
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
+import { triggerDraftBountySubmissionCreation } from "@/lib/api/bounties/trigger-draft-bounty-submissions";
import { getGroupOrThrow } from "@/lib/api/groups/get-group-or-throw";
import { createPartnerDefaultLinks } from "@/lib/api/partners/create-partner-default-links";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
@@ -189,6 +190,8 @@ export const bulkApprovePartnersAction = authActionClient
return acc;
}, new Map<string, Omit<Link, "partnerGroupDefaultLinkId">[]>());
+ const partnerIds = updatedEnrollments.map(({ partner }) => partner.id);
+
await Promise.allSettled([
// Send approval emails
...emailChunks.map((emailChunk) => sendBatchEmail(emailChunk)),
@@ -223,6 +226,11 @@ export const bulkApprovePartnersAction = authActionClient
],
})),
),
+
+ triggerDraftBountySubmissionCreation({
+ programId,
+ partnerIds,
+ }),
]);
})(),
);
diff --git a/apps/web/lib/api/bounties/get-bounties-by-groups.ts b/apps/web/lib/api/bounties/get-bounties-by-groups.ts
new file mode 100644
index 0000000000..fdaab5cf52
--- /dev/null
+++ b/apps/web/lib/api/bounties/get-bounties-by-groups.ts
@@ -0,0 +1,43 @@
+import { prisma } from "@dub/prisma";
+import { Bounty } from "@prisma/client";
+
+export async function getBountiesByGroups({
+ programId,
+ groupIds,
+}: {
+ programId: string;
+ groupIds: string[];
+}) {
+ const now = new Date();
+
+ const bounties = await prisma.bounty.findMany({
+ where: {
+ programId,
+ startsAt: {
+ lte: now,
+ },
+ OR: [{ endsAt: null }, { endsAt: { gt: now } }],
+ AND: [
+ {
+ OR: [
+ { groups: { none: {} } },
+ { groups: { some: { groupId: { in: groupIds } } } },
+ ],
+ },
+ ],
+ },
+ include: {
+ groups: true,
+ },
+ });
+
+ const bountiesByGroups: Record<string, Bounty[]> = {};
+
+ for (const groupId of groupIds) {
+ bountiesByGroups[groupId] = bounties.filter((bounty) =>
+ bounty.groups.some((g) => g.groupId === groupId),
+ );
+ }
+
+ return bountiesByGroups;
+}
diff --git a/apps/web/lib/api/bounties/trigger-draft-bounty-submissions.ts b/apps/web/lib/api/bounties/trigger-draft-bounty-submissions.ts
new file mode 100644
index 0000000000..fa854273e8
--- /dev/null
+++ b/apps/web/lib/api/bounties/trigger-draft-bounty-submissions.ts
@@ -0,0 +1,95 @@
+import { qstash } from "@/lib/cron";
+import { prisma } from "@dub/prisma";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { getBountiesByGroups } from "./get-bounties-by-groups";
+
+// TODO:
+// Need a better method name
+
+// Trigger the creation of draft submissions for performance bounties that uses all-time stats for the given partners
+export async function triggerDraftBountySubmissionCreation({
+ programId,
+ partnerIds,
+}: {
+ programId: string;
+ partnerIds: string[];
+}) {
+ const programEnrollments = await prisma.programEnrollment.findMany({
+ where: {
+ partnerId: {
+ in: partnerIds,
+ },
+ },
+ select: {
+ partnerId: true,
+ groupId: true,
+ },
+ });
+
+ const groupIds = [
+ ...new Set(
+ programEnrollments
+ .map(({ groupId }) => groupId)
+ .filter((id): id is string => id !== null),
+ ),
+ ];
+
+ if (groupIds.length === 0) {
+ return;
+ }
+
+ const bountiesByGroups = await getBountiesByGroups({
+ programId,
+ groupIds,
+ });
+
+ const partnersByGroup = programEnrollments.reduce(
+ (acc, enrollment) => {
+ if (enrollment.groupId) {
+ acc[enrollment.groupId] = [
+ ...(acc[enrollment.groupId] || []),
+ enrollment.partnerId,
+ ];
+ }
+ return acc;
+ },
+ {} as Record<string, string[]>,
+ );
+
+ for (const groupId in bountiesByGroups) {
+ const eligibleBounties = bountiesByGroups[groupId].filter(
+ (bounty) =>
+ bounty.type === "performance" && bounty.currentStatsOnly === false,
+ );
+
+ if (eligibleBounties.length === 0) {
+ console.log(
+ `No eligible bounties found for the group ${groupId}. Either there are no performance bounties, or there are no all-time stats.`,
+ );
+ continue;
+ }
+
+ const groupPartnerIds = partnersByGroup[groupId] || [];
+
+ if (groupPartnerIds.length === 0) {
+ console.log(`No partners found for the group ${groupId}.`);
+ continue;
+ }
+
+ console.log(
+ `Found ${eligibleBounties.length} eligible bounties for the group ${groupId}.`,
+ );
+
+ await Promise.allSettled(
+ eligibleBounties.map((bounty) =>
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/create-draft-submissions`,
+ body: {
+ bountyId: bounty.id,
+ partnerIds: groupPartnerIds,
+ },
+ }),
+ ),
+ );
+ }
+}
diff --git a/apps/web/lib/partners/approve-partner-enrollment.ts b/apps/web/lib/partners/approve-partner-enrollment.ts
index 1219cc2cb9..ef85abab4a 100644
--- a/apps/web/lib/partners/approve-partner-enrollment.ts
+++ b/apps/web/lib/partners/approve-partner-enrollment.ts
@@ -4,6 +4,7 @@ import PartnerApplicationApproved from "@dub/email/templates/partner-application
import { prisma } from "@dub/prisma";
import { waitUntil } from "@vercel/functions";
import { recordAuditLog } from "../api/audit-logs/record-audit-log";
+import { triggerDraftBountySubmissionCreation } from "../api/bounties/trigger-draft-bounty-submissions";
import { getGroupOrThrow } from "../api/groups/get-group-or-throw";
import { createPartnerDefaultLinks } from "../api/partners/create-partner-default-links";
import { RewardProps, WorkspaceProps } from "../types";
@@ -179,6 +180,11 @@ export async function approvePartnerEnrollment({
},
],
}),
+
+ triggerDraftBountySubmissionCreation({
+ programId,
+ partnerIds: [partner.id],
+ }),
]);
})(),
);