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 reward tests to Playwright (#4454)

Kiran Kd6d4c0ea111f
diff --git a/apps/web/playwright/api/conversions/helpers.ts b/apps/web/playwright/api/conversions/helpers.ts
index 3c68b1d978..4bf14a7edf 100644
--- a/apps/web/playwright/api/conversions/helpers.ts
+++ b/apps/web/playwright/api/conversions/helpers.ts
@@ -51,7 +51,7 @@ export async function trackClick({
TRACK_CLICK_HEADERS,
);
- expect(status).toEqual(200);
+ expect(status, JSON.stringify(data)).toEqual(200);
expect(data.clickId).toEqual(expect.any(String));
return data as { clickId: string };
@@ -71,13 +71,43 @@ export async function trackLead({
customerExternalId: customer.externalId,
customerEmail: customer.email,
customerName: customer.name,
+ mode: "wait",
...overrides,
});
- expect(status).toEqual(200);
+ expect(status, JSON.stringify(data)).toEqual(200);
return {
customer,
data,
};
}
+
+export async function trackSale({
+ customerExternalId,
+ ...overrides
+}: {
+ customerExternalId: string;
+} & Record<string, unknown>) {
+ const invoiceId =
+ (overrides.invoiceId as string | undefined) ?? `INV_${nanoid()}`;
+ const amount = (overrides.amount as number | undefined) ?? 1000;
+
+ const { status, data } = await postAuthenticatedJson("/api/track/sale", {
+ customerExternalId,
+ amount,
+ currency: "usd",
+ paymentProcessor: "stripe",
+ eventName: "Purchase",
+ invoiceId,
+ ...overrides,
+ });
+
+ expect(status, JSON.stringify(data)).toEqual(200);
+
+ return {
+ invoiceId,
+ amount,
+ data,
+ };
+}
diff --git a/apps/web/playwright/api/links/links-bulk.spec.ts b/apps/web/playwright/api/links/links-bulk.spec.ts
index 6856159e54..0ce500c7fd 100644
--- a/apps/web/playwright/api/links/links-bulk.spec.ts
+++ b/apps/web/playwright/api/links/links-bulk.spec.ts
@@ -46,6 +46,10 @@ function isBulkError(item: BulkLink | BulkLinkError): item is BulkLinkError {
return "error" in item;
}
+function isBulkLink(item: BulkLink | BulkLinkError): item is BulkLink {
+ return !isBulkError(item);
+}
+
test("POST /links/bulk – with valid programId and partnerId", async ({
api,
program,
@@ -63,7 +67,7 @@ test("POST /links/bulk – with valid programId and partnerId", async ({
});
const { status, data } = await createBulkLinks(api, [body]);
- const created = data.filter((item) => !isBulkError(item));
+ const created = data.filter(isBulkLink);
createdIds.push(...created.map((link) => link.id));
expect(status).toEqual(200);
@@ -95,7 +99,7 @@ test("POST /links/bulk – rejects invalid programId", async ({ api }) => {
invalidBody,
validBody,
]);
- const created = data.filter((item) => !isBulkError(item));
+ const created = data.filter(isBulkLink);
const errors = data.filter(isBulkError);
createdIds.push(...created.map((link) => link.id));
@@ -132,7 +136,7 @@ test("POST /links/bulk – rejects invalid partnerId", async ({
invalidBody,
validBody,
]);
- const created = data.filter((item) => !isBulkError(item));
+ const created = data.filter(isBulkLink);
const errors = data.filter(isBulkError);
createdIds.push(...created.map((link) => link.id));
@@ -166,7 +170,7 @@ test("PATCH /links/bulk – with valid programId and partnerId", async ({
bulkLinkBody(),
bulkLinkBody(),
]);
- const links = created.filter((item) => !isBulkError(item));
+ const links = created.filter(isBulkLink);
createdIds.push(...links.map((link) => link.id));
expect(links).toHaveLength(2);
@@ -204,7 +208,7 @@ test("PATCH /links/bulk – rejects invalid programId", async ({ api }) => {
try {
const { data: created } = await createBulkLinks(api, [bulkLinkBody()]);
- const links = created.filter((item) => !isBulkError(item));
+ const links = created.filter(isBulkLink);
createdIds.push(...links.map((link) => link.id));
expect(
@@ -239,7 +243,7 @@ test("PATCH /links/bulk – rejects invalid partnerId", async ({
try {
const { data: created } = await createBulkLinks(api, [bulkLinkBody()]);
- const links = created.filter((item) => !isBulkError(item));
+ const links = created.filter(isBulkLink);
createdIds.push(...links.map((link) => link.id));
expect(
diff --git a/apps/web/playwright/api/rewards/click-reward.spec.ts b/apps/web/playwright/api/rewards/click-reward.spec.ts
new file mode 100644
index 0000000000..9239469155
--- /dev/null
+++ b/apps/web/playwright/api/rewards/click-reward.spec.ts
@@ -0,0 +1,183 @@
+import { getRewardAmount } from "@/lib/partners/get-reward-amount";
+import type { RewardConditionsArray } from "@/lib/types";
+import { expect } from "@playwright/test";
+import { EventType, Prisma, Reward, RewardStructure } from "@prisma/client";
+import { resolveClickReward } from "../../../app/(ee)/api/cron/aggregate-clicks/resolve-click-reward-amount";
+import { test } from "../fixtures";
+import { createReward, deleteReward, updateReward } from "./helpers";
+
+const countryInModifier: RewardConditionsArray = [
+ {
+ operator: "AND",
+ type: RewardStructure.flat,
+ amountInCents: 100,
+ conditions: [
+ {
+ entity: "customer",
+ attribute: "country",
+ operator: "in",
+ value: ["US", "GB", "AU"],
+ },
+ ],
+ },
+];
+
+function resolvedAmount(reward: Reward, country: string) {
+ const resolved = resolveClickReward({ reward, country });
+
+ return getRewardAmount({
+ type: resolved.type,
+ amountInCents: resolved.amountInCents,
+ amountInPercentage:
+ resolved.amountInPercentage != null
+ ? Number(resolved.amountInPercentage)
+ : null,
+ });
+}
+
+test.describe("Click reward resolution", () => {
+ // Shared reward; serial so modifiers can be updated between tests.
+ test.describe.configure({ mode: "serial" });
+
+ let rewardId: string | undefined;
+
+ test.beforeAll(async ({ program }) => {
+ const reward = await createReward({
+ programId: program.id,
+ event: EventType.click,
+ type: RewardStructure.flat,
+ amountInCents: 20,
+ modifiers: countryInModifier,
+ });
+
+ rewardId = reward.id;
+ });
+
+ test.afterAll(async () => {
+ await deleteReward(rewardId);
+ });
+
+ test("countries in modifier list get modifier amount; others get base", async () => {
+ const reward = await updateReward(rewardId!, {
+ modifiers: countryInModifier,
+ });
+
+ const testCases = [
+ { country: "US", expected: 100 },
+ { country: "GB", expected: 100 },
+ { country: "AU", expected: 100 },
+ { country: "CA", expected: 20 },
+ { country: "FR", expected: 20 },
+ { country: "DE", expected: 20 },
+ { country: "JP", expected: 20 },
+ ];
+
+ for (const { country, expected } of testCases) {
+ expect(resolvedAmount(reward, country)).toBe(expected);
+ }
+ });
+
+ test("equals_to country modifier matches only that country", async () => {
+ const reward = await updateReward(rewardId!, {
+ modifiers: [
+ {
+ operator: "AND",
+ type: RewardStructure.flat,
+ amountInCents: 100,
+ conditions: [
+ {
+ entity: "customer",
+ attribute: "country",
+ operator: "equals_to",
+ value: "US",
+ },
+ ],
+ },
+ ],
+ });
+
+ expect(resolvedAmount(reward, "US")).toBe(100);
+ expect(resolvedAmount(reward, "GB")).toBe(20);
+ expect(resolvedAmount(reward, "CA")).toBe(20);
+ });
+
+ test("not_in country modifier excludes listed countries", async () => {
+ const reward = await updateReward(rewardId!, {
+ modifiers: [
+ {
+ operator: "AND",
+ type: RewardStructure.flat,
+ amountInCents: 100,
+ conditions: [
+ {
+ entity: "customer",
+ attribute: "country",
+ operator: "not_in",
+ value: ["US"],
+ },
+ ],
+ },
+ ],
+ });
+
+ expect(resolvedAmount(reward, "US")).toBe(20);
+ expect(resolvedAmount(reward, "GB")).toBe(100);
+ expect(resolvedAmount(reward, "CA")).toBe(100);
+ });
+
+ test("null modifiers always use base amount", async () => {
+ const reward = await updateReward(rewardId!, {
+ modifiers: Prisma.JsonNull,
+ });
+
+ expect(reward.modifiers).toBeNull();
+ expect(resolvedAmount(reward, "US")).toBe(20);
+ expect(resolvedAmount(reward, "GB")).toBe(20);
+ });
+
+ test("overlapping modifier groups pick the highest amount", async () => {
+ const reward = await updateReward(rewardId!, {
+ modifiers: [
+ {
+ operator: "AND",
+ type: RewardStructure.flat,
+ amountInCents: 100,
+ conditions: [
+ {
+ entity: "customer",
+ attribute: "country",
+ operator: "equals_to",
+ value: "US",
+ },
+ ],
+ },
+ {
+ operator: "AND",
+ type: RewardStructure.flat,
+ amountInCents: 250,
+ conditions: [
+ {
+ entity: "customer",
+ attribute: "country",
+ operator: "in",
+ value: ["US", "GB"],
+ },
+ ],
+ },
+ ],
+ });
+
+ expect(resolvedAmount(reward, "US")).toBe(250);
+ expect(resolvedAmount(reward, "GB")).toBe(250);
+ expect(resolvedAmount(reward, "CA")).toBe(20);
+ });
+
+ test("invalid modifiers JSON falls back to base amount", async () => {
+ const reward = await updateReward(rewardId!, {
+ modifiers: {},
+ });
+
+ expect(resolvedAmount(reward, "US")).toBe(20);
+ expect(resolvedAmount(reward, "GB")).toBe(20);
+ });
+});
diff --git a/apps/web/playwright/api/rewards/helpers.ts b/apps/web/playwright/api/rewards/helpers.ts
new file mode 100644
index 0000000000..46d8ed823f
--- /dev/null
+++ b/apps/web/playwright/api/rewards/helpers.ts
@@ -0,0 +1,36 @@
+import { createId } from "@/lib/api/create-id";
+import { prisma } from "@/lib/prisma";
+import type { Prisma, Reward } from "@prisma/client";
+
+export async function createReward(
+ data: Omit<Prisma.RewardUncheckedCreateInput, "id">,
+): Promise<Reward> {
+ return prisma.reward.create({
+ data: {
+ id: createId({ prefix: "rw_" }),
+ ...data,
+ },
+ });
+}
+
+export async function updateReward(
+ rewardId: string,
+ data: Prisma.RewardUncheckedUpdateInput,
+) {
+ return prisma.reward.update({
+ where: {
+ id: rewardId,
+ },
+ data,
+ });
+}
+
+export async function deleteReward(rewardId: string | undefined) {
+ if (!rewardId) return;
+
+ await prisma.reward.delete({
+ where: {
+ id: rewardId,
+ },
+ });
+}
diff --git a/apps/web/playwright/api/rewards/lead-reward.spec.ts b/apps/web/playwright/api/rewards/lead-reward.spec.ts
new file mode 100644
index 0000000000..485d00717a
--- /dev/null
+++ b/apps/web/playwright/api/rewards/lead-reward.spec.ts
@@ -0,0 +1,779 @@
+import { prisma } from "@/lib/prisma";
+import type {
+ CommissionResponse,
+ Customer,
+ EnrolledPartnerProps,
+ LinkProps,
+ RewardConditionsArray,
+} from "@/lib/types";
+import { expect } from "@playwright/test";
+import { EventType, Prisma, RewardStructure } from "@prisma/client";
+import { randomCustomer } from "../../utils";
+import { deleteCommissionPartner } from "../commissions/helpers";
+import { trackClick, trackLead } from "../conversions/helpers";
+import { test, type ApiClient } from "../fixtures";
+import { createPartner } from "../partners/helpers";
+import { createReward, deleteReward, updateReward } from "./helpers";
+
+const BASE_AMOUNT = 100;
+const MODIFIER_AMOUNT = 500;
+
+type LeadRewardCtx = {
+ api: ApiClient;
+ partnerId: string;
+ programId: string;
+ workspaceId: string;
+ link: Pick<LinkProps, "id" | "domain" | "key">;
+};
+
+const planProMetadataModifier: RewardConditionsArray = [
+ {
+ operator: "AND",
+ type: RewardStructure.flat,
+ amountInCents: MODIFIER_AMOUNT,
+ conditions: [
+ {
+ entity: "lead",
+ attribute: "metadata",
+ metadataField: "plan",
+ operator: "equals_to",
+ value: "pro",
+ },
+ ],
+ },
+];
+
+function modifier(
+ conditions: RewardConditionsArray[number]["conditions"],
+ amountInCents = MODIFIER_AMOUNT,
+): RewardConditionsArray {
+ return [
+ {
+ operator: "AND",
+ type: RewardStructure.flat,
+ amountInCents,
+ conditions,
+ },
+ ];
+}
+
+async function resetPartnerState(
+ ctx: LeadRewardCtx,
+ { country = "US" }: { country?: string } = {},
+) {
+ await prisma.partner.update({
+ where: {
+ id: ctx.partnerId,
+ },
+ data: {
+ country,
+ },
+ });
+
+ await prisma.link.update({
+ where: {
+ id: ctx.link.id,
+ },
+ data: {
+ clicks: 0,
+ leads: 0,
+ conversions: 0,
+ sales: 0,
+ saleAmount: 0,
+ },
+ });
+
+ await prisma.programEnrollment.update({
+ where: {
+ partnerId_programId: {
+ partnerId: ctx.partnerId,
+ programId: ctx.programId,
+ },
+ },
+ data: {
+ totalCommissions: 0,
+ },
+ });
+}
+
+async function trackPartnerLead(
+ ctx: LeadRewardCtx,
+ overrides: Record<string, unknown> = {},
+): Promise<{ customerExternalId: string }> {
+ const { clickId } = await trackClick({
+ domain: ctx.link.domain,
+ key: ctx.link.key,
+ });
+
+ const { customer } = await trackLead({
+ clickId,
+ eventName: "Signup",
+ ...overrides,
+ });
+
+ return {
+ customerExternalId:
+ (overrides.customerExternalId as string | undefined) ??
+ customer.externalId,
+ };
+}
+
+async function expectLeadCommission(
+ ctx: LeadRewardCtx,
+ {
+ customerExternalId,
+ expectedEarnings,
+ expectedMetadata,
+ }: {
+ customerExternalId: string;
+ expectedEarnings: number;
+ expectedMetadata?: Record<string, unknown> | null;
+ },
+) {
+ let customerId: string | undefined;
+
+ await expect
+ .poll(async () => {
+ const customer = await prisma.customer.findUnique({
+ where: {
+ projectId_externalId: {
+ projectId: ctx.workspaceId,
+ externalId: customerExternalId,
+ },
+ },
+ });
+
+ if (!customer) {
+ return null;
+ }
+
+ customerId = customer.id;
+
+ const commission = await prisma.commission.findFirst({
+ where: {
+ partnerId: ctx.partnerId,
+ programId: ctx.programId,
+ type: "lead",
+ customerId,
+ },
+ orderBy: {
+ createdAt: "desc",
+ },
+ });
+
+ if (!commission) {
+ return null;
+ }
+
+ return {
+ earnings: Number(commission.earnings),
+ metadata: commission.metadata,
+ };
+ })
+ .toEqual({
+ earnings: expectedEarnings,
+ metadata: expectedMetadata === undefined ? null : expectedMetadata,
+ });
+
+ const listQuery = new URLSearchParams({
+ partnerId: ctx.partnerId,
+ type: "lead",
+ customerId: customerId!,
+ });
+
+ const { status, data: commissions } = await ctx.api.get<CommissionResponse[]>(
+ `/api/commissions?${listQuery}`,
+ );
+
+ expect(status).toEqual(200);
+ expect(commissions.length).toBeGreaterThan(0);
+ expect(commissions[0]).toMatchObject({
+ type: "lead",
+ earnings: expectedEarnings,
+ ...(expectedMetadata !== undefined ? { metadata: expectedMetadata } : {}),
+ });
+}
+
+async function expectNoCommission(
+ ctx: LeadRewardCtx,
+ { customerExternalId }: { customerExternalId: string },
+) {
+ // Give the create-partner-commission workflow time to run (and skip).
+ await new Promise((resolve) => setTimeout(resolve, 5_000));
+
+ const customer = await prisma.customer.findUnique({
+ where: {
+ projectId_externalId: {
+ projectId: ctx.workspaceId,
+ externalId: customerExternalId,
+ },
+ },
+ });
+
+ expect(customer).toBeTruthy();
+
+ const commission = await prisma.commission.findFirst({
+ where: {
+ partnerId: ctx.partnerId,
+ programId: ctx.programId,
+ type: "lead",
+ customerId: customer!.id,
+ },
+ });
+
+ expect(commission).toBeNull();
+}
+
+async function expectLeadCommissionCount(
+ ctx: LeadRewardCtx,
+ {
+ customerExternalId,
+ count,
+ }: {
+ customerExternalId: string;
+ count: number;
+ },
+) {
+ const customer = await prisma.customer.findUniqueOrThrow({
+ where: {
+ projectId_externalId: {
+ projectId: ctx.workspaceId,
+ externalId: customerExternalId,
+ },
+ },
+ });
+
+ // Give a follow-up create-partner-commission workflow time to run (or skip).
+ await new Promise((resolve) => setTimeout(resolve, 5_000));
+
+ await expect
+ .poll(async () => {
+ return prisma.commission.count({
+ where: {
+ partnerId: ctx.partnerId,
+ programId: ctx.programId,
+ type: "lead",
+ customerId: customer.id,
+ },
+ });
+ })
+ .toEqual(count);
+}
+
+test.describe("Lead rewards", () => {
+ // Shared reward + enrollment; serial so modifiers can be updated between tests.
+ // No retries: a failed case leaves shared reward/partner state that would flake on retry.
+ test.describe.configure({ mode: "serial", retries: 0 });
+
+ let rewardId: string | undefined;
+ let ctx: LeadRewardCtx | undefined;
+
+ test.beforeAll(async ({ api, program, workspace }) => {
+ const reward = await createReward({
+ programId: program.id,
+ event: EventType.lead,
+ type: RewardStructure.flat,
+ amountInCents: BASE_AMOUNT,
+ maxDuration: 0,
+ });
+
+ const { data } = await createPartner(api, {
+ groupId: program.defaultGroupId,
+ country: "US",
+ });
+
+ const partner = data as EnrolledPartnerProps;
+ expect(partner.links?.[0]).toBeTruthy();
+
+ rewardId = reward.id;
+ ctx = {
+ api,
+ partnerId: partner.id,
+ programId: program.id,
+ workspaceId: workspace.id,
+ link: partner.links![0],
+ };
+
+ // Detach the default group's lead reward so the first test has none.
+ await prisma.programEnrollment.update({
+ where: {
+ partnerId_programId: {
+ partnerId: partner.id,
+ programId: program.id,
+ },
+ },
+ data: {
+ leadRewardId: null,
+ },
+ });
+ });
+
+ test.afterAll(async () => {
+ await deleteCommissionPartner({ partnerId: ctx?.partnerId });
+ await deleteReward(rewardId);
+ });
+
+ test("no lead reward skips commission creation", async () => {
+ const { customerExternalId } = await trackPartnerLead(ctx!);
+ await expectNoCommission(ctx!, { customerExternalId });
+ });
+
+ test("base reward with no conditions uses base amount", async () => {
+ await prisma.programEnrollment.update({
+ where: {
+ partnerId_programId: {
+ partnerId: ctx!.partnerId,
+ programId: ctx!.programId,
+ },
+ },
+ data: {
+ leadRewardId: rewardId!,
+ },
+ });
+
+ await updateReward(rewardId!, {
+ modifiers: Prisma.JsonNull,
+ });
+
+ const { customerExternalId } = await trackPartnerLead(ctx!);
+ await expectLeadCommission(ctx!, {
+ customerExternalId,
+ expectedEarnings: BASE_AMOUNT,
+ });
+ });
+
+ test("does not create a second lead commission for the same customer and partner", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: Prisma.JsonNull,
+ });
+
+ const customer = randomCustomer();
+ const { customerExternalId } = await trackPartnerLead(ctx!, {
+ eventName: "Signup",
+ customerExternalId: customer.externalId,
+ customerEmail: customer.email,
+ customerName: customer.name,
+ });
+ await expectLeadCommission(ctx!, {
+ customerExternalId,
+ expectedEarnings: BASE_AMOUNT,
+ });
+
+ // Different eventName so /track/lead is not Redis-deduped; commission
+ // workflow should still skip because a lead commission already exists.
+ await trackPartnerLead(ctx!, {
+ eventName: "Requested demo",
+ customerExternalId: customer.externalId,
+ customerEmail: customer.email,
+ customerName: customer.name,
+ });
+ await expectLeadCommissionCount(ctx!, {
+ customerExternalId,
+ count: 1,
+ });
+ });
+
+ test("customer source equals_to tracked matches", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "customer",
+ attribute: "source",
+ operator: "equals_to",
+ value: "tracked",
+ },
+ ]),
+ });
+
+ const { customerExternalId } = await trackPartnerLead(ctx!);
+ await expectLeadCommission(ctx!, {
+ customerExternalId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("customer source equals_to submitted misses and uses base", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "customer",
+ attribute: "source",
+ operator: "equals_to",
+ value: "submitted",
+ },
+ ]),
+ });
+
+ const { customerExternalId } = await trackPartnerLead(ctx!);
+ await expectLeadCommission(ctx!, {
+ customerExternalId,
+ expectedEarnings: BASE_AMOUNT,
+ });
+ });
+
+ test("customer country equals_to US matches", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "customer",
+ attribute: "country",
+ operator: "equals_to",
+ value: "US",
+ },
+ ]),
+ });
+
+ const { customerExternalId } = await trackPartnerLead(ctx!);
+ await expectLeadCommission(ctx!, {
+ customerExternalId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("customer country equals_to CA matches pre-created customer", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "customer",
+ attribute: "country",
+ operator: "equals_to",
+ value: "CA",
+ },
+ ]),
+ });
+
+ const customer = randomCustomer();
+ const { status } = await ctx!.api.post<Customer>("/api/customers", {
+ ...customer,
+ country: "CA",
+ });
+ expect(status).toEqual(201);
+
+ const { customerExternalId } = await trackPartnerLead(ctx!, {
+ customerExternalId: customer.externalId,
+ customerEmail: customer.email,
+ customerName: customer.name,
+ });
+
+ await expectLeadCommission(ctx!, {
+ customerExternalId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("partner country equals_to US matches", async () => {
+ await resetPartnerState(ctx!, { country: "US" });
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "partner",
+ attribute: "country",
+ operator: "equals_to",
+ value: "US",
+ },
+ ]),
+ });
+
+ const { customerExternalId } = await trackPartnerLead(ctx!);
+ await expectLeadCommission(ctx!, {
+ customerExternalId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("partner country equals_to US misses for SG partner", async () => {
+ await resetPartnerState(ctx!, { country: "SG" });
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "partner",
+ attribute: "country",
+ operator: "equals_to",
+ value: "US",
+ },
+ ]),
+ });
+
+ const { customerExternalId } = await trackPartnerLead(ctx!);
+ await expectLeadCommission(ctx!, {
+ customerExternalId,
+ expectedEarnings: BASE_AMOUNT,
+ });
+ });
+
+ test("partner totalClicks greater_than matches seeded clicks", async () => {
+ await resetPartnerState(ctx!);
+ await prisma.link.update({
+ where: {
+ id: ctx!.link.id,
+ },
+ data: {
+ clicks: 50,
+ },
+ });
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "partner",
+ attribute: "totalClicks",
+ operator: "greater_than",
+ value: 40,
+ },
+ ]),
+ });
+
+ const { customerExternalId } = await trackPartnerLead(ctx!);
+ await expectLeadCommission(ctx!, {
+ customerExternalId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("partner totalClicks greater_than misses when clicks are zero", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "partner",
+ attribute: "totalClicks",
+ operator: "greater_than",
+ value: 50,
+ },
+ ]),
+ });
+
+ const { customerExternalId } = await trackPartnerLead(ctx!);
+ await expectLeadCommission(ctx!, {
+ customerExternalId,
+ expectedEarnings: BASE_AMOUNT,
+ });
+ });
+
+ test("partner totalLeads greater_than matches seeded leads", async () => {
+ await resetPartnerState(ctx!);
+ await prisma.link.update({
+ where: {
+ id: ctx!.link.id,
+ },
+ data: {
+ leads: 50,
+ },
+ });
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "partner",
+ attribute: "totalLeads",
+ operator: "greater_than",
+ value: 40,
+ },
+ ]),
+ });
+
+ const { customerExternalId } = await trackPartnerLead(ctx!);
+ await expectLeadCommission(ctx!, {
+ customerExternalId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("partner totalConversions greater_than matches seeded conversions", async () => {
+ await resetPartnerState(ctx!);
+ await prisma.link.update({
+ where: {
+ id: ctx!.link.id,
+ },
+ data: {
+ conversions: 50,
+ },
+ });
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "partner",
+ attribute: "totalConversions",
+ operator: "greater_than",
+ value: 40,
+ },
+ ]),
+ });
+
+ const { customerExternalId } = await trackPartnerLead(ctx!);
+ await expectLeadCommission(ctx!, {
+ customerExternalId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("partner totalSaleAmount greater_than matches seeded saleAmount", async () => {
+ await resetPartnerState(ctx!);
+ await prisma.link.update({
+ where: {
+ id: ctx!.link.id,
+ },
+ data: {
+ saleAmount: 50_00,
+ },
+ });
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "partner",
+ attribute: "totalSaleAmount",
+ operator: "greater_than",
+ value: 40_00,
+ },
+ ]),
+ });
+
+ const { customerExternalId } = await trackPartnerLead(ctx!);
+ await expectLeadCommission(ctx!, {
+ customerExternalId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("partner totalCommissions greater_than matches seeded enrollment total", async () => {
+ await resetPartnerState(ctx!);
+ await prisma.programEnrollment.update({
+ where: {
+ partnerId_programId: {
+ partnerId: ctx!.partnerId,
+ programId: ctx!.programId,
+ },
+ },
+ data: {
+ totalCommissions: 50_00,
+ },
+ });
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "partner",
+ attribute: "totalCommissions",
+ operator: "greater_than",
+ value: 40_00,
+ },
+ ]),
+ });
+
+ const { customerExternalId } = await trackPartnerLead(ctx!);
+ await expectLeadCommission(ctx!, {
+ customerExternalId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("lead metadata plan equals_to pro matches", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: planProMetadataModifier,
+ });
+
+ const metadata = { plan: "pro" };
+ const { customerExternalId } = await trackPartnerLead(ctx!, { metadata });
+ await expectLeadCommission(ctx!, {
+ customerExternalId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ expectedMetadata: metadata,
+ });
+ });
+
+ test("lead metadata plan equals_to pro misses without metadata", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: planProMetadataModifier,
+ });
+
+ const { customerExternalId } = await trackPartnerLead(ctx!);
+ await expectLeadCommission(ctx!, {
+ customerExternalId,
+ expectedEarnings: BASE_AMOUNT,
+ });
+ });
+
+ test("when customer country is US and partner country is US", async () => {
+ await resetPartnerState(ctx!, { country: "US" });
+ await updateReward(rewardId!, {
+ modifiers: [
+ {
+ operator: "AND",
+ type: RewardStructure.flat,
+ amountInCents: 200,
+ conditions: [
+ {
+ entity: "customer",
+ attribute: "country",
+ operator: "equals_to",
+ value: "US",
+ },
+ ],
+ },
+ {
+ operator: "AND",
+ type: RewardStructure.flat,
+ amountInCents: 300,
+ conditions: [
+ {
+ entity: "partner",
+ attribute: "country",
+ operator: "equals_to",
+ value: "US",
+ },
+ ],
+ },
+ ],
+ });
+
+ const { customerExternalId } = await trackPartnerLead(ctx!);
+ await expectLeadCommission(ctx!, {
+ customerExternalId,
+ expectedEarnings: 300,
+ });
+ });
+
+ test("when customer country is US and partner country is not US", async () => {
+ await resetPartnerState(ctx!, { country: "SG" });
+ await updateReward(rewardId!, {
+ modifiers: [
+ {
+ operator: "AND",
+ type: RewardStructure.flat,
+ amountInCents: 200,
+ conditions: [
+ {
+ entity: "customer",
+ attribute: "country",
+ operator: "equals_to",
+ value: "US",
+ },
+ ],
+ },
+ {
+ operator: "AND",
+ type: RewardStructure.flat,
+ amountInCents: 300,
+ conditions: [
+ {
+ entity: "partner",
+ attribute: "country",
+ operator: "equals_to",
+ value: "US",
+ },
+ ],
+ },
+ ],
+ });
+
+ const { customerExternalId } = await trackPartnerLead(ctx!);
+ await expectLeadCommission(ctx!, {
+ customerExternalId,
+ expectedEarnings: 200,
+ });
+ });
+});
diff --git a/apps/web/playwright/api/rewards/sale-reward.spec.ts b/apps/web/playwright/api/rewards/sale-reward.spec.ts
new file mode 100644
index 0000000000..916b1d3ca1
--- /dev/null
+++ b/apps/web/playwright/api/rewards/sale-reward.spec.ts
@@ -0,0 +1,1146 @@
+import { prisma } from "@/lib/prisma";
+import type {
+ CommissionResponse,
+ EnrolledPartnerProps,
+ LinkProps,
+ RewardConditionsArray,
+} from "@/lib/types";
+import { expect } from "@playwright/test";
+import { EventType, Prisma, RewardStructure } from "@prisma/client";
+import { deleteCommissionPartner } from "../commissions/helpers";
+import { trackClick, trackLead, trackSale } from "../conversions/helpers";
+import { test, type ApiClient } from "../fixtures";
+import { createPartner } from "../partners/helpers";
+import { createReward, deleteReward, updateReward } from "./helpers";
+
+const BASE_AMOUNT = 100;
+const MODIFIER_AMOUNT = 500;
+const SALE_AMOUNT = 1000;
+
+type SaleRewardCtx = {
+ api: ApiClient;
+ partnerId: string;
+ programId: string;
+ workspaceId: string;
+ link: Pick<LinkProps, "id" | "domain" | "key">;
+};
+
+const bookTitleMetadataModifier: RewardConditionsArray = [
+ {
+ operator: "AND",
+ type: RewardStructure.flat,
+ amountInCents: MODIFIER_AMOUNT,
+ conditions: [
+ {
+ entity: "sale",
+ attribute: "metadata",
+ metadataField: "bookTitle",
+ operator: "equals_to",
+ value: "THGTTG",
+ },
+ ],
+ },
+];
+
+function modifier(
+ conditions: RewardConditionsArray[number]["conditions"],
+ amountInCents = MODIFIER_AMOUNT,
+): RewardConditionsArray {
+ return [
+ {
+ operator: "AND",
+ type: RewardStructure.flat,
+ amountInCents,
+ conditions,
+ },
+ ];
+}
+
+async function resetPartnerState(
+ ctx: SaleRewardCtx,
+ { country = "US" }: { country?: string } = {},
+) {
+ await prisma.partner.update({
+ where: {
+ id: ctx.partnerId,
+ },
+ data: {
+ country,
+ },
+ });
+
+ await prisma.link.update({
+ where: {
+ id: ctx.link.id,
+ },
+ data: {
+ clicks: 0,
+ leads: 0,
+ conversions: 0,
+ sales: 0,
+ saleAmount: 0,
+ },
+ });
+
+ await prisma.programEnrollment.update({
+ where: {
+ partnerId_programId: {
+ partnerId: ctx.partnerId,
+ programId: ctx.programId,
+ },
+ },
+ data: {
+ totalCommissions: 0,
+ },
+ });
+}
+
+async function trackPartnerSale(
+ ctx: SaleRewardCtx,
+ overrides: Record<string, unknown> = {},
+): Promise<{
+ customerExternalId: string;
+ invoiceId: string;
+ amount: number;
+}> {
+ const customerExternalIdOverride = overrides.customerExternalId as
+ | string
+ | undefined;
+ const saleOverrides = { ...overrides };
+ delete saleOverrides.customerExternalId;
+ delete saleOverrides.customerEmail;
+ delete saleOverrides.customerName;
+
+ const { clickId } = await trackClick({
+ domain: ctx.link.domain,
+ key: ctx.link.key,
+ });
+
+ const { customer } = await trackLead({
+ clickId,
+ eventName: "Signup",
+ ...(customerExternalIdOverride
+ ? {
+ customerExternalId: customerExternalIdOverride,
+ customerEmail: overrides.customerEmail,
+ customerName: overrides.customerName,
+ }
+ : {}),
+ });
+
+ const customerExternalId = customerExternalIdOverride ?? customer.externalId;
+
+ const { invoiceId, amount } = await trackSale({
+ customerExternalId,
+ amount: SALE_AMOUNT,
+ ...saleOverrides,
+ });
+
+ return {
+ customerExternalId,
+ invoiceId,
+ amount,
+ };
+}
+
+async function trackSaleForCustomer(
+ ctx: SaleRewardCtx,
+ {
+ customerExternalId,
+ ...overrides
+ }: {
+ customerExternalId: string;
+ } & Record<string, unknown>,
+): Promise<{ invoiceId: string; amount: number }> {
+ return trackSale({
+ customerExternalId,
+ amount: SALE_AMOUNT,
+ ...overrides,
+ });
+}
+
+async function expectSaleCommission(
+ ctx: SaleRewardCtx,
+ {
+ invoiceId,
+ expectedEarnings,
+ expectedMetadata,
+ }: {
+ invoiceId: string;
+ expectedEarnings: number;
+ expectedMetadata?: Record<string, unknown> | null;
+ },
+) {
+ await expect
+ .poll(async () => {
+ const commission = await prisma.commission.findFirst({
+ where: {
+ partnerId: ctx.partnerId,
+ programId: ctx.programId,
+ type: "sale",
+ invoiceId,
+ },
+ orderBy: {
+ createdAt: "desc",
+ },
+ });
+
+ if (!commission) {
+ return null;
+ }
+
+ return {
+ earnings: Number(commission.earnings),
+ metadata: commission.metadata,
+ };
+ })
+ .toEqual({
+ earnings: expectedEarnings,
+ metadata: expectedMetadata === undefined ? null : expectedMetadata,
+ });
+
+ const listQuery = new URLSearchParams({
+ partnerId: ctx.partnerId,
+ type: "sale",
+ invoiceId,
+ });
+
+ const { status, data: commissions } = await ctx.api.get<CommissionResponse[]>(
+ `/api/commissions?${listQuery}`,
+ );
+
+ expect(status).toEqual(200);
+ expect(commissions.length).toBeGreaterThan(0);
+ expect(commissions[0]).toMatchObject({
+ type: "sale",
+ earnings: expectedEarnings,
+ invoiceId,
+ ...(expectedMetadata !== undefined ? { metadata: expectedMetadata } : {}),
+ });
+}
+
+async function expectNoSaleCommission(
+ ctx: SaleRewardCtx,
+ { invoiceId }: { invoiceId: string },
+) {
+ // Give the create-partner-commission workflow time to run (and skip).
+ await new Promise((resolve) => setTimeout(resolve, 5_000));
+
+ const commission = await prisma.commission.findFirst({
+ where: {
+ partnerId: ctx.partnerId,
+ programId: ctx.programId,
+ type: "sale",
+ invoiceId,
+ },
+ });
+
+ expect(commission).toBeNull();
+}
+
+async function expectSaleCommissionCount(
+ ctx: SaleRewardCtx,
+ {
+ customerExternalId,
+ count,
+ }: {
+ customerExternalId: string;
+ count: number;
+ },
+) {
+ const customer = await prisma.customer.findUniqueOrThrow({
+ where: {
+ projectId_externalId: {
+ projectId: ctx.workspaceId,
+ externalId: customerExternalId,
+ },
+ },
+ });
+
+ // Give a follow-up create-partner-commission workflow time to run (or skip).
+ await new Promise((resolve) => setTimeout(resolve, 5_000));
+
+ await expect
+ .poll(async () => {
+ return prisma.commission.count({
+ where: {
+ partnerId: ctx.partnerId,
+ programId: ctx.programId,
+ type: "sale",
+ customerId: customer.id,
+ },
+ });
+ })
+ .toEqual(count);
+}
+
+test.describe("Sale rewards", () => {
+ // Shared reward + enrollment; serial so modifiers can be updated between tests.
+ // No retries: a failed case leaves shared reward/partner state that would flake on retry.
+ test.describe.configure({ mode: "serial", retries: 0 });
+
+ let rewardId: string | undefined;
+ let ctx: SaleRewardCtx | undefined;
+
+ test.beforeAll(async ({ api, program, workspace }) => {
+ const reward = await createReward({
+ programId: program.id,
+ event: EventType.sale,
+ type: RewardStructure.flat,
+ amountInCents: BASE_AMOUNT,
+ maxDuration: null,
+ });
+
+ const { data } = await createPartner(api, {
+ groupId: program.defaultGroupId,
+ country: "US",
+ });
+
+ const partner = data as EnrolledPartnerProps;
+ expect(partner.links?.[0]).toBeTruthy();
+
+ rewardId = reward.id;
+ ctx = {
+ api,
+ partnerId: partner.id,
+ programId: program.id,
+ workspaceId: workspace.id,
+ link: partner.links![0],
+ };
+
+ // Detach default group rewards so the first test has none, and so
+ // track/lead does not enqueue a lead commission before sale jobs.
+ await prisma.programEnrollment.update({
+ where: {
+ partnerId_programId: {
+ partnerId: partner.id,
+ programId: program.id,
+ },
+ },
+ data: {
+ saleRewardId: null,
+ leadRewardId: null,
+ },
+ });
+ });
+
+ test.afterAll(async () => {
+ await deleteCommissionPartner({ partnerId: ctx?.partnerId });
+ await deleteReward(rewardId);
+ });
+
+ test("no sale reward skips commission creation", async () => {
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectNoSaleCommission(ctx!, { invoiceId });
+ });
+
+ test("base reward with no conditions uses base amount", async () => {
+ await prisma.programEnrollment.update({
+ where: {
+ partnerId_programId: {
+ partnerId: ctx!.partnerId,
+ programId: ctx!.programId,
+ },
+ },
+ data: {
+ saleRewardId: rewardId!,
+ },
+ });
+
+ await updateReward(rewardId!, {
+ modifiers: Prisma.JsonNull,
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: BASE_AMOUNT,
+ });
+ });
+
+ test("does not create a second sale commission when maxDuration is 0", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: Prisma.JsonNull,
+ maxDuration: 0,
+ });
+
+ const { customerExternalId, invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: BASE_AMOUNT,
+ });
+
+ await trackSaleForCustomer(ctx!, { customerExternalId });
+ await expectSaleCommissionCount(ctx!, {
+ customerExternalId,
+ count: 1,
+ });
+
+ await updateReward(rewardId!, {
+ maxDuration: null,
+ });
+ });
+
+ test("customer source equals_to tracked matches", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "customer",
+ attribute: "source",
+ operator: "equals_to",
+ value: "tracked",
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("customer source equals_to submitted misses and uses base", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "customer",
+ attribute: "source",
+ operator: "equals_to",
+ value: "submitted",
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: BASE_AMOUNT,
+ });
+ });
+
+ test("customer country equals_to US matches", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "customer",
+ attribute: "country",
+ operator: "equals_to",
+ value: "US",
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("customer country equals_to SG matches after updating customer country", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "customer",
+ attribute: "country",
+ operator: "equals_to",
+ value: "SG",
+ },
+ ]),
+ });
+
+ // track/sale requires customer.linkId; POST /api/customers alone leaves it
+ // null. Create via click+lead, then override country before the sale.
+ const { clickId } = await trackClick({
+ domain: ctx!.link.domain,
+ key: ctx!.link.key,
+ });
+ const { customer } = await trackLead({
+ clickId,
+ eventName: "Signup",
+ });
+
+ await prisma.customer.update({
+ where: {
+ projectId_externalId: {
+ projectId: ctx!.workspaceId,
+ externalId: customer.externalId,
+ },
+ },
+ data: {
+ country: "SG",
+ },
+ });
+
+ const { invoiceId } = await trackSale({
+ customerExternalId: customer.externalId,
+ amount: SALE_AMOUNT,
+ });
+
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("customer signupDate window matches", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "customer",
+ attribute: "signupDate",
+ operator: "greater_than",
+ value: new Date("2026-02-16T00:00:00.000Z").getTime(),
+ },
+ {
+ entity: "customer",
+ attribute: "signupDate",
+ operator: "less_than",
+ value: new Date("2026-02-18T00:00:00.000Z").getTime(),
+ },
+ ]),
+ });
+
+ const { clickId } = await trackClick({
+ domain: ctx!.link.domain,
+ key: ctx!.link.key,
+ });
+ const { customer } = await trackLead({
+ clickId,
+ eventName: "Signup",
+ });
+
+ await prisma.customer.update({
+ where: {
+ projectId_externalId: {
+ projectId: ctx!.workspaceId,
+ externalId: customer.externalId,
+ },
+ },
+ data: {
+ createdAt: new Date("2026-02-17T00:00:00.000Z"),
+ },
+ });
+
+ const { invoiceId } = await trackSale({
+ customerExternalId: customer.externalId,
+ amount: SALE_AMOUNT,
+ });
+
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("customer signupDate window misses for current signup", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "customer",
+ attribute: "signupDate",
+ operator: "greater_than",
+ value: new Date("2026-02-16T00:00:00.000Z").getTime(),
+ },
+ {
+ entity: "customer",
+ attribute: "signupDate",
+ operator: "less_than",
+ value: new Date("2026-02-18T00:00:00.000Z").getTime(),
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: BASE_AMOUNT,
+ });
+ });
+
+ test("customer subscriptionDurationMonths less_than_or_equal 3 matches first sale", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "customer",
+ attribute: "subscriptionDurationMonths",
+ operator: "less_than_or_equal",
+ value: 3,
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("customer subscriptionDurationMonths less_than_or_equal 3 misses after 4 months", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "customer",
+ attribute: "subscriptionDurationMonths",
+ operator: "less_than_or_equal",
+ value: 3,
+ },
+ ]),
+ });
+
+ const { customerExternalId, invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+
+ const fourMonthsAgo = new Date();
+ fourMonthsAgo.setMonth(fourMonthsAgo.getMonth() - 4);
+
+ await prisma.commission.updateMany({
+ where: {
+ partnerId: ctx!.partnerId,
+ programId: ctx!.programId,
+ type: "sale",
+ invoiceId,
+ },
+ data: {
+ createdAt: fourMonthsAgo,
+ },
+ });
+
+ const second = await trackSaleForCustomer(ctx!, { customerExternalId });
+ await expectSaleCommission(ctx!, {
+ invoiceId: second.invoiceId,
+ expectedEarnings: BASE_AMOUNT,
+ });
+ });
+
+ test("customer subscriptionStartDate greater_than recent cutoff matches", async () => {
+ await resetPartnerState(ctx!);
+ const cutoff = Date.now() - 24 * 60 * 60 * 1000;
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "customer",
+ attribute: "subscriptionStartDate",
+ operator: "greater_than",
+ value: cutoff,
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("customer subscriptionStartDate greater_than future cutoff misses", async () => {
+ await resetPartnerState(ctx!);
+ const cutoff = Date.now() + 24 * 60 * 60 * 1000;
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "customer",
+ attribute: "subscriptionStartDate",
+ operator: "greater_than",
+ value: cutoff,
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: BASE_AMOUNT,
+ });
+ });
+
+ test("partner country equals_to US matches", async () => {
+ await resetPartnerState(ctx!, { country: "US" });
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "partner",
+ attribute: "country",
+ operator: "equals_to",
+ value: "US",
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("partner country equals_to US misses for SG partner", async () => {
+ await resetPartnerState(ctx!, { country: "SG" });
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "partner",
+ attribute: "country",
+ operator: "equals_to",
+ value: "US",
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: BASE_AMOUNT,
+ });
+ });
+
+ test("partner totalClicks greater_than matches seeded clicks", async () => {
+ await resetPartnerState(ctx!);
+ await prisma.link.update({
+ where: {
+ id: ctx!.link.id,
+ },
+ data: {
+ clicks: 50,
+ },
+ });
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "partner",
+ attribute: "totalClicks",
+ operator: "greater_than",
+ value: 40,
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("partner totalClicks greater_than misses when clicks are zero", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "partner",
+ attribute: "totalClicks",
+ operator: "greater_than",
+ value: 50,
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: BASE_AMOUNT,
+ });
+ });
+
+ test("partner totalLeads greater_than matches seeded leads", async () => {
+ await resetPartnerState(ctx!);
+ await prisma.link.update({
+ where: {
+ id: ctx!.link.id,
+ },
+ data: {
+ leads: 50,
+ },
+ });
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "partner",
+ attribute: "totalLeads",
+ operator: "greater_than",
+ value: 40,
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("partner totalConversions greater_than matches seeded conversions", async () => {
+ await resetPartnerState(ctx!);
+ await prisma.link.update({
+ where: {
+ id: ctx!.link.id,
+ },
+ data: {
+ conversions: 50,
+ },
+ });
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "partner",
+ attribute: "totalConversions",
+ operator: "greater_than",
+ value: 40,
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("partner totalSaleAmount greater_than matches seeded saleAmount", async () => {
+ await resetPartnerState(ctx!);
+ await prisma.link.update({
+ where: {
+ id: ctx!.link.id,
+ },
+ data: {
+ saleAmount: 50_00,
+ },
+ });
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "partner",
+ attribute: "totalSaleAmount",
+ operator: "greater_than",
+ value: 40_00,
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("partner totalCommissions greater_than matches seeded enrollment total", async () => {
+ await resetPartnerState(ctx!);
+ await prisma.programEnrollment.update({
+ where: {
+ partnerId_programId: {
+ partnerId: ctx!.partnerId,
+ programId: ctx!.programId,
+ },
+ },
+ data: {
+ totalCommissions: 50_00,
+ },
+ });
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "partner",
+ attribute: "totalCommissions",
+ operator: "greater_than",
+ value: 40_00,
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("sale productId equals_to premiumProductId matches", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "sale",
+ attribute: "productId",
+ operator: "equals_to",
+ value: "premiumProductId",
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!, {
+ metadata: {
+ productId: "premiumProductId",
+ },
+ });
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ expectedMetadata: {
+ productId: "premiumProductId",
+ },
+ });
+ });
+
+ test("sale productId equals_to premiumProductId misses for regularProductId", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "sale",
+ attribute: "productId",
+ operator: "equals_to",
+ value: "premiumProductId",
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!, {
+ metadata: {
+ productId: "regularProductId",
+ },
+ });
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: BASE_AMOUNT,
+ expectedMetadata: {
+ productId: "regularProductId",
+ },
+ });
+ });
+
+ test("sale amount greater_than 15000 matches", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "sale",
+ attribute: "amount",
+ operator: "greater_than",
+ value: 15000,
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!, {
+ amount: 17500,
+ });
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("sale amount greater_than 15000 misses for default amount", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "sale",
+ attribute: "amount",
+ operator: "greater_than",
+ value: 15000,
+ },
+ ]),
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: BASE_AMOUNT,
+ });
+ });
+
+ test("sale type equals_to new matches first sale and misses recurring", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "sale",
+ attribute: "type",
+ operator: "equals_to",
+ value: "new",
+ },
+ ]),
+ });
+
+ const { customerExternalId, invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+
+ const second = await trackSaleForCustomer(ctx!, { customerExternalId });
+ await expectSaleCommission(ctx!, {
+ invoiceId: second.invoiceId,
+ expectedEarnings: BASE_AMOUNT,
+ });
+ });
+
+ test("sale type equals_to recurring misses first sale and matches second", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: modifier([
+ {
+ entity: "sale",
+ attribute: "type",
+ operator: "equals_to",
+ value: "recurring",
+ },
+ ]),
+ });
+
+ const { customerExternalId, invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: BASE_AMOUNT,
+ });
+
+ const second = await trackSaleForCustomer(ctx!, { customerExternalId });
+ await expectSaleCommission(ctx!, {
+ invoiceId: second.invoiceId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ });
+ });
+
+ test("sale metadata bookTitle equals_to THGTTG matches", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: bookTitleMetadataModifier,
+ });
+
+ const metadata = { bookTitle: "THGTTG" };
+ const { invoiceId } = await trackPartnerSale(ctx!, { metadata });
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: MODIFIER_AMOUNT,
+ expectedMetadata: metadata,
+ });
+ });
+
+ test("sale metadata bookTitle equals_to THGTTG misses without metadata", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: bookTitleMetadataModifier,
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!);
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: BASE_AMOUNT,
+ });
+ });
+
+ test("when sale productId is premium and amount is greater than 15000", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: [
+ {
+ operator: "AND",
+ type: RewardStructure.flat,
+ amountInCents: 200,
+ conditions: [
+ {
+ entity: "sale",
+ attribute: "productId",
+ operator: "equals_to",
+ value: "premiumProductId",
+ },
+ ],
+ },
+ {
+ operator: "AND",
+ type: RewardStructure.flat,
+ amountInCents: 300,
+ conditions: [
+ {
+ entity: "sale",
+ attribute: "amount",
+ operator: "greater_than",
+ value: 15000,
+ },
+ ],
+ },
+ ],
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!, {
+ amount: 17500,
+ metadata: {
+ productId: "premiumProductId",
+ },
+ });
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: 300,
+ expectedMetadata: {
+ productId: "premiumProductId",
+ },
+ });
+ });
+
+ test("when sale productId is premium and amount is not greater than 15000", async () => {
+ await resetPartnerState(ctx!);
+ await updateReward(rewardId!, {
+ modifiers: [
+ {
+ operator: "AND",
+ type: RewardStructure.flat,
+ amountInCents: 200,
+ conditions: [
+ {
+ entity: "sale",
+ attribute: "productId",
+ operator: "equals_to",
+ value: "premiumProductId",
+ },
+ ],
+ },
+ {
+ operator: "AND",
+ type: RewardStructure.flat,
+ amountInCents: 300,
+ conditions: [
+ {
+ entity: "sale",
+ attribute: "amount",
+ operator: "greater_than",
+ value: 15000,
+ },
+ ],
+ },
+ ],
+ });
+
+ const { invoiceId } = await trackPartnerSale(ctx!, {
+ amount: SALE_AMOUNT,
+ metadata: {
+ productId: "premiumProductId",
+ },
+ });
+ await expectSaleCommission(ctx!, {
+ invoiceId,
+ expectedEarnings: 200,
+ expectedMetadata: {
+ productId: "premiumProductId",
+ },
+ });
+ });
+});
diff --git a/apps/web/tests/rewards/click-reward.test.ts b/apps/web/tests/rewards/click-reward.test.ts
deleted file mode 100644
index 9ce0035c94..0000000000
--- a/apps/web/tests/rewards/click-reward.test.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { serializeReward } from "@/lib/api/partners/serialize-reward";
-import { getRewardAmount } from "@/lib/partners/get-reward-amount";
-import { Reward } from "@prisma/client";
-import { describe, expect, test, vi } from "vitest";
-import { resolveClickReward } from "../../app/(ee)/api/cron/aggregate-clicks/resolve-click-reward-amount";
-import { IntegrationHarness } from "../utils/integration";
-
-// Mock server-only module
-vi.mock("server-only", () => ({}));
-
-const REWARD_ID = "rw_ZE0KAEtZuOGwNHtoVm1U0JpF";
-
-describe.sequential("Click reward resolution", async () => {
- const h = new IntegrationHarness();
- const { http } = await h.init();
-
- // Fetch the reward from the API
- const { status, data: reward } = await http.get<Reward>({
- path: `/rewards/${REWARD_ID}`,
- });
-
- if (status !== 200 || !reward) {
- throw new Error(`Failed to fetch reward from API: ${status}`);
- }
-
- test("countries in modifier list (US, GB, AU) get modifier amount", () => {
- // The reward has modifiers: US, GB, AU should get 100 cents
- const modifierCountries = ["US", "GB", "AU"];
-
- modifierCountries.forEach((country) => {
- const clickReward = resolveClickReward({
- reward,
- country,
- });
-
- const amount = getRewardAmount(serializeReward(clickReward));
-
- expect(amount).toBe(100);
- });
- });
-
- test("countries not in modifier list get base amount", () => {
- // The reward base amount is 20 cents
- // Countries not in the modifier list should get the base amount
- const otherCountries = ["CA", "FR", "DE", "JP"];
-
- otherCountries.forEach((country) => {
- const clickReward = resolveClickReward({
- reward,
- country,
- });
-
- const amount = getRewardAmount(serializeReward(clickReward));
-
- expect(amount).toBe(20);
- });
- });
-
- test("all countries return expected amounts", () => {
- // Test all countries to ensure correct behavior
- const testCases = [
- { country: "US", expected: 100 },
- { country: "GB", expected: 100 },
- { country: "AU", expected: 100 },
- { country: "CA", expected: 20 },
- { country: "FR", expected: 20 },
- { country: "DE", expected: 20 },
- { country: "JP", expected: 20 },
- ];
-
- testCases.forEach(({ country, expected }) => {
- const clickReward = resolveClickReward({
- reward,
- country,
- });
-
- const amount = getRewardAmount(serializeReward(clickReward));
-
- expect(amount).toBe(expected);
- });
- });
-});
diff --git a/apps/web/tests/rewards/lead-reward.test.ts b/apps/web/tests/rewards/lead-reward.test.ts
deleted file mode 100644
index abf28bc906..0000000000
--- a/apps/web/tests/rewards/lead-reward.test.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-import { TrackLeadResponse } from "@/lib/types";
-import { randomCustomer } from "tests/utils/helpers";
-import {
- E2E_LEAD_REWARD,
- E2E_PARTNERS,
- E2E_TRACK_CLICK_HEADERS,
-} from "tests/utils/resource";
-import { verifyCommission } from "tests/utils/verify-commission";
-import { describe, expect, test } from "vitest";
-import { IntegrationHarness } from "../utils/integration";
-
-describe.concurrent("Lead rewards", async () => {
- const h = new IntegrationHarness();
- const { http } = await h.init();
-
- test("when customer country is US and partner country is US", async () => {
- // Track the click
- const clickResponse = await http.post<{ clickId: string }>({
- path: "/track/click",
- headers: E2E_TRACK_CLICK_HEADERS,
- body: E2E_PARTNERS[0].shortLink,
- });
-
- expect(clickResponse.status).toEqual(200);
-
- const clickId = clickResponse.data.clickId;
- const customer = randomCustomer();
-
- // Track the lead
- const trackLeadResponse = await http.post<TrackLeadResponse>({
- path: "/track/lead",
- body: {
- clickId,
- eventName: "Signup",
- customerExternalId: customer.externalId,
- customerName: customer.name,
- customerEmail: customer.email,
- customerAvatar: customer.avatar,
- },
- });
-
- expect(trackLeadResponse.status).toEqual(200);
-
- // Verify the commission
- await verifyCommission({
- http,
- customerExternalId: customer.externalId,
- expectedEarnings: E2E_LEAD_REWARD.modifiers[1].amountInCents,
- });
- });
-
- test("when customer country is US and partner country is not US", async () => {
- // Track the click
- const clickResponse = await http.post<{ clickId: string }>({
- path: "/track/click",
- headers: E2E_TRACK_CLICK_HEADERS,
- body: {
- ...E2E_PARTNERS[1].shortLink,
- },
- });
-
- expect(clickResponse.status).toEqual(200);
-
- const clickId = clickResponse.data.clickId;
- const customer = randomCustomer();
-
- // Track the lead
- const trackLeadResponse = await http.post<TrackLeadResponse>({
- path: "/track/lead",
- body: {
- clickId,
- eventName: "Signup",
- customerExternalId: customer.externalId,
- customerName: customer.name,
- customerEmail: customer.email,
- customerAvatar: customer.avatar,
- },
- });
-
- expect(trackLeadResponse.status).toEqual(200);
-
- // Verify the commission
- await verifyCommission({
- http,
- customerExternalId: customer.externalId,
- expectedEarnings: E2E_LEAD_REWARD.modifiers[0].amountInCents,
- });
- });
-});
diff --git a/apps/web/tests/rewards/sale-reward.test.ts b/apps/web/tests/rewards/sale-reward.test.ts
deleted file mode 100644
index f71d63f99d..0000000000
--- a/apps/web/tests/rewards/sale-reward.test.ts
+++ /dev/null
@@ -1,236 +0,0 @@
-import { TrackLeadResponse, TrackSaleResponse } from "@/lib/types";
-import {
- randomCustomer,
- randomId,
- randomSaleAmount,
-} from "tests/utils/helpers";
-import {
- E2E_CUSTOMER_COUNTRY_CONDITIONS_EXTERNAL_ID,
- E2E_CUSTOMER_SIGNUP_DATE_CONDITIONS_EXTERNAL_ID,
- E2E_PARTNERS,
- E2E_SALE_REWARD,
- E2E_TRACK_CLICK_HEADERS,
-} from "tests/utils/resource";
-import { verifyCommission } from "tests/utils/verify-commission";
-import { describe, expect, test } from "vitest";
-import { IntegrationHarness } from "../utils/integration";
-
-describe("Sale rewards with conditions", async () => {
- const h = new IntegrationHarness();
- const { http } = await h.init();
-
- const clickResponse = await http.post<{ clickId: string }>({
- path: "/track/click",
- headers: E2E_TRACK_CLICK_HEADERS,
- body: E2E_PARTNERS[0].shortLink,
- });
- expect(clickResponse.status).toEqual(200);
- const clickId = clickResponse.data.clickId;
- const newCustomer = randomCustomer();
- const trackLeadResponse = await http.post<TrackLeadResponse>({
- path: "/track/lead",
- body: {
- clickId,
- eventName: "Signup",
- customerExternalId: newCustomer.externalId,
- customerName: newCustomer.name,
- customerEmail: newCustomer.email,
- customerAvatar: newCustomer.avatar,
- mode: "wait",
- },
- });
- expect(trackLeadResponse.status).toEqual(200);
-
- const randomSale = (eventName = "Payment") => ({
- eventName,
- currency: "usd",
- paymentProcessor: "stripe",
- amount: randomSaleAmount(),
- invoiceId: `INV_${randomId()}`,
- });
-
- describe.sequential("sequential track/sale tests", () => {
- test("when {Sale} {Type} is {new} vs {recurring}", async () => {
- const sale = randomSale("E2E first sale");
-
- const trackSaleResponse = await http.post<TrackSaleResponse>({
- path: "/track/sale",
- body: {
- ...sale,
- customerExternalId: newCustomer.externalId,
- },
- });
-
- expect(trackSaleResponse.status).toEqual(200);
-
- await new Promise((resolve) => setTimeout(resolve, 3000));
-
- await verifyCommission({
- http,
- invoiceId: sale.invoiceId,
- expectedEarnings: E2E_SALE_REWARD.modifiers[5].amountInCents!,
- });
-
- // no need to verify second sale since it will be verified below
- // in the {Customer} {Subscription Duration} is {less than or equal to} {3} test
- });
-
- test("when {Customer} {Subscription Duration} is {less than or equal to} {3}", async () => {
- const sale = randomSale("E2E customer subscription duration condition");
- const trackSaleResponse = await http.post<TrackSaleResponse>({
- path: "/track/sale",
- body: {
- ...sale,
- customerExternalId: newCustomer.externalId,
- },
- });
-
- expect(trackSaleResponse.status).toEqual(200);
-
- await verifyCommission({
- http,
- invoiceId: sale.invoiceId,
- expectedEarnings: E2E_SALE_REWARD.modifiers[3].amountInCents!,
- });
- });
- });
-
- describe.concurrent("concurrent track/sale tests", () => {
- // skipping this for now because we're using a newCustomer for each test,
- // and {Customer} {Subscription Duration} is {less than or equal to} {3} blocks the base case
- test.skip("When {Sale} {Product ID} is {regularProductId}", async () => {
- const sale = randomSale("E2E base condition");
-
- const response = await http.post<TrackSaleResponse>({
- path: "/track/sale",
- body: {
- ...sale,
- customerExternalId: newCustomer.externalId,
- metadata: {
- productId: "regularProductId",
- },
- },
- });
-
- expect(response.status).toEqual(200);
-
- await verifyCommission({
- http,
- invoiceId: sale.invoiceId,
- expectedEarnings: E2E_SALE_REWARD.amountInCents,
- });
- });
-
- test("When {Sale} {Product ID} is {premiumProductId}", async () => {
- const sale = randomSale("E2E sale product ID condition");
-
- const response = await http.post<TrackSaleResponse>({
- path: "/track/sale",
- body: {
- ...sale,
- customerExternalId: newCustomer.externalId,
- metadata: {
- productId: "premiumProductId",
- },
- },
- });
-
- expect(response.status).toEqual(200);
-
- await verifyCommission({
- http,
- invoiceId: sale.invoiceId,
- expectedEarnings: E2E_SALE_REWARD.modifiers[0].amountInCents!,
- });
- });
-
- test("When {Sale} {Amount} is greater than {15000}", async () => {
- const sale = randomSale("E2E sale amount condition");
-
- const response = await http.post<TrackSaleResponse>({
- path: "/track/sale",
- body: {
- ...sale,
- amount: 17500,
- customerExternalId: newCustomer.externalId,
- metadata: {
- productId: "premiumProductId",
- },
- },
- });
-
- expect(response.status).toEqual(200);
-
- await verifyCommission({
- http,
- invoiceId: sale.invoiceId,
- expectedEarnings: E2E_SALE_REWARD.modifiers[1].amountInCents!,
- });
- });
-
- test("when {Customer} {Country} is {SG}", async () => {
- const sale = randomSale("E2E customer country condition");
-
- const trackSaleResponse = await http.post<TrackSaleResponse>({
- path: "/track/sale",
- body: {
- ...sale,
- customerExternalId: E2E_CUSTOMER_COUNTRY_CONDITIONS_EXTERNAL_ID,
- },
- });
-
- expect(trackSaleResponse.status).toEqual(200);
-
- await verifyCommission({
- http,
- invoiceId: sale.invoiceId,
- expectedEarnings: E2E_SALE_REWARD.modifiers[2].amountInCents!,
- });
- });
-
- test("when {Customer} {Signup Date} is {greater than} {Feb 16, 2026} AND {less than} {Feb 18, 2026}", async () => {
- const sale = randomSale("E2E customer signup date condition");
-
- const trackSaleResponse = await http.post<TrackSaleResponse>({
- path: "/track/sale",
- body: {
- ...sale,
- customerExternalId: E2E_CUSTOMER_SIGNUP_DATE_CONDITIONS_EXTERNAL_ID,
- },
- });
-
- expect(trackSaleResponse.status).toEqual(200);
-
- await verifyCommission({
- http,
- invoiceId: sale.invoiceId,
- expectedEarnings: E2E_SALE_REWARD.modifiers[4].amountInCents!,
- });
- });
-
- test("when {Sale} {Metadata} {Key} is {Value}", async () => {
- const sale = randomSale("E2E sale metadata key-value condition");
- const metadata = {
- bookTitle: "THGTTG",
- };
-
- const trackSaleResponse = await http.post<TrackSaleResponse>({
- path: "/track/sale",
- body: {
- ...sale,
- customerExternalId: newCustomer.externalId,
- metadata,
- },
- });
-
- expect(trackSaleResponse.status).toEqual(200);
-
- await verifyCommission({
- http,
- invoiceId: sale.invoiceId,
- expectedEarnings: E2E_SALE_REWARD.modifiers[6].amountInCents!,
- expectedMetadata: metadata,
- });
- });
- });
-});