The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
wip
Kiran Ke27839b73189
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.tsindex 0d874b25be..6a265edec1 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts@@ -382,6 +382,11 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {trigger: WorkflowTrigger.saleRecorded,programId: link.programId,partnerId: link.partnerId,+ context: {+ recent: {+ saleAmount: saleData.amount,+ }+ }}),// same logic as lead.created webhook below:// if the clickEvent variable exists and there was no existing customer before,@@ -392,6 +397,11 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {trigger: WorkflowTrigger.leadRecorded,programId: link.programId,partnerId: link.partnerId,+ context: {+ recent: {+ leads: 1,+ },+ },}),]),);diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils.tsindex 1219607b98..0985426324 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/utils.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils.ts@@ -136,6 +136,11 @@ export async function createNewCustomer(event: Stripe.Event) {trigger: WorkflowTrigger.leadRecorded,programId: link.programId,partnerId: link.partnerId,+ context: {+ recent: {+ leads: 1,+ },+ },}),]),);diff --git a/apps/web/lib/api/conversions/track-lead.ts b/apps/web/lib/api/conversions/track-lead.tsindex 8f01d5a847..270b840231 100644--- a/apps/web/lib/api/conversions/track-lead.ts+++ b/apps/web/lib/api/conversions/track-lead.ts@@ -319,6 +319,11 @@ export const trackLead = async ({trigger: WorkflowTrigger.leadRecorded,programId: link.programId,partnerId: link.partnerId,+ context: {+ recent: {+ leads: 1,+ },+ },});}diff --git a/apps/web/lib/api/conversions/track-sale.ts b/apps/web/lib/api/conversions/track-sale.tsindex c9fca4eb72..67f5d02cdf 100644--- a/apps/web/lib/api/conversions/track-sale.ts+++ b/apps/web/lib/api/conversions/track-sale.ts@@ -366,6 +366,11 @@ const _trackLead = async ({trigger: WorkflowTrigger.leadRecorded,programId: link.programId,partnerId: link.partnerId,+ context: {+ recent: {+ leads: 1,+ },+ },});}diff --git a/apps/web/lib/api/workflows/execute-award-bounty-action.ts b/apps/web/lib/api/workflows/execute-award-bounty-action.tsindex db39c6a7a7..9240e36a6c 100644--- a/apps/web/lib/api/workflows/execute-award-bounty-action.ts+++ b/apps/web/lib/api/workflows/execute-award-bounty-action.ts@@ -1,16 +1,23 @@import { createPartnerCommission } from "@/lib/partners/create-partner-commission";-import { WorkflowAction, WorkflowContext } from "@/lib/types";+import {+ WorkflowAction,+ WorkflowCondition,+ WorkflowContext,+} from "@/lib/types";import { sendEmail } from "@dub/email";import BountyCompleted from "@dub/email/templates/bounty-completed";import { prisma } from "@dub/prisma";import { createId } from "../create-id";+import { evaluateWorkflowCondition } from "./execute-workflows";export const executeAwardBountyAction = async ({- action,+ condition,context,+ action,}: {- action: WorkflowAction;+ condition: WorkflowCondition;context: WorkflowContext;+ action: WorkflowAction;}) => {if (action.type !== "awardBounty") {return;@@ -45,6 +52,12 @@ export const executeAwardBountyAction = async ({return;}+ // this won't happen as we create workflows for performance based bounties only+ if (bounty.type !== "performance") {+ console.error(`Bounty ${bountyId} is not a performance based bounty.`);+ return;+ }+const now = new Date();// Check bounty validity@@ -64,10 +77,14 @@ export const executeAwardBountyAction = async ({// Check if the partner has already submitted a submission for this bountyif (submissions.length > 0) {- console.log(- `Partner ${partnerId} has an existing submission for bounty ${bounty.id}.`,- );- return;+ const submission = submissions[0];++ if (submission.status !== "draft") {+ console.log(+ `Partner ${partnerId} has an existing submission for bounty ${bounty.id} with status ${submission.status}.`,+ );+ return;+ }}// If the bounty is part of a group, check if the partner is in the group@@ -82,6 +99,61 @@ export const executeAwardBountyAction = async ({}}+ // Find the count to increment+ let count = 0;++ if (condition.attribute === "totalLeads") {+ count = context.recent.leads ?? 0;+ } else if (condition.attribute === "totalConversions") {+ count = context.recent.conversions ?? 0;+ } else if (condition.attribute === "totalSaleAmount") {+ count = context.recent.saleAmount ?? 0;+ } else if (condition.attribute === "totalCommissions") {+ count = context.recent.commissions ?? 0;+ }++ // Create or update the submission+ const bountySubmission = await prisma.bountySubmission.upsert({+ where: {+ bountyId_partnerId: {+ bountyId,+ partnerId,+ },+ },+ create: {+ id: createId({ prefix: "bnty_sub_" }),+ programId: bounty.programId,+ partnerId,+ bountyId: bounty.id,+ status: "draft",+ count,+ },+ update: {+ count: {+ increment: count,+ },+ },+ });++ // Check if the bounty submission meet the reward criteria+ const shouldExecute = evaluateWorkflowCondition({+ condition,+ context: {+ totalLeads: 0,+ totalConversions: 0,+ totalSaleAmount: 0,+ totalCommissions: 0,+ [condition.attribute]: bountySubmission.count, // override the attribute+ },+ });++ if (!shouldExecute) {+ console.log(+ `Bounty submission ${bountySubmission.id} does not meet the trigger condition.`,+ );+ return;+ }+const commission = await createPartnerCommission({event: "custom",partnerId,@@ -99,24 +171,19 @@ export const executeAwardBountyAction = async ({return;}- const { id: bountySubmissionId, partner } =- await prisma.bountySubmission.create({- data: {- id: createId({ prefix: "bnty_sub_" }),- programId: bounty.programId,- partnerId,- bountyId: bounty.id,- commissionId: commission.id,- status: "approved",- },- include: {- partner: true,- },- });-- console.log(- `A new bounty submission ${bountySubmissionId} is created for ${partnerId} for the bounty ${bounty.id}.`,- );+ // Update the bounty submission+ const { partner } = await prisma.bountySubmission.update({+ where: {+ id: bountySubmission.id,+ },+ data: {+ commissionId: commission.id,+ status: "approved",+ },+ include: {+ partner: true,+ },+ });if (partner.email) {await sendEmail({diff --git a/apps/web/lib/api/workflows/execute-workflows.ts b/apps/web/lib/api/workflows/execute-workflows.tsindex f4f7dc7d1f..70c50abbd5 100644--- a/apps/web/lib/api/workflows/execute-workflows.ts+++ b/apps/web/lib/api/workflows/execute-workflows.ts@@ -1,7 +1,6 @@-import { aggregatePartnerLinksStats } from "@/lib/partners/aggregate-partner-links-stats";import {- WorkflowAction,WorkflowCondition,+ WorkflowConditionAttribute,WorkflowContext,} from "@/lib/types";import {@@ -18,10 +17,12 @@ export async function executeWorkflows({programId,partnerId,trigger,+ context,}: {programId: string;partnerId: string;trigger: WorkflowTrigger;+ context?: Pick<WorkflowContext, "recent">;}) {const workflows = await prisma.workflow.findMany({where: {@@ -42,17 +43,8 @@ export async function executeWorkflows({},},select: {+ partnerId: true,groupId: true,- totalCommissions: true,- links: {- select: {- clicks: true,- sales: true,- leads: true,- conversions: true,- saleAmount: true,- },- },},});@@ -70,18 +62,15 @@ export async function executeWorkflows({return;}- const { totalLeads, totalConversions, totalSaleAmount } =- aggregatePartnerLinksStats(programEnrollment.links);-+ // Final context for the workflowconst workflowContext: WorkflowContext = {- partnerId,+ partnerId: programEnrollment.partnerId,groupId: programEnrollment.groupId,- totalLeads,- totalConversions,- totalSaleAmount,- totalCommissions: programEnrollment.totalCommissions,+ recent: context?.recent ?? {},};+ console.log("Workflow context", workflowContext);+// Execute each workflow for the programfor (const workflow of workflows) {const conditions = z@@ -102,31 +91,34 @@ export async function executeWorkflows({const condition = conditions[0];const action = actions[0];- const shouldExecute = evaluateWorkflowCondition({- condition,- context: workflowContext,- });+ // const shouldExecute = evaluateWorkflowCondition({+ // condition,+ // context: workflowContext,+ // });- if (!shouldExecute) {- console.log(- `Workflow ${workflow.id} does not meet the trigger condition.`,- );- continue;- }+ // if (!shouldExecute) {+ // console.log(+ // `Workflow ${workflow.id} does not meet the trigger condition.`,+ // );+ // continue;+ // }- await executeWorkflowAction({- action,- context: workflowContext,- });+ if (action.type === "awardBounty") {+ await executeAwardBountyAction({+ condition,+ context: workflowContext,+ action,+ });+ }}}-function evaluateWorkflowCondition({+export function evaluateWorkflowCondition({condition,context,}: {condition: WorkflowCondition;- context: WorkflowContext;+ context: Record<WorkflowConditionAttribute, number>;}) {console.log("Evaluating workflow condition", condition, context);@@ -140,20 +132,3 @@ function evaluateWorkflowCondition({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;- }-}diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex 97bc8162d1..b3513240a2 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -582,16 +582,26 @@ export type WorkflowAction = z.infer<typeof workflowActionSchema>;export type OperatorFn = (a: number, b: number) => boolean;export interface WorkflowContext {- totalLeads: number;- totalConversions: number;- totalSaleAmount: number;- totalCommissions: number;partnerId: string;groupId: string;+ // All time metrics+ // historical: {+ // leads: number;+ // conversions: number;+ // saleAmount: number;+ // commissions: number;+ // };+ // Recent metrics+ recent: {+ leads?: number;+ conversions?: number;+ saleAmount?: number;+ commissions?: number;+ };}export type BountySubmissionsQueryFilters = z.infer<typeof getBountySubmissionsQuerySchema>;-export type Message = z.infer<typeof MessageSchema>;+export type Message = z.infer<typeof MessageSchema>;\ No newline at end of filediff --git a/packages/prisma/schema/bounty.prisma b/packages/prisma/schema/bounty.prismaindex 09ac2e7bd6..17f96f1f42 100644--- a/packages/prisma/schema/bounty.prisma+++ b/packages/prisma/schema/bounty.prisma@@ -25,6 +25,7 @@ model Bounty {name Stringdescription String? @db.Texttype BountyType+ currentStatsOnly Boolean @default(false)startsAt DateTimeendsAt DateTime?rewardAmount Int?@@ -59,6 +60,7 @@ model BountySubmission {programId StringpartnerId StringbountyId String+ count Int?commissionId String? @uniqueuserId String?description String? @db.Text