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.

Add multi-currency support for commission imports

Kiran K7c7556c2cb09
diff --git a/apps/web/lib/analytics/convert-currency.ts b/apps/web/lib/analytics/convert-currency.ts
index e77c3ec32b..c338f8f81e 100644
--- a/apps/web/lib/analytics/convert-currency.ts
+++ b/apps/web/lib/analytics/convert-currency.ts
@@ -22,19 +22,21 @@ export const ZERO_DECIMAL_CURRENCIES = [
export const convertCurrency = async ({
currency,
amount,
+ fxRates,
}: {
currency: string;
amount: number;
+ fxRates?: Record<string, string>;
}) => {
- const isZeroDecimalCurrency = ZERO_DECIMAL_CURRENCIES.includes(
- currency.toUpperCase(),
- );
+ const currencyCode = currency.toUpperCase();
+ const isZeroDecimalCurrency = ZERO_DECIMAL_CURRENCIES.includes(currencyCode);
+ const fxRate =
+ fxRates?.[currencyCode] ?? (await redis.hget("fxRates:usd", currencyCode)); // e.g. for MYR it'll be around 4.4
- const fxRates = await redis.hget("fxRates:usd", currency.toUpperCase()); // e.g. for MYR it'll be around 4.4
-
- if (fxRates) {
+ if (fxRate) {
// convert amount to USD based on the current FX rate
- let convertedAmount = amount / Number(fxRates);
+ let convertedAmount = amount / Number(fxRate);
+
// if the currency is a zero decimal currency, we need to multiply the converted amount by 100
if (isZeroDecimalCurrency) {
convertedAmount = convertedAmount * 100;
diff --git a/apps/web/lib/partnerstack/import-commissions.ts b/apps/web/lib/partnerstack/import-commissions.ts
index 2d322965d8..a7827d2655 100644
--- a/apps/web/lib/partnerstack/import-commissions.ts
+++ b/apps/web/lib/partnerstack/import-commissions.ts
@@ -1,9 +1,11 @@
import { prisma } from "@dub/prisma";
import { nanoid } from "@dub/utils";
import { CommissionStatus } from "@prisma/client";
+import { convertCurrency } from "../analytics/convert-currency";
import { createId } from "../api/create-id";
import { syncTotalCommissions } from "../api/partners/sync-total-commissions";
import { getLeadEvent, recordSaleWithTimestamp } from "../tinybird";
+import { redis } from "../upstash";
import { clickEventSchemaTB } from "../zod/schemas/clicks";
import { PartnerStackApi } from "./api";
import { MAX_BATCHES, partnerStackImporter } from "./importer";
@@ -40,6 +42,8 @@ export async function importCommissions(payload: PartnerStackImportPayload) {
secretKey,
});
+ const fxRates = await redis.hgetall<Record<string, string>>("fxRates:usd");
+
let hasMore = true;
let processedBatches = 0;
let currentStartingAfter = startingAfter;
@@ -60,6 +64,7 @@ export async function importCommissions(payload: PartnerStackImportPayload) {
workspaceId,
programId,
commission,
+ fxRates,
}),
),
);
@@ -85,10 +90,12 @@ async function createCommission({
workspaceId,
programId,
commission,
+ fxRates,
}: {
workspaceId: string;
programId: string;
commission: PartnerStackCommission;
+ fxRates: Record<string, string> | null;
}) {
if (!commission.transaction) {
console.log(`Commission ${commission.key} has no transaction, skipping...`);
@@ -134,6 +141,34 @@ async function createCommission({
return;
}
+ // Sale amount
+ let amount = commission.transaction.amount;
+ const saleCurrency = commission.transaction.currency;
+
+ if (saleCurrency.toUpperCase() !== "USD" && fxRates) {
+ const { amount: convertedAmount } = await convertCurrency({
+ currency: saleCurrency,
+ amount,
+ fxRates,
+ });
+
+ amount = convertedAmount;
+ }
+
+ // Earnings
+ let earnings = commission.amount;
+ const earningsCurrency = commission.currency;
+
+ if (earningsCurrency.toUpperCase() !== "USD" && fxRates) {
+ const { amount: convertedAmount } = await convertCurrency({
+ currency: earningsCurrency,
+ amount: earnings,
+ fxRates,
+ });
+
+ earnings = convertedAmount;
+ }
+
// here, we also check for commissions that have already been recorded on Dub
// e.g. during the transition period
// since we don't have the Stripe invoiceId from PartnerStack, we use the referral's customer ID
@@ -199,8 +234,8 @@ async function createCommission({
partnerId: customer.link.partnerId,
linkId: customer.linkId,
customerId: customer.id,
- amount: commission.transaction.amount,
- earnings: commission.amount,
+ amount,
+ earnings,
currency: commission.transaction.currency,
quantity: 1,
status: toDubStatus[commission.reward_status],
@@ -213,7 +248,7 @@ async function createCommission({
...clickData,
event_id: eventId,
event_name: "Invoice paid",
- amount: commission.transaction.amount,
+ amount,
customer_id: customer.id,
payment_processor: "stripe",
currency: commission.transaction.currency,
@@ -231,7 +266,7 @@ async function createCommission({
increment: 1,
},
saleAmount: {
- increment: commission.transaction.amount,
+ increment: amount,
},
},
}),
@@ -246,7 +281,7 @@ async function createCommission({
increment: 1,
},
saleAmount: {
- increment: commission.transaction.amount,
+ increment: amount,
},
},
}),
diff --git a/apps/web/lib/partnerstack/schemas.ts b/apps/web/lib/partnerstack/schemas.ts
index 76168cccaa..00d83d17ab 100644
--- a/apps/web/lib/partnerstack/schemas.ts
+++ b/apps/web/lib/partnerstack/schemas.ts
@@ -64,6 +64,7 @@ export const partnerStackCustomer = z.object({
export const partnerStackCommission = z.object({
key: z.string(),
amount: z.number().describe("The amount of the reward in cents (USD)."),
+ currency: z.string(),
created_at: z.number(),
customer: z
.object({
diff --git a/apps/web/lib/rewardful/import-commissions.ts b/apps/web/lib/rewardful/import-commissions.ts
index 6d197f907b..2a55fe638a 100644
--- a/apps/web/lib/rewardful/import-commissions.ts
+++ b/apps/web/lib/rewardful/import-commissions.ts
@@ -3,7 +3,7 @@ import CampaignImported from "@dub/email/templates/campaign-imported";
import { prisma } from "@dub/prisma";
import { nanoid } from "@dub/utils";
import { CommissionStatus, Program } from "@prisma/client";
-import { ZERO_DECIMAL_CURRENCIES } from "../analytics/convert-currency";
+import { convertCurrency } from "../analytics/convert-currency";
import { createId } from "../api/create-id";
import { syncTotalCommissions } from "../api/partners/sync-total-commissions";
import { getLeadEvent } from "../tinybird";
@@ -14,6 +14,13 @@ import { RewardfulApi } from "./api";
import { MAX_BATCHES, rewardfulImporter } from "./importer";
import { RewardfulCommission, RewardfulImportPayload } from "./types";
+const toDubStatus: Record<RewardfulCommission["state"], CommissionStatus> = {
+ pending: "pending",
+ due: "pending",
+ paid: "paid",
+ voided: "canceled",
+};
+
export async function importCommissions(payload: RewardfulImportPayload) {
const { programId, userId, campaignId, page = 1 } = payload;
@@ -145,39 +152,30 @@ async function createCommission({
// Sale amount
let amount = sale.sale_amount_cents;
- let currency = sale.currency.toUpperCase();
-
- if (currency !== "USD" && fxRates) {
- const fxRate = fxRates[currency];
- const isZeroDecimalCurrency = ZERO_DECIMAL_CURRENCIES.includes(currency);
-
- if (fxRate) {
- let convertedAmount = amount / Number(fxRates);
+ const saleCurrency = sale.currency.toUpperCase();
- if (isZeroDecimalCurrency) {
- convertedAmount = convertedAmount * 100;
- }
+ if (saleCurrency !== "USD" && fxRates) {
+ const { amount: convertedAmount } = await convertCurrency({
+ currency: saleCurrency,
+ amount,
+ fxRates,
+ });
- amount = Math.round(convertedAmount);
- }
+ amount = convertedAmount;
}
+ // Earnings
let earnings = commission.amount;
- currency = commission.currency.toUpperCase();
+ const earningsCurrency = commission.currency.toUpperCase();
- if (currency !== "USD" && fxRates) {
- const fxRate = fxRates[currency];
- const isZeroDecimalCurrency = ZERO_DECIMAL_CURRENCIES.includes(currency);
-
- if (fxRate) {
- let convertedEarnings = earnings / Number(fxRates);
-
- if (isZeroDecimalCurrency) {
- convertedEarnings = convertedEarnings * 100;
- }
+ if (earningsCurrency !== "USD" && fxRates) {
+ const { amount: convertedAmount } = await convertCurrency({
+ currency: earningsCurrency,
+ amount: earnings,
+ fxRates,
+ });
- earnings = Math.round(convertedEarnings);
- }
+ earnings = convertedAmount;
}
// here, we also check for commissions that have already been recorded on Dub
@@ -196,7 +194,7 @@ async function createCommission({
stripeCustomerId: sale.referral.stripe_customer_id,
},
type: "sale",
- amount: sale.sale_amount_cents,
+ amount: amount,
},
});
@@ -251,13 +249,6 @@ async function createCommission({
const eventId = nanoid(16);
- const toDubStatus: Record<RewardfulCommission["state"], CommissionStatus> = {
- pending: "pending",
- due: "pending",
- paid: "paid",
- voided: "canceled",
- };
-
await Promise.all([
prisma.commission.create({
data: {
@@ -295,7 +286,7 @@ async function createCommission({
where: { id: customerFound.linkId },
data: {
sales: { increment: 1 },
- saleAmount: { increment: sale.sale_amount_cents },
+ saleAmount: { increment: amount },
},
}),
@@ -304,7 +295,7 @@ async function createCommission({
where: { id: customerFound.id },
data: {
sales: { increment: 1 },
- saleAmount: { increment: sale.sale_amount_cents },
+ saleAmount: { increment: amount },
},
}),
]);
diff --git a/apps/web/lib/tolt/api.ts b/apps/web/lib/tolt/api.ts
index 7e2e05debe..8f39a9ccbe 100644
--- a/apps/web/lib/tolt/api.ts
+++ b/apps/web/lib/tolt/api.ts
@@ -65,9 +65,7 @@ export class ToltApi {
}
return {
- ...ToltProgramSchema.parse({
- ...partner.program,
- }),
+ ...ToltProgramSchema.parse(partner.program),
affiliates: total_count,
};
}
diff --git a/apps/web/lib/tolt/import-commissions.ts b/apps/web/lib/tolt/import-commissions.ts
index ed937f27f9..f506940f7e 100644
--- a/apps/web/lib/tolt/import-commissions.ts
+++ b/apps/web/lib/tolt/import-commissions.ts
@@ -3,10 +3,12 @@ import CampaignImported from "@dub/email/templates/campaign-imported";
import { prisma } from "@dub/prisma";
import { nanoid } from "@dub/utils";
import { CommissionStatus } from "@prisma/client";
+import { convertCurrency } from "../analytics/convert-currency";
import { createId } from "../api/create-id";
import { syncTotalCommissions } from "../api/partners/sync-total-commissions";
import { getLeadEvent } from "../tinybird";
import { recordSaleWithTimestamp } from "../tinybird/record-sale";
+import { redis } from "../upstash";
import { clickEventSchemaTB } from "../zod/schemas/clicks";
import { ToltApi } from "./api";
import { MAX_BATCHES, toltImporter } from "./importer";
@@ -35,9 +37,14 @@ export async function importCommissions(payload: ToltImportPayload) {
const { workspace } = program;
const { token } = await toltImporter.getCredentials(workspace.id);
-
const toltApi = new ToltApi({ token });
+ const toltProgram = await toltApi.getProgram({
+ programId: toltProgramId,
+ });
+
+ const fxRates = await redis.hgetall<Record<string, string>>("fxRates:usd");
+
let hasMore = true;
let processedBatches = 0;
@@ -58,6 +65,8 @@ export async function importCommissions(payload: ToltImportPayload) {
workspaceId: workspace.id,
programId,
commission,
+ fxRates,
+ currency: toltProgram.currency_code.toLowerCase(),
}),
),
);
@@ -121,10 +130,14 @@ async function createCommission({
workspaceId,
programId,
commission,
+ fxRates,
+ currency,
}: {
workspaceId: string;
programId: string;
commission: ToltCommission;
+ fxRates: Record<string, string> | null;
+ currency: string;
}) {
const { customer, partner, ...sale } = commission;
@@ -166,6 +179,32 @@ async function createCommission({
return;
}
+ // Sale amount
+ let amount = Number(sale.amount);
+
+ if (currency.toUpperCase() !== "USD" && fxRates) {
+ const { amount: convertedAmount } = await convertCurrency({
+ currency,
+ amount,
+ fxRates,
+ });
+
+ amount = convertedAmount;
+ }
+
+ // Earnings
+ let earnings = Number(commission.amount);
+
+ if (currency.toUpperCase() !== "USD" && fxRates) {
+ const { amount: convertedAmount } = await convertCurrency({
+ currency,
+ amount: earnings,
+ fxRates,
+ });
+
+ earnings = convertedAmount;
+ }
+
// here, we also check for commissions that have already been recorded on Dub
// e.g. during the transition period
// since we don't have the Stripe invoiceId from Tolt, we use the referral's customer ID
@@ -180,7 +219,7 @@ async function createCommission({
},
customerId: customerFound.id,
type: "sale",
- amount: Number(sale.amount),
+ amount,
},
});
@@ -229,9 +268,9 @@ async function createCommission({
partnerId: customerFound.link.partnerId,
linkId: customerFound.linkId,
customerId: customerFound.id,
- amount: Number(sale.revenue),
- earnings: Number(commission.amount),
- currency: "usd", // TODO: there is no currency in the commission
+ amount,
+ earnings,
+ currency,
quantity: 1,
status: toDubStatus[commission.status],
invoiceId: sale.transaction_id, // this is not the actual invoice ID, but we use this to deduplicate the sales
@@ -243,10 +282,10 @@ async function createCommission({
...clickData,
event_id: eventId,
event_name: "Invoice paid",
- amount: Number(sale.revenue),
+ amount,
customer_id: customerFound.id,
payment_processor: "stripe",
- currency: "usd", // TODO: there is no currency in the commission
+ currency,
metadata: JSON.stringify(commission),
timestamp: new Date(sale.created_at).toISOString(),
}),
@@ -261,7 +300,7 @@ async function createCommission({
increment: 1,
},
saleAmount: {
- increment: Number(sale.revenue),
+ increment: amount,
},
},
}),
@@ -276,7 +315,7 @@ async function createCommission({
increment: 1,
},
saleAmount: {
- increment: Number(sale.revenue),
+ increment: amount,
},
},
}),
diff --git a/apps/web/lib/tolt/schemas.ts b/apps/web/lib/tolt/schemas.ts
index ecbc42cea3..fa9dac8808 100644
--- a/apps/web/lib/tolt/schemas.ts
+++ b/apps/web/lib/tolt/schemas.ts
@@ -22,6 +22,7 @@ export const ToltProgramSchema = z.object({
name: z.string(),
subdomain: z.string(),
payout_term: z.string(),
+ currency_code: z.string(),
});
export const ToltAffiliateSchema = z.object({