1 import { AdjustmentLineDTO, BigNumberInput, TaxLineDTO } from "@medusajs/types"
2 import { isDefined, pickValueFromObject } from "../../common"
3 import { calculateAdjustmentTotal } from "../adjustment"
4 import { BigNumber } from "../big-number"
5 import { MathBN } from "../math"
6 import { calculateTaxTotal } from "../tax"
7
8 interface GetLineItemsTotalsContext {
9 includeTax?: boolean
10 extraQuantityFields?: Record<string, string>
11 }
12
13 export interface GetItemTotalInput {
14 id: string
15 unit_price: BigNumber
16 quantity: BigNumber
17 is_tax_inclusive?: boolean
18 tax_lines?: Pick<TaxLineDTO, "rate">[]
19 adjustments?: Pick<AdjustmentLineDTO, "amount" | "is_tax_inclusive">[]
20 detail?: {
21 fulfilled_quantity: BigNumber
22 delivered_quantity: BigNumber
23 shipped_quantity: BigNumber
24 return_requested_quantity: BigNumber
25 return_received_quantity: BigNumber
26 return_dismissed_quantity: BigNumber
27 written_off_quantity: BigNumber
28 }
29 }
30
31 export interface GetItemTotalOutput {
32 quantity: BigNumber
33 unit_price: BigNumber
34
35 subtotal: BigNumber
36 original_subtotal: BigNumber
37
38 total: BigNumber
39 original_total: BigNumber
40
41 discount_total: BigNumber
42 discount_subtotal: BigNumber
43 discount_tax_total: BigNumber
44
45 refundable_total?: BigNumber
46 refundable_total_per_unit?: BigNumber
47
48 tax_total: BigNumber
49 original_tax_total: BigNumber
50
51 fulfilled_total?: BigNumber
52 shipped_total?: BigNumber
53 return_requested_total?: BigNumber
54 return_received_total?: BigNumber
55 return_dismissed_total?: BigNumber
56 write_off_total?: BigNumber
57 }
58
59 export function getLineItemsTotals(
60 items: GetItemTotalInput[],
61 context: GetLineItemsTotalsContext
62 ) {
63 const itemsTotals = {}
64
65 let index = 0
66 for (const item of items) {
67 itemsTotals[item.id ?? index] = getLineItemTotals(item, {
68 includeTax: context.includeTax || item.is_tax_inclusive,
69 extraQuantityFields: context.extraQuantityFields,
70 })
71 index++
72 }
73
74 return itemsTotals
75 }
76
77 function setRefundableTotal(
78 item: GetItemTotalInput,
79 discountsTotal: BigNumberInput,
80 discountsSubtotal: BigNumberInput,
81 totals: GetItemTotalOutput
82 ) {
83 const itemDetail = item.detail!
84 const totalReturnedQuantity = MathBN.sum(
85 itemDetail.return_requested_quantity ?? 0,
86 itemDetail.return_received_quantity ?? 0,
87 itemDetail.return_dismissed_quantity ?? 0
88 )
89 const currentQuantity = MathBN.sub(item.quantity, totalReturnedQuantity)
90 // For tax-inclusive items the unit price already includes tax, so the
91 // discount is subtracted in tax-inclusive terms and no tax is added back
92 // below. For non-tax-inclusive items the discount is pre-tax and tax is
93 // applied to the resulting net amount, so subtracting the tax-inclusive
94 // discount here would tax the discount a second time.
95 const discount = item.is_tax_inclusive ? discountsTotal : discountsSubtotal
96 const discountPerUnit = MathBN.div(discount, item.quantity)
97
98 const refundableSubTotal = MathBN.sub(
99 MathBN.mult(currentQuantity, item.unit_price),
100 MathBN.mult(currentQuantity, discountPerUnit)
101 )
102
103 const taxTotal = calculateTaxTotal({
104 isTaxInclusive: item.is_tax_inclusive,
105 taxLines: item.tax_lines || [],
106 taxableAmount: refundableSubTotal,
107 })
108 const refundableTotal = MathBN.add(refundableSubTotal, taxTotal)
109
110 totals.refundable_total_per_unit = new BigNumber(
111 MathBN.eq(currentQuantity, 0)
112 ? 0
113 : MathBN.div(refundableTotal, currentQuantity)
114 )
115 totals.refundable_total = new BigNumber(refundableTotal)
116 }
117
118 export function getLineItemTotals(
119 item: GetItemTotalInput,
120 context: GetLineItemsTotalsContext
121 ) {
122 const isTaxInclusive = item.is_tax_inclusive ?? context.includeTax
123 const sumTax = MathBN.sum(
124 ...((item.tax_lines ?? []).map((taxLine) => taxLine.rate) ?? [])
125 )
126
127 const sumTaxRate = MathBN.div(sumTax, 100)
128 const totalItemPrice = MathBN.mult(item.unit_price, item.quantity)
129
130 /*
131 If the price is inclusive of tax, we need to remove the taxed amount from the subtotal
132 Original Price = Total Price / (1 + Tax Rate)
133 */
134 const subtotal = isTaxInclusive
135 ? MathBN.div(totalItemPrice, MathBN.add(1, sumTaxRate))
136 : totalItemPrice
137
138 // Proportional discounts to current quantity and compute taxes on the current net amount
139 const {
140 adjustmentsTotal: discountsTotal,
141 adjustmentsSubtotal: discountsSubtotalFull,
142 adjustmentSubtotalPerItem,
143 } = calculateAdjustmentTotal({
144 item,
145 adjustments: item.adjustments || [],
146 taxRate: sumTaxRate,
147 })
148
149 const itemDetail = item.detail!
150 const totalReturnedQuantity = MathBN.sum(
151 itemDetail?.return_received_quantity ?? 0,
152 itemDetail?.return_dismissed_quantity ?? 0
153 )
154
155 const currentQuantity = MathBN.sub(item.quantity, totalReturnedQuantity)
156 const currentTotalItemPrice = MathBN.mult(item.unit_price, currentQuantity)
157 const currentSubtotal = isTaxInclusive
158 ? MathBN.div(currentTotalItemPrice, MathBN.add(1, sumTaxRate))
159 : currentTotalItemPrice
160
161 const currentDiscountsSubtotal = MathBN.mult(
162 adjustmentSubtotalPerItem ?? 0,
163 currentQuantity
164 )
165
166 const taxTotal = calculateTaxTotal({
167 taxLines: item.tax_lines || [],
168 taxableAmount: MathBN.sub(currentSubtotal, currentDiscountsSubtotal),
169 setTotalField: "total",
170 })
171
172 const originalTaxTotal = calculateTaxTotal({
173 taxLines: item.tax_lines || [],
174 taxableAmount: currentSubtotal,
175 setTotalField: "subtotal",
176 })
177
178 // Compute full-quantity net total after discounts and taxes to derive per-unit totals
179 const fullDiscountedTaxable = MathBN.sub(subtotal, discountsSubtotalFull ?? 0)
180 const taxTotalFull = calculateTaxTotal({
181 taxLines: item.tax_lines || [],
182 taxableAmount: fullDiscountedTaxable,
183 })
184 const fullNetTotal = MathBN.sum(fullDiscountedTaxable, taxTotalFull)
185
186 const totals: GetItemTotalOutput = {
187 quantity: item.quantity,
188 unit_price: item.unit_price,
189
190 subtotal: new BigNumber(currentSubtotal),
191
192 total: new BigNumber(
193 MathBN.sum(
194 MathBN.sub(currentSubtotal, currentDiscountsSubtotal),
195 taxTotal
196 )
197 ),
198
199 original_subtotal: new BigNumber(
200 MathBN.sub(
201 isTaxInclusive
202 ? currentTotalItemPrice
203 : MathBN.add(currentSubtotal, originalTaxTotal),
204 originalTaxTotal
205 )
206 ),
207
208 original_total: new BigNumber(
209 isTaxInclusive
210 ? currentTotalItemPrice
211 : MathBN.add(currentSubtotal, originalTaxTotal)
212 ),
213
214 // Discount values prorated to the current quantity
215 discount_subtotal: new BigNumber(currentDiscountsSubtotal),
216 discount_tax_total: new BigNumber(MathBN.sub(originalTaxTotal, taxTotal)),
217 discount_total: new BigNumber(
218 MathBN.add(
219 currentDiscountsSubtotal,
220 MathBN.sub(originalTaxTotal, taxTotal)
221 )
222 ),
223
224 tax_total: new BigNumber(taxTotal),
225 original_tax_total: new BigNumber(originalTaxTotal),
226 }
227
228 if (
229 isDefined(item.detail?.return_requested_quantity) ||
230 isDefined(item.detail?.return_received_quantity) ||
231 isDefined(item.detail?.return_dismissed_quantity)
232 ) {
233 setRefundableTotal(item, discountsTotal, discountsSubtotalFull, totals)
234 }
235
236 // Per-unit total should be based on full-quantity net total to support lifecycle totals consistently
237 const div = MathBN.eq(item.quantity, 0) ? 1 : item.quantity
238 const totalPerUnit = MathBN.div(fullNetTotal, div)
239
240 const optionalFields = {
241 ...(context.extraQuantityFields ?? {}),
242 }
243
244 for (const field in optionalFields) {
245 const totalField = optionalFields[field]
246
247 let target = field.includes(".")
248 ? pickValueFromObject(field, item)
249 : item[field]
250
251 if (!isDefined(target)) {
252 continue
253 }
254
255 totals[totalField] = new BigNumber(MathBN.mult(totalPerUnit, target))
256 }
257
258 return totals
259 }