b23-lib 2.0.6 → 2.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 (53) hide show
  1. package/dist/Auth/index.js +1 -1
  2. package/dist/Auth/index.js.map +1 -1
  3. package/dist/Auth/index.mjs +1 -1
  4. package/dist/Classes/Cart.js +1 -1
  5. package/dist/Classes/Cart.js.map +1 -1
  6. package/dist/Classes/Cart.mjs +1 -1
  7. package/dist/Classes/Cart.mjs.map +1 -1
  8. package/dist/Classes/Coupon.js +1 -1
  9. package/dist/Classes/Coupon.js.map +1 -1
  10. package/dist/Classes/Coupon.mjs +1 -1
  11. package/dist/Classes/Inventory.d.mts +3 -3
  12. package/dist/Classes/Inventory.d.ts +3 -3
  13. package/dist/Classes/Inventory.js +1 -1
  14. package/dist/Classes/Inventory.js.map +1 -1
  15. package/dist/Classes/Inventory.mjs +1 -1
  16. package/dist/Classes/Inventory.mjs.map +1 -1
  17. package/dist/Classes/LineItem.d.mts +3 -3
  18. package/dist/Classes/LineItem.d.ts +3 -3
  19. package/dist/Classes/LineItem.js +1 -1
  20. package/dist/Classes/LineItem.js.map +1 -1
  21. package/dist/Classes/LineItem.mjs +1 -1
  22. package/dist/Classes/Order.js +1 -1
  23. package/dist/Classes/Order.js.map +1 -1
  24. package/dist/Classes/Order.mjs +1 -1
  25. package/dist/Classes/Product.js +1 -1
  26. package/dist/Classes/Product.js.map +1 -1
  27. package/dist/Classes/Product.mjs +1 -1
  28. package/dist/Classes/ShoppingContainer.js +1 -1
  29. package/dist/Classes/ShoppingContainer.js.map +1 -1
  30. package/dist/Classes/ShoppingContainer.mjs +1 -1
  31. package/dist/Classes/TaxRule.js +1 -1
  32. package/dist/Classes/TaxRule.js.map +1 -1
  33. package/dist/Classes/TaxRule.mjs +1 -1
  34. package/dist/chunk-I3HHVQBK.mjs +2 -0
  35. package/dist/chunk-I3HHVQBK.mjs.map +1 -0
  36. package/dist/{chunk-LTJSCESA.mjs → chunk-K7AFM4R4.mjs} +2 -2
  37. package/dist/{chunk-LTJSCESA.mjs.map → chunk-K7AFM4R4.mjs.map} +1 -1
  38. package/dist/chunk-MALFMLW4.mjs +2 -0
  39. package/dist/chunk-MALFMLW4.mjs.map +1 -0
  40. package/dist/{chunk-JEQETTRX.mjs → chunk-T7SS4FEF.mjs} +2 -2
  41. package/dist/{chunk-JEQETTRX.mjs.map → chunk-T7SS4FEF.mjs.map} +1 -1
  42. package/dist/{chunk-CM5HQBRG.mjs → chunk-YSG6TG5B.mjs} +2 -2
  43. package/dist/{chunk-CM5HQBRG.mjs.map → chunk-YSG6TG5B.mjs.map} +1 -1
  44. package/dist/index.d.mts +2 -2
  45. package/dist/index.d.ts +2 -2
  46. package/dist/index.js +2 -2
  47. package/dist/index.js.map +1 -1
  48. package/dist/index.mjs +1 -1
  49. package/package.json +1 -1
  50. package/dist/chunk-54XPNXR6.mjs +0 -2
  51. package/dist/chunk-54XPNXR6.mjs.map +0 -1
  52. package/dist/chunk-FX672BZS.mjs +0 -2
  53. package/dist/chunk-FX672BZS.mjs.map +0 -1
@@ -1,2 +1,2 @@
1
- import {a}from'../chunk-JEQETTRX.mjs';import'../chunk-54XPNXR6.mjs';import'../chunk-LTJSCESA.mjs';import'../chunk-5KD2EW7O.mjs';import'../chunk-CM5HQBRG.mjs';import {b}from'../chunk-FX672BZS.mjs';import'../chunk-KWH7GE23.mjs';import'../chunk-54RUAXYE.mjs';import'../chunk-72DR3HF2.mjs';import'../chunk-NUTKOIGY.mjs';import {a as a$1}from'../chunk-NJKSUUOB.mjs';import'../chunk-55SOBG62.mjs';var u=(r=>(r.ACTIVE="ACTIVE",r.FROZEN="FROZEN",r.MERGED="MERGED",r.ORDERED="ORDERED",r))(u||{}),p={expiresAtInSeconds:120*24*60*60},c=class extends a{state;expireAt;config;constructor(t,e=new Date,i=p){super(t,e),this.state=t.state,this.expireAt=t.expireAt&&typeof t.expireAt=="number"?t.expireAt:Math.floor(e.getTime()/1e3)+i.expiresAtInSeconds,this.config=i;}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.couponTotal={},this.calculateTotals();}validateLineItems(t){this.lineItems=this.lineItems.map(e=>{try{e.updateProductData(t[e.getProductKey()],this.country,this.currency);}catch(i){console.error(`Error recalculating line item ${e.getId()}:`,i),e.clearLineItem();}return e}).filter(e=>e.getId()),this.calculateTotals();}addLineItem(t){let e=t.getProductKey(),i=t.getSelectionAttribute(),r=b.generateSelectionAttributesKey(i),s=this.lineItems.findIndex(n=>n.getProductKey()===e&&b.generateSelectionAttributesKey(n.getSelectionAttribute())===r);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,i){let r=this.lineItems,s=r.findIndex(n=>n.getId()===t);if(s<0)throw new a$1(t);return r[s].addSubItems([{size:e,quantity:i}],!1),this.calculateTotals(),s}removeLineItem(t){let i=this.lineItems.findIndex(r=>r.getId()===t);if(i<0)throw new a$1(t);return this.lineItems.splice(i,1),this.calculateTotals(),i}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-T7SS4FEF.mjs';import'../chunk-I3HHVQBK.mjs';import'../chunk-K7AFM4R4.mjs';import'../chunk-5KD2EW7O.mjs';import'../chunk-YSG6TG5B.mjs';import {b}from'../chunk-MALFMLW4.mjs';import'../chunk-KWH7GE23.mjs';import'../chunk-54RUAXYE.mjs';import'../chunk-72DR3HF2.mjs';import'../chunk-NUTKOIGY.mjs';import {a as a$1}from'../chunk-NJKSUUOB.mjs';import'../chunk-55SOBG62.mjs';var u=(r=>(r.ACTIVE="ACTIVE",r.FROZEN="FROZEN",r.MERGED="MERGED",r.ORDERED="ORDERED",r))(u||{}),p={expiresAtInSeconds:120*24*60*60},c=class extends a{state;expireAt;config;constructor(t,e=new Date,i=p){super(t,e),this.state=t.state,this.expireAt=t.expireAt&&typeof t.expireAt=="number"?t.expireAt:Math.floor(e.getTime()/1e3)+i.expiresAtInSeconds,this.config=i;}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.couponTotal={},this.calculateTotals();}validateLineItems(t){this.lineItems=this.lineItems.map(e=>{try{e.updateProductData(t[e.getProductKey()],this.country,this.currency);}catch(i){console.error(`Error recalculating line item ${e.getId()}:`,i),e.clearLineItem();}return e}).filter(e=>e.getId()),this.calculateTotals();}addLineItem(t){let e=t.getProductKey(),i=t.getSelectionAttributes(),r=b.generateSelectionAttributesKey(i),s=this.lineItems.findIndex(n=>n.getProductKey()===e&&b.generateSelectionAttributesKey(n.getSelectionAttributes())===r);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,i){let r=this.lineItems,s=r.findIndex(n=>n.getId()===t);if(s<0)throw new a$1(t);return r[s].addSubItems([{size:e,quantity:i}],!1),this.calculateTotals(),s}removeLineItem(t){let i=this.lineItems.findIndex(r=>r.getId()===t);if(i<0)throw new a$1(t);return this.lineItems.splice(i,1),this.calculateTotals(),i}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","selectionAttribute","selectionAttributeKey","ProductModel","index","item","lineItemId","size","quantity","lineItems","LineItemNotFoundError"],"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.couponTotal = {};\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 selectionAttribute = newLineItem.getSelectionAttribute();\r\n const selectionAttributeKey = ProductModel.generateSelectionAttributesKey(selectionAttribute);\r\n let index = this.lineItems.findIndex(\r\n (item) => item.getProductKey() === productKey && ProductModel.generateSelectionAttributesKey(item.getSelectionAttribute()) === 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.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"],"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.couponTotal = {};\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.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,2 +1,2 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var Z=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Z__default=/*#__PURE__*/_interopDefault(Z);var S=new Uint8Array(256),T=S.length;function O(){return T>S.length-16&&(Z__default.default.randomFillSync(S),T=0),S.slice(T,T+=16)}var k=/^(?:[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 X(r){return typeof r=="string"&&k.test(r)}var G=X;var d=[];for(let r=0;r<256;++r)d.push((r+256).toString(16).slice(1));function M(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 W(r){if(!G(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 Q=W;function J(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var _="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ee="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function F(r,e,t){function i(n,o,s,p){var a;if(typeof n=="string"&&(n=J(n)),typeof o=="string"&&(o=Q(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,s){p=p||0;for(let C=0;C<16;++C)s[p+C]=c[C];return s}return M(c)}try{i.name=r;}catch{}return i.DNS=_,i.URL=ee,i}var V={randomUUID:Z__default.default.randomUUID};function re(r,e,t){if(V.randomUUID&&!e&&!r)return V.randomUUID();r=r||{};let i=r.random||(r.rng||O)();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 M(i)}var z=re;function ne(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),Z__default.default.createHash("sha1").update(r).digest()}var K=ne;var oe=F("v5",80,K),B=oe;var f=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){this.customFields={...e.customFields},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};}getCustomField(e){return this.customFields[e]??null}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return {...this.customFields}}};var y={"en-IN":"en","kn-IN":"kn"};var j={INR:"\u20B9"},H={INR:"en-IN"};var I=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var w=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},v=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},E=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},L=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},R=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var x=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},b=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},m=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},g=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},D=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};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 D("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 D("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 h=class r{amount;currency;constructor(e){if(e.amount<0)throw new x("Amount cannot be negative.");if(!e.currency)throw new b("Currency code is required.");this.amount=e.amount,this.currency=e.currency;}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(e){if(e instanceof r){if(this.currency!==e.getCurrency())throw new m("Cannot compare prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return this.amount-e.getAmount()}add(e){if(e instanceof r){if(this.currency!==e.getCurrency())throw new m("Cannot add prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return new r({amount:this.amount+e.getAmount(),currency:this.currency})}subtract(e){if(e instanceof r){if(this.currency!==e.getCurrency())throw new m("Cannot subtract prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return new r({amount:this.amount-e.getAmount(),currency:this.currency})}multiply(e){if(e instanceof r){if(this.currency!==e.getCurrency())throw new m("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 g("Must be a non-negative number.")}divide(e){if(e instanceof r){if(this.currency!==e.getCurrency())throw new m("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 g("Must be a positive number.")}min(...e){if(e.length===0)throw new g("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(i instanceof r){if(t.getCurrency()!==i.getCurrency())throw new m("Cannot compare prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i})}max(...e){if(e.length===0)throw new g("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(i instanceof r){if(t.getCurrency()!==i.getCurrency())throw new m("Cannot compare prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return t.compareTo(i)>0?t:i})}zero(){return new r({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new r({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return r.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return r.getFormattedString(this.amount,this.currency)}static getFormattedString(e,t,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=H[t];if(!t||!n)throw new b("Invalid currency code for formatting.");let o=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&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,p).format(o)}catch(a){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,a),`${j[t]??t} ${r.addThousandSeparators(o.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 x("Amount cannot be negative for rounding.");if(t===void 0)throw new b("Invalid currency code for rounding.");let i=r.getDecimalPlaces(t),n=Math.pow(10,i);return Math.round(e*n)/n}};var N=class{baseUnitPrice;taxCategory;tiers;constructor(e){let t=new h(e.baseUnitPrice);if(!e.taxCategory)throw new w;let i=(e.tiers??[]).map(a=>({minQuantity:a.minQuantity,unitPrice:new h(a.unitPrice)})).sort((a,c)=>a.minQuantity-c.minQuantity);if(i.some(a=>a.minQuantity<=0))throw new v;let o=i.some(a=>a.unitPrice.getCurrency()!==t.getCurrency()),s=i.some((a,c)=>c>0&&a.unitPrice.compareTo(i[c-1].unitPrice)>0),p=i[0]?.unitPrice.compareTo(t)>0;if(o||s||p)throw new E("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 L;for(let t=this.tiers.length-1;t>=0;t--)if(e>=this.tiers[t].minQuantity)return this.tiers[t];throw new R(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 P=class r extends f{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 I("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,s]=n.split(":");s.startsWith("c+")?t[o]={name:s.slice(2)}:t[o]=s;}return t}catch(t){throw new I(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((i,n)=>(e.pricing[n]&&(i[n]=new N(e.pricing[n])),i),{}),this.targetGender=e.targetGender,this.attributes=l.deepClone(e.attributes),this.specifications=l.deepClone(e.specifications),this.categories=l.deepClone(e.categories),this.variants=(e.variants||[]).map(i=>({sku:i.sku,selectionAttributes:i.selectionAttributes,images:{primary:new A(i.images.primary),gallery:(i.images.gallery||[]).map(n=>new A(n))}})),this.isActive=e.isActive,this.searchTags=e.searchTags?l.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[y[e]]??this.name.en:l.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[y[e]]??this.description.en:l.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[y[e]]??this.slug.en:l.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:this.pricing}getAttributes(){return l.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 l.deepClone(this.categories)}getSpecifications(e){return e?l.deepClone(this.specifications[e]??this.specifications[y[e]]??this.specifications.en):l.deepClone(this.specifications)}getSearchTags(e){return e?l.deepClone(this.searchTags[e]??this.searchTags[y[e]]??this.searchTags.en):l.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:l.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}}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 se={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?B(r,e):z(),generateSearchId:(r,e)=>`${r}#${P.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:r=>{let[e,t]=r.split("#");return {key:e,selectionAttribute:t}},deepClone(r){return structuredClone(r)}},l=se;var ae=(t=>(t.COUPON="coupon",t.AUTOMATIC="automatic",t))(ae||{}),ce=(t=>(t.FLAT="flat",t.PERCENTAGE="percentage",t))(ce||{}),ue=(t=>(t.SHIPPING="SHIPPING",t.CUSTOMER="CUSTOMER",t))(ue||{}),le=(t=>(t.ALL="all",t.FTB="ftb",t))(le||{}),$=class extends f{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(e,t=new Date){if(super(e,t),this.couponCode=e.couponCode,this.name=l.deepClone(e.name),this.description=l.deepClone(e.description),this.type=e.type,this.customerId=e.customerId,this.validFrom=e.validFrom&&Date.parse(e.validFrom)?new Date(e.validFrom).toISOString():t.toISOString(),this.validTo=e.validTo&&Date.parse(e.validTo)?new Date(e.validTo).toISOString():t.toISOString(),this.minCartValue=Object.keys(e.minCartValue).reduce((i,n)=>{let o=e.minCartValue[n];return o&&(i[n]=new h(o)),i},{}),this.maxCartDiscount=Object.keys(e.maxCartDiscount).reduce((i,n)=>{let o=e.maxCartDiscount[n];return o&&(i[n]=new h(o)),i},{}),this.discountMethod=e.discountMethod,this.percentageValue=e.percentageValue??0,this.percentageValue>100)throw new g("Percentage value cannot be greater than 100");this.applicableTo=e.applicableTo,this.category=e.category;}getCode(){return this.couponCode}getName(e){return e?this.name[e]??this.name[y[e]]??this.name.en:{...this.name}}getDescription(e){return e?this.description[e]??this.description[y[e]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(e){return e?this.minCartValue[e]:this.minCartValue}getMaxCartDiscount(e){return e?this.maxCartDiscount[e]:this.maxCartDiscount}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:Object.keys(this.getMinCartValue()).reduce((e,t)=>{let i=this.getMinCartValue(t);return i&&(e[t]=i.getDetails()),e},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((e,t)=>{let i=this.getMaxCartDiscount(t);return i&&(e[t]=i.getDetails()),e},{}),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(e){return this.applicableTo==="all"||this.applicableTo==="ftb"&&e}calculateApplicableCouponDiscount(e,t,i,n,o=!0){let s=new h({amount:0,currency:n}),p;if(o&&!this.isActive())return s;let a=this.getMinCartValue(i),c=this.getMaxCartDiscount(i);if(!a||a.compareTo(e)>0||!c)return s;let C=this.getCategory(),Y=this.getDiscountMethod(),U=C==="SHIPPING"?t:e;if(U.getAmount()<=0)return s;switch(Y){case"flat":let q=c;p=U.min(q);break;case"percentage":p=U.multiply(this.getPercentageValue()/100).round();break;default:return s}return p.min(c)}};exports.ApplicableTo=le;exports.CouponCategory=ue;exports.CouponDiscountMethod=ce;exports.CouponType=ae;exports.default=$;//# sourceMappingURL=Coupon.js.map
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var Z=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Z__default=/*#__PURE__*/_interopDefault(Z);var S=new Uint8Array(256),T=S.length;function O(){return T>S.length-16&&(Z__default.default.randomFillSync(S),T=0),S.slice(T,T+=16)}var k=/^(?:[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 X(r){return typeof r=="string"&&k.test(r)}var G=X;var d=[];for(let r=0;r<256;++r)d.push((r+256).toString(16).slice(1));function M(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 W(r){if(!G(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 Q=W;function J(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var _="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ee="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function F(r,e,t){function i(n,o,s,p){var a;if(typeof n=="string"&&(n=J(n)),typeof o=="string"&&(o=Q(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,s){p=p||0;for(let C=0;C<16;++C)s[p+C]=c[C];return s}return M(c)}try{i.name=r;}catch{}return i.DNS=_,i.URL=ee,i}var V={randomUUID:Z__default.default.randomUUID};function re(r,e,t){if(V.randomUUID&&!e&&!r)return V.randomUUID();r=r||{};let i=r.random||(r.rng||O)();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 M(i)}var z=re;function ne(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),Z__default.default.createHash("sha1").update(r).digest()}var K=ne;var oe=F("v5",80,K),B=oe;var f=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){this.customFields={...e.customFields},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};}getCustomField(e){return this.customFields[e]??null}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return {...this.customFields}}};var y={"en-IN":"en","kn-IN":"kn"};var j={INR:"\u20B9"},H={INR:"en-IN"};var x=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var w=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},v=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},E=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},L=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},R=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";}},b=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},m=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},g=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},P=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};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 P("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 P("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 h=class r{amount;currency;constructor(e){if(e.amount<0)throw new D("Amount cannot be negative.");if(!e.currency)throw new b("Currency code is required.");this.amount=e.amount,this.currency=e.currency;}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(e){if(e instanceof r){if(this.currency!==e.getCurrency())throw new m("Cannot compare prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return this.amount-e.getAmount()}add(e){if(e instanceof r){if(this.currency!==e.getCurrency())throw new m("Cannot add prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return new r({amount:this.amount+e.getAmount(),currency:this.currency})}subtract(e){if(e instanceof r){if(this.currency!==e.getCurrency())throw new m("Cannot subtract prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return new r({amount:this.amount-e.getAmount(),currency:this.currency})}multiply(e){if(e instanceof r){if(this.currency!==e.getCurrency())throw new m("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 g("Must be a non-negative number.")}divide(e){if(e instanceof r){if(this.currency!==e.getCurrency())throw new m("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 g("Must be a positive number.")}min(...e){if(e.length===0)throw new g("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(i instanceof r){if(t.getCurrency()!==i.getCurrency())throw new m("Cannot compare prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i})}max(...e){if(e.length===0)throw new g("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(i instanceof r){if(t.getCurrency()!==i.getCurrency())throw new m("Cannot compare prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return t.compareTo(i)>0?t:i})}zero(){return new r({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new r({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return r.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return r.getFormattedString(this.amount,this.currency)}static getFormattedString(e,t,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=H[t];if(!t||!n)throw new b("Invalid currency code for formatting.");let o=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&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,p).format(o)}catch(a){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,a),`${j[t]??t} ${r.addThousandSeparators(o.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 D("Amount cannot be negative for rounding.");if(t===void 0)throw new b("Invalid currency code for rounding.");let i=r.getDecimalPlaces(t),n=Math.pow(10,i);return Math.round(e*n)/n}};var N=class{baseUnitPrice;taxCategory;tiers;constructor(e){let t=new h(e.baseUnitPrice);if(!e.taxCategory)throw new w;let i=(e.tiers??[]).map(a=>({minQuantity:a.minQuantity,unitPrice:new h(a.unitPrice)})).sort((a,c)=>a.minQuantity-c.minQuantity);if(i.some(a=>a.minQuantity<=0))throw new v;let o=i.some(a=>a.unitPrice.getCurrency()!==t.getCurrency()),s=i.some((a,c)=>c>0&&a.unitPrice.compareTo(i[c-1].unitPrice)>0),p=i[0]?.unitPrice.compareTo(t)>0;if(o||s||p)throw new E("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 L;for(let t=this.tiers.length-1;t>=0;t--)if(e>=this.tiers[t].minQuantity)return this.tiers[t];throw new R(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 I=class r extends f{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,s]=n.split(":");s.startsWith("c+")?t[o]={name:s.slice(2)}:t[o]=s;}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((i,n)=>(e.pricing[n]&&(i[n]=new N(e.pricing[n])),i),{}),this.targetGender=e.targetGender,this.attributes=l.deepClone(e.attributes),this.specifications=l.deepClone(e.specifications),this.categories=l.deepClone(e.categories),this.variants=(e.variants||[]).map(i=>({sku:i.sku,selectionAttributes:i.selectionAttributes,images:{primary:new A(i.images.primary),gallery:(i.images.gallery||[]).map(n=>new A(n))}})),this.isActive=e.isActive,this.searchTags=e.searchTags?l.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[y[e]]??this.name.en:l.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[y[e]]??this.description.en:l.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[y[e]]??this.slug.en:l.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:this.pricing}getAttributes(){return l.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 l.deepClone(this.categories)}getSpecifications(e){return e?l.deepClone(this.specifications[e]??this.specifications[y[e]]??this.specifications.en):l.deepClone(this.specifications)}getSearchTags(e){return e?l.deepClone(this.searchTags[e]??this.searchTags[y[e]]??this.searchTags.en):l.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:l.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}}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 se={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?B(r,e):z(),generateSearchId:(r,e)=>`${r}#${I.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:r=>{let[e,t]=r.split("#");return {key:e,selectionAttributes:I.parseSelectionAttributesKey(t)}},deepClone(r){return structuredClone(r)}},l=se;var ae=(t=>(t.COUPON="coupon",t.AUTOMATIC="automatic",t))(ae||{}),ce=(t=>(t.FLAT="flat",t.PERCENTAGE="percentage",t))(ce||{}),ue=(t=>(t.SHIPPING="SHIPPING",t.CUSTOMER="CUSTOMER",t))(ue||{}),le=(t=>(t.ALL="all",t.FTB="ftb",t))(le||{}),$=class extends f{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(e,t=new Date){if(super(e,t),this.couponCode=e.couponCode,this.name=l.deepClone(e.name),this.description=l.deepClone(e.description),this.type=e.type,this.customerId=e.customerId,this.validFrom=e.validFrom&&Date.parse(e.validFrom)?new Date(e.validFrom).toISOString():t.toISOString(),this.validTo=e.validTo&&Date.parse(e.validTo)?new Date(e.validTo).toISOString():t.toISOString(),this.minCartValue=Object.keys(e.minCartValue).reduce((i,n)=>{let o=e.minCartValue[n];return o&&(i[n]=new h(o)),i},{}),this.maxCartDiscount=Object.keys(e.maxCartDiscount).reduce((i,n)=>{let o=e.maxCartDiscount[n];return o&&(i[n]=new h(o)),i},{}),this.discountMethod=e.discountMethod,this.percentageValue=e.percentageValue??0,this.percentageValue>100)throw new g("Percentage value cannot be greater than 100");this.applicableTo=e.applicableTo,this.category=e.category;}getCode(){return this.couponCode}getName(e){return e?this.name[e]??this.name[y[e]]??this.name.en:{...this.name}}getDescription(e){return e?this.description[e]??this.description[y[e]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(e){return e?this.minCartValue[e]:this.minCartValue}getMaxCartDiscount(e){return e?this.maxCartDiscount[e]:this.maxCartDiscount}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:Object.keys(this.getMinCartValue()).reduce((e,t)=>{let i=this.getMinCartValue(t);return i&&(e[t]=i.getDetails()),e},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((e,t)=>{let i=this.getMaxCartDiscount(t);return i&&(e[t]=i.getDetails()),e},{}),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(e){return this.applicableTo==="all"||this.applicableTo==="ftb"&&e}calculateApplicableCouponDiscount(e,t,i,n,o=!0){let s=new h({amount:0,currency:n}),p;if(o&&!this.isActive())return s;let a=this.getMinCartValue(i),c=this.getMaxCartDiscount(i);if(!a||a.compareTo(e)>0||!c)return s;let C=this.getCategory(),Y=this.getDiscountMethod(),U=C==="SHIPPING"?t:e;if(U.getAmount()<=0)return s;switch(Y){case"flat":let q=c;p=U.min(q);break;case"percentage":p=U.multiply(this.getPercentageValue()/100).round();break;default:return s}return p.min(c)}};exports.ApplicableTo=le;exports.CouponCategory=ue;exports.CouponDiscountMethod=ce;exports.CouponType=ae;exports.default=$;//# sourceMappingURL=Coupon.js.map
2
2
  //# sourceMappingURL=Coupon.js.map