b23-lib 3.0.10 → 3.1.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.
- package/dist/Auth/index.js +1 -1
- package/dist/Auth/index.js.map +1 -1
- package/dist/Auth/index.mjs +1 -1
- package/dist/Classes/Address.d.mts +1 -1
- package/dist/Classes/Address.d.ts +1 -1
- package/dist/Classes/Base.d.mts +1 -1
- package/dist/Classes/Base.d.ts +1 -1
- package/dist/Classes/Cart.d.mts +1 -1
- package/dist/Classes/Cart.d.ts +1 -1
- package/dist/Classes/Cart.js +1 -1
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Cart.mjs.map +1 -1
- package/dist/Classes/Charge.d.mts +61 -51
- package/dist/Classes/Charge.d.ts +61 -51
- package/dist/Classes/Charge.js +1 -1
- package/dist/Classes/Charge.js.map +1 -1
- package/dist/Classes/Charge.mjs +1 -1
- package/dist/Classes/Common.d.mts +1 -1
- package/dist/Classes/Common.d.ts +1 -1
- package/dist/Classes/Coupon.d.mts +1 -1
- package/dist/Classes/Coupon.d.ts +1 -1
- package/dist/Classes/Coupon.js +1 -1
- package/dist/Classes/Coupon.js.map +1 -1
- package/dist/Classes/Coupon.mjs +1 -1
- package/dist/Classes/Customer.d.mts +1 -1
- package/dist/Classes/Customer.d.ts +1 -1
- package/dist/Classes/CustomerAddress.d.mts +1 -1
- package/dist/Classes/CustomerAddress.d.ts +1 -1
- package/dist/Classes/Enum.d.mts +1 -5
- package/dist/Classes/Enum.d.ts +1 -5
- package/dist/Classes/Enum.js +1 -1
- package/dist/Classes/Enum.js.map +1 -1
- package/dist/Classes/Enum.mjs +1 -1
- package/dist/Classes/Error.d.mts +4 -1
- package/dist/Classes/Error.d.ts +4 -1
- package/dist/Classes/Error.js +1 -1
- package/dist/Classes/Error.js.map +1 -1
- package/dist/Classes/Error.mjs +1 -1
- package/dist/Classes/ImageInfo.js +1 -1
- package/dist/Classes/ImageInfo.js.map +1 -1
- package/dist/Classes/ImageInfo.mjs +1 -1
- package/dist/Classes/Inventory.d.mts +1 -1
- package/dist/Classes/Inventory.d.ts +1 -1
- package/dist/Classes/Inventory.js +1 -1
- package/dist/Classes/Inventory.js.map +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/LineItem.d.mts +9 -9
- package/dist/Classes/LineItem.d.ts +9 -9
- package/dist/Classes/LineItem.js +1 -1
- package/dist/Classes/LineItem.js.map +1 -1
- package/dist/Classes/LineItem.mjs +1 -1
- package/dist/Classes/Order.d.mts +1 -1
- package/dist/Classes/Order.d.ts +1 -1
- package/dist/Classes/Order.js +1 -1
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/Payment.d.mts +1 -1
- package/dist/Classes/Payment.d.ts +1 -1
- package/dist/Classes/Price.d.mts +1 -1
- package/dist/Classes/Price.d.ts +1 -1
- package/dist/Classes/Price.js +1 -1
- package/dist/Classes/Price.js.map +1 -1
- package/dist/Classes/Price.mjs +1 -1
- package/dist/Classes/Product.d.mts +1 -1
- package/dist/Classes/Product.d.ts +1 -1
- package/dist/Classes/Product.js +1 -1
- package/dist/Classes/Product.js.map +1 -1
- package/dist/Classes/Product.mjs +1 -1
- package/dist/Classes/ShoppingContainer.d.mts +44 -40
- package/dist/Classes/ShoppingContainer.d.ts +44 -40
- package/dist/Classes/ShoppingContainer.js +1 -1
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/Classes/TaxRule.d.mts +35 -74
- package/dist/Classes/TaxRule.d.ts +35 -74
- package/dist/Classes/TaxRule.js +1 -1
- package/dist/Classes/TaxRule.js.map +1 -1
- package/dist/Classes/TaxRule.mjs +1 -1
- package/dist/Classes/TieredPrice.d.mts +1 -1
- package/dist/Classes/TieredPrice.d.ts +1 -1
- package/dist/Classes/TieredPrice.js +1 -1
- package/dist/Classes/TieredPrice.js.map +1 -1
- package/dist/Classes/TieredPrice.mjs +1 -1
- package/dist/{Common-XM4zQpWC.d.mts → Common-C4Fl1Axr.d.mts} +7 -0
- package/dist/{Common-uAn7Sunn.d.ts → Common-Cq0_dPyJ.d.ts} +7 -0
- package/dist/{chunk-OAE2FJFJ.mjs → chunk-2TK2CILF.mjs} +2 -2
- package/dist/{chunk-OAE2FJFJ.mjs.map → chunk-2TK2CILF.mjs.map} +1 -1
- package/dist/chunk-3UMWQ7S7.mjs +2 -0
- package/dist/chunk-3UMWQ7S7.mjs.map +1 -0
- package/dist/{chunk-QLYPJDDV.mjs → chunk-JZC4DEOP.mjs} +2 -2
- package/dist/{chunk-QLYPJDDV.mjs.map → chunk-JZC4DEOP.mjs.map} +1 -1
- package/dist/chunk-LNDZ2K5E.mjs +2 -0
- package/dist/chunk-LNDZ2K5E.mjs.map +1 -0
- package/dist/chunk-MIH2OONR.mjs +2 -0
- package/dist/chunk-MIH2OONR.mjs.map +1 -0
- package/dist/chunk-QK4XJ3GB.mjs +2 -0
- package/dist/chunk-QK4XJ3GB.mjs.map +1 -0
- package/dist/{chunk-XPKK6DFA.mjs → chunk-SJRXYUH2.mjs} +2 -2
- package/dist/chunk-SJRXYUH2.mjs.map +1 -0
- package/dist/chunk-SWE42U5U.mjs +2 -0
- package/dist/chunk-SWE42U5U.mjs.map +1 -0
- package/dist/{chunk-Z3CF4K5C.mjs → chunk-TVTIUN4Z.mjs} +2 -2
- package/dist/{chunk-Z3CF4K5C.mjs.map → chunk-TVTIUN4Z.mjs.map} +1 -1
- package/dist/{chunk-RSTZJZSQ.mjs → chunk-WUIJ47N2.mjs} +2 -2
- package/dist/{chunk-RSTZJZSQ.mjs.map → chunk-WUIJ47N2.mjs.map} +1 -1
- package/dist/chunk-ZY7AI75P.mjs +2 -0
- package/dist/chunk-ZY7AI75P.mjs.map +1 -0
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +8 -5
- package/dist/chunk-3HKY6ZOF.mjs +0 -2
- package/dist/chunk-3HKY6ZOF.mjs.map +0 -1
- package/dist/chunk-4ZFZXWD7.mjs +0 -2
- package/dist/chunk-4ZFZXWD7.mjs.map +0 -1
- package/dist/chunk-EHYGWYD7.mjs +0 -2
- package/dist/chunk-EHYGWYD7.mjs.map +0 -1
- package/dist/chunk-GFMGTV5E.mjs +0 -2
- package/dist/chunk-GFMGTV5E.mjs.map +0 -1
- package/dist/chunk-JCUHTCOC.mjs +0 -2
- package/dist/chunk-JCUHTCOC.mjs.map +0 -1
- package/dist/chunk-XPKK6DFA.mjs.map +0 -1
- package/dist/chunk-ZZ3B7OGM.mjs +0 -2
- package/dist/chunk-ZZ3B7OGM.mjs.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import BaseModel, { BaseAttributes, BaseData } from './Base.mjs';
|
|
2
2
|
import AddressModel, { AddressData } from './Address.mjs';
|
|
3
3
|
import LineItemModel, { LineItemData } from './LineItem.mjs';
|
|
4
|
-
import { b as PriceData, c as PriceModel, S as ShippingDetails, C as CountryCode, a as CurrencyCode, L as LocaleCode } from '../Common-
|
|
4
|
+
import { b as PriceData, c as PriceModel, S as ShippingDetails, C as CountryCode, a as CurrencyCode, L as LocaleCode } from '../Common-C4Fl1Axr.mjs';
|
|
5
5
|
import CouponModel, { CouponData } from './Coupon.mjs';
|
|
6
6
|
import { TaxSystem } from './Enum.mjs';
|
|
7
7
|
import ChargeModel, { ChargeData } from './Charge.mjs';
|
|
@@ -37,33 +37,35 @@ type ShoppingContainerTaxBreakdownModel = Record<string, TaxSystemBreakdownModel
|
|
|
37
37
|
*/
|
|
38
38
|
type ShoppingContainerTotal = {
|
|
39
39
|
/** Sum of all line item prices before any discounts or taxes */
|
|
40
|
-
|
|
40
|
+
lineItemSubtotal: PriceData;
|
|
41
41
|
/** Total item subtotal after item-level discounts have been applied (taxable base for items) */
|
|
42
|
-
|
|
42
|
+
netLineItemSubtotal: PriceData;
|
|
43
43
|
/** Total tax collected specifically from line items */
|
|
44
44
|
lineItemTaxTotal: PriceData;
|
|
45
45
|
/** Granular tax breakdown for all line items */
|
|
46
46
|
lineItemTaxBreakdown: Record<string, TaxSystemBreakdown>;
|
|
47
|
-
/** Sum of
|
|
48
|
-
|
|
49
|
-
/** Sum of
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
|
|
47
|
+
/** Sum of pre-discount chargeAmount for additive charges (tax-inclusive) */
|
|
48
|
+
additiveCharges: PriceData;
|
|
49
|
+
/** Sum of post-discount netChargeAmount for additive charges – final payable (tax-inclusive) */
|
|
50
|
+
netAdditiveCharges: PriceData;
|
|
51
|
+
/** Tax reverse-calculated from additive charges only */
|
|
52
|
+
additiveChargesTaxTotal: PriceData;
|
|
53
|
+
/** Granular tax breakdown from additive charges */
|
|
54
|
+
additiveChargesTaxBreakdown: Record<string, TaxSystemBreakdown>;
|
|
55
|
+
/** Sum of post-discount netChargeAmount for subtractive charges – absolute amount to subtract */
|
|
56
|
+
adjustmentCharges: PriceData;
|
|
57
|
+
/** Pre-discount shipping gross (tax-inclusive, part of additive charges) */
|
|
58
|
+
shippingCharges: PriceData;
|
|
53
59
|
/** Shipping cost after any shipping-specific discounts */
|
|
54
|
-
|
|
55
|
-
/** Total tax collected specifically from charges */
|
|
56
|
-
chargeTaxTotal: PriceData;
|
|
57
|
-
/** Granular tax breakdown for all charges */
|
|
58
|
-
chargeTaxBreakdown: Record<string, TaxSystemBreakdown>;
|
|
60
|
+
netShippingCharges: PriceData;
|
|
59
61
|
/** Combined total tax (lineItemTaxTotal + chargeTaxTotal) */
|
|
60
62
|
taxTotal: PriceData;
|
|
61
63
|
/** Combined granular tax breakdown for the entire container */
|
|
62
64
|
taxBreakdown: Record<string, TaxSystemBreakdown>;
|
|
63
|
-
/** Map of applied coupon codes to their calculated discount amounts */
|
|
64
|
-
discounts: Record<string, PriceData>;
|
|
65
65
|
/** Sum of all coupon discounts applied to the container */
|
|
66
|
-
|
|
66
|
+
discountTotal: PriceData;
|
|
67
|
+
/** Map of applied coupon codes to their calculated discount amounts */
|
|
68
|
+
discountBreakdown: Record<string, PriceData>;
|
|
67
69
|
/** Final total amount to be paid (NetSubtotal + ChargesTotal + TaxTotal - (any remaining discounts)) */
|
|
68
70
|
grandTotal: PriceData;
|
|
69
71
|
};
|
|
@@ -71,20 +73,21 @@ type ShoppingContainerTotal = {
|
|
|
71
73
|
* Internal model version of ShoppingContainerTotal using PriceModel instances.
|
|
72
74
|
*/
|
|
73
75
|
type ShoppingContainerTotalModel = {
|
|
74
|
-
|
|
75
|
-
|
|
76
|
+
lineItemSubtotal: PriceModel;
|
|
77
|
+
netLineItemSubtotal: PriceModel;
|
|
76
78
|
lineItemTaxTotal: PriceModel;
|
|
77
79
|
lineItemTaxBreakdown: Record<string, TaxSystemBreakdownModel>;
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
80
|
+
additiveCharges: PriceModel;
|
|
81
|
+
netAdditiveCharges: PriceModel;
|
|
82
|
+
additiveChargesTaxTotal: PriceModel;
|
|
83
|
+
additiveChargesTaxBreakdown: Record<string, TaxSystemBreakdownModel>;
|
|
84
|
+
adjustmentCharges: PriceModel;
|
|
85
|
+
shippingCharges: PriceModel;
|
|
86
|
+
netShippingCharges: PriceModel;
|
|
84
87
|
taxTotal: PriceModel;
|
|
85
88
|
taxBreakdown: Record<string, TaxSystemBreakdownModel>;
|
|
86
|
-
|
|
87
|
-
|
|
89
|
+
discountTotal: PriceModel;
|
|
90
|
+
discountBreakdown: Record<string, PriceModel>;
|
|
88
91
|
grandTotal: PriceModel;
|
|
89
92
|
};
|
|
90
93
|
type BaseShoppingContainerAttributes = BaseAttributes & {
|
|
@@ -230,8 +233,8 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
|
|
|
230
233
|
* @returns An object containing shipping, subtotal, coupon, and grand totals.
|
|
231
234
|
*/
|
|
232
235
|
getTotal(): {
|
|
233
|
-
|
|
234
|
-
|
|
236
|
+
lineItemSubtotal: PriceModel;
|
|
237
|
+
netLineItemSubtotal: PriceModel;
|
|
235
238
|
lineItemTaxTotal: PriceModel;
|
|
236
239
|
lineItemTaxBreakdown: {
|
|
237
240
|
[k: string]: {
|
|
@@ -242,12 +245,10 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
|
|
|
242
245
|
};
|
|
243
246
|
};
|
|
244
247
|
};
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
chargeTaxTotal: PriceModel;
|
|
250
|
-
chargeTaxBreakdown: {
|
|
248
|
+
additiveCharges: PriceModel;
|
|
249
|
+
netAdditiveCharges: PriceModel;
|
|
250
|
+
additiveChargesTaxTotal: PriceModel;
|
|
251
|
+
additiveChargesTaxBreakdown: {
|
|
251
252
|
[k: string]: {
|
|
252
253
|
system: TaxSystem;
|
|
253
254
|
totalAmount: PriceModel;
|
|
@@ -256,6 +257,13 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
|
|
|
256
257
|
};
|
|
257
258
|
};
|
|
258
259
|
};
|
|
260
|
+
adjustmentCharges: PriceModel;
|
|
261
|
+
shippingCharges: PriceModel;
|
|
262
|
+
netShippingCharges: PriceModel;
|
|
263
|
+
discountBreakdown: {
|
|
264
|
+
[x: string]: PriceModel;
|
|
265
|
+
};
|
|
266
|
+
discountTotal: PriceModel;
|
|
259
267
|
taxTotal: PriceModel;
|
|
260
268
|
taxBreakdown: {
|
|
261
269
|
[k: string]: {
|
|
@@ -266,10 +274,6 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
|
|
|
266
274
|
};
|
|
267
275
|
};
|
|
268
276
|
};
|
|
269
|
-
discounts: {
|
|
270
|
-
[x: string]: PriceModel;
|
|
271
|
-
};
|
|
272
|
-
totalDiscount: PriceModel;
|
|
273
277
|
grandTotal: PriceModel;
|
|
274
278
|
};
|
|
275
279
|
/**
|
|
@@ -300,7 +304,7 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
|
|
|
300
304
|
* @param couponTotal - A record of coupon codes and their calculated discount amounts.
|
|
301
305
|
*/
|
|
302
306
|
private applyDiscountsInLineItem;
|
|
303
|
-
private
|
|
307
|
+
private applyDiscountsInShippingCharges;
|
|
304
308
|
/**
|
|
305
309
|
* Selects and applies the best applicable non-shipping coupon.
|
|
306
310
|
* Currently supports applying only a single coupon of type COUPON.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import BaseModel, { BaseAttributes, BaseData } from './Base.js';
|
|
2
2
|
import AddressModel, { AddressData } from './Address.js';
|
|
3
3
|
import LineItemModel, { LineItemData } from './LineItem.js';
|
|
4
|
-
import { b as PriceData, c as PriceModel, S as ShippingDetails, C as CountryCode, a as CurrencyCode, L as LocaleCode } from '../Common-
|
|
4
|
+
import { b as PriceData, c as PriceModel, S as ShippingDetails, C as CountryCode, a as CurrencyCode, L as LocaleCode } from '../Common-Cq0_dPyJ.js';
|
|
5
5
|
import CouponModel, { CouponData } from './Coupon.js';
|
|
6
6
|
import { TaxSystem } from './Enum.js';
|
|
7
7
|
import ChargeModel, { ChargeData } from './Charge.js';
|
|
@@ -37,33 +37,35 @@ type ShoppingContainerTaxBreakdownModel = Record<string, TaxSystemBreakdownModel
|
|
|
37
37
|
*/
|
|
38
38
|
type ShoppingContainerTotal = {
|
|
39
39
|
/** Sum of all line item prices before any discounts or taxes */
|
|
40
|
-
|
|
40
|
+
lineItemSubtotal: PriceData;
|
|
41
41
|
/** Total item subtotal after item-level discounts have been applied (taxable base for items) */
|
|
42
|
-
|
|
42
|
+
netLineItemSubtotal: PriceData;
|
|
43
43
|
/** Total tax collected specifically from line items */
|
|
44
44
|
lineItemTaxTotal: PriceData;
|
|
45
45
|
/** Granular tax breakdown for all line items */
|
|
46
46
|
lineItemTaxBreakdown: Record<string, TaxSystemBreakdown>;
|
|
47
|
-
/** Sum of
|
|
48
|
-
|
|
49
|
-
/** Sum of
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
|
|
47
|
+
/** Sum of pre-discount chargeAmount for additive charges (tax-inclusive) */
|
|
48
|
+
additiveCharges: PriceData;
|
|
49
|
+
/** Sum of post-discount netChargeAmount for additive charges – final payable (tax-inclusive) */
|
|
50
|
+
netAdditiveCharges: PriceData;
|
|
51
|
+
/** Tax reverse-calculated from additive charges only */
|
|
52
|
+
additiveChargesTaxTotal: PriceData;
|
|
53
|
+
/** Granular tax breakdown from additive charges */
|
|
54
|
+
additiveChargesTaxBreakdown: Record<string, TaxSystemBreakdown>;
|
|
55
|
+
/** Sum of post-discount netChargeAmount for subtractive charges – absolute amount to subtract */
|
|
56
|
+
adjustmentCharges: PriceData;
|
|
57
|
+
/** Pre-discount shipping gross (tax-inclusive, part of additive charges) */
|
|
58
|
+
shippingCharges: PriceData;
|
|
53
59
|
/** Shipping cost after any shipping-specific discounts */
|
|
54
|
-
|
|
55
|
-
/** Total tax collected specifically from charges */
|
|
56
|
-
chargeTaxTotal: PriceData;
|
|
57
|
-
/** Granular tax breakdown for all charges */
|
|
58
|
-
chargeTaxBreakdown: Record<string, TaxSystemBreakdown>;
|
|
60
|
+
netShippingCharges: PriceData;
|
|
59
61
|
/** Combined total tax (lineItemTaxTotal + chargeTaxTotal) */
|
|
60
62
|
taxTotal: PriceData;
|
|
61
63
|
/** Combined granular tax breakdown for the entire container */
|
|
62
64
|
taxBreakdown: Record<string, TaxSystemBreakdown>;
|
|
63
|
-
/** Map of applied coupon codes to their calculated discount amounts */
|
|
64
|
-
discounts: Record<string, PriceData>;
|
|
65
65
|
/** Sum of all coupon discounts applied to the container */
|
|
66
|
-
|
|
66
|
+
discountTotal: PriceData;
|
|
67
|
+
/** Map of applied coupon codes to their calculated discount amounts */
|
|
68
|
+
discountBreakdown: Record<string, PriceData>;
|
|
67
69
|
/** Final total amount to be paid (NetSubtotal + ChargesTotal + TaxTotal - (any remaining discounts)) */
|
|
68
70
|
grandTotal: PriceData;
|
|
69
71
|
};
|
|
@@ -71,20 +73,21 @@ type ShoppingContainerTotal = {
|
|
|
71
73
|
* Internal model version of ShoppingContainerTotal using PriceModel instances.
|
|
72
74
|
*/
|
|
73
75
|
type ShoppingContainerTotalModel = {
|
|
74
|
-
|
|
75
|
-
|
|
76
|
+
lineItemSubtotal: PriceModel;
|
|
77
|
+
netLineItemSubtotal: PriceModel;
|
|
76
78
|
lineItemTaxTotal: PriceModel;
|
|
77
79
|
lineItemTaxBreakdown: Record<string, TaxSystemBreakdownModel>;
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
80
|
+
additiveCharges: PriceModel;
|
|
81
|
+
netAdditiveCharges: PriceModel;
|
|
82
|
+
additiveChargesTaxTotal: PriceModel;
|
|
83
|
+
additiveChargesTaxBreakdown: Record<string, TaxSystemBreakdownModel>;
|
|
84
|
+
adjustmentCharges: PriceModel;
|
|
85
|
+
shippingCharges: PriceModel;
|
|
86
|
+
netShippingCharges: PriceModel;
|
|
84
87
|
taxTotal: PriceModel;
|
|
85
88
|
taxBreakdown: Record<string, TaxSystemBreakdownModel>;
|
|
86
|
-
|
|
87
|
-
|
|
89
|
+
discountTotal: PriceModel;
|
|
90
|
+
discountBreakdown: Record<string, PriceModel>;
|
|
88
91
|
grandTotal: PriceModel;
|
|
89
92
|
};
|
|
90
93
|
type BaseShoppingContainerAttributes = BaseAttributes & {
|
|
@@ -230,8 +233,8 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
|
|
|
230
233
|
* @returns An object containing shipping, subtotal, coupon, and grand totals.
|
|
231
234
|
*/
|
|
232
235
|
getTotal(): {
|
|
233
|
-
|
|
234
|
-
|
|
236
|
+
lineItemSubtotal: PriceModel;
|
|
237
|
+
netLineItemSubtotal: PriceModel;
|
|
235
238
|
lineItemTaxTotal: PriceModel;
|
|
236
239
|
lineItemTaxBreakdown: {
|
|
237
240
|
[k: string]: {
|
|
@@ -242,12 +245,10 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
|
|
|
242
245
|
};
|
|
243
246
|
};
|
|
244
247
|
};
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
chargeTaxTotal: PriceModel;
|
|
250
|
-
chargeTaxBreakdown: {
|
|
248
|
+
additiveCharges: PriceModel;
|
|
249
|
+
netAdditiveCharges: PriceModel;
|
|
250
|
+
additiveChargesTaxTotal: PriceModel;
|
|
251
|
+
additiveChargesTaxBreakdown: {
|
|
251
252
|
[k: string]: {
|
|
252
253
|
system: TaxSystem;
|
|
253
254
|
totalAmount: PriceModel;
|
|
@@ -256,6 +257,13 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
|
|
|
256
257
|
};
|
|
257
258
|
};
|
|
258
259
|
};
|
|
260
|
+
adjustmentCharges: PriceModel;
|
|
261
|
+
shippingCharges: PriceModel;
|
|
262
|
+
netShippingCharges: PriceModel;
|
|
263
|
+
discountBreakdown: {
|
|
264
|
+
[x: string]: PriceModel;
|
|
265
|
+
};
|
|
266
|
+
discountTotal: PriceModel;
|
|
259
267
|
taxTotal: PriceModel;
|
|
260
268
|
taxBreakdown: {
|
|
261
269
|
[k: string]: {
|
|
@@ -266,10 +274,6 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
|
|
|
266
274
|
};
|
|
267
275
|
};
|
|
268
276
|
};
|
|
269
|
-
discounts: {
|
|
270
|
-
[x: string]: PriceModel;
|
|
271
|
-
};
|
|
272
|
-
totalDiscount: PriceModel;
|
|
273
277
|
grandTotal: PriceModel;
|
|
274
278
|
};
|
|
275
279
|
/**
|
|
@@ -300,7 +304,7 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
|
|
|
300
304
|
* @param couponTotal - A record of coupon codes and their calculated discount amounts.
|
|
301
305
|
*/
|
|
302
306
|
private applyDiscountsInLineItem;
|
|
303
|
-
private
|
|
307
|
+
private applyDiscountsInShippingCharges;
|
|
304
308
|
/**
|
|
305
309
|
* Selects and applies the best applicable non-shipping coupon.
|
|
306
310
|
* Currently supports applying only a single coupon of type COUPON.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var Lt=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Lt__default=/*#__PURE__*/_interopDefault(Lt);var ft=s=>structuredClone(s),O=class{customFields;constructor(t,e=new Date){this.customFields={...t.customFields};}getCustomField(t){let e=this.customFields[t];return e==null?e:ft(e)}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return ft(this.customFields)}},D=class extends O{version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){super(t),this.version=t.version??1,this.createdAt=t.createdAt&&!isNaN(Date.parse(t.createdAt))?new Date(t.createdAt).toISOString():e.toISOString(),this.modifiedAt=t.modifiedAt&&!isNaN(Date.parse(t.modifiedAt))?new Date(t.modifiedAt).toISOString():e.toISOString(),this.modifiedBy={...t.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(t,e,i,r){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:r};}};var B=class extends D{id;firstName;lastName;company;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(t,e=new Date){super(t,e),this.id=t.id,this.firstName=t.firstName,this.lastName=t.lastName||"",this.company=t.company||"",this.phone=t.phone,this.email=t.email,this.addressLine1=t.addressLine1,this.addressLine2=t.addressLine2||"",this.city=t.city,this.postalCode=t.postalCode,this.state=t.state,this.country=t.country,this.isBillingAddress=t.isBillingAddress,this.isShippingAddress=t.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),company:this.getCompany(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getCompany(){return this.company}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(t){return t==="shipping"||t==="billing&shipping"}static checkIfBillingAddress(t){return t==="billing"||t==="billing&shipping"}};var Y=new Uint8Array(256),H=Y.length;function pt(){return H>Y.length-16&&(Lt__default.default.randomFillSync(Y),H=0),Y.slice(H,H+=16)}var Pt=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Et(s){return typeof s=="string"&&Pt.test(s)}var It=Et;var x=[];for(let s=0;s<256;++s)x.push((s+256).toString(16).slice(1));function Z(s,t=0){return x[s[t+0]]+x[s[t+1]]+x[s[t+2]]+x[s[t+3]]+"-"+x[s[t+4]]+x[s[t+5]]+"-"+x[s[t+6]]+x[s[t+7]]+"-"+x[s[t+8]]+x[s[t+9]]+"-"+x[s[t+10]]+x[s[t+11]]+x[s[t+12]]+x[s[t+13]]+x[s[t+14]]+x[s[t+15]]}function Rt(s){if(!It(s))throw TypeError("Invalid UUID");let t,e=new Uint8Array(16);return e[0]=(t=parseInt(s.slice(0,8),16))>>>24,e[1]=t>>>16&255,e[2]=t>>>8&255,e[3]=t&255,e[4]=(t=parseInt(s.slice(9,13),16))>>>8,e[5]=t&255,e[6]=(t=parseInt(s.slice(14,18),16))>>>8,e[7]=t&255,e[8]=(t=parseInt(s.slice(19,23),16))>>>8,e[9]=t&255,e[10]=(t=parseInt(s.slice(24,36),16))/1099511627776&255,e[11]=t/4294967296&255,e[12]=t>>>24&255,e[13]=t>>>16&255,e[14]=t>>>8&255,e[15]=t&255,e}var St=Rt;function vt(s){s=unescape(encodeURIComponent(s));let t=[];for(let e=0;e<s.length;++e)t.push(s.charCodeAt(e));return t}var Bt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Nt="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function mt(s,t,e){function i(r,o,a,u){var l;if(typeof r=="string"&&(r=vt(r)),typeof o=="string"&&(o=St(o)),((l=o)===null||l===void 0?void 0:l.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+r.length);if(c.set(o),c.set(r,o.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,a){u=u||0;for(let d=0;d<16;++d)a[u+d]=c[d];return a}return Z(c)}try{i.name=s;}catch{}return i.DNS=Bt,i.URL=Nt,i}var ht={randomUUID:Lt__default.default.randomUUID};function Ot(s,t,e){if(ht.randomUUID&&!t&&!s)return ht.randomUUID();s=s||{};let i=s.random||(s.rng||pt)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){e=e||0;for(let r=0;r<16;++r)t[e+r]=i[r];return t}return Z(i)}var yt=Ot;function Ft(s){return Array.isArray(s)?s=Buffer.from(s):typeof s=="string"&&(s=Buffer.from(s,"utf8")),Lt__default.default.createHash("sha1").update(s).digest()}var Dt=Ft;var zt=mt("v5",80,Dt),bt=zt;var P={"en-IN":"en","kn-IN":"kn"};var At={INR:"\u20B9"},Mt={INR:"en-IN"};var X=(d=>(d.INITIAL="INITIAL",d.PROCESSING="PROCESSING",d.SHIPPED="SHIPPED",d.DELIVERED="DELIVERED",d.CANCELLED="CANCELLED",d.RETURN_REQUESTED="RETURN_REQUESTED",d.RETURNED="RETURNED",d.REFUND_INITIATED="REFUND_INITIATED",d.REFUNDED="REFUNDED",d.ON_HOLD="ON_HOLD",d))(X||{});var J=class extends Error{constructor(t){super(`Invalid line item state: ${t}`),this.name="InvalidLineItemStateError";}},W=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},_=class extends Error{constructor(t){super(`Duplicate selection attribute found: ${t}`),this.name="DuplicateSelectionAttributeError";}},tt=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},et=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},A=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},it=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},rt=class extends Error{constructor(t="Pricing details not available for the product"){super(`NotFound: ${t}`),this.name="PricingNotFoundError";}},k=class extends Error{constructor(t="Tax rule category mismatch."){super(`InvalidTaxRule: ${t}`),this.name="InvalidTaxRuleError";}},st=class extends Error{constructor(t="Tax category is not valid."){super(`InvalidTaxCategory: ${t}`),this.name="InvalidTaxCategoryError";}},ot=class extends Error{constructor(t="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${t}`),this.name="InvalidMinQuantityError";}},nt=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},at=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},ct=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}},lt=class extends Error{constructor(t="No applicable tax slab or multiple slabs found for the given unit price."){super(`TaxSlabNotFound: ${t}`),this.name="TaxSlabNotFoundError";}},G=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},F=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},M=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},I=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},q=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}},N=class extends Error{constructor(t="Invalid charge data."){super(`InvalidCharge: ${t}`),this.name="InvalidChargeError";}};var w=class{sources;alt;order;label;constructor(t){if(this.sources={...t.sources},this.alt=t.alt,this.order=t.order,this.label=t.label,!this.sources.original)throw new q("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(t){return this.sources[t]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(t){this.alt=t;}setOrder(t){this.order=t;}setLabel(t){this.label=t;}setSource(t,e){if(e===void 0){if(t==="original")throw new q("Cannot remove the 'original' image source.");delete this.sources[t];}else this.sources[t]=e;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var n=class s{#t;amount;currency;constructor(t){if(this.#t="PriceModel",t.amount<0)throw new G("Amount cannot be negative.");if(!t.currency)throw new F("Currency code is required.");this.amount=t.amount,this.currency=t.currency;}get kind(){return this.#t}static isPriceModel(t){return typeof t=="object"&&t!==null&&t.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new M("Cannot compare prices in different currencies.")}else throw new I("Must be a PriceModel instance.");return this.amount-t.getAmount()}add(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new M("Cannot add prices in different currencies.")}else throw new I("Must be a PriceModel instance.");return new s({amount:this.amount+t.getAmount(),currency:this.currency})}subtract(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new M("Cannot subtract prices in different currencies.")}else throw new I("Must be a PriceModel instance.");return new s({amount:this.amount-t.getAmount(),currency:this.currency})}multiply(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new M("Cannot multiply prices in different currencies.");return new s({amount:this.amount*t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>=0)return new s({amount:this.amount*t,currency:this.currency});throw new I("Must be a non-negative number.")}divide(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new M("Cannot divide prices in different currencies.");return new s({amount:this.amount/t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>0)return new s({amount:this.amount/t,currency:this.currency});throw new I("Must be a positive number.")}min(...t){if(t.length===0)throw new I("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(s.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new M("Cannot compare prices in different currencies.")}else throw new I("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i},this)}max(...t){if(t.length===0)throw new I("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(s.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new M("Cannot compare prices in different currencies.")}else throw new I("Must be a PriceModel instance.");return e.compareTo(i)>0?e:i},this)}zero(){return new s({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new s({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return s.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return s.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(t,e,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let r=Mt[e];if(!e||!r)throw new F("Invalid currency code for formatting.");let o=t,a=i.displayAsInteger?0:s.getDecimalPlaces(e),u={style:i.style??"currency",currency:e,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(r,u).format(o)}catch(l){return console.error(`Error formatting price for currency "${e}" and locale "${r}":`,l),`${At[e]??e} ${s.addThousandSeparators(o.toFixed(a))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),i=e[0],r=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+r}static getRoundedAmount(t,e){if(t<0)throw new G("Amount cannot be negative for rounding.");if(e===void 0)throw new F("Invalid currency code for rounding.");let i=s.getDecimalPlaces(e),r=Math.pow(10,i);return Math.round(t*r)/r}};var z=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new n(t.baseUnitPrice);if(!t.taxCategory)throw new st;let i=(t.tiers??[]).map(l=>({minQuantity:l.minQuantity,unitPrice:new n(l.unitPrice)})).sort((l,c)=>l.minQuantity-c.minQuantity);if(i.some(l=>l.minQuantity<=0))throw new ot;let o=i.some(l=>l.unitPrice.getCurrency()!==e.getCurrency()),a=i.some((l,c)=>c>0&&l.unitPrice.compareTo(i[c-1].unitPrice)>0),u=i[0]?.unitPrice.compareTo(e)>0;if(o||a||u)throw new nt("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=e,this.taxCategory=t.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice}))}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}}getApplicableTier(t){if(t<=0)throw new at;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity){let i=this.tiers[e];return {minQuantity:i.minQuantity,unitPrice:i.unitPrice}}throw new ct(t)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let t=this.tiers[this.tiers.length-1].unitPrice.getAmount(),e=this.baseUnitPrice.getAmount();return (e-t)/e*100}};var j=class s extends D{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(t){if(typeof t!="object")throw new A("Selection attributes must be an object");return Object.keys(t).filter(i=>t[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>t[i].name?`${i}:c+${t[i].name}`:`${i}:${t[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(t){try{let e={},i=t.split("|");for(let r of i){let[o,a]=r.split(":");a.startsWith("c+")?e[o]={name:a.slice(2)}:e[o]=a;}return e}catch(e){throw new A(e?.message)}}constructor(t,e=new Date){super(t,e),this.id=t.id,this.key=t.key,this.name={...t.name},this.description={...t.description},this.slug={...t.slug},this.brand=t.brand,this.pricing=Object.keys(t.pricing).reduce((r,o)=>(t.pricing[o]&&(r[o]=new z(t.pricing[o])),r),{}),this.targetGender=t.targetGender,this.attributes=g.deepClone(t.attributes),this.specifications=g.deepClone(t.specifications),this.categories=g.deepClone(t.categories);let i=new Set;this.variants=(t.variants||[]).map(r=>{if(!r.selectionAttributes||typeof r.selectionAttributes!="object")throw new A("Selection attributes are required");this.checkSelectionAttributes(r.selectionAttributes);let o=s.generateSelectionAttributesKey(r.selectionAttributes);if(i.has(o))throw new _(o);return i.add(o),{sku:r.sku,selectionAttributes:r.selectionAttributes,images:{primary:new w(r.images.primary),gallery:(r.images.gallery||[]).map(a=>new w(a))}}}),this.isActive=t.isActive,this.searchTags=t.searchTags?g.deepClone(t.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(t){return t?this.name[t]??this.name[P[t]]??this.name.en:g.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[P[t]]??this.description.en:g.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[P[t]]??this.slug.en:g.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:{...this.pricing}}getAttributes(){return g.deepClone(this.attributes)}getVariants(){return this.variants.map(t=>({sku:t.sku,selectionAttributes:g.deepClone(t.selectionAttributes),images:{primary:t.images.primary,gallery:[...t.images.gallery]}}))}getImagesBySelectionAttributes(t){let e=s.generateSelectionAttributesKey(t),i=this.variants.find(r=>s.generateSelectionAttributesKey(r.selectionAttributes)===e);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(t,e){switch(e){case"PRIMARY":return this.getImagesBySelectionAttributes(t)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(t)?.gallery??[];default:return this.getImagesBySelectionAttributes(t)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return g.deepClone(this.categories)}getSpecifications(t){return t?g.deepClone(this.specifications[t]??this.specifications[P[t]]??this.specifications.en):g.deepClone(this.specifications)}getSearchTags(t){return t?g.deepClone(this.searchTags[t]??this.searchTags[P[t]]??this.searchTags.en):g.deepClone(this.searchTags)}getDetails(){let t=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((e,i)=>(this.pricing[i]&&(e[i]=this.pricing[i]?.getDetails()),e),{}),attributes:this.getAttributes(),variants:this.variants.map(e=>({sku:e.sku,selectionAttributes:g.deepClone(e.selectionAttributes),images:{primary:e.images.primary.getDetails(),gallery:e.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...t}}checkSelectionAttributes(t){if(!t||typeof t!="object")throw new A("Selection attributes are required");Object.keys(this.attributes).forEach(e=>{if(e.toLowerCase()==="size")return;let i=this.attributes[e],r=t[e];if(r===void 0)throw new A(`Selection attribute '${e}' is missing`);if(typeof i=="string"){if(typeof r!="string"||i!==r)throw new A(`Selection attribute '${e}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof r!="string"||!i.includes(r))throw new A(`Selection attribute '${e}' is invalid`)}else if(typeof r!="object"||!("name"in r)||i.findIndex(o=>o.name===r.name)<0)throw new A(`Selection attribute '${e}' is invalid`)}});}validateSelectionAttribute(t){let e=s.generateSelectionAttributesKey(t);return this.variants.some(i=>s.generateSelectionAttributesKey(i.selectionAttributes)===e)}validateSize(t){return this.attributes.size.includes(t)}};var jt={isUUID:s=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(s),isEmail:s=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(s),isURL:s=>/^(http|https):\/\/[^ "]+$/.test(s),generateUUID:(s,t)=>t&&s?bt(s,t):yt(),generateSearchId:(s,t)=>`${s}#${j.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:s=>{let[t,e]=s.split("#");return {key:t,selectionAttributes:j.parseSelectionAttributesKey(e)}},deepClone(s){return structuredClone(s)}},g=jt;var ut=class{taxRuleId;taxCategory;taxSystem;taxSubSystem;taxCountry;effectiveFrom;effectiveTo;constructor(t){this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxSubSystem=t.taxSubSystem,this.taxCategory=t.taxCategory,this.taxCountry=t.taxCountry,this.effectiveFrom=new Date(t.effectiveFrom).toISOString(),this.effectiveTo=t.effectiveTo?new Date(t.effectiveTo).toISOString():void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getTaxCountry(){return this.taxCountry}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),taxCountry:this.getTaxCountry(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0}}appliesTo(t,e,i=new Date){return this.taxCategory===t&&this.taxCountry===e&&Date.parse(this.effectiveFrom)<=i.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=i.getTime():!0)}static getTaxRateDisplayString(t,e,i){let r=e*100,o=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,"");return i?.percentageOnly?`${o}%`:t.getTaxSystem()==="GST"?`${t.getTaxSubSystem()} ${o}%`:`${t.getTaxSystem()} ${o}%`}},dt=class s extends ut{slabs;constructor(t){super(t),this.slabs=t.slabs.map(e=>({rate:e.rate,minUnitPrice:new n(e.minUnitPrice),maxUnitPrice:e.maxUnitPrice?new n(e.maxUnitPrice):void 0}));}getSlabs(){return this.slabs.map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice,maxUnitPrice:t.maxUnitPrice}))}getDetails(){return {...super.getDetails(),slabs:this.getSlabs().map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0}))}}getApplicableTaxRate(t){return s.getApplicableTaxRate(t,this.slabs)}calculateTax(t){let e=this.getApplicableTaxRate(t);return t.multiply(e)}static getApplicableTaxRate(t,e){let i=e.filter(r=>(r.minUnitPrice===void 0||t.compareTo(r.minUnitPrice)>=0)&&(r.maxUnitPrice===void 0||t.compareTo(r.maxUnitPrice)<0));if(i.length!==1)throw new lt;return i[0].rate}},gt=class extends ut{rate;constructor(t){super(t),this.rate=t.rate;}getApplicableTaxRate(){return this.rate}calculateTax(t){let e=this.getApplicableTaxRate();return t.multiply(e)}getDetails(){return {...super.getDetails(),rate:this.getApplicableTaxRate()}}};var V=class extends O{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=g.deepClone(t.selectionAttributes),this.name=g.deepClone(t.name),this.specifications=g.deepClone(t.specifications),this.primaryImage=new w(t.primaryImage),this.subItems=g.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new W(i.size);e.add(i.size);}),this.pricing={unitPrice:new n(t.pricing.unitPrice),tierPricing:new z(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(i=>new dt(i))},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,unitPrice:new n(t.total.unitPrice),subtotal:new n(t.total.subtotal),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,r])=>[i,new n(r)])),totalDiscount:new n(t.total.totalDiscount),netUnitPrice:new n(t.total.netUnitPrice),netSubtotal:new n(t.total.netSubtotal),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:new n(r.taxableUnitPrice),taxPerUnit:new n(r.taxPerUnit),amount:new n(r.amount),system:r.system,subSystem:r.subSystem}])),taxTotal:new n(t.total.taxTotal),grandTotal:new n(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return g.deepClone(this.selectionAttributes)}getName(t){return t?g.deepClone(this.name[t]??this.name[P[t]]??this.name.en):g.deepClone(this.name)}getSpecifications(t){return t?g.deepClone(this.specifications[t]??this.specifications[P[t]]??this.specifications.en):g.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return g.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getState(){return this.state}getTotal(){return {quantity:this.total.quantity,unitPrice:this.total.unitPrice,subtotal:this.total.subtotal,discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,e])=>[t,e])),totalDiscount:this.total.totalDiscount,netUnitPrice:this.total.netUnitPrice,netSubtotal:this.total.netSubtotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableUnitPrice:e.taxableUnitPrice,taxPerUnit:e.taxPerUnit,amount:e.amount,system:e.system,subSystem:e.subSystem}])),taxTotal:this.total.taxTotal,grandTotal:this.total.grandTotal}}getDetails(){let t=this.getPricing(),e=this.getTotal();return {id:this.getId(),productKey:this.getProductKey(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:t.unitPrice.getDetails(),tierPricing:t.tierPricing.getDetails(),taxCategory:t.taxCategory,applicableTaxRule:t.applicableTaxRule.map(i=>i.getDetails())},state:this.getState(),total:{quantity:e.quantity,unitPrice:e.unitPrice.getDetails(),subtotal:e.subtotal.getDetails(),discounts:Object.fromEntries(Object.entries(e.discounts).map(([i,r])=>[i,r.getDetails()])),totalDiscount:e.totalDiscount.getDetails(),netUnitPrice:e.netUnitPrice.getDetails(),netSubtotal:e.netSubtotal.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(e.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:r.taxableUnitPrice.getDetails(),taxPerUnit:r.taxPerUnit.getDetails(),amount:r.amount.getDetails(),system:r.system,subSystem:r.subSystem}])),taxTotal:e.taxTotal.getDetails(),grandTotal:e.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(o=>o.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity>0),this.calculateTotals();}updateProductData(t,e,i){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new tt;if(!t.getIsActive())throw new et;this.subItems.forEach(u=>{if(!t.validateSize(u.size))throw new it});let r=t.getPriceDetails(e);if(!r||r.getBaseUnitPrice().getCurrency()!==i)throw new rt;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let o=this.subItems.reduce((u,l)=>u+l.quantity,0),{unitPrice:a}=r.getApplicableTier(o);this.pricing={unitPrice:a,tierPricing:r,taxCategory:r.getTaxCategory(),applicableTaxRule:this.pricing.applicableTaxRule},this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discounts=e,this.calculateTotals();}updateTax(t){t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getTaxCountry()))throw new k}),this.pricing.applicableTaxRule=t,this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((h,b)=>h+b.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,unitPrice:t,subtotal:t,discounts:{},totalDiscount:t,netUnitPrice:t,netSubtotal:t,taxBreakdown:{},taxTotal:t,grandTotal:t};return}let{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),r=i.multiply(e),o=Object.values(this.total.discounts).reduce((h,b)=>h.add(b),t),a=r.subtract(o),u=e>0?a.divide(e):t,l={},c=t;this.pricing.applicableTaxRule.forEach(h=>{let b=h.getApplicableTaxRate(u),L=h.calculateTax(u),E=L.multiply(e).round();l[h.getTaxRuleId()]={rate:b,taxableUnitPrice:u,taxPerUnit:L,amount:E,system:h.getTaxSystem(),subSystem:h.getTaxSubSystem()},c=c.add(E);});let d=a.add(c);this.total={quantity:e,unitPrice:i,subtotal:r,discounts:this.total.discounts,totalDiscount:o,netUnitPrice:u,netSubtotal:a,taxBreakdown:l,taxTotal:c,grandTotal:d};}updateState(t){if(this.state in X)this.state!==t&&(this.state=t);else throw new J(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new w({sources:{original:""}}),this.subItems=[],this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[]},this.total={quantity:0,unitPrice:t,subtotal:t,discounts:{},totalDiscount:t,netUnitPrice:t,netSubtotal:t,taxBreakdown:{},taxTotal:t,grandTotal:t};}};var K=class extends D{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(t,e=new Date){if(super(t,e),this.couponCode=t.couponCode,this.name=g.deepClone(t.name),this.description=g.deepClone(t.description),this.type=t.type,this.customerId=t.customerId,this.validFrom=t.validFrom&&Date.parse(t.validFrom)?new Date(t.validFrom).toISOString():e.toISOString(),this.validTo=t.validTo&&Date.parse(t.validTo)?new Date(t.validTo).toISOString():e.toISOString(),this.minCartValue=Object.keys(t.minCartValue).reduce((i,r)=>{let o=t.minCartValue[r];return o&&(i[r]=new n(o)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,r)=>{let o=t.maxCartDiscount[r];return o&&(i[r]=new n(o)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new I("Percentage value cannot be greater than 100");this.applicableTo=t.applicableTo,this.category=t.category;}getCode(){return this.couponCode}getName(t){return t?this.name[t]??this.name[P[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[P[t]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(t){return t?this.minCartValue[t]:{...this.minCartValue}}getMaxCartDiscount(t){return t?this.maxCartDiscount[t]:{...this.maxCartDiscount}}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:Object.keys(this.getMinCartValue()).reduce((t,e)=>{let i=this.getMinCartValue(e);return i&&(t[e]=i.getDetails()),t},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((t,e)=>{let i=this.getMaxCartDiscount(e);return i&&(t[e]=i.getDetails()),t},{}),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(t){return this.applicableTo==="all"||this.applicableTo==="ftb"&&t}calculateApplicableCouponDiscount(t,e,i,r,o=!0){let a=new n({amount:0,currency:r}),u;if(o&&!this.isActive())return a;let l=this.getMinCartValue(i),c=this.getMaxCartDiscount(i);if(!l||l.compareTo(t)>0||!c)return a;let d=this.getCategory(),h=this.getDiscountMethod(),b=d==="SHIPPING"?e:t;if(b.getAmount()<=0)return a;switch(h){case"flat":let E=c;u=b.min(E);break;case"percentage":u=b.multiply(this.getPercentageValue()/100).round();break;default:return a}return u.min(c)}};var $=class extends O{id;name;category;lineItemId;chargeType;impact;taxTreatment;pricing;total;constructor(t){if(super(t),this.id=t.id,this.name=t.name,this.category=t.category,this.lineItemId=t.lineItemId,this.chargeType=t.chargeType,this.impact=t.impact??"ADD",this.taxTreatment=t.taxTreatment??"APPLY",this.pricing={price:new n(t.pricing.price),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(e=>new gt(e))},this.chargeType!=="ADJUSTMENT"){if(this.impact!=="ADD")throw new N("Only adjustment charges can be subtractive.");if(this.taxTreatment!=="APPLY")throw new N("Non-adjustment charges must apply tax.")}else {if(this.taxTreatment!=="EXEMPT")throw new N("Adjustment charges must be tax exempt.");if(this.pricing.applicableTaxRule.length>0)throw new N("Adjustment charges cannot have tax rules.")}this.total={price:new n(t.total.price),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([e,i])=>[e,new n(i)])),totalDiscount:new n(t.total.totalDiscount),netPrice:new n(t.total.netPrice),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxablePrice:new n(i.taxablePrice),amount:new n(i.amount),system:i.system,subSystem:i.subSystem}])),taxTotal:new n(t.total.taxTotal),grandTotal:new n(t.total.grandTotal)};}getId(){return this.id}getName(t){return t?g.deepClone(this.name[t]??this.name[P[t]]??this.name.en):g.deepClone(this.name)}getCategory(){return this.category}getChargeType(){return this.chargeType}getImpact(){return this.impact}getTaxTreatment(){return this.taxTreatment}getLineItemId(){return this.lineItemId}getPricing(){return {price:this.pricing.price,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {price:this.total.price,discounts:{...this.total.discounts},netPrice:this.total.netPrice,totalDiscount:this.total.totalDiscount,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxablePrice:e.taxablePrice,amount:e.amount,system:e.system,subSystem:e.subSystem}])),taxTotal:this.total.taxTotal,grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(t){if(this.chargeType==="ADJUSTMENT")throw new N("Adjustment charges cannot apply tax rules.");t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getTaxCountry()))throw new k}),this.pricing.applicableTaxRule=t,this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discounts=e,this.calculateTotals();}calculateTotals(){let t=this.pricing.price.zero(),e=this.pricing.price,i=Object.values(this.total.discounts).reduce((C,f)=>C.add(f),t),r=e.subtract(i);if(this.taxTreatment==="EXEMPT"){this.total={price:e,discounts:this.total.discounts,netPrice:r,totalDiscount:i,taxBreakdown:{},taxTotal:t,grandTotal:r};return}let o={},a=this.pricing.applicableTaxRule.reduce((C,f)=>C+f.getApplicableTaxRate(),0),u=r.divide(1+a).round(),l=a>0?r.subtract(u):t,c=t,d=this.pricing.applicableTaxRule.reduce((C,f)=>f.getApplicableTaxRate()>C.getApplicableTaxRate()?f:C),h=d.getTaxRuleId();this.pricing.applicableTaxRule.forEach(C=>{if(C.getTaxRuleId()===h)return;let f=C.getApplicableTaxRate(),U=a>0?l.multiply(f).divide(a).round():t;o[C.getTaxRuleId()]={rate:f,taxablePrice:u,amount:U,system:C.getTaxSystem(),subSystem:C.getTaxSubSystem()},c=c.add(U);});let b=l.subtract(c);o[h]={rate:d.getApplicableTaxRate(),taxablePrice:u,amount:b,system:d.getTaxSystem(),subSystem:d.getTaxSubSystem()};let L=u,E=r;this.total={price:e,discounts:this.total.discounts,netPrice:L,totalDiscount:i,taxBreakdown:o,taxTotal:l,grandTotal:E};}getDetails(){return {id:this.id,name:g.deepClone(this.name),category:this.category,lineItemId:this.lineItemId,chargeType:this.chargeType,impact:this.impact,taxTreatment:this.taxTreatment,pricing:{price:this.pricing.price.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(e=>e.getDetails())},total:{price:this.total.price.getDetails(),discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([e,i])=>[e,i.getDetails()])),totalDiscount:this.total.totalDiscount.getDetails(),netPrice:this.total.netPrice.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxablePrice:i.taxablePrice.getDetails(),amount:i.amount.getDetails(),system:i.system,subSystem:i.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};var Tt=class extends D{id;customerId;customerEmail;anonymousId;lineItems;charges;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,e=new Date){super(t,e),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(i=>new V(i)),this.charges=(t.charges??[]).map(i=>new $(i)),this.billingAddress=t.billingAddress?new B(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new B(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new K(i)),this.shippingDetails=t.shippingDetails?g.deepClone(t.shippingDetails):null,this.total={subtotal:new n(t.total.subtotal),netSubtotal:new n(t.total.netSubtotal),lineItemTaxTotal:new n(t.total.lineItemTaxTotal||{amount:0,currency:t.currency}),lineItemTaxBreakdown:this.mapTaxBreakdown(t.total.lineItemTaxBreakdown||{}),chargesTotal:new n(t.total.chargesTotal||{amount:0,currency:t.currency}),adjustmentChargesTotal:new n(t.total.adjustmentChargesTotal),shippingCharge:new n(t.total.shippingCharge),netShippingCharge:new n(t.total.netShippingCharge),chargeTaxTotal:new n(t.total.chargeTaxTotal||{amount:0,currency:t.currency}),chargeTaxBreakdown:this.mapTaxBreakdown(t.total.chargeTaxBreakdown||{}),taxTotal:new n(t.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(t.total.taxBreakdown),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,r])=>[i,new n(r)])),totalDiscount:new n(t.total.totalDiscount),grandTotal:new n(t.total.grandTotal)};}mapTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,i])=>[e,{system:i.system,totalAmount:new n(i.totalAmount),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,o])=>[r,new n(o)]))}]))}serializeTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,i])=>[e,{system:i.system,totalAmount:i.totalAmount.getDetails(),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,o])=>[r,o.getDetails()]))}]))}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new V(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(t=>new $(t.getDetails()))}addCharge(t){this.charges.push(t),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?g.deepClone(this.shippingDetails):null}getShippingAddress(){return this.shippingAddress?new B(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new B(this.billingAddress.getDetails()):null}getCoupons(){return [...this.coupons]}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {subtotal:this.total.subtotal,netSubtotal:this.total.netSubtotal,lineItemTaxTotal:this.total.lineItemTaxTotal,lineItemTaxBreakdown:Object.fromEntries(Object.entries(this.total.lineItemTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),chargesTotal:this.total.chargesTotal,adjustmentChargesTotal:this.total.adjustmentChargesTotal,shippingCharge:this.total.shippingCharge,netShippingCharge:this.total.netShippingCharge,chargeTaxTotal:this.total.chargeTaxTotal,chargeTaxBreakdown:Object.fromEntries(Object.entries(this.total.chargeTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),discounts:{...this.total.discounts},totalDiscount:this.total.totalDiscount,grandTotal:this.total.grandTotal}}getDetails(){let t=this.getTotal();return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(e=>e.getDetails()),charges:this.getCharges().map(e=>e.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(e=>e.getDetails()),total:{subtotal:t.subtotal.getDetails(),netSubtotal:t.netSubtotal.getDetails(),lineItemTaxTotal:t.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(t.lineItemTaxBreakdown),chargesTotal:t.chargesTotal.getDetails(),adjustmentChargesTotal:t.adjustmentChargesTotal.getDetails(),shippingCharge:t.shippingCharge.getDetails(),netShippingCharge:t.netShippingCharge.getDetails(),chargeTaxTotal:t.chargeTaxTotal.getDetails(),chargeTaxBreakdown:this.serializeTaxBreakdown(t.chargeTaxBreakdown),taxTotal:t.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(t.taxBreakdown),discounts:Object.fromEntries(Object.entries(t.discounts).map(([e,i])=>[e,i.getDetails()])),totalDiscount:t.totalDiscount.getDetails(),grandTotal:t.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new n({amount:0,currency:this.currency}),e=this.lineItems.filter(p=>p.getState()!=="CANCELLED"),i=e.reduce((p,m)=>p.add(m.getTotal().subtotal),t),r=e.reduce((p,m)=>p.add(m.getTotal().netSubtotal),t),o=this.charges.filter(p=>p.getChargeType()==="SHIPPING").reduce((p,m)=>p.add(m.getTotal().price),t),a=t,u={},l={};this.coupons.forEach(p=>{let m=p.calculateApplicableCouponDiscount(i,o,this.country,this.currency);a=a.add(m),u[p.getCode()]=m,p.getCategory()!=="SHIPPING"&&(l[p.getCode()]=m);}),this.applyDiscountsInLineItem(l);let c=this.coupons.find(p=>p.getCategory()==="SHIPPING");c?this.applyDiscuountsInShippingCharges({[c.getCode()]:u[c.getCode()]||t}):this.applyDiscuountsInShippingCharges({});let d=this.charges.filter(p=>p.getImpact()==="ADD").reduce((p,m)=>p.add(m.getTotal().grandTotal),t),h=this.charges.filter(p=>p.getImpact()==="SUBTRACT").reduce((p,m)=>p.add(m.getTotal().grandTotal),t),b=d,L=h,E=this.charges.filter(p=>p.getChargeType()==="SHIPPING").reduce((p,m)=>p.add(m.getTotal().grandTotal),t),C=t,f=t,U=t,S={},xt={},Ct={},Q=(p,m)=>{Object.entries(p).forEach(([Gt,R])=>{let T=R.system,v=R.subSystem;m[T]||(m[T]={system:T,totalAmount:t,subSystems:{}}),m[T].subSystems[v]?m[T].subSystems[v]=m[T].subSystems[v].add(R.amount):m[T].subSystems[v]=R.amount,m[T].totalAmount=m[T].totalAmount.add(R.amount),S[T]||(S[T]={system:T,totalAmount:t,subSystems:{}}),S[T].subSystems[v]?S[T].subSystems[v]=S[T].subSystems[v].add(R.amount):S[T].subSystems[v]=R.amount,S[T].totalAmount=S[T].totalAmount.add(R.amount);});};e.forEach(p=>{let m=p.getTotal().taxBreakdown;m&&(Q(m,xt),Q(m,S),f=f.add(p.getTotal().taxTotal));}),this.charges.forEach(p=>{let m=p.getTotal().taxBreakdown;m&&(Q(m,Ct),Q(m,S),U=U.add(p.getTotal().taxTotal));}),C=f.add(U);let wt=r.add(f).add(b).subtract(L);this.total={subtotal:i,netSubtotal:r,lineItemTaxTotal:f,lineItemTaxBreakdown:xt,chargesTotal:b,adjustmentChargesTotal:L,shippingCharge:o,netShippingCharge:E,chargeTaxTotal:U,chargeTaxBreakdown:Ct,taxTotal:C,taxBreakdown:S,discounts:u,totalDiscount:a,grandTotal:wt};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let e=t.filter(r=>r.getCategory()==="SHIPPING"),i=t.filter(r=>r.getCategory()!=="SHIPPING");this.coupons=[],this.total.totalDiscount=this.total.subtotal.zero(),this.total.discounts={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.discounts),e.length&&this.applyShippingCoupons(e),this.calculateTotals();}applyDiscountsInLineItem(t){let e=Array.from(Object.entries(t)).filter(r=>!r[1].isZero()),i=new Map;this.lineItems.forEach(r=>i.set(r.getId(),[])),e.forEach(([r,o])=>{let a=this.coupons.find(c=>c.getCode()===r);if(!a||o.isZero())return;let u=this.lineItems.filter(c=>c.getState()!=="CANCELLED"&&!c.getTotal().subtotal.isZero()).sort((c,d)=>c.getTotal().subtotal.compareTo(d.getTotal().subtotal)),l=new n({amount:0,currency:this.currency});u.forEach((c,d)=>{let h;d===u.length-1?h=o.subtract(l):h=o.multiply(c.getTotal().subtotal).divide(this.total.subtotal).round(),l=l.add(h),i.get(c.getId())?.push({coupon:a,amount:h});});}),this.lineItems.forEach(r=>{r.getState()==="CANCELLED"||this.total.subtotal.isZero()?r.updateDiscounts([]):r.updateDiscounts(i.get(r.getId())||[]);});}applyDiscuountsInShippingCharges(t){let e=Array.from(Object.entries(t)).filter(o=>!o[1].isZero()),i=this.charges.filter(o=>o.getChargeType()==="SHIPPING"),r=new Map;i.forEach(o=>r.set(o.getId(),[])),e.forEach(([o,a])=>{let u=this.coupons.find(d=>d.getCode()===o);if(!u||a.isZero())return;let l=i.sort((d,h)=>d.getTotal().grandTotal.compareTo(h.getTotal().grandTotal)),c=new n({amount:0,currency:this.currency});l.forEach((d,h)=>{let b;h===l.length-1?b=a.subtract(c):b=a.multiply(d.getTotal().grandTotal).divide(this.total.subtotal).round(),c=c.add(b),r.get(d.getId())?.push({coupon:u,amount:b});});}),i.forEach(o=>{o.updateDiscounts(r.get(o.getId())||[]);});}applyNonShippingCoupons(t){let e=t.filter(i=>i.getType()==="coupon");if(e.length===1){let i=e[0].calculateApplicableCouponDiscount(this.total.subtotal,this.total.shippingCharge,this.country,this.currency);i.getAmount()>0&&(this.coupons.push(e[0]),this.total.discounts[e[0].getCode()]=i,this.total.totalDiscount=i);}}applyShippingCoupons(t){if(this.total.shippingCharge.getAmount()>0&&t.length>0){let e=this.total.subtotal.subtract(this.total.totalDiscount),i=t.reduce((o,a)=>{if(!o)return a;let u=a.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge),l=o.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge);return u===l?a.getType()==="coupon"?a:o:u.compareTo(l)>0?a:o}),r=i.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge);r.getAmount()>0&&(this.coupons.push(i),this.total.discounts[i.getCode()]=r,this.total.totalDiscount=this.total.totalDiscount.add(r),this.total.netShippingCharge=this.total.shippingCharge.subtract(r));}}};module.exports=Tt;//# sourceMappingURL=ShoppingContainer.js.map
|
|
1
|
+
'use strict';var Dt=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Dt__default=/*#__PURE__*/_interopDefault(Dt);var Tt=o=>structuredClone(o),v=class{customFields;constructor(t,e=new Date){this.customFields={...t.customFields};}getCustomField(t){let e=this.customFields[t];return e==null?e:Tt(e)}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return Tt(this.customFields)}},D=class extends v{version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){super(t),this.version=t.version??1,this.createdAt=t.createdAt&&!isNaN(Date.parse(t.createdAt))?new Date(t.createdAt).toISOString():e.toISOString(),this.modifiedAt=t.modifiedAt&&!isNaN(Date.parse(t.modifiedAt))?new Date(t.modifiedAt).toISOString():e.toISOString(),this.modifiedBy={...t.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(t,e,i,r){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:r};}};var N=class extends D{id;firstName;lastName;company;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(t,e=new Date){super(t,e),this.id=t.id,this.firstName=t.firstName,this.lastName=t.lastName||"",this.company=t.company||"",this.phone=t.phone,this.email=t.email,this.addressLine1=t.addressLine1,this.addressLine2=t.addressLine2||"",this.city=t.city,this.postalCode=t.postalCode,this.state=t.state,this.country=t.country,this.isBillingAddress=t.isBillingAddress,this.isShippingAddress=t.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),company:this.getCompany(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getCompany(){return this.company}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(t){return t==="shipping"||t==="billing&shipping"}static checkIfBillingAddress(t){return t==="billing"||t==="billing&shipping"}};var X=new Uint8Array(256),J=X.length;function pt(){return J>X.length-16&&(Dt__default.default.randomFillSync(X),J=0),X.slice(J,J+=16)}var ft=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function wt(o){return typeof o=="string"&&ft.test(o)}var xt=wt;var x=[];for(let o=0;o<256;++o)x.push((o+256).toString(16).slice(1));function W(o,t=0){return x[o[t+0]]+x[o[t+1]]+x[o[t+2]]+x[o[t+3]]+"-"+x[o[t+4]]+x[o[t+5]]+"-"+x[o[t+6]]+x[o[t+7]]+"-"+x[o[t+8]]+x[o[t+9]]+"-"+x[o[t+10]]+x[o[t+11]]+x[o[t+12]]+x[o[t+13]]+x[o[t+14]]+x[o[t+15]]}function Mt(o){if(!xt(o))throw TypeError("Invalid UUID");let t,e=new Uint8Array(16);return e[0]=(t=parseInt(o.slice(0,8),16))>>>24,e[1]=t>>>16&255,e[2]=t>>>8&255,e[3]=t&255,e[4]=(t=parseInt(o.slice(9,13),16))>>>8,e[5]=t&255,e[6]=(t=parseInt(o.slice(14,18),16))>>>8,e[7]=t&255,e[8]=(t=parseInt(o.slice(19,23),16))>>>8,e[9]=t&255,e[10]=(t=parseInt(o.slice(24,36),16))/1099511627776&255,e[11]=t/4294967296&255,e[12]=t>>>24&255,e[13]=t>>>16&255,e[14]=t>>>8&255,e[15]=t&255,e}var It=Mt;function Lt(o){o=unescape(encodeURIComponent(o));let t=[];for(let e=0;e<o.length;++e)t.push(o.charCodeAt(e));return t}var vt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Bt="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function mt(o,t,e){function i(r,n,a,u){var d;if(typeof r=="string"&&(r=Lt(r)),typeof n=="string"&&(n=It(n)),((d=n)===null||d===void 0?void 0:d.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+r.length);if(c.set(n),c.set(r,n.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,a){u=u||0;for(let g=0;g<16;++g)a[u+g]=c[g];return a}return W(c)}try{i.name=o;}catch{}return i.DNS=vt,i.URL=Bt,i}var ht={randomUUID:Dt__default.default.randomUUID};function Rt(o,t,e){if(ht.randomUUID&&!t&&!o)return ht.randomUUID();o=o||{};let i=o.random||(o.rng||pt)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){e=e||0;for(let r=0;r<16;++r)t[e+r]=i[r];return t}return W(i)}var yt=Rt;function Nt(o){return Array.isArray(o)?o=Buffer.from(o):typeof o=="string"&&(o=Buffer.from(o,"utf8")),Dt__default.default.createHash("sha1").update(o).digest()}var At=Nt;var Ut=mt("v5",80,At),bt=Ut;var I={"en-IN":"en","kn-IN":"kn"};var St={INR:"\u20B9"},Pt={INR:"en-IN"};var _=(g=>(g.INITIAL="INITIAL",g.PROCESSING="PROCESSING",g.SHIPPED="SHIPPED",g.DELIVERED="DELIVERED",g.CANCELLED="CANCELLED",g.RETURN_REQUESTED="RETURN_REQUESTED",g.RETURNED="RETURNED",g.REFUND_INITIATED="REFUND_INITIATED",g.REFUNDED="REFUNDED",g.ON_HOLD="ON_HOLD",g))(_||{});var tt=class extends Error{constructor(t){super(`Invalid line item state: ${t}`),this.name="InvalidLineItemStateError";}},et=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},it=class extends Error{constructor(t){super(`Duplicate selection attribute found: ${t}`),this.name="DuplicateSelectionAttributeError";}},rt=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},ot=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},w=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},nt=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},st=class extends Error{constructor(t="Pricing details not available for the product"){super(`NotFound: ${t}`),this.name="PricingNotFoundError";}},O=class extends Error{constructor(t="Tax rule category mismatch."){super(`InvalidTaxRule: ${t}`),this.name="InvalidTaxRuleError";}},at=class extends Error{constructor(t="Tax category is not valid."){super(`InvalidTaxCategory: ${t}`),this.name="InvalidTaxCategoryError";}},ct=class extends Error{constructor(t="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${t}`),this.name="InvalidMinQuantityError";}},lt=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},ut=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},dt=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var K=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},F=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},M=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},A=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},Q=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}},H=class extends Error{constructor(t="Invalid charge data."){super(`InvalidCharge: ${t}`),this.name="InvalidChargeError";}},Z=class extends Error{constructor(t="Invalid charge tax rule."){super(`InvalidChargeTaxRule: ${t}`),this.name="InvalidChargeTaxRuleError";}};var B=class{sources;alt;order;label;constructor(t){if(this.sources={...t.sources},this.alt=t.alt,this.order=t.order,this.label=t.label,!this.sources.original)throw new Q("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(t){return this.sources[t]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(t){this.alt=t;}setOrder(t){this.order=t;}setLabel(t){this.label=t;}setSource(t,e){if(e===void 0){if(t==="original")throw new Q("Cannot remove the 'original' image source.");delete this.sources[t];}else this.sources[t]=e;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var s=class o{#t;amount;currency;constructor(t){if(this.#t="PriceModel",t.amount<0)throw new K("Amount cannot be negative.");if(!t.currency)throw new F("Currency code is required.");this.currency=t.currency,this.amount=parseFloat(t.amount.toFixed(o.getPrecisionPlaces(this.currency)));}get kind(){return this.#t}static isPriceModel(t){return typeof t=="object"&&t!==null&&t.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}getPreciseAmount(t){return parseFloat(t.toFixed(o.getPrecisionPlaces(this.currency)))}compareTo(t){if(o.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new M("Cannot compare prices in different currencies.")}else throw new A("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-t.getAmount())}add(t){if(o.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new M("Cannot add prices in different currencies.")}else throw new A("Must be a PriceModel instance.");return new o({amount:this.getPreciseAmount(this.amount+t.getAmount()),currency:this.currency})}subtract(t){if(o.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new M("Cannot subtract prices in different currencies.")}else throw new A("Must be a PriceModel instance.");return new o({amount:this.getPreciseAmount(this.amount-t.getAmount()),currency:this.currency})}multiply(t){if(o.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new M("Cannot multiply prices in different currencies.");return new o({amount:this.getPreciseAmount(this.amount*t.getAmount()),currency:this.currency})}else if(typeof t=="number"&&t>=0)return new o({amount:this.getPreciseAmount(this.amount*t),currency:this.currency});throw new A("Must be a non-negative number.")}divide(t){if(o.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new M("Cannot divide prices in different currencies.");return new o({amount:this.getPreciseAmount(this.amount/t.getAmount()),currency:this.currency})}else if(typeof t=="number"&&t>0)return new o({amount:this.getPreciseAmount(this.amount/t),currency:this.currency});throw new A("Must be a positive number.")}min(...t){if(t.length===0)throw new A("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(o.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new M("Cannot compare prices in different currencies.")}else throw new A("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i},this)}max(...t){if(t.length===0)throw new A("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(o.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new M("Cannot compare prices in different currencies.")}else throw new A("Must be a PriceModel instance.");return e.compareTo(i)>0?e:i},this)}zero(){return new o({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new o({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return o.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return o.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(t,e,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let r=Pt[e];if(!e||!r)throw new F("Invalid currency code for formatting.");let n=t,a=i.displayAsInteger?0:o.getDecimalPlaces(e),u={style:i.style??"currency",currency:e,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};i.displayAsInteger&&(n=Math.ceil(n));try{return new Intl.NumberFormat(r,u).format(n)}catch(d){return console.error(`Error formatting price for currency "${e}" and locale "${r}":`,d),`${St[e]??e} ${o.addThousandSeparators(n.toFixed(a))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static getPrecisionPlaces(t){switch(t){case"INR":default:return 6}}static addThousandSeparators(t){let e=t.split("."),i=e[0],r=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+r}static getRoundedAmount(t,e){if(t<0)throw new K("Amount cannot be negative for rounding.");if(e===void 0)throw new F("Invalid currency code for rounding.");let i=o.getDecimalPlaces(e),r=Math.pow(10,i);return Math.round(t*r)/r}};var z=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new s(t.baseUnitPrice);if(!t.taxCategory)throw new at;let i=(t.tiers??[]).map(d=>({minQuantity:d.minQuantity,unitPrice:new s(d.unitPrice)})).sort((d,c)=>d.minQuantity-c.minQuantity);if(i.some(d=>d.minQuantity<=0))throw new ct;let n=i.some(d=>d.unitPrice.getCurrency()!==e.getCurrency()),a=i.some((d,c)=>c>0&&d.unitPrice.compareTo(i[c-1].unitPrice)>0),u=i[0]?.unitPrice.compareTo(e)>0;if(n||a||u)throw new lt("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=e,this.taxCategory=t.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice}))}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}}getApplicableTier(t){if(t<=0)throw new ut;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity){let i=this.tiers[e];return {minQuantity:i.minQuantity,unitPrice:i.unitPrice}}throw new dt(t)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let t=this.tiers[this.tiers.length-1].unitPrice.getAmount(),e=this.baseUnitPrice.getAmount();return (e-t)/e*100}};var j=class o extends D{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(t){if(typeof t!="object")throw new w("Selection attributes must be an object");return Object.keys(t).filter(i=>t[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>t[i].name?`${i}:c+${t[i].name}`:`${i}:${t[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(t){try{let e={},i=t.split("|");for(let r of i){let[n,a]=r.split(":");a.startsWith("c+")?e[n]={name:a.slice(2)}:e[n]=a;}return e}catch(e){throw new w(e?.message)}}constructor(t,e=new Date){super(t,e),this.id=t.id,this.key=t.key,this.name={...t.name},this.description={...t.description},this.slug={...t.slug},this.brand=t.brand,this.pricing=Object.keys(t.pricing).reduce((r,n)=>(t.pricing[n]&&(r[n]=new z(t.pricing[n])),r),{}),this.targetGender=t.targetGender,this.attributes=m.deepClone(t.attributes),this.specifications=m.deepClone(t.specifications),this.categories=m.deepClone(t.categories);let i=new Set;this.variants=(t.variants||[]).map(r=>{if(!r.selectionAttributes||typeof r.selectionAttributes!="object")throw new w("Selection attributes are required");this.checkSelectionAttributes(r.selectionAttributes);let n=o.generateSelectionAttributesKey(r.selectionAttributes);if(i.has(n))throw new it(n);return i.add(n),{sku:r.sku,selectionAttributes:r.selectionAttributes,images:{primary:new B(r.images.primary),gallery:(r.images.gallery||[]).map(a=>new B(a))}}}),this.isActive=t.isActive,this.searchTags=t.searchTags?m.deepClone(t.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(t){return t?this.name[t]??this.name[I[t]]??this.name.en:m.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[I[t]]??this.description.en:m.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[I[t]]??this.slug.en:m.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:{...this.pricing}}getAttributes(){return m.deepClone(this.attributes)}getVariants(){return this.variants.map(t=>({sku:t.sku,selectionAttributes:m.deepClone(t.selectionAttributes),images:{primary:t.images.primary,gallery:[...t.images.gallery]}}))}getImagesBySelectionAttributes(t){let e=o.generateSelectionAttributesKey(t),i=this.variants.find(r=>o.generateSelectionAttributesKey(r.selectionAttributes)===e);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(t,e){switch(e){case"PRIMARY":return this.getImagesBySelectionAttributes(t)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(t)?.gallery??[];default:return this.getImagesBySelectionAttributes(t)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return m.deepClone(this.categories)}getSpecifications(t){return t?m.deepClone(this.specifications[t]??this.specifications[I[t]]??this.specifications.en):m.deepClone(this.specifications)}getSearchTags(t){return t?m.deepClone(this.searchTags[t]??this.searchTags[I[t]]??this.searchTags.en):m.deepClone(this.searchTags)}getDetails(){let t=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((e,i)=>(this.pricing[i]&&(e[i]=this.pricing[i]?.getDetails()),e),{}),attributes:this.getAttributes(),variants:this.variants.map(e=>({sku:e.sku,selectionAttributes:m.deepClone(e.selectionAttributes),images:{primary:e.images.primary.getDetails(),gallery:e.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...t}}checkSelectionAttributes(t){if(!t||typeof t!="object")throw new w("Selection attributes are required");Object.keys(this.attributes).forEach(e=>{if(e.toLowerCase()==="size")return;let i=this.attributes[e],r=t[e];if(r===void 0)throw new w(`Selection attribute '${e}' is missing`);if(typeof i=="string"){if(typeof r!="string"||i!==r)throw new w(`Selection attribute '${e}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof r!="string"||!i.includes(r))throw new w(`Selection attribute '${e}' is invalid`)}else if(typeof r!="object"||!("name"in r)||i.findIndex(n=>n.name===r.name)<0)throw new w(`Selection attribute '${e}' is invalid`)}});}validateSelectionAttribute(t){let e=o.generateSelectionAttributesKey(t);return this.variants.some(i=>o.generateSelectionAttributesKey(i.selectionAttributes)===e)}validateSize(t){return this.attributes.size.includes(t)}};var Ot={isUUID:o=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(o),isEmail:o=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(o),isURL:o=>/^(http|https):\/\/[^ "]+$/.test(o),generateUUID:(o,t)=>t&&o?bt(o,t):yt(),generateSearchId:(o,t)=>`${o}#${j.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:o=>{let[t,e]=o.split("#");return {key:t,selectionAttributes:j.parseSelectionAttributesKey(e)}},deepClone(o){return structuredClone(o)}},m=Ot;var V=class extends v{taxRuleId;taxCategory;taxSystem;taxSubSystem;country;rate;minPrice;maxPrice;effectiveFrom;effectiveTo;constructor(t){super(t),this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxSubSystem=t.taxSubSystem,this.taxCategory=t.taxCategory,this.country=t.country,this.rate=t.rate,this.minPrice=new s(t.minPrice),this.maxPrice=t.maxPrice?new s(t.maxPrice):void 0,this.effectiveFrom=new Date(t.effectiveFrom).toISOString(),this.effectiveTo=t.effectiveTo?new Date(t.effectiveTo).toISOString():void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getRate(){return this.rate}getMinPrice(){return this.minPrice}getMaxPrice(){return this.maxPrice}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),rate:this.getRate(),minPrice:this.getMinPrice().getDetails(),maxPrice:this.getMaxPrice()?.getDetails(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0,customFields:this.getAllCustomFields()}}appliesTo(t,e,i,r=new Date){return this.taxCategory===t&&this.country===e&&(i?this.minPrice.compareTo(i)<=0&&(this.maxPrice?this.maxPrice.compareTo(i)>=0:!0):!0)&&Date.parse(this.effectiveFrom)<=r.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=r.getTime():!0)}getApplicableTaxRate(t){return this.appliesTo(this.taxCategory,this.country,t)?this.rate:0}calculateTax(t){return this.appliesTo(this.taxCategory,this.country,t)?t.multiply(this.rate):t.zero()}static getTaxRateDisplayString(t,e,i){let r=e*100,n=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,"");return i?.percentageOnly?`${n}%`:t.getTaxSystem()==="GST"?`${t.getTaxSubSystem()} ${n}%`:`${t.getTaxSystem()} ${n}%`}};var $=class extends v{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=m.deepClone(t.selectionAttributes),this.name=m.deepClone(t.name),this.specifications=m.deepClone(t.specifications),this.primaryImage=new B(t.primaryImage),this.subItems=m.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new et(i.size);e.add(i.size);}),this.pricing={unitPrice:new s(t.pricing.unitPrice),tierPricing:new z(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(i=>new V(i))},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,unitPrice:new s(t.total.unitPrice),subtotal:new s(t.total.subtotal),discountTotal:new s(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([i,r])=>[i,new s(r)])),netUnitPrice:new s(t.total.netUnitPrice),netSubtotal:new s(t.total.netSubtotal),taxTotal:new s(t.total.taxTotal),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:new s(r.taxableUnitPrice),taxPerUnit:new s(r.taxPerUnit),taxAmount:new s(r.taxAmount),system:r.system,subSystem:r.subSystem}])),grandTotal:new s(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return m.deepClone(this.selectionAttributes)}getName(t){return t?m.deepClone(this.name[t]??this.name[I[t]]??this.name.en):m.deepClone(this.name)}getSpecifications(t){return t?m.deepClone(this.specifications[t]??this.specifications[I[t]]??this.specifications.en):m.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return m.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getState(){return this.state}getTotal(){return {quantity:this.total.quantity,unitPrice:this.total.unitPrice,subtotal:this.total.subtotal,discountTotal:this.total.discountTotal,discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([t,e])=>[t,e])),netUnitPrice:this.total.netUnitPrice,netSubtotal:this.total.netSubtotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableUnitPrice:e.taxableUnitPrice,taxPerUnit:e.taxPerUnit,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),grandTotal:this.total.grandTotal}}getDetails(){let t=this.getPricing(),e=this.getTotal();return {id:this.getId(),productKey:this.getProductKey(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:t.unitPrice.getDetails(),tierPricing:t.tierPricing.getDetails(),taxCategory:t.taxCategory,applicableTaxRule:t.applicableTaxRule.map(i=>i.getDetails())},state:this.getState(),total:{quantity:e.quantity,unitPrice:e.unitPrice.getDetails(),subtotal:e.subtotal.getDetails(),discountTotal:e.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(e.discountBreakdown).map(([i,r])=>[i,r.getDetails()])),netUnitPrice:e.netUnitPrice.getDetails(),netSubtotal:e.netSubtotal.getDetails(),taxTotal:e.taxTotal.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(e.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:r.taxableUnitPrice.getDetails(),taxPerUnit:r.taxPerUnit.getDetails(),taxAmount:r.taxAmount.getDetails(),system:r.system,subSystem:r.subSystem}])),grandTotal:e.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(n=>n.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity>0),this.calculateTotals();}updateProductData(t,e,i){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new rt;if(!t.getIsActive())throw new ot;this.subItems.forEach(u=>{if(!t.validateSize(u.size))throw new nt});let r=t.getPriceDetails(e);if(!r||r.getBaseUnitPrice().getCurrency()!==i)throw new st;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let n=this.subItems.reduce((u,d)=>u+d.quantity,0),{unitPrice:a}=r.getApplicableTier(n);this.pricing={unitPrice:a,tierPricing:r,taxCategory:r.getTaxCategory(),applicableTaxRule:this.pricing.applicableTaxRule},this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discountBreakdown=e,this.calculateTotals();}updateTax(t){t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new O}),this.pricing.applicableTaxRule=t,this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((h,C)=>h+C.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,unitPrice:t,subtotal:t,discountTotal:t,discountBreakdown:{},netUnitPrice:t,netSubtotal:t,taxTotal:t,taxBreakdown:{},grandTotal:t};return}let{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),r=i.multiply(e),n=Object.values(this.total.discountBreakdown).reduce((h,C)=>h.add(C),t),a=r.subtract(n),u=e>0?a.divide(e):t,d={},c=t;this.pricing.applicableTaxRule.forEach(h=>{let C=h.getApplicableTaxRate(u),S=h.calculateTax(u),P=S.multiply(e).round();d[h.getTaxRuleId()]={rate:C,taxableUnitPrice:u,taxPerUnit:S,taxAmount:P,system:h.getTaxSystem(),subSystem:h.getTaxSubSystem()},c=c.add(P);});let g=a.add(c);this.total={quantity:e,unitPrice:i,subtotal:r,discountTotal:n,discountBreakdown:this.total.discountBreakdown,netUnitPrice:u,netSubtotal:a,taxTotal:c,taxBreakdown:d,grandTotal:g};}updateState(t){if(this.state in _)this.state!==t&&(this.state=t);else throw new tt(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new B({sources:{original:""}}),this.subItems=[],this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[]},this.total={quantity:0,unitPrice:t,subtotal:t,discountTotal:t,discountBreakdown:{},netUnitPrice:t,netSubtotal:t,taxTotal:t,taxBreakdown:{},grandTotal:t};}};var Y=class extends D{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(t,e=new Date){if(super(t,e),this.couponCode=t.couponCode,this.name=m.deepClone(t.name),this.description=m.deepClone(t.description),this.type=t.type,this.customerId=t.customerId,this.validFrom=t.validFrom&&Date.parse(t.validFrom)?new Date(t.validFrom).toISOString():e.toISOString(),this.validTo=t.validTo&&Date.parse(t.validTo)?new Date(t.validTo).toISOString():e.toISOString(),this.minCartValue=Object.keys(t.minCartValue).reduce((i,r)=>{let n=t.minCartValue[r];return n&&(i[r]=new s(n)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,r)=>{let n=t.maxCartDiscount[r];return n&&(i[r]=new s(n)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new A("Percentage value cannot be greater than 100");this.applicableTo=t.applicableTo,this.category=t.category;}getCode(){return this.couponCode}getName(t){return t?this.name[t]??this.name[I[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[I[t]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(t){return t?this.minCartValue[t]:{...this.minCartValue}}getMaxCartDiscount(t){return t?this.maxCartDiscount[t]:{...this.maxCartDiscount}}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:Object.keys(this.getMinCartValue()).reduce((t,e)=>{let i=this.getMinCartValue(e);return i&&(t[e]=i.getDetails()),t},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((t,e)=>{let i=this.getMaxCartDiscount(e);return i&&(t[e]=i.getDetails()),t},{}),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(t){return this.applicableTo==="all"||this.applicableTo==="ftb"&&t}calculateApplicableCouponDiscount(t,e,i,r,n=!0){let a=new s({amount:0,currency:r}),u;if(n&&!this.isActive())return a;let d=this.getMinCartValue(i),c=this.getMaxCartDiscount(i);if(!d||d.compareTo(t)>0||!c)return a;let g=this.getCategory(),h=this.getDiscountMethod(),C=g==="SHIPPING"?e:t;if(C.getAmount()<=0)return a;switch(h){case"flat":let P=c;u=C.min(P);break;case"percentage":u=C.multiply(this.getPercentageValue()/100).round();break;default:return a}return u.min(c)}};var G=class extends v{id;name;type;category;impact;pricing;lineItemId;total;constructor(t){if(super(t),this.id=t.id,this.name=t.name,this.type=t.type,this.category=t.category,this.impact=t.impact,this.lineItemId=t.lineItemId,this.pricing={chargeAmount:new s(t.pricing.chargeAmount),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(e=>new V(e))},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new H("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={chargeAmount:new s(t.total.chargeAmount),discountTotal:new s(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([e,i])=>[e,new s(i)])),netChargeAmount:new s(t.total.netChargeAmount),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxableAmount:new s(i.taxableAmount),taxAmount:new s(i.taxAmount),system:i.system,subSystem:i.subSystem}])),taxTotal:new s(t.total.taxTotal),grandTotal:new s(t.total.grandTotal)};}getId(){return this.id}getName(t){return t?m.deepClone(this.name[t]??this.name[I[t]]??this.name.en):m.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getPricing(){return {chargeAmount:this.pricing.chargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {chargeAmount:this.total.chargeAmount,discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},netChargeAmount:this.total.netChargeAmount,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableAmount:e.taxableAmount,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(t){if(this.type==="ADJUSTMENT"&&t.length>0)throw new H("Adjustment charges cannot apply tax rules.");t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new O}),this.validateTaxRules(t),this.pricing.applicableTaxRule=t,this.calculateTotals();}validateTaxRules(t){if(this.impact==="SUBTRACT"&&t.some(e=>e.getRate()>0))throw new Z("Subtractive charges cannot have positive tax rates.");for(let e=0;e<t.length;e++)for(let i=e+1;i<t.length;i++){let r=t[e],n=t[i],a=r.getMinPrice(),u=r.getMaxPrice(),d=n.getMinPrice(),c=n.getMaxPrice();if((c?a.compareTo(c)<=0:!0)&&(u?d.compareTo(u)<=0:!0)&&!(a.compareTo(d)===0&&(!u&&!c||u&&c&&u.compareTo(c)===0)))throw new Z(`Overlapping rules found: [${r.getTaxRuleId()}: ${a.getAmount()}-${u?.getAmount()??"\u221E"}] and [${n.getTaxRuleId()}: ${d.getAmount()}-${c?.getAmount()??"\u221E"}]`)}}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discountBreakdown=e,this.calculateTotals();}calculateTotals(){let t=this.pricing.chargeAmount.zero(),e=this.pricing.chargeAmount,i=Object.values(this.total.discountBreakdown).reduce((T,y)=>T.add(y),t),r=e.subtract(i),n={},a=this.pricing.applicableTaxRule.reduce((T,y)=>T+y.getApplicableTaxRate(r),0);if(a<=0){this.total={chargeAmount:e,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:r,taxTotal:t,taxBreakdown:{},grandTotal:r};return}let u=e.getCurrency(),d=e.getAmount(),c=1e3,g=s.getRoundedAmount(d/(1+a),u),h=g,C=Number.POSITIVE_INFINITY;for(let T=0;T<c;T++){let y=new s({amount:g,currency:u}),U=this.pricing.applicableTaxRule.sort((l,p)=>p.getApplicableTaxRate(y)-l.getApplicableTaxRate(y)).map(l=>s.getRoundedAmount(g*l.getApplicableTaxRate(y),u)).reduce((l,p)=>l+p,0),L=g+U-d,gt=this.pricing.applicableTaxRule.reduce((l,p)=>l+p.getApplicableTaxRate(y),0);if(Math.abs(L)<Math.abs(C)&&(C=L,h=g),L===0||(g=g-L/(1+gt),g<0||g>d))break}let S=new s({amount:h,currency:u}),P=t;this.pricing.applicableTaxRule.sort((T,y)=>y.getApplicableTaxRate(S)-T.getApplicableTaxRate(S)).forEach(T=>{let y=T.getApplicableTaxRate(S),q=s.getRoundedAmount(h*y,u),U=new s({amount:q,currency:u});n[T.getTaxRuleId()]={rate:y,taxableAmount:S,taxAmount:U,system:T.getTaxSystem(),subSystem:T.getTaxSubSystem()},P=P.add(U);});let E=e;this.total={chargeAmount:e,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:E,taxBreakdown:n,taxTotal:P,grandTotal:E};}getDetails(){return {id:this.id,name:m.deepClone(this.name),type:this.type,category:this.category,pricing:{chargeAmount:this.pricing.chargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(e=>e.getDetails())},impact:this.impact,lineItemId:this.lineItemId,total:{chargeAmount:this.total.chargeAmount.getDetails(),discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([e,i])=>[e,i.getDetails()])),netChargeAmount:this.total.netChargeAmount.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxableAmount:i.taxableAmount.getDetails(),taxAmount:i.taxAmount.getDetails(),system:i.system,subSystem:i.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};var Ct=class extends D{id;customerId;customerEmail;anonymousId;lineItems;charges;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,e=new Date){super(t,e),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(i=>new $(i)),this.charges=(t.charges??[]).map(i=>new G(i)),this.billingAddress=t.billingAddress?new N(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new N(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new Y(i)),this.shippingDetails=t.shippingDetails?m.deepClone(t.shippingDetails):null,this.total={lineItemSubtotal:new s(t.total.lineItemSubtotal),netLineItemSubtotal:new s(t.total.netLineItemSubtotal),lineItemTaxTotal:new s(t.total.lineItemTaxTotal),lineItemTaxBreakdown:this.mapTaxBreakdown(t.total.lineItemTaxBreakdown),additiveCharges:new s(t.total.additiveCharges),netAdditiveCharges:new s(t.total.netAdditiveCharges),additiveChargesTaxTotal:new s(t.total.additiveChargesTaxTotal),additiveChargesTaxBreakdown:this.mapTaxBreakdown(t.total.additiveChargesTaxBreakdown),adjustmentCharges:new s(t.total.adjustmentCharges),shippingCharges:new s(t.total.shippingCharges),netShippingCharges:new s(t.total.netShippingCharges),discountTotal:new s(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([i,r])=>[i,new s(r)])),taxTotal:new s(t.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(t.total.taxBreakdown),grandTotal:new s(t.total.grandTotal)};}mapTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,i])=>[e,{system:i.system,totalAmount:new s(i.totalAmount),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,n])=>[r,new s(n)]))}]))}serializeTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,i])=>[e,{system:i.system,totalAmount:i.totalAmount.getDetails(),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,n])=>[r,n.getDetails()]))}]))}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new $(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(t=>new G(t.getDetails()))}addCharge(t){this.charges.push(t),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?m.deepClone(this.shippingDetails):null}getShippingAddress(){return this.shippingAddress?new N(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new N(this.billingAddress.getDetails()):null}getCoupons(){return [...this.coupons]}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {lineItemSubtotal:this.total.lineItemSubtotal,netLineItemSubtotal:this.total.netLineItemSubtotal,lineItemTaxTotal:this.total.lineItemTaxTotal,lineItemTaxBreakdown:Object.fromEntries(Object.entries(this.total.lineItemTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),additiveCharges:this.total.additiveCharges,netAdditiveCharges:this.total.netAdditiveCharges,additiveChargesTaxTotal:this.total.additiveChargesTaxTotal,additiveChargesTaxBreakdown:Object.fromEntries(Object.entries(this.total.additiveChargesTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),adjustmentCharges:this.total.adjustmentCharges,shippingCharges:this.total.shippingCharges,netShippingCharges:this.total.netShippingCharges,discountBreakdown:{...this.total.discountBreakdown},discountTotal:this.total.discountTotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),grandTotal:this.total.grandTotal}}getDetails(){let t=this.getTotal();return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(e=>e.getDetails()),charges:this.getCharges().map(e=>e.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(e=>e.getDetails()),total:{lineItemSubtotal:t.lineItemSubtotal.getDetails(),netLineItemSubtotal:t.netLineItemSubtotal.getDetails(),lineItemTaxTotal:t.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(t.lineItemTaxBreakdown),additiveCharges:t.additiveCharges.getDetails(),netAdditiveCharges:t.netAdditiveCharges.getDetails(),additiveChargesTaxTotal:t.additiveChargesTaxTotal.getDetails(),additiveChargesTaxBreakdown:this.serializeTaxBreakdown(t.additiveChargesTaxBreakdown),adjustmentCharges:t.adjustmentCharges.getDetails(),shippingCharges:t.shippingCharges.getDetails(),netShippingCharges:t.netShippingCharges.getDetails(),discountTotal:t.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(t.discountBreakdown).map(([e,i])=>[e,i.getDetails()])),taxTotal:t.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(t.taxBreakdown),grandTotal:t.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new s({amount:0,currency:this.currency}),e=this.lineItems.filter(l=>l.getState()!=="CANCELLED"),i=e.reduce((l,p)=>l.add(p.getTotal().subtotal),t),r=this.charges.filter(l=>l.getType()==="SHIPPING").reduce((l,p)=>l.add(p.getTotal().chargeAmount),t);this.total.lineItemSubtotal=i,this.total.shippingCharges=r;let n=t,a={},u={};this.coupons.forEach(l=>{let p=l.calculateApplicableCouponDiscount(i,r,this.country,this.currency);n=n.add(p),a[l.getCode()]=p,l.getCategory()!=="SHIPPING"&&(u[l.getCode()]=p);}),this.total.discountTotal=n,this.total.discountBreakdown=a,this.applyDiscountsInLineItem(u);let d=this.coupons.find(l=>l.getCategory()==="SHIPPING");d?this.applyDiscountsInShippingCharges({[d.getCode()]:a[d.getCode()]||t}):this.applyDiscountsInShippingCharges({});let c=this.lineItems.reduce((l,p)=>l.add(p.getTotal().netSubtotal),t),g=this.charges.filter(l=>l.getType()==="SHIPPING").reduce((l,p)=>l.add(p.getTotal().grandTotal),t);this.total.netLineItemSubtotal=c,this.total.netShippingCharges=g;let h=this.charges.filter(l=>l.getImpact()==="ADD").reduce((l,p)=>l.add(p.getTotal().chargeAmount),t),C=this.charges.filter(l=>l.getImpact()==="ADD").reduce((l,p)=>l.add(p.getTotal().grandTotal),t),S=this.charges.filter(l=>l.getImpact()==="SUBTRACT").reduce((l,p)=>l.add(p.getTotal().grandTotal),t),P=t,E=t,T=t,y={},q={},U={},L=(l,p)=>{Object.entries(l).forEach(([jt,R])=>{let f=R.system,k=R.subSystem;p[f]||(p[f]={system:f,totalAmount:t,subSystems:{}}),p[f].subSystems[k]?p[f].subSystems[k]=p[f].subSystems[k].add(R.taxAmount):p[f].subSystems[k]=R.taxAmount,p[f].totalAmount=p[f].totalAmount.add(R.taxAmount),y[f]||(y[f]={system:f,totalAmount:t,subSystems:{}}),y[f].subSystems[k]?y[f].subSystems[k]=y[f].subSystems[k].add(R.taxAmount):y[f].subSystems[k]=R.taxAmount,y[f].totalAmount=y[f].totalAmount.add(R.taxAmount);});};e.forEach(l=>{let p=l.getTotal().taxBreakdown;p&&(L(p,q),L(p,y),E=E.add(l.getTotal().taxTotal));}),this.charges.forEach(l=>{let p=l.getTotal().taxBreakdown;p&&(L(p,U),L(p,y),T=T.add(l.getTotal().taxTotal));}),P=E.add(T);let gt=c.add(E).add(C).subtract(S);this.total={lineItemSubtotal:i,netLineItemSubtotal:c,lineItemTaxTotal:E,lineItemTaxBreakdown:q,additiveCharges:h,netAdditiveCharges:C,additiveChargesTaxTotal:T,additiveChargesTaxBreakdown:U,adjustmentCharges:S,shippingCharges:r,netShippingCharges:g,discountTotal:n,discountBreakdown:a,taxTotal:P,taxBreakdown:y,grandTotal:gt};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let e=t.filter(r=>r.getCategory()==="SHIPPING"),i=t.filter(r=>r.getCategory()!=="SHIPPING");this.coupons=[],this.total.discountTotal=this.total.lineItemSubtotal.zero(),this.total.discountBreakdown={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.discountBreakdown),e.length&&this.applyShippingCoupons(e),this.calculateTotals();}applyDiscountsInLineItem(t){let e=Array.from(Object.entries(t)).filter(r=>!r[1].isZero()),i=new Map;this.lineItems.forEach(r=>i.set(r.getId(),[])),e.forEach(([r,n])=>{let a=this.coupons.find(c=>c.getCode()===r);if(!a||n.isZero())return;let u=this.lineItems.filter(c=>c.getState()!=="CANCELLED"&&!c.getTotal().subtotal.isZero()).sort((c,g)=>c.getTotal().subtotal.compareTo(g.getTotal().subtotal)),d=new s({amount:0,currency:this.currency});u.forEach((c,g)=>{let h;g===u.length-1?h=n.subtract(d):h=n.multiply(c.getTotal().subtotal).divide(this.total.lineItemSubtotal).round(),d=d.add(h),i.get(c.getId())?.push({coupon:a,amount:h});});}),this.lineItems.forEach(r=>{r.getState()==="CANCELLED"||this.total.lineItemSubtotal.isZero()?r.updateDiscounts([]):r.updateDiscounts(i.get(r.getId())||[]);});}applyDiscountsInShippingCharges(t){let e=Array.from(Object.entries(t)).filter(n=>!n[1].isZero()),i=this.charges.filter(n=>n.getType()==="SHIPPING"),r=new Map;i.forEach(n=>r.set(n.getId(),[])),e.forEach(([n,a])=>{let u=this.coupons.find(g=>g.getCode()===n);if(!u||a.isZero())return;let d=i.sort((g,h)=>g.getTotal().grandTotal.compareTo(h.getTotal().grandTotal)),c=new s({amount:0,currency:this.currency});d.forEach((g,h)=>{let C;h===d.length-1?C=a.subtract(c):C=a.multiply(g.getTotal().chargeAmount).divide(this.total.shippingCharges).round(),c=c.add(C),r.get(g.getId())?.push({coupon:u,amount:C});});}),i.forEach(n=>{n.updateDiscounts(r.get(n.getId())||[]);});}applyNonShippingCoupons(t){let e=t.filter(i=>i.getType()==="coupon");if(e.length===1){let i=e[0].calculateApplicableCouponDiscount(this.total.lineItemSubtotal,this.total.shippingCharges,this.country,this.currency);i.getAmount()>0&&(this.coupons.push(e[0]),this.total.discountTotal=i,this.total.discountBreakdown[e[0].getCode()]=i);}}applyShippingCoupons(t){if(this.total.shippingCharges.getAmount()>0&&t.length>0){let e=this.total.lineItemSubtotal.subtract(this.total.discountTotal),i=t.reduce((n,a)=>{if(!n)return a;let u=a.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency).min(this.total.shippingCharges),d=n.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency).min(this.total.shippingCharges);return u.compareTo(d)===0?a.getType()==="coupon"?a:n:u.compareTo(d)>0?a:n}),r=i.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency).min(this.total.shippingCharges);r.getAmount()>0&&(this.coupons.push(i),this.total.discountTotal=this.total.discountTotal.add(r),this.total.discountBreakdown[i.getCode()]=r);}}};module.exports=Ct;//# sourceMappingURL=ShoppingContainer.js.map
|
|
2
2
|
//# sourceMappingURL=ShoppingContainer.js.map
|