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.

finalize tests

Steven Teyc2e5a20ebaef
diff --git a/apps/web/app/(ee)/api/commissions/[commissionId]/route.ts b/apps/web/app/(ee)/api/commissions/[commissionId]/route.ts
index c54a7d4786..9f11b1964a 100644
--- a/apps/web/app/(ee)/api/commissions/[commissionId]/route.ts
+++ b/apps/web/app/(ee)/api/commissions/[commissionId]/route.ts
@@ -1,9 +1,9 @@
+import { convertCurrency } from "@/lib/analytics/convert-currency";
import { DubApiError } from "@/lib/api/errors";
import { calculateSaleEarnings } from "@/lib/api/sales/calculate-sale-earnings";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { determinePartnerReward } from "@/lib/partners/determine-partner-reward";
-import { redis } from "@/lib/upstash";
import {
CommissionSchema,
updateCommissionSchema,
@@ -47,30 +47,34 @@ export const PATCH = withWorkspace(async ({ workspace, params, req }) => {
await parseRequestBody(req),
);
- // if currency is not USD, convert it to USD based on the current FX rate
- // TODO: allow custom "defaultCurrency" on workspace table in the future
- if (currency !== "usd") {
- const fxRates = await redis.hget("fxRates:usd", currency.toUpperCase()); // e.g. for MYR it'll be around 4.4
- if (fxRates) {
- currency = "usd";
- // convert amount to USD (in cents) based on the current FX rate
- // round it to 0 decimal places
- amount = Math.round(originalAmount / Number(fxRates));
- modifyAmount = modifyAmount
- ? Math.round(modifyAmount / Number(fxRates))
- : undefined;
- }
- }
-
let finalAmount: number | undefined;
let finalEarnings: number | undefined;
- let earningsDifference: number | undefined;
- if (status) {
- // if status is being set to refunded, duplicate, canceled, or fraudulent
- // we need to decrement the payout amount by the commission earnings
- earningsDifference = -commission.earnings;
- } else if (amount || modifyAmount) {
+ if (amount || modifyAmount) {
+ if (commission.type !== "sale") {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `Cannot update amount: Commission ${commissionId} is not a sale commission.`,
+ });
+ }
+
+ // if currency is not USD, convert it to USD based on the current FX rate
+ // TODO: allow custom "defaultCurrency" on workspace table in the future
+ if (currency !== "usd") {
+ const valueToConvert = modifyAmount || amount;
+ if (valueToConvert) {
+ const { currency: convertedCurrency, amount: convertedAmount } =
+ await convertCurrency({ currency, amount: valueToConvert });
+
+ if (modifyAmount) {
+ modifyAmount = convertedAmount;
+ } else {
+ amount = convertedAmount;
+ }
+ currency = convertedCurrency;
+ }
+ }
+
finalAmount = Math.max(
modifyAmount ? originalAmount + modifyAmount : amount ?? originalAmount,
0, // Ensure the amount is not negative
@@ -97,8 +101,6 @@ export const PATCH = withWorkspace(async ({ workspace, params, req }) => {
quantity: commission.quantity,
},
});
-
- earningsDifference = finalEarnings - commission.earnings;
}
const updatedCommission = await prisma.commission.update({
@@ -109,27 +111,42 @@ export const PATCH = withWorkspace(async ({ workspace, params, req }) => {
amount: finalAmount,
earnings: finalEarnings,
status,
+ // need to update payoutId to null if the commission has no earnings
+ // or is being updated to refunded, duplicate, canceled, or fraudulent
+ ...(finalEarnings === 0 || status ? { payoutId: null } : {}),
},
});
- // If the sale has already been paid, we need to update the payout
+ // If the commission has already been added to a payout, we need to update the payout amount
if (
- earningsDifference &&
commission.status === "processed" &&
- commission.payoutId
+ typeof commission.payoutId === "string"
) {
waitUntil(
- prisma.payout.update({
- where: {
- id: commission.payoutId,
- },
- data: {
- amount: {
- ...(earningsDifference < 0
- ? { decrement: Math.abs(earningsDifference) }
- : { increment: earningsDifference }),
+ prisma.$transaction(async (tx) => {
+ const commissions = await tx.commission.groupBy({
+ by: ["payoutId"],
+ where: {
+ payoutId: commission.payoutId,
+ },
+ _sum: {
+ earnings: true,
},
- },
+ });
+ console.log("commissions", commissions);
+
+ const newPayoutAmount = commissions[0]._sum.earnings ?? 0;
+
+ if (newPayoutAmount === 0) {
+ console.log("deleting payout", commission.payoutId);
+ // await tx.payout.delete({ where: { id: commission.payoutId! } });
+ } else {
+ console.log("updating payout", commission.payoutId, newPayoutAmount);
+ await tx.payout.update({
+ where: { id: commission.payoutId! },
+ data: { amount: newPayoutAmount },
+ });
+ }
}),
);
}
diff --git a/apps/web/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.ts
index dcd01d2471..473806488e 100644
--- a/apps/web/lib/zod/schemas/commissions.ts
+++ b/apps/web/lib/zod/schemas/commissions.ts
@@ -105,7 +105,7 @@ export const updateCommissionSchema = z.object({
modifyAmount: z
.number()
.describe(
- "Modify the current sale amount: use positive values to increase the amount, negative values to decrease it.",
+ "Modify the current sale amount: use positive values to increase the amount, negative values to decrease it. Takes precedence over `amount`.",
)
.optional(),
currency: z
diff --git a/apps/web/tests/commissions/index.test.ts b/apps/web/tests/commissions/index.test.ts
index 0730dc194c..54d3f9bf31 100644
--- a/apps/web/tests/commissions/index.test.ts
+++ b/apps/web/tests/commissions/index.test.ts
@@ -21,12 +21,14 @@ describe.sequential("/commissions/**", async () => {
const { http } = await h.init();
let testCommissionId: string;
+ let testLeadCommissionId: string;
let testPaidCommissionId: string;
test("GET /commissions", async () => {
const { status, data: commissions } = await http.get<Commission[]>({
path: "/commissions",
query: {
+ status: "processed",
page: "1",
pageSize: "10",
sortBy: "createdAt",
@@ -38,9 +40,9 @@ describe.sequential("/commissions/**", async () => {
expect(Array.isArray(commissions)).toBe(true);
expect(commissions.length).toBeGreaterThan(0);
expect(commissions[0]).toMatchObject(expectedCommission);
-
- // Store the first commission's ID for subsequent tests
- testCommissionId = commissions[0].id;
+ // Store the first sale and lead commission's ID for subsequent tests
+ testCommissionId = commissions.find((c) => c.type === "sale")!.id;
+ testLeadCommissionId = commissions.find((c) => c.type === "lead")!.id;
});
test("GET /commissions with filters", async () => {
@@ -59,6 +61,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);
testPaidCommissionId = paidCommissions[0].id;
});
@@ -96,8 +99,8 @@ describe.sequential("/commissions/**", async () => {
test("PATCH /commissions/{id} - foreign currency conversion", async () => {
const toUpdate = {
- amount: 10000, // 100 MYR
- currency: "myr",
+ amount: 1437, // approximately 1000 USD cents
+ currency: "jpy",
};
const { status, data: commission } = await http.patch<Commission>({
@@ -105,12 +108,24 @@ describe.sequential("/commissions/**", async () => {
body: toUpdate,
});
- console.log("commission", commission);
-
expect(status).toEqual(200);
- expect(commission.amount).toBeLessThan(6000);
- expect(commission.amount).toBeGreaterThanOrEqual(3000); // 100 MYR should be around 23 USD and hence 6000 - 2300 = 3700
expect(commission.currency).toEqual("usd");
+ expect(commission.amount).toBeGreaterThanOrEqual(900); // 900 cents
+ expect(commission.amount).toBeLessThanOrEqual(1100); // 1100 cents
+ });
+
+ test("PATCH /commissions/{id} - error on lead commission", async () => {
+ const toUpdate = {
+ amount: 5000,
+ };
+
+ const response = await http.patch<Commission>({
+ path: `/commissions/${testLeadCommissionId}`,
+ body: toUpdate,
+ });
+
+ expect(response.status).toEqual(400);
+ expect(response.data["error"].message).toContain("not a sale commission.");
});
test("PATCH /commissions/{id} - error on paid commission", async () => {
@@ -124,9 +139,7 @@ describe.sequential("/commissions/**", async () => {
});
expect(response.status).toEqual(400);
- // The error response will be in the response body
- const errorResponse = response.data as unknown as { message: string };
- expect(errorResponse.message).toContain("has already been paid");
+ expect(response.data["error"].message).toContain("has already been paid");
});
test("PATCH /commissions/{id} - update status to refunded", async () => {