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.

Move partner group workflow tests to Playwright (#4457)

Kiran Kcae764ae3920
diff --git a/apps/web/playwright/api/groups/helpers.ts b/apps/web/playwright/api/groups/helpers.ts
new file mode 100644
index 0000000000..97f23fd7bb
--- /dev/null
+++ b/apps/web/playwright/api/groups/helpers.ts
@@ -0,0 +1,263 @@
+import { prisma } from "@/lib/prisma";
+import type { EnrolledPartnerProps, GroupProps } from "@/lib/types";
+import { nanoid } from "@dub/utils";
+import { expect } from "@playwright/test";
+import type { Workflow } from "@prisma/client";
+import { randomName } from "../../utils";
+import { trackClick, trackLead, trackSale } from "../conversions/helpers";
+import type { ApiClient } from "../fixtures";
+
+export type MoveRule = {
+ attribute: string;
+ operator: string;
+ value: number | string | string[] | { min: number; max: number };
+};
+
+export function uniqueThreshold() {
+ return 10_000 + Math.floor(Math.random() * 1_000_000);
+}
+
+export async function createGroup(
+ api: ApiClient,
+ overrides: Record<string, unknown> = {},
+) {
+ const slug = `g-${nanoid(8).toLowerCase()}`;
+ const { status, data } = await api.post<GroupProps>("/api/groups", {
+ name: randomName("group"),
+ slug,
+ color: "blue",
+ ...overrides,
+ });
+
+ expect(status).toEqual(201);
+ return data;
+}
+
+// Best effort: the response is ignored so cleanup stays safe for groups a test
+// already deleted itself.
+export async function deleteGroup(api: ApiClient, id: string | undefined) {
+ if (!id) return;
+ await api.delete(`/api/groups/${id}`);
+}
+
+export async function setMoveRules(
+ api: ApiClient,
+ groupId: string,
+ moveRules: MoveRule[] | undefined,
+) {
+ return api.patch<GroupProps>(`/api/groups/${groupId}`, {
+ ...(moveRules !== undefined && { moveRules }),
+ });
+}
+
+export async function setGroupMoveDisabledAt(
+ api: ApiClient,
+ {
+ partnerId,
+ groupId,
+ groupMoveDisabledAt,
+ }: {
+ partnerId: string;
+ groupId: string;
+ groupMoveDisabledAt: Date | string;
+ },
+) {
+ const { status } = await api.post(`/api/groups/${groupId}/partners`, {
+ partnerIds: [partnerId],
+ groupMoveDisabledAt,
+ });
+
+ expect(status).toEqual(200);
+}
+
+export async function getGroup(
+ api: ApiClient,
+ groupId: string,
+): Promise<{ status: number; data: GroupProps }> {
+ return api.get<GroupProps>(`/api/groups/${groupId}`);
+}
+
+export async function trackPartnerLead(
+ partner: Pick<EnrolledPartnerProps, "links">,
+) {
+ const link = partner.links![0];
+ const { clickId } = await trackClick({ domain: link.domain, key: link.key });
+
+ return trackLead({ clickId });
+}
+
+export async function trackPartnerSale(
+ partner: Pick<EnrolledPartnerProps, "links">,
+ overrides: Record<string, unknown> = {},
+) {
+ const link = partner.links![0];
+ const { clickId } = await trackClick({ domain: link.domain, key: link.key });
+ const { customer } = await trackLead({ clickId });
+
+ return trackSale({
+ customerExternalId: customer.externalId,
+ ...overrides,
+ });
+}
+
+export async function getGroupWorkflow(
+ groupId: string,
+): Promise<Workflow | null> {
+ return prisma.workflow.findFirst({
+ where: {
+ partnerGroup: {
+ id: groupId,
+ },
+ },
+ });
+}
+
+export async function disableWorkflow(workflowId: string) {
+ return prisma.workflow.update({
+ where: {
+ id: workflowId,
+ },
+ data: {
+ disabledAt: new Date(),
+ },
+ });
+}
+
+export async function getEnrollment({
+ partnerId,
+ programId,
+}: {
+ partnerId: string;
+ programId: string;
+}) {
+ return prisma.programEnrollment.findUniqueOrThrow({
+ where: {
+ partnerId_programId: {
+ partnerId,
+ programId,
+ },
+ },
+ select: {
+ groupId: true,
+ groupMoveDisabledAt: true,
+ leadRewardId: true,
+ saleRewardId: true,
+ discountId: true,
+ clickRewardId: true,
+ referralRewardId: true,
+ },
+ });
+}
+
+export async function expectPartnerInGroup({
+ partnerId,
+ programId,
+ expectedGroupId,
+}: {
+ partnerId: string;
+ programId: string;
+ expectedGroupId: string;
+}) {
+ await expect
+ .poll(async () => {
+ const enrollment = await getEnrollment({ partnerId, programId });
+ return enrollment.groupId;
+ })
+ .toBe(expectedGroupId);
+
+ return getEnrollment({ partnerId, programId });
+}
+
+export async function expectPartnerStaysInGroup({
+ partnerId,
+ programId,
+ expectedGroupId,
+}: {
+ partnerId: string;
+ programId: string;
+ expectedGroupId: string;
+}) {
+ // Give executeWorkflows (waitUntil after /track/lead) time to run (and skip).
+ await new Promise((resolve) => setTimeout(resolve, 5_000));
+
+ const enrollment = await getEnrollment({ partnerId, programId });
+ expect(enrollment.groupId).toBe(expectedGroupId);
+ return enrollment;
+}
+
+export async function seedLinkStats(
+ linkId: string,
+ {
+ leads,
+ conversions,
+ saleAmount,
+ }: {
+ leads?: number;
+ conversions?: number;
+ saleAmount?: number;
+ },
+) {
+ await prisma.link.update({
+ where: {
+ id: linkId,
+ },
+ data: {
+ ...(leads !== undefined && { leads }),
+ ...(conversions !== undefined && { conversions }),
+ ...(saleAmount !== undefined && { saleAmount }),
+ },
+ });
+}
+
+export async function countGroupChangeActivityLogs({
+ partnerId,
+ programId,
+}: {
+ partnerId: string;
+ programId: string;
+}) {
+ return prisma.activityLog.count({
+ where: {
+ programId,
+ resourceType: "partner",
+ resourceId: partnerId,
+ action: "partner.groupChanged",
+ },
+ });
+}
+
+// removeGroupIdFromMoveRules runs in a waitUntil after DELETE /groups/:id, so
+// the scrubbed conditions land shortly after the response.
+export async function expectMoveRules({
+ groupId,
+ expected,
+}: {
+ groupId: string;
+ expected: MoveRule[];
+}) {
+ await expect
+ .poll(
+ async () => {
+ const workflow = await getGroupWorkflow(groupId);
+ return workflow?.triggerConditions ?? null;
+ },
+ { timeout: 15_000 },
+ )
+ .toEqual(expected);
+}
+
+export async function getPartnerGroupRewards(groupId: string) {
+ return prisma.partnerGroup.findUniqueOrThrow({
+ where: {
+ id: groupId,
+ },
+ select: {
+ id: true,
+ leadRewardId: true,
+ saleRewardId: true,
+ discountId: true,
+ clickRewardId: true,
+ referralRewardId: true,
+ },
+ });
+}
diff --git a/apps/web/playwright/api/groups/move-group-fixtures.ts b/apps/web/playwright/api/groups/move-group-fixtures.ts
new file mode 100644
index 0000000000..28ee556896
--- /dev/null
+++ b/apps/web/playwright/api/groups/move-group-fixtures.ts
@@ -0,0 +1,61 @@
+import type { EnrolledPartnerProps, GroupProps } from "@/lib/types";
+import { expect } from "@playwright/test";
+import { randomName } from "../../utils";
+import { deleteCommissionPartner } from "../commissions/helpers";
+import { test as base } from "../fixtures";
+import { createPartner as createPartnerRequest } from "../partners/helpers";
+import { createGroup as createGroupRequest, deleteGroup } from "./helpers";
+
+// Everything a test created, torn down afterwards. Partners are deleted before
+// groups so a group delete doesn't have to migrate enrollments to the default
+// group on the way out.
+type CreatedResources = {
+ groupIds: string[];
+ partnerIds: string[];
+};
+
+export const test = base.extend<{
+ created: CreatedResources;
+ createGroup: (overrides?: Record<string, unknown>) => Promise<GroupProps>;
+ createPartner: (options?: {
+ groupId?: string;
+ }) => Promise<EnrolledPartnerProps>;
+}>({
+ created: async ({ api }, use) => {
+ const created: CreatedResources = { groupIds: [], partnerIds: [] };
+
+ await use(created);
+
+ for (const partnerId of created.partnerIds) {
+ await deleteCommissionPartner({ partnerId });
+ }
+
+ for (const groupId of created.groupIds) {
+ await deleteGroup(api, groupId);
+ }
+ },
+
+ createGroup: async ({ api, created }, use) => {
+ await use(async (overrides = {}) => {
+ const group = await createGroupRequest(api, overrides);
+ created.groupIds.push(group.id);
+
+ return group;
+ });
+ },
+
+ createPartner: async ({ api, created }, use) => {
+ await use(async ({ groupId } = {}) => {
+ const { status, data } = await createPartnerRequest(api, {
+ name: randomName("partner"),
+ ...(groupId && { groupId }),
+ });
+
+ expect(status).toEqual(201);
+ expect(data.links?.[0]).toBeTruthy();
+ created.partnerIds.push(data.id);
+
+ return data;
+ });
+ },
+});
diff --git a/apps/web/playwright/api/groups/move-group-workflow.spec.ts b/apps/web/playwright/api/groups/move-group-workflow.spec.ts
new file mode 100644
index 0000000000..f9ea6de894
--- /dev/null
+++ b/apps/web/playwright/api/groups/move-group-workflow.spec.ts
@@ -0,0 +1,1048 @@
+import { prisma } from "@/lib/prisma";
+import { expect } from "@playwright/test";
+import { apiError } from "../../utils";
+import {
+ countGroupChangeActivityLogs,
+ disableWorkflow,
+ expectMoveRules,
+ expectPartnerInGroup,
+ expectPartnerStaysInGroup,
+ getEnrollment,
+ getGroup,
+ getGroupWorkflow,
+ getPartnerGroupRewards,
+ seedLinkStats,
+ setGroupMoveDisabledAt,
+ setMoveRules,
+ trackPartnerLead,
+ trackPartnerSale,
+ uniqueThreshold,
+} from "./helpers";
+import { test } from "./move-group-fixtures";
+
+// Serial: moveRules are validated program-wide against every other group's
+// rules, so concurrent PATCHes in this file would flake on overlap checks.
+// No retries: a failed case leaves groups/workflows that would flake on retry.
+test.describe.configure({ mode: "serial", retries: 0 });
+
+test.describe("Workflow execution", () => {
+ // totalCommissions is intentionally not covered: it only fires from the
+ // QStash create-partner-commission worker and would make this suite slow.
+
+ test("moves partner when totalLeads condition is met", async ({
+ api,
+ program,
+ createGroup,
+ createPartner,
+ }) => {
+ const source = await createGroup();
+ const target = await createGroup();
+ const n = uniqueThreshold();
+
+ const { status } = await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "between",
+ value: { min: n, max: n + 1 },
+ },
+ {
+ attribute: "partnerGroup",
+ operator: "eq",
+ value: source.id,
+ },
+ ]);
+ expect(status).toEqual(200);
+
+ const partner = await createPartner({ groupId: source.id });
+ await seedLinkStats(partner.links![0].id, { leads: n - 1 });
+
+ await trackPartnerLead(partner);
+
+ const enrollment = await expectPartnerInGroup({
+ partnerId: partner.id,
+ programId: program.id,
+ expectedGroupId: target.id,
+ });
+
+ const targetRewards = await getPartnerGroupRewards(target.id);
+ expect(enrollment.leadRewardId).toBe(targetRewards.leadRewardId);
+ expect(enrollment.saleRewardId).toBe(targetRewards.saleRewardId);
+ expect(enrollment.discountId).toBe(targetRewards.discountId);
+ });
+
+ // `gte` is the other operator every metric attribute accepts, and it is
+ // inclusive — seeding n-1 leaves the partner exactly on the threshold.
+ test("moves partner when totalLeads meets a gte threshold exactly", async ({
+ api,
+ program,
+ createGroup,
+ createPartner,
+ }) => {
+ const source = await createGroup();
+ const target = await createGroup();
+ const n = uniqueThreshold();
+
+ const { status } = await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "gte",
+ value: n,
+ },
+ {
+ attribute: "partnerGroup",
+ operator: "eq",
+ value: source.id,
+ },
+ ]);
+ expect(status).toEqual(200);
+
+ const partner = await createPartner({ groupId: source.id });
+ await seedLinkStats(partner.links![0].id, { leads: n - 1 });
+
+ await trackPartnerLead(partner);
+
+ await expectPartnerInGroup({
+ partnerId: partner.id,
+ programId: program.id,
+ expectedGroupId: target.id,
+ });
+ });
+
+ test("does not move partner when totalLeads condition is not met", async ({
+ api,
+ program,
+ createGroup,
+ createPartner,
+ }) => {
+ const source = await createGroup();
+ const target = await createGroup();
+ const n = uniqueThreshold();
+
+ const { status } = await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "between",
+ value: { min: n, max: n + 1 },
+ },
+ {
+ attribute: "partnerGroup",
+ operator: "eq",
+ value: source.id,
+ },
+ ]);
+ expect(status).toEqual(200);
+
+ const partner = await createPartner({ groupId: source.id });
+ // Seed far below the window so one lead cannot satisfy it.
+ await seedLinkStats(partner.links![0].id, { leads: 0 });
+
+ await trackPartnerLead(partner);
+
+ await expectPartnerStaysInGroup({
+ partnerId: partner.id,
+ programId: program.id,
+ expectedGroupId: source.id,
+ });
+ });
+
+ test("does not move partner when workflow is disabled", async ({
+ api,
+ program,
+ createGroup,
+ createPartner,
+ }) => {
+ const source = await createGroup();
+ const target = await createGroup();
+ const n = uniqueThreshold();
+
+ const { status } = await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "between",
+ value: { min: n, max: n + 1 },
+ },
+ {
+ attribute: "partnerGroup",
+ operator: "eq",
+ value: source.id,
+ },
+ ]);
+ expect(status).toEqual(200);
+
+ const workflow = await getGroupWorkflow(target.id);
+ expect(workflow).not.toBeNull();
+ await disableWorkflow(workflow!.id);
+
+ const partner = await createPartner({ groupId: source.id });
+ await seedLinkStats(partner.links![0].id, { leads: n - 1 });
+
+ await trackPartnerLead(partner);
+
+ await expectPartnerStaysInGroup({
+ partnerId: partner.id,
+ programId: program.id,
+ expectedGroupId: source.id,
+ });
+ });
+
+ test("moves partner when partnerGroup matches source group", async ({
+ api,
+ program,
+ createGroup,
+ createPartner,
+ }) => {
+ const source = await createGroup();
+ const target = await createGroup();
+ const n = uniqueThreshold();
+
+ const { status } = await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "between",
+ value: { min: n, max: n + 1 },
+ },
+ {
+ attribute: "partnerGroup",
+ operator: "eq",
+ value: source.id,
+ },
+ ]);
+ expect(status).toEqual(200);
+
+ const partner = await createPartner({ groupId: source.id });
+ expect(partner.groupId).toBe(source.id);
+ await seedLinkStats(partner.links![0].id, { leads: n - 1 });
+
+ await trackPartnerLead(partner);
+
+ await expectPartnerInGroup({
+ partnerId: partner.id,
+ programId: program.id,
+ expectedGroupId: target.id,
+ });
+ });
+
+ test("does not move partner when partnerGroup does not match", async ({
+ api,
+ program,
+ createGroup,
+ createPartner,
+ }) => {
+ const allowedSource = await createGroup();
+ const actualSource = await createGroup();
+ const target = await createGroup();
+ const n = uniqueThreshold();
+
+ const { status } = await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "between",
+ value: { min: n, max: n + 1 },
+ },
+ {
+ attribute: "partnerGroup",
+ operator: "eq",
+ value: allowedSource.id,
+ },
+ ]);
+ expect(status).toEqual(200);
+
+ const partner = await createPartner({ groupId: actualSource.id });
+ await seedLinkStats(partner.links![0].id, { leads: n - 1 });
+
+ await trackPartnerLead(partner);
+
+ await expectPartnerStaysInGroup({
+ partnerId: partner.id,
+ programId: program.id,
+ expectedGroupId: actualSource.id,
+ });
+ });
+
+ test("moves partner when partnerGroup is one of several source groups", async ({
+ api,
+ program,
+ createGroup,
+ createPartner,
+ }) => {
+ const otherSource = await createGroup();
+ const source = await createGroup();
+ const target = await createGroup();
+ const n = uniqueThreshold();
+
+ const { status } = await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "between",
+ value: { min: n, max: n + 1 },
+ },
+ {
+ attribute: "partnerGroup",
+ operator: "in",
+ value: [otherSource.id, source.id],
+ },
+ ]);
+ expect(status).toEqual(200);
+
+ const partner = await createPartner({ groupId: source.id });
+ await seedLinkStats(partner.links![0].id, { leads: n - 1 });
+
+ await trackPartnerLead(partner);
+
+ await expectPartnerInGroup({
+ partnerId: partner.id,
+ programId: program.id,
+ expectedGroupId: target.id,
+ });
+ });
+
+ test("does not move partner when partnerGroup is excluded by notIn", async ({
+ api,
+ program,
+ createGroup,
+ createPartner,
+ }) => {
+ const source = await createGroup();
+ const target = await createGroup();
+ const n = uniqueThreshold();
+
+ const { status } = await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "between",
+ value: { min: n, max: n + 1 },
+ },
+ {
+ attribute: "partnerGroup",
+ operator: "notIn",
+ value: [source.id],
+ },
+ ]);
+ expect(status).toEqual(200);
+
+ const partner = await createPartner({ groupId: source.id });
+ await seedLinkStats(partner.links![0].id, { leads: n - 1 });
+
+ await trackPartnerLead(partner);
+
+ await expectPartnerStaysInGroup({
+ partnerId: partner.id,
+ programId: program.id,
+ expectedGroupId: source.id,
+ });
+ });
+
+ test("skips partner with groupMoveDisabledAt set", async ({
+ api,
+ program,
+ createGroup,
+ createPartner,
+ }) => {
+ const source = await createGroup();
+ const target = await createGroup();
+ const n = uniqueThreshold();
+
+ const { status } = await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "between",
+ value: { min: n, max: n + 1 },
+ },
+ {
+ attribute: "partnerGroup",
+ operator: "eq",
+ value: source.id,
+ },
+ ]);
+ expect(status).toEqual(200);
+
+ const partner = await createPartner({ groupId: source.id });
+ await setGroupMoveDisabledAt(api, {
+ partnerId: partner.id,
+ groupId: source.id,
+ groupMoveDisabledAt: new Date().toISOString(),
+ });
+
+ const before = await getEnrollment({
+ partnerId: partner.id,
+ programId: program.id,
+ });
+ expect(before.groupMoveDisabledAt).not.toBeNull();
+ expect(before.groupId).toBe(source.id);
+
+ await seedLinkStats(partner.links![0].id, { leads: n - 1 });
+ await trackPartnerLead(partner);
+
+ const after = await expectPartnerStaysInGroup({
+ partnerId: partner.id,
+ programId: program.id,
+ expectedGroupId: source.id,
+ });
+ expect(after.groupMoveDisabledAt).not.toBeNull();
+ });
+
+ test("does not re-move partner on repeat triggers", async ({
+ api,
+ program,
+ createGroup,
+ createPartner,
+ }) => {
+ const source = await createGroup();
+ const target = await createGroup();
+ const n = uniqueThreshold();
+
+ const { status } = await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "between",
+ value: { min: n, max: n + 100 },
+ },
+ {
+ attribute: "partnerGroup",
+ operator: "eq",
+ value: source.id,
+ },
+ ]);
+ expect(status).toEqual(200);
+
+ const partner = await createPartner({ groupId: source.id });
+ await seedLinkStats(partner.links![0].id, { leads: n - 1 });
+
+ await trackPartnerLead(partner);
+ await expectPartnerInGroup({
+ partnerId: partner.id,
+ programId: program.id,
+ expectedGroupId: target.id,
+ });
+
+ // Second lead: the already-in-target guard skips before the redis lock is
+ // ever reached, since the first move has already committed by now.
+ await trackPartnerLead(partner);
+ await expectPartnerStaysInGroup({
+ partnerId: partner.id,
+ programId: program.id,
+ expectedGroupId: target.id,
+ });
+
+ // The enrollment update is idempotent, so only the activity log proves the
+ // partner was moved once rather than once per trigger.
+ await expect
+ .poll(
+ () =>
+ countGroupChangeActivityLogs({
+ partnerId: partner.id,
+ programId: program.id,
+ }),
+ { timeout: 15_000 },
+ )
+ .toBe(1);
+ });
+
+ test("moves partner when totalSaleAmount condition is met", async ({
+ api,
+ program,
+ createGroup,
+ createPartner,
+ }) => {
+ const source = await createGroup();
+ const target = await createGroup();
+ const n = uniqueThreshold();
+
+ const { status } = await setMoveRules(api, target.id, [
+ {
+ attribute: "totalSaleAmount",
+ operator: "between",
+ value: { min: n, max: n + 1 },
+ },
+ {
+ attribute: "partnerGroup",
+ operator: "eq",
+ value: source.id,
+ },
+ ]);
+ expect(status).toEqual(200);
+
+ const partner = await createPartner({ groupId: source.id });
+ await trackPartnerSale(partner, { amount: n });
+
+ await expectPartnerInGroup({
+ partnerId: partner.id,
+ programId: program.id,
+ expectedGroupId: target.id,
+ });
+ });
+
+ test("moves partner when totalConversions condition is met", async ({
+ api,
+ program,
+ createGroup,
+ createPartner,
+ }) => {
+ const source = await createGroup();
+ const target = await createGroup();
+ const n = uniqueThreshold();
+
+ const { status } = await setMoveRules(api, target.id, [
+ {
+ attribute: "totalConversions",
+ operator: "gte",
+ value: n,
+ },
+ {
+ attribute: "partnerGroup",
+ operator: "eq",
+ value: source.id,
+ },
+ ]);
+ expect(status).toEqual(200);
+
+ const partner = await createPartner({ groupId: source.id });
+ await seedLinkStats(partner.links![0].id, { conversions: n - 1 });
+
+ // conversions only increment on a customer's first sale, which is what
+ // trackPartnerSale produces (fresh customer per call).
+ await trackPartnerSale(partner);
+
+ await expectPartnerInGroup({
+ partnerId: partner.id,
+ programId: program.id,
+ expectedGroupId: target.id,
+ });
+ });
+});
+
+test.describe("Workflow lifecycle", () => {
+ test("configuring moveRules creates a moveGroup workflow", async ({
+ api,
+ createGroup,
+ }) => {
+ const target = await createGroup();
+ const n = uniqueThreshold();
+ const moveRules = [
+ {
+ attribute: "totalCommissions" as const,
+ operator: "between" as const,
+ value: { min: n, max: n + 1 },
+ },
+ ];
+
+ const { status } = await setMoveRules(api, target.id, moveRules);
+ expect(status).toEqual(200);
+
+ const workflow = await getGroupWorkflow(target.id);
+ expect(workflow).not.toBeNull();
+ expect(workflow!.disabledAt).toBeNull();
+ expect(workflow!.actions).toEqual([
+ {
+ type: "moveGroup",
+ data: { groupId: target.id },
+ },
+ ]);
+ expect(workflow!.triggerConditions).toEqual(moveRules);
+
+ const { status: getStatus, data: group } = await getGroup(api, target.id);
+ expect(getStatus).toEqual(200);
+ expect(group.moveRules).toEqual(moveRules);
+ });
+
+ test("changing moveRules updates the same workflow row", async ({
+ api,
+ createGroup,
+ }) => {
+ const target = await createGroup();
+ const n1 = uniqueThreshold();
+ const n2 = uniqueThreshold();
+
+ await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "between",
+ value: { min: n1, max: n1 + 1 },
+ },
+ ]);
+
+ const before = await getGroupWorkflow(target.id);
+ expect(before).not.toBeNull();
+
+ const nextRules = [
+ {
+ attribute: "totalConversions" as const,
+ operator: "between" as const,
+ value: { min: n2, max: n2 + 1 },
+ },
+ ];
+ const { status } = await setMoveRules(api, target.id, nextRules);
+ expect(status).toEqual(200);
+
+ const after = await getGroupWorkflow(target.id);
+ expect(after).not.toBeNull();
+ expect(after!.id).toBe(before!.id);
+ expect(after!.triggerConditions).toEqual(nextRules);
+ });
+
+ test("empty moveRules deletes the workflow", async ({ api, createGroup }) => {
+ const target = await createGroup();
+ const n = uniqueThreshold();
+
+ await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "between",
+ value: { min: n, max: n + 1 },
+ },
+ ]);
+ expect(await getGroupWorkflow(target.id)).not.toBeNull();
+
+ const { status } = await setMoveRules(api, target.id, []);
+ expect(status).toEqual(200);
+
+ expect(await getGroupWorkflow(target.id)).toBeNull();
+
+ const group = await prisma.partnerGroup.findUniqueOrThrow({
+ where: { id: target.id },
+ select: { workflowId: true },
+ });
+ expect(group.workflowId).toBeNull();
+ });
+
+ test("PATCH without moveRules leaves the workflow untouched", async ({
+ api,
+ createGroup,
+ }) => {
+ const target = await createGroup();
+ const n = uniqueThreshold();
+ const moveRules = [
+ {
+ attribute: "totalLeads" as const,
+ operator: "between" as const,
+ value: { min: n, max: n + 1 },
+ },
+ ];
+
+ await setMoveRules(api, target.id, moveRules);
+ const before = await getGroupWorkflow(target.id);
+ expect(before).not.toBeNull();
+
+ const { status } = await api.patch(`/api/groups/${target.id}`, {
+ name: `${target.name} updated`,
+ });
+ expect(status).toEqual(200);
+
+ const after = await getGroupWorkflow(target.id);
+ expect(after).not.toBeNull();
+ expect(after!.id).toBe(before!.id);
+ expect(after!.triggerConditions).toEqual(moveRules);
+ });
+
+ test("deleting a group deletes its attached workflow", async ({
+ api,
+ createGroup,
+ }) => {
+ const target = await createGroup();
+ const n = uniqueThreshold();
+
+ await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "between",
+ value: { min: n, max: n + 1 },
+ },
+ ]);
+
+ const workflow = await getGroupWorkflow(target.id);
+ expect(workflow).not.toBeNull();
+ const workflowId = workflow!.id;
+
+ const { status } = await api.delete(`/api/groups/${target.id}`);
+ expect(status).toEqual(200);
+
+ const deleted = await prisma.workflow.findUnique({
+ where: { id: workflowId },
+ });
+ expect(deleted).toBeNull();
+ });
+
+ test("deleting a source group drops it from another group's move rules", async ({
+ api,
+ createGroup,
+ }) => {
+ const source = await createGroup();
+ const target = await createGroup();
+ const n = uniqueThreshold();
+ const metricRule = {
+ attribute: "totalLeads" as const,
+ operator: "between" as const,
+ value: { min: n, max: n + 1 },
+ };
+
+ const { status } = await setMoveRules(api, target.id, [
+ metricRule,
+ {
+ attribute: "partnerGroup",
+ operator: "eq",
+ value: source.id,
+ },
+ ]);
+ expect(status).toEqual(200);
+
+ const { status: deleteStatus } = await api.delete(
+ `/api/groups/${source.id}`,
+ );
+ expect(deleteStatus).toEqual(200);
+
+ // The whole condition is dropped rather than the workflow being disabled,
+ // so what was "in group A and hit the metric" now matches every partner.
+ await expectMoveRules({ groupId: target.id, expected: [metricRule] });
+ });
+
+ test("deleting a source group only removes it from a partnerGroup list", async ({
+ api,
+ createGroup,
+ }) => {
+ const removed = await createGroup();
+ const kept = await createGroup();
+ const target = await createGroup();
+ const n = uniqueThreshold();
+ const metricRule = {
+ attribute: "totalLeads" as const,
+ operator: "between" as const,
+ value: { min: n, max: n + 1 },
+ };
+
+ const { status } = await setMoveRules(api, target.id, [
+ metricRule,
+ {
+ attribute: "partnerGroup",
+ operator: "in",
+ value: [removed.id, kept.id],
+ },
+ ]);
+ expect(status).toEqual(200);
+
+ const { status: deleteStatus } = await api.delete(
+ `/api/groups/${removed.id}`,
+ );
+ expect(deleteStatus).toEqual(200);
+
+ await expectMoveRules({
+ groupId: target.id,
+ expected: [
+ metricRule,
+ {
+ attribute: "partnerGroup",
+ operator: "in",
+ value: [kept.id],
+ },
+ ],
+ });
+ });
+
+ test("multiple metric move rules are stored in order", async ({
+ api,
+ createGroup,
+ }) => {
+ const target = await createGroup();
+ const n1 = uniqueThreshold();
+ const n2 = uniqueThreshold();
+ const moveRules = [
+ {
+ attribute: "totalLeads" as const,
+ operator: "between" as const,
+ value: { min: n1, max: n1 + 1 },
+ },
+ {
+ attribute: "totalConversions" as const,
+ operator: "between" as const,
+ value: { min: n2, max: n2 + 1 },
+ },
+ ];
+
+ const { status } = await setMoveRules(api, target.id, moveRules);
+ expect(status).toEqual(200);
+
+ const workflow = await getGroupWorkflow(target.id);
+ expect(workflow).not.toBeNull();
+ expect(workflow!.triggerConditions).toEqual(moveRules);
+ });
+
+ test("metric and partnerGroup move rules are stored together", async ({
+ api,
+ createGroup,
+ }) => {
+ const source = await createGroup();
+ const target = await createGroup();
+ const n = uniqueThreshold();
+ const moveRules = [
+ {
+ attribute: "totalLeads" as const,
+ operator: "between" as const,
+ value: { min: n, max: n + 1 },
+ },
+ {
+ attribute: "partnerGroup" as const,
+ operator: "eq" as const,
+ value: source.id,
+ },
+ ];
+
+ const { status } = await setMoveRules(api, target.id, moveRules);
+ expect(status).toEqual(200);
+
+ const workflow = await getGroupWorkflow(target.id);
+ expect(workflow).not.toBeNull();
+ expect(workflow!.triggerConditions).toEqual(moveRules);
+ });
+});
+
+test.describe("Move rule validation", () => {
+ test("rejects partnerGroup as the only condition", async ({
+ api,
+ createGroup,
+ }) => {
+ const source = await createGroup();
+ const target = await createGroup();
+
+ expect(
+ await setMoveRules(api, target.id, [
+ {
+ attribute: "partnerGroup",
+ operator: "eq",
+ value: source.id,
+ },
+ ]),
+ ).toEqual(
+ apiError({
+ code: "bad_request",
+ message:
+ "Partner group can only be used as an additional condition alongside a metric rule.",
+ }),
+ );
+ });
+
+ test("rejects partnerGroup pointing at the current group", async ({
+ api,
+ createGroup,
+ }) => {
+ const target = await createGroup();
+ const n = uniqueThreshold();
+
+ expect(
+ await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "between",
+ value: { min: n, max: n + 1 },
+ },
+ {
+ attribute: "partnerGroup",
+ operator: "eq",
+ value: target.id,
+ },
+ ]),
+ ).toEqual(
+ apiError({
+ code: "bad_request",
+ message:
+ "Condition 2: Cannot select the current group as a source group.",
+ }),
+ );
+ });
+
+ test("rejects partnerGroup with an unknown group id", async ({
+ api,
+ createGroup,
+ }) => {
+ const target = await createGroup();
+ const n = uniqueThreshold();
+ const missingGroupId = "grp_does_not_exist";
+
+ expect(
+ await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "between",
+ value: { min: n, max: n + 1 },
+ },
+ {
+ attribute: "partnerGroup",
+ operator: "eq",
+ value: missingGroupId,
+ },
+ ]),
+ ).toEqual(
+ apiError({
+ code: "bad_request",
+ message: `Condition 2: Invalid group IDs detected: ${missingGroupId}`,
+ }),
+ );
+ });
+
+ test("rejects a partnerGroup list containing the current group", async ({
+ api,
+ createGroup,
+ }) => {
+ const source = await createGroup();
+ const target = await createGroup();
+ const n = uniqueThreshold();
+
+ expect(
+ await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "between",
+ value: { min: n, max: n + 1 },
+ },
+ {
+ attribute: "partnerGroup",
+ operator: "in",
+ value: [source.id, target.id],
+ },
+ ]),
+ ).toEqual(
+ apiError({
+ code: "bad_request",
+ message:
+ "Condition 2: Cannot select the current group as a source group.",
+ }),
+ );
+ });
+
+ test("rejects a partnerGroup list with an unknown group id", async ({
+ api,
+ createGroup,
+ }) => {
+ const source = await createGroup();
+ const target = await createGroup();
+ const n = uniqueThreshold();
+ const missingGroupId = "grp_does_not_exist";
+
+ expect(
+ await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "between",
+ value: { min: n, max: n + 1 },
+ },
+ {
+ attribute: "partnerGroup",
+ operator: "in",
+ value: [source.id, missingGroupId],
+ },
+ ]),
+ ).toEqual(
+ apiError({
+ code: "bad_request",
+ message: `Condition 2: Invalid group IDs detected: ${missingGroupId}`,
+ }),
+ );
+ });
+
+ test("rejects operator not allowed for the attribute", async ({
+ api,
+ createGroup,
+ }) => {
+ const target = await createGroup();
+
+ expect(
+ await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "lte",
+ value: 1,
+ },
+ ]),
+ ).toEqual(
+ apiError({
+ code: "bad_request",
+ message:
+ 'Operator "is less than or equal to" is not valid for the activity "totalLeads".',
+ }),
+ );
+ });
+
+ test("rejects attribute not available for moveGroup", async ({
+ api,
+ createGroup,
+ }) => {
+ const target = await createGroup();
+
+ expect(
+ await setMoveRules(api, target.id, [
+ {
+ attribute: "partnerEnrolledDays",
+ operator: "gte",
+ value: 1,
+ },
+ ]),
+ ).toEqual(
+ apiError({
+ code: "bad_request",
+ message: "Condition 1: Invalid activity.",
+ }),
+ );
+ });
+
+ test("rejects between with max less than or equal to min", async ({
+ api,
+ createGroup,
+ }) => {
+ const target = await createGroup();
+ const n = uniqueThreshold();
+
+ const result = await setMoveRules(api, target.id, [
+ {
+ attribute: "totalLeads",
+ operator: "between",
+ value: { min: n, max: n },
+ },
+ ]);
+
+ expect(result.status).toEqual(422);
+ expect(result.data).toEqual({
+ error: {
+ code: "unprocessable_entity",
+ message: expect.stringContaining(
+ "Maximum value must be greater than minimum value.",
+ ),
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ });
+ });
+
+ test("rejects overlapping move rules across groups", async ({
+ api,
+ createGroup,
+ }) => {
+ const first = await createGroup();
+ const second = await createGroup();
+ const n = uniqueThreshold();
+ const overlapping = [
+ {
+ attribute: "totalLeads" as const,
+ operator: "between" as const,
+ value: { min: n, max: n + 1 },
+ },
+ ];
+
+ const created = await setMoveRules(api, first.id, overlapping);
+ expect(created.status).toEqual(200);
+
+ expect(await setMoveRules(api, second.id, overlapping)).toEqual(
+ apiError({
+ code: "bad_request",
+ message: `This rule is already in use by the ${first.name} group. Select a different activity or amount.`,
+ }),
+ );
+
+ const disjointN = uniqueThreshold();
+ const disjoint = await setMoveRules(api, second.id, [
+ {
+ attribute: "totalLeads",
+ operator: "between",
+ value: { min: disjointN, max: disjointN + 1 },
+ },
+ ]);
+ expect(disjoint.status).toEqual(200);
+ });
+});
diff --git a/apps/web/tests/workflows/move-group-workflow.test.ts b/apps/web/tests/workflows/move-group-workflow.test.ts
deleted file mode 100644
index 742f873a51..0000000000
--- a/apps/web/tests/workflows/move-group-workflow.test.ts
+++ /dev/null
@@ -1,787 +0,0 @@
-import { EnrolledPartnerProps } from "@/lib/types";
-import { RESOURCE_COLORS } from "@/ui/colors";
-import { randomValue } from "@dub/utils";
-import { PartnerGroup } from "@prisma/client";
-import { E2E_PARTNER } from "tests/utils/resource";
-import { describe, expect, onTestFinished, test } from "vitest";
-import { randomId, randomPartnerEmail } from "../utils/helpers";
-import { IntegrationHarness } from "../utils/integration";
-import { trackE2ELead } from "./utils/track-e2e-lead";
-import { verifyPartnerGroupMove } from "./utils/verify-partner-group-move";
-
-async function cleanupOrphanedGroup(http: any, slug: string) {
- const { data: allGroups } = await http.get<PartnerGroup[]>({
- path: "/groups",
- });
- const orphan = allGroups.find((g) => g.slug === slug);
- if (orphan) await http.delete({ path: `/groups/${orphan.id}` });
-}
-
-describe.sequential("Workflow - MoveGroup", async () => {
- const h = new IntegrationHarness();
- const { http } = await h.init();
-
- test("Workflow is created when move rules are configured", async () => {
- const slug = `e2e-target-config-${randomId(8)}`;
- await cleanupOrphanedGroup(http, slug);
-
- const { status: targetStatus, data: targetGroup } =
- await http.post<PartnerGroup>({
- path: "/groups",
- body: {
- name: "E2E Target Group - Config Test",
- slug,
- color: randomValue(RESOURCE_COLORS),
- },
- });
-
- expect(targetStatus).toEqual(201);
-
- onTestFinished(async () => {
- await http.delete({ path: `/groups/${targetGroup.id}` });
- });
-
- // Unique attribute + range so this doesn't collide with leftover/concurrent
- // totalLeads rules (e.g. "E2E Target Group - Not Met" uses 4–5).
- const min = 10_000 + Math.floor(Math.random() * 1_000_000);
- const moveRule = {
- attribute: "totalCommissions" as const,
- operator: "between" as const,
- value: { min, max: min + 1 },
- };
-
- const { status: patchStatus } = await http.patch({
- path: `/groups/${targetGroup.id}`,
- body: {
- moveRules: [moveRule],
- },
- });
-
- expect(patchStatus).toEqual(200);
-
- const { data: workflow } = await http.get<any>({
- path: "/e2e/workflows",
- query: { groupId: targetGroup.id },
- });
-
- expect(workflow).not.toBeNull();
- expect(workflow.disabledAt).toBeNull();
-
- const workflowActions = workflow.actions as any[];
- expect(workflowActions).toHaveLength(1);
- expect(workflowActions[0].type).toBe("moveGroup");
- expect(workflowActions[0].data.groupId).toBe(targetGroup.id);
-
- const workflowConditions = workflow.triggerConditions as any[];
- expect(workflowConditions).toHaveLength(1);
- expect(workflowConditions[0].attribute).toBe(moveRule.attribute);
- expect(workflowConditions[0].operator).toBe(moveRule.operator);
- expect(workflowConditions[0].value).toStrictEqual(moveRule.value);
- });
-
- test("Workflow is deleted when move rules are removed", async () => {
- const slug = "e2e-remove-rules";
- await cleanupOrphanedGroup(http, slug);
-
- const { status: groupStatus, data: group } = await http.post<PartnerGroup>({
- path: "/groups",
- body: {
- name: "E2E Group - Remove Rules",
- slug,
- color: randomValue(RESOURCE_COLORS),
- },
- });
-
- expect(groupStatus).toEqual(201);
-
- onTestFinished(async () => {
- await http.delete({ path: `/groups/${group.id}` });
- });
-
- const { status: addStatus } = await http.patch({
- path: `/groups/${group.id}`,
- body: {
- moveRules: [
- {
- attribute: "totalLeads",
- operator: "between",
- value: { min: 2, max: 3 },
- },
- ],
- },
- });
-
- expect(addStatus).toEqual(200);
-
- const { data: workflow } = await http.get<any>({
- path: "/e2e/workflows",
- query: { groupId: group.id },
- });
-
- expect(workflow).not.toBeNull();
-
- const { status: removeStatus } = await http.patch({
- path: `/groups/${group.id}`,
- body: {
- moveRules: [],
- },
- });
-
- expect(removeStatus).toEqual(200);
-
- await new Promise((resolve) => setTimeout(resolve, 5000));
-
- const { data: deletedWorkflow } = await http.get<any>({
- path: "/e2e/workflows",
- query: { groupId: group.id },
- });
-
- expect(deletedWorkflow).toBeNull();
- });
-
- test("Disabled workflow doesn't execute partner move", async () => {
- const slug = "e2e-target-disabled";
- await cleanupOrphanedGroup(http, slug);
-
- const { data: existingGroups } = await http.get<PartnerGroup[]>({
- path: "/groups",
- });
-
- expect(existingGroups.length).toBeGreaterThan(0);
- const sourceGroup = existingGroups[0];
-
- const { status: targetStatus, data: targetGroup } =
- await http.post<PartnerGroup>({
- path: "/groups",
- body: {
- name: "E2E Target Group - Disabled Move",
- slug,
- color: randomValue(RESOURCE_COLORS),
- },
- });
-
- expect(targetStatus).toEqual(201);
-
- onTestFinished(async () => {
- await http.delete({ path: `/groups/${targetGroup.id}` });
- });
-
- const { status: patchStatus } = await http.patch({
- path: `/groups/${targetGroup.id}`,
- body: {
- moveRules: [
- {
- attribute: "totalLeads",
- operator: "between",
- value: { min: 2, max: 3 },
- },
- ],
- },
- });
-
- expect(patchStatus).toEqual(200);
-
- const { data: workflow } = await http.get<any>({
- path: "/e2e/workflows",
- query: { groupId: targetGroup.id },
- });
-
- expect(workflow).not.toBeNull();
- expect(workflow.disabledAt).toBeNull();
-
- await http.patch({
- path: `/e2e/workflows/${workflow.id}`,
- body: { disabledAt: new Date().toISOString() },
- });
-
- const { status: partnerStatus, data: partner } =
- await http.post<EnrolledPartnerProps>({
- path: "/partners",
- body: {
- name: "E2E Test Partner - Disabled Move",
- email: randomPartnerEmail(),
- groupId: sourceGroup.id,
- },
- });
-
- expect(partnerStatus).toEqual(201);
- expect(partner.links).not.toBeNull();
-
- const partnerLink = partner.links![0];
-
- await trackE2ELead(http, partnerLink);
-
- await new Promise((resolve) => setTimeout(resolve, 10000));
-
- const { data: partnerAfter } = await http.get<EnrolledPartnerProps>({
- path: `/partners/${partner.id}`,
- });
-
- expect(partnerAfter.groupId).toBe(sourceGroup.id);
- });
-
- test("Workflow doesn't execute when conditions are not met", async () => {
- const slug = "e2e-target-not-met";
- await cleanupOrphanedGroup(http, slug);
-
- const { data: existingGroups } = await http.get<PartnerGroup[]>({
- path: "/groups",
- });
-
- expect(existingGroups.length).toBeGreaterThan(0);
- const sourceGroup = existingGroups[0];
-
- const { status: targetStatus, data: targetGroup } =
- await http.post<PartnerGroup>({
- path: "/groups",
- body: {
- name: "E2E Target Group - Not Met",
- slug,
- color: randomValue(RESOURCE_COLORS),
- },
- });
-
- expect(targetStatus).toEqual(201);
-
- onTestFinished(async () => {
- await http.delete({ path: `/groups/${targetGroup.id}` });
- });
-
- const { status: patchStatus } = await http.patch({
- path: `/groups/${targetGroup.id}`,
- body: {
- moveRules: [
- {
- attribute: "totalLeads",
- operator: "between",
- value: { min: 4, max: 5 },
- },
- ],
- },
- });
-
- expect(patchStatus).toEqual(200);
-
- const { status: partnerStatus, data: partner } =
- await http.post<EnrolledPartnerProps>({
- path: "/partners",
- body: {
- name: "E2E Test Partner - Not Met",
- email: randomPartnerEmail(),
- groupId: sourceGroup.id,
- },
- });
-
- expect(partnerStatus).toEqual(201);
- expect(partner.links).not.toBeNull();
-
- const partnerLink = partner.links![0];
-
- await trackE2ELead(http, partnerLink);
-
- await new Promise((resolve) => setTimeout(resolve, 10000));
-
- const { data: partnerAfter } = await http.get<EnrolledPartnerProps>({
- path: `/partners/${partner.id}`,
- });
-
- expect(partnerAfter.groupId).toBe(sourceGroup.id);
- });
-
- test(
- "Workflow executes when conditions are met - partner moves to target group",
- { timeout: 90000 },
- async () => {
- const slug = "e2e-target-exec";
- await cleanupOrphanedGroup(http, slug);
-
- const { data: existingGroups } = await http.get<PartnerGroup[]>({
- path: "/groups",
- });
-
- expect(existingGroups.length).toBeGreaterThan(0);
- const sourceGroup = existingGroups[0];
-
- const { status: targetStatus, data: targetGroup } =
- await http.post<PartnerGroup>({
- path: "/groups",
- body: {
- name: "E2E Target Group - Move Execution",
- slug,
- color: randomValue(RESOURCE_COLORS),
- },
- });
-
- expect(targetStatus).toEqual(201);
-
- onTestFinished(async () => {
- await http.delete({ path: `/groups/${targetGroup.id}` });
- });
-
- const { status: patchStatus } = await http.patch({
- path: `/groups/${targetGroup.id}`,
- body: {
- moveRules: [
- {
- attribute: "totalLeads",
- operator: "between",
- value: { min: 1, max: 2 },
- },
- ],
- },
- });
-
- expect(patchStatus).toEqual(200);
-
- const { status: partnerStatus, data: partner } =
- await http.post<EnrolledPartnerProps>({
- path: "/partners",
- body: {
- name: "E2E Test Partner - Move Execution",
- email: randomPartnerEmail(),
- groupId: sourceGroup.id,
- },
- });
-
- expect(partnerStatus).toEqual(201);
- expect(partner.links).not.toBeNull();
- expect(partner.groupId).toBe(sourceGroup.id);
-
- const partnerLink = partner.links![0];
-
- await trackE2ELead(http, partnerLink);
-
- await verifyPartnerGroupMove({
- http,
- partnerId: partner.id,
- expectedGroupId: targetGroup.id,
- });
- },
- );
-
- test(
- "No duplicate group moves on multiple triggers",
- { timeout: 90000 },
- async () => {
- const slug = "e2e-target-no-dup";
- await cleanupOrphanedGroup(http, slug);
-
- const { data: existingGroups } = await http.get<PartnerGroup[]>({
- path: "/groups",
- });
-
- expect(existingGroups.length).toBeGreaterThan(0);
- const sourceGroup = existingGroups[0];
-
- const { status: targetStatus, data: targetGroup } =
- await http.post<PartnerGroup>({
- path: "/groups",
- body: {
- name: "E2E Target Group - No Dup Move",
- slug,
- color: randomValue(RESOURCE_COLORS),
- },
- });
-
- expect(targetStatus).toEqual(201);
-
- onTestFinished(async () => {
- await http.delete({ path: `/groups/${targetGroup.id}` });
- });
-
- const { status: patchStatus } = await http.patch({
- path: `/groups/${targetGroup.id}`,
- body: {
- moveRules: [
- {
- attribute: "totalLeads",
- operator: "between",
- value: { min: 1, max: 2 },
- },
- ],
- },
- });
-
- expect(patchStatus).toEqual(200);
-
- const { status: partnerStatus, data: partner } =
- await http.post<EnrolledPartnerProps>({
- path: "/partners",
- body: {
- name: "E2E Test Partner - No Dup Move",
- email: randomPartnerEmail(),
- groupId: sourceGroup.id,
- },
- });
-
- expect(partnerStatus).toEqual(201);
- expect(partner.links).not.toBeNull();
-
- const partnerLink = partner.links![0];
-
- await trackE2ELead(http, partnerLink);
-
- await verifyPartnerGroupMove({
- http,
- partnerId: partner.id,
- expectedGroupId: targetGroup.id,
- });
-
- const { data: partnerAfter } = await http.get<EnrolledPartnerProps>({
- path: `/partners/${partner.id}`,
- });
-
- expect(partnerAfter.groupId).toBe(targetGroup.id);
- },
- );
-
- test("Multiple move rules can be configured (AND operator)", async () => {
- const slug = "e2e-multi-rules";
- await cleanupOrphanedGroup(http, slug);
-
- const { status: groupStatus, data: group } = await http.post<PartnerGroup>({
- path: "/groups",
- body: {
- name: "E2E Group - Multiple Rules",
- slug,
- color: randomValue(RESOURCE_COLORS),
- },
- });
-
- expect(groupStatus).toEqual(201);
-
- onTestFinished(async () => {
- await http.delete({ path: `/groups/${group.id}` });
- });
-
- const { status: patchStatus } = await http.patch({
- path: `/groups/${group.id}`,
- body: {
- moveRules: [
- {
- attribute: "totalLeads",
- operator: "between",
- value: { min: 2, max: 3 },
- },
- {
- attribute: "totalConversions",
- operator: "between",
- value: { min: 1, max: 2 },
- },
- ],
- },
- });
-
- expect(patchStatus).toEqual(200);
-
- const { data: workflow } = await http.get<any>({
- path: "/e2e/workflows",
- query: { groupId: group.id },
- });
-
- expect(workflow).not.toBeNull();
-
- const workflowConditions = workflow.triggerConditions as any[];
- expect(workflowConditions).toHaveLength(2);
- expect(workflowConditions[0].attribute).toBe("totalLeads");
- expect(workflowConditions[0].value).toStrictEqual({ min: 2, max: 3 });
- expect(workflowConditions[1].attribute).toBe("totalConversions");
- expect(workflowConditions[1].value).toStrictEqual({ min: 1, max: 2 });
- });
-
- test("Metric + partnerGroup move rules create workflow with both conditions", async () => {
- const slug = "e2e-partner-group-config";
- await cleanupOrphanedGroup(http, slug);
-
- const { data: existingGroups } = await http.get<PartnerGroup[]>({
- path: "/groups",
- });
-
- expect(existingGroups.length).toBeGreaterThan(0);
- const sourceGroup = existingGroups[0];
-
- const { status: groupStatus, data: group } = await http.post<PartnerGroup>({
- path: "/groups",
- body: {
- name: "E2E Group - Partner Group Config",
- slug,
- color: randomValue(RESOURCE_COLORS),
- },
- });
-
- expect(groupStatus).toEqual(201);
-
- onTestFinished(async () => {
- await http.delete({ path: `/groups/${group.id}` });
- });
-
- const { status: patchStatus } = await http.patch({
- path: `/groups/${group.id}`,
- body: {
- moveRules: [
- {
- attribute: "totalLeads",
- operator: "between",
- value: { min: 2, max: 3 },
- },
- {
- attribute: "partnerGroup",
- operator: "eq",
- value: sourceGroup.id,
- },
- ],
- },
- });
-
- expect(patchStatus).toEqual(200);
-
- const { data: workflow } = await http.get<any>({
- path: "/e2e/workflows",
- query: { groupId: group.id },
- });
-
- expect(workflow).not.toBeNull();
-
- const workflowConditions = workflow.triggerConditions as any[];
- expect(workflowConditions).toHaveLength(2);
- expect(workflowConditions[0].attribute).toBe("totalLeads");
- expect(workflowConditions[0].operator).toBe("between");
- expect(workflowConditions[0].value).toStrictEqual({ min: 2, max: 3 });
- expect(workflowConditions[1].attribute).toBe("partnerGroup");
- expect(workflowConditions[1].operator).toBe("eq");
- expect(workflowConditions[1].value).toBe(sourceGroup.id);
- });
-
- test(
- "Workflow executes when partnerGroup matches source group",
- { timeout: 90000 },
- async () => {
- const slug = "e2e-partner-group-match";
- await cleanupOrphanedGroup(http, slug);
-
- const { data: existingGroups } = await http.get<PartnerGroup[]>({
- path: "/groups",
- });
-
- expect(existingGroups.length).toBeGreaterThan(0);
- const sourceGroup = existingGroups[0];
-
- const { status: targetStatus, data: targetGroup } =
- await http.post<PartnerGroup>({
- path: "/groups",
- body: {
- name: "E2E Target Group - Partner Group Match",
- slug,
- color: randomValue(RESOURCE_COLORS),
- },
- });
-
- expect(targetStatus).toEqual(201);
-
- onTestFinished(async () => {
- await http.delete({ path: `/groups/${targetGroup.id}` });
- });
-
- const { status: patchStatus } = await http.patch({
- path: `/groups/${targetGroup.id}`,
- body: {
- moveRules: [
- {
- attribute: "totalLeads",
- operator: "between",
- value: { min: 1, max: 2 },
- },
- {
- attribute: "partnerGroup",
- operator: "eq",
- value: sourceGroup.id,
- },
- ],
- },
- });
-
- expect(patchStatus).toEqual(200);
-
- const { status: partnerStatus, data: partner } =
- await http.post<EnrolledPartnerProps>({
- path: "/partners",
- body: {
- name: "E2E Test Partner - Partner Group Match",
- email: randomPartnerEmail(),
- groupId: sourceGroup.id,
- },
- });
-
- expect(partnerStatus).toEqual(201);
- expect(partner.links).not.toBeNull();
- expect(partner.groupId).toBe(sourceGroup.id);
-
- const partnerLink = partner.links![0];
-
- await trackE2ELead(http, partnerLink);
-
- await verifyPartnerGroupMove({
- http,
- partnerId: partner.id,
- expectedGroupId: targetGroup.id,
- });
- },
- );
-
- test("Workflow doesn't execute when partnerGroup does not match source group", async () => {
- const slug = "e2e-partner-group-mismatch";
- const sourceSlug = "e2e-partner-group-mismatch-src";
- await cleanupOrphanedGroup(http, slug);
- await cleanupOrphanedGroup(http, sourceSlug);
-
- const { data: existingGroups } = await http.get<PartnerGroup[]>({
- path: "/groups",
- });
-
- expect(existingGroups.length).toBeGreaterThan(0);
- const allowedSourceGroup = existingGroups[0];
-
- const { status: nonMatchingSourceStatus, data: nonMatchingSourceGroup } =
- await http.post<PartnerGroup>({
- path: "/groups",
- body: {
- name: "E2E Source Group - Partner Group Mismatch",
- slug: sourceSlug,
- color: randomValue(RESOURCE_COLORS),
- },
- });
-
- expect(nonMatchingSourceStatus).toEqual(201);
-
- const { status: targetStatus, data: targetGroup } =
- await http.post<PartnerGroup>({
- path: "/groups",
- body: {
- name: "E2E Target Group - Partner Group Mismatch",
- slug,
- color: randomValue(RESOURCE_COLORS),
- },
- });
-
- expect(targetStatus).toEqual(201);
-
- onTestFinished(async () => {
- await http.delete({ path: `/groups/${targetGroup.id}` });
- await http.delete({ path: `/groups/${nonMatchingSourceGroup.id}` });
- });
-
- const { status: patchStatus } = await http.patch({
- path: `/groups/${targetGroup.id}`,
- body: {
- moveRules: [
- {
- attribute: "totalLeads",
- operator: "between",
- value: { min: 1, max: 2 },
- },
- {
- attribute: "partnerGroup",
- operator: "eq",
- value: allowedSourceGroup.id,
- },
- ],
- },
- });
-
- expect(patchStatus).toEqual(200);
-
- const { status: partnerStatus, data: partner } =
- await http.post<EnrolledPartnerProps>({
- path: "/partners",
- body: {
- name: "E2E Test Partner - Partner Group Mismatch",
- email: randomPartnerEmail(),
- groupId: nonMatchingSourceGroup.id,
- },
- });
-
- expect(partnerStatus).toEqual(201);
- expect(partner.links).not.toBeNull();
- expect(partner.groupId).toBe(nonMatchingSourceGroup.id);
-
- const partnerLink = partner.links![0];
-
- await trackE2ELead(http, partnerLink);
-
- await new Promise((resolve) => setTimeout(resolve, 10000));
-
- const { data: partnerAfter } = await http.get<EnrolledPartnerProps>({
- path: `/partners/${partner.id}`,
- });
-
- expect(partnerAfter.groupId).toBe(nonMatchingSourceGroup.id);
- });
-
- test("Workflow skips partner with groupMoveDisabledAt set", async () => {
- const slug = "e2e-target-skip-partner-move";
-
- // Get the current group of E2E_PARTNER
- const { data: partner, status: partnerStatus } = await http.get<
- EnrolledPartnerProps & { groupMoveDisabledAt: Date }
- >({
- path: `/partners/${E2E_PARTNER.id}`,
- });
-
- expect(partnerStatus).toEqual(200);
- expect(partner).not.toBeNull();
- expect(partner.groupMoveDisabledAt).not.toBeNull();
-
- const partnerLink = partner.links![0];
-
- // Create a new group
- const { data: targetGroup } = await http.post<PartnerGroup>({
- path: "/groups",
- body: {
- name: "E2E Target Group - Skip Partner Move",
- slug,
- color: randomValue(RESOURCE_COLORS),
- },
- });
-
- expect(targetGroup).not.toBeNull();
-
- onTestFinished(async () => {
- await http.delete({
- path: `/groups/${targetGroup.id}`,
- });
- });
-
- // Update the group with move rule
- const { status: patchStatus } = await http.patch({
- path: `/groups/${targetGroup.id}`,
- body: {
- moveRules: [
- {
- attribute: "totalLeads",
- operator: "gte",
- value: 1000,
- },
- ],
- },
- });
-
- expect(patchStatus).toEqual(200);
-
- await trackE2ELead(http, partnerLink);
-
- await verifyPartnerGroupMove({
- http,
- partnerId: partner.id,
- expectedGroupId: partner.groupId!,
- });
-
- const { data: partnerAfter } = await http.get<
- EnrolledPartnerProps & { groupMoveDisabledAt: Date }
- >({
- path: `/partners/${partner.id}`,
- });
-
- expect(partnerAfter.groupId).toBe(partner.groupId);
- expect(partnerAfter.groupMoveDisabledAt).not.toBeNull();
- });
-});
diff --git a/apps/web/tests/workflows/utils/verify-partner-group-move.ts b/apps/web/tests/workflows/utils/verify-partner-group-move.ts
deleted file mode 100644
index 2a9bd2a6aa..0000000000
--- a/apps/web/tests/workflows/utils/verify-partner-group-move.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import {
- VITEST_POLL_INTERVAL_MS,
- VITEST_TEST_TIMEOUT_MS,
-} from "@/lib/constants/misc";
-import { EnrolledPartnerProps } from "@/lib/types";
-import { expect } from "vitest";
-import { HttpClient } from "../../utils/http";
-
-interface VerifyPartnerGroupMoveProps {
- http: HttpClient;
- partnerId: string;
- expectedGroupId: string;
- query?: Record<string, string>;
-}
-
-export const verifyPartnerGroupMove = async ({
- http,
- partnerId,
- expectedGroupId,
- query = {},
-}: VerifyPartnerGroupMoveProps) => {
- const startTime = Date.now();
- let lastGroupId: string | null = null;
-
- while (Date.now() - startTime < VITEST_TEST_TIMEOUT_MS) {
- const { data: partner } = await http.get<EnrolledPartnerProps>({
- path: `/partners/${partnerId}`,
- query,
- });
-
- lastGroupId = partner?.groupId ?? null;
-
- if (partner?.groupId === expectedGroupId) {
- expect(partner.groupId).toBe(expectedGroupId);
- return partner;
- }
-
- await new Promise((resolve) =>
- setTimeout(resolve, VITEST_POLL_INTERVAL_MS),
- );
- }
-
- throw new Error(
- `Partner group move not found within ${VITEST_TEST_TIMEOUT_MS / 1000} seconds. ` +
- `partnerId: ${partnerId}, expectedGroupId: ${expectedGroupId}. ` +
- `Last seen groupId: ${lastGroupId}`,
- );
-};