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.

Accept nested sale.amount with deprecated fallbacks and add commission metadata.

Kiran Kf521ce2dbb36
diff --git a/apps/web/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.ts
index 1a0e37d435..a757ed1b7c 100644
--- a/apps/web/lib/zod/schemas/commissions.ts
+++ b/apps/web/lib/zod/schemas/commissions.ts
@@ -566,7 +566,7 @@ const createSaleCommissionSchema = z.object({
.nullish()
.default(false)
.describe(
- "When `true`, import all unimported paid Stripe invoices for the customer and create a commission for each. When `false`, create a single manual sale event using `saleAmount`.",
+ "When `true`, import all unimported paid Stripe invoices for the customer and create a commission for each. When `false`, create a single manual sale event using `sale.amount` (or deprecated `saleAmount`).",
),
date: parseDateSchema
.nullish()
@@ -575,42 +575,35 @@ const createSaleCommissionSchema = z.object({
),
sale: z
.object({
- amount: trackSaleRequestSchema.shape.amount,
+ amount: trackSaleRequestSchema.shape.amount.nullish(),
currency: trackSaleRequestSchema.shape.currency,
eventName: trackSaleRequestSchema.shape.eventName,
paymentProcessor: trackSaleRequestSchema.shape.paymentProcessor,
invoiceId: trackSaleRequestSchema.shape.invoiceId,
metadata: trackSaleRequestSchema.shape.metadata,
})
- .nullish(),
+ .nullish()
+ .describe("The sale event object to associate the commission with."),
// Deprecated fields
- saleAmount: centsSchema
- .pipe(z.number().min(0))
+ saleEventDate: parseDateSchema
.nullish()
- .describe(
- "Deprecated: Use `sale.amount` instead. Required when `importStripeInvoices` is `false`. The sale amount in cents for the manual sale event. Ignored when importing from Stripe.",
- )
+ .describe("Deprecated: Use `date` instead.")
.meta({ deprecated: true }),
- saleEventDate: parseDateSchema
+ saleAmount: centsSchema
+ .pipe(z.number().min(0))
.nullish()
- .describe(
- "Deprecated: Use `date` instead. Only used when `importStripeInvoices` is `false`. The date of the manual sale event. Defaults to the current date and time if not provided.",
- )
+ .describe("Deprecated: Use `sale.amount` instead.")
.meta({ deprecated: true }),
invoiceId: z
.string()
.nullish()
- .describe(
- "Deprecated: Use `sale.invoiceId` instead. Only used when `importStripeInvoices` is `false`. An optional invoice ID to attach to the generated sale event and commission entry for deduplication.",
- )
+ .describe("Deprecated: Use `sale.invoiceId` instead.")
.meta({ deprecated: true }),
productId: z
.string()
.nullish()
- .describe(
- "Deprecated: Use `sale.metadata.productId` instead. Only used when `importStripeInvoices` is `false`. An optional product ID stored on the sale event metadata – will also impact commission earnings calculation (if a `Sale` `Product ID` modifier is set).",
- )
+ .describe("Deprecated: Use `sale.metadata.productId` instead.")
.meta({ deprecated: true }),
});
@@ -638,21 +631,23 @@ export const createManualCommissionBodySchema = z
return;
}
- if (data.saleAmount == null) {
+ const saleAmount = data.sale?.amount ?? data.saleAmount;
+
+ if (saleAmount == null) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
- "`saleAmount` is required when `importStripeInvoices` is false.",
- path: ["saleAmount"],
+ "`sale.amount` or `saleAmount` is required when `importStripeInvoices` is false.",
+ path: data.sale ? ["sale", "amount"] : ["saleAmount"],
});
return;
}
- if (data.saleAmount === 0) {
+ if (saleAmount === 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Sale amount cannot be 0.",
- path: ["saleAmount"],
+ path: data.sale?.amount != null ? ["sale", "amount"] : ["saleAmount"],
});
}
}
diff --git a/apps/web/playwright/api/commissions/commissions.spec.ts b/apps/web/playwright/api/commissions/commissions.spec.ts
index f9f2f8df6c..dce6627da3 100644
--- a/apps/web/playwright/api/commissions/commissions.spec.ts
+++ b/apps/web/playwright/api/commissions/commissions.spec.ts
@@ -257,21 +257,23 @@ test.describe("Sale commissions", () => {
test("creates using nested sale", async ({ api, program }) => {
const invoiceId = `INV_${nanoid()}`;
+ const date = new Date("2024-02-20T00:00:00.000Z");
await withCommissionPartner(api, program, async (partnerId) => {
expect(
await api.post("/api/commissions", {
type: "sale",
partnerId,
- saleAmount: 1000,
- invoiceId,
+ date: date.toISOString(),
sale: {
amount: 1000,
currency: "usd",
eventName: "Invoice paid",
paymentProcessor: "stripe",
invoiceId,
- metadata: { productId: "sku_nested" },
+ metadata: {
+ productId: "sku_pro",
+ },
},
customer: customerBody(),
}),
@@ -282,6 +284,9 @@ test.describe("Sale commissions", () => {
programId: program.id,
type: "sale",
invoiceId,
+ expectedCreatedAt: date,
+ expectedEarnings:
+ TEST_COMMISSION_REWARDS.sale.modifiers[0].amountInCents,
});
});
});
@@ -297,7 +302,7 @@ test.describe("Sale commissions", () => {
partnerId,
saleAmount: 1000,
invoiceId,
- productId: "sku_deprecated",
+ productId: "sku_pro",
saleEventDate: saleEventDate.toISOString(),
customer: customerBody(),
}),
@@ -309,6 +314,101 @@ test.describe("Sale commissions", () => {
type: "sale",
invoiceId,
expectedCreatedAt: saleEventDate,
+ expectedEarnings:
+ TEST_COMMISSION_REWARDS.sale.modifiers[0].amountInCents,
+ });
+ });
+ });
+
+ test("creates with saleAmount when nested sale has no amount", async ({
+ api,
+ program,
+ }) => {
+ const invoiceId = `INV_${nanoid()}`;
+
+ await withCommissionPartner(api, program, async (partnerId) => {
+ expect(
+ await api.post("/api/commissions", {
+ type: "sale",
+ partnerId,
+ saleAmount: 1000,
+ sale: {
+ eventName: "Invoice paid",
+ invoiceId,
+ },
+ customer: customerBody(),
+ }),
+ ).toEqual(expectedQueuedResponse);
+
+ await expectCommissionCreated({
+ partnerId,
+ programId: program.id,
+ type: "sale",
+ invoiceId,
+ });
+ });
+ });
+
+ test("date takes precedence over saleEventDate", async ({ api, program }) => {
+ const date = new Date("2024-08-01T00:00:00.000Z");
+ const saleEventDate = new Date("2020-01-01T00:00:00.000Z");
+
+ await withCommissionPartner(api, program, async (partnerId) => {
+ expect(
+ await api.post("/api/commissions", {
+ type: "sale",
+ partnerId,
+ saleAmount: 1000,
+ date: date.toISOString(),
+ saleEventDate: saleEventDate.toISOString(),
+ customer: customerBody(),
+ }),
+ ).toEqual(expectedQueuedResponse);
+
+ await expectCommissionCreated({
+ partnerId,
+ programId: program.id,
+ type: "sale",
+ expectedCreatedAt: date,
+ });
+ });
+ });
+
+ test("nested sale takes precedence over deprecated fields", async ({
+ api,
+ program,
+ }) => {
+ const invoiceId = `INV_${nanoid()}`;
+ const date = new Date("2024-09-15T00:00:00.000Z");
+
+ await withCommissionPartner(api, program, async (partnerId) => {
+ expect(
+ await api.post("/api/commissions", {
+ type: "sale",
+ partnerId,
+ saleAmount: 500,
+ invoiceId: `INV_${nanoid()}`,
+ productId: "sku_old",
+ saleEventDate: new Date("2020-01-01T00:00:00.000Z").toISOString(),
+ date: date.toISOString(),
+ sale: {
+ amount: 2000,
+ invoiceId,
+ metadata: { productId: "sku_pro" },
+ },
+ customer: customerBody(),
+ }),
+ ).toEqual(expectedQueuedResponse);
+
+ await expectCommissionCreated({
+ partnerId,
+ programId: program.id,
+ type: "sale",
+ invoiceId,
+ expectedAmount: 2000,
+ expectedCreatedAt: date,
+ expectedEarnings:
+ TEST_COMMISSION_REWARDS.sale.modifiers[0].amountInCents,
});
});
});
@@ -347,6 +447,39 @@ test.describe("Sale commissions", () => {
});
});
+ test("rejects duplicate nested sale.invoiceId", async ({ api, program }) => {
+ const invoiceId = `INV_${nanoid()}`;
+
+ await withCommissionPartner(api, program, async (partnerId) => {
+ await prisma.commission.create({
+ data: {
+ id: createId({ prefix: "cm_" }),
+ programId: program.id,
+ partnerId,
+ type: "sale",
+ amount: 1000,
+ earnings: 100,
+ quantity: 1,
+ invoiceId,
+ },
+ });
+
+ expect(
+ await api.post("/api/commissions", {
+ type: "sale",
+ partnerId,
+ sale: { amount: 1000, invoiceId },
+ customer: customerBody(),
+ }),
+ ).toEqual(
+ apiError({
+ code: "conflict",
+ message: `There is already a commission for the invoice ${invoiceId}.`,
+ }),
+ );
+ });
+ });
+
test("imports Stripe invoices", async ({ api, program, workspace }) => {
await withCommissionPartner(api, program, async (partnerId) => {
expect(
@@ -368,7 +501,7 @@ test.describe("Sale commissions", () => {
test.describe("validates", () => {
const errorCases = [
{
- name: "rejects missing saleAmount",
+ name: "rejects missing sale.amount and saleAmount",
body: {
type: "sale",
partnerId: "pn_test",
@@ -378,7 +511,7 @@ test.describe("Sale commissions", () => {
expected: apiError({
code: "unprocessable_entity",
message:
- "custom: saleAmount: `saleAmount` is required when `importStripeInvoices` is false.",
+ "custom: saleAmount: `sale.amount` or `saleAmount` is required when `importStripeInvoices` is false.",
}),
},
{
@@ -396,17 +529,16 @@ test.describe("Sale commissions", () => {
}),
},
{
- name: "rejects missing sale.amount",
+ name: "rejects sale.amount of 0",
body: {
type: "sale",
partnerId: "pn_test",
customerId: "cus_test",
- saleAmount: 1000,
- sale: {},
+ sale: { amount: 0 },
},
expected: apiError({
code: "unprocessable_entity",
- message: "invalid_type: sale.amount: amount is required",
+ message: "custom: sale.amount: Sale amount cannot be 0.",
}),
},
{
@@ -437,20 +569,6 @@ test.describe("Sale commissions", () => {
"custom: sale.metadata: Metadata must be less than 10,000 characters when stringified",
}),
},
- {
- name: "rejects sale.amount without saleAmount",
- body: {
- type: "sale",
- partnerId: "pn_test",
- customerId: "cus_test",
- sale: { amount: 1000 },
- },
- expected: apiError({
- code: "unprocessable_entity",
- message:
- "custom: saleAmount: `saleAmount` is required when `importStripeInvoices` is false.",
- }),
- },
];
for (const { name, body, expected } of errorCases) {
diff --git a/apps/web/playwright/api/setup-test-workspace.ts b/apps/web/playwright/api/setup-test-workspace.ts
index bf6df951d3..ffa9449155 100644
--- a/apps/web/playwright/api/setup-test-workspace.ts
+++ b/apps/web/playwright/api/setup-test-workspace.ts
@@ -63,6 +63,21 @@ export const TEST_COMMISSION_REWARDS = {
type: RewardStructure.flat,
amountInCents: 2500,
maxDuration: 0,
+ modifiers: [
+ {
+ operator: "AND",
+ type: RewardStructure.flat,
+ amountInCents: 5000,
+ conditions: [
+ {
+ entity: "sale",
+ attribute: "productId",
+ operator: "equals_to",
+ value: "sku_pro",
+ },
+ ],
+ },
+ ],
},
} as const;
diff --git a/apps/web/prisma/schema/commission.prisma b/apps/web/prisma/schema/commission.prisma
index ebe5879c16..e6d657f4b7 100644
--- a/apps/web/prisma/schema/commission.prisma
+++ b/apps/web/prisma/schema/commission.prisma
@@ -37,6 +37,7 @@ model Commission {
userId String? // user who created the manual commission
sourceCommissionId String?
sourcePartnerId String?
+ metadata Json? @db.Json
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt