The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
improve the workflows
Kiran K12d56d6030aa
diff --git a/apps/web/lib/api/workflows/execute-award-bounty-action.ts b/apps/web/lib/api/workflows/execute-award-bounty-action.tsnew file mode 100644index 0000000000..a8f56fa65d--- /dev/null+++ b/apps/web/lib/api/workflows/execute-award-bounty-action.ts@@ -0,0 +1,108 @@+import { createPartnerCommission } from "@/lib/partners/create-partner-commission";+import { WorkflowAction, WorkflowContext } from "@/lib/types";+import { prisma } from "@dub/prisma";+import { BountySubmissionStatus } from "@dub/prisma/client";+import { createId } from "../create-id";++export const executeAwardBountyAction = async ({+ action,+ context,+}: {+ action: WorkflowAction;+ context: WorkflowContext;+}) => {+ if (action.type !== "awardBounty") {+ console.error(`Skipping workflow action ${action.type}`);+ return;+ }++ const { bountyId } = action.data;+ const { partnerId, groupId } = context;++ // Find the bounty+ const bounty = await prisma.bounty.findUnique({+ where: {+ id: bountyId,+ },+ include: {+ groups: true,+ submissions: {+ where: {+ partnerId,+ },+ },+ },+ });++ console.log(bounty);++ if (!bounty) {+ console.error(`Bounty ${bountyId} not found.`);+ return;+ }++ const now = new Date();++ // Check bounty validity+ 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;+ }++ // Check if the partner has already submitted a submission for this bounty+ if (bounty.submissions.length > 0) {+ console.log(+ `Partner ${partnerId} has an existing submission for bounty ${bounty.id}.`,+ );+ return;+ }++ // If the bounty is part of a group, check if the partner is in the group+ if (bounty.groups.length > 0) {+ const groupIds = bounty.groups.map(({ groupId }) => groupId);++ if (!groupIds.includes(groupId)) {+ console.log(+ `Partner ${partnerId} is not eligible for bounty ${bounty.id} because they are not in any of the assigned groups.`,+ );+ return;+ }+ }++ console.log(`Running the workflow with the context`, context);++ const commission = await createPartnerCommission({+ event: "custom",+ partnerId,+ programId: bounty.programId,+ amount: bounty.rewardAmount,+ quantity: 1,+ });++ if (!commission) {+ console.error(+ `Failed to create commission for partner ${partnerId} in program ${bounty.programId} for bounty ${bounty.id}.`,+ );+ return;+ }++ const bountySubmission = await prisma.bountySubmission.create({+ data: {+ id: createId({ prefix: "bounty_submission_" }),+ programId: bounty.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-bounty-workflow.ts b/apps/web/lib/api/workflows/execute-bounty-workflow.tsdeleted file mode 100644index 6651cb8c14..0000000000--- a/apps/web/lib/api/workflows/execute-bounty-workflow.ts+++ /dev/null@@ -1,192 +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 { 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,- });-- 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.tsindex ff6a53ad71..ee023e9d91 100644--- a/apps/web/lib/api/workflows/execute-workflows.ts+++ b/apps/web/lib/api/workflows/execute-workflows.ts@@ -1,6 +1,17 @@+import {+ WorkflowAction,+ WorkflowCondition,+ WorkflowContext,+} from "@/lib/types";+import {+ OPERATOR_FUNCTIONS,+ workflowActionSchema,+ workflowConditionSchema,+} from "@/lib/zod/schemas/workflows";import { prisma } from "@dub/prisma";import { WorkflowTrigger } from "@dub/prisma/client";-import { executeBountyWorkflow } from "./execute-bounty-workflow";+import { z } from "zod";+import { executeAwardBountyAction } from "./execute-award-bounty-action";export async function executeWorkflows({programId,@@ -16,9 +27,6 @@ export async function executeWorkflows({programId,trigger,},- include: {- bounty: true,- },});if (workflows.length === 0) {@@ -26,16 +34,138 @@ export async function executeWorkflows({return;}- await Promise.allSettled(- workflows- .filter((wf) => wf.bounty)- .map((workflow) =>- executeBountyWorkflow({- programId,- partnerId,- workflow,- bounty: workflow.bounty!,- }),- ),- );+ 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} is not enrolled in a group in program ${programId}.`,+ );+ return;+ }++ 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 },+ );++ const workflowContext: WorkflowContext = {+ partnerId,+ groupId: programEnrollment.groupId,+ totalLeads,+ totalConversions,+ totalSaleAmount,+ totalCommissions: programEnrollment.totalCommissions,+ };++ // Execute each workflow for the program+ for (const workflow of workflows) {+ const conditions = z+ .array(workflowConditionSchema)+ .parse(workflow.triggerConditions);++ if (conditions.length === 0) {+ console.log(`Workflow ${workflow.id} has no trigger conditions.`);+ continue;+ }++ const actions = z.array(workflowActionSchema).parse(workflow.actions);++ if (actions.length === 0) {+ console.log(`Workflow ${workflow.id} has no actions.`);+ }++ // We only support one trigger and action for now+ const condition = conditions[0];+ const action = actions[0];++ const shouldExecute = evaluateWorkflowCondition({+ condition,+ context: workflowContext,+ });++ if (!shouldExecute) {+ console.log(+ `Workflow ${workflow.id} is does not meet the trigger condition.`,+ );+ continue;+ }++ await executeWorkflowAction({+ action,+ context: workflowContext,+ });+ }+}++function evaluateWorkflowCondition({+ condition,+ context,+}: {+ condition: WorkflowCondition;+ context: WorkflowContext;+}) {+ console.log("Evaluating workflow condition", condition, context);++ const operatorFn = OPERATOR_FUNCTIONS[condition.operator];++ if (!operatorFn) {+ throw new Error(+ `Operator ${condition.operator} is not supported in the workflow trigger condition.`,+ );+ }++ return operatorFn(context[condition.attribute], condition.value);+}++async function executeWorkflowAction({+ action,+ context,+}: {+ action: WorkflowAction;+ context: WorkflowContext;+}) {+ switch (action.type) {+ case "awardBounty":+ await executeAwardBountyAction({+ action,+ context,+ });+ break;+ case "sendEmail":+ case "moveToGroup":+ case "triggerWebhook":+ console.log(`Not implemented ${action.type}`);+ break;+ }}diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex dd0fa5731c..cdb2546bf6 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -550,3 +550,12 @@ export type WorkflowComparisonOperator =export type WorkflowAction = z.infer<typeof workflowActionSchema>;export type OperatorFn = (a: number, b: number) => boolean;++export interface WorkflowContext {+ totalCommissions: number;+ totalLeads: number;+ totalConversions: number;+ totalSaleAmount: number;+ partnerId: string+ groupId: string+}