1 import {
2 BigNumberInput,
3 OrderDTO,
4 OrderSummaryDTO,
5 } from "@medusajs/framework/types"
6 import {
7 BigNumber,
8 ChangeActionType,
9 MathBN,
10 isPresent,
11 transformPropertiesToBigNumber,
12 } from "@medusajs/framework/utils"
13 import {
14 ActionTypeDefinition,
15 EVENT_STATUS,
16 InternalOrderChangeEvent,
17 OrderChangeEvent,
18 OrderSummaryCalculated,
19 OrderTransaction,
20 VirtualOrder,
21 } from "@types"
22
23 interface ProcessOptions {
24 addActionReferenceToObject?: boolean
25 [key: string]: any
26 }
27
28 export class OrderChangeProcessing {
29 private static typeDefinition: { [key: string]: ActionTypeDefinition } = {}
30 private static defaultConfig = {
31 isDeduction: false,
32 }
33
34 private order: VirtualOrder
35 private transactions: OrderTransaction[]
36 private actions: InternalOrderChangeEvent[]
37 private options: ProcessOptions = {}
38
39 private actionsProcessed: { [key: string]: InternalOrderChangeEvent[] } = {}
40 private groupTotal: Record<string, BigNumberInput> = {}
41 private summary: OrderSummaryCalculated
42
43 public static registerActionType(key: string, type: ActionTypeDefinition) {
44 OrderChangeProcessing.typeDefinition[key] = type
45 }
46
47 constructor({
48 order,
49 transactions,
50 actions,
51 options,
52 }: {
53 order: VirtualOrder
54 transactions: OrderTransaction[]
55 actions: InternalOrderChangeEvent[]
56 options: ProcessOptions
57 }) {
58 this.order = JSON.parse(JSON.stringify(order))
59 this.transactions = JSON.parse(JSON.stringify(transactions ?? []))
60 this.actions = JSON.parse(JSON.stringify(actions ?? []))
61 this.options = options
62
63 let paid = MathBN.convert(0)
64 let refunded = MathBN.convert(0)
65 let transactionTotal = MathBN.convert(0)
66 let creditLineTotal = (this.order.credit_lines || []).reduce(
67 (acc, creditLine) => MathBN.add(acc, creditLine.amount),
68 MathBN.convert(0)
69 )
70
71 for (const tr of transactions) {
72 if (MathBN.lt(tr.amount, 0)) {
73 refunded = MathBN.add(refunded, MathBN.abs(tr.amount))
74 } else {
75 paid = MathBN.add(paid, tr.amount)
76 }
77 transactionTotal = MathBN.add(transactionTotal, tr.amount)
78 }
79
80 transformPropertiesToBigNumber(this.order.metadata)
81
82 this.summary = {
83 pending_difference: 0,
84 current_order_total: this.order.total ?? 0,
85 original_order_total: this.order.total ?? 0,
86 transaction_total: transactionTotal,
87 paid_total: paid,
88 refunded_total: refunded,
89 credit_line_total: creditLineTotal,
90 accounting_total: MathBN.sub(this.order.total ?? 0, creditLineTotal),
91 }
92 }
93
94 private isEventActive(action: InternalOrderChangeEvent): boolean {
95 const status = action.status
96 return (
97 status === undefined ||
98 status === EVENT_STATUS.PENDING ||
99 status === EVENT_STATUS.DONE
100 )
101 }
102
103 public processActions() {
104 let newCreditLineTotal = (this.order.credit_lines ?? [])
105 .filter((cl) => !("id" in cl))
106 .reduce(
107 (acc, creditLine) => MathBN.add(acc, creditLine.amount),
108 MathBN.convert(0)
109 )
110
111 for (const action of this.actions) {
112 this.processAction_(action)
113 }
114
115 const summary = this.summary
116
117 for (const action of this.actions) {
118 if (!this.isEventActive(action)) {
119 continue
120 }
121
122 const type = {
123 ...OrderChangeProcessing.defaultConfig,
124 ...OrderChangeProcessing.typeDefinition[action.action],
125 }
126
127 const amount = MathBN.mult(action.amount!, type.isDeduction ? -1 : 1)
128
129 if (action.change_id) {
130 this.groupTotal[action.change_id] ??= 0
131 this.groupTotal[action.change_id] = MathBN.add(
132 this.groupTotal[action.change_id],
133 amount
134 )
135 }
136
137 if (action.action === ChangeActionType.CREDIT_LINE_ADD) {
138 newCreditLineTotal = MathBN.add(newCreditLineTotal, amount)
139 summary.current_order_total = MathBN.sub(
140 summary.current_order_total,
141 amount
142 )
143 } else {
144 summary.current_order_total = MathBN.add(
145 summary.current_order_total,
146 amount
147 )
148 }
149 }
150
151 summary.credit_line_total = newCreditLineTotal
152 summary.accounting_total = summary.current_order_total
153
154 summary.transaction_total = MathBN.sum(
155 ...this.transactions.map((tr) => tr.amount)
156 )
157
158 summary.pending_difference = MathBN.sub(
159 summary.current_order_total,
160 summary.transaction_total
161 )
162 }
163
164 private processAction_(
165 action: InternalOrderChangeEvent,
166 isReplay = false
167 ): void {
168 const definedType = OrderChangeProcessing.typeDefinition[action.action]
169
170 if (!isPresent(definedType)) {
171 throw new Error(`Action type ${action.action} is not defined`)
172 }
173
174 const type = {
175 ...OrderChangeProcessing.defaultConfig,
176 ...definedType,
177 }
178
179 this.actionsProcessed[action.action] ??= []
180
181 if (!isReplay) {
182 this.actionsProcessed[action.action].push(action)
183 }
184
185 let calculatedAmount = action.amount ?? 0
186 const params = {
187 actions: this.actions,
188 action,
189 currentOrder: this.order,
190 summary: this.summary,
191 transactions: this.transactions,
192 type,
193 options: this.options,
194 }
195 if (typeof type.validate === "function") {
196 type.validate(params)
197 }
198
199 if (typeof type.operation === "function") {
200 calculatedAmount = type.operation(params) as BigNumberInput
201
202 // the action.amount has priority over the calculated amount
203 if (action.amount == undefined) {
204 action.amount = calculatedAmount ?? 0
205 }
206 }
207 }
208
209 /**
210 * Only used for order creation.
211 */
212 public getSummary(): OrderSummaryDTO {
213 const summary = this.summary
214 const orderSummary = {
215 transaction_total: new BigNumber(summary.transaction_total),
216 original_order_total: new BigNumber(summary.original_order_total),
217 current_order_total: new BigNumber(summary.current_order_total),
218 pending_difference: new BigNumber(summary.pending_difference),
219 paid_total: new BigNumber(summary.paid_total),
220 refunded_total: new BigNumber(summary.refunded_total),
221 credit_line_total: new BigNumber(summary.credit_line_total),
222 accounting_total: new BigNumber(summary.accounting_total),
223 } as unknown as OrderSummaryDTO
224
225 return orderSummary
226 }
227
228 // Returns the order summary from a calculated order including taxes <- this is used for order preview flow
229 public getSummaryFromOrder(order: OrderDTO): OrderSummaryDTO {
230 const summary_ = this.summary
231 const total = order.total
232 const pendingDifference = MathBN.sub(total, summary_.transaction_total)
233
234 const orderSummary = {
235 transaction_total: new BigNumber(summary_.transaction_total),
236 original_order_total: new BigNumber(summary_.original_order_total),
237 current_order_total: new BigNumber(total),
238 pending_difference: new BigNumber(pendingDifference),
239 paid_total: new BigNumber(summary_.paid_total),
240 refunded_total: new BigNumber(summary_.refunded_total),
241 credit_line_total: new BigNumber(summary_.credit_line_total),
242 accounting_total: new BigNumber(summary_.accounting_total),
243 } as any
244
245 orderSummary.accounting_total = orderSummary.current_order_total
246
247 return orderSummary
248 }
249
250 public getCurrentOrder(): VirtualOrder {
251 return this.order
252 }
253 }
254
255 export function calculateOrderChange({
256 order,
257 transactions = [],
258 actions = [],
259 options = {},
260 }: {
261 order: VirtualOrder
262 transactions?: OrderTransaction[]
263 actions?: OrderChangeEvent[]
264 options?: ProcessOptions
265 }) {
266 const calc = new OrderChangeProcessing({
267 order,
268 transactions,
269 actions,
270 options,
271 })
272 calc.processActions()
273
274 return {
275 instance: calc,
276 summary: calc.getSummary(), // used for order creation, in other flows we call `getSummaryFromOrder` to get values from calculated totals
277 getSummaryFromOrder: (order: OrderDTO) => calc.getSummaryFromOrder(order),
278 order: calc.getCurrentOrder(),
279 }
280 }