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.

convertCurrencyWithFxRates

Steven Teydb4abe70f9ba
diff --git a/apps/web/lib/analytics/convert-currency.ts b/apps/web/lib/analytics/convert-currency.ts
index 48797fdbd3..248597917a 100644
--- a/apps/web/lib/analytics/convert-currency.ts
+++ b/apps/web/lib/analytics/convert-currency.ts
@@ -22,25 +22,52 @@ export const ZERO_DECIMAL_CURRENCIES = [
export const convertCurrency = async ({
currency,
amount,
- fxRates,
}: {
currency: string;
amount: number;
- fxRates?: Record<string, string>;
}) => {
- let fxRate: string | null = null;
const currencyCode = currency.toUpperCase();
const isZeroDecimalCurrency = ZERO_DECIMAL_CURRENCIES.includes(currencyCode);
+ const fxRates = await redis.hget("fxRates:usd", currencyCode); // e.g. for MYR it'll be around 4.4
+
if (fxRates) {
- fxRate = fxRates[currencyCode] ?? null;
- } else {
- fxRate = await redis.hget("fxRates:usd", currencyCode); // e.g. for MYR it'll be around 4.4
+ // convert amount to USD based on the current FX rate
+ let convertedAmount = amount / Number(fxRates);
+
+ // if the currency is a zero decimal currency, we need to multiply the converted amount by 100
+ if (isZeroDecimalCurrency) {
+ convertedAmount = convertedAmount * 100;
+ }
+
+ return {
+ currency: "usd",
+ // round the final converted amount to 0 decimal places (USD in cents)
+ amount: Math.round(convertedAmount),
+ };
}
- if (fxRate) {
+ return {
+ currency,
+ amount,
+ };
+};
+
+export const convertCurrencyWithFxRates = ({
+ currency,
+ amount,
+ fxRates,
+}: {
+ currency: string;
+ amount: number;
+ fxRates?: Record<string, string>;
+}) => {
+ const currencyCode = currency.toUpperCase();
+ const isZeroDecimalCurrency = ZERO_DECIMAL_CURRENCIES.includes(currencyCode);
+
+ if (fxRates) {
// convert amount to USD based on the current FX rate
- let convertedAmount = amount / Number(fxRate);
+ let convertedAmount = amount / Number(fxRates);
// if the currency is a zero decimal currency, we need to multiply the converted amount by 100
if (isZeroDecimalCurrency) {
diff --git a/apps/web/lib/partnerstack/import-commissions.ts b/apps/web/lib/partnerstack/import-commissions.ts
index a7827d2655..cac0ba7dd6 100644
--- a/apps/web/lib/partnerstack/import-commissions.ts
+++ b/apps/web/lib/partnerstack/import-commissions.ts
@@ -1,7 +1,7 @@
import { prisma } from "@dub/prisma";
import { nanoid } from "@dub/utils";
import { CommissionStatus } from "@prisma/client";
-import { convertCurrency } from "../analytics/convert-currency";
+import { convertCurrencyWithFxRates } from "../analytics/convert-currency";
import { createId } from "../api/create-id";
import { syncTotalCommissions } from "../api/partners/sync-total-commissions";
import { getLeadEvent, recordSaleWithTimestamp } from "../tinybird";
@@ -146,7 +146,7 @@ async function createCommission({
const saleCurrency = commission.transaction.currency;
if (saleCurrency.toUpperCase() !== "USD" && fxRates) {
- const { amount: convertedAmount } = await convertCurrency({
+ const { amount: convertedAmount } = convertCurrencyWithFxRates({
currency: saleCurrency,
amount,
fxRates,
@@ -160,7 +160,7 @@ async function createCommission({
const earningsCurrency = commission.currency;
if (earningsCurrency.toUpperCase() !== "USD" && fxRates) {
- const { amount: convertedAmount } = await convertCurrency({
+ const { amount: convertedAmount } = convertCurrencyWithFxRates({
currency: earningsCurrency,
amount: earnings,
fxRates,
@@ -236,7 +236,8 @@ async function createCommission({
customerId: customer.id,
amount,
earnings,
- currency: commission.transaction.currency,
+ // TODO: allow custom "defaultCurrency" on workspace table in the future
+ currency: "usd",
quantity: 1,
status: toDubStatus[commission.reward_status],
invoiceId: commission.key, // this is not the actual invoice ID, but we use this to deduplicate the sales
@@ -251,7 +252,8 @@ async function createCommission({
amount,
customer_id: customer.id,
payment_processor: "stripe",
- currency: commission.transaction.currency,
+ // TODO: allow custom "defaultCurrency" on workspace table in the future
+ currency: "usd",
metadata: JSON.stringify(commission),
timestamp: new Date(commission.created_at).toISOString(),
}),
diff --git a/apps/web/lib/rewardful/import-commissions.ts b/apps/web/lib/rewardful/import-commissions.ts
index e450923abd..675214d4a1 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 { convertCurrency } from "../analytics/convert-currency";
+import { convertCurrencyWithFxRates } from "../analytics/convert-currency";
import { createId } from "../api/create-id";
import { syncTotalCommissions } from "../api/partners/sync-total-commissions";
import { getLeadEvent } from "../tinybird";
@@ -175,7 +175,7 @@ async function createCommission({
const saleCurrency = sale.currency.toUpperCase();
if (saleCurrency !== "USD" && fxRates) {
- const { amount: convertedAmount } = await convertCurrency({
+ const { amount: convertedAmount } = convertCurrencyWithFxRates({
currency: saleCurrency,
amount,
fxRates,
@@ -189,7 +189,7 @@ async function createCommission({
const earningsCurrency = commission.currency.toUpperCase();
if (earningsCurrency !== "USD" && fxRates) {
- const { amount: convertedAmount } = await convertCurrency({
+ const { amount: convertedAmount } = convertCurrencyWithFxRates({
currency: earningsCurrency,
amount: earnings,
fxRates,
@@ -315,7 +315,8 @@ async function createCommission({
customerId: customerFound.id,
amount,
earnings,
- currency: sale.currency.toLowerCase(),
+ // TODO: allow custom "defaultCurrency" on workspace table in the future
+ currency: "usd",
quantity: 1,
status: toDubStatus[commission.state],
invoiceId: sale.id, // this is not the actual invoice ID, but we use this to deduplicate the sales
@@ -330,7 +331,8 @@ async function createCommission({
amount,
customer_id: customerFound.id,
payment_processor: "stripe",
- currency: sale.currency.toLowerCase(),
+ // TODO: allow custom "defaultCurrency" on workspace table in the future
+ currency: "usd",
metadata: JSON.stringify(commission),
timestamp: new Date(sale.created_at).toISOString(),
}),
diff --git a/apps/web/lib/tolt/import-commissions.ts b/apps/web/lib/tolt/import-commissions.ts
index f506940f7e..77e0024d52 100644
--- a/apps/web/lib/tolt/import-commissions.ts
+++ b/apps/web/lib/tolt/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 } from "@prisma/client";
-import { convertCurrency } from "../analytics/convert-currency";
+import { convertCurrencyWithFxRates } from "../analytics/convert-currency";
import { createId } from "../api/create-id";
import { syncTotalCommissions } from "../api/partners/sync-total-commissions";
import { getLeadEvent } from "../tinybird";
@@ -66,7 +66,7 @@ export async function importCommissions(payload: ToltImportPayload) {
programId,
commission,
fxRates,
- currency: toltProgram.currency_code.toLowerCase(),
+ programCurrency: toltProgram.currency_code.toLowerCase(),
}),
),
);
@@ -131,13 +131,13 @@ async function createCommission({
programId,
commission,
fxRates,
- currency,
+ programCurrency,
}: {
workspaceId: string;
programId: string;
commission: ToltCommission;
fxRates: Record<string, string> | null;
- currency: string;
+ programCurrency: string;
}) {
const { customer, partner, ...sale } = commission;
@@ -182,9 +182,9 @@ async function createCommission({
// Sale amount
let amount = Number(sale.amount);
- if (currency.toUpperCase() !== "USD" && fxRates) {
- const { amount: convertedAmount } = await convertCurrency({
- currency,
+ if (programCurrency.toUpperCase() !== "USD" && fxRates) {
+ const { amount: convertedAmount } = convertCurrencyWithFxRates({
+ currency: programCurrency,
amount,
fxRates,
});
@@ -195,9 +195,9 @@ async function createCommission({
// Earnings
let earnings = Number(commission.amount);
- if (currency.toUpperCase() !== "USD" && fxRates) {
- const { amount: convertedAmount } = await convertCurrency({
- currency,
+ if (programCurrency.toUpperCase() !== "USD" && fxRates) {
+ const { amount: convertedAmount } = convertCurrencyWithFxRates({
+ currency: programCurrency,
amount: earnings,
fxRates,
});
@@ -270,7 +270,8 @@ async function createCommission({
customerId: customerFound.id,
amount,
earnings,
- currency,
+ // TODO: allow custom "defaultCurrency" on workspace table in the future
+ currency: "usd",
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
@@ -285,7 +286,8 @@ async function createCommission({
amount,
customer_id: customerFound.id,
payment_processor: "stripe",
- currency,
+ // TODO: allow custom "defaultCurrency" on workspace table in the future
+ currency: "usd",
metadata: JSON.stringify(commission),
timestamp: new Date(sale.created_at).toISOString(),
}),
diff --git a/apps/web/lib/zod/schemas/sales.ts b/apps/web/lib/zod/schemas/sales.ts
index be4f36fffc..0248adbd57 100644
--- a/apps/web/lib/zod/schemas/sales.ts
+++ b/apps/web/lib/zod/schemas/sales.ts
@@ -98,7 +98,10 @@ export const saleEventSchemaTB = clickEventSchemaTB
payment_processor: z.string(),
amount: z.number(),
invoice_id: z.string().default(""),
- currency: z.string().default("usd"),
+ currency: z
+ .string()
+ .default("usd")
+ .transform((val) => val.toLowerCase()),
metadata: z.string().default(""),
}),
);