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.

Assert commission metadata on list, detail, and PATCH API responses.

Kiran K5f97b0c8eae5
diff --git a/apps/web/lib/api/commissions/create-manual-commissions.ts b/apps/web/lib/api/commissions/create-manual-commissions.ts
index ab4987ba0d..ae23cbcfcd 100644
--- a/apps/web/lib/api/commissions/create-manual-commissions.ts
+++ b/apps/web/lib/api/commissions/create-manual-commissions.ts
@@ -475,29 +475,12 @@ async function recordEvents(args: RecordEventsArgs) {
// Record sale events
let saleEvents: z.infer<typeof saleEventSchemaTBWithTimestamp>[] = [];
- // Only persist user-provided sale.metadata on the commission (not deprecated top-level productId).
+
+ // Only persist user-provided sale.metadata on the commission
let commissionMetadata: Record<string, unknown> | null = null;
if (type === "sale") {
- const { importStripeInvoices, sale } = args;
-
- const invoiceId = sale?.invoiceId ?? args.invoiceId;
- const productId = sale?.metadata?.productId ?? args.productId;
- const saleEventDate = args.date ?? args.saleEventDate ?? Date.now();
- const eventName = sale?.eventName ?? "Purchase";
- const paymentProcessor = sale?.paymentProcessor ?? "custom";
- let saleAmount = sale?.amount ?? args.saleAmount;
- let currency = sale?.currency ?? "usd";
-
- // Include productId in Tinybird event metadata for Sale → Product ID reward modifiers.
- const eventMetadata = {
- ...(productId ? { productId } : {}),
- ...(sale?.metadata ?? {}),
- };
-
- commissionMetadata = sale?.metadata ?? null;
-
- if (importStripeInvoices) {
+ if (args.importStripeInvoices) {
saleEvents = stripeCustomerInvoices.map((invoice) =>
saleEventSchemaTBWithTimestamp.parse({
...clickEvent,
@@ -512,13 +495,29 @@ async function recordEvents(args: RecordEventsArgs) {
metadata: JSON.stringify(invoice.metadata),
}),
);
- } else if (saleAmount) {
- // For non-USD currencies, convert the sale amount to USD based on the current FX rate
+ } else {
+ const { sale } = args;
+ const invoiceId = sale?.invoiceId ?? args.invoiceId;
+ const productId = sale?.metadata?.productId ?? args.productId;
+ const saleEventDate = args.date ?? args.saleEventDate ?? Date.now();
+ const eventName = sale?.eventName ?? "Purchase";
+ const paymentProcessor = sale?.paymentProcessor ?? "custom";
+ let currency = sale?.currency ?? "usd";
+ let saleAmount = sale?.amount ?? args.saleAmount;
+
+ const eventMetadata = {
+ ...(productId ? { productId } : {}),
+ ...(sale?.metadata ?? {}),
+ };
+
+ commissionMetadata = sale?.metadata ?? null;
+
+ // Convert the non-USD sale amount to USD based on the current FX rate
if (currency !== "usd") {
const { currency: convertedCurrency, amount: convertedAmount } =
await convertCurrency({
currency,
- amount: saleAmount,
+ amount: saleAmount!,
});
currency = convertedCurrency;
diff --git a/apps/web/playwright/api/commissions/commissions.spec.ts b/apps/web/playwright/api/commissions/commissions.spec.ts
index 54bf42a73b..cf5acc0bcc 100644
--- a/apps/web/playwright/api/commissions/commissions.spec.ts
+++ b/apps/web/playwright/api/commissions/commissions.spec.ts
@@ -1,5 +1,6 @@
import { createId } from "@/lib/api/create-id";
import { prisma } from "@/lib/prisma";
+import type { CommissionResponse } from "@/lib/types";
import { redis } from "@/lib/upstash";
import { nanoid } from "@dub/utils";
import { expect } from "@playwright/test";
@@ -54,6 +55,7 @@ test.describe("Custom commissions", () => {
).toEqual(expectedQueuedResponse);
await expectCommissionCreated({
+ api,
partnerId,
programId: program.id,
type: "custom",
@@ -76,6 +78,7 @@ test.describe("Custom commissions", () => {
).toEqual(expectedClawbackResponse);
await expectCommissionCreated({
+ api,
partnerId,
programId: program.id,
type: "custom",
@@ -127,6 +130,7 @@ test.describe("Lead commissions", () => {
).toEqual(expectedQueuedResponse);
await expectCommissionCreated({
+ api,
partnerId,
programId: program.id,
type: "lead",
@@ -157,6 +161,7 @@ test.describe("Lead commissions", () => {
).toEqual(expectedQueuedResponse);
await expectCommissionCreated({
+ api,
partnerId,
programId: program.id,
type: "lead",
@@ -186,6 +191,7 @@ test.describe("Lead commissions", () => {
).toEqual(expectedQueuedResponse);
await expectCommissionCreated({
+ api,
partnerId,
programId: program.id,
type: "lead",
@@ -211,6 +217,7 @@ test.describe("Lead commissions", () => {
).toEqual(expectedQueuedResponse);
await expectCommissionCreated({
+ api,
partnerId,
programId: program.id,
type: "lead",
@@ -255,6 +262,7 @@ test.describe("Sale commissions", () => {
).toEqual(expectedQueuedResponse);
await expectCommissionCreated({
+ api,
partnerId,
programId: program.id,
type: "sale",
@@ -288,6 +296,7 @@ test.describe("Sale commissions", () => {
).toEqual(expectedQueuedResponse);
await expectCommissionCreated({
+ api,
partnerId,
programId: program.id,
type: "sale",
@@ -300,6 +309,47 @@ test.describe("Sale commissions", () => {
});
});
+ test("PATCH preserves metadata on the response", async ({ api, program }) => {
+ const invoiceId = `INV_${nanoid()}`;
+ const metadata = { plan: "pro", campaign: "spring" };
+
+ await withCommissionPartner(api, program, async (partnerId) => {
+ expect(
+ await api.post("/api/commissions", {
+ type: "sale",
+ partnerId,
+ sale: {
+ amount: 1000,
+ invoiceId,
+ metadata,
+ },
+ customer: customerBody(),
+ }),
+ ).toEqual(expectedQueuedResponse);
+
+ const commissionId = await expectCommissionCreated({
+ api,
+ partnerId,
+ programId: program.id,
+ type: "sale",
+ invoiceId,
+ expectedMetadata: metadata,
+ });
+
+ const { status, data } = await api.patch<CommissionResponse>(
+ `/api/commissions/${commissionId}`,
+ { earnings: 2500 },
+ );
+
+ expect(status).toEqual(200);
+ expect(data).toMatchObject({
+ id: commissionId,
+ earnings: 2500,
+ metadata,
+ });
+ });
+ });
+
test("creates using nested sale with string amount", async ({
api,
program,
@@ -320,6 +370,7 @@ test.describe("Sale commissions", () => {
).toEqual(expectedQueuedResponse);
await expectCommissionCreated({
+ api,
partnerId,
programId: program.id,
type: "sale",
@@ -350,6 +401,7 @@ test.describe("Sale commissions", () => {
).toEqual(expectedQueuedResponse);
await expectCommissionCreated({
+ api,
partnerId,
programId: program.id,
type: "sale",
@@ -384,6 +436,7 @@ test.describe("Sale commissions", () => {
).toEqual(expectedQueuedResponse);
await expectCommissionCreated({
+ api,
partnerId,
programId: program.id,
type: "sale",
@@ -418,6 +471,7 @@ test.describe("Sale commissions", () => {
).toEqual(expectedQueuedResponse);
await expectCommissionCreated({
+ api,
partnerId,
programId: program.id,
type: "sale",
@@ -443,6 +497,7 @@ test.describe("Sale commissions", () => {
).toEqual(expectedQueuedResponse);
await expectCommissionCreated({
+ api,
partnerId,
programId: program.id,
type: "sale",
@@ -478,6 +533,7 @@ test.describe("Sale commissions", () => {
).toEqual(expectedQueuedResponse);
await expectCommissionCreated({
+ api,
partnerId,
programId: program.id,
type: "sale",
@@ -514,6 +570,7 @@ test.describe("Sale commissions", () => {
).toEqual(expectedQueuedResponse);
await expectCommissionCreated({
+ api,
partnerId,
programId: program.id,
type: "sale",
diff --git a/apps/web/playwright/api/commissions/helpers.ts b/apps/web/playwright/api/commissions/helpers.ts
index 4acbf07508..1252491b01 100644
--- a/apps/web/playwright/api/commissions/helpers.ts
+++ b/apps/web/playwright/api/commissions/helpers.ts
@@ -1,4 +1,5 @@
import { prisma } from "@/lib/prisma";
+import type { CommissionResponse } from "@/lib/types";
import { expect } from "@playwright/test";
import type { ApiClient } from "../fixtures";
import { createPartner, deletePartner } from "../partners/helpers";
@@ -54,6 +55,7 @@ export async function deleteCommissionPartner({
}
export async function expectCommissionCreated({
+ api,
partnerId,
programId,
type,
@@ -64,6 +66,7 @@ export async function expectCommissionCreated({
expectedCreatedAt,
expectedMetadata,
}: {
+ api: ApiClient;
partnerId: string;
programId: string;
type: "custom" | "lead" | "sale";
@@ -73,7 +76,7 @@ export async function expectCommissionCreated({
expectedEarnings?: number;
expectedCreatedAt?: Date;
expectedMetadata?: Record<string, unknown> | null;
-}) {
+}): Promise<string> {
const amount =
expectedAmount ?? (type === "lead" ? 0 : type === "sale" ? 1000 : 0);
const earnings =
@@ -83,6 +86,10 @@ export async function expectCommissionCreated({
: type === "sale"
? TEST_COMMISSION_REWARDS.sale.amountInCents
: 0);
+ const metadata =
+ expectedMetadata === undefined ? null : expectedMetadata;
+
+ let commissionId: string | undefined;
await expect
.poll(async () => {
@@ -103,6 +110,8 @@ export async function expectCommissionCreated({
return null;
}
+ commissionId = commission.id;
+
return {
partnerId: commission.partnerId,
programId: commission.programId,
@@ -130,6 +139,46 @@ export async function expectCommissionCreated({
createdAt: expectedCreatedAt
? expectedCreatedAt.toISOString()
: expect.any(String),
- metadata: expectedMetadata === undefined ? null : expectedMetadata,
+ metadata,
});
+
+ if (!commissionId) {
+ throw new Error("Commission was not created");
+ }
+
+ const listQuery = new URLSearchParams({
+ partnerId,
+ type,
+ ...(invoiceId ? { invoiceId } : {}),
+ });
+
+ const { status: listStatus, data: commissions } = await api.get<
+ CommissionResponse[]
+ >(`/api/commissions?${listQuery}`);
+
+ expect(listStatus).toEqual(200);
+
+ const listed = invoiceId
+ ? commissions.find((c) => c.invoiceId === invoiceId)
+ : description
+ ? commissions.find((c) => c.description === description)
+ : commissions.find((c) => c.id === commissionId);
+
+ expect(listed).toMatchObject({
+ id: commissionId,
+ type,
+ metadata,
+ });
+
+ const { status: detailStatus, data: detail } =
+ await api.get<CommissionResponse>(`/api/commissions/${commissionId}`);
+
+ expect(detailStatus).toEqual(200);
+ expect(detail).toMatchObject({
+ id: commissionId,
+ type,
+ metadata,
+ });
+
+ return commissionId;
}
diff --git a/apps/web/tests/commissions/index.test.ts b/apps/web/tests/commissions/index.test.ts
index cb6c927b4d..a372e0a4e9 100644
--- a/apps/web/tests/commissions/index.test.ts
+++ b/apps/web/tests/commissions/index.test.ts
@@ -16,6 +16,23 @@ const expectedCommission = {
customer: expect.any(Object),
};
+function expectCommissionResponse(
+ commission: CommissionResponse,
+ overrides: Record<string, unknown> = {},
+) {
+ expect(commission).toMatchObject({
+ ...expectedCommission,
+ ...overrides,
+ });
+ // metadata is nullable but must be present on workspace commission responses
+ expect(commission).toHaveProperty("metadata");
+ expect(
+ commission.metadata === null ||
+ (typeof commission.metadata === "object" &&
+ !Array.isArray(commission.metadata)),
+ ).toBe(true);
+}
+
describe.sequential("/commissions/**", async () => {
const h = new IntegrationHarness();
const { http } = await h.init();
@@ -37,7 +54,7 @@ describe.sequential("/commissions/**", async () => {
expect(status).toEqual(200);
expect(Array.isArray(commissions)).toBe(true);
expect(commissions.length).toBeGreaterThan(0);
- expect(commissions[0]).toMatchObject(expectedCommission);
+ expectCommissionResponse(commissions[0]);
// Store the first sale and lead commission's ID for subsequent tests
testCommissionId = commissions.find((c) => c.type === "sale")!.id;
@@ -60,7 +77,7 @@ describe.sequential("/commissions/**", async () => {
expect(paidStatus).toEqual(200);
expect(Array.isArray(paidCommissions)).toBe(true);
expect(paidCommissions.length).toBeGreaterThan(0);
- expect(paidCommissions[0]).toMatchObject(expectedCommission);
+ expectCommissionResponse(paidCommissions[0]);
testPaidCommissionId = paidCommissions[0].id;
});
@@ -75,10 +92,7 @@ describe.sequential("/commissions/**", async () => {
});
expect(status).toEqual(200);
- expect(commission).toMatchObject({
- ...expectedCommission,
- earnings: toUpdate.earnings,
- });
+ expectCommissionResponse(commission, { earnings: toUpdate.earnings });
});
test("PATCH /commissions/{id} - update saleAmount", async () => {
@@ -92,10 +106,7 @@ describe.sequential("/commissions/**", async () => {
});
expect(status).toEqual(200);
- expect(commission).toMatchObject({
- ...expectedCommission,
- amount: toUpdate.saleAmount,
- });
+ expectCommissionResponse(commission, { amount: toUpdate.saleAmount });
});
test("PATCH /commissions/{id} - modifySaleAmount", async () => {
@@ -111,6 +122,7 @@ describe.sequential("/commissions/**", async () => {
expect(status).toEqual(200);
expect(commission.amount).toEqual(6000);
+ expectCommissionResponse(commission, { amount: 6000 });
});
test("PATCH /commissions/{id} - update amount (backward compatibility)", async () => {
@@ -124,10 +136,7 @@ describe.sequential("/commissions/**", async () => {
});
expect(status).toEqual(200);
- expect(commission).toMatchObject({
- ...expectedCommission,
- amount: toUpdate.amount,
- });
+ expectCommissionResponse(commission, { amount: toUpdate.amount });
});
test("PATCH /commissions/{id} - foreign currency conversion", async () => {
@@ -145,6 +154,7 @@ describe.sequential("/commissions/**", async () => {
expect(commission.currency).toEqual("usd");
expect(commission.amount).toBeGreaterThanOrEqual(900); // 900 cents
expect(commission.amount).toBeLessThanOrEqual(1100); // 1100 cents
+ expectCommissionResponse(commission);
});
test("PATCH /commissions/{id} - error on lead commission", async () => {
@@ -186,9 +196,6 @@ describe.sequential("/commissions/**", async () => {
});
expect(status).toEqual(200);
- expect(commission).toMatchObject({
- ...expectedCommission,
- status: toUpdate.status,
- });
+ expectCommissionResponse(commission, { status: toUpdate.status });
});
});