b23-lib 2.1.7 → 3.0.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.
Files changed (112) hide show
  1. package/dist/Auth/index.js +1 -1
  2. package/dist/Auth/index.js.map +1 -1
  3. package/dist/Auth/index.mjs +1 -1
  4. package/dist/Classes/Cart.d.mts +1 -0
  5. package/dist/Classes/Cart.d.ts +1 -0
  6. package/dist/Classes/Cart.js +1 -2
  7. package/dist/Classes/Cart.js.map +1 -1
  8. package/dist/Classes/Cart.mjs +1 -1
  9. package/dist/Classes/Cart.mjs.map +1 -1
  10. package/dist/Classes/Charge.d.mts +99 -0
  11. package/dist/Classes/Charge.d.ts +99 -0
  12. package/dist/Classes/Charge.js +2 -0
  13. package/dist/Classes/Charge.js.map +1 -0
  14. package/dist/Classes/Charge.mjs +2 -0
  15. package/dist/Classes/Charge.mjs.map +1 -0
  16. package/dist/Classes/Coupon.js +1 -1
  17. package/dist/Classes/Coupon.js.map +1 -1
  18. package/dist/Classes/Coupon.mjs +1 -1
  19. package/dist/Classes/Enum.d.mts +4 -4
  20. package/dist/Classes/Enum.d.ts +4 -4
  21. package/dist/Classes/Enum.js +1 -1
  22. package/dist/Classes/Enum.js.map +1 -1
  23. package/dist/Classes/Enum.mjs +1 -1
  24. package/dist/Classes/Error.d.mts +4 -1
  25. package/dist/Classes/Error.d.ts +4 -1
  26. package/dist/Classes/Error.js +1 -1
  27. package/dist/Classes/Error.js.map +1 -1
  28. package/dist/Classes/Error.mjs +1 -1
  29. package/dist/Classes/ImageInfo.js.map +1 -1
  30. package/dist/Classes/ImageInfo.mjs +1 -1
  31. package/dist/Classes/Inventory.js +1 -1
  32. package/dist/Classes/Inventory.js.map +1 -1
  33. package/dist/Classes/Inventory.mjs +1 -1
  34. package/dist/Classes/LineItem.d.mts +46 -48
  35. package/dist/Classes/LineItem.d.ts +46 -48
  36. package/dist/Classes/LineItem.js +1 -2
  37. package/dist/Classes/LineItem.js.map +1 -1
  38. package/dist/Classes/LineItem.mjs +1 -1
  39. package/dist/Classes/Order.d.mts +1 -1
  40. package/dist/Classes/Order.d.ts +1 -1
  41. package/dist/Classes/Order.js +1 -2
  42. package/dist/Classes/Order.js.map +1 -1
  43. package/dist/Classes/Order.mjs +1 -1
  44. package/dist/Classes/Order.mjs.map +1 -1
  45. package/dist/Classes/Price.js +1 -1
  46. package/dist/Classes/Price.js.map +1 -1
  47. package/dist/Classes/Price.mjs +1 -1
  48. package/dist/Classes/Product.js +1 -1
  49. package/dist/Classes/Product.js.map +1 -1
  50. package/dist/Classes/Product.mjs +1 -1
  51. package/dist/Classes/ShoppingContainer.d.mts +98 -40
  52. package/dist/Classes/ShoppingContainer.d.ts +98 -40
  53. package/dist/Classes/ShoppingContainer.js +1 -2
  54. package/dist/Classes/ShoppingContainer.js.map +1 -1
  55. package/dist/Classes/ShoppingContainer.mjs +1 -1
  56. package/dist/Classes/TaxCategoryModel.d.mts +42 -0
  57. package/dist/Classes/TaxCategoryModel.d.ts +42 -0
  58. package/dist/Classes/TaxCategoryModel.js +2 -0
  59. package/dist/Classes/TaxCategoryModel.js.map +1 -0
  60. package/dist/Classes/TaxCategoryModel.mjs +2 -0
  61. package/dist/Classes/TaxCategoryModel.mjs.map +1 -0
  62. package/dist/Classes/TaxRule.d.mts +59 -79
  63. package/dist/Classes/TaxRule.d.ts +59 -79
  64. package/dist/Classes/TaxRule.js +1 -2
  65. package/dist/Classes/TaxRule.js.map +1 -1
  66. package/dist/Classes/TaxRule.mjs +1 -1
  67. package/dist/Classes/TieredPrice.d.mts +4 -4
  68. package/dist/Classes/TieredPrice.d.ts +4 -4
  69. package/dist/Classes/TieredPrice.js +1 -1
  70. package/dist/Classes/TieredPrice.js.map +1 -1
  71. package/dist/Classes/TieredPrice.mjs +1 -1
  72. package/dist/{chunk-TJ7AZBND.mjs → chunk-6X5O25W5.mjs} +2 -2
  73. package/dist/chunk-6X5O25W5.mjs.map +1 -0
  74. package/dist/chunk-FC4P26U3.mjs +2 -0
  75. package/dist/chunk-FC4P26U3.mjs.map +1 -0
  76. package/dist/chunk-IIPG3DTO.mjs +2 -0
  77. package/dist/chunk-IIPG3DTO.mjs.map +1 -0
  78. package/dist/{chunk-AWZ6KRLF.mjs → chunk-JE7BAYI5.mjs} +2 -2
  79. package/dist/{chunk-AWZ6KRLF.mjs.map → chunk-JE7BAYI5.mjs.map} +1 -1
  80. package/dist/chunk-KKQLCW6A.mjs +2 -0
  81. package/dist/chunk-KKQLCW6A.mjs.map +1 -0
  82. package/dist/chunk-PTIPDRB4.mjs +2 -0
  83. package/dist/chunk-PTIPDRB4.mjs.map +1 -0
  84. package/dist/{chunk-WS7ZY5ZZ.mjs → chunk-RSMXGZD4.mjs} +2 -2
  85. package/dist/{chunk-WS7ZY5ZZ.mjs.map → chunk-RSMXGZD4.mjs.map} +1 -1
  86. package/dist/{chunk-WSUPVXRZ.mjs → chunk-RSTZJZSQ.mjs} +2 -2
  87. package/dist/{chunk-WSUPVXRZ.mjs.map → chunk-RSTZJZSQ.mjs.map} +1 -1
  88. package/dist/chunk-U7DES3CI.mjs +2 -0
  89. package/dist/chunk-U7DES3CI.mjs.map +1 -0
  90. package/dist/{chunk-JHELVQYY.mjs → chunk-XPKK6DFA.mjs} +2 -2
  91. package/dist/chunk-XPKK6DFA.mjs.map +1 -0
  92. package/dist/chunk-XXETAAL4.mjs +2 -0
  93. package/dist/chunk-XXETAAL4.mjs.map +1 -0
  94. package/dist/index.d.mts +1 -5
  95. package/dist/index.d.ts +1 -5
  96. package/dist/index.js +2 -2
  97. package/dist/index.js.map +1 -1
  98. package/dist/index.mjs +2 -2
  99. package/dist/index.mjs.map +1 -1
  100. package/package.json +11 -1
  101. package/dist/chunk-232FJYNB.mjs +0 -2
  102. package/dist/chunk-232FJYNB.mjs.map +0 -1
  103. package/dist/chunk-72DR3HF2.mjs +0 -2
  104. package/dist/chunk-72DR3HF2.mjs.map +0 -1
  105. package/dist/chunk-ARMBZF3E.mjs +0 -3
  106. package/dist/chunk-ARMBZF3E.mjs.map +0 -1
  107. package/dist/chunk-JHELVQYY.mjs.map +0 -1
  108. package/dist/chunk-SFUOYZ3L.mjs +0 -2
  109. package/dist/chunk-SFUOYZ3L.mjs.map +0 -1
  110. package/dist/chunk-TJ7AZBND.mjs.map +0 -1
  111. package/dist/chunk-ZE7D77FR.mjs +0 -2
  112. package/dist/chunk-ZE7D77FR.mjs.map +0 -1
@@ -1,41 +1,96 @@
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 { P as PriceData, S as ShippingDetails, C as CountryCode, a as CurrencyCode, L as LocaleCode, b as PriceModel } from '../Common-Bd8Xv8x4.mjs';
4
+ import { P as PriceData, b as PriceModel, S as ShippingDetails, C as CountryCode, a as CurrencyCode, L as LocaleCode } from '../Common-Bd8Xv8x4.mjs';
5
5
  import CouponModel, { CouponData } from './Coupon.mjs';
6
- import { TaxCategory } from './Enum.mjs';
7
- import { TaxRuleModel } from './TaxRule.mjs';
6
+ import { TaxSystem } from './Enum.mjs';
7
+ import { TaxRuleModel, FixedTaxRuleModel } from './TaxRule.mjs';
8
+ import ChargeModel, { ChargeData } from './Charge.mjs';
8
9
  import '../Auth/index.mjs';
9
10
  import './ImageInfo.mjs';
10
11
  import './Product.mjs';
11
12
  import './TieredPrice.mjs';
12
13
 
14
+ /**
15
+ * Breakdown of a specific tax system (e.g., GST, VAT) for the entire container.
16
+ * Groups taxes by system and then by specific rule/subsystem.
17
+ */
18
+ type TaxSystemBreakdown = {
19
+ /** Name of the tax system (e.g., GST) */
20
+ system: TaxSystem;
21
+ /** Total tax amount collected for this system across all line items and charges */
22
+ totalAmount: PriceData;
23
+ /** Detailed breakdown by rule/subsystem to total tax amount (e.g., CGST, SGST) */
24
+ subSystems: Record<string, PriceData>;
25
+ };
26
+ /**
27
+ * Internal model for tax system breakdown using PriceModel instances.
28
+ */
29
+ type TaxSystemBreakdownModel = {
30
+ system: TaxSystem;
31
+ totalAmount: PriceModel;
32
+ subSystems: Record<string, PriceModel>;
33
+ };
34
+ type ShoppingContainerTaxBreakdownModel = Record<string, TaxSystemBreakdownModel>;
35
+ /**
36
+ * Comprehensive totals for a shopping container, logically grouped by source.
37
+ */
13
38
  type ShoppingContainerTotal = {
14
- /** Sum of item prices before discounts & tax */
39
+ /** Sum of all line item prices before any discounts or taxes */
15
40
  subtotal: PriceData;
16
- /** Original shipping cost before coupons / promotions */
17
- shipping: PriceData;
18
- /** Shipping after coupons / promotions (>= 0) */
19
- effectiveShipping: PriceData;
20
- /** Total tax amount (all tax rules combined) */
41
+ /** Total item subtotal after item-level discounts have been applied (taxable base for items) */
42
+ netSubtotal: PriceData;
43
+ /** Total tax collected specifically from line items */
44
+ lineItemTaxTotal: PriceData;
45
+ /** Granular tax breakdown for all line items */
46
+ lineItemTaxBreakdown: Record<string, TaxSystemBreakdown>;
47
+ /** Sum of all extra charges (shipping, processing, etc.) before tax */
48
+ chargesTotal: PriceData;
49
+ /** Specifically the shipping portion of charges */
50
+ shippingCharge: PriceData;
51
+ /** Shipping cost after any shipping-specific discounts */
52
+ netShippingCharge: PriceData;
53
+ /** Total tax collected specifically from charges */
54
+ chargeTaxTotal: PriceData;
55
+ /** Granular tax breakdown for all charges */
56
+ chargeTaxBreakdown: Record<string, TaxSystemBreakdown>;
57
+ /** Combined total tax (lineItemTaxTotal + chargeTaxTotal) */
21
58
  taxTotal: PriceData;
22
- /**
23
- * Coupon discounts applied
24
- * key = couponCode (or couponId)
25
- * value = discount amount (positive number)
26
- */
27
- couponTotal: Record<string, PriceData>;
28
- /** Total discount from coupons (derived, optional to store) */
29
- couponDiscountTotal: PriceData;
30
- /** Final payable amount */
59
+ /** Combined granular tax breakdown for the entire container */
60
+ taxBreakdown: Record<string, TaxSystemBreakdown>;
61
+ /** Map of applied coupon codes to their calculated discount amounts */
62
+ discounts: Record<string, PriceData>;
63
+ /** Sum of all coupon discounts applied to the container */
64
+ totalDiscount: PriceData;
65
+ /** Final total amount to be paid (NetSubtotal + ChargesTotal + TaxTotal - (any remaining discounts)) */
31
66
  grandTotal: PriceData;
32
67
  };
68
+ /**
69
+ * Internal model version of ShoppingContainerTotal using PriceModel instances.
70
+ */
71
+ type ShoppingContainerTotalModel = {
72
+ subtotal: PriceModel;
73
+ netSubtotal: PriceModel;
74
+ lineItemTaxTotal: PriceModel;
75
+ lineItemTaxBreakdown: Record<string, TaxSystemBreakdownModel>;
76
+ chargesTotal: PriceModel;
77
+ shippingCharge: PriceModel;
78
+ netShippingCharge: PriceModel;
79
+ chargeTaxTotal: PriceModel;
80
+ chargeTaxBreakdown: Record<string, TaxSystemBreakdownModel>;
81
+ taxTotal: PriceModel;
82
+ taxBreakdown: Record<string, TaxSystemBreakdownModel>;
83
+ discounts: Record<string, PriceModel>;
84
+ totalDiscount: PriceModel;
85
+ grandTotal: PriceModel;
86
+ };
33
87
  type BaseShoppingContainerAttributes = BaseAttributes & {
34
88
  id: string;
35
89
  customerId?: string;
36
90
  customerEmail?: string;
37
91
  anonymousId?: string;
38
92
  lineItems: LineItemData[];
93
+ charges: ChargeData[];
39
94
  shippingDetails: ShippingDetails | null;
40
95
  shippingAddress?: AddressData | null;
41
96
  billingAddress?: AddressData | null;
@@ -56,19 +111,12 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
56
111
  protected customerEmail?: string;
57
112
  protected anonymousId?: string;
58
113
  protected lineItems: LineItemModel[];
114
+ protected charges: ChargeModel[];
59
115
  protected shippingDetails: ShippingDetails | null;
60
116
  protected shippingAddress: AddressModel | null;
61
117
  protected billingAddress: AddressModel | null;
62
118
  protected coupons: CouponModel[];
63
- protected total: {
64
- subtotal: PriceModel;
65
- shipping: PriceModel;
66
- effectiveShipping: PriceModel;
67
- taxTotal: PriceModel;
68
- couponTotal: Record<string, PriceModel>;
69
- couponDiscountTotal: PriceModel;
70
- grandTotal: PriceModel;
71
- };
119
+ protected total: ShoppingContainerTotalModel;
72
120
  protected country: CountryCode;
73
121
  protected currency: CurrencyCode;
74
122
  protected locale: LocaleCode;
@@ -79,6 +127,8 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
79
127
  * @param date - Optional date object for setting creation/modification times (defaults to now).
80
128
  */
81
129
  constructor(data: BaseShoppingContainerAttributes, date?: Date);
130
+ private mapTaxBreakdown;
131
+ private serializeTaxBreakdown;
82
132
  /**
83
133
  * Gets the unique identifier for this shopping container (cart ID or order ID).
84
134
  * @returns The ID string.
@@ -110,6 +160,20 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
110
160
  * @returns The count of line items.
111
161
  */
112
162
  getLineItemsCount(): number;
163
+ /**
164
+ * Gets a defensive copy of the charges in the container.
165
+ * @returns An array of ChargeModel instances.
166
+ */
167
+ getCharges(): ChargeModel[];
168
+ /**
169
+ * Adds a new charge to the container and recalculates totals.
170
+ * @param charge - The charge to add.
171
+ */
172
+ addCharge(charge: ChargeModel): void;
173
+ /**
174
+ * Clears all charges from the container and recalculates totals.
175
+ */
176
+ clearCharges(): void;
113
177
  /**
114
178
  * Gets a copy of the shipping details associated with the container.
115
179
  * @returns A ShippingDetails object, or null if none are set.
@@ -162,15 +226,7 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
162
226
  * Gets a defensive copy of the calculated totals for the container.
163
227
  * @returns An object containing shipping, subtotal, coupon, and grand totals.
164
228
  */
165
- getTotal(): {
166
- subtotal: PriceModel;
167
- shipping: PriceModel;
168
- effectiveShipping: PriceModel;
169
- taxTotal: PriceModel;
170
- couponTotal: Record<string, PriceModel>;
171
- couponDiscountTotal: PriceModel;
172
- grandTotal: PriceModel;
173
- };
229
+ getTotal(): ShoppingContainerTotalModel;
174
230
  /**
175
231
  * Gets a plain data object representing the shopping container's current state.
176
232
  * Includes details from the base model and specific container properties.
@@ -199,11 +255,13 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
199
255
  * @param couponTotal - A record of coupon codes and their calculated discount amounts.
200
256
  */
201
257
  private applyDiscountsInLineItem;
258
+ private applyDiscuountsInShippingCharges;
202
259
  /**
203
- * Updates the tax rules for all line items and recalculates totals.
204
- * @param taxRules - A record of tax rules keyed by tax category.
260
+ * Updates the tax rules for all line items and charges, then recalculates totals.
261
+ * @param lineItemTaxRules - A record of tax rules keyed by lineItem Id.
262
+ * @param chargeTaxRules - A record of tax rules keyed by charge Id.
205
263
  */
206
- updateTax(taxRules: Record<TaxCategory, TaxRuleModel>): void;
264
+ updateTax(lineItemTaxRules: Record<string, TaxRuleModel[]>, chargeTaxRules?: Record<string, FixedTaxRuleModel[]>): void;
207
265
  /**
208
266
  * Selects and applies the best applicable non-shipping coupon.
209
267
  * Currently supports applying only a single coupon of type COUPON.
@@ -217,4 +275,4 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
217
275
  private applyShippingCoupons;
218
276
  }
219
277
 
220
- export { type BaseShoppingContainerAttributes, type BaseShoppingContainerData, type ShoppingContainerTotal, BaseShoppingContainerModel as default };
278
+ export { type BaseShoppingContainerAttributes, type BaseShoppingContainerData, type ShoppingContainerTaxBreakdownModel, type ShoppingContainerTotal, type ShoppingContainerTotalModel, type TaxSystemBreakdown, type TaxSystemBreakdownModel, BaseShoppingContainerModel as default };
@@ -1,41 +1,96 @@
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 { P as PriceData, S as ShippingDetails, C as CountryCode, a as CurrencyCode, L as LocaleCode, b as PriceModel } from '../Common-CXp_zjft.js';
4
+ import { P as PriceData, b as PriceModel, S as ShippingDetails, C as CountryCode, a as CurrencyCode, L as LocaleCode } from '../Common-CXp_zjft.js';
5
5
  import CouponModel, { CouponData } from './Coupon.js';
6
- import { TaxCategory } from './Enum.js';
7
- import { TaxRuleModel } from './TaxRule.js';
6
+ import { TaxSystem } from './Enum.js';
7
+ import { TaxRuleModel, FixedTaxRuleModel } from './TaxRule.js';
8
+ import ChargeModel, { ChargeData } from './Charge.js';
8
9
  import '../Auth/index.js';
9
10
  import './ImageInfo.js';
10
11
  import './Product.js';
11
12
  import './TieredPrice.js';
12
13
 
14
+ /**
15
+ * Breakdown of a specific tax system (e.g., GST, VAT) for the entire container.
16
+ * Groups taxes by system and then by specific rule/subsystem.
17
+ */
18
+ type TaxSystemBreakdown = {
19
+ /** Name of the tax system (e.g., GST) */
20
+ system: TaxSystem;
21
+ /** Total tax amount collected for this system across all line items and charges */
22
+ totalAmount: PriceData;
23
+ /** Detailed breakdown by rule/subsystem to total tax amount (e.g., CGST, SGST) */
24
+ subSystems: Record<string, PriceData>;
25
+ };
26
+ /**
27
+ * Internal model for tax system breakdown using PriceModel instances.
28
+ */
29
+ type TaxSystemBreakdownModel = {
30
+ system: TaxSystem;
31
+ totalAmount: PriceModel;
32
+ subSystems: Record<string, PriceModel>;
33
+ };
34
+ type ShoppingContainerTaxBreakdownModel = Record<string, TaxSystemBreakdownModel>;
35
+ /**
36
+ * Comprehensive totals for a shopping container, logically grouped by source.
37
+ */
13
38
  type ShoppingContainerTotal = {
14
- /** Sum of item prices before discounts & tax */
39
+ /** Sum of all line item prices before any discounts or taxes */
15
40
  subtotal: PriceData;
16
- /** Original shipping cost before coupons / promotions */
17
- shipping: PriceData;
18
- /** Shipping after coupons / promotions (>= 0) */
19
- effectiveShipping: PriceData;
20
- /** Total tax amount (all tax rules combined) */
41
+ /** Total item subtotal after item-level discounts have been applied (taxable base for items) */
42
+ netSubtotal: PriceData;
43
+ /** Total tax collected specifically from line items */
44
+ lineItemTaxTotal: PriceData;
45
+ /** Granular tax breakdown for all line items */
46
+ lineItemTaxBreakdown: Record<string, TaxSystemBreakdown>;
47
+ /** Sum of all extra charges (shipping, processing, etc.) before tax */
48
+ chargesTotal: PriceData;
49
+ /** Specifically the shipping portion of charges */
50
+ shippingCharge: PriceData;
51
+ /** Shipping cost after any shipping-specific discounts */
52
+ netShippingCharge: PriceData;
53
+ /** Total tax collected specifically from charges */
54
+ chargeTaxTotal: PriceData;
55
+ /** Granular tax breakdown for all charges */
56
+ chargeTaxBreakdown: Record<string, TaxSystemBreakdown>;
57
+ /** Combined total tax (lineItemTaxTotal + chargeTaxTotal) */
21
58
  taxTotal: PriceData;
22
- /**
23
- * Coupon discounts applied
24
- * key = couponCode (or couponId)
25
- * value = discount amount (positive number)
26
- */
27
- couponTotal: Record<string, PriceData>;
28
- /** Total discount from coupons (derived, optional to store) */
29
- couponDiscountTotal: PriceData;
30
- /** Final payable amount */
59
+ /** Combined granular tax breakdown for the entire container */
60
+ taxBreakdown: Record<string, TaxSystemBreakdown>;
61
+ /** Map of applied coupon codes to their calculated discount amounts */
62
+ discounts: Record<string, PriceData>;
63
+ /** Sum of all coupon discounts applied to the container */
64
+ totalDiscount: PriceData;
65
+ /** Final total amount to be paid (NetSubtotal + ChargesTotal + TaxTotal - (any remaining discounts)) */
31
66
  grandTotal: PriceData;
32
67
  };
68
+ /**
69
+ * Internal model version of ShoppingContainerTotal using PriceModel instances.
70
+ */
71
+ type ShoppingContainerTotalModel = {
72
+ subtotal: PriceModel;
73
+ netSubtotal: PriceModel;
74
+ lineItemTaxTotal: PriceModel;
75
+ lineItemTaxBreakdown: Record<string, TaxSystemBreakdownModel>;
76
+ chargesTotal: PriceModel;
77
+ shippingCharge: PriceModel;
78
+ netShippingCharge: PriceModel;
79
+ chargeTaxTotal: PriceModel;
80
+ chargeTaxBreakdown: Record<string, TaxSystemBreakdownModel>;
81
+ taxTotal: PriceModel;
82
+ taxBreakdown: Record<string, TaxSystemBreakdownModel>;
83
+ discounts: Record<string, PriceModel>;
84
+ totalDiscount: PriceModel;
85
+ grandTotal: PriceModel;
86
+ };
33
87
  type BaseShoppingContainerAttributes = BaseAttributes & {
34
88
  id: string;
35
89
  customerId?: string;
36
90
  customerEmail?: string;
37
91
  anonymousId?: string;
38
92
  lineItems: LineItemData[];
93
+ charges: ChargeData[];
39
94
  shippingDetails: ShippingDetails | null;
40
95
  shippingAddress?: AddressData | null;
41
96
  billingAddress?: AddressData | null;
@@ -56,19 +111,12 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
56
111
  protected customerEmail?: string;
57
112
  protected anonymousId?: string;
58
113
  protected lineItems: LineItemModel[];
114
+ protected charges: ChargeModel[];
59
115
  protected shippingDetails: ShippingDetails | null;
60
116
  protected shippingAddress: AddressModel | null;
61
117
  protected billingAddress: AddressModel | null;
62
118
  protected coupons: CouponModel[];
63
- protected total: {
64
- subtotal: PriceModel;
65
- shipping: PriceModel;
66
- effectiveShipping: PriceModel;
67
- taxTotal: PriceModel;
68
- couponTotal: Record<string, PriceModel>;
69
- couponDiscountTotal: PriceModel;
70
- grandTotal: PriceModel;
71
- };
119
+ protected total: ShoppingContainerTotalModel;
72
120
  protected country: CountryCode;
73
121
  protected currency: CurrencyCode;
74
122
  protected locale: LocaleCode;
@@ -79,6 +127,8 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
79
127
  * @param date - Optional date object for setting creation/modification times (defaults to now).
80
128
  */
81
129
  constructor(data: BaseShoppingContainerAttributes, date?: Date);
130
+ private mapTaxBreakdown;
131
+ private serializeTaxBreakdown;
82
132
  /**
83
133
  * Gets the unique identifier for this shopping container (cart ID or order ID).
84
134
  * @returns The ID string.
@@ -110,6 +160,20 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
110
160
  * @returns The count of line items.
111
161
  */
112
162
  getLineItemsCount(): number;
163
+ /**
164
+ * Gets a defensive copy of the charges in the container.
165
+ * @returns An array of ChargeModel instances.
166
+ */
167
+ getCharges(): ChargeModel[];
168
+ /**
169
+ * Adds a new charge to the container and recalculates totals.
170
+ * @param charge - The charge to add.
171
+ */
172
+ addCharge(charge: ChargeModel): void;
173
+ /**
174
+ * Clears all charges from the container and recalculates totals.
175
+ */
176
+ clearCharges(): void;
113
177
  /**
114
178
  * Gets a copy of the shipping details associated with the container.
115
179
  * @returns A ShippingDetails object, or null if none are set.
@@ -162,15 +226,7 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
162
226
  * Gets a defensive copy of the calculated totals for the container.
163
227
  * @returns An object containing shipping, subtotal, coupon, and grand totals.
164
228
  */
165
- getTotal(): {
166
- subtotal: PriceModel;
167
- shipping: PriceModel;
168
- effectiveShipping: PriceModel;
169
- taxTotal: PriceModel;
170
- couponTotal: Record<string, PriceModel>;
171
- couponDiscountTotal: PriceModel;
172
- grandTotal: PriceModel;
173
- };
229
+ getTotal(): ShoppingContainerTotalModel;
174
230
  /**
175
231
  * Gets a plain data object representing the shopping container's current state.
176
232
  * Includes details from the base model and specific container properties.
@@ -199,11 +255,13 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
199
255
  * @param couponTotal - A record of coupon codes and their calculated discount amounts.
200
256
  */
201
257
  private applyDiscountsInLineItem;
258
+ private applyDiscuountsInShippingCharges;
202
259
  /**
203
- * Updates the tax rules for all line items and recalculates totals.
204
- * @param taxRules - A record of tax rules keyed by tax category.
260
+ * Updates the tax rules for all line items and charges, then recalculates totals.
261
+ * @param lineItemTaxRules - A record of tax rules keyed by lineItem Id.
262
+ * @param chargeTaxRules - A record of tax rules keyed by charge Id.
205
263
  */
206
- updateTax(taxRules: Record<TaxCategory, TaxRuleModel>): void;
264
+ updateTax(lineItemTaxRules: Record<string, TaxRuleModel[]>, chargeTaxRules?: Record<string, FixedTaxRuleModel[]>): void;
207
265
  /**
208
266
  * Selects and applies the best applicable non-shipping coupon.
209
267
  * Currently supports applying only a single coupon of type COUPON.
@@ -217,4 +275,4 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
217
275
  private applyShippingCoupons;
218
276
  }
219
277
 
220
- export { type BaseShoppingContainerAttributes, type BaseShoppingContainerData, type ShoppingContainerTotal, BaseShoppingContainerModel as default };
278
+ export { type BaseShoppingContainerAttributes, type BaseShoppingContainerData, type ShoppingContainerTaxBreakdownModel, type ShoppingContainerTotal, type ShoppingContainerTotalModel, type TaxSystemBreakdown, type TaxSystemBreakdownModel, BaseShoppingContainerModel as default };
@@ -1,3 +1,2 @@
1
- 'use strict';var pt=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var pt__default=/*#__PURE__*/_interopDefault(pt);var L=class{customFields;constructor(t,e=new Date){this.customFields={...t.customFields};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}},b=class extends L{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,n){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:n};}};var A=class extends b{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 U=new Uint8Array(256),N=U.length;function J(){return N>U.length-16&&(pt__default.default.randomFillSync(U),N=0),U.slice(N,N+=16)}var ot=/^(?:[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 mt(r){return typeof r=="string"&&ot.test(r)}var st=mt;var h=[];for(let r=0;r<256;++r)h.push((r+256).toString(16).slice(1));function O(r,t=0){return h[r[t+0]]+h[r[t+1]]+h[r[t+2]]+h[r[t+3]]+"-"+h[r[t+4]]+h[r[t+5]]+"-"+h[r[t+6]]+h[r[t+7]]+"-"+h[r[t+8]]+h[r[t+9]]+"-"+h[r[t+10]]+h[r[t+11]]+h[r[t+12]]+h[r[t+13]]+h[r[t+14]]+h[r[t+15]]}function ht(r){if(!st(r))throw TypeError("Invalid UUID");let t,e=new Uint8Array(16);return e[0]=(t=parseInt(r.slice(0,8),16))>>>24,e[1]=t>>>16&255,e[2]=t>>>8&255,e[3]=t&255,e[4]=(t=parseInt(r.slice(9,13),16))>>>8,e[5]=t&255,e[6]=(t=parseInt(r.slice(14,18),16))>>>8,e[7]=t&255,e[8]=(t=parseInt(r.slice(19,23),16))>>>8,e[9]=t&255,e[10]=(t=parseInt(r.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 at=ht;function yt(r){r=unescape(encodeURIComponent(r));let t=[];for(let e=0;e<r.length;++e)t.push(r.charCodeAt(e));return t}var ft="6ba7b810-9dad-11d1-80b4-00c04fd430c8",bt="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function _(r,t,e){function i(n,o,s,c){var u;if(typeof n=="string"&&(n=yt(n)),typeof o=="string"&&(o=at(o)),((u=o)===null||u===void 0?void 0:u.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+n.length);if(a.set(o),a.set(n,o.length),a=e(a),a[6]=a[6]&15|t,a[8]=a[8]&63|128,s){c=c||0;for(let g=0;g<16;++g)s[c+g]=a[g];return s}return O(a)}try{i.name=r;}catch{}return i.DNS=ft,i.URL=bt,i}var tt={randomUUID:pt__default.default.randomUUID};function xt(r,t,e){if(tt.randomUUID&&!t&&!r)return tt.randomUUID();r=r||{};let i=r.random||(r.rng||J)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){e=e||0;for(let n=0;n<16;++n)t[e+n]=i[n];return t}return O(i)}var et=xt;function St(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),pt__default.default.createHash("sha1").update(r).digest()}var ct=St;var It=_("v5",80,ct),it=It;var C={"en-IN":"en","kn-IN":"kn"};var ut={INR:"\u20B9"},lt={INR:"en-IN"};var F=(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))(F||{});var B=class extends Error{constructor(t){super(`Invalid line item state: ${t}`),this.name="InvalidLineItemStateError";}},z=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";}},V=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},G=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},x=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},k=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},q=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";}},j=class extends Error{constructor(t="Tax category is not valid."){super(`InvalidTaxCategory: ${t}`),this.name="InvalidTaxCategoryError";}},Q=class extends Error{constructor(t="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${t}`),this.name="InvalidMinQuantityError";}},H=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},Z=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},Y=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}},X=class extends Error{constructor(t="No applicable tax slab or multiple slabs found for the given unit price."){super(`TaxSlabNotFound: ${t}`),this.name="TaxSlabNotFoundError";}},v=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},P=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},T=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},f=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},E=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}};var S=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 E("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 E("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 l=class r{#t;amount;currency;constructor(t){if(this.#t="PriceModel",t.amount<0)throw new v("Amount cannot be negative.");if(!t.currency)throw new P("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(r.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return this.amount-t.getAmount()}add(t){if(r.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot add prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return new r({amount:this.amount+t.getAmount(),currency:this.currency})}subtract(t){if(r.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot subtract prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return new r({amount:this.amount-t.getAmount(),currency:this.currency})}multiply(t){if(r.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot multiply prices in different currencies.");return new r({amount:this.amount*t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>=0)return new r({amount:this.amount*t,currency:this.currency});throw new f("Must be a non-negative number.")}divide(t){if(r.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot divide prices in different currencies.");return new r({amount:this.amount/t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>0)return new r({amount:this.amount/t,currency:this.currency});throw new f("Must be a positive number.")}min(...t){if(t.length===0)throw new f("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(r.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new T("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i})}max(...t){if(t.length===0)throw new f("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(r.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new T("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return e.compareTo(i)>0?e:i})}zero(){return new r({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new r({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return r.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return r.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(t,e,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=lt[e];if(!e||!n)throw new P("Invalid currency code for formatting.");let o=t,s=i.displayAsInteger?0:r.getDecimalPlaces(e),c={style:i.style??"currency",currency:e,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:s,maximumFractionDigits:s};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,c).format(o)}catch(u){return console.error(`Error formatting price for currency "${e}" and locale "${n}":`,u),`${ut[e]??e} ${r.addThousandSeparators(o.toFixed(s))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),i=e[0],n=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(t,e){if(t<0)throw new v("Amount cannot be negative for rounding.");if(e===void 0)throw new P("Invalid currency code for rounding.");let i=r.getDecimalPlaces(e),n=Math.pow(10,i);return Math.round(t*n)/n}};var D=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new l(t.baseUnitPrice);if(!t.taxCategory)throw new j;let i=(t.tiers??[]).map(u=>({minQuantity:u.minQuantity,unitPrice:new l(u.unitPrice)})).sort((u,a)=>u.minQuantity-a.minQuantity);if(i.some(u=>u.minQuantity<=0))throw new Q;let o=i.some(u=>u.unitPrice.getCurrency()!==e.getCurrency()),s=i.some((u,a)=>a>0&&u.unitPrice.compareTo(i[a-1].unitPrice)>0),c=i[0]?.unitPrice.compareTo(e)>0;if(o||s||c)throw new H("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}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 Z;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity)return this.tiers[e];throw new Y(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 M=class r extends b{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 x("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 n of i){let[o,s]=n.split(":");s.startsWith("c+")?e[o]={name:s.slice(2)}:e[o]=s;}return e}catch(e){throw new x(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((n,o)=>(t.pricing[o]&&(n[o]=new D(t.pricing[o])),n),{}),this.targetGender=t.targetGender,this.attributes=d.deepClone(t.attributes),this.specifications=d.deepClone(t.specifications),this.categories=d.deepClone(t.categories);let i=new Set;this.variants=(t.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new x("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let o=r.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(o))throw new $(o);return i.add(o),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new S(n.images.primary),gallery:(n.images.gallery||[]).map(s=>new S(s))}}}),this.isActive=t.isActive,this.searchTags=t.searchTags?d.deepClone(t.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(t){return t?this.name[t]??this.name[C[t]]??this.name.en:d.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[C[t]]??this.description.en:d.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[C[t]]??this.slug.en:d.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:this.pricing}getAttributes(){return d.deepClone(this.attributes)}getVariants(){return this.variants.map(t=>({sku:t.sku,selectionAttributes:t.selectionAttributes,images:{primary:t.images.primary,gallery:t.images.gallery}}))}getImagesBySelectionAttributes(t){let e=r.generateSelectionAttributesKey(t),i=this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===e);return i?i.images: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 d.deepClone(this.categories)}getSpecifications(t){return t?d.deepClone(this.specifications[t]??this.specifications[C[t]]??this.specifications.en):d.deepClone(this.specifications)}getSearchTags(t){return t?d.deepClone(this.searchTags[t]??this.searchTags[C[t]]??this.searchTags.en):d.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:d.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 x("Selection attributes are required");Object.keys(this.attributes).forEach(e=>{if(e.toLowerCase()==="size")return;let i=this.attributes[e],n=t[e];if(n===void 0)throw new x(`Selection attribute '${e}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new x(`Selection attribute '${e}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new x(`Selection attribute '${e}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(o=>o.name===n.name)<0)throw new x(`Selection attribute '${e}' is invalid`)}});}validateSelectionAttribute(t){let e=r.generateSelectionAttributesKey(t);return this.variants.some(i=>r.generateSelectionAttributesKey(i.selectionAttributes)===e)}validateSize(t){return this.attributes.size.includes(t)}};var At={isUUID:r=>/^[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(r),isEmail:r=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r),isURL:r=>/^(http|https):\/\/[^ "]+$/.test(r),generateUUID:(r,t)=>t&&r?it(r,t):et(),generateSearchId:(r,t)=>`${r}#${M.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:r=>{let[t,e]=r.split("#");return {key:t,selectionAttributes:M.parseSelectionAttributesKey(e)}},deepClone(r){return structuredClone(r)}},d=At;var rt=class{getBreakdown(t,e,i){let n=t*100,o=n%1===0?n.toString():n.toFixed(2).replace(/\.?0+$/,"");if(e==="IN"&&i?.merchantState&&i?.customerState)if(i.merchantState.toLowerCase().trim()===i.customerState.toLowerCase().trim()){let s=n/2%1===0?(n/2).toString():(n/2).toFixed(2).replace(/\.?0+$/,"");return {totalRate:t,label:`${s}% CGST + ${s}% SGST`,components:[{rate:t/2,label:`${s}% CGST`,type:"CGST"},{rate:t/2,label:`${s}% SGST`,type:"SGST"}]}}else return {totalRate:t,label:`${o}% IGST`,components:[{rate:t,label:`${o}% IGST`,type:"IGST"}]};return {totalRate:t,label:`${o}% GST`,components:[{rate:t,label:`${o}% GST`,type:"GST"}]}}getLongName(){return "Goods and Services Tax"}},dt={GST:new rt},W=class r extends b{taxRuleId;taxSystem;taxCategory;country;slabs;effectiveFrom;effectiveTo;constructor(t,e=new Date){super(t,e),this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxCategory=t.taxCategory,this.country=t.country,this.slabs=t.slabs.map(i=>({rate:i.rate,minUnitPrice:new l(i.minUnitPrice),maxUnitPrice:i.maxUnitPrice?new l(i.maxUnitPrice):void 0})),this.effectiveFrom=new Date(t.effectiveFrom),this.effectiveTo=t.effectiveTo?new Date(t.effectiveTo):void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getSlabs(){return this.slabs}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),slabs:this.getSlabs().map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0})),effectiveFrom:this.effectiveFrom.toISOString(),effectiveTo:this.effectiveTo?this.effectiveTo.toISOString():void 0,...super.getDetails()}}appliesTo(t,e,i=new Date){return this.taxCategory===t&&this.country===e&&this.effectiveFrom<=i&&(this.effectiveTo?this.effectiveTo>=i:!0)}getApplicableTaxRate(t){return r.getApplicableTaxRate(t,this.slabs)}getTaxRateDisplayString(t,e){let i=this.getApplicableTaxRate(t);return r.getTaxRateDisplayString(i,{taxSystem:this.taxSystem,merchantState:e?.merchantState,customerState:e?.customerState})}getTaxRateBreakdown(t,e){let i=this.getApplicableTaxRate(t),n=dt[this.taxSystem];if(n)return n.getBreakdown(i,this.country,e);let o=i*100,c=`${o%1===0?o.toString():o.toFixed(2).replace(/\.?0+$/,"")}% ${this.taxSystem}`;return {totalRate:i,label:c,components:[{rate:i,label:c,type:this.taxSystem}]}}getFormattedTaxRate(t,e={}){let n=this.getApplicableTaxRate(t)*100,o=n%1===0?n.toString():n.toFixed(2).replace(/\.?0+$/,""),s=e.variant||"short",c="";switch(s){case"percentageOnly":c=`${o}%`;break;case"detailed":let u=this.getTaxRateBreakdown(t,e),a=e.separator||(e.multiline?`
2
- `:" + ");c=u.components.map(m=>m.label).join(a);break;case"long":let g=dt[this.taxSystem],y=g?g.getLongName(this.country):this.taxSystem.toString();c=`${o}% ${y}`;break;case"short":default:c=`${o}% ${this.taxSystem}`;break}return e.includeTaxesSuffix&&(c+=" (Incl. Taxes)"),c}static getApplicableTaxRate(t,e){let i=e.filter(n=>(n.minUnitPrice===void 0||t.compareTo(n.minUnitPrice)>=0)&&(n.maxUnitPrice===void 0||t.compareTo(n.maxUnitPrice)<0));if(i.length!==1)throw new X;return i[0].rate}static getTaxRateDisplayString(t,e){let i=t*100,n=i%1===0?i.toString():i.toFixed(2).replace(/\.?0+$/,"");if(e.taxSystem==="GST"&&e.merchantState&&e.customerState)if(e.merchantState.toLowerCase().trim()===e.customerState.toLowerCase().trim()){let o=i/2%1===0?(i/2).toString():(i/2).toFixed(2).replace(/\.?0+$/,"");return `${o}% CGST + ${o}% SGST`}else return `${n}% IGST`;return e.taxSystem?`${n}% ${e.taxSystem}`:`${n}%`}};var w=class extends L{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=d.deepClone(t.selectionAttributes),this.name=d.deepClone(t.name),this.specifications=d.deepClone(t.specifications),this.primaryImage=new S(t.primaryImage),this.subItems=d.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new z(i.size);e.add(i.size);}),this.pricing={unitPrice:new l(t.pricing.unitPrice),tierPricing:new D(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,tax:{taxRuleId:t.pricing.tax.taxRuleId,taxSystem:t.pricing.tax.taxSystem,country:t.pricing.tax.country,rate:t.pricing.tax.rate,taxSlabs:t.pricing.tax.taxSlabs.map(i=>({rate:i.rate,minUnitPrice:new l(i.minUnitPrice),maxUnitPrice:i.maxUnitPrice?new l(i.maxUnitPrice):void 0}))}},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,subtotal:new l(t.total.subtotal),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,n])=>[i,new l(n)])),taxableAmount:new l(t.total.taxableAmount),taxTotal:new l(t.total.taxTotal),grandTotal:new l(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return d.deepClone(this.selectionAttributes)}getName(t){return t?d.deepClone(this.name[t]??this.name[C[t]]??this.name.en):d.deepClone(this.name)}getSpecifications(t){return t?d.deepClone(this.specifications[t]??this.specifications[C[t]]??this.specifications.en):d.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return d.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:{taxRuleId:this.pricing.tax.taxRuleId,taxSystem:this.pricing.tax.taxSystem,country:this.pricing.tax.country,rate:this.pricing.tax.rate,taxSlabs:this.pricing.tax.taxSlabs}}}getState(){return this.state}getTotal(){return {quantity:this.total.quantity,subtotal:this.total.subtotal,taxableAmount:this.total.taxableAmount,taxTotal:this.total.taxTotal,discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,e])=>[t,e])),grandTotal:this.total.grandTotal}}getDetails(){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:this.getPricing().unitPrice.getDetails(),tierPricing:this.getPricing().tierPricing.getDetails(),taxCategory:this.getPricing().taxCategory,tax:{taxRuleId:this.getPricing().tax.taxRuleId,taxSystem:this.getPricing().tax.taxSystem,country:this.getPricing().tax.country,rate:this.getPricing().tax.rate,taxSlabs:this.getPricing().tax.taxSlabs.map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0}))}},state:this.getState(),total:{quantity:this.getTotal().quantity,subtotal:this.getTotal().subtotal.getDetails(),taxableAmount:this.getTotal().taxableAmount.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),discounts:Object.fromEntries(Object.entries(this.getTotal().discounts).map(([t,e])=>[t,e.getDetails()])),grandTotal:this.getTotal().grandTotal.getDetails()},customFields:this.getAllCustomFields()}}addSubItems(t,e){t.forEach(i=>{let n=this.subItems.find(o=>o.size===i.size);n?n.quantity=e?n.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 V;if(!t.getIsActive())throw new G;this.subItems.forEach(c=>{if(!t.validateSize(c.size))throw new k});let n=t.getPriceDetails(e);if(!n||n.getBaseUnitPrice().getCurrency()!==i)throw new q;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let o=this.subItems.reduce((c,u)=>c+u.quantity,0),{unitPrice:s}=n.getApplicableTier(o);this.pricing={unitPrice:s,tierPricing:n,taxCategory:n.getTaxCategory(),tax:this.pricing.tax},this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discounts=e,this.calculateTotals();}updateTax(t){if(!t.appliesTo(this.pricing.taxCategory,this.pricing.tax.country))throw new K;let e=this.total.quantity>0?this.total.taxableAmount.divide(this.total.quantity):this.total.taxableAmount.zero();this.pricing.tax={taxRuleId:t.getTaxRuleId(),taxSystem:t.getTaxSystem(),country:t.getCountry(),rate:t.getApplicableTaxRate(e),taxSlabs:t.getSlabs()},this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((y,m)=>y+m.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,subtotal:t,taxableAmount:t,taxTotal:t,discounts:{},grandTotal:t};return}let{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),n=i.multiply(e),o=Object.values(this.total.discounts).reduce((y,m)=>y.add(m),t),s=n.subtract(o),c=e>0?s.divide(e):t,u=W.getApplicableTaxRate(c,this.pricing.tax.taxSlabs),a=s.multiply(u).round(),g=n.subtract(o).add(a);this.total={quantity:e,subtotal:n,taxableAmount:s,taxTotal:a,discounts:this.total.discounts,grandTotal:g};}updateState(t){if(this.state in F)this.state!==t&&(this.state=t);else throw new B(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new S({sources:{original:""}}),this.subItems=[],this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:this.pricing.tax},this.total={quantity:0,subtotal:t,taxableAmount:t,taxTotal:t,discounts:{},grandTotal:t};}};var R=class extends b{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=d.deepClone(t.name),this.description=d.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,n)=>{let o=t.minCartValue[n];return o&&(i[n]=new l(o)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,n)=>{let o=t.maxCartDiscount[n];return o&&(i[n]=new l(o)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new f("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[C[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[C[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,n,o=!0){let s=new l({amount:0,currency:n}),c;if(o&&!this.isActive())return s;let u=this.getMinCartValue(i),a=this.getMaxCartDiscount(i);if(!u||u.compareTo(t)>0||!a)return s;let g=this.getCategory(),y=this.getDiscountMethod(),m=g==="SHIPPING"?e:t;if(m.getAmount()<=0)return s;switch(y){case"flat":let gt=a;c=m.min(gt);break;case"percentage":c=m.multiply(this.getPercentageValue()/100).round();break;default:return s}return c.min(a)}};var nt=class extends b{id;customerId;customerEmail;anonymousId;lineItems;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 w(i)),this.billingAddress=t.billingAddress?new A(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new A(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new R(i)),this.shippingDetails=t.shippingDetails?d.deepClone(t.shippingDetails):null,this.total={subtotal:new l(t.total.subtotal),shipping:new l(t.total.shipping),effectiveShipping:new l(t.total.effectiveShipping),taxTotal:new l(t.total.taxTotal),couponTotal:Object.fromEntries(Object.entries(t.total.couponTotal).map(([i,n])=>[i,new l(n)])),couponDiscountTotal:new l(t.total.couponDiscountTotal),grandTotal:new l(t.total.grandTotal)};}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new w(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new A(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new A(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return this.total}getDetails(){return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(t=>t.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(t=>t.getDetails()),total:{subtotal:this.getTotal().subtotal.getDetails(),shipping:this.getTotal().shipping.getDetails(),effectiveShipping:this.getTotal().effectiveShipping.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),couponTotal:Object.fromEntries(Object.entries(this.getTotal().couponTotal).map(([t,e])=>[t,e.getDetails()])),couponDiscountTotal:this.getTotal().couponDiscountTotal.getDetails(),grandTotal:this.getTotal().grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new l({amount:0,currency:this.currency}),e=this.lineItems.filter(m=>m.getState()!=="CANCELLED"),i=e.reduce((m,I)=>m.add(I.getTotal().subtotal),t),n=new l({amount:this.shippingDetails?.cost||0,currency:this.currency}).round(),o=t,s={},c={};this.coupons.forEach(m=>{let I=m.calculateApplicableCouponDiscount(i,n,this.country,this.currency);o=o.add(I),s[m.getCode()]=I,m.getCategory()!=="SHIPPING"&&(c[m.getCode()]=I);}),this.applyDiscountsInLineItem(c);let u=e.reduce((m,I)=>m.add(I.getTotal().taxTotal),t),a=this.coupons.find(m=>m.getCategory()==="SHIPPING"),g=a?n.subtract(s[a.getCode()]||t):n,y=i.add(n).add(u).subtract(o);this.total={subtotal:i,shipping:n,effectiveShipping:g,couponTotal:s,couponDiscountTotal:o,taxTotal:u,grandTotal:y};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let e=t.filter(n=>n.getCategory()==="SHIPPING"),i=t.filter(n=>n.getCategory()!=="SHIPPING");this.coupons=[],this.total.couponDiscountTotal=this.total.subtotal.zero(),this.total.couponTotal={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.couponTotal),e.length&&this.applyShippingCoupons(e),this.calculateTotals();}applyDiscountsInLineItem(t){let e=Array.from(Object.entries(t)).filter(n=>!n[1].isZero()),i=new Map;this.lineItems.forEach(n=>i.set(n.getId(),[])),e.forEach(([n,o])=>{let s=this.coupons.find(a=>a.getCode()===n);if(!s||o.isZero())return;let c=this.lineItems.filter(a=>a.getState()!=="CANCELLED"&&!a.getTotal().subtotal.isZero()).sort((a,g)=>a.getTotal().subtotal.compareTo(g.getTotal().subtotal)),u=new l({amount:0,currency:this.currency});c.forEach((a,g)=>{let y;g===c.length-1?y=o.subtract(u):y=o.multiply(a.getTotal().subtotal).divide(this.total.subtotal).round(),u=u.add(y),i.get(a.getId())?.push({coupon:s,amount:y});});}),this.lineItems.forEach(n=>{n.getState()==="CANCELLED"||this.total.subtotal.isZero()?n.updateDiscounts([]):n.updateDiscounts(i.get(n.getId())||[]);});}updateTax(t){this.lineItems.forEach(e=>{e.updateTax(t[e.getPricing().taxCategory]);}),this.calculateTotals();}applyNonShippingCoupons(t){let e=t.filter(i=>i.getType()==="coupon");if(e.length===1){let i=e[0].calculateApplicableCouponDiscount(this.total.subtotal,this.total.shipping,this.country,this.currency);i.getAmount()>0&&(this.coupons.push(e[0]),this.total.couponTotal[e[0].getCode()]=i,this.total.couponDiscountTotal=i);}}applyShippingCoupons(t){if(this.total.shipping.getAmount()>0&&t.length>0){let e=this.total.subtotal.subtract(this.total.couponDiscountTotal),i=t.reduce((o,s)=>{if(!o)return s;let c=s.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping),u=o.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping);return c===u?s.getType()==="coupon"?s:o:c>u?s:o}),n=i.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping);n.getAmount()>0&&(this.coupons.push(i),this.total.couponTotal[i.getCode()]=n,this.total.couponDiscountTotal=this.total.couponDiscountTotal.add(n),this.total.effectiveShipping=this.total.shipping.subtract(n));}}};module.exports=nt;//# sourceMappingURL=ShoppingContainer.js.map
1
+ 'use strict';var It=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var It__default=/*#__PURE__*/_interopDefault(It);var B=class{customFields;constructor(t,e=new Date){this.customFields={...t.customFields};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}},A=class extends B{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 E=class extends A{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 H=new Uint8Array(256),K=H.length;function ut(){return K>H.length-16&&(It__default.default.randomFillSync(H),K=0),H.slice(K,K+=16)}var yt=/^(?:[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 Pt(o){return typeof o=="string"&&yt.test(o)}var bt=Pt;var T=[];for(let o=0;o<256;++o)T.push((o+256).toString(16).slice(1));function Q(o,t=0){return T[o[t+0]]+T[o[t+1]]+T[o[t+2]]+T[o[t+3]]+"-"+T[o[t+4]]+T[o[t+5]]+"-"+T[o[t+6]]+T[o[t+7]]+"-"+T[o[t+8]]+T[o[t+9]]+"-"+T[o[t+10]]+T[o[t+11]]+T[o[t+12]]+T[o[t+13]]+T[o[t+14]]+T[o[t+15]]}function Dt(o){if(!bt(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 ft=Dt;function At(o){o=unescape(encodeURIComponent(o));let t=[];for(let e=0;e<o.length;++e)t.push(o.charCodeAt(e));return t}var Mt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",wt="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function dt(o,t,e){function i(r,s,a,u){var l;if(typeof r=="string"&&(r=At(r)),typeof s=="string"&&(s=ft(s)),((l=s)===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(s),c.set(r,s.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 Q(c)}try{i.name=o;}catch{}return i.DNS=Mt,i.URL=wt,i}var gt={randomUUID:It__default.default.randomUUID};function Rt(o,t,e){if(gt.randomUUID&&!t&&!o)return gt.randomUUID();o=o||{};let i=o.random||(o.rng||ut)();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 Q(i)}var pt=Rt;function Et(o){return Array.isArray(o)?o=Buffer.from(o):typeof o=="string"&&(o=Buffer.from(o,"utf8")),It__default.default.createHash("sha1").update(o).digest()}var xt=Et;var Bt=dt("v5",80,xt),mt=Bt;var I={"en-IN":"en","kn-IN":"kn"};var Tt={INR:"\u20B9"},Ct={INR:"en-IN"};var Z=(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))(Z||{});var Y=class extends Error{constructor(t){super(`Invalid line item state: ${t}`),this.name="InvalidLineItemStateError";}},J=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},W=class extends Error{constructor(t){super(`Duplicate selection attribute found: ${t}`),this.name="DuplicateSelectionAttributeError";}},X=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},_=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},M=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},tt=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},et=class extends Error{constructor(t="Pricing details not available for the product"){super(`NotFound: ${t}`),this.name="PricingNotFoundError";}},it=class extends Error{constructor(t="Tax rule category mismatch."){super(`InvalidTaxRule: ${t}`),this.name="InvalidTaxRuleError";}},rt=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";}},st=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},nt=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},at=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}},ct=class extends Error{constructor(t="No applicable tax slab or multiple slabs found for the given unit price."){super(`TaxSlabNotFound: ${t}`),this.name="TaxSlabNotFoundError";}},V=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},N=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},w=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},C=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},$=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}};var L=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 $("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 $("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 o{#t;amount;currency;constructor(t){if(this.#t="PriceModel",t.amount<0)throw new V("Amount cannot be negative.");if(!t.currency)throw new N("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(o.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot compare prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return this.amount-t.getAmount()}add(t){if(o.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot add prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return new o({amount:this.amount+t.getAmount(),currency:this.currency})}subtract(t){if(o.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot subtract prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return new o({amount:this.amount-t.getAmount(),currency:this.currency})}multiply(t){if(o.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot multiply prices in different currencies.");return new o({amount:this.amount*t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>=0)return new o({amount:this.amount*t,currency:this.currency});throw new C("Must be a non-negative number.")}divide(t){if(o.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot divide prices in different currencies.");return new o({amount:this.amount/t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>0)return new o({amount:this.amount/t,currency:this.currency});throw new C("Must be a positive number.")}min(...t){if(t.length===0)throw new C("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(o.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new w("Cannot compare prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i},this)}max(...t){if(t.length===0)throw new C("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(o.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new w("Cannot compare prices in different currencies.")}else throw new C("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=Ct[e];if(!e||!r)throw new N("Invalid currency code for formatting.");let s=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&&(s=Math.ceil(s));try{return new Intl.NumberFormat(r,u).format(s)}catch(l){return console.error(`Error formatting price for currency "${e}" and locale "${r}":`,l),`${Tt[e]??e} ${o.addThousandSeparators(s.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 V("Amount cannot be negative for rounding.");if(e===void 0)throw new N("Invalid currency code for rounding.");let i=o.getDecimalPlaces(e),r=Math.pow(10,i);return Math.round(t*r)/r}};var U=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new n(t.baseUnitPrice);if(!t.taxCategory)throw new rt;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 s=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(s||a||u)throw new st("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}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 nt;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity)return this.tiers[e];throw new at(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 O=class o extends A{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 M("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[s,a]=r.split(":");a.startsWith("c+")?e[s]={name:a.slice(2)}:e[s]=a;}return e}catch(e){throw new M(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,s)=>(t.pricing[s]&&(r[s]=new U(t.pricing[s])),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 M("Selection attributes are required");this.checkSelectionAttributes(r.selectionAttributes);let s=o.generateSelectionAttributesKey(r.selectionAttributes);if(i.has(s))throw new W(s);return i.add(s),{sku:r.sku,selectionAttributes:r.selectionAttributes,images:{primary:new L(r.images.primary),gallery:(r.images.gallery||[]).map(a=>new L(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[I[t]]??this.name.en:g.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[I[t]]??this.description.en:g.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[I[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: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?i.images: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[I[t]]??this.specifications.en):g.deepClone(this.specifications)}getSearchTags(t){return t?g.deepClone(this.searchTags[t]??this.searchTags[I[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 M("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 M(`Selection attribute '${e}' is missing`);if(typeof i=="string"){if(typeof r!="string"||i!==r)throw new M(`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 M(`Selection attribute '${e}' is invalid`)}else if(typeof r!="object"||!("name"in r)||i.findIndex(s=>s.name===r.name)<0)throw new M(`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 Nt={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?mt(o,t):pt(),generateSearchId:(o,t)=>`${o}#${O.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:o=>{let[t,e]=o.split("#");return {key:t,selectionAttributes:O.parseSelectionAttributesKey(e)}},deepClone(o){return structuredClone(o)}},g=Nt;var j=class o{taxRuleId;taxCategory;taxSystem;taxSubSystem;country;slabs;effectiveFrom;effectiveTo;constructor(t){this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxSubSystem=t.taxSubSystem,this.taxCategory=t.taxCategory,this.country=t.country,this.slabs=t.slabs.map(e=>({rate:e.rate,minUnitPrice:new n(e.minUnitPrice),maxUnitPrice:e.maxUnitPrice?new n(e.maxUnitPrice):void 0})),this.effectiveFrom=new Date(t.effectiveFrom),this.effectiveTo=t.effectiveTo?new Date(t.effectiveTo):void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getSlabs(){return this.slabs}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),slabs:this.getSlabs().map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0})),effectiveFrom:this.effectiveFrom.toISOString(),effectiveTo:this.effectiveTo?this.effectiveTo.toISOString():void 0}}appliesTo(t,e,i=new Date){return this.taxCategory===t&&this.country===e&&this.effectiveFrom<=i&&(this.effectiveTo?this.effectiveTo>=i:!0)}getApplicableTaxRate(t){return o.getApplicableTaxRate(t,this.slabs)}calculateTax(t){let e=this.getApplicableTaxRate(t);return t.multiply(e).round()}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 ct;return i[0].rate}static getTaxRateDisplayString(t,e,i){let r=e*100,s=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,"");return i.percentageOnly?`${s}%`:t.getTaxSystem()==="GST"?`${s}% ${t.getTaxSubSystem()}`:`${s}% ${t.getTaxSystem()}`}},lt=class extends j{rate;constructor(t){super({taxRuleId:t.taxRuleId,taxSystem:t.taxSystem,taxSubSystem:t.taxSubSystem,taxCategory:t.taxCategory,country:t.country,effectiveFrom:t.effectiveFrom,effectiveTo:t.effectiveTo,slabs:[{minUnitPrice:{amount:0,currency:"INR"},rate:t.rate}]}),this.rate=t.rate;}getApplicableTaxRate(){return this.slabs[0].rate}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),rate:this.getApplicableTaxRate(),slabs:this.getSlabs().map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0})),effectiveFrom:this.effectiveFrom.toISOString(),effectiveTo:this.effectiveTo?this.effectiveTo.toISOString():void 0}}};var k=class extends B{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 L(t.primaryImage),this.subItems=g.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new J(i.size);e.add(i.size);}),this.pricing={unitPrice:new n(t.pricing.unitPrice),tierPricing:new U(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(i=>new j(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[I[t]]??this.name.en):g.deepClone(this.name)}getSpecifications(t){return t?g.deepClone(this.specifications[t]??this.specifications[I[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:this.total.taxBreakdown,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(s=>s.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 X;if(!t.getIsActive())throw new _;this.subItems.forEach(u=>{if(!t.validateSize(u.size))throw new tt});let r=t.getPriceDetails(e);if(!r||r.getBaseUnitPrice().getCurrency()!==i)throw new et;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let s=this.subItems.reduce((u,l)=>u+l.quantity,0),{unitPrice:a}=r.getApplicableTier(s);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.getCountry()))throw new it}),this.pricing.applicableTaxRule=t,this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((h,f)=>h+f.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),s=Object.values(this.total.discounts).reduce((h,f)=>h.add(f),t),a=r.subtract(s),u=e>0?a.divide(e):t,l={},c=t;this.pricing.applicableTaxRule.forEach(h=>{let f=h.getApplicableTaxRate(u),P=h.calculateTax(u),D=P.multiply(e);l[h.getTaxRuleId()]={rate:f,taxableUnitPrice:u,taxPerUnit:P,amount:D,system:h.getTaxSystem(),subSystem:h.getTaxSubSystem()},c=c.add(D);});let d=a.add(c);this.total={quantity:e,unitPrice:i,subtotal:r,discounts:this.total.discounts,totalDiscount:s,netUnitPrice:u,netSubtotal:a,taxBreakdown:l,taxTotal:c,grandTotal:d};}updateState(t){if(this.state in Z)this.state!==t&&(this.state=t);else throw new Y(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new L({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 G=class extends A{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 s=t.minCartValue[r];return s&&(i[r]=new n(s)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,r)=>{let s=t.maxCartDiscount[r];return s&&(i[r]=new n(s)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new C("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,s=!0){let a=new n({amount:0,currency:r}),u;if(s&&!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(),f=d==="SHIPPING"?e:t;if(f.getAmount()<=0)return a;switch(h){case"flat":let D=c;u=f.min(D);break;case"percentage":u=f.multiply(this.getPercentageValue()/100).round();break;default:return a}return u.min(c)}};var F=class extends B{id;name;category;lineItemId;chargeType;pricing;total;constructor(t){super(t),this.id=t.id,this.name=t.name,this.category=t.category,this.lineItemId=t.lineItemId,this.chargeType=t.chargeType,this.pricing={price:new n(t.pricing.price),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(e=>new lt(e))},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(){return this.name}getCategory(){return this.category}getChargeType(){return this.chargeType}getLineItemId(){return this.lineItemId}getPricing(){return this.pricing}getTotal(){return this.total}getApplicableTaxRules(){return this.pricing.applicableTaxRule}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((y,S)=>y.add(S),t),r=e.subtract(i),s={},a=this.pricing.applicableTaxRule.reduce((y,S)=>y+S.getApplicableTaxRate(),0),u=r.divide(1+a).round(),l=r.subtract(u),c=t,d=this.pricing.applicableTaxRule.reduce((y,S)=>S.getApplicableTaxRate()>y.getApplicableTaxRate()?S:y),h=d.getTaxRuleId();this.pricing.applicableTaxRule.forEach(y=>{if(y.getTaxRuleId()===h)return;let S=y.getApplicableTaxRate(),z=l.multiply(S).divide(a).round();s[y.getTaxRuleId()]={rate:S,taxablePrice:u,amount:z,system:y.getTaxSystem(),subSystem:y.getTaxSubSystem()},c=c.add(z);});let f=l.subtract(c);s[h]={rate:d.getApplicableTaxRate(),taxablePrice:u,amount:f,system:d.getTaxSystem(),subSystem:d.getTaxSubSystem()};let P=u,D=r;this.total={price:e,discounts:this.total.discounts,netPrice:P,totalDiscount:i,taxBreakdown:s,taxTotal:l,grandTotal:D};}updateTax(t){this.pricing.applicableTaxRule=t,this.calculateTotals();}getDetails(){return {id:this.id,name:g.deepClone(this.name),category:this.category,lineItemId:this.lineItemId,chargeType:this.chargeType,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 ht=class extends A{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 k(i)),this.charges=(t.charges??[]).map(i=>new F(i)),this.billingAddress=t.billingAddress?new E(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new E(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new G(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}),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,s])=>[r,new n(s)]))}]))}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,s])=>[r,s.getDetails()]))}]))}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new k(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(t=>new F(t.getDetails()))}addCharge(t){this.charges.push(t),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new E(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new E(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return this.total}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(),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),s=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,s,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});let d=this.charges.reduce((p,m)=>p.add(m.getTotal().grandTotal),t),h=this.charges.filter(p=>p.getChargeType()==="SHIPPING").reduce((p,m)=>p.add(m.getTotal().grandTotal),t),f=t,P=t,D=t,y={},S={},z={},q=(p,m)=>{Object.entries(p).forEach(([Ut,R])=>{let x=R.system,v=R.subSystem;m[x]||(m[x]={system:x,totalAmount:t,subSystems:{}}),m[x].subSystems[v]?m[x].subSystems[v]=m[x].subSystems[v].add(R.amount):m[x].subSystems[v]=R.amount,m[x].totalAmount=m[x].totalAmount.add(R.amount),y[x]||(y[x]={system:x,totalAmount:t,subSystems:{}}),y[x].subSystems[v]?y[x].subSystems[v]=y[x].subSystems[v].add(R.amount):y[x].subSystems[v]=R.amount,y[x].totalAmount=y[x].totalAmount.add(R.amount);});};e.forEach(p=>{let m=p.getTotal().taxBreakdown;m&&(q(m,S),q(m,y),P=P.add(p.getTotal().taxTotal));}),this.charges.forEach(p=>{let m=p.getTotal().taxBreakdown;m&&(q(m,z),q(m,y),D=D.add(p.getTotal().taxTotal));}),f=P.add(D);let St=r.add(P).add(d);this.total={subtotal:i,netSubtotal:r,lineItemTaxTotal:P,lineItemTaxBreakdown:S,chargesTotal:d,shippingCharge:s,netShippingCharge:h,chargeTaxTotal:D,chargeTaxBreakdown:z,taxTotal:f,taxBreakdown:y,discounts:u,totalDiscount:a,grandTotal:St};}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,s])=>{let a=this.coupons.find(c=>c.getCode()===r);if(!a||s.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=s.subtract(l):h=s.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(s=>!s[1].isZero()),i=this.charges.filter(s=>s.getChargeType()==="SHIPPING"),r=new Map;i.forEach(s=>r.set(s.getId(),[])),e.forEach(([s,a])=>{let u=this.coupons.find(d=>d.getCode()===s);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 f;h===l.length-1?f=a.subtract(c):f=a.multiply(d.getTotal().grandTotal).divide(this.total.subtotal).round(),c=c.add(f),r.get(d.getId())?.push({coupon:u,amount:f});});}),i.forEach(s=>{s.updateDiscounts(r.get(s.getId())||[]);});}updateTax(t,e={}){this.lineItems.forEach(i=>{let r=t[i.getId()];r&&i.updateTax(r);}),this.charges.forEach(i=>{let r=e[i.getId()];r&&i.updateTax(r);}),this.calculateTotals();}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((s,a)=>{if(!s)return a;let u=a.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge),l=s.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge);return u===l?a.getType()==="coupon"?a:s:u.compareTo(l)>0?a:s}),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=ht;//# sourceMappingURL=ShoppingContainer.js.map
3
2
  //# sourceMappingURL=ShoppingContainer.js.map