b23-lib 3.0.10 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/dist/Auth/index.js +1 -1
  2. package/dist/Auth/index.js.map +1 -1
  3. package/dist/Auth/index.mjs +1 -1
  4. package/dist/Classes/Address.d.mts +1 -1
  5. package/dist/Classes/Address.d.ts +1 -1
  6. package/dist/Classes/Base.d.mts +1 -1
  7. package/dist/Classes/Base.d.ts +1 -1
  8. package/dist/Classes/Cart.d.mts +1 -1
  9. package/dist/Classes/Cart.d.ts +1 -1
  10. package/dist/Classes/Cart.js +1 -1
  11. package/dist/Classes/Cart.js.map +1 -1
  12. package/dist/Classes/Cart.mjs +1 -1
  13. package/dist/Classes/Cart.mjs.map +1 -1
  14. package/dist/Classes/Charge.d.mts +61 -51
  15. package/dist/Classes/Charge.d.ts +61 -51
  16. package/dist/Classes/Charge.js +1 -1
  17. package/dist/Classes/Charge.js.map +1 -1
  18. package/dist/Classes/Charge.mjs +1 -1
  19. package/dist/Classes/Common.d.mts +1 -1
  20. package/dist/Classes/Common.d.ts +1 -1
  21. package/dist/Classes/Coupon.d.mts +1 -1
  22. package/dist/Classes/Coupon.d.ts +1 -1
  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 +1 -1
  27. package/dist/Classes/Customer.d.ts +1 -1
  28. package/dist/Classes/CustomerAddress.d.mts +1 -1
  29. package/dist/Classes/CustomerAddress.d.ts +1 -1
  30. package/dist/Classes/Enum.d.mts +1 -5
  31. package/dist/Classes/Enum.d.ts +1 -5
  32. package/dist/Classes/Enum.js +1 -1
  33. package/dist/Classes/Enum.js.map +1 -1
  34. package/dist/Classes/Enum.mjs +1 -1
  35. package/dist/Classes/Error.d.mts +4 -1
  36. package/dist/Classes/Error.d.ts +4 -1
  37. package/dist/Classes/Error.js +1 -1
  38. package/dist/Classes/Error.js.map +1 -1
  39. package/dist/Classes/Error.mjs +1 -1
  40. package/dist/Classes/ImageInfo.js +1 -1
  41. package/dist/Classes/ImageInfo.js.map +1 -1
  42. package/dist/Classes/ImageInfo.mjs +1 -1
  43. package/dist/Classes/Inventory.d.mts +1 -1
  44. package/dist/Classes/Inventory.d.ts +1 -1
  45. package/dist/Classes/Inventory.js +1 -1
  46. package/dist/Classes/Inventory.js.map +1 -1
  47. package/dist/Classes/Inventory.mjs +1 -1
  48. package/dist/Classes/LineItem.d.mts +9 -9
  49. package/dist/Classes/LineItem.d.ts +9 -9
  50. package/dist/Classes/LineItem.js +1 -1
  51. package/dist/Classes/LineItem.js.map +1 -1
  52. package/dist/Classes/LineItem.mjs +1 -1
  53. package/dist/Classes/Order.d.mts +1 -1
  54. package/dist/Classes/Order.d.ts +1 -1
  55. package/dist/Classes/Order.js +1 -1
  56. package/dist/Classes/Order.js.map +1 -1
  57. package/dist/Classes/Order.mjs +1 -1
  58. package/dist/Classes/Payment.d.mts +1 -1
  59. package/dist/Classes/Payment.d.ts +1 -1
  60. package/dist/Classes/Price.d.mts +1 -1
  61. package/dist/Classes/Price.d.ts +1 -1
  62. package/dist/Classes/Price.js +1 -1
  63. package/dist/Classes/Price.js.map +1 -1
  64. package/dist/Classes/Price.mjs +1 -1
  65. package/dist/Classes/Product.d.mts +1 -1
  66. package/dist/Classes/Product.d.ts +1 -1
  67. package/dist/Classes/Product.js +1 -1
  68. package/dist/Classes/Product.js.map +1 -1
  69. package/dist/Classes/Product.mjs +1 -1
  70. package/dist/Classes/ShoppingContainer.d.mts +44 -40
  71. package/dist/Classes/ShoppingContainer.d.ts +44 -40
  72. package/dist/Classes/ShoppingContainer.js +1 -1
  73. package/dist/Classes/ShoppingContainer.js.map +1 -1
  74. package/dist/Classes/ShoppingContainer.mjs +1 -1
  75. package/dist/Classes/TaxRule.d.mts +35 -74
  76. package/dist/Classes/TaxRule.d.ts +35 -74
  77. package/dist/Classes/TaxRule.js +1 -1
  78. package/dist/Classes/TaxRule.js.map +1 -1
  79. package/dist/Classes/TaxRule.mjs +1 -1
  80. package/dist/Classes/TieredPrice.d.mts +1 -1
  81. package/dist/Classes/TieredPrice.d.ts +1 -1
  82. package/dist/Classes/TieredPrice.js +1 -1
  83. package/dist/Classes/TieredPrice.js.map +1 -1
  84. package/dist/Classes/TieredPrice.mjs +1 -1
  85. package/dist/{Common-XM4zQpWC.d.mts → Common-C4Fl1Axr.d.mts} +7 -0
  86. package/dist/{Common-uAn7Sunn.d.ts → Common-Cq0_dPyJ.d.ts} +7 -0
  87. package/dist/{chunk-OAE2FJFJ.mjs → chunk-2TK2CILF.mjs} +2 -2
  88. package/dist/{chunk-OAE2FJFJ.mjs.map → chunk-2TK2CILF.mjs.map} +1 -1
  89. package/dist/chunk-3UMWQ7S7.mjs +2 -0
  90. package/dist/chunk-3UMWQ7S7.mjs.map +1 -0
  91. package/dist/{chunk-QLYPJDDV.mjs → chunk-JZC4DEOP.mjs} +2 -2
  92. package/dist/{chunk-QLYPJDDV.mjs.map → chunk-JZC4DEOP.mjs.map} +1 -1
  93. package/dist/chunk-LNDZ2K5E.mjs +2 -0
  94. package/dist/chunk-LNDZ2K5E.mjs.map +1 -0
  95. package/dist/chunk-MIH2OONR.mjs +2 -0
  96. package/dist/chunk-MIH2OONR.mjs.map +1 -0
  97. package/dist/chunk-QK4XJ3GB.mjs +2 -0
  98. package/dist/chunk-QK4XJ3GB.mjs.map +1 -0
  99. package/dist/{chunk-XPKK6DFA.mjs → chunk-SJRXYUH2.mjs} +2 -2
  100. package/dist/chunk-SJRXYUH2.mjs.map +1 -0
  101. package/dist/chunk-SWE42U5U.mjs +2 -0
  102. package/dist/chunk-SWE42U5U.mjs.map +1 -0
  103. package/dist/{chunk-Z3CF4K5C.mjs → chunk-TVTIUN4Z.mjs} +2 -2
  104. package/dist/{chunk-Z3CF4K5C.mjs.map → chunk-TVTIUN4Z.mjs.map} +1 -1
  105. package/dist/{chunk-RSTZJZSQ.mjs → chunk-WUIJ47N2.mjs} +2 -2
  106. package/dist/{chunk-RSTZJZSQ.mjs.map → chunk-WUIJ47N2.mjs.map} +1 -1
  107. package/dist/chunk-ZY7AI75P.mjs +2 -0
  108. package/dist/chunk-ZY7AI75P.mjs.map +1 -0
  109. package/dist/index.d.mts +1 -1
  110. package/dist/index.d.ts +1 -1
  111. package/dist/index.js +2 -2
  112. package/dist/index.js.map +1 -1
  113. package/dist/index.mjs +1 -1
  114. package/package.json +8 -5
  115. package/dist/chunk-3HKY6ZOF.mjs +0 -2
  116. package/dist/chunk-3HKY6ZOF.mjs.map +0 -1
  117. package/dist/chunk-4ZFZXWD7.mjs +0 -2
  118. package/dist/chunk-4ZFZXWD7.mjs.map +0 -1
  119. package/dist/chunk-EHYGWYD7.mjs +0 -2
  120. package/dist/chunk-EHYGWYD7.mjs.map +0 -1
  121. package/dist/chunk-GFMGTV5E.mjs +0 -2
  122. package/dist/chunk-GFMGTV5E.mjs.map +0 -1
  123. package/dist/chunk-JCUHTCOC.mjs +0 -2
  124. package/dist/chunk-JCUHTCOC.mjs.map +0 -1
  125. package/dist/chunk-XPKK6DFA.mjs.map +0 -1
  126. package/dist/chunk-ZZ3B7OGM.mjs +0 -2
  127. package/dist/chunk-ZZ3B7OGM.mjs.map +0 -1
@@ -1,2 +1,2 @@
1
- import {a}from'../chunk-EHYGWYD7.mjs';import'../chunk-ZZ3B7OGM.mjs';import'../chunk-HX32EJ3F.mjs';import'../chunk-4ZFZXWD7.mjs';import'../chunk-JCUHTCOC.mjs';import'../chunk-Z3CF4K5C.mjs';import {b}from'../chunk-OAE2FJFJ.mjs';import'../chunk-QLYPJDDV.mjs';import'../chunk-3HKY6ZOF.mjs';import'../chunk-GFMGTV5E.mjs';import'../chunk-RSTZJZSQ.mjs';import {a as a$1}from'../chunk-XPKK6DFA.mjs';import'../chunk-UXZBULDS.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-ZY7AI75P.mjs';import'../chunk-MIH2OONR.mjs';import'../chunk-HX32EJ3F.mjs';import'../chunk-LNDZ2K5E.mjs';import'../chunk-SWE42U5U.mjs';import'../chunk-TVTIUN4Z.mjs';import {b}from'../chunk-2TK2CILF.mjs';import'../chunk-JZC4DEOP.mjs';import'../chunk-3UMWQ7S7.mjs';import'../chunk-QK4XJ3GB.mjs';import'../chunk-WUIJ47N2.mjs';import {a as a$1}from'../chunk-SJRXYUH2.mjs';import'../chunk-UXZBULDS.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.charges=[],this.coupons=[],this.shippingDetails=null,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
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":"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","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":"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","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.charges = [];\r\n this.coupons = [];\r\n this.shippingDetails = null;\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,62 +1,80 @@
1
1
  import { CustomFieldAttributes, CustomFieldModel } from './Base.mjs';
2
- import { b as PriceData, c as PriceModel, d as LocalizedString, L as LocaleCode } from '../Common-XM4zQpWC.mjs';
3
- import { TaxSystem, ChargeType, ChargeImpact, ChargeTaxTreatment } from './Enum.mjs';
4
- import { FixedTaxRuleData, FixedTaxRuleModel } from './TaxRule.mjs';
2
+ import { b as PriceData, c as PriceModel, d as LocalizedString, L as LocaleCode } from '../Common-C4Fl1Axr.mjs';
3
+ import { TaxSystem, ChargeType, ChargeImpact } from './Enum.mjs';
4
+ import { TaxRuleData, TaxRuleModel } from './TaxRule.mjs';
5
5
  import CouponModel from './Coupon.mjs';
6
6
  import '../Auth/index.mjs';
7
7
 
8
8
  type ChargePricing = {
9
- price: PriceData;
9
+ /** Tax-inclusive original charge amount before any discounts. Always non-negative. */
10
+ chargeAmount: PriceData;
11
+ /** Tax category of the charge. */
10
12
  taxCategory: string;
11
- applicableTaxRule: FixedTaxRuleData[];
13
+ /** Tax rules applicable to the charge. */
14
+ applicableTaxRule: TaxRuleData[];
15
+ };
16
+ type ChargePricingModel = {
17
+ /** Tax-inclusive original charge amount before any discounts. Always non-negative. */
18
+ chargeAmount: PriceModel;
19
+ /** Tax category of the charge. */
20
+ taxCategory: string;
21
+ /** Tax rules applicable to the charge. */
22
+ applicableTaxRule: TaxRuleModel[];
12
23
  };
13
24
  type ChargeTaxBreakdown = {
25
+ /** Tax rate: e.g., 0.09 for 9% */
14
26
  rate: number;
15
- taxablePrice: PriceData;
16
- amount: PriceData;
27
+ /** Reverse-calculated pre-tax base from the netChargeAmount (post-discount) */
28
+ taxableAmount: PriceData;
29
+ /** Tax portion for this rule (netChargeAmount - taxableAmount) */
30
+ taxAmount: PriceData;
17
31
  system: TaxSystem;
18
32
  subSystem: string;
19
33
  };
20
34
  type ChargeTaxBreakdownModel = {
21
35
  rate: number;
22
- taxablePrice: PriceModel;
23
- amount: PriceModel;
36
+ taxableAmount: PriceModel;
37
+ taxAmount: PriceModel;
24
38
  system: TaxSystem;
25
39
  subSystem: string;
26
40
  };
27
41
  type ChargeTotals = {
28
- price: PriceData;
29
- discounts: Record<string, PriceData>;
30
- totalDiscount: PriceData;
31
- netPrice: PriceData;
32
- taxBreakdown: Record<string, ChargeTaxBreakdown>;
42
+ /** Tax-inclusive original charge amount before discounts (copied from pricing) */
43
+ chargeAmount: PriceData;
44
+ /** Coupon code -> discount amount mapping */
45
+ discountBreakdown: Record<string, PriceData>;
46
+ /** Sum of all discounts */
47
+ discountTotal: PriceData;
48
+ /** chargeAmount - totalDiscount → final tax-inclusive payable amount after discounts */
49
+ netChargeAmount: PriceData;
50
+ /** Sum of all taxAmount values */
33
51
  taxTotal: PriceData;
52
+ /** Tax breakdown per rule/category (reverse-calculated from netChargeAmount) */
53
+ taxBreakdown: Record<string, ChargeTaxBreakdown>;
54
+ /** Final payable/contribution amount. Equals netChargeAmount (tax-inclusive after discounts). */
34
55
  grandTotal: PriceData;
35
56
  };
36
57
  type ChargeTotalsModel = {
37
- price: PriceModel;
38
- discounts: Record<string, PriceModel>;
39
- totalDiscount: PriceModel;
40
- netPrice: PriceModel;
41
- taxBreakdown: Record<string, ChargeTaxBreakdownModel>;
58
+ chargeAmount: PriceModel;
59
+ discountTotal: PriceModel;
60
+ discountBreakdown: Record<string, PriceModel>;
61
+ netChargeAmount: PriceModel;
42
62
  taxTotal: PriceModel;
63
+ taxBreakdown: Record<string, ChargeTaxBreakdownModel>;
43
64
  grandTotal: PriceModel;
44
65
  };
45
66
  type ChargeAttributes = CustomFieldAttributes & {
46
67
  id: string;
47
68
  name: LocalizedString;
69
+ type: ChargeType;
48
70
  category: string;
49
- lineItemId?: string;
50
- chargeType: ChargeType;
51
- impact?: ChargeImpact;
52
- taxTreatment?: ChargeTaxTreatment;
71
+ impact: ChargeImpact;
53
72
  pricing: ChargePricing;
73
+ lineItemId?: string;
54
74
  total: ChargeTotals;
55
75
  };
56
- type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId' | 'impact' | 'taxTreatment'> & {
76
+ type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId'> & {
57
77
  lineItemId?: string;
58
- impact?: ChargeImpact;
59
- taxTreatment?: ChargeTaxTreatment;
60
78
  };
61
79
  /**
62
80
  * Represents an additional charge (or discount if amount is negative) in a shopping container.
@@ -65,16 +83,11 @@ type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId' | 'impact' | 'ta
65
83
  declare class ChargeModel extends CustomFieldModel {
66
84
  protected id: string;
67
85
  protected name: LocalizedString;
86
+ protected type: ChargeType;
68
87
  protected category: string;
69
- protected lineItemId?: string;
70
- protected chargeType: ChargeType;
71
88
  protected impact: ChargeImpact;
72
- protected taxTreatment: ChargeTaxTreatment;
73
- protected pricing: {
74
- price: PriceModel;
75
- taxCategory: string;
76
- applicableTaxRule: FixedTaxRuleModel[];
77
- };
89
+ protected pricing: ChargePricingModel;
90
+ protected lineItemId?: string;
78
91
  protected total: ChargeTotalsModel;
79
92
  constructor(data: ChargeAttributes);
80
93
  /**
@@ -102,17 +115,12 @@ declare class ChargeModel extends CustomFieldModel {
102
115
  * Gets the charge type.
103
116
  * @returns The charge type enum value.
104
117
  */
105
- getChargeType(): ChargeType;
118
+ getType(): ChargeType;
106
119
  /**
107
120
  * Gets the charge impact (add or subtract).
108
121
  * @returns The charge impact.
109
122
  */
110
123
  getImpact(): ChargeImpact;
111
- /**
112
- * Gets how tax is treated for this charge.
113
- * @returns The tax treatment for this charge.
114
- */
115
- getTaxTreatment(): ChargeTaxTreatment;
116
124
  /**
117
125
  * Gets the related line item id, if any.
118
126
  * @returns The line item id or undefined.
@@ -122,11 +130,7 @@ declare class ChargeModel extends CustomFieldModel {
122
130
  * Gets the pricing details (models) for this charge.
123
131
  * @returns Pricing details including price, tax category, and tax rules.
124
132
  */
125
- getPricing(): {
126
- price: PriceModel;
127
- taxCategory: string;
128
- applicableTaxRule: FixedTaxRuleModel[];
129
- };
133
+ getPricing(): ChargePricingModel;
130
134
  /**
131
135
  * Gets the computed totals for this charge.
132
136
  * @returns Totals including discounts, taxes, and grand total.
@@ -136,17 +140,23 @@ declare class ChargeModel extends CustomFieldModel {
136
140
  * Gets the applicable tax rules for this charge.
137
141
  * @returns A list of tax rules.
138
142
  */
139
- getApplicableTaxRules(): FixedTaxRuleModel[];
143
+ getApplicableTaxRules(): TaxRuleModel[];
140
144
  /**
141
145
  * Updates the tax rule for this line item and recalculates totals.
142
146
  * @param taxRule - The new tax rule to apply.
143
147
  * @throws {Error} If the tax rule category does not match the item's tax category.
144
148
  */
145
- updateTax(taxRules: FixedTaxRuleModel[]): void;
149
+ updateTax(taxRules: TaxRuleModel[]): void;
150
+ /**
151
+ * Validates that there are no overlapping price brackets for any tax rules within the charge.
152
+ * @param taxRules - The list of tax rules to validate.
153
+ * @throws {CoincidingTaxBracketError} If any overlapping rules are found.
154
+ */
155
+ private validateTaxRules;
146
156
  /**
147
- * Updates the discounts applied to this line item and recalculates totals.
148
- * @param appliedDiscounts - List of coupons and their allocated discount amounts.
149
- */
157
+ * Updates the discounts applied to this line item and recalculates totals.
158
+ * @param appliedDiscounts - List of coupons and their allocated discount amounts.
159
+ */
150
160
  updateDiscounts(appliedDiscounts: {
151
161
  coupon: CouponModel;
152
162
  amount: PriceModel;
@@ -162,4 +172,4 @@ declare class ChargeModel extends CustomFieldModel {
162
172
  getDetails(): ChargeData;
163
173
  }
164
174
 
165
- export { type ChargeAttributes, type ChargeData, type ChargePricing, type ChargeTaxBreakdown, type ChargeTaxBreakdownModel, type ChargeTotals, type ChargeTotalsModel, ChargeModel as default };
175
+ export { type ChargeAttributes, type ChargeData, type ChargePricing, type ChargePricingModel, type ChargeTaxBreakdown, type ChargeTaxBreakdownModel, type ChargeTotals, type ChargeTotalsModel, ChargeModel as default };
@@ -1,62 +1,80 @@
1
1
  import { CustomFieldAttributes, CustomFieldModel } from './Base.js';
2
- import { b as PriceData, c as PriceModel, d as LocalizedString, L as LocaleCode } from '../Common-uAn7Sunn.js';
3
- import { TaxSystem, ChargeType, ChargeImpact, ChargeTaxTreatment } from './Enum.js';
4
- import { FixedTaxRuleData, FixedTaxRuleModel } from './TaxRule.js';
2
+ import { b as PriceData, c as PriceModel, d as LocalizedString, L as LocaleCode } from '../Common-Cq0_dPyJ.js';
3
+ import { TaxSystem, ChargeType, ChargeImpact } from './Enum.js';
4
+ import { TaxRuleData, TaxRuleModel } from './TaxRule.js';
5
5
  import CouponModel from './Coupon.js';
6
6
  import '../Auth/index.js';
7
7
 
8
8
  type ChargePricing = {
9
- price: PriceData;
9
+ /** Tax-inclusive original charge amount before any discounts. Always non-negative. */
10
+ chargeAmount: PriceData;
11
+ /** Tax category of the charge. */
10
12
  taxCategory: string;
11
- applicableTaxRule: FixedTaxRuleData[];
13
+ /** Tax rules applicable to the charge. */
14
+ applicableTaxRule: TaxRuleData[];
15
+ };
16
+ type ChargePricingModel = {
17
+ /** Tax-inclusive original charge amount before any discounts. Always non-negative. */
18
+ chargeAmount: PriceModel;
19
+ /** Tax category of the charge. */
20
+ taxCategory: string;
21
+ /** Tax rules applicable to the charge. */
22
+ applicableTaxRule: TaxRuleModel[];
12
23
  };
13
24
  type ChargeTaxBreakdown = {
25
+ /** Tax rate: e.g., 0.09 for 9% */
14
26
  rate: number;
15
- taxablePrice: PriceData;
16
- amount: PriceData;
27
+ /** Reverse-calculated pre-tax base from the netChargeAmount (post-discount) */
28
+ taxableAmount: PriceData;
29
+ /** Tax portion for this rule (netChargeAmount - taxableAmount) */
30
+ taxAmount: PriceData;
17
31
  system: TaxSystem;
18
32
  subSystem: string;
19
33
  };
20
34
  type ChargeTaxBreakdownModel = {
21
35
  rate: number;
22
- taxablePrice: PriceModel;
23
- amount: PriceModel;
36
+ taxableAmount: PriceModel;
37
+ taxAmount: PriceModel;
24
38
  system: TaxSystem;
25
39
  subSystem: string;
26
40
  };
27
41
  type ChargeTotals = {
28
- price: PriceData;
29
- discounts: Record<string, PriceData>;
30
- totalDiscount: PriceData;
31
- netPrice: PriceData;
32
- taxBreakdown: Record<string, ChargeTaxBreakdown>;
42
+ /** Tax-inclusive original charge amount before discounts (copied from pricing) */
43
+ chargeAmount: PriceData;
44
+ /** Coupon code -> discount amount mapping */
45
+ discountBreakdown: Record<string, PriceData>;
46
+ /** Sum of all discounts */
47
+ discountTotal: PriceData;
48
+ /** chargeAmount - totalDiscount → final tax-inclusive payable amount after discounts */
49
+ netChargeAmount: PriceData;
50
+ /** Sum of all taxAmount values */
33
51
  taxTotal: PriceData;
52
+ /** Tax breakdown per rule/category (reverse-calculated from netChargeAmount) */
53
+ taxBreakdown: Record<string, ChargeTaxBreakdown>;
54
+ /** Final payable/contribution amount. Equals netChargeAmount (tax-inclusive after discounts). */
34
55
  grandTotal: PriceData;
35
56
  };
36
57
  type ChargeTotalsModel = {
37
- price: PriceModel;
38
- discounts: Record<string, PriceModel>;
39
- totalDiscount: PriceModel;
40
- netPrice: PriceModel;
41
- taxBreakdown: Record<string, ChargeTaxBreakdownModel>;
58
+ chargeAmount: PriceModel;
59
+ discountTotal: PriceModel;
60
+ discountBreakdown: Record<string, PriceModel>;
61
+ netChargeAmount: PriceModel;
42
62
  taxTotal: PriceModel;
63
+ taxBreakdown: Record<string, ChargeTaxBreakdownModel>;
43
64
  grandTotal: PriceModel;
44
65
  };
45
66
  type ChargeAttributes = CustomFieldAttributes & {
46
67
  id: string;
47
68
  name: LocalizedString;
69
+ type: ChargeType;
48
70
  category: string;
49
- lineItemId?: string;
50
- chargeType: ChargeType;
51
- impact?: ChargeImpact;
52
- taxTreatment?: ChargeTaxTreatment;
71
+ impact: ChargeImpact;
53
72
  pricing: ChargePricing;
73
+ lineItemId?: string;
54
74
  total: ChargeTotals;
55
75
  };
56
- type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId' | 'impact' | 'taxTreatment'> & {
76
+ type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId'> & {
57
77
  lineItemId?: string;
58
- impact?: ChargeImpact;
59
- taxTreatment?: ChargeTaxTreatment;
60
78
  };
61
79
  /**
62
80
  * Represents an additional charge (or discount if amount is negative) in a shopping container.
@@ -65,16 +83,11 @@ type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId' | 'impact' | 'ta
65
83
  declare class ChargeModel extends CustomFieldModel {
66
84
  protected id: string;
67
85
  protected name: LocalizedString;
86
+ protected type: ChargeType;
68
87
  protected category: string;
69
- protected lineItemId?: string;
70
- protected chargeType: ChargeType;
71
88
  protected impact: ChargeImpact;
72
- protected taxTreatment: ChargeTaxTreatment;
73
- protected pricing: {
74
- price: PriceModel;
75
- taxCategory: string;
76
- applicableTaxRule: FixedTaxRuleModel[];
77
- };
89
+ protected pricing: ChargePricingModel;
90
+ protected lineItemId?: string;
78
91
  protected total: ChargeTotalsModel;
79
92
  constructor(data: ChargeAttributes);
80
93
  /**
@@ -102,17 +115,12 @@ declare class ChargeModel extends CustomFieldModel {
102
115
  * Gets the charge type.
103
116
  * @returns The charge type enum value.
104
117
  */
105
- getChargeType(): ChargeType;
118
+ getType(): ChargeType;
106
119
  /**
107
120
  * Gets the charge impact (add or subtract).
108
121
  * @returns The charge impact.
109
122
  */
110
123
  getImpact(): ChargeImpact;
111
- /**
112
- * Gets how tax is treated for this charge.
113
- * @returns The tax treatment for this charge.
114
- */
115
- getTaxTreatment(): ChargeTaxTreatment;
116
124
  /**
117
125
  * Gets the related line item id, if any.
118
126
  * @returns The line item id or undefined.
@@ -122,11 +130,7 @@ declare class ChargeModel extends CustomFieldModel {
122
130
  * Gets the pricing details (models) for this charge.
123
131
  * @returns Pricing details including price, tax category, and tax rules.
124
132
  */
125
- getPricing(): {
126
- price: PriceModel;
127
- taxCategory: string;
128
- applicableTaxRule: FixedTaxRuleModel[];
129
- };
133
+ getPricing(): ChargePricingModel;
130
134
  /**
131
135
  * Gets the computed totals for this charge.
132
136
  * @returns Totals including discounts, taxes, and grand total.
@@ -136,17 +140,23 @@ declare class ChargeModel extends CustomFieldModel {
136
140
  * Gets the applicable tax rules for this charge.
137
141
  * @returns A list of tax rules.
138
142
  */
139
- getApplicableTaxRules(): FixedTaxRuleModel[];
143
+ getApplicableTaxRules(): TaxRuleModel[];
140
144
  /**
141
145
  * Updates the tax rule for this line item and recalculates totals.
142
146
  * @param taxRule - The new tax rule to apply.
143
147
  * @throws {Error} If the tax rule category does not match the item's tax category.
144
148
  */
145
- updateTax(taxRules: FixedTaxRuleModel[]): void;
149
+ updateTax(taxRules: TaxRuleModel[]): void;
150
+ /**
151
+ * Validates that there are no overlapping price brackets for any tax rules within the charge.
152
+ * @param taxRules - The list of tax rules to validate.
153
+ * @throws {CoincidingTaxBracketError} If any overlapping rules are found.
154
+ */
155
+ private validateTaxRules;
146
156
  /**
147
- * Updates the discounts applied to this line item and recalculates totals.
148
- * @param appliedDiscounts - List of coupons and their allocated discount amounts.
149
- */
157
+ * Updates the discounts applied to this line item and recalculates totals.
158
+ * @param appliedDiscounts - List of coupons and their allocated discount amounts.
159
+ */
150
160
  updateDiscounts(appliedDiscounts: {
151
161
  coupon: CouponModel;
152
162
  amount: PriceModel;
@@ -162,4 +172,4 @@ declare class ChargeModel extends CustomFieldModel {
162
172
  getDetails(): ChargeData;
163
173
  }
164
174
 
165
- export { type ChargeAttributes, type ChargeData, type ChargePricing, type ChargeTaxBreakdown, type ChargeTaxBreakdownModel, type ChargeTotals, type ChargeTotalsModel, ChargeModel as default };
175
+ export { type ChargeAttributes, type ChargeData, type ChargePricing, type ChargePricingModel, type ChargeTaxBreakdown, type ChargeTaxBreakdownModel, type ChargeTotals, type ChargeTotalsModel, ChargeModel as default };
@@ -1,2 +1,2 @@
1
- 'use strict';var se=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var se__default=/*#__PURE__*/_interopDefault(se);var Z=r=>structuredClone(r),I=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:Z(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return Z(this.customFields)}},D=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 E=new Uint8Array(256),R=E.length;function j(){return R>E.length-16&&(se__default.default.randomFillSync(E),R=0),E.slice(R,R+=16)}var J=/^(?:[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"&&J.test(r)}var W=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 ce(r){if(!W(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 _=ce;function ue(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var le="6ba7b810-9dad-11d1-80b4-00c04fd430c8",de="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Q(r,e,t){function i(n,a,s,p){var o;if(typeof n=="string"&&(n=ue(n)),typeof a=="string"&&(a=_(a)),((o=a)===null||o===void 0?void 0:o.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(a),l.set(n,a.length),l=t(l),l[6]=l[6]&15|e,l[8]=l[8]&63|128,s){p=p||0;for(let f=0;f<16;++f)s[p+f]=l[f];return s}return v(l)}try{i.name=r;}catch{}return i.DNS=le,i.URL=de,i}var G={randomUUID:se__default.default.randomUUID};function pe(r,e,t){if(G.randomUUID&&!e&&!r)return G.randomUUID();r=r||{};let i=r.random||(r.rng||j)();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=pe;function he(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),se__default.default.createHash("sha1").update(r).digest()}var ee=he;var ye=Q("v5",80,ee),K=ye;var T={"en-IN":"en","kn-IN":"kn"};var te={INR:"\u20B9"},re={INR:"en-IN"};var U=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 L=class extends Error{constructor(e="Tax rule category mismatch."){super(`InvalidTaxRule: ${e}`),this.name="InvalidTaxRuleError";}},N=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},F=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},B=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},O=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},$=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var w=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},P=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},x=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";}},M=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}},C=class extends Error{constructor(e="Invalid charge data."){super(`InvalidCharge: ${e}`),this.name="InvalidChargeError";}};var A=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 M("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 M("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 w("Amount cannot be negative.");if(!e.currency)throw new P("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 x("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 x("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 x("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 x("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 x("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 x("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 x("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=re[t];if(!t||!n)throw new P("Invalid currency code for formatting.");let a=e,s=i.displayAsInteger?0:r.getDecimalPlaces(t),p={style:i.style??"currency",currency:t,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:s,maximumFractionDigits:s};i.displayAsInteger&&(a=Math.ceil(a));try{return new Intl.NumberFormat(n,p).format(a)}catch(o){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,o),`${te[t]??t} ${r.addThousandSeparators(a.toFixed(s))}`}}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 w("Amount cannot be negative for rounding.");if(t===void 0)throw new P("Invalid currency code for rounding.");let i=r.getDecimalPlaces(t),n=Math.pow(10,i);return Math.round(e*n)/n}};var k=class{baseUnitPrice;taxCategory;tiers;constructor(e){let t=new g(e.baseUnitPrice);if(!e.taxCategory)throw new N;let i=(e.tiers??[]).map(o=>({minQuantity:o.minQuantity,unitPrice:new g(o.unitPrice)})).sort((o,l)=>o.minQuantity-l.minQuantity);if(i.some(o=>o.minQuantity<=0))throw new F;let a=i.some(o=>o.unitPrice.getCurrency()!==t.getCurrency()),s=i.some((o,l)=>l>0&&o.unitPrice.compareTo(i[l-1].unitPrice)>0),p=i[0]?.unitPrice.compareTo(t)>0;if(a||s||p)throw new B("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 O;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 $(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 S=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[a,s]=n.split(":");s.startsWith("c+")?t[a]={name:s.slice(2)}:t[a]=s;}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,a)=>(e.pricing[a]&&(n[a]=new k(e.pricing[a])),n),{}),this.targetGender=e.targetGender,this.attributes=u.deepClone(e.attributes),this.specifications=u.deepClone(e.specifications),this.categories=u.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 a=r.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(a))throw new U(a);return i.add(a),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new A(n.images.primary),gallery:(n.images.gallery||[]).map(s=>new A(s))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?u.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:u.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[T[e]]??this.description.en:u.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[T[e]]??this.slug.en:u.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return u.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:u.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 u.deepClone(this.categories)}getSpecifications(e){return e?u.deepClone(this.specifications[e]??this.specifications[T[e]]??this.specifications.en):u.deepClone(this.specifications)}getSearchTags(e){return e?u.deepClone(this.searchTags[e]??this.searchTags[T[e]]??this.searchTags.en):u.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:u.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(a=>a.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 xe={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?K(r,e):V(),generateSearchId:(r,e)=>`${r}#${S.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:r=>{let[e,t]=r.split("#");return {key:e,selectionAttributes:S.parseSelectionAttributesKey(t)}},deepClone(r){return structuredClone(r)}},u=xe;var Y=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,a=n%1===0?n.toString():n.toFixed(2).replace(/\.?0+$/,"");return i?.percentageOnly?`${a}%`:e.getTaxSystem()==="GST"?`${e.getTaxSubSystem()} ${a}%`:`${e.getTaxSystem()} ${a}%`}};var z=class extends Y{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 I{id;name;category;lineItemId;chargeType;impact;taxTreatment;pricing;total;constructor(e){if(super(e),this.id=e.id,this.name=e.name,this.category=e.category,this.lineItemId=e.lineItemId,this.chargeType=e.chargeType,this.impact=e.impact??"ADD",this.taxTreatment=e.taxTreatment??"APPLY",this.pricing={price:new g(e.pricing.price),taxCategory:e.pricing.taxCategory,applicableTaxRule:e.pricing.applicableTaxRule.map(t=>new z(t))},this.chargeType!=="ADJUSTMENT"){if(this.impact!=="ADD")throw new C("Only adjustment charges can be subtractive.");if(this.taxTreatment!=="APPLY")throw new C("Non-adjustment charges must apply tax.")}else {if(this.taxTreatment!=="EXEMPT")throw new C("Adjustment charges must be tax exempt.");if(this.pricing.applicableTaxRule.length>0)throw new C("Adjustment charges cannot have tax rules.")}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?u.deepClone(this.name[e]??this.name[T[e]]??this.name.en):u.deepClone(this.name)}getCategory(){return this.category}getChargeType(){return this.chargeType}getImpact(){return this.impact}getTaxTreatment(){return this.taxTreatment}getLineItemId(){return this.lineItemId}getPricing(){return {price:this.pricing.price,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {price:this.total.price,discounts:{...this.total.discounts},netPrice:this.total.netPrice,totalDiscount:this.total.totalDiscount,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([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){if(this.chargeType==="ADJUSTMENT")throw new C("Adjustment charges cannot apply tax rules.");e.forEach(t=>{if(!t.appliesTo(this.pricing.taxCategory,t.getTaxCountry()))throw new L}),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);if(this.taxTreatment==="EXEMPT"){this.total={price:t,discounts:this.total.discounts,netPrice:n,totalDiscount:i,taxBreakdown:{},taxTotal:e,grandTotal:n};return}let a={},s=this.pricing.applicableTaxRule.reduce((m,b)=>m+b.getApplicableTaxRate(),0),p=n.divide(1+s).round(),o=s>0?n.subtract(p):e,l=e,f=this.pricing.applicableTaxRule.reduce((m,b)=>b.getApplicableTaxRate()>m.getApplicableTaxRate()?b:m),H=f.getTaxRuleId();this.pricing.applicableTaxRule.forEach(m=>{if(m.getTaxRuleId()===H)return;let b=m.getApplicableTaxRate(),X=s>0?o.multiply(b).divide(s).round():e;a[m.getTaxRuleId()]={rate:b,taxablePrice:p,amount:X,system:m.getTaxSystem(),subSystem:m.getTaxSubSystem()},l=l.add(X);});let ie=o.subtract(l);a[H]={rate:f.getApplicableTaxRate(),taxablePrice:p,amount:ie,system:f.getTaxSystem(),subSystem:f.getTaxSubSystem()};let ne=p,ae=n;this.total={price:t,discounts:this.total.discounts,netPrice:ne,totalDiscount:i,taxBreakdown:a,taxTotal:o,grandTotal:ae};}getDetails(){return {id:this.id,name:u.deepClone(this.name),category:this.category,lineItemId:this.lineItemId,chargeType:this.chargeType,impact:this.impact,taxTreatment:this.taxTreatment,pricing:{price:this.pricing.price.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(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 de=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var de__default=/*#__PURE__*/_interopDefault(de);var ne=r=>structuredClone(r),C=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:ne(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return ne(this.customFields)}},D=class extends C{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 O=new Uint8Array(256),F=O.length;function Z(){return F>O.length-16&&(de__default.default.randomFillSync(O),F=0),O.slice(F,F+=16)}var oe=/^(?:[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 me(r){return typeof r=="string"&&oe.test(r)}var se=me;var m=[];for(let r=0;r<256;++r)m.push((r+256).toString(16).slice(1));function k(r,e=0){return m[r[e+0]]+m[r[e+1]]+m[r[e+2]]+m[r[e+3]]+"-"+m[r[e+4]]+m[r[e+5]]+"-"+m[r[e+6]]+m[r[e+7]]+"-"+m[r[e+8]]+m[r[e+9]]+"-"+m[r[e+10]]+m[r[e+11]]+m[r[e+12]]+m[r[e+13]]+m[r[e+14]]+m[r[e+15]]}function pe(r){if(!se(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 ae=pe;function he(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var ye="6ba7b810-9dad-11d1-80b4-00c04fd430c8",fe="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function J(r,e,t){function i(n,o,u,l){var a;if(typeof n=="string"&&(n=he(n)),typeof o=="string"&&(o=ae(o)),((a=o)===null||a===void 0?void 0:a.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(o),c.set(n,o.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,u){l=l||0;for(let p=0;p<16;++p)u[l+p]=c[p];return u}return k(c)}try{i.name=r;}catch{}return i.DNS=ye,i.URL=fe,i}var X={randomUUID:de__default.default.randomUUID};function be(r,e,t){if(X.randomUUID&&!e&&!r)return X.randomUUID();r=r||{};let i=r.random||(r.rng||Z)();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 k(i)}var W=be;function Ae(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),de__default.default.createHash("sha1").update(r).digest()}var ce=Ae;var Ce=J("v5",80,ce),_=Ce;var T={"en-IN":"en","kn-IN":"kn"};var ue={INR:"\u20B9"},le={INR:"en-IN"};var $=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var x=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var z=class extends Error{constructor(e="Tax rule category mismatch."){super(`InvalidTaxRule: ${e}`),this.name="InvalidTaxRuleError";}},V=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},Q=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},j=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},G=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},K=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var M=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},I=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},b=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},f=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},R=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}},v=class extends Error{constructor(e="Invalid charge data."){super(`InvalidCharge: ${e}`),this.name="InvalidChargeError";}},E=class extends Error{constructor(e="Invalid charge tax rule."){super(`InvalidChargeTaxRule: ${e}`),this.name="InvalidChargeTaxRuleError";}};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 R("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 R("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 s=class r{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new M("Amount cannot be negative.");if(!e.currency)throw new I("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(r.getPrecisionPlaces(this.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}}getPreciseAmount(e){return parseFloat(e.toFixed(r.getPrecisionPlaces(this.currency)))}compareTo(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot add prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return new r({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot subtract prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return new r({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot multiply prices in different currencies.");return new r({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new r({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new f("Must be a non-negative number.")}divide(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot divide prices in different currencies.");return new r({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new r({amount:this.getPreciseAmount(this.amount/e),currency:this.currency});throw new f("Must be a positive number.")}min(...e){if(e.length===0)throw new f("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new b("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i},this)}max(...e){if(e.length===0)throw new f("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new b("Cannot compare prices in different currencies.")}else throw new f("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=le[t];if(!t||!n)throw new I("Invalid currency code for formatting.");let o=e,u=i.displayAsInteger?0:r.getDecimalPlaces(t),l={style:i.style??"currency",currency:t,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:u,maximumFractionDigits:u};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,l).format(o)}catch(a){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,a),`${ue[t]??t} ${r.addThousandSeparators(o.toFixed(u))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static getPrecisionPlaces(e){switch(e){case"INR":default:return 6}}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 M("Amount cannot be negative for rounding.");if(t===void 0)throw new I("Invalid currency code for rounding.");let i=r.getDecimalPlaces(t),n=Math.pow(10,i);return Math.round(e*n)/n}};var Y=class{baseUnitPrice;taxCategory;tiers;constructor(e){let t=new s(e.baseUnitPrice);if(!e.taxCategory)throw new V;let i=(e.tiers??[]).map(a=>({minQuantity:a.minQuantity,unitPrice:new s(a.unitPrice)})).sort((a,c)=>a.minQuantity-c.minQuantity);if(i.some(a=>a.minQuantity<=0))throw new Q;let o=i.some(a=>a.unitPrice.getCurrency()!==t.getCurrency()),u=i.some((a,c)=>c>0&&a.unitPrice.compareTo(i[c-1].unitPrice)>0),l=i[0]?.unitPrice.compareTo(t)>0;if(o||u||l)throw new j("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 G;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 K(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 S=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 x("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,u]=n.split(":");u.startsWith("c+")?t[o]={name:u.slice(2)}:t[o]=u;}return t}catch(t){throw new x(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 Y(e.pricing[o])),n),{}),this.targetGender=e.targetGender,this.attributes=d.deepClone(e.attributes),this.specifications=d.deepClone(e.specifications),this.categories=d.deepClone(e.categories);let i=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new x("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let o=r.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(o))throw new $(o);return i.add(o),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new P(n.images.primary),gallery:(n.images.gallery||[]).map(u=>new P(u))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?d.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:d.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[T[e]]??this.description.en:d.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[T[e]]??this.slug.en:d.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return d.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:d.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 d.deepClone(this.categories)}getSpecifications(e){return e?d.deepClone(this.specifications[e]??this.specifications[T[e]]??this.specifications.en):d.deepClone(this.specifications)}getSearchTags(e){return e?d.deepClone(this.searchTags[e]??this.searchTags[T[e]]??this.searchTags.en):d.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:d.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 x("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 x(`Selection attribute '${t}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new x(`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 x(`Selection attribute '${t}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(o=>o.name===n.name)<0)throw new x(`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 Ie={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?_(r,e):W(),generateSearchId:(r,e)=>`${r}#${S.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:r=>{let[e,t]=r.split("#");return {key:e,selectionAttributes:S.parseSelectionAttributesKey(t)}},deepClone(r){return structuredClone(r)}},d=Ie;var q=class extends C{taxRuleId;taxCategory;taxSystem;taxSubSystem;country;rate;minPrice;maxPrice;effectiveFrom;effectiveTo;constructor(e){super(e),this.taxRuleId=e.taxRuleId,this.taxSystem=e.taxSystem,this.taxSubSystem=e.taxSubSystem,this.taxCategory=e.taxCategory,this.country=e.country,this.rate=e.rate,this.minPrice=new s(e.minPrice),this.maxPrice=e.maxPrice?new s(e.maxPrice):void 0,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}getCountry(){return this.country}getRate(){return this.rate}getMinPrice(){return this.minPrice}getMaxPrice(){return this.maxPrice}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),rate:this.getRate(),minPrice:this.getMinPrice().getDetails(),maxPrice:this.getMaxPrice()?.getDetails(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0,customFields:this.getAllCustomFields()}}appliesTo(e,t,i,n=new Date){return this.taxCategory===e&&this.country===t&&(i?this.minPrice.compareTo(i)<=0&&(this.maxPrice?this.maxPrice.compareTo(i)>=0:!0):!0)&&Date.parse(this.effectiveFrom)<=n.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=n.getTime():!0)}getApplicableTaxRate(e){return this.appliesTo(this.taxCategory,this.country,e)?this.rate:0}calculateTax(e){return this.appliesTo(this.taxCategory,this.country,e)?e.multiply(this.rate):e.zero()}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 ee=class extends C{id;name;type;category;impact;pricing;lineItemId;total;constructor(e){if(super(e),this.id=e.id,this.name=e.name,this.type=e.type,this.category=e.category,this.impact=e.impact,this.lineItemId=e.lineItemId,this.pricing={chargeAmount:new s(e.pricing.chargeAmount),taxCategory:e.pricing.taxCategory,applicableTaxRule:e.pricing.applicableTaxRule.map(t=>new q(t))},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new v("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={chargeAmount:new s(e.total.chargeAmount),discountTotal:new s(e.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(e.total.discountBreakdown).map(([t,i])=>[t,new s(i)])),netChargeAmount:new s(e.total.netChargeAmount),taxBreakdown:Object.fromEntries(Object.entries(e.total.taxBreakdown).map(([t,i])=>[t,{rate:i.rate,taxableAmount:new s(i.taxableAmount),taxAmount:new s(i.taxAmount),system:i.system,subSystem:i.subSystem}])),taxTotal:new s(e.total.taxTotal),grandTotal:new s(e.total.grandTotal)};}getId(){return this.id}getName(e){return e?d.deepClone(this.name[e]??this.name[T[e]]??this.name.en):d.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getPricing(){return {chargeAmount:this.pricing.chargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {chargeAmount:this.total.chargeAmount,discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},netChargeAmount:this.total.netChargeAmount,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,t])=>[e,{rate:t.rate,taxableAmount:t.taxableAmount,taxAmount:t.taxAmount,system:t.system,subSystem:t.subSystem}])),grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(e){if(this.type==="ADJUSTMENT"&&e.length>0)throw new v("Adjustment charges cannot apply tax rules.");e.forEach(t=>{if(!t.appliesTo(this.pricing.taxCategory,t.getCountry()))throw new z}),this.validateTaxRules(e),this.pricing.applicableTaxRule=e,this.calculateTotals();}validateTaxRules(e){if(this.impact==="SUBTRACT"&&e.some(t=>t.getRate()>0))throw new E("Subtractive charges cannot have positive tax rates.");for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++){let n=e[t],o=e[i],u=n.getMinPrice(),l=n.getMaxPrice(),a=o.getMinPrice(),c=o.getMaxPrice();if((c?u.compareTo(c)<=0:!0)&&(l?a.compareTo(l)<=0:!0)&&!(u.compareTo(a)===0&&(!l&&!c||l&&c&&l.compareTo(c)===0)))throw new E(`Overlapping rules found: [${n.getTaxRuleId()}: ${u.getAmount()}-${l?.getAmount()??"\u221E"}] and [${o.getTaxRuleId()}: ${a.getAmount()}-${c?.getAmount()??"\u221E"}]`)}}updateDiscounts(e){let t={};e.forEach(i=>{t[i.coupon.getCode()]=i.amount;}),this.total.discountBreakdown=t,this.calculateTotals();}calculateTotals(){let e=this.pricing.chargeAmount.zero(),t=this.pricing.chargeAmount,i=Object.values(this.total.discountBreakdown).reduce((h,y)=>h.add(y),e),n=t.subtract(i),o={},u=this.pricing.applicableTaxRule.reduce((h,y)=>h+y.getApplicableTaxRate(n),0);if(u<=0){this.total={chargeAmount:t,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:n,taxTotal:e,taxBreakdown:{},grandTotal:n};return}let l=t.getCurrency(),a=t.getAmount(),c=1e3,p=s.getRoundedAmount(a/(1+u),l),L=p,te=Number.POSITIVE_INFINITY;for(let h=0;h<c;h++){let y=new s({amount:p,currency:l}),U=this.pricing.applicableTaxRule.sort((A,w)=>w.getApplicableTaxRate(y)-A.getApplicableTaxRate(y)).map(A=>s.getRoundedAmount(p*A.getApplicableTaxRate(y),l)).reduce((A,w)=>A+w,0),B=p+U-a,ge=this.pricing.applicableTaxRule.reduce((A,w)=>A+w.getApplicableTaxRate(y),0);if(Math.abs(B)<Math.abs(te)&&(te=B,L=p),B===0||(p=p-B/(1+ge),p<0||p>a))break}let N=new s({amount:L,currency:l}),H=e;this.pricing.applicableTaxRule.sort((h,y)=>y.getApplicableTaxRate(N)-h.getApplicableTaxRate(N)).forEach(h=>{let y=h.getApplicableTaxRate(N),ie=s.getRoundedAmount(L*y,l),U=new s({amount:ie,currency:l});o[h.getTaxRuleId()]={rate:y,taxableAmount:N,taxAmount:U,system:h.getTaxSystem(),subSystem:h.getTaxSubSystem()},H=H.add(U);});let re=t;this.total={chargeAmount:t,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:re,taxBreakdown:o,taxTotal:H,grandTotal:re};}getDetails(){return {id:this.id,name:d.deepClone(this.name),type:this.type,category:this.category,pricing:{chargeAmount:this.pricing.chargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(t=>t.getDetails())},impact:this.impact,lineItemId:this.lineItemId,total:{chargeAmount:this.total.chargeAmount.getDetails(),discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([t,i])=>[t,i.getDetails()])),netChargeAmount:this.total.netChargeAmount.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,i])=>[t,{rate:i.rate,taxableAmount:i.taxableAmount.getDetails(),taxAmount:i.taxAmount.getDetails(),system:i.system,subSystem:i.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};module.exports=ee;//# sourceMappingURL=Charge.js.map
2
2
  //# sourceMappingURL=Charge.js.map