b23-lib 3.2.0 → 3.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Auth/index.mjs +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Charge.mjs +1 -1
- package/dist/Classes/Coupon.mjs +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/Invoice.d.mts +29 -9
- package/dist/Classes/Invoice.d.ts +29 -9
- package/dist/Classes/Invoice.js +1 -1
- package/dist/Classes/Invoice.js.map +1 -1
- package/dist/Classes/Invoice.mjs +1 -1
- package/dist/Classes/Invoice.mjs.map +1 -1
- package/dist/Classes/LineItem.mjs +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/Product.mjs +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/{chunk-B2VFJRLS.mjs → chunk-5IRYC2KY.mjs} +2 -2
- package/dist/{chunk-B2VFJRLS.mjs.map → chunk-5IRYC2KY.mjs.map} +1 -1
- package/dist/{chunk-FR22CXZF.mjs → chunk-MJGCYQ53.mjs} +2 -2
- package/dist/{chunk-FR22CXZF.mjs.map → chunk-MJGCYQ53.mjs.map} +1 -1
- package/dist/{chunk-RQ2FFWUW.mjs → chunk-PWWKQNF7.mjs} +2 -2
- package/dist/{chunk-RQ2FFWUW.mjs.map → chunk-PWWKQNF7.mjs.map} +1 -1
- package/dist/{chunk-MHLRJ4IJ.mjs → chunk-QGIQ3MH6.mjs} +2 -2
- package/dist/{chunk-MHLRJ4IJ.mjs.map → chunk-QGIQ3MH6.mjs.map} +1 -1
- package/dist/{chunk-BSDPFVRK.mjs → chunk-XJPFHEW3.mjs} +2 -2
- package/dist/{chunk-BSDPFVRK.mjs.map → chunk-XJPFHEW3.mjs.map} +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/Coupon.ts"],"names":["CouponType","CouponDiscountMethod","CouponCategory","ApplicableTo","CouponModel","BaseModel","data","date","Utils_default","acc","country","priceData","PriceModel","InvalidArgumentError","locale","LocaleLanguageMap","priceModel","ftbCustomer","cartValue","shippingCost","currency","checkExpiry","zeroDiscount","potentialDiscount","minCartValueReq","maxCartDiscountCap","couponCategory","discountMethod","targetValue","flatAmount"],"mappings":"uMAOO,IAAKA,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,MAAS,CAAA,QAAA,CACTA,EAAA,SAAY,CAAA,WAAA,CAFFA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAKAC,OACVA,CAAA,CAAA,IAAA,CAAO,MACPA,CAAAA,CAAAA,CAAA,WAAa,YAFHA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAKAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,CAAA,CAAA,QAAA,CAAW,UACXA,CAAAA,CAAAA,CAAA,SAAW,UAFDA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAKAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,EAAA,GAAM,CAAA,KAAA,CACNA,CAAA,CAAA,GAAA,CAAM,MAFIA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CA0BSC,CAArB,CAAA,cAAyCC,GAAU,CACvC,UACA,CAAA,IAAA,CACA,YACA,IACA,CAAA,UAAA,CACA,SACA,CAAA,OAAA,CACA,aAGA,eAGA,CAAA,cAAA,CACA,eACA,CAAA,YAAA,CACA,SAOV,WAAYC,CAAAA,CAAAA,CAAuBC,CAAa,CAAA,IAAI,IAAQ,CAAA,CA0B1D,GAzBA,KAAA,CAAMD,EAAMC,CAAI,CAAA,CAEhB,IAAK,CAAA,UAAA,CAAaD,EAAK,UACvB,CAAA,IAAA,CAAK,IAAOE,CAAAA,CAAAA,CAAM,UAAUF,CAAK,CAAA,IAAI,CACr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AY,IAAIC,CAAU,CAAA,CAC9C,MACF,IAAK,aAEHN,CAAoBK,CAAAA,CAAAA,CAAY,QAAS,CAAA,IAAA,CAAK,oBAAuB,CAAA,GAAG,CAAE,CAAA,KAAA,GAC1E,MACF,QAEE,OAAON,CACX,CAKA,OAFsBC,CAAAA,CAAkB,GAAIE,CAAAA,CAAkB,CAGhE,CACF","file":"chunk-RQ2FFWUW.mjs","sourcesContent":["import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, CurrencyCode, ISODateTimeUTC, LocaleCode, LocalizedString, RegionalPrice } from \"./Common\";\r\nimport { LocaleLanguageMap } from \"./Enum\";\r\nimport { InvalidArgumentError } from \"./Error\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\n\r\nexport enum CouponType {\r\n COUPON = \"coupon\",\r\n AUTOMATIC = \"automatic\",\r\n}\r\n\r\nexport enum CouponDiscountMethod {\r\n FLAT = \"flat\",\r\n PERCENTAGE = \"percentage\",\r\n}\r\n\r\nexport enum CouponCategory {\r\n SHIPPING = \"SHIPPING\",\r\n CUSTOMER = \"CUSTOMER\",\r\n}\r\n\r\nexport enum ApplicableTo {\r\n ALL = \"all\",\r\n FTB = \"ftb\",\r\n}\r\n\r\nexport type CouponAttribute = BaseAttributes & {\r\n couponCode: string;\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n type: CouponType;\r\n customerId?: string;\r\n validFrom: ISODateTimeUTC;\r\n validTo: ISODateTimeUTC;\r\n minCartValue: RegionalPrice;\r\n maxCartDiscount: RegionalPrice;\r\n discountMethod: CouponDiscountMethod;\r\n percentageValue?: number;\r\n applicableTo: ApplicableTo;\r\n category: CouponCategory;\r\n};\r\n\r\nexport type CouponData = Required<CouponAttribute>\r\n\r\n/**\r\n * Represents a discount coupon, extending BaseModel.\r\n */\r\nexport default class CouponModel extends BaseModel {\r\n protected couponCode: string;\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected type: CouponType;\r\n protected customerId?: string;\r\n protected validFrom: ISODateTimeUTC;\r\n protected validTo: ISODateTimeUTC;\r\n protected minCartValue: {\r\n [country in CountryCode]?: PriceModel;\r\n };\r\n protected maxCartDiscount: {\r\n [country in CountryCode]?: PriceModel;\r\n };\r\n protected discountMethod: CouponDiscountMethod;\r\n protected percentageValue: number;\r\n protected applicableTo: ApplicableTo;\r\n protected category: CouponCategory;\r\n\r\n /**\r\n * Creates an instance of CouponModel.\r\n * @param data - The initial coupon attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: CouponAttribute, date: Date = new Date()) {\r\n super(data, date);\r\n\r\n this.couponCode = data.couponCode;\r\n this.name = Utils.deepClone(data.name);\r\n this.description = Utils.deepClone(data.description);\r\n this.type = data.type;\r\n this.customerId = data.customerId;\r\n this.validFrom = data.validFrom && Date.parse(data.validFrom) ? new Date(data.validFrom).toISOString() : date.toISOString();\r\n this.validTo = data.validTo && Date.parse(data.validTo) ? new Date(data.validTo).toISOString() : date.toISOString();\r\n this.minCartValue = (Object.keys(data.minCartValue) as CountryCode[]).reduce((acc, country) => {\r\n const priceData = data.minCartValue[country] as PriceData;\r\n if (priceData) {\r\n acc[country] = new PriceModel(priceData);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: PriceModel });\r\n this.maxCartDiscount = (Object.keys(data.maxCartDiscount) as CountryCode[]).reduce((acc, country) => {\r\n const priceData = data.maxCartDiscount[country] as PriceData;\r\n if (priceData) {\r\n acc[country] = new PriceModel(priceData);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: PriceModel });\r\n this.discountMethod = data.discountMethod;\r\n this.percentageValue = data.percentageValue ?? 0;\r\n if (this.percentageValue > 100) {\r\n throw new InvalidArgumentError('Percentage value cannot be greater than 100');\r\n }\r\n\r\n this.applicableTo = data.applicableTo;\r\n this.category = data.category;\r\n }\r\n\r\n /** Gets the unique coupon code. */\r\n getCode(): string {\r\n return this.couponCode;\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the coupon name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon description object.\r\n * @returns A copy of the LocalizedString object for the description, or undefined.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the coupon description for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The description string for the specified locale.\r\n */\r\n getDescription(locale: LocaleCode): string\r\n getDescription(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.description[locale] ?? this.description[LocaleLanguageMap[locale]] ?? this.description.en;\r\n } else {\r\n return { ...this.description };\r\n }\r\n }\r\n\r\n /** Gets the type of coupon (COUPON or AUTOMATIC). */\r\n getType(): CouponType {\r\n return this.type;\r\n }\r\n\r\n /** Gets the specific customer ID this coupon is limited to, if any. */\r\n getCustomerId(): string {\r\n return this.customerId ?? '';\r\n }\r\n\r\n /** Gets the ISO date string from when the coupon is valid. */\r\n getValidFrom(): ISODateTimeUTC {\r\n return this.validFrom;\r\n }\r\n\r\n /** Gets the ISO date string until when the coupon is valid. */\r\n getValidTo(): ISODateTimeUTC {\r\n return this.validTo;\r\n }\r\n\r\n /**\r\n * Gets the list of minimum cart values required for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional minimum cart values.\r\n */\r\n getMinCartValue(): { [country in CountryCode]?: PriceModel }\r\n\r\n /**\r\n * Gets the minimum cart value required for the coupon for a specific country.\r\n * @param country - The country code to filter the minimum value for.\r\n * @returns The regional minimum cart value for the specified country, or undefined if not set for that country.\r\n */\r\n getMinCartValue(country: CountryCode): PriceModel | undefined\r\n getMinCartValue(country?: CountryCode) {\n if (country) {\n return this.minCartValue[country];\n }\n return { ...this.minCartValue };\n }\n\r\n /**\r\n * Gets the list of maximum discount amounts allowed for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional maximum discount caps.\r\n */\r\n getMaxCartDiscount(): { [country in CountryCode]?: PriceModel }\r\n /**\r\n * Gets the maximum discount amount allowed for the coupon for a specific country.\r\n * @param country - The country code to filter the maximum discount for.\r\n * @returns The regional maximum discount cap for the specified country, or undefined if not set for that country.\r\n */\r\n getMaxCartDiscount(country: CountryCode): PriceModel | undefined\r\n getMaxCartDiscount(country?: CountryCode) {\n if (country) {\n return this.maxCartDiscount[country];\n }\n return { ...this.maxCartDiscount };\n }\n\r\n /** Gets the discount method (FLAT or PERCENTAGE). */\r\n getDiscountMethod(): CouponDiscountMethod {\r\n return this.discountMethod;\r\n }\r\n\r\n /** Gets the percentage discount value (0-100). */\r\n getPercentageValue(): number {\r\n return this.percentageValue;\r\n }\r\n\r\n /** Gets the customer applicability rule (ALL or FTB). */\r\n getApplicableTo(): ApplicableTo {\r\n return this.applicableTo;\r\n }\r\n\r\n /** Gets the category of the coupon (SHIPPING or CUSTOMER). */\r\n getCategory(): CouponCategory {\r\n return this.category;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the coupon's details.\r\n * @returns A CouponData object.\r\n */\r\n getDetails(): CouponData {\r\n return {\r\n ...super.getDetails(),\r\n couponCode: this.getCode(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n type: this.getType(),\r\n customerId: this.getCustomerId(),\r\n validFrom: this.getValidFrom(),\r\n validTo: this.getValidTo(),\r\n minCartValue: (Object.keys(this.getMinCartValue()) as CountryCode[]).reduce((acc, country) => {\r\n const priceModel = this.getMinCartValue(country);\r\n if (priceModel) {\r\n acc[country] = priceModel.getDetails();\r\n }\r\n return acc;\r\n }, {} as RegionalPrice),\r\n maxCartDiscount: (Object.keys(this.getMaxCartDiscount()) as CountryCode[]).reduce((acc, country) => {\r\n const priceModel = this.getMaxCartDiscount(country);\r\n if (priceModel) {\r\n acc[country] = priceModel.getDetails();\r\n }\r\n return acc;\r\n }, {} as RegionalPrice),\r\n discountMethod: this.getDiscountMethod(),\r\n percentageValue: this.getPercentageValue(),\r\n applicableTo: this.getApplicableTo(),\r\n category: this.getCategory(),\r\n };\r\n }\r\n\r\n /**\r\n * Checks if the coupon is currently active based on its validity dates.\r\n * @returns True if the coupon is currently within its validity period, false otherwise.\r\n */\r\n isActive(): boolean {\r\n return new Date(this.validFrom) <= new Date() && new Date(this.validTo) >= new Date();\r\n }\r\n\r\n\r\n /**\r\n * Checks if the coupon is applicable to a customer based on their status (e.g., first-time buyer).\r\n * @param ftbCustomer - A boolean indicating whether the customer is a first-time buyer.\r\n * @returns True if the coupon's applicability rule matches the customer's status, false otherwise.\r\n */\r\n isApplicableTo(ftbCustomer: boolean): boolean {\r\n return this.applicableTo === ApplicableTo.ALL || (this.applicableTo === ApplicableTo.FTB && ftbCustomer);\r\n }\r\n\r\n /**\r\n * Calculates the discount value for a given coupon based on the current container state.\r\n * Returns 0 if the coupon is invalid, expired, or not applicable based on cart value or target category.\r\n * @param cartValue - The cart subtotal as a PriceModel.\r\n * @param shippingCost - The cart shipping cost.\r\n * @param country - The country code.\r\n * @param currency - The currency code.\r\n * @returns The calculated discount amount (rounded according to country rules).\r\n */\r\n public calculateApplicableCouponDiscount(cartValue: PriceModel, shippingCost: PriceModel, country: CountryCode, currency: CurrencyCode, checkExpiry: boolean = true): PriceModel {\r\n let zeroDiscount: PriceModel = new PriceModel({ amount: 0, currency });\r\n let potentialDiscount: PriceModel;\r\n\r\n // 1. Basic validation (active)\r\n if (checkExpiry && !this.isActive()) {\r\n return zeroDiscount;\r\n }\r\n\r\n // 2. Check regional requirements (min cart value, max discount)\r\n const minCartValueReq = this.getMinCartValue(country);\r\n const maxCartDiscountCap = this.getMaxCartDiscount(country);\r\n\r\n // If minCartValueReq is not set or the cart value is less than the minimum required, return zero discount\r\n if (!minCartValueReq || minCartValueReq.compareTo(cartValue) > 0) {\r\n return zeroDiscount;\r\n }\r\n\r\n // If maxCartDiscountCap is not set, return zero discount\r\n if (!maxCartDiscountCap) {\r\n return zeroDiscount;\r\n }\r\n\r\n // 3. Calculate potential discount based on method and category\r\n const couponCategory = this.getCategory();\r\n const discountMethod = this.getDiscountMethod();\r\n // Determine the value the coupon applies to (shipping cost or subtotal)\r\n const targetValue = couponCategory === CouponCategory.SHIPPING ? shippingCost : cartValue;\r\n\r\n // No discount if the target value is zero or less\r\n if (targetValue.getAmount() <= 0) return zeroDiscount;\r\n\r\n switch (discountMethod) {\r\n case CouponDiscountMethod.FLAT:\r\n // Flat discount is capped by the target value itself and the max discount cap\r\n const flatAmount = maxCartDiscountCap; // Use cap as the flat amount source? Or coupon.value? Needs clarification. Assuming cap IS the flat amount here.\r\n potentialDiscount = targetValue.min(flatAmount);\r\n break;\r\n case CouponDiscountMethod.PERCENTAGE:\r\n // Calculate percentage discount based on the target value\r\n potentialDiscount = targetValue.multiply(this.getPercentageValue() / 100).round();\r\n break;\r\n default:\r\n // Unknown discount method\r\n return zeroDiscount;\r\n }\r\n\r\n // 4. Apply maximum discount cap to the calculated potential discount\r\n const finalDiscount = potentialDiscount.min(maxCartDiscountCap);\r\n\r\n return finalDiscount;\r\n }\r\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/Classes/Coupon.ts"],"names":["CouponType","CouponDiscountMethod","CouponCategory","ApplicableTo","CouponModel","BaseModel","data","date","Utils_default","acc","country","priceData","PriceModel","InvalidArgumentError","locale","LocaleLanguageMap","priceModel","ftbCustomer","cartValue","shippingCost","currency","checkExpiry","zeroDiscount","potentialDiscount","minCartValueReq","maxCartDiscountCap","couponCategory","discountMethod","targetValue","flatAmount"],"mappings":"uMAOO,IAAKA,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,MAAS,CAAA,QAAA,CACTA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import { CountryCode, CurrencyCode, ISODateTimeUTC, LocaleCode, LocalizedString, RegionalPrice } from \"./Common\";\r\nimport { LocaleLanguageMap } from \"./Enum\";\r\nimport { InvalidArgumentError } from \"./Error\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\n\r\nexport enum CouponType {\r\n COUPON = \"coupon\",\r\n AUTOMATIC = \"automatic\",\r\n}\r\n\r\nexport enum CouponDiscountMethod {\r\n FLAT = \"flat\",\r\n PERCENTAGE = \"percentage\",\r\n}\r\n\r\nexport enum CouponCategory {\r\n SHIPPING = \"SHIPPING\",\r\n CUSTOMER = \"CUSTOMER\",\r\n}\r\n\r\nexport enum ApplicableTo {\r\n ALL = \"all\",\r\n FTB = \"ftb\",\r\n}\r\n\r\nexport type CouponAttribute = BaseAttributes & {\r\n couponCode: string;\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n type: CouponType;\r\n customerId?: string;\r\n validFrom: ISODateTimeUTC;\r\n validTo: ISODateTimeUTC;\r\n minCartValue: RegionalPrice;\r\n maxCartDiscount: RegionalPrice;\r\n discountMethod: CouponDiscountMethod;\r\n percentageValue?: number;\r\n applicableTo: ApplicableTo;\r\n category: CouponCategory;\r\n};\r\n\r\nexport type CouponData = Required<CouponAttribute>\r\n\r\n/**\r\n * Represents a discount coupon, extending BaseModel.\r\n */\r\nexport default class CouponModel extends BaseModel {\r\n protected couponCode: string;\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected type: CouponType;\r\n protected customerId?: string;\r\n protected validFrom: ISODateTimeUTC;\r\n protected validTo: ISODateTimeUTC;\r\n protected minCartValue: {\r\n [country in CountryCode]?: PriceModel;\r\n };\r\n protected maxCartDiscount: {\r\n [country in CountryCode]?: PriceModel;\r\n };\r\n protected discountMethod: CouponDiscountMethod;\r\n protected percentageValue: number;\r\n protected applicableTo: ApplicableTo;\r\n protected category: CouponCategory;\r\n\r\n /**\r\n * Creates an instance of CouponModel.\r\n * @param data - The initial coupon attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: CouponAttribute, date: Date = new Date()) {\r\n super(data, date);\r\n\r\n this.couponCode = data.couponCode;\r\n this.name = Utils.deepClone(data.name);\r\n this.description = Utils.deepClone(data.description);\r\n this.type = data.type;\r\n this.customerId = data.customerId;\r\n this.validFrom = data.validFrom && Date.parse(data.validFrom) ? new Date(data.validFrom).toISOString() : date.toISOString();\r\n this.validTo = data.validTo && Date.parse(data.validTo) ? new Date(data.validTo).toISOString() : date.toISOString();\r\n this.minCartValue = (Object.keys(data.minCartValue) as CountryCode[]).reduce((acc, country) => {\r\n const priceData = data.minCartValue[country] as PriceData;\r\n if (priceData) {\r\n acc[country] = new PriceModel(priceData);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: PriceModel });\r\n this.maxCartDiscount = (Object.keys(data.maxCartDiscount) as CountryCode[]).reduce((acc, country) => {\r\n const priceData = data.maxCartDiscount[country] as PriceData;\r\n if (priceData) {\r\n acc[country] = new PriceModel(priceData);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: PriceModel });\r\n this.discountMethod = data.discountMethod;\r\n this.percentageValue = data.percentageValue ?? 0;\r\n if (this.percentageValue > 100) {\r\n throw new InvalidArgumentError('Percentage value cannot be greater than 100');\r\n }\r\n\r\n this.applicableTo = data.applicableTo;\r\n this.category = data.category;\r\n }\r\n\r\n /** Gets the unique coupon code. */\r\n getCode(): string {\r\n return this.couponCode;\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the coupon name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon description object.\r\n * @returns A copy of the LocalizedString object for the description, or undefined.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the coupon description for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The description string for the specified locale.\r\n */\r\n getDescription(locale: LocaleCode): string\r\n getDescription(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.description[locale] ?? this.description[LocaleLanguageMap[locale]] ?? this.description.en;\r\n } else {\r\n return { ...this.description };\r\n }\r\n }\r\n\r\n /** Gets the type of coupon (COUPON or AUTOMATIC). */\r\n getType(): CouponType {\r\n return this.type;\r\n }\r\n\r\n /** Gets the specific customer ID this coupon is limited to, if any. */\r\n getCustomerId(): string {\r\n return this.customerId ?? '';\r\n }\r\n\r\n /** Gets the ISO date string from when the coupon is valid. */\r\n getValidFrom(): ISODateTimeUTC {\r\n return this.validFrom;\r\n }\r\n\r\n /** Gets the ISO date string until when the coupon is valid. */\r\n getValidTo(): ISODateTimeUTC {\r\n return this.validTo;\r\n }\r\n\r\n /**\r\n * Gets the list of minimum cart values required for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional minimum cart values.\r\n */\r\n getMinCartValue(): { [country in CountryCode]?: PriceModel }\r\n\r\n /**\r\n * Gets the minimum cart value required for the coupon for a specific country.\r\n * @param country - The country code to filter the minimum value for.\r\n * @returns The regional minimum cart value for the specified country, or undefined if not set for that country.\r\n */\r\n getMinCartValue(country: CountryCode): PriceModel | undefined\r\n getMinCartValue(country?: CountryCode) {\n if (country) {\n return this.minCartValue[country];\n }\n return { ...this.minCartValue };\n }\n\r\n /**\r\n * Gets the list of maximum discount amounts allowed for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional maximum discount caps.\r\n */\r\n getMaxCartDiscount(): { [country in CountryCode]?: PriceModel }\r\n /**\r\n * Gets the maximum discount amount allowed for the coupon for a specific country.\r\n * @param country - The country code to filter the maximum discount for.\r\n * @returns The regional maximum discount cap for the specified country, or undefined if not set for that country.\r\n */\r\n getMaxCartDiscount(country: CountryCode): PriceModel | undefined\r\n getMaxCartDiscount(country?: CountryCode) {\n if (country) {\n return this.maxCartDiscount[country];\n }\n return { ...this.maxCartDiscount };\n }\n\r\n /** Gets the discount method (FLAT or PERCENTAGE). */\r\n getDiscountMethod(): CouponDiscountMethod {\r\n return this.discountMethod;\r\n }\r\n\r\n /** Gets the percentage discount value (0-100). */\r\n getPercentageValue(): number {\r\n return this.percentageValue;\r\n }\r\n\r\n /** Gets the customer applicability rule (ALL or FTB). */\r\n getApplicableTo(): ApplicableTo {\r\n return this.applicableTo;\r\n }\r\n\r\n /** Gets the category of the coupon (SHIPPING or CUSTOMER). */\r\n getCategory(): CouponCategory {\r\n return this.category;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the coupon's details.\r\n * @returns A CouponData object.\r\n */\r\n getDetails(): CouponData {\r\n return {\r\n ...super.getDetails(),\r\n couponCode: this.getCode(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n type: this.getType(),\r\n customerId: this.getCustomerId(),\r\n validFrom: this.getValidFrom(),\r\n validTo: this.getValidTo(),\r\n minCartValue: (Object.keys(this.getMinCartValue()) as CountryCode[]).reduce((acc, country) => {\r\n const priceModel = this.getMinCartValue(country);\r\n if (priceModel) {\r\n acc[country] = priceModel.getDetails();\r\n }\r\n return acc;\r\n }, {} as RegionalPrice),\r\n maxCartDiscount: (Object.keys(this.getMaxCartDiscount()) as CountryCode[]).reduce((acc, country) => {\r\n const priceModel = this.getMaxCartDiscount(country);\r\n if (priceModel) {\r\n acc[country] = priceModel.getDetails();\r\n }\r\n return acc;\r\n }, {} as RegionalPrice),\r\n discountMethod: this.getDiscountMethod(),\r\n percentageValue: this.getPercentageValue(),\r\n applicableTo: this.getApplicableTo(),\r\n category: this.getCategory(),\r\n };\r\n }\r\n\r\n /**\r\n * Checks if the coupon is currently active based on its validity dates.\r\n * @returns True if the coupon is currently within its validity period, false otherwise.\r\n */\r\n isActive(): boolean {\r\n return new Date(this.validFrom) <= new Date() && new Date(this.validTo) >= new Date();\r\n }\r\n\r\n\r\n /**\r\n * Checks if the coupon is applicable to a customer based on their status (e.g., first-time buyer).\r\n * @param ftbCustomer - A boolean indicating whether the customer is a first-time buyer.\r\n * @returns True if the coupon's applicability rule matches the customer's status, false otherwise.\r\n */\r\n isApplicableTo(ftbCustomer: boolean): boolean {\r\n return this.applicableTo === ApplicableTo.ALL || (this.applicableTo === ApplicableTo.FTB && ftbCustomer);\r\n }\r\n\r\n /**\r\n * Calculates the discount value for a given coupon based on the current container state.\r\n * Returns 0 if the coupon is invalid, expired, or not applicable based on cart value or target category.\r\n * @param cartValue - The cart subtotal as a PriceModel.\r\n * @param shippingCost - The cart shipping cost.\r\n * @param country - The country code.\r\n * @param currency - The currency code.\r\n * @returns The calculated discount amount (rounded according to country rules).\r\n */\r\n public calculateApplicableCouponDiscount(cartValue: PriceModel, shippingCost: PriceModel, country: CountryCode, currency: CurrencyCode, checkExpiry: boolean = true): PriceModel {\r\n let zeroDiscount: PriceModel = new PriceModel({ amount: 0, currency });\r\n let potentialDiscount: PriceModel;\r\n\r\n // 1. Basic validation (active)\r\n if (checkExpiry && !this.isActive()) {\r\n return zeroDiscount;\r\n }\r\n\r\n // 2. Check regional requirements (min cart value, max discount)\r\n const minCartValueReq = this.getMinCartValue(country);\r\n const maxCartDiscountCap = this.getMaxCartDiscount(country);\r\n\r\n // If minCartValueReq is not set or the cart value is less than the minimum required, return zero discount\r\n if (!minCartValueReq || minCartValueReq.compareTo(cartValue) > 0) {\r\n return zeroDiscount;\r\n }\r\n\r\n // If maxCartDiscountCap is not set, return zero discount\r\n if (!maxCartDiscountCap) {\r\n return zeroDiscount;\r\n }\r\n\r\n // 3. Calculate potential discount based on method and category\r\n const couponCategory = this.getCategory();\r\n const discountMethod = this.getDiscountMethod();\r\n // Determine the value the coupon applies to (shipping cost or subtotal)\r\n const targetValue = couponCategory === CouponCategory.SHIPPING ? shippingCost : cartValue;\r\n\r\n // No discount if the target value is zero or less\r\n if (targetValue.getAmount() <= 0) return zeroDiscount;\r\n\r\n switch (discountMethod) {\r\n case CouponDiscountMethod.FLAT:\r\n // Flat discount is capped by the target value itself and the max discount cap\r\n const flatAmount = maxCartDiscountCap; // Use cap as the flat amount source? Or coupon.value? Needs clarification. Assuming cap IS the flat amount here.\r\n potentialDiscount = targetValue.min(flatAmount);\r\n break;\r\n case CouponDiscountMethod.PERCENTAGE:\r\n // Calculate percentage discount based on the target value\r\n potentialDiscount = targetValue.multiply(this.getPercentageValue() / 100).round();\r\n break;\r\n default:\r\n // Unknown discount method\r\n return zeroDiscount;\r\n }\r\n\r\n // 4. Apply maximum discount cap to the calculated potential discount\r\n const finalDiscount = potentialDiscount.min(maxCartDiscountCap);\r\n\r\n return finalDiscount;\r\n }\r\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-FCRJAAPY.mjs';import {
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-FCRJAAPY.mjs';import {e as e$1}from'./chunk-QK4XJ3GB.mjs';import {b as b$2}from'./chunk-2B2XI6FG.mjs';import {h as h$1,e}from'./chunk-R5DM7WCD.mjs';import {b as b$1}from'./chunk-UXZBULDS.mjs';import K from'crypto';var y=new Uint8Array(256),h=y.length;function I(){return h>y.length-16&&(K.randomFillSync(y),h=0),y.slice(h,h+=16)}var z=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function $(t){return typeof t=="string"&&z.test(t)}var U=$;var n=[];for(let t=0;t<256;++t)n.push((t+256).toString(16).slice(1));function b(t,e=0){return n[t[e+0]]+n[t[e+1]]+n[t[e+2]]+n[t[e+3]]+"-"+n[t[e+4]]+n[t[e+5]]+"-"+n[t[e+6]]+n[t[e+7]]+"-"+n[t[e+8]]+n[t[e+9]]+"-"+n[t[e+10]]+n[t[e+11]]+n[t[e+12]]+n[t[e+13]]+n[t[e+14]]+n[t[e+15]]}function k(t){if(!U(t))throw TypeError("Invalid UUID");let e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}var M=k;function V(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var G="6ba7b810-9dad-11d1-80b4-00c04fd430c8",B="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function x(t,e,r){function i(o,s,u,S){var A;if(typeof o=="string"&&(o=V(o)),typeof s=="string"&&(s=M(s)),((A=s)===null||A===void 0?void 0:A.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let g=new Uint8Array(16+o.length);if(g.set(s),g.set(o,s.length),g=r(g),g[6]=g[6]&15|e,g[8]=g[8]&63|128,u){S=S||0;for(let m=0;m<16;++m)u[S+m]=g[m];return u}return b(g)}try{i.name=t;}catch{}return i.DNS=G,i.URL=B,i}var L={randomUUID:K.randomUUID};function j(t,e,r){if(L.randomUUID&&!e&&!t)return L.randomUUID();t=t||{};let i=t.random||(t.rng||I)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){r=r||0;for(let o=0;o<16;++o)e[r+o]=i[o];return e}return b(i)}var D=j;function Z(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),K.createHash("sha1").update(t).digest()}var R=Z;var q=x("v5",80,R),P=q;var O={isUUID:t=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t),isEmail:t=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t),isURL:t=>/^(http|https):\/\/[^ "]+$/.test(t),generateUUID:(t,e)=>e&&t?P(t,e):D(),generateSearchId:(t,e)=>`${t}#${f.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:t=>{let[e,r]=t.split("#");return {key:e,selectionAttributes:f.parseSelectionAttributesKey(r)}},deepClone(t){return structuredClone(t)}},a=O;var f=class t extends b$1{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new h$1("Selection attributes must be an object");return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let r={},i=e.split("|");for(let o of i){let[s,u]=o.split(":");u.startsWith("c+")?r[s]={name:u.slice(2)}:r[s]=u;}return r}catch(r){throw new h$1(r?.message)}}constructor(e$1,r=new Date){super(e$1,r),this.id=e$1.id,this.key=e$1.key,this.name={...e$1.name},this.description={...e$1.description},this.slug={...e$1.slug},this.brand=e$1.brand,this.pricing=Object.keys(e$1.pricing).reduce((o,s)=>(e$1.pricing[s]&&(o[s]=new a$1(e$1.pricing[s])),o),{}),this.targetGender=e$1.targetGender,this.attributes=a.deepClone(e$1.attributes),this.specifications=a.deepClone(e$1.specifications),this.categories=a.deepClone(e$1.categories);let i=new Set;this.variants=(e$1.variants||[]).map(o=>{if(!o.selectionAttributes||typeof o.selectionAttributes!="object")throw new h$1("Selection attributes are required");this.checkSelectionAttributes(o.selectionAttributes);let s=t.generateSelectionAttributesKey(o.selectionAttributes);if(i.has(s))throw new e(s);return i.add(s),{sku:o.sku,selectionAttributes:o.selectionAttributes,images:{primary:new b$2(o.images.primary),gallery:(o.images.gallery||[]).map(u=>new b$2(u))}}}),this.isActive=e$1.isActive,this.searchTags=e$1.searchTags?a.deepClone(e$1.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[e$1[e]]??this.name.en:a.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[e$1[e]]??this.description.en:a.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[e$1[e]]??this.slug.en:a.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return a.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:a.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let r=t.generateSelectionAttributesKey(e),i=this.variants.find(o=>t.generateSelectionAttributesKey(o.selectionAttributes)===r);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,r){switch(r){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return a.deepClone(this.categories)}getSpecifications(e){return e?a.deepClone(this.specifications[e]??this.specifications[e$1[e]]??this.specifications.en):a.deepClone(this.specifications)}getSearchTags(e){return e?a.deepClone(this.searchTags[e]??this.searchTags[e$1[e]]??this.searchTags.en):a.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((r,i)=>(this.pricing[i]&&(r[i]=this.pricing[i]?.getDetails()),r),{}),attributes:this.getAttributes(),variants:this.variants.map(r=>({sku:r.sku,selectionAttributes:a.deepClone(r.selectionAttributes),images:{primary:r.images.primary.getDetails(),gallery:r.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new h$1("Selection attributes are required");Object.keys(this.attributes).forEach(r=>{if(r.toLowerCase()==="size")return;let i=this.attributes[r],o=e[r];if(o===void 0)throw new h$1(`Selection attribute '${r}' is missing`);if(typeof i=="string"){if(typeof o!="string"||i!==o)throw new h$1(`Selection attribute '${r}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof o!="string"||!i.includes(o))throw new h$1(`Selection attribute '${r}' is invalid`)}else if(typeof o!="object"||!("name"in o)||i.findIndex(s=>s.name===o.name)<0)throw new h$1(`Selection attribute '${r}' is invalid`)}});}validateSelectionAttribute(e){let r=t.generateSelectionAttributesKey(e);return this.variants.some(i=>t.generateSelectionAttributesKey(i.selectionAttributes)===r)}validateSize(e){return this.attributes.size.includes(e)}};export{a,f as b};//# sourceMappingURL=chunk-QGIQ3MH6.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-QGIQ3MH6.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../node_modules/uuid/dist/esm-node/rng.js","../node_modules/uuid/dist/esm-node/regex.js","../node_modules/uuid/dist/esm-node/validate.js","../node_modules/uuid/dist/esm-node/stringify.js","../node_modules/uuid/dist/esm-node/parse.js","../node_modules/uuid/dist/esm-node/v35.js","../node_modules/uuid/dist/esm-node/native.js","../node_modules/uuid/dist/esm-node/v4.js","../node_modules/uuid/dist/esm-node/sha1.js","../node_modules/uuid/dist/esm-node/v5.js","../src/Utils/index.ts","../src/Classes/Product.ts"],"names":["rnds8Pool","poolPtr","rng","crypto","regex_default","validate","uuid","validate_default","byteToHex","i","unsafeStringify","arr","offset","parse","v","parse_default","stringToBytes","str","bytes","DNS","URL","v35","name","version","hashfunc","generateUUID","value","namespace","buf","_namespace","native_default","v4","options","rnds","v4_default","sha1","sha1_default","v5","v5_default","Utils","key","selectionAttributes","ProductModel","searchId","selectionAttributesKey","obj","Utils_default","_ProductModel","BaseModel","SelectionAttributeParseError","attributes","parts","part","error","data","date","acc","country","TieredPriceModel","uniqueSelectionAttributes","variant","DuplicateSelectionAttributeError","ImageInfoModel","image","locale","LocaleLanguageMap","searchKey","match","category","baseDetails","img","allowedAttributeValues","providedValue","c","size"],"mappings":"oPACA,IAAMA,CAAAA,CAAY,IAAI,UAAW,CAAA,GAAG,EAEhCC,CAAUD,CAAAA,CAAAA,CAAU,OACT,SAARE,CAAAA,EAAuB,CAC5B,OAAID,CAAAA,CAAUD,EAAU,MAAS,CAAA,EAAA,GAC/BG,CAAO,CAAA,cAAA,CAAeH,CAAS,CAAA,CAC/BC,EAAU,CAGLD,CAAAA,CAAAA,CAAAA,CAAU,MAAMC,CAASA,CAAAA,CAAAA,EAAW,EAAE,CAC/C,CCXA,IAAOG,CAAAA,CAAQ,qHCEf,CAAA,SAASC,EAASC,CAAM,CAAA,CACtB,OAAO,OAAOA,CAAAA,EAAS,UAAYF,CAAM,CAAA,IAAA,CAAKE,CAAI,CACpD,CAEA,IAAOC,EAAQF,CCAf,CAAA,IAAMG,EAAY,EAAC,CAEnB,QAASC,CAAI,CAAA,CAAA,CAAGA,EAAI,GAAK,CAAA,EAAEA,EACzBD,CAAU,CAAA,IAAA,CAAA,CAAMC,EAAI,GAAO,EAAA,QAAA,CAAS,EAAE,CAAE,CAAA,KAAA,CAAM,CAAC,CAAC,CAG3C,CAAA,SAASC,EAAgBC,CAAKC,CAAAA,CAAAA,CAAS,EAAG,CAG/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,YAAA,CAAA,CAAA,CAAA,KAAA,GAKhF,OAAOgC,CAAkB,EAAA,QAAA,EACzB,EAAE,MAAA,GAAUA,CACXD,CAAAA,EAAAA,CAAAA,CAAmC,UAAUE,CAAKA,EAAAA,CAAAA,CAAE,OAAUD,CAAwB,CAAA,IAAI,EAAI,CAE/F,CAAA,MAAM,IAAIvB,GAAAA,CAA6B,CAAwBT,qBAAAA,EAAAA,CAAG,cAAc,CAIxF,CAAA,CAAC,EACH,CAOA,0BAAA,CAA2BC,EAAmD,CAC5E,IAAMyB,CAAYnB,CAAAA,CAAAA,CAAa,8BAA+BN,CAAAA,CAAmB,EAEjF,OAAO,IAAA,CAAK,SAAS,IAAKmB,CAAAA,CAAAA,EAAWb,EAAa,8BAA+Ba,CAAAA,CAAAA,CAAQ,mBAAmB,CAAA,GAAMM,CAAS,CAC7H,CAOA,YAAaQ,CAAAA,CAAAA,CAAuB,CAClC,OAAO,IAAA,CAAK,WAAW,IAAK,CAAA,QAAA,CAASA,CAAI,CAC3C,CACF","file":"chunk-MHLRJ4IJ.mjs","sourcesContent":["import crypto from 'crypto';\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\n\nlet poolPtr = rnds8Pool.length;\nexport default function rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n crypto.randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}","export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\n\nexport function unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];\n}\n\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import validate from './validate.js';\n\nfunction parse(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n let v;\n const arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nexport default parse;","import { unsafeStringify } from './stringify.js';\nimport parse from './parse.js';\n\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n const bytes = [];\n\n for (let i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n\n return bytes;\n}\n\nexport const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexport const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nexport default function v35(name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n var _namespace;\n\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n\n if (typeof namespace === 'string') {\n namespace = parse(namespace);\n }\n\n if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n } // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n\n\n let bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n\n return buf;\n }\n\n return unsafeStringify(bytes);\n } // Function#name is not settable on some platforms (#270)\n\n\n try {\n generateUUID.name = name; // eslint-disable-next-line no-empty\n } catch (err) {} // For CommonJS default export support\n\n\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","import crypto from 'crypto';\nexport default {\n randomUUID: crypto.randomUUID\n};","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\n\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n\n options = options || {};\n const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return unsafeStringify(rnds);\n}\n\nexport default v4;","import crypto from 'crypto';\n\nfunction sha1(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n\n return crypto.createHash('sha1').update(bytes).digest();\n}\n\nexport default sha1;","import v35 from './v35.js';\nimport sha1 from './sha1.js';\nconst v5 = v35('v5', 0x50, sha1);\nexport default v5;","import { v4 as uuidv4, v5 as uuidv5 } from 'uuid';\r\nimport ProductModel, { SelectionAttributes } from '../Classes/Product';\r\n\r\nconst Utils = {\r\n isUUID: (value: string): boolean => {\r\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\r\n return uuidRegex.test(value);\r\n },\r\n\r\n isEmail: (value: string): boolean => {\r\n const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;\r\n return emailRegex.test(value);\r\n },\r\n\r\n isURL: (value: string): boolean => {\r\n const urlRegex = /^(http|https):\\/\\/[^ \"]+$/;\r\n return urlRegex.test(value);\r\n },\r\n \r\n generateUUID: (value?: string, namespace?: string) => {\r\n if(namespace && value){\r\n return uuidv5(value, namespace);\r\n }\r\n return uuidv4();\r\n },\r\n\r\n generateSearchId: (key: string, selectionAttributes: SelectionAttributes) => {\r\n return `${key}#${ProductModel.generateSelectionAttributesKey(selectionAttributes)}`;\r\n },\r\n\r\n getKeyfromSearchId: (searchId: string) => {\r\n const [key, selectionAttributesKey] = searchId.split('#');\r\n return {\r\n key,\r\n selectionAttributes: ProductModel.parseSelectionAttributesKey(selectionAttributesKey)\r\n }\r\n },\r\n\r\n /**\r\n * Deep clones an object using `structuredClone`. Don't use this on a class instance.\r\n * @param obj - The object to clone.\r\n * @returns A deep clone of the object.\r\n */\r\n deepClone<T>(obj: T): T {\r\n return structuredClone(obj);\r\n }\r\n}\r\n\r\nexport default Utils;\r\n","import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { Color, LocalizedString, CountryCode, LocaleCode, LocalizedValue, Prettify } from './Common';\r\nimport { GenderCategory, ImageCategory, LocaleLanguageMap } from \"./Enum\";\r\nimport { DuplicateSelectionAttributeError, DuplicateSizeError, SelectionAttributeParseError } from \"./Error\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport { TieredPriceModel, TieredPriceAttributes, TieredPriceData } from \"./TieredPrice\";\r\n\r\nexport type ProductSelectionAttributes = Prettify<{\r\n color: Color[];\r\n size: string[];\r\n} & {\r\n [key: string]: string | string[] | Color[];\r\n}>;\r\n\r\nexport type SelectionAttributes = {\r\n color: Color;\r\n [key: string]: string | Color;\r\n};\r\n\r\nexport type VariantData = {\r\n sku: string;\r\n selectionAttributes: SelectionAttributes;\r\n images: {\r\n primary: ImageInfoData;\r\n gallery: ImageInfoData[];\r\n };\r\n};\r\n\r\nexport type VariantModel = {\r\n sku: string;\r\n selectionAttributes: SelectionAttributes;\r\n images: {\r\n primary: ImageInfoModel;\r\n gallery: ImageInfoModel[];\r\n };\r\n};\r\n\r\n\r\nexport type ProductSpecification = { [key: string]: string | string[] };\r\n\r\nexport type ProductAttributes = BaseAttributes & {\r\n id: string;\r\n key: string;\r\n\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n slug: LocalizedString;\r\n brand: string;\r\n\r\n pricing: {\r\n [country in CountryCode]?: TieredPriceAttributes;\r\n };\r\n\r\n targetGender: GenderCategory;\r\n attributes: ProductSelectionAttributes;\r\n specifications: LocalizedValue<ProductSpecification>;\r\n categories: string[];\r\n\r\n variants: VariantData[];\r\n\r\n // Metadata\r\n isActive: boolean;\r\n searchTags?: LocalizedValue<string[]>;\r\n};\r\n\r\nexport type ProductData = Required<ProductAttributes>\r\n\r\nexport default class ProductModel extends BaseModel {\r\n protected id: string;\r\n protected key: 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 pricing: {\r\n [country in CountryCode]?: TieredPriceModel;\r\n };\r\n\r\n protected variants: VariantModel[];\r\n\r\n protected targetGender: GenderCategory;\r\n protected attributes: ProductSelectionAttributes;\r\n protected specifications: LocalizedValue<ProductSpecification>;\r\n protected categories: string[];\r\n\r\n // Metadata\r\n protected isActive: boolean;\r\n\r\n protected searchTags: LocalizedValue<string[]>;\r\n\r\n static productKeyRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n static productSKURegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n\r\n /**\r\n * Generates a unique key for checking uniqueness for a given selection attributes.\r\n * Excludes 'size' from the key generation.\r\n * @param selectionAttributes - The selection attributes.\r\n * @returns A string key representing the unique attribute combination.\r\n */\r\n static generateSelectionAttributesKey(selectionAttributes: SelectionAttributes): string {\r\n if (typeof selectionAttributes !== 'object') {\r\n throw new SelectionAttributeParseError('Selection attributes must be an object');\r\n }\r\n\r\n const sortedKeys = Object.keys(selectionAttributes)\r\n .filter(key => selectionAttributes[key] !== undefined && key.toLowerCase() !== 'size')\r\n .sort()\r\n\r\n return sortedKeys.map(key => {\r\n if ((selectionAttributes[key] as Color).name) {\r\n return `${key}:c+${(selectionAttributes[key] as Color).name}`;\r\n }\r\n return `${key}:${selectionAttributes[key]}`;\r\n }).join('|').toLowerCase();\r\n }\r\n\r\n /**\r\n * Parses a selection attributes key into an object.\r\n * @param key - The selection attributes key to parse.\r\n * @returns An object containing the parsed selection attributes.\r\n */\r\n static parseSelectionAttributesKey(key: string): SelectionAttributes {\r\n try {\r\n const attributes: SelectionAttributes = {} as unknown as SelectionAttributes;\r\n const parts = key.split('|');\r\n for (const part of parts) {\r\n const [key, value] = part.split(':');\r\n if (value.startsWith('c+')) {\r\n attributes[key] = { name: value.slice(2) } as Color;\r\n } else {\r\n attributes[key] = value;\r\n }\r\n }\r\n return attributes;\r\n } catch (error: any) {\r\n throw new SelectionAttributeParseError(error?.message);\r\n }\r\n }\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\r\n this.id = data.id;\r\n this.key = data.key;\r\n\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.pricing = (Object.keys(data.pricing) as CountryCode[]).reduce((acc, country) => {\r\n if (data.pricing[country]) {\r\n acc[country] = new TieredPriceModel(data.pricing[country]);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: TieredPriceModel });\r\n\r\n this.targetGender = data.targetGender;\r\n this.attributes = Utils.deepClone(data.attributes);\r\n this.specifications = Utils.deepClone(data.specifications);\r\n this.categories = Utils.deepClone(data.categories);\r\n\r\n const uniqueSelectionAttributes = new Set<string>();\r\n this.variants = (data.variants || []).map(variant => {\r\n if (!variant.selectionAttributes || typeof variant.selectionAttributes !== 'object') {\r\n throw new SelectionAttributeParseError('Selection attributes are required');\r\n }\r\n\r\n this.checkSelectionAttributes(variant.selectionAttributes);\r\n const key = ProductModel.generateSelectionAttributesKey(variant.selectionAttributes);\r\n if (uniqueSelectionAttributes.has(key)) {\r\n throw new DuplicateSelectionAttributeError(key);\r\n }\r\n uniqueSelectionAttributes.add(key);\r\n return {\r\n sku: variant.sku,\r\n selectionAttributes: variant.selectionAttributes,\r\n images: {\r\n primary: new ImageInfoModel(variant.images.primary),\r\n gallery: (variant.images.gallery || []).map(image => new ImageInfoModel(image))\r\n }\r\n };\r\n });\r\n\r\n this.isActive = data.isActive;\r\n this.searchTags = data.searchTags ? Utils.deepClone(data.searchTags) : { en: [] };\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 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 Utils.deepClone(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 Utils.deepClone(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 Utils.deepClone(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 tiered price details for the product.\r\n * @returns Pricing details mapped by country.\r\n */\r\n getPriceDetails(): { [country in CountryCode]?: TieredPriceModel }\r\n /**\r\n * Gets the tiered price details for a specific country.\r\n * @param country - The country code.\r\n * @returns The tiered price model for the country, or null if not found.\r\n */\r\n getPriceDetails(country: CountryCode): TieredPriceModel | null\r\n getPriceDetails(country?: CountryCode): { [country in CountryCode]?: TieredPriceModel } | TieredPriceModel | null {\r\n if (country) {\r\n return this.pricing[country] ?? null;\r\n }\r\n return { ...this.pricing };\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(): ProductSelectionAttributes {\r\n return Utils.deepClone(this.attributes);\r\n }\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 getVariants(): VariantModel[] {\r\n return this.variants.map(variant => ({\r\n sku: variant.sku,\r\n selectionAttributes: Utils.deepClone(variant.selectionAttributes),\r\n images: {\r\n primary: variant.images.primary,\r\n gallery: [...variant.images.gallery]\r\n }\r\n }));\r\n }\r\n\r\n /**\r\n * Gets the images for a specific selection attribute combination.\r\n * @param selectionAttributes - The selection attributes to search for.\r\n * @returns The matching image set or null if not found.\r\n */\r\n private getImagesBySelectionAttributes(selectionAttributes: SelectionAttributes): { primary: ImageInfoModel; gallery: ImageInfoModel[] } | null {\r\n const searchKey = ProductModel.generateSelectionAttributesKey(selectionAttributes);\r\n\r\n const match = this.variants.find(variant =>\r\n ProductModel.generateSelectionAttributesKey(variant.selectionAttributes) === searchKey\r\n );\r\n\r\n return match ? {\r\n primary: match.images.primary,\r\n gallery: [...match.images.gallery]\r\n } : null;\r\n }\r\n\r\n /**\r\n * Gets the images for a specific selection attribute combination.\r\n * @param selectionAttributes - The selection attributes to search for.\r\n * @returns The matching image set or null if not found.\r\n */\r\n getImages(selectionAttributes: SelectionAttributes): { primary: ImageInfoModel; gallery: ImageInfoModel[] }\r\n getImages(selectionAttributes: SelectionAttributes, category: ImageCategory.PRIMARY): ImageInfoModel\r\n getImages(selectionAttributes: SelectionAttributes, category: ImageCategory.GALLERY): ImageInfoModel[]\r\n getImages(selectionAttributes: SelectionAttributes, category?: ImageCategory): { primary: ImageInfoModel; gallery: ImageInfoModel[] } | ImageInfoModel | ImageInfoModel[] {\r\n switch (category) {\r\n case ImageCategory.PRIMARY:\r\n return this.getImagesBySelectionAttributes(selectionAttributes)?.primary ?? this.variants[0]?.images?.primary;\r\n case ImageCategory.GALLERY:\r\n return this.getImagesBySelectionAttributes(selectionAttributes)?.gallery ?? [];\r\n default:\r\n return this.getImagesBySelectionAttributes(selectionAttributes) ?? { primary: this.variants[0]?.images?.primary, gallery: [] };\r\n }\r\n }\r\n\r\n\r\n /**\r\n * Checks if the product 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 Utils.deepClone(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(): LocalizedValue<ProductSpecification>\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\r\n getSpecifications(locale?: LocaleCode): LocalizedValue<ProductSpecification> | ProductSpecification {\r\n if (locale) {\r\n return Utils.deepClone(this.specifications[locale] ?? this.specifications[LocaleLanguageMap[locale]] ?? this.specifications.en);\r\n } else {\r\n return Utils.deepClone(this.specifications);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the localized list of search tags. Returns a copy.\r\n * @returns Localized array of search tags.\r\n */\r\n getSearchTags(): LocalizedValue<string[]>\r\n /**\r\n * Gets the search tags for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The array of search tags for the specified locale, or undefined if not found.\r\n */\r\n getSearchTags(locale: LocaleCode): string[]\r\n getSearchTags(locale?: LocaleCode): LocalizedValue<string[]> | string[] {\r\n if (locale) {\r\n return Utils.deepClone(this.searchTags[locale] ?? this.searchTags[LocaleLanguageMap[locale]] ?? this.searchTags.en);\r\n } else {\r\n return Utils.deepClone(this.searchTags);\r\n }\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 name: this.getName(),\r\n description: this.getDescription(),\r\n slug: this.getSlug(),\r\n brand: this.getBrand(),\r\n pricing: (Object.keys(this.pricing) as CountryCode[]).reduce((acc, country) => {\r\n if (this.pricing[country]) {\r\n acc[country] = this.pricing[country]?.getDetails();\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]: TieredPriceData }),\r\n attributes: this.getAttributes(),\r\n variants: this.variants.map(v => ({\r\n sku: v.sku,\r\n selectionAttributes: Utils.deepClone(v.selectionAttributes),\r\n images: {\r\n primary: v.images.primary.getDetails(),\r\n gallery: v.images.gallery.map(img => img.getDetails())\r\n }\r\n })),\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 * Checks if the provided selection attributes are valid for the product.\r\n * @param selectionAttributes The selection attributes to validate.\r\n * @throws {SelectionAttributeParseError} If the selection attributes are invalid.\r\n */\r\n checkSelectionAttributes(selectionAttributes: SelectionAttributes): void {\r\n if (!selectionAttributes || typeof selectionAttributes !== 'object') {\r\n throw new SelectionAttributeParseError('Selection attributes are required');\r\n }\r\n\r\n Object.keys(this.attributes).forEach(key => {\r\n if(key.toLowerCase() === 'size') return;\r\n \r\n const allowedAttributeValues = this.attributes[key];\r\n const providedValue = selectionAttributes[key];\r\n\r\n if (providedValue === undefined) {\r\n throw new SelectionAttributeParseError(`Selection attribute '${key}' is missing`);\r\n }\r\n\r\n if (typeof allowedAttributeValues === 'string') {\r\n if (typeof providedValue !== 'string' || allowedAttributeValues !== providedValue) {\r\n throw new SelectionAttributeParseError(`Selection attribute '${key}' is invalid`);\r\n }\r\n } else if (Array.isArray(allowedAttributeValues)) {\r\n if (allowedAttributeValues.length > 0 && typeof allowedAttributeValues[0] === 'string') {\r\n if (typeof providedValue !== 'string' || !(allowedAttributeValues as string[]).includes(providedValue)) {\r\n throw new SelectionAttributeParseError(`Selection attribute '${key}' is invalid`);\r\n }\r\n } else {\r\n // Color validation\r\n if (\r\n typeof providedValue !== 'object' ||\r\n !('name' in providedValue) ||\r\n (allowedAttributeValues as Color[]).findIndex(c => c.name === (providedValue as Color).name) < 0\r\n ) {\r\n throw new SelectionAttributeParseError(`Selection attribute '${key}' is invalid`);\r\n }\r\n }\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Validates if the provided selection attributes exist for this product.\r\n * @param selectionAttributes - The attributes to validate.\r\n * @returns True if a valid selection attribute exists, false otherwise.\r\n */\r\n validateSelectionAttribute(selectionAttributes: SelectionAttributes): boolean {\r\n const searchKey = ProductModel.generateSelectionAttributesKey(selectionAttributes);\r\n\r\n return this.variants.some(variant => ProductModel.generateSelectionAttributesKey(variant.selectionAttributes) === searchKey);\r\n }\r\n\r\n /**\r\n * Validates if a specific size is available for this product.\r\n * @param size - The size to check.\r\n * @returns True if the size exists in the product's attributes, false otherwise.\r\n */\r\n validateSize(size: string): boolean {\r\n return this.attributes.size.includes(size);\r\n }\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../node_modules/uuid/dist/esm-node/rng.js","../node_modules/uuid/dist/esm-node/regex.js","../node_modules/uuid/dist/esm-node/validate.js","../node_modules/uuid/dist/esm-node/stringify.js","../node_modules/uuid/dist/esm-node/parse.js","../node_modules/uuid/dist/esm-node/v35.js","../node_modules/uuid/dist/esm-node/native.js","../node_modules/uuid/dist/esm-node/v4.js","../node_modules/uuid/dist/esm-node/sha1.js","../node_modules/uuid/dist/esm-node/v5.js","../src/Utils/index.ts","../src/Classes/Product.ts"],"names":["rnds8Pool","poolPtr","rng","crypto","regex_default","validate","uuid","validate_default","byteToHex","i","unsafeStringify","arr","offset","parse","v","parse_default","stringToBytes","str","bytes","DNS","URL","v35","name","version","hashfunc","generateUUID","value","namespace","buf","_namespace","native_default","v4","options","rnds","v4_default","sha1","sha1_default","v5","v5_default","Utils","key","selectionAttributes","ProductModel","searchId","selectionAttributesKey","obj","Utils_default","_ProductModel","BaseModel","SelectionAttributeParseError","attributes","parts","part","error","data","date","acc","country","TieredPriceModel","uniqueSelectionAttributes","variant","DuplicateSelectionAttributeError","ImageInfoModel","image","locale","LocaleLanguageMap","searchKey","match","category","baseDetails","img","allowedAttributeValues","providedValue","c","size"],"mappings":"oPACA,IAAMA,CAAAA,CAAY,IAAI,UAAW,CAAA,GAAG,EAEhCC,CAAUD,CAAAA,CAAAA,CAAU,OACT,SAARE,CAAAA,EAAuB,CAC5B,OAAID,CAAA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I,CAC3C,CACF","file":"chunk-QGIQ3MH6.mjs","sourcesContent":["import crypto from 'crypto';\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\n\nlet poolPtr = rnds8Pool.length;\nexport default function rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n crypto.randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}","export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\n\nexport function unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];\n}\n\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import validate from './validate.js';\n\nfunction parse(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n let v;\n const arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nexport default parse;","import { unsafeStringify } from './stringify.js';\nimport parse from './parse.js';\n\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n const bytes = [];\n\n for (let i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n\n return bytes;\n}\n\nexport const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexport const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nexport default function v35(name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n var _namespace;\n\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n\n if (typeof namespace === 'string') {\n namespace = parse(namespace);\n }\n\n if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n } // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n\n\n let bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n\n return buf;\n }\n\n return unsafeStringify(bytes);\n } // Function#name is not settable on some platforms (#270)\n\n\n try {\n generateUUID.name = name; // eslint-disable-next-line no-empty\n } catch (err) {} // For CommonJS default export support\n\n\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","import crypto from 'crypto';\nexport default {\n randomUUID: crypto.randomUUID\n};","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\n\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n\n options = options || {};\n const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return unsafeStringify(rnds);\n}\n\nexport default v4;","import crypto from 'crypto';\n\nfunction sha1(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n\n return crypto.createHash('sha1').update(bytes).digest();\n}\n\nexport default sha1;","import v35 from './v35.js';\nimport sha1 from './sha1.js';\nconst v5 = v35('v5', 0x50, sha1);\nexport default v5;","import { v4 as uuidv4, v5 as uuidv5 } from 'uuid';\r\nimport ProductModel, { SelectionAttributes } from '../Classes/Product';\r\n\r\nconst Utils = {\r\n isUUID: (value: string): boolean => {\r\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\r\n return uuidRegex.test(value);\r\n },\r\n\r\n isEmail: (value: string): boolean => {\r\n const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;\r\n return emailRegex.test(value);\r\n },\r\n\r\n isURL: (value: string): boolean => {\r\n const urlRegex = /^(http|https):\\/\\/[^ \"]+$/;\r\n return urlRegex.test(value);\r\n },\r\n \r\n generateUUID: (value?: string, namespace?: string) => {\r\n if(namespace && value){\r\n return uuidv5(value, namespace);\r\n }\r\n return uuidv4();\r\n },\r\n\r\n generateSearchId: (key: string, selectionAttributes: SelectionAttributes) => {\r\n return `${key}#${ProductModel.generateSelectionAttributesKey(selectionAttributes)}`;\r\n },\r\n\r\n getKeyfromSearchId: (searchId: string) => {\r\n const [key, selectionAttributesKey] = searchId.split('#');\r\n return {\r\n key,\r\n selectionAttributes: ProductModel.parseSelectionAttributesKey(selectionAttributesKey)\r\n }\r\n },\r\n\r\n /**\r\n * Deep clones an object using `structuredClone`. Don't use this on a class instance.\r\n * @param obj - The object to clone.\r\n * @returns A deep clone of the object.\r\n */\r\n deepClone<T>(obj: T): T {\r\n return structuredClone(obj);\r\n }\r\n}\r\n\r\nexport default Utils;\r\n","import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { Color, LocalizedString, CountryCode, LocaleCode, LocalizedValue, Prettify } from './Common';\r\nimport { GenderCategory, ImageCategory, LocaleLanguageMap } from \"./Enum\";\r\nimport { DuplicateSelectionAttributeError, DuplicateSizeError, SelectionAttributeParseError } from \"./Error\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport { TieredPriceModel, TieredPriceAttributes, TieredPriceData } from \"./TieredPrice\";\r\n\r\nexport type ProductSelectionAttributes = Prettify<{\r\n color: Color[];\r\n size: string[];\r\n} & {\r\n [key: string]: string | string[] | Color[];\r\n}>;\r\n\r\nexport type SelectionAttributes = {\r\n color: Color;\r\n [key: string]: string | Color;\r\n};\r\n\r\nexport type VariantData = {\r\n sku: string;\r\n selectionAttributes: SelectionAttributes;\r\n images: {\r\n primary: ImageInfoData;\r\n gallery: ImageInfoData[];\r\n };\r\n};\r\n\r\nexport type VariantModel = {\r\n sku: string;\r\n selectionAttributes: SelectionAttributes;\r\n images: {\r\n primary: ImageInfoModel;\r\n gallery: ImageInfoModel[];\r\n };\r\n};\r\n\r\n\r\nexport type ProductSpecification = { [key: string]: string | string[] };\r\n\r\nexport type ProductAttributes = BaseAttributes & {\r\n id: string;\r\n key: string;\r\n\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n slug: LocalizedString;\r\n brand: string;\r\n\r\n pricing: {\r\n [country in CountryCode]?: TieredPriceAttributes;\r\n };\r\n\r\n targetGender: GenderCategory;\r\n attributes: ProductSelectionAttributes;\r\n specifications: LocalizedValue<ProductSpecification>;\r\n categories: string[];\r\n\r\n variants: VariantData[];\r\n\r\n // Metadata\r\n isActive: boolean;\r\n searchTags?: LocalizedValue<string[]>;\r\n};\r\n\r\nexport type ProductData = Required<ProductAttributes>\r\n\r\nexport default class ProductModel extends BaseModel {\r\n protected id: string;\r\n protected key: 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 pricing: {\r\n [country in CountryCode]?: TieredPriceModel;\r\n };\r\n\r\n protected variants: VariantModel[];\r\n\r\n protected targetGender: GenderCategory;\r\n protected attributes: ProductSelectionAttributes;\r\n protected specifications: LocalizedValue<ProductSpecification>;\r\n protected categories: string[];\r\n\r\n // Metadata\r\n protected isActive: boolean;\r\n\r\n protected searchTags: LocalizedValue<string[]>;\r\n\r\n static productKeyRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n static productSKURegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n\r\n /**\r\n * Generates a unique key for checking uniqueness for a given selection attributes.\r\n * Excludes 'size' from the key generation.\r\n * @param selectionAttributes - The selection attributes.\r\n * @returns A string key representing the unique attribute combination.\r\n */\r\n static generateSelectionAttributesKey(selectionAttributes: SelectionAttributes): string {\r\n if (typeof selectionAttributes !== 'object') {\r\n throw new SelectionAttributeParseError('Selection attributes must be an object');\r\n }\r\n\r\n const sortedKeys = Object.keys(selectionAttributes)\r\n .filter(key => selectionAttributes[key] !== undefined && key.toLowerCase() !== 'size')\r\n .sort()\r\n\r\n return sortedKeys.map(key => {\r\n if ((selectionAttributes[key] as Color).name) {\r\n return `${key}:c+${(selectionAttributes[key] as Color).name}`;\r\n }\r\n return `${key}:${selectionAttributes[key]}`;\r\n }).join('|').toLowerCase();\r\n }\r\n\r\n /**\r\n * Parses a selection attributes key into an object.\r\n * @param key - The selection attributes key to parse.\r\n * @returns An object containing the parsed selection attributes.\r\n */\r\n static parseSelectionAttributesKey(key: string): SelectionAttributes {\r\n try {\r\n const attributes: SelectionAttributes = {} as unknown as SelectionAttributes;\r\n const parts = key.split('|');\r\n for (const part of parts) {\r\n const [key, value] = part.split(':');\r\n if (value.startsWith('c+')) {\r\n attributes[key] = { name: value.slice(2) } as Color;\r\n } else {\r\n attributes[key] = value;\r\n }\r\n }\r\n return attributes;\r\n } catch (error: any) {\r\n throw new SelectionAttributeParseError(error?.message);\r\n }\r\n }\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\r\n this.id = data.id;\r\n this.key = data.key;\r\n\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.pricing = (Object.keys(data.pricing) as CountryCode[]).reduce((acc, country) => {\r\n if (data.pricing[country]) {\r\n acc[country] = new TieredPriceModel(data.pricing[country]);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: TieredPriceModel });\r\n\r\n this.targetGender = data.targetGender;\r\n this.attributes = Utils.deepClone(data.attributes);\r\n this.specifications = Utils.deepClone(data.specifications);\r\n this.categories = Utils.deepClone(data.categories);\r\n\r\n const uniqueSelectionAttributes = new Set<string>();\r\n this.variants = (data.variants || []).map(variant => {\r\n if (!variant.selectionAttributes || typeof variant.selectionAttributes !== 'object') {\r\n throw new SelectionAttributeParseError('Selection attributes are required');\r\n }\r\n\r\n this.checkSelectionAttributes(variant.selectionAttributes);\r\n const key = ProductModel.generateSelectionAttributesKey(variant.selectionAttributes);\r\n if (uniqueSelectionAttributes.has(key)) {\r\n throw new DuplicateSelectionAttributeError(key);\r\n }\r\n uniqueSelectionAttributes.add(key);\r\n return {\r\n sku: variant.sku,\r\n selectionAttributes: variant.selectionAttributes,\r\n images: {\r\n primary: new ImageInfoModel(variant.images.primary),\r\n gallery: (variant.images.gallery || []).map(image => new ImageInfoModel(image))\r\n }\r\n };\r\n });\r\n\r\n this.isActive = data.isActive;\r\n this.searchTags = data.searchTags ? Utils.deepClone(data.searchTags) : { en: [] };\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 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 Utils.deepClone(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 Utils.deepClone(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 Utils.deepClone(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 tiered price details for the product.\r\n * @returns Pricing details mapped by country.\r\n */\r\n getPriceDetails(): { [country in CountryCode]?: TieredPriceModel }\r\n /**\r\n * Gets the tiered price details for a specific country.\r\n * @param country - The country code.\r\n * @returns The tiered price model for the country, or null if not found.\r\n */\r\n getPriceDetails(country: CountryCode): TieredPriceModel | null\r\n getPriceDetails(country?: CountryCode): { [country in CountryCode]?: TieredPriceModel } | TieredPriceModel | null {\r\n if (country) {\r\n return this.pricing[country] ?? null;\r\n }\r\n return { ...this.pricing };\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(): ProductSelectionAttributes {\r\n return Utils.deepClone(this.attributes);\r\n }\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 getVariants(): VariantModel[] {\r\n return this.variants.map(variant => ({\r\n sku: variant.sku,\r\n selectionAttributes: Utils.deepClone(variant.selectionAttributes),\r\n images: {\r\n primary: variant.images.primary,\r\n gallery: [...variant.images.gallery]\r\n }\r\n }));\r\n }\r\n\r\n /**\r\n * Gets the images for a specific selection attribute combination.\r\n * @param selectionAttributes - The selection attributes to search for.\r\n * @returns The matching image set or null if not found.\r\n */\r\n private getImagesBySelectionAttributes(selectionAttributes: SelectionAttributes): { primary: ImageInfoModel; gallery: ImageInfoModel[] } | null {\r\n const searchKey = ProductModel.generateSelectionAttributesKey(selectionAttributes);\r\n\r\n const match = this.variants.find(variant =>\r\n ProductModel.generateSelectionAttributesKey(variant.selectionAttributes) === searchKey\r\n );\r\n\r\n return match ? {\r\n primary: match.images.primary,\r\n gallery: [...match.images.gallery]\r\n } : null;\r\n }\r\n\r\n /**\r\n * Gets the images for a specific selection attribute combination.\r\n * @param selectionAttributes - The selection attributes to search for.\r\n * @returns The matching image set or null if not found.\r\n */\r\n getImages(selectionAttributes: SelectionAttributes): { primary: ImageInfoModel; gallery: ImageInfoModel[] }\r\n getImages(selectionAttributes: SelectionAttributes, category: ImageCategory.PRIMARY): ImageInfoModel\r\n getImages(selectionAttributes: SelectionAttributes, category: ImageCategory.GALLERY): ImageInfoModel[]\r\n getImages(selectionAttributes: SelectionAttributes, category?: ImageCategory): { primary: ImageInfoModel; gallery: ImageInfoModel[] } | ImageInfoModel | ImageInfoModel[] {\r\n switch (category) {\r\n case ImageCategory.PRIMARY:\r\n return this.getImagesBySelectionAttributes(selectionAttributes)?.primary ?? this.variants[0]?.images?.primary;\r\n case ImageCategory.GALLERY:\r\n return this.getImagesBySelectionAttributes(selectionAttributes)?.gallery ?? [];\r\n default:\r\n return this.getImagesBySelectionAttributes(selectionAttributes) ?? { primary: this.variants[0]?.images?.primary, gallery: [] };\r\n }\r\n }\r\n\r\n\r\n /**\r\n * Checks if the product 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 Utils.deepClone(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(): LocalizedValue<ProductSpecification>\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\r\n getSpecifications(locale?: LocaleCode): LocalizedValue<ProductSpecification> | ProductSpecification {\r\n if (locale) {\r\n return Utils.deepClone(this.specifications[locale] ?? this.specifications[LocaleLanguageMap[locale]] ?? this.specifications.en);\r\n } else {\r\n return Utils.deepClone(this.specifications);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the localized list of search tags. Returns a copy.\r\n * @returns Localized array of search tags.\r\n */\r\n getSearchTags(): LocalizedValue<string[]>\r\n /**\r\n * Gets the search tags for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The array of search tags for the specified locale, or undefined if not found.\r\n */\r\n getSearchTags(locale: LocaleCode): string[]\r\n getSearchTags(locale?: LocaleCode): LocalizedValue<string[]> | string[] {\r\n if (locale) {\r\n return Utils.deepClone(this.searchTags[locale] ?? this.searchTags[LocaleLanguageMap[locale]] ?? this.searchTags.en);\r\n } else {\r\n return Utils.deepClone(this.searchTags);\r\n }\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 name: this.getName(),\r\n description: this.getDescription(),\r\n slug: this.getSlug(),\r\n brand: this.getBrand(),\r\n pricing: (Object.keys(this.pricing) as CountryCode[]).reduce((acc, country) => {\r\n if (this.pricing[country]) {\r\n acc[country] = this.pricing[country]?.getDetails();\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]: TieredPriceData }),\r\n attributes: this.getAttributes(),\r\n variants: this.variants.map(v => ({\r\n sku: v.sku,\r\n selectionAttributes: Utils.deepClone(v.selectionAttributes),\r\n images: {\r\n primary: v.images.primary.getDetails(),\r\n gallery: v.images.gallery.map(img => img.getDetails())\r\n }\r\n })),\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 * Checks if the provided selection attributes are valid for the product.\r\n * @param selectionAttributes The selection attributes to validate.\r\n * @throws {SelectionAttributeParseError} If the selection attributes are invalid.\r\n */\r\n checkSelectionAttributes(selectionAttributes: SelectionAttributes): void {\r\n if (!selectionAttributes || typeof selectionAttributes !== 'object') {\r\n throw new SelectionAttributeParseError('Selection attributes are required');\r\n }\r\n\r\n Object.keys(this.attributes).forEach(key => {\r\n if(key.toLowerCase() === 'size') return;\r\n \r\n const allowedAttributeValues = this.attributes[key];\r\n const providedValue = selectionAttributes[key];\r\n\r\n if (providedValue === undefined) {\r\n throw new SelectionAttributeParseError(`Selection attribute '${key}' is missing`);\r\n }\r\n\r\n if (typeof allowedAttributeValues === 'string') {\r\n if (typeof providedValue !== 'string' || allowedAttributeValues !== providedValue) {\r\n throw new SelectionAttributeParseError(`Selection attribute '${key}' is invalid`);\r\n }\r\n } else if (Array.isArray(allowedAttributeValues)) {\r\n if (allowedAttributeValues.length > 0 && typeof allowedAttributeValues[0] === 'string') {\r\n if (typeof providedValue !== 'string' || !(allowedAttributeValues as string[]).includes(providedValue)) {\r\n throw new SelectionAttributeParseError(`Selection attribute '${key}' is invalid`);\r\n }\r\n } else {\r\n // Color validation\r\n if (\r\n typeof providedValue !== 'object' ||\r\n !('name' in providedValue) ||\r\n (allowedAttributeValues as Color[]).findIndex(c => c.name === (providedValue as Color).name) < 0\r\n ) {\r\n throw new SelectionAttributeParseError(`Selection attribute '${key}' is invalid`);\r\n }\r\n }\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Validates if the provided selection attributes exist for this product.\r\n * @param selectionAttributes - The attributes to validate.\r\n * @returns True if a valid selection attribute exists, false otherwise.\r\n */\r\n validateSelectionAttribute(selectionAttributes: SelectionAttributes): boolean {\r\n const searchKey = ProductModel.generateSelectionAttributesKey(selectionAttributes);\r\n\r\n return this.variants.some(variant => ProductModel.generateSelectionAttributesKey(variant.selectionAttributes) === searchKey);\r\n }\r\n\r\n /**\r\n * Validates if a specific size is available for this product.\r\n * @param size - The size to check.\r\n * @returns True if the size exists in the product's attributes, false otherwise.\r\n */\r\n validateSize(size: string): boolean {\r\n return this.attributes.size.includes(size);\r\n }\r\n}\r\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$2}from'./chunk-SOZHGHMY.mjs';import {a as a$3}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a as a$2}from'./chunk-SOZHGHMY.mjs';import {a as a$3}from'./chunk-QGIQ3MH6.mjs';import {a as a$1}from'./chunk-LI5JQ6UC.mjs';import {e}from'./chunk-QK4XJ3GB.mjs';import {w,k,x}from'./chunk-R5DM7WCD.mjs';import {a}from'./chunk-UXZBULDS.mjs';var I=class extends a{id;name;type;category;impact;pricing;lineItemId;total;constructor(t){if(super(t),this.id=t.id,this.name=t.name,this.type=t.type,this.category=t.category,this.impact=t.impact,this.lineItemId=t.lineItemId,this.pricing={baseChargeAmount:new a$1(t.pricing.baseChargeAmount),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(e=>new a$2(e))},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new w("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={chargeAmount:new a$1(t.total.chargeAmount),discountTotal:new a$1(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([e,a])=>[e,new a$1(a)])),netChargeAmount:new a$1(t.total.netChargeAmount),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([e,a])=>[e,{rate:a.rate,taxableAmount:new a$1(a.taxableAmount),taxAmount:new a$1(a.taxAmount),system:a.system,subSystem:a.subSystem}])),taxTotal:new a$1(t.total.taxTotal),grandTotal:new a$1(t.total.grandTotal)};}getId(){return this.id}getName(t){return t?a$3.deepClone(this.name[t]??this.name[e[t]]??this.name.en):a$3.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getPricing(){return {baseChargeAmount:this.pricing.baseChargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {chargeAmount:this.total.chargeAmount,discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},netChargeAmount:this.total.netChargeAmount,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableAmount:e.taxableAmount,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(t){if(this.type==="ADJUSTMENT"&&t.length>0)throw new w("Adjustment charges cannot apply tax rules.");t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new k}),this.validateTaxRules(t),this.pricing.applicableTaxRule=t,this.calculateTotals();}validateTaxRules(t){if(this.impact==="SUBTRACT"&&t.some(a=>a.getRate()>0))throw new x("Subtractive charges cannot have positive tax rates.");let e=new Set;for(let a=0;a<t.length;a++){let g=t[a].getTaxRuleId();if(e.has(g))throw new x("Duplicate tax rule ID found: "+g);e.add(g);for(let T=a+1;T<t.length;T++){let u=t[a],s=t[T],d=u.getMinPrice(),p=u.getMaxPrice(),n=u.getExcludeMin(),m=u.getExcludeMax(),b=s.getMinPrice(),l=s.getMaxPrice(),h=s.getExcludeMin(),A=s.getExcludeMax(),r=(()=>{if(!p)return !1;let c=p.compareTo(b);return c<0||c===0&&(m||h)})(),i=(()=>{if(!l)return !1;let c=l.compareTo(d);return c<0||c===0&&(A||n)})();if(!(r||i)&&!(d.compareTo(b)===0&&n===h&&m===A&&(!p&&!l||p&&l&&p.compareTo(l)===0)))throw new x(`Overlapping rules found: [${u.getTaxRuleId()}: ${n?"(":"["}${d.getAmount()}-${p?.getAmount()??"Infinity"}${m?")":"]"}] and [${s.getTaxRuleId()}: ${h?"(":"["}${b.getAmount()}-${l?.getAmount()??"Infinity"}${A?")":"]"}]`)}}}updateDiscounts(t){let e={};t.forEach(a=>{e[a.coupon.getCode()]=a.amount;}),this.total.discountBreakdown=e,this.calculateTotals();}calculateTotals(){let t=this.pricing.baseChargeAmount.zero(),e=this.pricing.baseChargeAmount,a=Object.values(this.total.discountBreakdown).reduce((r,i)=>r.add(i),t),g=e.subtract(a),T={},u=this.pricing.applicableTaxRule.reduce((r,i)=>r+i.getApplicableTaxRate(g),0);if(u<=0){this.total={chargeAmount:e,discountTotal:a,discountBreakdown:this.total.discountBreakdown,netChargeAmount:g,taxTotal:t,taxBreakdown:{},grandTotal:g};return}let s=e.getCurrency(),d=e.getAmount(),p=1e3,n=a$1.getRoundedAmount(d/(1+u),s),m=n,b=Number.POSITIVE_INFINITY;for(let r=0;r<p;r++){let i=new a$1({amount:n,currency:s}),c=this.pricing.applicableTaxRule.sort((x,C)=>C.getApplicableTaxRate(i)-x.getApplicableTaxRate(i)).map(x=>a$1.getRoundedAmount(n*x.getApplicableTaxRate(i),s)).reduce((x,C)=>x+C,0),y=n+c-d,k=this.pricing.applicableTaxRule.reduce((x,C)=>x+C.getApplicableTaxRate(i),0);if(Math.abs(y)<Math.abs(b)&&(b=y,m=n),y===0||(n=n-y/(1+k),n<0||n>d))break}let l=new a$1({amount:m,currency:s}),h=t;this.pricing.applicableTaxRule.sort((r,i)=>i.getApplicableTaxRate(l)-r.getApplicableTaxRate(l)).forEach(r=>{let i=r.getApplicableTaxRate(l),f=a$1.getRoundedAmount(m*i,s),c=new a$1({amount:f,currency:s});T[r.getTaxRuleId()]={rate:i,taxableAmount:l,taxAmount:c,system:r.getTaxSystem(),subSystem:r.getTaxSubSystem()},h=h.add(c);});let A=g;this.total={chargeAmount:e,discountTotal:a,discountBreakdown:this.total.discountBreakdown,netChargeAmount:g,taxBreakdown:T,taxTotal:h,grandTotal:A};}getDetails(){return {id:this.id,name:a$3.deepClone(this.name),type:this.type,category:this.category,pricing:{baseChargeAmount:this.pricing.baseChargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(e=>e.getDetails())},impact:this.impact,lineItemId:this.lineItemId,total:{chargeAmount:this.total.chargeAmount.getDetails(),discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([e,a])=>[e,a.getDetails()])),netChargeAmount:this.total.netChargeAmount.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,a])=>[e,{rate:a.rate,taxableAmount:a.taxableAmount.getDetails(),taxAmount:a.taxAmount.getDetails(),system:a.system,subSystem:a.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};export{I as a};//# sourceMappingURL=chunk-XJPFHEW3.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-XJPFHEW3.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/Charge.ts"],"names":["ChargeModel","CustomFieldModel","data","PriceModel","r","TaxRuleModel","InvalidChargeError","discountId","discount","taxRuleId","taxBreakdown","locale","Utils_default","LocaleLanguageMap","key","value","taxRules","taxRule","InvalidTaxRuleError","InvalidChargeTaxRuleError","uniqueTaxRule","i","currentTaxRuleId","j","r1","r2","r1Min","r1Max","r1ExcludeMin","r1ExcludeMax","r2Min","r2Max","r2ExcludeMin","r2ExcludeMax","r1EndsBeforeR2Starts","compare","r2EndsBeforeR1Starts","appliedDiscounts","chargeDiscounts","zero","baseChargeAmount","totalDiscount","sum","s","netChargeAmount","totalRate","currency","grossValue","maxIterations","baseValue","bestBaseValue","bestDiff","currentTaxableBase","taxSum","a","b","rule","v","diff","currentTotalRate","taxableBase","distributedTax","rate","taxAmountValue","taxAmount","grandTotal","k"],"mappings":"uPA4FA,IAAqBA,CAArB,CAAA,cAAyCC,CAAiB,CAC/C,EACA,CAAA,IAAA,CACA,IACA,CAAA,QAAA,CACA,MACA,CAAA,OAAA,CACA,UACA,CAAA,KAAA,CAEV,YAAYC,CAAwB,CAAA,CAenC,GAdA,KAAA,CAAMA,CAAI,CAAA,CACV,IAAK,CAAA,EAAA,CAAKA,CAAK,CAAA,EAAA,CACf,IAAK,CAAA,IAAA,CAAOA,CAAK,CAAA,IAAA,CACjB,IAAK,CAAA,IAAA,CAAOA,EAAK,IACjB,CAAA,IAAA,CAAK,QAAWA,CAAAA,CAAAA,CAAK,QACrB,CAAA,IAAA,CAAK,MAASA,CAAAA,CAAAA,CAAK,MACnB,CAAA,IAAA,CAAK,UAAaA,CAA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AAC,IAAM,CAACS,CAAAA,CAAG,CAC5F,IAAA,CAAMT,CAAE,CAAA,IAAA,CACR,aAAeA,CAAAA,CAAAA,CAAE,cAAc,UAAW,EAAA,CAC1C,SAAWA,CAAAA,CAAAA,CAAE,SAAU,CAAA,UAAA,EACvB,CAAA,MAAA,CAAQA,CAAE,CAAA,MAAA,CACV,SAAWA,CAAAA,CAAAA,CAAE,SACd,CAAC,CAAC,CAAC,EACH,QAAU,CAAA,IAAA,CAAK,KAAM,CAAA,QAAA,CAAS,UAAW,EAAA,CACzC,UAAY,CAAA,IAAA,CAAK,MAAM,UAAW,CAAA,UAAA,EACnC,CAAA,CACA,YAAc,CAAA,IAAA,CAAK,kBAAmB,EACvC,CAED,CACD","file":"chunk-BSDPFVRK.mjs","sourcesContent":["import { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\nimport Utils from \"../Utils\";\r\nimport { LocaleCode, LocalizedString } from \"./Common\";\r\nimport { ChargeImpact, ChargeType, LocaleLanguageMap, TaxSystem } from \"./Enum\";\r\nimport { InvalidChargeTaxRuleError, InvalidChargeError, InvalidTaxRuleError } from \"./Error\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport { TaxRuleData, TaxRuleModel } from \"./TaxRule\";\r\nimport CouponModel from \"./Coupon\";\r\n\r\nexport type ChargePricing = {\r\n /** Tax-inclusive original charge amount before any discounts. Always non-negative. */\r\n baseChargeAmount: PriceData;\r\n /** Tax category of the charge. */\r\n taxCategory: string;\r\n /** Tax rules applicable to the charge. */\r\n applicableTaxRule: TaxRuleData[];\r\n};\r\n\r\nexport type ChargePricingModel = {\r\n /** Tax-inclusive original charge amount before any discounts. Always non-negative. */\r\n baseChargeAmount: PriceModel;\r\n /** Tax category of the charge. */\r\n taxCategory: string;\r\n /** Tax rules applicable to the charge. */\r\n applicableTaxRule: TaxRuleModel[];\r\n};\r\n\r\nexport type ChargeTaxBreakdown = {\r\n /** Tax rate: e.g., 0.09 for 9% */\r\n rate: number;\r\n /** Reverse-calculated pre-tax base from the netChargeAmount (post-discount) */\r\n taxableAmount: PriceData;\r\n /** Tax portion for this rule (netChargeAmount - taxableAmount) */\r\n taxAmount: PriceData;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type ChargeTaxBreakdownModel = {\r\n rate: number;\r\n taxableAmount: PriceModel;\r\n taxAmount: PriceModel;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type ChargeTotals = {\r\n /** Tax-inclusive original charge amount before discounts (copied from pricing) */\r\n chargeAmount: PriceData;\r\n /** Coupon code -> discount amount mapping */\r\n discountBreakdown: Record<string, PriceData>;\r\n /** Sum of all discounts */\r\n discountTotal: PriceData;\r\n /** chargeAmount - totalDiscount → final tax-inclusive payable amount after discounts */\r\n netChargeAmount: PriceData;\r\n /** Sum of all taxAmount values */\r\n taxTotal: PriceData;\r\n /** Tax breakdown per rule/category (reverse-calculated from netChargeAmount) */\r\n taxBreakdown: Record<string, ChargeTaxBreakdown>;\r\n /** Final payable/contribution amount. Equals netChargeAmount (tax-inclusive after discounts). */\r\n grandTotal: PriceData;\r\n};\r\n\r\nexport type ChargeTotalsModel = {\r\n chargeAmount: PriceModel;\r\n discountTotal: PriceModel;\r\n discountBreakdown: Record<string, PriceModel>;\r\n netChargeAmount: PriceModel;\r\n taxTotal: PriceModel;\r\n taxBreakdown: Record<string, ChargeTaxBreakdownModel>;\r\n grandTotal: PriceModel; // Equals netChargeAmount\r\n};\r\n\r\nexport type ChargeAttributes = CustomFieldAttributes & {\r\n id: string;\r\n name: LocalizedString;\r\n type: ChargeType;\r\n category: string;\r\n impact: ChargeImpact; // ADD or SUBTRACT\r\n pricing: ChargePricing;\r\n lineItemId?: string;\r\n total: ChargeTotals;\r\n};\r\n\r\nexport type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId'> & {\r\n\tlineItemId?: string;\r\n};\r\n\r\n/**\r\n * Represents an additional charge (or discount if amount is negative) in a shopping container.\r\n * Supports its own tax rules.\r\n */\r\nexport default class ChargeModel extends CustomFieldModel {\r\n\tprotected id: string;\r\n\tprotected name: LocalizedString;\r\n\tprotected type: ChargeType;\r\n\tprotected category: string;\r\n\tprotected impact: ChargeImpact;\r\n\tprotected pricing: ChargePricingModel;\r\n\tprotected lineItemId?: string;\r\n\tprotected total: ChargeTotalsModel;\r\n\r\n\tconstructor(data: ChargeAttributes) {\r\n\t\tsuper(data);\r\n\t\tthis.id = data.id;\r\n\t\tthis.name = data.name;\r\n\t\tthis.type = data.type;\r\n\t\tthis.category = data.category;\r\n\t\tthis.impact = data.impact;\r\n\t\tthis.lineItemId = data.lineItemId;\r\n\t\tthis.pricing = {\r\n\t\t\tbaseChargeAmount: new PriceModel(data.pricing.baseChargeAmount),\r\n\t\t\ttaxCategory: data.pricing.taxCategory,\r\n\t\t\tapplicableTaxRule: data.pricing.applicableTaxRule.map(r => new TaxRuleModel(r))\r\n\t\t};\r\n\r\n\t\tthis.validateTaxRules(this.pricing.applicableTaxRule);\r\n\t\tif(this.impact === ChargeImpact.SUBTRACT && this.type !== ChargeType.ADJUSTMENT) {\r\n\t\t\tthrow new InvalidChargeError('SUBTRACT impact is only allowed for ADJUSTMENT charge');\r\n\t\t}\r\n\r\n\t\tthis.total = {\r\n\t\t\tchargeAmount: new PriceModel(data.total.chargeAmount),\r\n\t\t\tdiscountTotal: new PriceModel(data.total.discountTotal),\r\n\t\t\tdiscountBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(data.total.discountBreakdown).map(([discountId, discount]) => [\r\n\t\t\t\t\tdiscountId,\r\n\t\t\t\t\tnew PriceModel(discount)\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\tnetChargeAmount: new PriceModel(data.total.netChargeAmount),\r\n\t\t\ttaxBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(data.total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n\t\t\t\t\ttaxRuleId,\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\trate: taxBreakdown.rate,\r\n\t\t\t\t\t\ttaxableAmount: new PriceModel(taxBreakdown.taxableAmount),\r\n\t\t\t\t\t\ttaxAmount: new PriceModel(taxBreakdown.taxAmount),\r\n\t\t\t\t\t\tsystem: taxBreakdown.system,\r\n\t\t\t\t\t\tsubSystem: taxBreakdown.subSystem\r\n\t\t\t\t\t}\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\ttaxTotal: new PriceModel(data.total.taxTotal),\r\n\t\t\tgrandTotal: new PriceModel(data.total.grandTotal),\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the unique identifier of the charge.\r\n\t * @returns \r\n\t */\r\n\tpublic getId(): string { return this.id; }\r\n\r\n\r\n\t/**\r\n\t * Gets the full localized product name object.\r\n\t * @returns A copy of the LocalizedString object for the name.\r\n\t */\r\n\tgetName(): LocalizedString\r\n\t/**\r\n\t * Gets the product name for a specific locale, falling back to English ('en').\r\n\t * @param locale - The desired locale code.\r\n\t * @returns The name string for the specified locale.\r\n\t */\r\n\tgetName(locale: LocaleCode): string\r\n\tgetName(locale?: LocaleCode): LocalizedString | string {\r\n\t\tif (locale) {\r\n\t\t\treturn Utils.deepClone(this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en);\r\n\t\t} else {\r\n\t\t\treturn Utils.deepClone(this.name);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the charge category.\r\n\t * @returns The category string.\r\n\t */\r\n\tpublic getCategory(): string { return this.category; }\r\n\r\n\t/**\r\n\t * Gets the charge type.\r\n\t * @returns The charge type enum value.\r\n\t */\r\n\tpublic getType(): ChargeType { return this.type; }\r\n\t/**\r\n\t * Gets the charge impact (add or subtract).\r\n\t * @returns The charge impact.\r\n\t */\r\n\tpublic getImpact(): ChargeImpact { return this.impact; }\r\n\r\n\t/**\r\n\t * Gets the related line item id, if any.\r\n\t * @returns The line item id or undefined.\r\n\t */\r\n\tpublic getLineItemId(): string | undefined { return this.lineItemId; }\r\n\r\n\t/**\r\n\t * Gets the pricing details (models) for this charge.\r\n\t * @returns Pricing details including price, tax category, and tax rules.\r\n\t */\r\n\tpublic getPricing(): ChargePricingModel {\r\n\t\treturn {\r\n\t\t\tbaseChargeAmount: this.pricing.baseChargeAmount,\r\n\t\t\ttaxCategory: this.pricing.taxCategory,\r\n\t\t\tapplicableTaxRule: [...this.pricing.applicableTaxRule]\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the computed totals for this charge.\r\n\t * @returns Totals including discounts, taxes, and grand total.\r\n\t */\r\n\tpublic getTotal(): ChargeTotalsModel {\r\n\t\treturn {\r\n\t\t\tchargeAmount: this.total.chargeAmount,\r\n\t\t\tdiscountTotal: this.total.discountTotal,\r\n\t\t\tdiscountBreakdown: { ...this.total.discountBreakdown },\r\n\t\t\tnetChargeAmount: this.total.netChargeAmount,\r\n\t\t\ttaxTotal: this.total.taxTotal,\r\n\t\t\ttaxBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(this.total.taxBreakdown).map(([key, value]) => [\r\n\t\t\t\t\tkey,\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\trate: value.rate,\r\n\t\t\t\t\t\ttaxableAmount: value.taxableAmount,\r\n\t\t\t\t\t\ttaxAmount: value.taxAmount,\r\n\t\t\t\t\t\tsystem: value.system,\r\n\t\t\t\t\t\tsubSystem: value.subSystem\r\n\t\t\t\t\t}\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\tgrandTotal: this.total.grandTotal,\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the applicable tax rules for this charge.\r\n\t * @returns A list of tax rules.\r\n\t */\r\n\tpublic getApplicableTaxRules(): TaxRuleModel[] {\r\n\t\treturn [...this.pricing.applicableTaxRule];\r\n\t}\r\n\r\n\t/**\r\n\t * Updates the tax rule for this line item and recalculates totals.\r\n\t * @param taxRule - The new tax rule to apply.\r\n\t * @throws {Error} If the tax rule category does not match the item's tax category.\r\n\t */\r\n\tpublic updateTax(taxRules: TaxRuleModel[]): void {\r\n\t\tif (this.type === ChargeType.ADJUSTMENT && taxRules.length > 0) {\r\n\t\t\tthrow new InvalidChargeError(\"Adjustment charges cannot apply tax rules.\");\r\n\t\t}\r\n\t\ttaxRules.forEach(taxRule => {\r\n\t\t\tif (!taxRule.appliesTo(this.pricing.taxCategory, taxRule.getCountry())) {\r\n\t\t\t\tthrow new InvalidTaxRuleError();\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\t// Remove the old taxableUnitPrice calculation - no longer needed\r\n\t\tthis.validateTaxRules(taxRules);\r\n\t\tthis.pricing.applicableTaxRule = taxRules;\r\n\t\tthis.calculateTotals();\r\n\t}\r\n\r\n\t/**\r\n\t * Validates that there are no overlapping price brackets for any tax rules within the charge.\r\n\t * @param taxRules - The list of tax rules to validate.\r\n\t * @throws {InvalidChargeTaxRuleError} If any rules have positive tax rates with SUBTRACT impact or if duplicate rule IDs are found.\r\n\t * @throws {InvalidChargeTaxRuleError} Duplicate tax rule IDs will results in error.\r\n\t * @throws {CoincidingTaxBracketError} If any overlapping rules are found.\r\n\t */\r\n\tprivate validateTaxRules(taxRules: TaxRuleModel[]): void {\r\n\t\tif(this.impact === ChargeImpact.SUBTRACT) {\r\n\t\t\tif(taxRules.some(taxRule => taxRule.getRate() > 0)) {\r\n\t\t\t\tthrow new InvalidChargeTaxRuleError(\"Subtractive charges cannot have positive tax rates.\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst uniqueTaxRule = new Set();\r\n\t\tfor (let i = 0; i < taxRules.length; i++) {\r\n\t\t\tconst currentTaxRuleId = taxRules[i].getTaxRuleId();\r\n\t\t\tif(uniqueTaxRule.has(currentTaxRuleId)){\r\n\t\t\t\tthrow new InvalidChargeTaxRuleError(\"Duplicate tax rule ID found: \" + currentTaxRuleId);\r\n\t\t\t} else {\r\n\t\t\t\tuniqueTaxRule.add(currentTaxRuleId);\r\n\t\t\t}\r\n\r\n\t\t\tfor (let j = i + 1; j < taxRules.length; j++) {\r\n\t\t\t\tconst r1 = taxRules[i];\r\n\t\t\t\tconst r2 = taxRules[j];\r\n\r\n\t\t\t\tconst r1Min = r1.getMinPrice();\r\n\t\t\t\tconst r1Max = r1.getMaxPrice();\r\n\t\t\t\tconst r1ExcludeMin = r1.getExcludeMin();\r\n\t\t\t\tconst r1ExcludeMax = r1.getExcludeMax();\r\n\t\t\t\tconst r2Min = r2.getMinPrice();\r\n\t\t\t\tconst r2Max = r2.getMaxPrice();\r\n\t\t\t\tconst r2ExcludeMin = r2.getExcludeMin();\r\n\t\t\t\tconst r2ExcludeMax = r2.getExcludeMax();\r\n\r\n\t\t\t\t// Two ranges are disjoint if one ends strictly before the other starts.\r\n\t\t\t\t// If they only touch at one point, disjoint only when either side excludes that point.\r\n\t\t\t\tconst r1EndsBeforeR2Starts = (() => {\r\n\t\t\t\t\tif (!r1Max) return false;\r\n\t\t\t\t\tconst compare = r1Max.compareTo(r2Min);\r\n\t\t\t\t\treturn compare < 0 || (compare === 0 && (r1ExcludeMax || r2ExcludeMin));\r\n\t\t\t\t})();\r\n\t\t\t\tconst r2EndsBeforeR1Starts = (() => {\r\n\t\t\t\t\tif (!r2Max) return false;\r\n\t\t\t\t\tconst compare = r2Max.compareTo(r1Min);\r\n\t\t\t\t\treturn compare < 0 || (compare === 0 && (r2ExcludeMax || r1ExcludeMin));\r\n\t\t\t\t})();\r\n\t\t\t\tconst overlap = !(r1EndsBeforeR2Starts || r2EndsBeforeR1Starts);\r\n\r\n\t\t\t\tif (overlap) {\r\n\t\t\t\t\t// Exception: Allow overlapping rules if they have the exact same price bracket (slab)\r\n\t\t\t\t\tconst sameSlab = r1Min.compareTo(r2Min) === 0 &&\r\n\t\t\t\t\t\tr1ExcludeMin === r2ExcludeMin &&\r\n\t\t\t\t\t\tr1ExcludeMax === r2ExcludeMax &&\r\n\t\t\t\t\t\t((!r1Max && !r2Max) || (r1Max && r2Max && r1Max.compareTo(r2Max) === 0));\r\n\r\n\t\t\t\t\tif (!sameSlab) {\r\n\t\t\t\t\t\tthrow new InvalidChargeTaxRuleError(\r\n\t\t\t\t\t\t\t`Overlapping rules found: [${r1.getTaxRuleId()}: ${r1ExcludeMin ? \"(\" : \"[\"}${r1Min.getAmount()}-${r1Max?.getAmount() ?? \"Infinity\"}${r1ExcludeMax ? \")\" : \"]\"}] and [${r2.getTaxRuleId()}: ${r2ExcludeMin ? \"(\" : \"[\"}${r2Min.getAmount()}-${r2Max?.getAmount() ?? \"Infinity\"}${r2ExcludeMax ? \")\" : \"]\"}]`\r\n\t\t\t\t\t\t);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t\t* Updates the discounts applied to this line item and recalculates totals.\r\n\t\t* @param appliedDiscounts - List of coupons and their allocated discount amounts.\r\n\t*/\r\n\tpublic updateDiscounts(appliedDiscounts: { coupon: CouponModel, amount: PriceModel }[]): void {\r\n\t\tlet chargeDiscounts = {} as Record<string, PriceModel>;\r\n\t\tappliedDiscounts.forEach(discount => {\r\n\t\t\tchargeDiscounts[discount.coupon.getCode()] = discount.amount;\r\n\t\t});\r\n\r\n\t\tthis.total.discountBreakdown = chargeDiscounts;\r\n\t\tthis.calculateTotals();\r\n\t}\r\n\r\n\t/**\r\n\t * Recalculates totals for this charge based on pricing and discounts.\r\n\t */\r\n\tpublic calculateTotals(): void {\r\n\t\tconst zero = this.pricing.baseChargeAmount.zero();\r\n\t\tconst baseChargeAmount = this.pricing.baseChargeAmount;\r\n\r\n\t\tconst totalDiscount = Object.values(this.total.discountBreakdown).reduce((sum, s) => sum.add(s), zero);\r\n\t\tconst netChargeAmount = baseChargeAmount.subtract(totalDiscount);\r\n\r\n\t\tconst taxBreakdown: Record<string, ChargeTaxBreakdownModel> = {};\r\n\r\n\t\t// 1. Calculate total rate for inclusive back-calculation\r\n\t\tconst totalRate = this.pricing.applicableTaxRule.reduce((sum, r) => sum + r.getApplicableTaxRate(netChargeAmount), 0);\r\n\r\n\t\tif (totalRate <= 0) {\r\n\t\t\tthis.total = {\r\n\t\t\t\tchargeAmount: baseChargeAmount,\r\n\t\t\t\tdiscountTotal: totalDiscount,\r\n\t\t\t\tdiscountBreakdown: this.total.discountBreakdown,\r\n\t\t\t\tnetChargeAmount: netChargeAmount,\r\n\t\t\t\ttaxTotal: zero,\r\n\t\t\t\ttaxBreakdown: {},\r\n\t\t\t\tgrandTotal: netChargeAmount\r\n\t\t\t};\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// 2. Iteratively find a taxable base so that base + sum(rounded taxes) == gross\r\n\t\tconst currency = baseChargeAmount.getCurrency();\r\n\t\tconst grossValue = baseChargeAmount.getAmount();\r\n\t\tconst maxIterations = 1000;\r\n\r\n\t\tlet baseValue = PriceModel.getRoundedAmount(grossValue / (1 + totalRate), currency);\r\n\t\tlet bestBaseValue = baseValue;\r\n\t\tlet bestDiff = Number.POSITIVE_INFINITY;\r\n\r\n\t\tfor (let i = 0; i < maxIterations; i++) {\r\n\t\t\tconst currentTaxableBase = new PriceModel({ amount: baseValue, currency });\r\n\t\t\tconst taxes = this.pricing.applicableTaxRule\r\n\t\t\t\t.sort((a, b) => b.getApplicableTaxRate(currentTaxableBase) - a.getApplicableTaxRate(currentTaxableBase))\r\n\t\t\t\t.map(rule =>\r\n\t\t\t\t\tPriceModel.getRoundedAmount(baseValue * rule.getApplicableTaxRate(currentTaxableBase), currency)\r\n\t\t\t\t);\r\n\r\n\t\t\tconst taxSum = taxes.reduce((sum, v) => sum + v, 0);\r\n\t\t\tconst diff = (baseValue + taxSum) - grossValue;\r\n\r\n\t\t\tconst currentTotalRate = this.pricing.applicableTaxRule.reduce((sum, r) => sum + r.getApplicableTaxRate(currentTaxableBase), 0);\r\n\r\n\t\t\tif (Math.abs(diff) < Math.abs(bestDiff)) {\r\n\t\t\t\tbestDiff = diff;\r\n\t\t\t\tbestBaseValue = baseValue;\r\n\t\t\t}\r\n\r\n\t\t\tif (diff === 0) break;\r\n\t\t\tbaseValue = baseValue - diff / (1 + currentTotalRate); // Adjust base value based on the difference\r\n\t\t\tif (baseValue < 0 || baseValue > grossValue) break;\r\n\t\t}\r\n\r\n\t\tconst taxableBase = new PriceModel({ amount: bestBaseValue, currency });\r\n\r\n\t\t// 3. Compute tax amounts per rule based on final taxable base\r\n\t\tlet distributedTax = zero;\r\n\t\tthis.pricing.applicableTaxRule\r\n\t\t\t.sort((a, b) => b.getApplicableTaxRate(taxableBase) - a.getApplicableTaxRate(taxableBase))\r\n\t\t\t.forEach((taxRule) => {\r\n\t\t\t\tconst rate = taxRule.getApplicableTaxRate(taxableBase);\r\n\t\t\t\tconst taxAmountValue = PriceModel.getRoundedAmount(bestBaseValue * rate, currency);\r\n\t\t\t\tconst taxAmount = new PriceModel({ amount: taxAmountValue, currency });\r\n\r\n\t\t\t\ttaxBreakdown[taxRule.getTaxRuleId()] = {\r\n\t\t\t\t\trate: rate,\r\n\t\t\t\t\ttaxableAmount: taxableBase,\r\n\t\t\t\t\ttaxAmount: taxAmount,\r\n\t\t\t\t\tsystem: taxRule.getTaxSystem(),\r\n\t\t\t\t\tsubSystem: taxRule.getTaxSubSystem()\r\n\t\t\t\t};\r\n\t\t\t\tdistributedTax = distributedTax.add(taxAmount);\r\n\t\t\t});\r\n\r\n\t\tconst grandTotal = netChargeAmount;\r\n\t\tthis.total = {\r\n\t\t\tchargeAmount: baseChargeAmount,\r\n\t\t\tdiscountTotal: totalDiscount,\r\n\t\t\tdiscountBreakdown: this.total.discountBreakdown,\r\n\t\t\tnetChargeAmount: netChargeAmount,\r\n\t\t\ttaxBreakdown: taxBreakdown,\r\n\t\t\ttaxTotal: distributedTax,\r\n\t\t\tgrandTotal: grandTotal\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets a plain data object representing this charge.\r\n\t * @returns ChargeData for serialization.\r\n\t */\r\n\tpublic getDetails(): ChargeData {\r\n\t\tconst details: ChargeData = {\r\n\t\t\tid: this.id,\r\n\t\t\tname: Utils.deepClone(this.name),\r\n\t\t\ttype: this.type,\r\n\t\t\tcategory: this.category,\r\n\t\t\tpricing: {\r\n\t\t\t\tbaseChargeAmount: this.pricing.baseChargeAmount.getDetails(),\r\n\t\t\t\ttaxCategory: this.pricing.taxCategory,\r\n\t\t\t\tapplicableTaxRule: this.pricing.applicableTaxRule.map(r => r.getDetails())\r\n\t\t\t},\r\n\t\t\timpact: this.impact,\r\n\t\t\tlineItemId: this.lineItemId,\r\n\t\t\ttotal: {\r\n\t\t\t\tchargeAmount: this.total.chargeAmount.getDetails(),\r\n\t\t\t\tdiscountTotal: this.total.discountTotal.getDetails(),\r\n\t\t\t\tdiscountBreakdown: Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([k, v]) => [k, v.getDetails()])),\r\n\t\t\t\tnetChargeAmount: this.total.netChargeAmount.getDetails(),\r\n\t\t\t\ttaxBreakdown: Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([k, v]) => [k, {\r\n\t\t\t\t\trate: v.rate,\r\n\t\t\t\t\ttaxableAmount: v.taxableAmount.getDetails(),\r\n\t\t\t\t\ttaxAmount: v.taxAmount.getDetails(),\r\n\t\t\t\t\tsystem: v.system,\r\n\t\t\t\t\tsubSystem: v.subSystem\r\n\t\t\t\t}])),\r\n\t\t\t\ttaxTotal: this.total.taxTotal.getDetails(),\r\n\t\t\t\tgrandTotal: this.total.grandTotal.getDetails()\r\n\t\t\t},\r\n\t\t\tcustomFields: this.getAllCustomFields()\r\n\t\t};\r\n\t\treturn details;\r\n\t}\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/Classes/Charge.ts"],"names":["ChargeModel","CustomFieldModel","data","PriceModel","r","TaxRuleModel","InvalidChargeError","discountId","discount","taxRuleId","taxBreakdown","locale","Utils_default","LocaleLanguageMap","key","value","taxRules","taxRule","InvalidTaxRuleError","InvalidChargeTaxRuleError","uniqueTaxRule","i","currentTaxRuleId","j","r1","r2","r1Min","r1Max","r1ExcludeMin","r1ExcludeMax","r2Min","r2Max","r2ExcludeMin","r2ExcludeMax","r1EndsBeforeR2Starts","compare","r2EndsBeforeR1Starts","appliedDiscounts","chargeDiscounts","zero","baseChargeAmount","totalDiscount","sum","s","netChargeAmount","totalRate","currency","grossValue","maxIterations","baseValue","bestBaseValue","bestDiff","currentTaxableBase","taxSum","a","b","rule","v","diff","currentTotalRate","taxableBase","distributedTax","rate","taxAmountValue","taxAmount","grandTotal","k"],"mappings":"uPA4FA,IAAqBA,CAArB,CAAA,cAAyCC,CAAiB,CAC/C,EACA,CAAA,IAAA,CACA,IACA,CAAA,QAAA,CACA,MACA,CAAA,OAAA,CACA,UACA,CAAA,KAAA,CAEV,YAAYC,CAAwB,CAAA,CAenC,GAdA,KAAA,CAAMA,CAAI,CAAA,CACV,IAAK,CAAA,EAAA,CAAKA,CAAK,CAAA,EAAA,CACf,IAAK,CAAA,IAAA,CAAOA,CAAK,CAAA,IAAA,CACjB,IAAK,CAAA,IAAA,CAAOA,EAAK,IACjB,CAAA,IAAA,CAAK,QAAWA,CAAAA,CAAAA,CAAK,QACrB,CAAA,IAAA,CAAK,MAASA,CAAAA,CAAAA,CAAK,MACnB,CAAA,IAAA,CAAK,UAAaA,CAAAA,CAAAA,CAAK,UACvB,CAAA,IAAA,CAAK,OAAU,CAAA,CACd,iBAAkB,IAAIC,GAAAA,CAAWD,CAAK,CAAA,OAAA,CAAQ,gBAAgB,CAAA,CAC9D,WAAaA,CAAAA,CAAAA,CAAK,QAAQ,WAC1B,CAAA,iBAAA,CAAmBA,CAAK,CAAA,OAAA,CAAQ,iBAAkB,CAAA,GAAA,CAAIE,CAAK,EAAA,IAAIC,IAAaD,CAAC,CAAC,CAC/E,CAAA,CAEA,IAAK,CAAA,gBAAA,CAAiB,IAAK,CAAA,OAAA,CAAQ,iBAAiB,CAAA,CACjD,IAAK,CAAA,MAAA,GAAW,UAAyB,EAAA,IAAA,CAAK,IAAS,GAAA,YAAA,CACzD,MAAM,IAAIE,CAAAA,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js","sourcesContent":["import { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\nimport Utils from \"../Utils\";\r\nimport { LocaleCode, LocalizedString } from \"./Common\";\r\nimport { ChargeImpact, ChargeType, LocaleLanguageMap, TaxSystem } from \"./Enum\";\r\nimport { InvalidChargeTaxRuleError, InvalidChargeError, InvalidTaxRuleError } from \"./Error\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport { TaxRuleData, TaxRuleModel } from \"./TaxRule\";\r\nimport CouponModel from \"./Coupon\";\r\n\r\nexport type ChargePricing = {\r\n /** Tax-inclusive original charge amount before any discounts. Always non-negative. */\r\n baseChargeAmount: PriceData;\r\n /** Tax category of the charge. */\r\n taxCategory: string;\r\n /** Tax rules applicable to the charge. */\r\n applicableTaxRule: TaxRuleData[];\r\n};\r\n\r\nexport type ChargePricingModel = {\r\n /** Tax-inclusive original charge amount before any discounts. Always non-negative. */\r\n baseChargeAmount: PriceModel;\r\n /** Tax category of the charge. */\r\n taxCategory: string;\r\n /** Tax rules applicable to the charge. */\r\n applicableTaxRule: TaxRuleModel[];\r\n};\r\n\r\nexport type ChargeTaxBreakdown = {\r\n /** Tax rate: e.g., 0.09 for 9% */\r\n rate: number;\r\n /** Reverse-calculated pre-tax base from the netChargeAmount (post-discount) */\r\n taxableAmount: PriceData;\r\n /** Tax portion for this rule (netChargeAmount - taxableAmount) */\r\n taxAmount: PriceData;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type ChargeTaxBreakdownModel = {\r\n rate: number;\r\n taxableAmount: PriceModel;\r\n taxAmount: PriceModel;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type ChargeTotals = {\r\n /** Tax-inclusive original charge amount before discounts (copied from pricing) */\r\n chargeAmount: PriceData;\r\n /** Coupon code -> discount amount mapping */\r\n discountBreakdown: Record<string, PriceData>;\r\n /** Sum of all discounts */\r\n discountTotal: PriceData;\r\n /** chargeAmount - totalDiscount → final tax-inclusive payable amount after discounts */\r\n netChargeAmount: PriceData;\r\n /** Sum of all taxAmount values */\r\n taxTotal: PriceData;\r\n /** Tax breakdown per rule/category (reverse-calculated from netChargeAmount) */\r\n taxBreakdown: Record<string, ChargeTaxBreakdown>;\r\n /** Final payable/contribution amount. Equals netChargeAmount (tax-inclusive after discounts). */\r\n grandTotal: PriceData;\r\n};\r\n\r\nexport type ChargeTotalsModel = {\r\n chargeAmount: PriceModel;\r\n discountTotal: PriceModel;\r\n discountBreakdown: Record<string, PriceModel>;\r\n netChargeAmount: PriceModel;\r\n taxTotal: PriceModel;\r\n taxBreakdown: Record<string, ChargeTaxBreakdownModel>;\r\n grandTotal: PriceModel; // Equals netChargeAmount\r\n};\r\n\r\nexport type ChargeAttributes = CustomFieldAttributes & {\r\n id: string;\r\n name: LocalizedString;\r\n type: ChargeType;\r\n category: string;\r\n impact: ChargeImpact; // ADD or SUBTRACT\r\n pricing: ChargePricing;\r\n lineItemId?: string;\r\n total: ChargeTotals;\r\n};\r\n\r\nexport type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId'> & {\r\n\tlineItemId?: string;\r\n};\r\n\r\n/**\r\n * Represents an additional charge (or discount if amount is negative) in a shopping container.\r\n * Supports its own tax rules.\r\n */\r\nexport default class ChargeModel extends CustomFieldModel {\r\n\tprotected id: string;\r\n\tprotected name: LocalizedString;\r\n\tprotected type: ChargeType;\r\n\tprotected category: string;\r\n\tprotected impact: ChargeImpact;\r\n\tprotected pricing: ChargePricingModel;\r\n\tprotected lineItemId?: string;\r\n\tprotected total: ChargeTotalsModel;\r\n\r\n\tconstructor(data: ChargeAttributes) {\r\n\t\tsuper(data);\r\n\t\tthis.id = data.id;\r\n\t\tthis.name = data.name;\r\n\t\tthis.type = data.type;\r\n\t\tthis.category = data.category;\r\n\t\tthis.impact = data.impact;\r\n\t\tthis.lineItemId = data.lineItemId;\r\n\t\tthis.pricing = {\r\n\t\t\tbaseChargeAmount: new PriceModel(data.pricing.baseChargeAmount),\r\n\t\t\ttaxCategory: data.pricing.taxCategory,\r\n\t\t\tapplicableTaxRule: data.pricing.applicableTaxRule.map(r => new TaxRuleModel(r))\r\n\t\t};\r\n\r\n\t\tthis.validateTaxRules(this.pricing.applicableTaxRule);\r\n\t\tif(this.impact === ChargeImpact.SUBTRACT && this.type !== ChargeType.ADJUSTMENT) {\r\n\t\t\tthrow new InvalidChargeError('SUBTRACT impact is only allowed for ADJUSTMENT charge');\r\n\t\t}\r\n\r\n\t\tthis.total = {\r\n\t\t\tchargeAmount: new PriceModel(data.total.chargeAmount),\r\n\t\t\tdiscountTotal: new PriceModel(data.total.discountTotal),\r\n\t\t\tdiscountBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(data.total.discountBreakdown).map(([discountId, discount]) => [\r\n\t\t\t\t\tdiscountId,\r\n\t\t\t\t\tnew PriceModel(discount)\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\tnetChargeAmount: new PriceModel(data.total.netChargeAmount),\r\n\t\t\ttaxBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(data.total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n\t\t\t\t\ttaxRuleId,\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\trate: taxBreakdown.rate,\r\n\t\t\t\t\t\ttaxableAmount: new PriceModel(taxBreakdown.taxableAmount),\r\n\t\t\t\t\t\ttaxAmount: new PriceModel(taxBreakdown.taxAmount),\r\n\t\t\t\t\t\tsystem: taxBreakdown.system,\r\n\t\t\t\t\t\tsubSystem: taxBreakdown.subSystem\r\n\t\t\t\t\t}\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\ttaxTotal: new PriceModel(data.total.taxTotal),\r\n\t\t\tgrandTotal: new PriceModel(data.total.grandTotal),\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the unique identifier of the charge.\r\n\t * @returns \r\n\t */\r\n\tpublic getId(): string { return this.id; }\r\n\r\n\r\n\t/**\r\n\t * Gets the full localized product name object.\r\n\t * @returns A copy of the LocalizedString object for the name.\r\n\t */\r\n\tgetName(): LocalizedString\r\n\t/**\r\n\t * Gets the product name for a specific locale, falling back to English ('en').\r\n\t * @param locale - The desired locale code.\r\n\t * @returns The name string for the specified locale.\r\n\t */\r\n\tgetName(locale: LocaleCode): string\r\n\tgetName(locale?: LocaleCode): LocalizedString | string {\r\n\t\tif (locale) {\r\n\t\t\treturn Utils.deepClone(this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en);\r\n\t\t} else {\r\n\t\t\treturn Utils.deepClone(this.name);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the charge category.\r\n\t * @returns The category string.\r\n\t */\r\n\tpublic getCategory(): string { return this.category; }\r\n\r\n\t/**\r\n\t * Gets the charge type.\r\n\t * @returns The charge type enum value.\r\n\t */\r\n\tpublic getType(): ChargeType { return this.type; }\r\n\t/**\r\n\t * Gets the charge impact (add or subtract).\r\n\t * @returns The charge impact.\r\n\t */\r\n\tpublic getImpact(): ChargeImpact { return this.impact; }\r\n\r\n\t/**\r\n\t * Gets the related line item id, if any.\r\n\t * @returns The line item id or undefined.\r\n\t */\r\n\tpublic getLineItemId(): string | undefined { return this.lineItemId; }\r\n\r\n\t/**\r\n\t * Gets the pricing details (models) for this charge.\r\n\t * @returns Pricing details including price, tax category, and tax rules.\r\n\t */\r\n\tpublic getPricing(): ChargePricingModel {\r\n\t\treturn {\r\n\t\t\tbaseChargeAmount: this.pricing.baseChargeAmount,\r\n\t\t\ttaxCategory: this.pricing.taxCategory,\r\n\t\t\tapplicableTaxRule: [...this.pricing.applicableTaxRule]\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the computed totals for this charge.\r\n\t * @returns Totals including discounts, taxes, and grand total.\r\n\t */\r\n\tpublic getTotal(): ChargeTotalsModel {\r\n\t\treturn {\r\n\t\t\tchargeAmount: this.total.chargeAmount,\r\n\t\t\tdiscountTotal: this.total.discountTotal,\r\n\t\t\tdiscountBreakdown: { ...this.total.discountBreakdown },\r\n\t\t\tnetChargeAmount: this.total.netChargeAmount,\r\n\t\t\ttaxTotal: this.total.taxTotal,\r\n\t\t\ttaxBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(this.total.taxBreakdown).map(([key, value]) => [\r\n\t\t\t\t\tkey,\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\trate: value.rate,\r\n\t\t\t\t\t\ttaxableAmount: value.taxableAmount,\r\n\t\t\t\t\t\ttaxAmount: value.taxAmount,\r\n\t\t\t\t\t\tsystem: value.system,\r\n\t\t\t\t\t\tsubSystem: value.subSystem\r\n\t\t\t\t\t}\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\tgrandTotal: this.total.grandTotal,\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the applicable tax rules for this charge.\r\n\t * @returns A list of tax rules.\r\n\t */\r\n\tpublic getApplicableTaxRules(): TaxRuleModel[] {\r\n\t\treturn [...this.pricing.applicableTaxRule];\r\n\t}\r\n\r\n\t/**\r\n\t * Updates the tax rule for this line item and recalculates totals.\r\n\t * @param taxRule - The new tax rule to apply.\r\n\t * @throws {Error} If the tax rule category does not match the item's tax category.\r\n\t */\r\n\tpublic updateTax(taxRules: TaxRuleModel[]): void {\r\n\t\tif (this.type === ChargeType.ADJUSTMENT && taxRules.length > 0) {\r\n\t\t\tthrow new InvalidChargeError(\"Adjustment charges cannot apply tax rules.\");\r\n\t\t}\r\n\t\ttaxRules.forEach(taxRule => {\r\n\t\t\tif (!taxRule.appliesTo(this.pricing.taxCategory, taxRule.getCountry())) {\r\n\t\t\t\tthrow new InvalidTaxRuleError();\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\t// Remove the old taxableUnitPrice calculation - no longer needed\r\n\t\tthis.validateTaxRules(taxRules);\r\n\t\tthis.pricing.applicableTaxRule = taxRules;\r\n\t\tthis.calculateTotals();\r\n\t}\r\n\r\n\t/**\r\n\t * Validates that there are no overlapping price brackets for any tax rules within the charge.\r\n\t * @param taxRules - The list of tax rules to validate.\r\n\t * @throws {InvalidChargeTaxRuleError} If any rules have positive tax rates with SUBTRACT impact or if duplicate rule IDs are found.\r\n\t * @throws {InvalidChargeTaxRuleError} Duplicate tax rule IDs will results in error.\r\n\t * @throws {CoincidingTaxBracketError} If any overlapping rules are found.\r\n\t */\r\n\tprivate validateTaxRules(taxRules: TaxRuleModel[]): void {\r\n\t\tif(this.impact === ChargeImpact.SUBTRACT) {\r\n\t\t\tif(taxRules.some(taxRule => taxRule.getRate() > 0)) {\r\n\t\t\t\tthrow new InvalidChargeTaxRuleError(\"Subtractive charges cannot have positive tax rates.\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst uniqueTaxRule = new Set();\r\n\t\tfor (let i = 0; i < taxRules.length; i++) {\r\n\t\t\tconst currentTaxRuleId = taxRules[i].getTaxRuleId();\r\n\t\t\tif(uniqueTaxRule.has(currentTaxRuleId)){\r\n\t\t\t\tthrow new InvalidChargeTaxRuleError(\"Duplicate tax rule ID found: \" + currentTaxRuleId);\r\n\t\t\t} else {\r\n\t\t\t\tuniqueTaxRule.add(currentTaxRuleId);\r\n\t\t\t}\r\n\r\n\t\t\tfor (let j = i + 1; j < taxRules.length; j++) {\r\n\t\t\t\tconst r1 = taxRules[i];\r\n\t\t\t\tconst r2 = taxRules[j];\r\n\r\n\t\t\t\tconst r1Min = r1.getMinPrice();\r\n\t\t\t\tconst r1Max = r1.getMaxPrice();\r\n\t\t\t\tconst r1ExcludeMin = r1.getExcludeMin();\r\n\t\t\t\tconst r1ExcludeMax = r1.getExcludeMax();\r\n\t\t\t\tconst r2Min = r2.getMinPrice();\r\n\t\t\t\tconst r2Max = r2.getMaxPrice();\r\n\t\t\t\tconst r2ExcludeMin = r2.getExcludeMin();\r\n\t\t\t\tconst r2ExcludeMax = r2.getExcludeMax();\r\n\r\n\t\t\t\t// Two ranges are disjoint if one ends strictly before the other starts.\r\n\t\t\t\t// If they only touch at one point, disjoint only when either side excludes that point.\r\n\t\t\t\tconst r1EndsBeforeR2Starts = (() => {\r\n\t\t\t\t\tif (!r1Max) return false;\r\n\t\t\t\t\tconst compare = r1Max.compareTo(r2Min);\r\n\t\t\t\t\treturn compare < 0 || (compare === 0 && (r1ExcludeMax || r2ExcludeMin));\r\n\t\t\t\t})();\r\n\t\t\t\tconst r2EndsBeforeR1Starts = (() => {\r\n\t\t\t\t\tif (!r2Max) return false;\r\n\t\t\t\t\tconst compare = r2Max.compareTo(r1Min);\r\n\t\t\t\t\treturn compare < 0 || (compare === 0 && (r2ExcludeMax || r1ExcludeMin));\r\n\t\t\t\t})();\r\n\t\t\t\tconst overlap = !(r1EndsBeforeR2Starts || r2EndsBeforeR1Starts);\r\n\r\n\t\t\t\tif (overlap) {\r\n\t\t\t\t\t// Exception: Allow overlapping rules if they have the exact same price bracket (slab)\r\n\t\t\t\t\tconst sameSlab = r1Min.compareTo(r2Min) === 0 &&\r\n\t\t\t\t\t\tr1ExcludeMin === r2ExcludeMin &&\r\n\t\t\t\t\t\tr1ExcludeMax === r2ExcludeMax &&\r\n\t\t\t\t\t\t((!r1Max && !r2Max) || (r1Max && r2Max && r1Max.compareTo(r2Max) === 0));\r\n\r\n\t\t\t\t\tif (!sameSlab) {\r\n\t\t\t\t\t\tthrow new InvalidChargeTaxRuleError(\r\n\t\t\t\t\t\t\t`Overlapping rules found: [${r1.getTaxRuleId()}: ${r1ExcludeMin ? \"(\" : \"[\"}${r1Min.getAmount()}-${r1Max?.getAmount() ?? \"Infinity\"}${r1ExcludeMax ? \")\" : \"]\"}] and [${r2.getTaxRuleId()}: ${r2ExcludeMin ? \"(\" : \"[\"}${r2Min.getAmount()}-${r2Max?.getAmount() ?? \"Infinity\"}${r2ExcludeMax ? \")\" : \"]\"}]`\r\n\t\t\t\t\t\t);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t\t* Updates the discounts applied to this line item and recalculates totals.\r\n\t\t* @param appliedDiscounts - List of coupons and their allocated discount amounts.\r\n\t*/\r\n\tpublic updateDiscounts(appliedDiscounts: { coupon: CouponModel, amount: PriceModel }[]): void {\r\n\t\tlet chargeDiscounts = {} as Record<string, PriceModel>;\r\n\t\tappliedDiscounts.forEach(discount => {\r\n\t\t\tchargeDiscounts[discount.coupon.getCode()] = discount.amount;\r\n\t\t});\r\n\r\n\t\tthis.total.discountBreakdown = chargeDiscounts;\r\n\t\tthis.calculateTotals();\r\n\t}\r\n\r\n\t/**\r\n\t * Recalculates totals for this charge based on pricing and discounts.\r\n\t */\r\n\tpublic calculateTotals(): void {\r\n\t\tconst zero = this.pricing.baseChargeAmount.zero();\r\n\t\tconst baseChargeAmount = this.pricing.baseChargeAmount;\r\n\r\n\t\tconst totalDiscount = Object.values(this.total.discountBreakdown).reduce((sum, s) => sum.add(s), zero);\r\n\t\tconst netChargeAmount = baseChargeAmount.subtract(totalDiscount);\r\n\r\n\t\tconst taxBreakdown: Record<string, ChargeTaxBreakdownModel> = {};\r\n\r\n\t\t// 1. Calculate total rate for inclusive back-calculation\r\n\t\tconst totalRate = this.pricing.applicableTaxRule.reduce((sum, r) => sum + r.getApplicableTaxRate(netChargeAmount), 0);\r\n\r\n\t\tif (totalRate <= 0) {\r\n\t\t\tthis.total = {\r\n\t\t\t\tchargeAmount: baseChargeAmount,\r\n\t\t\t\tdiscountTotal: totalDiscount,\r\n\t\t\t\tdiscountBreakdown: this.total.discountBreakdown,\r\n\t\t\t\tnetChargeAmount: netChargeAmount,\r\n\t\t\t\ttaxTotal: zero,\r\n\t\t\t\ttaxBreakdown: {},\r\n\t\t\t\tgrandTotal: netChargeAmount\r\n\t\t\t};\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// 2. Iteratively find a taxable base so that base + sum(rounded taxes) == gross\r\n\t\tconst currency = baseChargeAmount.getCurrency();\r\n\t\tconst grossValue = baseChargeAmount.getAmount();\r\n\t\tconst maxIterations = 1000;\r\n\r\n\t\tlet baseValue = PriceModel.getRoundedAmount(grossValue / (1 + totalRate), currency);\r\n\t\tlet bestBaseValue = baseValue;\r\n\t\tlet bestDiff = Number.POSITIVE_INFINITY;\r\n\r\n\t\tfor (let i = 0; i < maxIterations; i++) {\r\n\t\t\tconst currentTaxableBase = new PriceModel({ amount: baseValue, currency });\r\n\t\t\tconst taxes = this.pricing.applicableTaxRule\r\n\t\t\t\t.sort((a, b) => b.getApplicableTaxRate(currentTaxableBase) - a.getApplicableTaxRate(currentTaxableBase))\r\n\t\t\t\t.map(rule =>\r\n\t\t\t\t\tPriceModel.getRoundedAmount(baseValue * rule.getApplicableTaxRate(currentTaxableBase), currency)\r\n\t\t\t\t);\r\n\r\n\t\t\tconst taxSum = taxes.reduce((sum, v) => sum + v, 0);\r\n\t\t\tconst diff = (baseValue + taxSum) - grossValue;\r\n\r\n\t\t\tconst currentTotalRate = this.pricing.applicableTaxRule.reduce((sum, r) => sum + r.getApplicableTaxRate(currentTaxableBase), 0);\r\n\r\n\t\t\tif (Math.abs(diff) < Math.abs(bestDiff)) {\r\n\t\t\t\tbestDiff = diff;\r\n\t\t\t\tbestBaseValue = baseValue;\r\n\t\t\t}\r\n\r\n\t\t\tif (diff === 0) break;\r\n\t\t\tbaseValue = baseValue - diff / (1 + currentTotalRate); // Adjust base value based on the difference\r\n\t\t\tif (baseValue < 0 || baseValue > grossValue) break;\r\n\t\t}\r\n\r\n\t\tconst taxableBase = new PriceModel({ amount: bestBaseValue, currency });\r\n\r\n\t\t// 3. Compute tax amounts per rule based on final taxable base\r\n\t\tlet distributedTax = zero;\r\n\t\tthis.pricing.applicableTaxRule\r\n\t\t\t.sort((a, b) => b.getApplicableTaxRate(taxableBase) - a.getApplicableTaxRate(taxableBase))\r\n\t\t\t.forEach((taxRule) => {\r\n\t\t\t\tconst rate = taxRule.getApplicableTaxRate(taxableBase);\r\n\t\t\t\tconst taxAmountValue = PriceModel.getRoundedAmount(bestBaseValue * rate, currency);\r\n\t\t\t\tconst taxAmount = new PriceModel({ amount: taxAmountValue, currency });\r\n\r\n\t\t\t\ttaxBreakdown[taxRule.getTaxRuleId()] = {\r\n\t\t\t\t\trate: rate,\r\n\t\t\t\t\ttaxableAmount: taxableBase,\r\n\t\t\t\t\ttaxAmount: taxAmount,\r\n\t\t\t\t\tsystem: taxRule.getTaxSystem(),\r\n\t\t\t\t\tsubSystem: taxRule.getTaxSubSystem()\r\n\t\t\t\t};\r\n\t\t\t\tdistributedTax = distributedTax.add(taxAmount);\r\n\t\t\t});\r\n\r\n\t\tconst grandTotal = netChargeAmount;\r\n\t\tthis.total = {\r\n\t\t\tchargeAmount: baseChargeAmount,\r\n\t\t\tdiscountTotal: totalDiscount,\r\n\t\t\tdiscountBreakdown: this.total.discountBreakdown,\r\n\t\t\tnetChargeAmount: netChargeAmount,\r\n\t\t\ttaxBreakdown: taxBreakdown,\r\n\t\t\ttaxTotal: distributedTax,\r\n\t\t\tgrandTotal: grandTotal\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets a plain data object representing this charge.\r\n\t * @returns ChargeData for serialization.\r\n\t */\r\n\tpublic getDetails(): ChargeData {\r\n\t\tconst details: ChargeData = {\r\n\t\t\tid: this.id,\r\n\t\t\tname: Utils.deepClone(this.name),\r\n\t\t\ttype: this.type,\r\n\t\t\tcategory: this.category,\r\n\t\t\tpricing: {\r\n\t\t\t\tbaseChargeAmount: this.pricing.baseChargeAmount.getDetails(),\r\n\t\t\t\ttaxCategory: this.pricing.taxCategory,\r\n\t\t\t\tapplicableTaxRule: this.pricing.applicableTaxRule.map(r => r.getDetails())\r\n\t\t\t},\r\n\t\t\timpact: this.impact,\r\n\t\t\tlineItemId: this.lineItemId,\r\n\t\t\ttotal: {\r\n\t\t\t\tchargeAmount: this.total.chargeAmount.getDetails(),\r\n\t\t\t\tdiscountTotal: this.total.discountTotal.getDetails(),\r\n\t\t\t\tdiscountBreakdown: Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([k, v]) => [k, v.getDetails()])),\r\n\t\t\t\tnetChargeAmount: this.total.netChargeAmount.getDetails(),\r\n\t\t\t\ttaxBreakdown: Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([k, v]) => [k, {\r\n\t\t\t\t\trate: v.rate,\r\n\t\t\t\t\ttaxableAmount: v.taxableAmount.getDetails(),\r\n\t\t\t\t\ttaxAmount: v.taxAmount.getDetails(),\r\n\t\t\t\t\tsystem: v.system,\r\n\t\t\t\t\tsubSystem: v.subSystem\r\n\t\t\t\t}])),\r\n\t\t\t\ttaxTotal: this.total.taxTotal.getDetails(),\r\n\t\t\t\tgrandTotal: this.total.grandTotal.getDetails()\r\n\t\t\t},\r\n\t\t\tcustomFields: this.getAllCustomFields()\r\n\t\t};\r\n\t\treturn details;\r\n\t}\r\n}\r\n"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export{d as Fetch,b as Logger,c as ResponseUtility}from'./chunk-AMIRIUMH.mjs';import {b}from'./chunk-
|
|
1
|
+
export{d as Fetch,b as Logger,c as ResponseUtility}from'./chunk-AMIRIUMH.mjs';import {b}from'./chunk-QGIQ3MH6.mjs';export{a as Utils}from'./chunk-QGIQ3MH6.mjs';import'./chunk-FCRJAAPY.mjs';import'./chunk-LI5JQ6UC.mjs';import {j,a,b as b$1,c as c$1,d}from'./chunk-QK4XJ3GB.mjs';import'./chunk-2B2XI6FG.mjs';import'./chunk-R5DM7WCD.mjs';import'./chunk-UXZBULDS.mjs';var p={$id:"standards",definitions:{lowercaseText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]*$"},lowercaseText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,10}$"},lowercaseText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,16}$"},lowercaseText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,30}$"},lowercaseText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,50}$"},lowercaseText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,256}$"},text:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).*$"},text10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,10}$"},text16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,16}$"},text30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,30}$"},text50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,50}$"},text256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,256}$"},requiredText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).+$"},requiredText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,10}$"},requiredText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,16}$"},requiredText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,30}$"},requiredText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,50}$"},requiredText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,256}$"},url:{type:"string",pattern:"^https://[^\\s/$.?#].[^\\s]*$",maxLength:2048},uuid:{type:"string",minLength:1,pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"},productKey:{type:"string",pattern:b.productKeyRegex.source},productSku:{type:"string",pattern:b.productSKURegex.source},genderCategory:{type:"string",enum:Object.values(j)},price:{type:"object",properties:{amount:{type:"number",minimum:0},currency:{$ref:"#/definitions/currency"}},additionalProperties:!1,required:["amount","currency"]},color:{type:"object",properties:{name:{type:"string"},hex:{type:"string"}},additionalProperties:!1,required:["name"]},attributeValue:{oneOf:[{type:"string"},{$ref:"#/definitions/color"}]},selectionAttributes:{type:"object",properties:{color:{$ref:"#/definitions/color"}},required:["color"],additionalProperties:{$ref:"#/definitions/attributeValue"}},firstName:{$ref:"#/definitions/requiredText30"},lastName:{$ref:"#/definitions/text30"},company:{$ref:"#/definitions/text50"},phone:{type:"string",pattern:"^[0-9]{10}$"},email:{type:"string",pattern:"^[^\\s]+@[^\\s]+\\.[^\\s]+$"},addressLine1:{$ref:"#/definitions/requiredText50"},addressLine2:{$ref:"#/definitions/text50"},city:{$ref:"#/definitions/requiredText30"},postalCode:{$ref:"#/definitions/requiredText16"},state:{type:"string",enum:["AP","AR","AS","BR","CT","GA","GJ","HR","HP","JH","KA","KL","MP","MH","MN","ML","MZ","NL","OR","PB","RJ","SK","TN","TG","TR","UP","UT","WB","AN","CH","DH","LD","DL","PY","LA","JK"]},country:{type:"string",enum:Object.values(a)},currency:{type:"string",enum:Object.values(b$1)},locale:{type:"string",enum:Object.values(c$1)},language:{type:"string",enum:Object.values(d)},localeOrLanguage:{type:"string",enum:[...Object.values(c$1),...Object.values(d)]},addressType:{type:"string",enum:["shipping","billing","billing&shipping"]},address:{type:"object",properties:{firstName:{$ref:"standards#/definitions/firstName"},lastName:{$ref:"standards#/definitions/lastName"},company:{$ref:"standards#/definitions/company"},phone:{$ref:"standards#/definitions/phone"},email:{$ref:"standards#/definitions/email"},addressLine1:{$ref:"standards#/definitions/addressLine1"},addressLine2:{$ref:"standards#/definitions/addressLine2"},city:{$ref:"standards#/definitions/city"},postalCode:{$ref:"standards#/definitions/postalCode"},state:{$ref:"standards#/definitions/state"},country:{$ref:"standards#/definitions/country"}},required:["firstName","lastName","phone","email","addressLine1","postalCode","state","country"]}}};var $={getStandardSchemaDefinition(){return p}},c=$;
|
|
2
2
|
export{c as Schema};//# sourceMappingURL=index.mjs.map
|
|
3
3
|
//# sourceMappingURL=index.mjs.map
|