The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Refactor bounty workflow handling: remove validatePerformanceBounty function, introduce executeWorkflows for streamlined workflow execution, and add executeBountyWorkflow for bounty-specific logic. Update BountySubmission and ProgramEnrollment models to support new relationships.
Kiran Ke78f8dc56fd3
diff --git a/apps/web/lib/api/bounties/validate-performance-bounty.ts b/apps/web/lib/api/bounties/validate-performance-bounty.tsdeleted file mode 100644index 09b631d0f1..0000000000--- a/apps/web/lib/api/bounties/validate-performance-bounty.ts+++ /dev/null@@ -1,205 +0,0 @@-import { createPartnerCommission } from "@/lib/partners/create-partner-commission";-import {- OPERATOR_FUNCTIONS,- workflowConditionSchema,-} from "@/lib/zod/schemas/workflows";-import { prisma } from "@dub/prisma";-import { BountySubmissionStatus, WorkflowTrigger } from "@dub/prisma/client";-import { z } from "zod";-import { createId } from "../create-id";--export const validatePerformanceBounty = async ({- programId,- partnerId,- workflowTrigger,-}: {- programId: string;- partnerId: string;- workflowTrigger: WorkflowTrigger;-}) => {- const now = new Date();-- // Find all active bounties for the program- const bounties = await prisma.bounty.findMany({- where: {- programId,- workflow: {- trigger: workflowTrigger,- },- startsAt: {- lte: now,- },- OR: [- {- endsAt: {- gte: now,- },- },- {- endsAt: null,- },- ],- },- include: {- groups: true,- workflow: true,- submissions: {- where: {- partnerId,- programId,- },- },- },- });-- if (bounties.length === 0) {- console.log(`Program ${programId} has no active performance bounties.`);- }-- // Find the program enrollment for the partner- const programEnrollment = await prisma.programEnrollment.findUnique({- where: {- partnerId_programId: {- partnerId,- programId,- },- },- select: {- groupId: true,- totalCommissions: true,- links: {- select: {- leads: true,- conversions: true,- saleAmount: true,- },- },- },- });-- if (!programEnrollment) {- console.error(- `Partner ${partnerId} is not enrolled in program ${programId}.`,- );- return;- }-- if (!programEnrollment?.groupId) {- console.error(- `Partner ${partnerId} doesn't belong to any group for program ${programId}.`,- );- return;- }-- // Evaluate each bounty to see if the partner is eligible for it- for (const bounty of bounties) {- if (!bounty.workflow) {- console.error(`Bounty ${bounty.id} has no workflow.`);- continue;- }-- const workflowConditions = z- .array(workflowConditionSchema)- .parse(bounty.workflow.triggerConditions);-- if (workflowConditions.length === 0) {- console.error(- `Bounty ${bounty.id} has no workflow conditions. It seems like workflow configuration is incorrect.`,- );- continue;- }-- console.log(bounty);-- if (bounty.submissions.length > 0) {- console.log(- `Partner ${partnerId} has an existing submission for bounty ${bounty.id}.`,- );- continue;- }-- if (bounty.groups.length > 0) {- const allowedGroupIds = bounty.groups.map(({ groupId }) => groupId);-- if (!allowedGroupIds.includes(programEnrollment.groupId)) {- console.log(- `Partner ${partnerId} is not eligible for bounty ${bounty.id} because they are not in any of the assigned groups.`,- );- continue;- }- }-- // Calculate the metrics- const totalCommission = programEnrollment.totalCommissions;-- const { totalLeads, totalConversions, totalSaleAmount } =- programEnrollment.links.reduce(- (acc, link) => {- acc.totalLeads += link.leads;- acc.totalConversions += link.conversions;- acc.totalSaleAmount += link.saleAmount;- return acc;- },- { totalLeads: 0, totalConversions: 0, totalSaleAmount: 0 },- );-- // Evaluate the workflow condition- // Note: We only support one condition for now- const { attribute, operator, value } = workflowConditions[0];- const operatorFn = OPERATOR_FUNCTIONS[operator];-- if (!operatorFn) {- throw new Error(- `Operator ${operator} is not supported in the workflow trigger condition.`,- );- }-- const context = {- totalCommission,- totalLeads,- totalConversions,- totalSaleAmount,- };-- const isEligible = operatorFn(context[attribute], value);-- if (!isEligible) {- console.log(- `Partner ${partnerId} does not meet the requirements for bounty ${bounty.id}.`,- {- attribute,- value,- context,- },- );- return;- }-- const commission = await createPartnerCommission({- event: "custom",- partnerId,- programId,- amount: 0,- quantity: 1,- description: `Awarded for meeting the requirements for "${bounty.name}" bounty.`,- });-- if (!commission) {- console.error(- `Failed to create commission for partner ${partnerId} in program ${programId} for bounty ${bounty.id}.`,- );- return;- }-- await prisma.bountySubmission.create({- data: {- id: createId({ prefix: "bounty_submission_" }),- programId,- partnerId,- bountyId: bounty.id,- commissionId: commission.id,- status: BountySubmissionStatus.approved,- },- });- }-};diff --git a/apps/web/lib/api/conversions/track-lead.ts b/apps/web/lib/api/conversions/track-lead.tsindex 13e4daca4e..8477610539 100644--- a/apps/web/lib/api/conversions/track-lead.ts+++ b/apps/web/lib/api/conversions/track-lead.ts@@ -19,7 +19,7 @@ import { Customer, WorkflowTrigger } from "@dub/prisma/client";import { nanoid, R2_URL } from "@dub/utils";import { waitUntil } from "@vercel/functions";import { z } from "zod";-import { validatePerformanceBounty } from "../bounties/validate-performance-bounty";+import { executeWorkflows } from "../workflows/execute-workflows";type TrackLeadParams = z.input<typeof trackLeadRequestSchema> & {rawBody: any;@@ -263,10 +263,10 @@ export const trackLead = async ({},});- await validatePerformanceBounty({+ await executeWorkflows({+ trigger: WorkflowTrigger.leadRecorded,programId: link.programId,partnerId: link.partnerId,- workflowTrigger: WorkflowTrigger.leadRecorded,});}diff --git a/apps/web/lib/api/conversions/track-sale.ts b/apps/web/lib/api/conversions/track-sale.tsindex 3611213026..53f8930fcc 100644--- a/apps/web/lib/api/conversions/track-sale.ts+++ b/apps/web/lib/api/conversions/track-sale.ts@@ -16,9 +16,11 @@ import {trackSaleResponseSchema,} from "@/lib/zod/schemas/sales";import { prisma } from "@dub/prisma";+import { WorkflowTrigger } from "@dub/prisma/client";import { nanoid } from "@dub/utils";import { waitUntil } from "@vercel/functions";import { z } from "zod";+import { executeWorkflows } from "../workflows/execute-workflows";type TrackSaleParams = z.input<typeof trackSaleRequestSchema> & {rawBody: any;@@ -244,6 +246,12 @@ export const trackSale = async ({commission,});}++ await executeWorkflows({+ trigger: WorkflowTrigger.saleRecorded,+ programId: link.programId,+ partnerId: link.partnerId,+ });}// Send workspace webhookdiff --git a/apps/web/lib/api/workflows/execute-bounty-workflow.ts b/apps/web/lib/api/workflows/execute-bounty-workflow.tsnew file mode 100644index 0000000000..3dbd31f412--- /dev/null+++ b/apps/web/lib/api/workflows/execute-bounty-workflow.ts@@ -0,0 +1,193 @@+import { createPartnerCommission } from "@/lib/partners/create-partner-commission";+import {+ OPERATOR_FUNCTIONS,+ workflowConditionSchema,+} from "@/lib/zod/schemas/workflows";+import { prisma } from "@dub/prisma";+import { Bounty, BountySubmissionStatus, Workflow } from "@dub/prisma/client";+import { z } from "zod";+import { createId } from "../create-id";++export const executeBountyWorkflow = async ({+ programId,+ partnerId,+ workflow,+ bounty,+}: {+ programId: string;+ partnerId: string;+ workflow: Workflow;+ bounty: Bounty;+}) => {+ console.log(`Executing workflow ${workflow.id} for partner ${partnerId}.`);++ const now = new Date();++ if (bounty.startsAt && bounty.startsAt > now) {+ console.log(`Bounty ${bounty.id} has not started yet.`);+ return;+ }++ if (bounty.endsAt && bounty.endsAt < now) {+ console.log(`Bounty ${bounty.id} has already ended on ${bounty.endsAt}.`);+ return;+ }++ // Find the program enrollment for the partner+ const programEnrollment = await prisma.programEnrollment.findUnique({+ where: {+ partnerId_programId: {+ partnerId,+ programId,+ },+ },+ select: {+ groupId: true,+ totalCommissions: true,+ links: {+ select: {+ leads: true,+ conversions: true,+ saleAmount: true,+ },+ },+ bountySubmission: {+ where: {+ bountyId: bounty.id,+ },+ },+ },+ });++ if (!programEnrollment) {+ console.error(+ `Partner ${partnerId} is not enrolled in program ${programId}.`,+ );+ return;+ }++ if (!programEnrollment?.groupId) {+ console.error(+ `Partner ${partnerId} doesn't belong to any group for program ${programId}.`,+ );+ return;+ }++ if (programEnrollment.bountySubmission.length > 0) {+ console.log(+ `Partner ${partnerId} has an existing submission for bounty ${bounty.id}.`,+ );+ return;+ }++ // Find the groups for the bounty+ const bountyGroups = await prisma.bountyGroup.findMany({+ where: {+ bountyId: bounty.id,+ },+ select: {+ groupId: true,+ },+ });++ // If the bounty is part of a group, check if the partner is in the group+ if (bountyGroups.length > 0) {+ const allowedGroupIds = bountyGroups.map(({ groupId }) => groupId);++ if (!allowedGroupIds.includes(programEnrollment.groupId)) {+ console.log(+ `Partner ${partnerId} is not eligible for bounty ${bounty.id} because they are not in any of the assigned groups.`,+ );+ return;+ }+ }++ // Calculate the metrics+ const totalCommission = programEnrollment.totalCommissions;++ const { totalLeads, totalConversions, totalSaleAmount } =+ programEnrollment.links.reduce(+ (acc, link) => {+ acc.totalLeads += link.leads;+ acc.totalConversions += link.conversions;+ acc.totalSaleAmount += link.saleAmount;+ return acc;+ },+ { totalLeads: 0, totalConversions: 0, totalSaleAmount: 0 },+ );++ // Evaluate the workflow condition+ const workflowConditions = z+ .array(workflowConditionSchema)+ .parse(workflow.triggerConditions);++ if (workflowConditions.length === 0) {+ console.error(+ `Bounty ${bounty.id} has no workflow conditions. It seems like workflow configuration is incorrect.`,+ );+ return;+ }++ // Note: We only support one condition for now+ const { attribute, operator, value } = workflowConditions[0];+ const operatorFn = OPERATOR_FUNCTIONS[operator];++ if (!operatorFn) {+ throw new Error(+ `Operator ${operator} is not supported in the workflow trigger condition.`,+ );+ }++ const context = {+ totalCommission,+ totalLeads,+ totalConversions,+ totalSaleAmount,+ };++ console.log(`Running the workflow with the context`, context);++ const isEligible = operatorFn(context[attribute], value);++ if (!isEligible) {+ console.log(+ `Partner ${partnerId} does not meet the requirements for bounty ${bounty.id}.`,+ {+ attribute,+ value,+ },+ );+ return;+ }++ const commission = await createPartnerCommission({+ event: "custom",+ partnerId,+ programId,+ amount: bounty.rewardAmount,+ quantity: 1,+ description: `Awarded for meeting the requirements for "${bounty.name}" bounty.`,+ });++ if (!commission) {+ console.error(+ `Failed to create commission for partner ${partnerId} in program ${programId} for bounty ${bounty.id}.`,+ );+ return;+ }++ const bountySubmission = await prisma.bountySubmission.create({+ data: {+ id: createId({ prefix: "bounty_submission_" }),+ programId,+ partnerId,+ bountyId: bounty.id,+ commissionId: commission.id,+ status: BountySubmissionStatus.approved,+ },+ });++ console.log(+ `A new bounty submission ${bountySubmission.id} is created for ${partnerId} for the bounty ${bounty.id}.`,+ );+};diff --git a/apps/web/lib/api/workflows/execute-workflows.ts b/apps/web/lib/api/workflows/execute-workflows.tsnew file mode 100644index 0000000000..ff6a53ad71--- /dev/null+++ b/apps/web/lib/api/workflows/execute-workflows.ts@@ -0,0 +1,41 @@+import { prisma } from "@dub/prisma";+import { WorkflowTrigger } from "@dub/prisma/client";+import { executeBountyWorkflow } from "./execute-bounty-workflow";++export async function executeWorkflows({+ programId,+ partnerId,+ trigger,+}: {+ programId: string;+ partnerId: string;+ trigger: WorkflowTrigger;+}) {+ const workflows = await prisma.workflow.findMany({+ where: {+ programId,+ trigger,+ },+ include: {+ bounty: true,+ },+ });++ if (workflows.length === 0) {+ console.log(`Program ${programId} has no workflows to execute.`);+ return;+ }++ await Promise.allSettled(+ workflows+ .filter((wf) => wf.bounty)+ .map((workflow) =>+ executeBountyWorkflow({+ programId,+ partnerId,+ workflow,+ bounty: workflow.bounty!,+ }),+ ),+ );+}diff --git a/packages/prisma/schema/bounty.prisma b/packages/prisma/schema/bounty.prismaindex 7f25345c57..48c8462e18 100644--- a/packages/prisma/schema/bounty.prisma+++ b/packages/prisma/schema/bounty.prisma@@ -64,13 +64,15 @@ model BountySubmission {createdAt DateTime @default(now())updatedAt DateTime @updatedAt- bounty Bounty @relation(fields: [bountyId], references: [id], onDelete: Cascade)- partner Partner @relation(fields: [partnerId], references: [id], onDelete: Cascade)- commission Commission? @relation(fields: [commissionId], references: [id], onDelete: Cascade)- program Program @relation(fields: [programId], references: [id], onDelete: Cascade)- user User? @relation(fields: [userId], references: [id])+ bounty Bounty @relation(fields: [bountyId], references: [id], onDelete: Cascade)+ partner Partner @relation(fields: [partnerId], references: [id], onDelete: Cascade)+ commission Commission? @relation(fields: [commissionId], references: [id], onDelete: Cascade)+ program Program @relation(fields: [programId], references: [id], onDelete: Cascade)+ user User? @relation(fields: [userId], references: [id])+ programEnrollment ProgramEnrollment? @relation(fields: [programId, partnerId], references: [programId, partnerId])@@unique([bountyId, partnerId])+ @@index([programId, partnerId])@@index(programId)@@index(partnerId)@@index(userId)diff --git a/packages/prisma/schema/program.prisma b/packages/prisma/schema/program.prismaindex 24f3f61f4b..ec54dec771 100644--- a/packages/prisma/schema/program.prisma+++ b/packages/prisma/schema/program.prisma@@ -96,15 +96,16 @@ model ProgramEnrollment {bannedAt DateTime?bannedReason PartnerBannedReason?- partner Partner @relation(fields: [partnerId], references: [id], onUpdate: Cascade, onDelete: Cascade)- program Program @relation(fields: [programId], references: [id], onUpdate: Cascade, onDelete: Cascade)- links Link[]- partnerGroup PartnerGroup? @relation(fields: [groupId], references: [id])- application ProgramApplication? @relation(fields: [applicationId], references: [id])- clickReward Reward? @relation("ClickRewardEnrollments", fields: [clickRewardId], references: [id])- leadReward Reward? @relation("LeadRewardEnrollments", fields: [leadRewardId], references: [id])- saleReward Reward? @relation("SaleRewardEnrollments", fields: [saleRewardId], references: [id])- discount Discount? @relation(fields: [discountId], references: [id])+ partner Partner @relation(fields: [partnerId], references: [id], onUpdate: Cascade, onDelete: Cascade)+ program Program @relation(fields: [programId], references: [id], onUpdate: Cascade, onDelete: Cascade)+ links Link[]+ partnerGroup PartnerGroup? @relation(fields: [groupId], references: [id])+ application ProgramApplication? @relation(fields: [applicationId], references: [id])+ clickReward Reward? @relation("ClickRewardEnrollments", fields: [clickRewardId], references: [id])+ leadReward Reward? @relation("LeadRewardEnrollments", fields: [leadRewardId], references: [id])+ saleReward Reward? @relation("SaleRewardEnrollments", fields: [saleRewardId], references: [id])+ discount Discount? @relation(fields: [discountId], references: [id])+ bountySubmission BountySubmission[]@@unique([partnerId, programId])@@unique([tenantId, programId])