b23-lib 1.8.9 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) 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/Common.d.mts +4 -3
  5. package/dist/Classes/Common.d.ts +4 -3
  6. package/dist/Classes/Coupon.js +1 -1
  7. package/dist/Classes/Coupon.js.map +1 -1
  8. package/dist/Classes/Coupon.mjs +1 -1
  9. package/dist/Classes/Enum.d.mts +8 -2
  10. package/dist/Classes/Enum.d.ts +8 -2
  11. package/dist/Classes/Enum.js +1 -1
  12. package/dist/Classes/Enum.js.map +1 -1
  13. package/dist/Classes/Enum.mjs +1 -1
  14. package/dist/Classes/LineItem.js +1 -1
  15. package/dist/Classes/LineItem.js.map +1 -1
  16. package/dist/Classes/LineItem.mjs +1 -1
  17. package/dist/Classes/Order.js +1 -1
  18. package/dist/Classes/Order.js.map +1 -1
  19. package/dist/Classes/Order.mjs +1 -1
  20. package/dist/Classes/Order.mjs.map +1 -1
  21. package/dist/Classes/Price.js +1 -1
  22. package/dist/Classes/Price.js.map +1 -1
  23. package/dist/Classes/Price.mjs +1 -1
  24. package/dist/Classes/Product.d.mts +2 -2
  25. package/dist/Classes/Product.d.ts +2 -2
  26. package/dist/Classes/Product.js +1 -1
  27. package/dist/Classes/Product.js.map +1 -1
  28. package/dist/Classes/Product.mjs +1 -1
  29. package/dist/Classes/Product.mjs.map +1 -1
  30. package/dist/Classes/ShoppingContainer.js +1 -1
  31. package/dist/Classes/ShoppingContainer.js.map +1 -1
  32. package/dist/Classes/ShoppingContainer.mjs +1 -1
  33. package/dist/chunk-5I5EKOWK.mjs +2 -0
  34. package/dist/chunk-5I5EKOWK.mjs.map +1 -0
  35. package/dist/chunk-6CM2HXBH.mjs +2 -0
  36. package/dist/chunk-6CM2HXBH.mjs.map +1 -0
  37. package/dist/chunk-JZTLV4NZ.mjs +2 -0
  38. package/dist/{chunk-MHMEOIHK.mjs.map → chunk-JZTLV4NZ.mjs.map} +1 -1
  39. package/dist/{chunk-MPZ4IPRM.mjs → chunk-KT46HMDM.mjs} +2 -2
  40. package/dist/{chunk-MPZ4IPRM.mjs.map → chunk-KT46HMDM.mjs.map} +1 -1
  41. package/dist/{chunk-2NO3E4TI.mjs → chunk-ONM27TEK.mjs} +2 -2
  42. package/dist/{chunk-2NO3E4TI.mjs.map → chunk-ONM27TEK.mjs.map} +1 -1
  43. package/dist/chunk-QZDXRDTG.mjs +2 -0
  44. package/dist/chunk-QZDXRDTG.mjs.map +1 -0
  45. package/package.json +1 -1
  46. package/dist/chunk-65X54TKF.mjs +0 -2
  47. package/dist/chunk-65X54TKF.mjs.map +0 -1
  48. package/dist/chunk-DM2BJMLJ.mjs +0 -2
  49. package/dist/chunk-DM2BJMLJ.mjs.map +0 -1
  50. package/dist/chunk-MHMEOIHK.mjs +0 -2
  51. package/dist/chunk-STQZVQ7K.mjs +0 -2
  52. package/dist/chunk-STQZVQ7K.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/Classes/Enum.ts","../../src/Classes/Price.ts"],"names":["CountryCurrencyMap","CurrencySymbolMap","PriceModel","_PriceModel","price","country","locale","options","displayAsInteger","currency","valueToFormat","fractionDigits","formattingOptions","error","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier"],"mappings":"aAkBO,IAAMA,CAAqB,CAAA,CAClB,EAAwB,CAAA,KACxC,CAEaC,CAAAA,CAAAA,CAAoB,CAC9B,GAAA,CAAiC,QACpC,CAAA,CCrBqBC,IAAAA,CAAAA,CAArB,MAAqBC,CAAW,CACpB,KAAA,CACA,OAQV,CAAA,WAAA,CAAYC,CAAeC,CAAAA,CAAAA,CAAsB,CAG/C,GAFA,IAAK,CAAA,OAAA,CAAUA,CAEZD,CAAAA,CAAAA,CAAQ,CACT,CAAA,MAAM,IAAI,KAAM,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AA,CAAAA,CAA8B,CAC/C,OAAOL,CAAmBK,CAAAA,CAAO,CACnC,CAEF","file":"Price.js","sourcesContent":["/**\r\n * Represents the countries where the application operates or products are available.\r\n */\r\nexport enum OperationalCountry {\r\n /** India */ IN = 'IN',\r\n}\r\n \r\nexport enum OperationalCountryCurrency {\r\n /** India */ INR = 'INR',\r\n}\r\n\r\nexport enum OperationalLocale {\r\n /** India */ 'en-IN' = 'en-IN',\r\n}\r\n\r\n/**\r\n * Defines the supported ISO 4217 currency codes as an enumeration.\r\n */\r\nexport const CountryCurrencyMap = {\r\n /** India */ [OperationalCountry.IN]: OperationalCountryCurrency.INR,\r\n};\r\n\r\nexport const CurrencySymbolMap = {\r\n [OperationalCountryCurrency.INR]: '₹',\r\n}\r\n\r\n/**\r\n * Defines standard gender categories for product targeting.\r\n */\r\nexport enum GenderCategory {\r\n MALE = 'Male',\r\n FEMALE = 'Female',\r\n UNISEX = 'Unisex',\r\n KIDS = 'Kids',\r\n BOY = 'Boy',\r\n GIRL = 'Girl',\r\n}","import { CountryCode, CurrencyCode, LocaleCode } from \"./Common\"; // Assuming these are in Common.ts\r\nimport { CountryCurrencyMap, CurrencySymbolMap } from \"./Enum\"; // Ensure these maps exist\r\n\r\nexport default class PriceModel {\r\n protected price: number;\r\n protected country: CountryCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param price - The initial price value.\r\n * @param country - The country code used for rounding and determining the currency symbol.\r\n * @throws {Error} If price is negative or country/currency mapping is missing.\r\n */\r\n constructor(price: number, country: CountryCode) {\r\n this.country = country;\r\n\r\n if(price < 0) {\r\n throw new Error(\"InvalidPrice: Price cannot be negative.\");\r\n }\r\n\r\n this.price = price\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this price instance.\r\n * The country code is used for determining currency and formatting rules.\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 rounded price value based on standard currency rules.\r\n * @returns The numeric price, rounded according to its currency's typical decimal places.\r\n */\r\n public getRoundedPrice(): number {\r\n return PriceModel.getRoundedPrice(this.price, this.country);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price stored in this instance.\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @param locale - The locale code (e.g., 'en-IN') to use for formatting rules.\r\n * @returns The formatted price string according to locale rules.\r\n * @throws {Error} If the currency mapping for the instance's country is not found (via the static method).\r\n */\r\n public getFormattedString(locale: LocaleCode){\r\n return PriceModel.getFormattedString(this.price, this.country, locale);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param price - The initial price value.\r\n * @param country - The country code used for rounding and determining the currency symbol.\r\n * @param locale - The locale code (e.g., 'en-IN') to use for formatting rules.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the price rounded to the nearest integer (no decimals). Defaults to false.\r\n * @param options.style - The style of formatting, either 'currency' or 'decimal'. Defaults to 'currency'.\r\n * @param options.currencyDisplay - The display format for the currency symbol. Options are 'symbol', 'narrowSymbol', 'code', or 'name'. Defaults to 'symbol'.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n static getFormattedString(price: number, country: CountryCode, locale?: LocaleCode, options: { displayAsInteger?: boolean, style?: 'currency' | 'decimal', currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name' } = {}): string {\r\n const displayAsInteger = options.displayAsInteger ?? false;\r\n const currency: CurrencyCode | undefined = CountryCurrencyMap[country];\r\n\r\n if (currency === undefined) {\r\n throw new Error('Currency mapping not found for CountryCode');\r\n }\r\n\r\n let valueToFormat = price;\r\n const fractionDigits = displayAsInteger ? 0 : PriceModel.getDecimalPlaces(currency);\r\n\r\n let formattingOptions: Intl.NumberFormatOptions = {\r\n style: options.style ?? 'currency',\r\n currency: currency,\r\n signDisplay: 'never',\r\n currencyDisplay: options.currencyDisplay,\r\n minimumFractionDigits: fractionDigits,\r\n maximumFractionDigits: fractionDigits,\r\n };\r\n\r\n if (displayAsInteger) {\r\n valueToFormat = Math.round(valueToFormat);\r\n }\r\n\r\n try {\r\n return new Intl.NumberFormat(locale, formattingOptions).format(valueToFormat);\r\n } catch (error) {\r\n console.error(`Error formatting price for country \"${country}\" and currency \"${currency}\":`, error);\r\n // Basic fallback without symbol if Intl fails completely\r\n return `${CurrencySymbolMap[currency] ?? currency} ${PriceModel.addThousandSeparators(valueToFormat.toFixed(fractionDigits))}`;\r\n }\r\n }\r\n\r\n /**\r\n * Helper method to determine standard decimal places for a currency.\r\n * @param currency - The currency code.\r\n * @returns The number of decimal places (0, 2, or 3 based on common rules).\r\n */\r\n private static getDecimalPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case 'INR':\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n /**\r\n * Adds basic thousand separators (commas) to a number string.\r\n * Does not handle different locale separators (e.g., periods, spaces).\r\n * @param numStr - The number string (potentially with decimals).\r\n * @returns The number string with commas added.\r\n */\r\n private static addThousandSeparators(numStr: string): string {\r\n const parts = numStr.split('.');\r\n const integerPart = parts[0];\r\n const decimalPart = parts.length > 1 ? '.' + parts[1] : '';\r\n\r\n const formattedInteger = integerPart.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\r\n return formattedInteger + decimalPart;\r\n }\r\n\r\n /**\r\n * Rounds a price value according to the standard decimal places\r\n * for the currency associated with the given country.\r\n *\r\n * @param price - The price value to round. Must be a non-negative number.\r\n * @param country - The country code to determine the currency and rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the country code is not found in the CountryCurrencyMap or price is negative.\r\n */\r\n static getRoundedPrice(price: number, country: CountryCode): number {\r\n if (price < 0) {\r\n throw new Error(\"Price cannot be negative for rounding.\");\r\n }\r\n\r\n const currency: CurrencyCode | undefined = CountryCurrencyMap[country];\r\n if (currency === undefined) {\r\n throw new Error(`Currency mapping not found for CountryCode: ${country}`);\r\n }\r\n\r\n const decimalPlaces = PriceModel.getDecimalPlaces(currency);\r\n const multiplier = Math.pow(10, decimalPlaces);\r\n const roundedValue = Math.round(price * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n\r\n /**\r\n * Static method to retrieve the currency code associated with a given country code.\r\n * Uses the `CountryCurrencyMap` to find the corresponding currency.\r\n *\r\n * @param country - The country code (e.g., 'IN') for which to find the currency.\r\n * @returns The currency code (e.g., 'INR') as a string, or undefined if the mapping doesn't exist.\r\n */\r\n static getCurrency(country: CountryCode): string {\r\n return CountryCurrencyMap[country];\r\n }\r\n\r\n}"]}
1
+ {"version":3,"sources":["../../src/Classes/Enum.ts","../../src/Classes/Price.ts"],"names":["CountryCurrencyMap","CurrencySymbolMap","PriceModel","_PriceModel","price","country","locale","options","displayAsInteger","currency","valueToFormat","fractionDigits","formattingOptions","error","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier"],"mappings":"aA6BO,IAAMA,CAAqB,CAAA,CAClB,EAAwB,CAAA,KACxC,CAEaC,CAAAA,CAAAA,CAAoB,CAC9B,GAAA,CAAiC,QACpC,CAAA,CChCqBC,IAAAA,CAAAA,CAArB,MAAqBC,CAAW,CACpB,KAAA,CACA,OAQV,CAAA,WAAA,CAAYC,CAAeC,CAAAA,CAAAA,CAAsB,CAG/C,GAFA,IAAK,CAAA,OAAA,CAAUA,CAEZD,CAAAA,CAAAA,CAAQ,CACT,CAAA,MAAM,IAAI,KAAM,CAAA,yCAAyC,CAG3D,CAAA,IAAA,CAAK,KAAQA,CAAAA,EACf,CAOO,UAAA,EAA0B,CAC/B,OAAO,IAAK,CAAA,OACd,CAMO,eAAA,EAA0B,CAC/B,OAAOD,EAAW,eAAgB,CAAA,IAAA,CAAK,KAAO,CAAA,IAAA,CAAK,OAAO,CAC5D,CASO,kBAAA,CAAmBG,CAAmB,CAAA,CAC3C,OAAOH,CAAAA,CAAW,kBAAmB,CAAA,IAAA,CAAK,KA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QA,CAAU,EAChB,IAAK,KAAA,CACL,QACE,OACJ,CAAA,CACF,CAQA,OAAe,sBAAsBK,CAAwB,CAAA,CAC3D,IAAMC,CAAAA,CAAQD,CAAO,CAAA,KAAA,CAAM,GAAG,CAAA,CACxBE,CAAcD,CAAAA,CAAAA,CAAM,CAAC,CAAA,CACrBE,CAAcF,CAAAA,CAAAA,CAAM,MAAS,CAAA,CAAA,CAAI,IAAMA,CAAM,CAAA,CAAC,CAAI,CAAA,EAAA,CAGxD,OADyBC,CAAAA,CAAY,OAAQ,CAAA,uBAAA,CAAyB,GAAG,CAAA,CAC/CC,CAC5B,CAWA,OAAO,eAAA,CAAgBb,CAAeC,CAAAA,CAAAA,CAA8B,CAClE,GAAID,CAAAA,CAAQ,CACV,CAAA,MAAM,IAAI,KAAA,CAAM,wCAAwC,CAAA,CAG1D,IAAMK,CAAAA,CAAqCT,CAAmBK,CAAAA,CAAO,CACrE,CAAA,GAAII,CAAa,GAAA,KAAA,CAAA,CACf,MAAM,IAAI,KAAA,CAAM,CAA+CJ,4CAAAA,EAAAA,CAAO,CAAE,CAAA,CAAA,CAG1E,IAAMa,CAAAA,CAAgBf,CAAW,CAAA,gBAAA,CAAiBM,CAAQ,CAAA,CACpDU,CAAa,CAAA,IAAA,CAAK,GAAI,CAAA,EAAA,CAAID,CAAa,CAG7C,CAAA,OAFqB,IAAK,CAAA,KAAA,CAAMd,CAAQe,CAAAA,CAAU,CAAIA,CAAAA,CAGxD,CASA,OAAO,WAAYd,CAAAA,CAAAA,CAA8B,CAC/C,OAAOL,CAAmBK,CAAAA,CAAO,CACnC,CAEF","file":"Price.js","sourcesContent":["/**\r\n * Represents the countries where the application operates or products are available.\r\n */\r\nexport enum OperationalCountry {\r\n /** India */ IN = 'IN',\r\n}\r\n \r\nexport enum OperationalCountryCurrency {\r\n /** India */ INR = 'INR',\r\n}\r\n\r\nexport enum OperationalLocale {\r\n /** India */ 'en-IN' = 'en-IN',\r\n /** India ( Kannada) */ 'ka-IN' = 'ka-IN'\r\n}\r\n\r\nexport enum OperationalLanguage {\r\n en = 'en',\r\n ka = 'ka'\r\n}\r\n\r\nexport const LocaleLanguageMap: Record<OperationalLocale, OperationalLanguage> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalLanguage.en,\r\n [OperationalLocale[\"ka-IN\"]]: OperationalLanguage.ka,\r\n}\r\n\r\n/**\r\n * Defines the supported ISO 4217 currency codes as an enumeration.\r\n */\r\nexport const CountryCurrencyMap = {\r\n /** India */ [OperationalCountry.IN]: OperationalCountryCurrency.INR,\r\n};\r\n\r\nexport const CurrencySymbolMap = {\r\n [OperationalCountryCurrency.INR]: '₹',\r\n}\r\n\r\n/**\r\n * Defines standard gender categories for product targeting.\r\n */\r\nexport enum GenderCategory {\r\n MALE = 'Male',\r\n FEMALE = 'Female',\r\n UNISEX = 'Unisex',\r\n KIDS = 'Kids',\r\n BOY = 'Boy',\r\n GIRL = 'Girl',\r\n}","import { CountryCode, CurrencyCode, LocaleCode } from \"./Common\"; // Assuming these are in Common.ts\r\nimport { CountryCurrencyMap, CurrencySymbolMap } from \"./Enum\"; // Ensure these maps exist\r\n\r\nexport default class PriceModel {\r\n protected price: number;\r\n protected country: CountryCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param price - The initial price value.\r\n * @param country - The country code used for rounding and determining the currency symbol.\r\n * @throws {Error} If price is negative or country/currency mapping is missing.\r\n */\r\n constructor(price: number, country: CountryCode) {\r\n this.country = country;\r\n\r\n if(price < 0) {\r\n throw new Error(\"InvalidPrice: Price cannot be negative.\");\r\n }\r\n\r\n this.price = price\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this price instance.\r\n * The country code is used for determining currency and formatting rules.\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 rounded price value based on standard currency rules.\r\n * @returns The numeric price, rounded according to its currency's typical decimal places.\r\n */\r\n public getRoundedPrice(): number {\r\n return PriceModel.getRoundedPrice(this.price, this.country);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price stored in this instance.\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @param locale - The locale code (e.g., 'en-IN') to use for formatting rules.\r\n * @returns The formatted price string according to locale rules.\r\n * @throws {Error} If the currency mapping for the instance's country is not found (via the static method).\r\n */\r\n public getFormattedString(locale: LocaleCode){\r\n return PriceModel.getFormattedString(this.price, this.country, locale);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param price - The initial price value.\r\n * @param country - The country code used for rounding and determining the currency symbol.\r\n * @param locale - The locale code (e.g., 'en-IN') to use for formatting rules.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the price rounded to the nearest integer (no decimals). Defaults to false.\r\n * @param options.style - The style of formatting, either 'currency' or 'decimal'. Defaults to 'currency'.\r\n * @param options.currencyDisplay - The display format for the currency symbol. Options are 'symbol', 'narrowSymbol', 'code', or 'name'. Defaults to 'symbol'.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n static getFormattedString(price: number, country: CountryCode, locale?: LocaleCode, options: { displayAsInteger?: boolean, style?: 'currency' | 'decimal', currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name' } = {}): string {\r\n const displayAsInteger = options.displayAsInteger ?? false;\r\n const currency: CurrencyCode | undefined = CountryCurrencyMap[country];\r\n\r\n if (currency === undefined) {\r\n throw new Error('Currency mapping not found for CountryCode');\r\n }\r\n\r\n let valueToFormat = price;\r\n const fractionDigits = displayAsInteger ? 0 : PriceModel.getDecimalPlaces(currency);\r\n\r\n let formattingOptions: Intl.NumberFormatOptions = {\r\n style: options.style ?? 'currency',\r\n currency: currency,\r\n signDisplay: 'never',\r\n currencyDisplay: options.currencyDisplay,\r\n minimumFractionDigits: fractionDigits,\r\n maximumFractionDigits: fractionDigits,\r\n };\r\n\r\n if (displayAsInteger) {\r\n valueToFormat = Math.round(valueToFormat);\r\n }\r\n\r\n try {\r\n return new Intl.NumberFormat(locale, formattingOptions).format(valueToFormat);\r\n } catch (error) {\r\n console.error(`Error formatting price for country \"${country}\" and currency \"${currency}\":`, error);\r\n // Basic fallback without symbol if Intl fails completely\r\n return `${CurrencySymbolMap[currency] ?? currency} ${PriceModel.addThousandSeparators(valueToFormat.toFixed(fractionDigits))}`;\r\n }\r\n }\r\n\r\n /**\r\n * Helper method to determine standard decimal places for a currency.\r\n * @param currency - The currency code.\r\n * @returns The number of decimal places (0, 2, or 3 based on common rules).\r\n */\r\n private static getDecimalPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case 'INR':\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n /**\r\n * Adds basic thousand separators (commas) to a number string.\r\n * Does not handle different locale separators (e.g., periods, spaces).\r\n * @param numStr - The number string (potentially with decimals).\r\n * @returns The number string with commas added.\r\n */\r\n private static addThousandSeparators(numStr: string): string {\r\n const parts = numStr.split('.');\r\n const integerPart = parts[0];\r\n const decimalPart = parts.length > 1 ? '.' + parts[1] : '';\r\n\r\n const formattedInteger = integerPart.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\r\n return formattedInteger + decimalPart;\r\n }\r\n\r\n /**\r\n * Rounds a price value according to the standard decimal places\r\n * for the currency associated with the given country.\r\n *\r\n * @param price - The price value to round. Must be a non-negative number.\r\n * @param country - The country code to determine the currency and rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the country code is not found in the CountryCurrencyMap or price is negative.\r\n */\r\n static getRoundedPrice(price: number, country: CountryCode): number {\r\n if (price < 0) {\r\n throw new Error(\"Price cannot be negative for rounding.\");\r\n }\r\n\r\n const currency: CurrencyCode | undefined = CountryCurrencyMap[country];\r\n if (currency === undefined) {\r\n throw new Error(`Currency mapping not found for CountryCode: ${country}`);\r\n }\r\n\r\n const decimalPlaces = PriceModel.getDecimalPlaces(currency);\r\n const multiplier = Math.pow(10, decimalPlaces);\r\n const roundedValue = Math.round(price * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n\r\n /**\r\n * Static method to retrieve the currency code associated with a given country code.\r\n * Uses the `CountryCurrencyMap` to find the corresponding currency.\r\n *\r\n * @param country - The country code (e.g., 'IN') for which to find the currency.\r\n * @returns The currency code (e.g., 'INR') as a string, or undefined if the mapping doesn't exist.\r\n */\r\n static getCurrency(country: CountryCode): string {\r\n return CountryCurrencyMap[country];\r\n }\r\n\r\n}"]}
@@ -1,2 +1,2 @@
1
- export{a as default}from'../chunk-MHMEOIHK.mjs';import'../chunk-65X54TKF.mjs';//# sourceMappingURL=Price.mjs.map
1
+ export{a as default}from'../chunk-JZTLV4NZ.mjs';import'../chunk-QZDXRDTG.mjs';//# sourceMappingURL=Price.mjs.map
2
2
  //# sourceMappingURL=Price.mjs.map
@@ -1,5 +1,5 @@
1
1
  import BaseModel, { BaseAttributes } from './Base.mjs';
2
- import { LocalizedString, BasePriceList, PriceTierList, Color, LocaleCode, CountryCode, BasePrice } from './Common.mjs';
2
+ import { LocalizedString, BasePriceList, PriceTierList, Color, LocaleCode, LanguageCode, CountryCode, BasePrice } from './Common.mjs';
3
3
  import { GenderCategory } from './Enum.mjs';
4
4
  import ImageInfoModel, { ImageInfoData } from './ImageInfo.mjs';
5
5
  import '../Auth/index.mjs';
@@ -41,7 +41,7 @@ type ProductSpecification = {
41
41
  type LocalizedProductSpecification = {
42
42
  en: ProductSpecification;
43
43
  } & {
44
- [locale in LocaleCode]?: ProductSpecification;
44
+ [locale in (LocaleCode | LanguageCode)]?: ProductSpecification;
45
45
  };
46
46
  declare class ProductModel extends BaseModel {
47
47
  protected id: string;
@@ -1,5 +1,5 @@
1
1
  import BaseModel, { BaseAttributes } from './Base.js';
2
- import { LocalizedString, BasePriceList, PriceTierList, Color, LocaleCode, CountryCode, BasePrice } from './Common.js';
2
+ import { LocalizedString, BasePriceList, PriceTierList, Color, LocaleCode, LanguageCode, CountryCode, BasePrice } from './Common.js';
3
3
  import { GenderCategory } from './Enum.js';
4
4
  import ImageInfoModel, { ImageInfoData } from './ImageInfo.js';
5
5
  import '../Auth/index.js';
@@ -41,7 +41,7 @@ type ProductSpecification = {
41
41
  type LocalizedProductSpecification = {
42
42
  en: ProductSpecification;
43
43
  } & {
44
- [locale in LocaleCode]?: ProductSpecification;
44
+ [locale in (LocaleCode | LanguageCode)]?: ProductSpecification;
45
45
  };
46
46
  declare class ProductModel extends BaseModel {
47
47
  protected id: string;
@@ -1,2 +1,2 @@
1
- 'use strict';var n=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){this.customFields={...e.customFields},this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,t,i,o){this.modifiedBy={id:e,authType:t,requestId:i,lambdaName:o};}getCustomField(e){return this.customFields[e]??null}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return {...this.customFields}}};var r=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw "ImageInfoModel cannot be created without an 'original' source URL."}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,t){if(t===void 0){if(e==="original")throw "Cannot remove the 'original' image source.";delete this.sources[e];}else this.sources[e]=t;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var a=class extends n{id;key;variantId;name;description;slug;brand;basePrices;priceTiers;attributes;primaryImage;additionalImages;isActive;targetGender;categories;specifications;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static variantIdRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;constructor(e,t=new Date){super(e,t),this.id=e.id,this.key=e.key,this.variantId=e.variantId,this.name=e.name,this.description=e.description,this.slug=e.slug,this.brand=e.brand,this.basePrices=e.basePrices.map(i=>({...i})),this.priceTiers=e.priceTiers?e.priceTiers.map(i=>({...i})):e.basePrices.map(i=>({...i})),this.attributes={...e.attributes,sizes:[...e.attributes.sizes]},this.primaryImage=new r(e.primaryImage),this.additionalImages=(e.additionalImages||[]).map(i=>new r(i)),this.isActive=e.isActive,this.targetGender=e.targetGender,this.categories=[...e.categories],this.specifications=JSON.parse(JSON.stringify({...e.specifications})),this.searchTags=e.searchTags?[...e.searchTags]:[];}getId(){return this.id}getKey(){return this.key}getVariantId(){return this.variantId}getName(e){return e?this.name[e]??this.name.en:{...this.name}}getDescription(e){return e?this.description[e]??this.description.en:{...this.description}}getSlug(e){return e?this.slug[e]??this.slug.en:{...this.slug}}getBrand(){return this.brand}getBasePrices(e){if(e){let t=this.basePrices.find(i=>i.country===e);return t?{...t}:null}return this.basePrices.map(t=>({...t}))}getPriceTiers(e){return (e?this.priceTiers.filter(i=>i.country===e):this.priceTiers).map(i=>({...i})).sort((i,o)=>i.minQuantity-o.minQuantity)}getAttributes(){return {...this.attributes,color:{...this.attributes.color},sizes:[...this.attributes.sizes]}}getPrimaryImage(){return this.primaryImage}getAdditionalImages(){return this.additionalImages}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return [...this.categories]}getSpecifications(e){return e?this.specifications[e]??this.specifications.en:JSON.parse(JSON.stringify(this.specifications))}getSearchTags(){return [...this.searchTags]}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),variantId:this.getVariantId(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),basePrices:this.getBasePrices(),priceTiers:this.getPriceTiers(),attributes:this.getAttributes(),primaryImage:this.getPrimaryImage().getDetails(),additionalImages:this.getAdditionalImages().map(t=>t.getDetails()),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}getMaxDiscountPercent(e){let t=this.basePrices.find(s=>s.country===e),i=this.priceTiers?.filter(s=>s.country===e).sort((s,g)=>s.unitPrice-g.unitPrice)[0]?.unitPrice;return !t||t.unitPrice<=0||i===void 0?0:Math.max(0,t.unitPrice-i)/t.unitPrice*100}getMinQuantity(e){let t=this.getPriceTiers(e);if(t.length===0)throw Error("No price tiers found for country");return t[0].minQuantity}};module.exports=a;//# sourceMappingURL=Product.js.map
1
+ 'use strict';var n=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){this.customFields={...e.customFields},this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,t,i,a){this.modifiedBy={id:e,authType:t,requestId:i,lambdaName:a};}getCustomField(e){return this.customFields[e]??null}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return {...this.customFields}}};var o={"en-IN":"en","ka-IN":"ka"};var r=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw "ImageInfoModel cannot be created without an 'original' source URL."}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,t){if(t===void 0){if(e==="original")throw "Cannot remove the 'original' image source.";delete this.sources[e];}else this.sources[e]=t;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var d=class extends n{id;key;variantId;name;description;slug;brand;basePrices;priceTiers;attributes;primaryImage;additionalImages;isActive;targetGender;categories;specifications;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static variantIdRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;constructor(e,t=new Date){super(e,t),this.id=e.id,this.key=e.key,this.variantId=e.variantId,this.name=e.name,this.description=e.description,this.slug=e.slug,this.brand=e.brand,this.basePrices=e.basePrices.map(i=>({...i})),this.priceTiers=e.priceTiers?e.priceTiers.map(i=>({...i})):e.basePrices.map(i=>({...i})),this.attributes={...e.attributes,sizes:[...e.attributes.sizes]},this.primaryImage=new r(e.primaryImage),this.additionalImages=(e.additionalImages||[]).map(i=>new r(i)),this.isActive=e.isActive,this.targetGender=e.targetGender,this.categories=[...e.categories],this.specifications=JSON.parse(JSON.stringify({...e.specifications})),this.searchTags=e.searchTags?[...e.searchTags]:[];}getId(){return this.id}getKey(){return this.key}getVariantId(){return this.variantId}getName(e){return e?this.name[e]??this.name[o[e]]??this.name.en:{...this.name}}getDescription(e){return e?this.description[e]??this.description[o[e]]??this.description.en:{...this.description}}getSlug(e){return e?this.slug[e]??this.slug[o[e]]??this.slug.en:{...this.slug}}getBrand(){return this.brand}getBasePrices(e){if(e){let t=this.basePrices.find(i=>i.country===e);return t?{...t}:null}return this.basePrices.map(t=>({...t}))}getPriceTiers(e){return (e?this.priceTiers.filter(i=>i.country===e):this.priceTiers).map(i=>({...i})).sort((i,a)=>i.minQuantity-a.minQuantity)}getAttributes(){return {...this.attributes,color:{...this.attributes.color},sizes:[...this.attributes.sizes]}}getPrimaryImage(){return this.primaryImage}getAdditionalImages(){return this.additionalImages}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return [...this.categories]}getSpecifications(e){return e?this.specifications[e]??this.specifications[o[e]]??this.specifications.en:JSON.parse(JSON.stringify(this.specifications))}getSearchTags(){return [...this.searchTags]}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),variantId:this.getVariantId(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),basePrices:this.getBasePrices(),priceTiers:this.getPriceTiers(),attributes:this.getAttributes(),primaryImage:this.getPrimaryImage().getDetails(),additionalImages:this.getAdditionalImages().map(t=>t.getDetails()),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}getMaxDiscountPercent(e){let t=this.basePrices.find(s=>s.country===e),i=this.priceTiers?.filter(s=>s.country===e).sort((s,u)=>s.unitPrice-u.unitPrice)[0]?.unitPrice;return !t||t.unitPrice<=0||i===void 0?0:Math.max(0,t.unitPrice-i)/t.unitPrice*100}getMinQuantity(e){let t=this.getPriceTiers(e);if(t.length===0)throw Error("No price tiers found for country");return t[0].minQuantity}};module.exports=d;//# sourceMappingURL=Product.js.map
2
2
  //# sourceMappingURL=Product.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/Classes/Base.ts","../../src/Classes/ImageInfo.ts","../../src/Classes/Product.ts"],"names":["BaseModel","data","date","id","authType","requestId","lambdaName","fieldName","value","ImageInfoModel","resolutionKey","altText","order","label","url","ProductModel","price","tier","image","locale","country","countryPrice","a","b","baseDetails","basePrice","lowestTierPrice","priceTiers"],"mappings":"aA4BA,IAAqBA,CAAAA,CAArB,KAA+B,CACnB,YACA,CAAA,OAAA,CACA,UACA,UACA,CAAA,UAAA,CAQV,WAAYC,CAAAA,CAAAA,CAAsBC,CAAa,CAAA,IAAI,KAAQ,CACzD,IAAA,CAAK,YAAe,CAAA,CAAE,GAAGD,CAAAA,CAAK,YAAa,CAC3C,CAAA,IAAA,CAAK,OAAUA,CAAAA,CAAAA,CAAK,OAAW,EAAA,CAAA,CAC/B,KAAK,SAAYA,CAAAA,CAAAA,CAAK,SAAa,EAAA,CAAC,KAAM,CAAA,IAAA,CAAK,MAAMA,CAAK,CAAA,SAAS,CAAC,CAAA,CAElE,IAAI,IAAA,CAAKA,EAAK,SAAS,CAAA,CAAE,WAAY,EAAA,CAErCC,CAAK,CAAA,WAAA,EACP,CAAA,IAAA,CAAK,UAAaD,CAAAA,CAAAA,CAAK,UAAc,EAAA,CAAC,KAAM,CAAA,IAAA,CAAK,MAAMA,CAAK,CAAA,UAAU,CAAC,CAAA,CACnE,IAAI,IAAA,CAAKA,EAAK,UAAU,CAAA,CAAE,WAAY,EAAA,CACtCC,CAAK,CAAA,WAAA,GAET,IAAK,CAAA,UAAA,CAAa,CAAE,GAAGD,CAAK,CAAA,UAAW,EACzC,CAMA,UAAuB,EAAA,CACrB,OAAO,CACL,YAAc,CAAA,IAAA,CAAK,oBACnB,CAAA,OAAA,CAAS,IAAK,CAAA,UAAA,EACd,CAAA,SAAA,CAAW,KAAK,YAAa,EAAA,CAC7B,UAAY,CAAA,IAAA,CAAK,aAAc,EAAA,CAC/B,WAAY,IAAK,CAAA,aAAA,EACnB,CACF,CAMA,UAAA,EAAqB,CACnB,OAAO,IAAK,CAAA,OACd,CAMA,YAAA,EAAuB,CACrB,OAAO,KAAK,SACd,CAM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AAoB,KACvD,CAAA,CAAA,CAAA,CAIM,IAAK,CAAA,GAAA,CAAI,CAAGD,CAAAA,CAAAA,CAAU,SAAYC,CAAAA,CAAe,EAG/CD,CAAU,CAAA,SAAA,CAAa,GAC5C,CAUA,cAAeL,CAAAA,CAAAA,CAA8B,CAC3C,IAAMO,CAAAA,CAAa,IAAK,CAAA,aAAA,CAAcP,CAAO,CAAA,CAE7C,GAAIO,CAAW,CAAA,MAAA,GAAW,CACxB,CAAA,MAAM,KAAM,CAAA,kCAAkC,CAEhD,CAAA,OAAOA,CAAW,CAAA,CAAC,CAAE,CAAA,WACvB,CAGF","file":"Product.js","sourcesContent":["import { AuthType } from \"../Auth\";\r\nimport { ISODateTime } from \"./Common\";\r\n\r\nexport interface CustomFields {\r\n [key: string]: any;\r\n}\r\n\r\nexport type ModifiedBy = {\r\n id?: string;\r\n authType?: string;\r\n requestId?: string;\r\n lambdaName?: string;\r\n}\r\n\r\nexport type BaseAttributes = {\r\n customFields?: CustomFields;\r\n version?: number;\r\n createdAt?: ISODateTime;\r\n modifiedAt?: ISODateTime;\r\n modifiedBy?: ModifiedBy;\r\n};\r\n\r\nexport type BaseData = Required<BaseAttributes>;\r\n\r\n/**\r\n * Provides common foundational properties and methods for other data models.\r\n * Handles tracking of custom fields, versioning, and timestamps.\r\n */\r\nexport default class BaseModel {\r\n protected customFields: CustomFields;\r\n protected version: number;\r\n protected createdAt: ISODateTime;\r\n protected modifiedAt: ISODateTime;\r\n protected modifiedBy: ModifiedBy;\r\n\r\n /**\r\n * Creates an instance of BaseModel.\r\n * Initializes common properties like timestamps, version, and custom fields.\r\n * @param data - Optional initial attributes for the base model.\r\n * @param date - Optional date object to use for default timestamps (defaults to current time).\r\n */\r\n constructor(data: BaseAttributes, date: Date = new Date()) {\r\n this.customFields = { ...data.customFields };\r\n this.version = data.version ?? 1;\r\n this.createdAt = data.createdAt && !isNaN(Date.parse(data.createdAt))\r\n ?\r\n new Date(data.createdAt).toISOString()\r\n :\r\n date.toISOString();\r\n this.modifiedAt = data.modifiedAt && !isNaN(Date.parse(data.modifiedAt))\r\n ? new Date(data.modifiedAt).toISOString()\r\n : date.toISOString();\r\n\r\n this.modifiedBy = { ...data.modifiedBy };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the base model's current state.\r\n * @returns BaseData object containing common properties.\r\n */\r\n getDetails(): BaseData {\r\n return {\r\n customFields: this.getAllCustomFields(), // Use getter to return a copy\r\n version: this.getVersion(),\r\n createdAt: this.getCreatedAt(),\r\n modifiedAt: this.getModifiedAt(),\r\n modifiedBy: this.getModifiedBy(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the current version number of the model instance.\r\n * @returns The version number.\r\n */\r\n getVersion(): number {\r\n return this.version;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as an ISO 8601 string.\r\n * @returns The creation timestamp string.\r\n */\r\n getCreatedAt(): string {\r\n return this.createdAt;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as a Unix epoch time (milliseconds).\r\n * @returns The creation time in milliseconds since the epoch.\r\n */\r\n getCreatedAtTime(): number {\r\n return new Date(this.createdAt).getTime();\r\n }\r\n\r\n\r\n /**\r\n * Gets the last modification timestamp as an ISO 8601 string.\r\n * @returns The last modification timestamp string.\r\n */\r\n getModifiedAt(): string {\r\n return this.modifiedAt;\r\n }\r\n\r\n /**\r\n * Gets the last modification timestamp as a Unix epoch time (milliseconds).\r\n * @returns The last modification time in milliseconds since the epoch.\r\n */\r\n getModifiedAtTime(): number {\r\n return new Date(this.modifiedAt).getTime();\r\n }\r\n\r\n /**\r\n * Gets the identifier of the user or process that last modified the instance.\r\n * @returns\r\n */\r\n getModifiedBy(): ModifiedBy {\r\n return { ...this.modifiedBy };\r\n }\r\n\r\n /**\r\n * Sets the identifier of the user or process that last modified the instance.\r\n * @param modifiedBy - The identifier string.\r\n */\r\n setModifiedBy(id?: string, authType?: AuthType, requestId?: string, lambdaName?: string): void {\r\n this.modifiedBy = {\r\n id,\r\n authType,\r\n requestId,\r\n lambdaName,\r\n };\r\n }\r\n\r\n /**\r\n * Retrieves the value of a specific custom field.\r\n * @param fieldName - The name (key) of the custom field to retrieve.\r\n * @returns The value of the custom field, or null if the field does not exist.\r\n */\r\n getCustomField(fieldName: string): any {\r\n return this.customFields[fieldName] ?? null;\r\n }\r\n\r\n /**\r\n * Sets the value of a specific custom field.\r\n * Also updates the modification timestamp and increments the version.\r\n * @param fieldName - The name (key) of the custom field to set.\r\n * @param value - The value to assign to the custom field.\r\n */\r\n setCustomField(fieldName: string, value: any): void {\r\n this.customFields[fieldName] = value;\r\n }\r\n\r\n /**\r\n * Retrieves a shallow copy of all custom fields associated with the instance.\r\n * @returns An object containing all custom fields.\r\n */\r\n getAllCustomFields(): CustomFields {\r\n return { ...this.customFields };\r\n }\r\n}\r\n","export enum ImageResolution {\r\n THUMBNAIL = 'thumbnail',\r\n SMALL = 'small',\r\n MEDIUM = 'medium',\r\n LARGE = 'large',\r\n ORIGINAL = 'original',\r\n}\r\n\r\nexport type ImageInfoAttribute = {\r\n sources: { [key in ImageResolution]?: string } & { original: string };\r\n alt?: string;\r\n order?: number;\r\n label?: string;\r\n};\r\n\r\nexport type ImageInfoData = ImageInfoAttribute;\r\n\r\n/**\r\n * Represents and manages structured image data, including multiple resolutions.\r\n */\r\nexport default class ImageInfoModel {\r\n protected sources: { [key in ImageResolution]?: string } & { original: string };\r\n protected alt?: string;\r\n protected order?: number;\r\n protected label?: string;\r\n\r\n /**\r\n * Creates an instance of ImageInfoModel.\r\n * @param data - The initial image data.\r\n */\r\n constructor(data: ImageInfoAttribute) {\r\n this.sources = { ...data.sources };\r\n this.alt = data.alt;\r\n this.order = data.order;\r\n this.label = data.label;\r\n\r\n if (!this.sources.original) {\r\n throw (\"ImageInfoModel cannot be created without an 'original' source URL.\");\r\n }\r\n }\r\n\r\n /**\r\n * Gets the sources object containing URLs for different resolutions.\r\n * Returns a copy to prevent external modification.\r\n */\r\n getSources() {\r\n return { ...this.sources };\r\n }\r\n\r\n /**\r\n * Gets the URL for a specific resolution key.\r\n * @param resolutionKey - The key of the desired resolution (e.g., 'thumbnail', 'medium').\r\n * @returns The URL string if the key doesn't exist, otherwise original image URL will be returned.\r\n */\r\n getSource(resolutionKey: ImageResolution): string{\r\n return this.sources[resolutionKey] || this.sources.original;\r\n }\r\n\r\n /**\r\n * Gets the alternative text for the image.\r\n */\r\n getAlt(): string | undefined {\r\n return this.alt;\r\n }\r\n\r\n /**\r\n * Gets the display order number for the image.\r\n */\r\n getOrder(): number | undefined {\r\n return this.order;\r\n }\r\n\r\n /**\r\n * Gets the display label or caption for the image.\r\n */\r\n getLabel(): string | undefined {\r\n return this.label;\r\n }\r\n\r\n /**\r\n * Sets the alternative text for the image.\r\n * @param altText - The new alt text.\r\n */\r\n setAlt(altText: string | undefined): void {\r\n this.alt = altText;\r\n // Potentially add logic here to trigger updates if needed\r\n }\r\n\r\n /**\r\n * Sets the display order for the image.\r\n * @param order - The new order number.\r\n */\r\n setOrder(order: number | undefined): void {\r\n this.order = order;\r\n }\r\n\r\n /**\r\n * Sets the display label for the image.\r\n * @param label - The new label text.\r\n */\r\n setLabel(label: string | undefined): void {\r\n this.label = label;\r\n }\r\n\r\n /**\r\n * Updates or adds a URL for a specific resolution.\r\n * @param resolutionKey - The key of the resolution to update/add.\r\n * @param url - The URL for the resolution. Set to undefined to remove.\r\n */\r\n setSource(resolutionKey: ImageResolution, url: string | undefined): void {\r\n if (url === undefined) {\r\n // Prevent deleting the 'original' key if it's required\r\n if (resolutionKey === 'original') {\r\n throw (\"Cannot remove the 'original' image source.\");\r\n return;\r\n }\r\n delete this.sources[resolutionKey];\r\n } else {\r\n this.sources[resolutionKey] = url;\r\n }\r\n }\r\n\r\n /**\r\n * Returns a plain JavaScript object representation of the image info.\r\n */\r\n getDetails(): ImageInfoData {\r\n return {\r\n sources: this.getSources(),\r\n alt: this.getAlt(),\r\n order: this.getOrder(),\r\n label: this.getLabel(),\r\n };\r\n }\r\n}","import BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { BasePriceList, PriceTierList, Color, LocalizedString, CountryCode, LocaleCode, BasePrice } from './Common';\r\nimport { GenderCategory } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\n\r\nexport type ProductVariantIdentifier = {\r\n key: string;\r\n variantId: string;\r\n};\r\n\r\nexport type ProductHashKey = {\r\n id: string;\r\n variantId: string;\r\n}\r\n\r\nexport type ProductAttributes = BaseAttributes & {\r\n id: string;\r\n key: string;\r\n variantId: string;\r\n\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n slug: LocalizedString;\r\n brand: string;\r\n\r\n basePrices: BasePriceList;\r\n priceTiers: PriceTierList;\r\n\r\n attributes: {\r\n color: Color;\r\n sizes: string[];\r\n };\r\n\r\n primaryImage: ImageInfoData;\r\n additionalImages?: ImageInfoData[];\r\n\r\n // Metadata & Categorization\r\n isActive: boolean;\r\n targetGender: GenderCategory;\r\n categories: string[];\r\n specifications: LocalizedProductSpecification;\r\n searchTags?: string[];\r\n};\r\n\r\nexport type ProductData = Required<ProductAttributes>\r\n\r\nexport type ProductSpecification = { [key: string]: string | string[] };\r\n\r\nexport type LocalizedProductSpecification = {\r\n en: ProductSpecification\r\n} & {\r\n [locale in LocaleCode]?: ProductSpecification\r\n}\r\n\r\nexport default class ProductModel extends BaseModel {\r\n protected id: string;\r\n protected key: string;\r\n protected variantId: string;\r\n\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected slug: LocalizedString;\r\n protected brand: string;\r\n\r\n protected basePrices: BasePriceList;\r\n protected priceTiers: PriceTierList;\r\n\r\n protected attributes: {\r\n color: Color;\r\n sizes: string[];\r\n };\r\n\r\n protected primaryImage: ImageInfoModel;\r\n protected additionalImages: ImageInfoModel[];\r\n\r\n protected isActive: boolean;\r\n protected targetGender: GenderCategory;\r\n protected categories: string[];\r\n protected specifications: LocalizedProductSpecification;\r\n protected searchTags: string[];\r\n\r\n static productKeyRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n static variantIdRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n\r\n /**\r\n * Creates an instance of ProductModel.\r\n * Initializes properties based on the provided data, creating copies where necessary.\r\n * @param data - The initial product attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: ProductAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.key = data.key;\r\n this.variantId = data.variantId;\r\n this.name = data.name;\r\n this.description = data.description;\r\n this.slug = data.slug;\r\n this.brand = data.brand;\r\n\r\n this.basePrices = data.basePrices.map(price => ({ ...price }));\r\n this.priceTiers = data.priceTiers ? \r\n data.priceTiers.map(tier => ({ ...tier })) \r\n : \r\n data.basePrices.map(price => ({ ...price }));;\r\n\r\n this.attributes = {\r\n ...data.attributes,\r\n sizes: [...data.attributes.sizes]\r\n };\r\n\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.additionalImages = (data.additionalImages || []).map(image => new ImageInfoModel(image));\r\n this.isActive = data.isActive;\r\n this.targetGender = data.targetGender;\r\n this.categories = [...data.categories];\r\n this.specifications = JSON.parse(JSON.stringify({ ...data.specifications }));\r\n this.searchTags = data.searchTags ? [...data.searchTags] : [];\r\n }\r\n\r\n /**\r\n * Gets the base Product ID.\r\n * @returns Product ID.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the user-friendly product key.\r\n * @returns Product Key.\r\n */\r\n getKey(): string {\r\n return this.key;\r\n }\r\n\r\n /**\r\n * Gets the specific Variant ID.\r\n * @returns Variant ID.\r\n */\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.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product description object.\r\n * @returns A copy of the LocalizedString object for the description.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the product 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.en;\r\n } else {\r\n return { ...this.description };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product slug object.\r\n * @returns A copy of the LocalizedString object for the slug.\r\n */\r\n getSlug(): LocalizedString\r\n /**\r\n * Gets the product slug for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The slug string for the specified locale.\r\n */\r\n getSlug(locale: LocaleCode): string\r\n getSlug(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.slug[locale] ?? this.slug.en;\r\n } else {\r\n return { ...this.slug };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the brand associated with the product.\r\n * @returns The brand name string.\r\n */\r\n getBrand(): string {\r\n return this.brand;\r\n }\r\n\r\n /**\r\n * Gets the base price(s) for the product variant.\r\n * If a country code is provided, it returns the specific base price defined for that country, or null if no price is defined for that country.\r\n * If no country code is provided, it returns a list of all defined base prices across different countries.\r\n * Returns copies of the price objects to prevent modification of internal state.\r\n *\r\n * @param country - Optional country code to retrieve the base price for a specific region.\r\n */\r\n getBasePrices(): BasePriceList\r\n getBasePrices(country: CountryCode): BasePrice | null\r\n getBasePrices(country?: CountryCode): BasePriceList | BasePrice | null {\r\n if(country) {\r\n const countryPrice = this.basePrices.find(price => price.country === country);\r\n return countryPrice ? { ...countryPrice } : null;\r\n }\r\n\r\n return this.basePrices.map(price => ({ ...price }));\r\n }\r\n\r\n /**\r\n * Gets the list of quantity-based price tiers for the product variant, sorted by minimum quantity in ascending order.\r\n * Returns copies of the price tier objects to prevent modification of internal state.\r\n * If a country code is provided, the list is filtered to include only tiers applicable to that country.\r\n *\r\n * @param country - Optional country code to filter the price tiers for a specific region.\r\n * @returns A sorted list (by `minQuantity`) of applicable `PriceTier` objects. Returns an empty list if no tiers are defined or if none match the specified country.\r\n */\r\n getPriceTiers(country?: CountryCode): PriceTierList {\r\n const filteredTiers = country ? this.priceTiers.filter(tier => tier.country === country) : this.priceTiers;\r\n return filteredTiers\r\n .map(tier => ({ ...tier }))\r\n .sort((a,b) => a.minQuantity - b.minQuantity);\r\n }\r\n\r\n /**\r\n * Gets the variant-specific attributes (color, sizes). Returns copies.\r\n * @returns Product Attributes.\r\n */\r\n getAttributes(): { color: Color; sizes: string[] } {\r\n return {\r\n ...this.attributes,\r\n color: { ...this.attributes.color },\r\n sizes: [...this.attributes.sizes]\r\n };\r\n }\r\n\r\n /**\r\n * Gets details of product's primary image.\r\n * @returns The ImageInfoModel instance for the primary image.\r\n */\r\n getPrimaryImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /**\r\n * Gets the list of additional product images.\r\n * @returns An array of ImageInfoModel instances.\r\n */\r\n getAdditionalImages(): ImageInfoModel[] {\r\n return this.additionalImages;\r\n }\r\n\r\n /**\r\n * Checks if the product variant is active.\r\n * @returns True if the product is active, false otherwise.\r\n */\r\n getIsActive(): boolean {\r\n return this.isActive;\r\n }\r\n\r\n /**\r\n * Gets the target gender category for the product.\r\n * @returns The GenderCategory enum value.\r\n */\r\n getTargetGender(): GenderCategory {\r\n return this.targetGender;\r\n }\r\n\r\n /**\r\n * Gets the list of categories the product belongs to. Returns a copy.\r\n * @returns An array of category.\r\n */\r\n getCategories(): string[] {\r\n return [...this.categories];\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.en;\r\n } else {\r\n return JSON.parse(JSON.stringify(this.specifications));\r\n }\r\n }\r\n\r\n /**\r\n * Gets the list of search tags. Returns a copy.\r\n * @returns An array of search tags.\r\n */\r\n getSearchTags(): string[] {\r\n return [...this.searchTags];\r\n }\r\n\r\n /**\r\n *\r\n * @returns ProductData\r\n */\r\n getDetails(): ProductData {\r\n const baseDetails = super.getDetails();\r\n return {\r\n id: this.getId(),\r\n key: this.getKey(),\r\n variantId: this.getVariantId(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n slug: this.getSlug(),\r\n brand: this.getBrand(),\r\n basePrices: this.getBasePrices(),\r\n priceTiers: this.getPriceTiers(),\r\n attributes: this.getAttributes(),\r\n primaryImage: this.getPrimaryImage().getDetails(),\r\n additionalImages: this.getAdditionalImages().map(image => image.getDetails()),\r\n isActive: this.getIsActive(),\r\n targetGender: this.getTargetGender(),\r\n categories: this.getCategories(),\r\n specifications: this.getSpecifications(),\r\n searchTags: this.getSearchTags(),\r\n ...baseDetails\r\n }; \r\n }\r\n\r\n /**\r\n * Calculates the maximum potential discount percentage for a given country\r\n * based on the lowest price tier compared to the base price.\r\n * @param country - The country code to calculate the discount for.\r\n * @returns The maximum discount percentage (0-100), or 0 if calculation is not possible.\r\n */\r\n getMaxDiscountPercent(country: CountryCode): number {\r\n // Find base price for the country (should be unique per country)\r\n const basePrice = this.basePrices.find(price => price.country === country);\r\n\r\n // Find the lowest unit price among tiers for the country\r\n const lowestTierPrice = this.priceTiers\r\n ?.filter(tier => tier.country === country) // Filter tiers for the country first\r\n .sort((a, b) => a.unitPrice - b.unitPrice)[0]?.unitPrice; // Then sort and get lowest\r\n\r\n // Validate prices before calculation\r\n if (!basePrice || basePrice.unitPrice <= 0 || lowestTierPrice === undefined) {\r\n return 0; // Cannot calculate discount\r\n }\r\n\r\n // Calculate discount, ensuring it's not negative\r\n const discount = Math.max(0, basePrice.unitPrice - lowestTierPrice);\r\n\r\n // Calculate percentage\r\n return (discount / basePrice.unitPrice) * 100;\r\n }\r\n\r\n /**\r\n * Gets the minimum quantity required to purchase this product variant in a specific country,\r\n * based on the lowest minimum quantity defined in its price tiers for that country.\r\n *\r\n * @param country - The country code for which to determine the minimum purchase quantity.\r\n * @returns The minimum quantity required.\r\n * @throws {Error} If no price tiers are defined for the specified country.\r\n */\r\n getMinQuantity(country: CountryCode): number {\r\n const priceTiers = this.getPriceTiers(country);\r\n\r\n if (priceTiers.length === 0) {\r\n throw Error('No price tiers found for country');\r\n }\r\n return priceTiers[0].minQuantity;\r\n }\r\n\r\n \r\n}"]}
1
+ {"version":3,"sources":["../../src/Classes/Base.ts","../../src/Classes/Enum.ts","../../src/Classes/ImageInfo.ts","../../src/Classes/Product.ts"],"names":["BaseModel","data","date","id","authType","requestId","lambdaName","fieldName","value","LocaleLanguageMap","ImageInfoModel","resolutionKey","altText","order","label","url","ProductModel","price","tier","image","locale","country","countryPrice","a","b","baseDetails","basePrice","lowestTierPrice","priceTiers"],"mappings":"aA4BA,IAAqBA,CAAAA,CAArB,KAA+B,CACnB,YACA,CAAA,OAAA,CACA,UACA,UACA,CAAA,UAAA,CAQV,WAAYC,CAAAA,CAAAA,CAAsBC,CAAa,CAAA,IAAI,KAAQ,CACzD,IAAA,CAAK,YAAe,CAAA,CAAE,GAAGD,CAAAA,CAAK,YAAa,CAAA,CAC3C,IAAK,CAAA,OAAA,CAAUA,CAAK,CAAA,OAAA,EAAW,CAC/B,CAAA,IAAA,CAAK,UAAYA,CAAK,CAAA,SAAA,EAAa,CAAC,KAAA,CAAM,IAAK,CAAA,KAAA,CAAMA,CAAK,CAAA,SA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AA,IAAA,CAAK,GAAI,CAAA,CAAA,CAAGD,CAAU,CAAA,SAAA,CAAYC,CAAe,CAG/CD,CAAAA,CAAAA,CAAU,SAAa,CAAA,GAC5C,CAUA,cAAA,CAAeL,CAA8B,CAAA,CAC3C,IAAMO,CAAAA,CAAa,IAAK,CAAA,aAAA,CAAcP,CAAO,CAAA,CAE7C,GAAIO,CAAW,CAAA,MAAA,GAAW,CACxB,CAAA,MAAM,KAAM,CAAA,kCAAkC,CAEhD,CAAA,OAAOA,CAAW,CAAA,CAAC,CAAE,CAAA,WACvB,CAGF","file":"Product.js","sourcesContent":["import { AuthType } from \"../Auth\";\r\nimport { ISODateTime } from \"./Common\";\r\n\r\nexport interface CustomFields {\r\n [key: string]: any;\r\n}\r\n\r\nexport type ModifiedBy = {\r\n id?: string;\r\n authType?: string;\r\n requestId?: string;\r\n lambdaName?: string;\r\n}\r\n\r\nexport type BaseAttributes = {\r\n customFields?: CustomFields;\r\n version?: number;\r\n createdAt?: ISODateTime;\r\n modifiedAt?: ISODateTime;\r\n modifiedBy?: ModifiedBy;\r\n};\r\n\r\nexport type BaseData = Required<BaseAttributes>;\r\n\r\n/**\r\n * Provides common foundational properties and methods for other data models.\r\n * Handles tracking of custom fields, versioning, and timestamps.\r\n */\r\nexport default class BaseModel {\r\n protected customFields: CustomFields;\r\n protected version: number;\r\n protected createdAt: ISODateTime;\r\n protected modifiedAt: ISODateTime;\r\n protected modifiedBy: ModifiedBy;\r\n\r\n /**\r\n * Creates an instance of BaseModel.\r\n * Initializes common properties like timestamps, version, and custom fields.\r\n * @param data - Optional initial attributes for the base model.\r\n * @param date - Optional date object to use for default timestamps (defaults to current time).\r\n */\r\n constructor(data: BaseAttributes, date: Date = new Date()) {\r\n this.customFields = { ...data.customFields };\r\n this.version = data.version ?? 1;\r\n this.createdAt = data.createdAt && !isNaN(Date.parse(data.createdAt))\r\n ?\r\n new Date(data.createdAt).toISOString()\r\n :\r\n date.toISOString();\r\n this.modifiedAt = data.modifiedAt && !isNaN(Date.parse(data.modifiedAt))\r\n ? new Date(data.modifiedAt).toISOString()\r\n : date.toISOString();\r\n\r\n this.modifiedBy = { ...data.modifiedBy };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the base model's current state.\r\n * @returns BaseData object containing common properties.\r\n */\r\n getDetails(): BaseData {\r\n return {\r\n customFields: this.getAllCustomFields(), // Use getter to return a copy\r\n version: this.getVersion(),\r\n createdAt: this.getCreatedAt(),\r\n modifiedAt: this.getModifiedAt(),\r\n modifiedBy: this.getModifiedBy(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the current version number of the model instance.\r\n * @returns The version number.\r\n */\r\n getVersion(): number {\r\n return this.version;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as an ISO 8601 string.\r\n * @returns The creation timestamp string.\r\n */\r\n getCreatedAt(): string {\r\n return this.createdAt;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as a Unix epoch time (milliseconds).\r\n * @returns The creation time in milliseconds since the epoch.\r\n */\r\n getCreatedAtTime(): number {\r\n return new Date(this.createdAt).getTime();\r\n }\r\n\r\n\r\n /**\r\n * Gets the last modification timestamp as an ISO 8601 string.\r\n * @returns The last modification timestamp string.\r\n */\r\n getModifiedAt(): string {\r\n return this.modifiedAt;\r\n }\r\n\r\n /**\r\n * Gets the last modification timestamp as a Unix epoch time (milliseconds).\r\n * @returns The last modification time in milliseconds since the epoch.\r\n */\r\n getModifiedAtTime(): number {\r\n return new Date(this.modifiedAt).getTime();\r\n }\r\n\r\n /**\r\n * Gets the identifier of the user or process that last modified the instance.\r\n * @returns\r\n */\r\n getModifiedBy(): ModifiedBy {\r\n return { ...this.modifiedBy };\r\n }\r\n\r\n /**\r\n * Sets the identifier of the user or process that last modified the instance.\r\n * @param modifiedBy - The identifier string.\r\n */\r\n setModifiedBy(id?: string, authType?: AuthType, requestId?: string, lambdaName?: string): void {\r\n this.modifiedBy = {\r\n id,\r\n authType,\r\n requestId,\r\n lambdaName,\r\n };\r\n }\r\n\r\n /**\r\n * Retrieves the value of a specific custom field.\r\n * @param fieldName - The name (key) of the custom field to retrieve.\r\n * @returns The value of the custom field, or null if the field does not exist.\r\n */\r\n getCustomField(fieldName: string): any {\r\n return this.customFields[fieldName] ?? null;\r\n }\r\n\r\n /**\r\n * Sets the value of a specific custom field.\r\n * Also updates the modification timestamp and increments the version.\r\n * @param fieldName - The name (key) of the custom field to set.\r\n * @param value - The value to assign to the custom field.\r\n */\r\n setCustomField(fieldName: string, value: any): void {\r\n this.customFields[fieldName] = value;\r\n }\r\n\r\n /**\r\n * Retrieves a shallow copy of all custom fields associated with the instance.\r\n * @returns An object containing all custom fields.\r\n */\r\n getAllCustomFields(): CustomFields {\r\n return { ...this.customFields };\r\n }\r\n}\r\n","/**\r\n * Represents the countries where the application operates or products are available.\r\n */\r\nexport enum OperationalCountry {\r\n /** India */ IN = 'IN',\r\n}\r\n \r\nexport enum OperationalCountryCurrency {\r\n /** India */ INR = 'INR',\r\n}\r\n\r\nexport enum OperationalLocale {\r\n /** India */ 'en-IN' = 'en-IN',\r\n /** India ( Kannada) */ 'ka-IN' = 'ka-IN'\r\n}\r\n\r\nexport enum OperationalLanguage {\r\n en = 'en',\r\n ka = 'ka'\r\n}\r\n\r\nexport const LocaleLanguageMap: Record<OperationalLocale, OperationalLanguage> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalLanguage.en,\r\n [OperationalLocale[\"ka-IN\"]]: OperationalLanguage.ka,\r\n}\r\n\r\n/**\r\n * Defines the supported ISO 4217 currency codes as an enumeration.\r\n */\r\nexport const CountryCurrencyMap = {\r\n /** India */ [OperationalCountry.IN]: OperationalCountryCurrency.INR,\r\n};\r\n\r\nexport const CurrencySymbolMap = {\r\n [OperationalCountryCurrency.INR]: '₹',\r\n}\r\n\r\n/**\r\n * Defines standard gender categories for product targeting.\r\n */\r\nexport enum GenderCategory {\r\n MALE = 'Male',\r\n FEMALE = 'Female',\r\n UNISEX = 'Unisex',\r\n KIDS = 'Kids',\r\n BOY = 'Boy',\r\n GIRL = 'Girl',\r\n}","export enum ImageResolution {\r\n THUMBNAIL = 'thumbnail',\r\n SMALL = 'small',\r\n MEDIUM = 'medium',\r\n LARGE = 'large',\r\n ORIGINAL = 'original',\r\n}\r\n\r\nexport type ImageInfoAttribute = {\r\n sources: { [key in ImageResolution]?: string } & { original: string };\r\n alt?: string;\r\n order?: number;\r\n label?: string;\r\n};\r\n\r\nexport type ImageInfoData = ImageInfoAttribute;\r\n\r\n/**\r\n * Represents and manages structured image data, including multiple resolutions.\r\n */\r\nexport default class ImageInfoModel {\r\n protected sources: { [key in ImageResolution]?: string } & { original: string };\r\n protected alt?: string;\r\n protected order?: number;\r\n protected label?: string;\r\n\r\n /**\r\n * Creates an instance of ImageInfoModel.\r\n * @param data - The initial image data.\r\n */\r\n constructor(data: ImageInfoAttribute) {\r\n this.sources = { ...data.sources };\r\n this.alt = data.alt;\r\n this.order = data.order;\r\n this.label = data.label;\r\n\r\n if (!this.sources.original) {\r\n throw (\"ImageInfoModel cannot be created without an 'original' source URL.\");\r\n }\r\n }\r\n\r\n /**\r\n * Gets the sources object containing URLs for different resolutions.\r\n * Returns a copy to prevent external modification.\r\n */\r\n getSources() {\r\n return { ...this.sources };\r\n }\r\n\r\n /**\r\n * Gets the URL for a specific resolution key.\r\n * @param resolutionKey - The key of the desired resolution (e.g., 'thumbnail', 'medium').\r\n * @returns The URL string if the key doesn't exist, otherwise original image URL will be returned.\r\n */\r\n getSource(resolutionKey: ImageResolution): string{\r\n return this.sources[resolutionKey] || this.sources.original;\r\n }\r\n\r\n /**\r\n * Gets the alternative text for the image.\r\n */\r\n getAlt(): string | undefined {\r\n return this.alt;\r\n }\r\n\r\n /**\r\n * Gets the display order number for the image.\r\n */\r\n getOrder(): number | undefined {\r\n return this.order;\r\n }\r\n\r\n /**\r\n * Gets the display label or caption for the image.\r\n */\r\n getLabel(): string | undefined {\r\n return this.label;\r\n }\r\n\r\n /**\r\n * Sets the alternative text for the image.\r\n * @param altText - The new alt text.\r\n */\r\n setAlt(altText: string | undefined): void {\r\n this.alt = altText;\r\n // Potentially add logic here to trigger updates if needed\r\n }\r\n\r\n /**\r\n * Sets the display order for the image.\r\n * @param order - The new order number.\r\n */\r\n setOrder(order: number | undefined): void {\r\n this.order = order;\r\n }\r\n\r\n /**\r\n * Sets the display label for the image.\r\n * @param label - The new label text.\r\n */\r\n setLabel(label: string | undefined): void {\r\n this.label = label;\r\n }\r\n\r\n /**\r\n * Updates or adds a URL for a specific resolution.\r\n * @param resolutionKey - The key of the resolution to update/add.\r\n * @param url - The URL for the resolution. Set to undefined to remove.\r\n */\r\n setSource(resolutionKey: ImageResolution, url: string | undefined): void {\r\n if (url === undefined) {\r\n // Prevent deleting the 'original' key if it's required\r\n if (resolutionKey === 'original') {\r\n throw (\"Cannot remove the 'original' image source.\");\r\n return;\r\n }\r\n delete this.sources[resolutionKey];\r\n } else {\r\n this.sources[resolutionKey] = url;\r\n }\r\n }\r\n\r\n /**\r\n * Returns a plain JavaScript object representation of the image info.\r\n */\r\n getDetails(): ImageInfoData {\r\n return {\r\n sources: this.getSources(),\r\n alt: this.getAlt(),\r\n order: this.getOrder(),\r\n label: this.getLabel(),\r\n };\r\n }\r\n}","import BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { BasePriceList, PriceTierList, Color, LocalizedString, CountryCode, LocaleCode, BasePrice, LanguageCode } from './Common';\r\nimport { GenderCategory, LocaleLanguageMap } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\n\r\nexport type ProductVariantIdentifier = {\r\n key: string;\r\n variantId: string;\r\n};\r\n\r\nexport type ProductHashKey = {\r\n id: string;\r\n variantId: string;\r\n}\r\n\r\nexport type ProductAttributes = BaseAttributes & {\r\n id: string;\r\n key: string;\r\n variantId: string;\r\n\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n slug: LocalizedString;\r\n brand: string;\r\n\r\n basePrices: BasePriceList;\r\n priceTiers: PriceTierList;\r\n\r\n attributes: {\r\n color: Color;\r\n sizes: string[];\r\n };\r\n\r\n primaryImage: ImageInfoData;\r\n additionalImages?: ImageInfoData[];\r\n\r\n // Metadata & Categorization\r\n isActive: boolean;\r\n targetGender: GenderCategory;\r\n categories: string[];\r\n specifications: LocalizedProductSpecification;\r\n searchTags?: string[];\r\n};\r\n\r\nexport type ProductData = Required<ProductAttributes>\r\n\r\nexport type ProductSpecification = { [key: string]: string | string[] };\r\n\r\nexport type LocalizedProductSpecification = {\r\n en: ProductSpecification\r\n} & {\r\n [locale in (LocaleCode | LanguageCode)]?: ProductSpecification\r\n}\r\n\r\nexport default class ProductModel extends BaseModel {\r\n protected id: string;\r\n protected key: string;\r\n protected variantId: string;\r\n\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected slug: LocalizedString;\r\n protected brand: string;\r\n\r\n protected basePrices: BasePriceList;\r\n protected priceTiers: PriceTierList;\r\n\r\n protected attributes: {\r\n color: Color;\r\n sizes: string[];\r\n };\r\n\r\n protected primaryImage: ImageInfoModel;\r\n protected additionalImages: ImageInfoModel[];\r\n\r\n protected isActive: boolean;\r\n protected targetGender: GenderCategory;\r\n protected categories: string[];\r\n protected specifications: LocalizedProductSpecification;\r\n protected searchTags: string[];\r\n\r\n static productKeyRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n static variantIdRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n\r\n /**\r\n * Creates an instance of ProductModel.\r\n * Initializes properties based on the provided data, creating copies where necessary.\r\n * @param data - The initial product attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: ProductAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.key = data.key;\r\n this.variantId = data.variantId;\r\n this.name = data.name;\r\n this.description = data.description;\r\n this.slug = data.slug;\r\n this.brand = data.brand;\r\n\r\n this.basePrices = data.basePrices.map(price => ({ ...price }));\r\n this.priceTiers = data.priceTiers ? \r\n data.priceTiers.map(tier => ({ ...tier })) \r\n : \r\n data.basePrices.map(price => ({ ...price }));;\r\n\r\n this.attributes = {\r\n ...data.attributes,\r\n sizes: [...data.attributes.sizes]\r\n };\r\n\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.additionalImages = (data.additionalImages || []).map(image => new ImageInfoModel(image));\r\n this.isActive = data.isActive;\r\n this.targetGender = data.targetGender;\r\n this.categories = [...data.categories];\r\n this.specifications = JSON.parse(JSON.stringify({ ...data.specifications }));\r\n this.searchTags = data.searchTags ? [...data.searchTags] : [];\r\n }\r\n\r\n /**\r\n * Gets the base Product ID.\r\n * @returns Product ID.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the user-friendly product key.\r\n * @returns Product Key.\r\n */\r\n getKey(): string {\r\n return this.key;\r\n }\r\n\r\n /**\r\n * Gets the specific Variant ID.\r\n * @returns Variant ID.\r\n */\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 full localized product description object.\r\n * @returns A copy of the LocalizedString object for the description.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the product 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 /**\r\n * Gets the full localized product slug object.\r\n * @returns A copy of the LocalizedString object for the slug.\r\n */\r\n getSlug(): LocalizedString\r\n /**\r\n * Gets the product slug for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The slug string for the specified locale.\r\n */\r\n getSlug(locale: LocaleCode): string\r\n getSlug(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.slug[locale] ?? this.slug[LocaleLanguageMap[locale]] ?? this.slug.en;\r\n } else {\r\n return { ...this.slug };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the brand associated with the product.\r\n * @returns The brand name string.\r\n */\r\n getBrand(): string {\r\n return this.brand;\r\n }\r\n\r\n /**\r\n * Gets the base price(s) for the product variant.\r\n * If a country code is provided, it returns the specific base price defined for that country, or null if no price is defined for that country.\r\n * If no country code is provided, it returns a list of all defined base prices across different countries.\r\n * Returns copies of the price objects to prevent modification of internal state.\r\n *\r\n * @param country - Optional country code to retrieve the base price for a specific region.\r\n */\r\n getBasePrices(): BasePriceList\r\n getBasePrices(country: CountryCode): BasePrice | null\r\n getBasePrices(country?: CountryCode): BasePriceList | BasePrice | null {\r\n if(country) {\r\n const countryPrice = this.basePrices.find(price => price.country === country);\r\n return countryPrice ? { ...countryPrice } : null;\r\n }\r\n\r\n return this.basePrices.map(price => ({ ...price }));\r\n }\r\n\r\n /**\r\n * Gets the list of quantity-based price tiers for the product variant, sorted by minimum quantity in ascending order.\r\n * Returns copies of the price tier objects to prevent modification of internal state.\r\n * If a country code is provided, the list is filtered to include only tiers applicable to that country.\r\n *\r\n * @param country - Optional country code to filter the price tiers for a specific region.\r\n * @returns A sorted list (by `minQuantity`) of applicable `PriceTier` objects. Returns an empty list if no tiers are defined or if none match the specified country.\r\n */\r\n getPriceTiers(country?: CountryCode): PriceTierList {\r\n const filteredTiers = country ? this.priceTiers.filter(tier => tier.country === country) : this.priceTiers;\r\n return filteredTiers\r\n .map(tier => ({ ...tier }))\r\n .sort((a,b) => a.minQuantity - b.minQuantity);\r\n }\r\n\r\n /**\r\n * Gets the variant-specific attributes (color, sizes). Returns copies.\r\n * @returns Product Attributes.\r\n */\r\n getAttributes(): { color: Color; sizes: string[] } {\r\n return {\r\n ...this.attributes,\r\n color: { ...this.attributes.color },\r\n sizes: [...this.attributes.sizes]\r\n };\r\n }\r\n\r\n /**\r\n * Gets details of product's primary image.\r\n * @returns The ImageInfoModel instance for the primary image.\r\n */\r\n getPrimaryImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /**\r\n * Gets the list of additional product images.\r\n * @returns An array of ImageInfoModel instances.\r\n */\r\n getAdditionalImages(): ImageInfoModel[] {\r\n return this.additionalImages;\r\n }\r\n\r\n /**\r\n * Checks if the product variant is active.\r\n * @returns True if the product is active, false otherwise.\r\n */\r\n getIsActive(): boolean {\r\n return this.isActive;\r\n }\r\n\r\n /**\r\n * Gets the target gender category for the product.\r\n * @returns The GenderCategory enum value.\r\n */\r\n getTargetGender(): GenderCategory {\r\n return this.targetGender;\r\n }\r\n\r\n /**\r\n * Gets the list of categories the product belongs to. Returns a copy.\r\n * @returns An array of category.\r\n */\r\n getCategories(): string[] {\r\n return [...this.categories];\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 /**\r\n * Gets the list of search tags. Returns a copy.\r\n * @returns An array of search tags.\r\n */\r\n getSearchTags(): string[] {\r\n return [...this.searchTags];\r\n }\r\n\r\n /**\r\n *\r\n * @returns ProductData\r\n */\r\n getDetails(): ProductData {\r\n const baseDetails = super.getDetails();\r\n return {\r\n id: this.getId(),\r\n key: this.getKey(),\r\n variantId: this.getVariantId(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n slug: this.getSlug(),\r\n brand: this.getBrand(),\r\n basePrices: this.getBasePrices(),\r\n priceTiers: this.getPriceTiers(),\r\n attributes: this.getAttributes(),\r\n primaryImage: this.getPrimaryImage().getDetails(),\r\n additionalImages: this.getAdditionalImages().map(image => image.getDetails()),\r\n isActive: this.getIsActive(),\r\n targetGender: this.getTargetGender(),\r\n categories: this.getCategories(),\r\n specifications: this.getSpecifications(),\r\n searchTags: this.getSearchTags(),\r\n ...baseDetails\r\n }; \r\n }\r\n\r\n /**\r\n * Calculates the maximum potential discount percentage for a given country\r\n * based on the lowest price tier compared to the base price.\r\n * @param country - The country code to calculate the discount for.\r\n * @returns The maximum discount percentage (0-100), or 0 if calculation is not possible.\r\n */\r\n getMaxDiscountPercent(country: CountryCode): number {\r\n // Find base price for the country (should be unique per country)\r\n const basePrice = this.basePrices.find(price => price.country === country);\r\n\r\n // Find the lowest unit price among tiers for the country\r\n const lowestTierPrice = this.priceTiers\r\n ?.filter(tier => tier.country === country) // Filter tiers for the country first\r\n .sort((a, b) => a.unitPrice - b.unitPrice)[0]?.unitPrice; // Then sort and get lowest\r\n\r\n // Validate prices before calculation\r\n if (!basePrice || basePrice.unitPrice <= 0 || lowestTierPrice === undefined) {\r\n return 0; // Cannot calculate discount\r\n }\r\n\r\n // Calculate discount, ensuring it's not negative\r\n const discount = Math.max(0, basePrice.unitPrice - lowestTierPrice);\r\n\r\n // Calculate percentage\r\n return (discount / basePrice.unitPrice) * 100;\r\n }\r\n\r\n /**\r\n * Gets the minimum quantity required to purchase this product variant in a specific country,\r\n * based on the lowest minimum quantity defined in its price tiers for that country.\r\n *\r\n * @param country - The country code for which to determine the minimum purchase quantity.\r\n * @returns The minimum quantity required.\r\n * @throws {Error} If no price tiers are defined for the specified country.\r\n */\r\n getMinQuantity(country: CountryCode): number {\r\n const priceTiers = this.getPriceTiers(country);\r\n\r\n if (priceTiers.length === 0) {\r\n throw Error('No price tiers found for country');\r\n }\r\n return priceTiers[0].minQuantity;\r\n }\r\n\r\n \r\n}"]}
@@ -1,2 +1,2 @@
1
- import {b}from'../chunk-DKI6BDWK.mjs';import {a}from'../chunk-ATUUYYQT.mjs';var n=class extends a{id;key;variantId;name;description;slug;brand;basePrices;priceTiers;attributes;primaryImage;additionalImages;isActive;targetGender;categories;specifications;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static variantIdRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;constructor(e,i=new Date){super(e,i),this.id=e.id,this.key=e.key,this.variantId=e.variantId,this.name=e.name,this.description=e.description,this.slug=e.slug,this.brand=e.brand,this.basePrices=e.basePrices.map(t=>({...t})),this.priceTiers=e.priceTiers?e.priceTiers.map(t=>({...t})):e.basePrices.map(t=>({...t})),this.attributes={...e.attributes,sizes:[...e.attributes.sizes]},this.primaryImage=new b(e.primaryImage),this.additionalImages=(e.additionalImages||[]).map(t=>new b(t)),this.isActive=e.isActive,this.targetGender=e.targetGender,this.categories=[...e.categories],this.specifications=JSON.parse(JSON.stringify({...e.specifications})),this.searchTags=e.searchTags?[...e.searchTags]:[];}getId(){return this.id}getKey(){return this.key}getVariantId(){return this.variantId}getName(e){return e?this.name[e]??this.name.en:{...this.name}}getDescription(e){return e?this.description[e]??this.description.en:{...this.description}}getSlug(e){return e?this.slug[e]??this.slug.en:{...this.slug}}getBrand(){return this.brand}getBasePrices(e){if(e){let i=this.basePrices.find(t=>t.country===e);return i?{...i}:null}return this.basePrices.map(i=>({...i}))}getPriceTiers(e){return (e?this.priceTiers.filter(t=>t.country===e):this.priceTiers).map(t=>({...t})).sort((t,c)=>t.minQuantity-c.minQuantity)}getAttributes(){return {...this.attributes,color:{...this.attributes.color},sizes:[...this.attributes.sizes]}}getPrimaryImage(){return this.primaryImage}getAdditionalImages(){return this.additionalImages}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return [...this.categories]}getSpecifications(e){return e?this.specifications[e]??this.specifications.en:JSON.parse(JSON.stringify(this.specifications))}getSearchTags(){return [...this.searchTags]}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),variantId:this.getVariantId(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),basePrices:this.getBasePrices(),priceTiers:this.getPriceTiers(),attributes:this.getAttributes(),primaryImage:this.getPrimaryImage().getDetails(),additionalImages:this.getAdditionalImages().map(i=>i.getDetails()),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}getMaxDiscountPercent(e){let i=this.basePrices.find(r=>r.country===e),t=this.priceTiers?.filter(r=>r.country===e).sort((r,a)=>r.unitPrice-a.unitPrice)[0]?.unitPrice;return !i||i.unitPrice<=0||t===void 0?0:Math.max(0,i.unitPrice-t)/i.unitPrice*100}getMinQuantity(e){let i=this.getPriceTiers(e);if(i.length===0)throw Error("No price tiers found for country");return i[0].minQuantity}};export{n as default};//# sourceMappingURL=Product.mjs.map
1
+ import {b}from'../chunk-DKI6BDWK.mjs';import {e}from'../chunk-QZDXRDTG.mjs';import {a as a$1}from'../chunk-ATUUYYQT.mjs';var a=class extends a$1{id;key;variantId;name;description;slug;brand;basePrices;priceTiers;attributes;primaryImage;additionalImages;isActive;targetGender;categories;specifications;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static variantIdRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;constructor(e,i=new Date){super(e,i),this.id=e.id,this.key=e.key,this.variantId=e.variantId,this.name=e.name,this.description=e.description,this.slug=e.slug,this.brand=e.brand,this.basePrices=e.basePrices.map(t=>({...t})),this.priceTiers=e.priceTiers?e.priceTiers.map(t=>({...t})):e.basePrices.map(t=>({...t})),this.attributes={...e.attributes,sizes:[...e.attributes.sizes]},this.primaryImage=new b(e.primaryImage),this.additionalImages=(e.additionalImages||[]).map(t=>new b(t)),this.isActive=e.isActive,this.targetGender=e.targetGender,this.categories=[...e.categories],this.specifications=JSON.parse(JSON.stringify({...e.specifications})),this.searchTags=e.searchTags?[...e.searchTags]:[];}getId(){return this.id}getKey(){return this.key}getVariantId(){return this.variantId}getName(e$1){return e$1?this.name[e$1]??this.name[e[e$1]]??this.name.en:{...this.name}}getDescription(e$1){return e$1?this.description[e$1]??this.description[e[e$1]]??this.description.en:{...this.description}}getSlug(e$1){return e$1?this.slug[e$1]??this.slug[e[e$1]]??this.slug.en:{...this.slug}}getBrand(){return this.brand}getBasePrices(e){if(e){let i=this.basePrices.find(t=>t.country===e);return i?{...i}:null}return this.basePrices.map(i=>({...i}))}getPriceTiers(e){return (e?this.priceTiers.filter(t=>t.country===e):this.priceTiers).map(t=>({...t})).sort((t,o)=>t.minQuantity-o.minQuantity)}getAttributes(){return {...this.attributes,color:{...this.attributes.color},sizes:[...this.attributes.sizes]}}getPrimaryImage(){return this.primaryImage}getAdditionalImages(){return this.additionalImages}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return [...this.categories]}getSpecifications(e$1){return e$1?this.specifications[e$1]??this.specifications[e[e$1]]??this.specifications.en:JSON.parse(JSON.stringify(this.specifications))}getSearchTags(){return [...this.searchTags]}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),variantId:this.getVariantId(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),basePrices:this.getBasePrices(),priceTiers:this.getPriceTiers(),attributes:this.getAttributes(),primaryImage:this.getPrimaryImage().getDetails(),additionalImages:this.getAdditionalImages().map(i=>i.getDetails()),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}getMaxDiscountPercent(e){let i=this.basePrices.find(r=>r.country===e),t=this.priceTiers?.filter(r=>r.country===e).sort((r,g)=>r.unitPrice-g.unitPrice)[0]?.unitPrice;return !i||i.unitPrice<=0||t===void 0?0:Math.max(0,i.unitPrice-t)/i.unitPrice*100}getMinQuantity(e){let i=this.getPriceTiers(e);if(i.length===0)throw Error("No price tiers found for country");return i[0].minQuantity}};export{a as default};//# sourceMappingURL=Product.mjs.map
2
2
  //# sourceMappingURL=Product.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/Classes/Product.ts"],"names":["ProductModel","BaseModel","data","date","price","tier","ImageInfoModel","image","locale","country","countryPrice","a","b","baseDetails","basePrice","lowestTierPrice","priceTiers"],"mappings":"4EAsDA,IAAqBA,CAArB,CAAA,cAA0CC,CAAU,CACtC,EACA,CAAA,GAAA,CACA,SAEA,CAAA,IAAA,CACA,WACA,CAAA,IAAA,CACA,KAEA,CAAA,UAAA,CACA,WAEA,UAKA,CAAA,YAAA,CACA,gBAEA,CAAA,QAAA,CACA,YACA,CAAA,UAAA,CACA,cACA,CAAA,UAAA,CAEV,OAAO,eAAkB,CAAA,kCAAA,CACzB,OAAO,cAAA,CAAiB,kCAQxB,CAAA,WAAA,CAAYC,CAAyBC,CAAAA,CAAAA,CAAa,IAAI,IAAQ,CAAA,CAC1D,KAAMD,CAAAA,CAAAA,CAAMC,CAAI,CAAA,CAChB,IAAK,CAAA,EAAA,CAAKD,EAAK,EACf,CAAA,IAAA,CAAK,GAAMA,CAAAA,CAAAA,CAAK,GAChB,CAAA,IAAA,CAAK,SAAYA,CAAAA,CAAAA,CAAK,UACtB,IAAK,CAAA,IAAA,CAAOA,CAAK,CAAA,IAAA,CACjB,IAAK,CAAA,WAAA,CAAcA,CAAK,CAAA,WAAA,CACxB,KAAK,IAAOA,CAAAA,CAAAA,CAAK,IACjB,CA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BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { BasePriceList, PriceTierList, Color, LocalizedString, CountryCode, LocaleCode, BasePrice } from './Common';\r\nimport { GenderCategory } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\n\r\nexport type ProductVariantIdentifier = {\r\n key: string;\r\n variantId: string;\r\n};\r\n\r\nexport type ProductHashKey = {\r\n id: string;\r\n variantId: string;\r\n}\r\n\r\nexport type ProductAttributes = BaseAttributes & {\r\n id: string;\r\n key: string;\r\n variantId: string;\r\n\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n slug: LocalizedString;\r\n brand: string;\r\n\r\n basePrices: BasePriceList;\r\n priceTiers: PriceTierList;\r\n\r\n attributes: {\r\n color: Color;\r\n sizes: string[];\r\n };\r\n\r\n primaryImage: ImageInfoData;\r\n additionalImages?: ImageInfoData[];\r\n\r\n // Metadata & Categorization\r\n isActive: boolean;\r\n targetGender: GenderCategory;\r\n categories: string[];\r\n specifications: LocalizedProductSpecification;\r\n searchTags?: string[];\r\n};\r\n\r\nexport type ProductData = Required<ProductAttributes>\r\n\r\nexport type ProductSpecification = { [key: string]: string | string[] };\r\n\r\nexport type LocalizedProductSpecification = {\r\n en: ProductSpecification\r\n} & {\r\n [locale in LocaleCode]?: ProductSpecification\r\n}\r\n\r\nexport default class ProductModel extends BaseModel {\r\n protected id: string;\r\n protected key: string;\r\n protected variantId: string;\r\n\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected slug: LocalizedString;\r\n protected brand: string;\r\n\r\n protected basePrices: BasePriceList;\r\n protected priceTiers: PriceTierList;\r\n\r\n protected attributes: {\r\n color: Color;\r\n sizes: string[];\r\n };\r\n\r\n protected primaryImage: ImageInfoModel;\r\n protected additionalImages: ImageInfoModel[];\r\n\r\n protected isActive: boolean;\r\n protected targetGender: GenderCategory;\r\n protected categories: string[];\r\n protected specifications: LocalizedProductSpecification;\r\n protected searchTags: string[];\r\n\r\n static productKeyRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n static variantIdRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n\r\n /**\r\n * Creates an instance of ProductModel.\r\n * Initializes properties based on the provided data, creating copies where necessary.\r\n * @param data - The initial product attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: ProductAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.key = data.key;\r\n this.variantId = data.variantId;\r\n this.name = data.name;\r\n this.description = data.description;\r\n this.slug = data.slug;\r\n this.brand = data.brand;\r\n\r\n this.basePrices = data.basePrices.map(price => ({ ...price }));\r\n this.priceTiers = data.priceTiers ? \r\n data.priceTiers.map(tier => ({ ...tier })) \r\n : \r\n data.basePrices.map(price => ({ ...price }));;\r\n\r\n this.attributes = {\r\n ...data.attributes,\r\n sizes: [...data.attributes.sizes]\r\n };\r\n\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.additionalImages = (data.additionalImages || []).map(image => new ImageInfoModel(image));\r\n this.isActive = data.isActive;\r\n this.targetGender = data.targetGender;\r\n this.categories = [...data.categories];\r\n this.specifications = JSON.parse(JSON.stringify({ ...data.specifications }));\r\n this.searchTags = data.searchTags ? [...data.searchTags] : [];\r\n }\r\n\r\n /**\r\n * Gets the base Product ID.\r\n * @returns Product ID.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the user-friendly product key.\r\n * @returns Product Key.\r\n */\r\n getKey(): string {\r\n return this.key;\r\n }\r\n\r\n /**\r\n * Gets the specific Variant ID.\r\n * @returns Variant ID.\r\n */\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.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product description object.\r\n * @returns A copy of the LocalizedString object for the description.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the product 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.en;\r\n } else {\r\n return { ...this.description };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product slug object.\r\n * @returns A copy of the LocalizedString object for the slug.\r\n */\r\n getSlug(): LocalizedString\r\n /**\r\n * Gets the product slug for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The slug string for the specified locale.\r\n */\r\n getSlug(locale: LocaleCode): string\r\n getSlug(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.slug[locale] ?? this.slug.en;\r\n } else {\r\n return { ...this.slug };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the brand associated with the product.\r\n * @returns The brand name string.\r\n */\r\n getBrand(): string {\r\n return this.brand;\r\n }\r\n\r\n /**\r\n * Gets the base price(s) for the product variant.\r\n * If a country code is provided, it returns the specific base price defined for that country, or null if no price is defined for that country.\r\n * If no country code is provided, it returns a list of all defined base prices across different countries.\r\n * Returns copies of the price objects to prevent modification of internal state.\r\n *\r\n * @param country - Optional country code to retrieve the base price for a specific region.\r\n */\r\n getBasePrices(): BasePriceList\r\n getBasePrices(country: CountryCode): BasePrice | null\r\n getBasePrices(country?: CountryCode): BasePriceList | BasePrice | null {\r\n if(country) {\r\n const countryPrice = this.basePrices.find(price => price.country === country);\r\n return countryPrice ? { ...countryPrice } : null;\r\n }\r\n\r\n return this.basePrices.map(price => ({ ...price }));\r\n }\r\n\r\n /**\r\n * Gets the list of quantity-based price tiers for the product variant, sorted by minimum quantity in ascending order.\r\n * Returns copies of the price tier objects to prevent modification of internal state.\r\n * If a country code is provided, the list is filtered to include only tiers applicable to that country.\r\n *\r\n * @param country - Optional country code to filter the price tiers for a specific region.\r\n * @returns A sorted list (by `minQuantity`) of applicable `PriceTier` objects. Returns an empty list if no tiers are defined or if none match the specified country.\r\n */\r\n getPriceTiers(country?: CountryCode): PriceTierList {\r\n const filteredTiers = country ? this.priceTiers.filter(tier => tier.country === country) : this.priceTiers;\r\n return filteredTiers\r\n .map(tier => ({ ...tier }))\r\n .sort((a,b) => a.minQuantity - b.minQuantity);\r\n }\r\n\r\n /**\r\n * Gets the variant-specific attributes (color, sizes). Returns copies.\r\n * @returns Product Attributes.\r\n */\r\n getAttributes(): { color: Color; sizes: string[] } {\r\n return {\r\n ...this.attributes,\r\n color: { ...this.attributes.color },\r\n sizes: [...this.attributes.sizes]\r\n };\r\n }\r\n\r\n /**\r\n * Gets details of product's primary image.\r\n * @returns The ImageInfoModel instance for the primary image.\r\n */\r\n getPrimaryImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /**\r\n * Gets the list of additional product images.\r\n * @returns An array of ImageInfoModel instances.\r\n */\r\n getAdditionalImages(): ImageInfoModel[] {\r\n return this.additionalImages;\r\n }\r\n\r\n /**\r\n * Checks if the product variant is active.\r\n * @returns True if the product is active, false otherwise.\r\n */\r\n getIsActive(): boolean {\r\n return this.isActive;\r\n }\r\n\r\n /**\r\n * Gets the target gender category for the product.\r\n * @returns The GenderCategory enum value.\r\n */\r\n getTargetGender(): GenderCategory {\r\n return this.targetGender;\r\n }\r\n\r\n /**\r\n * Gets the list of categories the product belongs to. Returns a copy.\r\n * @returns An array of category.\r\n */\r\n getCategories(): string[] {\r\n return [...this.categories];\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.en;\r\n } else {\r\n return JSON.parse(JSON.stringify(this.specifications));\r\n }\r\n }\r\n\r\n /**\r\n * Gets the list of search tags. Returns a copy.\r\n * @returns An array of search tags.\r\n */\r\n getSearchTags(): string[] {\r\n return [...this.searchTags];\r\n }\r\n\r\n /**\r\n *\r\n * @returns ProductData\r\n */\r\n getDetails(): ProductData {\r\n const baseDetails = super.getDetails();\r\n return {\r\n id: this.getId(),\r\n key: this.getKey(),\r\n variantId: this.getVariantId(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n slug: this.getSlug(),\r\n brand: this.getBrand(),\r\n basePrices: this.getBasePrices(),\r\n priceTiers: this.getPriceTiers(),\r\n attributes: this.getAttributes(),\r\n primaryImage: this.getPrimaryImage().getDetails(),\r\n additionalImages: this.getAdditionalImages().map(image => image.getDetails()),\r\n isActive: this.getIsActive(),\r\n targetGender: this.getTargetGender(),\r\n categories: this.getCategories(),\r\n specifications: this.getSpecifications(),\r\n searchTags: this.getSearchTags(),\r\n ...baseDetails\r\n }; \r\n }\r\n\r\n /**\r\n * Calculates the maximum potential discount percentage for a given country\r\n * based on the lowest price tier compared to the base price.\r\n * @param country - The country code to calculate the discount for.\r\n * @returns The maximum discount percentage (0-100), or 0 if calculation is not possible.\r\n */\r\n getMaxDiscountPercent(country: CountryCode): number {\r\n // Find base price for the country (should be unique per country)\r\n const basePrice = this.basePrices.find(price => price.country === country);\r\n\r\n // Find the lowest unit price among tiers for the country\r\n const lowestTierPrice = this.priceTiers\r\n ?.filter(tier => tier.country === country) // Filter tiers for the country first\r\n .sort((a, b) => a.unitPrice - b.unitPrice)[0]?.unitPrice; // Then sort and get lowest\r\n\r\n // Validate prices before calculation\r\n if (!basePrice || basePrice.unitPrice <= 0 || lowestTierPrice === undefined) {\r\n return 0; // Cannot calculate discount\r\n }\r\n\r\n // Calculate discount, ensuring it's not negative\r\n const discount = Math.max(0, basePrice.unitPrice - lowestTierPrice);\r\n\r\n // Calculate percentage\r\n return (discount / basePrice.unitPrice) * 100;\r\n }\r\n\r\n /**\r\n * Gets the minimum quantity required to purchase this product variant in a specific country,\r\n * based on the lowest minimum quantity defined in its price tiers for that country.\r\n *\r\n * @param country - The country code for which to determine the minimum purchase quantity.\r\n * @returns The minimum quantity required.\r\n * @throws {Error} If no price tiers are defined for the specified country.\r\n */\r\n getMinQuantity(country: CountryCode): number {\r\n const priceTiers = this.getPriceTiers(country);\r\n\r\n if (priceTiers.length === 0) {\r\n throw Error('No price tiers found for country');\r\n }\r\n return priceTiers[0].minQuantity;\r\n }\r\n\r\n \r\n}"]}
1
+ {"version":3,"sources":["../../src/Classes/Product.ts"],"names":["ProductModel","BaseModel","data","date","price","tier","ImageInfoModel","image","locale","LocaleLanguageMap","country","countryPrice","a","b","baseDetails","basePrice","lowestTierPrice","priceTiers"],"mappings":"yHAsDA,IAAqBA,CAArB,CAAA,cAA0CC,GAAU,CACtC,GACA,GACA,CAAA,SAAA,CAEA,IACA,CAAA,WAAA,CACA,IACA,CAAA,KAAA,CAEA,UACA,CAAA,UAAA,CAEA,WAKA,YACA,CAAA,gBAAA,CAEA,QACA,CAAA,YAAA,CACA,UACA,CAAA,cAAA,CACA,UAEV,CAAA,OAAO,gBAAkB,kCACzB,CAAA,OAAO,cAAiB,CAAA,kCAAA,CAQxB,YAAYC,CAAyBC,CAAAA,CAAAA,CAAa,IAAI,IAAA,CAAQ,CAC1D,KAAMD,CAAAA,CAAAA,CAAMC,CAAI,CAAA,CAChB,IAAK,CAAA,EAAA,CAAKD,CAAK,CAAA,EAAA,CACf,KAAK,GAAMA,CAAAA,CAAAA,CAA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,CAAA,IAAA,CAAK,GAAI,CAAA,CAAA,CAAGD,EAAU,SAAYC,CAAAA,CAAe,CAG/CD,CAAAA,CAAAA,CAAU,UAAa,GAC5C,CAUA,cAAeL,CAAAA,CAAAA,CAA8B,CAC3C,IAAMO,CAAAA,CAAa,IAAK,CAAA,aAAA,CAAcP,CAAO,CAAA,CAE7C,GAAIO,CAAAA,CAAW,SAAW,CACxB,CAAA,MAAM,KAAM,CAAA,kCAAkC,EAEhD,OAAOA,CAAAA,CAAW,CAAC,CAAA,CAAE,WACvB,CAGF","file":"Product.mjs","sourcesContent":["import BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { BasePriceList, PriceTierList, Color, LocalizedString, CountryCode, LocaleCode, BasePrice, LanguageCode } from './Common';\r\nimport { GenderCategory, LocaleLanguageMap } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\n\r\nexport type ProductVariantIdentifier = {\r\n key: string;\r\n variantId: string;\r\n};\r\n\r\nexport type ProductHashKey = {\r\n id: string;\r\n variantId: string;\r\n}\r\n\r\nexport type ProductAttributes = BaseAttributes & {\r\n id: string;\r\n key: string;\r\n variantId: string;\r\n\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n slug: LocalizedString;\r\n brand: string;\r\n\r\n basePrices: BasePriceList;\r\n priceTiers: PriceTierList;\r\n\r\n attributes: {\r\n color: Color;\r\n sizes: string[];\r\n };\r\n\r\n primaryImage: ImageInfoData;\r\n additionalImages?: ImageInfoData[];\r\n\r\n // Metadata & Categorization\r\n isActive: boolean;\r\n targetGender: GenderCategory;\r\n categories: string[];\r\n specifications: LocalizedProductSpecification;\r\n searchTags?: string[];\r\n};\r\n\r\nexport type ProductData = Required<ProductAttributes>\r\n\r\nexport type ProductSpecification = { [key: string]: string | string[] };\r\n\r\nexport type LocalizedProductSpecification = {\r\n en: ProductSpecification\r\n} & {\r\n [locale in (LocaleCode | LanguageCode)]?: ProductSpecification\r\n}\r\n\r\nexport default class ProductModel extends BaseModel {\r\n protected id: string;\r\n protected key: string;\r\n protected variantId: string;\r\n\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected slug: LocalizedString;\r\n protected brand: string;\r\n\r\n protected basePrices: BasePriceList;\r\n protected priceTiers: PriceTierList;\r\n\r\n protected attributes: {\r\n color: Color;\r\n sizes: string[];\r\n };\r\n\r\n protected primaryImage: ImageInfoModel;\r\n protected additionalImages: ImageInfoModel[];\r\n\r\n protected isActive: boolean;\r\n protected targetGender: GenderCategory;\r\n protected categories: string[];\r\n protected specifications: LocalizedProductSpecification;\r\n protected searchTags: string[];\r\n\r\n static productKeyRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n static variantIdRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n\r\n /**\r\n * Creates an instance of ProductModel.\r\n * Initializes properties based on the provided data, creating copies where necessary.\r\n * @param data - The initial product attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: ProductAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.key = data.key;\r\n this.variantId = data.variantId;\r\n this.name = data.name;\r\n this.description = data.description;\r\n this.slug = data.slug;\r\n this.brand = data.brand;\r\n\r\n this.basePrices = data.basePrices.map(price => ({ ...price }));\r\n this.priceTiers = data.priceTiers ? \r\n data.priceTiers.map(tier => ({ ...tier })) \r\n : \r\n data.basePrices.map(price => ({ ...price }));;\r\n\r\n this.attributes = {\r\n ...data.attributes,\r\n sizes: [...data.attributes.sizes]\r\n };\r\n\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.additionalImages = (data.additionalImages || []).map(image => new ImageInfoModel(image));\r\n this.isActive = data.isActive;\r\n this.targetGender = data.targetGender;\r\n this.categories = [...data.categories];\r\n this.specifications = JSON.parse(JSON.stringify({ ...data.specifications }));\r\n this.searchTags = data.searchTags ? [...data.searchTags] : [];\r\n }\r\n\r\n /**\r\n * Gets the base Product ID.\r\n * @returns Product ID.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the user-friendly product key.\r\n * @returns Product Key.\r\n */\r\n getKey(): string {\r\n return this.key;\r\n }\r\n\r\n /**\r\n * Gets the specific Variant ID.\r\n * @returns Variant ID.\r\n */\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 full localized product description object.\r\n * @returns A copy of the LocalizedString object for the description.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the product 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 /**\r\n * Gets the full localized product slug object.\r\n * @returns A copy of the LocalizedString object for the slug.\r\n */\r\n getSlug(): LocalizedString\r\n /**\r\n * Gets the product slug for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The slug string for the specified locale.\r\n */\r\n getSlug(locale: LocaleCode): string\r\n getSlug(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.slug[locale] ?? this.slug[LocaleLanguageMap[locale]] ?? this.slug.en;\r\n } else {\r\n return { ...this.slug };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the brand associated with the product.\r\n * @returns The brand name string.\r\n */\r\n getBrand(): string {\r\n return this.brand;\r\n }\r\n\r\n /**\r\n * Gets the base price(s) for the product variant.\r\n * If a country code is provided, it returns the specific base price defined for that country, or null if no price is defined for that country.\r\n * If no country code is provided, it returns a list of all defined base prices across different countries.\r\n * Returns copies of the price objects to prevent modification of internal state.\r\n *\r\n * @param country - Optional country code to retrieve the base price for a specific region.\r\n */\r\n getBasePrices(): BasePriceList\r\n getBasePrices(country: CountryCode): BasePrice | null\r\n getBasePrices(country?: CountryCode): BasePriceList | BasePrice | null {\r\n if(country) {\r\n const countryPrice = this.basePrices.find(price => price.country === country);\r\n return countryPrice ? { ...countryPrice } : null;\r\n }\r\n\r\n return this.basePrices.map(price => ({ ...price }));\r\n }\r\n\r\n /**\r\n * Gets the list of quantity-based price tiers for the product variant, sorted by minimum quantity in ascending order.\r\n * Returns copies of the price tier objects to prevent modification of internal state.\r\n * If a country code is provided, the list is filtered to include only tiers applicable to that country.\r\n *\r\n * @param country - Optional country code to filter the price tiers for a specific region.\r\n * @returns A sorted list (by `minQuantity`) of applicable `PriceTier` objects. Returns an empty list if no tiers are defined or if none match the specified country.\r\n */\r\n getPriceTiers(country?: CountryCode): PriceTierList {\r\n const filteredTiers = country ? this.priceTiers.filter(tier => tier.country === country) : this.priceTiers;\r\n return filteredTiers\r\n .map(tier => ({ ...tier }))\r\n .sort((a,b) => a.minQuantity - b.minQuantity);\r\n }\r\n\r\n /**\r\n * Gets the variant-specific attributes (color, sizes). Returns copies.\r\n * @returns Product Attributes.\r\n */\r\n getAttributes(): { color: Color; sizes: string[] } {\r\n return {\r\n ...this.attributes,\r\n color: { ...this.attributes.color },\r\n sizes: [...this.attributes.sizes]\r\n };\r\n }\r\n\r\n /**\r\n * Gets details of product's primary image.\r\n * @returns The ImageInfoModel instance for the primary image.\r\n */\r\n getPrimaryImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /**\r\n * Gets the list of additional product images.\r\n * @returns An array of ImageInfoModel instances.\r\n */\r\n getAdditionalImages(): ImageInfoModel[] {\r\n return this.additionalImages;\r\n }\r\n\r\n /**\r\n * Checks if the product variant is active.\r\n * @returns True if the product is active, false otherwise.\r\n */\r\n getIsActive(): boolean {\r\n return this.isActive;\r\n }\r\n\r\n /**\r\n * Gets the target gender category for the product.\r\n * @returns The GenderCategory enum value.\r\n */\r\n getTargetGender(): GenderCategory {\r\n return this.targetGender;\r\n }\r\n\r\n /**\r\n * Gets the list of categories the product belongs to. Returns a copy.\r\n * @returns An array of category.\r\n */\r\n getCategories(): string[] {\r\n return [...this.categories];\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 /**\r\n * Gets the list of search tags. Returns a copy.\r\n * @returns An array of search tags.\r\n */\r\n getSearchTags(): string[] {\r\n return [...this.searchTags];\r\n }\r\n\r\n /**\r\n *\r\n * @returns ProductData\r\n */\r\n getDetails(): ProductData {\r\n const baseDetails = super.getDetails();\r\n return {\r\n id: this.getId(),\r\n key: this.getKey(),\r\n variantId: this.getVariantId(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n slug: this.getSlug(),\r\n brand: this.getBrand(),\r\n basePrices: this.getBasePrices(),\r\n priceTiers: this.getPriceTiers(),\r\n attributes: this.getAttributes(),\r\n primaryImage: this.getPrimaryImage().getDetails(),\r\n additionalImages: this.getAdditionalImages().map(image => image.getDetails()),\r\n isActive: this.getIsActive(),\r\n targetGender: this.getTargetGender(),\r\n categories: this.getCategories(),\r\n specifications: this.getSpecifications(),\r\n searchTags: this.getSearchTags(),\r\n ...baseDetails\r\n }; \r\n }\r\n\r\n /**\r\n * Calculates the maximum potential discount percentage for a given country\r\n * based on the lowest price tier compared to the base price.\r\n * @param country - The country code to calculate the discount for.\r\n * @returns The maximum discount percentage (0-100), or 0 if calculation is not possible.\r\n */\r\n getMaxDiscountPercent(country: CountryCode): number {\r\n // Find base price for the country (should be unique per country)\r\n const basePrice = this.basePrices.find(price => price.country === country);\r\n\r\n // Find the lowest unit price among tiers for the country\r\n const lowestTierPrice = this.priceTiers\r\n ?.filter(tier => tier.country === country) // Filter tiers for the country first\r\n .sort((a, b) => a.unitPrice - b.unitPrice)[0]?.unitPrice; // Then sort and get lowest\r\n\r\n // Validate prices before calculation\r\n if (!basePrice || basePrice.unitPrice <= 0 || lowestTierPrice === undefined) {\r\n return 0; // Cannot calculate discount\r\n }\r\n\r\n // Calculate discount, ensuring it's not negative\r\n const discount = Math.max(0, basePrice.unitPrice - lowestTierPrice);\r\n\r\n // Calculate percentage\r\n return (discount / basePrice.unitPrice) * 100;\r\n }\r\n\r\n /**\r\n * Gets the minimum quantity required to purchase this product variant in a specific country,\r\n * based on the lowest minimum quantity defined in its price tiers for that country.\r\n *\r\n * @param country - The country code for which to determine the minimum purchase quantity.\r\n * @returns The minimum quantity required.\r\n * @throws {Error} If no price tiers are defined for the specified country.\r\n */\r\n getMinQuantity(country: CountryCode): number {\r\n const priceTiers = this.getPriceTiers(country);\r\n\r\n if (priceTiers.length === 0) {\r\n throw Error('No price tiers found for country');\r\n }\r\n return priceTiers[0].minQuantity;\r\n }\r\n\r\n \r\n}"]}
@@ -1,2 +1,2 @@
1
- 'use strict';var u=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){this.customFields={...t.customFields},this.version=t.version??1,this.createdAt=t.createdAt&&!isNaN(Date.parse(t.createdAt))?new Date(t.createdAt).toISOString():e.toISOString(),this.modifiedAt=t.modifiedAt&&!isNaN(Date.parse(t.modifiedAt))?new Date(t.modifiedAt).toISOString():e.toISOString(),this.modifiedBy={...t.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(t,e,i,r){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:r};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}};var c=class extends u{id;firstName;lastName;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(t,e=new Date){super(t,e),this.id=t.id,this.firstName=t.firstName,this.lastName=t.lastName||"",this.phone=t.phone,this.email=t.email,this.addressLine1=t.addressLine1,this.addressLine2=t.addressLine2||"",this.city=t.city,this.postalCode=t.postalCode,this.state=t.state,this.country=t.country,this.isBillingAddress=t.isBillingAddress,this.isShippingAddress=t.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(t){return t==="shipping"||t==="billing&shipping"}static checkIfBillingAddress(t){return t==="billing"||t==="billing&shipping"}};var p=class{sources;alt;order;label;constructor(t){if(this.sources={...t.sources},this.alt=t.alt,this.order=t.order,this.label=t.label,!this.sources.original)throw "ImageInfoModel cannot be created without an 'original' source URL."}getSources(){return {...this.sources}}getSource(t){return this.sources[t]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(t){this.alt=t;}setOrder(t){this.order=t;}setLabel(t){this.label=t;}setSource(t,e){if(e===void 0){if(t==="original")throw "Cannot remove the 'original' image source.";delete this.sources[t];}else this.sources[t]=e;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var g=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 p(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.en:{...this.name}}getAttributes(){return {...this.attributes}}getSpecifications(t){return t?this.specifications[t]??this.specifications.en:JSON.parse(JSON.stringify(this.specifications))}getImage(){return this.primaryImage}getSubItems(){return this.subItems.map(t=>({...t}))}getTotalQuantity(){return this.totalQuantity}getBasePrice(){return {...this.basePrice}}getPriceTotals(){return {...this.priceTotals}}getPriceTiers(){return this.priceTiers.map(t=>({...t}))}recalculateTotalQuantity(){this.totalQuantity=this.subItems.reduce((t,e)=>t+e.quantity,0);}recalculatePriceTotal(){let t=this.totalQuantity,e=this.basePrice.unitPrice,i=null;for(let r of this.priceTiers.sort((s,o)=>o.minQuantity-s.minQuantity))if(t>=r.minQuantity){i=r;break}i&&(e=i.unitPrice),this.priceTotals.mrpTotal=this.basePrice.unitPrice*t,this.priceTotals.subtotal=e*t;}getDetails(){return {id:this.getId(),productKey:this.getProductKey(),variantId:this.getVariantId(),name:this.getName(),attributes:this.getAttributes(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),totalQuantity:this.getTotalQuantity(),basePrice:this.getBasePrice(),priceTotals:this.getPriceTotals(),priceTiers:this.getPriceTiers()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(s=>s.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity),this.recalculateTotalQuantity(),this.recalculatePriceTotal();}clearLineItem(){this.id="",this.productKey="",this.variantId="",this.name={en:""},this.attributes={color:{name:"",hex:""}},this.primaryImage=new p({sources:{original:""}}),this.subItems=[],this.recalculateTotalQuantity(),this.recalculatePriceTotal();}};var y={IN:"INR"},C={INR:"\u20B9"};var n=class a{price;country;constructor(t,e){if(this.country=e,t<0)throw new Error("InvalidPrice: Price cannot be negative.");this.price=t;}getCountry(){return this.country}getRoundedPrice(){return a.getRoundedPrice(this.price,this.country)}getFormattedString(t){return a.getFormattedString(this.price,this.country,t)}static getFormattedString(t,e,i,r={}){let s=r.displayAsInteger??!1,o=y[e];if(o===void 0)throw new Error("Currency mapping not found for CountryCode");let l=t,m=s?0:a.getDecimalPlaces(o),b={style:r.style??"currency",currency:o,signDisplay:"never",currencyDisplay:r.currencyDisplay,minimumFractionDigits:m,maximumFractionDigits:m};s&&(l=Math.round(l));try{return new Intl.NumberFormat(i,b).format(l)}catch(f){return console.error(`Error formatting price for country "${e}" and currency "${o}":`,f),`${C[o]??o} ${a.addThousandSeparators(l.toFixed(m))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),i=e[0],r=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+r}static getRoundedPrice(t,e){if(t<0)throw new Error("Price cannot be negative for rounding.");let i=y[e];if(i===void 0)throw new Error(`Currency mapping not found for CountryCode: ${e}`);let r=a.getDecimalPlaces(i),s=Math.pow(10,r);return Math.round(t*s)/s}static getCurrency(t){return y[t]}};var h=class extends u{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(t,e=new Date){super(t,e),this.couponCode=t.couponCode,this.name={...t.name},this.description={...t.description},this.type=t.type,this.customerId=t.customerId,this.validFrom=t.validFrom&&Date.parse(t.validFrom)?new Date(t.validFrom).toISOString():e.toISOString(),this.validTo=t.validTo&&Date.parse(t.validTo)?new Date(t.validTo).toISOString():e.toISOString(),this.minCartValue=t.minCartValue.map(i=>({...i})),this.maxCartDiscount=t.maxCartDiscount.map(i=>({...i})),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.applicableTo=t.applicableTo,this.category=t.category;}getCode(){return this.couponCode}getName(t){return t?this.name[t]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(t){return t?this.minCartValue.find(e=>e.country===t):this.minCartValue}getMaxCartDiscount(t){return t?this.maxCartDiscount.find(e=>e.country===t):this.maxCartDiscount}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:this.getMinCartValue(),maxCartDiscount:this.getMaxCartDiscount(),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(t){return this.applicableTo==="all"||this.applicableTo==="ftb"&&t}};var I=class extends u{id;customerId;customerEmail;anonymousId;lineItems;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,e=new Date){super(t,e),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(i=>new g(i)),this.billingAddress=t.billingAddress?new c(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new c(t.shippingAddress,e):null,this.coupons=(t.coupons||[]).map(i=>new h(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=n.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=n.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 g(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new c(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new c(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons.map(t=>new h(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 r=t.getCategory(),s=t.getDiscountMethod(),o=0,l=r==="SHIPPING"?this.total.shipping:this.total.subtotal;if(l<=0)return 0;switch(s){case"flat":let b=i?.price??0;o=Math.min(l,b);break;case"percentage":o=l*(t.getPercentageValue()/100);break;default:return 0}let m=Math.min(o,i.price);return n.getRoundedPrice(Math.max(0,m),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);}),n.getRoundedPrice(t,this.country)}updateCartTotals(){this.total.subtotal=n.getRoundedPrice(this.lineItems.reduce((r,s)=>r+s.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=n.getRoundedPrice(this.lineItems.reduce((r,s)=>r+s.getPriceTotals().mrpTotal,0),this.country),this.recalculateCouponTotals();let t=this.coupons.filter(r=>r.getCategory()==="SHIPPING").reduce((r,s)=>r+(this.total.couponTotal[s.getCode()]??0),0);this.total.effectiveShipping=n.getRoundedPrice(Math.max(0,this.total.shipping-t),this.country);let e=this.coupons.filter(r=>r.getCategory()!=="SHIPPING").reduce((r,s)=>r+(this.total.couponTotal[s.getCode()]??0),0),i=this.total.subtotal+this.total.effectiveShipping;this.total.grandTotal=n.getRoundedPrice(Math.max(0,i-e),this.country);}setShippingDetails(t){this.shippingDetails=t?{...t}:null,this.total.shipping=n.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()}}};module.exports=I;//# sourceMappingURL=ShoppingContainer.js.map
1
+ 'use strict';var u=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){this.customFields={...t.customFields},this.version=t.version??1,this.createdAt=t.createdAt&&!isNaN(Date.parse(t.createdAt))?new Date(t.createdAt).toISOString():e.toISOString(),this.modifiedAt=t.modifiedAt&&!isNaN(Date.parse(t.modifiedAt))?new Date(t.modifiedAt).toISOString():e.toISOString(),this.modifiedBy={...t.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(t,e,i,r){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:r};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}};var l=class extends u{id;firstName;lastName;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(t,e=new Date){super(t,e),this.id=t.id,this.firstName=t.firstName,this.lastName=t.lastName||"",this.phone=t.phone,this.email=t.email,this.addressLine1=t.addressLine1,this.addressLine2=t.addressLine2||"",this.city=t.city,this.postalCode=t.postalCode,this.state=t.state,this.country=t.country,this.isBillingAddress=t.isBillingAddress,this.isShippingAddress=t.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(t){return t==="shipping"||t==="billing&shipping"}static checkIfBillingAddress(t){return t==="billing"||t==="billing&shipping"}};var p={"en-IN":"en","ka-IN":"ka"},b={IN:"INR"},f={INR:"\u20B9"};var g=class{sources;alt;order;label;constructor(t){if(this.sources={...t.sources},this.alt=t.alt,this.order=t.order,this.label=t.label,!this.sources.original)throw "ImageInfoModel cannot be created without an 'original' source URL."}getSources(){return {...this.sources}}getSource(t){return this.sources[t]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(t){this.alt=t;}setOrder(t){this.order=t;}setLabel(t){this.label=t;}setSource(t,e){if(e===void 0){if(t==="original")throw "Cannot remove the 'original' image source.";delete this.sources[t];}else this.sources[t]=e;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var h=class{id;productKey;variantId;name;attributes;specifications;primaryImage;subItems;totalQuantity;basePrice;priceTotals;priceTiers;constructor(t){this.id=t.id,this.productKey=t.productKey,this.variantId=t.variantId,this.name={...t.name},this.attributes={...t.attributes},this.specifications={...t.specifications},this.primaryImage=new g(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[p[t]]??this.name.en:{...this.name}}getAttributes(){return {...this.attributes}}getSpecifications(t){return t?this.specifications[t]??this.specifications[p[t]]??this.specifications.en:JSON.parse(JSON.stringify(this.specifications))}getImage(){return this.primaryImage}getSubItems(){return this.subItems.map(t=>({...t}))}getTotalQuantity(){return this.totalQuantity}getBasePrice(){return {...this.basePrice}}getPriceTotals(){return {...this.priceTotals}}getPriceTiers(){return this.priceTiers.map(t=>({...t}))}recalculateTotalQuantity(){this.totalQuantity=this.subItems.reduce((t,e)=>t+e.quantity,0);}recalculatePriceTotal(){let t=this.totalQuantity,e=this.basePrice.unitPrice,i=null;for(let r of this.priceTiers.sort((s,o)=>o.minQuantity-s.minQuantity))if(t>=r.minQuantity){i=r;break}i&&(e=i.unitPrice),this.priceTotals.mrpTotal=this.basePrice.unitPrice*t,this.priceTotals.subtotal=e*t;}getDetails(){return {id:this.getId(),productKey:this.getProductKey(),variantId:this.getVariantId(),name:this.getName(),attributes:this.getAttributes(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),totalQuantity:this.getTotalQuantity(),basePrice:this.getBasePrice(),priceTotals:this.getPriceTotals(),priceTiers:this.getPriceTiers()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(s=>s.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity),this.recalculateTotalQuantity(),this.recalculatePriceTotal();}clearLineItem(){this.id="",this.productKey="",this.variantId="",this.name={en:""},this.attributes={color:{name:"",hex:""}},this.primaryImage=new g({sources:{original:""}}),this.subItems=[],this.recalculateTotalQuantity(),this.recalculatePriceTotal();}};var n=class a{price;country;constructor(t,e){if(this.country=e,t<0)throw new Error("InvalidPrice: Price cannot be negative.");this.price=t;}getCountry(){return this.country}getRoundedPrice(){return a.getRoundedPrice(this.price,this.country)}getFormattedString(t){return a.getFormattedString(this.price,this.country,t)}static getFormattedString(t,e,i,r={}){let s=r.displayAsInteger??!1,o=b[e];if(o===void 0)throw new Error("Currency mapping not found for CountryCode");let c=t,y=s?0:a.getDecimalPlaces(o),I={style:r.style??"currency",currency:o,signDisplay:"never",currencyDisplay:r.currencyDisplay,minimumFractionDigits:y,maximumFractionDigits:y};s&&(c=Math.round(c));try{return new Intl.NumberFormat(i,I).format(c)}catch(A){return console.error(`Error formatting price for country "${e}" and currency "${o}":`,A),`${f[o]??o} ${a.addThousandSeparators(c.toFixed(y))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),i=e[0],r=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+r}static getRoundedPrice(t,e){if(t<0)throw new Error("Price cannot be negative for rounding.");let i=b[e];if(i===void 0)throw new Error(`Currency mapping not found for CountryCode: ${e}`);let r=a.getDecimalPlaces(i),s=Math.pow(10,r);return Math.round(t*s)/s}static getCurrency(t){return b[t]}};var m=class extends u{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(t,e=new Date){super(t,e),this.couponCode=t.couponCode,this.name={...t.name},this.description={...t.description},this.type=t.type,this.customerId=t.customerId,this.validFrom=t.validFrom&&Date.parse(t.validFrom)?new Date(t.validFrom).toISOString():e.toISOString(),this.validTo=t.validTo&&Date.parse(t.validTo)?new Date(t.validTo).toISOString():e.toISOString(),this.minCartValue=t.minCartValue.map(i=>({...i})),this.maxCartDiscount=t.maxCartDiscount.map(i=>({...i})),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.applicableTo=t.applicableTo,this.category=t.category;}getCode(){return this.couponCode}getName(t){return t?this.name[t]??this.name[p[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[p[t]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(t){return t?this.minCartValue.find(e=>e.country===t):this.minCartValue}getMaxCartDiscount(t){return t?this.maxCartDiscount.find(e=>e.country===t):this.maxCartDiscount}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:this.getMinCartValue(),maxCartDiscount:this.getMaxCartDiscount(),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(t){return this.applicableTo==="all"||this.applicableTo==="ftb"&&t}};var C=class extends u{id;customerId;customerEmail;anonymousId;lineItems;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,e=new Date){super(t,e),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(i=>new h(i)),this.billingAddress=t.billingAddress?new l(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new l(t.shippingAddress,e):null,this.coupons=(t.coupons||[]).map(i=>new m(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=n.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=n.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().mrpTotal,0),this.country);}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new h(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new l(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new l(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons.map(t=>new m(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 r=t.getCategory(),s=t.getDiscountMethod(),o=0,c=r==="SHIPPING"?this.total.shipping:this.total.subtotal;if(c<=0)return 0;switch(s){case"flat":let I=i?.price??0;o=Math.min(c,I);break;case"percentage":o=c*(t.getPercentageValue()/100);break;default:return 0}let y=Math.min(o,i.price);return n.getRoundedPrice(Math.max(0,y),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);}),n.getRoundedPrice(t,this.country)}updateCartTotals(){this.total.subtotal=n.getRoundedPrice(this.lineItems.reduce((r,s)=>r+s.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=n.getRoundedPrice(this.lineItems.reduce((r,s)=>r+s.getPriceTotals().mrpTotal,0),this.country),this.recalculateCouponTotals();let t=this.coupons.filter(r=>r.getCategory()==="SHIPPING").reduce((r,s)=>r+(this.total.couponTotal[s.getCode()]??0),0);this.total.effectiveShipping=n.getRoundedPrice(Math.max(0,this.total.shipping-t),this.country);let e=this.coupons.filter(r=>r.getCategory()!=="SHIPPING").reduce((r,s)=>r+(this.total.couponTotal[s.getCode()]??0),0),i=this.total.subtotal+this.total.effectiveShipping;this.total.grandTotal=n.getRoundedPrice(Math.max(0,i-e),this.country);}setShippingDetails(t){this.shippingDetails=t?{...t}:null,this.total.shipping=n.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()}}};module.exports=C;//# sourceMappingURL=ShoppingContainer.js.map
2
2
  //# sourceMappingURL=ShoppingContainer.js.map