@aptos-scp/scp-component-store-selling-features-domain-model 2.28.0 → 2.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -151,6 +151,7 @@ export declare const CUSTOMER_INPUT_EVENT: string;
151
151
  export declare const CUSTOMER_INPUT_RESULT_EVENT: string;
152
152
  export declare const PAYMENT_ACCOUNT_HOLDER_VALIDATE_EVENT: string;
153
153
  export declare const SHIPPING_FEE_REFUND_EVENT: string;
154
+ export declare const RETURN_ORDER_SHIPPING_FEE_REFUND_EVENT: string;
154
155
  export declare const RETURN_ITEM_EVENT: string;
155
156
  export declare const ITEM_FEE_REFUND_EVENT: string;
156
157
  export declare const ORDER_ITEM_EVENT: string;
@@ -274,6 +275,7 @@ export declare const EXIT_RETURN_WITH_TRANSACTION_EVENT: string;
274
275
  export declare const RECORD_TRANSACTION_FOR_RETURN_EVENT: string;
275
276
  export declare const RECORD_RELATED_TRANSACTIONS_FOR_RETURN_EVENT: string;
276
277
  export declare const RECORD_RELATED_TRANSACTION_FOR_RETURN_EVENT: string;
278
+ export declare const RECORD_RELATED_ORDER_FOR_RETURN_EVENT: string;
277
279
  export declare const SELECT_TRANSACTION_FOR_RETURN_EVENT: string;
278
280
  export declare const RECORD_TRANSACTION_FOR_ORDER_EVENT: string;
279
281
  export declare const START_TILL_RECONCILIATION_EVENT = "StartTillReconciliation";
@@ -154,6 +154,7 @@ exports.CUSTOMER_INPUT_EVENT = "CustomerInput";
154
154
  exports.CUSTOMER_INPUT_RESULT_EVENT = "CustomerInputResult";
155
155
  exports.PAYMENT_ACCOUNT_HOLDER_VALIDATE_EVENT = "PaymentAccountHolderValidate";
156
156
  exports.SHIPPING_FEE_REFUND_EVENT = "ShippingFeeRefund";
157
+ exports.RETURN_ORDER_SHIPPING_FEE_REFUND_EVENT = "ReturnOrderShippingFeeRefund";
157
158
  exports.RETURN_ITEM_EVENT = "ReturnItem";
158
159
  exports.ITEM_FEE_REFUND_EVENT = "RefundItemFee";
159
160
  exports.ORDER_ITEM_EVENT = "OrderItem";
@@ -281,6 +282,7 @@ exports.EXIT_RETURN_WITH_TRANSACTION_EVENT = "ExitReturnWithTransaction";
281
282
  exports.RECORD_TRANSACTION_FOR_RETURN_EVENT = "RecordTransactionForReturn";
282
283
  exports.RECORD_RELATED_TRANSACTIONS_FOR_RETURN_EVENT = "RecordRelatedTransactionsForReturn";
283
284
  exports.RECORD_RELATED_TRANSACTION_FOR_RETURN_EVENT = "RecordRelatedTransactionForReturn";
285
+ exports.RECORD_RELATED_ORDER_FOR_RETURN_EVENT = "RecordRelatedOrderForReturn";
284
286
  exports.SELECT_TRANSACTION_FOR_RETURN_EVENT = "SelectTransactionForReturn";
285
287
  exports.RECORD_TRANSACTION_FOR_ORDER_EVENT = "RecordTransactionForOrder";
286
288
  exports.START_TILL_RECONCILIATION_EVENT = "StartTillReconciliation";
@@ -461,7 +461,12 @@ export declare enum UiInputKey {
461
461
  CUSTOMER_INPUT_MODE = "input_customerInputMode",
462
462
  FORCE_FISCAL_COMPLETION = "input_forceFiscalCompletion",
463
463
  IS_FISCALISE_VOID = "input_isFiscaliseVoid",
464
- PAYMENT_FUNCTION = "input_paymentFunction"
464
+ PAYMENT_FUNCTION = "input_paymentFunction",
465
+ SELECTED_RETURN_FEES = "input_selectedReturnFees",
466
+ SELECTED_RETURN_ITEMS = "input_selectedReturnItems",
467
+ FEE_LINE_FOR_REFUND = "input_feeLineForRefund",
468
+ FEE_REFUND_SOURCE = "input_feeRefundSource",
469
+ FEE_REFUNDABLE_AMOUNT = "input_feeRefundableAmount"
465
470
  }
466
471
  export declare enum CollectedDataKey {
467
472
  Abort = "abort",
@@ -649,12 +654,15 @@ export declare enum CollectedDataKey {
649
654
  OfflineAuthorizationCode = "OfflineAuthorizationCode",
650
655
  OriginalExtendedAmount = "OriginalExtendedAmount",
651
656
  Order = "order",
657
+ CustomerOrders = "CustomerOrders",
652
658
  OrderInquiryCustomerOrders = "orderInquiryCustomerOrders",
653
659
  LineNumberFromOrder = "lineNumberFromOrder",
654
660
  OrderLineReference = "orderLineReference",
655
661
  OrderReference = "orderReference",
656
662
  OrderReferenceId = "orderReferenceId",
657
663
  OrderReferenceOrder = "orderReferenceOrder",
664
+ OrderForReturn = "orderForReturn",
665
+ UsingExistingOrderInformation = "usingExistingOrderInformation",
658
666
  OriginalOrderTransactionReference = "originalOrderTransactionReference",
659
667
  ExtendedAmountFromExternalItem = "extendedAmountFromExternalItem",
660
668
  ExtendedAmountIncludingTaxFromExternalItem = "extendedAmountIncludingTaxFromExternalItem",
@@ -463,6 +463,11 @@ var UiInputKey;
463
463
  UiInputKey["FORCE_FISCAL_COMPLETION"] = "input_forceFiscalCompletion";
464
464
  UiInputKey["IS_FISCALISE_VOID"] = "input_isFiscaliseVoid";
465
465
  UiInputKey["PAYMENT_FUNCTION"] = "input_paymentFunction";
466
+ UiInputKey["SELECTED_RETURN_FEES"] = "input_selectedReturnFees";
467
+ UiInputKey["SELECTED_RETURN_ITEMS"] = "input_selectedReturnItems";
468
+ UiInputKey["FEE_LINE_FOR_REFUND"] = "input_feeLineForRefund";
469
+ UiInputKey["FEE_REFUND_SOURCE"] = "input_feeRefundSource";
470
+ UiInputKey["FEE_REFUNDABLE_AMOUNT"] = "input_feeRefundableAmount";
466
471
  })(UiInputKey = exports.UiInputKey || (exports.UiInputKey = {}));
467
472
  //
468
473
  // Keys for use in relaying data collectedData (qualification) and nonContextualData (action).
@@ -656,12 +661,15 @@ var CollectedDataKey;
656
661
  CollectedDataKey["OfflineAuthorizationCode"] = "OfflineAuthorizationCode";
657
662
  CollectedDataKey["OriginalExtendedAmount"] = "OriginalExtendedAmount";
658
663
  CollectedDataKey["Order"] = "order";
664
+ CollectedDataKey["CustomerOrders"] = "CustomerOrders";
659
665
  CollectedDataKey["OrderInquiryCustomerOrders"] = "orderInquiryCustomerOrders";
660
666
  CollectedDataKey["LineNumberFromOrder"] = "lineNumberFromOrder";
661
667
  CollectedDataKey["OrderLineReference"] = "orderLineReference";
662
668
  CollectedDataKey["OrderReference"] = "orderReference";
663
669
  CollectedDataKey["OrderReferenceId"] = "orderReferenceId";
664
670
  CollectedDataKey["OrderReferenceOrder"] = "orderReferenceOrder";
671
+ CollectedDataKey["OrderForReturn"] = "orderForReturn";
672
+ CollectedDataKey["UsingExistingOrderInformation"] = "usingExistingOrderInformation";
665
673
  CollectedDataKey["OriginalOrderTransactionReference"] = "originalOrderTransactionReference";
666
674
  CollectedDataKey["ExtendedAmountFromExternalItem"] = "extendedAmountFromExternalItem";
667
675
  CollectedDataKey["ExtendedAmountIncludingTaxFromExternalItem"] = "extendedAmountIncludingTaxFromExternalItem";
@@ -0,0 +1,113 @@
1
+ import { Money } from "@aptos-scp/scp-component-business-core";
2
+ import { IConfigurationManager, IState } from "@aptos-scp/scp-component-store-selling-core";
3
+ import { FeeType, IFeeLine } from "@aptos-scp/scp-types-commerce-transaction";
4
+ import { CustomerOrder } from "@aptos-scp/scp-types-orders";
5
+ import { IOriginalTender } from "./TenderHandlingSession";
6
+ export declare const ORDER_HANDLING_SESSION: string;
7
+ /**
8
+ * Wrapper containing original CustomerOrder plus converted/processed data for return operations.
9
+ * Follows the pattern from ItemHandlingSession (TransactionInformation) and TenderHandlingSession (IOriginalTransactionDetails).
10
+ */
11
+ export interface OrderInformation {
12
+ /** The unique order reference identifier */
13
+ orderReferenceId: string;
14
+ /** The original customer order from OMS */
15
+ customerOrder: CustomerOrder;
16
+ /** Fee lines converted from order fees, ready for return operations */
17
+ originalFees?: IOriginalFee[];
18
+ /** Original tenders from the order (for future tender return logic) */
19
+ originalTenders?: IOriginalTender[];
20
+ /** Timestamp of the order information creation, for tracking order staleness*/
21
+ informationTimestamp: Date;
22
+ }
23
+ export interface IOriginalFee {
24
+ originalFeeAmount: Money;
25
+ refundedAmount: Money;
26
+ previouslyRefundedAmount: Money;
27
+ refundableAmount: Money;
28
+ refundAllowed: boolean;
29
+ feeId: string;
30
+ feeType: FeeType;
31
+ customFeeType?: string;
32
+ description: string;
33
+ longDescription: string;
34
+ feeLine: IFeeLine;
35
+ }
36
+ export declare class OrderHandlingSession implements IState {
37
+ private _state;
38
+ private _orderInformationCollection;
39
+ private _orderInformationForReturn?;
40
+ private _type;
41
+ static create(): OrderHandlingSession;
42
+ static createFromJsonObject(orderHandlingSessionJsonObject: any): OrderHandlingSession;
43
+ get stateValues(): Readonly<Map<string, any>>;
44
+ get type(): Readonly<string>;
45
+ get inProgress(): boolean;
46
+ /**
47
+ * Gets the collection of OrderInformation objects.
48
+ * This provides access to all the orders and their information.
49
+ */
50
+ get orderInformationCollection(): OrderInformation[];
51
+ /**
52
+ * Gets the OrderInformation wrapper for the order for return.
53
+ * This provides access to both the original order and all converted data.
54
+ */
55
+ get orderInformationForReturn(): OrderInformation | undefined;
56
+ /**
57
+ * Gets the original fee lines converted from the order for return.
58
+ * These are IFeeLine objects ready to be used in return operations.
59
+ */
60
+ get originalFeesForReturn(): IOriginalFee[] | undefined;
61
+ /**
62
+ * Sets an order as the order for return AND processes its information.
63
+ * This is the key method that converts order data for return operations.
64
+ *
65
+ * @param order The CustomerOrder to set as the order for return
66
+ * @param inputSource Optional source identifier
67
+ * @param configurationManager Configuration manager for fee definitions (optional)
68
+ */
69
+ setOrderInformationForReturn(order: CustomerOrder, configurationManager?: IConfigurationManager): OrderHandlingSession;
70
+ /**
71
+ * Selects an order from the collection to be the order for return.
72
+ * @param orderReferenceId The order request ID to select
73
+ * @param configurationManager Configuration manager for fee definitions (optional)
74
+ */
75
+ selectOrderForReturn(orderReferenceId: string): OrderHandlingSession;
76
+ /**
77
+ * Resets the session to initial state with no order information.
78
+ */
79
+ reset(): OrderHandlingSession;
80
+ /**
81
+ * Starts the order handling session (transitions to InProgress state).
82
+ */
83
+ startSession(): OrderHandlingSession;
84
+ /**
85
+ * Completes the order handling session (transitions to Completed state).
86
+ */
87
+ completeSession(): OrderHandlingSession;
88
+ /**
89
+ * Updates the refundedAmount for an IOriginalFee in the orderInformationForReturn.
90
+ * This is called when a shipping fee refund line is added to the transaction.
91
+ *
92
+ * @param orderReferenceId The order reference ID to identify which order's fee to update
93
+ * @param feeId The fee ID to identify which fee to update
94
+ * @param feeType The fee type to identify which fee to update
95
+ * @param refundAmount The amount to add to the refundedAmount (positive for refund, negative for void)
96
+ * @returns A new OrderHandlingSession with the updated originalFee
97
+ */
98
+ updateOriginalFeeRefundedAmount(orderReferenceId: string, feeId: string, feeType: FeeType, refundAmount: Money): OrderHandlingSession;
99
+ private constructor();
100
+ /**
101
+ * Processes an order for return operations by converting fees to IFeeLine.
102
+ * @private
103
+ */
104
+ private processOrderForReturn;
105
+ /**
106
+ * Converts order fees to IOriginalFee array for tracking refundable amounts.
107
+ *
108
+ * @private
109
+ */
110
+ private processOriginalFees;
111
+ private createOriginalFeeFromOrderFee;
112
+ private isFeeRefundAllowed;
113
+ }
@@ -0,0 +1,316 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const scp_component_logging_1 = require("@aptos-scp/scp-component-logging");
4
+ const scp_component_business_core_1 = require("@aptos-scp/scp-component-business-core");
5
+ const scp_types_commerce_transaction_1 = require("@aptos-scp/scp-types-commerce-transaction");
6
+ const utility_1 = require("../utility");
7
+ const configuration_1 = require("./configuration");
8
+ const logger = scp_component_logging_1.LogManager.getLogger("com.aptos.storesellingfeatures.domain.model.OrderHandlingSession");
9
+ exports.ORDER_HANDLING_SESSION = "OrderHandlingSession";
10
+ var OrderHandlingSessionState;
11
+ (function (OrderHandlingSessionState) {
12
+ OrderHandlingSessionState["Initial"] = "Initial";
13
+ OrderHandlingSessionState["InProgress"] = "InProgress";
14
+ OrderHandlingSessionState["Completed"] = "Completed";
15
+ })(OrderHandlingSessionState || (OrderHandlingSessionState = {}));
16
+ class OrderHandlingSession {
17
+ constructor(state, orderInformationCollection, orderInformationForReturn) {
18
+ this._state = state;
19
+ this._orderInformationCollection = orderInformationCollection;
20
+ this._orderInformationForReturn = orderInformationForReturn;
21
+ this._type = exports.ORDER_HANDLING_SESSION;
22
+ }
23
+ static create() {
24
+ return new OrderHandlingSession(OrderHandlingSessionState.Initial, [], undefined);
25
+ }
26
+ static createFromJsonObject(orderHandlingSessionJsonObject) {
27
+ const state = orderHandlingSessionJsonObject._state;
28
+ const orderInformationCollection = createOrderInformationCollectionFromJson(orderHandlingSessionJsonObject._orderInformationCollection);
29
+ const orderInformationForReturn = createOrderInformationFromJson(orderHandlingSessionJsonObject._orderInformationForReturn);
30
+ return new OrderHandlingSession(state, orderInformationCollection, orderInformationForReturn);
31
+ }
32
+ get stateValues() {
33
+ return new Map([
34
+ ["OrderHandlingSession.state", this._state],
35
+ ["OrderHandlingSession.orderInformationCollection", this._orderInformationCollection],
36
+ ["OrderHandlingSession.orderInformationForReturn", this._orderInformationForReturn],
37
+ ["OrderHandlingSession.inProgress", this.inProgress],
38
+ ]);
39
+ }
40
+ get type() {
41
+ return this._type;
42
+ }
43
+ get inProgress() {
44
+ return this._state === OrderHandlingSessionState.InProgress;
45
+ }
46
+ /**
47
+ * Gets the collection of OrderInformation objects.
48
+ * This provides access to all the orders and their information.
49
+ */
50
+ get orderInformationCollection() {
51
+ return this._orderInformationCollection ? this._orderInformationCollection : [];
52
+ }
53
+ /**
54
+ * Gets the OrderInformation wrapper for the order for return.
55
+ * This provides access to both the original order and all converted data.
56
+ */
57
+ get orderInformationForReturn() {
58
+ return this._orderInformationForReturn;
59
+ }
60
+ /**
61
+ * Gets the original fee lines converted from the order for return.
62
+ * These are IFeeLine objects ready to be used in return operations.
63
+ */
64
+ get originalFeesForReturn() {
65
+ var _a;
66
+ return (_a = this._orderInformationForReturn) === null || _a === void 0 ? void 0 : _a.originalFees;
67
+ }
68
+ /**
69
+ * Sets an order as the order for return AND processes its information.
70
+ * This is the key method that converts order data for return operations.
71
+ *
72
+ * @param order The CustomerOrder to set as the order for return
73
+ * @param inputSource Optional source identifier
74
+ * @param configurationManager Configuration manager for fee definitions (optional)
75
+ */
76
+ setOrderInformationForReturn(order, configurationManager) {
77
+ var _a;
78
+ logger.traceEntry("setOrderInformationForReturn", (_a = order) === null || _a === void 0 ? void 0 : _a.orderRequestId);
79
+ if (!order) {
80
+ logger.warn("Order not provided to setOrderInformationForReturn");
81
+ return this;
82
+ }
83
+ // Process the order and convert fees
84
+ const processedOrderInfo = this.processOrderForReturn(order, configurationManager);
85
+ // Also add to collection if not already there, or replace if it already exists
86
+ const orderInformationCollection = [...(this._orderInformationCollection || [])];
87
+ const existingIndex = orderInformationCollection.findIndex((info) => info.orderReferenceId === order.orderRequestId);
88
+ if (existingIndex >= 0) {
89
+ // Update existing with processed data
90
+ orderInformationCollection[existingIndex] = processedOrderInfo;
91
+ }
92
+ else {
93
+ // Add new
94
+ orderInformationCollection.push(processedOrderInfo);
95
+ }
96
+ logger.debug(() => `Set order ${order.orderRequestId} as orderForReturn`);
97
+ return new OrderHandlingSession(this._state, orderInformationCollection, processedOrderInfo);
98
+ }
99
+ /**
100
+ * Selects an order from the collection to be the order for return.
101
+ * @param orderReferenceId The order request ID to select
102
+ * @param configurationManager Configuration manager for fee definitions (optional)
103
+ */
104
+ selectOrderForReturn(orderReferenceId) {
105
+ logger.traceEntry("selectOrderForReturn", orderReferenceId);
106
+ const orderInformationForReturn = this._orderInformationCollection.find((info) => info.orderReferenceId === orderReferenceId);
107
+ if (!orderInformationForReturn) {
108
+ logger.warn(`Order not found in collection: ${orderReferenceId}`);
109
+ return this;
110
+ }
111
+ return new OrderHandlingSession(this._state, this._orderInformationCollection, orderInformationForReturn);
112
+ }
113
+ /**
114
+ * Resets the session to initial state with no order information.
115
+ */
116
+ reset() {
117
+ return new OrderHandlingSession(OrderHandlingSessionState.Initial, [], undefined);
118
+ }
119
+ /**
120
+ * Starts the order handling session (transitions to InProgress state).
121
+ */
122
+ startSession() {
123
+ return new OrderHandlingSession(OrderHandlingSessionState.InProgress, this._orderInformationCollection, this._orderInformationForReturn);
124
+ }
125
+ /**
126
+ * Completes the order handling session (transitions to Completed state).
127
+ */
128
+ completeSession() {
129
+ return new OrderHandlingSession(OrderHandlingSessionState.Completed, this._orderInformationCollection, this._orderInformationForReturn);
130
+ }
131
+ /**
132
+ * Updates the refundedAmount for an IOriginalFee in the orderInformationForReturn.
133
+ * This is called when a shipping fee refund line is added to the transaction.
134
+ *
135
+ * @param orderReferenceId The order reference ID to identify which order's fee to update
136
+ * @param feeId The fee ID to identify which fee to update
137
+ * @param feeType The fee type to identify which fee to update
138
+ * @param refundAmount The amount to add to the refundedAmount (positive for refund, negative for void)
139
+ * @returns A new OrderHandlingSession with the updated originalFee
140
+ */
141
+ updateOriginalFeeRefundedAmount(orderReferenceId, feeId, feeType, refundAmount) {
142
+ var _a;
143
+ logger.traceEntry("updateOriginalFeeRefundedAmount", orderReferenceId, feeId, feeType, refundAmount);
144
+ // Find the order in the collection by orderReferenceId
145
+ const orderInfoIndex = this._orderInformationCollection.findIndex((info) => info.orderReferenceId === orderReferenceId);
146
+ if (orderInfoIndex < 0) {
147
+ logger.warn(`Order not found in collection: ${orderReferenceId}`);
148
+ return this;
149
+ }
150
+ const orderInfo = this._orderInformationCollection[orderInfoIndex];
151
+ const originalFees = orderInfo.originalFees;
152
+ if (!originalFees || originalFees.length === 0) {
153
+ logger.warn("No original fees to update");
154
+ return this;
155
+ }
156
+ // Find the matching fee by feeId and feeType
157
+ const feeIndex = originalFees.findIndex((fee) => fee.feeId === feeId && fee.feeType === feeType);
158
+ if (feeIndex < 0) {
159
+ logger.warn(`Original fee not found: feeId=${feeId}, feeType=${feeType}`);
160
+ return this;
161
+ }
162
+ // Create updated fees array with the new refundedAmount
163
+ const updatedFees = [...originalFees];
164
+ const originalFee = updatedFees[feeIndex];
165
+ const refundedAmount = scp_component_business_core_1.Money.fromIMoney(originalFee.refundedAmount);
166
+ const refundableAmount = scp_component_business_core_1.Money.fromIMoney(originalFee.refundableAmount);
167
+ const newRefundedAmount = refundedAmount.plus(refundAmount);
168
+ const newRefundableAmount = refundableAmount.minus(refundAmount);
169
+ updatedFees[feeIndex] = Object.assign(Object.assign({}, originalFee), { refundedAmount: newRefundedAmount, refundableAmount: newRefundableAmount });
170
+ // Create updated orderInformation
171
+ const updatedOrderInfo = Object.assign(Object.assign({}, orderInfo), { originalFees: updatedFees });
172
+ // Update the collection
173
+ const updatedCollection = [...this._orderInformationCollection];
174
+ updatedCollection[orderInfoIndex] = updatedOrderInfo;
175
+ // Update _orderInformationForReturn if this is the selected order
176
+ let updatedOrderInfoForReturn = this._orderInformationForReturn;
177
+ if (((_a = this._orderInformationForReturn) === null || _a === void 0 ? void 0 : _a.orderReferenceId) === orderReferenceId) {
178
+ updatedOrderInfoForReturn = updatedOrderInfo;
179
+ }
180
+ logger.debug(() => `Updated refundedAmount for fee ${feeId}: ${refundedAmount.amount.toString()} -> ${newRefundedAmount.amount.toString()}`);
181
+ return new OrderHandlingSession(this._state, updatedCollection, updatedOrderInfoForReturn);
182
+ }
183
+ /**
184
+ * Processes an order for return operations by converting fees to IFeeLine.
185
+ * @private
186
+ */
187
+ processOrderForReturn(order, configurationManager) {
188
+ logger.traceEntry("processOrderForReturn", order.orderRequestId);
189
+ const orderInfo = {
190
+ orderReferenceId: order.orderRequestId,
191
+ customerOrder: order,
192
+ informationTimestamp: new Date(),
193
+ };
194
+ // Convert fees to IFeeLine for return operations
195
+ if (order.fees && order.fees.length > 0) {
196
+ orderInfo.originalFees = this.processOriginalFees(order.fees, order.orderRequestId, configurationManager);
197
+ logger.debug(() => `Converted ${orderInfo.originalFees.length} fees for order ${order.orderRequestId}`);
198
+ }
199
+ // TODO: Future - convert tenders to IOriginalTender
200
+ // if (order.orderTenders?.length > 0) {
201
+ // orderInfo.originalTenders = this.convertOrderTenders(order.orderTenders);
202
+ // }
203
+ return orderInfo;
204
+ }
205
+ /**
206
+ * Converts order fees to IOriginalFee array for tracking refundable amounts.
207
+ *
208
+ * @private
209
+ */
210
+ processOriginalFees(orderFees, orderReferenceId, configurationManager) {
211
+ if (!orderFees || orderFees.length === 0) {
212
+ return [];
213
+ }
214
+ const convertedFees = [];
215
+ orderFees.forEach((fee) => {
216
+ try {
217
+ if (fee.feeId && fee.quantity && fee.unitAmount) {
218
+ const originalFee = this.createOriginalFeeFromOrderFee(fee, orderReferenceId, configurationManager);
219
+ if (originalFee) {
220
+ convertedFees.push(originalFee);
221
+ }
222
+ }
223
+ }
224
+ catch (error) {
225
+ logger.warn(`Failed to process original fee ${fee.feeId}: ${error}`);
226
+ }
227
+ });
228
+ return convertedFees;
229
+ }
230
+ createOriginalFeeFromOrderFee(orderFee, orderReferenceId, configurationManager) {
231
+ const feeLine = utility_1.convertOrderFee(orderFee, orderReferenceId, configurationManager);
232
+ // Defensive check: convertOrderFee can return undefined if orderFee is missing required properties
233
+ if (!feeLine) {
234
+ logger.warn(`convertOrderFee returned undefined for fee ${orderFee.feeId}`);
235
+ return undefined;
236
+ }
237
+ const originalFeeAmount = scp_component_business_core_1.Money.fromIMoney(orderFee.extendedNetAmount);
238
+ const currency = orderFee.extendedNetAmount.currency;
239
+ const previouslyRefundedAmount = utility_1.calculatePreviouslyRefundedAmount(orderFee.amountModifiers, currency);
240
+ const refundableAmount = originalFeeAmount.minus(previouslyRefundedAmount);
241
+ const refundedAmount = new scp_component_business_core_1.Money("0", originalFeeAmount.currency);
242
+ const refundAllowed = this.isFeeRefundAllowed(orderFee, configurationManager);
243
+ return {
244
+ originalFeeAmount,
245
+ refundedAmount,
246
+ previouslyRefundedAmount,
247
+ refundableAmount,
248
+ refundAllowed: refundAllowed,
249
+ feeId: feeLine.feeId,
250
+ feeType: feeLine.feeType,
251
+ customFeeType: feeLine.customFeeType,
252
+ description: feeLine.description,
253
+ longDescription: feeLine.longDescription,
254
+ feeLine: feeLine,
255
+ };
256
+ }
257
+ isFeeRefundAllowed(orderFee, configurationManager) {
258
+ var _a, _b, _c, _d, _e;
259
+ let refundAllowed = false;
260
+ if (orderFee.feeType === scp_types_commerce_transaction_1.FeeType.Shipping) {
261
+ const allowRefundOrderShippingFee = (_d = (_c = (_b = (_a = configurationManager.getFunctionalBehaviorValues()) === null || _a === void 0 ? void 0 : _a.omniChannelBehaviors) === null || _b === void 0 ? void 0 : _b.orders) === null || _c === void 0 ? void 0 : _c.shippingFeeRefundRules) === null || _d === void 0 ? void 0 : _d.allowRefundOrderShippingFee;
262
+ refundAllowed = allowRefundOrderShippingFee === true;
263
+ }
264
+ else {
265
+ const feeDefinition = utility_1.getFeeDefinitionByFeeId(orderFee.feeId, configurationManager);
266
+ refundAllowed = ((_e = feeDefinition) === null || _e === void 0 ? void 0 : _e.returnRule) !== configuration_1.ReturnRule.NonReturnable;
267
+ }
268
+ return refundAllowed;
269
+ }
270
+ }
271
+ exports.OrderHandlingSession = OrderHandlingSession;
272
+ // ============================================================================
273
+ // JSON Restoration Helper Functions
274
+ // ============================================================================
275
+ function createOrderInformationCollectionFromJson(jsonArray) {
276
+ if (!jsonArray || jsonArray.length === 0) {
277
+ return [];
278
+ }
279
+ return jsonArray.map((jsonOrderInfo) => createOrderInformationFromJson(jsonOrderInfo)).filter(Boolean);
280
+ }
281
+ function createOrderInformationFromJson(jsonObject) {
282
+ if (!jsonObject) {
283
+ return undefined;
284
+ }
285
+ return {
286
+ orderReferenceId: jsonObject.orderReferenceId,
287
+ customerOrder: jsonObject.customerOrder,
288
+ originalFees: createOriginalFeesFromJson(jsonObject.originalFees),
289
+ originalTenders: jsonObject.originalTenders,
290
+ informationTimestamp: jsonObject.informationTimestamp
291
+ ? new Date(jsonObject.informationTimestamp)
292
+ : undefined,
293
+ };
294
+ }
295
+ function createOriginalFeesFromJson(jsonArray) {
296
+ if (!jsonArray || jsonArray.length === 0) {
297
+ return undefined;
298
+ }
299
+ return jsonArray.map((jsonFee) => createOriginalFeeFromJson(jsonFee));
300
+ }
301
+ function createOriginalFeeFromJson(jsonObject) {
302
+ return {
303
+ originalFeeAmount: jsonObject.originalFeeAmount && scp_component_business_core_1.Money.fromIMoney(jsonObject.originalFeeAmount),
304
+ refundedAmount: jsonObject.refundedAmount && scp_component_business_core_1.Money.fromIMoney(jsonObject.refundedAmount),
305
+ previouslyRefundedAmount: jsonObject.previouslyRefundedAmount && scp_component_business_core_1.Money.fromIMoney(jsonObject.previouslyRefundedAmount),
306
+ refundableAmount: jsonObject.refundableAmount && scp_component_business_core_1.Money.fromIMoney(jsonObject.refundableAmount),
307
+ refundAllowed: jsonObject.refundAllowed,
308
+ feeId: jsonObject.feeId,
309
+ feeType: jsonObject.feeType,
310
+ customFeeType: jsonObject.customFeeType,
311
+ description: jsonObject.description,
312
+ longDescription: jsonObject.longDescription,
313
+ feeLine: jsonObject.feeLine,
314
+ };
315
+ }
316
+ //# sourceMappingURL=OrderHandlingSession.js.map
@@ -190,6 +190,7 @@ export declare function isTransactionFeeLine(transactionLine: ITransactionLine):
190
190
  export declare function isTransactionFeeRefundLine(transactionLine: ITransactionLine): transactionLine is FeeLine;
191
191
  export declare function isBagFeeLine(transactionLine: ITransactionLine): transactionLine is FeeLine;
192
192
  export declare function isShippingFeeLine(transactionLine: ITransactionLine): transactionLine is FeeLine;
193
+ export declare function isShippingFeeRefundLine(transactionLine: ITransactionLine): transactionLine is FeeLine;
193
194
  export declare function isDeliveryFeeLine(transactionLine: ITransactionLine): transactionLine is FeeLine;
194
195
  export declare function isItemFeeLine(transactionLine: ITransactionLine): transactionLine is FeeLine;
195
196
  export declare function isItemFeeRefundLine(transactionLine: ITransactionLine): transactionLine is FeeLine;
@@ -742,6 +742,14 @@ function isShippingFeeLine(transactionLine) {
742
742
  return isTransactionFeeLine(transactionLine) && transactionLine.feeType === scp_types_commerce_transaction_1.FeeType.Shipping;
743
743
  }
744
744
  exports.isShippingFeeLine = isShippingFeeLine;
745
+ function isShippingFeeRefundLine(transactionLine) {
746
+ if (!isTransactionFeeRefundLine(transactionLine)) {
747
+ return false;
748
+ }
749
+ const feeLine = transactionLine;
750
+ return feeLine.feeType === scp_types_commerce_transaction_1.FeeType.Shipping && !!feeLine.orderReferenceId;
751
+ }
752
+ exports.isShippingFeeRefundLine = isShippingFeeRefundLine;
745
753
  function isDeliveryFeeLine(transactionLine) {
746
754
  return isTransactionFeeLine(transactionLine) && transactionLine.feeType === scp_types_commerce_transaction_1.FeeType.Delivery;
747
755
  }
@@ -111,3 +111,4 @@ export * from "./IReceipt";
111
111
  export * from "./storeGoals/";
112
112
  export * from "./IStoreItemSummary";
113
113
  export * from "./PaymentFunctionSession";
114
+ export * from "./OrderHandlingSession";
@@ -95,4 +95,5 @@ __export(require("./taxRecord/"));
95
95
  __export(require("./taxLottery/"));
96
96
  __export(require("./lottery/"));
97
97
  __export(require("./PaymentFunctionSession"));
98
+ __export(require("./OrderHandlingSession"));
98
99
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,20 @@
1
+ import { Money } from "@aptos-scp/scp-component-business-core";
2
+ import { AmountModifier } from "@aptos-scp/scp-types-orders";
3
+ /**
4
+ * Calculates the total amount previously refunded from a fee's amountModifiers.
5
+ * Only counts modifiers with "Subtract" action code AND a known refund code
6
+ * (SSARefund, NonSSAShippingAppeasement) to avoid counting other types of subtractions.
7
+ *
8
+ * @param amountModifiers - The array of amount modifiers from the order fee
9
+ * @param currency - The currency code for creating Money objects
10
+ * @returns The total previously refunded amount as a Money object
11
+ */
12
+ export declare function calculatePreviouslyRefundedAmount(amountModifiers: AmountModifier[] | undefined, currency: string): Money;
13
+ /**
14
+ * Calculates the refundable amount remaining after subtracting previously refunded amounts.
15
+ *
16
+ * @param originalAmount - The original fee amount
17
+ * @param previouslyRefundedAmount - The amount already refunded
18
+ * @returns The remaining refundable amount as a Money object
19
+ */
20
+ export declare function calculateRefundableAmount(originalAmount: Money, previouslyRefundedAmount: Money): Money;
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const scp_component_business_core_1 = require("@aptos-scp/scp-component-business-core");
4
+ /**
5
+ * Known refund codes that identify legitimate fee refunds/credits.
6
+ * - SSARefund: Refunds generated through Store Selling App return flow
7
+ * - NonSSAShippingAppeasement: Shipping fee credits/appeasements from external OMS
8
+ */
9
+ const KNOWN_REFUND_CODES = ["SSARefund", "NonSSAShippingAppeasement"];
10
+ /**
11
+ * Checks if an AmountModifier represents a known refund/credit operation.
12
+ * Checks controlledOperation.reason.code first (more universal across OMS implementations),
13
+ * then falls back to amountModificationRule.name.
14
+ *
15
+ * @param modifier - The amount modifier to check
16
+ * @returns true if the modifier has a known refund code
17
+ */
18
+ function isKnownRefundModifier(modifier) {
19
+ var _a, _b, _c;
20
+ // Primary: Check controlledOperation.reason.code (more universal across OMS implementations)
21
+ const reasonCode = (_b = (_a = modifier.controlledOperation) === null || _a === void 0 ? void 0 : _a.reason) === null || _b === void 0 ? void 0 : _b.code;
22
+ if (reasonCode && KNOWN_REFUND_CODES.includes(reasonCode)) {
23
+ return true;
24
+ }
25
+ // Fallback: Check amountModificationRule.name
26
+ const ruleName = (_c = modifier.amountModificationRule) === null || _c === void 0 ? void 0 : _c.name;
27
+ if (ruleName && KNOWN_REFUND_CODES.includes(ruleName)) {
28
+ return true;
29
+ }
30
+ return false;
31
+ }
32
+ /**
33
+ * Calculates the total amount previously refunded from a fee's amountModifiers.
34
+ * Only counts modifiers with "Subtract" action code AND a known refund code
35
+ * (SSARefund, NonSSAShippingAppeasement) to avoid counting other types of subtractions.
36
+ *
37
+ * @param amountModifiers - The array of amount modifiers from the order fee
38
+ * @param currency - The currency code for creating Money objects
39
+ * @returns The total previously refunded amount as a Money object
40
+ */
41
+ function calculatePreviouslyRefundedAmount(amountModifiers, currency) {
42
+ if (!amountModifiers || amountModifiers.length === 0) {
43
+ return new scp_component_business_core_1.Money("0", currency);
44
+ }
45
+ return amountModifiers
46
+ .filter((modifier) => modifier.actionCode === "Subtract" && isKnownRefundModifier(modifier))
47
+ .reduce((total, modifier) => {
48
+ return total.plus(scp_component_business_core_1.Money.fromIMoney(modifier.amount));
49
+ }, new scp_component_business_core_1.Money("0", currency));
50
+ }
51
+ exports.calculatePreviouslyRefundedAmount = calculatePreviouslyRefundedAmount;
52
+ /**
53
+ * Calculates the refundable amount remaining after subtracting previously refunded amounts.
54
+ *
55
+ * @param originalAmount - The original fee amount
56
+ * @param previouslyRefundedAmount - The amount already refunded
57
+ * @returns The remaining refundable amount as a Money object
58
+ */
59
+ function calculateRefundableAmount(originalAmount, previouslyRefundedAmount) {
60
+ return originalAmount.minus(previouslyRefundedAmount);
61
+ }
62
+ exports.calculateRefundableAmount = calculateRefundableAmount;
63
+ //# sourceMappingURL=feeRefundUtils.js.map
@@ -1,3 +1,5 @@
1
1
  export * from "./utils";
2
2
  export * from "./orderUtils";
3
+ export * from "./orderFeeUtils";
3
4
  export * from "./itemImageUtils";
5
+ export * from "./feeRefundUtils";
@@ -5,5 +5,7 @@ function __export(m) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  __export(require("./utils"));
7
7
  __export(require("./orderUtils"));
8
+ __export(require("./orderFeeUtils"));
8
9
  __export(require("./itemImageUtils"));
10
+ __export(require("./feeRefundUtils"));
9
11
  //# sourceMappingURL=index.js.map