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.

Derive workflow attribute and operator keys from definitions

Kiran Kac5e7cad5355
diff --git a/apps/web/lib/api/workflows/attribute-definitions.ts b/apps/web/lib/api/workflows/attribute-definitions.ts
index 850fc4d78d..84a32a804a 100644
--- a/apps/web/lib/api/workflows/attribute-definitions.ts
+++ b/apps/web/lib/api/workflows/attribute-definitions.ts
@@ -43,3 +43,9 @@ export const WORKFLOW_ATTRIBUTES = {
operators: ["gte"],
},
} as const;
+
+export const WORKFLOW_ATTRIBUTE_KEYS = Object.keys(
+ WORKFLOW_ATTRIBUTES,
+) as readonly (keyof typeof WORKFLOW_ATTRIBUTES)[];
+
+export type WorkflowAttributeKey = (typeof WORKFLOW_ATTRIBUTE_KEYS)[number];
diff --git a/apps/web/lib/api/workflows/award-bounty/execute.ts b/apps/web/lib/api/workflows/award-bounty/execute.ts
index 48e6d4efa4..26c83d3e37 100644
--- a/apps/web/lib/api/workflows/award-bounty/execute.ts
+++ b/apps/web/lib/api/workflows/award-bounty/execute.ts
@@ -1,8 +1,5 @@
import { evaluateWorkflowConditions } from "@/lib/api/workflows/evaluate-workflow-conditions";
-import {
- WorkflowConditionAttribute,
- WorkflowContext,
-} from "@/lib/api/workflows/types";
+import { WorkflowContext } from "@/lib/api/workflows/types";
import { prisma } from "@/lib/prisma";
import { WORKFLOW_ACTION_TYPES } from "@/lib/zod/schemas/workflows";
import { sendBatchEmail, sendEmail } from "@dub/email";
@@ -15,6 +12,7 @@ import {
} from "@prisma/client";
import { createId } from "../../create-id";
import { getWorkspaceUsers } from "../../get-workspace-users";
+import { WorkflowAttributeKey } from "../attribute-definitions";
import { parseWorkflowConfig } from "../parse-workflow-config";
const terminalStatusReason: Record<
@@ -136,9 +134,7 @@ export const executeAwardBountyWorkflow = async ({
`Partner is eligible for bounty ${bounty.id}, executing workflow ${bounty.workflowId}...`,
);
- const finalContext: Partial<
- Record<WorkflowConditionAttribute, number | null>
- > = {
+ const finalContext: Partial<Record<WorkflowAttributeKey, number | null>> = {
totalLeads: metrics?.current?.leads ?? 0,
totalConversions: metrics?.current?.conversions ?? 0,
totalSaleAmount: metrics?.current?.saleAmount ?? 0,
diff --git a/apps/web/lib/api/workflows/evaluate-workflow-conditions.ts b/apps/web/lib/api/workflows/evaluate-workflow-conditions.ts
index 5c32c708e7..10814c2283 100644
--- a/apps/web/lib/api/workflows/evaluate-workflow-conditions.ts
+++ b/apps/web/lib/api/workflows/evaluate-workflow-conditions.ts
@@ -1,7 +1,5 @@
-import {
- WorkflowCondition,
- WorkflowConditionAttribute,
-} from "@/lib/api/workflows/types";
+import { WorkflowCondition } from "@/lib/api/workflows/types";
+import { WorkflowAttributeKey } from "./attribute-definitions";
import { WORKFLOW_OPERATORS } from "./operator-definitions";
export function evaluateWorkflowConditions({
@@ -9,7 +7,7 @@ export function evaluateWorkflowConditions({
attributes,
}: {
conditions: WorkflowCondition[];
- attributes: Partial<Record<WorkflowConditionAttribute, number | null>>;
+ attributes: Partial<Record<WorkflowAttributeKey, number | null>>;
}): boolean {
if (conditions.length === 0) return false;
diff --git a/apps/web/lib/api/workflows/execute-workflows.ts b/apps/web/lib/api/workflows/execute-workflows.ts
index f1462df985..d50aa283d9 100644
--- a/apps/web/lib/api/workflows/execute-workflows.ts
+++ b/apps/web/lib/api/workflows/execute-workflows.ts
@@ -1,11 +1,9 @@
-import {
- WorkflowConditionAttribute,
- WorkflowContext,
-} from "@/lib/api/workflows/types";
+import { WorkflowContext } from "@/lib/api/workflows/types";
import { aggregatePartnerLinksStats } from "@/lib/partners/aggregate-partner-links-stats";
import { prisma } from "@/lib/prisma";
import { WORKFLOW_ACTION_TYPES } from "@/lib/zod/schemas/workflows";
import { Workflow } from "@prisma/client";
+import { WorkflowAttributeKey } from "./attribute-definitions";
import { executeAwardBountyWorkflow } from "./award-bounty/execute";
import { executeMoveGroupWorkflow } from "./move-group/execute";
import { parseWorkflowConfig } from "./parse-workflow-config";
@@ -36,7 +34,7 @@ const ACTION_HANDLERS: Record<WORKFLOW_ACTION_TYPES, WorkflowActionHandler> = {
// This prevents workflows from executing unnecessarily
const REASON_TO_ATTRIBUTES: Record<
NonNullable<WorkflowContext["reason"]>,
- WorkflowConditionAttribute[]
+ WorkflowAttributeKey[]
> = {
lead: ["totalLeads"],
sale: ["totalConversions", "totalSaleAmount"],
diff --git a/apps/web/lib/api/workflows/move-group/execute.ts b/apps/web/lib/api/workflows/move-group/execute.ts
index 8145dc9f67..15f681edf7 100644
--- a/apps/web/lib/api/workflows/move-group/execute.ts
+++ b/apps/web/lib/api/workflows/move-group/execute.ts
@@ -1,12 +1,10 @@
-import {
- WorkflowConditionAttribute,
- WorkflowContext,
-} from "@/lib/api/workflows/types";
+import { WorkflowContext } from "@/lib/api/workflows/types";
import { prisma } from "@/lib/prisma";
import { redis } from "@/lib/upstash/redis";
import { WORKFLOW_ACTION_TYPES } from "@/lib/zod/schemas/workflows";
import { Workflow } from "@prisma/client";
import { movePartnersToGroup } from "../../groups/move-partners-to-group";
+import { WorkflowAttributeKey } from "../attribute-definitions";
import { evaluateWorkflowConditions } from "../evaluate-workflow-conditions";
import { parseWorkflowConfig } from "../parse-workflow-config";
@@ -65,13 +63,12 @@ export const executeMoveGroupWorkflow = async ({
return;
}
- const attributes: Partial<Record<WorkflowConditionAttribute, number | null>> =
- {
- totalLeads: metrics?.aggregated?.leads ?? 0,
- totalConversions: metrics?.aggregated?.conversions ?? 0,
- totalSaleAmount: metrics?.aggregated?.saleAmount ?? 0,
- totalCommissions: metrics?.aggregated?.commissions ?? 0,
- };
+ const attributes: Partial<Record<WorkflowAttributeKey, number | null>> = {
+ totalLeads: metrics?.aggregated?.leads ?? 0,
+ totalConversions: metrics?.aggregated?.conversions ?? 0,
+ totalSaleAmount: metrics?.aggregated?.saleAmount ?? 0,
+ totalCommissions: metrics?.aggregated?.commissions ?? 0,
+ };
const shouldExecute = evaluateWorkflowConditions({
conditions,
diff --git a/apps/web/lib/api/workflows/operator-definitions.ts b/apps/web/lib/api/workflows/operator-definitions.ts
index b4cbbc71c9..55cdf3a75d 100644
--- a/apps/web/lib/api/workflows/operator-definitions.ts
+++ b/apps/web/lib/api/workflows/operator-definitions.ts
@@ -1,28 +1,23 @@
-import { WorkflowComparisonOperator } from "@/lib/api/workflows/types";
-
type ConditionValue = number | { min: number; max?: number };
type WorkflowOperator = {
- name: WorkflowComparisonOperator;
+ name: string;
label: string;
validate: (value: ConditionValue) => void;
evaluate: (attributeValue: number, conditionValue: ConditionValue) => boolean;
};
-export const WORKFLOW_OPERATORS: Record<
- WorkflowComparisonOperator,
- WorkflowOperator
-> = {
+export const WORKFLOW_OPERATORS = {
// Greater than or equal to
gte: {
name: "gte",
label: "at least",
- validate(value) {
+ validate(value: ConditionValue) {
if (typeof value !== "number" || isNaN(value) || value <= 0) {
throw new Error("Please enter a value greater than 0.");
}
},
- evaluate(attributeValue, conditionValue) {
+ evaluate(attributeValue: number, conditionValue: ConditionValue) {
if (typeof conditionValue !== "number") {
return false;
}
@@ -35,7 +30,7 @@ export const WORKFLOW_OPERATORS: Record<
between: {
name: "between",
label: "between",
- validate(value) {
+ validate(value: ConditionValue) {
if (typeof value !== "object" || value === null) {
throw new Error("Please enter a valid value.");
}
@@ -55,7 +50,7 @@ export const WORKFLOW_OPERATORS: Record<
throw new Error("Maximum value must be greater than minimum value.");
}
},
- evaluate(attributeValue, conditionValue) {
+ evaluate(attributeValue: number, conditionValue: ConditionValue) {
if (typeof conditionValue !== "object" || conditionValue === null) {
return false;
}
@@ -69,4 +64,8 @@ export const WORKFLOW_OPERATORS: Record<
return attributeValue >= min && attributeValue <= max;
},
},
-};
+} satisfies Record<string, WorkflowOperator>;
+
+export const WORKFLOW_OPERATOR_KEYS = Object.keys(
+ WORKFLOW_OPERATORS,
+) as readonly (keyof typeof WORKFLOW_OPERATORS)[];
diff --git a/apps/web/lib/api/workflows/send-campaign/execute.ts b/apps/web/lib/api/workflows/send-campaign/execute.ts
index eb07f28ff3..d17435bbe4 100644
--- a/apps/web/lib/api/workflows/send-campaign/execute.ts
+++ b/apps/web/lib/api/workflows/send-campaign/execute.ts
@@ -1,8 +1,5 @@
import { evaluateWorkflowConditions } from "@/lib/api/workflows/evaluate-workflow-conditions";
-import {
- WorkflowConditionAttribute,
- WorkflowContext,
-} from "@/lib/api/workflows/types";
+import { WorkflowContext } from "@/lib/api/workflows/types";
import { aggregatePartnerLinksStats } from "@/lib/partners/aggregate-partner-links-stats";
import { constructPartnerLink } from "@/lib/partners/construct-partner-link";
import { prisma } from "@/lib/prisma";
@@ -16,6 +13,7 @@ import { addHours, differenceInDays, subDays } from "date-fns";
import { renderCampaignEmailHTML } from "../../campaigns/render-campaign-email-html";
import { validateCampaignFromAddress } from "../../campaigns/validate-campaign";
import { createId } from "../../create-id";
+import { WorkflowAttributeKey } from "../attribute-definitions";
import { parseWorkflowConfig } from "../parse-workflow-config";
import type { SendCampaignCondition } from "./types";
@@ -303,40 +301,39 @@ async function getProgramEnrollments({
return [];
}
- const context: Partial<Record<WorkflowConditionAttribute, number | null>> =
- {
- ...(isPartnerLinkStatsAttribute
- ? aggregatePartnerLinksStats(
- programEnrollment.links as unknown as NonNullable<
- Parameters<typeof aggregatePartnerLinksStats>[0]
- >,
- )
- : {}),
- ...(attribute === "totalCommissions"
- ? {
- totalCommissions:
- (
- await prisma.commission.aggregate({
- where: {
- earnings: { not: 0 },
- programId,
- partnerId,
- status: { in: ["pending", "processed", "paid"] },
- },
- _sum: { earnings: true },
- })
- )._sum.earnings || 0,
- }
- : {}),
- ...(attribute === "partnerJoined"
- ? {
- partnerJoined: differenceInDays(
- new Date(),
- programEnrollment.createdAt,
- ),
- }
- : {}),
- };
+ const context: Partial<Record<WorkflowAttributeKey, number | null>> = {
+ ...(isPartnerLinkStatsAttribute
+ ? aggregatePartnerLinksStats(
+ programEnrollment.links as unknown as NonNullable<
+ Parameters<typeof aggregatePartnerLinksStats>[0]
+ >,
+ )
+ : {}),
+ ...(attribute === "totalCommissions"
+ ? {
+ totalCommissions:
+ (
+ await prisma.commission.aggregate({
+ where: {
+ earnings: { not: 0 },
+ programId,
+ partnerId,
+ status: { in: ["pending", "processed", "paid"] },
+ },
+ _sum: { earnings: true },
+ })
+ )._sum.earnings || 0,
+ }
+ : {}),
+ ...(attribute === "partnerJoined"
+ ? {
+ partnerJoined: differenceInDays(
+ new Date(),
+ programEnrollment.createdAt,
+ ),
+ }
+ : {}),
+ };
const shouldExecute = evaluateWorkflowConditions({
conditions: [condition],
diff --git a/apps/web/lib/api/workflows/types.ts b/apps/web/lib/api/workflows/types.ts
index 5de35cf82f..41d7d84769 100644
--- a/apps/web/lib/api/workflows/types.ts
+++ b/apps/web/lib/api/workflows/types.ts
@@ -1,6 +1,4 @@
import {
- WORKFLOW_ATTRIBUTES,
- WORKFLOW_COMPARISON_OPERATORS,
workflowActionSchema,
workflowConditionSchema,
} from "@/lib/zod/schemas/workflows";
@@ -9,11 +7,6 @@ import type * as z from "zod/v4";
export type WorkflowCondition = z.infer<typeof workflowConditionSchema>;
-export type WorkflowConditionAttribute = (typeof WORKFLOW_ATTRIBUTES)[number];
-
-export type WorkflowComparisonOperator =
- (typeof WORKFLOW_COMPARISON_OPERATORS)[number];
-
export type WorkflowAction = z.infer<typeof workflowActionSchema>;
interface WorkflowIdentity {
diff --git a/apps/web/lib/api/workflows/utils.ts b/apps/web/lib/api/workflows/utils.ts
index 6621df1fc1..af48c0bbd6 100644
--- a/apps/web/lib/api/workflows/utils.ts
+++ b/apps/web/lib/api/workflows/utils.ts
@@ -1,9 +1,9 @@
-import { WorkflowConditionAttribute } from "@/lib/api/workflows/types";
import { SCHEDULED_WORKFLOW_TRIGGERS } from "@/lib/zod/schemas/workflows";
import { Workflow } from "@prisma/client";
+import { WorkflowAttributeKey } from "./attribute-definitions";
import { parseWorkflowConfig } from "./parse-workflow-config";
-export const isCurrencyAttribute = (activity: WorkflowConditionAttribute) =>
+export const isCurrencyAttribute = (activity: WorkflowAttributeKey) =>
activity === "totalCommissions" || activity === "totalSaleAmount";
export const isScheduledWorkflow = (workflow: Workflow) => {
diff --git a/apps/web/lib/zod/schemas/workflows.ts b/apps/web/lib/zod/schemas/workflows.ts
index fe4a6201c5..9a6c688c22 100644
--- a/apps/web/lib/zod/schemas/workflows.ts
+++ b/apps/web/lib/zod/schemas/workflows.ts
@@ -1,19 +1,13 @@
+import {
+ WORKFLOW_ATTRIBUTE_KEYS,
+ WorkflowAttributeKey,
+} from "@/lib/api/workflows/attribute-definitions";
+import { WORKFLOW_OPERATOR_KEYS } from "@/lib/api/workflows/operator-definitions";
import { WorkflowTrigger } from "@prisma/client";
import * as z from "zod/v4";
-export const WORKFLOW_ATTRIBUTES = [
- "totalLeads",
- "totalConversions",
- "totalSaleAmount",
- "totalCommissions",
- "partnerEnrolledDays",
- "partnerJoined",
-] as const;
-
-type WorkflowConditionAttribute = (typeof WORKFLOW_ATTRIBUTES)[number];
-
export const WORKFLOW_ATTRIBUTE_TRIGGER: Record<
- WorkflowConditionAttribute,
+ WorkflowAttributeKey,
WorkflowTrigger
> = {
totalLeads: WorkflowTrigger.partnerMetricsUpdated,
@@ -24,8 +18,6 @@ export const WORKFLOW_ATTRIBUTE_TRIGGER: Record<
partnerJoined: WorkflowTrigger.partnerEnrolled,
} as const;
-export const WORKFLOW_COMPARISON_OPERATORS = ["gte", "between"] as const;
-
export const SCHEDULED_WORKFLOW_TRIGGERS: WorkflowTrigger[] = [
"partnerEnrolled",
];
@@ -40,12 +32,10 @@ export enum WORKFLOW_ACTION_TYPES {
MoveGroup = "moveGroup",
}
-export const WORKFLOW_LOGICAL_OPERATORS = ["AND"] as const;
-
// Individual condition
export const workflowConditionSchema = z.object({
- attribute: z.enum(WORKFLOW_ATTRIBUTES),
- operator: z.enum(WORKFLOW_COMPARISON_OPERATORS).default("gte"),
+ attribute: z.enum(WORKFLOW_ATTRIBUTE_KEYS),
+ operator: z.enum(WORKFLOW_OPERATOR_KEYS).default("gte"),
value: z.union([
z.number(),
z.object({
@@ -55,12 +45,6 @@ export const workflowConditionSchema = z.object({
]),
});
-// Array of conditions with AND operator
-export const workflowConditionsSchema = z.object({
- operator: z.enum(WORKFLOW_LOGICAL_OPERATORS).default("AND"),
- conditions: z.array(workflowConditionSchema).min(1),
-});
-
// Individual action
export const workflowActionSchema = z.discriminatedUnion("type", [
z.object({
@@ -84,19 +68,3 @@ export const workflowActionSchema = z.discriminatedUnion("type", [
}),
}),
]);
-
-// Array of actions (Only supports one action for now)
-export const workflowActionsSchema = z.array(workflowActionSchema);
-
-export const createWorkflowSchema = z.object({
- trigger: z.enum(WorkflowTrigger),
- triggerConditions: workflowConditionsSchema,
- actions: workflowActionsSchema,
-});
-
-export const workflowSchema = z.object({
- name: z.string(),
- trigger: z.enum(WorkflowTrigger),
- triggerConditions: workflowConditionsSchema,
- actions: workflowActionsSchema,
-});