1 import {
2 ChangeActionType,
3 MathBN,
4 MedusaError,
5 } from "@medusajs/framework/utils"
6 import { CreateOrderCreditLineDTO, OrderCreditLineDTO } from "@medusajs/types"
7 import { OrderChangeProcessing } from "../calculate-order-change"
8 import { setActionReference } from "../set-action-reference"
9
10 OrderChangeProcessing.registerActionType(ChangeActionType.CREDIT_LINE_ADD, {
11 operation({ action, currentOrder, options }) {
12 const creditLines: (OrderCreditLineDTO | CreateOrderCreditLineDTO)[] =
13 currentOrder.credit_lines ?? []
14 const existing = creditLines.find(
15 (cl) => "id" in cl && cl?.id === action.reference_id
16 )
17
18 if (existing) {
19 return
20 }
21
22 const newCreditLine = {
23 order_id: currentOrder.id,
24 amount: MathBN.convert(action.amount!),
25 reference: action.reference!,
26 reference_id: action.reference_id!,
27 }
28
29 creditLines.push(newCreditLine)
30
31 setActionReference(newCreditLine, action, options)
32
33 currentOrder.credit_lines = creditLines
34 },
35 validate({ action }) {
36 if (action.amount == null) {
37 throw new MedusaError(
38 MedusaError.Types.INVALID_DATA,
39 "Amount is required."
40 )
41 }
42 },
43 })