The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
create workflow for performance based bounty
Kiran K3da1d3b6eb9a
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/route.tsindex 0fa1329c30..01b032f7bf 100644--- a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts@@ -30,7 +30,7 @@ export const PATCH = withWorkspace(async ({ workspace, params, req }) => {const programId = getDefaultProgramIdOrThrow(workspace);// TODO: [bounties] Persist performance logic to workflow and groupIds to bountyGroup- const { performanceLogic, groupIds, ...data } = updateBountySchema.parse(+ const { performanceCondition, groupIds, ...data } = updateBountySchema.parse(await parseRequestBody(req),);diff --git a/apps/web/app/(ee)/api/bounties/route.ts b/apps/web/app/(ee)/api/bounties/route.tsindex c35632c2fc..9c3d80b65d 100644--- a/apps/web/app/(ee)/api/bounties/route.ts+++ b/apps/web/app/(ee)/api/bounties/route.ts@@ -2,16 +2,20 @@ import { getBounties } from "@/lib/api/bounties/get-bounties";import { createId } from "@/lib/api/create-id";import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";import { parseRequestBody } from "@/lib/api/utils";-import { createWorkflow } from "@/lib/api/workflows/create-workflow";import { withWorkspace } from "@/lib/auth";+import { WorkflowAction } from "@/lib/types";import {BountySchema,BountySchemaExtended,createBountySchema,getBountiesQuerySchema,} from "@/lib/zod/schemas/bounties";+import {+ WORKFLOW_ACTION_TYPES,+ WORKFLOW_ATTRIBUTE_TRIGGER_MAP,+} from "@/lib/zod/schemas/workflows";import { prisma } from "@dub/prisma";-import { Prisma } from "@prisma/client";+import { Workflow } from "@dub/prisma/client";import { NextResponse } from "next/server";import { z } from "zod";@@ -32,7 +36,6 @@ export const GET = withWorkspace(async ({ workspace, searchParams }) => {export const POST = withWorkspace(async ({ workspace, req }) => {const programId = getDefaultProgramIdOrThrow(workspace);- // TODO: [bounties] Persist performance logic to workflow and groupIds to bountyGroupconst {name,description,@@ -42,21 +45,9 @@ export const POST = withWorkspace(async ({ workspace, req }) => {endsAt,submissionRequirements,groupIds,+ performanceCondition: condition,} = createBountySchema.parse(await parseRequestBody(req));- const workflow = await createWorkflow({- program: {- id: programId,- },- workflow: {- trigger: "clicks",- triggerConditions: {- conditions: [],- },- actions: [],- },- });-const groups = groupIds?.length? await prisma.partnerGroup.findMany({where: {@@ -68,29 +59,56 @@ export const POST = withWorkspace(async ({ workspace, req }) => {}): null;- const bounty = await prisma.bounty.create({- data: {- id: createId({ prefix: "bounty_" }),- programId,- workflowId: workflow.id,- name,- description,- type,- startsAt: startsAt!, // Can remove the ! when we're on a newer TS version (currently 5.4.4)- endsAt,- rewardAmount,- submissionRequirements: submissionRequirements ?? Prisma.JsonNull,+ const bounty = await prisma.$transaction(async (tx) => {+ let workflow: Workflow | null = null;+ const bountyId = createId({ prefix: "bounty_" });- ...(groups?.length && {- groups: {- createMany: {- data: groups?.map((group) => ({- groupId: group.id,- })),- },+ // Create a workflow if there is a performance condition+ if (condition) {+ const action: WorkflowAction = {+ type: WORKFLOW_ACTION_TYPES.AwardBounty,+ data: {+ bountyId,},- }),- },+ };++ workflow = await tx.workflow.create({+ data: {+ id: createId({ prefix: "wf_" }),+ programId,+ trigger: WORKFLOW_ATTRIBUTE_TRIGGER_MAP[condition.attribute],+ triggerConditions: [condition],+ actions: [action],+ },+ });+ }++ // Create a bounty+ return await tx.bounty.create({+ data: {+ id: bountyId,+ programId,+ workflowId: workflow?.id,+ name,+ description,+ type,+ startsAt: startsAt!, // Can remove the ! when we're on a newer TS version (currently 5.4.4)+ endsAt,+ rewardAmount,+ ...(submissionRequirements && {+ submissionRequirements,+ }),+ ...(groups?.length && {+ groups: {+ createMany: {+ data: groups.map(({ id }) => ({+ groupId: id,+ })),+ },+ },+ }),+ },+ });});return NextResponse.json(BountySchema.parse(bounty));diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsxindex 84751da38d..f35d8c8d82 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx@@ -1,16 +1,16 @@+import { isCurrencyAttribute } from "@/lib/api/workflows/utils";import { mutatePrefix } from "@/lib/swr/mutate";import useWorkspace from "@/lib/swr/use-workspace";import {BountyExtendedProps,- BountyPerformanceLogic,BountyProps,+ BountySubmissionRequirement,} from "@/lib/types";+import { createBountySchema } from "@/lib/zod/schemas/bounties";import {- bountyPerformanceLogicSchema,- createBountySchema,- PERFORMANCE_CURRENCY_ACTIVITIES,- SUBMISSION_REQUIREMENTS,-} from "@/lib/zod/schemas/bounties";+ WORKFLOW_CONDITION_ATTRIBUTES_LABELS,+ workflowConditionSchema,+} from "@/lib/zod/schemas/workflows";import { BountyLogic } from "@/ui/partners/bounties/bounty-logic";import { GroupsMultiSelect } from "@/ui/partners/groups/groups-multi-select";import {@@ -52,8 +52,6 @@ type FormData = z.infer<typeof createBountySchema>;export const useAddEditBountyForm = () => useFormContext<FormData>();-type SubmissionRequirement = (typeof SUBMISSION_REQUIREMENTS)[number];-const BOUNTY_TYPES: CardSelectorOption[] = [{key: "performance",@@ -94,12 +92,8 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {type: bounty?.type || "performance",submissionRequirements: bounty?.submissionRequirements || null,groupIds: null,-- // TODO: [bounties] Get existing performance logic from bounty/workflow- performanceLogic: {- activity: undefined,+ performanceCondition: {operator: "gte",- value: undefined,},},});@@ -110,17 +104,18 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {setValue,control,register,- setError,formState: { errors },} = form;- const [startsAt, rewardAmount, type, name, description] = watch([- "startsAt",- "rewardAmount",- "type",- "name",- "description",- ]);+ const [startsAt, rewardAmount, type, name, description, performanceCondition] =+ watch([+ "startsAt",+ "rewardAmount",+ "type",+ "name",+ "description",+ "performanceCondition",+ ]);// Make sure endsAt is null if hasEndDate is falseuseEffect(() => {@@ -131,7 +126,7 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {// Set submission requirementsuseEffect(() => {- const requirements: SubmissionRequirement[] = [];+ const requirements: BountySubmissionRequirement[] = [];if (requireImage) {requirements.push("image");@@ -158,8 +153,25 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {return true;}+ if (+ type === "performance" &&+ ["attribute", "operator", "value"].some(+ (key) => performanceCondition?.[key] === undefined,+ )+ ) {+ return true;+ }+return false;- }, [startsAt, rewardAmount, type, name]);+ }, [+ startsAt,+ rewardAmount,+ type,+ name,+ performanceCondition?.attribute,+ performanceCondition?.operator,+ performanceCondition?.value,+ ]);// Handle form submissionconst onSubmit = async (data: FormData) => {@@ -167,41 +179,36 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {data.rewardAmount = data.rewardAmount * 100;+ // Parse performance logicif (data.type === "performance") {- data.submissionRequirements = null;-- let performanceLogic: BountyPerformanceLogic | null = null;- if (data.performanceLogic) {- try {- const isCurrency = PERFORMANCE_CURRENCY_ACTIVITIES.includes(- data.performanceLogic.activity,- );-- performanceLogic = bountyPerformanceLogicSchema.parse({- ...data.performanceLogic,- value: isCurrency- ? data.performanceLogic.value * 100- : data.performanceLogic.value,- });-- data.name =- `Earn ${currencyFormatter(data.rewardAmount / 100)} after generating ` +- `${isCurrency ? `${currencyFormatter(performanceLogic.value)} in` : performanceLogic.value} ` +- performanceLogic.activity;- } catch (error) {- console.error(error);- setError("root.performanceLogic", {- message: "Invalid performance logic",- });- toast.error(- "Invalid performance logic. Please fix the errors and try again.",- );- return;- }-- data.performanceLogic = performanceLogic;+ const result = workflowConditionSchema.safeParse(data.performanceCondition);++ if (!result.success) {+ toast.error(+ "Invalid performance logic. Please fix the errors and try again.",+ );+ return;}- } else data.performanceLogic = null;++ let { data: condition } = result;+ const isCurrency = isCurrencyAttribute(condition.attribute);++ // Format the value to be in cents if it's a currency attribute+ condition = {+ ...condition,+ value: isCurrency ? condition.value * 100 : condition.value,+ };++ data.performanceCondition = condition;++ // Generate a name+ data.name =+ `Earn ${currencyFormatter(data.rewardAmount / 100)} after generating ` ++ `${isCurrency ? `${currencyFormatter(condition.value / 100)} in` : condition.value} ` ++ WORKFLOW_CONDITION_ATTRIBUTES_LABELS[condition.attribute];+ } else if (type === "submission") {+ data.performanceCondition = null;+ }await makeRequest(bounty ? `/api/bounties/${bounty.id}` : "/api/bounties", {method: bounty ? "PATCH" : "POST",diff --git a/apps/web/lib/api/workflows/create-workflow.ts b/apps/web/lib/api/workflows/create-workflow.tsdeleted file mode 100644index e5b6b77ba7..0000000000--- a/apps/web/lib/api/workflows/create-workflow.ts+++ /dev/null@@ -1,23 +0,0 @@-import { ProgramProps } from "@/lib/types";-import { createWorkflowSchema } from "@/lib/zod/schemas/workflows";-import { prisma } from "@dub/prisma";-import { z } from "zod";-import { createId } from "../create-id";--export const createWorkflow = async ({- workflow,- program,-}: {- workflow: z.input<typeof createWorkflowSchema>;- program: Pick<ProgramProps, "id">;-}) => {- return await prisma.workflow.create({- data: {- id: createId({ prefix: "wf_" }),- programId: program.id,- trigger: workflow.trigger,- triggerConditions: workflow.triggerConditions,- actions: workflow.actions,- },- });-};diff --git a/apps/web/lib/api/workflows/utils.ts b/apps/web/lib/api/workflows/utils.tsnew file mode 100644index 0000000000..61741b354e--- /dev/null+++ b/apps/web/lib/api/workflows/utils.ts@@ -0,0 +1,4 @@+import { WorkflowConditionAttribute } from "@/lib/types";++export const isCurrencyAttribute = (activity: WorkflowConditionAttribute) =>+ activity === "totalCommission" || activity === "totalSaleAmount";diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex a13fad679b..cfe257b426 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -24,10 +24,10 @@ import {} from "./folder/constants";import { WEBHOOK_TRIGGER_DESCRIPTIONS } from "./webhook/constants";import {- bountyPerformanceLogicSchema,BountySchema,BountySchemaExtended,BountySubmissionSchema,+ SUBMISSION_REQUIREMENTS,} from "./zod/schemas/bounties";import {clickEventResponseSchema,@@ -94,6 +94,12 @@ import {webhookEventSchemaTB,WebhookSchema,} from "./zod/schemas/webhooks";+import {+ WORKFLOW_COMPARISON_OPERATORS,+ WORKFLOW_CONDITION_ATTRIBUTES,+ workflowActionSchema,+ workflowConditionSchema,+} from "./zod/schemas/workflows";import { workspacePreferencesSchema } from "./zod/schemas/workspace-preferences";export type LinkProps = Link;@@ -516,12 +522,21 @@ export type GroupProps = z.infer<typeof GroupSchema>;export type GroupExtendedProps = z.infer<typeof GroupSchemaExtended>;-export type BountyPerformanceLogic = z.infer<- typeof bountyPerformanceLogicSchema->;-export type BountyProps = z.infer<typeof BountySchema>;export type BountyExtendedProps = z.infer<typeof BountySchemaExtended>;export type BountySubmissionProps = z.infer<typeof BountySubmissionSchema>;++export type BountySubmissionRequirement =+ (typeof SUBMISSION_REQUIREMENTS)[number];++export type WorkflowCondition = z.infer<typeof workflowConditionSchema>;++export type WorkflowConditionAttribute =+ (typeof WORKFLOW_CONDITION_ATTRIBUTES)[number];++export type WorkflowComparisonOperator =+ (typeof WORKFLOW_COMPARISON_OPERATORS)[number];++export type WorkflowAction = z.infer<typeof workflowActionSchema>;diff --git a/apps/web/lib/zod/schemas/bounties.ts b/apps/web/lib/zod/schemas/bounties.tsindex 51eaf74b51..90688772f6 100644--- a/apps/web/lib/zod/schemas/bounties.ts+++ b/apps/web/lib/zod/schemas/bounties.ts@@ -5,34 +5,10 @@ import { booleanQuerySchema, getPaginationQuerySchema } from "./misc";import { PartnerSchema } from "./partners";import { UserSchema } from "./users";import { parseDateSchema } from "./utils";+import { workflowConditionSchema } from "./workflows";export const SUBMISSION_REQUIREMENTS = ["image", "url"] as const;-export const PERFORMANCE_ACTIVITIES = [- "earnings",- "revenue",- "clicks",- "click earnings",- "leads",- "lead earnings",- "sales",- "sale earnings",-] as const;--export const PERFORMANCE_CURRENCY_ACTIVITIES = [- "click earnings",- "lead earnings",- "sale earnings",- "earnings",- "revenue",-];--export const bountyPerformanceLogicSchema = z.object({- activity: z.enum(PERFORMANCE_ACTIVITIES),- operator: z.enum(["gte"]).default("gte"),- value: z.number().min(0, "Logic value must be at least 0"),-});-const bountySubmissionRequirementsSchema = z.array(z.enum(SUBMISSION_REQUIREMENTS)).min(0)@@ -54,8 +30,8 @@ export const createBountySchema = z.object({endsAt: parseDateSchema.nullish(),rewardAmount: z.number().min(1, "Reward amount must be greater than 1"),submissionRequirements: bountySubmissionRequirementsSchema.nullish(),- performanceLogic: bountyPerformanceLogicSchema.nullish(),groupIds: z.array(z.string()).nullable(),+ performanceCondition: workflowConditionSchema.nullish(),});export const updateBountySchema = createBountySchema;diff --git a/apps/web/lib/zod/schemas/workflows.ts b/apps/web/lib/zod/schemas/workflows.tsindex bfaedbfccd..5ac30ebfaa 100644--- a/apps/web/lib/zod/schemas/workflows.ts+++ b/apps/web/lib/zod/schemas/workflows.ts@@ -1,3 +1,7 @@+import {+ WorkflowComparisonOperator,+ WorkflowConditionAttribute,+} from "@/lib/types";import { WorkflowTrigger } from "@dub/prisma/client";import { z } from "zod";@@ -8,22 +12,49 @@ export const WORKFLOW_CONDITION_ATTRIBUTES = ["totalCommission",] as const;-export const WORKFLOW_ACTION_TYPES = [- "sendEmail",- "moveToGroup",- "awardBounty",- "triggerWebhook",-] as const;+export const WORKFLOW_CONDITION_ATTRIBUTES_LABELS: Record<+ WorkflowConditionAttribute,+ string+> = {+ totalLeads: "total leads",+ totalConversions: "total conversions",+ totalSaleAmount: "total sale amount",+ totalCommission: "total commission",+} as const;++export const WORKFLOW_ATTRIBUTE_TRIGGER_MAP: Record<+ WorkflowConditionAttribute,+ WorkflowTrigger+> = {+ totalLeads: WorkflowTrigger.leadRecorded,+ totalConversions: WorkflowTrigger.saleRecorded,+ totalSaleAmount: WorkflowTrigger.saleRecorded,+ totalCommission: WorkflowTrigger.commissionEarned,+} as const;export const WORKFLOW_COMPARISON_OPERATORS = ["gte"] as const;+export const WORKFLOW_COMPARISON_OPERATOR_LABELS: Record<+ WorkflowComparisonOperator,+ string+> = {+ gte: "more than",+} as const;++export enum WORKFLOW_ACTION_TYPES {+ SendEmail = "sendEmail",+ MoveToGroup = "moveToGroup",+ AwardBounty = "awardBounty",+ TriggerWebhook = "triggerWebhook",+}+export const WORKFLOW_LOGICAL_OPERATORS = ["AND"] as const;// Individual condition-const workflowConditionSchema = z.object({+export const workflowConditionSchema = z.object({attribute: z.enum(WORKFLOW_CONDITION_ATTRIBUTES),operator: z.enum(WORKFLOW_COMPARISON_OPERATORS),- value: z.union([z.string(), z.number()]),+ value: z.number(),});// Array of conditions with AND operator@@ -33,7 +64,7 @@ export const workflowConditionsSchema = z.object({});// Individual action-const workflowActionSchema = z.discriminatedUnion("type", [+export const workflowActionSchema = z.discriminatedUnion("type", [z.object({type: z.literal("sendEmail"),data: z.object({diff --git a/apps/web/ui/partners/bounties/bounty-logic.tsx b/apps/web/ui/partners/bounties/bounty-logic.tsxindex 56cb35a02b..71950fbac5 100644--- a/apps/web/ui/partners/bounties/bounty-logic.tsx+++ b/apps/web/ui/partners/bounties/bounty-logic.tsx@@ -1,8 +1,9 @@+import { isCurrencyAttribute } from "@/lib/api/workflows/utils";import { handleMoneyInputChange, handleMoneyKeyDown } from "@/lib/form-utils";import {- PERFORMANCE_ACTIVITIES,- PERFORMANCE_CURRENCY_ACTIVITIES,-} from "@/lib/zod/schemas/bounties";+ WORKFLOW_CONDITION_ATTRIBUTES,+ WORKFLOW_CONDITION_ATTRIBUTES_LABELS,+} from "@/lib/zod/schemas/workflows";import {InlineBadgePopover,InlineBadgePopoverContext,@@ -17,17 +18,15 @@ import { Controller } from "react-hook-form";export function BountyLogic({ className }: { className?: string }) {const { control, watch } = useAddEditBountyForm();- const [activity, value] = watch([- "performanceLogic.activity",- "performanceLogic.value",+ const [attribute, value] = watch([+ "performanceCondition.attribute",+ "performanceCondition.value",]);- const isCurrency = PERFORMANCE_CURRENCY_ACTIVITIES.includes(activity);-return (<divclassName={cn(- "block flex w-full items-center gap-1.5 rounded-md border border-neutral-300 px-3 py-2",+ "flex w-full items-center gap-1.5 rounded-md border border-neutral-300 px-3 py-2",className,)}>@@ -38,31 +37,35 @@ export function BountyLogic({ className }: { className?: string }) {When partner{" "}<Controllercontrol={control}- name="performanceLogic.activity"+ name="performanceCondition.attribute"render={({ field }) => (<InlineBadgePopover- text={field.value ?? "activity"}+ text={+ field.value+ ? WORKFLOW_CONDITION_ATTRIBUTES_LABELS[field.value]+ : "activity"+ }invalid={!field.value}><InlineBadgePopoverMenuselectedValue={field.value}onSelect={field.onChange}- items={PERFORMANCE_ACTIVITIES.map((activity) => ({- text: activity,- value: activity,+ items={WORKFLOW_CONDITION_ATTRIBUTES.map((attribute) => ({+ text: WORKFLOW_CONDITION_ATTRIBUTES_LABELS[attribute],+ value: attribute,}))}/></InlineBadgePopover>)}/>- {activity && (+ {attribute && (<>{" "}is at least{" "}<InlineBadgePopovertext={value- ? isCurrency+ ? isCurrencyAttribute(attribute)? currencyFormatter(value): value: "amount"@@ -80,13 +83,11 @@ export function BountyLogic({ className }: { className?: string }) {function ValueInput() {const { watch, register } = useAddEditBountyForm();-- const activity = watch("performanceLogic.activity");-- const isCurrency = PERFORMANCE_CURRENCY_ACTIVITIES.includes(activity);-const { setIsOpen } = useContext(InlineBadgePopoverContext);+ const attribute = watch("performanceCondition.attribute");+ const isCurrency = isCurrencyAttribute(attribute);+return (<div className="relative rounded-md shadow-sm">{isCurrency && (@@ -99,7 +100,7 @@ function ValueInput() {"block w-full rounded-md border-neutral-300 px-1.5 py-1 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:w-32 sm:text-sm",isCurrency ? "pl-4 pr-12" : "pr-7",)}- {...register("performanceLogic.value", {+ {...register("performanceCondition.value", {required: true,setValueAs: (value: string) => (value === "" ? undefined : +value),min: 0,diff --git a/packages/prisma/client.ts b/packages/prisma/client.tsindex a84620bc3c..64d820ad39 100644--- a/packages/prisma/client.ts+++ b/packages/prisma/client.ts@@ -21,4 +21,5 @@ export {Role,WebhookReceiver,WorkflowTrigger,+ WorkflowTriggerType,} from "@prisma/client";diff --git a/packages/prisma/schema/workflow.prisma b/packages/prisma/schema/workflow.prismaindex 88803985c9..6b6f74ae7c 100644--- a/packages/prisma/schema/workflow.prisma+++ b/packages/prisma/schema/workflow.prisma@@ -16,7 +16,7 @@ model Workflow {programId Stringname String?trigger WorkflowTrigger- triggerType WorkflowTriggerType+ triggerType WorkflowTriggerType @default(event)triggerConditions Json?actions Json?createdAt DateTime @default(now())