b23-lib 3.0.5 → 3.0.7

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 (136) 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 +1 -1
  8. package/dist/Classes/Address.js.map +1 -1
  9. package/dist/Classes/Address.mjs +1 -1
  10. package/dist/Classes/Base.d.mts +1 -1
  11. package/dist/Classes/Base.d.ts +1 -1
  12. package/dist/Classes/Base.js +1 -1
  13. package/dist/Classes/Base.js.map +1 -1
  14. package/dist/Classes/Base.mjs +1 -1
  15. package/dist/Classes/Cart.d.mts +1 -1
  16. package/dist/Classes/Cart.d.ts +1 -1
  17. package/dist/Classes/Cart.js +1 -1
  18. package/dist/Classes/Cart.js.map +1 -1
  19. package/dist/Classes/Cart.mjs +1 -1
  20. package/dist/Classes/Cart.mjs.map +1 -1
  21. package/dist/Classes/Charge.d.mts +11 -1
  22. package/dist/Classes/Charge.d.ts +11 -1
  23. package/dist/Classes/Charge.js +1 -1
  24. package/dist/Classes/Charge.js.map +1 -1
  25. package/dist/Classes/Charge.mjs +1 -1
  26. package/dist/Classes/Common.d.mts +1 -1
  27. package/dist/Classes/Common.d.ts +1 -1
  28. package/dist/Classes/Coupon.d.mts +1 -1
  29. package/dist/Classes/Coupon.d.ts +1 -1
  30. package/dist/Classes/Coupon.js +1 -1
  31. package/dist/Classes/Coupon.js.map +1 -1
  32. package/dist/Classes/Coupon.mjs +1 -1
  33. package/dist/Classes/Customer.d.mts +1 -1
  34. package/dist/Classes/Customer.d.ts +1 -1
  35. package/dist/Classes/Customer.js +1 -1
  36. package/dist/Classes/Customer.js.map +1 -1
  37. package/dist/Classes/Customer.mjs +1 -1
  38. package/dist/Classes/Customer.mjs.map +1 -1
  39. package/dist/Classes/CustomerAddress.d.mts +1 -1
  40. package/dist/Classes/CustomerAddress.d.ts +1 -1
  41. package/dist/Classes/CustomerAddress.js +1 -1
  42. package/dist/Classes/CustomerAddress.js.map +1 -1
  43. package/dist/Classes/CustomerAddress.mjs +1 -1
  44. package/dist/Classes/CustomerAddress.mjs.map +1 -1
  45. package/dist/Classes/Inventory.d.mts +1 -1
  46. package/dist/Classes/Inventory.d.ts +1 -1
  47. package/dist/Classes/Inventory.js +1 -1
  48. package/dist/Classes/Inventory.js.map +1 -1
  49. package/dist/Classes/Inventory.mjs +1 -1
  50. package/dist/Classes/Inventory.mjs.map +1 -1
  51. package/dist/Classes/LineItem.d.mts +1 -1
  52. package/dist/Classes/LineItem.d.ts +1 -1
  53. package/dist/Classes/LineItem.js +1 -1
  54. package/dist/Classes/LineItem.js.map +1 -1
  55. package/dist/Classes/LineItem.mjs +1 -1
  56. package/dist/Classes/Order.d.mts +5 -5
  57. package/dist/Classes/Order.d.ts +5 -5
  58. package/dist/Classes/Order.js +1 -1
  59. package/dist/Classes/Order.js.map +1 -1
  60. package/dist/Classes/Order.mjs +1 -1
  61. package/dist/Classes/Order.mjs.map +1 -1
  62. package/dist/Classes/Payment.d.mts +1 -1
  63. package/dist/Classes/Payment.d.ts +1 -1
  64. package/dist/Classes/Payment.js +1 -1
  65. package/dist/Classes/Payment.js.map +1 -1
  66. package/dist/Classes/Payment.mjs +1 -1
  67. package/dist/Classes/Payment.mjs.map +1 -1
  68. package/dist/Classes/Price.d.mts +1 -1
  69. package/dist/Classes/Price.d.ts +1 -1
  70. package/dist/Classes/Product.d.mts +1 -1
  71. package/dist/Classes/Product.d.ts +1 -1
  72. package/dist/Classes/Product.js +1 -1
  73. package/dist/Classes/Product.js.map +1 -1
  74. package/dist/Classes/Product.mjs +1 -1
  75. package/dist/Classes/ShoppingContainer.d.mts +43 -2
  76. package/dist/Classes/ShoppingContainer.d.ts +43 -2
  77. package/dist/Classes/ShoppingContainer.js +1 -1
  78. package/dist/Classes/ShoppingContainer.js.map +1 -1
  79. package/dist/Classes/ShoppingContainer.mjs +1 -1
  80. package/dist/Classes/TaxRule.d.mts +5 -9
  81. package/dist/Classes/TaxRule.d.ts +5 -9
  82. package/dist/Classes/TaxRule.js +1 -1
  83. package/dist/Classes/TaxRule.js.map +1 -1
  84. package/dist/Classes/TaxRule.mjs +1 -1
  85. package/dist/Classes/TieredPrice.d.mts +1 -1
  86. package/dist/Classes/TieredPrice.d.ts +1 -1
  87. package/dist/Classes/TieredPrice.js +1 -1
  88. package/dist/Classes/TieredPrice.js.map +1 -1
  89. package/dist/Classes/TieredPrice.mjs +1 -1
  90. package/dist/{Common-Bd8Xv8x4.d.mts → Common-XM4zQpWC.d.mts} +1 -1
  91. package/dist/{Common-CXp_zjft.d.ts → Common-uAn7Sunn.d.ts} +1 -1
  92. package/dist/chunk-GJ2DSRIP.mjs +2 -0
  93. package/dist/chunk-GJ2DSRIP.mjs.map +1 -0
  94. package/dist/chunk-HKXV6QWV.mjs +2 -0
  95. package/dist/chunk-HKXV6QWV.mjs.map +1 -0
  96. package/dist/chunk-IQNK7EEI.mjs +2 -0
  97. package/dist/chunk-IQNK7EEI.mjs.map +1 -0
  98. package/dist/chunk-L3CNGDFJ.mjs +2 -0
  99. package/dist/chunk-L3CNGDFJ.mjs.map +1 -0
  100. package/dist/{chunk-YSUBOEFT.mjs → chunk-R3ZADSUJ.mjs} +2 -2
  101. package/dist/{chunk-YSUBOEFT.mjs.map → chunk-R3ZADSUJ.mjs.map} +1 -1
  102. package/dist/chunk-RHSKHT5F.mjs +2 -0
  103. package/dist/chunk-RHSKHT5F.mjs.map +1 -0
  104. package/dist/chunk-URFRPQCT.mjs +2 -0
  105. package/dist/chunk-URFRPQCT.mjs.map +1 -0
  106. package/dist/chunk-XBFSNBKL.mjs +2 -0
  107. package/dist/chunk-XBFSNBKL.mjs.map +1 -0
  108. package/dist/index.d.mts +1 -1
  109. package/dist/index.d.ts +1 -1
  110. package/dist/index.js +2 -2
  111. package/dist/index.js.map +1 -1
  112. package/dist/index.mjs +1 -1
  113. package/dist/index.mjs.map +1 -1
  114. package/package.json +1 -11
  115. package/dist/Classes/TaxCategory.d.mts +0 -42
  116. package/dist/Classes/TaxCategory.d.ts +0 -42
  117. package/dist/Classes/TaxCategory.js +0 -2
  118. package/dist/Classes/TaxCategory.js.map +0 -1
  119. package/dist/Classes/TaxCategory.mjs +0 -2
  120. package/dist/Classes/TaxCategory.mjs.map +0 -1
  121. package/dist/chunk-2HBQ3C6V.mjs +0 -2
  122. package/dist/chunk-2HBQ3C6V.mjs.map +0 -1
  123. package/dist/chunk-2ZQIRKRB.mjs +0 -2
  124. package/dist/chunk-2ZQIRKRB.mjs.map +0 -1
  125. package/dist/chunk-4KMF3LE7.mjs +0 -2
  126. package/dist/chunk-4KMF3LE7.mjs.map +0 -1
  127. package/dist/chunk-6KCJVEZD.mjs +0 -2
  128. package/dist/chunk-6KCJVEZD.mjs.map +0 -1
  129. package/dist/chunk-GF3OGUDE.mjs +0 -2
  130. package/dist/chunk-GF3OGUDE.mjs.map +0 -1
  131. package/dist/chunk-HR5HHV6O.mjs +0 -2
  132. package/dist/chunk-HR5HHV6O.mjs.map +0 -1
  133. package/dist/chunk-SNDTKUMW.mjs +0 -2
  134. package/dist/chunk-SNDTKUMW.mjs.map +0 -1
  135. package/dist/chunk-Y5D6RHTJ.mjs +0 -2
  136. package/dist/chunk-Y5D6RHTJ.mjs.map +0 -1
@@ -1,2 +1,2 @@
1
- import {a}from'../chunk-4KMF3LE7.mjs';import'../chunk-2ZQIRKRB.mjs';import'../chunk-GF3OGUDE.mjs';import'../chunk-YSUBOEFT.mjs';import'../chunk-SNDTKUMW.mjs';import'../chunk-2HBQ3C6V.mjs';import {b}from'../chunk-Y5D6RHTJ.mjs';import'../chunk-HR5HHV6O.mjs';import'../chunk-XHGUVYQO.mjs';import'../chunk-FC4P26U3.mjs';import'../chunk-RSTZJZSQ.mjs';import {a as a$1}from'../chunk-XPKK6DFA.mjs';import'../chunk-6KCJVEZD.mjs';var u=(i=>(i.ACTIVE="ACTIVE",i.FROZEN="FROZEN",i.MERGED="MERGED",i.ORDERED="ORDERED",i))(u||{}),p={expiresAtInSeconds:120*24*60*60},c=class extends a{state;expireAt;config;constructor(t,e=new Date,r=p){super(t,e),this.state=t.state,this.expireAt=t.expireAt&&typeof t.expireAt=="number"?t.expireAt:Math.floor(e.getTime()/1e3)+r.expiresAtInSeconds,this.config=r;}getState(){return this.state}getExpireAt(){return this.expireAt}isActive(){let t=Math.ceil(Date.now()/1e3);return this.state==="ACTIVE"&&this.expireAt>t}clearCartItems(){this.lineItems=[],this.coupons=[],this.shippingDetails=null,this.total.discounts={},this.calculateTotals();}validateLineItems(t){this.lineItems=this.lineItems.map(e=>{try{e.updateProductData(t[e.getProductKey()],this.country,this.currency);}catch(r){console.error(`Error recalculating line item ${e.getId()}:`,r),e.clearLineItem();}return e}).filter(e=>e.getId()),this.calculateTotals();}addLineItem(t){let e=t.getProductKey(),r=t.getSelectionAttributes(),i=b.generateSelectionAttributesKey(r),s=this.lineItems.findIndex(n=>n.getProductKey()===e&&b.generateSelectionAttributesKey(n.getSelectionAttributes())===i);return s>=0?this.lineItems[s].addSubItems(t.getSubItems(),!0):this.lineItems.push(t),this.calculateTotals(),s>=0?s:this.lineItems.length-1}updateLineItem(t,e,r){let i=this.lineItems,s=i.findIndex(n=>n.getId()===t);if(s<0)throw new a$1(t);return i[s].addSubItems([{size:e,quantity:r}],!1),this.calculateTotals(),s}removeLineItem(t){let r=this.lineItems.findIndex(i=>i.getId()===t);if(r<0)throw new a$1(t);return this.lineItems.splice(r,1),this.charges=this.charges.filter(i=>i.getLineItemId()!==t),this.calculateTotals(),r}getDetails(){return {...super.getDetails(),state:this.getState(),expireAt:this.getExpireAt()}}};export{u as CartState,p as DEFAULT_CART_CONFIG,c as default};//# sourceMappingURL=Cart.mjs.map
1
+ import {a}from'../chunk-URFRPQCT.mjs';import'../chunk-RHSKHT5F.mjs';import'../chunk-R3ZADSUJ.mjs';import'../chunk-GJ2DSRIP.mjs';import'../chunk-L3CNGDFJ.mjs';import'../chunk-IQNK7EEI.mjs';import {d}from'../chunk-HKXV6QWV.mjs';import'../chunk-XBFSNBKL.mjs';import'../chunk-XHGUVYQO.mjs';import'../chunk-FC4P26U3.mjs';import'../chunk-RSTZJZSQ.mjs';import {a as a$1}from'../chunk-XPKK6DFA.mjs';var u=(i=>(i.ACTIVE="ACTIVE",i.FROZEN="FROZEN",i.MERGED="MERGED",i.ORDERED="ORDERED",i))(u||{}),p={expiresAtInSeconds:120*24*60*60},c=class extends a{state;expireAt;config;constructor(t,e=new Date,r=p){super(t,e),this.state=t.state,this.expireAt=t.expireAt&&typeof t.expireAt=="number"?t.expireAt:Math.floor(e.getTime()/1e3)+r.expiresAtInSeconds,this.config=r;}getState(){return this.state}getExpireAt(){return this.expireAt}isActive(){let t=Math.ceil(Date.now()/1e3);return this.state==="ACTIVE"&&this.expireAt>t}clearCartItems(){this.lineItems=[],this.coupons=[],this.shippingDetails=null,this.total.discounts={},this.calculateTotals();}validateLineItems(t){this.lineItems=this.lineItems.map(e=>{try{e.updateProductData(t[e.getProductKey()],this.country,this.currency);}catch(r){console.error(`Error recalculating line item ${e.getId()}:`,r),e.clearLineItem();}return e}).filter(e=>e.getId()),this.calculateTotals();}addLineItem(t){let e=t.getProductKey(),r=t.getSelectionAttributes(),i=d.generateSelectionAttributesKey(r),s=this.lineItems.findIndex(n=>n.getProductKey()===e&&d.generateSelectionAttributesKey(n.getSelectionAttributes())===i);return s>=0?this.lineItems[s].addSubItems(t.getSubItems(),!0):this.lineItems.push(t),this.calculateTotals(),s>=0?s:this.lineItems.length-1}updateLineItem(t,e,r){let i=this.lineItems,s=i.findIndex(n=>n.getId()===t);if(s<0)throw new a$1(t);return i[s].addSubItems([{size:e,quantity:r}],!1),this.calculateTotals(),s}removeLineItem(t){let r=this.lineItems.findIndex(i=>i.getId()===t);if(r<0)throw new a$1(t);return this.lineItems.splice(r,1),this.charges=this.charges.filter(i=>i.getLineItemId()!==t),this.calculateTotals(),r}getDetails(){return {...super.getDetails(),state:this.getState(),expireAt:this.getExpireAt()}}};export{u as CartState,p as DEFAULT_CART_CONFIG,c as default};//# sourceMappingURL=Cart.mjs.map
2
2
  //# sourceMappingURL=Cart.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/Classes/Cart.ts"],"names":["CartState","DEFAULT_CART_CONFIG","CartModel","BaseShoppingContainerModel","data","date","config","nowSeconds","products","lineItem","error","newLineItem","productKey","selectionAttributes","selectionAttributeKey","ProductModel","index","item","lineItemId","size","quantity","lineItems","LineItemNotFoundError","charge"],"mappings":"qaAKO,IAAKA,OACVA,CAAA,CAAA,MAAA,CAAS,QACTA,CAAAA,CAAAA,CAAA,OAAS,QACTA,CAAAA,CAAAA,CAAA,MAAS,CAAA,QAAA,CACTA,EAAA,OAAU,CAAA,SAAA,CAJAA,OAAA,EAwBCC,CAAAA,CAAAA,CAAAA,CAAkC,CAC7C,kBAAoB,CAAA,GAAA,CAAM,EAAK,CAAA,EAAA,CAAK,EACtC,CAEqBC,CAAAA,CAAAA,CAArB,cAAuCC,CAA2B,CACtD,MACA,QACA,CAAA,MAAA,CAEV,WAAYC,CAAAA,CAAAA,CAAsBC,EAAa,IAAI,IAAA,CAAQC,EAAqBL,CAAqB,CAAA,CACnG,MAAMG,CAAMC,CAAAA,CAAI,CAChB,CAAA,IAAA,CAAK,MAAQD,CAAK,CAAA,KAAA,CAClB,KAAK,QAAWA,CAAAA,CAAAA,CAAK,UAAY,OAAOA,CAAAA,CAAK,QAAa,EAAA,QAAA,CAAWA,EAAK,QAAW,CAAA,IAAA,CAAK,MAAMC,CAAK,CAAA,OAAA,GAAY,GAAI,CAAA,CAAIC,CAAO,CAAA,kBAAA,CAChI,KAAK,MAASA,CAAAA,EAChB,CAMO,QAAsB,EAAA,CAC3B,OAAO,IAAK,CAAA,KACd,CAMO,WAAA,EAAsB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,MAAM,UAAW,EAAA,CACpB,KAAO,CAAA,IAAA,CAAK,UACZ,CAAA,QAAA,CAAU,KAAK,WAAY,EAC7B,CACF,CACF","file":"Cart.mjs","sourcesContent":["import { LineItemNotFoundError } from \"./Error\";\r\nimport LineItemModel from \"./LineItem\";\r\nimport ProductModel from \"./Product\";\r\nimport BaseShoppingContainerModel, { BaseShoppingContainerAttributes, BaseShoppingContainerData } from \"./ShoppingContainer\";\r\n\r\nexport enum CartState {\r\n ACTIVE = \"ACTIVE\",\r\n FROZEN = \"FROZEN\",\r\n MERGED = \"MERGED\",\r\n ORDERED = \"ORDERED\"\r\n}\r\n\r\n/**\r\n * Input attributes for creating or updating a CartModel.\r\n */\r\nexport type CartAttributes = BaseShoppingContainerAttributes & {\r\n state: CartState;\r\n expireAt: number;\r\n};\r\n\r\nexport type CartData = BaseShoppingContainerData & {\r\n state: CartState;\r\n expireAt: number;\r\n};\r\n\r\nexport type CartConfig = {\r\n expiresAtInSeconds: number;\r\n}\r\n\r\nexport const DEFAULT_CART_CONFIG: CartConfig = {\r\n expiresAtInSeconds: 120 * 24 * 60 * 60\r\n}\r\n\r\nexport default class CartModel extends BaseShoppingContainerModel {\r\n protected state: CartState;\r\n protected expireAt: number;\r\n protected config: CartConfig;\r\n\r\n constructor(data: CartAttributes, date: Date = new Date(), config: CartConfig = DEFAULT_CART_CONFIG) {\r\n super(data, date);\r\n this.state = data.state;\r\n this.expireAt = data.expireAt && typeof data.expireAt === 'number' ? data.expireAt : Math.floor(date.getTime() / 1000) + config.expiresAtInSeconds;\r\n this.config = config;\r\n }\r\n\r\n /**\r\n * Gets the current state of the cart (e.g., ACTIVE, ORDERED).\r\n * @returns The CartState enum value.\r\n */\r\n public getState(): CartState {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the timestamp when the cart expires.\r\n * @returns The expiration timestamp in seconds (Unix epoch).\r\n */\r\n public getExpireAt(): number {\r\n return this.expireAt;\r\n }\r\n\r\n /**\r\n * Checks if the cart is currently active and not expired.\r\n * @returns True if active and not expired, false otherwise.\r\n */\r\n public isActive(): boolean {\r\n const nowSeconds = Math.ceil(Date.now() / 1000);\r\n return this.state === CartState.ACTIVE && (this.expireAt > nowSeconds);\r\n }\r\n\r\n /**\r\n * Clears all line items, coupons, and shipping details from the cart and resets totals.\r\n */\r\n public clearCartItems() {\r\n this.lineItems = [];\r\n this.coupons = [];\r\n this.shippingDetails = null;\r\n this.total.discounts = {};\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Validates line items against the current product catalog.\r\n * Updates product data for each item and removes invalid items.\r\n * @param products - A record map of ProductModels keyed by product ID/key.\r\n */\r\n public validateLineItems(products: Record<string, ProductModel>): void {\r\n this.lineItems = this.lineItems.map(lineItem => {\r\n try {\r\n lineItem.updateProductData(products[lineItem.getProductKey()], this.country, this.currency);\r\n } catch (error) {\r\n console.error(`Error recalculating line item ${lineItem.getId()}:`, error);\r\n lineItem.clearLineItem();\r\n }\r\n return lineItem;\r\n }).filter(lineItem => lineItem.getId());\r\n\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Adds a new line item or updates the quantity of an existing one.\r\n * @param newLineItem The LineItemModel to add.\r\n * @returns The index of the added/updated line item in the internal array.\r\n */\r\n public addLineItem(newLineItem: LineItemModel) {\r\n const productKey = newLineItem.getProductKey();\r\n const selectionAttributes = newLineItem.getSelectionAttributes();\r\n const selectionAttributeKey = ProductModel.generateSelectionAttributesKey(selectionAttributes);\r\n let index = this.lineItems.findIndex(\r\n (item) => item.getProductKey() === productKey && ProductModel.generateSelectionAttributesKey(item.getSelectionAttributes()) === selectionAttributeKey\r\n );\r\n\r\n if (index >= 0) {\r\n this.lineItems[index].addSubItems(newLineItem.getSubItems(), true);\r\n } else {\r\n this.lineItems.push(newLineItem);\r\n }\r\n\r\n this.calculateTotals();\r\n return index >= 0 ? index : this.lineItems.length - 1;\r\n }\r\n\r\n /**\r\n * Updates the quantity for a specific size within a line item.\r\n * @param lineItemId The ID of the LineItemModel to update.\r\n * @param size The size identifier within the line item.\r\n * @param quantity The new quantity for the size (0 to remove).\r\n * @returns The index of the updated line item.\r\n * @throws {Error} If the line item is not found.\r\n */\r\n public updateLineItem(lineItemId: string, size: string, quantity: number) {\r\n const lineItems = this.lineItems;\r\n let index = lineItems.findIndex((item) => item.getId() === lineItemId);\r\n\r\n if (index < 0) {\r\n throw new LineItemNotFoundError(lineItemId);\r\n }\r\n\r\n lineItems[index].addSubItems([{ size, quantity }], false);\r\n this.calculateTotals();\r\n\r\n return index;\r\n }\r\n\r\n /**\r\n * Removes a line item completely from the cart.\r\n * @param lineItemId The ID of the LineItemModel to remove.\r\n * @returns The index the item previously occupied.\r\n * @throws {Error} If the line item is not found.\r\n */\r\n public removeLineItem(lineItemId: string) {\r\n const lineItems = this.lineItems;\r\n const index = lineItems.findIndex((item) => item.getId() === lineItemId);\r\n\r\n if (index < 0) {\r\n throw new LineItemNotFoundError(lineItemId);\r\n }\r\n\r\n this.lineItems.splice(index, 1);\r\n this.charges = this.charges.filter(charge => charge.getLineItemId() !== lineItemId);\r\n this.calculateTotals();\r\n\r\n return index;\r\n }\r\n\r\n getDetails(): CartData {\r\n return {\r\n ...super.getDetails(),\r\n state: this.getState(),\r\n expireAt: this.getExpireAt(),\r\n }\r\n }\r\n}\r\n"]}
1
+ {"version":3,"sources":["../../src/Classes/Cart.ts"],"names":["CartState","DEFAULT_CART_CONFIG","CartModel","BaseShoppingContainerModel","data","date","config","nowSeconds","products","lineItem","error","newLineItem","productKey","selectionAttributes","selectionAttributeKey","ProductModel","index","item","lineItemId","size","quantity","lineItems","LineItemNotFoundError","charge"],"mappings":"uYAKO,IAAKA,OACVA,CAAA,CAAA,MAAA,CAAS,QACTA,CAAAA,CAAAA,CAAA,OAAS,QACTA,CAAAA,CAAAA,CAAA,MAAS,CAAA,QAAA,CACTA,EAAA,OAAU,CAAA,SAAA,CAJAA,OAAA,EAwBCC,CAAAA,CAAAA,CAAAA,CAAkC,CAC7C,kBAAoB,CAAA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AG,EAAM,QAAAC,CAAAA,CAAS,CAAC,CAAG,CAAA,CAAA,CAAK,EACxD,IAAK,CAAA,eAAA,EAEEJ,CAAAA,CACT,CAQO,cAAeE,CAAAA,CAAAA,CAAoB,CAExC,IAAMF,CAAAA,CADY,KAAK,SACC,CAAA,SAAA,CAAWC,CAASA,EAAAA,CAAAA,CAAK,OAAYC,GAAAA,CAAU,EAEvE,GAAIF,CAAAA,CAAQ,EACV,MAAM,IAAIM,GAAsBJ,CAAAA,CAAU,EAG5C,OAAK,IAAA,CAAA,SAAA,CAAU,OAAOF,CAAO,CAAA,CAAC,EAC9B,IAAK,CAAA,OAAA,CAAU,IAAK,CAAA,OAAA,CAAQ,OAAOO,CAAUA,EAAAA,CAAAA,CAAO,eAAoBL,GAAAA,CAAU,EAClF,IAAK,CAAA,eAAA,EAEEF,CAAAA,CACT,CAEA,UAAuB,EAAA,CACrB,OAAO,CACL,GAAG,MAAM,UAAW,EAAA,CACpB,KAAO,CAAA,IAAA,CAAK,UACZ,CAAA,QAAA,CAAU,KAAK,WAAY,EAC7B,CACF,CACF","file":"Cart.mjs","sourcesContent":["import { LineItemNotFoundError } from \"./Error\";\r\nimport LineItemModel from \"./LineItem\";\r\nimport ProductModel from \"./Product\";\r\nimport BaseShoppingContainerModel, { BaseShoppingContainerAttributes, BaseShoppingContainerData } from \"./ShoppingContainer\";\r\n\r\nexport enum CartState {\r\n ACTIVE = \"ACTIVE\",\r\n FROZEN = \"FROZEN\",\r\n MERGED = \"MERGED\",\r\n ORDERED = \"ORDERED\"\r\n}\r\n\r\n/**\r\n * Input attributes for creating or updating a CartModel.\r\n */\r\nexport type CartAttributes = BaseShoppingContainerAttributes & {\r\n state: CartState;\r\n expireAt: number;\r\n};\r\n\r\nexport type CartData = BaseShoppingContainerData & {\r\n state: CartState;\r\n expireAt: number;\r\n};\r\n\r\nexport type CartConfig = {\r\n expiresAtInSeconds: number;\r\n}\r\n\r\nexport const DEFAULT_CART_CONFIG: CartConfig = {\r\n expiresAtInSeconds: 120 * 24 * 60 * 60\r\n}\r\n\r\nexport default class CartModel extends BaseShoppingContainerModel {\r\n protected state: CartState;\r\n protected expireAt: number;\r\n protected config: CartConfig;\r\n\r\n constructor(data: CartAttributes, date: Date = new Date(), config: CartConfig = DEFAULT_CART_CONFIG) {\r\n super(data, date);\r\n this.state = data.state;\r\n this.expireAt = data.expireAt && typeof data.expireAt === 'number' ? data.expireAt : Math.floor(date.getTime() / 1000) + config.expiresAtInSeconds;\r\n this.config = config;\r\n }\r\n\r\n /**\r\n * Gets the current state of the cart (e.g., ACTIVE, ORDERED).\r\n * @returns The CartState enum value.\r\n */\r\n public getState(): CartState {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the timestamp when the cart expires.\r\n * @returns The expiration timestamp in seconds (Unix epoch).\r\n */\r\n public getExpireAt(): number {\r\n return this.expireAt;\r\n }\r\n\r\n /**\r\n * Checks if the cart is currently active and not expired.\r\n * @returns True if active and not expired, false otherwise.\r\n */\r\n public isActive(): boolean {\r\n const nowSeconds = Math.ceil(Date.now() / 1000);\r\n return this.state === CartState.ACTIVE && (this.expireAt > nowSeconds);\r\n }\r\n\r\n /**\r\n * Clears all line items, coupons, and shipping details from the cart and resets totals.\r\n */\r\n public clearCartItems() {\r\n this.lineItems = [];\r\n this.coupons = [];\r\n this.shippingDetails = null;\r\n this.total.discounts = {};\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Validates line items against the current product catalog.\r\n * Updates product data for each item and removes invalid items.\r\n * @param products - A record map of ProductModels keyed by product ID/key.\r\n */\r\n public validateLineItems(products: Record<string, ProductModel>): void {\r\n this.lineItems = this.lineItems.map(lineItem => {\r\n try {\r\n lineItem.updateProductData(products[lineItem.getProductKey()], this.country, this.currency);\r\n } catch (error) {\r\n console.error(`Error recalculating line item ${lineItem.getId()}:`, error);\r\n lineItem.clearLineItem();\r\n }\r\n return lineItem;\r\n }).filter(lineItem => lineItem.getId());\r\n\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Adds a new line item or updates the quantity of an existing one.\r\n * @param newLineItem The LineItemModel to add.\r\n * @returns The index of the added/updated line item in the internal array.\r\n */\r\n public addLineItem(newLineItem: LineItemModel) {\r\n const productKey = newLineItem.getProductKey();\r\n const selectionAttributes = newLineItem.getSelectionAttributes();\r\n const selectionAttributeKey = ProductModel.generateSelectionAttributesKey(selectionAttributes);\r\n let index = this.lineItems.findIndex(\r\n (item) => item.getProductKey() === productKey && ProductModel.generateSelectionAttributesKey(item.getSelectionAttributes()) === selectionAttributeKey\r\n );\r\n\r\n if (index >= 0) {\r\n this.lineItems[index].addSubItems(newLineItem.getSubItems(), true);\r\n } else {\r\n this.lineItems.push(newLineItem);\r\n }\r\n\r\n this.calculateTotals();\r\n return index >= 0 ? index : this.lineItems.length - 1;\r\n }\r\n\r\n /**\r\n * Updates the quantity for a specific size within a line item.\r\n * @param lineItemId The ID of the LineItemModel to update.\r\n * @param size The size identifier within the line item.\r\n * @param quantity The new quantity for the size (0 to remove).\r\n * @returns The index of the updated line item.\r\n * @throws {Error} If the line item is not found.\r\n */\r\n public updateLineItem(lineItemId: string, size: string, quantity: number) {\r\n const lineItems = this.lineItems;\r\n let index = lineItems.findIndex((item) => item.getId() === lineItemId);\r\n\r\n if (index < 0) {\r\n throw new LineItemNotFoundError(lineItemId);\r\n }\r\n\r\n lineItems[index].addSubItems([{ size, quantity }], false);\r\n this.calculateTotals();\r\n\r\n return index;\r\n }\r\n\r\n /**\r\n * Removes a line item completely from the cart.\r\n * @param lineItemId The ID of the LineItemModel to remove.\r\n * @returns The index the item previously occupied.\r\n * @throws {Error} If the line item is not found.\r\n */\r\n public removeLineItem(lineItemId: string) {\r\n const lineItems = this.lineItems;\r\n const index = lineItems.findIndex((item) => item.getId() === lineItemId);\r\n\r\n if (index < 0) {\r\n throw new LineItemNotFoundError(lineItemId);\r\n }\r\n\r\n this.lineItems.splice(index, 1);\r\n this.charges = this.charges.filter(charge => charge.getLineItemId() !== lineItemId);\r\n this.calculateTotals();\r\n\r\n return index;\r\n }\r\n\r\n getDetails(): CartData {\r\n return {\r\n ...super.getDetails(),\r\n state: this.getState(),\r\n expireAt: this.getExpireAt(),\r\n }\r\n }\r\n}\r\n"]}
@@ -1,5 +1,5 @@
1
1
  import { CustomFieldAttributes, CustomFieldModel } from './Base.mjs';
2
- import { P as PriceData, b as PriceModel, c as LocalizedString } from '../Common-Bd8Xv8x4.mjs';
2
+ import { b as PriceData, c as PriceModel, d as LocalizedString, L as LocaleCode } from '../Common-XM4zQpWC.mjs';
3
3
  import { TaxSystem, ChargeType } from './Enum.mjs';
4
4
  import { FixedTaxRuleData, FixedTaxRuleModel } from './TaxRule.mjs';
5
5
  import CouponModel from './Coupon.mjs';
@@ -72,7 +72,17 @@ declare class ChargeModel extends CustomFieldModel {
72
72
  protected total: ChargeTotalsModel;
73
73
  constructor(data: ChargeAttributes);
74
74
  getId(): string;
75
+ /**
76
+ * Gets the full localized product name object.
77
+ * @returns A copy of the LocalizedString object for the name.
78
+ */
75
79
  getName(): LocalizedString;
80
+ /**
81
+ * Gets the product name for a specific locale, falling back to English ('en').
82
+ * @param locale - The desired locale code.
83
+ * @returns The name string for the specified locale.
84
+ */
85
+ getName(locale: LocaleCode): string;
76
86
  getCategory(): string;
77
87
  getChargeType(): ChargeType;
78
88
  getLineItemId(): string | undefined;
@@ -1,5 +1,5 @@
1
1
  import { CustomFieldAttributes, CustomFieldModel } from './Base.js';
2
- import { P as PriceData, b as PriceModel, c as LocalizedString } from '../Common-CXp_zjft.js';
2
+ import { b as PriceData, c as PriceModel, d as LocalizedString, L as LocaleCode } from '../Common-uAn7Sunn.js';
3
3
  import { TaxSystem, ChargeType } from './Enum.js';
4
4
  import { FixedTaxRuleData, FixedTaxRuleModel } from './TaxRule.js';
5
5
  import CouponModel from './Coupon.js';
@@ -72,7 +72,17 @@ declare class ChargeModel extends CustomFieldModel {
72
72
  protected total: ChargeTotalsModel;
73
73
  constructor(data: ChargeAttributes);
74
74
  getId(): string;
75
+ /**
76
+ * Gets the full localized product name object.
77
+ * @returns A copy of the LocalizedString object for the name.
78
+ */
75
79
  getName(): LocalizedString;
80
+ /**
81
+ * Gets the product name for a specific locale, falling back to English ('en').
82
+ * @param locale - The desired locale code.
83
+ * @returns The name string for the specified locale.
84
+ */
85
+ getName(locale: LocaleCode): string;
76
86
  getCategory(): string;
77
87
  getChargeType(): ChargeType;
78
88
  getLineItemId(): string | undefined;
@@ -1,2 +1,2 @@
1
- 'use strict';var ne=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ne__default=/*#__PURE__*/_interopDefault(ne);var I=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){return this.customFields[e]??null}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return {...this.customFields}}},S=class extends I{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.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(e,t,i,n){this.modifiedBy={id:e,authType:t,requestId:i,lambdaName:n};}};var R=new Uint8Array(256),M=R.length;function k(){return M>R.length-16&&(ne__default.default.randomFillSync(R),M=0),R.slice(M,M+=16)}var Z=/^(?:[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 se(r){return typeof r=="string"&&Z.test(r)}var J=se;var d=[];for(let r=0;r<256;++r)d.push((r+256).toString(16).slice(1));function v(r,e=0){return d[r[e+0]]+d[r[e+1]]+d[r[e+2]]+d[r[e+3]]+"-"+d[r[e+4]]+d[r[e+5]]+"-"+d[r[e+6]]+d[r[e+7]]+"-"+d[r[e+8]]+d[r[e+9]]+"-"+d[r[e+10]]+d[r[e+11]]+d[r[e+12]]+d[r[e+13]]+d[r[e+14]]+d[r[e+15]]}function oe(r){if(!J(r))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(r.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(r.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(r.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(r.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var X=oe;function ae(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var ce="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ue="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function G(r,e,t){function i(n,s,l,p){var o;if(typeof n=="string"&&(n=ae(n)),typeof s=="string"&&(s=X(s)),((o=s)===null||o===void 0?void 0:o.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+n.length);if(c.set(s),c.set(n,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,l){p=p||0;for(let x=0;x<16;++x)l[p+x]=c[x];return l}return v(c)}try{i.name=r;}catch{}return i.DNS=ce,i.URL=ue,i}var V={randomUUID:ne__default.default.randomUUID};function de(r,e,t){if(V.randomUUID&&!e&&!r)return V.randomUUID();r=r||{};let i=r.random||(r.rng||k)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(let n=0;n<16;++n)e[t+n]=i[n];return e}return v(i)}var Q=de;function pe(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),ne__default.default.createHash("sha1").update(r).digest()}var W=pe;var me=G("v5",80,W),j=me;var T={"en-IN":"en","kn-IN":"kn"};var _={INR:"\u20B9"},ee={INR:"en-IN"};var E=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var y=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var U=class extends Error{constructor(e="Tax rule category mismatch."){super(`InvalidTaxRule: ${e}`),this.name="InvalidTaxRuleError";}},L=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},N=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},F=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},B=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},O=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var D=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},C=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},f=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},h=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},w=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};var P=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw new w("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,t){if(t===void 0){if(e==="original")throw new w("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=t;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var u=class r{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new D("Amount cannot be negative.");if(!e.currency)throw new C("Currency code is required.");this.amount=e.amount,this.currency=e.currency;}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot compare prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return this.amount-e.getAmount()}add(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot add prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return new r({amount:this.amount+e.getAmount(),currency:this.currency})}subtract(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot subtract prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return new r({amount:this.amount-e.getAmount(),currency:this.currency})}multiply(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot multiply prices in different currencies.");return new r({amount:this.amount*e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new r({amount:this.amount*e,currency:this.currency});throw new h("Must be a non-negative number.")}divide(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot divide prices in different currencies.");return new r({amount:this.amount/e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>0)return new r({amount:this.amount/e,currency:this.currency});throw new h("Must be a positive number.")}min(...e){if(e.length===0)throw new h("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new f("Cannot compare prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i},this)}max(...e){if(e.length===0)throw new h("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new f("Cannot compare prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return t.compareTo(i)>0?t:i},this)}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(e,t,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=ee[t];if(!t||!n)throw new C("Invalid currency code for formatting.");let s=e,l=i.displayAsInteger?0:r.getDecimalPlaces(t),p={style:i.style??"currency",currency:t,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:l,maximumFractionDigits:l};i.displayAsInteger&&(s=Math.ceil(s));try{return new Intl.NumberFormat(n,p).format(s)}catch(o){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,o),`${_[t]??t} ${r.addThousandSeparators(s.toFixed(l))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static addThousandSeparators(e){let t=e.split("."),i=t[0],n=t.length>1?"."+t[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,t){if(e<0)throw new D("Amount cannot be negative for rounding.");if(t===void 0)throw new C("Invalid currency code for rounding.");let i=r.getDecimalPlaces(t),n=Math.pow(10,i);return Math.round(e*n)/n}};var $=class{baseUnitPrice;taxCategory;tiers;constructor(e){let t=new u(e.baseUnitPrice);if(!e.taxCategory)throw new L;let i=(e.tiers??[]).map(o=>({minQuantity:o.minQuantity,unitPrice:new u(o.unitPrice)})).sort((o,c)=>o.minQuantity-c.minQuantity);if(i.some(o=>o.minQuantity<=0))throw new N;let s=i.some(o=>o.unitPrice.getCurrency()!==t.getCurrency()),l=i.some((o,c)=>c>0&&o.unitPrice.compareTo(i[c-1].unitPrice)>0),p=i[0]?.unitPrice.compareTo(t)>0;if(s||l||p)throw new F("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=t,this.taxCategory=e.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(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}getApplicableTier(e){if(e<=0)throw new B;for(let t=this.tiers.length-1;t>=0;t--)if(e>=this.tiers[t].minQuantity)return this.tiers[t];throw new O(e)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let e=this.tiers[this.tiers.length-1].unitPrice.getAmount(),t=this.baseUnitPrice.getAmount();return (t-e)/t*100}};var A=class r extends S{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(e){if(typeof e!="object")throw new y("Selection attributes must be an object");return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let t={},i=e.split("|");for(let n of i){let[s,l]=n.split(":");l.startsWith("c+")?t[s]={name:l.slice(2)}:t[s]=l;}return t}catch(t){throw new y(t?.message)}}constructor(e,t=new Date){super(e,t),this.id=e.id,this.key=e.key,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((n,s)=>(e.pricing[s]&&(n[s]=new $(e.pricing[s])),n),{}),this.targetGender=e.targetGender,this.attributes=g.deepClone(e.attributes),this.specifications=g.deepClone(e.specifications),this.categories=g.deepClone(e.categories);let i=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new y("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let s=r.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(s))throw new E(s);return i.add(s),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new P(n.images.primary),gallery:(n.images.gallery||[]).map(l=>new P(l))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?g.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[T[e]]??this.name.en:g.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[T[e]]??this.description.en:g.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[T[e]]??this.slug.en:g.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:this.pricing}getAttributes(){return g.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:e.selectionAttributes,images:{primary:e.images.primary,gallery:e.images.gallery}}))}getImagesBySelectionAttributes(e){let t=r.generateSelectionAttributesKey(e),i=this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===t);return i?i.images:null}getImages(e,t){switch(t){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return g.deepClone(this.categories)}getSpecifications(e){return e?g.deepClone(this.specifications[e]??this.specifications[T[e]]??this.specifications.en):g.deepClone(this.specifications)}getSearchTags(e){return e?g.deepClone(this.searchTags[e]??this.searchTags[T[e]]??this.searchTags.en):g.deepClone(this.searchTags)}getDetails(){let e=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((t,i)=>(this.pricing[i]&&(t[i]=this.pricing[i]?.getDetails()),t),{}),attributes:this.getAttributes(),variants:this.variants.map(t=>({sku:t.sku,selectionAttributes:g.deepClone(t.selectionAttributes),images:{primary:t.images.primary.getDetails(),gallery:t.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new y("Selection attributes are required");Object.keys(this.attributes).forEach(t=>{if(t.toLowerCase()==="size")return;let i=this.attributes[t],n=e[t];if(n===void 0)throw new y(`Selection attribute '${t}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new y(`Selection attribute '${t}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new y(`Selection attribute '${t}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(s=>s.name===n.name)<0)throw new y(`Selection attribute '${t}' is invalid`)}});}validateSelectionAttribute(e){let t=r.generateSelectionAttributesKey(e);return this.variants.some(i=>r.generateSelectionAttributesKey(i.selectionAttributes)===t)}validateSize(e){return this.attributes.size.includes(e)}};var he={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,e)=>e&&r?j(r,e):Q(),generateSearchId:(r,e)=>`${r}#${A.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:r=>{let[e,t]=r.split("#");return {key:e,selectionAttributes:A.parseSelectionAttributesKey(t)}},deepClone(r){return structuredClone(r)}},g=he;var K=class{taxRuleId;taxCategory;taxSystem;taxSubSystem;taxCountry;effectiveFrom;effectiveTo;constructor(e){this.taxRuleId=e.taxRuleId,this.taxSystem=e.taxSystem,this.taxSubSystem=e.taxSubSystem,this.taxCategory=e.taxCategory,this.taxCountry=e.taxCountry,this.effectiveFrom=new Date(e.effectiveFrom),this.effectiveTo=e.effectiveTo?new Date(e.effectiveTo):void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getTaxCountry(){return this.taxCountry}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),taxCountry:this.getTaxCountry(),effectiveFrom:this.effectiveFrom.toISOString(),effectiveTo:this.effectiveTo?this.effectiveTo.toISOString():void 0}}appliesTo(e,t,i=new Date){return this.taxCategory===e&&this.taxCountry===t&&this.effectiveFrom<=i&&(this.effectiveTo?this.effectiveTo>=i:!0)}static getTaxRateDisplayString(e,t,i){let n=t*100,s=n%1===0?n.toString():n.toFixed(2).replace(/\.?0+$/,"");return i?.percentageOnly?`${s}%`:e.getTaxSystem()==="GST"?`${s}% ${e.getTaxSubSystem()}`:`${s}% ${e.getTaxSystem()}`}};var z=class extends K{rate;minUnitPrice;maxUnitPrice;constructor(e){super(e),this.rate=e.rate,this.minUnitPrice=new u(e.minUnitPrice),this.maxUnitPrice=e.maxUnitPrice?new u(e.maxUnitPrice):void 0;}getApplicableTaxRate(){return this.rate}calculateTax(e){let t=this.getApplicableTaxRate();return e.multiply(t).round()}getDetails(){return {...super.getDetails(),rate:this.getApplicableTaxRate(),minUnitPrice:this.minUnitPrice.getDetails(),maxUnitPrice:this.maxUnitPrice?this.maxUnitPrice.getDetails():void 0}}};var q=class extends I{id;name;category;lineItemId;chargeType;pricing;total;constructor(e){super(e),this.id=e.id,this.name=e.name,this.category=e.category,this.lineItemId=e.lineItemId,this.chargeType=e.chargeType,this.pricing={price:new u(e.pricing.price),taxCategory:e.pricing.taxCategory,applicableTaxRule:e.pricing.applicableTaxRule.map(t=>new z(t))},this.total={price:new u(e.total.price),discounts:Object.fromEntries(Object.entries(e.total.discounts).map(([t,i])=>[t,new u(i)])),totalDiscount:new u(e.total.totalDiscount),netPrice:new u(e.total.netPrice),taxBreakdown:Object.fromEntries(Object.entries(e.total.taxBreakdown).map(([t,i])=>[t,{rate:i.rate,taxablePrice:new u(i.taxablePrice),amount:new u(i.amount),system:i.system,subSystem:i.subSystem}])),taxTotal:new u(e.total.taxTotal),grandTotal:new u(e.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}updateTax(e){e.forEach(t=>{if(!t.appliesTo(this.pricing.taxCategory,t.getTaxCountry()))throw new U}),this.pricing.applicableTaxRule=e,this.calculateTotals();}updateDiscounts(e){let t={};e.forEach(i=>{t[i.coupon.getCode()]=i.amount;}),this.total.discounts=t,this.calculateTotals();}calculateTotals(){let e=this.pricing.price.zero(),t=this.pricing.price,i=Object.values(this.total.discounts).reduce((m,b)=>m.add(b),e),n=t.subtract(i),s={},l=this.pricing.applicableTaxRule.reduce((m,b)=>m+b.getApplicableTaxRate(),0),p=n.divide(1+l).round(),o=n.subtract(p),c=e,x=this.pricing.applicableTaxRule.reduce((m,b)=>b.getApplicableTaxRate()>m.getApplicableTaxRate()?b:m),H=x.getTaxRuleId();this.pricing.applicableTaxRule.forEach(m=>{if(m.getTaxRuleId()===H)return;let b=m.getApplicableTaxRate(),Y=o.multiply(b).divide(l).round();s[m.getTaxRuleId()]={rate:b,taxablePrice:p,amount:Y,system:m.getTaxSystem(),subSystem:m.getTaxSubSystem()},c=c.add(Y);});let te=o.subtract(c);s[H]={rate:x.getApplicableTaxRate(),taxablePrice:p,amount:te,system:x.getTaxSystem(),subSystem:x.getTaxSubSystem()};let re=p,ie=n;this.total={price:t,discounts:this.total.discounts,netPrice:re,totalDiscount:i,taxBreakdown:s,taxTotal:o,grandTotal:ie};}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(t=>t.getDetails())},total:{price:this.total.price.getDetails(),discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,i])=>[t,i.getDetails()])),totalDiscount:this.total.totalDiscount.getDetails(),netPrice:this.total.netPrice.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,i])=>[t,{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()}}};module.exports=q;//# sourceMappingURL=Charge.js.map
1
+ 'use strict';var ne=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ne__default=/*#__PURE__*/_interopDefault(ne);var R=new Uint8Array(256),M=R.length;function k(){return M>R.length-16&&(ne__default.default.randomFillSync(R),M=0),R.slice(M,M+=16)}var Z=/^(?:[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 oe(r){return typeof r=="string"&&Z.test(r)}var J=oe;var d=[];for(let r=0;r<256;++r)d.push((r+256).toString(16).slice(1));function v(r,e=0){return d[r[e+0]]+d[r[e+1]]+d[r[e+2]]+d[r[e+3]]+"-"+d[r[e+4]]+d[r[e+5]]+"-"+d[r[e+6]]+d[r[e+7]]+"-"+d[r[e+8]]+d[r[e+9]]+"-"+d[r[e+10]]+d[r[e+11]]+d[r[e+12]]+d[r[e+13]]+d[r[e+14]]+d[r[e+15]]}function se(r){if(!J(r))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(r.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(r.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(r.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(r.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var X=se;function ae(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var ce="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ue="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Q(r,e,t){function i(n,o,a,p){var c;if(typeof n=="string"&&(n=ae(n)),typeof o=="string"&&(o=X(o)),((c=o)===null||c===void 0?void 0:c.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+n.length);if(l.set(o),l.set(n,o.length),l=t(l),l[6]=l[6]&15|e,l[8]=l[8]&63|128,a){p=p||0;for(let x=0;x<16;++x)a[p+x]=l[x];return a}return v(l)}try{i.name=r;}catch{}return i.DNS=ce,i.URL=ue,i}var G={randomUUID:ne__default.default.randomUUID};function de(r,e,t){if(G.randomUUID&&!e&&!r)return G.randomUUID();r=r||{};let i=r.random||(r.rng||k)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(let n=0;n<16;++n)e[t+n]=i[n];return e}return v(i)}var V=de;function pe(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),ne__default.default.createHash("sha1").update(r).digest()}var W=pe;var me=Q("v5",80,W),j=me;var T={"en-IN":"en","kn-IN":"kn"};var _={INR:"\u20B9"},ee={INR:"en-IN"};var E=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var y=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var U=class extends Error{constructor(e="Tax rule category mismatch."){super(`InvalidTaxRule: ${e}`),this.name="InvalidTaxRuleError";}},L=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},N=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},F=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},B=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},O=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var S=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},C=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},f=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},h=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},I=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};var P=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw new I("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,t){if(t===void 0){if(e==="original")throw new I("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=t;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var g=class r{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new S("Amount cannot be negative.");if(!e.currency)throw new C("Currency code is required.");this.amount=e.amount,this.currency=e.currency;}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot compare prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return this.amount-e.getAmount()}add(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot add prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return new r({amount:this.amount+e.getAmount(),currency:this.currency})}subtract(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot subtract prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return new r({amount:this.amount-e.getAmount(),currency:this.currency})}multiply(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot multiply prices in different currencies.");return new r({amount:this.amount*e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new r({amount:this.amount*e,currency:this.currency});throw new h("Must be a non-negative number.")}divide(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot divide prices in different currencies.");return new r({amount:this.amount/e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>0)return new r({amount:this.amount/e,currency:this.currency});throw new h("Must be a positive number.")}min(...e){if(e.length===0)throw new h("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new f("Cannot compare prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i},this)}max(...e){if(e.length===0)throw new h("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new f("Cannot compare prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return t.compareTo(i)>0?t:i},this)}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(e,t,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=ee[t];if(!t||!n)throw new C("Invalid currency code for formatting.");let o=e,a=i.displayAsInteger?0:r.getDecimalPlaces(t),p={style:i.style??"currency",currency:t,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,p).format(o)}catch(c){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,c),`${_[t]??t} ${r.addThousandSeparators(o.toFixed(a))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static addThousandSeparators(e){let t=e.split("."),i=t[0],n=t.length>1?"."+t[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,t){if(e<0)throw new S("Amount cannot be negative for rounding.");if(t===void 0)throw new C("Invalid currency code for rounding.");let i=r.getDecimalPlaces(t),n=Math.pow(10,i);return Math.round(e*n)/n}};var $=class{baseUnitPrice;taxCategory;tiers;constructor(e){let t=new g(e.baseUnitPrice);if(!e.taxCategory)throw new L;let i=(e.tiers??[]).map(c=>({minQuantity:c.minQuantity,unitPrice:new g(c.unitPrice)})).sort((c,l)=>c.minQuantity-l.minQuantity);if(i.some(c=>c.minQuantity<=0))throw new N;let o=i.some(c=>c.unitPrice.getCurrency()!==t.getCurrency()),a=i.some((c,l)=>l>0&&c.unitPrice.compareTo(i[l-1].unitPrice)>0),p=i[0]?.unitPrice.compareTo(t)>0;if(o||a||p)throw new F("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=t,this.taxCategory=e.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}getApplicableTier(e){if(e<=0)throw new B;for(let t=this.tiers.length-1;t>=0;t--)if(e>=this.tiers[t].minQuantity){let i=this.tiers[t];return {minQuantity:i.minQuantity,unitPrice:i.unitPrice}}throw new O(e)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let e=this.tiers[this.tiers.length-1].unitPrice.getAmount(),t=this.baseUnitPrice.getAmount();return (t-e)/t*100}};var A=class r extends D{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new y("Selection attributes must be an object");return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let t={},i=e.split("|");for(let n of i){let[o,a]=n.split(":");a.startsWith("c+")?t[o]={name:a.slice(2)}:t[o]=a;}return t}catch(t){throw new y(t?.message)}}constructor(e,t=new Date){super(e,t),this.id=e.id,this.key=e.key,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((n,o)=>(e.pricing[o]&&(n[o]=new $(e.pricing[o])),n),{}),this.targetGender=e.targetGender,this.attributes=s.deepClone(e.attributes),this.specifications=s.deepClone(e.specifications),this.categories=s.deepClone(e.categories);let i=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new y("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let o=r.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(o))throw new E(o);return i.add(o),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new P(n.images.primary),gallery:(n.images.gallery||[]).map(a=>new P(a))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?s.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[T[e]]??this.name.en:s.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[T[e]]??this.description.en:s.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[T[e]]??this.slug.en:s.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return s.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:s.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let t=r.generateSelectionAttributesKey(e),i=this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===t);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,t){switch(t){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return s.deepClone(this.categories)}getSpecifications(e){return e?s.deepClone(this.specifications[e]??this.specifications[T[e]]??this.specifications.en):s.deepClone(this.specifications)}getSearchTags(e){return e?s.deepClone(this.searchTags[e]??this.searchTags[T[e]]??this.searchTags.en):s.deepClone(this.searchTags)}getDetails(){let e=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((t,i)=>(this.pricing[i]&&(t[i]=this.pricing[i]?.getDetails()),t),{}),attributes:this.getAttributes(),variants:this.variants.map(t=>({sku:t.sku,selectionAttributes:s.deepClone(t.selectionAttributes),images:{primary:t.images.primary.getDetails(),gallery:t.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new y("Selection attributes are required");Object.keys(this.attributes).forEach(t=>{if(t.toLowerCase()==="size")return;let i=this.attributes[t],n=e[t];if(n===void 0)throw new y(`Selection attribute '${t}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new y(`Selection attribute '${t}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new y(`Selection attribute '${t}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(o=>o.name===n.name)<0)throw new y(`Selection attribute '${t}' is invalid`)}});}validateSelectionAttribute(e){let t=r.generateSelectionAttributesKey(e);return this.variants.some(i=>r.generateSelectionAttributesKey(i.selectionAttributes)===t)}validateSize(e){return this.attributes.size.includes(e)}};var he={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,e)=>e&&r?j(r,e):V(),generateSearchId:(r,e)=>`${r}#${A.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:r=>{let[e,t]=r.split("#");return {key:e,selectionAttributes:A.parseSelectionAttributesKey(t)}},deepClone(r){return structuredClone(r)}},s=he;var w=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:s.deepClone(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return s.deepClone(this.customFields)}},D=class extends w{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.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(e,t,i,n){this.modifiedBy={id:e,authType:t,requestId:i,lambdaName:n};}};var K=class{taxRuleId;taxCategory;taxSystem;taxSubSystem;taxCountry;effectiveFrom;effectiveTo;constructor(e){this.taxRuleId=e.taxRuleId,this.taxSystem=e.taxSystem,this.taxSubSystem=e.taxSubSystem,this.taxCategory=e.taxCategory,this.taxCountry=e.taxCountry,this.effectiveFrom=new Date(e.effectiveFrom).toISOString(),this.effectiveTo=e.effectiveTo?new Date(e.effectiveTo).toISOString():void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getTaxCountry(){return this.taxCountry}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),taxCountry:this.getTaxCountry(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0}}appliesTo(e,t,i=new Date){return this.taxCategory===e&&this.taxCountry===t&&Date.parse(this.effectiveFrom)<=i.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=i.getTime():!0)}static getTaxRateDisplayString(e,t,i){let n=t*100,o=n%1===0?n.toString():n.toFixed(2).replace(/\.?0+$/,"");return i?.percentageOnly?`${o}%`:e.getTaxSystem()==="GST"?`${e.getTaxSubSystem()} ${o}%`:`${e.getTaxSystem()} ${o}%`}};var z=class extends K{rate;constructor(e){super(e),this.rate=e.rate;}getApplicableTaxRate(){return this.rate}calculateTax(e){let t=this.getApplicableTaxRate();return e.multiply(t)}getDetails(){return {...super.getDetails(),rate:this.getApplicableTaxRate()}}};var q=class extends w{id;name;category;lineItemId;chargeType;pricing;total;constructor(e){super(e),this.id=e.id,this.name=e.name,this.category=e.category,this.lineItemId=e.lineItemId,this.chargeType=e.chargeType,this.pricing={price:new g(e.pricing.price),taxCategory:e.pricing.taxCategory,applicableTaxRule:e.pricing.applicableTaxRule.map(t=>new z(t))},this.total={price:new g(e.total.price),discounts:Object.fromEntries(Object.entries(e.total.discounts).map(([t,i])=>[t,new g(i)])),totalDiscount:new g(e.total.totalDiscount),netPrice:new g(e.total.netPrice),taxBreakdown:Object.fromEntries(Object.entries(e.total.taxBreakdown).map(([t,i])=>[t,{rate:i.rate,taxablePrice:new g(i.taxablePrice),amount:new g(i.amount),system:i.system,subSystem:i.subSystem}])),taxTotal:new g(e.total.taxTotal),grandTotal:new g(e.total.grandTotal)};}getId(){return this.id}getName(e){return e?s.deepClone(this.name[e]??this.name[T[e]]??this.name.en):s.deepClone(this.name)}getCategory(){return this.category}getChargeType(){return this.chargeType}getLineItemId(){return this.lineItemId}getPricing(){return {price:this.pricing.price,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {price:this.total.price,discounts:{...this.total.discounts},netPrice:this.total.netPrice,totalDiscount:this.total.totalDiscount,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,t])=>[e,{rate:t.rate,taxablePrice:t.taxablePrice,amount:t.amount,system:t.system,subSystem:t.subSystem}])),taxTotal:this.total.taxTotal,grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(e){e.forEach(t=>{if(!t.appliesTo(this.pricing.taxCategory,t.getTaxCountry()))throw new U}),this.pricing.applicableTaxRule=e,this.calculateTotals();}updateDiscounts(e){let t={};e.forEach(i=>{t[i.coupon.getCode()]=i.amount;}),this.total.discounts=t,this.calculateTotals();}calculateTotals(){let e=this.pricing.price.zero(),t=this.pricing.price,i=Object.values(this.total.discounts).reduce((m,b)=>m.add(b),e),n=t.subtract(i),o={},a=this.pricing.applicableTaxRule.reduce((m,b)=>m+b.getApplicableTaxRate(),0),p=n.divide(1+a).round(),c=a>0?n.subtract(p):e,l=e,x=this.pricing.applicableTaxRule.reduce((m,b)=>b.getApplicableTaxRate()>m.getApplicableTaxRate()?b:m),H=x.getTaxRuleId();this.pricing.applicableTaxRule.forEach(m=>{if(m.getTaxRuleId()===H)return;let b=m.getApplicableTaxRate(),Y=a>0?c.multiply(b).divide(a).round():e;o[m.getTaxRuleId()]={rate:b,taxablePrice:p,amount:Y,system:m.getTaxSystem(),subSystem:m.getTaxSubSystem()},l=l.add(Y);});let te=c.subtract(l);o[H]={rate:x.getApplicableTaxRate(),taxablePrice:p,amount:te,system:x.getTaxSystem(),subSystem:x.getTaxSubSystem()};let re=p,ie=n;this.total={price:t,discounts:this.total.discounts,netPrice:re,totalDiscount:i,taxBreakdown:o,taxTotal:c,grandTotal:ie};}getDetails(){return {id:this.id,name:s.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(t=>t.getDetails())},total:{price:this.total.price.getDetails(),discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,i])=>[t,i.getDetails()])),totalDiscount:this.total.totalDiscount.getDetails(),netPrice:this.total.netPrice.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,i])=>[t,{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()}}};module.exports=q;//# sourceMappingURL=Charge.js.map
2
2
  //# sourceMappingURL=Charge.js.map