|
1
|
import { BigNumberInput } from "@medusajs/framework/types" |
|
2
|
import { BigNumber, MathBN } from "@medusajs/framework/utils" |
|
3
|
|
|
4
|
function getCurrencyMultiplier(currency) { |
|
5
|
const currencyMultipliers = { |
|
6
|
0: [ |
|
7
|
"BIF", |
|
8
|
"CLP", |
|
9
|
"DJF", |
|
10
|
"GNF", |
|
11
|
"JPY", |
|
12
|
"KMF", |
|
13
|
"KRW", |
|
14
|
"MGA", |
|
15
|
"PYG", |
|
16
|
"RWF", |
|
17
|
"UGX", |
|
18
|
"VND", |
|
19
|
"VUV", |
|
20
|
"XAF", |
|
21
|
"XOF", |
|
22
|
"XPF", |
|
23
|
], |
|
24
|
3: ["BHD", "IQD", "JOD", "KWD", "OMR", "TND"], |
|
25
|
} |
|
26
|
|
|
27
|
currency = currency.toUpperCase() |
|
28
|
let power = 2 |
|
29
|
for (const [key, value] of Object.entries(currencyMultipliers)) { |
|
30
|
if (value.includes(currency)) { |
|
31
|
power = parseInt(key, 10) |
|
32
|
break |
|
33
|
} |
|
34
|
} |
|
35
|
return Math.pow(10, power) |
|
36
|
} |
|
37
|
|
|
38
|
/** |
|
39
|
* Converts an amount to the format required by Stripe based on currency. |
|
40
|
* https://docs.stripe.com/currencies |
|
41
|
* @param {BigNumberInput} amount - The amount to be converted. |
|
42
|
* @param {string} currency - The currency code (e.g., 'USD', 'JOD'). |
|
43
|
* @returns {number} - The converted amount in the smallest currency unit. |
|
44
|
*/ |
|
45
|
export function getSmallestUnit( |
|
46
|
amount: BigNumberInput, |
|
47
|
currency: string |
|
48
|
): number { |
|
49
|
const multiplier = getCurrencyMultiplier(currency) |
|
50
|
|
|
51
|
let amount_ = |
|
52
|
Math.round(new BigNumber(MathBN.mult(amount, multiplier)).numeric) / |
|
53
|
multiplier |
|
54
|
|
|
55
|
const smallestAmount = new BigNumber(MathBN.mult(amount_, multiplier)) |
|
56
|
|
|
57
|
let numeric = smallestAmount.numeric |
|
58
|
// Check if the currency requires rounding to the nearest ten |
|
59
|
if (multiplier === 1e3) { |
|
60
|
numeric = Math.ceil(numeric / 10) * 10 |
|
61
|
} |
|
62
|
|
|
63
|
return parseInt(numeric.toString().split(".").shift()!, 10) |
|
64
|
} |
|
65
|
|
|
66
|
/** |
|
67
|
* Converts an amount from the smallest currency unit to the standard unit based on currency. |
|
68
|
* @param {BigNumberInput} amount - The amount in the smallest currency unit. |
|
69
|
* @param {string} currency - The currency code (e.g., 'USD', 'JOD'). |
|
70
|
* @returns {number} - The converted amount in the standard currency unit. |
|
71
|
*/ |
|
72
|
export function getAmountFromSmallestUnit( |
|
73
|
amount: BigNumberInput, |
|
74
|
currency: string |
|
75
|
): number { |
|
76
|
const multiplier = getCurrencyMultiplier(currency) |
|
77
|
const standardAmount = new BigNumber(MathBN.div(amount, multiplier)) |
|
78
|
return standardAmount.numeric |
|
79
|
} |