|
1
|
import { BigNumberInput, TaxLineDTO } from "@medusajs/types" |
|
2
|
import { BigNumber } from "../big-number" |
|
3
|
import { MathBN } from "../math" |
|
4
|
|
|
5
|
export function calculateTaxTotal({ |
|
6
|
isTaxInclusive = false, |
|
7
|
taxLines, |
|
8
|
taxableAmount, |
|
9
|
setTotalField, |
|
10
|
}: { |
|
11
|
isTaxInclusive?: boolean |
|
12
|
taxLines: Pick<TaxLineDTO, "rate">[] |
|
13
|
taxableAmount: BigNumberInput |
|
14
|
setTotalField?: string |
|
15
|
}) { |
|
16
|
let taxTotal = MathBN.convert(0) |
|
17
|
if (isTaxInclusive) { |
|
18
|
return taxTotal |
|
19
|
} |
|
20
|
|
|
21
|
for (const taxLine of taxLines) { |
|
22
|
const rate = MathBN.div(taxLine.rate, 100) |
|
23
|
let taxAmount = MathBN.mult(taxableAmount, rate) |
|
24
|
|
|
25
|
if (setTotalField) { |
|
26
|
;(taxLine as any)[setTotalField] = new BigNumber(taxAmount) |
|
27
|
} |
|
28
|
|
|
29
|
taxTotal = MathBN.add(taxTotal, taxAmount) |
|
30
|
} |
|
31
|
|
|
32
|
return taxTotal |
|
33
|
} |
|
34
|
|
|
35
|
export function calculateAmountsWithTax({ |
|
36
|
taxLines, |
|
37
|
amount, |
|
38
|
includesTax, |
|
39
|
}: { |
|
40
|
taxLines: Pick<TaxLineDTO, "rate">[] |
|
41
|
amount: number |
|
42
|
includesTax?: boolean |
|
43
|
}) { |
|
44
|
const sumTaxRate = MathBN.div( |
|
45
|
MathBN.sum(...((taxLines ?? []).map((taxLine) => taxLine.rate) ?? [])), |
|
46
|
100 |
|
47
|
) |
|
48
|
|
|
49
|
const taxableAmount = includesTax |
|
50
|
? MathBN.div(amount, MathBN.add(1, sumTaxRate)) |
|
51
|
: amount |
|
52
|
|
|
53
|
const tax = calculateTaxTotal({ |
|
54
|
taxLines, |
|
55
|
taxableAmount, |
|
56
|
}) |
|
57
|
|
|
58
|
return { |
|
59
|
priceWithTax: includesTax ? amount : MathBN.add(tax, amount).toNumber(), |
|
60
|
priceWithoutTax: includesTax ? MathBN.sub(amount, tax).toNumber() : amount, |
|
61
|
} |
|
62
|
} |