|
1
|
import { BigNumberInput } from "@medusajs/types" |
|
2
|
import { isDefined } from "../../common" |
|
3
|
import { defaultCurrencies } from "../../defaults/currencies" |
|
4
|
import { BigNumber, getEpsilonFromDecimalPrecision } from "../big-number" |
|
5
|
import { MathBN } from "../math" |
|
6
|
|
|
7
|
export function calculateCreditLinesTotal({ |
|
8
|
creditLines, |
|
9
|
includesTax, |
|
10
|
taxRate, |
|
11
|
currencyCode, |
|
12
|
}: { |
|
13
|
creditLines: { amount: BigNumberInput }[] |
|
14
|
includesTax?: boolean |
|
15
|
taxRate?: BigNumberInput |
|
16
|
currencyCode?: string |
|
17
|
}) { |
|
18
|
// the sum of all creditLine amounts excluding tax |
|
19
|
let creditLinesSubtotal = MathBN.convert(0) |
|
20
|
// the sum of all creditLine amounts including tax |
|
21
|
let creditLinesTotal = MathBN.convert(0) |
|
22
|
// the sum of all taxes on subtotals |
|
23
|
let creditLinesTaxTotal = MathBN.convert(0) |
|
24
|
|
|
25
|
for (const cl of creditLines) { |
|
26
|
if (!isDefined(cl.amount)) { |
|
27
|
continue |
|
28
|
} |
|
29
|
|
|
30
|
const creditLineAmount = MathBN.convert(cl.amount) |
|
31
|
creditLinesSubtotal = MathBN.add(creditLinesSubtotal, creditLineAmount) |
|
32
|
|
|
33
|
if (isDefined(taxRate)) { |
|
34
|
const creditLineSubtotal = includesTax |
|
35
|
? MathBN.div(creditLineAmount, MathBN.add(1, taxRate)) |
|
36
|
: creditLineAmount |
|
37
|
|
|
38
|
const creditLineTaxTotal = MathBN.mult(creditLineSubtotal, taxRate) |
|
39
|
const creditLineTotal = MathBN.add(creditLineSubtotal, creditLineTaxTotal) |
|
40
|
|
|
41
|
cl["subtotal"] = new BigNumber(creditLineSubtotal) |
|
42
|
cl["total"] = new BigNumber(creditLineTotal) |
|
43
|
|
|
44
|
creditLinesTotal = MathBN.add(creditLinesTotal, creditLineTotal) |
|
45
|
creditLinesTaxTotal = MathBN.add(creditLinesTaxTotal, creditLineTaxTotal) |
|
46
|
} else { |
|
47
|
cl["subtotal"] = new BigNumber(creditLineAmount) |
|
48
|
creditLinesTotal = MathBN.add(creditLinesTotal, creditLineAmount) |
|
49
|
} |
|
50
|
} |
|
51
|
|
|
52
|
const upperCurCode = currencyCode?.toUpperCase() as string |
|
53
|
const currencyEpsilon = getEpsilonFromDecimalPrecision( |
|
54
|
defaultCurrencies[upperCurCode]?.decimal_digits |
|
55
|
) |
|
56
|
|
|
57
|
const isZero = MathBN.lte(MathBN.abs(creditLinesTotal), currencyEpsilon) |
|
58
|
return { |
|
59
|
creditLinesTotal: isZero ? MathBN.convert(0) : creditLinesTotal, |
|
60
|
creditLinesSubtotal: isZero ? MathBN.convert(0) : creditLinesSubtotal, |
|
61
|
creditLinesTaxTotal: isZero ? MathBN.convert(0) : creditLinesTaxTotal, |
|
62
|
} |
|
63
|
} |