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.

Allow targeting campaigns and bounties by partner tags (#4221)

Kiran K136cafae9cba
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
index f83efe5f5b..93d2af7eb1 100644
--- a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
@@ -1,6 +1,7 @@
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
import { DubApiError } from "@/lib/api/errors";
import { throwIfInvalidGroupIds } from "@/lib/api/groups/throw-if-invalid-group-ids";
+import { throwIfInvalidPartnerTagIds } from "@/lib/api/partner-tags/throw-if-invalid-partner-tag-ids";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { parseRequestBody } from "@/lib/api/utils";
import { WorkflowCondition } from "@/lib/api/workflows/types";
@@ -11,6 +12,7 @@ import { generatePerformanceBountyName } from "@/lib/bounty/api/generate-perform
import { getBountyOrThrow } from "@/lib/bounty/api/get-bounty-or-throw";
import { getBountyWithDetails } from "@/lib/bounty/api/get-bounty-with-details";
import { PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES } from "@/lib/bounty/api/performance-bounty-scope-attributes";
+import { transformBounty } from "@/lib/bounty/api/transform-bounty";
import { shouldUpsertDraftSubmissionsOnReopen } from "@/lib/bounty/api/upsert-draft-bounty-submissions";
import { validateBounty } from "@/lib/bounty/api/validate-bounty";
import { qstash } from "@/lib/cron";
@@ -22,7 +24,12 @@ import {
submissionRequirementsSchema,
updateBountySchema,
} from "@/lib/zod/schemas/bounties";
-import { APP_DOMAIN_WITH_NGROK, arrayEqual, deepEqual } from "@dub/utils";
+import {
+ APP_DOMAIN_WITH_NGROK,
+ arrayEqual,
+ deepEqual,
+ pluck,
+} from "@dub/utils";
import { BountyStartMode, PartnerGroup, Prisma } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
@@ -69,6 +76,7 @@ export const PATCH = withWorkspace(
submissionRequirements,
performanceCondition,
groupIds,
+ partnerTagIds,
} = updateBountySchema.parse(await parseRequestBody(req));
const bounty = await getBountyOrThrow({
@@ -90,6 +98,8 @@ export const PATCH = withWorkspace(
// Absolute end dates are cleared when switching to relative (unless the
// client explicitly sends endsAt) or when setting endsAfterDays.
+ // Do not clear a relative bounty's fixed endsAt on unrelated PATCHes —
+ // relative + calendar endsAt is a supported shape (custom end).
let endsAtUpdate: { endsAt?: Date | null } = {};
if (endsAt !== undefined) {
@@ -97,6 +107,7 @@ export const PATCH = withWorkspace(
} else if (endsAfterDays != null) {
endsAtUpdate = { endsAt: null };
} else if (
+ bounty.startMode === BountyStartMode.absolute &&
nextStartMode === BountyStartMode.relative &&
bounty.endsAt != null
) {
@@ -159,9 +170,11 @@ export const PATCH = withWorkspace(
// if groupIds is provided and is different from the current groupIds, update the groups
let updatedPartnerGroups: PartnerGroup[] | undefined = undefined;
let shouldUpdatePartnerGroups = false;
+ let updatedPartnerTags: { id: string }[] | undefined = undefined;
+ let shouldUpdatePartnerTags = false;
if (groupIds !== undefined) {
- const currentGroupIds = bounty.groups.map((group) => group.groupId);
+ const currentGroupIds = pluck(bounty.groups, "groupId");
const newGroupIds = groupIds || [];
if (!arrayEqual(currentGroupIds, newGroupIds)) {
@@ -176,6 +189,22 @@ export const PATCH = withWorkspace(
}
}
+ if (partnerTagIds !== undefined) {
+ const currentPartnerTagIds = pluck(bounty.partnerTags, "partnerTagId");
+ const newPartnerTagIds = partnerTagIds || [];
+
+ if (!arrayEqual(currentPartnerTagIds, newPartnerTagIds)) {
+ if (newPartnerTagIds.length > 0) {
+ updatedPartnerTags = await throwIfInvalidPartnerTagIds({
+ programId,
+ partnerTagIds: newPartnerTagIds,
+ });
+ }
+
+ shouldUpdatePartnerTags = true;
+ }
+ }
+
// Prevent updates if `performanceCondition.attribute` differs from the current value if there are existing submissions
if (performanceCondition && bounty.workflow) {
const submissionCount = bounty._count.submissions;
@@ -285,6 +314,17 @@ export const PATCH = withWorkspace(
}),
},
}),
+ ...(shouldUpdatePartnerTags && {
+ partnerTags: {
+ deleteMany: {},
+ ...(updatedPartnerTags &&
+ updatedPartnerTags.length > 0 && {
+ create: updatedPartnerTags.map((tag) => ({
+ partnerTagId: tag.id,
+ })),
+ }),
+ },
+ }),
},
include: {
workflow: true,
@@ -309,11 +349,7 @@ export const PATCH = withWorkspace(
};
});
- const updatedBounty = BountySchema.parse({
- ...data,
- groups: data.groups.map(({ groupId }) => ({ id: groupId })),
- performanceCondition: data.workflow?.triggerConditions?.[0],
- });
+ const updatedBounty = BountySchema.parse(transformBounty(data));
const shouldUpsertDraftSubmissions = shouldUpsertDraftSubmissionsOnReopen({
type: bounty.type,
@@ -412,11 +448,7 @@ export const DELETE = withWorkspace(
}
});
- const deletedBounty = BountySchema.parse({
- ...bounty,
- groups: bounty.groups.map(({ groupId }) => ({ id: groupId })),
- performanceCondition: bounty.workflow?.triggerConditions?.[0],
- });
+ const deletedBounty = BountySchema.parse(transformBounty(bounty));
waitUntil(
recordAuditLog({
diff --git a/apps/web/app/(ee)/api/bounties/route.ts b/apps/web/app/(ee)/api/bounties/route.ts
index aa8ae62f83..a5e55e24bf 100644
--- a/apps/web/app/(ee)/api/bounties/route.ts
+++ b/apps/web/app/(ee)/api/bounties/route.ts
@@ -2,6 +2,7 @@ import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
import { createId } from "@/lib/api/create-id";
import { DubApiError } from "@/lib/api/errors";
import { throwIfInvalidGroupIds } from "@/lib/api/groups/throw-if-invalid-group-ids";
+import { throwIfInvalidPartnerTagIds } from "@/lib/api/partner-tags/throw-if-invalid-partner-tag-ids";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
import { parseRequestBody } from "@/lib/api/utils";
@@ -15,6 +16,7 @@ import {
isPartnerEligibleForBounty,
} from "@/lib/bounty/api/bounty-availability";
import { generatePerformanceBountyName } from "@/lib/bounty/api/generate-performance-bounty-name";
+import { transformBounty } from "@/lib/bounty/api/transform-bounty";
import { validateBounty } from "@/lib/bounty/api/validate-bounty";
import { qstash } from "@/lib/cron";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
@@ -26,11 +28,8 @@ import {
createBountySchema,
getBountiesQuerySchema,
} from "@/lib/zod/schemas/bounties";
-import {
- WORKFLOW_ACTION_TYPES,
- WORKFLOW_ATTRIBUTE_TRIGGER,
-} from "@/lib/zod/schemas/workflows";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { WORKFLOW_ACTION_TYPES } from "@/lib/zod/schemas/workflows";
+import { APP_DOMAIN_WITH_NGROK, pluck } from "@dub/utils";
import { BountyStartMode, Workflow } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
@@ -53,18 +52,30 @@ export const GET = withWorkspace(
defaultGroupId: true,
},
},
+ programPartnerTags: {
+ select: {
+ partnerTagId: true,
+ },
+ },
},
})
: null;
const partnerGroupId =
programEnrollment?.groupId || programEnrollment?.program.defaultGroupId;
+ const partnerTagIds = programEnrollment
+ ? pluck(programEnrollment.programPartnerTags, "partnerTagId")
+ : [];
const [bounties, allBountiesSubmissionsCount] = await Promise.all([
prisma.bounty.findMany({
where: {
programId,
- ...(programEnrollment && buildBountyEligibilityWhere(partnerGroupId)),
+ ...(programEnrollment &&
+ buildBountyEligibilityWhere({
+ groupId: partnerGroupId,
+ partnerTagIds,
+ })),
},
include: {
...bountyEligibilityIncludes,
@@ -138,11 +149,10 @@ export const GET = withWorkspace(
return [
BountyListSchema.parse({
- ...bounty,
+ ...transformBounty(bounty),
...(allBountiesSubmissionsCount && {
submissionsCountData: aggregateSubmissionsCountForBounty(bounty.id),
}),
- groups: bounty.groups.map(({ groupId }) => ({ id: groupId })),
}),
];
});
@@ -174,6 +184,7 @@ export const POST = withWorkspace(
maxSubmissions,
submissionRequirements,
groupIds,
+ partnerTagIds,
performanceCondition,
performanceScope,
sendNotificationEmails,
@@ -205,6 +216,11 @@ export const POST = withWorkspace(
groupIds,
});
+ const partnerTags = await throwIfInvalidPartnerTagIds({
+ programId,
+ partnerTagIds,
+ });
+
// Bounty name
let bountyName = name;
@@ -244,7 +260,6 @@ export const POST = withWorkspace(
data: {
id: createId({ prefix: "wf_" }),
programId,
- trigger: WORKFLOW_ATTRIBUTE_TRIGGER[performanceCondition.attribute],
triggerConditions: [performanceCondition],
actions: [action],
},
@@ -284,6 +299,15 @@ export const POST = withWorkspace(
},
},
}),
+ ...(partnerTags.length && {
+ partnerTags: {
+ createMany: {
+ data: partnerTags.map(({ id }) => ({
+ partnerTagId: id,
+ })),
+ },
+ },
+ }),
},
include: {
workflow: true,
@@ -292,11 +316,7 @@ export const POST = withWorkspace(
});
});
- const createdBounty = BountySchema.parse({
- ...bounty,
- groups: bounty.groups.map(({ groupId }) => ({ id: groupId })),
- performanceCondition: bounty.workflow?.triggerConditions?.[0],
- });
+ const createdBounty = BountySchema.parse(transformBounty(bounty));
const shouldScheduleDraftSubmissions =
bounty.type === "performance" &&
diff --git a/apps/web/app/(ee)/api/campaigns/[campaignId]/duplicate/route.ts b/apps/web/app/(ee)/api/campaigns/[campaignId]/duplicate/route.ts
index 7d36486088..c1329aef05 100644
--- a/apps/web/app/(ee)/api/campaigns/[campaignId]/duplicate/route.ts
+++ b/apps/web/app/(ee)/api/campaigns/[campaignId]/duplicate/route.ts
@@ -1,5 +1,6 @@
import { DEFAULT_CAMPAIGN_BODY } from "@/lib/api/campaigns/constants";
import { getCampaignOrThrow } from "@/lib/api/campaigns/get-campaign-or-throw";
+import { campaignEligibilityIncludes } from "@/lib/api/campaigns/transform-campaign";
import { createId } from "@/lib/api/create-id";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { parseWorkflowConfig } from "@/lib/api/workflows/parse-workflow-config";
@@ -17,8 +18,16 @@ export const POST = withWorkspace(
const campaign = await getCampaignOrThrow({
programId,
campaignId,
- includeWorkflow: true,
- includeGroups: true,
+ include: {
+ ...campaignEligibilityIncludes,
+ workflow: {
+ select: {
+ id: true,
+ actions: true,
+ triggerConditions: true,
+ },
+ },
+ },
});
const duplicatedCampaign = await prisma.$transaction(async (tx) => {
@@ -26,15 +35,16 @@ export const POST = withWorkspace(
const campaignId = createId({ prefix: "cmp_" });
if (campaign.workflow) {
- const { action, condition } = parseWorkflowConfig(campaign.workflow);
+ const { action, conditions: triggerConditions } = parseWorkflowConfig(
+ campaign.workflow,
+ );
const newWorkflow = await tx.workflow.create({
data: {
id: createId({ prefix: "wf_" }),
programId,
name: campaign.name,
- trigger: campaign.workflow.trigger,
- triggerConditions: [condition],
+ triggerConditions,
actions: [
{
...action,
@@ -70,6 +80,13 @@ export const POST = withWorkspace(
})),
},
},
+ partnerTags: {
+ createMany: {
+ data: campaign.partnerTags.map(({ partnerTagId }) => ({
+ partnerTagId,
+ })),
+ },
+ },
},
});
});
diff --git a/apps/web/app/(ee)/api/campaigns/[campaignId]/route.ts b/apps/web/app/(ee)/api/campaigns/[campaignId]/route.ts
index b5c864af79..a5ded7839a 100644
--- a/apps/web/app/(ee)/api/campaigns/[campaignId]/route.ts
+++ b/apps/web/app/(ee)/api/campaigns/[campaignId]/route.ts
@@ -1,23 +1,25 @@
import { getCampaignOrThrow } from "@/lib/api/campaigns/get-campaign-or-throw";
import {
- scheduleMarketingCampaign,
- scheduleTransactionalCampaign,
+ deleteCampaignSchedule,
+ scheduleCampaign,
} from "@/lib/api/campaigns/schedule-campaigns";
+import {
+ campaignEligibilityIncludes,
+ transformCampaign,
+} from "@/lib/api/campaigns/transform-campaign";
import { validateCampaign } from "@/lib/api/campaigns/validate-campaign";
import { throwIfInvalidGroupIds } from "@/lib/api/groups/throw-if-invalid-group-ids";
+import { throwIfInvalidPartnerTagIds } from "@/lib/api/partner-tags/throw-if-invalid-partner-tag-ids";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { parseRequestBody } from "@/lib/api/utils";
-import { parseWorkflowConfig } from "@/lib/api/workflows/parse-workflow-config";
import { validateWorkflowConditions } from "@/lib/api/workflows/validate-workflow-conditions";
import { withWorkspace } from "@/lib/auth";
-import { qstash } from "@/lib/cron";
import { prisma } from "@/lib/prisma";
import {
CampaignSchema,
updateCampaignSchema,
} from "@/lib/zod/schemas/campaigns";
-import { WORKFLOW_ATTRIBUTE_TRIGGER } from "@/lib/zod/schemas/workflows";
-import { arrayEqual } from "@dub/utils";
+import { arrayEqual, pluck } from "@dub/utils";
import { PartnerGroup } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
@@ -31,17 +33,17 @@ export const GET = withWorkspace(
const campaign = await getCampaignOrThrow({
programId,
campaignId,
- includeWorkflow: true,
- includeGroups: true,
- });
-
- const parsedCampaign = CampaignSchema.parse({
- ...campaign,
- groups: campaign.groups.map(({ groupId }) => ({ id: groupId })),
- triggerCondition: campaign.workflow?.triggerConditions?.[0],
+ include: {
+ ...campaignEligibilityIncludes,
+ workflow: {
+ select: {
+ triggerConditions: true,
+ },
+ },
+ },
});
- return NextResponse.json(parsedCampaign);
+ return NextResponse.json(CampaignSchema.parse(transformCampaign(campaign)));
},
{
requiredPlan: ["advanced", "enterprise"],
@@ -58,8 +60,14 @@ export const PATCH = withWorkspace(
const campaign = await getCampaignOrThrow({
programId,
campaignId,
- includeWorkflow: true,
- includeGroups: true,
+ include: {
+ ...campaignEligibilityIncludes,
+ workflow: {
+ select: {
+ triggerConditions: true,
+ },
+ },
+ },
});
const {
@@ -70,16 +78,17 @@ export const PATCH = withWorkspace(
status,
bodyJson,
groupIds,
- triggerCondition,
+ partnerTagIds,
+ triggerConditions,
scheduledAt,
} = await validateCampaign({
input: updateCampaignSchema.parse(await parseRequestBody(req)),
campaign,
});
- if (triggerCondition) {
+ if (triggerConditions !== undefined && triggerConditions?.length) {
await validateWorkflowConditions({
- conditions: [triggerCondition],
+ conditions: triggerConditions,
workflowType: "sendCampaign",
});
}
@@ -87,9 +96,11 @@ export const PATCH = withWorkspace(
// if groupIds is provided and is different from the current groupIds, update the groups
let updatedPartnerGroups: PartnerGroup[] | undefined = undefined;
let shouldUpdateGroups = false;
+ let updatedPartnerTags: { id: string }[] | undefined = undefined;
+ let shouldUpdatePartnerTags = false;
if (groupIds !== undefined) {
- const currentGroupIds = campaign.groups.map(({ groupId }) => groupId);
+ const currentGroupIds = pluck(campaign.groups, "groupId");
const newGroupIds = groupIds || []; // treat null as empty array (all groups)
if (!arrayEqual(currentGroupIds, newGroupIds)) {
@@ -104,6 +115,22 @@ export const PATCH = withWorkspace(
}
}
+ if (partnerTagIds !== undefined) {
+ const currentPartnerTagIds = pluck(campaign.partnerTags, "partnerTagId");
+ const newPartnerTagIds = partnerTagIds || []; // treat null as empty array (no tag restriction)
+
+ if (!arrayEqual(currentPartnerTagIds, newPartnerTagIds)) {
+ if (newPartnerTagIds.length > 0) {
+ updatedPartnerTags = await throwIfInvalidPartnerTagIds({
+ programId,
+ partnerTagIds: newPartnerTagIds,
+ });
+ }
+
+ shouldUpdatePartnerTags = true;
+ }
+ }
+
const updatedCampaign = await prisma.$transaction(async (tx) => {
if (campaign.workflowId) {
await tx.workflow.update({
@@ -111,9 +138,8 @@ export const PATCH = withWorkspace(
id: campaign.workflowId,
},
data: {
- ...(triggerCondition && {
- triggerConditions: [triggerCondition],
- trigger: WORKFLOW_ATTRIBUTE_TRIGGER[triggerCondition.attribute],
+ ...(triggerConditions !== undefined && {
+ triggerConditions: triggerConditions ?? [],
}),
...(status && {
disabledAt: status === "paused" ? new Date() : null,
@@ -146,37 +172,35 @@ export const PATCH = withWorkspace(
}),
},
}),
+ ...(shouldUpdatePartnerTags && {
+ partnerTags: {
+ deleteMany: {},
+ ...(updatedPartnerTags &&
+ updatedPartnerTags.length > 0 && {
+ create: updatedPartnerTags.map((tag) => ({
+ partnerTagId: tag.id,
+ })),
+ }),
+ },
+ }),
},
include: {
- groups: true,
+ ...campaignEligibilityIncludes,
workflow: true,
},
});
});
waitUntil(
- (async () => {
- if (updatedCampaign.type === "marketing") {
- await scheduleMarketingCampaign({
- campaign,
- updatedCampaign,
- });
- } else if (updatedCampaign.type === "transactional") {
- await scheduleTransactionalCampaign({
- campaign,
- updatedCampaign,
- });
- }
- })(),
+ scheduleCampaign({
+ campaign,
+ updatedCampaign,
+ }),
);
- const response = CampaignSchema.parse({
- ...updatedCampaign,
- groups: updatedCampaign.groups.map(({ groupId }) => ({ id: groupId })),
- triggerCondition: updatedCampaign.workflow?.triggerConditions?.[0],
- });
-
- return NextResponse.json(response);
+ return NextResponse.json(
+ CampaignSchema.parse(transformCampaign(updatedCampaign)),
+ );
},
{
requiredPlan: ["advanced", "enterprise"],
@@ -193,7 +217,15 @@ export const DELETE = withWorkspace(
const campaign = await getCampaignOrThrow({
programId,
campaignId,
- includeWorkflow: true,
+ include: {
+ workflow: {
+ select: {
+ id: true,
+ actions: true,
+ triggerConditions: true,
+ },
+ },
+ },
});
await prisma.$transaction(async (tx) => {
@@ -212,21 +244,7 @@ export const DELETE = withWorkspace(
}
});
- waitUntil(
- (async () => {
- if (campaign.type === "marketing" && campaign.qstashMessageId) {
- await qstash.messages.cancel(campaign.qstashMessageId);
- } else if (campaign.type === "transactional" && campaign.workflow) {
- const { condition } = parseWorkflowConfig(campaign.workflow);
-
- if (condition.attribute === "partnerJoined") {
- return;
- }
-
- await qstash.schedules.delete(campaign.workflow.id);
- }
- })(),
- );
+ waitUntil(deleteCampaignSchedule(campaign));
return NextResponse.json({ id: campaignId });
},
diff --git a/apps/web/app/(ee)/api/campaigns/route.ts b/apps/web/app/(ee)/api/campaigns/route.ts
index fdfb44df06..0cdf250032 100644
--- a/apps/web/app/(ee)/api/campaigns/route.ts
+++ b/apps/web/app/(ee)/api/campaigns/route.ts
@@ -1,4 +1,8 @@
import { DEFAULT_CAMPAIGN_BODY } from "@/lib/api/campaigns/constants";
+import {
+ campaignEligibilityIncludes,
+ transformCampaign,
+} from "@/lib/api/campaigns/transform-campaign";
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";
@@ -10,12 +14,10 @@ import {
createCampaignSchema,
getCampaignsQuerySchema,
} from "@/lib/zod/schemas/campaigns";
-import {
- WORKFLOW_ACTION_TYPES,
- WORKFLOW_ATTRIBUTE_TRIGGER,
-} from "@/lib/zod/schemas/workflows";
+import { WORKFLOW_ACTION_TYPES } from "@/lib/zod/schemas/workflows";
import { CampaignStatus } from "@prisma/client";
import { NextResponse } from "next/server";
+import * as z from "zod/v4";
// GET /api/campaigns - get all email campaigns for a program
export const GET = withWorkspace(
@@ -26,7 +28,7 @@ export const GET = withWorkspace(
type,
status,
search,
- triggerCondition,
+ triggerConditions,
page = 1,
pageSize,
} = getCampaignsQuerySchema.parse(searchParams);
@@ -42,17 +44,21 @@ export const GET = withWorkspace(
{ subject: { contains: search } },
],
}),
- ...(triggerCondition && {
+ ...(triggerConditions && {
workflow: {
triggerConditions: {
- equals: [triggerCondition],
+ equals: triggerConditions,
},
},
}),
},
include: {
- groups: true,
- workflow: true,
+ ...campaignEligibilityIncludes,
+ workflow: {
+ select: {
+ triggerConditions: true,
+ },
+ },
},
orderBy: {
createdAt: "desc",
@@ -62,13 +68,7 @@ export const GET = withWorkspace(
});
return NextResponse.json(
- campaigns.map((campaign) =>
- CampaignSchema.parse({
- ...campaign,
- groups: campaign.groups.map(({ groupId }) => ({ id: groupId })),
- triggerCondition: campaign.workflow?.triggerConditions?.[0],
- }),
- ),
+ z.array(CampaignSchema).parse(campaigns.map(transformCampaign)),
);
},
{
@@ -102,13 +102,13 @@ export const POST = withWorkspace(
});
if (type === "transactional") {
- const trigger = WORKFLOW_ATTRIBUTE_TRIGGER["partnerJoined"];
-
- const triggerCondition: WorkflowCondition = {
- attribute: "partnerJoined",
- operator: "gte",
- value: 0,
- };
+ const triggerConditions: WorkflowCondition[] = [
+ {
+ attribute: "partnerJoined",
+ operator: "gte",
+ value: 0,
+ },
+ ];
const action: WorkflowAction = {
type: WORKFLOW_ACTION_TYPES.SendCampaign,
@@ -121,8 +121,7 @@ export const POST = withWorkspace(
data: {
id: workflowId,
programId,
- trigger,
- triggerConditions: [triggerCondition],
+ triggerConditions,
actions: [action],
disabledAt: new Date(), // TODO: Replace this with publishedAt
},
diff --git a/apps/web/app/(ee)/api/cron/bounties/notify-partners/route.ts b/apps/web/app/(ee)/api/cron/bounties/notify-partners/route.ts
index 8f1bd4c298..8849ad1f6b 100644
--- a/apps/web/app/(ee)/api/cron/bounties/notify-partners/route.ts
+++ b/apps/web/app/(ee)/api/cron/bounties/notify-partners/route.ts
@@ -1,12 +1,13 @@
import { createId } from "@/lib/api/create-id";
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { bountyEligibilityIncludes } from "@/lib/bounty/api/bounty-availability";
import { qstash } from "@/lib/cron";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
import { prisma } from "@/lib/prisma";
import { ACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";
import { sendBatchEmail } from "@dub/email";
import NewBountyAvailable from "@dub/email/templates/new-bounty-available";
-import { APP_DOMAIN_WITH_NGROK, log } from "@dub/utils";
+import { APP_DOMAIN_WITH_NGROK, log, pluck } from "@dub/utils";
import { BountyStartMode, NotificationEmailType } from "@prisma/client";
import { differenceInMinutes } from "date-fns";
import * as z from "zod/v4";
@@ -50,7 +51,7 @@ export async function POST(req: Request) {
id: bountyId,
},
include: {
- groups: true,
+ ...bountyEligibilityIncludes,
program: {
include: {
emailDomains: {
@@ -85,12 +86,15 @@ export async function POST(req: Request) {
}
}
- const bountyGroupIds = bounty.groups.map(({ groupId }) => groupId);
+ const bountyGroupIds = pluck(bounty.groups, "groupId");
+ const bountyPartnerTagIds = pluck(bounty.partnerTags, "partnerTagId");
console.log(
`Bounty ${bountyId} is applicable to ${
bountyGroupIds.length === 0 ? "all" : bountyGroupIds.length
- } groups (groupIds: ${JSON.stringify(bountyGroupIds)})`,
+ } groups (groupIds: ${JSON.stringify(bountyGroupIds)}) and ${
+ bountyPartnerTagIds.length === 0 ? "all" : bountyPartnerTagIds.length
+ } partner tags (partnerTagIds: ${JSON.stringify(bountyPartnerTagIds)})`,
);
const programEnrollments = await prisma.programEnrollment.findMany({
@@ -101,6 +105,15 @@ export async function POST(req: Request) {
in: bountyGroupIds,
},
}),
+ ...(bountyPartnerTagIds.length > 0 && {
+ programPartnerTags: {
+ some: {
+ partnerTagId: {
+ in: bountyPartnerTagIds,
+ },
+ },
+ },
+ }),
status: {
in: ACTIVE_ENROLLMENT_STATUSES,
},
diff --git a/apps/web/app/(ee)/api/cron/bounties/upsert-draft-submissions/route.ts b/apps/web/app/(ee)/api/cron/bounties/upsert-draft-submissions/route.ts
index 21dea4b9e5..61084f1ec7 100644
--- a/apps/web/app/(ee)/api/cron/bounties/upsert-draft-submissions/route.ts
+++ b/apps/web/app/(ee)/api/cron/bounties/upsert-draft-submissions/route.ts
@@ -1,5 +1,6 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { awardBountyConditionSchema } from "@/lib/api/workflows/award-bounty/schema";
+import { bountyEligibilityIncludes } from "@/lib/bounty/api/bounty-availability";
import {
PartnerLifetimeStats,
planDraftBountySubmissionUpserts,
@@ -9,7 +10,7 @@ import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
import { aggregatePartnerLinksStats } from "@/lib/partners/aggregate-partner-links-stats";
import { prisma } from "@/lib/prisma";
import { COMMISSION_ELIGIBLE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";
-import { APP_DOMAIN_WITH_NGROK, log, toCentsNumber } from "@dub/utils";
+import { APP_DOMAIN_WITH_NGROK, log, pluck, toCentsNumber } from "@dub/utils";
import { differenceInMinutes } from "date-fns";
import * as z from "zod/v4";
import { logAndRespond } from "../../utils";
@@ -43,16 +44,12 @@ export async function POST(req: Request) {
id: bountyId,
},
include: {
+ ...bountyEligibilityIncludes,
workflow: {
select: {
triggerConditions: true,
},
},
- groups: {
- select: {
- groupId: true,
- },
- },
program: {
select: {
id: true,
@@ -92,7 +89,8 @@ export async function POST(req: Request) {
return logAndRespond(`Bounty ${bountyId} has no workflow.`);
}
- const bountyGroupIds = bounty.groups.map(({ groupId }) => groupId);
+ const bountyGroupIds = pluck(bounty.groups, "groupId");
+ const bountyPartnerTagIds = pluck(bounty.partnerTags, "partnerTagId");
// Find program enrollments
const programEnrollments = await prisma.programEnrollment.findMany({
@@ -103,6 +101,15 @@ export async function POST(req: Request) {
in: bountyGroupIds,
},
}),
+ ...(bountyPartnerTagIds.length > 0 && {
+ programPartnerTags: {
+ some: {
+ partnerTagId: {
+ in: bountyPartnerTagIds,
+ },
+ },
+ },
+ }),
...(partnerIds && {
partnerId: {
in: partnerIds,
diff --git a/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts b/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts
index 4052f78fc8..ced6b7dd48 100644
--- a/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts
+++ b/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts
@@ -1,5 +1,6 @@
import { resolveCampaignEmailVariables } from "@/lib/api/campaigns/interpolate-email-template";
import { renderCampaignEmailHTML } from "@/lib/api/campaigns/render-campaign-email-html";
+import { campaignEligibilityIncludes } from "@/lib/api/campaigns/transform-campaign";
import { validateCampaignFromAddress } from "@/lib/api/campaigns/validate-campaign";
import { createId } from "@/lib/api/create-id";
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
@@ -11,7 +12,7 @@ import { TiptapNode } from "@/lib/types";
import { ACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";
import { sendBatchEmail } from "@dub/email";
import CampaignEmail from "@dub/email/templates/campaign-email";
-import { APP_DOMAIN_WITH_NGROK, chunk, log } from "@dub/utils";
+import { APP_DOMAIN_WITH_NGROK, chunk, log, pluck } from "@dub/utils";
import { NotificationEmailType } from "@prisma/client";
import { differenceInMinutes } from "date-fns";
import { headers } from "next/headers";
@@ -55,7 +56,7 @@ export async function POST(req: Request) {
id: campaignId,
},
include: {
- groups: true,
+ ...campaignEligibilityIncludes,
program: {
include: {
emailDomains: {
@@ -141,7 +142,8 @@ export async function POST(req: Request) {
}
}
- const campaignGroupIds = campaign.groups.map(({ groupId }) => groupId);
+ const campaignGroupIds = pluck(campaign.groups, "groupId");
+ const campaignPartnerTagIds = pluck(campaign.partnerTags, "partnerTagId");
const programEnrollments = await prisma.programEnrollment.findMany({
where: {
@@ -154,6 +156,17 @@ export async function POST(req: Request) {
in: campaignGroupIds,
},
}),
+ ...(campaignPartnerTagIds.length > 0 && {
+ partner: {
+ programPartnerTags: {
+ some: {
+ partnerTagId: {
+ in: campaignPartnerTagIds,
+ },
+ },
+ },
+ },
+ }),
},
select: {
id: true,
diff --git a/apps/web/app/(ee)/api/e2e/enrollments/route.ts b/apps/web/app/(ee)/api/e2e/enrollments/route.ts
index e8fcbc0cb2..a9518b40c5 100644
--- a/apps/web/app/(ee)/api/e2e/enrollments/route.ts
+++ b/apps/web/app/(ee)/api/e2e/enrollments/route.ts
@@ -1,17 +1,86 @@
+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 { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { NextResponse } from "next/server";
+import * as z from "zod/v4";
import { assertE2EWorkspace } from "../guard";
+const bodySchema = z.object({
+ partnerId: z.string(),
+ createdAt: z.string().optional(),
+ // Set Link.leads on the partner's first program link (used by send-campaign AND conditions)
+ leads: z.number().int().min(0).optional(),
+ // Create a User + PartnerUser from the partner email so campaign emails have a recipient
+ createUser: z.boolean().optional(),
+});
+
// PATCH /api/e2e/enrollments - Update enrollment (e.g., backdate createdAt)
export const PATCH = withWorkspace(
async ({ req, workspace }) => {
assertE2EWorkspace(workspace);
const programId = getDefaultProgramIdOrThrow(workspace);
- const body = await req.json();
- const { partnerId, createdAt } = body;
+ const { partnerId, createdAt, leads, createUser } = bodySchema.parse(
+ await parseRequestBody(req),
+ );
+
+ if (createUser) {
+ const partner = await prisma.partner.findUnique({
+ where: { id: partnerId },
+ select: { email: true, name: true },
+ });
+
+ if (partner?.email) {
+ const user = await prisma.user.create({
+ data: {
+ id: createId({ prefix: "user_" }),
+ email: partner.email,
+ name: partner.name,
+ emailVerified: new Date(),
+ defaultPartnerId: partnerId,
+ },
+ });
+
+ await prisma.partnerUser.create({
+ data: {
+ userId: user.id,
+ partnerId,
+ role: "owner",
+ notificationPreferences: {
+ create: {},
+ },
+ },
+ });
+ }
+ }
+
+ if (typeof leads === "number") {
+ const link = await prisma.link.findFirst({
+ where: {
+ partnerId,
+ programId,
+ },
+ orderBy: {
+ id: "asc",
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (link) {
+ await prisma.link.update({
+ where: {
+ id: link.id,
+ },
+ data: {
+ leads,
+ },
+ });
+ }
+ }
const enrollment = await prisma.programEnrollment.update({
where: {
@@ -22,11 +91,13 @@ export const PATCH = withWorkspace(
},
data: {
...(createdAt && { createdAt: new Date(createdAt) }),
+ ...(typeof leads === "number" && { totalLeads: leads }),
},
select: {
partnerId: true,
programId: true,
createdAt: true,
+ totalLeads: true,
},
});
diff --git a/apps/web/app/(ee)/api/e2e/workflows/route.ts b/apps/web/app/(ee)/api/e2e/workflows/route.ts
index 4116b5584c..be4e7d18df 100644
--- a/apps/web/app/(ee)/api/e2e/workflows/route.ts
+++ b/apps/web/app/(ee)/api/e2e/workflows/route.ts
@@ -21,7 +21,6 @@ export const GET = withWorkspace(async ({ workspace, searchParams }) => {
},
select: {
id: true,
- trigger: true,
actions: true,
triggerConditions: true,
disabledAt: true,
diff --git a/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/social-content-stats/route.ts b/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/social-content-stats/route.ts
index 7496e7ccc4..ea7b327d2b 100644
--- a/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/social-content-stats/route.ts
+++ b/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/social-content-stats/route.ts
@@ -1,9 +1,13 @@
import { DubApiError } from "@/lib/api/errors";
import { getSocialContent } from "@/lib/api/scrape-creators/get-social-content";
-import { canPartnerSubmitBounty } from "@/lib/bounty/api/bounty-availability";
+import {
+ bountyEligibilityIncludes,
+ canPartnerSubmitBounty,
+} from "@/lib/bounty/api/bounty-availability";
import { getBountyOrThrow } from "@/lib/bounty/api/get-bounty-or-throw";
import { resolveBountyDetails } from "@/lib/bounty/utils";
import { withReferralsEmbedToken } from "@/lib/embed/referrals/auth";
+import { prisma } from "@/lib/prisma";
import { ratelimit } from "@/lib/upstash";
import { NextResponse } from "next/server";
import * as z from "zod/v4";
@@ -33,11 +37,7 @@ export const GET = withReferralsEmbedToken(
bountyId,
programId: programEnrollment.programId,
include: {
- groups: {
- select: {
- groupId: true,
- },
- },
+ ...bountyEligibilityIncludes,
},
});
@@ -50,10 +50,23 @@ export const GET = withReferralsEmbedToken(
});
}
+ const partnerTags = await prisma.programPartnerTag.findMany({
+ where: {
+ programId: programEnrollment.programId,
+ partnerId: programEnrollment.partnerId,
+ },
+ select: {
+ partnerTagId: true,
+ },
+ });
+
const canSubmitBounty = canPartnerSubmitBounty({
program,
bounty,
- programEnrollment,
+ programEnrollment: {
+ ...programEnrollment,
+ programPartnerTags: partnerTags,
+ },
});
if (!canSubmitBounty) {
diff --git a/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/upload/route.ts b/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/upload/route.ts
index f3955af166..8a42cbf977 100644
--- a/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/upload/route.ts
+++ b/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/upload/route.ts
@@ -1,5 +1,7 @@
+import { parseRequestBody } from "@/lib/api/utils";
import { getBountySubmissionUploadUrl } from "@/lib/bounty/api/get-bounty-submission-upload-url";
import { withReferralsEmbedToken } from "@/lib/embed/referrals/auth";
+import { prisma } from "@/lib/prisma";
import { NextResponse } from "next/server";
import * as z from "zod/v4";
@@ -14,15 +16,28 @@ export const POST = withReferralsEmbedToken(
async ({ req, programEnrollment, params }) => {
const { bountyId } = params;
const { fileName, contentType, contentLength } = bodySchema.parse(
- await req.json(),
+ await parseRequestBody(req),
);
+ const programPartnerTags = await prisma.programPartnerTag.findMany({
+ where: {
+ programId: programEnrollment.programId,
+ partnerId: programEnrollment.partnerId,
+ },
+ select: {
+ partnerTagId: true,
+ },
+ });
+
const { signedUrl, destinationUrl } = await getBountySubmissionUploadUrl({
bountyId,
fileName,
contentType,
contentLength,
- programEnrollment,
+ programEnrollment: {
+ ...programEnrollment,
+ programPartnerTags,
+ },
});
return NextResponse.json({
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/route.ts
index f050307478..d783c09868 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/route.ts
@@ -2,6 +2,7 @@ import { DubApiError } from "@/lib/api/errors";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
import { withPartnerProfile } from "@/lib/auth/partner";
import {
+ bountyEligibilityIncludes,
canPartnerSeeBounty,
getEffectiveBountyPeriod,
} from "@/lib/bounty/api/bounty-availability";
@@ -34,6 +35,11 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {
saleAmount: true,
},
},
+ programPartnerTags: {
+ select: {
+ partnerTagId: true,
+ },
+ },
},
});
@@ -41,12 +47,12 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {
programId: program.id,
bountyId,
include: {
+ ...bountyEligibilityIncludes,
workflow: {
select: {
triggerConditions: true,
},
},
- groups: true,
submissions: {
where: {
partnerId: partner.id,
@@ -83,7 +89,7 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {
bounty,
});
- const { groups, ...bountyWithoutGroups } = bounty;
+ const { groups, partnerTags, ...bountyWithoutGroups } = bounty;
return NextResponse.json(
PartnerBountySchema.parse({
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/social-content-stats/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/social-content-stats/route.ts
index 931b4efdd2..9c5227c4d5 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/social-content-stats/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/[bountyId]/social-content-stats/route.ts
@@ -2,7 +2,10 @@ import { DubApiError } from "@/lib/api/errors";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
import { getSocialContent } from "@/lib/api/scrape-creators/get-social-content";
import { withPartnerProfile } from "@/lib/auth/partner";
-import { canPartnerSubmitBounty } from "@/lib/bounty/api/bounty-availability";
+import {
+ bountyEligibilityIncludes,
+ canPartnerSubmitBounty,
+} from "@/lib/bounty/api/bounty-availability";
import { getBountyOrThrow } from "@/lib/bounty/api/get-bounty-or-throw";
import { resolveBountyDetails } from "@/lib/bounty/utils";
import { ratelimit } from "@/lib/upstash";
@@ -41,6 +44,11 @@ export const GET = withPartnerProfile(
defaultGroupId: true,
},
},
+ programPartnerTags: {
+ select: {
+ partnerTagId: true,
+ },
+ },
},
});
@@ -48,11 +56,7 @@ export const GET = withPartnerProfile(
bountyId,
programId: programEnrollment.programId,
include: {
- groups: {
- select: {
- groupId: true,
- },
- },
+ ...bountyEligibilityIncludes,
submissions: {
where: {
partnerId: partner.id,
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/route.ts
index a8106c0209..03fadc4089 100644
--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/bounties/route.ts
@@ -24,6 +24,11 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {
saleAmount: true,
},
},
+ programPartnerTags: {
+ select: {
+ partnerTagId: true,
+ },
+ },
},
});
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.ts
index 7ba2693410..0b87fe5716 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
@@ -533,8 +533,7 @@ export async function checkoutSessionCompleted({
waitUntil(
Promise.allSettled([
executeWorkflows({
- trigger: "partnerMetricsUpdated",
- reason: "sale",
+ event: "saleRecorded",
identity: {
workspaceId: workspace.id,
programId: link.programId,
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts
index b10a67a567..9c03fbd7ad 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts
@@ -355,8 +355,7 @@ export async function invoicePaid({
waitUntil(
Promise.allSettled([
executeWorkflows({
- trigger: "partnerMetricsUpdated",
- reason: "sale",
+ event: "saleRecorded",
identity: {
workspaceId: workspace.id,
programId: link.programId,
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts
index 53bb848e95..8d455725c9 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts
@@ -219,8 +219,7 @@ export async function attributeViaPromotionCodeId({
await Promise.allSettled([
executeWorkflows({
- trigger: "partnerMetricsUpdated",
- reason: "lead",
+ event: "leadRecorded",
identity: {
workspaceId: workspace.id,
programId: link.programId,
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/sync-customer.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/sync-customer.ts
index dbf7e9f78c..c8023f4ace 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/sync-customer.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/sync-customer.ts
@@ -234,8 +234,7 @@ export async function syncCustomer({
await Promise.allSettled([
executeWorkflows({
- trigger: "partnerMetricsUpdated",
- reason: "lead",
+ event: "leadRecorded",
identity: {
workspaceId: workspace.id,
programId: link.programId,
diff --git a/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts b/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts
index 867914acfa..d64ab12bd1 100644
--- a/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts
+++ b/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts
@@ -692,8 +692,7 @@ async function stepRunSideEffects(
// Execute Dub workflows
shouldTriggerWorkflow &&
executeWorkflows({
- trigger: "partnerMetricsUpdated",
- reason: "commission",
+ event: "commissionRecorded",
identity: {
workspaceId: workspace.id,
programId,
diff --git a/apps/web/app/(ee)/api/workflows/partner-approved/route.ts b/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
index 2f35ba6f26..599f02aed1 100644
--- a/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
+++ b/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
@@ -308,7 +308,7 @@ export const { POST } = serve<Input>(
// Step 6: Execute Dub workflows using the “partnerEnrolled” trigger.
await context.run("execute-workflows", async () => {
await executeWorkflows({
- trigger: "partnerEnrolled",
+ event: "partnerEnrolled",
identity: {
workspaceId: program.workspaceId,
programId,
diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts b/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts
index 840b6083a0..1c07d048f0 100644
--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts
+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/get-referrals-embed-data.ts
@@ -59,6 +59,11 @@ export const getReferralsEmbedData = async (token: string) => {
saleReward: true,
referralReward: true,
discount: true,
+ programPartnerTags: {
+ select: {
+ partnerTagId: true,
+ },
+ },
},
});
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx
index 06ba2863ee..40737fcbf5 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx
@@ -2,31 +2,17 @@
import { getProgramBountyMeta } from "@/lib/bounty/bounty-period";
import useBounty from "@/lib/swr/use-bounty";
-import useGroups from "@/lib/swr/use-groups";
import useWorkspace from "@/lib/swr/use-workspace";
+import { BountyEligibilitySummary } from "@/ui/partners/bounties/bounty-eligibility-summary";
import { BountyRewardDescription } from "@/ui/partners/bounties/bounty-reward-description";
import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
-import { GroupColorCircle } from "@/ui/partners/groups/group-color-circle";
-import { ScrollableTooltipContent, Tooltip } from "@dub/ui";
-import { Calendar6, Users6 } from "@dub/ui/icons";
-import { useMemo } from "react";
+import { Calendar6 } from "@dub/ui/icons";
import { BountyActionButton } from "../bounty-action-button";
export function BountyInfo() {
const { bounty, loading } = useBounty();
const { isOwner } = useWorkspace();
- const { groups } = useGroups();
-
- const eligibleGroups = useMemo(() => {
- if (!groups || !bounty || bounty.groups.length === 0) {
- return [];
- }
- return bounty.groups
- .map((bountyGroup) => groups.find((g) => g.id === bountyGroup.id))
- .filter((g): g is NonNullable<typeof g> => g !== undefined);
- }, [groups, bounty]);
-
if (loading) {
return <BountyInfoSkeleton />;
}
@@ -53,47 +39,20 @@ export function BountyInfo() {
</div>
</div>
- <div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
+ <div className="text-content-subtle flex items-center gap-2 text-sm font-normal">
<Calendar6 className="size-4 shrink-0" />
<span>{dateRangeLabel}</span>
</div>
- <BountyRewardDescription bounty={bounty} className="font-regular" />
+ <BountyRewardDescription bounty={bounty} className="font-normal" />
{isOwner && (
- <div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
- <Users6 className="size-4 shrink-0" />
- {bounty.groups.length === 0 ? (
- <span>All groups</span>
- ) : eligibleGroups.length === 1 ? (
- <div className="flex items-center gap-1.5">
- <GroupColorCircle group={eligibleGroups[0]} />
- <span className="truncate">{eligibleGroups[0].name}</span>
- </div>
- ) : eligibleGroups.length > 1 ? (
- <Tooltip
- content={
- <ScrollableTooltipContent>
- {eligibleGroups.map((group) => (
- <div key={group.id} className="flex items-center gap-2">
- <GroupColorCircle group={group} />
- <span className="font-regular text-sm text-neutral-700">
- {group.name}
- </span>
- </div>
- ))}
- </ScrollableTooltipContent>
- }
- >
- <div className="flex items-center gap-1.5">
- <GroupColorCircle group={eligibleGroups[0]} />
- <span className="truncate">
- {eligibleGroups[0].name} +{eligibleGroups.length - 1}
- </span>
- </div>
- </Tooltip>
- ) : null}
- </div>
+ <BountyEligibilitySummary
+ groups={bounty.groups}
+ partnerTags={bounty.partnerTags}
+ iconClassName="size-4"
+ className="font-normal"
+ />
)}
</div>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/add-edit-bounty-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/add-edit-bounty-sheet.tsx
index d142276ccf..1e73ff202a 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/add-edit-bounty-sheet.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/add-edit-bounty-sheet.tsx
@@ -6,7 +6,6 @@ import { getPlanCapabilities } from "@/lib/plan-capabilities";
import useProgram from "@/lib/swr/use-program";
import useWorkspace from "@/lib/swr/use-workspace";
import { BountyProps } from "@/lib/types";
-import { GroupsMultiSelect } from "@/ui/partners/groups/groups-multi-select";
import {
ProgramSheetAccordion,
ProgramSheetAccordionContent,
@@ -42,6 +41,7 @@ import { cn } from "@dub/utils";
import { BountyStartMode, BountySubmissionFrequency } from "@prisma/client";
import { Dispatch, SetStateAction, useMemo, useState } from "react";
import { Controller, FormProvider } from "react-hook-form";
+import { AudienceEligibilityPanel } from "./audience-eligibility-panel";
import { BountyCriteria } from "./bounty-criteria";
import { BountyDuration } from "./bounty-duration";
import { useAddEditBountyForm } from "./use-add-edit-bounty-form";
@@ -397,21 +397,12 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {
<BountyCriteria />
- <ProgramSheetAccordionItem value="groups">
+ <ProgramSheetAccordionItem value="eligibility">
<ProgramSheetAccordionTrigger>
- Groups
+ Eligibility
</ProgramSheetAccordionTrigger>
<ProgramSheetAccordionContent>
- <Controller
- control={control}
- name="groupIds"
- render={({ field }) => (
- <GroupsMultiSelect
- selectedGroupIds={field.value}
- setSelectedGroupIds={(ids) => field.onChange(ids)}
- />
- )}
- />
+ <AudienceEligibilityPanel />
</ProgramSheetAccordionContent>
</ProgramSheetAccordionItem>
</ProgramSheetAccordion>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/audience-eligibility-panel.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/audience-eligibility-panel.tsx
new file mode 100644
index 0000000000..f11af67569
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/audience-eligibility-panel.tsx
@@ -0,0 +1,35 @@
+"use client";
+
+import { PartnerGroupsSelect } from "@/ui/partners/groups/partner-groups-select";
+import { PartnerTagsSelect } from "@/ui/partners/partner-tags-select";
+import { Controller } from "react-hook-form";
+import { useBountyFormContext } from "./bounty-form-context";
+
+export function AudienceEligibilityPanel() {
+ const { control } = useBountyFormContext();
+
+ return (
+ <div className="flex flex-col gap-6">
+ <Controller
+ control={control}
+ name="groupIds"
+ render={({ field }) => (
+ <PartnerGroupsSelect
+ selectedGroupIds={field.value ?? null}
+ setSelectedGroupIds={field.onChange}
+ />
+ )}
+ />
+ <Controller
+ control={control}
+ name="partnerTagIds"
+ render={({ field }) => (
+ <PartnerTagsSelect
+ selectedPartnerTagIds={field.value ?? null}
+ setSelectedPartnerTagIds={field.onChange}
+ />
+ )}
+ />
+ </div>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-duration.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-duration.tsx
index 41f56b6dc7..d547ffaa38 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-duration.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/bounty-duration.tsx
@@ -418,14 +418,6 @@ export function BountyDuration({
initialPresets.customEndsAfterDays,
);
- const [endDateLocked] = useState(
- () => isEditing && (value.endsAt != null || value.endsAfterDays != null),
- );
-
- const endOptions = endDateLocked
- ? END_OPTIONS.filter((option) => option.value !== "never")
- : END_OPTIONS;
-
useEffect(() => {
const presets = parsePresetsFromValue(value, isEditing);
setStartPreset(presets.startPreset);
@@ -526,16 +518,12 @@ export function BountyDuration({
and ends{" "}
<BountyDatePicker
label={endLabel ?? "never"}
- options={endOptions}
+ options={END_OPTIONS}
selectedPreset={customEndsAfterDays != null ? undefined : endPreset}
customDate={
customEndsAt ?? value.endsAt ?? addWeeks(value.startsAt, 2)
}
onSelectPreset={(preset) => {
- if (endDateLocked && preset === "never") {
- return;
- }
-
setEndPreset(preset);
setCustomEndsAfterDays(null);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/confirm-create-bounty-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/confirm-create-bounty-modal.tsx
index 996641ef3c..3c39fd8cf8 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/confirm-create-bounty-modal.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/confirm-create-bounty-modal.tsx
@@ -1,12 +1,11 @@
import { getProgramBountyMeta } from "@/lib/bounty/bounty-period";
import { getBountyRewardDescription } from "@/lib/bounty/rewards";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
-import useGroups from "@/lib/swr/use-groups";
import { usePartnersCountByGroupIds } from "@/lib/swr/use-partners-count-by-groupids";
import useWorkspace from "@/lib/swr/use-workspace";
import { BountyProps } from "@/lib/types";
+import { BountyEligibilitySummary } from "@/ui/partners/bounties/bounty-eligibility-summary";
import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
-import { GroupColorCircle } from "@/ui/partners/groups/group-color-circle";
import {
Button,
Calendar6,
@@ -14,15 +13,12 @@ import {
DynamicTooltipWrapper,
Gift,
Modal,
- ScrollableTooltipContent,
- Tooltip,
TooltipContent,
} from "@dub/ui";
-import { Users6 } from "@dub/ui/icons";
-import { nFormatter, pluralize } from "@dub/utils";
+import { nFormatter, pluck, pluralize } from "@dub/utils";
import { cn } from "@dub/utils/src";
import { BountyStartMode } from "@prisma/client";
-import { Dispatch, SetStateAction, useMemo, useState } from "react";
+import { Dispatch, SetStateAction, useState } from "react";
type ConfirmCreateBountyModalProps = {
bounty?: Pick<
@@ -37,6 +33,7 @@ type ConfirmCreateBountyModalProps = {
| "rewardDescription"
| "submissionRequirements"
| "groups"
+ | "partnerTags"
>;
onConfirm: (data: { sendNotificationEmails: boolean }) => Promise<void>;
};
@@ -50,7 +47,6 @@ function ConfirmCreateBountyModal({
showConfirmCreateBountyModal: boolean;
setShowConfirmCreateBountyModal: Dispatch<SetStateAction<boolean>>;
} & ConfirmCreateBountyModalProps) {
- const { groups } = useGroups();
const { plan, slug: workspaceSlug, isOwner } = useWorkspace();
const { canSendEmailCampaigns } = getPlanCapabilities(plan);
@@ -65,19 +61,16 @@ function ConfirmCreateBountyModal({
const { totalPartners, loading } = usePartnersCountByGroupIds({
groupIds: isRelative
? null
- : bounty?.groups?.map((group) => group.id) ?? [],
+ : bounty?.groups
+ ? pluck(bounty.groups, "id")
+ : [],
+ partnerTagIds: isRelative
+ ? null
+ : bounty?.partnerTags
+ ? pluck(bounty.partnerTags, "id")
+ : [],
});
- const eligibleGroups = useMemo(() => {
- if (!groups || !bounty || bounty.groups.length === 0) {
- return [];
- }
-
- return bounty.groups
- .map((bountyGroup) => groups.find((g) => g.id === bountyGroup.id))
- .filter((g): g is NonNullable<typeof g> => g !== undefined);
- }, [groups, bounty?.groups]);
-
if (!bounty) {
return null;
}
@@ -106,7 +99,7 @@ function ConfirmCreateBountyModal({
Confirm bounty creation
</h3>
<p className="text-content-subtle mt-1 text-sm">
- You are about to create this bounty for the selected partner groups.
+ You are about to create this bounty for the selected partners.
</p>
<div className="border-border-subtle mt-4 rounded-xl border bg-white p-2">
@@ -122,13 +115,13 @@ function ConfirmCreateBountyModal({
{bounty.name}
</h3>
- <div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
+ <div className="text-content-subtle flex items-center gap-2 text-sm font-normal">
<Calendar6 className="size-3.5" />
<span>{dateRangeLabel}</span>
</div>
{!isOwner && (
- <div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
+ <div className="text-content-subtle flex items-center gap-2 text-sm font-normal">
<Gift className="size-3.5 shrink-0" />
<span className="truncate">
{getBountyRewardDescription(bounty)}
@@ -137,42 +130,11 @@ function ConfirmCreateBountyModal({
)}
{isOwner && (
- <div className="text-content-subtle font-regular flex items-center gap-2 text-sm">
- <Users6 className="size-3.5" />
- {bounty.groups.length === 0 ? (
- <span>All groups</span>
- ) : eligibleGroups.length === 1 ? (
- <div className="flex items-center gap-1.5">
- <GroupColorCircle group={eligibleGroups[0]} />
- <span className="truncate">{eligibleGroups[0].name}</span>
- </div>
- ) : eligibleGroups.length > 1 ? (
- <Tooltip
- content={
- <ScrollableTooltipContent>
- {eligibleGroups.map((group) => (
- <div
- key={group.id}
- className="flex items-center gap-2"
- >
- <GroupColorCircle group={group} />
- <span className="font-regular text-sm text-neutral-700">
- {group.name}
- </span>
- </div>
- ))}
- </ScrollableTooltipContent>
- }
- >
- <div className="flex items-center gap-1.5">
- <GroupColorCircle group={eligibleGroups[0]} />
- <span className="truncate">
- {eligibleGroups[0].name} +{eligibleGroups.length - 1}
- </span>
- </div>
- </Tooltip>
- ) : null}
- </div>
+ <BountyEligibilitySummary
+ groups={bounty.groups}
+ partnerTags={bounty.partnerTags}
+ className="font-normal"
+ />
)}
</div>
</div>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/use-add-edit-bounty-form.ts b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/use-add-edit-bounty-form.ts
index b4c9dd73e9..847716672b 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/use-add-edit-bounty-form.ts
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty/use-add-edit-bounty-form.ts
@@ -14,7 +14,7 @@ import { useApiMutation } from "@/lib/swr/use-api-mutation";
import useWorkspace from "@/lib/swr/use-workspace";
import { BountyProps } from "@/lib/types";
import { bountySocialContentRequirementsSchema } from "@/lib/zod/schemas/bounties";
-import { formatDate } from "@dub/utils";
+import { formatDate, pluck } from "@dub/utils";
import { BountyStartMode, BountySubmissionFrequency } from "@prisma/client";
import { addDays } from "date-fns";
import {
@@ -34,7 +34,7 @@ const ACCORDION_ITEMS = [
"bounty-type",
"bounty-details",
"bounty-criteria",
- "groups",
+ "eligibility",
];
const DEFAULT_SOCIAL_METRICS_CRITERIA = {
@@ -161,7 +161,10 @@ export function useAddEditBountyForm({
? "submission"
: "performance",
submissionRequirements: initialSubmissionRequirements,
- groupIds: bounty?.groups?.map(({ id }) => id) || null,
+ groupIds: bounty?.groups?.length ? pluck(bounty.groups, "id") : null,
+ partnerTagIds: bounty?.partnerTags?.length
+ ? pluck(bounty.partnerTags, "id")
+ : null,
performanceCondition: bounty?.performanceCondition
? {
...bounty.performanceCondition,
@@ -202,6 +205,7 @@ export function useAddEditBountyForm({
description,
performanceCondition,
groupIds,
+ partnerTagIds,
rewardType,
submissionRequirements,
] = watch([
@@ -217,6 +221,7 @@ export function useAddEditBountyForm({
"description",
"performanceCondition",
"groupIds",
+ "partnerTagIds",
"rewardType",
"submissionRequirements",
]);
@@ -724,6 +729,7 @@ export function useAddEditBountyForm({
rewardDescription: rewardDescription || null,
submissionRequirements: submissionRequirements ?? null,
groups: groupIds?.map((id) => ({ id })) || [],
+ partnerTags: partnerTagIds?.map((id) => ({ id })) || [],
}
: undefined,
onConfirm: async ({ sendNotificationEmails }) => {
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx
index 10df67a7c5..972256c7ba 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx
@@ -1,41 +1,28 @@
import { getProgramBountyMeta } from "@/lib/bounty/bounty-period";
-import useGroups from "@/lib/swr/use-groups";
import { usePartnersCountByGroupIds } from "@/lib/swr/use-partners-count-by-groupids";
import useWorkspace from "@/lib/swr/use-workspace";
import { BountyListProps } from "@/lib/types";
+import { BountyEligibilitySummary } from "@/ui/partners/bounties/bounty-eligibility-summary";
import {
BountyProgressBarRow,
EmphasisNumber,
} from "@/ui/partners/bounties/bounty-progress-bar-row";
import { BountyRewardDescription } from "@/ui/partners/bounties/bounty-reward-description";
import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
-import { GroupColorCircle } from "@/ui/partners/groups/group-color-circle";
-import { DynamicTooltipWrapper, ScrollableTooltipContent } from "@dub/ui";
-import { Calendar6, Users6 } from "@dub/ui/icons";
-import { formatDate, nFormatter, pluralize } from "@dub/utils";
+import { Calendar6 } from "@dub/ui/icons";
+import { formatDate, nFormatter, pluck, pluralize } from "@dub/utils";
import Link from "next/link";
-import { useMemo } from "react";
export function BountyCard({ bounty }: { bounty: BountyListProps }) {
const { slug: workspaceSlug } = useWorkspace();
const { totalPartners, loading } = usePartnersCountByGroupIds({
- groupIds: bounty.groups.map((group) => group.id),
+ groupIds: pluck(bounty.groups, "id"),
+ partnerTagIds: pluck(bounty.partnerTags, "id"),
});
- const { groups } = useGroups();
-
const { dateRangeLabel } = getProgramBountyMeta(bounty);
- const eligibleGroups = useMemo(() => {
- if (!groups || bounty.groups.length === 0) {
- return [];
- }
- return bounty.groups
- .map((bountyGroup) => groups.find((g) => g.id === bountyGroup.id))
- .filter((g): g is NonNullable<typeof g> => g !== undefined);
- }, [groups, bounty.groups]);
-
const submissionsCount = bounty.submissionsCountData?.total ?? 0;
const progress =
totalPartners > 0 ? (submissionsCount / totalPartners) * 100 : 0;
@@ -81,48 +68,10 @@ export function BountyCard({ bounty }: { bounty: BountyListProps }) {
onTooltipClick={(e) => e.preventDefault()}
/>
- <div className="text-content-subtle flex items-center gap-2 text-sm font-normal">
- <Users6 className="size-3.5" />
- {bounty.groups.length === 0 ? (
- <span>All groups</span>
- ) : eligibleGroups.length > 0 ? (
- <DynamicTooltipWrapper
- tooltipProps={
- eligibleGroups.length > 1
- ? {
- content: (
- <ScrollableTooltipContent>
- {eligibleGroups.map((group) => (
- <div
- key={group.id}
- className="flex items-center gap-2"
- >
- <GroupColorCircle group={group} />
- <span className="text-sm font-normal text-neutral-700">
- {group.name}
- </span>
- </div>
- ))}
- </ScrollableTooltipContent>
- ),
- }
- : undefined
- }
- >
- <div className="flex items-center gap-1.5">
- <GroupColorCircle group={eligibleGroups[0]} />
- <span className="truncate">
- {eligibleGroups[0].name}{" "}
- {eligibleGroups.length > 1
- ? `+${eligibleGroups.length - 1}`
- : ""}
- </span>
- </div>
- </DynamicTooltipWrapper>
- ) : (
- <div className="h-5 w-32 animate-pulse rounded bg-neutral-200" />
- )}
- </div>
+ <BountyEligibilitySummary
+ groups={bounty.groups}
+ partnerTags={bounty.partnerTags}
+ />
</div>
</div>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-controls.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-controls.tsx
index beb654c416..a14eb31d02 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-controls.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-controls.tsx
@@ -58,7 +58,7 @@ export function CampaignControls({ campaign }: CampaignControlsProps) {
subject,
groupIds,
bodyJson,
- triggerCondition,
+ triggerConditions,
from,
scheduledAt,
] = useWatch({
@@ -68,7 +68,7 @@ export function CampaignControls({ campaign }: CampaignControlsProps) {
"subject",
"groupIds",
"bodyJson",
- "triggerCondition",
+ "triggerConditions",
"from",
"scheduledAt",
],
@@ -103,7 +103,7 @@ export function CampaignControls({ campaign }: CampaignControlsProps) {
if (
!sendPreview &&
campaign.type === "transactional" &&
- !triggerCondition
+ !triggerConditions?.length
) {
return "Please select a trigger condition.";
}
@@ -112,7 +112,7 @@ export function CampaignControls({ campaign }: CampaignControlsProps) {
return "Please write the message you want to send to the partners.";
}
},
- [name, subject, groupIds, triggerCondition, bodyJson, from],
+ [name, subject, groupIds, triggerConditions, bodyJson, from],
);
// Confirmation modals
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor-skeleton.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor-skeleton.tsx
index 7bd1cc2bfe..67b7cb2cce 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor-skeleton.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor-skeleton.tsx
@@ -24,7 +24,7 @@ export function CampaignEditorSkeleton() {
</div>
}
>
- <PageWidthWrapper className="mb-8 max-w-[600px]">
+ <PageWidthWrapper className="mb-8 max-w-[720px]">
<div className="grid grid-cols-[max-content_minmax(0,1fr)] items-center gap-x-6 gap-y-2">
<span className={labelClassName}>Name</span>
<div className="h-8 w-full animate-pulse rounded-md bg-neutral-100" />
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.tsx
index d8bc9a6441..182eb463bf 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
@@ -1,5 +1,6 @@
import { uploadCampaignImageAction } from "@/lib/actions/partners/upload-campaign-image";
import { CAMPAIGN_READONLY_STATUSES } from "@/lib/api/campaigns/constants";
+import { checkWorkflowConditions } from "@/lib/api/workflows/check-workflow-conditions";
import {
formatCampaignFromAddress,
parseCampaignFromAddress,
@@ -26,7 +27,7 @@ import {
TooltipContent,
useKeyboardShortcut,
} from "@dub/ui";
-import { capitalize, cn } from "@dub/utils";
+import { capitalize, cn, pluck } from "@dub/utils";
import { CampaignStatus } from "@prisma/client";
import slugify from "@sindresorhus/slugify";
import { motion } from "motion/react";
@@ -46,11 +47,13 @@ import { CAMPAIGN_STATUS_BADGES } from "../campaign-status-badges";
import { CampaignActionBar } from "./campaign-action-bar";
import { CampaignControls } from "./campaign-controls";
import { CampaignEvents } from "./campaign-events";
-import { CampaignGroupsSelector } from "./campaign-groups-selector";
import { CampaignMetrics } from "./campaign-metrics";
+import {
+ CampaignGroupsSelector,
+ CampaignTagsSelector,
+} from "./campaign-recipients-selector";
import { DuplicateLogicWarning } from "./duplicate-logic-warning";
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 sm:text-sm text-content-default placeholder:text-content-muted hover:bg-neutral-100 hover:cursor-pointer";
@@ -64,7 +67,7 @@ const DisabledInputWrapper = ({
hideIcon = false,
}: {
children: React.ReactNode;
- tooltip: string;
+ tooltip: React.ReactNode;
disabled?: boolean;
hideIcon?: boolean;
}) => {
@@ -74,22 +77,29 @@ const DisabledInputWrapper = ({
return (
<Tooltip content={tooltip}>
- <div className="relative">
+ <div className="group/locked relative cursor-not-allowed rounded-md transition-colors duration-150 hover:bg-neutral-100">
<div className="pointer-events-none select-none opacity-80">
{children}
</div>
- {!hideIcon && (
- <Lock className="absolute right-2 top-1/2 size-3 -translate-y-1/2 text-neutral-400" />
- )}
+ <Lock
+ className={cn(
+ "pointer-events-none absolute right-2 top-4 size-3 -translate-y-1/2 text-neutral-400 transition-opacity duration-150",
+ hideIcon
+ ? "opacity-0 group-hover/locked:opacity-100"
+ : "opacity-100",
+ )}
+ />
</div>
</Tooltip>
);
};
-const statusMessages = {
+const statusMessages: Partial<Record<CampaignStatus, string>> = {
sending: "Edits aren't allowed while sending.",
sent: "Edits aren't allowed after sending.",
canceled: "Edits aren't allowed after cancellation.",
+ active:
+ "Edits aren't allowed while the campaign is active. Pause the campaign to make changes.",
};
function CampaignFromField({
@@ -233,6 +243,8 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
const isActive = campaign.status === CampaignStatus.active;
const isReadOnly = CAMPAIGN_READONLY_STATUSES.includes(campaign.status);
+ const isLocked = isActive || isReadOnly;
+ const lockTooltip = isLocked ? statusMessages[campaign.status] : undefined;
const { makeRequest, isSubmitting: isSavingCampaign } =
useApiMutation<Campaign>();
@@ -244,8 +256,11 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
preview: campaign.preview,
from: campaign.from ?? undefined,
bodyJson: campaign.bodyJson,
- groupIds: campaign.groups.map(({ id }) => id),
- triggerCondition: campaign.triggerCondition,
+ groupIds: campaign.groups.length ? pluck(campaign.groups, "id") : null,
+ partnerTagIds: campaign.partnerTags.length
+ ? pluck(campaign.partnerTags, "id")
+ : null,
+ triggerConditions: campaign.triggerConditions ?? [],
scheduledAt: campaign.scheduledAt,
},
});
@@ -302,10 +317,27 @@ 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 ("partnerTagIds" in changedFields) {
+ changedFields.partnerTagIds = Array.isArray(
+ changedFields.partnerTagIds,
+ )
+ ? changedFields.partnerTagIds
+ : null;
+ }
+
+ if ("triggerConditions" in changedFields) {
+ const { valid, errors } = checkWorkflowConditions({
+ conditions: changedFields.triggerConditions,
+ workflowType: "sendCampaign",
+ });
+
+ if (!valid) {
+ if (isDraft) {
+ delete changedFields.triggerConditions;
+ } else {
+ toast.error(errors[0]);
+ return;
+ }
}
}
@@ -372,7 +404,7 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
saveCampaign({ isDraft: false });
}
},
- { enabled: true },
+ { enabled: !isLocked },
);
const { executeAsync: executeImageUpload } = useAction(
@@ -446,19 +478,19 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
individualScrolling
contentWrapperClassName="flex flex-col"
>
- <PageWidthWrapper className="mb-8 max-w-[600px]">
+ <PageWidthWrapper className="mb-8 max-w-[720px]">
<div className="grid grid-cols-[max-content_minmax(0,1fr)] items-center gap-x-6 [&>*:nth-child(n+3)]:mt-2">
<span className={labelClassName}>Name</span>
<DisabledInputWrapper
- tooltip={isReadOnly ? statusMessages[campaign.status] : ""}
- disabled={isReadOnly}
- hideIcon={true}
+ tooltip={lockTooltip}
+ disabled={isLocked}
+ hideIcon
>
<input
type="text"
placeholder="Enter a name..."
className={inputClassName}
- disabled={isReadOnly}
+ disabled={isLocked}
{...register("name")}
/>
</DisabledInputWrapper>
@@ -469,13 +501,13 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
control={control}
name="from"
render={({ field }) => {
- const isDisabled = isReadOnly || !verifiedEmailDomain;
+ const isDisabled = isLocked || !verifiedEmailDomain;
return (
<DisabledInputWrapper
tooltip={
- isReadOnly ? (
- statusMessages[campaign.status]
+ isLocked ? (
+ lockTooltip
) : !verifiedEmailDomain ? (
<TooltipContent
title="You haven't configured an email domain yet. Please configure an email domain to enable campaign sending."
@@ -486,7 +518,7 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
) : undefined
}
disabled={isDisabled}
- hideIcon={true}
+ hideIcon
>
<CampaignFromField
value={field.value}
@@ -501,19 +533,15 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
/>
</label>
- <span className={labelClassName}>To</span>
+ <span className={labelClassName}>Groups</span>
<Controller
control={control}
name="groupIds"
render={({ field }) => (
<DisabledInputWrapper
- tooltip={
- isReadOnly
- ? statusMessages[campaign.status]
- : "Cannot change recipients while campaign is active. Pause the campaign to make changes."
- }
- disabled={isActive || isReadOnly}
- hideIcon={isReadOnly}
+ tooltip={lockTooltip}
+ disabled={isLocked}
+ hideIcon
>
<CampaignGroupsSelector
selectedGroupIds={field.value ?? null}
@@ -523,6 +551,24 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
)}
/>
+ <span className={labelClassName}>Tags</span>
+ <Controller
+ control={control}
+ name="partnerTagIds"
+ render={({ field }) => (
+ <DisabledInputWrapper
+ tooltip={lockTooltip}
+ disabled={isLocked}
+ hideIcon
+ >
+ <CampaignTagsSelector
+ selectedPartnerTagIds={field.value ?? null}
+ setSelectedPartnerTagIds={field.onChange}
+ />
+ </DisabledInputWrapper>
+ )}
+ />
+
{campaign.type === "marketing" && (
<>
<span className={labelClassName}>When</span>
@@ -531,11 +577,9 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
name="scheduledAt"
render={({ field }) => (
<DisabledInputWrapper
- tooltip={
- isReadOnly ? statusMessages[campaign.status] : undefined
- }
- disabled={isReadOnly}
- hideIcon={true}
+ tooltip={lockTooltip}
+ disabled={isLocked}
+ hideIcon
>
<SmartDateTimePicker
value={field.value}
@@ -551,9 +595,9 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
<span className={labelClassName}>Subject</span>
<DisabledInputWrapper
- tooltip={isReadOnly ? statusMessages[campaign.status] : ""}
- disabled={isReadOnly}
- hideIcon={true}
+ tooltip={lockTooltip}
+ disabled={isLocked}
+ hideIcon
>
<div className="relative">
<input
@@ -561,12 +605,12 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
placeholder="Enter a subject..."
className={cn(
inputClassName,
- !isReadOnly && !showPreviewText && "pr-24",
+ !isLocked && !showPreviewText && "pr-24",
)}
- disabled={isReadOnly}
+ disabled={isLocked}
{...register("subject")}
/>
- {!isReadOnly && (
+ {!isLocked && (
<div className="absolute right-0 top-1/2 -translate-y-1/2">
<button
type="button"
@@ -591,98 +635,107 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {
</span>
</ConditionalColumn>
<ConditionalColumn show={showPreviewText}>
- <input
- type="text"
- placeholder="Enter preview text..."
- className={inputClassName}
- disabled={isReadOnly}
- {...previewInputProps}
- ref={(e) => {
- previewInputProps.ref(e);
- previewInputRef.current = e;
- }}
- />
+ <DisabledInputWrapper
+ tooltip={lockTooltip}
+ disabled={isLocked}
+ hideIcon
+ >
+ <input
+ type="text"
+ placeholder="Enter preview text..."
+ className={inputClassName}
+ disabled={isLocked}
+ {...previewInputProps}
+ ref={(e) => {
+ previewInputProps.ref(e);
+ previewInputRef.current = e;
+ }}
+ />
+ </DisabledInputWrapper>
</ConditionalColumn>
{campaign.type === "transactional" && (
<>
- <span className={labelClassName}>Logic</span>
+ <span className={cn(labelClassName, "self-start pt-1")}>
+ Logic
+ </span>
<DisabledInputWrapper
- tooltip={
- isReadOnly
- ? statusMessages[campaign.status]
- : "Cannot change trigger logic while campaign is active. Pause the campaign to make changes."
- }
- disabled={isActive || isReadOnly}
+ tooltip={lockTooltip}
+ disabled={isLocked}
+ hideIcon
>
- <TransactionalCampaignLogic />
+ <TransactionalCampaignLogic locked={isLocked} />
</DisabledInputWrapper>
</>
)}
</div>
- {!isReadOnly && <DuplicateLogicWarning />}
+ {!isLocked && <DuplicateLogicWarning />}
<div className="mt-4">
<Controller
control={control}
name="bodyJson"
render={({ field }) => (
- <RichTextProvider
- ref={editorRef}
- editorClassName="-m-2 min-h-[200px] p-2"
- style="relaxed"
- features={[...DEFAULT_RICH_TEXT_FEATURES, "imageControls"]}
- initialValue={field.value}
- onChange={(editor) => field.onChange(editor.getJSON())}
- variables={[...EMAIL_TEMPLATE_VARIABLES]}
- editable={
- campaign.type === "marketing" ? !isReadOnly : !isActive
- }
- uploadImage={async (file) => {
- try {
- const result = await executeImageUpload({
- workspaceId: workspaceId!,
- });
-
- if (!result?.data) {
- throw new Error("Failed to get signed upload URL");
- }
-
- const { signedUrl, destinationUrl } = result.data;
-
- const uploadResponse = await fetch(signedUrl, {
- method: "PUT",
- body: file,
- headers: {
- "Content-Type": file.type,
- "Content-Length": file.size.toString(),
- },
- });
-
- if (!uploadResponse.ok) {
- throw new Error("Failed to upload to signed URL");
+ <DisabledInputWrapper
+ tooltip={lockTooltip}
+ disabled={isLocked}
+ hideIcon
+ >
+ <RichTextProvider
+ ref={editorRef}
+ editorClassName="-m-2 min-h-[200px] p-2"
+ style="relaxed"
+ features={[...DEFAULT_RICH_TEXT_FEATURES, "imageControls"]}
+ initialValue={field.value}
+ onChange={(editor) => field.onChange(editor.getJSON())}
+ variables={[...EMAIL_TEMPLATE_VARIABLES]}
+ editable={!isLocked}
+ uploadImage={async (file) => {
+ try {
+ const result = await executeImageUpload({
+ workspaceId: workspaceId!,
+ });
+
+ if (!result?.data) {
+ throw new Error("Failed to get signed upload URL");
+ }
+
+ const { signedUrl, destinationUrl } = result.data;
+
+ const uploadResponse = await fetch(signedUrl, {
+ method: "PUT",
+ body: file,
+ headers: {
+ "Content-Type": file.type,
+ "Content-Length": file.size.toString(),
+ },
+ });
+
+ if (!uploadResponse.ok) {
+ throw new Error("Failed to upload to signed URL");
+ }
+
+ return destinationUrl;
+ } catch (e) {
+ console.error("Failed to upload image", e);
+ toast.error("Failed to upload image");
}
- return destinationUrl;
- } catch (e) {
- console.error("Failed to upload image", e);
- toast.error("Failed to upload image");
- }
-
- return null;
- }}
- >
- <div className="relative z-0 flex flex-col gap-1">
- <div className="sticky -top-4 z-10 sm:-top-6">
- <div className="bg-white pb-1 pt-2">
- <RichTextToolbar />
+ return null;
+ }}
+ >
+ <div className="relative z-0 flex flex-col gap-1">
+ <div className="sticky -top-4 z-10 sm:-top-6">
+ <div className="bg-white pb-1 pt-2">
+ <RichTextToolbar />
+ </div>
+ <div className="h-2 bg-gradient-to-b from-white" />
</div>
- <div className="h-2 bg-gradient-to-b from-white" />
+ <RichTextArea />
</div>
- <RichTextArea />
- </div>
- </RichTextProvider>
+ </RichTextProvider>
+ </DisabledInputWrapper>
)}
/>
</div>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-groups-selector.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-groups-selector.tsx
deleted file mode 100644
index f2df7ab50d..0000000000
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-groups-selector.tsx
+++ /dev/null
@@ -1,125 +0,0 @@
-"use client";
-
-import useGroups from "@/lib/swr/use-groups";
-import { GroupColorCircle } from "@/ui/partners/groups/group-color-circle";
-import { GroupsMultiSelect } from "@/ui/partners/groups/groups-multi-select";
-import { Popover, Users6 } from "@dub/ui";
-import { cn } from "@dub/utils";
-import { useMemo, useState } from "react";
-
-const MAX_DISPLAYED_GROUPS = 1;
-
-interface CampaignGroupsSelectorProps {
- selectedGroupIds: string[] | null;
- setSelectedGroupIds: (groupIds: string[] | null) => void;
-}
-
-export function CampaignGroupsSelector({
- selectedGroupIds,
- setSelectedGroupIds,
-}: CampaignGroupsSelectorProps) {
- const { groups, loading } = useGroups();
- const [openPopover, setOpenPopover] = useState(false);
-
- const selectedGroups = useMemo(() => {
- if (!selectedGroupIds?.length || !groups) {
- return null;
- }
-
- return groups.filter((group) => selectedGroupIds.includes(group.id));
- }, [groups, selectedGroupIds]);
-
- const displayAllGroups = !selectedGroupIds || selectedGroupIds.length === 0;
-
- const plusCount = selectedGroups
- ? Math.max(0, selectedGroups.length - MAX_DISPLAYED_GROUPS)
- : 0;
-
- return (
- <Popover
- content={
- <div className="w-full p-3 sm:w-[440px]">
- <GroupsMultiSelect
- selectedGroupIds={selectedGroupIds}
- setSelectedGroupIds={setSelectedGroupIds}
- />
- </div>
- }
- align="start"
- openPopover={openPopover}
- setOpenPopover={setOpenPopover}
- >
- <div
- className={cn(
- "group relative flex h-8 w-full cursor-pointer items-center gap-2 rounded-lg p-1.5 text-sm transition-colors duration-150 hover:bg-neutral-100",
- openPopover && "bg-neutral-100",
- )}
- onClick={() => setOpenPopover(true)}
- >
- {loading && selectedGroupIds?.length ? (
- <div className="h-5 w-1/3 animate-pulse rounded bg-neutral-200" />
- ) : displayAllGroups ? (
- <div
- className={cn(
- "flex h-5 items-center gap-1 rounded-md px-1.5 transition-colors",
- openPopover
- ? "bg-neutral-200"
- : "bg-neutral-100 group-hover:bg-neutral-200",
- )}
- >
- <Users6 className="size-3.5 shrink-0" />
- <span className="text-content-default text-sm font-medium">
- All groups
- </span>
- </div>
- ) : selectedGroups && selectedGroups.length > 0 ? (
- <div className="flex min-w-0 flex-1 items-center gap-2">
- {selectedGroups.slice(0, MAX_DISPLAYED_GROUPS).map((group) => (
- <div
- key={group.id}
- className={cn(
- "flex h-5 min-w-0 items-center gap-1 rounded-md px-1.5 transition-colors",
- openPopover
- ? "bg-neutral-200"
- : "bg-neutral-100 group-hover:bg-neutral-200",
- )}
- >
- <GroupColorCircle group={group} />
- <span className="text-content-default min-w-0 truncate text-sm font-medium">
- {group.name}
- </span>
- </div>
- ))}
-
- {plusCount > 0 && (
- <span
- className={cn(
- "flex items-center rounded-md px-2 py-0.5 text-xs font-medium text-neutral-600 transition-colors",
- openPopover
- ? "bg-neutral-200"
- : "bg-neutral-100 group-hover:bg-neutral-200",
- )}
- >
- +{plusCount}
- </span>
- )}
- </div>
- ) : null}
-
- <button
- type="button"
- className={cn(
- "ml-auto h-5 shrink-0 rounded-md bg-neutral-200 px-2 text-xs font-semibold text-neutral-700 transition-opacity",
- openPopover ? "opacity-100" : "opacity-0 group-hover:opacity-100",
- )}
- onClick={(e) => {
- e.stopPropagation();
- setOpenPopover(true);
- }}
- >
- Edit
- </button>
- </div>
- </Popover>
- );
-}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-recipients-selector.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-recipients-selector.tsx
new file mode 100644
index 0000000000..b16f204bfc
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-recipients-selector.tsx
@@ -0,0 +1,214 @@
+"use client";
+
+import useGroups from "@/lib/swr/use-groups";
+import { usePartnerTags } from "@/lib/swr/use-partner-tags";
+import { GroupColorCircle } from "@/ui/partners/groups/group-color-circle";
+import { GroupsMultiSelect } from "@/ui/partners/groups/groups-multi-select";
+import { TagsMultiSelect } from "@/ui/partners/tags-multi-select";
+import { Popover, Tag as TagIcon } from "@dub/ui";
+import { Users6 } from "@dub/ui/icons";
+import { cn } from "@dub/utils";
+import { ReactNode, useState } from "react";
+
+const MAX_DISPLAYED = 1;
+
+export function CampaignGroupsSelector({
+ selectedGroupIds,
+ setSelectedGroupIds,
+}: {
+ selectedGroupIds: string[] | null;
+ setSelectedGroupIds: (groupIds: string[] | null) => void;
+}) {
+ const hasGroupFilter = Boolean(selectedGroupIds?.length);
+ const { groups: selectedGroups, loading: groupsLoading } = useGroups({
+ query: { groupIds: selectedGroupIds ?? undefined },
+ enabled: hasGroupFilter,
+ });
+ const [openPopover, setOpenPopover] = useState(false);
+
+ const isLoading = groupsLoading && hasGroupFilter;
+ const plusCount = Math.max(0, (selectedGroups?.length ?? 0) - MAX_DISPLAYED);
+
+ return (
+ <CampaignRecipientPopover
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ content={
+ <GroupsMultiSelect
+ selectedGroupIds={selectedGroupIds}
+ setSelectedGroupIds={setSelectedGroupIds}
+ />
+ }
+ >
+ {isLoading ? (
+ <div className="h-5 w-1/3 animate-pulse rounded bg-neutral-200" />
+ ) : !hasGroupFilter ? (
+ <RecipientChip openPopover={openPopover}>
+ <Users6 className="size-3.5 shrink-0" />
+ <span className="text-content-default text-sm font-medium">
+ All groups
+ </span>
+ </RecipientChip>
+ ) : (
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ {selectedGroups?.slice(0, MAX_DISPLAYED).map((group) => (
+ <RecipientChip key={group.id} openPopover={openPopover}>
+ <GroupColorCircle group={group} />
+ <span className="text-content-default min-w-0 truncate text-sm font-medium">
+ {group.name}
+ </span>
+ </RecipientChip>
+ ))}
+
+ {plusCount > 0 && (
+ <PlusCountBadge count={plusCount} openPopover={openPopover} />
+ )}
+ </div>
+ )}
+ </CampaignRecipientPopover>
+ );
+}
+
+export function CampaignTagsSelector({
+ selectedPartnerTagIds,
+ setSelectedPartnerTagIds,
+}: {
+ selectedPartnerTagIds: string[] | null;
+ setSelectedPartnerTagIds: (tagIds: string[] | null) => void;
+}) {
+ const hasTagFilter = Boolean(selectedPartnerTagIds?.length);
+ const { partnerTags: selectedTags, isLoading: tagsLoading } = usePartnerTags({
+ query: { ids: selectedPartnerTagIds ?? undefined },
+ enabled: hasTagFilter,
+ });
+ const [openPopover, setOpenPopover] = useState(false);
+
+ const isLoading = tagsLoading && hasTagFilter;
+ const plusCount = Math.max(0, (selectedTags?.length ?? 0) - MAX_DISPLAYED);
+
+ return (
+ <CampaignRecipientPopover
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ content={
+ <TagsMultiSelect
+ selectedPartnerTagIds={selectedPartnerTagIds}
+ setSelectedPartnerTagIds={setSelectedPartnerTagIds}
+ />
+ }
+ >
+ {isLoading ? (
+ <div className="h-5 w-1/3 animate-pulse rounded bg-neutral-200" />
+ ) : !hasTagFilter ? (
+ <RecipientChip openPopover={openPopover}>
+ <TagIcon className="size-3.5 shrink-0" />
+ <span className="text-content-default text-sm font-medium">
+ All tags
+ </span>
+ </RecipientChip>
+ ) : (
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ {selectedTags?.slice(0, MAX_DISPLAYED).map((tag) => (
+ <RecipientChip key={tag.id} openPopover={openPopover}>
+ <TagIcon className="size-3.5 shrink-0" />
+ <span className="text-content-default min-w-0 truncate text-sm font-medium">
+ {tag.name}
+ </span>
+ </RecipientChip>
+ ))}
+
+ {plusCount > 0 && (
+ <PlusCountBadge count={plusCount} openPopover={openPopover} />
+ )}
+ </div>
+ )}
+ </CampaignRecipientPopover>
+ );
+}
+
+function CampaignRecipientPopover({
+ openPopover,
+ setOpenPopover,
+ content,
+ children,
+}: {
+ openPopover: boolean;
+ setOpenPopover: (open: boolean) => void;
+ content: ReactNode;
+ children: ReactNode;
+}) {
+ return (
+ <Popover
+ content={<div className="w-full p-3 sm:w-[440px]">{content}</div>}
+ align="start"
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ >
+ <div
+ className={cn(
+ "group relative flex h-8 w-full cursor-pointer items-center gap-2 rounded-lg p-1.5 text-sm transition-colors duration-150 hover:bg-neutral-100",
+ openPopover && "bg-neutral-100",
+ )}
+ onClick={() => setOpenPopover(true)}
+ >
+ {children}
+
+ <button
+ type="button"
+ className={cn(
+ "ml-auto h-5 shrink-0 rounded-md bg-neutral-200 px-2 text-xs font-semibold text-neutral-700 transition-opacity",
+ openPopover ? "opacity-100" : "opacity-0 group-hover:opacity-100",
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ setOpenPopover(true);
+ }}
+ >
+ Edit
+ </button>
+ </div>
+ </Popover>
+ );
+}
+
+function RecipientChip({
+ openPopover,
+ children,
+}: {
+ openPopover: boolean;
+ children: ReactNode;
+}) {
+ return (
+ <div
+ className={cn(
+ "flex h-5 min-w-0 items-center gap-1 rounded-md px-1.5 transition-colors",
+ openPopover
+ ? "bg-neutral-200"
+ : "bg-neutral-100 group-hover:bg-neutral-200",
+ )}
+ >
+ {children}
+ </div>
+ );
+}
+
+function PlusCountBadge({
+ count,
+ openPopover,
+}: {
+ count: number;
+ openPopover: boolean;
+}) {
+ return (
+ <span
+ className={cn(
+ "flex items-center rounded-md px-2 py-0.5 text-xs font-medium text-neutral-600 transition-colors",
+ openPopover
+ ? "bg-neutral-200"
+ : "bg-neutral-100 group-hover:bg-neutral-200",
+ )}
+ >
+ +{count}
+ </span>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/duplicate-logic-warning.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/duplicate-logic-warning.tsx
index c79f402973..d80bacfae3 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/duplicate-logic-warning.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/duplicate-logic-warning.tsx
@@ -1,4 +1,4 @@
-import { sendCampaignConditionSchema } from "@/lib/api/workflows/send-campaign/schema";
+import { sendCampaignConditionsSchema } from "@/lib/api/workflows/send-campaign/schema";
import useWorkspace from "@/lib/swr/use-workspace";
import { CampaignList } from "@/lib/types";
import { ChevronUp, Copy, LoadingSpinner } from "@dub/ui";
@@ -18,19 +18,19 @@ export function DuplicateLogicWarning() {
const { control } = useCampaignFormContext();
- const triggerCondition = useWatch({ control, name: "triggerCondition" });
+ const triggerConditions = useWatch({ control, name: "triggerConditions" });
- const parsedTriggerCondition = triggerCondition
- ? sendCampaignConditionSchema.safeParse(triggerCondition)
+ const parsedTriggerConditions = triggerConditions?.length
+ ? sendCampaignConditionsSchema.safeParse(triggerConditions)
: undefined;
const { data: campaigns, isLoading } = useSWR<CampaignList[]>(
workspaceId &&
- parsedTriggerCondition?.success &&
+ parsedTriggerConditions?.success &&
`/api/campaigns?${new URLSearchParams({
workspaceId,
type: "transactional",
- triggerCondition: JSON.stringify(parsedTriggerCondition.data),
+ triggerConditions: JSON.stringify(parsedTriggerConditions.data),
})}`,
fetcher,
{
@@ -60,7 +60,7 @@ export function DuplicateLogicWarning() {
hasDuplicates &&
cn(
"grid-rows-[1fr] opacity-100",
- (isLoading || !parsedTriggerCondition?.success) &&
+ (isLoading || !parsedTriggerConditions?.success) &&
"pointer-events-none opacity-50",
),
)}
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.tsx
index 629a1d1bb1..93b48192dd 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,7 +1,14 @@
+"use client";
+
import {
- SEND_CAMPAIGN_ATTRIBUTE_KEYS,
SEND_CAMPAIGN_ATTRIBUTES,
+ SEND_CAMPAIGN_ATTRIBUTE_KEYS,
+ SEND_CAMPAIGN_ENROLLMENT_ATTRIBUTE_KEYS,
+ SEND_CAMPAIGN_OPERATORS,
+ SEND_CAMPAIGN_OPERATOR_KEYS,
+ type SendCampaignAttributeKey,
} from "@/lib/api/workflows/send-campaign/schema";
+import { satisfiesExclusiveAttributeRules } from "@/lib/api/workflows/utils";
import { handleMoneyInputChange, handleMoneyKeyDown } from "@/lib/form-utils";
import { DurationPopoverContent } from "@/ui/shared/duration-popover-content";
import {
@@ -9,88 +16,250 @@ import {
InlineBadgePopoverContext,
InlineBadgePopoverMenu,
} from "@/ui/shared/inline-badge-popover";
+import { Button } from "@dub/ui";
+import { Xmark } from "@dub/ui/icons";
import { cn, currencyFormatter, pluralize } from "@dub/utils";
-import { useContext, useEffect, useRef } from "react";
-import { Controller } from "react-hook-form";
+import { useContext, useEffect, useMemo, useRef } from "react";
+import { Controller, useFieldArray } from "react-hook-form";
import { useCampaignFormContext } from "./campaign-form-context";
-export function TransactionalCampaignLogic() {
+type SendCampaignOperatorKey = (typeof SEND_CAMPAIGN_OPERATOR_KEYS)[number];
+
+function isSendCampaignEnrollmentAttribute(
+ attribute: string,
+): attribute is (typeof SEND_CAMPAIGN_ENROLLMENT_ATTRIBUTE_KEYS)[number] {
+ return (
+ SEND_CAMPAIGN_ENROLLMENT_ATTRIBUTE_KEYS as readonly string[]
+ ).includes(attribute);
+}
+
+export function TransactionalCampaignLogic({ locked }: { locked: boolean }) {
+ const { control, watch } = useCampaignFormContext();
+
+ const { fields, append, remove, update } = useFieldArray({
+ control,
+ name: "triggerConditions",
+ });
+
+ const triggerConditions = watch("triggerConditions") ?? [];
+
+ const usedAttributes = useMemo(
+ () =>
+ triggerConditions
+ .map((condition) => condition?.attribute)
+ .filter((attribute): attribute is SendCampaignAttributeKey =>
+ Boolean(attribute),
+ ),
+ [triggerConditions],
+ );
+
+ const availableAttributesToAdd = useMemo(() => {
+ return SEND_CAMPAIGN_ATTRIBUTE_KEYS.filter((attribute) =>
+ satisfiesExclusiveAttributeRules({
+ attribute,
+ usedAttributes,
+ attributes: SEND_CAMPAIGN_ATTRIBUTES,
+ }),
+ );
+ }, [usedAttributes]);
+
+ return (
+ <div className="flex w-full flex-col gap-1.5 px-2 py-1">
+ {fields.map((field, index) => {
+ const condition = triggerConditions[index];
+ const availableAttributes = SEND_CAMPAIGN_ATTRIBUTE_KEYS.filter(
+ (attribute) =>
+ satisfiesExclusiveAttributeRules({
+ attribute,
+ usedAttributes,
+ currentAttribute: condition?.attribute,
+ attributes: SEND_CAMPAIGN_ATTRIBUTES,
+ }),
+ );
+
+ return (
+ <ConditionRow
+ key={field.id}
+ index={index}
+ availableAttributes={availableAttributes}
+ canRemove={!locked && fields.length > 1}
+ onRemove={() => remove(index)}
+ onUpdate={(updates) => {
+ update(index, {
+ ...condition,
+ ...updates,
+ });
+ }}
+ />
+ );
+ })}
+
+ {!locked && availableAttributesToAdd.length > 0 && (
+ <Button
+ type="button"
+ text="Add condition"
+ variant="secondary"
+ className="mt-1.5 h-8 w-fit rounded-lg px-3"
+ onClick={() => {
+ const nextAttribute = availableAttributesToAdd[0];
+ append({
+ attribute: nextAttribute,
+ operator: "gte",
+ value:
+ nextAttribute === "partnerJoined"
+ ? 0
+ : (null as unknown as number),
+ });
+ }}
+ />
+ )}
+ </div>
+ );
+}
+
+function ConditionRow({
+ index,
+ availableAttributes,
+ canRemove,
+ onRemove,
+ onUpdate,
+}: {
+ index: number;
+ availableAttributes: readonly SendCampaignAttributeKey[];
+ canRemove: boolean;
+ onRemove: () => void;
+ onUpdate: (updates: {
+ attribute?: SendCampaignAttributeKey;
+ operator?: SendCampaignOperatorKey;
+ value?: number;
+ }) => void;
+}) {
const { control, watch, setValue } = useCampaignFormContext();
- const attribute = watch("triggerCondition.attribute");
- const value = watch("triggerCondition.value");
+ const attribute = watch(`triggerConditions.${index}.attribute`);
+ const value = watch(`triggerConditions.${index}.value`);
const prevAttributeRef = useRef(attribute);
const config = attribute ? SEND_CAMPAIGN_ATTRIBUTES[attribute] : null;
+ const isEnrollment = attribute
+ ? isSendCampaignEnrollmentAttribute(attribute)
+ : false;
+ const allowedOperators = config?.operators ?? (["gte"] as const);
// Reset value when attribute changes
useEffect(() => {
if (prevAttributeRef.current && prevAttributeRef.current !== attribute) {
- // Set value to 0 for partnerJoined, null for others
setValue(
- "triggerCondition.value",
+ `triggerConditions.${index}.value`,
attribute === "partnerJoined" ? 0 : (null as any),
);
+ setValue(`triggerConditions.${index}.operator`, "gte");
}
prevAttributeRef.current = attribute;
- }, [attribute, setValue]);
+ }, [attribute, index, setValue]);
// Ensure partnerJoined always has value 0
useEffect(() => {
if (attribute === "partnerJoined" && value !== 0) {
- setValue("triggerCondition.value", 0);
+ setValue(`triggerConditions.${index}.value`, 0);
}
- }, [attribute, value, setValue]);
+ }, [attribute, value, index, 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{config?.inputType !== "none" && "'s"}
- <div className="inline-flex items-center gap-1">
- <Controller
- control={control}
- name="triggerCondition.attribute"
- render={({ field }) => (
- <InlineBadgePopover
- text={
- field.value
- ? SEND_CAMPAIGN_ATTRIBUTES[field.value].label
- : "activity"
- }
- invalid={!field.value}
- >
- <InlineBadgePopoverMenu
- selectedValue={field.value}
- onSelect={field.onChange}
- items={SEND_CAMPAIGN_ATTRIBUTE_KEYS.map((attr) => ({
- text: SEND_CAMPAIGN_ATTRIBUTES[attr].label,
- value: attr,
- }))}
- />
- </InlineBadgePopover>
- )}
- />
-
- {config && config.inputType !== "none" && (
- <>
- reaches at least{" "}
- {config.inputType === "dropdown" ? (
- <DropdownValueInput config={config} />
- ) : (
- <ValueInput config={config} value={value} />
- )}
- </>
+ <div className="flex items-start gap-1">
+ <span className="text-content-default flex min-w-0 flex-1 flex-wrap items-center gap-1 text-sm font-medium leading-relaxed">
+ {index === 0 ? "When partner" : "And when partner"}
+ {config?.inputType !== "none" && "'s"}
+ <Controller
+ control={control}
+ name={`triggerConditions.${index}.attribute`}
+ render={({ field }) => (
+ <InlineBadgePopover
+ text={SEND_CAMPAIGN_ATTRIBUTES[field.value]?.label ?? "activity"}
+ invalid={!field.value}
+ >
+ <InlineBadgePopoverMenu
+ selectedValue={field.value}
+ onSelect={(nextAttribute) => {
+ field.onChange(nextAttribute);
+ onUpdate({
+ attribute: nextAttribute as SendCampaignAttributeKey,
+ operator: "gte",
+ value:
+ nextAttribute === "partnerJoined"
+ ? 0
+ : (null as unknown as number),
+ });
+ }}
+ items={availableAttributes.map((attr) => ({
+ text: SEND_CAMPAIGN_ATTRIBUTES[attr].label,
+ value: attr,
+ }))}
+ />
+ </InlineBadgePopover>
)}
- </div>
+ />
+
+ {config && config.inputType !== "none" && (
+ <>
+ {isEnrollment ? (
+ <>reaches at least</>
+ ) : (
+ <Controller
+ control={control}
+ name={`triggerConditions.${index}.operator`}
+ render={({ field }) => (
+ <InlineBadgePopover
+ text={
+ field.value
+ ? SEND_CAMPAIGN_OPERATORS[
+ field.value as SendCampaignOperatorKey
+ ]?.label
+ : "at least"
+ }
+ invalid={!field.value}
+ >
+ <InlineBadgePopoverMenu
+ selectedValue={field.value}
+ onSelect={field.onChange}
+ items={allowedOperators.map((op) => ({
+ text: SEND_CAMPAIGN_OPERATORS[op].label,
+ value: op,
+ }))}
+ />
+ </InlineBadgePopover>
+ )}
+ />
+ )}{" "}
+ {config.inputType === "dropdown" ? (
+ <DropdownValueInput index={index} config={config} />
+ ) : (
+ <ValueInput index={index} config={config} value={value} />
+ )}
+ </>
+ )}
</span>
+
+ {canRemove && (
+ <Button
+ type="button"
+ variant="secondary"
+ onClick={onRemove}
+ icon={<Xmark className="size-3.5" />}
+ className="h-6 w-[26px] shrink-0 px-1.5"
+ aria-label="Remove condition"
+ />
+ )}
</div>
);
}
function DropdownValueInput({
+ index,
config,
}: {
+ index: number;
config: { dropdownValues?: readonly number[] };
}) {
const { control } = useCampaignFormContext();
@@ -98,7 +267,7 @@ function DropdownValueInput({
return (
<Controller
control={control}
- name="triggerCondition.value"
+ name={`triggerConditions.${index}.value`}
render={({ field }) => (
<>
<InlineBadgePopover
@@ -128,26 +297,30 @@ function DropdownValueInput({
}
function ValueInput({
+ index,
config,
value,
}: {
+ index: number;
config: { inputType?: string };
value: number | null | undefined;
}) {
const { watch, setValue } = useCampaignFormContext();
const { setIsOpen } = useContext(InlineBadgePopoverContext);
- const storedValue = watch("triggerCondition.value");
+ const storedValue = watch(`triggerConditions.${index}.value`);
const isCurrency = config.inputType === "currency";
const displayValue =
isCurrency && storedValue ? storedValue / 100 : storedValue;
+ const hasValue = value !== null && value !== undefined;
+
return (
<InlineBadgePopover
text={
- value
+ hasValue
? isCurrency
? currencyFormatter(value, {
trailingZeroDisplay: "stripIfInteger",
@@ -155,7 +328,7 @@ function ValueInput({
: value
: "amount"
}
- invalid={!value}
+ invalid={!hasValue}
>
<div className="relative rounded-md shadow-sm">
{isCurrency && (
@@ -170,13 +343,13 @@ function ValueInput({
)}
value={displayValue ?? ""}
onChange={(e) => {
- const value = e.target.value;
- if (value === "") {
- setValue("triggerCondition.value", null as any);
+ const nextValue = e.target.value;
+ if (nextValue === "") {
+ setValue(`triggerConditions.${index}.value`, null as any);
} else {
- const numValue = +value;
+ const numValue = +nextValue;
setValue(
- "triggerCondition.value",
+ `triggerConditions.${index}.value`,
isCurrency ? Math.round(numValue * 100) : numValue,
);
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/use-campaign-confirmation-modals.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/use-campaign-confirmation-modals.tsx
index 649f8168e5..d49444ce60 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/use-campaign-confirmation-modals.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/use-campaign-confirmation-modals.tsx
@@ -72,7 +72,8 @@ export function useCampaignConfirmationModals({
});
const { totalPartners } = usePartnersCountByGroupIds({
- groupIds: campaign.type === "marketing" ? watch("groupIds") : undefined,
+ groupIds: watch("groupIds"),
+ partnerTagIds: watch("partnerTagIds"),
});
const {
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.ts
deleted file mode 100644
index 355dc4cb99..0000000000
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/utils.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { SEND_CAMPAIGN_ATTRIBUTES } from "@/lib/api/workflows/send-campaign/schema";
-import type { WorkflowCondition } from "@/lib/api/workflows/types";
-
-export function isValidTriggerCondition(
- triggerCondition: WorkflowCondition | null | undefined,
-): boolean {
- // Null/undefined is valid (no trigger condition set)
- if (!triggerCondition) {
- return true;
- }
-
- // Must have an attribute
- if (!triggerCondition.attribute) {
- return false;
- }
-
- const config = SEND_CAMPAIGN_ATTRIBUTES[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/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/delete-campaign-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/delete-campaign-modal.tsx
index 767c8a3ab7..1b7484abfe 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/delete-campaign-modal.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/delete-campaign-modal.tsx
@@ -42,10 +42,10 @@ const DeleteCampaignModal = ({
await deleteCampaign(`/api/campaigns/${campaign.id}`, {
method: "DELETE",
onSuccess: async () => {
- setShowModal(false);
+ router.push(`/${slug}/program/campaigns`);
await mutatePrefix("/api/campaigns");
+ setShowModal(false);
toast.success("Campaign deleted successfully!");
- router.push(`/${slug}/program/campaigns`);
},
});
};
diff --git a/apps/web/lib/actions/partners/accept-program-invite.ts b/apps/web/lib/actions/partners/accept-program-invite.ts
index 447806269d..48d54bf073 100644
--- a/apps/web/lib/actions/partners/accept-program-invite.ts
+++ b/apps/web/lib/actions/partners/accept-program-invite.ts
@@ -88,7 +88,7 @@ export const acceptProgramInviteAction = authPartnerActionClient
}),
// 4. Execute Dub workflows using the “partnerEnrolled” trigger.
executeWorkflows({
- trigger: "partnerEnrolled",
+ event: "partnerEnrolled",
identity: {
workspaceId: workspace.id,
programId,
diff --git a/apps/web/lib/actions/partners/tags/update-program-partner-tags.ts b/apps/web/lib/actions/partners/tags/update-program-partner-tags.ts
index 4d9f1287b8..20f95e2dbe 100644
--- a/apps/web/lib/actions/partners/tags/update-program-partner-tags.ts
+++ b/apps/web/lib/actions/partners/tags/update-program-partner-tags.ts
@@ -3,6 +3,7 @@
import { includeProgramEnrollment } from "@/lib/api/links/include-program-enrollment";
import { includeTags } from "@/lib/api/links/include-tags";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { triggerDraftBountySubmissionCreation } from "@/lib/bounty/api/trigger-draft-bounty-submissions";
import { prisma } from "@/lib/prisma";
import { recordLink } from "@/lib/tinybird";
import { updatePartnerTagsSchema } from "@/lib/zod/schemas/partner-tags";
@@ -94,9 +95,16 @@ export const updateProgramPartnerTagsAction = authActionClient
]);
});
- // Sync updated partner tags to Tinybird for analytics (top_partner_tags)
waitUntil(
(async () => {
+ if (addTagIds.length > 0) {
+ await triggerDraftBountySubmissionCreation({
+ programId,
+ partnerIds,
+ });
+ }
+
+ // Sync updated partner tags to Tinybird for analytics (top_partner_tags)
let cursor: string | undefined;
while (true) {
diff --git a/apps/web/lib/actions/partners/upload-bounty-submission-file.ts b/apps/web/lib/actions/partners/upload-bounty-submission-file.ts
index 05b1b83621..897a803f53 100644
--- a/apps/web/lib/actions/partners/upload-bounty-submission-file.ts
+++ b/apps/web/lib/actions/partners/upload-bounty-submission-file.ts
@@ -23,7 +23,13 @@ export const uploadBountySubmissionFileAction = authPartnerActionClient
const programEnrollment = await getProgramEnrollmentOrThrow({
partnerId: partner.id,
programId,
- include: {},
+ include: {
+ programPartnerTags: {
+ select: {
+ partnerTagId: true,
+ },
+ },
+ },
});
const { signedUrl, destinationUrl } = await getBountySubmissionUploadUrl({
diff --git a/apps/web/lib/api/campaigns/get-campaign-or-throw.ts b/apps/web/lib/api/campaigns/get-campaign-or-throw.ts
index 95ca6d61df..b3eed662a3 100644
--- a/apps/web/lib/api/campaigns/get-campaign-or-throw.ts
+++ b/apps/web/lib/api/campaigns/get-campaign-or-throw.ts
@@ -1,40 +1,33 @@
import { prisma } from "@/lib/prisma";
+import { Prisma } from "@prisma/client";
import { DubApiError } from "../errors";
-export const getCampaignOrThrow = async ({
- campaignId,
+export async function getCampaignOrThrow<
+ T extends Prisma.CampaignInclude = {},
+>({
programId,
- includeWorkflow = false,
- includeGroups = false,
+ campaignId,
+ include,
}: {
- campaignId: string;
programId: string;
- includeWorkflow?: boolean;
- includeGroups?: boolean;
-}) => {
+ campaignId: string;
+ include?: T;
+}): Promise<Prisma.CampaignGetPayload<{ include: T }>> {
const campaign = await prisma.campaign.findUnique({
where: {
id: campaignId,
},
- include: {
- workflow: includeWorkflow,
- groups: includeGroups,
- },
+ include,
});
- if (!campaign) {
+ if (!campaign || campaign.programId !== programId) {
throw new DubApiError({
code: "not_found",
message: "Campaign not found.",
});
}
- if (campaign.programId !== programId) {
- throw new DubApiError({
- code: "forbidden",
- message: "You are not authorized to access this campaign.",
- });
- }
-
- return campaign;
-};
+ return campaign as Prisma.CampaignGetPayload<{
+ include: T;
+ }>;
+}
diff --git a/apps/web/lib/api/campaigns/schedule-campaigns.ts b/apps/web/lib/api/campaigns/schedule-campaigns.ts
index 0d990fa3c3..0d25cea733 100644
--- a/apps/web/lib/api/campaigns/schedule-campaigns.ts
+++ b/apps/web/lib/api/campaigns/schedule-campaigns.ts
@@ -1,18 +1,74 @@
import { qstash } from "@/lib/cron";
import { prisma } from "@/lib/prisma";
-import { WORKFLOW_SCHEDULES } from "@/lib/zod/schemas/workflows";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
-import { Campaign, Workflow } from "@prisma/client";
+import { PARTNER_ENROLLED_WORKFLOW_CRON } from "@/lib/zod/schemas/workflows";
+import { APP_DOMAIN_WITH_NGROK, log } from "@dub/utils";
+import { Campaign, CampaignType, Workflow } from "@prisma/client";
import { isScheduledWorkflow } from "../workflows/utils";
+type ScheduleCampaignProps = {
+ campaign: Campaign;
+ updatedCampaign: Campaign & {
+ workflow: Workflow | null;
+ };
+};
+
+export const scheduleCampaign = async ({
+ campaign,
+ updatedCampaign,
+}: ScheduleCampaignProps) => {
+ if (campaign.type == CampaignType.marketing) {
+ return scheduleMarketingCampaign({
+ campaign,
+ updatedCampaign,
+ });
+ }
+
+ if (campaign.type == CampaignType.transactional) {
+ return scheduleTransactionalCampaign({
+ campaign,
+ updatedCampaign,
+ });
+ }
+};
+
+export const deleteCampaignSchedule = async (
+ campaign: Pick<Campaign, "type" | "qstashMessageId"> & {
+ workflow: Pick<Workflow, "id" | "triggerConditions" | "actions"> | null;
+ },
+) => {
+ if (campaign.type == CampaignType.marketing && campaign.qstashMessageId) {
+ try {
+ await qstash.messages.cancel(campaign.qstashMessageId);
+ } catch (error) {
+ console.warn(
+ `Failed to delete QStash message ${campaign.qstashMessageId}:`,
+ error,
+ );
+ }
+ return;
+ }
+
+ if (
+ campaign.type == CampaignType.transactional &&
+ campaign.workflow &&
+ isScheduledWorkflow(campaign.workflow)
+ ) {
+ try {
+ await qstash.schedules.delete(campaign.workflow.id);
+ } catch (error) {
+ console.warn(
+ `Failed to delete QStash schedule ${campaign.workflow.id}:`,
+ error,
+ );
+ }
+ }
+};
+
// Schedule a marketing campaign
-export const scheduleMarketingCampaign = async ({
+const scheduleMarketingCampaign = async ({
campaign,
updatedCampaign,
-}: {
- campaign: Campaign;
- updatedCampaign: Campaign;
-}) => {
+}: ScheduleCampaignProps) => {
if (updatedCampaign.status === "draft") {
return;
}
@@ -82,17 +138,11 @@ export const scheduleMarketingCampaign = async ({
export const scheduleTransactionalCampaign = async ({
campaign,
updatedCampaign,
-}: {
- campaign: Campaign;
- updatedCampaign: Campaign & {
- workflow: Workflow | null;
- };
-}) => {
- if (!updatedCampaign.workflow) {
- return;
- }
-
- if (!isScheduledWorkflow(updatedCampaign.workflow)) {
+}: ScheduleCampaignProps) => {
+ if (
+ !updatedCampaign.workflow ||
+ !isScheduledWorkflow(updatedCampaign.workflow)
+ ) {
return;
}
@@ -100,26 +150,39 @@ export const scheduleTransactionalCampaign = async ({
(campaign.status === "draft" || campaign.status === "paused") &&
updatedCampaign.status === "active";
- const cronSchedule = WORKFLOW_SCHEDULES[updatedCampaign.workflow.trigger];
-
- if (!cronSchedule) {
- throw new Error(
- `Cron schedule not found for trigger ${updatedCampaign.workflow.trigger}`,
- );
- }
-
if (shouldSchedule) {
- return await qstash.schedules.create({
- destination: `${APP_DOMAIN_WITH_NGROK}/api/cron/workflows/${updatedCampaign.workflow.id}`,
- cron: cronSchedule,
- scheduleId: updatedCampaign.workflow.id,
- });
+ try {
+ return await qstash.schedules.create({
+ destination: `${APP_DOMAIN_WITH_NGROK}/api/cron/workflows/${updatedCampaign.workflow.id}`,
+ cron: PARTNER_ENROLLED_WORKFLOW_CRON,
+ scheduleId: updatedCampaign.workflow.id,
+ });
+ } catch (error) {
+ // should never happen, but just in case
+ const errorMessage = `Failed to create QStash schedule ${updatedCampaign.workflow.id}: ${error}`;
+ console.warn(errorMessage);
+ await log({
+ type: "errors",
+ message: errorMessage,
+ });
+ }
+ return;
}
const shouldDeleteSchedule =
campaign.status === "active" && updatedCampaign.status === "paused";
if (shouldDeleteSchedule) {
- return await qstash.schedules.delete(updatedCampaign.workflow.id);
+ try {
+ return await qstash.schedules.delete(updatedCampaign.workflow.id);
+ } catch (error) {
+ // should never happen, but just in case
+ const errorMessage = `Failed to delete QStash schedule ${updatedCampaign.workflow.id}: ${error}`;
+ console.warn(errorMessage);
+ await log({
+ type: "errors",
+ message: errorMessage,
+ });
+ }
}
};
diff --git a/apps/web/lib/api/campaigns/transform-campaign.ts b/apps/web/lib/api/campaigns/transform-campaign.ts
new file mode 100644
index 0000000000..7b64c033d2
--- /dev/null
+++ b/apps/web/lib/api/campaigns/transform-campaign.ts
@@ -0,0 +1,49 @@
+import { Prisma } from "@prisma/client";
+
+export const campaignEligibilityIncludes = {
+ groups: {
+ select: {
+ groupId: true,
+ },
+ },
+ partnerTags: {
+ select: {
+ partnerTagId: true,
+ },
+ },
+} satisfies Prisma.CampaignInclude;
+
+export type TransformCampaignInput = Prisma.CampaignGetPayload<{
+ include: {
+ groups: {
+ select: {
+ groupId: true;
+ };
+ };
+ partnerTags: {
+ select: {
+ partnerTagId: true;
+ };
+ };
+ workflow: {
+ select: {
+ triggerConditions: true;
+ };
+ };
+ };
+}>;
+
+export const transformCampaign = (campaign: TransformCampaignInput) => {
+ const groups = campaign.groups.map(({ groupId }) => ({ id: groupId }));
+
+ const partnerTags = campaign.partnerTags.map(({ partnerTagId }) => ({
+ id: partnerTagId,
+ }));
+
+ return {
+ ...campaign,
+ groups,
+ partnerTags,
+ triggerConditions: campaign.workflow?.triggerConditions,
+ };
+};
diff --git a/apps/web/lib/api/campaigns/validate-campaign.ts b/apps/web/lib/api/campaigns/validate-campaign.ts
index 9e628a595d..46db6f36c5 100644
--- a/apps/web/lib/api/campaigns/validate-campaign.ts
+++ b/apps/web/lib/api/campaigns/validate-campaign.ts
@@ -37,8 +37,9 @@ export async function validateCampaign({
input.subject ||
input.preview ||
input.bodyJson ||
- input.groupIds ||
- input.triggerCondition !== undefined ||
+ input.groupIds !== undefined ||
+ input.partnerTagIds !== undefined ||
+ input.triggerConditions !== undefined ||
input.from ||
input.scheduledAt
) {
@@ -51,7 +52,7 @@ export async function validateCampaign({
}
if (campaign.type === "marketing") {
- delete input.triggerCondition;
+ delete input.triggerConditions;
}
if (campaign.type === "transactional") {
diff --git a/apps/web/lib/api/commissions/create-manual-commissions.ts b/apps/web/lib/api/commissions/create-manual-commissions.ts
index a75327bd6f..ffbd3f7ebe 100644
--- a/apps/web/lib/api/commissions/create-manual-commissions.ts
+++ b/apps/web/lib/api/commissions/create-manual-commissions.ts
@@ -678,8 +678,7 @@ async function executeSideEffects(args: ExecuteSideEffectsArgs) {
}),
executeWorkflows({
- trigger: "partnerMetricsUpdated",
- reason: "commission",
+ event: "commissionRecorded",
identity: {
workspaceId: workspace.id,
programId,
diff --git a/apps/web/lib/api/conversions/track-lead.ts b/apps/web/lib/api/conversions/track-lead.ts
index 7aed29a8b7..6a45d65869 100644
--- a/apps/web/lib/api/conversions/track-lead.ts
+++ b/apps/web/lib/api/conversions/track-lead.ts
@@ -316,8 +316,7 @@ export const trackLead = async ({
await Promise.allSettled([
executeWorkflows({
- trigger: "partnerMetricsUpdated",
- reason: "lead",
+ event: "leadRecorded",
identity: {
workspaceId: workspace.id,
programId: link.programId,
diff --git a/apps/web/lib/api/conversions/track-sale.ts b/apps/web/lib/api/conversions/track-sale.ts
index b22e04de09..036a45622a 100644
--- a/apps/web/lib/api/conversions/track-sale.ts
+++ b/apps/web/lib/api/conversions/track-sale.ts
@@ -408,8 +408,7 @@ const _trackLead = async ({
if (link.programId && link.partnerId && customer) {
await Promise.allSettled([
executeWorkflows({
- trigger: "partnerMetricsUpdated",
- reason: "lead",
+ event: "leadRecorded",
identity: {
workspaceId: workspace.id,
programId: link.programId,
@@ -598,8 +597,7 @@ const _trackSale = async ({
await Promise.allSettled([
executeWorkflows({
- trigger: "partnerMetricsUpdated",
- reason: "sale",
+ event: "saleRecorded",
identity: {
workspaceId: workspace.id,
programId: link.programId,
diff --git a/apps/web/lib/api/fraud/release-hold-commissions.ts b/apps/web/lib/api/fraud/release-hold-commissions.ts
index 5d270927a4..82b39e92d7 100644
--- a/apps/web/lib/api/fraud/release-hold-commissions.ts
+++ b/apps/web/lib/api/fraud/release-hold-commissions.ts
@@ -203,8 +203,7 @@ export async function releaseHoldCommissions({
// should always be > 0, but just in case
releasedEarnings > 0 &&
executeWorkflows({
- trigger: "partnerMetricsUpdated",
- reason: "commission",
+ event: "commissionRecorded",
identity: {
workspaceId: program.workspaceId,
programId,
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 1306dc4156..ea141cc3bd 100644
--- a/apps/web/lib/api/groups/upsert-group-move-rules.ts
+++ b/apps/web/lib/api/groups/upsert-group-move-rules.ts
@@ -5,7 +5,7 @@ import { prisma } from "@/lib/prisma";
import { WorkspaceProps } from "@/lib/types";
import { WORKFLOW_ACTION_TYPES } from "@/lib/zod/schemas/workflows";
import { pluralize } from "@dub/utils";
-import { PartnerGroup, WorkflowTrigger } from "@prisma/client";
+import { PartnerGroup } from "@prisma/client";
import { createId } from "../create-id";
import { DubApiError } from "../errors";
import { validateWorkflowConditions } from "../workflows/validate-workflow-conditions";
@@ -82,7 +82,6 @@ export async function upsertGroupMoveRules({
};
const workflowData = {
- trigger: "partnerMetricsUpdated" as WorkflowTrigger,
triggerConditions: moveRules,
actions: [action],
};
diff --git a/apps/web/lib/api/partner-tags/throw-if-invalid-partner-tag-ids.ts b/apps/web/lib/api/partner-tags/throw-if-invalid-partner-tag-ids.ts
new file mode 100644
index 0000000000..84cf8b82f6
--- /dev/null
+++ b/apps/web/lib/api/partner-tags/throw-if-invalid-partner-tag-ids.ts
@@ -0,0 +1,39 @@
+import { DubApiError } from "@/lib/api/errors";
+import { prisma } from "@/lib/prisma";
+
+export async function throwIfInvalidPartnerTagIds({
+ programId,
+ partnerTagIds,
+}: {
+ programId: string;
+ partnerTagIds: string[] | null | undefined;
+}) {
+ if (!partnerTagIds || partnerTagIds.length === 0) {
+ return [];
+ }
+
+ const partnerTags = await prisma.partnerTag.findMany({
+ where: {
+ programId,
+ id: {
+ in: partnerTagIds,
+ },
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ const invalidPartnerTagIds = partnerTagIds.filter(
+ (partnerTagId) => !partnerTags.some((tag) => tag.id === partnerTagId),
+ );
+
+ if (invalidPartnerTagIds.length) {
+ throw new DubApiError({
+ message: `Invalid partner tag IDs detected: ${invalidPartnerTagIds.join(", ")}`,
+ code: "bad_request",
+ });
+ }
+
+ return partnerTags;
+}
diff --git a/apps/web/lib/api/workflows/attribute-definitions.ts b/apps/web/lib/api/workflows/attribute-definitions.ts
index bf2c2f42b6..a61bc3eea2 100644
--- a/apps/web/lib/api/workflows/attribute-definitions.ts
+++ b/apps/web/lib/api/workflows/attribute-definitions.ts
@@ -2,32 +2,68 @@
* Private to lib/api/workflows.
* Do not import from UI or other packages — use AWARD_BOUNTY_* /
* GROUP_MOVE_* / SEND_CAMPAIGN_* from the workflow schema instead.
+ * This is the superset of attributes that are used in the workflow schema.
*/
-export const WORKFLOW_ATTRIBUTES = {
+const WORKFLOW_DATA_REQUIREMENTS = ["commissions", "partnerLinkStats"] as const;
+
+export type WorkflowDataRequirement =
+ (typeof WORKFLOW_DATA_REQUIREMENTS)[number];
+
+export type WorkflowAttribute = {
+ name: string;
+ label: string;
+ inputType: "number" | "currency" | "dropdown" | "none" | "group";
+ operators: readonly string[];
+ requires: readonly WorkflowDataRequirement[];
+ dropdownValues?: readonly number[];
+ exclusive?: boolean;
+ scheduled?: boolean;
+};
+
+export const WORKFLOW_ATTRIBUTE_KEYS = [
+ "totalLeads",
+ "totalConversions",
+ "totalSaleAmount",
+ "totalCommissions",
+ "partnerEnrolledDays",
+ "partnerJoined",
+ "partnerGroup",
+] as const;
+
+export type WorkflowAttributeKey = (typeof WORKFLOW_ATTRIBUTE_KEYS)[number];
+
+export const WORKFLOW_ATTRIBUTES: Record<
+ WorkflowAttributeKey,
+ WorkflowAttribute
+> = {
totalLeads: {
name: "totalLeads",
label: "total leads",
inputType: "number",
operators: ["gte"],
+ requires: ["partnerLinkStats"],
},
totalConversions: {
name: "totalConversions",
label: "total conversions",
inputType: "number",
operators: ["gte"],
+ requires: ["partnerLinkStats"],
},
totalSaleAmount: {
name: "totalSaleAmount",
label: "total revenue",
inputType: "currency",
operators: ["gte"],
+ requires: ["partnerLinkStats"],
},
totalCommissions: {
name: "totalCommissions",
label: "total commissions",
inputType: "currency",
operators: ["gte"],
+ requires: ["commissions"],
},
partnerEnrolledDays: {
name: "partnerEnrolledDays",
@@ -35,23 +71,22 @@ export const WORKFLOW_ATTRIBUTES = {
inputType: "dropdown",
operators: ["gte"],
dropdownValues: [1, 3, 7, 14, 30],
+ requires: [],
+ scheduled: true,
},
partnerJoined: {
name: "partnerJoined",
label: "joins the program",
inputType: "none",
operators: ["gte"],
+ requires: [],
+ exclusive: true,
},
partnerGroup: {
name: "partnerGroup",
label: "group",
inputType: "group",
operators: ["eq", "ne", "in", "notIn"],
+ requires: [],
},
-} 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 f9b1476eba..1e6ee92d54 100644
--- a/apps/web/lib/api/workflows/award-bounty/execute.ts
+++ b/apps/web/lib/api/workflows/award-bounty/execute.ts
@@ -1,6 +1,7 @@
import { evaluateWorkflowConditions } from "@/lib/api/workflows/evaluate-workflow-conditions";
import { WorkflowContext } from "@/lib/api/workflows/types";
import {
+ bountyEligibilityIncludes,
getEffectiveBountyPeriod,
isPartnerEligibleForBounty,
} from "@/lib/bounty/api/bounty-availability";
@@ -35,7 +36,14 @@ export const executeAwardBountyWorkflow = async ({
workflow: Workflow;
context: WorkflowContext;
}) => {
- const { condition, action } = parseWorkflowConfig(workflow);
+ const { conditions, action } = parseWorkflowConfig(workflow);
+
+ // Award bounty workflows require exactly one condition
+ if (conditions.length !== 1) {
+ return;
+ }
+
+ const condition = conditions[0];
if (action.type !== WORKFLOW_ACTION_TYPES.AwardBounty) {
return;
@@ -63,6 +71,7 @@ export const executeAwardBountyWorkflow = async ({
id: bountyId,
},
include: {
+ ...bountyEligibilityIncludes,
program: {
select: {
id: true,
@@ -72,11 +81,6 @@ export const executeAwardBountyWorkflow = async ({
defaultGroupId: true,
},
},
- groups: {
- select: {
- groupId: true,
- },
- },
submissions: {
select: {
id: true,
@@ -193,7 +197,7 @@ export const executeAwardBountyWorkflow = async ({
// Check if the bounty submission meet the reward criteria
const shouldExecute = evaluateWorkflowConditions({
conditions: [condition],
- attributes: {
+ context: {
[condition.attribute]: Number(bountySubmission.performanceCount ?? 0),
},
});
diff --git a/apps/web/lib/api/workflows/check-workflow-conditions.ts b/apps/web/lib/api/workflows/check-workflow-conditions.ts
new file mode 100644
index 0000000000..6ab2da664c
--- /dev/null
+++ b/apps/web/lib/api/workflows/check-workflow-conditions.ts
@@ -0,0 +1,92 @@
+import { WORKFLOW_OPERATORS } from "@/lib/api/workflows/operator-definitions";
+import type {
+ WorkflowCondition,
+ WorkflowType,
+} from "@/lib/api/workflows/types";
+import { WORKFLOW_TYPE_ATTRIBUTES } from "./workflow-type-attributes";
+
+export function checkWorkflowConditions({
+ conditions,
+ workflowType,
+}: {
+ conditions?: WorkflowCondition[] | null;
+ workflowType: WorkflowType;
+}): {
+ valid: boolean;
+ errors: string[];
+} {
+ if (!conditions || conditions.length === 0) {
+ return {
+ valid: true,
+ errors: [],
+ };
+ }
+
+ const attributes = WORKFLOW_TYPE_ATTRIBUTES[workflowType];
+ const errors: string[] = [];
+
+ for (let i = 0; i < conditions.length; i++) {
+ const condition = conditions[i];
+ const conditionIndex = i;
+
+ if (!condition?.attribute) {
+ errors.push(
+ `Condition ${conditionIndex + 1}: Please select an activity.`,
+ );
+ continue;
+ }
+
+ const attributeDefinition =
+ attributes[condition.attribute as keyof typeof attributes];
+
+ if (!attributeDefinition) {
+ errors.push(`Condition ${conditionIndex + 1}: Invalid activity.`);
+ continue;
+ }
+
+ const operatorDefinition =
+ WORKFLOW_OPERATORS[condition.operator as keyof typeof WORKFLOW_OPERATORS];
+
+ if (!operatorDefinition) {
+ errors.push(`Condition ${conditionIndex + 1}: Invalid operator.`);
+ continue;
+ }
+
+ if (
+ !(attributeDefinition.operators as readonly string[]).includes(
+ condition.operator,
+ )
+ ) {
+ const operatorLabel = operatorDefinition.label ?? condition.operator;
+ errors.push(
+ `Operator "${operatorLabel}" is not valid for the activity "${condition.attribute}".`,
+ );
+ continue;
+ }
+
+ // Attributes with inputType "none" (e.g. partnerJoined) don't require a value.
+ if (attributeDefinition.inputType === "none") {
+ continue;
+ }
+
+ if (condition.value == null || condition.value === undefined) {
+ errors.push(`Condition ${conditionIndex + 1}: Please enter a value.`);
+ continue;
+ }
+
+ try {
+ operatorDefinition.validate(condition.value as any);
+ } catch (error) {
+ errors.push(
+ `Condition ${conditionIndex + 1}: ${
+ error instanceof Error ? error.message : "Invalid value."
+ }`,
+ );
+ }
+ }
+
+ return {
+ valid: errors.length === 0,
+ errors,
+ };
+}
diff --git a/apps/web/lib/api/workflows/evaluate-workflow-conditions.ts b/apps/web/lib/api/workflows/evaluate-workflow-conditions.ts
index fa26baa9af..659b15b196 100644
--- a/apps/web/lib/api/workflows/evaluate-workflow-conditions.ts
+++ b/apps/web/lib/api/workflows/evaluate-workflow-conditions.ts
@@ -1,16 +1,23 @@
import { WorkflowCondition } from "@/lib/api/workflows/types";
+import { prettyPrint } from "@dub/utils";
+import { isLocalDev } from "../environment";
import { WorkflowAttributeKey } from "./attribute-definitions";
import { WORKFLOW_OPERATORS } from "./operator-definitions";
export function evaluateWorkflowConditions({
conditions,
- attributes,
+ context,
}: {
conditions: WorkflowCondition[];
- attributes: Partial<Record<WorkflowAttributeKey, number | string | null>>;
+ context: Partial<Record<WorkflowAttributeKey, number | string | null>>;
}): boolean {
if (conditions.length === 0) return false;
+ if (isLocalDev) {
+ console.log("[Workflows] Conditions", prettyPrint(conditions));
+ console.log("[Workflows] Context", prettyPrint(context));
+ }
+
for (const condition of conditions) {
const operator = WORKFLOW_OPERATORS[condition.operator];
@@ -19,7 +26,7 @@ export function evaluateWorkflowConditions({
return false;
}
- const attributeValue = attributes[condition.attribute];
+ const attributeValue = context[condition.attribute];
if (attributeValue == null) {
console.error(`${condition.attribute} doesn't exist in the context.`);
diff --git a/apps/web/lib/api/workflows/execute-workflows.ts b/apps/web/lib/api/workflows/execute-workflows.ts
index a1da1513ed..a77d25ae47 100644
--- a/apps/web/lib/api/workflows/execute-workflows.ts
+++ b/apps/web/lib/api/workflows/execute-workflows.ts
@@ -1,9 +1,12 @@
-import { WorkflowContext } from "@/lib/api/workflows/types";
+import {
+ WorkflowContext,
+ WorkflowTriggerEvent,
+} from "@/lib/api/workflows/types";
import { logger, toErrorFields } from "@/lib/axiom/server";
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 { CommissionStatus, Workflow } from "@prisma/client";
import { WorkflowAttributeKey } from "./attribute-definitions";
import { executeAwardBountyWorkflow } from "./award-bounty/execute";
import { executeMoveGroupWorkflow } from "./move-group/execute";
@@ -31,39 +34,45 @@ const ACTION_HANDLERS: Record<WORKFLOW_ACTION_TYPES, WorkflowActionHandler> = {
},
};
-// Map reason to expected attributes for early filtering optimization.
-// This prevents workflows from executing unnecessarily
-const REASON_TO_ATTRIBUTES: Record<
- NonNullable<WorkflowContext["reason"]>,
- WorkflowAttributeKey[]
-> = {
- lead: ["totalLeads"],
- sale: ["totalConversions", "totalSaleAmount"],
- commission: ["totalCommissions"],
+const EVENT_ATTRIBUTES: Record<WorkflowTriggerEvent, WorkflowAttributeKey[]> = {
+ partnerEnrolled: ["partnerJoined"],
+ leadRecorded: ["totalLeads", "partnerGroup"],
+ saleRecorded: ["totalConversions", "totalSaleAmount", "partnerGroup"],
+ commissionRecorded: ["totalCommissions", "partnerGroup"],
};
export async function executeWorkflows({
- trigger,
- reason,
+ event,
identity,
metrics,
}: WorkflowContext) {
const { programId, partnerId } = identity;
console.log("[Workflows] Executing workflows...", {
- trigger,
- reason,
+ event,
programId,
partnerId,
identity,
metrics,
});
+ const attributes = EVENT_ATTRIBUTES[event];
+
+ if (attributes.length === 0) {
+ console.log("[Workflows] No attributes found to execute workflows.");
+ return;
+ }
+
const workflows = await prisma.workflow.findMany({
where: {
programId,
disabledAt: null,
- trigger,
+ OR: attributes.map((attribute) => ({
+ triggerConditions: {
+ path: "$[*].attribute",
+ array_contains: attribute,
+ },
+ })),
},
});
@@ -99,28 +108,9 @@ export async function executeWorkflows({
return;
}
- // Filter by reason if provided
- let filteredWorkflows = parsedWorkflows;
- if (reason) {
- const expectedAttributes = REASON_TO_ATTRIBUTES[reason];
-
- filteredWorkflows = parsedWorkflows.filter(({ config }) =>
- config.conditions.some(({ attribute }) =>
- expectedAttributes.includes(attribute),
- ),
- );
-
- if (filteredWorkflows.length === 0) {
- console.log(
- `[Workflows] No relevant workflows found to execute for trigger.`,
- );
- return;
- }
- }
-
// Commissions require a separate expensive aggregate query.
// We only fetch if needed to avoid unnecessary database queries.
- const shouldFetchCommissions = filteredWorkflows.some(({ config }) =>
+ const shouldFetchCommissions = parsedWorkflows.some(({ config }) =>
config.conditions.some((c) => c.attribute === "totalCommissions"),
);
@@ -142,24 +132,39 @@ export async function executeWorkflows({
saleAmount: true,
},
},
+ programPartnerTags: {
+ select: {
+ partnerTagId: true,
+ },
+ },
},
}),
shouldFetchCommissions
? prisma.commission.aggregate({
where: {
- earnings: { not: 0 },
+ earnings: {
+ not: 0,
+ },
programId,
partnerId,
status: {
- in: ["pending", "processed", "paid"],
+ in: [
+ CommissionStatus.pending,
+ CommissionStatus.processed,
+ CommissionStatus.paid,
+ ],
},
},
_sum: {
earnings: true,
},
})
- : Promise.resolve({ _sum: { earnings: null } }),
+ : Promise.resolve({
+ _sum: {
+ earnings: null,
+ },
+ }),
]);
if (!programEnrollment) {
@@ -180,9 +185,15 @@ export async function executeWorkflows({
aggregatePartnerLinksStats(programEnrollment.links);
const workflowContext: WorkflowContext = {
- programEnrollment,
- trigger,
- reason,
+ event,
+ programEnrollment: {
+ groupId: programEnrollment.groupId,
+ createdAt: programEnrollment.createdAt,
+ partnerId: programEnrollment.partnerId,
+ programId: programEnrollment.programId,
+ status: programEnrollment.status,
+ programPartnerTags: programEnrollment.programPartnerTags,
+ },
identity: {
...identity,
groupId: programEnrollment.groupId,
@@ -198,7 +209,7 @@ export async function executeWorkflows({
},
};
- for (const { workflow, config } of filteredWorkflows) {
+ for (const { workflow, config } of parsedWorkflows) {
try {
const handler = ACTION_HANDLERS[config.action.type];
diff --git a/apps/web/lib/api/workflows/move-group/execute.ts b/apps/web/lib/api/workflows/move-group/execute.ts
index 8d25841956..1174b41e5d 100644
--- a/apps/web/lib/api/workflows/move-group/execute.ts
+++ b/apps/web/lib/api/workflows/move-group/execute.ts
@@ -63,7 +63,7 @@ export const executeMoveGroupWorkflow = async ({
return;
}
- const attributes: Partial<
+ const workflowContext: Partial<
Record<WorkflowAttributeKey, number | string | null>
> = {
totalLeads: metrics?.aggregated?.leads ?? 0,
@@ -75,7 +75,7 @@ export const executeMoveGroupWorkflow = async ({
const shouldExecute = evaluateWorkflowConditions({
conditions,
- attributes,
+ context: workflowContext,
});
if (!shouldExecute) {
@@ -110,7 +110,7 @@ export const executeMoveGroupWorkflow = async ({
}
// Prevents duplicate moves when a workflow with matching conditions
- // are triggered by the same partnerMetricsUpdated event.
+ // are triggered by the same event.
const lockKey = `workflow:moveGroup:${programId}:${newGroupId}:${partnerId}`;
const acquired = await redis.set(lockKey, "1", { nx: true, ex: 10 });
diff --git a/apps/web/lib/api/workflows/operator-definitions.ts b/apps/web/lib/api/workflows/operator-definitions.ts
index 33e6db7fd3..8a354d046d 100644
--- a/apps/web/lib/api/workflows/operator-definitions.ts
+++ b/apps/web/lib/api/workflows/operator-definitions.ts
@@ -1,4 +1,4 @@
-export type ConditionValue =
+type ConditionValue =
| number
| { min?: number; max?: number }
| string
@@ -18,7 +18,7 @@ export const WORKFLOW_OPERATORS = {
// Greater than or equal to
gte: {
name: "gte",
- label: "at least",
+ label: "is at least",
validate(value: ConditionValue) {
if (typeof value !== "number" || isNaN(value) || value < 0) {
throw new Error("Please enter a value greater than or equal to 0.");
@@ -36,10 +36,31 @@ export const WORKFLOW_OPERATORS = {
},
},
+ // Less than or equal to
+ lte: {
+ name: "lte",
+ label: "is less than or equal to",
+ validate(value: ConditionValue) {
+ if (typeof value !== "number" || isNaN(value) || value < 0) {
+ throw new Error("Please enter a value greater than or equal to 0.");
+ }
+ },
+ evaluate(attributeValue: number | string, conditionValue: ConditionValue) {
+ if (
+ typeof attributeValue !== "number" ||
+ typeof conditionValue !== "number"
+ ) {
+ return false;
+ }
+
+ return attributeValue <= conditionValue;
+ },
+ },
+
// Between (inclusive)
between: {
name: "between",
- label: "between",
+ label: "is between",
validate(value: ConditionValue) {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
throw new Error("Please enter a valid value.");
diff --git a/apps/web/lib/api/workflows/parse-workflow-config.ts b/apps/web/lib/api/workflows/parse-workflow-config.ts
index 49c40f6363..51940ac588 100644
--- a/apps/web/lib/api/workflows/parse-workflow-config.ts
+++ b/apps/web/lib/api/workflows/parse-workflow-config.ts
@@ -26,7 +26,6 @@ export function parseWorkflowConfig(
return {
conditions,
- condition: conditions[0],
action: actions[0],
};
}
diff --git a/apps/web/lib/api/workflows/send-campaign/execute.ts b/apps/web/lib/api/workflows/send-campaign/execute.ts
index acd4ff60d3..8a4d0c4e6a 100644
--- a/apps/web/lib/api/workflows/send-campaign/execute.ts
+++ b/apps/web/lib/api/workflows/send-campaign/execute.ts
@@ -7,15 +7,38 @@ import { TiptapNode } from "@/lib/types";
import { WORKFLOW_ACTION_TYPES } from "@/lib/zod/schemas/workflows";
import { sendBatchEmail } from "@dub/email";
import CampaignEmail from "@dub/email/templates/campaign-email";
-import { chunk } from "@dub/utils";
-import { NotificationEmailType, Prisma, Workflow } from "@prisma/client";
+import { chunk, pluck } from "@dub/utils";
+import {
+ CommissionStatus,
+ NotificationEmailType,
+ Prisma,
+ ProgramEnrollmentStatus,
+ Workflow,
+} from "@prisma/client";
import { addHours, differenceInDays, subDays } from "date-fns";
import { resolveCampaignEmailVariables } from "../../campaigns/interpolate-email-template";
import { renderCampaignEmailHTML } from "../../campaigns/render-campaign-email-html";
+import { campaignEligibilityIncludes } from "../../campaigns/transform-campaign";
import { validateCampaignFromAddress } from "../../campaigns/validate-campaign";
import { createId } from "../../create-id";
import { WorkflowAttributeKey } from "../attribute-definitions";
import { parseWorkflowConfig } from "../parse-workflow-config";
+import { getWorkflowDataRequirements } from "../utils";
+
+type ResolveProgramEnrollment = {
+ partnerId: string;
+ programId: string;
+ groupIds: string[];
+ partnerTagIds: string[];
+ conditions: WorkflowCondition[];
+};
+
+type ProgramEnrollmentForWorkflowContext = Pick<
+ Prisma.ProgramEnrollmentGetPayload<{
+ include: typeof programEnrollmentInclude;
+ }>,
+ "links" | "createdAt" | "groupId"
+>;
export const executeSendCampaignWorkflow = async ({
workflow,
@@ -24,7 +47,7 @@ export const executeSendCampaignWorkflow = async ({
workflow: Workflow;
context?: WorkflowContext;
}) => {
- const { condition, action } = parseWorkflowConfig(workflow);
+ const { conditions, action } = parseWorkflowConfig(workflow);
if (action.type !== WORKFLOW_ACTION_TYPES.SendCampaign) {
console.log(
@@ -44,7 +67,7 @@ export const executeSendCampaignWorkflow = async ({
id: campaignId,
},
include: {
- groups: true,
+ ...campaignEligibilityIncludes,
program: {
include: {
emailDomains: {
@@ -67,12 +90,23 @@ export const executeSendCampaignWorkflow = async ({
return;
}
- let programEnrollments = await getProgramEnrollments({
- programId,
- partnerId,
- groupIds: campaign.groups.map(({ groupId }) => groupId),
- condition: condition as WorkflowCondition,
- });
+ const campaignGroupIds = pluck(campaign.groups, "groupId");
+ const campaignPartnerTagIds = pluck(campaign.partnerTags, "partnerTagId");
+
+ let programEnrollments = partnerId
+ ? await resolveProgramEnrollment({
+ programId,
+ partnerId,
+ groupIds: campaignGroupIds,
+ partnerTagIds: campaignPartnerTagIds,
+ conditions,
+ })
+ : await resolveProgramEnrollments({
+ programId,
+ groupIds: campaignGroupIds,
+ partnerTagIds: campaignPartnerTagIds,
+ conditions,
+ });
if (programEnrollments.length === 0) {
console.log(
@@ -91,7 +125,7 @@ export const executeSendCampaignWorkflow = async ({
campaignId: campaign.id,
type: "Campaign",
partnerId: {
- in: programEnrollments.map(({ partnerId }) => partnerId),
+ in: pluck(programEnrollments, "partnerId"),
},
},
select: {
@@ -99,19 +133,19 @@ export const executeSendCampaignWorkflow = async ({
},
});
- if (alreadySentEmails.length > 0) {
+ const alreadySentPartnerIds = pluck(alreadySentEmails, "partnerId");
+
+ if (alreadySentPartnerIds.length > 0) {
console.log(
- `Workflow ${workflow.id} already sent campaign emails to ${alreadySentEmails.length} partners: ${alreadySentEmails.map(({ partnerId }) => partnerId).join(", ")}`,
+ `Workflow ${workflow.id} already sent campaign emails to ${alreadySentPartnerIds.length} partners: ${alreadySentPartnerIds.join(", ")}`,
);
}
- const alreadySentPartnerIds = new Set(
- alreadySentEmails.map(({ partnerId }) => partnerId),
- );
+ const alreadySentPartnerIdSet = new Set(alreadySentPartnerIds);
// Exclude partners who already got the campaign
programEnrollments = programEnrollments.filter(
- ({ partnerId }) => !alreadySentPartnerIds.has(partnerId),
+ ({ partnerId }) => !alreadySentPartnerIdSet.has(partnerId),
);
if (programEnrollments.length === 0) {
@@ -150,6 +184,13 @@ export const executeSendCampaignWorkflow = async ({
})),
);
+ if (partnerUsers.length === 0) {
+ console.log(
+ `Workflow ${workflow.id} found enrollments but no partner users with emails to send campaign emails to.`,
+ );
+ continue;
+ }
+
// Send emails
const { data } = await sendBatchEmail(
partnerUsers.map((partnerUser) => ({
@@ -215,7 +256,7 @@ export const executeSendCampaignWorkflow = async ({
}
};
-const includePartnerUsers = {
+const programEnrollmentInclude = {
partner: {
include: {
users: {
@@ -235,6 +276,11 @@ const includePartnerUsers = {
shortLink: true,
key: true,
url: true,
+ clicks: true,
+ leads: true,
+ conversions: true,
+ sales: true,
+ saleAmount: true,
},
orderBy: {
id: "asc" as const,
@@ -246,135 +292,224 @@ const includePartnerUsers = {
referralReward: true,
} satisfies Prisma.ProgramEnrollmentInclude;
-async function getProgramEnrollments({
- programId,
- partnerId,
+function buildWorkflowContext({
+ programEnrollment,
+ totalCommissions,
+}: {
+ programEnrollment: ProgramEnrollmentForWorkflowContext;
+ totalCommissions: number | null | undefined;
+}): Record<WorkflowAttributeKey, string | number | null> {
+ const { totalLeads, totalConversions, totalSaleAmount } =
+ aggregatePartnerLinksStats(programEnrollment.links);
+
+ const daysSinceEnrollment = differenceInDays(
+ new Date(),
+ programEnrollment.createdAt,
+ );
+
+ return {
+ totalLeads,
+ totalConversions,
+ totalSaleAmount,
+ totalCommissions: totalCommissions ?? 0,
+ partnerEnrolledDays: daysSinceEnrollment,
+ partnerJoined: daysSinceEnrollment,
+ partnerGroup: programEnrollment.groupId,
+ };
+}
+
+function campaignAudienceWhere({
groupIds,
- condition,
+ partnerTagIds,
}: {
- programId: string;
- partnerId?: string;
groupIds: string[];
- condition: WorkflowCondition;
+ partnerTagIds: string[];
}) {
- if (partnerId) {
- const { attribute } = condition;
+ return {
+ status: ProgramEnrollmentStatus.approved,
+ ...(groupIds.length > 0 && {
+ groupId: {
+ in: groupIds,
+ },
+ }),
+ ...(partnerTagIds.length > 0 && {
+ partner: {
+ programPartnerTags: {
+ some: {
+ partnerTagId: {
+ in: partnerTagIds,
+ },
+ },
+ },
+ },
+ }),
+ };
+}
- const isPartnerLinkStatsAttribute = [
- "totalLeads",
- "totalConversions",
- "totalSaleAmount",
- ].includes(attribute);
+async function resolveProgramEnrollment({
+ programId,
+ partnerId,
+ groupIds,
+ partnerTagIds,
+ conditions,
+}: ResolveProgramEnrollment) {
+ const { commissions } = getWorkflowDataRequirements({
+ conditions,
+ });
- const programEnrollment = await prisma.programEnrollment.findUnique({
+ const [programEnrollment, totalCommissions] = await Promise.all([
+ prisma.programEnrollment.findUnique({
where: {
partnerId_programId: {
partnerId,
programId,
},
- status: "approved",
- ...(groupIds.length > 0 && {
- groupId: {
- in: groupIds,
- },
+ ...campaignAudienceWhere({
+ groupIds,
+ partnerTagIds,
}),
},
- include: {
- ...includePartnerUsers,
- ...(isPartnerLinkStatsAttribute
- ? {
- links: {
- select: {
- shortLink: true,
- key: true,
- url: true,
- clicks: true,
- leads: true,
- conversions: true,
- sales: true,
- saleAmount: true,
- },
- orderBy: {
- id: "asc",
- },
- },
- }
- : {}),
- },
- });
+ include: programEnrollmentInclude,
+ }),
+
+ commissions
+ ? prisma.commission.aggregate({
+ where: {
+ earnings: {
+ not: 0,
+ },
+ programId,
+ partnerId,
+ status: {
+ in: [
+ CommissionStatus.pending,
+ CommissionStatus.processed,
+ CommissionStatus.paid,
+ ],
+ },
+ },
+ _sum: {
+ earnings: true,
+ },
+ })
+ : Promise.resolve({
+ _sum: {
+ earnings: 0,
+ },
+ }),
+ ]);
- if (!programEnrollment) {
- return [];
- }
+ if (!programEnrollment) {
+ return [];
+ }
- 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],
- attributes: {
- [condition.attribute]: context[condition.attribute],
- },
- });
+ const workflowContext = buildWorkflowContext({
+ programEnrollment,
+ totalCommissions: totalCommissions._sum.earnings,
+ });
- if (!shouldExecute) {
- return [];
- }
+ const shouldExecute = evaluateWorkflowConditions({
+ conditions,
+ context: workflowContext,
+ });
- return [programEnrollment];
+ if (!shouldExecute) {
+ return [];
}
- const startDate = subDays(new Date(), condition.value as number);
- // add 12 hours to the start date since we run the partnerEnrolled workflow every 12 hours
+ return [programEnrollment];
+}
+
+// Run only for scheduled workflows
+async function resolveProgramEnrollments({
+ programId,
+ groupIds,
+ partnerTagIds,
+ conditions,
+}: Omit<ResolveProgramEnrollment, "partnerId">) {
+ const partnerEnrolledDays = conditions.find(
+ (condition) => condition.attribute === "partnerEnrolledDays",
+ );
+
+ if (!partnerEnrolledDays) {
+ console.log("No partner enrolled days condition found. Skipping...");
+ return [];
+ }
+
+ const startDate = subDays(new Date(), partnerEnrolledDays.value as number);
+ // add 12 hours to the start date since we run the scheduled enrollment workflow every 12 hours
const endDate = addHours(startDate, 12);
- // We need to get all program enrollments that match the condition for the scheduled workflows
- return await prisma.programEnrollment.findMany({
+ // partnerEnrolledDays is enforced by the enrollment window query below —
+ // re-evaluating it with differenceInDays can false-negative partners in the window.
+ const remainingConditions = conditions.filter(
+ (condition) => condition.attribute !== "partnerEnrolledDays",
+ );
+
+ const { commissions } = getWorkflowDataRequirements({
+ conditions: remainingConditions,
+ });
+
+ const programEnrollments = await prisma.programEnrollment.findMany({
where: {
programId,
- status: "approved",
- ...(groupIds.length > 0 && {
- groupId: {
- in: groupIds,
- },
+ ...campaignAudienceWhere({
+ groupIds,
+ partnerTagIds,
}),
createdAt: {
gte: startDate,
lte: endDate,
},
},
- include: includePartnerUsers,
+ include: programEnrollmentInclude,
take: 1000, // rough estimate that a program cannot get more than 1000 enrollments every 12 hours
});
+
+ if (programEnrollments.length === 0 || remainingConditions.length === 0) {
+ return programEnrollments;
+ }
+
+ const commissionsByPartnerId = new Map<string, number>();
+
+ if (commissions) {
+ const commissionTotals = await prisma.commission.groupBy({
+ by: ["partnerId"],
+ where: {
+ earnings: {
+ not: 0,
+ },
+ programId,
+ partnerId: {
+ in: pluck(programEnrollments, "partnerId"),
+ },
+ status: {
+ in: [
+ CommissionStatus.pending,
+ CommissionStatus.processed,
+ CommissionStatus.paid,
+ ],
+ },
+ },
+ _sum: {
+ earnings: true,
+ },
+ });
+
+ for (const { partnerId, _sum } of commissionTotals) {
+ commissionsByPartnerId.set(partnerId, _sum.earnings ?? 0);
+ }
+ }
+
+ return programEnrollments.filter((programEnrollment) => {
+ const workflowContext = buildWorkflowContext({
+ programEnrollment,
+ totalCommissions: commissionsByPartnerId.get(programEnrollment.partnerId),
+ });
+
+ return evaluateWorkflowConditions({
+ conditions: remainingConditions,
+ context: workflowContext,
+ });
+ });
}
diff --git a/apps/web/lib/api/workflows/send-campaign/schema.ts b/apps/web/lib/api/workflows/send-campaign/schema.ts
index 8b04698ba0..7b510c33a0 100644
--- a/apps/web/lib/api/workflows/send-campaign/schema.ts
+++ b/apps/web/lib/api/workflows/send-campaign/schema.ts
@@ -2,24 +2,58 @@ import { WORKFLOW_OPERATORS } from "@/lib/api/workflows/operator-definitions";
import * as z from "zod/v4";
import { WORKFLOW_ATTRIBUTES } from "../attribute-definitions";
+const SEND_CAMPAIGN_METRIC_ATTRIBUTES = {
+ totalLeads: {
+ ...WORKFLOW_ATTRIBUTES.totalLeads,
+ operators: ["lte", "gte"] as const,
+ },
+ totalConversions: {
+ ...WORKFLOW_ATTRIBUTES.totalConversions,
+ operators: ["lte", "gte"] as const,
+ },
+ totalSaleAmount: {
+ ...WORKFLOW_ATTRIBUTES.totalSaleAmount,
+ operators: ["lte", "gte"] as const,
+ },
+ totalCommissions: {
+ ...WORKFLOW_ATTRIBUTES.totalCommissions,
+ operators: ["lte", "gte"] as const,
+ },
+} as const;
+
+const SEND_CAMPAIGN_ENROLLMENT_ATTRIBUTES = {
+ partnerEnrolledDays: {
+ ...WORKFLOW_ATTRIBUTES.partnerEnrolledDays,
+ operators: ["gte"] as const,
+ },
+ partnerJoined: {
+ ...WORKFLOW_ATTRIBUTES.partnerJoined,
+ operators: ["gte"] as const,
+ },
+} as const;
+
export const SEND_CAMPAIGN_ATTRIBUTES = {
- totalLeads: WORKFLOW_ATTRIBUTES.totalLeads,
- totalConversions: WORKFLOW_ATTRIBUTES.totalConversions,
- totalSaleAmount: WORKFLOW_ATTRIBUTES.totalSaleAmount,
- totalCommissions: WORKFLOW_ATTRIBUTES.totalCommissions,
- partnerEnrolledDays: WORKFLOW_ATTRIBUTES.partnerEnrolledDays,
- partnerJoined: WORKFLOW_ATTRIBUTES.partnerJoined,
+ ...SEND_CAMPAIGN_METRIC_ATTRIBUTES,
+ ...SEND_CAMPAIGN_ENROLLMENT_ATTRIBUTES,
};
export const SEND_CAMPAIGN_ATTRIBUTE_KEYS = Object.keys(
SEND_CAMPAIGN_ATTRIBUTES,
) as readonly (keyof typeof SEND_CAMPAIGN_ATTRIBUTES)[];
-const SEND_CAMPAIGN_OPERATORS = {
+export type SendCampaignAttributeKey =
+ (typeof SEND_CAMPAIGN_ATTRIBUTE_KEYS)[number];
+
+export const SEND_CAMPAIGN_ENROLLMENT_ATTRIBUTE_KEYS = Object.keys(
+ SEND_CAMPAIGN_ENROLLMENT_ATTRIBUTES,
+) as readonly (keyof typeof SEND_CAMPAIGN_ENROLLMENT_ATTRIBUTES)[];
+
+export const SEND_CAMPAIGN_OPERATORS = {
+ lte: WORKFLOW_OPERATORS.lte,
gte: WORKFLOW_OPERATORS.gte,
};
-const SEND_CAMPAIGN_OPERATOR_KEYS = Object.keys(
+export const SEND_CAMPAIGN_OPERATOR_KEYS = Object.keys(
SEND_CAMPAIGN_OPERATORS,
) as readonly (keyof typeof SEND_CAMPAIGN_OPERATORS)[];
@@ -28,3 +62,7 @@ export const sendCampaignConditionSchema = z.object({
operator: z.enum(SEND_CAMPAIGN_OPERATOR_KEYS).default("gte"),
value: z.number(),
});
+
+export const sendCampaignConditionsSchema = z.array(
+ sendCampaignConditionSchema,
+);
diff --git a/apps/web/lib/api/workflows/types.ts b/apps/web/lib/api/workflows/types.ts
index d7f8055a46..269136a85f 100644
--- a/apps/web/lib/api/workflows/types.ts
+++ b/apps/web/lib/api/workflows/types.ts
@@ -2,7 +2,7 @@ import {
workflowActionSchema,
workflowConditionSchema,
} from "@/lib/zod/schemas/workflows";
-import { ProgramEnrollment, WorkflowTrigger } from "@prisma/client";
+import { ProgramEnrollment, ProgramPartnerTag } from "@prisma/client";
import type * as z from "zod/v4";
export type WorkflowCondition = z.infer<typeof workflowConditionSchema>;
@@ -26,8 +26,7 @@ interface PartnerMetrics {
}
export interface WorkflowContext {
- trigger: WorkflowTrigger;
- reason?: "lead" | "sale" | "commission";
+ event: WorkflowTriggerEvent;
identity: WorkflowIdentity;
metrics?: {
current?: PartnerMetrics;
@@ -36,7 +35,15 @@ export interface WorkflowContext {
programEnrollment?: Pick<
ProgramEnrollment,
"groupId" | "createdAt" | "partnerId" | "programId" | "status"
- >;
+ > & {
+ programPartnerTags: Pick<ProgramPartnerTag, "partnerTagId">[];
+ };
}
export type WorkflowType = "awardBounty" | "sendCampaign" | "moveGroup";
+
+export type WorkflowTriggerEvent =
+ | "partnerEnrolled"
+ | "leadRecorded"
+ | "saleRecorded"
+ | "commissionRecorded";
diff --git a/apps/web/lib/api/workflows/utils.ts b/apps/web/lib/api/workflows/utils.ts
index af48c0bbd6..7b6260e21f 100644
--- a/apps/web/lib/api/workflows/utils.ts
+++ b/apps/web/lib/api/workflows/utils.ts
@@ -1,22 +1,121 @@
-import { SCHEDULED_WORKFLOW_TRIGGERS } from "@/lib/zod/schemas/workflows";
+import { workflowConditionsSchema } from "@/lib/zod/schemas/workflows";
import { Workflow } from "@prisma/client";
-import { WorkflowAttributeKey } from "./attribute-definitions";
-import { parseWorkflowConfig } from "./parse-workflow-config";
+import {
+ WORKFLOW_ATTRIBUTES,
+ WorkflowAttributeKey,
+ WorkflowDataRequirement,
+} from "./attribute-definitions";
+import { WorkflowCondition } from "./types";
-export const isCurrencyAttribute = (activity: WorkflowAttributeKey) =>
- activity === "totalCommissions" || activity === "totalSaleAmount";
+export const isCurrencyAttribute = (activity: WorkflowAttributeKey) => {
+ const attribute = WORKFLOW_ATTRIBUTES[activity];
-export const isScheduledWorkflow = (workflow: Workflow) => {
- const { condition } = parseWorkflowConfig(workflow);
+ if (!attribute) {
+ return false;
+ }
+
+ return attribute.inputType === "currency";
+};
+
+export const isScheduledWorkflow = (
+ workflow: Pick<Workflow, "id" | "triggerConditions" | "actions">,
+) => {
+ const parsed = workflowConditionsSchema.safeParse(workflow.triggerConditions);
+
+ if (!parsed.success || parsed.data.length === 0) {
+ return false;
+ }
+
+ return parsed.data.some((condition) => {
+ const attribute = WORKFLOW_ATTRIBUTES[condition.attribute];
+
+ return attribute?.scheduled === true;
+ });
+};
+
+export function getWorkflowDataRequirements({
+ conditions,
+}: {
+ conditions: Pick<WorkflowCondition, "attribute">[];
+}): Record<WorkflowDataRequirement, boolean> {
+ const requirements = new Set<WorkflowDataRequirement>();
+
+ for (const condition of conditions) {
+ const attribute = WORKFLOW_ATTRIBUTES[condition.attribute];
+
+ if (!attribute) {
+ continue;
+ }
+
+ for (const requirement of attribute.requires) {
+ requirements.add(requirement);
+ }
+ }
+
+ return {
+ commissions: requirements.has("commissions"),
+ partnerLinkStats: requirements.has("partnerLinkStats"),
+ };
+}
+
+function isExclusiveAttributeDefinition(
+ definition: unknown,
+): definition is { exclusive: true } {
+ return (
+ typeof definition === "object" &&
+ definition != null &&
+ "exclusive" in definition &&
+ (definition as { exclusive?: boolean }).exclusive === true
+ );
+}
+
+export function isExclusiveWorkflowAttribute(
+ attribute: string,
+ attributes: Record<string, unknown>,
+): boolean {
+ return isExclusiveAttributeDefinition(attributes[attribute]);
+}
- const shouldSchedule = SCHEDULED_WORKFLOW_TRIGGERS.includes(workflow.trigger);
+// Enforces exclusive-attribute combination rules for workflow conditions.
+// Exclusive attributes (e.g. partnerJoined) must be the sole condition.
+export function satisfiesExclusiveAttributeRules<T extends string>({
+ attribute,
+ usedAttributes,
+ currentAttribute,
+ attributes,
+}: {
+ attribute: T;
+ usedAttributes: T[];
+ currentAttribute?: T;
+ attributes: Record<string, unknown>;
+}): boolean {
+ if (attribute === currentAttribute) {
+ return true;
+ }
+
+ if (usedAttributes.includes(attribute)) {
+ return false;
+ }
+
+ const otherUsedAttributes = usedAttributes.filter(
+ (used) => used !== currentAttribute,
+ );
if (
- !shouldSchedule ||
- (shouldSchedule && condition.attribute === "partnerJoined") // for partnerJoined, we execute immediately on partner enrollment
+ isExclusiveWorkflowAttribute(attribute, attributes) &&
+ otherUsedAttributes.length > 0
+ ) {
+ return false;
+ }
+
+ if (
+ !isExclusiveWorkflowAttribute(attribute, attributes) &&
+ otherUsedAttributes.some((used) =>
+ isExclusiveWorkflowAttribute(used, attributes),
+ )
) {
return false;
}
return true;
-};
+}
diff --git a/apps/web/lib/api/workflows/validate-workflow-conditions.ts b/apps/web/lib/api/workflows/validate-workflow-conditions.ts
index 239354236a..6dfa8f7942 100644
--- a/apps/web/lib/api/workflows/validate-workflow-conditions.ts
+++ b/apps/web/lib/api/workflows/validate-workflow-conditions.ts
@@ -1,23 +1,13 @@
-import { AWARD_BOUNTY_ATTRIBUTES } from "@/lib/api/workflows/award-bounty/schema";
-import { GROUP_MOVE_ATTRIBUTES } from "@/lib/api/workflows/move-group/schema";
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 = {
- awardBounty: AWARD_BOUNTY_ATTRIBUTES,
- sendCampaign: SEND_CAMPAIGN_ATTRIBUTES,
- moveGroup: GROUP_MOVE_ATTRIBUTES,
-} as const satisfies Record<
- WorkflowType,
- Record<string, { operators: readonly string[] }>
->;
+import { SEND_CAMPAIGN_ATTRIBUTES } from "./send-campaign/schema";
+import { isExclusiveWorkflowAttribute } from "./utils";
+import { WORKFLOW_TYPE_ATTRIBUTES } from "./workflow-type-attributes";
type WorkflowConditionInput = {
attribute: string;
@@ -34,6 +24,17 @@ export async function validateWorkflowConditions({
workflowType: WorkflowType;
context?: WorkflowAttributeValidatorContext;
}): Promise<void> {
+ // Award bounty workflows require exactly one condition
+ if (
+ workflowType === "awardBounty" &&
+ (!conditions || conditions.length !== 1)
+ ) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Award bounty workflows require exactly one condition.",
+ });
+ }
+
if (!conditions || conditions.length === 0) {
return;
}
@@ -58,6 +59,30 @@ export async function validateWorkflowConditions({
}
}
+ if (workflowType === "sendCampaign") {
+ const attributesUsed = conditions
+ .map((condition) => condition.attribute)
+ .filter(Boolean);
+
+ if (new Set(attributesUsed).size !== attributesUsed.length) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Each activity can only be used once in the campaign logic.",
+ });
+ }
+
+ const exclusiveUsed = attributesUsed.filter((attr) =>
+ isExclusiveWorkflowAttribute(attr, SEND_CAMPAIGN_ATTRIBUTES),
+ );
+
+ if (exclusiveUsed.length > 0 && attributesUsed.length > 1) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `Campaign logic with "${SEND_CAMPAIGN_ATTRIBUTES[exclusiveUsed[0]].label}" cannot include other conditions.`,
+ });
+ }
+ }
+
const attributes = WORKFLOW_TYPE_ATTRIBUTES[workflowType];
for (let i = 0; i < conditions.length; i++) {
@@ -106,20 +131,25 @@ export async function validateWorkflowConditions({
});
}
- if (condition.value == null || condition.value === undefined) {
- throw new DubApiError({
- code: "bad_request",
- message: `Condition ${conditionIndex + 1}: Please enter a value.`,
- });
- }
+ // Some conditions (inputType "none", e.g. partnerJoined) don't require a value.
+ if (attributeDefinition.inputType !== "none") {
+ if (condition.value == null || condition.value === undefined) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `Condition ${conditionIndex + 1}: Please enter a value.`,
+ });
+ }
- try {
- operatorDefinition.validate(condition.value as any);
- } catch (error) {
- throw new DubApiError({
- code: "bad_request",
- message: `Condition ${conditionIndex + 1}: ${error instanceof Error ? error.message : "Invalid value."}`,
- });
+ try {
+ operatorDefinition.validate(condition.value as any);
+ } catch (error) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `Condition ${conditionIndex + 1}: ${
+ error instanceof Error ? error.message : "Invalid value."
+ }`,
+ });
+ }
}
const attributeValidator =
diff --git a/apps/web/lib/api/workflows/workflow-type-attributes.ts b/apps/web/lib/api/workflows/workflow-type-attributes.ts
new file mode 100644
index 0000000000..551a25af87
--- /dev/null
+++ b/apps/web/lib/api/workflows/workflow-type-attributes.ts
@@ -0,0 +1,18 @@
+import { AWARD_BOUNTY_ATTRIBUTES } from "@/lib/api/workflows/award-bounty/schema";
+import { GROUP_MOVE_ATTRIBUTES } from "@/lib/api/workflows/move-group/schema";
+import { SEND_CAMPAIGN_ATTRIBUTES } from "@/lib/api/workflows/send-campaign/schema";
+import type { WorkflowType } from "@/lib/api/workflows/types";
+
+type WorkflowTypeAttributeDefinition = {
+ operators: readonly string[];
+ inputType: string;
+};
+
+export const WORKFLOW_TYPE_ATTRIBUTES: Record<
+ WorkflowType,
+ Record<string, WorkflowTypeAttributeDefinition>
+> = {
+ awardBounty: AWARD_BOUNTY_ATTRIBUTES,
+ sendCampaign: SEND_CAMPAIGN_ATTRIBUTES,
+ moveGroup: GROUP_MOVE_ATTRIBUTES,
+};
diff --git a/apps/web/lib/bounty/api/bounty-availability.ts b/apps/web/lib/bounty/api/bounty-availability.ts
index 9f4e726830..02b259d48f 100644
--- a/apps/web/lib/bounty/api/bounty-availability.ts
+++ b/apps/web/lib/bounty/api/bounty-availability.ts
@@ -1,12 +1,15 @@
import { ACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";
+import { pluck } from "@dub/utils";
import {
Bounty,
BountyGroup,
+ BountyPartnerTag,
BountyStartMode,
BountySubmission,
Prisma,
Program,
ProgramEnrollment,
+ ProgramPartnerTag,
} from "@prisma/client";
import { addDays } from "date-fns";
import { isBountyEnded, isBountyStarted } from "../bounty-period";
@@ -24,34 +27,75 @@ type PartnerBountyEligibilityInput = {
| "createdAt"
> & {
groups: Pick<BountyGroup, "groupId">[];
+ partnerTags: Pick<BountyPartnerTag, "partnerTagId">[];
};
programEnrollment: Pick<
ProgramEnrollment,
"createdAt" | "groupId" | "status"
- >;
+ > & {
+ programPartnerTags: Pick<ProgramPartnerTag, "partnerTagId">[];
+ };
};
-export function buildBountyEligibilityWhere(
- groupId: string | undefined,
-): Prisma.BountyWhereInput {
+// Audience filter only (groups + tags). A bounty with no groups/tags is open to all;
+// otherwise the partner must match an assigned group AND at least one assigned tag.
+export function buildBountyEligibilityWhere({
+ groupId,
+ partnerTagIds,
+}: {
+ groupId: string | undefined | string[];
+ partnerTagIds?: string[];
+}): Prisma.BountyWhereInput {
+ const groupIds = (Array.isArray(groupId) ? groupId : [groupId]).filter(
+ (id): id is string => Boolean(id),
+ );
+
return {
- OR: [
+ AND: [
{
- groups: {
- none: {},
- },
- },
- ...(groupId
- ? [
- {
- groups: {
- some: {
- groupId,
+ OR: [
+ {
+ groups: {
+ none: {},
+ },
+ },
+ ...(groupIds && groupIds.length > 0
+ ? [
+ {
+ groups: {
+ some: {
+ groupId: {
+ in: groupIds,
+ },
+ },
+ },
},
- },
+ ]
+ : []),
+ ],
+ },
+ {
+ OR: [
+ {
+ partnerTags: {
+ none: {},
},
- ]
- : []),
+ },
+ ...(partnerTagIds && partnerTagIds.length > 0
+ ? [
+ {
+ partnerTags: {
+ some: {
+ partnerTagId: {
+ in: partnerTagIds,
+ },
+ },
+ },
+ },
+ ]
+ : []),
+ ],
+ },
],
};
}
@@ -90,6 +134,11 @@ export const bountyEligibilityIncludes = {
groupId: true,
},
},
+ partnerTags: {
+ select: {
+ partnerTagId: true,
+ },
+ },
} satisfies Prisma.BountyInclude;
export function getEffectiveBountyPeriod({
@@ -125,7 +174,7 @@ export function isPartnerEligibleForBounty({
}
// If the bounty has groups, check if the partner is in one of them
- const bountyGroupIds = bounty.groups.map((g) => g.groupId);
+ const bountyGroupIds = pluck(bounty.groups, "groupId");
const partnerGroupId = programEnrollment.groupId || program.defaultGroupId;
if (bountyGroupIds.length > 0 && !bountyGroupIds.includes(partnerGroupId)) {
@@ -135,6 +184,26 @@ export function isPartnerEligibleForBounty({
return false;
}
+ // If the bounty has partner tags, the partner must have at least one matching tag
+ const bountyPartnerTagIds = pluck(bounty.partnerTags, "partnerTagId");
+ const partnerTagIds = pluck(
+ programEnrollment.programPartnerTags,
+ "partnerTagId",
+ );
+
+ if (bountyPartnerTagIds.length > 0) {
+ const hasMatchingTag = partnerTagIds.some((tagId) =>
+ bountyPartnerTagIds.includes(tagId),
+ );
+
+ if (!hasMatchingTag) {
+ console.log(
+ `Partner is not eligible for bounty ${bounty.id} because they do not have any of the assigned partner tags. Partner's partnerTagIds: ${partnerTagIds.join(", ")}. Assigned partnerTagIds: ${bountyPartnerTagIds.join(", ")}.`,
+ );
+ return false;
+ }
+ }
+
// Relative bounties are for new partners only (enrolled on/after bounty creation)
if (bounty.startMode === BountyStartMode.relative) {
if (programEnrollment.createdAt < bounty.createdAt) {
diff --git a/apps/web/lib/bounty/api/create-bounty-submission.ts b/apps/web/lib/bounty/api/create-bounty-submission.ts
index 68915130e8..096f1519ff 100644
--- a/apps/web/lib/bounty/api/create-bounty-submission.ts
+++ b/apps/web/lib/bounty/api/create-bounty-submission.ts
@@ -4,6 +4,7 @@ import { getWorkspaceUsers } from "@/lib/api/get-workspace-users";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
import { getSocialContent } from "@/lib/api/scrape-creators/get-social-content";
import {
+ bountyEligibilityIncludes,
canPartnerSubmitBounty,
getEffectiveBountyPeriod,
} from "@/lib/bounty/api/bounty-availability";
@@ -39,8 +40,7 @@ type CreateBountySubmissionParams = z.infer<
};
type BountyWithRelations = Prisma.BountyGetPayload<{
- include: {
- groups: true;
+ include: typeof bountyEligibilityIncludes & {
submissions: true;
};
}>;
@@ -69,6 +69,11 @@ export class BountySubmissionHandler {
defaultGroupId: true;
};
};
+ programPartnerTags: {
+ select: {
+ partnerTagId: true;
+ };
+ };
};
}>;
@@ -118,6 +123,11 @@ export class BountySubmissionHandler {
defaultGroupId: true,
},
},
+ programPartnerTags: {
+ select: {
+ partnerTagId: true,
+ },
+ },
},
}),
@@ -125,7 +135,7 @@ export class BountySubmissionHandler {
bountyId: this.bountyId,
programId: this.programId,
include: {
- groups: true,
+ ...bountyEligibilityIncludes,
submissions: {
where: {
partnerId: this.partner.id,
diff --git a/apps/web/lib/bounty/api/get-bounties-by-groups.ts b/apps/web/lib/bounty/api/get-bounties-by-groups.ts
deleted file mode 100644
index 68dec8dfce..0000000000
--- a/apps/web/lib/bounty/api/get-bounties-by-groups.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { prisma } from "@/lib/prisma";
-import { Bounty } from "@prisma/client";
-
-export async function getBountiesByGroups({
- programId,
- groupIds,
-}: {
- programId: string;
- groupIds: string[];
-}) {
- const bounties = await prisma.bounty.findMany({
- where: {
- programId,
- AND: [
- {
- OR: [
- { groups: { none: {} } },
- { groups: { some: { groupId: { in: groupIds } } } },
- ],
- },
- ],
- },
- include: {
- groups: true,
- },
- });
-
- const bountiesByGroups: Record<string, Bounty[]> = {};
-
- // Note: global bounties are not included here
- for (const groupId of groupIds) {
- bountiesByGroups[groupId] = bounties.filter((bounty) =>
- bounty.groups.some((g) => g.groupId === groupId),
- );
- }
-
- return bountiesByGroups;
-}
diff --git a/apps/web/lib/bounty/api/get-bounties-for-partner.ts b/apps/web/lib/bounty/api/get-bounties-for-partner.ts
index 467244f872..372389702c 100644
--- a/apps/web/lib/bounty/api/get-bounties-for-partner.ts
+++ b/apps/web/lib/bounty/api/get-bounties-for-partner.ts
@@ -4,7 +4,8 @@ import {
} from "@/lib/partners/aggregate-partner-links-stats";
import { prisma } from "@/lib/prisma";
import { PartnerBountySchema } from "@/lib/zod/schemas/partner-profile";
-import { Program, ProgramEnrollment } from "@prisma/client";
+import { pluck } from "@dub/utils";
+import { Program, ProgramEnrollment, ProgramPartnerTag } from "@prisma/client";
import * as z from "zod/v4";
import {
bountyEligibilityIncludes,
@@ -20,16 +21,19 @@ type GetBountiesForPartnerParams = Pick<
> & {
links: PartnerLink[];
program: Pick<Program, "id" | "defaultGroupId">;
+ programPartnerTags: Pick<ProgramPartnerTag, "partnerTagId">[];
};
export async function getBountiesForPartner({
program,
links,
+ programPartnerTags,
...programEnrollment
}: GetBountiesForPartnerParams) {
const { groupId, partnerId, totalCommissions, createdAt } = programEnrollment;
const partnerGroupId = groupId || program.defaultGroupId;
+ const partnerTagIds = pluck(programPartnerTags, "partnerTagId");
const bounties = await prisma.bounty.findMany({
where: {
@@ -45,7 +49,10 @@ export async function getBountiesForPartner({
},
{
AND: [
- buildBountyEligibilityWhere(partnerGroupId),
+ buildBountyEligibilityWhere({
+ groupId: partnerGroupId,
+ partnerTagIds,
+ }),
buildBountyActivePeriodWhere(),
],
},
@@ -82,7 +89,10 @@ export async function getBountiesForPartner({
canPartnerSeeBounty({
program,
bounty,
- programEnrollment,
+ programEnrollment: {
+ ...programEnrollment,
+ programPartnerTags,
+ },
}),
);
diff --git a/apps/web/lib/bounty/api/get-bounty-submission-upload-url.ts b/apps/web/lib/bounty/api/get-bounty-submission-upload-url.ts
index be9bc0b74c..216a5d02c3 100644
--- a/apps/web/lib/bounty/api/get-bounty-submission-upload-url.ts
+++ b/apps/web/lib/bounty/api/get-bounty-submission-upload-url.ts
@@ -4,8 +4,11 @@ import { ratelimit } from "@/lib/upstash";
import { submissionRequirementsSchema } from "@/lib/zod/schemas/bounties";
import { ACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";
import { nanoid, R2_URL } from "@dub/utils";
-import { ProgramEnrollment } from "@prisma/client";
-import { canPartnerSubmitBounty } from "./bounty-availability";
+import { ProgramEnrollment, ProgramPartnerTag } from "@prisma/client";
+import {
+ bountyEligibilityIncludes,
+ canPartnerSubmitBounty,
+} from "./bounty-availability";
import { getBountyOrThrow } from "./get-bounty-or-throw";
const MAX_ATTEMPTS = 25;
@@ -19,7 +22,9 @@ type GetBountySubmissionUploadUrlParams = {
programEnrollment: Pick<
ProgramEnrollment,
"programId" | "partnerId" | "groupId" | "status" | "createdAt"
- >;
+ > & {
+ programPartnerTags: Pick<ProgramPartnerTag, "partnerTagId">[];
+ };
};
const MAX_UPLOAD_SIZE_BYTES = 5 * 1024 * 1024;
@@ -87,11 +92,7 @@ export async function getBountySubmissionUploadUrl({
bountyId,
programId,
include: {
- groups: {
- select: {
- groupId: true,
- },
- },
+ ...bountyEligibilityIncludes,
program: {
select: {
id: true,
diff --git a/apps/web/lib/bounty/api/get-bounty-with-details.ts b/apps/web/lib/bounty/api/get-bounty-with-details.ts
index e7e3f23980..b22c93b226 100644
--- a/apps/web/lib/bounty/api/get-bounty-with-details.ts
+++ b/apps/web/lib/bounty/api/get-bounty-with-details.ts
@@ -38,7 +38,19 @@ export const getBountyWithDetails = async ({
WHERE bountyId = b.id
),
JSON_ARRAY()
- ) AS \`groups\`
+ ) AS \`groups\`,
+
+ -- Bounty partner tags
+ COALESCE(
+ (
+ SELECT JSON_ARRAYAGG(
+ JSON_OBJECT('id', partnerTagId)
+ )
+ FROM BountyPartnerTag
+ WHERE bountyId = b.id
+ ),
+ JSON_ARRAY()
+ ) AS \`partnerTags\`
FROM Bounty b
LEFT JOIN Workflow wf ON wf.id = b.workflowId
@@ -77,5 +89,6 @@ export const getBountyWithDetails = async ({
performanceScope,
performanceCondition,
groups: bounty.groups.filter((group) => group !== null) ?? [],
+ partnerTags: bounty.partnerTags.filter((tag) => tag !== null) ?? [],
};
};
diff --git a/apps/web/lib/bounty/api/transform-bounty.ts b/apps/web/lib/bounty/api/transform-bounty.ts
new file mode 100644
index 0000000000..0e7c25aa7d
--- /dev/null
+++ b/apps/web/lib/bounty/api/transform-bounty.ts
@@ -0,0 +1,27 @@
+import { BountyGroup, BountyPartnerTag, Workflow } from "@prisma/client";
+
+export type TransformBountyInput = {
+ groups: Pick<BountyGroup, "groupId">[];
+ partnerTags: Pick<BountyPartnerTag, "partnerTagId">[];
+ workflow?: Pick<Workflow, "triggerConditions"> | null;
+};
+
+export const transformBounty = <T extends TransformBountyInput>(bounty: T) => {
+ const groups = bounty.groups.map(({ groupId }) => ({ id: groupId }));
+
+ const partnerTags = bounty.partnerTags.map(({ partnerTagId }) => ({
+ id: partnerTagId,
+ }));
+
+ const triggerConditions = bounty.workflow?.triggerConditions;
+ const performanceCondition = Array.isArray(triggerConditions)
+ ? triggerConditions[0] ?? null
+ : null;
+
+ return {
+ ...bounty,
+ groups,
+ partnerTags,
+ performanceCondition,
+ };
+};
diff --git a/apps/web/lib/bounty/api/trigger-draft-bounty-submissions.ts b/apps/web/lib/bounty/api/trigger-draft-bounty-submissions.ts
index b8e143b787..93cc5acc98 100644
--- a/apps/web/lib/bounty/api/trigger-draft-bounty-submissions.ts
+++ b/apps/web/lib/bounty/api/trigger-draft-bounty-submissions.ts
@@ -1,8 +1,13 @@
import { qstash } from "@/lib/cron";
import { prisma } from "@/lib/prisma";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
-import { Bounty } from "@prisma/client";
-import { getBountiesByGroups } from "./get-bounties-by-groups";
+import { APP_DOMAIN_WITH_NGROK, pluck, prettyPrint } from "@dub/utils";
+import { BountyPerformanceScope, BountyType } from "@prisma/client";
+import {
+ bountyEligibilityIncludes,
+ buildBountyActivePeriodWhere,
+ buildBountyEligibilityWhere,
+ isPartnerEligibleForBounty,
+} from "./bounty-availability";
// Trigger the creation of draft submissions for performance bounties that uses lifetime stats for the given partners
export async function triggerDraftBountySubmissionCreation({
@@ -22,83 +27,119 @@ export async function triggerDraftBountySubmissionCreation({
select: {
partnerId: true,
groupId: true,
+ createdAt: true,
+ status: true,
+ programPartnerTags: {
+ select: {
+ partnerTagId: true,
+ },
+ },
},
});
if (programEnrollments.length === 0) {
+ console.log(
+ `No program enrollments found to trigger draft bounty submissions.`,
+ );
return;
}
const groupIds = [
...new Set(
- programEnrollments
- .map(({ groupId }) => groupId)
- .filter((id): id is string => id !== null),
+ pluck(programEnrollments, "groupId").filter(
+ (id): id is string => id !== null,
+ ),
),
];
- const bountiesByGroups = await getBountiesByGroups({
- programId,
- groupIds,
- });
+ const partnerTagIds = [
+ ...new Set(
+ pluck(programEnrollments, "programPartnerTags").flatMap((tags) =>
+ tags.map((tag) => tag.partnerTagId),
+ ),
+ ),
+ ];
- const partnersByGroup = programEnrollments.reduce(
- (acc, enrollment) => {
- if (enrollment.groupId) {
- acc[enrollment.groupId] = [
- ...(acc[enrollment.groupId] || []),
- enrollment.partnerId,
- ];
- }
- return acc;
+ // Find the bounties matching the criteria
+ const bounties = await prisma.bounty.findMany({
+ where: {
+ programId,
+ archivedAt: null,
+ type: BountyType.performance,
+ performanceScope: BountyPerformanceScope.lifetime,
+ AND: [
+ buildBountyEligibilityWhere({ groupId: groupIds, partnerTagIds }),
+ buildBountyActivePeriodWhere(),
+ ],
},
- {} as Record<string, string[]>,
- );
+ include: {
+ ...bountyEligibilityIncludes,
+ },
+ });
- for (const groupId in bountiesByGroups) {
- const eligibleBounties = bountiesByGroups[groupId].filter((bounty) =>
- isEligiblePerformanceBounty(bounty),
+ if (bounties.length === 0) {
+ console.log(
+ `No eligible performance bounties found to trigger draft bounty submissions.`,
);
+ return;
+ }
- if (eligibleBounties.length === 0) {
- console.log(
- `No eligible bounties found for the group ${groupId}. Either there are no performance bounties, or there are no lifetime stats.`,
- );
- continue;
- }
+ const program = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ select: {
+ defaultGroupId: true,
+ },
+ });
+
+ // Find the partners eligible for each bounty
+ const bountySubmissionCreationData: {
+ bountyId: string;
+ partnerIds: string[];
+ }[] = [];
- const groupPartnerIds = partnersByGroup[groupId] || [];
+ for (const bounty of bounties) {
+ const eligiblePartnerIds = programEnrollments
+ .filter((programEnrollment) =>
+ isPartnerEligibleForBounty({ program, bounty, programEnrollment }),
+ )
+ .map((e) => e.partnerId);
- if (groupPartnerIds.length === 0) {
- console.log(`No partners found for the group ${groupId}.`);
- continue;
+ if (eligiblePartnerIds.length > 0) {
+ bountySubmissionCreationData.push({
+ bountyId: bounty.id,
+ partnerIds: eligiblePartnerIds,
+ });
}
+ }
+ if (bountySubmissionCreationData.length === 0) {
console.log(
- `Found ${eligibleBounties.length} eligible bounties for the group ${groupId}.`,
- );
-
- await Promise.allSettled(
- eligibleBounties.map((bounty) =>
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/upsert-draft-submissions`,
- body: {
- bountyId: bounty.id,
- partnerIds: groupPartnerIds,
- },
- }),
- ),
+ `No eligible partners found to trigger draft bounty submissions.`,
);
+ return;
}
-}
-function isEligiblePerformanceBounty(bounty: Bounty) {
- const now = new Date();
+ console.log(
+ `Triggering draft bounty submissions for ${bountySubmissionCreationData.length} bounties.`,
+ prettyPrint(bountySubmissionCreationData),
+ );
- if (bounty.type !== "performance") return false;
- if (bounty.performanceScope === "new") return false;
- if (bounty.startsAt && bounty.startsAt > now) return false;
- if (bounty.endsAt && bounty.endsAt <= now) return false;
+ const results = await Promise.allSettled(
+ bountySubmissionCreationData.map(({ bountyId, partnerIds }) =>
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/upsert-draft-submissions`,
+ body: {
+ bountyId,
+ partnerIds,
+ },
+ }),
+ ),
+ );
- return true;
+ console.log(
+ `Triggered draft bounty submissions for ${results.length} bounties.`,
+ results,
+ );
}
diff --git a/apps/web/lib/bounty/api/upsert-draft-bounty-submissions.ts b/apps/web/lib/bounty/api/upsert-draft-bounty-submissions.ts
index 7c5c05968d..63af4faa6d 100644
--- a/apps/web/lib/bounty/api/upsert-draft-bounty-submissions.ts
+++ b/apps/web/lib/bounty/api/upsert-draft-bounty-submissions.ts
@@ -87,7 +87,7 @@ export function planDraftBountySubmissionUpserts({
const conditionMet = evaluateWorkflowConditions({
conditions: [condition],
- attributes: {
+ context: {
[condition.attribute]: performanceCount,
},
});
diff --git a/apps/web/lib/integrations/shopify/create-sale.ts b/apps/web/lib/integrations/shopify/create-sale.ts
index 7f78bd96a0..d4b20f2b80 100644
--- a/apps/web/lib/integrations/shopify/create-sale.ts
+++ b/apps/web/lib/integrations/shopify/create-sale.ts
@@ -166,8 +166,7 @@ export async function createShopifySale({
waitUntil(
Promise.allSettled([
executeWorkflows({
- trigger: "partnerMetricsUpdated",
- reason: "sale",
+ event: "saleRecorded",
identity: {
workspaceId: workspaceId,
programId: link.programId,
diff --git a/apps/web/lib/integrations/shopify/process-order.ts b/apps/web/lib/integrations/shopify/process-order.ts
index 49ca9ba511..1a9f2866d6 100644
--- a/apps/web/lib/integrations/shopify/process-order.ts
+++ b/apps/web/lib/integrations/shopify/process-order.ts
@@ -172,8 +172,7 @@ export async function attributeViaDiscountCode({
await Promise.allSettled([
executeWorkflows({
- trigger: "partnerMetricsUpdated",
- reason: "lead",
+ event: "leadRecorded",
identity: {
workspaceId: workspace.id,
programId: link.programId,
diff --git a/apps/web/lib/swr/use-partners-count-by-groupids.ts b/apps/web/lib/swr/use-partners-count-by-groupids.ts
index c4dfdfc7e2..6920ec7ac2 100644
--- a/apps/web/lib/swr/use-partners-count-by-groupids.ts
+++ b/apps/web/lib/swr/use-partners-count-by-groupids.ts
@@ -1,38 +1,21 @@
-import { useMemo } from "react";
import usePartnersCount from "./use-partners-count";
export function usePartnersCountByGroupIds({
groupIds,
+ partnerTagIds,
}: {
groupIds?: string[] | null;
+ partnerTagIds?: string[] | null;
}) {
- const { partnersCount: groupCount, loading } = usePartnersCount<
- | {
- groupId: string;
- _count: number;
- }[]
- | undefined
- >({
- groupBy: "groupId",
+ const { partnersCount, loading } = usePartnersCount<number | undefined>({
ignoreParams: true,
- enabled: !!groupIds,
+ status: "approved",
+ ...(groupIds?.length ? { groupId: groupIds } : {}),
+ ...(partnerTagIds?.length ? { partnerTagId: partnerTagIds } : {}),
});
- const totalPartners = useMemo(() => {
- if (!groupIds || groupIds.length === 0) {
- // if no groups set, return all partners
- return groupCount?.reduce((acc, curr) => acc + curr._count, 0) ?? 0;
- }
-
- return (
- groupCount?.reduce((acc, curr) => {
- if (groupIds.includes(curr.groupId)) {
- return acc + curr._count;
- }
- return acc;
- }, 0) ?? 0
- );
- }, [groupCount, groupIds]);
-
- return { totalPartners, loading };
+ return {
+ totalPartners: partnersCount ?? 0,
+ loading,
+ };
}
diff --git a/apps/web/lib/webhook/sample-events/bounty-created.json b/apps/web/lib/webhook/sample-events/bounty-created.json
index dd9f943f5e..f43dc63b53 100644
--- a/apps/web/lib/webhook/sample-events/bounty-created.json
+++ b/apps/web/lib/webhook/sample-events/bounty-created.json
@@ -22,5 +22,6 @@
{
"id": "grp_1K2E25381GVMG7HHM057TB92F"
}
- ]
+ ],
+ "partnerTags": []
}
diff --git a/apps/web/lib/webhook/sample-events/bounty-updated.json b/apps/web/lib/webhook/sample-events/bounty-updated.json
index 109d1a74cf..1b45be1876 100644
--- a/apps/web/lib/webhook/sample-events/bounty-updated.json
+++ b/apps/web/lib/webhook/sample-events/bounty-updated.json
@@ -22,5 +22,6 @@
{
"id": "grp_1K2E25381GVMG7HHM057TB92F"
}
- ]
+ ],
+ "partnerTags": []
}
diff --git a/apps/web/lib/zod/schemas/bounties.ts b/apps/web/lib/zod/schemas/bounties.ts
index e3f0b32b14..ea3cfff66d 100644
--- a/apps/web/lib/zod/schemas/bounties.ts
+++ b/apps/web/lib/zod/schemas/bounties.ts
@@ -23,6 +23,7 @@ import { awardBountyConditionSchema } from "../../api/workflows/award-bounty/sch
import { CommissionSchema } from "./commissions";
import { GroupSchema } from "./groups";
import { booleanQuerySchema, getPaginationQuerySchema } from "./misc";
+import { PartnerTagSchema } from "./partner-tags";
import { EnrolledPartnerSchema } from "./partners";
import { UserSchema } from "./users";
import { nullableCountSchema, parseDateSchema } from "./utils";
@@ -201,7 +202,14 @@ export const createBountySchema = z.object({
groupIds: z
.array(z.string())
.nullable()
- .describe("The IDs of the partner groups that this bounty is available to"),
+ .describe(
+ "The IDs of the partner groups that this bounty is available to.",
+ ),
+ partnerTagIds: z
+ .array(z.string())
+ .nullable()
+ .optional()
+ .describe("The IDs of the partner tags that this bounty is available to."),
sendNotificationEmails: z
.boolean()
.optional()
@@ -216,7 +224,12 @@ export const updateBountySchema = createBountySchema
type: true,
performanceScope: true,
})
- .partial();
+ .partial()
+ // Avoid inheriting create's `.default(absolute)` — Zod still applies defaults
+ // on omitted keys after `.partial()`, which would coerce relative bounties.
+ .extend({
+ startMode: z.enum(BountyStartMode).optional(),
+ });
export const BountySubmissionFileSchema = z.object({
url: z.httpUrl().describe("The URL of the uploaded file."),
@@ -244,6 +257,7 @@ export const BountySchema = z.object({
submissionRequirements: submissionRequirementsSchema.nullable().default(null),
socialMetricsLastSyncedAt: z.date().nullable().optional(),
groups: z.array(GroupSchema.pick({ id: true })),
+ partnerTags: z.array(PartnerTagSchema.pick({ id: true })),
});
export const getBountiesQuerySchema = z.object({
diff --git a/apps/web/lib/zod/schemas/campaigns.ts b/apps/web/lib/zod/schemas/campaigns.ts
index 9d2a1b2f08..6259c740a1 100644
--- a/apps/web/lib/zod/schemas/campaigns.ts
+++ b/apps/web/lib/zod/schemas/campaigns.ts
@@ -4,9 +4,10 @@ import {
} from "@/lib/email/parse-campaign-from-address";
import { CampaignStatus, CampaignType } from "@prisma/client";
import * as z from "zod/v4";
-import { sendCampaignConditionSchema } from "../../api/workflows/send-campaign/schema";
+import { sendCampaignConditionsSchema } from "../../api/workflows/send-campaign/schema";
import { GroupSchema } from "./groups";
import { getPaginationQuerySchema } from "./misc";
+import { PartnerTagSchema } from "./partner-tags";
import { EnrolledPartnerSchema } from "./partners";
import { parseDateSchema } from "./utils";
@@ -50,8 +51,9 @@ export const CampaignSchema = z.object({
bodyJson: z.record(z.string(), z.any()),
type: z.enum(CampaignType),
status: z.enum(CampaignStatus),
- triggerCondition: sendCampaignConditionSchema.nullable().default(null),
+ triggerConditions: sendCampaignConditionsSchema.nullable().default(null),
groups: z.array(GroupSchema.pick({ id: true })),
+ partnerTags: z.array(PartnerTagSchema.pick({ id: true })),
scheduledAt: z.date().nullable(),
createdAt: z.date(),
updatedAt: z.date(),
@@ -67,6 +69,7 @@ export const CampaignListSchema = z.object({
createdAt: z.date(),
updatedAt: z.date(),
groups: z.array(GroupSchema.pick({ id: true })),
+ partnerTags: z.array(PartnerTagSchema.pick({ id: true })),
});
export const createCampaignSchema = z.object({
@@ -83,8 +86,9 @@ export const updateCampaignSchema = z
preview: z.string().nullish(),
from: campaignFromSchema,
bodyJson: z.record(z.string(), z.any()),
- triggerCondition: sendCampaignConditionSchema.nullish(),
+ triggerConditions: sendCampaignConditionsSchema.nullish(),
groupIds: z.array(z.string()).nullable(),
+ partnerTagIds: z.array(z.string()).nullable(),
scheduledAt: parseDateSchema.nullish(),
status: z.enum([
CampaignStatus.draft,
@@ -101,12 +105,12 @@ export const getCampaignsQuerySchema = z
type: z.enum(CampaignType).optional(),
status: z.enum(CampaignStatus).optional(),
search: z.string().optional(),
- triggerCondition: z
+ triggerConditions: z
.string()
.pipe(
z.preprocess(
(input: string) => JSON.parse(input),
- sendCampaignConditionSchema,
+ sendCampaignConditionsSchema,
),
)
.optional(),
diff --git a/apps/web/lib/zod/schemas/partner-profile.ts b/apps/web/lib/zod/schemas/partner-profile.ts
index f55fa8030d..f8dee55ddc 100644
--- a/apps/web/lib/zod/schemas/partner-profile.ts
+++ b/apps/web/lib/zod/schemas/partner-profile.ts
@@ -161,6 +161,7 @@ export const partnerBountySubmissionSchema = BountySubmissionSchema.extend({
export const PartnerBountySchema = BountySchema.omit({
groups: true,
+ partnerTags: true,
socialMetricsLastSyncedAt: true,
}).extend({
startsAt: z.date(), // Always resolved to the partner's effective start date (never null)
diff --git a/apps/web/lib/zod/schemas/workflows.ts b/apps/web/lib/zod/schemas/workflows.ts
index c84bd6aeb1..c6daae0626 100644
--- a/apps/web/lib/zod/schemas/workflows.ts
+++ b/apps/web/lib/zod/schemas/workflows.ts
@@ -1,34 +1,12 @@
-import {
- WORKFLOW_ATTRIBUTE_KEYS,
- WorkflowAttributeKey,
-} from "@/lib/api/workflows/attribute-definitions";
+import { WORKFLOW_ATTRIBUTE_KEYS } from "@/lib/api/workflows/attribute-definitions";
import {
WORKFLOW_OPERATOR_KEYS,
WORKFLOW_OPERATORS,
} from "@/lib/api/workflows/operator-definitions";
-import { WorkflowTrigger } from "@prisma/client";
import * as z from "zod/v4";
-export const WORKFLOW_ATTRIBUTE_TRIGGER: Record<
- WorkflowAttributeKey,
- WorkflowTrigger
-> = {
- totalLeads: WorkflowTrigger.partnerMetricsUpdated,
- totalConversions: WorkflowTrigger.partnerMetricsUpdated,
- totalSaleAmount: WorkflowTrigger.partnerMetricsUpdated,
- totalCommissions: WorkflowTrigger.partnerMetricsUpdated,
- partnerEnrolledDays: WorkflowTrigger.partnerEnrolled,
- partnerJoined: WorkflowTrigger.partnerEnrolled,
- partnerGroup: WorkflowTrigger.partnerMetricsUpdated,
-} as const;
-
-export const SCHEDULED_WORKFLOW_TRIGGERS: WorkflowTrigger[] = [
- "partnerEnrolled",
-];
-
-export const WORKFLOW_SCHEDULES: Partial<Record<WorkflowTrigger, string>> = {
- partnerEnrolled: "0 */12 * * *", // every 12 hours
-};
+// Cron for scheduled workflows that use partnerEnrolledDays conditions
+export const PARTNER_ENROLLED_WORKFLOW_CRON = "0 */12 * * *"; // every 12 hours
export enum WORKFLOW_ACTION_TYPES {
AwardBounty = "awardBounty",
diff --git a/apps/web/playwright/api/bounties/bounties.spec.ts b/apps/web/playwright/api/bounties/bounties.spec.ts
index 86c9384be5..2dee72deef 100644
--- a/apps/web/playwright/api/bounties/bounties.spec.ts
+++ b/apps/web/playwright/api/bounties/bounties.spec.ts
@@ -1,3 +1,5 @@
+import { createId } from "@/lib/api/create-id";
+import { prisma } from "@/lib/prisma";
import type { BountyProps } from "@/lib/types";
import { expect } from "@playwright/test";
import { BountyStartMode, type Program } from "@prisma/client";
@@ -17,6 +19,7 @@ type BountyJson = Omit<
endsAt: string | null;
submissionsOpenAt: string | null;
socialMetricsLastSyncedAt?: string | null;
+ partnerTags: { id: string }[];
};
type ProgramFixture = Pick<Program, "id" | "defaultGroupId">;
@@ -60,6 +63,21 @@ async function deleteBounty(api: ApiClient, id: string | undefined) {
await api.delete(`/api/bounties/${id}`);
}
+async function createPartnerTag(programId: string) {
+ return prisma.partnerTag.create({
+ data: {
+ id: createId({ prefix: "ptag_" }),
+ programId,
+ name: randomName("tag"),
+ },
+ });
+}
+
+async function deletePartnerTag(id: string | undefined) {
+ if (!id) return;
+ await prisma.partnerTag.delete({ where: { id } });
+}
+
const expectedBountyDefaults = {
id: expect.any(String),
endsAt: null,
@@ -72,6 +90,7 @@ const expectedBountyDefaults = {
performanceCondition: null,
performanceScope: null,
socialMetricsLastSyncedAt: null,
+ partnerTags: [],
};
const unprocessable = (message: string) => ({
@@ -651,6 +670,19 @@ test("POST /bounties – relative with endsAfterDays", async ({
startsAt: null,
endsAfterDays: 180,
});
+
+ const { status: descriptionPatchStatus, data: descriptionUpdated } =
+ await api.patch<BountyJson>(`/api/bounties/${id}`, {
+ description: "updated description only",
+ });
+
+ expect(descriptionPatchStatus).toEqual(200);
+ expect(descriptionUpdated).toMatchObject({
+ startMode: BountyStartMode.relative,
+ startsAt: null,
+ endsAfterDays: 180,
+ description: "updated description only",
+ });
} finally {
await deleteBounty(api, id);
}
@@ -765,6 +797,111 @@ test("POST /bounties – invalid group IDs", async ({ api, program }) => {
).toEqual(badRequest("Invalid group IDs detected: invalid-group-id"));
});
+test("POST /bounties – invalid partner tag IDs", async ({ api, program }) => {
+ expect(
+ await api.post("/api/bounties", {
+ ...bountyPayload(program, {
+ partnerTagIds: ["invalid-partner-tag-id"],
+ }),
+ }),
+ ).toEqual(
+ badRequest("Invalid partner tag IDs detected: invalid-partner-tag-id"),
+ );
+});
+
+test("POST /bounties – with partnerTagIds null returns empty partnerTags", async ({
+ api,
+ program,
+}) => {
+ let id: string | undefined;
+
+ try {
+ const { status, data } = await createBounty(api, program, {
+ partnerTagIds: null,
+ });
+ id = data.id;
+
+ expect(status).toEqual(200);
+ expect(data.partnerTags).toEqual([]);
+ } finally {
+ await deleteBounty(api, id);
+ }
+});
+
+test("POST /bounties – with valid partnerTagIds", async ({ api, program }) => {
+ let id: string | undefined;
+ let partnerTagId: string | undefined;
+
+ try {
+ const partnerTag = await createPartnerTag(program.id);
+ partnerTagId = partnerTag.id;
+
+ const { status, data } = await createBounty(api, program, {
+ partnerTagIds: [partnerTag.id],
+ });
+ id = data.id;
+
+ expect(status).toEqual(200);
+ expect(data.partnerTags).toEqual([{ id: partnerTag.id }]);
+ } finally {
+ await deleteBounty(api, id);
+ await deletePartnerTag(partnerTagId);
+ }
+});
+
+test("PATCH /bounties/{bountyId} – clear partner tags", async ({
+ api,
+ program,
+}) => {
+ let id: string | undefined;
+ let partnerTagId: string | undefined;
+
+ try {
+ const partnerTag = await createPartnerTag(program.id);
+ partnerTagId = partnerTag.id;
+
+ const { data: created } = await createBounty(api, program, {
+ partnerTagIds: [partnerTag.id],
+ });
+ id = created.id;
+
+ expect(created.partnerTags).toEqual([{ id: partnerTag.id }]);
+
+ const { status, data } = await api.patch<BountyJson>(
+ `/api/bounties/${id}`,
+ { partnerTagIds: null },
+ );
+
+ expect(status).toEqual(200);
+ expect(data.partnerTags).toEqual([]);
+ } finally {
+ await deleteBounty(api, id);
+ await deletePartnerTag(partnerTagId);
+ }
+});
+
+test("PATCH /bounties/{bountyId} – invalid partner tag IDs", async ({
+ api,
+ program,
+}) => {
+ let id: string | undefined;
+
+ try {
+ const { data: created } = await createBounty(api, program);
+ id = created.id;
+
+ expect(
+ await api.patch(`/api/bounties/${id}`, {
+ partnerTagIds: ["invalid-partner-tag-id"],
+ }),
+ ).toEqual(
+ badRequest("Invalid partner tag IDs detected: invalid-partner-tag-id"),
+ );
+ } finally {
+ await deleteBounty(api, id);
+ }
+});
+
test("POST /bounties – maxSubmissions below minimum is rejected", async ({
api,
program,
diff --git a/apps/web/playwright/workspaces/onboarding-dub-partners.spec.ts b/apps/web/playwright/workspaces/onboarding-dub-partners.spec.ts
index 3410513b67..f879253c8c 100644
--- a/apps/web/playwright/workspaces/onboarding-dub-partners.spec.ts
+++ b/apps/web/playwright/workspaces/onboarding-dub-partners.spec.ts
@@ -129,11 +129,12 @@ test.describe("Dub Partners onboarding", () => {
mimeType: "image/png",
buffer: MINIMAL_PNG,
});
- await expect
- .poll(async () => page.locator('img[alt="Preview"]').count(), {
- timeout: 30_000,
- })
- .toBeGreaterThan(0);
+ // skipping this for now since it's a bit flaky
+ // await expect
+ // .poll(async () => page.locator('img[alt="Preview"]').count(), {
+ // timeout: 30_000,
+ // })
+ // .toBeGreaterThan(0);
await page
.getByTestId("onboarding-program-destination-url")
diff --git a/apps/web/prisma/schema/bounty.prisma b/apps/web/prisma/schema/bounty.prisma
index ea6d298615..9e2fed99d3 100644
--- a/apps/web/prisma/schema/bounty.prisma
+++ b/apps/web/prisma/schema/bounty.prisma
@@ -59,6 +59,7 @@ model Bounty {
submissions BountySubmission[]
groups BountyGroup[]
+ partnerTags BountyPartnerTag[]
program Program @relation(fields: [programId], references: [id], onDelete: Cascade)
workflow Workflow? @relation(fields: [workflowId], references: [id], onDelete: Cascade)
emails NotificationEmail[]
@@ -78,6 +79,18 @@ model BountyGroup {
@@index([groupId])
}
+model BountyPartnerTag {
+ id String @id @default(cuid())
+ bountyId String
+ partnerTagId String
+
+ bounty Bounty @relation(fields: [bountyId], references: [id], onDelete: Cascade)
+ partnerTag PartnerTag @relation(fields: [partnerTagId], references: [id], onDelete: Cascade)
+
+ @@unique([bountyId, partnerTagId])
+ @@index(partnerTagId)
+}
+
model BountySubmission {
id String @id
programId String
diff --git a/apps/web/prisma/schema/campaign.prisma b/apps/web/prisma/schema/campaign.prisma
index db1182b1af..7f94a4e060 100644
--- a/apps/web/prisma/schema/campaign.prisma
+++ b/apps/web/prisma/schema/campaign.prisma
@@ -36,6 +36,7 @@ model Campaign {
program Program @relation(fields: [programId], references: [id])
workflow Workflow? @relation(fields: [workflowId], references: [id], onDelete: Cascade)
groups CampaignGroup[]
+ partnerTags CampaignPartnerTag[]
emails NotificationEmail[]
@@index(programId)
@@ -52,3 +53,15 @@ model CampaignGroup {
@@unique([campaignId, groupId])
@@index(groupId)
}
+
+model CampaignPartnerTag {
+ id String @id @default(cuid())
+ campaignId String
+ partnerTagId String
+
+ campaign Campaign @relation(fields: [campaignId], references: [id], onDelete: Cascade)
+ partnerTag PartnerTag @relation(fields: [partnerTagId], references: [id], onDelete: Cascade)
+
+ @@unique([campaignId, partnerTagId])
+ @@index(partnerTagId)
+}
diff --git a/apps/web/prisma/schema/tag.prisma b/apps/web/prisma/schema/tag.prisma
index 67b7f05a85..2a24a9da13 100644
--- a/apps/web/prisma/schema/tag.prisma
+++ b/apps/web/prisma/schema/tag.prisma
@@ -32,8 +32,10 @@ model PartnerTag {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
- program Program? @relation(fields: [programId], references: [id], onDelete: Cascade)
- programPartnerTags ProgramPartnerTag[]
+ program Program? @relation(fields: [programId], references: [id], onDelete: Cascade)
+ programPartnerTags ProgramPartnerTag[]
+ campaignPartnerTags CampaignPartnerTag[]
+ bountyPartnerTags BountyPartnerTag[]
@@unique([programId, name])
@@index(programId)
diff --git a/apps/web/prisma/schema/workflow.prisma b/apps/web/prisma/schema/workflow.prisma
index dbe88017ae..679bee227f 100644
--- a/apps/web/prisma/schema/workflow.prisma
+++ b/apps/web/prisma/schema/workflow.prisma
@@ -10,15 +10,15 @@ enum WorkflowTrigger {
}
model Workflow {
- id String @id
+ id String @id
programId String
name String?
- trigger WorkflowTrigger
+ trigger WorkflowTrigger?
triggerConditions Json
actions Json
disabledAt DateTime?
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
program Program @relation(fields: [programId], references: [id], onDelete: Cascade)
bounty Bounty?
diff --git a/apps/web/scripts/dev/seed-partner-enrollment.ts b/apps/web/scripts/dev/seed-partner-enrollment.ts
index 22809c9b62..d3831597e2 100644
--- a/apps/web/scripts/dev/seed-partner-enrollment.ts
+++ b/apps/web/scripts/dev/seed-partner-enrollment.ts
@@ -51,6 +51,9 @@ async function main() {
userId,
partnerId,
role: "owner",
+ notificationPreferences: {
+ create: {},
+ },
},
});
diff --git a/apps/web/scripts/dev/seed.ts b/apps/web/scripts/dev/seed.ts
index da25d2eaa4..4683c622ba 100644
--- a/apps/web/scripts/dev/seed.ts
+++ b/apps/web/scripts/dev/seed.ts
@@ -413,7 +413,25 @@ const createPartners = async (data: SeedData) => {
})),
});
+ // Query PartnerUsers to get the actual IDs (since createMany doesn't return them)
+ const partnerUsers = await prisma.partnerUser.findMany({
+ where: {
+ partnerId: { in: partners.map((p) => p.id) },
+ userId: { in: partners.map((p) => p.user.id) },
+ },
+ });
+
+ const { count: notificationPreferencesCount } =
+ await prisma.partnerNotificationPreferences.createMany({
+ data: partnerUsers.map((partnerUser) => ({
+ partnerUserId: partnerUser.id,
+ })),
+ });
+
console.log(`Created ${partnerCount} partners`);
+ console.log(
+ `Created ${notificationPreferencesCount} partner notification preferences`,
+ );
// Create program enrollments
const { count: enrollmentCount } = await prisma.programEnrollment.createMany({
diff --git a/apps/web/scripts/programs/backfill-reuse-commission.ts b/apps/web/scripts/programs/backfill-reuse-commission.ts
index 4ce58e1bd2..b8473ba5a6 100644
--- a/apps/web/scripts/programs/backfill-reuse-commission.ts
+++ b/apps/web/scripts/programs/backfill-reuse-commission.ts
@@ -320,8 +320,7 @@ async function main() {
if (["lead", "sale"].includes(commissionType)) {
await Promise.allSettled([
executeWorkflows({
- trigger: "partnerMetricsUpdated",
- reason: "commission",
+ event: "commissionRecorded",
identity: {
workspaceId,
programId,
diff --git a/apps/web/tests/campaigns/index.test.ts b/apps/web/tests/campaigns/index.test.ts
index a32365c8ae..4fed75034f 100644
--- a/apps/web/tests/campaigns/index.test.ts
+++ b/apps/web/tests/campaigns/index.test.ts
@@ -1,18 +1,20 @@
import { Campaign, CampaignList } from "@/lib/types";
import { updateCampaignSchema } from "@/lib/zod/schemas/campaigns";
import { E2E_PARTNER_GROUP } from "tests/utils/resource";
-import { describe, expect, onTestFinished, test } from "vitest";
+import { afterAll, describe, expect, test } from "vitest";
import * as z from "zod/v4";
import { IntegrationHarness } from "../utils/integration";
const campaign: z.infer<typeof updateCampaignSchema> = {
name: "Updated Test Campaign",
subject: "Updated Test Subject",
- triggerCondition: {
- attribute: "totalConversions",
- operator: "gte",
- value: 50,
- },
+ triggerConditions: [
+ {
+ attribute: "totalConversions",
+ operator: "gte",
+ value: 50,
+ },
+ ],
bodyJson: {
type: "doc",
content: [
@@ -37,6 +39,7 @@ const expectedCampaign: Partial<Campaign> = {
from: null,
scheduledAt: null,
groups: [{ id: E2E_PARTNER_GROUP.id }],
+ partnerTags: [],
createdAt: expect.any(String),
updatedAt: expect.any(String),
};
@@ -46,6 +49,11 @@ describe.sequential("/campaigns/**", async () => {
const { http } = await h.init();
let campaignId = "";
+ const createdCampaignIds: string[] = [];
+
+ afterAll(async () => {
+ await Promise.all(createdCampaignIds.map((id) => h.deleteCampaign(id)));
+ });
test("POST /campaigns - create draft campaign", async () => {
const { status, data } = await http.post<{ id: string }>({
@@ -55,12 +63,15 @@ describe.sequential("/campaigns/**", async () => {
},
});
+ if (data?.id) {
+ campaignId = data.id;
+ createdCampaignIds.push(data.id);
+ }
+
expect(status).toEqual(201);
expect(data).toMatchObject({
id: expect.any(String),
});
-
- campaignId = data.id;
});
test("PATCH /campaigns/[campaignId] - update campaign content", async () => {
@@ -93,6 +104,40 @@ describe.sequential("/campaigns/**", async () => {
});
});
+ test("PATCH /campaigns/[campaignId] - invalid partner tag IDs", async () => {
+ const { status, data } = await http.patch({
+ path: `/campaigns/${campaignId}`,
+ body: {
+ partnerTagIds: ["invalid-partner-tag-id"],
+ },
+ });
+
+ expect(status).toEqual(400);
+ expect(data).toMatchObject({
+ error: {
+ message: "Invalid partner tag IDs detected: invalid-partner-tag-id",
+ code: "bad_request",
+ },
+ });
+ });
+
+ test("PATCH /campaigns/[campaignId] - clear partner tags", async () => {
+ const { status, data: updatedCampaign } = await http.patch<Campaign>({
+ path: `/campaigns/${campaignId}`,
+ body: {
+ partnerTagIds: null,
+ },
+ });
+
+ expect(status).toEqual(200);
+ expect(updatedCampaign).toStrictEqual({
+ ...expectedCampaign,
+ id: campaignId,
+ status: "draft",
+ partnerTags: [],
+ });
+ });
+
test("PATCH /campaigns/[campaignId] - publish campaign", async () => {
const { status, data: publishedCampaign } = await http.patch<Campaign>({
path: `/campaigns/${campaignId}`,
@@ -146,13 +191,13 @@ describe.sequential("/campaigns/**", async () => {
path: `/campaigns/${campaignId}/duplicate`,
});
+ if (data?.id) {
+ createdCampaignIds.push(data.id);
+ }
+
expect(status).toEqual(200);
expect(data.id).toBeDefined();
- onTestFinished(async () => {
- await h.deleteCampaign(data.id);
- });
-
const { data: duplicatedCampaign } = await http.get<Campaign>({
path: `/campaigns/${data.id}`,
});
diff --git a/apps/web/tests/workflows/comparison-operators.test.ts b/apps/web/tests/workflows/comparison-operators.test.ts
index c89880e55b..33fdbe8814 100644
--- a/apps/web/tests/workflows/comparison-operators.test.ts
+++ b/apps/web/tests/workflows/comparison-operators.test.ts
@@ -18,6 +18,24 @@ describe("WORKFLOW_OPERATORS.gte.evaluate", () => {
});
});
+describe("WORKFLOW_OPERATORS.lte.evaluate", () => {
+ const { evaluate } = WORKFLOW_OPERATORS.lte;
+
+ it("returns true when attribute value is less than or equal to condition", () => {
+ expect(evaluate(10, 10)).toBe(true);
+ expect(evaluate(9, 10)).toBe(true);
+ expect(evaluate(0, 0)).toBe(true);
+ });
+
+ it("returns false when attribute value is greater than condition", () => {
+ expect(evaluate(11, 10)).toBe(false);
+ });
+
+ it("returns false when condition value is not a number", () => {
+ expect(evaluate(10, { min: 1, max: 5 })).toBe(false);
+ });
+});
+
describe("WORKFLOW_OPERATORS.between.evaluate", () => {
const { evaluate } = WORKFLOW_OPERATORS.between;
@@ -63,6 +81,28 @@ describe("WORKFLOW_OPERATORS.gte.validate", () => {
});
});
+describe("WORKFLOW_OPERATORS.lte.validate", () => {
+ const { validate } = WORKFLOW_OPERATORS.lte;
+
+ it("accepts a non-negative number", () => {
+ expect(() => validate(0)).not.toThrow();
+ expect(() => validate(1)).not.toThrow();
+ expect(() => validate(100)).not.toThrow();
+ });
+
+ it("rejects non-number, NaN, and negative values", () => {
+ expect(() => validate({ min: 1, max: 5 })).toThrow(
+ "Please enter a value greater than or equal to 0.",
+ );
+ expect(() => validate(NaN)).toThrow(
+ "Please enter a value greater than or equal to 0.",
+ );
+ expect(() => validate(-1)).toThrow(
+ "Please enter a value greater than or equal to 0.",
+ );
+ });
+});
+
describe("WORKFLOW_OPERATORS.between.validate", () => {
const { validate } = WORKFLOW_OPERATORS.between;
diff --git a/apps/web/tests/workflows/find-groups-with-matching-rules.test.ts b/apps/web/tests/workflows/find-groups-with-matching-rules.test.ts
index 6621c41552..bfd88d3449 100644
--- a/apps/web/tests/workflows/find-groups-with-matching-rules.test.ts
+++ b/apps/web/tests/workflows/find-groups-with-matching-rules.test.ts
@@ -2,9 +2,21 @@ import { findGroupsWithMatchingRules } from "@/lib/api/groups/find-groups-with-m
import type { GroupMoveRules } from "@/lib/api/workflows/move-group/types";
import { describe, expect, it } from "vitest";
-const groupA = { id: "grp_a", name: "Group A", moveRules: [] as GroupMoveRules };
-const groupB = { id: "grp_b", name: "Group B", moveRules: [] as GroupMoveRules };
-const groupC = { id: "grp_c", name: "Group C", moveRules: [] as GroupMoveRules };
+const groupA = {
+ id: "grp_a",
+ name: "Group A",
+ moveRules: [] as GroupMoveRules,
+};
+const groupB = {
+ id: "grp_b",
+ name: "Group B",
+ moveRules: [] as GroupMoveRules,
+};
+const groupC = {
+ id: "grp_c",
+ name: "Group C",
+ moveRules: [] as GroupMoveRules,
+};
describe("findGroupsWithMatchingRules", () => {
it("returns no conflict when partnerGroup eq/in filters are disjoint", () => {
diff --git a/apps/web/tests/workflows/move-group-workflow.test.ts b/apps/web/tests/workflows/move-group-workflow.test.ts
index 3bf3f497e7..f0192d76c4 100644
--- a/apps/web/tests/workflows/move-group-workflow.test.ts
+++ b/apps/web/tests/workflows/move-group-workflow.test.ts
@@ -67,7 +67,6 @@ describe.sequential("Workflow - MoveGroup", async () => {
});
expect(workflow).not.toBeNull();
- expect(workflow.trigger).toBe("partnerMetricsUpdated");
expect(workflow.disabledAt).toBeNull();
const workflowActions = workflow.actions as any[];
diff --git a/apps/web/tests/workflows/send-campaign-workflow.test.ts b/apps/web/tests/workflows/send-campaign-workflow.test.ts
index 6cce53977e..e8dcd03132 100644
--- a/apps/web/tests/workflows/send-campaign-workflow.test.ts
+++ b/apps/web/tests/workflows/send-campaign-workflow.test.ts
@@ -5,6 +5,7 @@ import { describe, expect, onTestFinished, test } from "vitest";
import { randomPartnerEmail } from "../utils/helpers";
import { IntegrationHarness } from "../utils/integration";
import { E2E_USER_ID } from "../utils/resource";
+import { verifyCampaignSent } from "./utils/verify-campaign-sent";
describe.sequential("Workflow - SendCampaign", async () => {
const h = new IntegrationHarness();
@@ -48,11 +49,13 @@ describe.sequential("Workflow - SendCampaign", async () => {
},
],
},
- triggerCondition: {
- attribute: "partnerEnrolledDays",
- operator: "gte",
- value: 1,
- },
+ triggerConditions: [
+ {
+ attribute: "partnerEnrolledDays",
+ operator: "gte",
+ value: 1,
+ },
+ ],
},
});
@@ -75,7 +78,6 @@ describe.sequential("Workflow - SendCampaign", async () => {
});
expect(workflow).not.toBeNull();
- expect(workflow.trigger).toBe("partnerEnrolled");
expect(workflow.disabledAt).toBeNull();
const workflowActions = workflow.actions as any[];
@@ -121,11 +123,13 @@ describe.sequential("Workflow - SendCampaign", async () => {
},
],
},
- triggerCondition: {
- attribute: "partnerEnrolledDays",
- operator: "gte",
- value: 1,
- },
+ triggerConditions: [
+ {
+ attribute: "partnerEnrolledDays",
+ operator: "gte",
+ value: 1,
+ },
+ ],
},
});
@@ -173,11 +177,13 @@ describe.sequential("Workflow - SendCampaign", async () => {
},
],
},
- triggerCondition: {
- attribute: "partnerEnrolledDays",
- operator: "gte",
- value: 1,
- },
+ triggerConditions: [
+ {
+ attribute: "partnerEnrolledDays",
+ operator: "gte",
+ value: 1,
+ },
+ ],
status: "active",
},
});
@@ -229,11 +235,13 @@ describe.sequential("Workflow - SendCampaign", async () => {
},
],
},
- triggerCondition: {
- attribute: "partnerEnrolledDays",
- operator: "gte",
- value: 1,
- },
+ triggerConditions: [
+ {
+ attribute: "partnerEnrolledDays",
+ operator: "gte",
+ value: 1,
+ },
+ ],
status: "active",
},
});
@@ -298,11 +306,13 @@ describe.sequential("Workflow - SendCampaign", async () => {
},
],
},
- triggerCondition: {
- attribute: "partnerEnrolledDays",
- operator: "gte",
- value: 1,
- },
+ triggerConditions: [
+ {
+ attribute: "partnerEnrolledDays",
+ operator: "gte",
+ value: 1,
+ },
+ ],
status: "active",
},
});
@@ -374,11 +384,13 @@ describe.sequential("Workflow - SendCampaign", async () => {
},
],
},
- triggerCondition: {
- attribute: "partnerEnrolledDays",
- operator: "gte",
- value: 1,
- },
+ triggerConditions: [
+ {
+ attribute: "partnerEnrolledDays",
+ operator: "gte",
+ value: 1,
+ },
+ ],
status: "active",
},
});
@@ -453,11 +465,13 @@ describe.sequential("Workflow - SendCampaign", async () => {
},
],
},
- triggerCondition: {
- attribute: "partnerEnrolledDays",
- operator: "gte",
- value: 1,
- },
+ triggerConditions: [
+ {
+ attribute: "partnerEnrolledDays",
+ operator: "gte",
+ value: 1,
+ },
+ ],
status: "active",
},
});
@@ -551,11 +565,13 @@ describe.sequential("Workflow - SendCampaign", async () => {
},
],
},
- triggerCondition: {
- attribute: "partnerEnrolledDays",
- operator: "gte",
- value: 1,
- },
+ triggerConditions: [
+ {
+ attribute: "partnerEnrolledDays",
+ operator: "gte",
+ value: 1,
+ },
+ ],
status: "active",
},
});
@@ -587,4 +603,274 @@ describe.sequential("Workflow - SendCampaign", async () => {
expect(pausedWorkflow.disabledAt).not.toBeNull();
});
+
+ test("Campaign supports mixed enrollment and metric conditions", async () => {
+ const { status: createStatus, data: campaign } = await http.post<{
+ id: string;
+ }>({
+ path: "/campaigns",
+ body: {
+ type: "transactional",
+ },
+ });
+
+ expect(createStatus).toEqual(201);
+
+ const campaignId = campaign.id;
+
+ onTestFinished(async () => {
+ await h.deleteCampaign(campaignId);
+ });
+
+ const { status: updateStatus, data: updatedCampaign } =
+ await http.patch<Campaign>({
+ path: `/campaigns/${campaignId}`,
+ body: {
+ name: "E2E Mixed Conditions Campaign",
+ subject: "Still no leads after 30 days",
+ bodyJson: {
+ type: "doc",
+ content: [
+ {
+ type: "paragraph",
+ content: [{ type: "text", text: "Let's get those leads!" }],
+ },
+ ],
+ },
+ triggerConditions: [
+ {
+ attribute: "partnerEnrolledDays",
+ operator: "gte",
+ value: 30,
+ },
+ {
+ attribute: "totalLeads",
+ operator: "lte",
+ value: 0,
+ },
+ ],
+ status: "active",
+ },
+ });
+
+ expect(updateStatus).toEqual(200);
+
+ const { data: workflow } = await http.get<any>({
+ path: "/e2e/workflows",
+ query: { campaignId },
+ });
+
+ expect(workflow).not.toBeNull();
+ expect(workflow.disabledAt).toBeNull();
+
+ const conditions = workflow.triggerConditions as any[];
+ expect(conditions).toHaveLength(2);
+ expect(conditions[0]).toMatchObject({
+ attribute: "partnerEnrolledDays",
+ operator: "gte",
+ value: 30,
+ });
+ expect(conditions[1]).toMatchObject({
+ attribute: "totalLeads",
+ operator: "lte",
+ value: 0,
+ });
+
+ // Response shape exposes the full conditions array
+ expect((updatedCampaign as any).triggerConditions).toEqual(conditions);
+ });
+
+ test(
+ "Cron sends campaign when all conditions are met (AND)",
+ { timeout: 90000 },
+ async () => {
+ const { status: createStatus, data: campaign } = await http.post<{
+ id: string;
+ }>({
+ path: "/campaigns",
+ body: {
+ type: "transactional",
+ },
+ });
+
+ expect(createStatus).toEqual(201);
+
+ const campaignId = campaign.id;
+
+ onTestFinished(async () => {
+ await http.delete({
+ path: "/e2e/notification-emails",
+ query: { campaignId },
+ });
+ await h.deleteCampaign(campaignId);
+ });
+
+ await http.patch({
+ path: `/campaigns/${campaignId}`,
+ body: {
+ name: "E2E AND Match Campaign",
+ subject: "You got a lead!",
+ bodyJson: {
+ type: "doc",
+ content: [
+ {
+ type: "paragraph",
+ content: [{ type: "text", text: "Congrats on your first lead!" }],
+ },
+ ],
+ },
+ triggerConditions: [
+ {
+ attribute: "partnerEnrolledDays",
+ operator: "gte",
+ value: 1,
+ },
+ {
+ attribute: "totalLeads",
+ operator: "gte",
+ value: 1,
+ },
+ ],
+ status: "active",
+ },
+ });
+
+ const { data: workflow } = await http.get<any>({
+ path: "/e2e/workflows",
+ query: { campaignId },
+ });
+
+ expect(workflow).not.toBeNull();
+
+ const { status: partnerStatus, data: partner } =
+ await http.post<EnrolledPartnerProps>({
+ path: "/partners",
+ body: {
+ name: "E2E Test Partner - AND Match",
+ email: randomPartnerEmail(),
+ },
+ });
+
+ expect(partnerStatus).toEqual(201);
+ expect(partner.links).not.toBeNull();
+
+ // API-created partners have no PartnerUser, and campaign emails only
+ // go to users with an email. Create one and set link.leads directly so
+ // the cron AND conditions are met without racing Tinybird waitUntil.
+ const { status: enrollmentStatus } = await http.patch({
+ path: "/e2e/enrollments",
+ body: {
+ partnerId: partner.id,
+ createdAt: subHours(new Date(), 18).toISOString(),
+ leads: 1,
+ createUser: true,
+ },
+ });
+
+ expect(enrollmentStatus).toEqual(200);
+
+ const { status, data } = await http.post<{ message: string }>({
+ path: `/e2e/trigger-workflow/${workflow.id}`,
+ });
+
+ expect(status).toEqual(200);
+ expect(data.message).toContain("Finished executing workflow");
+
+ await verifyCampaignSent({
+ http,
+ campaignId,
+ partnerId: partner.id,
+ });
+ },
+ );
+
+ test("Cron doesn't send when metric condition fails (AND)", async () => {
+ const { status: createStatus, data: campaign } = await http.post<{
+ id: string;
+ }>({
+ path: "/campaigns",
+ body: {
+ type: "transactional",
+ },
+ });
+
+ expect(createStatus).toEqual(201);
+
+ const campaignId = campaign.id;
+
+ onTestFinished(async () => {
+ await h.deleteCampaign(campaignId);
+ });
+
+ await http.patch({
+ path: `/campaigns/${campaignId}`,
+ body: {
+ name: "E2E AND Partial Match Campaign",
+ subject: "Should not be sent",
+ bodyJson: {
+ type: "doc",
+ content: [
+ {
+ type: "paragraph",
+ content: [{ type: "text", text: "Test" }],
+ },
+ ],
+ },
+ triggerConditions: [
+ {
+ attribute: "partnerEnrolledDays",
+ operator: "gte",
+ value: 1,
+ },
+ {
+ attribute: "totalLeads",
+ operator: "gte",
+ value: 1,
+ },
+ ],
+ status: "active",
+ },
+ });
+
+ const { data: workflow } = await http.get<any>({
+ path: "/e2e/workflows",
+ query: { campaignId },
+ });
+
+ expect(workflow).not.toBeNull();
+
+ const { status: partnerStatus, data: partner } =
+ await http.post<EnrolledPartnerProps>({
+ path: "/partners",
+ body: {
+ name: "E2E Test Partner - AND Partial",
+ email: randomPartnerEmail(),
+ },
+ });
+
+ expect(partnerStatus).toEqual(201);
+
+ // Enrollment window matches, but totalLeads is 0 — AND fails
+ await http.patch({
+ path: "/e2e/enrollments",
+ body: {
+ partnerId: partner.id,
+ createdAt: subHours(new Date(), 18).toISOString(),
+ },
+ });
+
+ const { status, data: triggerData } = await http.post<{ message: string }>({
+ path: `/e2e/trigger-workflow/${workflow.id}`,
+ });
+
+ expect(status).toEqual(200);
+ expect(triggerData.message).toContain("Finished executing workflow");
+
+ const { data: emailsSent } = await http.get<any[]>({
+ path: "/e2e/notification-emails",
+ query: { campaignId, partnerId: partner.id },
+ });
+
+ expect(emailsSent).toHaveLength(0);
+ });
});
diff --git a/apps/web/ui/layout/sidebar/app-sidebar-nav.tsx b/apps/web/ui/layout/sidebar/app-sidebar-nav.tsx
index 0e3a30eb22..d5da8a07f8 100644
--- a/apps/web/ui/layout/sidebar/app-sidebar-nav.tsx
+++ b/apps/web/ui/layout/sidebar/app-sidebar-nav.tsx
@@ -113,7 +113,7 @@ const NAV_GROUPS: SidebarNavGroups<SidebarNavData> = ({
active: pathname.startsWith(`/${slug}/links`),
};
- return (defaultProduct ?? "links") === "links"
+ return defaultProduct === "links"
? [linksGroup, programGroup]
: [programGroup, linksGroup];
};
diff --git a/apps/web/ui/partners/audience-limit-select-shell.tsx b/apps/web/ui/partners/audience-limit-select-shell.tsx
new file mode 100644
index 0000000000..87f0e7e866
--- /dev/null
+++ b/apps/web/ui/partners/audience-limit-select-shell.tsx
@@ -0,0 +1,169 @@
+"use client";
+
+import {
+ AnimatedSizeContainer,
+ Check2,
+ LoadingSpinner,
+ Magnifier,
+ ScrollContainer,
+ Switch,
+} from "@dub/ui";
+import { cn } from "@dub/utils";
+import { Command } from "cmdk";
+import { ReactNode } from "react";
+
+export function AudienceLimitSelectShell<T extends { id: string }>({
+ selectedIds,
+ setSelectedIds,
+ title,
+ enabledDescription,
+ disabledDescription,
+ searchPlaceholder,
+ search,
+ setSearch,
+ useAsync,
+ items,
+ getItemValue,
+ renderItem,
+}: {
+ selectedIds: string[] | null;
+ setSelectedIds: (ids: string[] | null) => void;
+ title: string;
+ enabledDescription: string;
+ disabledDescription: string;
+ searchPlaceholder: string;
+ search: string;
+ setSearch: (search: string) => void;
+ useAsync: boolean;
+ items: T[] | undefined;
+ getItemValue: (item: T) => string;
+ renderItem: (item: T) => ReactNode;
+}) {
+ const limitEnabled = selectedIds !== null;
+
+ return (
+ <div>
+ <div className="flex items-start gap-3">
+ <div className="flex h-5 shrink-0 items-center">
+ <Switch
+ checked={limitEnabled}
+ fn={(checked) => {
+ if (checked) {
+ setSelectedIds(selectedIds ?? []);
+ } else {
+ setSelectedIds(null);
+ setSearch("");
+ }
+ }}
+ trackDimensions="w-8 h-4"
+ thumbDimensions="w-3 h-3"
+ thumbTranslate="translate-x-4"
+ />
+ </div>
+ <div className="flex flex-col gap-0.5">
+ <span className="text-content-emphasis text-sm font-medium">
+ {title}
+ </span>
+ <p className="text-content-subtle text-xs">
+ {limitEnabled ? enabledDescription : disabledDescription}
+ </p>
+ </div>
+ </div>
+
+ <AnimatedSizeContainer
+ height
+ transition={{ ease: "easeInOut", duration: 0.1 }}
+ className="-m-0.5"
+ >
+ <div className="p-0.5">
+ {limitEnabled && (
+ <div className="mt-3">
+ <Command loop shouldFilter={!useAsync}>
+ <label className="relative flex grow items-center overflow-hidden rounded-lg border border-neutral-300 focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500">
+ <Magnifier className="text-content-default ml-3 size-3.5 shrink-0" />
+ <Command.Input
+ placeholder={searchPlaceholder}
+ value={search}
+ onValueChange={setSearch}
+ className="grow border-none px-2 text-neutral-900 placeholder-neutral-400 focus:outline-none focus:ring-0 sm:text-sm"
+ />
+ </label>
+ <div className="mt-1">
+ <ScrollContainer className="h-[190px]">
+ <Command.List className="flex w-full flex-col gap-1 p-1">
+ {items !== undefined ? (
+ <>
+ {items.map((item) => {
+ const checked = Boolean(
+ selectedIds?.includes(item.id),
+ );
+
+ return (
+ <Command.Item
+ key={item.id}
+ value={getItemValue(item)}
+ onSelect={() =>
+ setSelectedIds(
+ selectedIds?.includes(item.id)
+ ? selectedIds.length === 1
+ ? null // Revert to null if there will be no ids selected
+ : selectedIds.filter(
+ (id) => id !== item.id,
+ )
+ : [...(selectedIds ?? []), item.id],
+ )
+ }
+ className={cn(
+ "flex cursor-pointer select-none items-center gap-3 whitespace-nowrap rounded-md px-3 py-2.5 text-left text-sm text-neutral-700",
+ "data-[selected=true]:bg-neutral-100",
+ )}
+ >
+ <div
+ className={cn(
+ "border-border-emphasis flex size-4 shrink-0 items-center justify-center rounded border bg-white transition-colors duration-75",
+ checked &&
+ "border-neutral-900 bg-neutral-900",
+ )}
+ >
+ {checked && (
+ <span className="sr-only">Checked</span>
+ )}
+ <Check2
+ className={cn(
+ "size-2.5 text-white transition-[transform,opacity] duration-75",
+ !checked && "scale-75 opacity-0",
+ )}
+ />
+ </div>
+ {renderItem(item)}
+ </Command.Item>
+ );
+ })}
+ {!useAsync ? (
+ <Command.Empty className="flex min-h-12 items-center justify-center text-sm text-neutral-500">
+ No matches
+ </Command.Empty>
+ ) : items.length === 0 ? (
+ <div className="flex min-h-12 items-center justify-center text-sm text-neutral-500">
+ No matches
+ </div>
+ ) : null}
+ </>
+ ) : (
+ <Command.Loading>
+ <div className="flex h-12 items-center justify-center">
+ <LoadingSpinner />
+ </div>
+ </Command.Loading>
+ )}
+ </Command.List>
+ </ScrollContainer>
+ </div>
+ </Command>
+ </div>
+ )}
+ </div>
+ </AnimatedSizeContainer>
+ </div>
+ );
+}
diff --git a/apps/web/ui/partners/bounties/bounty-eligibility-summary.tsx b/apps/web/ui/partners/bounties/bounty-eligibility-summary.tsx
new file mode 100644
index 0000000000..6589e3e9f4
--- /dev/null
+++ b/apps/web/ui/partners/bounties/bounty-eligibility-summary.tsx
@@ -0,0 +1,174 @@
+"use client";
+
+import useGroups from "@/lib/swr/use-groups";
+import { usePartnerTags } from "@/lib/swr/use-partner-tags";
+import { GroupProps, PartnerTagProps } from "@/lib/types";
+import { GroupColorCircle } from "@/ui/partners/groups/group-color-circle";
+import { DynamicTooltipWrapper, ScrollableTooltipContent } from "@dub/ui";
+import { Tag, Users6 } from "@dub/ui/icons";
+import { cn } from "@dub/utils";
+import { useMemo } from "react";
+
+type BountyEligibilitySummaryProps = {
+ groups: { id: string }[];
+ partnerTags: { id: string }[];
+ iconClassName?: string;
+ className?: string;
+};
+
+export function BountyEligibilitySummary({
+ groups: bountyGroups,
+ partnerTags: bountyPartnerTags,
+ iconClassName = "size-3.5",
+ className,
+}: BountyEligibilitySummaryProps) {
+ const { groups } = useGroups();
+ const { partnerTags } = usePartnerTags();
+
+ const eligibleGroups = useMemo(() => {
+ if (!groups || bountyGroups.length === 0) {
+ return [];
+ }
+
+ return bountyGroups
+ .map((bountyGroup) => groups.find((g) => g.id === bountyGroup.id))
+ .filter((g): g is GroupProps => g !== undefined);
+ }, [groups, bountyGroups]);
+
+ const eligibleTags = useMemo(() => {
+ if (!partnerTags || bountyPartnerTags.length === 0) {
+ return [];
+ }
+
+ return bountyPartnerTags
+ .map((bountyTag) => partnerTags.find((t) => t.id === bountyTag.id))
+ .filter((t): t is PartnerTagProps => t !== undefined);
+ }, [partnerTags, bountyPartnerTags]);
+
+ const groupsLoading = bountyGroups.length > 0 && !groups;
+ const tagsLoading = bountyPartnerTags.length > 0 && !partnerTags;
+
+ return (
+ <div
+ className={cn(
+ "text-content-subtle flex min-w-0 items-center gap-2 text-sm font-normal",
+ className,
+ )}
+ >
+ <Users6 className={cn("shrink-0", iconClassName)} />
+ <div className="flex min-w-0 items-center gap-1.5">
+ {groupsLoading ? (
+ <div className="h-5 w-24 animate-pulse rounded bg-neutral-200" />
+ ) : (
+ <GroupsLabel
+ bountyGroupCount={bountyGroups.length}
+ eligibleGroups={eligibleGroups}
+ />
+ )}
+
+ {(tagsLoading || bountyPartnerTags.length > 0) && (
+ <>
+ <span className="text-content-muted shrink-0">·</span>
+
+ {tagsLoading ? (
+ <div className="h-5 w-20 animate-pulse rounded bg-neutral-200" />
+ ) : (
+ <TagsLabel eligibleTags={eligibleTags} />
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function GroupsLabel({
+ bountyGroupCount,
+ eligibleGroups,
+}: {
+ bountyGroupCount: number;
+ eligibleGroups: GroupProps[];
+}) {
+ if (bountyGroupCount === 0) {
+ return <span>All groups</span>;
+ }
+
+ if (eligibleGroups.length === 0) {
+ return null;
+ }
+
+ const content = (
+ <div className="flex min-w-0 items-center gap-1.5">
+ <GroupColorCircle group={eligibleGroups[0]} />
+ <span className="truncate">
+ {eligibleGroups[0].name}
+ {eligibleGroups.length > 1 ? ` +${eligibleGroups.length - 1}` : ""}
+ </span>
+ </div>
+ );
+
+ if (eligibleGroups.length === 1) {
+ return content;
+ }
+
+ return (
+ <DynamicTooltipWrapper
+ tooltipProps={{
+ content: (
+ <ScrollableTooltipContent>
+ {eligibleGroups.map((group) => (
+ <div key={group.id} className="flex items-center gap-2">
+ <GroupColorCircle group={group} />
+ <span className="text-sm font-normal text-neutral-700">
+ {group.name}
+ </span>
+ </div>
+ ))}
+ </ScrollableTooltipContent>
+ ),
+ }}
+ >
+ {content}
+ </DynamicTooltipWrapper>
+ );
+}
+
+function TagsLabel({ eligibleTags }: { eligibleTags: PartnerTagProps[] }) {
+ if (eligibleTags.length === 0) {
+ return null;
+ }
+
+ const content = (
+ <div className="flex min-w-0 items-center gap-1.5">
+ <Tag className="size-3.5 shrink-0" />
+ <span className="truncate">
+ {eligibleTags[0].name}
+ {eligibleTags.length > 1 ? ` +${eligibleTags.length - 1}` : ""}
+ </span>
+ </div>
+ );
+
+ if (eligibleTags.length === 1) {
+ return content;
+ }
+
+ return (
+ <DynamicTooltipWrapper
+ tooltipProps={{
+ content: (
+ <ScrollableTooltipContent>
+ {eligibleTags.map((tag) => (
+ <div key={tag.id} className="flex items-center gap-2">
+ <span className="text-sm font-normal text-neutral-700">
+ {tag.name}
+ </span>
+ </div>
+ ))}
+ </ScrollableTooltipContent>
+ ),
+ }}
+ >
+ {content}
+ </DynamicTooltipWrapper>
+ );
+}
diff --git a/apps/web/ui/partners/groups/partner-groups-select.tsx b/apps/web/ui/partners/groups/partner-groups-select.tsx
new file mode 100644
index 0000000000..e72a3d8904
--- /dev/null
+++ b/apps/web/ui/partners/groups/partner-groups-select.tsx
@@ -0,0 +1,111 @@
+"use client";
+
+import useGroups from "@/lib/swr/use-groups";
+import { GroupProps } from "@/lib/types";
+import { GROUPS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/groups";
+import { AudienceLimitSelectShell } from "@/ui/partners/audience-limit-select-shell";
+import { GroupColorCircle } from "@/ui/partners/groups/group-color-circle";
+import { useCallback, useEffect, useState } from "react";
+import { useDebounce } from "use-debounce";
+
+type GroupWithPartners = GroupProps & { totalPartners?: number };
+
+export function PartnerGroupsSelect({
+ selectedGroupIds,
+ setSelectedGroupIds,
+}: {
+ selectedGroupIds: string[] | null;
+ setSelectedGroupIds: (groupIds: string[] | null) => void;
+}) {
+ const [search, setSearch] = useState("");
+ const [useAsync, setUseAsync] = useState(false);
+ const [debouncedSearch] = useDebounce(search, 500);
+ const [shouldSortGroups, setShouldSortGroups] = useState(false);
+ const [sortedGroups, setSortedGroups] = useState<
+ GroupWithPartners[] | undefined
+ >(undefined);
+
+ const { groups } = useGroups<GroupWithPartners>({
+ query: { ...(useAsync ? { search: debouncedSearch } : undefined) },
+ });
+
+ const { groups: selectedGroups } = useGroups<GroupWithPartners>({
+ query: { groupIds: selectedGroupIds ?? undefined },
+ enabled: Boolean(selectedGroupIds?.length),
+ });
+
+ useEffect(
+ () =>
+ setUseAsync(
+ Boolean(groups && !useAsync && groups.length >= GROUPS_MAX_PAGE_SIZE),
+ ),
+ [groups, useAsync],
+ );
+
+ const sortGroups = useCallback(
+ (groups: GroupWithPartners[], search: string) => {
+ return search === ""
+ ? [
+ ...groups.filter((g) => selectedGroupIds?.includes(g.id)),
+ ...groups.filter((g) => !selectedGroupIds?.includes(g.id)),
+ ]
+ : groups;
+ },
+ [selectedGroupIds],
+ );
+
+ useEffect(() => {
+ if (
+ !shouldSortGroups ||
+ !groups ||
+ (selectedGroupIds?.length && !selectedGroups)
+ )
+ return;
+
+ setSortedGroups(
+ sortGroups(
+ [
+ ...(selectedGroups ?? []),
+ ...groups.filter(
+ (g) => !selectedGroups?.some((sg) => sg.id === g.id),
+ ),
+ ],
+ search,
+ ),
+ );
+ setShouldSortGroups(false);
+ }, [
+ shouldSortGroups,
+ groups,
+ selectedGroupIds,
+ selectedGroups,
+ sortGroups,
+ search,
+ ]);
+
+ useEffect(() => setShouldSortGroups(true), [groups]);
+
+ return (
+ <AudienceLimitSelectShell
+ selectedIds={selectedGroupIds}
+ setSelectedIds={setSelectedGroupIds}
+ title="Limit to specific groups"
+ enabledDescription="Select eligible groups"
+ disabledDescription="All groups are eligible"
+ searchPlaceholder="Search groups..."
+ search={search}
+ setSearch={setSearch}
+ useAsync={useAsync}
+ items={sortedGroups}
+ getItemValue={(group) => `${group.name}::${group.slug}`}
+ renderItem={(group) => (
+ <>
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <GroupColorCircle group={group} />
+ <span className="min-w-0 truncate">{group.name}</span>
+ </div>
+ </>
+ )}
+ />
+ );
+}
diff --git a/apps/web/ui/partners/partner-tags-select.tsx b/apps/web/ui/partners/partner-tags-select.tsx
new file mode 100644
index 0000000000..fdd3c4483a
--- /dev/null
+++ b/apps/web/ui/partners/partner-tags-select.tsx
@@ -0,0 +1,107 @@
+"use client";
+
+import { usePartnerTags } from "@/lib/swr/use-partner-tags";
+import { PartnerTagProps } from "@/lib/types";
+import { PARTNER_TAGS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/partner-tags";
+import { AudienceLimitSelectShell } from "@/ui/partners/audience-limit-select-shell";
+import { useCallback, useEffect, useState } from "react";
+import { useDebounce } from "use-debounce";
+
+export function PartnerTagsSelect({
+ selectedPartnerTagIds,
+ setSelectedPartnerTagIds,
+}: {
+ selectedPartnerTagIds: string[] | null;
+ setSelectedPartnerTagIds: (tagIds: string[] | null) => void;
+}) {
+ const [search, setSearch] = useState("");
+ const [useAsync, setUseAsync] = useState(false);
+ const [debouncedSearch] = useDebounce(search, 500);
+ const [shouldSortTags, setShouldSortTags] = useState(false);
+ const [sortedTags, setSortedTags] = useState<PartnerTagProps[] | undefined>(
+ undefined,
+ );
+
+ const { partnerTags } = usePartnerTags({
+ query: useAsync ? { search: debouncedSearch } : undefined,
+ });
+
+ const { partnerTags: selectedTags } = usePartnerTags({
+ query: { ids: selectedPartnerTagIds ?? undefined },
+ enabled: Boolean(selectedPartnerTagIds?.length),
+ });
+
+ useEffect(
+ () =>
+ setUseAsync(
+ Boolean(
+ partnerTags &&
+ !useAsync &&
+ partnerTags.length >= PARTNER_TAGS_MAX_PAGE_SIZE,
+ ),
+ ),
+ [partnerTags, useAsync],
+ );
+
+ const sortTags = useCallback(
+ (tags: PartnerTagProps[], search: string) => {
+ return search === ""
+ ? [
+ ...tags.filter((t) => selectedPartnerTagIds?.includes(t.id)),
+ ...tags.filter((t) => !selectedPartnerTagIds?.includes(t.id)),
+ ]
+ : tags;
+ },
+ [selectedPartnerTagIds],
+ );
+
+ useEffect(() => {
+ if (
+ !shouldSortTags ||
+ !partnerTags ||
+ (selectedPartnerTagIds?.length && !selectedTags)
+ )
+ return;
+
+ setSortedTags(
+ sortTags(
+ [
+ ...(selectedTags ?? []),
+ ...partnerTags.filter(
+ (t) => !selectedTags?.some((st) => st.id === t.id),
+ ),
+ ],
+ search,
+ ),
+ );
+ setShouldSortTags(false);
+ }, [
+ shouldSortTags,
+ partnerTags,
+ selectedPartnerTagIds,
+ selectedTags,
+ sortTags,
+ search,
+ ]);
+
+ useEffect(() => setShouldSortTags(true), [partnerTags]);
+
+ return (
+ <AudienceLimitSelectShell
+ selectedIds={selectedPartnerTagIds}
+ setSelectedIds={setSelectedPartnerTagIds}
+ title="Limit to specific partner tags"
+ enabledDescription="Select eligible partner tags"
+ disabledDescription="All tags are eligible"
+ searchPlaceholder="Search tags..."
+ search={search}
+ setSearch={setSearch}
+ useAsync={useAsync}
+ items={sortedTags}
+ getItemValue={(tag) => `${tag.name}::${tag.id}`}
+ renderItem={(tag) => (
+ <span className="min-w-0 flex-1 truncate">{tag.name}</span>
+ )}
+ />
+ );
+}
diff --git a/apps/web/ui/partners/tags-multi-select.tsx b/apps/web/ui/partners/tags-multi-select.tsx
new file mode 100644
index 0000000000..620d007f70
--- /dev/null
+++ b/apps/web/ui/partners/tags-multi-select.tsx
@@ -0,0 +1,248 @@
+"use client";
+
+import { usePartnerTags } from "@/lib/swr/use-partner-tags";
+import { usePartnerTagsCount } from "@/lib/swr/use-partner-tags-count";
+import { PartnerTagProps } from "@/lib/types";
+import { PARTNER_TAGS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/partner-tags";
+import {
+ AnimatedSizeContainer,
+ Check2,
+ LoadingSpinner,
+ Magnifier,
+ ScrollContainer,
+ Tag as TagIcon,
+ ToggleGroup,
+} from "@dub/ui";
+import { cn } from "@dub/utils";
+import { Command } from "cmdk";
+import { useCallback, useEffect, useState } from "react";
+import { useDebounce } from "use-debounce";
+
+interface TagsMultiSelectProps {
+ selectedPartnerTagIds: string[] | null;
+ setSelectedPartnerTagIds: (tagIds: string[] | null) => void;
+ className?: string;
+}
+
+export function TagsMultiSelect({
+ selectedPartnerTagIds,
+ setSelectedPartnerTagIds,
+ className,
+}: TagsMultiSelectProps) {
+ const [selectedMode, setSelectedMode] = useState<"all" | "select">(
+ selectedPartnerTagIds?.length ? "select" : "all",
+ );
+
+ const [search, setSearch] = useState("");
+ const [useAsync, setUseAsync] = useState(false);
+ const [debouncedSearch] = useDebounce(search, 500);
+
+ const [shouldSortTags, setShouldSortTags] = useState(false);
+ const [sortedTags, setSortedTags] = useState<PartnerTagProps[] | undefined>(
+ undefined,
+ );
+
+ const { partnerTagsCount } = usePartnerTagsCount();
+
+ const { partnerTags } = usePartnerTags({
+ query: useAsync ? { search: debouncedSearch } : undefined,
+ });
+
+ const { partnerTags: selectedTags } = usePartnerTags({
+ query: { ids: selectedPartnerTagIds ?? undefined },
+ enabled: Boolean(selectedPartnerTagIds?.length),
+ });
+
+ // Determine if we should use async loading
+ useEffect(
+ () =>
+ setUseAsync(
+ Boolean(
+ partnerTags &&
+ !useAsync &&
+ partnerTags.length >= PARTNER_TAGS_MAX_PAGE_SIZE,
+ ),
+ ),
+ [partnerTags, useAsync],
+ );
+
+ const sortTags = useCallback(
+ (tags: PartnerTagProps[], search: string) => {
+ return search === ""
+ ? [
+ ...tags.filter((t) => selectedPartnerTagIds?.includes(t.id)),
+ ...tags.filter((t) => !selectedPartnerTagIds?.includes(t.id)),
+ ]
+ : tags;
+ },
+ [selectedPartnerTagIds],
+ );
+
+ // Actually sort the tags when needed
+ useEffect(() => {
+ if (
+ !shouldSortTags ||
+ !partnerTags ||
+ (selectedPartnerTagIds?.length && !selectedTags)
+ )
+ return;
+
+ setSortedTags(
+ sortTags(
+ [
+ ...(selectedTags ?? []),
+ ...partnerTags.filter(
+ (t) => !selectedTags?.some((st) => st.id === t.id),
+ ),
+ ],
+ search,
+ ),
+ );
+ setShouldSortTags(false);
+ }, [
+ shouldSortTags,
+ partnerTags,
+ selectedPartnerTagIds,
+ selectedTags,
+ sortTags,
+ search,
+ ]);
+
+ // Sort when the search-filtered tags change
+ useEffect(() => setShouldSortTags(true), [partnerTags]);
+
+ return (
+ <div className={className}>
+ <ToggleGroup
+ layout={false}
+ className="flex w-full items-center gap-1 rounded-lg border-none bg-neutral-100 p-1"
+ optionClassName="h-8 flex items-center justify-center flex-1 text-sm normal-case"
+ indicatorClassName="bg-white"
+ options={[
+ { value: "all", label: "All tags" },
+ { value: "select", label: "Select tags" },
+ ]}
+ selected={selectedMode}
+ selectAction={(value) => {
+ setSelectedMode(value as "all" | "select");
+ if (value === "all") setSelectedPartnerTagIds(null);
+ }}
+ />
+
+ <div className="mt-2">
+ <AnimatedSizeContainer
+ height
+ transition={{ ease: "easeInOut", duration: 0.1 }}
+ className="-m-0.5"
+ >
+ <div className="p-0.5">
+ {selectedMode === "all" ? (
+ <div className="flex flex-col items-center justify-center px-4 py-6">
+ <div className="text-content-default flex items-center gap-1.5 font-semibold">
+ <TagIcon className="size-4 shrink-0" />
+ {partnerTagsCount === undefined ? (
+ <div className="h-5 w-6 animate-pulse rounded-md bg-neutral-200" />
+ ) : (
+ partnerTagsCount
+ )}
+ </div>
+ <span className="text-content-subtle text-sm font-medium">
+ Tags selected
+ </span>
+ </div>
+ ) : (
+ <Command loop shouldFilter={!useAsync}>
+ <label className="relative flex grow items-center overflow-hidden rounded-lg border border-neutral-300 focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500">
+ <Magnifier className="text-content-default ml-3 size-3.5 shrink-0" />
+ <Command.Input
+ placeholder="Search tags..."
+ value={search}
+ onValueChange={setSearch}
+ className="grow border-none px-2 text-neutral-900 placeholder-neutral-400 focus:outline-none focus:ring-0 sm:text-sm"
+ />
+ </label>
+ <ScrollContainer className="h-[190px]">
+ <Command.List
+ className={cn("flex w-full flex-col gap-1 py-1")}
+ >
+ {sortedTags !== undefined ? (
+ <>
+ {sortedTags.map((tag) => {
+ const checked = Boolean(
+ selectedPartnerTagIds?.includes(tag.id),
+ );
+
+ return (
+ <Command.Item
+ key={tag.id}
+ value={`${tag.name}::${tag.id}`}
+ onSelect={() =>
+ setSelectedPartnerTagIds(
+ selectedPartnerTagIds?.includes(tag.id)
+ ? selectedPartnerTagIds.length === 1
+ ? null // Revert to null if there will be no tags selected
+ : selectedPartnerTagIds.filter(
+ (id) => id !== tag.id,
+ )
+ : [
+ ...(selectedPartnerTagIds ?? []),
+ tag.id,
+ ],
+ )
+ }
+ className={cn(
+ "flex cursor-pointer select-none items-center gap-3 whitespace-nowrap rounded-md px-3 py-2.5 text-left text-sm text-neutral-700",
+ "data-[selected=true]:bg-neutral-100",
+ )}
+ >
+ <div
+ className={cn(
+ "border-border-emphasis flex size-4 shrink-0 items-center justify-center rounded border bg-white transition-colors duration-75",
+ checked &&
+ "border-neutral-900 bg-neutral-900",
+ )}
+ >
+ {checked && (
+ <span className="sr-only">Checked</span>
+ )}
+ <Check2
+ className={cn(
+ "size-2.5 text-white transition-[transform,opacity] duration-75",
+ !checked && "scale-75 opacity-0",
+ )}
+ />
+ </div>
+ <span className="min-w-0 truncate">
+ {tag.name}
+ </span>
+ </Command.Item>
+ );
+ })}
+ {!useAsync ? (
+ <Command.Empty className="flex min-h-12 items-center justify-center text-sm text-neutral-500">
+ No matches
+ </Command.Empty>
+ ) : sortedTags.length === 0 ? (
+ <div className="flex min-h-12 items-center justify-center text-sm text-neutral-500">
+ No matches
+ </div>
+ ) : null}
+ </>
+ ) : (
+ // undefined data / explicit loading state
+ <Command.Loading>
+ <div className="flex h-12 items-center justify-center">
+ <LoadingSpinner />
+ </div>
+ </Command.Loading>
+ )}
+ </Command.List>
+ </ScrollContainer>
+ </Command>
+ )}
+ </div>
+ </AnimatedSizeContainer>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/email/src/index.ts b/packages/email/src/index.ts
index f609603230..9dc3855292 100644
--- a/packages/email/src/index.ts
+++ b/packages/email/src/index.ts
@@ -54,7 +54,9 @@ export const sendBatchEmail = async (
);
return {
- data: null,
+ data: {
+ data: emails.map(() => ({ id: crypto.randomUUID() })),
+ },
error: null,
};
}
diff --git a/packages/utils/src/functions/index.ts b/packages/utils/src/functions/index.ts
index a0f7a6526c..a6661f6853 100644
--- a/packages/utils/src/functions/index.ts
+++ b/packages/utils/src/functions/index.ts
@@ -27,6 +27,7 @@ export * from "./nformatter";
export * from "./normalize-string";
export * from "./parse-filter-value";
export * from "./pick";
+export * from "./pluck";
export * from "./pluralize";
export * from "./pretty-print";
export * from "./process-in-batches";
diff --git a/packages/utils/src/functions/pluck.ts b/packages/utils/src/functions/pluck.ts
new file mode 100644
index 0000000000..668466b99b
--- /dev/null
+++ b/packages/utils/src/functions/pluck.ts
@@ -0,0 +1,8 @@
+// Extracts a property from each object in an array.
+// Example: pluck([{ id: "a" }, { id: "b" }], "id") => ["a", "b"]
+export const pluck = <T, K extends keyof T>(
+ items: readonly T[],
+ key: K,
+): T[K][] => {
+ return items.map((item) => item[key]);
+};