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.

Add partner group source condition to group move rules.

Kiran K019d7c92b6fd
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/settings/group-move-rules.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/settings/group-move-rules.tsx
index d49595d6c1..000634b01d 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/settings/group-move-rules.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/settings/group-move-rules.tsx
@@ -1,8 +1,9 @@
"use client";
import {
- GROUP_MOVE_ATTRIBUTE_KEYS,
GROUP_MOVE_ATTRIBUTES,
+ GROUP_MOVE_METRIC_ATTRIBUTE_KEYS,
+ GROUP_MOVE_OPERATORS,
} from "@/lib/api/workflows/move-group/schema";
import type {
GroupMoveAttribute,
@@ -12,6 +13,7 @@ import type {
import { WorkflowCondition } from "@/lib/api/workflows/types";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import useGroup from "@/lib/swr/use-group";
+import useGroups from "@/lib/swr/use-groups";
import useWorkspace from "@/lib/swr/use-workspace";
import { useAdvancedUpsellModal } from "@/ui/partners/advanced-upsell-modal";
import { GroupColorCircle } from "@/ui/partners/groups/group-color-circle";
@@ -21,20 +23,31 @@ import {
InlineBadgePopoverMenu,
} from "@/ui/shared/inline-badge-popover";
import { ArrowTurnRight2, Button, UserArrowRight, Users } from "@dub/ui";
-import { currencyFormatter, nFormatter } from "@dub/utils";
+import { currencyFormatter, nFormatter, pluralize } from "@dub/utils";
import { X } from "lucide-react";
import { Fragment, useMemo } from "react";
import { Controller, useFieldArray, useFormContext } from "react-hook-form";
// Draft form value shapes (partial ranges allowed while editing)
type RangeValue = { min: number; max?: number };
-type ValueType = number | RangeValue | undefined;
+type ValueType = number | RangeValue | string | string[] | undefined;
+
+type MetricAttributeKey = (typeof GROUP_MOVE_METRIC_ATTRIBUTE_KEYS)[number];
const RANGE_SELECTOR_OPTIONS = [
{ text: "and no limit", value: "noLimit" },
{ text: "and less than", value: "lessThan" },
];
+const PARTNER_GROUP_OPERATORS = ["eq", "ne", "in", "notIn"] as const;
+
+const isMultiGroupOperator = (
+ operator: WorkflowCondition["operator"],
+): boolean => operator === "in" || operator === "notIn";
+
+const isPartnerGroupRule = (rule: WorkflowCondition | undefined) =>
+ rule?.attribute === "partnerGroup";
+
export function GroupMoveRules() {
const { plan } = useWorkspace();
@@ -49,25 +62,60 @@ export function GroupMoveRules() {
append: appendRule,
remove: removeRule,
update: updateRule,
+ replace: replaceRules,
} = useFieldArray({
control,
name: "moveRules",
shouldUnregister: false,
});
- const usedAttributes = useMemo(
+ const metricRuleIndexes = useMemo(
() =>
moveRules
- ?.map((r) => r.attribute)
- .filter((a): a is NonNullable<typeof a> => a != null),
+ .map((rule, index) => ({ rule, index }))
+ .filter(({ rule }) => !isPartnerGroupRule(rule)),
[moveRules],
);
- const disableAddRuleButton =
- ruleFields.length >= GROUP_MOVE_ATTRIBUTE_KEYS.length;
+ const partnerGroupRuleIndex = useMemo(
+ () => moveRules.findIndex((rule) => isPartnerGroupRule(rule)),
+ [moveRules],
+ );
+
+ const hasPartnerGroupCondition = partnerGroupRuleIndex !== -1;
+
+ const usedMetricAttributes = useMemo(
+ () =>
+ metricRuleIndexes
+ .map(({ rule }) => rule.attribute)
+ .filter((a): a is NonNullable<typeof a> => a != null),
+ [metricRuleIndexes],
+ );
+
+ const canAddMetricRule =
+ usedMetricAttributes.length < GROUP_MOVE_METRIC_ATTRIBUTE_KEYS.length;
+
+ // Source group is only an additional condition after at least one metric rule
+ const canAddPartnerGroupCondition =
+ metricRuleIndexes.length > 0 && !hasPartnerGroupCondition;
const { canUseGroupMoveRule } = getPlanCapabilities(plan);
+ const handleRemoveRule = (index: number) => {
+ const removingLastMetric =
+ !isPartnerGroupRule(moveRules[index]) &&
+ metricRuleIndexes.length === 1 &&
+ hasPartnerGroupCondition;
+
+ if (removingLastMetric) {
+ // Partner group can only exist as a second condition
+ replaceRules([]);
+ return;
+ }
+
+ removeRule(index);
+ };
+
return (
<>
{!canUseGroupMoveRule ? (
@@ -76,24 +124,19 @@ export function GroupMoveRules() {
<NoGroupRule />
) : (
<div className="relative flex flex-col">
- {ruleFields.map((field, index) => {
- const rule = moveRules?.[index];
- if (!rule) {
- return null;
- }
-
- // Filter out attributes already used by other rules
- const availableAttributes = GROUP_MOVE_ATTRIBUTE_KEYS.filter(
+ {metricRuleIndexes.map(({ rule, index }, metricIndex) => {
+ const availableAttributes = GROUP_MOVE_METRIC_ATTRIBUTE_KEYS.filter(
(attribute) =>
attribute === rule.attribute ||
- !usedAttributes?.includes(attribute),
+ !usedMetricAttributes.includes(attribute),
);
return (
- <Fragment key={field.id}>
- <GroupRule
+ <Fragment key={ruleFields[index]?.id ?? index}>
+ <MetricGroupRule
index={index}
rule={rule}
+ metricIndex={metricIndex}
availableAttributes={availableAttributes}
onUpdate={(updatedRule) => {
updateRule(index, {
@@ -101,9 +144,7 @@ export function GroupMoveRules() {
...updatedRule,
});
}}
- onRemove={() => {
- removeRule(index);
- }}
+ onRemove={() => handleRemoveRule(index)}
/>
<div className="ml-6 h-4 w-px bg-neutral-200" />
@@ -111,6 +152,40 @@ export function GroupMoveRules() {
);
})}
+ {hasPartnerGroupCondition && (
+ <>
+ <PartnerGroupCondition
+ rule={moveRules[partnerGroupRuleIndex]!}
+ onUpdate={(updatedRule) => {
+ updateRule(partnerGroupRuleIndex, {
+ ...moveRules[partnerGroupRuleIndex],
+ ...updatedRule,
+ });
+ }}
+ onRemove={() => removeRule(partnerGroupRuleIndex)}
+ />
+ <div className="ml-6 h-4 w-px bg-neutral-200" />
+ </>
+ )}
+
+ {canAddPartnerGroupCondition && (
+ <>
+ <Button
+ text="Add condition"
+ variant="secondary"
+ className="h-8 w-fit rounded-lg px-3"
+ onClick={() => {
+ appendRule({
+ attribute: "partnerGroup",
+ operator: "eq",
+ value: undefined,
+ } as unknown as WorkflowCondition);
+ }}
+ />
+ <div className="ml-6 h-4 w-px bg-neutral-200" />
+ </>
+ )}
+
<GroupMoveTarget />
</div>
)}
@@ -127,9 +202,9 @@ export function GroupMoveRules() {
value: undefined,
} as unknown as WorkflowCondition);
}}
- disabled={disableAddRuleButton}
+ disabled={!canAddMetricRule && ruleFields.length > 0}
disabledTooltip={
- disableAddRuleButton
+ !canAddMetricRule && ruleFields.length > 0
? "All rules are in use. Delete existing rules."
: undefined
}
@@ -139,22 +214,24 @@ export function GroupMoveRules() {
);
}
-function GroupRule({
+function MetricGroupRule({
rule,
onUpdate,
onRemove,
index,
+ metricIndex,
availableAttributes,
}: {
rule: WorkflowCondition;
onUpdate: (updates: Partial<WorkflowCondition>) => void;
onRemove: () => void;
index: number;
- availableAttributes: GroupMoveAttributeKey[];
+ metricIndex: number;
+ availableAttributes: MetricAttributeKey[];
}) {
- const isFirst = index === 0;
+ const isFirst = metricIndex === 0;
const attributeConfig = rule.attribute
- ? GROUP_MOVE_ATTRIBUTES[rule.attribute]
+ ? GROUP_MOVE_ATTRIBUTES[rule.attribute as GroupMoveAttributeKey]
: undefined;
const attributeType = attributeConfig?.inputType || "number";
@@ -219,7 +296,6 @@ function GroupRule({
}))}
selectedValue={rule.attribute}
onSelect={(value) => {
- // Reset to default gte operator when attribute changes
onUpdate({
...rule,
attribute: value,
@@ -229,7 +305,6 @@ function GroupRule({
}}
/>
</InlineBadgePopover>
- {/* Select the attribute value */}
{rule.attribute && (
<>
is at least
@@ -296,6 +371,160 @@ function GroupRule({
);
}
+function PartnerGroupCondition({
+ rule,
+ onUpdate,
+ onRemove,
+}: {
+ rule: WorkflowCondition;
+ onUpdate: (updates: Partial<WorkflowCondition>) => void;
+ onRemove: () => void;
+}) {
+ const { group: currentGroup } = useGroup();
+ const { groups } = useGroups();
+
+ const availableGroups = useMemo(
+ () => groups?.filter((g) => g.id !== currentGroup?.id) ?? [],
+ [groups, currentGroup?.id],
+ );
+
+ const isMulti = isMultiGroupOperator(rule.operator);
+ const selectedOperator = PARTNER_GROUP_OPERATORS.includes(
+ rule.operator as (typeof PARTNER_GROUP_OPERATORS)[number],
+ )
+ ? rule.operator
+ : "eq";
+
+ const selectedGroupIds = useMemo(() => {
+ if (typeof rule.value === "string") {
+ return [rule.value];
+ }
+ if (Array.isArray(rule.value)) {
+ return rule.value;
+ }
+ return [];
+ }, [rule.value]);
+
+ const selectedGroups = useMemo(
+ () => (groups ?? []).filter((group) => selectedGroupIds.includes(group.id)),
+ [groups, selectedGroupIds],
+ );
+
+ const groupBadgeText = (() => {
+ if (selectedGroups.length === 0) {
+ return isMulti ? "Select groups" : "Select group";
+ }
+
+ if (isMulti && selectedGroups.length > 1) {
+ return `${selectedGroups.length} Partner ${pluralize("Group", selectedGroups.length)}`;
+ }
+
+ return (
+ <span className="inline-flex items-center gap-1.5">
+ <GroupColorCircle group={selectedGroups[0]} />
+ {selectedGroups[0].name}
+ </span>
+ );
+ })();
+
+ const handleOperatorSelect = (
+ operator: (typeof PARTNER_GROUP_OPERATORS)[number],
+ ) => {
+ const nextIsMulti = isMultiGroupOperator(operator);
+ const wasMulti = isMultiGroupOperator(rule.operator);
+
+ let nextValue: string | string[] | undefined;
+
+ if (nextIsMulti === wasMulti) {
+ nextValue = rule.value as string | string[] | undefined;
+ } else if (nextIsMulti) {
+ nextValue =
+ typeof rule.value === "string" && rule.value ? [rule.value] : [];
+ } else {
+ nextValue =
+ Array.isArray(rule.value) && rule.value.length > 0
+ ? rule.value[0]
+ : undefined;
+ }
+
+ onUpdate({
+ operator,
+ value: nextValue as any,
+ });
+ };
+
+ const handleGroupSelect = (groupId: string) => {
+ if (isMulti) {
+ const current = Array.isArray(rule.value) ? rule.value : [];
+ const next = current.includes(groupId)
+ ? current.filter((id) => id !== groupId)
+ : [...current, groupId];
+ onUpdate({ value: next as any });
+ return;
+ }
+
+ onUpdate({ value: groupId });
+ };
+
+ return (
+ <div className="flex flex-col rounded-lg border border-neutral-200 bg-white">
+ <div className="flex items-center justify-between p-2.5 pr-3">
+ <div className="flex items-center gap-2">
+ <div className="flex size-7 shrink-0 items-center justify-center rounded-md bg-neutral-100">
+ <ArrowTurnRight2 className="size-4 text-neutral-600" />
+ </div>
+ <span className="text-sm font-medium text-neutral-800">
+ And if
+ <span className="mx-1 inline-block rounded bg-blue-50 px-1.5 text-sm font-semibold text-blue-700">
+ partner group
+ </span>
+ <InlineBadgePopover
+ text={
+ GROUP_MOVE_OPERATORS[
+ selectedOperator as keyof typeof GROUP_MOVE_OPERATORS
+ ]?.label ?? "condition"
+ }
+ buttonClassName="mx-1"
+ >
+ <InlineBadgePopoverMenu
+ selectedValue={selectedOperator}
+ onSelect={handleOperatorSelect}
+ items={PARTNER_GROUP_OPERATORS.map((operator) => ({
+ value: operator,
+ text: GROUP_MOVE_OPERATORS[operator].label,
+ }))}
+ />
+ </InlineBadgePopover>
+ <InlineBadgePopover
+ text={groupBadgeText}
+ invalid={selectedGroupIds.length === 0}
+ buttonClassName="mx-1"
+ >
+ <InlineBadgePopoverMenu
+ search
+ selectedValue={isMulti ? selectedGroupIds : selectedGroupIds[0]}
+ onSelect={handleGroupSelect}
+ items={availableGroups.map((group) => ({
+ value: group.id,
+ text: group.name,
+ icon: <GroupColorCircle group={group} />,
+ }))}
+ />
+ </InlineBadgePopover>
+ </span>
+ </div>
+ <button
+ type="button"
+ onClick={onRemove}
+ className="rounded p-1 text-neutral-400 hover:bg-neutral-100 hover:text-neutral-600"
+ >
+ <X className="size-4" />
+ </button>
+ </div>
+ </div>
+ );
+}
+
function GroupMoveTarget() {
const { group, loading } = useGroup();
@@ -416,7 +645,7 @@ function ValueInput({
return (
<InlineBadgePopoverAmountInput
- type={attributeType}
+ type={attributeType === "currency" ? "currency" : "number"}
value={displayValue}
onChange={handleChange}
onBlur={field.onBlur}
@@ -497,7 +726,7 @@ const getMinValue = (value: ValueType): number | null => {
return value;
}
- if (typeof value === "object" && value !== null && value.min != null) {
+ if (isRangeValue(value) && value.min != null) {
return value.min;
}
@@ -505,7 +734,7 @@ const getMinValue = (value: ValueType): number | null => {
};
const getMaxValue = (value: ValueType): number | null => {
- if (typeof value === "object" && value !== null && value.max != null) {
+ if (isRangeValue(value) && value.max != null) {
return value.max;
}
@@ -516,6 +745,7 @@ const isRangeValue = (value: ValueType): value is RangeValue => {
return (
typeof value === "object" &&
value !== null &&
+ !Array.isArray(value) &&
("min" in value || "max" in value)
);
};
diff --git a/apps/web/lib/api/groups/find-groups-with-matching-rules.ts b/apps/web/lib/api/groups/find-groups-with-matching-rules.ts
index 6cbb3d9c0c..51fa3098b3 100644
--- a/apps/web/lib/api/groups/find-groups-with-matching-rules.ts
+++ b/apps/web/lib/api/groups/find-groups-with-matching-rules.ts
@@ -48,9 +48,10 @@ const doRuleSetsOverlap = (
rules2ByAttribute.set(rule.attribute, rule);
}
- // Get all attributes that appear in BOTH rule sets (intersection)
- const sharedAttributes = Array.from(rules1ByAttribute.keys()).filter((attr) =>
- rules2ByAttribute.has(attr),
+ // Get all attributes that appear in BOTH rule sets (intersection).
+ // Skip partnerGroup — conflict detection is metric-interval only for now.
+ const sharedAttributes = Array.from(rules1ByAttribute.keys()).filter(
+ (attr) => attr !== "partnerGroup" && rules2ByAttribute.has(attr),
);
// If there are no shared attributes, the rule sets cannot conflict
@@ -92,7 +93,13 @@ const conditionToInterval = (
return null;
case "between":
- if (typeof condition.value === "object" && condition.value !== null) {
+ if (
+ typeof condition.value === "object" &&
+ condition.value !== null &&
+ !Array.isArray(condition.value) &&
+ "min" in condition.value &&
+ "max" in condition.value
+ ) {
return {
min: condition.value.min,
max: condition.value.max,
diff --git a/apps/web/lib/api/groups/upsert-group-move-rules.ts b/apps/web/lib/api/groups/upsert-group-move-rules.ts
index 5718b60068..1306dc4156 100644
--- a/apps/web/lib/api/groups/upsert-group-move-rules.ts
+++ b/apps/web/lib/api/groups/upsert-group-move-rules.ts
@@ -53,6 +53,10 @@ export async function upsertGroupMoveRules({
await validateWorkflowConditions({
conditions: moveRules,
workflowType: "moveGroup",
+ context: {
+ programId: group.programId,
+ groupId: group.id,
+ },
});
const groupsWithMatchingRules = findGroupsWithMatchingRules({
diff --git a/apps/web/lib/api/workflows/attribute-definitions.ts b/apps/web/lib/api/workflows/attribute-definitions.ts
index 84a32a804a..bf2c2f42b6 100644
--- a/apps/web/lib/api/workflows/attribute-definitions.ts
+++ b/apps/web/lib/api/workflows/attribute-definitions.ts
@@ -42,6 +42,12 @@ export const WORKFLOW_ATTRIBUTES = {
inputType: "none",
operators: ["gte"],
},
+ partnerGroup: {
+ name: "partnerGroup",
+ label: "group",
+ inputType: "group",
+ operators: ["eq", "ne", "in", "notIn"],
+ },
} as const;
export const WORKFLOW_ATTRIBUTE_KEYS = Object.keys(
diff --git a/apps/web/lib/api/workflows/attribute-validators.ts b/apps/web/lib/api/workflows/attribute-validators.ts
new file mode 100644
index 0000000000..eea2196445
--- /dev/null
+++ b/apps/web/lib/api/workflows/attribute-validators.ts
@@ -0,0 +1,57 @@
+import { throwIfInvalidGroupIds } from "@/lib/api/groups/throw-if-invalid-group-ids";
+import { DubApiError } from "../errors";
+
+export type WorkflowAttributeValidatorContext = {
+ programId: string;
+ groupId?: string;
+};
+
+type WorkflowAttributeValidator = ({
+ value,
+ context,
+}: {
+ value: unknown;
+ operator: string;
+ context: WorkflowAttributeValidatorContext;
+}) => Promise<void>;
+
+export const WORKFLOW_ATTRIBUTE_VALIDATORS: Partial<
+ Record<string, WorkflowAttributeValidator>
+> = {
+ partnerGroup: async ({ value, context }) => {
+ const groupIds = normalizeStringArray(value);
+
+ if (groupIds.length === 0) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Please select at least one group.",
+ });
+ }
+
+ if (context.groupId && groupIds.includes(context.groupId)) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Cannot select the current group as a source group.",
+ });
+ }
+
+ await throwIfInvalidGroupIds({
+ programId: context.programId,
+ groupIds,
+ });
+ },
+};
+
+const normalizeStringArray = (value: unknown): string[] => {
+ if (typeof value === "string") {
+ return value ? [value] : [];
+ }
+
+ if (Array.isArray(value)) {
+ return value.filter(
+ (id): id is string => typeof id === "string" && id.length > 0,
+ );
+ }
+
+ return [];
+};
diff --git a/apps/web/lib/api/workflows/evaluate-workflow-conditions.ts b/apps/web/lib/api/workflows/evaluate-workflow-conditions.ts
index 10814c2283..fda2561078 100644
--- a/apps/web/lib/api/workflows/evaluate-workflow-conditions.ts
+++ b/apps/web/lib/api/workflows/evaluate-workflow-conditions.ts
@@ -7,7 +7,7 @@ export function evaluateWorkflowConditions({
attributes,
}: {
conditions: WorkflowCondition[];
- attributes: Partial<Record<WorkflowAttributeKey, number | null>>;
+ attributes: Partial<Record<WorkflowAttributeKey, number | string | null>>;
}): boolean {
if (conditions.length === 0) return false;
diff --git a/apps/web/lib/api/workflows/move-group/execute.ts b/apps/web/lib/api/workflows/move-group/execute.ts
index 15f681edf7..8d25841956 100644
--- a/apps/web/lib/api/workflows/move-group/execute.ts
+++ b/apps/web/lib/api/workflows/move-group/execute.ts
@@ -63,11 +63,14 @@ export const executeMoveGroupWorkflow = async ({
return;
}
- const attributes: Partial<Record<WorkflowAttributeKey, number | null>> = {
+ const attributes: Partial<
+ Record<WorkflowAttributeKey, number | string | null>
+ > = {
totalLeads: metrics?.aggregated?.leads ?? 0,
totalConversions: metrics?.aggregated?.conversions ?? 0,
totalSaleAmount: metrics?.aggregated?.saleAmount ?? 0,
totalCommissions: metrics?.aggregated?.commissions ?? 0,
+ partnerGroup: programEnrollment.groupId,
};
const shouldExecute = evaluateWorkflowConditions({
diff --git a/apps/web/lib/api/workflows/move-group/schema.ts b/apps/web/lib/api/workflows/move-group/schema.ts
index cc9124bd90..6a67f85cde 100644
--- a/apps/web/lib/api/workflows/move-group/schema.ts
+++ b/apps/web/lib/api/workflows/move-group/schema.ts
@@ -1,3 +1,4 @@
+import { WORKFLOW_OPERATORS } from "@/lib/api/workflows/operator-definitions";
import { WORKFLOW_ATTRIBUTES } from "../attribute-definitions";
export const GROUP_MOVE_ATTRIBUTES = {
@@ -17,8 +18,28 @@ export const GROUP_MOVE_ATTRIBUTES = {
...WORKFLOW_ATTRIBUTES.totalCommissions,
operators: ["gte", "between"] as const,
},
+ partnerGroup: WORKFLOW_ATTRIBUTES.partnerGroup,
};
export const GROUP_MOVE_ATTRIBUTE_KEYS = Object.keys(
GROUP_MOVE_ATTRIBUTES,
) as readonly (keyof typeof GROUP_MOVE_ATTRIBUTES)[];
+
+export const GROUP_MOVE_METRIC_ATTRIBUTE_KEYS =
+ GROUP_MOVE_ATTRIBUTE_KEYS.filter(
+ (
+ key,
+ ): key is Exclude<
+ (typeof GROUP_MOVE_ATTRIBUTE_KEYS)[number],
+ "partnerGroup"
+ > => key !== "partnerGroup",
+ );
+
+export const GROUP_MOVE_OPERATORS = {
+ gte: WORKFLOW_OPERATORS.gte,
+ between: WORKFLOW_OPERATORS.between,
+ eq: WORKFLOW_OPERATORS.eq,
+ ne: WORKFLOW_OPERATORS.ne,
+ in: WORKFLOW_OPERATORS.in,
+ notIn: WORKFLOW_OPERATORS.notIn,
+};
diff --git a/apps/web/lib/api/workflows/operator-definitions.ts b/apps/web/lib/api/workflows/operator-definitions.ts
index e06d565a55..817978d18e 100644
--- a/apps/web/lib/api/workflows/operator-definitions.ts
+++ b/apps/web/lib/api/workflows/operator-definitions.ts
@@ -1,10 +1,17 @@
-type ConditionValue = number | { min: number; max?: number };
+export type ConditionValue =
+ | number
+ | { min: number; max?: number }
+ | string
+ | string[];
type WorkflowOperator = {
name: string;
label: string;
validate: (value: ConditionValue) => void;
- evaluate: (attributeValue: number, conditionValue: ConditionValue) => boolean;
+ evaluate: (
+ attributeValue: number | string,
+ conditionValue: ConditionValue,
+ ) => boolean;
};
export const WORKFLOW_OPERATORS = {
@@ -17,8 +24,11 @@ export const WORKFLOW_OPERATORS = {
throw new Error("Please enter a value greater than or equal to 0.");
}
},
- evaluate(attributeValue: number, conditionValue: ConditionValue) {
- if (typeof conditionValue !== "number") {
+ evaluate(attributeValue: number | string, conditionValue: ConditionValue) {
+ if (
+ typeof attributeValue !== "number" ||
+ typeof conditionValue !== "number"
+ ) {
return false;
}
@@ -31,7 +41,7 @@ export const WORKFLOW_OPERATORS = {
name: "between",
label: "between",
validate(value: ConditionValue) {
- if (typeof value !== "object" || value === null) {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
throw new Error("Please enter a valid value.");
}
@@ -50,8 +60,13 @@ export const WORKFLOW_OPERATORS = {
throw new Error("Maximum value must be greater than minimum value.");
}
},
- evaluate(attributeValue: number, conditionValue: ConditionValue) {
- if (typeof conditionValue !== "object" || conditionValue === null) {
+ evaluate(attributeValue: number | string, conditionValue: ConditionValue) {
+ if (
+ typeof attributeValue !== "number" ||
+ typeof conditionValue !== "object" ||
+ conditionValue === null ||
+ Array.isArray(conditionValue)
+ ) {
return false;
}
@@ -64,6 +79,98 @@ export const WORKFLOW_OPERATORS = {
return attributeValue >= min && attributeValue <= max;
},
},
+
+ // Equality (string)
+ eq: {
+ name: "eq",
+ label: "is",
+ validate(value: ConditionValue) {
+ if (typeof value !== "string" || value.length === 0) {
+ throw new Error("Please select a valid value.");
+ }
+ },
+ evaluate(attributeValue: number | string, conditionValue: ConditionValue) {
+ if (
+ typeof attributeValue !== "string" ||
+ typeof conditionValue !== "string"
+ ) {
+ return false;
+ }
+
+ return attributeValue === conditionValue;
+ },
+ },
+
+ // Not equal (string)
+ ne: {
+ name: "ne",
+ label: "is not",
+ validate(value: ConditionValue) {
+ if (typeof value !== "string" || value.length === 0) {
+ throw new Error("Please select a valid value.");
+ }
+ },
+ evaluate(attributeValue: number | string, conditionValue: ConditionValue) {
+ if (
+ typeof attributeValue !== "string" ||
+ typeof conditionValue !== "string"
+ ) {
+ return false;
+ }
+
+ return attributeValue !== conditionValue;
+ },
+ },
+
+ // In list (string[])
+ in: {
+ name: "in",
+ label: "is any of",
+ validate(value: ConditionValue) {
+ if (
+ !Array.isArray(value) ||
+ value.length === 0 ||
+ value.some((v) => typeof v !== "string" || v.length === 0)
+ ) {
+ throw new Error("Please select at least one valid value.");
+ }
+ },
+ evaluate(attributeValue: number | string, conditionValue: ConditionValue) {
+ if (
+ typeof attributeValue !== "string" ||
+ !Array.isArray(conditionValue)
+ ) {
+ return false;
+ }
+
+ return conditionValue.includes(attributeValue);
+ },
+ },
+
+ // Not in list (string[])
+ notIn: {
+ name: "notIn",
+ label: "is not any of",
+ validate(value: ConditionValue) {
+ if (
+ !Array.isArray(value) ||
+ value.length === 0 ||
+ value.some((v) => typeof v !== "string" || v.length === 0)
+ ) {
+ throw new Error("Please select at least one valid value.");
+ }
+ },
+ evaluate(attributeValue: number | string, conditionValue: ConditionValue) {
+ if (
+ typeof attributeValue !== "string" ||
+ !Array.isArray(conditionValue)
+ ) {
+ return false;
+ }
+
+ return !conditionValue.includes(attributeValue);
+ },
+ },
} satisfies Record<string, WorkflowOperator>;
export const WORKFLOW_OPERATOR_KEYS = Object.keys(
diff --git a/apps/web/lib/api/workflows/validate-workflow-conditions.ts b/apps/web/lib/api/workflows/validate-workflow-conditions.ts
index 2ed705f0b5..38b2d9e420 100644
--- a/apps/web/lib/api/workflows/validate-workflow-conditions.ts
+++ b/apps/web/lib/api/workflows/validate-workflow-conditions.ts
@@ -4,6 +4,10 @@ import { WORKFLOW_OPERATORS } from "@/lib/api/workflows/operator-definitions";
import { SEND_CAMPAIGN_ATTRIBUTES } from "@/lib/api/workflows/send-campaign/schema";
import type { WorkflowType } from "@/lib/api/workflows/types";
import { DubApiError } from "../errors";
+import {
+ WORKFLOW_ATTRIBUTE_VALIDATORS,
+ type WorkflowAttributeValidatorContext,
+} from "./attribute-validators";
// Map of workflow type to its attributes
const WORKFLOW_TYPE_ATTRIBUTES = {
@@ -24,14 +28,36 @@ type WorkflowConditionInput = {
export async function validateWorkflowConditions({
conditions,
workflowType,
+ context,
}: {
conditions?: WorkflowConditionInput[] | null;
workflowType: WorkflowType;
+ context?: WorkflowAttributeValidatorContext;
}): Promise<void> {
if (!conditions || conditions.length === 0) {
return;
}
+ // Move group workflow requires at least one metric condition and one partner group condition
+ if (workflowType === "moveGroup") {
+ const hasPartnerGroup = conditions.some(
+ (condition) => condition.attribute === "partnerGroup",
+ );
+
+ const hasMetricCondition = conditions.some(
+ (condition) =>
+ condition.attribute && condition.attribute !== "partnerGroup",
+ );
+
+ if (hasPartnerGroup && !hasMetricCondition) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "Partner group can only be used as an additional condition alongside a metric rule.",
+ });
+ }
+ }
+
const attributes = WORKFLOW_TYPE_ATTRIBUTES[workflowType];
for (let i = 0; i < conditions.length; i++) {
@@ -95,5 +121,30 @@ export async function validateWorkflowConditions({
message: `Condition ${conditionIndex + 1}: ${error instanceof Error ? error.message : "Invalid value."}`,
});
}
+
+ const attributeValidator =
+ WORKFLOW_ATTRIBUTE_VALIDATORS[condition.attribute];
+
+ if (attributeValidator && context) {
+ try {
+ await attributeValidator({
+ value: condition.value,
+ operator: condition.operator,
+ context,
+ });
+ } catch (error) {
+ if (error instanceof DubApiError) {
+ throw new DubApiError({
+ code: error.code,
+ message: `Condition ${conditionIndex + 1}: ${error.message}`,
+ });
+ }
+
+ throw new DubApiError({
+ code: "bad_request",
+ message: `Condition ${conditionIndex + 1}: ${error instanceof Error ? error.message : "Invalid value."}`,
+ });
+ }
+ }
}
}
diff --git a/apps/web/lib/bounty/api/generate-performance-bounty-name.ts b/apps/web/lib/bounty/api/generate-performance-bounty-name.ts
index b70691ec71..e0e7108e1d 100644
--- a/apps/web/lib/bounty/api/generate-performance-bounty-name.ts
+++ b/apps/web/lib/bounty/api/generate-performance-bounty-name.ts
@@ -16,7 +16,13 @@ export const generatePerformanceBountyName = ({
condition.attribute as keyof typeof PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES
];
const value =
- typeof condition.value === "number" ? condition.value : condition.value.min;
+ typeof condition.value === "number"
+ ? condition.value
+ : typeof condition.value === "object" &&
+ condition.value !== null &&
+ !Array.isArray(condition.value)
+ ? condition.value.min
+ : 0;
const valueFormatted = isCurrency
? `${currencyFormatter(value, { trailingZeroDisplay: "stripIfInteger" })} in`
: `${nFormatter(value, { full: true })}`;
diff --git a/apps/web/lib/zod/schemas/workflows.ts b/apps/web/lib/zod/schemas/workflows.ts
index 7ce0441064..a358c780c2 100644
--- a/apps/web/lib/zod/schemas/workflows.ts
+++ b/apps/web/lib/zod/schemas/workflows.ts
@@ -16,6 +16,7 @@ export const WORKFLOW_ATTRIBUTE_TRIGGER: Record<
totalCommissions: WorkflowTrigger.partnerMetricsUpdated,
partnerEnrolledDays: WorkflowTrigger.partnerEnrolled,
partnerJoined: WorkflowTrigger.partnerEnrolled,
+ partnerGroup: WorkflowTrigger.partnerMetricsUpdated,
} as const;
export const SCHEDULED_WORKFLOW_TRIGGERS: WorkflowTrigger[] = [
@@ -42,6 +43,8 @@ export const workflowConditionSchema = z.object({
min: z.number(),
max: z.number(),
}),
+ z.string(),
+ z.array(z.string()).min(1),
]),
});
diff --git a/apps/web/tests/workflows/comparison-operators.test.ts b/apps/web/tests/workflows/comparison-operators.test.ts
index 4ca46278bc..c89880e55b 100644
--- a/apps/web/tests/workflows/comparison-operators.test.ts
+++ b/apps/web/tests/workflows/comparison-operators.test.ts
@@ -74,6 +74,10 @@ describe("WORKFLOW_OPERATORS.between.validate", () => {
expect(() => validate(5)).toThrow("Please enter a valid value.");
});
+ it("rejects arrays", () => {
+ expect(() => validate(["grp_1"])).toThrow("Please enter a valid value.");
+ });
+
it("rejects non-positive or missing min", () => {
expect(() => validate({ min: 0, max: 5 })).toThrow(
"Please enter a minimum value greater than 0.",
@@ -101,3 +105,80 @@ describe("WORKFLOW_OPERATORS.between.validate", () => {
);
});
});
+
+describe("WORKFLOW_OPERATORS.eq", () => {
+ const { evaluate, validate } = WORKFLOW_OPERATORS.eq;
+
+ it("evaluates string equality", () => {
+ expect(evaluate("grp_1", "grp_1")).toBe(true);
+ expect(evaluate("grp_1", "grp_2")).toBe(false);
+ });
+
+ it("returns false for non-string inputs", () => {
+ expect(evaluate(1, "grp_1")).toBe(false);
+ expect(evaluate("grp_1", 1)).toBe(false);
+ });
+
+ it("validates non-empty strings", () => {
+ expect(() => validate("grp_1")).not.toThrow();
+ expect(() => validate("")).toThrow("Please select a valid value.");
+ expect(() => validate(["grp_1"])).toThrow("Please select a valid value.");
+ });
+});
+
+describe("WORKFLOW_OPERATORS.ne", () => {
+ const { evaluate, validate } = WORKFLOW_OPERATORS.ne;
+
+ it("evaluates string inequality", () => {
+ expect(evaluate("grp_1", "grp_2")).toBe(true);
+ expect(evaluate("grp_1", "grp_1")).toBe(false);
+ });
+
+ it("validates non-empty strings", () => {
+ expect(() => validate("grp_1")).not.toThrow();
+ expect(() => validate("")).toThrow("Please select a valid value.");
+ });
+});
+
+describe("WORKFLOW_OPERATORS.in", () => {
+ const { evaluate, validate } = WORKFLOW_OPERATORS.in;
+
+ it("evaluates membership in a list", () => {
+ expect(evaluate("grp_1", ["grp_1", "grp_2"])).toBe(true);
+ expect(evaluate("grp_3", ["grp_1", "grp_2"])).toBe(false);
+ });
+
+ it("returns false for invalid shapes", () => {
+ expect(evaluate("grp_1", "grp_1")).toBe(false);
+ expect(evaluate(1, ["grp_1"])).toBe(false);
+ });
+
+ it("validates non-empty string arrays", () => {
+ expect(() => validate(["grp_1"])).not.toThrow();
+ expect(() => validate([])).toThrow(
+ "Please select at least one valid value.",
+ );
+ expect(() => validate("grp_1")).toThrow(
+ "Please select at least one valid value.",
+ );
+ expect(() => validate([""])).toThrow(
+ "Please select at least one valid value.",
+ );
+ });
+});
+
+describe("WORKFLOW_OPERATORS.notIn", () => {
+ const { evaluate, validate } = WORKFLOW_OPERATORS.notIn;
+
+ it("evaluates exclusion from a list", () => {
+ expect(evaluate("grp_3", ["grp_1", "grp_2"])).toBe(true);
+ expect(evaluate("grp_1", ["grp_1", "grp_2"])).toBe(false);
+ });
+
+ it("validates non-empty string arrays", () => {
+ expect(() => validate(["grp_1", "grp_2"])).not.toThrow();
+ expect(() => validate([])).toThrow(
+ "Please select at least one valid value.",
+ );
+ });
+});