|
1
|
import { AdjustmentLineDTO, BigNumberInput } from "@medusajs/types" |
|
2
|
import { isDefined } from "../../common" |
|
3
|
import { BigNumber } from "../big-number" |
|
4
|
import { MathBN } from "../math" |
|
5
|
|
|
6
|
export function calculateAdjustmentTotal({ |
|
7
|
item, |
|
8
|
adjustments, |
|
9
|
taxRate, |
|
10
|
}: { |
|
11
|
item?: { quantity: BigNumberInput } |
|
12
|
adjustments: Pick<AdjustmentLineDTO, "amount" | "is_tax_inclusive">[] |
|
13
|
taxRate?: BigNumberInput |
|
14
|
}) { |
|
15
|
// the sum of all adjustment amounts excluding tax |
|
16
|
let adjustmentsSubtotal = MathBN.convert(0) |
|
17
|
// the sum of all adjustment amounts including tax |
|
18
|
let adjustmentsTotal = MathBN.convert(0) |
|
19
|
// the sum of all taxes on subtotals |
|
20
|
let adjustmentsTaxTotal = MathBN.convert(0) |
|
21
|
|
|
22
|
for (const adj of adjustments) { |
|
23
|
if (!isDefined(adj.amount)) { |
|
24
|
continue |
|
25
|
} |
|
26
|
|
|
27
|
const adjustmentSubtotal = |
|
28
|
isDefined(taxRate) && adj.is_tax_inclusive |
|
29
|
? MathBN.div(adj.amount, MathBN.add(1, taxRate)) |
|
30
|
: adj.amount |
|
31
|
|
|
32
|
const adjustmentTaxTotal = isDefined(taxRate) |
|
33
|
? MathBN.mult(adjustmentSubtotal, taxRate) |
|
34
|
: 0 |
|
35
|
const adjustmentTotal = MathBN.add(adjustmentSubtotal, adjustmentTaxTotal) |
|
36
|
|
|
37
|
adjustmentsSubtotal = MathBN.add(adjustmentsSubtotal, adjustmentSubtotal) |
|
38
|
adjustmentsTaxTotal = MathBN.add(adjustmentsTaxTotal, adjustmentTaxTotal) |
|
39
|
adjustmentsTotal = MathBN.add(adjustmentsTotal, adjustmentTotal) |
|
40
|
|
|
41
|
// Assign this adjustment's OWN subtotal/total — not the running cumulative |
|
42
|
// sum across all adjustments. Using the plural accumulators here inflated |
|
43
|
// every adjustment after the first to the cumulative total. |
|
44
|
adj["subtotal"] = new BigNumber(adjustmentSubtotal) |
|
45
|
adj["total"] = new BigNumber(adjustmentTotal) |
|
46
|
} |
|
47
|
|
|
48
|
const quantity = item?.quantity || MathBN.convert(1) |
|
49
|
|
|
50
|
let adjustmentPerItem = MathBN.convert(0) |
|
51
|
let adjustmentSubtotalPerItem = MathBN.convert(0) |
|
52
|
let adjustmentTaxTotalPerItem = MathBN.convert(0) |
|
53
|
|
|
54
|
if (!MathBN.eq(quantity, 0)) { |
|
55
|
adjustmentPerItem = MathBN.div(adjustmentsTotal, quantity) |
|
56
|
adjustmentSubtotalPerItem = MathBN.div(adjustmentsSubtotal, quantity) |
|
57
|
adjustmentTaxTotalPerItem = MathBN.div(adjustmentsTaxTotal, quantity) |
|
58
|
} |
|
59
|
|
|
60
|
return { |
|
61
|
adjustmentsTotal, |
|
62
|
adjustmentsSubtotal, |
|
63
|
adjustmentsTaxTotal, |
|
64
|
adjustmentPerItem, |
|
65
|
adjustmentSubtotalPerItem, |
|
66
|
adjustmentTaxTotalPerItem, |
|
67
|
} |
|
68
|
} |