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.

Convert nested sale currencies to USD and expose commission metadata on the API.

Kiran K1fc48453ffa3
diff --git a/apps/web/lib/api/commissions/create-manual-commissions.ts b/apps/web/lib/api/commissions/create-manual-commissions.ts
index 4364826c02..7e20b3e371 100644
--- a/apps/web/lib/api/commissions/create-manual-commissions.ts
+++ b/apps/web/lib/api/commissions/create-manual-commissions.ts
@@ -1,3 +1,4 @@
+import { convertCurrency } from "@/lib/analytics/convert-currency";
import { isFirstConversion } from "@/lib/analytics/is-first-conversion";
import { Session } from "@/lib/auth";
import { generateRandomName } from "@/lib/names";
@@ -488,11 +489,11 @@ async function recordEvents(args: RecordEventsArgs) {
const invoiceId = sale?.invoiceId ?? args.invoiceId;
const productId = sale?.metadata?.productId ?? args.productId;
- const saleAmount = sale?.amount ?? args.saleAmount;
const saleEventDate = args.date ?? args.saleEventDate ?? Date.now();
const eventName = sale?.eventName ?? "Purchase";
- const currency = sale?.currency ?? "usd";
const paymentProcessor = sale?.paymentProcessor ?? "custom";
+ let saleAmount = sale?.amount ?? args.saleAmount;
+ let currency = sale?.currency ?? "usd";
const metadata = {
...(productId ? { productId } : {}),
...(sale?.metadata ?? {}),
@@ -508,12 +509,24 @@ async function recordEvents(args: RecordEventsArgs) {
amount: invoice.amount,
customer_id: targetCustomer.id,
payment_processor: "stripe",
- currency,
+ currency: "usd",
timestamp: invoice.createdAt.toISOString(),
metadata: JSON.stringify(invoice.metadata),
}),
);
} else if (saleAmount) {
+ // For non-USD currencies, convert the sale amount to USD based on the current FX rate
+ if (currency !== "usd") {
+ const { currency: convertedCurrency, amount: convertedAmount } =
+ await convertCurrency({
+ currency,
+ amount: saleAmount,
+ });
+
+ currency = convertedCurrency;
+ saleAmount = convertedAmount;
+ }
+
saleEvents = [
saleEventSchemaTBWithTimestamp.parse({
...clickEvent,
diff --git a/apps/web/lib/webhook/sample-events/commission-created.json b/apps/web/lib/webhook/sample-events/commission-created.json
index ed322cbacc..f612bee91c 100644
--- a/apps/web/lib/webhook/sample-events/commission-created.json
+++ b/apps/web/lib/webhook/sample-events/commission-created.json
@@ -9,6 +9,7 @@
"description": null,
"quantity": 1,
"userId": "cludszk1h0000wmd2e0ea2b0p",
+ "metadata": null,
"createdAt": "2025-07-16T10:48:14.722Z",
"updatedAt": "2025-07-16T10:48:14.960Z",
"partner": {
diff --git a/apps/web/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.ts
index a757ed1b7c..5cdfc19895 100644
--- a/apps/web/lib/zod/schemas/commissions.ts
+++ b/apps/web/lib/zod/schemas/commissions.ts
@@ -19,20 +19,52 @@ export const CommissionSchema = z.object({
id: z.string().describe("The commission's unique ID on Dub.").meta({
example: "cm_1JVR7XRCSR0EDBAF39FZ4PMYE",
}),
- type: z.enum(CommissionType).optional(), // Note: Not sure the type will ever be optional
- amount: z.number(),
- earnings: z.number(),
- currency: z.string(),
- status: z.enum(CommissionStatus),
- invoiceId: z.string().nullable(),
- description: z.string().nullable(),
- quantity: z.number(),
+ type: z
+ .enum(CommissionType)
+ .describe(
+ "The type of commission. Can be `click`, `lead`, `sale`, `referral`, or `custom`.",
+ ),
+ amount: z
+ .number()
+ .describe(
+ "The associated event amount in cents. For sale commissions, this is the sale amount.",
+ ),
+ earnings: z.number().describe("The amount earned by the partner, in cents."),
+ currency: z
+ .string()
+ .describe("The currency of the commission, as an ISO 4217 currency code."),
+ status: z
+ .enum(CommissionStatus)
+ .describe("The current status of the commission."),
+ invoiceId: z
+ .string()
+ .nullable()
+ .describe("The associated invoice ID. Only set for sale commissions."),
+ description: z
+ .string()
+ .nullable()
+ .describe("An optional description of the commission."),
+ quantity: z
+ .number()
+ .describe(
+ "The event quantity. Used for click and lead commissions; typically `1` for sale and custom commissions.",
+ ),
userId: z
.string()
.nullish()
.describe("The user who created the manual commission."),
- createdAt: z.date(),
- updatedAt: z.date(),
+ metadata: z
+ .record(z.string(), z.any())
+ .nullable()
+ .describe(
+ "User-provided metadata from the associated lead or sale event (`lead.metadata` / `sale.metadata`).",
+ ),
+ createdAt: z
+ .date()
+ .describe("The date and time when the commission was created."),
+ updatedAt: z
+ .date()
+ .describe("The date and time when the commission was last updated."),
});
// Represents the commission object used in webhook and API responses (/api/commissions/**)
@@ -149,6 +181,14 @@ export const getCommissionsQuerySchema = z
.describe(
"Filter the list of commissions by the associated invoice. Since invoiceId is unique on a per-program basis, this will only return one commission per invoice.",
),
+ query: z
+ .string()
+ .max(10000)
+ .optional()
+ .describe(
+ "Search commissions by a custom metadata value. Only matches lead and sale commissions with persisted user-provided metadata. " +
+ "Examples: `metadata['key']:'value'`",
+ ),
status: z
.enum(CommissionStatus)
.optional()
diff --git a/apps/web/lib/zod/schemas/partner-profile.ts b/apps/web/lib/zod/schemas/partner-profile.ts
index f8dee55ddc..4ebf624517 100644
--- a/apps/web/lib/zod/schemas/partner-profile.ts
+++ b/apps/web/lib/zod/schemas/partner-profile.ts
@@ -32,6 +32,7 @@ import { centsSchema } from "./utils";
export const PartnerEarningsSchema = CommissionSchema.omit({
userId: true,
invoiceId: true,
+ metadata: true,
}).extend({
customer: z
.object({
@@ -51,6 +52,7 @@ export const getPartnerEarningsQuerySchema = getCommissionsQuerySchema
.omit({
partnerId: true,
sortBy: true,
+ query: true,
})
.extend({
interval: z
@@ -66,6 +68,7 @@ export const getPartnerEarningsQuerySchema = getCommissionsQuerySchema
export const getPartnerEarningsCountQuerySchema = getCommissionsCountQuerySchema
.omit({
partnerId: true,
+ query: true,
})
.extend({
interval: z
diff --git a/apps/web/playwright/api/commissions/commissions.spec.ts b/apps/web/playwright/api/commissions/commissions.spec.ts
index dce6627da3..f2af30dfa5 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 { redis } from "@/lib/upstash";
import { nanoid } from "@dub/utils";
import { expect } from "@playwright/test";
import { apiError, randomCustomer } from "../../utils";
@@ -291,6 +292,44 @@ test.describe("Sale commissions", () => {
});
});
+ test("converts nested sale.currency to USD", async ({ api, program }) => {
+ const invoiceId = `INV_${nanoid()}`;
+ const previousEurRate = await redis.hget("fxRates:usd", "EUR");
+
+ try {
+ await redis.hset("fxRates:usd", { EUR: 2 });
+
+ await withCommissionPartner(api, program, async (partnerId) => {
+ expect(
+ await api.post("/api/commissions", {
+ type: "sale",
+ partnerId,
+ sale: {
+ amount: 10000,
+ currency: "eur",
+ invoiceId,
+ },
+ customer: customerBody(),
+ }),
+ ).toEqual(expectedQueuedResponse);
+
+ await expectCommissionCreated({
+ partnerId,
+ programId: program.id,
+ type: "sale",
+ invoiceId,
+ expectedAmount: 5000,
+ });
+ });
+ } finally {
+ if (previousEurRate == null) {
+ await redis.hdel("fxRates:usd", "EUR");
+ } else {
+ await redis.hset("fxRates:usd", { EUR: previousEurRate });
+ }
+ }
+ });
+
test("supports deprecated sale fields", async ({ api, program }) => {
const invoiceId = `INV_${nanoid()}`;
const saleEventDate = new Date("2024-03-01T08:30:00.000Z");
diff --git a/apps/web/playwright/api/commissions/helpers.ts b/apps/web/playwright/api/commissions/helpers.ts
index 8f6fbf9972..9cc618f101 100644
--- a/apps/web/playwright/api/commissions/helpers.ts
+++ b/apps/web/playwright/api/commissions/helpers.ts
@@ -110,6 +110,7 @@ export async function expectCommissionCreated({
quantity: commission.quantity,
description: commission.description,
invoiceId: commission.invoiceId,
+ currency: commission.currency,
createdAt: commission.createdAt.toISOString(),
};
})
@@ -122,6 +123,7 @@ export async function expectCommissionCreated({
quantity: 1,
description: description ?? null,
invoiceId: invoiceId ?? null,
+ currency: "usd",
createdAt: expectedCreatedAt
? expectedCreatedAt.toISOString()
: expect.any(String),