b23-lib 2.0.0 → 2.0.1

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 (150) 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/Auth/index.mjs.map +1 -1
  5. package/dist/Classes/Address.d.mts +1 -1
  6. package/dist/Classes/Address.d.ts +1 -1
  7. package/dist/Classes/Address.js.map +1 -1
  8. package/dist/Classes/Address.mjs +1 -1
  9. package/dist/Classes/Base.d.mts +5 -5
  10. package/dist/Classes/Base.d.ts +5 -5
  11. package/dist/Classes/Base.js.map +1 -1
  12. package/dist/Classes/Base.mjs +1 -1
  13. package/dist/Classes/Cart.d.mts +27 -12
  14. package/dist/Classes/Cart.d.ts +27 -12
  15. package/dist/Classes/Cart.js +1 -1
  16. package/dist/Classes/Cart.js.map +1 -1
  17. package/dist/Classes/Cart.mjs +1 -1
  18. package/dist/Classes/Cart.mjs.map +1 -1
  19. package/dist/Classes/Common.d.mts +2 -93
  20. package/dist/Classes/Common.d.ts +2 -93
  21. package/dist/Classes/Coupon.d.mts +33 -15
  22. package/dist/Classes/Coupon.d.ts +33 -15
  23. package/dist/Classes/Coupon.js +1 -1
  24. package/dist/Classes/Coupon.js.map +1 -1
  25. package/dist/Classes/Coupon.mjs +1 -1
  26. package/dist/Classes/Customer.d.mts +2 -2
  27. package/dist/Classes/Customer.d.ts +2 -2
  28. package/dist/Classes/Customer.js.map +1 -1
  29. package/dist/Classes/Customer.mjs +1 -1
  30. package/dist/Classes/Customer.mjs.map +1 -1
  31. package/dist/Classes/CustomerAddress.d.mts +1 -1
  32. package/dist/Classes/CustomerAddress.d.ts +1 -1
  33. package/dist/Classes/CustomerAddress.js.map +1 -1
  34. package/dist/Classes/CustomerAddress.mjs +1 -1
  35. package/dist/Classes/Enum.d.mts +43 -2
  36. package/dist/Classes/Enum.d.ts +43 -2
  37. package/dist/Classes/Enum.js +1 -1
  38. package/dist/Classes/Enum.js.map +1 -1
  39. package/dist/Classes/Enum.mjs +1 -1
  40. package/dist/Classes/Error.d.mts +59 -0
  41. package/dist/Classes/Error.d.ts +59 -0
  42. package/dist/Classes/Error.js +2 -0
  43. package/dist/Classes/Error.js.map +1 -0
  44. package/dist/Classes/Error.mjs +2 -0
  45. package/dist/Classes/Error.mjs.map +1 -0
  46. package/dist/Classes/ImageInfo.js +1 -1
  47. package/dist/Classes/ImageInfo.js.map +1 -1
  48. package/dist/Classes/ImageInfo.mjs +1 -1
  49. package/dist/Classes/Inventory.d.mts +25 -6
  50. package/dist/Classes/Inventory.d.ts +25 -6
  51. package/dist/Classes/Inventory.js +1 -1
  52. package/dist/Classes/Inventory.js.map +1 -1
  53. package/dist/Classes/Inventory.mjs +1 -1
  54. package/dist/Classes/Inventory.mjs.map +1 -1
  55. package/dist/Classes/LineItem.d.mts +140 -58
  56. package/dist/Classes/LineItem.d.ts +140 -58
  57. package/dist/Classes/LineItem.js +1 -1
  58. package/dist/Classes/LineItem.js.map +1 -1
  59. package/dist/Classes/LineItem.mjs +1 -1
  60. package/dist/Classes/Order.d.mts +7 -51
  61. package/dist/Classes/Order.d.ts +7 -51
  62. package/dist/Classes/Order.js +1 -1
  63. package/dist/Classes/Order.js.map +1 -1
  64. package/dist/Classes/Order.mjs +1 -1
  65. package/dist/Classes/Order.mjs.map +1 -1
  66. package/dist/Classes/Payment.d.mts +4 -4
  67. package/dist/Classes/Payment.d.ts +4 -4
  68. package/dist/Classes/Payment.js.map +1 -1
  69. package/dist/Classes/Payment.mjs +1 -1
  70. package/dist/Classes/Payment.mjs.map +1 -1
  71. package/dist/Classes/Price.d.mts +1 -82
  72. package/dist/Classes/Price.d.ts +1 -82
  73. package/dist/Classes/Price.js +1 -1
  74. package/dist/Classes/Price.js.map +1 -1
  75. package/dist/Classes/Price.mjs +1 -1
  76. package/dist/Classes/Product.d.mts +103 -85
  77. package/dist/Classes/Product.d.ts +103 -85
  78. package/dist/Classes/Product.js +1 -1
  79. package/dist/Classes/Product.js.map +1 -1
  80. package/dist/Classes/Product.mjs +1 -1
  81. package/dist/Classes/Product.mjs.map +1 -1
  82. package/dist/Classes/ShoppingContainer.d.mts +79 -63
  83. package/dist/Classes/ShoppingContainer.d.ts +79 -63
  84. package/dist/Classes/ShoppingContainer.js +1 -1
  85. package/dist/Classes/ShoppingContainer.js.map +1 -1
  86. package/dist/Classes/ShoppingContainer.mjs +1 -1
  87. package/dist/Classes/TaxRule.d.mts +63 -0
  88. package/dist/Classes/TaxRule.d.ts +63 -0
  89. package/dist/Classes/TaxRule.js +2 -0
  90. package/dist/Classes/TaxRule.js.map +1 -0
  91. package/dist/Classes/TaxRule.mjs +2 -0
  92. package/dist/Classes/TaxRule.mjs.map +1 -0
  93. package/dist/Classes/TieredPrice.d.mts +75 -0
  94. package/dist/Classes/TieredPrice.d.ts +75 -0
  95. package/dist/Classes/TieredPrice.js +2 -0
  96. package/dist/Classes/TieredPrice.js.map +1 -0
  97. package/dist/Classes/TieredPrice.mjs +2 -0
  98. package/dist/Classes/TieredPrice.mjs.map +1 -0
  99. package/dist/Common-D-UoxwM0.d.ts +210 -0
  100. package/dist/Common-FbQ5-3QN.d.mts +210 -0
  101. package/dist/chunk-2SGUPNWZ.mjs +2 -0
  102. package/dist/chunk-2SGUPNWZ.mjs.map +1 -0
  103. package/dist/chunk-54RUAXYE.mjs +2 -0
  104. package/dist/chunk-54RUAXYE.mjs.map +1 -0
  105. package/dist/{chunk-ATUUYYQT.mjs → chunk-55SOBG62.mjs} +2 -2
  106. package/dist/chunk-55SOBG62.mjs.map +1 -0
  107. package/dist/{chunk-H5GPM4LA.mjs → chunk-5KD2EW7O.mjs} +2 -2
  108. package/dist/{chunk-H5GPM4LA.mjs.map → chunk-5KD2EW7O.mjs.map} +1 -1
  109. package/dist/chunk-72DR3HF2.mjs +2 -0
  110. package/dist/chunk-72DR3HF2.mjs.map +1 -0
  111. package/dist/chunk-AMIRIUMH.mjs +2 -0
  112. package/dist/chunk-AMIRIUMH.mjs.map +1 -0
  113. package/dist/chunk-CEGQFFYZ.mjs +2 -0
  114. package/dist/chunk-CEGQFFYZ.mjs.map +1 -0
  115. package/dist/chunk-EP7WVZXC.mjs +2 -0
  116. package/dist/chunk-EP7WVZXC.mjs.map +1 -0
  117. package/dist/chunk-KWH7GE23.mjs +2 -0
  118. package/dist/chunk-KWH7GE23.mjs.map +1 -0
  119. package/dist/chunk-LNIZAPER.mjs +2 -0
  120. package/dist/chunk-LNIZAPER.mjs.map +1 -0
  121. package/dist/chunk-NJKSUUOB.mjs +2 -0
  122. package/dist/chunk-NJKSUUOB.mjs.map +1 -0
  123. package/dist/chunk-NUTKOIGY.mjs +2 -0
  124. package/dist/chunk-NUTKOIGY.mjs.map +1 -0
  125. package/dist/chunk-RBROVHJ4.mjs +2 -0
  126. package/dist/chunk-RBROVHJ4.mjs.map +1 -0
  127. package/dist/index.d.mts +9 -6
  128. package/dist/index.d.ts +9 -6
  129. package/dist/index.js +2 -2
  130. package/dist/index.js.map +1 -1
  131. package/dist/index.mjs +2 -2
  132. package/dist/index.mjs.map +1 -1
  133. package/package.json +1 -1
  134. package/dist/chunk-6PDP4ETM.mjs +0 -2
  135. package/dist/chunk-6PDP4ETM.mjs.map +0 -1
  136. package/dist/chunk-ATUUYYQT.mjs.map +0 -1
  137. package/dist/chunk-CKUUUEWT.mjs +0 -2
  138. package/dist/chunk-CKUUUEWT.mjs.map +0 -1
  139. package/dist/chunk-DKI6BDWK.mjs +0 -2
  140. package/dist/chunk-DKI6BDWK.mjs.map +0 -1
  141. package/dist/chunk-K3AXPTGG.mjs +0 -2
  142. package/dist/chunk-K3AXPTGG.mjs.map +0 -1
  143. package/dist/chunk-LMMJSJTO.mjs +0 -2
  144. package/dist/chunk-LMMJSJTO.mjs.map +0 -1
  145. package/dist/chunk-RWBNLNQ6.mjs +0 -2
  146. package/dist/chunk-RWBNLNQ6.mjs.map +0 -1
  147. package/dist/chunk-V4H3X4PI.mjs +0 -2
  148. package/dist/chunk-V4H3X4PI.mjs.map +0 -1
  149. package/dist/chunk-WOMA746Z.mjs +0 -2
  150. package/dist/chunk-WOMA746Z.mjs.map +0 -1
@@ -1,22 +1,34 @@
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 { ShippingDetails, CountryCode, CurrencyCode, LocaleCode } from './Common.js';
4
+ import { P as PriceData, S as ShippingDetails, C as CountryCode, a as CurrencyCode, L as LocaleCode, b as PriceModel } from '../Common-D-UoxwM0.js';
5
5
  import CouponModel, { CouponData } from './Coupon.js';
6
+ import { TaxCategory } from './Enum.js';
7
+ import { TaxRuleModel } from './TaxRule.js';
6
8
  import '../Auth/index.js';
7
9
  import './ImageInfo.js';
8
10
  import './Product.js';
9
- import './Enum.js';
11
+ import './TieredPrice.js';
10
12
 
11
13
  type ShoppingContainerTotal = {
12
- shipping?: number;
13
- effectiveShipping?: number;
14
- subtotal?: number;
15
- mrpTotal?: number;
16
- couponTotal?: {
17
- [key: string]: number;
18
- };
19
- grandTotal?: number;
14
+ /** Sum of item prices before discounts & tax */
15
+ 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) */
21
+ 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 */
31
+ grandTotal: PriceData;
20
32
  };
21
33
  type BaseShoppingContainerAttributes = BaseAttributes & {
22
34
  id: string;
@@ -27,25 +39,13 @@ type BaseShoppingContainerAttributes = BaseAttributes & {
27
39
  shippingDetails: ShippingDetails | null;
28
40
  shippingAddress?: AddressData | null;
29
41
  billingAddress?: AddressData | null;
30
- coupons?: CouponData[];
31
- total?: ShoppingContainerTotal;
42
+ coupons: CouponData[];
43
+ total: ShoppingContainerTotal;
32
44
  country: CountryCode;
33
45
  currency: CurrencyCode;
34
46
  locale: LocaleCode;
35
47
  };
36
- type BaseShoppingContainerData = Omit<BaseShoppingContainerAttributes, 'coupons' | 'total'> & BaseData & {
37
- coupons: CouponData[];
38
- total: {
39
- shipping: number;
40
- effectiveShipping: number;
41
- subtotal: number;
42
- mrpTotal: number;
43
- couponTotal: {
44
- [key: string]: number;
45
- };
46
- grandTotal: number;
47
- };
48
- };
48
+ type BaseShoppingContainerData = BaseShoppingContainerAttributes & BaseData;
49
49
  /**
50
50
  * Abstract base class for shopping-related containers like carts and orders.
51
51
  * Manages common elements such as line items, addresses, coupons, and totals.
@@ -61,14 +61,13 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
61
61
  protected billingAddress: AddressModel | null;
62
62
  protected coupons: CouponModel[];
63
63
  protected total: {
64
- shipping: number;
65
- effectiveShipping: number;
66
- subtotal: number;
67
- mrpTotal: number;
68
- couponTotal: {
69
- [key: string]: number;
70
- };
71
- grandTotal: number;
64
+ subtotal: PriceModel;
65
+ shipping: PriceModel;
66
+ effectiveShipping: PriceModel;
67
+ taxTotal: PriceModel;
68
+ couponTotal: Record<string, PriceModel>;
69
+ couponDiscountTotal: PriceModel;
70
+ grandTotal: PriceModel;
72
71
  };
73
72
  protected country: CountryCode;
74
73
  protected currency: CurrencyCode;
@@ -80,11 +79,6 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
80
79
  * @param date - Optional date object for setting creation/modification times (defaults to now).
81
80
  */
82
81
  constructor(data: BaseShoppingContainerAttributes, date?: Date);
83
- /**
84
- * Recalculates the subtotal and mrpTotal based on the current line items.
85
- * Uses PriceModel for rounding based on the country.
86
- */
87
- protected recalculateBaseTotals(): void;
88
82
  /**
89
83
  * Gets the unique identifier for this shopping container (cart ID or order ID).
90
84
  * @returns The ID string.
@@ -112,8 +106,8 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
112
106
  */
113
107
  getLineItems(): LineItemModel[];
114
108
  /**
115
- * Gets current number of line items in the container
116
- * @returns
109
+ * Gets current number of line items in the container.
110
+ * @returns The count of line items.
117
111
  */
118
112
  getLineItemsCount(): number;
119
113
  /**
@@ -169,36 +163,58 @@ declare abstract class BaseShoppingContainerModel extends BaseModel {
169
163
  * @returns An object containing shipping, subtotal, coupon, and grand totals.
170
164
  */
171
165
  getTotal(): {
172
- couponTotal: {
173
- [x: string]: number;
174
- };
175
- shipping: number;
176
- effectiveShipping: number;
177
- subtotal: number;
178
- mrpTotal: number;
179
- grandTotal: number;
166
+ subtotal: PriceModel;
167
+ shipping: PriceModel;
168
+ effectiveShipping: PriceModel;
169
+ taxTotal: PriceModel;
170
+ couponTotal: Record<string, PriceModel>;
171
+ couponDiscountTotal: PriceModel;
172
+ grandTotal: PriceModel;
180
173
  };
181
- /**
182
- * Calculates the discount value for a given coupon based on the current container state.
183
- * Returns 0 if the coupon is invalid, expired, or not applicable based on cart value or target category.
184
- * @param coupon - The CouponModel instance to evaluate.
185
- * @param checkExpiry - Whether to check the coupon's expiry status.
186
- * @returns The calculated discount amount (rounded according to country rules).
187
- */
188
- calculateApplicableCouponDiscount(coupon: CouponModel, checkExpiry?: boolean): number;
189
- /**
190
- * Recalculates the `couponTotal` map based on currently applied coupons.
191
- * Iterates through coupons, calculates their applicable discount, and stores it.
192
- * @param checkExpiry - Whether to check the expiry status of coupons.
193
- * @returns The total discount amount from all valid and applicable coupons (rounded).
194
- */
195
- recalculateCouponTotals(checkExpiry?: boolean): number;
196
174
  /**
197
175
  * Gets a plain data object representing the shopping container's current state.
198
176
  * Includes details from the base model and specific container properties.
199
177
  * @returns BaseShoppingContainerData object suitable for serialization or API responses.
200
178
  */
201
179
  getDetails(): BaseShoppingContainerData;
180
+ /**
181
+ * Recalculates the total costs for the shopping container.
182
+ * This includes summing line items, calculating shipping, applying coupons, and computing taxes.
183
+ */
184
+ calculateTotals(): void;
185
+ /**
186
+ * Updates the shipping details and recalculates the totals.
187
+ * @param shippingDetails - The new shipping details to apply.
188
+ */
189
+ updateShippingDetails(shippingDetails: ShippingDetails): void;
190
+ /**
191
+ * Applies a list of coupons to the shopping container.
192
+ * Filters out invalid coupons, separates shipping and non-shipping coupons,
193
+ * and distributes discounts to line items.
194
+ * @param applicableCoupons - The list of coupons to attempt to apply.
195
+ */
196
+ applyCoupons(applicableCoupons: CouponModel[]): void;
197
+ /**
198
+ * Distributes the total discount amount among the line items.
199
+ * @param couponTotal - A record of coupon codes and their calculated discount amounts.
200
+ */
201
+ private applyDiscountsInLineItem;
202
+ /**
203
+ * Updates the tax rules for all line items and recalculates totals.
204
+ * @param taxRules - A record of tax rules keyed by tax category.
205
+ */
206
+ updateTax(taxRules: Record<TaxCategory, TaxRuleModel>): void;
207
+ /**
208
+ * Selects and applies the best applicable non-shipping coupon.
209
+ * Currently supports applying only a single coupon of type COUPON.
210
+ * @param applicableCoupons - List of available non-shipping coupons.
211
+ */
212
+ private applyNonShippingCoupons;
213
+ /**
214
+ * Selects and applies the best applicable shipping coupon.
215
+ * @param applicableCoupons - List of available shipping coupons.
216
+ */
217
+ private applyShippingCoupons;
202
218
  }
203
219
 
204
220
  export { type BaseShoppingContainerAttributes, type BaseShoppingContainerData, type ShoppingContainerTotal, BaseShoppingContainerModel as default };
@@ -1,2 +1,2 @@
1
- 'use strict';var a=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){this.customFields={...t.customFields},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};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}};var c=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 g={"en-IN":"en","kn-IN":"kn"};var b={IN:"INR"},A={INR:"\u20B9"};var m=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 "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 "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 h=class{id;productKey;variantId;name;attributes;specifications;primaryImage;subItems;totalQuantity;basePrice;priceTotals;priceTiers;constructor(t){this.id=t.id,this.productKey=t.productKey,this.variantId=t.variantId,this.name={...t.name},this.attributes={...t.attributes},this.specifications={...t.specifications},this.primaryImage=new m(t.primaryImage),this.subItems=t.subItems.map(e=>({...e})),this.basePrice={...t.basePrice},this.priceTiers=t.priceTiers.map(e=>({...e})),this.totalQuantity=0,this.priceTotals={subtotal:0,mrpTotal:0},this.recalculateTotalQuantity(),this.recalculatePriceTotal();}getId(){return this.id}getProductKey(){return this.productKey}getVariantId(){return this.variantId}getName(t){return t?this.name[t]??this.name[g[t]]??this.name.en:{...this.name}}getAttributes(){return {...this.attributes}}getSpecifications(t){return t?this.specifications[t]??this.specifications[g[t]]??this.specifications.en:JSON.parse(JSON.stringify(this.specifications))}getImage(){return this.primaryImage}getSubItems(){return this.subItems.map(t=>({...t}))}getTotalQuantity(){return this.totalQuantity}getBasePrice(){return {...this.basePrice}}getPriceTotals(){return {...this.priceTotals}}getPriceTiers(){return this.priceTiers.map(t=>({...t}))}recalculateTotalQuantity(){this.totalQuantity=this.subItems.reduce((t,e)=>t+e.quantity,0);}recalculatePriceTotal(){let t=this.totalQuantity,e=this.basePrice.unitPrice,i=null;for(let r of this.priceTiers.sort((s,o)=>o.minQuantity-s.minQuantity))if(t>=r.minQuantity){i=r;break}i&&(e=i.unitPrice),this.priceTotals.mrpTotal=this.basePrice.unitPrice*t,this.priceTotals.subtotal=e*t;}getDetails(){return {id:this.getId(),productKey:this.getProductKey(),variantId:this.getVariantId(),name:this.getName(),attributes:this.getAttributes(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),totalQuantity:this.getTotalQuantity(),basePrice:this.getBasePrice(),priceTotals:this.getPriceTotals(),priceTiers:this.getPriceTiers()}}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),this.recalculateTotalQuantity(),this.recalculatePriceTotal();}clearLineItem(){this.id="",this.productKey="",this.variantId="",this.name={en:""},this.attributes={color:{name:"",hex:""}},this.primaryImage=new m({sources:{original:""}}),this.subItems=[],this.recalculateTotalQuantity(),this.recalculatePriceTotal();}};var l=class n{price;country;constructor(t,e){if(this.country=e,t<0)throw new Error("InvalidPrice: Price cannot be negative.");this.price=t;}getCountry(){return this.country}getRoundedPrice(){return n.getRoundedPrice(this.price,this.country)}getFormattedString(t){return n.getFormattedString(this.price,this.country,t)}static getFormattedString(t,e,i,r={}){let s=r.displayAsInteger??!1,o=b[e];if(o===void 0)throw new Error("Currency mapping not found for CountryCode");let u=t,d=s?0:n.getDecimalPlaces(o),I={style:r.style??"currency",currency:o,signDisplay:"never",currencyDisplay:r.currencyDisplay,minimumFractionDigits:d,maximumFractionDigits:d};s&&(u=Math.round(u));try{return new Intl.NumberFormat(i,I).format(u)}catch(C){return console.error(`Error formatting price for country "${e}" and currency "${o}":`,C),`${A[o]??o} ${n.addThousandSeparators(u.toFixed(d))}`}}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 getRoundedPrice(t,e){if(t<0)throw new Error("Price cannot be negative for rounding.");let i=b[e];if(i===void 0)throw new Error(`Currency mapping not found for CountryCode: ${e}`);let r=n.getDecimalPlaces(i),s=Math.pow(10,r);return Math.round(t*s)/s}static getCurrency(t){return b[t]}};var y=class extends a{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(t,e=new Date){super(t,e),this.couponCode=t.couponCode,this.name={...t.name},this.description={...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=t.minCartValue.map(i=>({...i})),this.maxCartDiscount=t.maxCartDiscount.map(i=>({...i})),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.applicableTo=t.applicableTo,this.category=t.category;}getCode(){return this.couponCode}getName(t){return t?this.name[t]??this.name[g[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[g[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.find(e=>e.country===t):this.minCartValue}getMaxCartDiscount(t){return t?this.maxCartDiscount.find(e=>e.country===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:this.getMinCartValue(),maxCartDiscount:this.getMaxCartDiscount(),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}};var f=class extends a{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 h(i)),this.billingAddress=t.billingAddress?new c(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new c(t.shippingAddress,e):null,this.coupons=(t.coupons||[]).map(i=>new y(i)),this.shippingDetails=t.shippingDetails?{...t.shippingDetails}:null,this.total={shipping:t.total?.shipping||0,effectiveShipping:t.total?.effectiveShipping??t.total?.shipping??0,subtotal:t.total?.subtotal||0,mrpTotal:t.total?.mrpTotal||0,couponTotal:t.total?.couponTotal||{},grandTotal:t.total?.grandTotal||0};}recalculateBaseTotals(){this.total.subtotal=l.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=l.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().mrpTotal,0),this.country);}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new h(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new c(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new c(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons.map(t=>new y(t.getDetails()))}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {...this.total,couponTotal:{...this.total.couponTotal}}}calculateApplicableCouponDiscount(t,e=!0){if(e&&!t.isActive())return 0;let i=t.getMinCartValue(this.country),r=t.getMaxCartDiscount(this.country);if(!i||this.total.subtotal<i.price||!r||r.price<0)return 0;let s=t.getCategory(),o=t.getDiscountMethod(),u=0,d=s==="SHIPPING"?this.total.shipping:this.total.subtotal;if(d<=0)return 0;switch(o){case"flat":let C=r?.price??0;u=Math.min(d,C);break;case"percentage":u=d*(t.getPercentageValue()/100);break;default:return 0}let I=Math.min(u,r.price);return l.getRoundedPrice(Math.max(0,I),this.country)}recalculateCouponTotals(t=!0){this.total.couponTotal={};let e=0;return this.coupons.forEach(i=>{let r=this.calculateApplicableCouponDiscount(i,t);r>0&&(this.total.couponTotal[i.getCode()]=r,e+=r);}),l.getRoundedPrice(e,this.country)}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:this.getTotal(),country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}};module.exports=f;//# sourceMappingURL=ShoppingContainer.js.map
1
+ 'use strict';var at=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var at__default=/*#__PURE__*/_interopDefault(at);var f=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){this.customFields={...t.customFields},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,o){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:o};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}};var A=class extends f{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 N=new Uint8Array(256),E=N.length;function Y(){return E>N.length-16&&(at__default.default.randomFillSync(N),E=0),N.slice(E,E+=16)}var tt=/^(?:[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 ct(r){return typeof r=="string"&&tt.test(r)}var et=ct;var m=[];for(let r=0;r<256;++r)m.push((r+256).toString(16).slice(1));function R(r,t=0){return m[r[t+0]]+m[r[t+1]]+m[r[t+2]]+m[r[t+3]]+"-"+m[r[t+4]]+m[r[t+5]]+"-"+m[r[t+6]]+m[r[t+7]]+"-"+m[r[t+8]]+m[r[t+9]]+"-"+m[r[t+10]]+m[r[t+11]]+m[r[t+12]]+m[r[t+13]]+m[r[t+14]]+m[r[t+15]]}function ut(r){if(!et(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 it=ut;function lt(r){r=unescape(encodeURIComponent(r));let t=[];for(let e=0;e<r.length;++e)t.push(r.charCodeAt(e));return t}var dt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",gt="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Z(r,t,e){function i(o,n,s,d){var u;if(typeof o=="string"&&(o=lt(o)),typeof n=="string"&&(n=it(n)),((u=n)===null||u===void 0?void 0:u.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+o.length);if(c.set(n),c.set(o,n.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,s){d=d||0;for(let h=0;h<16;++h)s[d+h]=c[h];return s}return R(c)}try{i.name=r;}catch{}return i.DNS=dt,i.URL=gt,i}var X={randomUUID:at__default.default.randomUUID};function mt(r,t,e){if(X.randomUUID&&!t&&!r)return X.randomUUID();r=r||{};let i=r.random||(r.rng||Y)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){e=e||0;for(let o=0;o<16;++o)t[e+o]=i[o];return t}return R(i)}var W=mt;function yt(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),at__default.default.createHash("sha1").update(r).digest()}var rt=yt;var ft=Z("v5",80,rt),J=ft;var C={"en-IN":"en","kn-IN":"kn"};var ot={INR:"\u20B9"},nt={INR:"en-IN"};var U=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},O=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},B=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},z=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},F=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},V=class extends Error{constructor(t="Pricing details not available for the product"){super(`NotFound: ${t}`),this.name="PricingNotFoundError";}},G=class extends Error{constructor(t="Tax rule category mismatch."){super(`InvalidTaxRule: ${t}`),this.name="InvalidTaxRuleError";}},k=class extends Error{constructor(t="Tax category is not valid."){super(`InvalidTaxCategory: ${t}`),this.name="InvalidTaxCategoryError";}},$=class extends Error{constructor(t="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${t}`),this.name="InvalidMinQuantityError";}},q=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},K=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},Q=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}},H=class extends Error{constructor(t="No applicable tax slab or multiple slabs found for the given unit price."){super(`TaxSlabNotFound: ${t}`),this.name="TaxSlabNotFoundError";}},M=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},D=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},I=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},y=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},L=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}};var x=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 L("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 L("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{amount;currency;constructor(t){if(t.amount<0)throw new M("Amount cannot be negative.");if(!t.currency)throw new D("Currency code is required.");this.amount=t.amount,this.currency=t.currency;}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(t){if(t instanceof r){if(this.currency!==t.getCurrency())throw new I("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return this.amount-t.getAmount()}add(t){if(t instanceof r){if(this.currency!==t.getCurrency())throw new I("Cannot add prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return new r({amount:this.amount+t.getAmount(),currency:this.currency})}subtract(t){if(t instanceof r){if(this.currency!==t.getCurrency())throw new I("Cannot subtract prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return new r({amount:this.amount-t.getAmount(),currency:this.currency})}multiply(t){if(t instanceof r){if(this.currency!==t.getCurrency())throw new I("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 y("Must be a non-negative number.")}divide(t){if(t instanceof r){if(this.currency!==t.getCurrency())throw new I("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 y("Must be a positive number.")}min(...t){if(t.length===0)throw new y("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(i instanceof r){if(e.getCurrency()!==i.getCurrency())throw new I("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i})}max(...t){if(t.length===0)throw new y("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(i instanceof r){if(e.getCurrency()!==i.getCurrency())throw new I("Cannot compare prices in different currencies.")}else throw new y("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)}static getFormattedString(t,e,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let o=nt[e];if(!e||!o)throw new D("Invalid currency code for formatting.");let n=t,s=i.displayAsInteger?0:r.getDecimalPlaces(e),d={style:i.style??"currency",currency:e,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:s,maximumFractionDigits:s};i.displayAsInteger&&(n=Math.ceil(n));try{return new Intl.NumberFormat(o,d).format(n)}catch(u){return console.error(`Error formatting price for currency "${e}" and locale "${o}":`,u),`${ot[e]??e} ${r.addThousandSeparators(n.toFixed(s))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),i=e[0],o=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+o}static getRoundedAmount(t,e){if(t<0)throw new M("Amount cannot be negative for rounding.");if(e===void 0)throw new D("Invalid currency code for rounding.");let i=r.getDecimalPlaces(e),o=Math.pow(10,i);return Math.round(t*o)/o}};var S=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new l(t.baseUnitPrice);if(!t.taxCategory)throw new k;let i=(t.tiers??[]).map(u=>({minQuantity:u.minQuantity,unitPrice:new l(u.unitPrice)})).sort((u,c)=>u.minQuantity-c.minQuantity);if(i.some(u=>u.minQuantity<=0))throw new $;let n=i.some(u=>u.unitPrice.getCurrency()!==e.getCurrency()),s=i.some((u,c)=>c>0&&u.unitPrice.compareTo(i[c-1].unitPrice)>0),d=i[0]?.unitPrice.compareTo(e)>0;if(n||s||d)throw new q("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 K;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity)return this.tiers[e];throw new Q(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 v=class r extends f{id;key;sku;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(t){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("|")}static parseSelectionAttributesKey(t){try{let e={},i=t.split("|");for(let o of i){let[n,s]=o.split(":");s.startsWith("c+")?e[n]={name:s.slice(2)}:e[n]=s;}return e}catch(e){throw new z(e?.message)}}constructor(t,e=new Date){super(t,e),this.id=t.id,this.key=t.key,this.sku=t.sku,this.name={...t.name},this.description={...t.description},this.slug={...t.slug},this.brand=t.brand,this.pricing=Object.keys(t.pricing).reduce((i,o)=>(t.pricing[o]&&(i[o]=new S(t.pricing[o])),i),{}),this.targetGender=t.targetGender,this.attributes=a.deepClone(t.attributes),this.specifications=a.deepClone(t.specifications),this.categories=a.deepClone(t.categories),this.variants=(t.variants||[]).map(i=>({selectionAttributes:i.selectionAttributes,images:{primary:new x(i.images.primary),gallery:(i.images.gallery||[]).map(o=>new x(o))}})),this.isActive=t.isActive,this.searchTags=t.searchTags?a.deepClone(t.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getSku(){return this.sku}getName(t){return t?this.name[t]??this.name[C[t]]??this.name.en:a.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[C[t]]??this.description.en:a.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[C[t]]??this.slug.en:a.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:this.pricing}getAttributes(){return a.deepClone(this.attributes)}getImagesBySelectionAttributes(t){let e=r.generateSelectionAttributesKey(t),i=this.variants.find(o=>r.generateSelectionAttributesKey(o.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 a.deepClone(this.categories)}getSpecifications(t){return t?a.deepClone(this.specifications[t]??this.specifications[C[t]]??this.specifications.en):a.deepClone(this.specifications)}getSearchTags(t){return t?a.deepClone(this.searchTags[t]??this.searchTags[C[t]]??this.searchTags.en):a.deepClone(this.searchTags)}getDetails(){let t=super.getDetails();return {id:this.getId(),key:this.getKey(),sku:this.getSku(),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=>({selectionAttributes:a.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}}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 bt={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?J(r,t):W(),generateSearchId:(r,t)=>`${r}#${v.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:r=>{let[t,e]=r.split("#");return {key:t,selectionAttribute:e}},deepClone(r){return structuredClone(r)}},a=bt;var j=class r extends f{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=a.deepClone(t.slabs),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 a.deepClone(this.slabs)}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),slabs:this.getSlabs(),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)}static getApplicableTaxRate(t,e){let i=t.getAmount(),o=e.filter(n=>(n.minUnitPrice===void 0||i>=n.minUnitPrice)&&(n.maxUnitPrice===void 0||i<n.maxUnitPrice));if(o.length!==1)throw new H;return o[0].rate}};var P=class{id;productKey;selectionAttribute;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){this.id=t.id,this.productKey=t.productKey,this.selectionAttribute=a.deepClone(t.selectionAttribute),this.name=a.deepClone(t.name),this.specifications=a.deepClone(t.specifications),this.primaryImage=new x(t.primaryImage),this.subItems=a.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new U(i.size);e.add(i.size);}),this.pricing={unitPrice:new l(t.pricing.unitPrice),tierPricing:new S(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:a.deepClone(t.pricing.tax.taxSlabs)}},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,o])=>[i,new l(o)])),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}getSelectionAttribute(){return a.deepClone(this.selectionAttribute)}getName(t){return t?a.deepClone(this.name[t]??this.name[C[t]]??this.name.en):a.deepClone(this.name)}getSpecifications(t){return t?a.deepClone(this.specifications[t]??this.specifications[C[t]]??this.specifications.en):a.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return a.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:a.deepClone(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(),selectionAttribute:this.getSelectionAttribute(),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:this.getPricing().tax},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()}}}addSubItems(t,e){t.forEach(i=>{let o=this.subItems.find(n=>n.size===i.size);o?o.quantity=e?o.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.selectionAttribute))throw new O;if(!t.getIsActive())throw new B;this.subItems.forEach(d=>{if(!t.validateSize(d.size))throw new F});let o=t.getPriceDetails(e);if(!o||o.getBaseUnitPrice().getCurrency()!==i)throw new V;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttribute).primary;let n=this.subItems.reduce((d,u)=>d+u.quantity,0),{unitPrice:s}=o.getApplicableTier(n);this.pricing={unitPrice:s,tierPricing:o,taxCategory:o.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 G;let e=this.total.taxableAmount.divide(this.total.quantity);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((b,p)=>b+p.quantity,0),{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),o=i.multiply(e),n=Object.values(this.total.discounts).reduce((b,p)=>b.add(p),t),s=o.subtract(n),d=s.divide(e),u=j.getApplicableTaxRate(d,this.pricing.tax.taxSlabs),c=s.multiply(u).round(),h=o.subtract(n).add(c);this.total={quantity:e,subtotal:o,taxableAmount:s,taxTotal:c,discounts:this.total.discounts,grandTotal:h};}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttribute={color:{name:""}},this.name={en:""},this.primaryImage=new x({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 w=class extends f{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=a.deepClone(t.name),this.description=a.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,o)=>{let n=t.minCartValue[o];return n&&(i[o]=new l(n)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,o)=>{let n=t.maxCartDiscount[o];return n&&(i[o]=new l(n)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new y("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,o,n=!0){let s=new l({amount:0,currency:o}),d;if(n&&!this.isActive())return s;let u=this.getMinCartValue(i),c=this.getMaxCartDiscount(i);if(!u||u.compareTo(t)>0||!c)return s;let h=this.getCategory(),b=this.getDiscountMethod(),p=h==="SHIPPING"?e:t;if(p.getAmount()<=0)return s;switch(b){case"flat":let st=c;d=p.min(st);break;case"percentage":d=p.multiply(this.getPercentageValue()/100).round();break;default:return s}return d.min(c)}};var _=class extends f{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 P(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 w(i)),this.shippingDetails=t.shippingDetails?a.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,o])=>[i,new l(o)])),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 P(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(p=>p.getState()!=="CANCELLED"),i=e.reduce((p,T)=>p.add(T.getTotal().subtotal),t),o=new l({amount:this.shippingDetails?.cost||0,currency:this.currency}).round(),n=t,s={},d={};this.coupons.forEach(p=>{let T=p.calculateApplicableCouponDiscount(i,o,this.country,this.currency);n=n.add(T),s[p.getCode()]=T,p.getCategory()!=="SHIPPING"&&(d[p.getCode()]=T);}),this.applyDiscountsInLineItem(d);let u=e.reduce((p,T)=>p.add(T.getTotal().taxTotal),t),c=this.coupons.find(p=>p.getCategory()==="SHIPPING"),h=c?o.subtract(s[c.getCode()]||t):o,b=i.add(o).add(u).subtract(n);this.total={subtotal:i,shipping:o,effectiveShipping:h,couponTotal:s,couponDiscountTotal:n,taxTotal:u,grandTotal:b};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let e=t.filter(o=>o.getCategory()==="SHIPPING"),i=t.filter(o=>o.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(o=>!o[1].isZero()),i=new Map;this.lineItems.forEach(o=>i.set(o.getId(),[])),e.forEach(([o,n])=>{let s=this.coupons.find(c=>c.getCode()===o);if(!s)return;let d=this.lineItems.filter(c=>c.getState()!=="CANCELLED"&&!c.getTotal().subtotal.isZero()).sort((c,h)=>c.getTotal().subtotal.compareTo(h.getTotal().subtotal)),u=new l({amount:0,currency:this.currency});d.forEach((c,h)=>{let b;h===d.length-1?b=n.subtract(u):b=n.multiply(c.getTotal().subtotal).divide(this.total.subtotal).round(),u=u.add(b),i.get(c.getId())?.push({coupon:s,amount:b});});}),this.lineItems.forEach(o=>{o.getState()==="CANCELLED"||this.total.subtotal.isZero()?o.updateDiscounts([]):o.updateDiscounts(i.get(o.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((n,s)=>{if(!n)return s;let d=s.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping),u=n.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping);return d===u?s.getType()==="coupon"?s:n:d>u?s:n}),o=i.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping);o.getAmount()>0&&(this.coupons.push(i),this.total.couponTotal[i.getCode()]=o,this.total.couponDiscountTotal=this.total.couponDiscountTotal.add(o),this.total.effectiveShipping=this.total.shipping.subtract(o));}}};module.exports=_;//# sourceMappingURL=ShoppingContainer.js.map
2
2
  //# sourceMappingURL=ShoppingContainer.js.map