b23-lib 1.9.0 → 1.9.2

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 (46) hide show
  1. package/dist/Classes/Cart.js +1 -1
  2. package/dist/Classes/Cart.js.map +1 -1
  3. package/dist/Classes/Cart.mjs +1 -1
  4. package/dist/Classes/Coupon.js +1 -1
  5. package/dist/Classes/Coupon.js.map +1 -1
  6. package/dist/Classes/Coupon.mjs +1 -1
  7. package/dist/Classes/Enum.d.mts +2 -1
  8. package/dist/Classes/Enum.d.ts +2 -1
  9. package/dist/Classes/Enum.js +1 -1
  10. package/dist/Classes/Enum.js.map +1 -1
  11. package/dist/Classes/Enum.mjs +1 -1
  12. package/dist/Classes/LineItem.js +1 -1
  13. package/dist/Classes/LineItem.js.map +1 -1
  14. package/dist/Classes/LineItem.mjs +1 -1
  15. package/dist/Classes/Order.js +1 -1
  16. package/dist/Classes/Order.js.map +1 -1
  17. package/dist/Classes/Order.mjs +1 -1
  18. package/dist/Classes/Price.js +1 -1
  19. package/dist/Classes/Price.js.map +1 -1
  20. package/dist/Classes/Price.mjs +1 -1
  21. package/dist/Classes/Product.js.map +1 -1
  22. package/dist/Classes/Product.mjs +1 -1
  23. package/dist/Classes/ShoppingContainer.js +1 -1
  24. package/dist/Classes/ShoppingContainer.js.map +1 -1
  25. package/dist/Classes/ShoppingContainer.mjs +1 -1
  26. package/dist/{chunk-ONM27TEK.mjs → chunk-7T4QJTIJ.mjs} +2 -2
  27. package/dist/{chunk-ONM27TEK.mjs.map → chunk-7T4QJTIJ.mjs.map} +1 -1
  28. package/dist/{chunk-JZTLV4NZ.mjs → chunk-DJHX4EUG.mjs} +2 -2
  29. package/dist/{chunk-JZTLV4NZ.mjs.map → chunk-DJHX4EUG.mjs.map} +1 -1
  30. package/dist/chunk-G6EL2Y7V.mjs +2 -0
  31. package/dist/chunk-G6EL2Y7V.mjs.map +1 -0
  32. package/dist/{chunk-6CM2HXBH.mjs → chunk-GTH5SKQK.mjs} +2 -2
  33. package/dist/{chunk-6CM2HXBH.mjs.map → chunk-GTH5SKQK.mjs.map} +1 -1
  34. package/dist/{chunk-KT46HMDM.mjs → chunk-KUUS5GQR.mjs} +2 -2
  35. package/dist/{chunk-KT46HMDM.mjs.map → chunk-KUUS5GQR.mjs.map} +1 -1
  36. package/dist/{chunk-5I5EKOWK.mjs → chunk-SY36ZFQ6.mjs} +2 -2
  37. package/dist/{chunk-5I5EKOWK.mjs.map → chunk-SY36ZFQ6.mjs.map} +1 -1
  38. package/dist/index.d.mts +5 -3
  39. package/dist/index.d.ts +5 -3
  40. package/dist/index.js +2 -2
  41. package/dist/index.js.map +1 -1
  42. package/dist/index.mjs +2 -2
  43. package/dist/index.mjs.map +1 -1
  44. package/package.json +1 -1
  45. package/dist/chunk-QZDXRDTG.mjs +0 -2
  46. package/dist/chunk-QZDXRDTG.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Classes/Coupon.ts"],"names":["CouponType","CouponDiscountMethod","CouponCategory","ApplicableTo","CouponModel","BaseModel","data","date","price","locale","LocaleLanguageMap","country","ftbCustomer"],"mappings":"iFAIYA,IAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,EAAA,MAAS,CAAA,QAAA,CACTA,EAAA,SAAY,CAAA,WAAA,CAFFA,OAAA,EAKAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,EAAA,IAAO,CAAA,MAAA,CACPA,EAAA,UAAa,CAAA,YAAA,CAFHA,OAAA,EAKAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,EAAA,QAAW,CAAA,UAAA,CACXA,EAAA,QAAW,CAAA,UAAA,CAFDA,OAAA,EAKAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,EAAA,GAAM,CAAA,KAAA,CACNA,EAAA,GAAM,CAAA,KAAA,CAFIA,OAAA,EA0BSC,CAAAA,CAAAA,CA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AAyB,EAAA,CACvB,OAAO,CACH,GAAG,MAAM,UAAW,EAAA,CACpB,WAAY,IAAK,CAAA,OAAA,GACjB,IAAM,CAAA,IAAA,CAAK,OAAQ,EAAA,CACnB,WAAa,CAAA,IAAA,CAAK,gBAClB,CAAA,IAAA,CAAM,KAAK,OAAQ,EAAA,CACnB,WAAY,IAAK,CAAA,aAAA,GACjB,SAAW,CAAA,IAAA,CAAK,cAChB,CAAA,OAAA,CAAS,KAAK,UAAW,EAAA,CACzB,aAAc,IAAK,CAAA,eAAA,EACnB,CAAA,eAAA,CAAiB,IAAK,CAAA,kBAAA,GACtB,cAAgB,CAAA,IAAA,CAAK,mBACrB,CAAA,eAAA,CAAiB,KAAK,kBAAmB,EAAA,CACzC,aAAc,IAAK,CAAA,eAAA,GACnB,QAAU,CAAA,IAAA,CAAK,aACnB,CACF,CAMA,QAAoB,EAAA,CAClB,OAAO,IAAI,IAAK,CAAA,IAAA,CAAK,SAAS,CAAK,EAAA,IAAI,MAAU,IAAI,IAAA,CAAK,KAAK,OAAO,CAAA,EAAK,IAAI,IACjF,CAQA,eAAeC,CAA+B,CAAA,CAC5C,OAAO,IAAK,CAAA,YAAA,GAAiB,OAAqB,IAAK,CAAA,YAAA,GAAiB,KAAoBA,EAAAA,CAC9F,CACF","file":"chunk-6CM2HXBH.mjs","sourcesContent":["import BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, ISODateTime, LocaleCode, LocalizedString, RegionalPrice, RegionalPriceList } from \"./Common\";\r\nimport { LocaleLanguageMap } from \"./Enum\";\r\n\r\nexport enum CouponType {\r\n COUPON = \"coupon\",\r\n AUTOMATIC = \"automatic\",\r\n}\r\n\r\nexport enum CouponDiscountMethod {\r\n FLAT = \"flat\",\r\n PERCENTAGE = \"percentage\",\r\n}\r\n\r\nexport enum CouponCategory {\r\n SHIPPING = \"SHIPPING\",\r\n CUSTOMER = \"CUSTOMER\",\r\n}\r\n\r\nexport enum ApplicableTo {\r\n ALL = \"all\",\r\n FTB = \"ftb\",\r\n}\r\n\r\nexport type CouponAttribute = BaseAttributes & {\r\n couponCode: string;\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n type: CouponType;\r\n customerId?: string;\r\n validFrom: ISODateTime;\r\n validTo: ISODateTime;\r\n minCartValue: RegionalPriceList;\r\n maxCartDiscount: RegionalPriceList;\r\n discountMethod: CouponDiscountMethod;\r\n percentageValue?: number;\r\n applicableTo: ApplicableTo;\r\n category: CouponCategory;\r\n};\r\n\r\nexport type CouponData = Required<CouponAttribute>\r\n\r\n/**\r\n * Represents a discount coupon, extending BaseModel.\r\n */\r\nexport default class CouponModel extends BaseModel {\r\n protected couponCode: string;\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected type: CouponType;\r\n protected customerId?: string;\r\n protected validFrom: ISODateTime;\r\n protected validTo: ISODateTime;\r\n protected minCartValue: RegionalPriceList;\r\n protected maxCartDiscount: RegionalPriceList;\r\n protected discountMethod: CouponDiscountMethod;\r\n protected percentageValue: number;\r\n protected applicableTo: ApplicableTo;\r\n protected category: CouponCategory;\r\n\r\n /**\r\n * Creates an instance of CouponModel.\r\n * @param data - The initial coupon attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: CouponAttribute, date: Date = new Date()) {\r\n super(data, date);\r\n\r\n this.couponCode = data.couponCode;\r\n this.name = { ...data.name };\r\n this.description = { ...data.description };\r\n this.type = data.type;\r\n this.customerId = data.customerId;\r\n this.validFrom = data.validFrom && Date.parse(data.validFrom) ? new Date(data.validFrom).toISOString() : date.toISOString();\r\n this.validTo = data.validTo && Date.parse(data.validTo) ? new Date(data.validTo).toISOString() : date.toISOString();\r\n this.minCartValue = data.minCartValue.map(price => ({ ...price }));\r\n this.maxCartDiscount = data.maxCartDiscount.map(price => ({ ...price }));\r\n this.discountMethod = data.discountMethod;\r\n this.percentageValue = data.percentageValue ?? 0;\r\n this.applicableTo = data.applicableTo;\r\n this.category = data.category;\r\n }\r\n\r\n /** Gets the unique coupon code. */\r\n getCode(): string {\r\n return this.couponCode;\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the coupon name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon description object.\r\n * @returns A copy of the LocalizedString object for the description, or undefined.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the coupon description for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The description string for the specified locale.\r\n */\r\n getDescription(locale: LocaleCode): string\r\n getDescription(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.description[locale] ?? this.description[LocaleLanguageMap[locale]] ?? this.description.en;\r\n } else {\r\n return { ...this.description };\r\n }\r\n }\r\n\r\n /** Gets the type of coupon (COUPON or AUTOMATIC). */\r\n getType(): CouponType {\r\n return this.type;\r\n }\r\n\r\n /** Gets the specific customer ID this coupon is limited to, if any. */\r\n getCustomerId(): string {\r\n return this.customerId ?? '';\r\n }\r\n\r\n /** Gets the ISO date string from when the coupon is valid. */\r\n getValidFrom(): ISODateTime {\r\n return this.validFrom;\r\n }\r\n\r\n /** Gets the ISO date string until when the coupon is valid. */\r\n getValidTo(): ISODateTime {\r\n return this.validTo;\r\n }\r\n\r\n /**\r\n * Gets the list of minimum cart values required for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional minimum cart values.\r\n */\r\n getMinCartValue(): RegionalPriceList\r\n /**\r\n * Gets the minimum cart value required for the coupon for a specific country.\r\n * @param country - The country code to filter the minimum value for.\r\n * @returns The regional minimum cart value for the specified country, or undefined if not set for that country.\r\n */\r\n getMinCartValue(country: CountryCode): RegionalPrice | undefined\r\n getMinCartValue(country?: CountryCode){\r\n if(country) {\r\n return this.minCartValue.find(price => price.country === country);\r\n }\r\n return this.minCartValue;\r\n }\r\n\r\n /**\r\n * Gets the list of maximum discount amounts allowed for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional maximum discount caps.\r\n */\r\n getMaxCartDiscount(): RegionalPriceList\r\n /**\r\n * Gets the maximum discount amount allowed for the coupon for a specific country.\r\n * @param country - The country code to filter the maximum discount for.\r\n * @returns The regional maximum discount cap for the specified country, or undefined if not set for that country.\r\n */\r\n getMaxCartDiscount(country: CountryCode): RegionalPrice | undefined\r\n getMaxCartDiscount(country?: CountryCode){\r\n if(country) {\r\n return this.maxCartDiscount.find(price => price.country === country);\r\n }\r\n return this.maxCartDiscount;\r\n }\r\n\r\n /** Gets the discount method (FLAT or PERCENTAGE). */\r\n getDiscountMethod(): CouponDiscountMethod {\r\n return this.discountMethod;\r\n }\r\n\r\n /** Gets the percentage discount value (0-100). */\r\n getPercentageValue(): number {\r\n return this.percentageValue;\r\n }\r\n\r\n /** Gets the customer applicability rule (ALL or FTB). */\r\n getApplicableTo(): ApplicableTo {\r\n return this.applicableTo;\r\n }\r\n\r\n /** Gets the category of the coupon (SHIPPING or CUSTOMER). */\r\n getCategory(): CouponCategory {\r\n return this.category;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the coupon's details.\r\n * @returns A CouponData object.\r\n */\r\n getDetails(): CouponData {\r\n return {\r\n ...super.getDetails(),\r\n couponCode: this.getCode(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n type: this.getType(),\r\n customerId: this.getCustomerId(),\r\n validFrom: this.getValidFrom(),\r\n validTo: this.getValidTo(),\r\n minCartValue: this.getMinCartValue(),\r\n maxCartDiscount: this.getMaxCartDiscount(),\r\n discountMethod: this.getDiscountMethod(),\r\n percentageValue: this.getPercentageValue(),\r\n applicableTo: this.getApplicableTo(),\r\n category: this.getCategory(),\r\n };\r\n }\r\n\r\n /**\r\n * Checks if the coupon is currently active based on its validity dates.\r\n * @returns True if the coupon is currently within its validity period, false otherwise.\r\n */\r\n isActive(): boolean {\r\n return new Date(this.validFrom) <= new Date() && new Date(this.validTo) >= new Date();\r\n }\r\n\r\n \r\n /**\r\n * Checks if the coupon is applicable to a customer based on their status (e.g., first-time buyer).\r\n * @param ftbCustomer - A boolean indicating whether the customer is a first-time buyer.\r\n * @returns True if the coupon's applicability rule matches the customer's status, false otherwise.\r\n */\r\n isApplicableTo(ftbCustomer: boolean): boolean {\r\n return this.applicableTo === ApplicableTo.ALL || (this.applicableTo === ApplicableTo.FTB && ftbCustomer);\r\n }\r\n}"]}
1
+ {"version":3,"sources":["../src/Classes/Coupon.ts"],"names":["CouponType","CouponDiscountMethod","CouponCategory","ApplicableTo","CouponModel","BaseModel","data","date","price","locale","LocaleLanguageMap","country","ftbCustomer"],"mappings":"iFAIYA,IAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,EAAA,MAAS,CAAA,QAAA,CACTA,EAAA,SAAY,CAAA,WAAA,CAFFA,OAAA,EAKAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,EAAA,IAAO,CAAA,MAAA,CACPA,EAAA,UAAa,CAAA,YAAA,CAFHA,OAAA,EAKAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,EAAA,QAAW,CAAA,UAAA,CACXA,EAAA,QAAW,CAAA,UAAA,CAFDA,OAAA,EAKAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,EAAA,GAAM,CAAA,KAAA,CACNA,EAAA,GAAM,CAAA,KAAA,CAFIA,OAAA,EA0BSC,CAAAA,CAAAA,CAAAA,CAArB,cAAyCC,GAAU,CACvC,WACA,IACA,CAAA,WAAA,CACA,IACA,CAAA,UAAA,CACA,SACA,CAAA,OAAA,CACA,aACA,e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CAAK,OAAQ,EAAA,CACnB,WAAa,CAAA,IAAA,CAAK,gBAClB,CAAA,IAAA,CAAM,KAAK,OAAQ,EAAA,CACnB,WAAY,IAAK,CAAA,aAAA,GACjB,SAAW,CAAA,IAAA,CAAK,cAChB,CAAA,OAAA,CAAS,KAAK,UAAW,EAAA,CACzB,aAAc,IAAK,CAAA,eAAA,EACnB,CAAA,eAAA,CAAiB,IAAK,CAAA,kBAAA,GACtB,cAAgB,CAAA,IAAA,CAAK,mBACrB,CAAA,eAAA,CAAiB,KAAK,kBAAmB,EAAA,CACzC,aAAc,IAAK,CAAA,eAAA,GACnB,QAAU,CAAA,IAAA,CAAK,aACnB,CACF,CAMA,QAAoB,EAAA,CAClB,OAAO,IAAI,IAAK,CAAA,IAAA,CAAK,SAAS,CAAK,EAAA,IAAI,MAAU,IAAI,IAAA,CAAK,KAAK,OAAO,CAAA,EAAK,IAAI,IACjF,CAQA,eAAeC,CAA+B,CAAA,CAC5C,OAAO,IAAK,CAAA,YAAA,GAAiB,OAAqB,IAAK,CAAA,YAAA,GAAiB,KAAoBA,EAAAA,CAC9F,CACF","file":"chunk-GTH5SKQK.mjs","sourcesContent":["import BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, ISODateTime, LocaleCode, LocalizedString, RegionalPrice, RegionalPriceList } from \"./Common\";\r\nimport { LocaleLanguageMap } from \"./Enum\";\r\n\r\nexport enum CouponType {\r\n COUPON = \"coupon\",\r\n AUTOMATIC = \"automatic\",\r\n}\r\n\r\nexport enum CouponDiscountMethod {\r\n FLAT = \"flat\",\r\n PERCENTAGE = \"percentage\",\r\n}\r\n\r\nexport enum CouponCategory {\r\n SHIPPING = \"SHIPPING\",\r\n CUSTOMER = \"CUSTOMER\",\r\n}\r\n\r\nexport enum ApplicableTo {\r\n ALL = \"all\",\r\n FTB = \"ftb\",\r\n}\r\n\r\nexport type CouponAttribute = BaseAttributes & {\r\n couponCode: string;\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n type: CouponType;\r\n customerId?: string;\r\n validFrom: ISODateTime;\r\n validTo: ISODateTime;\r\n minCartValue: RegionalPriceList;\r\n maxCartDiscount: RegionalPriceList;\r\n discountMethod: CouponDiscountMethod;\r\n percentageValue?: number;\r\n applicableTo: ApplicableTo;\r\n category: CouponCategory;\r\n};\r\n\r\nexport type CouponData = Required<CouponAttribute>\r\n\r\n/**\r\n * Represents a discount coupon, extending BaseModel.\r\n */\r\nexport default class CouponModel extends BaseModel {\r\n protected couponCode: string;\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected type: CouponType;\r\n protected customerId?: string;\r\n protected validFrom: ISODateTime;\r\n protected validTo: ISODateTime;\r\n protected minCartValue: RegionalPriceList;\r\n protected maxCartDiscount: RegionalPriceList;\r\n protected discountMethod: CouponDiscountMethod;\r\n protected percentageValue: number;\r\n protected applicableTo: ApplicableTo;\r\n protected category: CouponCategory;\r\n\r\n /**\r\n * Creates an instance of CouponModel.\r\n * @param data - The initial coupon attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: CouponAttribute, date: Date = new Date()) {\r\n super(data, date);\r\n\r\n this.couponCode = data.couponCode;\r\n this.name = { ...data.name };\r\n this.description = { ...data.description };\r\n this.type = data.type;\r\n this.customerId = data.customerId;\r\n this.validFrom = data.validFrom && Date.parse(data.validFrom) ? new Date(data.validFrom).toISOString() : date.toISOString();\r\n this.validTo = data.validTo && Date.parse(data.validTo) ? new Date(data.validTo).toISOString() : date.toISOString();\r\n this.minCartValue = data.minCartValue.map(price => ({ ...price }));\r\n this.maxCartDiscount = data.maxCartDiscount.map(price => ({ ...price }));\r\n this.discountMethod = data.discountMethod;\r\n this.percentageValue = data.percentageValue ?? 0;\r\n this.applicableTo = data.applicableTo;\r\n this.category = data.category;\r\n }\r\n\r\n /** Gets the unique coupon code. */\r\n getCode(): string {\r\n return this.couponCode;\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the coupon name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon description object.\r\n * @returns A copy of the LocalizedString object for the description, or undefined.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the coupon description for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The description string for the specified locale.\r\n */\r\n getDescription(locale: LocaleCode): string\r\n getDescription(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.description[locale] ?? this.description[LocaleLanguageMap[locale]] ?? this.description.en;\r\n } else {\r\n return { ...this.description };\r\n }\r\n }\r\n\r\n /** Gets the type of coupon (COUPON or AUTOMATIC). */\r\n getType(): CouponType {\r\n return this.type;\r\n }\r\n\r\n /** Gets the specific customer ID this coupon is limited to, if any. */\r\n getCustomerId(): string {\r\n return this.customerId ?? '';\r\n }\r\n\r\n /** Gets the ISO date string from when the coupon is valid. */\r\n getValidFrom(): ISODateTime {\r\n return this.validFrom;\r\n }\r\n\r\n /** Gets the ISO date string until when the coupon is valid. */\r\n getValidTo(): ISODateTime {\r\n return this.validTo;\r\n }\r\n\r\n /**\r\n * Gets the list of minimum cart values required for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional minimum cart values.\r\n */\r\n getMinCartValue(): RegionalPriceList\r\n /**\r\n * Gets the minimum cart value required for the coupon for a specific country.\r\n * @param country - The country code to filter the minimum value for.\r\n * @returns The regional minimum cart value for the specified country, or undefined if not set for that country.\r\n */\r\n getMinCartValue(country: CountryCode): RegionalPrice | undefined\r\n getMinCartValue(country?: CountryCode){\r\n if(country) {\r\n return this.minCartValue.find(price => price.country === country);\r\n }\r\n return this.minCartValue;\r\n }\r\n\r\n /**\r\n * Gets the list of maximum discount amounts allowed for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional maximum discount caps.\r\n */\r\n getMaxCartDiscount(): RegionalPriceList\r\n /**\r\n * Gets the maximum discount amount allowed for the coupon for a specific country.\r\n * @param country - The country code to filter the maximum discount for.\r\n * @returns The regional maximum discount cap for the specified country, or undefined if not set for that country.\r\n */\r\n getMaxCartDiscount(country: CountryCode): RegionalPrice | undefined\r\n getMaxCartDiscount(country?: CountryCode){\r\n if(country) {\r\n return this.maxCartDiscount.find(price => price.country === country);\r\n }\r\n return this.maxCartDiscount;\r\n }\r\n\r\n /** Gets the discount method (FLAT or PERCENTAGE). */\r\n getDiscountMethod(): CouponDiscountMethod {\r\n return this.discountMethod;\r\n }\r\n\r\n /** Gets the percentage discount value (0-100). */\r\n getPercentageValue(): number {\r\n return this.percentageValue;\r\n }\r\n\r\n /** Gets the customer applicability rule (ALL or FTB). */\r\n getApplicableTo(): ApplicableTo {\r\n return this.applicableTo;\r\n }\r\n\r\n /** Gets the category of the coupon (SHIPPING or CUSTOMER). */\r\n getCategory(): CouponCategory {\r\n return this.category;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the coupon's details.\r\n * @returns A CouponData object.\r\n */\r\n getDetails(): CouponData {\r\n return {\r\n ...super.getDetails(),\r\n couponCode: this.getCode(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n type: this.getType(),\r\n customerId: this.getCustomerId(),\r\n validFrom: this.getValidFrom(),\r\n validTo: this.getValidTo(),\r\n minCartValue: this.getMinCartValue(),\r\n maxCartDiscount: this.getMaxCartDiscount(),\r\n discountMethod: this.getDiscountMethod(),\r\n percentageValue: this.getPercentageValue(),\r\n applicableTo: this.getApplicableTo(),\r\n category: this.getCategory(),\r\n };\r\n }\r\n\r\n /**\r\n * Checks if the coupon is currently active based on its validity dates.\r\n * @returns True if the coupon is currently within its validity period, false otherwise.\r\n */\r\n isActive(): boolean {\r\n return new Date(this.validFrom) <= new Date() && new Date(this.validTo) >= new Date();\r\n }\r\n\r\n \r\n /**\r\n * Checks if the coupon is applicable to a customer based on their status (e.g., first-time buyer).\r\n * @param ftbCustomer - A boolean indicating whether the customer is a first-time buyer.\r\n * @returns True if the coupon's applicability rule matches the customer's status, false otherwise.\r\n */\r\n isApplicableTo(ftbCustomer: boolean): boolean {\r\n return this.applicableTo === ApplicableTo.ALL || (this.applicableTo === ApplicableTo.FTB && ftbCustomer);\r\n }\r\n}"]}
@@ -1,2 +1,2 @@
1
- import {a as a$2}from'./chunk-JZTLV4NZ.mjs';import {a as a$1}from'./chunk-5I5EKOWK.mjs';import {b}from'./chunk-HTJJLLGW.mjs';import {e}from'./chunk-6CM2HXBH.mjs';import {a}from'./chunk-ATUUYYQT.mjs';var c=class extends a{id;customerId;customerEmail;anonymousId;lineItems;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,e$1=new Date){super(t,e$1),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(i=>new a$1(i)),this.billingAddress=t.billingAddress?new b(t.billingAddress,e$1):null,this.shippingAddress=t.shippingAddress?new b(t.shippingAddress,e$1):null,this.coupons=(t.coupons||[]).map(i=>new e(i)),this.shippingDetails=t.shippingDetails?{...t.shippingDetails}:null,this.total={shipping:t.total?.shipping||0,effectiveShipping:t.total?.effectiveShipping??t.total?.shipping??0,subtotal:0,mrpTotal:0,couponTotal:t.total?.couponTotal||{},grandTotal:t.total?.grandTotal||0},this.recalculateBaseTotals();}recalculateBaseTotals(){this.total.subtotal=a$2.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=a$2.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().mrpTotal,0),this.country);}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new a$1(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new b(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new b(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons.map(t=>new e(t.getDetails()))}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {...this.total,couponTotal:{...this.total.couponTotal}}}calculateApplicableCouponDiscount(t){if(!t.isActive())return 0;let e=t.getMinCartValue(this.country),i=t.getMaxCartDiscount(this.country);if(!e||this.total.subtotal<e.price||!i||i.price<0)return 0;let s=t.getCategory(),n=t.getDiscountMethod(),l=0,u=s==="SHIPPING"?this.total.shipping:this.total.subtotal;if(u<=0)return 0;switch(n){case"flat":let h=i?.price??0;l=Math.min(u,h);break;case"percentage":l=u*(t.getPercentageValue()/100);break;default:return 0}let g=Math.min(l,i.price);return a$2.getRoundedPrice(Math.max(0,g),this.country)}recalculateCouponTotals(){this.total.couponTotal={};let t=0;return this.coupons.forEach(e=>{let i=this.calculateApplicableCouponDiscount(e);i>0&&(this.total.couponTotal[e.getCode()]=i,t+=i);}),a$2.getRoundedPrice(t,this.country)}updateCartTotals(){this.total.subtotal=a$2.getRoundedPrice(this.lineItems.reduce((s,n)=>s+n.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=a$2.getRoundedPrice(this.lineItems.reduce((s,n)=>s+n.getPriceTotals().mrpTotal,0),this.country),this.recalculateCouponTotals();let t=this.coupons.filter(s=>s.getCategory()==="SHIPPING").reduce((s,n)=>s+(this.total.couponTotal[n.getCode()]??0),0);this.total.effectiveShipping=a$2.getRoundedPrice(Math.max(0,this.total.shipping-t),this.country);let e=this.coupons.filter(s=>s.getCategory()!=="SHIPPING").reduce((s,n)=>s+(this.total.couponTotal[n.getCode()]??0),0),i=this.total.subtotal+this.total.effectiveShipping;this.total.grandTotal=a$2.getRoundedPrice(Math.max(0,i-e),this.country);}setShippingDetails(t){this.shippingDetails=t?{...t}:null,this.total.shipping=a$2.getRoundedPrice(this.shippingDetails?.estimatedCost??0,this.country),this.updateCartTotals();}getDetails(){return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(t=>t.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(t=>t.getDetails()),total:this.getTotal(),country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}};export{c as a};//# sourceMappingURL=chunk-KT46HMDM.mjs.map
2
- //# sourceMappingURL=chunk-KT46HMDM.mjs.map
1
+ import {a as a$1}from'./chunk-SY36ZFQ6.mjs';import {a as a$2}from'./chunk-DJHX4EUG.mjs';import {b}from'./chunk-HTJJLLGW.mjs';import {e}from'./chunk-GTH5SKQK.mjs';import {a}from'./chunk-ATUUYYQT.mjs';var c=class extends a{id;customerId;customerEmail;anonymousId;lineItems;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,e$1=new Date){super(t,e$1),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(i=>new a$1(i)),this.billingAddress=t.billingAddress?new b(t.billingAddress,e$1):null,this.shippingAddress=t.shippingAddress?new b(t.shippingAddress,e$1):null,this.coupons=(t.coupons||[]).map(i=>new e(i)),this.shippingDetails=t.shippingDetails?{...t.shippingDetails}:null,this.total={shipping:t.total?.shipping||0,effectiveShipping:t.total?.effectiveShipping??t.total?.shipping??0,subtotal:0,mrpTotal:0,couponTotal:t.total?.couponTotal||{},grandTotal:t.total?.grandTotal||0},this.recalculateBaseTotals();}recalculateBaseTotals(){this.total.subtotal=a$2.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=a$2.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().mrpTotal,0),this.country);}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new a$1(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new b(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new b(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons.map(t=>new e(t.getDetails()))}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {...this.total,couponTotal:{...this.total.couponTotal}}}calculateApplicableCouponDiscount(t){if(!t.isActive())return 0;let e=t.getMinCartValue(this.country),i=t.getMaxCartDiscount(this.country);if(!e||this.total.subtotal<e.price||!i||i.price<0)return 0;let s=t.getCategory(),n=t.getDiscountMethod(),l=0,u=s==="SHIPPING"?this.total.shipping:this.total.subtotal;if(u<=0)return 0;switch(n){case"flat":let h=i?.price??0;l=Math.min(u,h);break;case"percentage":l=u*(t.getPercentageValue()/100);break;default:return 0}let g=Math.min(l,i.price);return a$2.getRoundedPrice(Math.max(0,g),this.country)}recalculateCouponTotals(){this.total.couponTotal={};let t=0;return this.coupons.forEach(e=>{let i=this.calculateApplicableCouponDiscount(e);i>0&&(this.total.couponTotal[e.getCode()]=i,t+=i);}),a$2.getRoundedPrice(t,this.country)}updateCartTotals(){this.total.subtotal=a$2.getRoundedPrice(this.lineItems.reduce((s,n)=>s+n.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=a$2.getRoundedPrice(this.lineItems.reduce((s,n)=>s+n.getPriceTotals().mrpTotal,0),this.country),this.recalculateCouponTotals();let t=this.coupons.filter(s=>s.getCategory()==="SHIPPING").reduce((s,n)=>s+(this.total.couponTotal[n.getCode()]??0),0);this.total.effectiveShipping=a$2.getRoundedPrice(Math.max(0,this.total.shipping-t),this.country);let e=this.coupons.filter(s=>s.getCategory()!=="SHIPPING").reduce((s,n)=>s+(this.total.couponTotal[n.getCode()]??0),0),i=this.total.subtotal+this.total.effectiveShipping;this.total.grandTotal=a$2.getRoundedPrice(Math.max(0,i-e),this.country);}setShippingDetails(t){this.shippingDetails=t?{...t}:null,this.total.shipping=a$2.getRoundedPrice(this.shippingDetails?.estimatedCost??0,this.country),this.updateCartTotals();}getDetails(){return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(t=>t.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(t=>t.getDetails()),total:this.getTotal(),country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}};export{c as a};//# sourceMappingURL=chunk-KUUS5GQR.mjs.map
2
+ //# sourceMappingURL=chunk-KUUS5GQR.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Classes/ShoppingContainer.ts"],"names":["BaseShoppingContainerModel","BaseModel","data","date","item","LineItemModel","AddressModel","coupon","CouponModel","PriceModel","sum","minCartValueReq","maxCartDiscountCap","couponCategory","discountMethod","potentialDiscount","targetValue","flatAmount","finalDiscount","totalDiscount","discount","shippingCouponDiscount","c","nonShippingCouponDiscount","grossTotal","details"],"mappings":"uMAmDA,IAA8BA,EAA9B,cAAiEC,CAAU,CAC/D,EACA,CAAA,UAAA,CACA,cACA,WACA,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,EAAA,CAC/B,cAAe,IAAK,CAAA,gBAAA,GACpB,WAAa,CAAA,IAAA,CAAK,gBAClB,CAAA,SAAA,CAAW,KAAK,YAAa,EAAA,CAAE,IAAIL,CAAQA,EAAAA,CAAAA,CAAK,YAAY,CAAA,CAC5D,eAAiB,CAAA,IAAA,CAAK,oBACtB,CAAA,eAAA,CAAiB,KAAK,kBAAmB,EAAA,EAAG,YAAgB,EAAA,IAAA,CAC5D,eAAgB,IAAK,CAAA,iBAAA,IAAqB,UAAW,EAAA,EAAK,KAC1D,OAAS,CAAA,IAAA,CAAK,YAAa,CAAA,GAAA,CAAIG,GAAUA,CAAO,CAAA,UAAA,EAAY,CAC5D,CAAA,KAAA,CAAO,KAAK,QAAS,EAAA,CACrB,QAAS,IAAK,CAAA,UAAA,GACd,QAAU,CAAA,IAAA,CAAK,aACf,CAAA,MAAA,CAAQ,KAAK,SAAU,EACzB,CACF,CACH","file":"chunk-KT46HMDM.mjs","sourcesContent":["import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport AddressModel, { AddressData } from \"./Address\";\r\nimport LineItemModel, { LineItemData } from \"./LineItem\";\r\nimport { CountryCode, CurrencyCode, LocaleCode, ShippingDetails } from \"./Common\";\r\nimport PriceModel from \"./Price\";\r\nimport CouponModel, { CouponCategory, CouponData, CouponDiscountMethod } from \"./Coupon\";\r\n\r\nexport type ShoppingContainerTotal = {\r\n shipping?: number;\r\n effectiveShipping?: number;\r\n subtotal?: number;\r\n mrpTotal?: number;\r\n couponTotal?: { [key: string]: number };\r\n grandTotal?: number;\r\n}\r\n\r\nexport type BaseShoppingContainerAttributes = BaseAttributes & {\r\n id: string;\r\n customerId?: string;\r\n customerEmail?: string;\r\n anonymousId?: string;\r\n lineItems: LineItemData[];\r\n shippingDetails: ShippingDetails | null;\r\n shippingAddress?: AddressData | null;\r\n billingAddress?: AddressData | null;\r\n coupons?: CouponData[];\r\n total?: ShoppingContainerTotal;\r\n country: CountryCode;\r\n currency: CurrencyCode;\r\n locale: LocaleCode;\r\n};\r\n\r\nexport type BaseShoppingContainerData = Omit<BaseShoppingContainerAttributes, 'coupons' | 'total'>\r\n& BaseData\r\n& {\r\n coupons: CouponData[],\r\n total: {\r\n shipping: number,\r\n effectiveShipping: number,\r\n subtotal: number,\r\n mrpTotal: number,\r\n couponTotal: { [key: string]: number },\r\n grandTotal: number\r\n };\r\n };\r\n\r\n\r\n/**\r\n * Abstract base class for shopping-related containers like carts and orders.\r\n * Manages common elements such as line items, addresses, coupons, and totals.\r\n */\r\nexport default abstract class BaseShoppingContainerModel extends BaseModel {\r\n protected id: string;\r\n protected customerId?: string;\r\n protected customerEmail?: string;\r\n protected anonymousId?: string;\r\n protected lineItems: LineItemModel[];\r\n protected shippingDetails: ShippingDetails | null;\r\n protected shippingAddress: AddressModel | null;\r\n protected billingAddress: AddressModel | null;\r\n\r\n // CouponsCodes\r\n protected coupons: CouponModel[];\r\n\r\n // Cart Totals\r\n protected total: {\r\n shipping: number;\r\n effectiveShipping: number;\r\n subtotal: number;\r\n mrpTotal: number;\r\n couponTotal: { [key: string]: number; };\r\n grandTotal: number;\r\n };\r\n\r\n protected country: CountryCode;\r\n protected currency: CurrencyCode;\r\n protected locale: LocaleCode;\r\n\r\n /**\r\n * Creates an instance of BaseShoppingContainerModel.\r\n * Initializes common properties and calculates initial base totals.\r\n * @param data - The initial attributes for the shopping container.\r\n * @param date - Optional date object for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: BaseShoppingContainerAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.customerId = data.customerId;\r\n this.customerEmail = data.customerEmail;\r\n this.anonymousId = data.anonymousId;\r\n this.country = data.country;\r\n this.currency = data.currency;\r\n this.locale = data.locale;\r\n this.lineItems = (data.lineItems ?? []).map(item => new LineItemModel(item));\r\n this.billingAddress = data.billingAddress ? new AddressModel(data.billingAddress, date) : null;\r\n this.shippingAddress = data.shippingAddress ? new AddressModel(data.shippingAddress, date) : null;\r\n this.coupons = (data.coupons || []).map(coupon => new CouponModel(coupon));\r\n\r\n this.shippingDetails = data.shippingDetails ? { ...data.shippingDetails } : null;\r\n\r\n this.total = {\r\n shipping: data.total?.shipping || 0,\r\n effectiveShipping: data.total?.effectiveShipping ?? data.total?.shipping ?? 0,\r\n subtotal: 0, // Will be calculated\r\n mrpTotal: 0, // Will be calculated\r\n couponTotal: data.total?.couponTotal || {},\r\n grandTotal: data.total?.grandTotal || 0, // Will be recalculated\r\n };\r\n\r\n this.recalculateBaseTotals();\r\n }\r\n\r\n /**\r\n * Recalculates the subtotal and mrpTotal based on the current line items.\r\n * Uses PriceModel for rounding based on the country.\r\n */\r\n protected recalculateBaseTotals(): void {\r\n this.total.subtotal = PriceModel.getRoundedPrice(this.lineItems.reduce((sum, item) => sum + item.getPriceTotals().subtotal, 0), this.country);\r\n this.total.mrpTotal = PriceModel.getRoundedPrice(this.lineItems.reduce((sum, item) => sum + item.getPriceTotals().mrpTotal, 0), this.country);\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for this shopping container (cart ID or order ID).\r\n * @returns The ID string.\r\n */\r\n public getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the customer ID associated with this container, if available.\r\n * @returns The customer ID string, or undefined.\r\n */\r\n public getCustomerId(): string | undefined {\r\n return this.customerId;\r\n }\r\n\r\n /**\r\n * Gets the customer email associated with this container, if available.\r\n * @returns The customer email string, or undefined.\r\n */\r\n public getCustomerEmail(): string | undefined {\r\n return this.customerEmail;\r\n }\r\n\r\n /**\r\n * Gets the anonymous user ID associated with this container, if available.\r\n * @returns The anonymous ID string, or undefined.\r\n */\r\n public getAnonymousId(): string | undefined {\r\n return this.anonymousId;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the line items in the container.\r\n * Each item is a new LineItemModel instance created from the original's details.\r\n * @returns An array of LineItemModel instances.\r\n */\r\n public getLineItems(): LineItemModel[] {\r\n // Return new instances to prevent modification of internal state\r\n return this.lineItems.map(item => new LineItemModel(item.getDetails()));\r\n }\r\n\r\n /**\r\n * Gets current number of line items in the container\r\n * @returns \r\n */\r\n public getLineItemsCount(): number {\r\n return this.lineItems.length;\r\n }\r\n\r\n /**\r\n * Gets a copy of the shipping details associated with the container.\r\n * @returns A ShippingDetails object, or null if none are set.\r\n */\r\n public getShippingDetails(): ShippingDetails | null {\r\n // Return a shallow copy if details exist\r\n return this.shippingDetails ? { ...this.shippingDetails } : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the shipping address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no shipping address is set.\r\n */\r\n public getShippingAddress(): AddressModel | null {\r\n return this.shippingAddress ? new AddressModel(this.shippingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Checks if a shipping address is associated with this container.\r\n * @returns True if a shipping address is set, false otherwise.\r\n */\r\n public hasShippingAddress(): boolean {\r\n return !!this.shippingAddress;\r\n }\r\n\r\n /**\r\n * Checks if a billing address is associated with this container.\r\n * @returns True if a billing address is set, false otherwise.\r\n */\r\n public hasBillingAddress(): boolean {\r\n return !!this.billingAddress;\r\n }\r\n \r\n /**\r\n * Gets a defensive copy of the billing address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no billing address is set.\r\n */\r\n public getBillingAddress(): AddressModel | null {\r\n return this.billingAddress ? new AddressModel(this.billingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the coupons applied to the container.\r\n * Each item is a new CouponModel instance created from the original's details.\r\n * @returns An array of CouponModel instances.\r\n */\r\n public getCoupons(): CouponModel[] {\r\n return this.coupons.map(coupon => new CouponModel(coupon.getDetails()));\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this container.\r\n * @returns The CountryCode enum value.\r\n */\r\n public getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Gets the currency code associated with this container.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Gets the locale code associated with this container.\r\n * @returns The LocaleCode enum value.\r\n */\r\n public getLocale(): LocaleCode {\r\n return this.locale;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the calculated totals for the container.\r\n * @returns An object containing shipping, subtotal, coupon, and grand totals.\r\n */\r\n public getTotal() {\r\n return { ...this.total, couponTotal: { ...this.total.couponTotal } };\r\n }\r\n\r\n /**\r\n * Calculates the discount value for a given coupon based on the current container state.\r\n * Returns 0 if the coupon is invalid, expired, or not applicable based on cart value or target category.\r\n * @param coupon - The CouponModel instance to evaluate.\r\n * @returns The calculated discount amount (rounded according to country rules).\r\n */\r\n public calculateApplicableCouponDiscount(coupon: CouponModel): number {\r\n // 1. Basic validation (active)\r\n if (!coupon.isActive()) {\r\n return 0;\r\n }\r\n\r\n // 2. Check regional requirements (min cart value, max discount)\r\n const minCartValueReq = coupon.getMinCartValue(this.country);\r\n const maxCartDiscountCap = coupon.getMaxCartDiscount(this.country);\r\n\r\n // Ensure minCartValueReq exists and subtotal meets the requirement\r\n if (!minCartValueReq || this.total.subtotal < minCartValueReq.price) {\r\n return 0;\r\n }\r\n\r\n // Ensure maxCartDiscountCap exists and is non-negative\r\n if (!maxCartDiscountCap || maxCartDiscountCap.price < 0) {\r\n return 0;\r\n }\r\n\r\n // 3. Calculate potential discount based on method and category\r\n const couponCategory = coupon.getCategory();\r\n const discountMethod = coupon.getDiscountMethod();\r\n let potentialDiscount = 0;\r\n // Determine the value the coupon applies to (shipping cost or subtotal)\r\n const targetValue = couponCategory === CouponCategory.SHIPPING ? this.total.shipping : this.total.subtotal;\r\n\r\n // No discount if the target value is zero or less\r\n if (targetValue <= 0) return 0;\r\n\r\n switch (discountMethod) {\r\n case CouponDiscountMethod.FLAT:\r\n // Flat discount is capped by the target value itself and the max discount cap\r\n const flatAmount = maxCartDiscountCap?.price ?? 0; // Use cap as the flat amount source? Or coupon.value? Needs clarification. Assuming cap IS the flat amount here.\r\n potentialDiscount = Math.min(targetValue, flatAmount);\r\n break;\r\n case CouponDiscountMethod.PERCENTAGE:\r\n // Calculate percentage discount based on the target value\r\n potentialDiscount = targetValue * (coupon.getPercentageValue() / 100);\r\n break;\r\n default:\r\n // Unknown discount method\r\n return 0;\r\n }\r\n\r\n // 4. Apply maximum discount cap to the calculated potential discount\r\n const finalDiscount = Math.min(potentialDiscount, maxCartDiscountCap.price);\r\n\r\n // 5. Round the final discount, ensuring it's not negative\r\n return PriceModel.getRoundedPrice(Math.max(0, finalDiscount), this.country);\r\n }\r\n\r\n /**\r\n * Recalculates the `couponTotal` map based on currently applied coupons.\r\n * Iterates through coupons, calculates their applicable discount, and stores it.\r\n * @returns The total discount amount from all valid and applicable coupons (rounded).\r\n */\r\n public recalculateCouponTotals(): number {\r\n this.total.couponTotal = {}; // Reset the map\r\n let totalDiscount = 0;\r\n\r\n this.coupons.forEach(coupon => {\r\n const discount = this.calculateApplicableCouponDiscount(coupon);\r\n if (discount > 0) {\r\n this.total.couponTotal[coupon.getCode()] = discount; // Store per-coupon discount\r\n totalDiscount += discount; // Accumulate total discount\r\n }\r\n });\r\n // Return the rounded total discount\r\n return PriceModel.getRoundedPrice(totalDiscount, this.country);\r\n }\r\n\r\n /**\r\n * Recalculates all container totals (subtotal, mrpTotal, coupons, shipping, grandTotal).\r\n * Should be called whenever line items, coupons, or base shipping cost change.\r\n */\r\n public updateCartTotals(): void {\r\n // 1. Calculate line item totals (subtotal, mrpTotal)\r\n this.total.subtotal = PriceModel.getRoundedPrice(this.lineItems.reduce((sum, item) => sum + item.getPriceTotals().subtotal, 0), this.country);\r\n this.total.mrpTotal = PriceModel.getRoundedPrice(this.lineItems.reduce((sum, item) => sum + item.getPriceTotals().mrpTotal, 0), this.country);\r\n\r\n // 2. Calculate total coupon discount and update the per-coupon discount map\r\n this.recalculateCouponTotals(); // This updates this.total.couponTotal\r\n\r\n // 3. Calculate effective shipping cost after applying shipping-specific coupons\r\n const shippingCouponDiscount = this.coupons\r\n .filter(c => c.getCategory() === CouponCategory.SHIPPING)\r\n .reduce((sum, c) => sum + (this.total.couponTotal[c.getCode()] ?? 0), 0);\r\n this.total.effectiveShipping = PriceModel.getRoundedPrice(Math.max(0, this.total.shipping - shippingCouponDiscount), this.country);\r\n\r\n // 4. Calculate total discount from non-shipping coupons\r\n const nonShippingCouponDiscount = this.coupons\r\n .filter(c => c.getCategory() !== CouponCategory.SHIPPING)\r\n .reduce((sum, c) => sum + (this.total.couponTotal[c.getCode()] ?? 0), 0);\r\n\r\n // 5. Calculate final grand total: (subtotal + effective shipping) - non-shipping discounts\r\n const grossTotal = this.total.subtotal + this.total.effectiveShipping;\r\n this.total.grandTotal = PriceModel.getRoundedPrice(Math.max(0, grossTotal - nonShippingCouponDiscount), this.country);\r\n }\r\n\r\n /**\r\n * Updates the shipping details (including estimated cost) for the container and recalculates totals.\r\n * @param details - The new ShippingDetails object, or null to clear shipping details and cost.\r\n */\r\n public setShippingDetails(details: ShippingDetails | null): void {\r\n // Store a copy of the details or null\r\n this.shippingDetails = details ? { ...details } : null;\r\n\r\n // Update the base shipping cost based on the new details\r\n this.total.shipping = PriceModel.getRoundedPrice(this.shippingDetails?.estimatedCost ?? 0, this.country);\r\n // Recalculate all totals as shipping cost affects effective shipping and grand total\r\n this.updateCartTotals();\r\n }\r\n\r\n\r\n /**\r\n * Gets a plain data object representing the shopping container's current state.\r\n * Includes details from the base model and specific container properties.\r\n * @returns BaseShoppingContainerData object suitable for serialization or API responses.\r\n */\r\n getDetails(): BaseShoppingContainerData {\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n customerId: this.getCustomerId(),\r\n customerEmail: this.getCustomerEmail(),\r\n anonymousId: this.getAnonymousId(),\r\n lineItems: this.getLineItems().map(item => item.getDetails()),\r\n shippingDetails: this.getShippingDetails(),\r\n shippingAddress: this.getShippingAddress()?.getDetails() || null,\r\n billingAddress: this.getBillingAddress()?.getDetails() || null,\r\n coupons: this.getCoupons().map(coupon => coupon.getDetails()),\r\n total: this.getTotal(),\r\n country: this.getCountry(),\r\n currency: this.getCurrency(),\r\n locale: this.getLocale(),\r\n }\r\n };\r\n}\r\n"]}
1
+ {"version":3,"sources":["../src/Classes/ShoppingContainer.ts"],"names":["BaseShoppingContainerModel","BaseModel","data","date","item","LineItemModel","AddressModel","coupon","CouponModel","PriceModel","sum","minCartValueReq","maxCartDiscountCap","couponCategory","discountMethod","potentialDiscount","targetValue","flatAmount","finalDiscount","totalDiscount","discount","shippingCouponDiscount","c","nonShippingCouponDiscount","grossTotal","details"],"mappings":"uMAmDA,IAA8BA,EAA9B,cAAiEC,CAAU,CAC/D,EACA,CAAA,UAAA,CACA,cACA,WACA,CAAA,SAAA,CACA,gBACA,eACA,CAAA,cAAA,CAGA,QAGA,KASA,CAAA,OAAA,CACA,SACA,MAQV,CAAA,WAAA,CAAYC,EAAuCC,GAAa,CAAA,IAAI,IAAQ,CAAA,CAC1E,MAAMD,CAAMC,CAAAA,GAAI,EAChB,IAAK,CAAA,EAAA,CAAKD,EAAK,EACf,CAAA,IAAA,CAAK,WAAaA,CAAK,CAAA,UAAA,CACvB,KAAK,aAAgBA,CAAAA,CAAAA,CAAK,cAC1B,IAAK,CAAA,WAAA,CAAcA,EAAK,WACxB,CAAA,IAAA,CAAK,OAAUA,CAAAA,CAAAA,CAAK,QACpB,IAAK,CAAA,QAAA,CAAWA,EAAK,QACrB,CAAA,IAAA,CAAK,OAASA,CAAK,CAAA,MAAA,CACnB,KAAK,SAAaA,CAAAA,CAAAA,CAAAA,CAAK,WAAa,EAAC,EAAG,IAAIE,CAAQ,EAAA,IAAIC,IAAcD,CAAI,CAAC,EAC3E,IAAK,CAAA,cAAA,CAAiBF,EAAK,cAAiB,CAAA,IAAII,EAAaJ,CAAK,CAAA,cAAA,CAAgBC,GAAI,CAAI,CAAA,IAAA,CAC1F,KAAK,eAAkBD,CAAAA,CAAAA,CAAK,gBAAkB,IAAII,CAAAA,CAAaJ,EAA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AA,CAAGe,EAAaD,CAAyB,CAAA,CAAG,KAAK,OAAO,EACtH,CAMO,kBAAmBE,CAAAA,CAAAA,CAAuC,CAE/D,IAAK,CAAA,eAAA,CAAkBA,EAAU,CAAE,GAAGA,CAAQ,CAAI,CAAA,IAAA,CAGlD,KAAK,KAAM,CAAA,QAAA,CAAWhB,GAAW,CAAA,eAAA,CAAgB,KAAK,eAAiB,EAAA,aAAA,EAAiB,EAAG,IAAK,CAAA,OAAO,EAEvG,IAAK,CAAA,gBAAA,GACP,CAQA,UAAA,EAAwC,CACrC,OAAO,CACL,GAAG,KAAM,CAAA,UAAA,GACT,EAAI,CAAA,IAAA,CAAK,OACT,CAAA,UAAA,CAAY,KAAK,aAAc,EAAA,CAC/B,cAAe,IAAK,CAAA,gBAAA,GACpB,WAAa,CAAA,IAAA,CAAK,gBAClB,CAAA,SAAA,CAAW,KAAK,YAAa,EAAA,CAAE,IAAIL,CAAQA,EAAAA,CAAAA,CAAK,YAAY,CAAA,CAC5D,eAAiB,CAAA,IAAA,CAAK,oBACtB,CAAA,eAAA,CAAiB,KAAK,kBAAmB,EAAA,EAAG,YAAgB,EAAA,IAAA,CAC5D,eAAgB,IAAK,CAAA,iBAAA,IAAqB,UAAW,EAAA,EAAK,KAC1D,OAAS,CAAA,IAAA,CAAK,YAAa,CAAA,GAAA,CAAIG,GAAUA,CAAO,CAAA,UAAA,EAAY,CAC5D,CAAA,KAAA,CAAO,KAAK,QAAS,EAAA,CACrB,QAAS,IAAK,CAAA,UAAA,GACd,QAAU,CAAA,IAAA,CAAK,aACf,CAAA,MAAA,CAAQ,KAAK,SAAU,EACzB,CACF,CACH","file":"chunk-KUUS5GQR.mjs","sourcesContent":["import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport AddressModel, { AddressData } from \"./Address\";\r\nimport LineItemModel, { LineItemData } from \"./LineItem\";\r\nimport { CountryCode, CurrencyCode, LocaleCode, ShippingDetails } from \"./Common\";\r\nimport PriceModel from \"./Price\";\r\nimport CouponModel, { CouponCategory, CouponData, CouponDiscountMethod } from \"./Coupon\";\r\n\r\nexport type ShoppingContainerTotal = {\r\n shipping?: number;\r\n effectiveShipping?: number;\r\n subtotal?: number;\r\n mrpTotal?: number;\r\n couponTotal?: { [key: string]: number };\r\n grandTotal?: number;\r\n}\r\n\r\nexport type BaseShoppingContainerAttributes = BaseAttributes & {\r\n id: string;\r\n customerId?: string;\r\n customerEmail?: string;\r\n anonymousId?: string;\r\n lineItems: LineItemData[];\r\n shippingDetails: ShippingDetails | null;\r\n shippingAddress?: AddressData | null;\r\n billingAddress?: AddressData | null;\r\n coupons?: CouponData[];\r\n total?: ShoppingContainerTotal;\r\n country: CountryCode;\r\n currency: CurrencyCode;\r\n locale: LocaleCode;\r\n};\r\n\r\nexport type BaseShoppingContainerData = Omit<BaseShoppingContainerAttributes, 'coupons' | 'total'>\r\n& BaseData\r\n& {\r\n coupons: CouponData[],\r\n total: {\r\n shipping: number,\r\n effectiveShipping: number,\r\n subtotal: number,\r\n mrpTotal: number,\r\n couponTotal: { [key: string]: number },\r\n grandTotal: number\r\n };\r\n };\r\n\r\n\r\n/**\r\n * Abstract base class for shopping-related containers like carts and orders.\r\n * Manages common elements such as line items, addresses, coupons, and totals.\r\n */\r\nexport default abstract class BaseShoppingContainerModel extends BaseModel {\r\n protected id: string;\r\n protected customerId?: string;\r\n protected customerEmail?: string;\r\n protected anonymousId?: string;\r\n protected lineItems: LineItemModel[];\r\n protected shippingDetails: ShippingDetails | null;\r\n protected shippingAddress: AddressModel | null;\r\n protected billingAddress: AddressModel | null;\r\n\r\n // CouponsCodes\r\n protected coupons: CouponModel[];\r\n\r\n // Cart Totals\r\n protected total: {\r\n shipping: number;\r\n effectiveShipping: number;\r\n subtotal: number;\r\n mrpTotal: number;\r\n couponTotal: { [key: string]: number; };\r\n grandTotal: number;\r\n };\r\n\r\n protected country: CountryCode;\r\n protected currency: CurrencyCode;\r\n protected locale: LocaleCode;\r\n\r\n /**\r\n * Creates an instance of BaseShoppingContainerModel.\r\n * Initializes common properties and calculates initial base totals.\r\n * @param data - The initial attributes for the shopping container.\r\n * @param date - Optional date object for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: BaseShoppingContainerAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.customerId = data.customerId;\r\n this.customerEmail = data.customerEmail;\r\n this.anonymousId = data.anonymousId;\r\n this.country = data.country;\r\n this.currency = data.currency;\r\n this.locale = data.locale;\r\n this.lineItems = (data.lineItems ?? []).map(item => new LineItemModel(item));\r\n this.billingAddress = data.billingAddress ? new AddressModel(data.billingAddress, date) : null;\r\n this.shippingAddress = data.shippingAddress ? new AddressModel(data.shippingAddress, date) : null;\r\n this.coupons = (data.coupons || []).map(coupon => new CouponModel(coupon));\r\n\r\n this.shippingDetails = data.shippingDetails ? { ...data.shippingDetails } : null;\r\n\r\n this.total = {\r\n shipping: data.total?.shipping || 0,\r\n effectiveShipping: data.total?.effectiveShipping ?? data.total?.shipping ?? 0,\r\n subtotal: 0, // Will be calculated\r\n mrpTotal: 0, // Will be calculated\r\n couponTotal: data.total?.couponTotal || {},\r\n grandTotal: data.total?.grandTotal || 0, // Will be recalculated\r\n };\r\n\r\n this.recalculateBaseTotals();\r\n }\r\n\r\n /**\r\n * Recalculates the subtotal and mrpTotal based on the current line items.\r\n * Uses PriceModel for rounding based on the country.\r\n */\r\n protected recalculateBaseTotals(): void {\r\n this.total.subtotal = PriceModel.getRoundedPrice(this.lineItems.reduce((sum, item) => sum + item.getPriceTotals().subtotal, 0), this.country);\r\n this.total.mrpTotal = PriceModel.getRoundedPrice(this.lineItems.reduce((sum, item) => sum + item.getPriceTotals().mrpTotal, 0), this.country);\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for this shopping container (cart ID or order ID).\r\n * @returns The ID string.\r\n */\r\n public getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the customer ID associated with this container, if available.\r\n * @returns The customer ID string, or undefined.\r\n */\r\n public getCustomerId(): string | undefined {\r\n return this.customerId;\r\n }\r\n\r\n /**\r\n * Gets the customer email associated with this container, if available.\r\n * @returns The customer email string, or undefined.\r\n */\r\n public getCustomerEmail(): string | undefined {\r\n return this.customerEmail;\r\n }\r\n\r\n /**\r\n * Gets the anonymous user ID associated with this container, if available.\r\n * @returns The anonymous ID string, or undefined.\r\n */\r\n public getAnonymousId(): string | undefined {\r\n return this.anonymousId;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the line items in the container.\r\n * Each item is a new LineItemModel instance created from the original's details.\r\n * @returns An array of LineItemModel instances.\r\n */\r\n public getLineItems(): LineItemModel[] {\r\n // Return new instances to prevent modification of internal state\r\n return this.lineItems.map(item => new LineItemModel(item.getDetails()));\r\n }\r\n\r\n /**\r\n * Gets current number of line items in the container\r\n * @returns \r\n */\r\n public getLineItemsCount(): number {\r\n return this.lineItems.length;\r\n }\r\n\r\n /**\r\n * Gets a copy of the shipping details associated with the container.\r\n * @returns A ShippingDetails object, or null if none are set.\r\n */\r\n public getShippingDetails(): ShippingDetails | null {\r\n // Return a shallow copy if details exist\r\n return this.shippingDetails ? { ...this.shippingDetails } : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the shipping address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no shipping address is set.\r\n */\r\n public getShippingAddress(): AddressModel | null {\r\n return this.shippingAddress ? new AddressModel(this.shippingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Checks if a shipping address is associated with this container.\r\n * @returns True if a shipping address is set, false otherwise.\r\n */\r\n public hasShippingAddress(): boolean {\r\n return !!this.shippingAddress;\r\n }\r\n\r\n /**\r\n * Checks if a billing address is associated with this container.\r\n * @returns True if a billing address is set, false otherwise.\r\n */\r\n public hasBillingAddress(): boolean {\r\n return !!this.billingAddress;\r\n }\r\n \r\n /**\r\n * Gets a defensive copy of the billing address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no billing address is set.\r\n */\r\n public getBillingAddress(): AddressModel | null {\r\n return this.billingAddress ? new AddressModel(this.billingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the coupons applied to the container.\r\n * Each item is a new CouponModel instance created from the original's details.\r\n * @returns An array of CouponModel instances.\r\n */\r\n public getCoupons(): CouponModel[] {\r\n return this.coupons.map(coupon => new CouponModel(coupon.getDetails()));\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this container.\r\n * @returns The CountryCode enum value.\r\n */\r\n public getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Gets the currency code associated with this container.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Gets the locale code associated with this container.\r\n * @returns The LocaleCode enum value.\r\n */\r\n public getLocale(): LocaleCode {\r\n return this.locale;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the calculated totals for the container.\r\n * @returns An object containing shipping, subtotal, coupon, and grand totals.\r\n */\r\n public getTotal() {\r\n return { ...this.total, couponTotal: { ...this.total.couponTotal } };\r\n }\r\n\r\n /**\r\n * Calculates the discount value for a given coupon based on the current container state.\r\n * Returns 0 if the coupon is invalid, expired, or not applicable based on cart value or target category.\r\n * @param coupon - The CouponModel instance to evaluate.\r\n * @returns The calculated discount amount (rounded according to country rules).\r\n */\r\n public calculateApplicableCouponDiscount(coupon: CouponModel): number {\r\n // 1. Basic validation (active)\r\n if (!coupon.isActive()) {\r\n return 0;\r\n }\r\n\r\n // 2. Check regional requirements (min cart value, max discount)\r\n const minCartValueReq = coupon.getMinCartValue(this.country);\r\n const maxCartDiscountCap = coupon.getMaxCartDiscount(this.country);\r\n\r\n // Ensure minCartValueReq exists and subtotal meets the requirement\r\n if (!minCartValueReq || this.total.subtotal < minCartValueReq.price) {\r\n return 0;\r\n }\r\n\r\n // Ensure maxCartDiscountCap exists and is non-negative\r\n if (!maxCartDiscountCap || maxCartDiscountCap.price < 0) {\r\n return 0;\r\n }\r\n\r\n // 3. Calculate potential discount based on method and category\r\n const couponCategory = coupon.getCategory();\r\n const discountMethod = coupon.getDiscountMethod();\r\n let potentialDiscount = 0;\r\n // Determine the value the coupon applies to (shipping cost or subtotal)\r\n const targetValue = couponCategory === CouponCategory.SHIPPING ? this.total.shipping : this.total.subtotal;\r\n\r\n // No discount if the target value is zero or less\r\n if (targetValue <= 0) return 0;\r\n\r\n switch (discountMethod) {\r\n case CouponDiscountMethod.FLAT:\r\n // Flat discount is capped by the target value itself and the max discount cap\r\n const flatAmount = maxCartDiscountCap?.price ?? 0; // Use cap as the flat amount source? Or coupon.value? Needs clarification. Assuming cap IS the flat amount here.\r\n potentialDiscount = Math.min(targetValue, flatAmount);\r\n break;\r\n case CouponDiscountMethod.PERCENTAGE:\r\n // Calculate percentage discount based on the target value\r\n potentialDiscount = targetValue * (coupon.getPercentageValue() / 100);\r\n break;\r\n default:\r\n // Unknown discount method\r\n return 0;\r\n }\r\n\r\n // 4. Apply maximum discount cap to the calculated potential discount\r\n const finalDiscount = Math.min(potentialDiscount, maxCartDiscountCap.price);\r\n\r\n // 5. Round the final discount, ensuring it's not negative\r\n return PriceModel.getRoundedPrice(Math.max(0, finalDiscount), this.country);\r\n }\r\n\r\n /**\r\n * Recalculates the `couponTotal` map based on currently applied coupons.\r\n * Iterates through coupons, calculates their applicable discount, and stores it.\r\n * @returns The total discount amount from all valid and applicable coupons (rounded).\r\n */\r\n public recalculateCouponTotals(): number {\r\n this.total.couponTotal = {}; // Reset the map\r\n let totalDiscount = 0;\r\n\r\n this.coupons.forEach(coupon => {\r\n const discount = this.calculateApplicableCouponDiscount(coupon);\r\n if (discount > 0) {\r\n this.total.couponTotal[coupon.getCode()] = discount; // Store per-coupon discount\r\n totalDiscount += discount; // Accumulate total discount\r\n }\r\n });\r\n // Return the rounded total discount\r\n return PriceModel.getRoundedPrice(totalDiscount, this.country);\r\n }\r\n\r\n /**\r\n * Recalculates all container totals (subtotal, mrpTotal, coupons, shipping, grandTotal).\r\n * Should be called whenever line items, coupons, or base shipping cost change.\r\n */\r\n public updateCartTotals(): void {\r\n // 1. Calculate line item totals (subtotal, mrpTotal)\r\n this.total.subtotal = PriceModel.getRoundedPrice(this.lineItems.reduce((sum, item) => sum + item.getPriceTotals().subtotal, 0), this.country);\r\n this.total.mrpTotal = PriceModel.getRoundedPrice(this.lineItems.reduce((sum, item) => sum + item.getPriceTotals().mrpTotal, 0), this.country);\r\n\r\n // 2. Calculate total coupon discount and update the per-coupon discount map\r\n this.recalculateCouponTotals(); // This updates this.total.couponTotal\r\n\r\n // 3. Calculate effective shipping cost after applying shipping-specific coupons\r\n const shippingCouponDiscount = this.coupons\r\n .filter(c => c.getCategory() === CouponCategory.SHIPPING)\r\n .reduce((sum, c) => sum + (this.total.couponTotal[c.getCode()] ?? 0), 0);\r\n this.total.effectiveShipping = PriceModel.getRoundedPrice(Math.max(0, this.total.shipping - shippingCouponDiscount), this.country);\r\n\r\n // 4. Calculate total discount from non-shipping coupons\r\n const nonShippingCouponDiscount = this.coupons\r\n .filter(c => c.getCategory() !== CouponCategory.SHIPPING)\r\n .reduce((sum, c) => sum + (this.total.couponTotal[c.getCode()] ?? 0), 0);\r\n\r\n // 5. Calculate final grand total: (subtotal + effective shipping) - non-shipping discounts\r\n const grossTotal = this.total.subtotal + this.total.effectiveShipping;\r\n this.total.grandTotal = PriceModel.getRoundedPrice(Math.max(0, grossTotal - nonShippingCouponDiscount), this.country);\r\n }\r\n\r\n /**\r\n * Updates the shipping details (including estimated cost) for the container and recalculates totals.\r\n * @param details - The new ShippingDetails object, or null to clear shipping details and cost.\r\n */\r\n public setShippingDetails(details: ShippingDetails | null): void {\r\n // Store a copy of the details or null\r\n this.shippingDetails = details ? { ...details } : null;\r\n\r\n // Update the base shipping cost based on the new details\r\n this.total.shipping = PriceModel.getRoundedPrice(this.shippingDetails?.estimatedCost ?? 0, this.country);\r\n // Recalculate all totals as shipping cost affects effective shipping and grand total\r\n this.updateCartTotals();\r\n }\r\n\r\n\r\n /**\r\n * Gets a plain data object representing the shopping container's current state.\r\n * Includes details from the base model and specific container properties.\r\n * @returns BaseShoppingContainerData object suitable for serialization or API responses.\r\n */\r\n getDetails(): BaseShoppingContainerData {\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n customerId: this.getCustomerId(),\r\n customerEmail: this.getCustomerEmail(),\r\n anonymousId: this.getAnonymousId(),\r\n lineItems: this.getLineItems().map(item => item.getDetails()),\r\n shippingDetails: this.getShippingDetails(),\r\n shippingAddress: this.getShippingAddress()?.getDetails() || null,\r\n billingAddress: this.getBillingAddress()?.getDetails() || null,\r\n coupons: this.getCoupons().map(coupon => coupon.getDetails()),\r\n total: this.getTotal(),\r\n country: this.getCountry(),\r\n currency: this.getCurrency(),\r\n locale: this.getLocale(),\r\n }\r\n };\r\n}\r\n"]}
@@ -1,2 +1,2 @@
1
- import {b}from'./chunk-DKI6BDWK.mjs';import {e}from'./chunk-QZDXRDTG.mjs';var o=class{id;productKey;variantId;name;attributes;specifications;primaryImage;subItems;totalQuantity;basePrice;priceTotals;priceTiers;constructor(t){this.id=t.id,this.productKey=t.productKey,this.variantId=t.variantId,this.name={...t.name},this.attributes={...t.attributes},this.specifications={...t.specifications},this.primaryImage=new b(t.primaryImage),this.subItems=t.subItems.map(e=>({...e})),this.basePrice={...t.basePrice},this.priceTiers=t.priceTiers.map(e=>({...e})),this.totalQuantity=0,this.priceTotals={subtotal:0,mrpTotal:0},this.recalculateTotalQuantity(),this.recalculatePriceTotal();}getId(){return this.id}getProductKey(){return this.productKey}getVariantId(){return this.variantId}getName(t){return t?this.name[t]??this.name[e[t]]??this.name.en:{...this.name}}getAttributes(){return {...this.attributes}}getSpecifications(t){return t?this.specifications[t]??this.specifications[e[t]]??this.specifications.en:JSON.parse(JSON.stringify(this.specifications))}getImage(){return this.primaryImage}getSubItems(){return this.subItems.map(t=>({...t}))}getTotalQuantity(){return this.totalQuantity}getBasePrice(){return {...this.basePrice}}getPriceTotals(){return {...this.priceTotals}}getPriceTiers(){return this.priceTiers.map(t=>({...t}))}recalculateTotalQuantity(){this.totalQuantity=this.subItems.reduce((t,e)=>t+e.quantity,0);}recalculatePriceTotal(){let t=this.totalQuantity,e=this.basePrice.unitPrice,i=null;for(let r of this.priceTiers.sort((a,n)=>n.minQuantity-a.minQuantity))if(t>=r.minQuantity){i=r;break}i&&(e=i.unitPrice),this.priceTotals.mrpTotal=this.basePrice.unitPrice*t,this.priceTotals.subtotal=e*t;}getDetails(){return {id:this.getId(),productKey:this.getProductKey(),variantId:this.getVariantId(),name:this.getName(),attributes:this.getAttributes(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),totalQuantity:this.getTotalQuantity(),basePrice:this.getBasePrice(),priceTotals:this.getPriceTotals(),priceTiers:this.getPriceTiers()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(a=>a.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity),this.recalculateTotalQuantity(),this.recalculatePriceTotal();}clearLineItem(){this.id="",this.productKey="",this.variantId="",this.name={en:""},this.attributes={color:{name:"",hex:""}},this.primaryImage=new b({sources:{original:""}}),this.subItems=[],this.recalculateTotalQuantity(),this.recalculatePriceTotal();}};export{o as a};//# sourceMappingURL=chunk-5I5EKOWK.mjs.map
2
- //# sourceMappingURL=chunk-5I5EKOWK.mjs.map
1
+ import {b}from'./chunk-DKI6BDWK.mjs';import {e}from'./chunk-G6EL2Y7V.mjs';var o=class{id;productKey;variantId;name;attributes;specifications;primaryImage;subItems;totalQuantity;basePrice;priceTotals;priceTiers;constructor(t){this.id=t.id,this.productKey=t.productKey,this.variantId=t.variantId,this.name={...t.name},this.attributes={...t.attributes},this.specifications={...t.specifications},this.primaryImage=new b(t.primaryImage),this.subItems=t.subItems.map(e=>({...e})),this.basePrice={...t.basePrice},this.priceTiers=t.priceTiers.map(e=>({...e})),this.totalQuantity=0,this.priceTotals={subtotal:0,mrpTotal:0},this.recalculateTotalQuantity(),this.recalculatePriceTotal();}getId(){return this.id}getProductKey(){return this.productKey}getVariantId(){return this.variantId}getName(t){return t?this.name[t]??this.name[e[t]]??this.name.en:{...this.name}}getAttributes(){return {...this.attributes}}getSpecifications(t){return t?this.specifications[t]??this.specifications[e[t]]??this.specifications.en:JSON.parse(JSON.stringify(this.specifications))}getImage(){return this.primaryImage}getSubItems(){return this.subItems.map(t=>({...t}))}getTotalQuantity(){return this.totalQuantity}getBasePrice(){return {...this.basePrice}}getPriceTotals(){return {...this.priceTotals}}getPriceTiers(){return this.priceTiers.map(t=>({...t}))}recalculateTotalQuantity(){this.totalQuantity=this.subItems.reduce((t,e)=>t+e.quantity,0);}recalculatePriceTotal(){let t=this.totalQuantity,e=this.basePrice.unitPrice,i=null;for(let r of this.priceTiers.sort((a,n)=>n.minQuantity-a.minQuantity))if(t>=r.minQuantity){i=r;break}i&&(e=i.unitPrice),this.priceTotals.mrpTotal=this.basePrice.unitPrice*t,this.priceTotals.subtotal=e*t;}getDetails(){return {id:this.getId(),productKey:this.getProductKey(),variantId:this.getVariantId(),name:this.getName(),attributes:this.getAttributes(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),totalQuantity:this.getTotalQuantity(),basePrice:this.getBasePrice(),priceTotals:this.getPriceTotals(),priceTiers:this.getPriceTiers()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(a=>a.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity),this.recalculateTotalQuantity(),this.recalculatePriceTotal();}clearLineItem(){this.id="",this.productKey="",this.variantId="",this.name={en:""},this.attributes={color:{name:"",hex:""}},this.primaryImage=new b({sources:{original:""}}),this.subItems=[],this.recalculateTotalQuantity(),this.recalculatePriceTotal();}};export{o as a};//# sourceMappingURL=chunk-SY36ZFQ6.mjs.map
2
+ //# sourceMappingURL=chunk-SY36ZFQ6.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Classes/LineItem.ts"],"names":["LineItemModel","data","ImageInfoModel","item","tier","locale","LocaleLanguageMap","sum","quantity","unitPrice","applicableTier","b","subItems","addQuantity","subItem","existingSubItem","sub"],"mappings":"0EAoCqBA,IAAAA,CAAAA,CAArB,KAAmC,CACvB,EACA,CAAA,UAAA,CACA,UACA,IACA,CAAA,UAAA,CAGA,cACA,CAAA,YAAA,CACA,QACA,CAAA,aAAA,CACA,UACA,WAIA,CAAA,UAAA,CAMV,WAAYC,CAAAA,CAAAA,CAA0B,CAClC,IAAA,CAAK,EAAKA,CAAAA,CAAAA,CAAK,EACf,CAAA,IAAA,CAAK,UAAaA,CAAAA,CAAAA,CAAK,UACvB,CAAA,IAAA,CAAK,UAAYA,CAAK,CAAA,SAAA,CAEtB,IAAK,CAAA,IAAA,CAAO,CAAE,GAAGA,EAAK,IAAK,CAAA,CAC3B,IAAK,CAAA,UAAA,CAAa,CAAE,GAAGA,EAAK,UAAW,CAAA,CACvC,IAAK,CAAA,cAAA,CAAiB,CAAC,GAAGA,CAAK,CAAA,cAAe,CAC9C,CAAA,IAAA,CAAK,YAAe,CAAA,IAAIC,CAAeD,CAAAA,CAAAA,CAAK,YAAY,CACxD,CAAA,IAAA,CAAK,QAAWA,CAAAA,CAAAA,CAAK,QAAS,CAAA,GAAA,CAAIE,IAAS,CAAE,GAAGA,CAAK,CAAA,CAAE,CACvD,CAAA,IAAA,CAAK,UAAY,CAAE,GAAGF,CAAK,CAAA,SAAU,CACrC,CAAA,IAAA,CAAK,UAAaA,CAAAA,CAAAA,CAAK,UAAW,CAAA,GAAA,CAAIG,CAAS,GAAA,CAAE,GAAGA,CAAK,EAAE,CAE3D,CAAA,IAAA,CAAK,aAAgB,CAAA,CAAA,CACrB,IAAK,CAAA,WAAA,CAAc,CACf,QAAA,CAAU,CACV,CAAA,Q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./Common\";\r\nimport { LocaleLanguageMap } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport { LocalizedProductSpecification, ProductSpecification } from \"./Product\";\r\n\r\nexport type SubItem = {\r\n size: string;\r\n quantity: number;\r\n};\r\n\r\nexport type LineItemAttributes = {\r\n id: string;\r\n productKey: string;\r\n variantId: string;\r\n name: LocalizedString;\r\n attributes: {\r\n color: Color;\r\n };\r\n specifications: LocalizedProductSpecification;\r\n primaryImage: ImageInfoData;\r\n subItems: SubItem[];\r\n basePrice: BasePrice;\r\n priceTiers: PriceTier[];\r\n}\r\n\r\nexport type LineItemData = LineItemAttributes & {\r\n totalQuantity: number;\r\n priceTotals: {\r\n subtotal: number;\r\n mrpTotal: number;\r\n };\r\n}\r\n\r\n/**\r\n * Represents a line item within a shopping cart.\r\n */\r\nexport default class LineItemModel {\r\n protected id: string;\r\n protected productKey: string;\r\n protected variantId: string;\r\n protected name: LocalizedString;\r\n protected attributes: {\r\n color: Color;\r\n };\r\n protected specifications: LocalizedProductSpecification;\r\n protected primaryImage: ImageInfoModel;\r\n protected subItems: SubItem[];\r\n protected totalQuantity: number;\r\n protected basePrice: BasePrice;\r\n protected priceTotals: {\r\n subtotal: number;\r\n mrpTotal: number;\r\n };\r\n protected priceTiers: PriceTier[];\r\n\r\n /**\r\n * Creates an instance of LineItemModel.\r\n * @param data - The initial line item attributes.\r\n */\r\n constructor(data: LineItemAttributes) {\r\n this.id = data.id;\r\n this.productKey = data.productKey;\r\n this.variantId = data.variantId;\r\n\r\n this.name = { ...data.name };\r\n this.attributes = { ...data.attributes };\r\n this.specifications = {...data.specifications };\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.subItems = data.subItems.map(item => ({ ...item }));\r\n this.basePrice = { ...data.basePrice };\r\n this.priceTiers = data.priceTiers.map(tier => ({ ...tier }));\r\n\r\n this.totalQuantity = 0;\r\n this.priceTotals = {\r\n subtotal: 0,\r\n mrpTotal: 0\r\n };\r\n\r\n this.recalculateTotalQuantity();\r\n this.recalculatePriceTotal();\r\n }\r\n\r\n /** Gets the unique identifier of the line item. */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /** Gets the product key associated with this line item. */\r\n getProductKey(): string {\r\n return this.productKey;\r\n }\r\n\r\n /** Gets the product variant ID associated with this line item. */\r\n getVariantId(): string {\r\n return this.variantId;\r\n }\r\n\r\n /**\r\n * Gets the full localized product name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the product name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if(locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n\r\n /** Gets the variant attributes. */\r\n getAttributes(): { color: Color } {\r\n return { ...this.attributes };\r\n }\r\n\r\n /**\r\n * Gets the full localized product specifications object.\r\n * @returns Product Specifications\r\n */\r\n getSpecifications(): LocalizedProductSpecification\r\n /**\r\n * Gets the product specifications for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The ProductSpecification object for the specified locale, or undefined if not found.\r\n */\r\n getSpecifications(locale: LocaleCode): ProductSpecification | undefined\r\n getSpecifications(locale?: LocaleCode): LocalizedProductSpecification | ProductSpecification | undefined {\r\n if(locale){\r\n return this.specifications[locale] ?? this.specifications[LocaleLanguageMap[locale]] ?? this.specifications.en;\r\n } else {\r\n return JSON.parse(JSON.stringify(this.specifications));\r\n }\r\n }\r\n\r\n /** Gets the image information model for this line item. */\r\n getImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /** Gets the sub-items (size/quantity breakdown). */\r\n getSubItems(): SubItem[] {\r\n return this.subItems.map(item => ({ ...item }));\r\n }\r\n\r\n /** Gets the total quantity for this line item across all sub-items. */\r\n getTotalQuantity(): number {\r\n return this.totalQuantity;\r\n }\r\n\r\n /** Gets the base price for a single unit. */\r\n getBasePrice(): BasePrice {\r\n return { ...this.basePrice };\r\n }\r\n\r\n /** Gets the calculated price details (subtotal, mrpTotal) for this line item. */\r\n getPriceTotals(): { subtotal: number; mrpTotal: number } {\r\n return { ...this.priceTotals };\r\n }\r\n\r\n /** Gets the applicable price tiers for this product variant. */\r\n getPriceTiers(): PriceTier[] {\r\n return this.priceTiers.map(tier => ({ ...tier }));\r\n }\r\n\r\n /**\r\n * Recalculates the total quantity based on the quantities in subItems.\r\n */\r\n protected recalculateTotalQuantity(): void {\r\n this.totalQuantity = this.subItems.reduce((sum, item) => sum + item.quantity, 0);\r\n }\r\n\r\n /**\r\n * Recalculates the line item's price (subtotal and mrpTotal)\r\n * based on total quantity, base price, and applicable price tiers.\r\n */\r\n protected recalculatePriceTotal(): void {\r\n const quantity = this.totalQuantity;\r\n let unitPrice = this.basePrice.unitPrice;\r\n\r\n let applicableTier = null;\r\n for (const tier of this.priceTiers.sort((a, b) => b.minQuantity - a.minQuantity)) { \r\n if (quantity >= tier.minQuantity) {\r\n applicableTier = tier;\r\n break;\r\n }\r\n }\r\n\r\n if (applicableTier) {\r\n unitPrice = applicableTier.unitPrice;\r\n }\r\n\r\n // Calculate totals\r\n this.priceTotals.mrpTotal = this.basePrice.unitPrice * quantity;\r\n this.priceTotals.subtotal = unitPrice * quantity;\r\n }\r\n\r\n\r\n /**\r\n * Gets a plain data object representing the line item's details.\r\n * @returns LineItemData.\r\n */\r\n getDetails(): LineItemData {\r\n return {\r\n id: this.getId(),\r\n productKey: this.getProductKey(),\r\n variantId: this.getVariantId(),\r\n name: this.getName(),\r\n attributes: this.getAttributes(),\r\n specifications: this.getSpecifications(),\r\n primaryImage: this.getImage().getDetails(),\r\n subItems: this.getSubItems(),\r\n totalQuantity: this.getTotalQuantity(),\r\n basePrice: this.getBasePrice(),\r\n priceTotals: this.getPriceTotals(),\r\n priceTiers: this.getPriceTiers(),\r\n };\r\n }\r\n \r\n /**\r\n * Adds or updates sub-items (e.g., sizes with quantities) to the line item.\r\n * If a sub-item with the same size already exists, its quantity is either\r\n * updated by adding the new quantity or replaced entirely, based on the `addQuantity` flag.\r\n * Sub-items with a resulting quantity of 0 are removed.\r\n * Recalculates total quantity and price totals afterwards.\r\n *\r\n * @param subItems - An array of `SubItem` objects to add or update.\r\n * @param addQuantity - If true, adds the quantity from `subItem` to the existing quantity.\r\n * If false, replaces the existing quantity with the one from `subItem`.\r\n */\r\n addSubItems(subItems: SubItem[], addQuantity: boolean): void {\r\n subItems.forEach(subItem => {\r\n const existingSubItem = this.subItems.find(item => item.size === subItem.size);\r\n if (existingSubItem) {\r\n existingSubItem.quantity = addQuantity ? existingSubItem.quantity + subItem.quantity : subItem.quantity;\r\n } else {\r\n this.subItems.push(subItem);\r\n }\r\n })\r\n this.subItems = this.subItems.filter(sub => sub.quantity);\r\n\r\n this.recalculateTotalQuantity();\r\n this.recalculatePriceTotal();\r\n }\r\n\r\n /**\r\n * Resets the line item's properties to their default empty or initial state.\r\n * Useful for clearing out line item data without creating a new instance.\r\n * Recalculates total quantity and price totals afterwards (which will be zero).\r\n */\r\n clearLineItem(): void {\r\n this.id = '';\r\n this.productKey = '';\r\n this.variantId = '';\r\n this.name = { en: '' };\r\n this.attributes = { color: { name: '', hex: '' } };\r\n this.primaryImage = new ImageInfoModel({ sources: { original: '' } });\r\n this.subItems = [];\r\n this.recalculateTotalQuantity();\r\n this.recalculatePriceTotal();\r\n }\r\n}"]}
1
+ {"version":3,"sources":["../src/Classes/LineItem.ts"],"names":["LineItemModel","data","ImageInfoModel","item","tier","locale","LocaleLanguageMap","sum","quantity","unitPrice","applicableTier","b","subItems","addQuantity","subItem","existingSubItem","sub"],"mappings":"0EAoCqBA,IAAAA,CAAAA,CAArB,KAAmC,CACvB,EACA,CAAA,UAAA,CACA,UACA,IACA,CAAA,UAAA,CAGA,cACA,CAAA,YAAA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WF,CAAAA,CAAAA,CAAcE,EAAgB,QAAWD,CAAAA,CAAAA,CAAQ,QAAWA,CAAAA,CAAAA,CAAQ,QAE/F,CAAA,IAAA,CAAK,SAAS,IAAKA,CAAAA,CAAO,EAEhC,CAAC,CACD,CAAA,IAAA,CAAK,QAAW,CAAA,IAAA,CAAK,QAAS,CAAA,MAAA,CAAOE,CAAOA,EAAAA,CAAAA,CAAI,QAAQ,CAAA,CAExD,KAAK,wBAAyB,EAAA,CAC9B,IAAK,CAAA,qBAAA,GACP,CAOA,eAAsB,CACpB,IAAA,CAAK,EAAK,CAAA,EAAA,CACV,IAAK,CAAA,UAAA,CAAa,GAClB,IAAK,CAAA,SAAA,CAAY,EACjB,CAAA,IAAA,CAAK,IAAO,CAAA,CAAE,EAAI,CAAA,EAAG,CACrB,CAAA,IAAA,CAAK,UAAa,CAAA,CAAE,KAAO,CAAA,CAAE,KAAM,EAAI,CAAA,GAAA,CAAK,EAAG,CAAE,CACjD,CAAA,IAAA,CAAK,YAAe,CAAA,IAAId,CAAe,CAAA,CAAE,OAAS,CAAA,CAAE,QAAU,CAAA,EAAG,CAAE,CAAC,CAAA,CACpE,IAAK,CAAA,QAAA,CAAW,EAAC,CACjB,IAAK,CAAA,wBAAA,EACL,CAAA,IAAA,CAAK,qBAAsB,GAC7B,CACF","file":"chunk-SY36ZFQ6.mjs","sourcesContent":["import { BasePrice, Color, LocaleCode, LocalizedString, PriceTier } from \"./Common\";\r\nimport { LocaleLanguageMap } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport { LocalizedProductSpecification, ProductSpecification } from \"./Product\";\r\n\r\nexport type SubItem = {\r\n size: string;\r\n quantity: number;\r\n};\r\n\r\nexport type LineItemAttributes = {\r\n id: string;\r\n productKey: string;\r\n variantId: string;\r\n name: LocalizedString;\r\n attributes: {\r\n color: Color;\r\n };\r\n specifications: LocalizedProductSpecification;\r\n primaryImage: ImageInfoData;\r\n subItems: SubItem[];\r\n basePrice: BasePrice;\r\n priceTiers: PriceTier[];\r\n}\r\n\r\nexport type LineItemData = LineItemAttributes & {\r\n totalQuantity: number;\r\n priceTotals: {\r\n subtotal: number;\r\n mrpTotal: number;\r\n };\r\n}\r\n\r\n/**\r\n * Represents a line item within a shopping cart.\r\n */\r\nexport default class LineItemModel {\r\n protected id: string;\r\n protected productKey: string;\r\n protected variantId: string;\r\n protected name: LocalizedString;\r\n protected attributes: {\r\n color: Color;\r\n };\r\n protected specifications: LocalizedProductSpecification;\r\n protected primaryImage: ImageInfoModel;\r\n protected subItems: SubItem[];\r\n protected totalQuantity: number;\r\n protected basePrice: BasePrice;\r\n protected priceTotals: {\r\n subtotal: number;\r\n mrpTotal: number;\r\n };\r\n protected priceTiers: PriceTier[];\r\n\r\n /**\r\n * Creates an instance of LineItemModel.\r\n * @param data - The initial line item attributes.\r\n */\r\n constructor(data: LineItemAttributes) {\r\n this.id = data.id;\r\n this.productKey = data.productKey;\r\n this.variantId = data.variantId;\r\n\r\n this.name = { ...data.name };\r\n this.attributes = { ...data.attributes };\r\n this.specifications = {...data.specifications };\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.subItems = data.subItems.map(item => ({ ...item }));\r\n this.basePrice = { ...data.basePrice };\r\n this.priceTiers = data.priceTiers.map(tier => ({ ...tier }));\r\n\r\n this.totalQuantity = 0;\r\n this.priceTotals = {\r\n subtotal: 0,\r\n mrpTotal: 0\r\n };\r\n\r\n this.recalculateTotalQuantity();\r\n this.recalculatePriceTotal();\r\n }\r\n\r\n /** Gets the unique identifier of the line item. */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /** Gets the product key associated with this line item. */\r\n getProductKey(): string {\r\n return this.productKey;\r\n }\r\n\r\n /** Gets the product variant ID associated with this line item. */\r\n getVariantId(): string {\r\n return this.variantId;\r\n }\r\n\r\n /**\r\n * Gets the full localized product name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the product name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if(locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n\r\n /** Gets the variant attributes. */\r\n getAttributes(): { color: Color } {\r\n return { ...this.attributes };\r\n }\r\n\r\n /**\r\n * Gets the full localized product specifications object.\r\n * @returns Product Specifications\r\n */\r\n getSpecifications(): LocalizedProductSpecification\r\n /**\r\n * Gets the product specifications for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The ProductSpecification object for the specified locale, or undefined if not found.\r\n */\r\n getSpecifications(locale: LocaleCode): ProductSpecification | undefined\r\n getSpecifications(locale?: LocaleCode): LocalizedProductSpecification | ProductSpecification | undefined {\r\n if(locale){\r\n return this.specifications[locale] ?? this.specifications[LocaleLanguageMap[locale]] ?? this.specifications.en;\r\n } else {\r\n return JSON.parse(JSON.stringify(this.specifications));\r\n }\r\n }\r\n\r\n /** Gets the image information model for this line item. */\r\n getImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /** Gets the sub-items (size/quantity breakdown). */\r\n getSubItems(): SubItem[] {\r\n return this.subItems.map(item => ({ ...item }));\r\n }\r\n\r\n /** Gets the total quantity for this line item across all sub-items. */\r\n getTotalQuantity(): number {\r\n return this.totalQuantity;\r\n }\r\n\r\n /** Gets the base price for a single unit. */\r\n getBasePrice(): BasePrice {\r\n return { ...this.basePrice };\r\n }\r\n\r\n /** Gets the calculated price details (subtotal, mrpTotal) for this line item. */\r\n getPriceTotals(): { subtotal: number; mrpTotal: number } {\r\n return { ...this.priceTotals };\r\n }\r\n\r\n /** Gets the applicable price tiers for this product variant. */\r\n getPriceTiers(): PriceTier[] {\r\n return this.priceTiers.map(tier => ({ ...tier }));\r\n }\r\n\r\n /**\r\n * Recalculates the total quantity based on the quantities in subItems.\r\n */\r\n protected recalculateTotalQuantity(): void {\r\n this.totalQuantity = this.subItems.reduce((sum, item) => sum + item.quantity, 0);\r\n }\r\n\r\n /**\r\n * Recalculates the line item's price (subtotal and mrpTotal)\r\n * based on total quantity, base price, and applicable price tiers.\r\n */\r\n protected recalculatePriceTotal(): void {\r\n const quantity = this.totalQuantity;\r\n let unitPrice = this.basePrice.unitPrice;\r\n\r\n let applicableTier = null;\r\n for (const tier of this.priceTiers.sort((a, b) => b.minQuantity - a.minQuantity)) { \r\n if (quantity >= tier.minQuantity) {\r\n applicableTier = tier;\r\n break;\r\n }\r\n }\r\n\r\n if (applicableTier) {\r\n unitPrice = applicableTier.unitPrice;\r\n }\r\n\r\n // Calculate totals\r\n this.priceTotals.mrpTotal = this.basePrice.unitPrice * quantity;\r\n this.priceTotals.subtotal = unitPrice * quantity;\r\n }\r\n\r\n\r\n /**\r\n * Gets a plain data object representing the line item's details.\r\n * @returns LineItemData.\r\n */\r\n getDetails(): LineItemData {\r\n return {\r\n id: this.getId(),\r\n productKey: this.getProductKey(),\r\n variantId: this.getVariantId(),\r\n name: this.getName(),\r\n attributes: this.getAttributes(),\r\n specifications: this.getSpecifications(),\r\n primaryImage: this.getImage().getDetails(),\r\n subItems: this.getSubItems(),\r\n totalQuantity: this.getTotalQuantity(),\r\n basePrice: this.getBasePrice(),\r\n priceTotals: this.getPriceTotals(),\r\n priceTiers: this.getPriceTiers(),\r\n };\r\n }\r\n \r\n /**\r\n * Adds or updates sub-items (e.g., sizes with quantities) to the line item.\r\n * If a sub-item with the same size already exists, its quantity is either\r\n * updated by adding the new quantity or replaced entirely, based on the `addQuantity` flag.\r\n * Sub-items with a resulting quantity of 0 are removed.\r\n * Recalculates total quantity and price totals afterwards.\r\n *\r\n * @param subItems - An array of `SubItem` objects to add or update.\r\n * @param addQuantity - If true, adds the quantity from `subItem` to the existing quantity.\r\n * If false, replaces the existing quantity with the one from `subItem`.\r\n */\r\n addSubItems(subItems: SubItem[], addQuantity: boolean): void {\r\n subItems.forEach(subItem => {\r\n const existingSubItem = this.subItems.find(item => item.size === subItem.size);\r\n if (existingSubItem) {\r\n existingSubItem.quantity = addQuantity ? existingSubItem.quantity + subItem.quantity : subItem.quantity;\r\n } else {\r\n this.subItems.push(subItem);\r\n }\r\n })\r\n this.subItems = this.subItems.filter(sub => sub.quantity);\r\n\r\n this.recalculateTotalQuantity();\r\n this.recalculatePriceTotal();\r\n }\r\n\r\n /**\r\n * Resets the line item's properties to their default empty or initial state.\r\n * Useful for clearing out line item data without creating a new instance.\r\n * Recalculates total quantity and price totals afterwards (which will be zero).\r\n */\r\n clearLineItem(): void {\r\n this.id = '';\r\n this.productKey = '';\r\n this.variantId = '';\r\n this.name = { en: '' };\r\n this.attributes = { color: { name: '', hex: '' } };\r\n this.primaryImage = new ImageInfoModel({ sources: { original: '' } });\r\n this.subItems = [];\r\n this.recalculateTotalQuantity();\r\n this.recalculatePriceTotal();\r\n }\r\n}"]}
package/dist/index.d.mts CHANGED
@@ -1,3 +1,5 @@
1
+ import { OperationalCountry, OperationalCountryCurrency, OperationalLocale } from './Classes/Enum.mjs';
2
+
1
3
  declare const Schema: {
2
4
  getStandardSchemaDefinition(): {
3
5
  $id: string;
@@ -124,15 +126,15 @@ declare const Schema: {
124
126
  };
125
127
  country: {
126
128
  type: string;
127
- enum: string[];
129
+ enum: OperationalCountry.IN[];
128
130
  };
129
131
  currency: {
130
132
  type: string;
131
- enum: string[];
133
+ enum: OperationalCountryCurrency.INR[];
132
134
  };
133
135
  locale: {
134
136
  type: string;
135
- enum: string[];
137
+ enum: OperationalLocale[];
136
138
  };
137
139
  addressType: {
138
140
  type: string;
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { OperationalCountry, OperationalCountryCurrency, OperationalLocale } from './Classes/Enum.js';
2
+
1
3
  declare const Schema: {
2
4
  getStandardSchemaDefinition(): {
3
5
  $id: string;
@@ -124,15 +126,15 @@ declare const Schema: {
124
126
  };
125
127
  country: {
126
128
  type: string;
127
- enum: string[];
129
+ enum: OperationalCountry.IN[];
128
130
  };
129
131
  currency: {
130
132
  type: string;
131
- enum: string[];
133
+ enum: OperationalCountryCurrency.INR[];
132
134
  };
133
135
  locale: {
134
136
  type: string;
135
- enum: string[];
137
+ enum: OperationalLocale[];
136
138
  };
137
139
  addressType: {
138
140
  type: string;
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict';var F=require('crypto'),W=require('util');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var F__default=/*#__PURE__*/_interopDefault(F);var W__default=/*#__PURE__*/_interopDefault(W);var A={$id:"standards",definitions:{lowercaseText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]*$"},lowercaseText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,10}$"},lowercaseText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,16}$"},lowercaseText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,30}$"},lowercaseText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,50}$"},lowercaseText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,256}$"},text:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).*$"},text10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,10}$"},text16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,16}$"},text30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,30}$"},text50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,50}$"},text256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,256}$"},requiredText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).+$"},requiredText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,10}$"},requiredText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,16}$"},requiredText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,30}$"},requiredText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,50}$"},requiredText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,256}$"},url:{type:"string",pattern:"^https://[^\\s/$.?#].[^\\s]*$",maxLength:2048},uuid:{type:"string",minLength:1,pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"},productKey:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$"},variantId:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$"},firstName:{$ref:"#/definitions/requiredText30"},lastName:{$ref:"#/definitions/text30"},phone:{type:"string",pattern:"^[0-9]{10}$"},email:{type:"string",pattern:"^[^\\s]+@[^\\s]+\\.[^\\s]+$"},addressLine1:{$ref:"#/definitions/requiredText50"},addressLine2:{$ref:"#/definitions/text50"},city:{$ref:"#/definitions/requiredText30"},postalCode:{$ref:"#/definitions/requiredText16"},state:{type:"string",enum:["AP","AR","AS","BR","CT","GA","GJ","HR","HP","JH","KA","KL","MP","MH","MN","ML","MZ","NL","OR","PB","RJ","SK","TN","TG","TR","UP","UT","WB","AN","CH","DH","LD","DL","PY","LA","JK"]},country:{type:"string",enum:["IN"]},currency:{type:"string",enum:["INR"]},locale:{type:"string",enum:["en-IN"]},addressType:{type:"string",enum:["shipping","billing","billing&shipping"]},address:{type:"object",properties:{firstName:{$ref:"standards#/definitions/firstName"},lastName:{$ref:"standards#/definitions/lastName"},phone:{$ref:"standards#/definitions/phone"},email:{$ref:"standards#/definitions/email"},addressLine1:{$ref:"standards#/definitions/addressLine1"},addressLine2:{$ref:"standards#/definitions/addressLine2"},city:{$ref:"standards#/definitions/city"},postalCode:{$ref:"standards#/definitions/postalCode"},state:{$ref:"standards#/definitions/state"},country:{$ref:"standards#/definitions/country"}},required:["firstName","lastName","phone","email","addressLine1","postalCode","state","country"]}}};var D={getStandardSchemaDefinition(){return A}},v=D;var x=new Uint8Array(256),m=x.length;function N(){return m>x.length-16&&(F__default.default.randomFillSync(x),m=0),x.slice(m,m+=16)}var U=/^(?:[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 P(t){return typeof t=="string"&&U.test(t)}var R=P;var i=[];for(let t=0;t<256;++t)i.push((t+256).toString(16).slice(1));function T(t,e=0){return i[t[e+0]]+i[t[e+1]]+i[t[e+2]]+i[t[e+3]]+"-"+i[t[e+4]]+i[t[e+5]]+"-"+i[t[e+6]]+i[t[e+7]]+"-"+i[t[e+8]]+i[t[e+9]]+"-"+i[t[e+10]]+i[t[e+11]]+i[t[e+12]]+i[t[e+13]]+i[t[e+14]]+i[t[e+15]]}function w(t){if(!R(t))throw TypeError("Invalid UUID");let e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}var O=w;function K(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var b="6ba7b810-9dad-11d1-80b4-00c04fd430c8",M="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function $(t,e,r){function o(a,f,d,g){var s;if(typeof a=="string"&&(a=K(a)),typeof f=="string"&&(f=O(f)),((s=f)===null||s===void 0?void 0:s.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let p=new Uint8Array(16+a.length);if(p.set(f),p.set(a,f.length),p=r(p),p[6]=p[6]&15|e,p[8]=p[8]&63|128,d){g=g||0;for(let l=0;l<16;++l)d[g+l]=p[l];return d}return T(p)}try{o.name=t;}catch{}return o.DNS=b,o.URL=M,o}var I={randomUUID:F__default.default.randomUUID};function Y(t,e,r){if(I.randomUUID&&!e&&!t)return I.randomUUID();t=t||{};let o=t.random||(t.rng||N)();if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,e){r=r||0;for(let a=0;a<16;++a)e[r+a]=o[a];return e}return T(o)}var S=Y;function H(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),F__default.default.createHash("sha1").update(t).digest()}var L=H;var q=$("v5",80,L),_=q;var z={isUUID:t=>/^[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(t),isEmail:t=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t),isURL:t=>/^(http|https):\/\/[^ "]+$/.test(t),generateUUID:(t,e)=>e&&t?_(t,e):S(),generateSearchId:(t,e)=>`${t}#${e}`,getKeyfromSearchId:t=>{let[e,r]=t.split("#");return {key:e,variantId:r}}},B=z;var y=Object.freeze({INVALID_UUID:"Invalid UUID",INVALID_EMAIL:"Invalid Email",INVALID_TOKEN:"Invalid Token",TOKEN_EXPIRED:"Token Expired",INVALID_VERIFIER:"Invalid Verifier",INVALID_PERMISSIONS:"Invalid Permissions",INVALID_AUTH_TYPE:"Invalid Authorization Type",USER_PRIVATE_KEY_NOT_FOUND:"User Private Key Not Found",USER_PUBLIC_KEY_NOT_FOUND:"User Public Key Not Found",ANONYMOUS_PRIVATE_KEY_NOT_FOUND:"Anonymous Private Key Not Found",ANONYMOUS_PUBLIC_KEY_NOT_FOUND:"Anonymous Public Key Not Found",SYSTEM_PRIVATE_KEY_NOT_FOUND:"System Private Key Not Found",SYSTEM_PUBLIC_KEY_NOT_FOUND:"System Public Key Not Found",ADMIN_PRIVATE_KEY_NOT_FOUND:"Admin Private Key Not Found",ADMIN_PUBLIC_KEY_NOT_FOUND:"Admin Public Key Not Found",SECRET_TOKEN_NOT_FOUND:"Secret Token Not Found",ANONYMOUS_SESSION_NOT_ALLOWED:"Anonymous Session Not Allowed",USER_SESSION_NOT_ALLOWED:"User Session Not Allowed",SYSTEM_SESSION_NOT_ALLOWED:"System Session Not Allowed",CDN_SESSION_NOT_ALLOWED:"CDN Session Not Allowed",INTERNAL_SERVER_ERROR:"Internal Server Error",SOMETHING_WENT_WRONG:"Something went wrong",AUTH_CONTEXT_NOT_INITIALIZED:"Auth Context not Initialized"});var c={logException:(t,e)=>{console.error(`Exception Occurred in Function: ${t}, Error: ${c.inspect(e)}`);},logError:(t,e)=>{console.error(`Error Occurred in Function: ${t}, Error: ${c.inspect(e)}`);},logWarning:(t,e)=>{console.warn(`Warning in Function: ${t} - ${c.inspect(e)}`);},logMessage:(t,e)=>{console.log(`Message in Function: ${t} - ${c.inspect(e)}`);},logInvalidPayload:(t,e)=>{console.error(`Invalid Payload received for Function: ${t}, Error: ${c.inspect(e)}`);},inspect:t=>typeof t=="string"?t:W__default.default.inspect(t)},u=c;var G={handleException:(t,e,r)=>{e.knownError?(e.logError&&u.logError(t,e),r.status(e.status).json({status:e.status,error:e.error})):e.status&&e.error?(u.logException(t,e),r.status(e.status).json({error:e.errorMessage||JSON.stringify(e.error),status:e.status})):(u.logException(t,e),r.status(500).json({status:500,error:y.INTERNAL_SERVER_ERROR}));},generateResponse:(t,e,r)=>({status:t,data:e,error:r}),generateError:(t,e,r=!0,o=!1)=>({status:t,error:e,knownError:r,logError:o})},J=G;var j=async(t,e,r="GET",o={},a)=>{let f={method:r,headers:{"Content-Type":"application/json",...o}};r!=="GET"&&a&&(f.body=JSON.stringify(a));let d=`${t}${e?"/"+e:""}`,g=d.includes("api.xetile.com")||d.includes("localhost");try{let s=await fetch(d,f);if(!s.ok){let l,E=await s.text();try{l=JSON.parse(E);}catch{l={status:s.status,error:E||s.statusText},u.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${d}. Raw text: ${E}`);}throw {status:s.status,statusText:s.statusText,error:l}}let p=await s.json();return u.logMessage("Fetch",`API call successful: URL-${d}, Status- ${s.status}`),{status:s.status,statusText:s.statusText,data:g?p.data:p}}catch(s){throw u.logError("Fetch",`API call failed: URL-${d}, Status- ${s.status||500}, Error- ${u.inspect(s.error||s)}`),{status:s.status||500,statusText:s.statusText||y.INTERNAL_SERVER_ERROR,error:s.error||{status:s.status||500,error:s.statusText||y.SOMETHING_WENT_WRONG}}}},k=j;
2
- exports.Fetch=k;exports.Logger=u;exports.ResponseUtility=J;exports.Schema=v;exports.Utils=B;//# sourceMappingURL=index.js.map
1
+ 'use strict';var M=require('crypto'),j=require('util');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var M__default=/*#__PURE__*/_interopDefault(M);var j__default=/*#__PURE__*/_interopDefault(j);var I=(e=>(e.IN="IN",e))(I||{}),T=(e=>(e.INR="INR",e))(T||{}),$=(t=>(t["en-IN"]="en-IN",t["ka-IN"]="ka-IN",t))($||{});var U={$id:"standards",definitions:{lowercaseText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]*$"},lowercaseText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,10}$"},lowercaseText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,16}$"},lowercaseText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,30}$"},lowercaseText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,50}$"},lowercaseText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,256}$"},text:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).*$"},text10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,10}$"},text16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,16}$"},text30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,30}$"},text50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,50}$"},text256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,256}$"},requiredText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).+$"},requiredText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,10}$"},requiredText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,16}$"},requiredText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,30}$"},requiredText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,50}$"},requiredText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,256}$"},url:{type:"string",pattern:"^https://[^\\s/$.?#].[^\\s]*$",maxLength:2048},uuid:{type:"string",minLength:1,pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"},productKey:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$"},variantId:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$"},firstName:{$ref:"#/definitions/requiredText30"},lastName:{$ref:"#/definitions/text30"},phone:{type:"string",pattern:"^[0-9]{10}$"},email:{type:"string",pattern:"^[^\\s]+@[^\\s]+\\.[^\\s]+$"},addressLine1:{$ref:"#/definitions/requiredText50"},addressLine2:{$ref:"#/definitions/text50"},city:{$ref:"#/definitions/requiredText30"},postalCode:{$ref:"#/definitions/requiredText16"},state:{type:"string",enum:["AP","AR","AS","BR","CT","GA","GJ","HR","HP","JH","KA","KL","MP","MH","MN","ML","MZ","NL","OR","PB","RJ","SK","TN","TG","TR","UP","UT","WB","AN","CH","DH","LD","DL","PY","LA","JK"]},country:{type:"string",enum:Object.values(I)},currency:{type:"string",enum:Object.values(T)},locale:{type:"string",enum:Object.values($)},addressType:{type:"string",enum:["shipping","billing","billing&shipping"]},address:{type:"object",properties:{firstName:{$ref:"standards#/definitions/firstName"},lastName:{$ref:"standards#/definitions/lastName"},phone:{$ref:"standards#/definitions/phone"},email:{$ref:"standards#/definitions/email"},addressLine1:{$ref:"standards#/definitions/addressLine1"},addressLine2:{$ref:"standards#/definitions/addressLine2"},city:{$ref:"standards#/definitions/city"},postalCode:{$ref:"standards#/definitions/postalCode"},state:{$ref:"standards#/definitions/state"},country:{$ref:"standards#/definitions/country"}},required:["firstName","lastName","phone","email","addressLine1","postalCode","state","country"]}}};var F={getStandardSchemaDefinition(){return U}},P=F;var m=new Uint8Array(256),x=m.length;function S(){return x>m.length-16&&(M__default.default.randomFillSync(m),x=0),m.slice(x,x+=16)}var L=/^(?:[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 K(t){return typeof t=="string"&&L.test(t)}var h=K;var o=[];for(let t=0;t<256;++t)o.push((t+256).toString(16).slice(1));function N(t,e=0){return o[t[e+0]]+o[t[e+1]]+o[t[e+2]]+o[t[e+3]]+"-"+o[t[e+4]]+o[t[e+5]]+"-"+o[t[e+6]]+o[t[e+7]]+"-"+o[t[e+8]]+o[t[e+9]]+"-"+o[t[e+10]]+o[t[e+11]]+o[t[e+12]]+o[t[e+13]]+o[t[e+14]]+o[t[e+15]]}function w(t){if(!h(t))throw TypeError("Invalid UUID");let e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}var D=w;function b(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var C="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Y="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function O(t,e,r){function i(a,d,u,y){var n;if(typeof a=="string"&&(a=b(a)),typeof d=="string"&&(d=D(d)),((n=d)===null||n===void 0?void 0:n.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let p=new Uint8Array(16+a.length);if(p.set(d),p.set(a,d.length),p=r(p),p[6]=p[6]&15|e,p[8]=p[8]&63|128,u){y=y||0;for(let f=0;f<16;++f)u[y+f]=p[f];return u}return N(p)}try{i.name=t;}catch{}return i.DNS=C,i.URL=Y,i}var _={randomUUID:M__default.default.randomUUID};function k(t,e,r){if(_.randomUUID&&!e&&!t)return _.randomUUID();t=t||{};let i=t.random||(t.rng||S)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){r=r||0;for(let a=0;a<16;++a)e[r+a]=i[a];return e}return N(i)}var A=k;function H(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),M__default.default.createHash("sha1").update(t).digest()}var v=H;var q=O("v5",80,v),R=q;var z={isUUID:t=>/^[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(t),isEmail:t=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t),isURL:t=>/^(http|https):\/\/[^ "]+$/.test(t),generateUUID:(t,e)=>e&&t?R(t,e):A(),generateSearchId:(t,e)=>`${t}#${e}`,getKeyfromSearchId:t=>{let[e,r]=t.split("#");return {key:e,variantId:r}}},W=z;var g=Object.freeze({INVALID_UUID:"Invalid UUID",INVALID_EMAIL:"Invalid Email",INVALID_TOKEN:"Invalid Token",TOKEN_EXPIRED:"Token Expired",INVALID_VERIFIER:"Invalid Verifier",INVALID_PERMISSIONS:"Invalid Permissions",INVALID_AUTH_TYPE:"Invalid Authorization Type",USER_PRIVATE_KEY_NOT_FOUND:"User Private Key Not Found",USER_PUBLIC_KEY_NOT_FOUND:"User Public Key Not Found",ANONYMOUS_PRIVATE_KEY_NOT_FOUND:"Anonymous Private Key Not Found",ANONYMOUS_PUBLIC_KEY_NOT_FOUND:"Anonymous Public Key Not Found",SYSTEM_PRIVATE_KEY_NOT_FOUND:"System Private Key Not Found",SYSTEM_PUBLIC_KEY_NOT_FOUND:"System Public Key Not Found",ADMIN_PRIVATE_KEY_NOT_FOUND:"Admin Private Key Not Found",ADMIN_PUBLIC_KEY_NOT_FOUND:"Admin Public Key Not Found",SECRET_TOKEN_NOT_FOUND:"Secret Token Not Found",ANONYMOUS_SESSION_NOT_ALLOWED:"Anonymous Session Not Allowed",USER_SESSION_NOT_ALLOWED:"User Session Not Allowed",SYSTEM_SESSION_NOT_ALLOWED:"System Session Not Allowed",CDN_SESSION_NOT_ALLOWED:"CDN Session Not Allowed",INTERNAL_SERVER_ERROR:"Internal Server Error",SOMETHING_WENT_WRONG:"Something went wrong",AUTH_CONTEXT_NOT_INITIALIZED:"Auth Context not Initialized"});var c={logException:(t,e)=>{console.error(`Exception Occurred in Function: ${t}, Error: ${c.inspect(e)}`);},logError:(t,e)=>{console.error(`Error Occurred in Function: ${t}, Error: ${c.inspect(e)}`);},logWarning:(t,e)=>{console.warn(`Warning in Function: ${t} - ${c.inspect(e)}`);},logMessage:(t,e)=>{console.log(`Message in Function: ${t} - ${c.inspect(e)}`);},logInvalidPayload:(t,e)=>{console.error(`Invalid Payload received for Function: ${t}, Error: ${c.inspect(e)}`);},inspect:t=>typeof t=="string"?t:j__default.default.inspect(t)},l=c;var J={handleException:(t,e,r)=>{e.knownError?(e.logError&&l.logError(t,e),r.status(e.status).json({status:e.status,error:e.error})):e.status&&e.error?(l.logException(t,e),r.status(e.status).json({error:e.errorMessage||JSON.stringify(e.error),status:e.status})):(l.logException(t,e),r.status(500).json({status:500,error:g.INTERNAL_SERVER_ERROR}));},generateResponse:(t,e,r)=>({status:t,data:e,error:r}),generateError:(t,e,r=!0,i=!1)=>({status:t,error:e,knownError:r,logError:i})},G=J;var Z=async(t,e,r="GET",i={},a)=>{let d={method:r,headers:{"Content-Type":"application/json",...i}};r!=="GET"&&a&&(d.body=JSON.stringify(a));let u=`${t}${e?"/"+e:""}`,y=u.includes("api.xetile.com")||u.includes("localhost");try{let n=await fetch(u,d);if(!n.ok){let f,E=await n.text();try{f=JSON.parse(E);}catch{f={status:n.status,error:E||n.statusText},l.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${u}. Raw text: ${E}`);}throw {status:n.status,statusText:n.statusText,error:f}}let p=await n.json();return l.logMessage("Fetch",`API call successful: URL-${u}, Status- ${n.status}`),{status:n.status,statusText:n.statusText,data:y?p.data:p}}catch(n){throw l.logError("Fetch",`API call failed: URL-${u}, Status- ${n.status||500}, Error- ${l.inspect(n.error||n)}`),{status:n.status||500,statusText:n.statusText||g.INTERNAL_SERVER_ERROR,error:n.error||{status:n.status||500,error:n.statusText||g.SOMETHING_WENT_WRONG}}}},X=Z;
2
+ exports.Fetch=X;exports.Logger=l;exports.ResponseUtility=G;exports.Schema=P;exports.Utils=W;//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map