The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Implement trigger condition validation and enhance campaign logic with dropdown support
Kiran Kaef32817cfef
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsxindex fdbfafba7e..0cb39df482 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx@@ -29,6 +29,7 @@ import { CampaignEvents } from "./campaign-events";import { CampaignGroupsSelector } from "./campaign-groups-selector";import { CampaignMetrics } from "./campaign-metrics";import { TransactionalCampaignLogic } from "./transactional-campaign-logic";+import { isValidTriggerCondition } from "./utils";const inputClassName ="hover:border-border-subtle h-8 w-full rounded-md transition-colors duration-150 focus:border-black/75 border focus:ring-black/75 border-transparent px-1.5 py-0 text-sm text-content-default placeholder:text-content-muted hover:bg-neutral-100 hover:cursor-pointer";@@ -84,6 +85,17 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {: null;}+ // Remove invalid triggerCondition when saving a draft to prevent API validation errors+ if (isDraft && "triggerCondition" in changedFields) {+ if (!isValidTriggerCondition(changedFields.triggerCondition)) {+ delete changedFields.triggerCondition;+ }+ }++ if (Object.keys(changedFields).length === 0) {+ return;+ }+await makeRequest(`/api/campaigns/${campaign.id}`, {method: "PATCH",body: changedFields,diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/transactional-campaign-logic.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/transactional-campaign-logic.tsxindex 82581d70ae..feb2f9b61f 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/transactional-campaign-logic.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/transactional-campaign-logic.tsx@@ -1,33 +1,40 @@-import {- isCurrencyAttribute,- isDaysAttribute,-} from "@/lib/api/workflows/utils";import { handleMoneyInputChange, handleMoneyKeyDown } from "@/lib/form-utils";-import {- ALLOWED_ATTRIBUTE_VALUES_IN_DAYS,- CAMPAIGN_WORKFLOW_ATTRIBUTES,-} from "@/lib/zod/schemas/campaigns";-import { WORKFLOW_ATTRIBUTE_LABELS } from "@/lib/zod/schemas/workflows";+import { CAMPAIGN_WORKFLOW_ATTRIBUTE_CONFIG } from "@/lib/zod/schemas/campaigns";+import { WORKFLOW_ATTRIBUTES } from "@/lib/zod/schemas/workflows";import {InlineBadgePopover,InlineBadgePopoverContext,InlineBadgePopoverMenu,} from "@/ui/shared/inline-badge-popover";import { cn, currencyFormatter, pluralize } from "@dub/utils";-import { useContext } from "react";+import { useContext, useEffect, useRef } from "react";import { Controller } from "react-hook-form";import { useCampaignFormContext } from "./campaign-form-context";export function TransactionalCampaignLogic() {- const { control, watch } = useCampaignFormContext();+ const { control, watch, setValue } = useCampaignFormContext();const attribute = watch("triggerCondition.attribute");const value = watch("triggerCondition.value");+ const prevAttributeRef = useRef(attribute);++ const config = attribute+ ? CAMPAIGN_WORKFLOW_ATTRIBUTE_CONFIG[attribute]+ : null;++ // Reset value when attribute changes+ useEffect(() => {+ if (prevAttributeRef.current && prevAttributeRef.current !== attribute) {+ setValue("triggerCondition.value", null as any);+ }++ prevAttributeRef.current = attribute;+ }, [attribute, setValue]);return (<div className="flex h-8 w-full items-center px-2"><span className="text-content-default flex gap-1 text-sm font-medium leading-relaxed">- When partner's+ When partner{config?.inputType !== "none" && "'s"}<div className="inline-flex items-center gap-1"><Controllercontrol={control}@@ -36,7 +43,7 @@ export function TransactionalCampaignLogic() {<InlineBadgePopovertext={field.value- ? WORKFLOW_ATTRIBUTE_LABELS[field.value].toLowerCase()+ ? CAMPAIGN_WORKFLOW_ATTRIBUTE_CONFIG[field.value].label: "activity"}invalid={!field.value}@@ -44,8 +51,8 @@ export function TransactionalCampaignLogic() {<InlineBadgePopoverMenuselectedValue={field.value}onSelect={field.onChange}- items={CAMPAIGN_WORKFLOW_ATTRIBUTES.map((attr) => ({- text: WORKFLOW_ATTRIBUTE_LABELS[attr].toLowerCase(),+ items={WORKFLOW_ATTRIBUTES.map((attr) => ({+ text: CAMPAIGN_WORKFLOW_ATTRIBUTE_CONFIG[attr].label,value: attr,}))}/>@@ -53,59 +60,13 @@ export function TransactionalCampaignLogic() {)}/>- {attribute && (+ {config && config.inputType !== "none" && (<>- {isDaysAttribute(attribute) ? (- <Controller- control={control}- name="triggerCondition.value"- render={({ field }) => (- <>- <InlineBadgePopover- text={- field.value !== undefined && field.value !== null- ? String(field.value)- : "1"- }- invalid={- field.value === undefined || field.value === null- }- >- <InlineBadgePopoverMenu- selectedValue={- field.value !== undefined && field.value !== null- ? String(field.value)- : "1"- }- onSelect={(val) => field.onChange(Number(val))}- items={ALLOWED_ATTRIBUTE_VALUES_IN_DAYS.filter(- (days) => days !== 0,- ).map((days) => ({- text: String(days),- value: String(days),- }))}- />- </InlineBadgePopover>- {pluralize("day", field.value || 1)}- </>- )}- />+ reaches at least{" "}+ {config.inputType === "dropdown" ? (+ <DropdownValueInput config={config} />) : (- <>- is at least{" "}- <InlineBadgePopover- text={- value- ? isCurrencyAttribute(attribute)- ? currencyFormatter(value / 100)- : value- : "amount"- }- invalid={!value}- >- <ValueInput />- </InlineBadgePopover>- </>+ <ValueInput config={config} value={value} />)}</>)}@@ -115,63 +76,117 @@ export function TransactionalCampaignLogic() {);}-function ValueInput() {- const { watch, register, setValue } = useCampaignFormContext();+function DropdownValueInput({+ config,+}: {+ config: { dropdownValues?: number[] };+}) {+ const { control } = useCampaignFormContext();++ return (+ <Controller+ control={control}+ name="triggerCondition.value"+ render={({ field }) => (+ <>+ <InlineBadgePopover+ text={+ field.value !== undefined && field.value !== null+ ? String(field.value)+ : "1"+ }+ invalid={field.value === undefined || field.value === null}+ >+ <InlineBadgePopoverMenu+ selectedValue={+ field.value !== undefined && field.value !== null+ ? String(field.value)+ : "1"+ }+ onSelect={(val) => field.onChange(Number(val))}+ items={(config.dropdownValues || []).map((val) => ({+ text: String(val),+ value: String(val),+ }))}+ />+ </InlineBadgePopover>+ {pluralize("day", field.value || 1)}+ </>+ )}+ />+ );+}++function ValueInput({+ config,+ value,+}: {+ config: { inputType?: string };+ value: number | null | undefined;+}) {+ const { watch, setValue } = useCampaignFormContext();const { setIsOpen } = useContext(InlineBadgePopoverContext);- const attribute = watch("triggerCondition.attribute");const storedValue = watch("triggerCondition.value");- const isCurrency = isCurrencyAttribute(attribute);- // Display value in dollars for currency, but store in cents+ const isCurrency = config.inputType === "currency";+const displayValue =isCurrency && storedValue ? storedValue / 100 : storedValue;return (- <div className="relative rounded-md shadow-sm">- {isCurrency && (- <span className="absolute inset-y-0 left-0 flex items-center pl-1.5 text-sm text-neutral-400">- $- </span>- )}- <input- className={cn(- "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",+ <InlineBadgePopover+ text={+ value ? (isCurrency ? currencyFormatter(value / 100) : value) : "amount"+ }+ invalid={!value}+ >+ <div className="relative rounded-md shadow-sm">+ {isCurrency && (+ <span className="absolute inset-y-0 left-0 flex items-center pl-1.5 text-sm text-neutral-400">+ $+ </span>)}- value={displayValue ?? ""}- onChange={(e) => {- const value = e.target.value;- if (value === "") {- setValue("triggerCondition.value", null as any);- } else {- const numValue = +value;- setValue(- "triggerCondition.value",- isCurrency ? Math.round(numValue * 100) : numValue,- );- }- if (isCurrency) {- handleMoneyInputChange(e);- }- }}- onKeyDown={(e) => {- if (e.key === "Enter") {- e.preventDefault();- setIsOpen(false);- return;- }-- if (isCurrency) {- handleMoneyKeyDown(e);- }- }}- />- {isCurrency && (- <span className="absolute inset-y-0 right-0 flex items-center pr-1.5 text-sm text-neutral-400">- USD- </span>- )}- </div>+ <input+ className={cn(+ "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",+ )}+ value={displayValue ?? ""}+ onChange={(e) => {+ const value = e.target.value;+ if (value === "") {+ setValue("triggerCondition.value", null as any);+ } else {+ const numValue = +value;+ setValue(+ "triggerCondition.value",+ isCurrency ? Math.round(numValue * 100) : numValue,+ );+ }++ if (isCurrency) {+ handleMoneyInputChange(e);+ }+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ setIsOpen(false);+ return;+ }++ if (isCurrency) {+ handleMoneyKeyDown(e);+ }+ }}+ />+ {isCurrency && (+ <span className="absolute inset-y-0 right-0 flex items-center pr-1.5 text-sm text-neutral-400">+ USD+ </span>+ )}+ </div>+ </InlineBadgePopover>);}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/utils.ts b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/utils.tsnew file mode 100644index 0000000000..4aa1340a2c--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/utils.ts@@ -0,0 +1,36 @@+import { WorkflowCondition } from "@/lib/types";+import { CAMPAIGN_WORKFLOW_ATTRIBUTE_CONFIG } from "@/lib/zod/schemas/campaigns";++export function isValidTriggerCondition(+ triggerCondition: WorkflowCondition,+): boolean {+ // Null/undefined is valid (no trigger condition set)+ if (!triggerCondition) {+ return true;+ }++ // Must have an attribute+ if (!triggerCondition.attribute) {+ return false;+ }++ const config = CAMPAIGN_WORKFLOW_ATTRIBUTE_CONFIG[triggerCondition.attribute];++ // If attribute doesn't exist in config, invalid+ if (!config) {+ return false;+ }++ // For "none" inputType (e.g., partnerJoined), no value is needed+ if (config.inputType === "none") {+ return true;+ }++ // For all other input types, value must be present and a valid number+ return (+ triggerCondition.value !== null &&+ triggerCondition.value !== undefined &&+ typeof triggerCondition.value === "number" &&+ !isNaN(triggerCondition.value)+ );+}diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex d0cb9fbc09..80ab652e6d 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -34,7 +34,6 @@ import {SUBMISSION_REQUIREMENTS,} from "./zod/schemas/bounties";import {- CAMPAIGN_WORKFLOW_ATTRIBUTES,CampaignListSchema,CampaignSchema,campaignSummarySchema,@@ -667,9 +666,6 @@ export type Campaign = z.infer<typeof CampaignSchema>;export type UpdateCampaignFormData = z.infer<typeof updateCampaignSchema>;-export type CampaignWorkflowAttribute =- (typeof CAMPAIGN_WORKFLOW_ATTRIBUTES)[number];-export type CampaignSummary = z.infer<typeof campaignSummarySchema>;export type StripeMode = "test" | "sandbox" | "live";@@ -686,3 +682,11 @@ export interface TiptapNode {content?: TiptapNode[];marks?: Array<{ type: string; attrs?: Record<string, any> }>;}++export interface CampaignWorkflowAttributeConfig {+ label: string;+ inputType: "number" | "currency" | "dropdown" | "none";+ dropdownValues?: number[];+}++export type WorkflowAttribute = (typeof WORKFLOW_ATTRIBUTES)[number];diff --git a/apps/web/lib/zod/schemas/campaigns.ts b/apps/web/lib/zod/schemas/campaigns.tsindex b4ea40a530..49aaa9adb0 100644--- a/apps/web/lib/zod/schemas/campaigns.ts+++ b/apps/web/lib/zod/schemas/campaigns.ts@@ -1,4 +1,7 @@-import { CampaignWorkflowAttribute } from "@/lib/types";+import {+ WorkflowAttribute,+ CampaignWorkflowAttributeConfig,+} from "@/lib/types";import { CampaignStatus, CampaignType } from "@dub/prisma/client";import { z } from "zod";import { GroupSchema } from "./groups";@@ -6,35 +9,49 @@ import { getPaginationQuerySchema } from "./misc";import { EnrolledPartnerSchema } from "./partners";import { workflowConditionSchema } from "./workflows";-export const ALLOWED_ATTRIBUTE_VALUES_IN_DAYS = [0, 1, 3, 7, 14, 30];-export const EMAIL_TEMPLATE_VARIABLES = ["PartnerName","PartnerEmail",] as const;-export const CAMPAIGN_WORKFLOW_ATTRIBUTES = [- "totalClicks",- "totalLeads",- "totalConversions",- "totalSales",- "totalSaleAmount",- "totalCommissions",- "partnerEnrolledDays",-] as const;--export const CAMPAIGN_WORKFLOW_ATTRIBUTE_LABELS: Record<- CampaignWorkflowAttribute,- string+export const CAMPAIGN_WORKFLOW_ATTRIBUTE_CONFIG: Record<+ WorkflowAttribute,+ CampaignWorkflowAttributeConfig> = {- totalClicks: "Clicks",- totalLeads: "Leads",- totalConversions: "Conversions",- totalSales: "Sales",- totalSaleAmount: "Revenue",- totalCommissions: "Commissions",- partnerEnrolledDays: "days since enrollment",-} as const;+ totalClicks: {+ label: "clicks",+ inputType: "number",+ },+ totalLeads: {+ label: "leads",+ inputType: "number",+ },+ totalConversions: {+ label: "conversions",+ inputType: "number",+ },+ totalSales: {+ label: "sales",+ inputType: "number",+ },+ totalSaleAmount: {+ label: "revenue",+ inputType: "currency",+ },+ totalCommissions: {+ label: "commissions",+ inputType: "currency",+ },+ partnerEnrolledDays: {+ label: "enrollment duration",+ inputType: "dropdown",+ dropdownValues: [1, 3, 7, 14, 30],+ },+ partnerJoined: {+ label: "joins the program",+ inputType: "none",+ },+};export const CampaignSchema = z.object({id: z.string(),diff --git a/apps/web/lib/zod/schemas/workflows.ts b/apps/web/lib/zod/schemas/workflows.tsindex bd7a7ba2bd..b8b66a8788 100644--- a/apps/web/lib/zod/schemas/workflows.ts+++ b/apps/web/lib/zod/schemas/workflows.ts@@ -14,6 +14,7 @@ export const WORKFLOW_ATTRIBUTES = ["totalSaleAmount","totalCommissions","partnerEnrolledDays",+ "partnerJoined",] as const;export const WORKFLOW_ATTRIBUTE_LABELS: Record<@@ -27,6 +28,7 @@ export const WORKFLOW_ATTRIBUTE_LABELS: Record<totalSaleAmount: "Revenue",totalCommissions: "Commissions",partnerEnrolledDays: "days since enrollment",+ partnerJoined: "joins the program",} as const;export const WORKFLOW_ATTRIBUTE_TRIGGER: Record<@@ -40,6 +42,7 @@ export const WORKFLOW_ATTRIBUTE_TRIGGER: Record<totalSaleAmount: WorkflowTrigger.saleRecorded,totalCommissions: WorkflowTrigger.commissionEarned,partnerEnrolledDays: WorkflowTrigger.partnerEnrolled,+ partnerJoined: WorkflowTrigger.partnerEnrolled,} as const;export const WORKFLOW_COMPARISON_OPERATORS = ["gte"] as const;@@ -69,7 +72,7 @@ export const WORKFLOW_LOGICAL_OPERATORS = ["AND"] as const;export const workflowConditionSchema = z.object({attribute: z.enum(WORKFLOW_ATTRIBUTES),operator: z.enum(WORKFLOW_COMPARISON_OPERATORS).default("gte"),- value: z.number(),+ value: z.number().nullish().describe("value is optional for none inputType"),});// Array of conditions with AND operator