b23-lib 3.0.3 → 3.0.5
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.js.map +1 -1
- package/dist/Auth/index.mjs +1 -1
- package/dist/Classes/Cart.js +1 -1
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Cart.mjs.map +1 -1
- package/dist/Classes/Charge.d.mts +8 -3
- package/dist/Classes/Charge.d.ts +8 -3
- package/dist/Classes/Charge.js +1 -1
- package/dist/Classes/Charge.js.map +1 -1
- package/dist/Classes/Charge.mjs +1 -1
- package/dist/Classes/Coupon.js.map +1 -1
- package/dist/Classes/Coupon.mjs +1 -1
- package/dist/Classes/Inventory.js.map +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/LineItem.js +1 -1
- package/dist/Classes/LineItem.js.map +1 -1
- package/dist/Classes/LineItem.mjs +1 -1
- package/dist/Classes/Order.js +1 -1
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/Price.js.map +1 -1
- package/dist/Classes/Price.mjs +1 -1
- package/dist/Classes/Product.js.map +1 -1
- package/dist/Classes/Product.mjs +1 -1
- package/dist/Classes/ShoppingContainer.d.mts +1 -7
- package/dist/Classes/ShoppingContainer.d.ts +1 -7
- package/dist/Classes/ShoppingContainer.js +1 -1
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/Classes/TaxCategory.js.map +1 -1
- package/dist/Classes/TaxCategory.mjs +1 -1
- package/dist/Classes/TaxRule.d.mts +54 -62
- package/dist/Classes/TaxRule.d.ts +54 -62
- package/dist/Classes/TaxRule.js +1 -1
- package/dist/Classes/TaxRule.js.map +1 -1
- package/dist/Classes/TaxRule.mjs +1 -1
- package/dist/Classes/TieredPrice.js.map +1 -1
- package/dist/Classes/TieredPrice.mjs +1 -1
- package/dist/chunk-2HBQ3C6V.mjs +2 -0
- package/dist/chunk-2HBQ3C6V.mjs.map +1 -0
- package/dist/{chunk-RSMXGZD4.mjs → chunk-2ZQIRKRB.mjs} +2 -2
- package/dist/{chunk-RSMXGZD4.mjs.map → chunk-2ZQIRKRB.mjs.map} +1 -1
- package/dist/{chunk-PTIPDRB4.mjs → chunk-4KMF3LE7.mjs} +2 -2
- package/dist/chunk-4KMF3LE7.mjs.map +1 -0
- package/dist/{chunk-IIPG3DTO.mjs → chunk-GF3OGUDE.mjs} +2 -2
- package/dist/{chunk-IIPG3DTO.mjs.map → chunk-GF3OGUDE.mjs.map} +1 -1
- package/dist/{chunk-U7DES3CI.mjs → chunk-HR5HHV6O.mjs} +2 -2
- package/dist/{chunk-U7DES3CI.mjs.map → chunk-HR5HHV6O.mjs.map} +1 -1
- package/dist/chunk-SNDTKUMW.mjs +2 -0
- package/dist/chunk-SNDTKUMW.mjs.map +1 -0
- package/dist/{chunk-6X5O25W5.mjs → chunk-XHGUVYQO.mjs} +2 -2
- package/dist/{chunk-6X5O25W5.mjs.map → chunk-XHGUVYQO.mjs.map} +1 -1
- package/dist/{chunk-JE7BAYI5.mjs → chunk-Y5D6RHTJ.mjs} +2 -2
- package/dist/{chunk-JE7BAYI5.mjs.map → chunk-Y5D6RHTJ.mjs.map} +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-KKQLCW6A.mjs +0 -2
- package/dist/chunk-KKQLCW6A.mjs.map +0 -1
- package/dist/chunk-PTIPDRB4.mjs.map +0 -1
- package/dist/chunk-XXETAAL4.mjs +0 -2
- package/dist/chunk-XXETAAL4.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/Classes/Enum.ts","../../src/Classes/Error.ts","../../src/Classes/Price.ts","../../src/Classes/TaxRule.ts"],"names":["CurrencySymbolMap","CurrencyLocaleMap","TaxSlabNotFoundError","message","InvalidPriceAmountError","InvalidCurrencyCodeError","CurrencyMismatchError","InvalidArgumentError","PriceModel","_PriceModel","#kind","data","obj","priceModel","factor","divisor","priceModels","minPrice","currentPrice","maxPrice","amount","currency","options","locale","valueToFormat","fractionDigits","formattingOptions","error","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier","TaxRuleModel","_TaxRuleModel","s","taxCategory","country","at","unitPrice","rate","taxSlabs","slabs","taxRule","formateOption","percentage","rateStr","FixedTaxRuleModel"],"mappings":"aAsCO,IAAMA,CAAoB,CAAA,CAC9B,GAAiC,CAAA,QACpC,EAEaC,CAAoB,CAAA,CAC9B,GAAiC,CAAA,OACpC,EC6DO,IAAMC,CAAAA,CAAN,cAAmC,KAAM,CAC5C,WAAYC,CAAAA,CAAAA,CAAkB,0EAA4E,CAAA,CACtG,KAAM,CAAA,CAAA,iBAAA,EAAoBA,CAAO,CAAA,CAAE,EACnC,IAAK,CAAA,IAAA,CAAO,uBAChB,CACJ,EAEaC,CAAN,CAAA,cAAsC,KAAM,CAC/C,YAAYD,CAAkB,CAAA,4BAAA,CAA8B,CACxD,KAAA,CAAM,CAAkBA,eAAAA,EAAAA,CAAO,CAAE,CAAA,CAAA,CACjC,KAAK,IAAO,CAAA,0BAChB,CACJ,CAAA,CAEaE,EAAN,cAAuC,KAAM,CAChD,WAAA,CAAYF,EAAkB,4BAA8B,CAAA,CACxD,KAAM,CAAA,CAAA,iBAAA,EAAoBA,CAAO,CAAE,CAAA,CAAA,CACnC,IAAK,CAAA,IAAA,CAAO,2BAChB,CACJ,CAAA,CAEaG,CAAN,CAAA,cAAoC,KAAM,CAC7C,WAAA,CAAYH,CAAkB,CAAA,+DAAA,CAAiE,CAC3F,KAAM,CAAA,CAAA,kBAAA,EAAqBA,CAAO,CAAA,CAAE,CACpC,CAAA,IAAA,CAAK,IAAO,CAAA,wBAChB,CACJ,CAEaI,CAAAA,CAAAA,CAAN,cAAmC,KAAM,CAC5C,WAAYJ,CAAAA,CAAAA,CAAiB,CACzB,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,aAAA,CAAe,IAAK,CAAA,aAAA,CAAc,aAClC,CAAA,WAAA,CAAa,IAAK,CAAA,WAAA,CAAc,KAAK,WAAY,CAAA,WAAA,EAAgB,CAAA,KAAA,CACnE,CACF,CACF","file":"TaxRule.js","sourcesContent":["/**\r\n * Represents the countries where the application operates or products are available.\r\n */\r\nexport enum OperationalCountry {\r\n /** India */ IN = 'IN',\r\n}\r\n\r\nexport enum OperationalCountryCurrency {\r\n /** India */ INR = 'INR',\r\n}\r\n\r\nexport enum OperationalLocale {\r\n /** India */ 'en-IN' = 'en-IN',\r\n /** India ( Kannada) */ 'kn-IN' = 'kn-IN'\r\n}\r\n\r\nexport enum OperationalLanguage {\r\n en = 'en',\r\n kn = 'kn'\r\n}\r\n\r\nexport const LocaleLanguageMap: Record<OperationalLocale, OperationalLanguage> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalLanguage.en,\r\n [OperationalLocale[\"kn-IN\"]]: OperationalLanguage.kn,\r\n}\r\n\r\nexport const LocaleCountryMap: Record<OperationalLocale, OperationalCountry> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalCountry.IN,\r\n [OperationalLocale[\"kn-IN\"]]: OperationalCountry.IN,\r\n}\r\n\r\n/**\r\n * Defines the supported ISO 4217 currency codes as an enumeration.\r\n */\r\nexport const CountryCurrencyMap = {\r\n /** India */[OperationalCountry.IN]: OperationalCountryCurrency.INR,\r\n};\r\n\r\nexport const CurrencySymbolMap = {\r\n [OperationalCountryCurrency.INR]: '₹',\r\n}\r\n\r\nexport const CurrencyLocaleMap = {\r\n [OperationalCountryCurrency.INR]: OperationalLocale[\"en-IN\"],\r\n}\r\n\r\n/**\r\n * Defines standard gender categories for product targeting.\r\n */\r\nexport enum GenderCategory {\r\n MALE = 'Male',\r\n FEMALE = 'Female',\r\n UNISEX = 'Unisex',\r\n KIDS = 'Kids',\r\n BOY = 'Boy',\r\n GIRL = 'Girl',\r\n GENERAL = 'General',\r\n}\r\n\r\nexport enum ImageCategory {\r\n PRIMARY = 'PRIMARY',\r\n GALLERY = 'GALLERY'\r\n}\r\n\r\nexport enum ChargeType {\r\n SHIPPING = 'SHIPPING',\r\n ADJUSTMENT = 'ADJUSTMENT'\r\n}\r\n\r\nexport enum TaxSystem {\r\n GST = 'GST',\r\n}\r\n\r\n/**\r\n * LineItemState\r\n * \r\n * INITIAL: Item added to order, not yet processed.\r\n * PROCESSING: Item is being prepared for shipment.\r\n * SHIPPED: Item dispatched to customer.\r\n * DELIVERED: Item delivered to customer.\r\n * CANCELLED: Item cancelled before shipment or delivery.\r\n * RETURN_REQUESTED: Customer requests to return item.\r\n * RETURNED: Item received back from customer.\r\n * REFUND_INITIATED: Refund initiated for item.\r\n * REFUNDED: Refund processed for item.\r\n * ON_HOLD: Item is paused due to payment, inventory, or other issues.\r\n */\r\nexport enum LineItemState {\r\n INITIAL = \"INITIAL\",\r\n PROCESSING = \"PROCESSING\",\r\n SHIPPED = \"SHIPPED\",\r\n DELIVERED = \"DELIVERED\",\r\n CANCELLED = \"CANCELLED\",\r\n RETURN_REQUESTED = \"RETURN_REQUESTED\",\r\n RETURNED = \"RETURNED\",\r\n REFUND_INITIATED = \"REFUND_INITIATED\",\r\n REFUNDED = \"REFUNDED\",\r\n ON_HOLD = \"ON_HOLD\",\r\n}","export class LineItemNotFoundError extends Error {\r\n constructor(lineItemId: string) {\r\n super(`Line item with ID '${lineItemId}' not found in the cart.`);\r\n this.name = 'LineItemNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidLineItemStateError extends Error {\r\n constructor(state: string) {\r\n super(`Invalid line item state: ${state}`);\r\n this.name = 'InvalidLineItemStateError';\r\n }\r\n}\r\n\r\nexport class DuplicateSizeError extends Error {\r\n constructor(size: string) {\r\n super(`Duplicate size found: ${size}`);\r\n this.name = 'DuplicateSizeError';\r\n }\r\n}\r\n\r\nexport class DuplicateSelectionAttributeError extends Error {\r\n constructor(attribute: string) {\r\n super(`Duplicate selection attribute found: ${attribute}`);\r\n this.name = 'DuplicateSelectionAttributeError';\r\n }\r\n}\r\n\r\nexport class ProductMismatchError extends Error {\r\n constructor(message: string = \"Product and selection attributes do not match.\") {\r\n super(`ProductMismatch: ${message}`);\r\n this.name = 'ProductMismatchError';\r\n }\r\n}\r\n\r\nexport class ProductInactiveError extends Error {\r\n constructor(message: string = \"Product is not active.\") {\r\n super(`ProductInactive: ${message}`);\r\n this.name = 'ProductInactiveError';\r\n }\r\n}\r\n\r\nexport class SelectionAttributeParseError extends Error {\r\n constructor(message: string = \"Failed to parse selection attributes key.\") {\r\n super(`SelectionAttributeParseError: ${message}`);\r\n this.name = 'SelectionAttributeParseError';\r\n }\r\n}\r\n\r\nexport class SizeMismatchError extends Error {\r\n constructor(message: string = \"Size does not match.\") {\r\n super(`SizeMismatch: ${message}`);\r\n this.name = 'SizeMismatchError';\r\n }\r\n}\r\n\r\nexport class PricingNotFoundError extends Error {\r\n constructor(message: string = \"Pricing details not available for the product\") {\r\n super(`NotFound: ${message}`);\r\n this.name = 'PricingNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxRuleError extends Error {\r\n constructor(message: string = \"Tax rule category mismatch.\") {\r\n super(`InvalidTaxRule: ${message}`);\r\n this.name = 'InvalidTaxRuleError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxCategoryError extends Error {\r\n constructor(message: string = \"Tax category is not valid.\") {\r\n super(`InvalidTaxCategory: ${message}`);\r\n this.name = 'InvalidTaxCategoryError';\r\n }\r\n}\r\n\r\nexport class InvalidMinQuantityError extends Error {\r\n constructor(message: string = \"Minimum quantity must be greater than zero.\") {\r\n super(`InvalidMinQuantity: ${message}`);\r\n this.name = 'InvalidMinQuantityError';\r\n }\r\n}\r\n\r\nexport class InvalidTieredPriceError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidTieredPrice: ${message}`);\r\n this.name = 'InvalidTieredPriceError';\r\n }\r\n}\r\n\r\nexport class InvalidQuantityError extends Error {\r\n constructor(message: string = \"Quantity must be greater than zero.\") {\r\n super(`InvalidQuantity: ${message}`);\r\n this.name = 'InvalidQuantityError';\r\n }\r\n}\r\n\r\nexport class NoApplicableTierError extends Error {\r\n constructor(quantity: number) {\r\n super(`NoApplicableTier: Quantity ${quantity} does not meet the minimum purchase requirement.`);\r\n this.name = 'NoApplicableTierError';\r\n }\r\n}\r\n\r\nexport class TaxSlabNotFoundError extends Error {\r\n constructor(message: string = \"No applicable tax slab or multiple slabs found for the given unit price.\") {\r\n super(`TaxSlabNotFound: ${message}`);\r\n this.name = 'TaxSlabNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidPriceAmountError extends Error {\r\n constructor(message: string = \"Amount cannot be negative.\") {\r\n super(`InvalidAmount: ${message}`);\r\n this.name = 'InvalidPriceAmountError';\r\n }\r\n}\r\n\r\nexport class InvalidCurrencyCodeError extends Error {\r\n constructor(message: string = \"Currency code is required.\") {\r\n super(`InvalidCurrency: ${message}`);\r\n this.name = 'InvalidCurrencyCodeError';\r\n }\r\n}\r\n\r\nexport class CurrencyMismatchError extends Error {\r\n constructor(message: string = \"Cannot perform operation on prices with different currencies.\") {\r\n super(`CurrencyMismatch: ${message}`);\r\n this.name = 'CurrencyMismatchError';\r\n }\r\n}\r\n\r\nexport class InvalidArgumentError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidArgument: ${message}`);\r\n this.name = 'InvalidArgumentError';\r\n }\r\n}\r\n\r\nexport class InvalidImageSourceError extends Error {\r\n constructor(message: string = \"Invalid image source configuration.\") {\r\n super(`InvalidImageSource: ${message}`);\r\n this.name = 'InvalidImageSourceError';\r\n }\r\n}\r\n\r\nexport class InvalidChargeError extends Error {\r\n constructor(message: string = \"Invalid charge data.\") {\r\n super(`InvalidCharge: ${message}`);\r\n this.name = 'InvalidChargeError';\r\n }\r\n}\r\n","import { CurrencyCode } from \"./Common\";\r\nimport { CurrencyLocaleMap, CurrencySymbolMap, OperationalCountryCurrency } from \"./Enum\";\r\nimport {\r\n InvalidPriceAmountError,\r\n InvalidCurrencyCodeError,\r\n CurrencyMismatchError,\r\n InvalidArgumentError\r\n} from \"./Error\";\r\n\r\nexport type PriceAttributes = {\r\n amount: number;\r\n currency: CurrencyCode;\r\n}\r\n\r\nexport type PriceData = PriceAttributes;\r\n\r\nexport default class PriceModel {\r\n #kind: string;\r\n protected amount: number;\r\n protected currency: CurrencyCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param amount - The initial price value.\r\n * @param currency - The currency code used for rounding and determining the currency symbol.\r\n * @throws {Error} If price is negative or country/currency mapping is missing.\r\n */\r\n constructor(data: PriceAttributes) {\r\n this.#kind = \"PriceModel\";\r\n if (data.amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative.\");\r\n }\r\n\r\n if (!data.currency) {\r\n throw new InvalidCurrencyCodeError(\"Currency code is required.\");\r\n }\r\n\r\n this.amount = data.amount;\r\n this.currency = data.currency;\r\n }\r\n\r\n get kind() {\r\n return this.#kind;\r\n }\r\n\r\n static isPriceModel(obj: unknown): obj is PriceModel {\r\n return typeof obj === \"object\" &&\r\n obj !== null &&\r\n (obj as any).kind === \"PriceModel\";\r\n }\r\n\r\n /**\r\n * Gets the currency associated with this price instance.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Returns the raw numeric price value.\r\n */\r\n public getAmount(): number {\r\n return this.amount;\r\n }\r\n\r\n /**\r\n *\r\n * @returns PriceData\r\n */\r\n public getDetails(): PriceData {\r\n return {\r\n amount: this.amount,\r\n currency: this.currency\r\n }\r\n }\r\n\r\n /**\r\n * Compares this price with another {@link PriceModel} instance.\r\n *\r\n * The comparison is performed using the numeric price value and is only valid\r\n * when both prices are expressed in the same currency.\r\n *\r\n * ### Comparison result:\r\n * - Returns a **negative number** if this price is **less than** `priceModel`\r\n * - Returns **zero** if both prices are **equal**\r\n * - Returns a **positive number** if this price is **greater than** `priceModel`\r\n *\r\n * @param priceModel - The {@link PriceModel} instance to compare against.\r\n *\r\n * @returns\r\n * A signed number representing the comparison result:\r\n * - `< 0` → this price is lower\r\n * - `0` → prices are equal\r\n * - `> 0` → this price is higher\r\n *\r\n * @throws {Error}\r\n * Throws an error if:\r\n * - `priceModel` is not an instance of {@link PriceModel}\r\n * - The currencies of the two prices do not match\r\n *\r\n * @example\r\n * ```ts\r\n * const a = new PriceModel(\"USD\", 100);\r\n * const b = new PriceModel(\"USD\", 150);\r\n *\r\n * a.compareTo(b); // -50\r\n * b.compareTo(a); // 50\r\n * a.compareTo(a); // 0\r\n * ```\r\n */\r\n public compareTo(priceModel: PriceModel): number {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return this.amount - priceModel.getAmount();\r\n }\r\n\r\n public add(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot add prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.amount + priceModel.getAmount(),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public subtract(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot subtract prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.amount - priceModel.getAmount(),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public multiply(factor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(factor)) {\r\n if (this.currency !== factor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot multiply prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.amount * factor.getAmount(),\r\n currency: this.currency\r\n });\r\n } else if (typeof factor === \"number\" && factor >= 0) {\r\n return new PriceModel({\r\n amount: this.amount * factor,\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a non-negative number.\");\r\n }\r\n\r\n public divide(divisor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(divisor)) {\r\n if (this.currency !== divisor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot divide prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.amount / divisor.getAmount(),\r\n currency: this.currency\r\n });\r\n } else if (typeof divisor === \"number\" && divisor > 0) {\r\n return new PriceModel({\r\n amount: this.amount / divisor,\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a positive number.\");\r\n }\r\n\r\n public min(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((minPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (minPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return minPrice.compareTo(currentPrice) < 0 ? minPrice : currentPrice;\r\n }, this);\r\n }\r\n\r\n public max(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((maxPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (maxPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return maxPrice.compareTo(currentPrice) > 0 ? maxPrice : currentPrice;\r\n }, this);\r\n }\r\n\r\n /**\r\n * Gets a zero value PriceModel for the same currency.\r\n * @returns A PriceModel instance representing zero in the same currency.\r\n */\r\n public zero(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: 0\r\n });\r\n }\r\n\r\n /**\r\n * Checks if the price is zero.\r\n * @returns True if the price is zero, false otherwise.\r\n */\r\n public isZero(): boolean {\r\n return this.amount === 0;\r\n }\r\n\r\n\r\n public round(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: this.getRoundedAmount()\r\n });\r\n }\r\n /**\r\n * Gets the rounded price value based on standard currency rules.\r\n * @returns The numeric price, rounded according to its currency's typical decimal places.\r\n */\r\n public getRoundedAmount(): number {\r\n return PriceModel.getRoundedAmount(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price stored in this instance.\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n public getFormattedString() {\r\n return PriceModel.getFormattedString(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n toString() {\r\n return this.getFormattedString();\r\n }\r\n\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the amount.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param amount - The initial amount value.\r\n * @param currency - The currency code for formatting.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the amount rounded to the next nearest integer (no decimals). Defaults to false.\r\n * @param options.style - The style of formatting, either 'currency' or 'decimal'. Defaults to 'currency'.\r\n * @param options.currencyDisplay - The display format for the currency symbol. Options are 'symbol', 'narrowSymbol', 'code', or 'name'. Defaults to 'symbol'.\r\n * @returns The formatted price string according to locale rules.\r\n * @throws {Error} If currency code is invalid.\r\n */\r\n static getFormattedString(amount: number, currency: CurrencyCode, options: {\r\n displayAsInteger?: boolean,\r\n style?: 'currency' | 'decimal',\r\n currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name'\r\n } = {\r\n displayAsInteger: false,\r\n style: 'currency',\r\n currencyDisplay: 'symbol'\r\n }): string {\r\n\r\n const locale = CurrencyLocaleMap[currency];\r\n if (!currency || !locale) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for formatting.');\r\n }\r\n\r\n let valueToFormat = amount;\r\n const fractionDigits = options.displayAsInteger ? 0 : PriceModel.getDecimalPlaces(currency);\r\n\r\n let formattingOptions: Intl.NumberFormatOptions = {\r\n style: options.style ?? 'currency',\r\n currency: currency,\r\n signDisplay: 'never',\r\n currencyDisplay: options.currencyDisplay,\r\n minimumFractionDigits: fractionDigits,\r\n maximumFractionDigits: fractionDigits,\r\n };\r\n\r\n if (options.displayAsInteger) {\r\n valueToFormat = Math.ceil(valueToFormat);\r\n }\r\n\r\n try {\r\n return new Intl.NumberFormat(locale, formattingOptions).format(valueToFormat);\r\n } catch (error) {\r\n console.error(`Error formatting price for currency \"${currency}\" and locale \"${locale}\":`, error);\r\n // Basic fallback without symbol if Intl fails completely\r\n return `${CurrencySymbolMap[currency] ?? currency} ${PriceModel.addThousandSeparators(valueToFormat.toFixed(fractionDigits))}`;\r\n }\r\n }\r\n\r\n /**\r\n * Helper method to determine standard decimal places for a currency.\r\n * @param currency - The currency code.\r\n * @returns The number of decimal places (0, 2, or 3 based on common rules).\r\n */\r\n private static getDecimalPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case OperationalCountryCurrency.INR:\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n /**\r\n * Adds basic thousand separators (commas) to a number string.\r\n * Does not handle different locale separators (e.g., periods, spaces).\r\n * @param numStr - The number string (potentially with decimals).\r\n * @returns The number string with commas added.\r\n */\r\n private static addThousandSeparators(numStr: string): string {\r\n const parts = numStr.split('.');\r\n const integerPart = parts[0];\r\n const decimalPart = parts.length > 1 ? '.' + parts[1] : '';\r\n\r\n const formattedInteger = integerPart.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\r\n return formattedInteger + decimalPart;\r\n }\r\n\r\n /**\r\n * Rounds a price value according to the standard decimal places\r\n * for the currency associated with the given country.\r\n *\r\n * @param price - The price value to round. Must be a non-negative number.\r\n * @param currency - The currency code to determine the rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the price is negative or currency is invalid.\r\n */\r\n static getRoundedAmount(amount: number, currency: CurrencyCode): number {\r\n if (amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative for rounding.\");\r\n }\r\n\r\n if (currency === undefined) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for rounding.');\r\n }\r\n\r\n const decimalPlaces = PriceModel.getDecimalPlaces(currency);\r\n const multiplier = Math.pow(10, decimalPlaces);\r\n const roundedValue = Math.round(amount * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n}","import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, ISODateTimeUTC } from \"./Common\";\r\nimport { TaxSystem } from \"./Enum\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport { TaxSlabNotFoundError } from \"./Error\";\r\n\r\nexport type TaxSlabData = {\r\n minUnitPrice: PriceData; // inclusive\r\n maxUnitPrice?: PriceData; // exclusive\r\n rate: number; // e.g. 0.05 = 5%\r\n};\r\n\r\nexport type TaxSlabModel = {\r\n minUnitPrice: PriceModel; // inclusive\r\n maxUnitPrice?: PriceModel; // exclusive\r\n rate: number; // e.g. 0.05 = 5%\r\n};\r\n\r\nexport type TaxSlabs = TaxSlabData[];\r\n\r\nexport type TaxRuleAttributes = {\r\n taxRuleId: string;\r\n taxCategory: string;\r\n taxSystem: TaxSystem;\r\n taxSubSystem: string;\r\n country: CountryCode;\r\n slabs: TaxSlabs;\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n};\r\n\r\nexport type TaxRuleData = Required<Omit<TaxRuleAttributes, 'effectiveFrom' | 'effectiveTo'>> & {\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n};\r\n\r\nexport class TaxRuleModel {\r\n protected taxRuleId: string;\r\n protected taxCategory: string;\r\n protected taxSystem: TaxSystem;\r\n protected taxSubSystem: string;\r\n protected country: CountryCode;\r\n protected slabs: TaxSlabModel[];\r\n protected effectiveFrom: Date;\r\n protected effectiveTo?: Date;\r\n\r\n /**\r\n * Creates an instance of TaxRuleModel.\r\n * @param data - The initial tax rule attributes.\r\n * @param date - Optional date for creation/modification (defaults to now).\r\n */\r\n constructor(data: TaxRuleAttributes) {\r\n this.taxRuleId = data.taxRuleId;\r\n this.taxSystem = data.taxSystem;\r\n this.taxSubSystem = data.taxSubSystem;\r\n this.taxCategory = data.taxCategory;\r\n this.country = data.country;\r\n this.slabs = data.slabs.map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: new PriceModel(s.minUnitPrice),\r\n maxUnitPrice: s.maxUnitPrice ? new PriceModel(s.maxUnitPrice) : undefined,\r\n }));\r\n this.effectiveFrom = new Date(data.effectiveFrom);\r\n this.effectiveTo = data.effectiveTo ? new Date(data.effectiveTo) : undefined;\r\n }\r\n\r\n getTaxRuleId(): string {\r\n return this.taxRuleId;\r\n }\r\n\r\n getTaxSystem(): TaxSystem {\r\n return this.taxSystem;\r\n }\r\n\r\n getTaxSubSystem(): string {\r\n return this.taxSubSystem;\r\n }\r\n\r\n getTaxCategory(): string {\r\n return this.taxCategory;\r\n }\r\n\r\n getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n getSlabs(): TaxSlabModel[] {\r\n return this.slabs;\r\n }\r\n\r\n getDetails(): TaxRuleData {\r\n return {\r\n taxRuleId: this.getTaxRuleId(),\r\n taxSystem: this.getTaxSystem(),\r\n taxSubSystem: this.getTaxSubSystem(),\r\n taxCategory: this.getTaxCategory(),\r\n country: this.getCountry(),\r\n slabs: this.getSlabs().map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: s.minUnitPrice.getDetails(),\r\n maxUnitPrice: s.maxUnitPrice ? s.maxUnitPrice.getDetails() : undefined,\r\n })),\r\n effectiveFrom: this.effectiveFrom.toISOString(),\r\n effectiveTo: this.effectiveTo ? this.effectiveTo.toISOString() : undefined\r\n };\r\n }\r\n\r\n /**\r\n * Checks whether this tax rule is applicable for the given category and country at a specific time.\r\n * @param taxCategory - The tax category to check.\r\n * @param country - The country code to check.\r\n * @param at - The date to check effectiveness against (defaults to now).\r\n * @returns True if the rule is applicable, false otherwise.\r\n */\r\n appliesTo(taxCategory: string, country: CountryCode, at: Date = new Date()): boolean {\r\n return (\r\n this.taxCategory === taxCategory &&\r\n this.country === country &&\r\n this.effectiveFrom <= at &&\r\n (this.effectiveTo ? this.effectiveTo >= at : true)\r\n );\r\n }\r\n\r\n /**\r\n * Gets the applicable tax rate for the given unit price based on the slabs.\r\n * @param unitPrice - The unit price to match against slabs.\r\n * @returns The applicable tax rate as a decimal (e.g., 0.18 for 18%).\r\n */\r\n getApplicableTaxRate(unitPrice: PriceModel): number {\r\n return TaxRuleModel.getApplicableTaxRate(unitPrice, this.slabs);\r\n }\r\n\r\n /**\r\n * Calculates the tax amount for a given taxable amount.\r\n * @param unitPrice - The unit price used to determine which tax slab applies.\r\n * @returns The calculated tax amount as a PriceModel.\r\n */\r\n calculateTax(unitPrice: PriceModel): PriceModel {\r\n const rate = this.getApplicableTaxRate(unitPrice);\r\n return unitPrice.multiply(rate).round();\r\n }\r\n\r\n /**\r\n * Calculates the applicable tax rate for a given unit price.\r\n * @param unitPrice - The unit price to find the matching tax slab for.\r\n * @returns The tax rate as a decimal (e.g., 0.05 for 5%).\r\n * @throws {TaxSlabNotFoundError} If no applicable slab or multiple slabs are found.\r\n */\r\n static getApplicableTaxRate(unitPrice: PriceModel, taxSlabs: TaxSlabModel[]): number {\r\n const slabs = taxSlabs.filter(s =>\r\n (s.minUnitPrice === undefined || unitPrice.compareTo(s.minUnitPrice) >= 0) &&\r\n (s.maxUnitPrice === undefined || unitPrice.compareTo(s.maxUnitPrice) < 0)\r\n );\r\n\r\n if (slabs.length !== 1) {\r\n throw new TaxSlabNotFoundError();\r\n }\r\n\r\n return slabs[0].rate;\r\n }\r\n\r\n static getTaxRateDisplayString(taxRule: TaxRuleModel, rate: number, formateOption: {\r\n percentageOnly?: boolean;\r\n }): string {\r\n const percentage = rate * 100;\r\n // Format to remove trailing zeros if it's an integer, otherwise keep up to 2 decimal places\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n\r\n if (formateOption.percentageOnly) {\r\n return `${rateStr}%`;\r\n }\r\n\r\n if (taxRule.getTaxSystem() === TaxSystem.GST) {\r\n return `${rateStr}% ${taxRule.getTaxSubSystem()}`;\r\n }\r\n return `${rateStr}% ${taxRule.getTaxSystem()}`;\r\n }\r\n}\r\n\r\n\r\nexport type FixedTaxRuleAttributes = {\r\n taxRuleId: string;\r\n taxCategory: string;\r\n taxSystem: TaxSystem;\r\n taxSubSystem: string;\r\n country: CountryCode;\r\n rate: number;\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n}\r\n\r\nexport type FixedTaxRuleData = TaxRuleData & {\r\n rate: number;\r\n};\r\n\r\n/**\r\n * A specialized version of TaxRuleModel for fixed-rate taxes (single slab).\r\n * Ideal for components like Charges where slab-based logic is not required.\r\n */\r\nexport class FixedTaxRuleModel extends TaxRuleModel {\r\n protected rate: number;\r\n /**\r\n * Creates an instance of FixedTaxRuleModel with a single fixed-rate slab.\r\n * @param id - Unique identifier for the tax rule.\r\n * @param system - The tax system (e.g., GST).\r\n * @param subSystem - The tax sub-system (e.g., CGST).\r\n * @param rate - The fixed tax rate (e.g., 0.18 for 18%).\r\n * @param category - The tax category (e.g., SHIPPING).\r\n * @param country - The country code.\r\n */\r\n constructor(data: FixedTaxRuleAttributes) {\r\n super({\r\n taxRuleId: data.taxRuleId,\r\n taxSystem: data.taxSystem,\r\n taxSubSystem: data.taxSubSystem,\r\n taxCategory: data.taxCategory,\r\n country: data.country,\r\n effectiveFrom: data.effectiveFrom,\r\n effectiveTo: data.effectiveTo,\r\n slabs: [\r\n {\r\n minUnitPrice: { amount: 0, currency: 'INR' as any }, // Default base, currency agnostic for matching\r\n rate: data.rate\r\n }\r\n ]\r\n });\r\n this.rate = data.rate;\r\n }\r\n\r\n /**\r\n * Overrides calculateTax to ensure it always uses the fixed rate, \r\n * bypassing price-based slab lookup if unnecessary (though the slab will match anyway).\r\n */\r\n public getApplicableTaxRate(): number {\r\n return this.slabs[0].rate;\r\n }\r\n\r\n public getDetails(): FixedTaxRuleData {\r\n return {\r\n taxRuleId: this.getTaxRuleId(),\r\n taxSystem: this.getTaxSystem(),\r\n taxSubSystem: this.getTaxSubSystem(),\r\n taxCategory: this.getTaxCategory(),\r\n country: this.getCountry(),\r\n rate: this.getApplicableTaxRate(),\r\n slabs: this.getSlabs().map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: s.minUnitPrice.getDetails(),\r\n maxUnitPrice: s.maxUnitPrice ? s.maxUnitPrice.getDetails() : undefined,\r\n })),\r\n effectiveFrom: this.effectiveFrom.toISOString(),\r\n effectiveTo: this.effectiveTo ? this.effectiveTo.toISOString() : undefined\r\n };\r\n }\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/Classes/Enum.ts","../../src/Classes/Error.ts","../../src/Classes/Price.ts","../../src/Classes/TaxRule.ts"],"names":["CurrencySymbolMap","CurrencyLocaleMap","TaxSlabNotFoundError","message","InvalidPriceAmountError","InvalidCurrencyCodeError","CurrencyMismatchError","InvalidArgumentError","PriceModel","_PriceModel","#kind","data","obj","priceModel","factor","divisor","priceModels","minPrice","currentPrice","maxPrice","amount","currency","options","locale","valueToFormat","fractionDigits","formattingOptions","error","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier","TaxRuleBaseModel","taxCategory","taxCountry","at","taxRule","rate","formateOption","percentage","rateStr","TaxRuleModel","_TaxRuleModel","s","unitPrice","taxSlabs","slabs","FixedTaxRuleModel"],"mappings":"aAsCO,IAAMA,CAAoB,CAAA,CAC9B,GAAiC,CAAA,QACpC,EAEaC,CAAoB,CAAA,CAC9B,GAAiC,CAAA,OACpC,EC6DO,IAAMC,CAAAA,CAAN,cAAmC,KAAM,CAC5C,WAAYC,CAAAA,CAAAA,CAAkB,0EAA4E,CAAA,CACtG,KAAM,CAAA,CAAA,iBAAA,EAAoBA,CAAO,CAAA,CAAE,EACnC,IAAK,CAAA,IAAA,CAAO,uBAChB,CACJ,EAEaC,CAAN,CAAA,cAAsC,KAAM,CAC/C,YAAYD,CAAkB,CAAA,4BAAA,CAA8B,CACxD,KAAA,CAAM,CAAkBA,eAAAA,EAAAA,CAAO,CAAE,CAAA,CAAA,CACjC,KAAK,IAAO,CAAA,0BAChB,CACJ,CAAA,CAEaE,EAAN,cAAuC,KAAM,CAChD,WAAA,CAAYF,EAAkB,4BAA8B,CAAA,CACxD,KAAM,CAAA,CAAA,iBAAA,EAAoBA,CAAO,CAAA,CAAE,CACnC,CAAA,IAAA,CAAK,KAAO,2BAChB,CACJ,CAEaG,CAAAA,CAAAA,CAAN,cAAoC,KAAM,CAC7C,WAAYH,CAAAA,CAAAA,CAAkB,gEAAiE,CAC3F,KAAA,CAAM,CAAqBA,kBAAAA,EAAAA,CAAO,CAAE,CAAA,CAAA,CACpC,IAAK,CAAA,IAAA,CAAO,wBAChB,CACJ,CAAA,CAEaI,CAAN,CAAA,cAAmC,KAAM,CAC5C,WAAA,CAAYJ,CAAiB,CAAA,CACzB,MAAM,CAAoBA,iBAAAA,EAAAA,CAAO,CAAE,CAAA,CAAA,CACnC,IAAK,CAAA,IAAA,CAAO,uBAChB,CACJ,EC1HA,IAAqBK,CAAAA,CAArB,MAAqBC,CAAW,CAC9BC,EACU,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IAC3BA,CAAE,CAAA,YAAA,GAAiB,KAAaC,CAAAA,EAAAA,CAAAA,CAAU,SAAUD,CAAAA,CAAAA,CAAE,YAAY,CAAA,EAAK,KACvEA,CAAE,CAAA,YAAA,GAAiB,KAAaC,CAAAA,EAAAA,CAAAA,CAAU,UAAUD,CAAE,CAAA,YAAY,CAAI,CAAA,CAAA,CACzE,EAEA,GAAIG,CAAAA,CAAM,MAAW,GAAA,CAAA,CACnB,MAAM,IAAI9C,CAAAA,CAGZ,OAAO8C,CAAAA,CAAM,CAAC,CAAE,CAAA,IAClB,CACF,CAAA,CAeaC,EAAN,cAAgCf,CAAiB,CAC5C,IAAA,CACA,aACA,YAEV,CAAA,WAAA,CAAYvB,CAA8B,CAAA,CACxC,KAAMA,CAAAA,CAAI,CACV,CAAA,IAAA,CAAK,KAAOA,CAAK,CAAA,IAAA,CACjB,IAAK,CAAA,YAAA,CAAe,IAAIH,CAAWG,CAAAA,CAAAA,CAAK,YAAY,CAAA,CACpD,KAAK,YAAeA,CAAAA,CAAAA,CAAK,YAAe,CAAA,IAAIH,CAAWG,CAAAA,CAAAA,CAAK,YAAY,CAAA,CAAI,OAC9E,CAEO,oBAAA,EAA+B,CACpC,OAAO,KAAK,IACd,CAMA,YAAamC,CAAAA,CAAAA,CAAmC,CAC9C,IAAMP,CAAAA,CAAO,IAAK,CAAA,oBAAA,EAClB,CAAA,OAAOO,CAAU,CAAA,QAAA,CAASP,CAAI,CAAE,CAAA,KAAA,EAClC,CAEO,YAA+B,CACpC,OAAO,CACL,GAAG,MAAM,UAAW,EAAA,CACpB,IAAM,CAAA,IAAA,CAAK,sBACX,CAAA,YAAA,CAAc,IAAK,CAAA,YAAA,CAAa,YAChC,CAAA,YAAA,CAAc,IAAK,CAAA,YAAA,CAAe,KAAK,YAAa,CAAA,UAAA,EAAe,CAAA,KAAA,CACrE,CACF,CACF","file":"TaxRule.js","sourcesContent":["/**\r\n * Represents the countries where the application operates or products are available.\r\n */\r\nexport enum OperationalCountry {\r\n /** India */ IN = 'IN',\r\n}\r\n\r\nexport enum OperationalCountryCurrency {\r\n /** India */ INR = 'INR',\r\n}\r\n\r\nexport enum OperationalLocale {\r\n /** India */ 'en-IN' = 'en-IN',\r\n /** India ( Kannada) */ 'kn-IN' = 'kn-IN'\r\n}\r\n\r\nexport enum OperationalLanguage {\r\n en = 'en',\r\n kn = 'kn'\r\n}\r\n\r\nexport const LocaleLanguageMap: Record<OperationalLocale, OperationalLanguage> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalLanguage.en,\r\n [OperationalLocale[\"kn-IN\"]]: OperationalLanguage.kn,\r\n}\r\n\r\nexport const LocaleCountryMap: Record<OperationalLocale, OperationalCountry> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalCountry.IN,\r\n [OperationalLocale[\"kn-IN\"]]: OperationalCountry.IN,\r\n}\r\n\r\n/**\r\n * Defines the supported ISO 4217 currency codes as an enumeration.\r\n */\r\nexport const CountryCurrencyMap = {\r\n /** India */[OperationalCountry.IN]: OperationalCountryCurrency.INR,\r\n};\r\n\r\nexport const CurrencySymbolMap = {\r\n [OperationalCountryCurrency.INR]: '₹',\r\n}\r\n\r\nexport const CurrencyLocaleMap = {\r\n [OperationalCountryCurrency.INR]: OperationalLocale[\"en-IN\"],\r\n}\r\n\r\n/**\r\n * Defines standard gender categories for product targeting.\r\n */\r\nexport enum GenderCategory {\r\n MALE = 'Male',\r\n FEMALE = 'Female',\r\n UNISEX = 'Unisex',\r\n KIDS = 'Kids',\r\n BOY = 'Boy',\r\n GIRL = 'Girl',\r\n GENERAL = 'General',\r\n}\r\n\r\nexport enum ImageCategory {\r\n PRIMARY = 'PRIMARY',\r\n GALLERY = 'GALLERY'\r\n}\r\n\r\nexport enum ChargeType {\r\n SHIPPING = 'SHIPPING',\r\n ADJUSTMENT = 'ADJUSTMENT'\r\n}\r\n\r\nexport enum TaxSystem {\r\n GST = 'GST',\r\n}\r\n\r\n/**\r\n * LineItemState\r\n * \r\n * INITIAL: Item added to order, not yet processed.\r\n * PROCESSING: Item is being prepared for shipment.\r\n * SHIPPED: Item dispatched to customer.\r\n * DELIVERED: Item delivered to customer.\r\n * CANCELLED: Item cancelled before shipment or delivery.\r\n * RETURN_REQUESTED: Customer requests to return item.\r\n * RETURNED: Item received back from customer.\r\n * REFUND_INITIATED: Refund initiated for item.\r\n * REFUNDED: Refund processed for item.\r\n * ON_HOLD: Item is paused due to payment, inventory, or other issues.\r\n */\r\nexport enum LineItemState {\r\n INITIAL = \"INITIAL\",\r\n PROCESSING = \"PROCESSING\",\r\n SHIPPED = \"SHIPPED\",\r\n DELIVERED = \"DELIVERED\",\r\n CANCELLED = \"CANCELLED\",\r\n RETURN_REQUESTED = \"RETURN_REQUESTED\",\r\n RETURNED = \"RETURNED\",\r\n REFUND_INITIATED = \"REFUND_INITIATED\",\r\n REFUNDED = \"REFUNDED\",\r\n ON_HOLD = \"ON_HOLD\",\r\n}","export class LineItemNotFoundError extends Error {\r\n constructor(lineItemId: string) {\r\n super(`Line item with ID '${lineItemId}' not found in the cart.`);\r\n this.name = 'LineItemNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidLineItemStateError extends Error {\r\n constructor(state: string) {\r\n super(`Invalid line item state: ${state}`);\r\n this.name = 'InvalidLineItemStateError';\r\n }\r\n}\r\n\r\nexport class DuplicateSizeError extends Error {\r\n constructor(size: string) {\r\n super(`Duplicate size found: ${size}`);\r\n this.name = 'DuplicateSizeError';\r\n }\r\n}\r\n\r\nexport class DuplicateSelectionAttributeError extends Error {\r\n constructor(attribute: string) {\r\n super(`Duplicate selection attribute found: ${attribute}`);\r\n this.name = 'DuplicateSelectionAttributeError';\r\n }\r\n}\r\n\r\nexport class ProductMismatchError extends Error {\r\n constructor(message: string = \"Product and selection attributes do not match.\") {\r\n super(`ProductMismatch: ${message}`);\r\n this.name = 'ProductMismatchError';\r\n }\r\n}\r\n\r\nexport class ProductInactiveError extends Error {\r\n constructor(message: string = \"Product is not active.\") {\r\n super(`ProductInactive: ${message}`);\r\n this.name = 'ProductInactiveError';\r\n }\r\n}\r\n\r\nexport class SelectionAttributeParseError extends Error {\r\n constructor(message: string = \"Failed to parse selection attributes key.\") {\r\n super(`SelectionAttributeParseError: ${message}`);\r\n this.name = 'SelectionAttributeParseError';\r\n }\r\n}\r\n\r\nexport class SizeMismatchError extends Error {\r\n constructor(message: string = \"Size does not match.\") {\r\n super(`SizeMismatch: ${message}`);\r\n this.name = 'SizeMismatchError';\r\n }\r\n}\r\n\r\nexport class PricingNotFoundError extends Error {\r\n constructor(message: string = \"Pricing details not available for the product\") {\r\n super(`NotFound: ${message}`);\r\n this.name = 'PricingNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxRuleError extends Error {\r\n constructor(message: string = \"Tax rule category mismatch.\") {\r\n super(`InvalidTaxRule: ${message}`);\r\n this.name = 'InvalidTaxRuleError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxCategoryError extends Error {\r\n constructor(message: string = \"Tax category is not valid.\") {\r\n super(`InvalidTaxCategory: ${message}`);\r\n this.name = 'InvalidTaxCategoryError';\r\n }\r\n}\r\n\r\nexport class InvalidMinQuantityError extends Error {\r\n constructor(message: string = \"Minimum quantity must be greater than zero.\") {\r\n super(`InvalidMinQuantity: ${message}`);\r\n this.name = 'InvalidMinQuantityError';\r\n }\r\n}\r\n\r\nexport class InvalidTieredPriceError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidTieredPrice: ${message}`);\r\n this.name = 'InvalidTieredPriceError';\r\n }\r\n}\r\n\r\nexport class InvalidQuantityError extends Error {\r\n constructor(message: string = \"Quantity must be greater than zero.\") {\r\n super(`InvalidQuantity: ${message}`);\r\n this.name = 'InvalidQuantityError';\r\n }\r\n}\r\n\r\nexport class NoApplicableTierError extends Error {\r\n constructor(quantity: number) {\r\n super(`NoApplicableTier: Quantity ${quantity} does not meet the minimum purchase requirement.`);\r\n this.name = 'NoApplicableTierError';\r\n }\r\n}\r\n\r\nexport class TaxSlabNotFoundError extends Error {\r\n constructor(message: string = \"No applicable tax slab or multiple slabs found for the given unit price.\") {\r\n super(`TaxSlabNotFound: ${message}`);\r\n this.name = 'TaxSlabNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidPriceAmountError extends Error {\r\n constructor(message: string = \"Amount cannot be negative.\") {\r\n super(`InvalidAmount: ${message}`);\r\n this.name = 'InvalidPriceAmountError';\r\n }\r\n}\r\n\r\nexport class InvalidCurrencyCodeError extends Error {\r\n constructor(message: string = \"Currency code is required.\") {\r\n super(`InvalidCurrency: ${message}`);\r\n this.name = 'InvalidCurrencyCodeError';\r\n }\r\n}\r\n\r\nexport class CurrencyMismatchError extends Error {\r\n constructor(message: string = \"Cannot perform operation on prices with different currencies.\") {\r\n super(`CurrencyMismatch: ${message}`);\r\n this.name = 'CurrencyMismatchError';\r\n }\r\n}\r\n\r\nexport class InvalidArgumentError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidArgument: ${message}`);\r\n this.name = 'InvalidArgumentError';\r\n }\r\n}\r\n\r\nexport class InvalidImageSourceError extends Error {\r\n constructor(message: string = \"Invalid image source configuration.\") {\r\n super(`InvalidImageSource: ${message}`);\r\n this.name = 'InvalidImageSourceError';\r\n }\r\n}\r\n\r\nexport class InvalidChargeError extends Error {\r\n constructor(message: string = \"Invalid charge data.\") {\r\n super(`InvalidCharge: ${message}`);\r\n this.name = 'InvalidChargeError';\r\n }\r\n}\r\n","import { CurrencyCode } from \"./Common\";\r\nimport { CurrencyLocaleMap, CurrencySymbolMap, OperationalCountryCurrency } from \"./Enum\";\r\nimport {\r\n InvalidPriceAmountError,\r\n InvalidCurrencyCodeError,\r\n CurrencyMismatchError,\r\n InvalidArgumentError\r\n} from \"./Error\";\r\n\r\nexport type PriceAttributes = {\r\n amount: number;\r\n currency: CurrencyCode;\r\n}\r\n\r\nexport type PriceData = PriceAttributes;\r\n\r\nexport default class PriceModel {\r\n #kind: string;\r\n protected amount: number;\r\n protected currency: CurrencyCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param amount - The initial price value.\r\n * @param currency - The currency code used for rounding and determining the currency symbol.\r\n * @throws {Error} If price is negative or country/currency mapping is missing.\r\n */\r\n constructor(data: PriceAttributes) {\r\n this.#kind = \"PriceModel\";\r\n if (data.amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative.\");\r\n }\r\n\r\n if (!data.currency) {\r\n throw new InvalidCurrencyCodeError(\"Currency code is required.\");\r\n }\r\n\r\n this.amount = data.amount;\r\n this.currency = data.currency;\r\n }\r\n\r\n get kind() {\r\n return this.#kind;\r\n }\r\n\r\n static isPriceModel(obj: unknown): obj is PriceModel {\r\n return typeof obj === \"object\" &&\r\n obj !== null &&\r\n (obj as any).kind === \"PriceModel\";\r\n }\r\n\r\n /**\r\n * Gets the currency associated with this price instance.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Returns the raw numeric price value.\r\n */\r\n public getAmount(): number {\r\n return this.amount;\r\n }\r\n\r\n /**\r\n *\r\n * @returns PriceData\r\n */\r\n public getDetails(): PriceData {\r\n return {\r\n amount: this.amount,\r\n currency: this.currency\r\n }\r\n }\r\n\r\n /**\r\n * Compares this price with another {@link PriceModel} instance.\r\n *\r\n * The comparison is performed using the numeric price value and is only valid\r\n * when both prices are expressed in the same currency.\r\n *\r\n * ### Comparison result:\r\n * - Returns a **negative number** if this price is **less than** `priceModel`\r\n * - Returns **zero** if both prices are **equal**\r\n * - Returns a **positive number** if this price is **greater than** `priceModel`\r\n *\r\n * @param priceModel - The {@link PriceModel} instance to compare against.\r\n *\r\n * @returns\r\n * A signed number representing the comparison result:\r\n * - `< 0` → this price is lower\r\n * - `0` → prices are equal\r\n * - `> 0` → this price is higher\r\n *\r\n * @throws {Error}\r\n * Throws an error if:\r\n * - `priceModel` is not an instance of {@link PriceModel}\r\n * - The currencies of the two prices do not match\r\n *\r\n * @example\r\n * ```ts\r\n * const a = new PriceModel(\"USD\", 100);\r\n * const b = new PriceModel(\"USD\", 150);\r\n *\r\n * a.compareTo(b); // -50\r\n * b.compareTo(a); // 50\r\n * a.compareTo(a); // 0\r\n * ```\r\n */\r\n public compareTo(priceModel: PriceModel): number {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return this.amount - priceModel.getAmount();\r\n }\r\n\r\n public add(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot add prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.amount + priceModel.getAmount(),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public subtract(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot subtract prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.amount - priceModel.getAmount(),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public multiply(factor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(factor)) {\r\n if (this.currency !== factor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot multiply prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.amount * factor.getAmount(),\r\n currency: this.currency\r\n });\r\n } else if (typeof factor === \"number\" && factor >= 0) {\r\n return new PriceModel({\r\n amount: this.amount * factor,\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a non-negative number.\");\r\n }\r\n\r\n public divide(divisor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(divisor)) {\r\n if (this.currency !== divisor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot divide prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.amount / divisor.getAmount(),\r\n currency: this.currency\r\n });\r\n } else if (typeof divisor === \"number\" && divisor > 0) {\r\n return new PriceModel({\r\n amount: this.amount / divisor,\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a positive number.\");\r\n }\r\n\r\n public min(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((minPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (minPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return minPrice.compareTo(currentPrice) < 0 ? minPrice : currentPrice;\r\n }, this);\r\n }\r\n\r\n public max(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((maxPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (maxPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return maxPrice.compareTo(currentPrice) > 0 ? maxPrice : currentPrice;\r\n }, this);\r\n }\r\n\r\n /**\r\n * Gets a zero value PriceModel for the same currency.\r\n * @returns A PriceModel instance representing zero in the same currency.\r\n */\r\n public zero(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: 0\r\n });\r\n }\r\n\r\n /**\r\n * Checks if the price is zero.\r\n * @returns True if the price is zero, false otherwise.\r\n */\r\n public isZero(): boolean {\r\n return this.amount === 0;\r\n }\r\n\r\n\r\n public round(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: this.getRoundedAmount()\r\n });\r\n }\r\n\r\n /**\r\n * Gets the rounded price value based on standard currency rules.\r\n * @returns The numeric price, rounded according to its currency's typical decimal places.\r\n */\r\n public getRoundedAmount(): number {\r\n return PriceModel.getRoundedAmount(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price stored in this instance.\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n public getFormattedString() {\r\n return PriceModel.getFormattedString(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n toString() {\r\n return this.getFormattedString();\r\n }\r\n\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the amount.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param amount - The initial amount value.\r\n * @param currency - The currency code for formatting.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the amount rounded to the next nearest integer (no decimals). Defaults to false.\r\n * @param options.style - The style of formatting, either 'currency' or 'decimal'. Defaults to 'currency'.\r\n * @param options.currencyDisplay - The display format for the currency symbol. Options are 'symbol', 'narrowSymbol', 'code', or 'name'. Defaults to 'symbol'.\r\n * @returns The formatted price string according to locale rules.\r\n * @throws {Error} If currency code is invalid.\r\n */\r\n static getFormattedString(amount: number, currency: CurrencyCode, options: {\r\n displayAsInteger?: boolean,\r\n style?: 'currency' | 'decimal',\r\n currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name'\r\n } = {\r\n displayAsInteger: false,\r\n style: 'currency',\r\n currencyDisplay: 'symbol'\r\n }): string {\r\n\r\n const locale = CurrencyLocaleMap[currency];\r\n if (!currency || !locale) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for formatting.');\r\n }\r\n\r\n let valueToFormat = amount;\r\n const fractionDigits = options.displayAsInteger ? 0 : PriceModel.getDecimalPlaces(currency);\r\n\r\n let formattingOptions: Intl.NumberFormatOptions = {\r\n style: options.style ?? 'currency',\r\n currency: currency,\r\n signDisplay: 'never',\r\n currencyDisplay: options.currencyDisplay,\r\n minimumFractionDigits: fractionDigits,\r\n maximumFractionDigits: fractionDigits,\r\n };\r\n\r\n if (options.displayAsInteger) {\r\n valueToFormat = Math.ceil(valueToFormat);\r\n }\r\n\r\n try {\r\n return new Intl.NumberFormat(locale, formattingOptions).format(valueToFormat);\r\n } catch (error) {\r\n console.error(`Error formatting price for currency \"${currency}\" and locale \"${locale}\":`, error);\r\n // Basic fallback without symbol if Intl fails completely\r\n return `${CurrencySymbolMap[currency] ?? currency} ${PriceModel.addThousandSeparators(valueToFormat.toFixed(fractionDigits))}`;\r\n }\r\n }\r\n\r\n /**\r\n * Helper method to determine standard decimal places for a currency.\r\n * @param currency - The currency code.\r\n * @returns The number of decimal places (0, 2, or 3 based on common rules).\r\n */\r\n private static getDecimalPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case OperationalCountryCurrency.INR:\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n /**\r\n * Adds basic thousand separators (commas) to a number string.\r\n * Does not handle different locale separators (e.g., periods, spaces).\r\n * @param numStr - The number string (potentially with decimals).\r\n * @returns The number string with commas added.\r\n */\r\n private static addThousandSeparators(numStr: string): string {\r\n const parts = numStr.split('.');\r\n const integerPart = parts[0];\r\n const decimalPart = parts.length > 1 ? '.' + parts[1] : '';\r\n\r\n const formattedInteger = integerPart.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\r\n return formattedInteger + decimalPart;\r\n }\r\n\r\n /**\r\n * Rounds a price value according to the standard decimal places\r\n * for the currency associated with the given country.\r\n *\r\n * @param price - The price value to round. Must be a non-negative number.\r\n * @param currency - The currency code to determine the rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the price is negative or currency is invalid.\r\n */\r\n static getRoundedAmount(amount: number, currency: CurrencyCode): number {\r\n if (amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative for rounding.\");\r\n }\r\n\r\n if (currency === undefined) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for rounding.');\r\n }\r\n\r\n const decimalPlaces = PriceModel.getDecimalPlaces(currency);\r\n const multiplier = Math.pow(10, decimalPlaces);\r\n const roundedValue = Math.round(amount * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n}","import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, ISODateTimeUTC } from \"./Common\";\r\nimport { TaxSystem } from \"./Enum\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport { TaxSlabNotFoundError } from \"./Error\";\r\n\r\nexport type TaxRuleBaseAttributes = {\r\n taxRuleId: string;\r\n taxCategory: string;\r\n taxSystem: TaxSystem;\r\n taxSubSystem: string;\r\n taxCountry: CountryCode;\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n}\r\n\r\nexport type TaxRuleBaseData = TaxRuleBaseAttributes;\r\n\r\nexport class TaxRuleBaseModel {\r\n protected taxRuleId: string;\r\n protected taxCategory: string;\r\n protected taxSystem: TaxSystem;\r\n protected taxSubSystem: string;\r\n protected taxCountry: CountryCode;\r\n protected effectiveFrom: Date;\r\n protected effectiveTo?: Date;\r\n\r\n constructor(data: TaxRuleBaseAttributes) {\r\n this.taxRuleId = data.taxRuleId;\r\n this.taxSystem = data.taxSystem;\r\n this.taxSubSystem = data.taxSubSystem;\r\n this.taxCategory = data.taxCategory;\r\n this.taxCountry = data.taxCountry;\r\n this.effectiveFrom = new Date(data.effectiveFrom);\r\n this.effectiveTo = data.effectiveTo ? new Date(data.effectiveTo) : undefined;\r\n }\r\n\r\n getTaxRuleId(): string {\r\n return this.taxRuleId;\r\n }\r\n\r\n getTaxSystem(): TaxSystem {\r\n return this.taxSystem;\r\n }\r\n\r\n getTaxSubSystem(): string {\r\n return this.taxSubSystem;\r\n }\r\n\r\n getTaxCategory(): string {\r\n return this.taxCategory;\r\n }\r\n\r\n getTaxCountry(): CountryCode {\r\n return this.taxCountry;\r\n }\r\n\r\n getEffectiveFrom(): Date {\r\n return this.effectiveFrom;\r\n }\r\n\r\n getEffectiveTo(): Date | undefined {\r\n return this.effectiveTo;\r\n }\r\n\r\n getDetails(): TaxRuleBaseData {\r\n return {\r\n taxRuleId: this.getTaxRuleId(),\r\n taxSystem: this.getTaxSystem(),\r\n taxSubSystem: this.getTaxSubSystem(),\r\n taxCategory: this.getTaxCategory(),\r\n taxCountry: this.getTaxCountry(),\r\n effectiveFrom: this.effectiveFrom.toISOString(),\r\n effectiveTo: this.effectiveTo ? this.effectiveTo.toISOString() : undefined\r\n };\r\n }\r\n\r\n /**\r\n * Checks whether this tax rule is applicable for the given category and taxCountry at a specific time.\r\n * @param taxCategory - The tax category to check.\r\n * @param taxCountry - The taxCountry code to check.\r\n * @param at - The date to check effectiveness against (defaults to now).\r\n * @returns True if the rule is applicable, false otherwise.\r\n */\r\n appliesTo(taxCategory: string, taxCountry: CountryCode, at: Date = new Date()): boolean {\r\n return (\r\n this.taxCategory === taxCategory &&\r\n this.taxCountry === taxCountry &&\r\n this.effectiveFrom <= at &&\r\n (this.effectiveTo ? this.effectiveTo >= at : true)\r\n );\r\n }\r\n\r\n static getTaxRateDisplayString(taxRule: TaxRuleBaseModel, rate: number, formateOption?: {\r\n percentageOnly?: boolean;\r\n }): string {\r\n const percentage = rate * 100;\r\n // Format to remove trailing zeros if it's an integer, otherwise keep up to 2 decimal places\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n\r\n if (formateOption?.percentageOnly) {\r\n return `${rateStr}%`;\r\n }\r\n\r\n if (taxRule.getTaxSystem() === TaxSystem.GST) {\r\n return `${rateStr}% ${taxRule.getTaxSubSystem()}`;\r\n }\r\n return `${rateStr}% ${taxRule.getTaxSystem()}`;\r\n }\r\n}\r\n\r\nexport type TaxSlabData = {\r\n minUnitPrice: PriceData; // inclusive\r\n maxUnitPrice?: PriceData; // exclusive\r\n rate: number; // e.g. 0.05 = 5%\r\n};\r\n\r\nexport type TaxSlabModel = {\r\n minUnitPrice: PriceModel; // inclusive\r\n maxUnitPrice?: PriceModel; // exclusive\r\n rate: number; // e.g. 0.05 = 5%\r\n};\r\n\r\nexport type TaxSlabs = TaxSlabData[];\r\n\r\nexport type TaxRuleAttributes = TaxRuleBaseAttributes & {\r\n slabs: TaxSlabs;\r\n};\r\n\r\nexport type TaxRuleData = TaxRuleAttributes;\r\n\r\nexport class TaxRuleModel extends TaxRuleBaseModel {\r\n protected slabs: TaxSlabModel[];\r\n\r\n /**\r\n * Creates an instance of TaxRuleModel.\r\n * @param data - The initial tax rule attributes.\r\n */\r\n constructor(data: TaxRuleAttributes) {\r\n super(data)\r\n this.slabs = data.slabs.map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: new PriceModel(s.minUnitPrice),\r\n maxUnitPrice: s.maxUnitPrice ? new PriceModel(s.maxUnitPrice) : undefined,\r\n }));\r\n }\r\n\r\n getSlabs(): TaxSlabModel[] {\r\n return this.slabs;\r\n }\r\n\r\n getDetails(): TaxRuleData {\r\n return {\r\n ...super.getDetails(),\r\n slabs: this.getSlabs().map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: s.minUnitPrice.getDetails(),\r\n maxUnitPrice: s.maxUnitPrice ? s.maxUnitPrice.getDetails() : undefined,\r\n })),\r\n };\r\n }\r\n\r\n /**\r\n * Gets the applicable tax rate for the given unit price based on the slabs.\r\n * @param unitPrice - The unit price to match against slabs.\r\n * @returns The applicable tax rate as a decimal (e.g., 0.18 for 18%).\r\n */\r\n getApplicableTaxRate(unitPrice: PriceModel): number {\r\n return TaxRuleModel.getApplicableTaxRate(unitPrice, this.slabs);\r\n }\r\n\r\n /**\r\n * Calculates the tax amount for a given taxable amount.\r\n * @param unitPrice - The unit price used to determine which tax slab applies.\r\n * @returns The calculated tax amount as a PriceModel.\r\n */\r\n calculateTax(unitPrice: PriceModel): PriceModel {\r\n const rate = this.getApplicableTaxRate(unitPrice);\r\n return unitPrice.multiply(rate).round();\r\n }\r\n\r\n /**\r\n * Calculates the applicable tax rate for a given unit price.\r\n * @param unitPrice - The unit price to find the matching tax slab for.\r\n * @returns The tax rate as a decimal (e.g., 0.05 for 5%).\r\n * @throws {TaxSlabNotFoundError} If no applicable slab or multiple slabs are found.\r\n */\r\n static getApplicableTaxRate(unitPrice: PriceModel, taxSlabs: TaxSlabModel[]): number {\r\n const slabs = taxSlabs.filter(s =>\r\n (s.minUnitPrice === undefined || unitPrice.compareTo(s.minUnitPrice) >= 0) &&\r\n (s.maxUnitPrice === undefined || unitPrice.compareTo(s.maxUnitPrice) < 0)\r\n );\r\n\r\n if (slabs.length !== 1) {\r\n throw new TaxSlabNotFoundError();\r\n }\r\n\r\n return slabs[0].rate;\r\n }\r\n}\r\n\r\n\r\nexport type FixedTaxRuleAttributes = TaxRuleBaseAttributes & {\r\n rate: number;\r\n minUnitPrice: PriceData;\r\n maxUnitPrice?: PriceData;\r\n}\r\n\r\nexport type FixedTaxRuleData = FixedTaxRuleAttributes;\r\n\r\n/**\r\n * A specialized version of TaxRuleModel for fixed-rate taxes (single slab).\r\n * Ideal for components like Charges where slab-based logic is not required.\r\n */\r\nexport class FixedTaxRuleModel extends TaxRuleBaseModel {\r\n protected rate: number;\r\n protected minUnitPrice: PriceModel;\r\n protected maxUnitPrice?: PriceModel;\r\n\r\n constructor(data: FixedTaxRuleAttributes) {\r\n super(data);\r\n this.rate = data.rate;\r\n this.minUnitPrice = new PriceModel(data.minUnitPrice);\r\n this.maxUnitPrice = data.maxUnitPrice ? new PriceModel(data.maxUnitPrice) : undefined;\r\n }\r\n\r\n public getApplicableTaxRate(): number {\r\n return this.rate;\r\n }\r\n\r\n /**\r\n * Calculates the tax amount for a given taxable amount.\r\n * @returns The calculated tax amount as a PriceModel.\r\n */\r\n calculateTax(unitPrice: PriceModel): PriceModel {\r\n const rate = this.getApplicableTaxRate();\r\n return unitPrice.multiply(rate).round();\r\n }\r\n\r\n public getDetails(): FixedTaxRuleData {\r\n return {\r\n ...super.getDetails(),\r\n rate: this.getApplicableTaxRate(),\r\n minUnitPrice: this.minUnitPrice.getDetails(),\r\n maxUnitPrice: this.maxUnitPrice ? this.maxUnitPrice.getDetails() : undefined,\r\n };\r\n }\r\n}\r\n"]}
|
package/dist/Classes/TaxRule.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export{c as FixedTaxRuleModel,a as TaxRuleBaseModel,b as TaxRuleModel}from'../chunk-2HBQ3C6V.mjs';import'../chunk-XHGUVYQO.mjs';import'../chunk-FC4P26U3.mjs';import'../chunk-XPKK6DFA.mjs';//# sourceMappingURL=TaxRule.mjs.map
|
|
2
2
|
//# sourceMappingURL=TaxRule.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/Classes/Enum.ts","../../src/Classes/Error.ts","../../src/Classes/Price.ts","../../src/Classes/TieredPrice.ts"],"names":["CurrencySymbolMap","CurrencyLocaleMap","InvalidTaxCategoryError","message","InvalidMinQuantityError","InvalidTieredPriceError","InvalidQuantityError","NoApplicableTierError","quantity","InvalidPriceAmountError","InvalidCurrencyCodeError","CurrencyMismatchError","InvalidArgumentError","PriceModel","_PriceModel","#kind","data","obj","priceModel","factor","divisor","priceModels","minPrice","currentPrice","maxPrice","amount","currency","options","locale","valueToFormat","fractionDigits","formattingOptions","error","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier","TieredPriceModel","baseUnitPrice","tiers","tier","a","b","t","hasDifferentCurrency","hasIrregularPricing","index","basePriceExceedsFirstTier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A,IAAM2C,CAAkB,CAAA,IAAA,CAAK,MAAM,IAAK,CAAA,KAAA,CAAM,MAAS,CAAA,CAAC,CAAE,CAAA,SAAA,CAAU,SAAU,EAAA,CACxEC,EAAY,IAAK,CAAA,aAAA,CAAc,SAAU,EAAA,CAE/C,OAASA,CAAAA,CAAAA,CAAYD,CAAmBC,EAAAA,CAAAA,CAAa,GACvD,CACF","file":"TieredPrice.js","sourcesContent":["/**\r\n * Represents the countries where the application operates or products are available.\r\n */\r\nexport enum OperationalCountry {\r\n /** India */ IN = 'IN',\r\n}\r\n\r\nexport enum OperationalCountryCurrency {\r\n /** India */ INR = 'INR',\r\n}\r\n\r\nexport enum OperationalLocale {\r\n /** India */ 'en-IN' = 'en-IN',\r\n /** India ( Kannada) */ 'kn-IN' = 'kn-IN'\r\n}\r\n\r\nexport enum OperationalLanguage {\r\n en = 'en',\r\n kn = 'kn'\r\n}\r\n\r\nexport const LocaleLanguageMap: Record<OperationalLocale, OperationalLanguage> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalLanguage.en,\r\n [OperationalLocale[\"kn-IN\"]]: OperationalLanguage.kn,\r\n}\r\n\r\nexport const LocaleCountryMap: Record<OperationalLocale, OperationalCountry> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalCountry.IN,\r\n [OperationalLocale[\"kn-IN\"]]: OperationalCountry.IN,\r\n}\r\n\r\n/**\r\n * Defines the supported ISO 4217 currency codes as an enumeration.\r\n */\r\nexport const CountryCurrencyMap = {\r\n /** India */[OperationalCountry.IN]: OperationalCountryCurrency.INR,\r\n};\r\n\r\nexport const CurrencySymbolMap = {\r\n [OperationalCountryCurrency.INR]: '₹',\r\n}\r\n\r\nexport const CurrencyLocaleMap = {\r\n [OperationalCountryCurrency.INR]: OperationalLocale[\"en-IN\"],\r\n}\r\n\r\n/**\r\n * Defines standard gender categories for product targeting.\r\n */\r\nexport enum GenderCategory {\r\n MALE = 'Male',\r\n FEMALE = 'Female',\r\n UNISEX = 'Unisex',\r\n KIDS = 'Kids',\r\n BOY = 'Boy',\r\n GIRL = 'Girl',\r\n GENERAL = 'General',\r\n}\r\n\r\nexport enum ImageCategory {\r\n PRIMARY = 'PRIMARY',\r\n GALLERY = 'GALLERY'\r\n}\r\n\r\nexport enum ChargeType {\r\n SHIPPING = 'SHIPPING',\r\n ADJUSTMENT = 'ADJUSTMENT'\r\n}\r\n\r\nexport enum TaxSystem {\r\n GST = 'GST',\r\n}\r\n\r\n/**\r\n * LineItemState\r\n * \r\n * INITIAL: Item added to order, not yet processed.\r\n * PROCESSING: Item is being prepared for shipment.\r\n * SHIPPED: Item dispatched to customer.\r\n * DELIVERED: Item delivered to customer.\r\n * CANCELLED: Item cancelled before shipment or delivery.\r\n * RETURN_REQUESTED: Customer requests to return item.\r\n * RETURNED: Item received back from customer.\r\n * REFUND_INITIATED: Refund initiated for item.\r\n * REFUNDED: Refund processed for item.\r\n * ON_HOLD: Item is paused due to payment, inventory, or other issues.\r\n */\r\nexport enum LineItemState {\r\n INITIAL = \"INITIAL\",\r\n PROCESSING = \"PROCESSING\",\r\n SHIPPED = \"SHIPPED\",\r\n DELIVERED = \"DELIVERED\",\r\n CANCELLED = \"CANCELLED\",\r\n RETURN_REQUESTED = \"RETURN_REQUESTED\",\r\n RETURNED = \"RETURNED\",\r\n REFUND_INITIATED = \"REFUND_INITIATED\",\r\n REFUNDED = \"REFUNDED\",\r\n ON_HOLD = \"ON_HOLD\",\r\n}","export class LineItemNotFoundError extends Error {\r\n constructor(lineItemId: string) {\r\n super(`Line item with ID '${lineItemId}' not found in the cart.`);\r\n this.name = 'LineItemNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidLineItemStateError extends Error {\r\n constructor(state: string) {\r\n super(`Invalid line item state: ${state}`);\r\n this.name = 'InvalidLineItemStateError';\r\n }\r\n}\r\n\r\nexport class DuplicateSizeError extends Error {\r\n constructor(size: string) {\r\n super(`Duplicate size found: ${size}`);\r\n this.name = 'DuplicateSizeError';\r\n }\r\n}\r\n\r\nexport class DuplicateSelectionAttributeError extends Error {\r\n constructor(attribute: string) {\r\n super(`Duplicate selection attribute found: ${attribute}`);\r\n this.name = 'DuplicateSelectionAttributeError';\r\n }\r\n}\r\n\r\nexport class ProductMismatchError extends Error {\r\n constructor(message: string = \"Product and selection attributes do not match.\") {\r\n super(`ProductMismatch: ${message}`);\r\n this.name = 'ProductMismatchError';\r\n }\r\n}\r\n\r\nexport class ProductInactiveError extends Error {\r\n constructor(message: string = \"Product is not active.\") {\r\n super(`ProductInactive: ${message}`);\r\n this.name = 'ProductInactiveError';\r\n }\r\n}\r\n\r\nexport class SelectionAttributeParseError extends Error {\r\n constructor(message: string = \"Failed to parse selection attributes key.\") {\r\n super(`SelectionAttributeParseError: ${message}`);\r\n this.name = 'SelectionAttributeParseError';\r\n }\r\n}\r\n\r\nexport class SizeMismatchError extends Error {\r\n constructor(message: string = \"Size does not match.\") {\r\n super(`SizeMismatch: ${message}`);\r\n this.name = 'SizeMismatchError';\r\n }\r\n}\r\n\r\nexport class PricingNotFoundError extends Error {\r\n constructor(message: string = \"Pricing details not available for the product\") {\r\n super(`NotFound: ${message}`);\r\n this.name = 'PricingNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxRuleError extends Error {\r\n constructor(message: string = \"Tax rule category mismatch.\") {\r\n super(`InvalidTaxRule: ${message}`);\r\n this.name = 'InvalidTaxRuleError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxCategoryError extends Error {\r\n constructor(message: string = \"Tax category is not valid.\") {\r\n super(`InvalidTaxCategory: ${message}`);\r\n this.name = 'InvalidTaxCategoryError';\r\n }\r\n}\r\n\r\nexport class InvalidMinQuantityError extends Error {\r\n constructor(message: string = \"Minimum quantity must be greater than zero.\") {\r\n super(`InvalidMinQuantity: ${message}`);\r\n this.name = 'InvalidMinQuantityError';\r\n }\r\n}\r\n\r\nexport class InvalidTieredPriceError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidTieredPrice: ${message}`);\r\n this.name = 'InvalidTieredPriceError';\r\n }\r\n}\r\n\r\nexport class InvalidQuantityError extends Error {\r\n constructor(message: string = \"Quantity must be greater than zero.\") {\r\n super(`InvalidQuantity: ${message}`);\r\n this.name = 'InvalidQuantityError';\r\n }\r\n}\r\n\r\nexport class NoApplicableTierError extends Error {\r\n constructor(quantity: number) {\r\n super(`NoApplicableTier: Quantity ${quantity} does not meet the minimum purchase requirement.`);\r\n this.name = 'NoApplicableTierError';\r\n }\r\n}\r\n\r\nexport class TaxSlabNotFoundError extends Error {\r\n constructor(message: string = \"No applicable tax slab or multiple slabs found for the given unit price.\") {\r\n super(`TaxSlabNotFound: ${message}`);\r\n this.name = 'TaxSlabNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidPriceAmountError extends Error {\r\n constructor(message: string = \"Amount cannot be negative.\") {\r\n super(`InvalidAmount: ${message}`);\r\n this.name = 'InvalidPriceAmountError';\r\n }\r\n}\r\n\r\nexport class InvalidCurrencyCodeError extends Error {\r\n constructor(message: string = \"Currency code is required.\") {\r\n super(`InvalidCurrency: ${message}`);\r\n this.name = 'InvalidCurrencyCodeError';\r\n }\r\n}\r\n\r\nexport class CurrencyMismatchError extends Error {\r\n constructor(message: string = \"Cannot perform operation on prices with different currencies.\") {\r\n super(`CurrencyMismatch: ${message}`);\r\n this.name = 'CurrencyMismatchError';\r\n }\r\n}\r\n\r\nexport class InvalidArgumentError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidArgument: ${message}`);\r\n this.name = 'InvalidArgumentError';\r\n }\r\n}\r\n\r\nexport class InvalidImageSourceError extends Error {\r\n constructor(message: string = \"Invalid image source configuration.\") {\r\n super(`InvalidImageSource: ${message}`);\r\n this.name = 'InvalidImageSourceError';\r\n }\r\n}\r\n\r\nexport class InvalidChargeError extends Error {\r\n constructor(message: string = \"Invalid charge data.\") {\r\n super(`InvalidCharge: ${message}`);\r\n this.name = 'InvalidChargeError';\r\n }\r\n}\r\n","import { CurrencyCode } from \"./Common\";\r\nimport { CurrencyLocaleMap, CurrencySymbolMap, OperationalCountryCurrency } from \"./Enum\";\r\nimport {\r\n InvalidPriceAmountError,\r\n InvalidCurrencyCodeError,\r\n CurrencyMismatchError,\r\n InvalidArgumentError\r\n} from \"./Error\";\r\n\r\nexport type PriceAttributes = {\r\n amount: number;\r\n currency: CurrencyCode;\r\n}\r\n\r\nexport type PriceData = PriceAttributes;\r\n\r\nexport default class PriceModel {\r\n #kind: string;\r\n protected amount: number;\r\n protected currency: CurrencyCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param amount - The initial price value.\r\n * @param currency - The currency code used for rounding and determining the currency symbol.\r\n * @throws {Error} If price is negative or country/currency mapping is missing.\r\n */\r\n constructor(data: PriceAttributes) {\r\n this.#kind = \"PriceModel\";\r\n if (data.amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative.\");\r\n }\r\n\r\n if (!data.currency) {\r\n throw new InvalidCurrencyCodeError(\"Currency code is required.\");\r\n }\r\n\r\n this.amount = data.amount;\r\n this.currency = data.currency;\r\n }\r\n\r\n get kind() {\r\n return this.#kind;\r\n }\r\n\r\n static isPriceModel(obj: unknown): obj is PriceModel {\r\n return typeof obj === \"object\" &&\r\n obj !== null &&\r\n (obj as any).kind === \"PriceModel\";\r\n }\r\n\r\n /**\r\n * Gets the currency associated with this price instance.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Returns the raw numeric price value.\r\n */\r\n public getAmount(): number {\r\n return this.amount;\r\n }\r\n\r\n /**\r\n *\r\n * @returns PriceData\r\n */\r\n public getDetails(): PriceData {\r\n return {\r\n amount: this.amount,\r\n currency: this.currency\r\n }\r\n }\r\n\r\n /**\r\n * Compares this price with another {@link PriceModel} instance.\r\n *\r\n * The comparison is performed using the numeric price value and is only valid\r\n * when both prices are expressed in the same currency.\r\n *\r\n * ### Comparison result:\r\n * - Returns a **negative number** if this price is **less than** `priceModel`\r\n * - Returns **zero** if both prices are **equal**\r\n * - Returns a **positive number** if this price is **greater than** `priceModel`\r\n *\r\n * @param priceModel - The {@link PriceModel} instance to compare against.\r\n *\r\n * @returns\r\n * A signed number representing the comparison result:\r\n * - `< 0` → this price is lower\r\n * - `0` → prices are equal\r\n * - `> 0` → this price is higher\r\n *\r\n * @throws {Error}\r\n * Throws an error if:\r\n * - `priceModel` is not an instance of {@link PriceModel}\r\n * - The currencies of the two prices do not match\r\n *\r\n * @example\r\n * ```ts\r\n * const a = new PriceModel(\"USD\", 100);\r\n * const b = new PriceModel(\"USD\", 150);\r\n *\r\n * a.compareTo(b); // -50\r\n * b.compareTo(a); // 50\r\n * a.compareTo(a); // 0\r\n * ```\r\n */\r\n public compareTo(priceModel: PriceModel): number {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return this.amount - priceModel.getAmount();\r\n }\r\n\r\n public add(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot add prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.amount + priceModel.getAmount(),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public subtract(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot subtract prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.amount - priceModel.getAmount(),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public multiply(factor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(factor)) {\r\n if (this.currency !== factor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot multiply prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.amount * factor.getAmount(),\r\n currency: this.currency\r\n });\r\n } else if (typeof factor === \"number\" && factor >= 0) {\r\n return new PriceModel({\r\n amount: this.amount * factor,\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a non-negative number.\");\r\n }\r\n\r\n public divide(divisor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(divisor)) {\r\n if (this.currency !== divisor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot divide prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.amount / divisor.getAmount(),\r\n currency: this.currency\r\n });\r\n } else if (typeof divisor === \"number\" && divisor > 0) {\r\n return new PriceModel({\r\n amount: this.amount / divisor,\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a positive number.\");\r\n }\r\n\r\n public min(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((minPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (minPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return minPrice.compareTo(currentPrice) < 0 ? minPrice : currentPrice;\r\n }, this);\r\n }\r\n\r\n public max(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((maxPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (maxPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return maxPrice.compareTo(currentPrice) > 0 ? maxPrice : currentPrice;\r\n }, this);\r\n }\r\n\r\n /**\r\n * Gets a zero value PriceModel for the same currency.\r\n * @returns A PriceModel instance representing zero in the same currency.\r\n */\r\n public zero(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: 0\r\n });\r\n }\r\n\r\n /**\r\n * Checks if the price is zero.\r\n * @returns True if the price is zero, false otherwise.\r\n */\r\n public isZero(): boolean {\r\n return this.amount === 0;\r\n }\r\n\r\n\r\n public round(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: this.getRoundedAmount()\r\n });\r\n }\r\n /**\r\n * Gets the rounded price value based on standard currency rules.\r\n * @returns The numeric price, rounded according to its currency's typical decimal places.\r\n */\r\n public getRoundedAmount(): number {\r\n return PriceModel.getRoundedAmount(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price stored in this instance.\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n public getFormattedString() {\r\n return PriceModel.getFormattedString(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n toString() {\r\n return this.getFormattedString();\r\n }\r\n\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the amount.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param amount - The initial amount value.\r\n * @param currency - The currency code for formatting.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the amount rounded to the next nearest integer (no decimals). Defaults to false.\r\n * @param options.style - The style of formatting, either 'currency' or 'decimal'. Defaults to 'currency'.\r\n * @param options.currencyDisplay - The display format for the currency symbol. Options are 'symbol', 'narrowSymbol', 'code', or 'name'. Defaults to 'symbol'.\r\n * @returns The formatted price string according to locale rules.\r\n * @throws {Error} If currency code is invalid.\r\n */\r\n static getFormattedString(amount: number, currency: CurrencyCode, options: {\r\n displayAsInteger?: boolean,\r\n style?: 'currency' | 'decimal',\r\n currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name'\r\n } = {\r\n displayAsInteger: false,\r\n style: 'currency',\r\n currencyDisplay: 'symbol'\r\n }): string {\r\n\r\n const locale = CurrencyLocaleMap[currency];\r\n if (!currency || !locale) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for formatting.');\r\n }\r\n\r\n let valueToFormat = amount;\r\n const fractionDigits = options.displayAsInteger ? 0 : PriceModel.getDecimalPlaces(currency);\r\n\r\n let formattingOptions: Intl.NumberFormatOptions = {\r\n style: options.style ?? 'currency',\r\n currency: currency,\r\n signDisplay: 'never',\r\n currencyDisplay: options.currencyDisplay,\r\n minimumFractionDigits: fractionDigits,\r\n maximumFractionDigits: fractionDigits,\r\n };\r\n\r\n if (options.displayAsInteger) {\r\n valueToFormat = Math.ceil(valueToFormat);\r\n }\r\n\r\n try {\r\n return new Intl.NumberFormat(locale, formattingOptions).format(valueToFormat);\r\n } catch (error) {\r\n console.error(`Error formatting price for currency \"${currency}\" and locale \"${locale}\":`, error);\r\n // Basic fallback without symbol if Intl fails completely\r\n return `${CurrencySymbolMap[currency] ?? currency} ${PriceModel.addThousandSeparators(valueToFormat.toFixed(fractionDigits))}`;\r\n }\r\n }\r\n\r\n /**\r\n * Helper method to determine standard decimal places for a currency.\r\n * @param currency - The currency code.\r\n * @returns The number of decimal places (0, 2, or 3 based on common rules).\r\n */\r\n private static getDecimalPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case OperationalCountryCurrency.INR:\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n /**\r\n * Adds basic thousand separators (commas) to a number string.\r\n * Does not handle different locale separators (e.g., periods, spaces).\r\n * @param numStr - The number string (potentially with decimals).\r\n * @returns The number string with commas added.\r\n */\r\n private static addThousandSeparators(numStr: string): string {\r\n const parts = numStr.split('.');\r\n const integerPart = parts[0];\r\n const decimalPart = parts.length > 1 ? '.' + parts[1] : '';\r\n\r\n const formattedInteger = integerPart.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\r\n return formattedInteger + decimalPart;\r\n }\r\n\r\n /**\r\n * Rounds a price value according to the standard decimal places\r\n * for the currency associated with the given country.\r\n *\r\n * @param price - The price value to round. Must be a non-negative number.\r\n * @param currency - The currency code to determine the rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the price is negative or currency is invalid.\r\n */\r\n static getRoundedAmount(amount: number, currency: CurrencyCode): number {\r\n if (amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative for rounding.\");\r\n }\r\n\r\n if (currency === undefined) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for rounding.');\r\n }\r\n\r\n const decimalPlaces = PriceModel.getDecimalPlaces(currency);\r\n const multiplier = Math.pow(10, decimalPlaces);\r\n const roundedValue = Math.round(amount * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n}","import PriceModel, { PriceData } from \"./Price\";\r\nimport {\r\n InvalidTaxCategoryError,\r\n InvalidMinQuantityError,\r\n InvalidTieredPriceError,\r\n InvalidQuantityError,\r\n NoApplicableTierError\r\n} from \"./Error\";\r\n\r\n/**\r\n * Represents a pricing tier based on a minimum purchase quantity.\r\n */\r\nexport type PriceTier = {\r\n minQuantity: number;\r\n unitPrice: PriceModel;\r\n};\r\n\r\n/**\r\n * Represents the attributes required for tiered pricing.\r\n */\r\nexport type TieredPriceAttributes = {\r\n baseUnitPrice: PriceData;\r\n taxCategory: string;\r\n\r\n /** Quantity-based pricing tiers */\r\n tiers: {\r\n minQuantity: number;\r\n unitPrice: PriceData;\r\n }[];\r\n};\r\n\r\nexport type TieredPriceData = TieredPriceAttributes;\r\n\r\nexport class TieredPriceModel {\r\n protected baseUnitPrice: PriceModel;\r\n protected taxCategory: string;\r\n protected tiers: PriceTier[];\r\n\r\n /** Constructor\r\n * Initializes the tiered pricing model with the provided attributes.\r\n * @param data - The tiered pricing attributes.\r\n *\r\n * @throws {Error}\r\n * - If the tax category is not valid\r\n * - If any tier has an invalid minimum quantity or unit price\r\n * - If the base unit price is not valid\r\n */\r\n constructor(data: TieredPriceAttributes) {\r\n const baseUnitPrice = new PriceModel(data.baseUnitPrice);\r\n\r\n if (!data.taxCategory) {\r\n throw new InvalidTaxCategoryError();\r\n }\r\n\r\n const tiers = (data.tiers ?? [])\r\n .map(tier => ({\r\n minQuantity: tier.minQuantity,\r\n unitPrice: new PriceModel(tier.unitPrice),\r\n }))\r\n .sort((a, b) => a.minQuantity - b.minQuantity);\r\n\r\n const hasInvalidMinQuantity = tiers.some(t => t.minQuantity <= 0);\r\n if (hasInvalidMinQuantity) {\r\n throw new InvalidMinQuantityError();\r\n }\r\n\r\n const hasDifferentCurrency = tiers.some(\r\n t => t.unitPrice.getCurrency() !== baseUnitPrice.getCurrency()\r\n );\r\n const hasIrregularPricing = tiers.some(\r\n (tier, index) =>\r\n index > 0 &&\r\n tier.unitPrice.compareTo(tiers[index - 1].unitPrice) > 0\r\n );\r\n const basePriceExceedsFirstTier = tiers[0]?.unitPrice.compareTo(baseUnitPrice) > 0;\r\n\r\n if (hasDifferentCurrency || hasIrregularPricing || basePriceExceedsFirstTier) {\r\n throw new InvalidTieredPriceError(\r\n \"Tiers must share the same currency and must not increase in unit price.\"\r\n );\r\n }\r\n\r\n this.baseUnitPrice = baseUnitPrice;\r\n this.taxCategory = data.taxCategory;\r\n this.tiers = tiers;\r\n }\r\n\r\n /** \r\n * Returns the base unit price \r\n * @returns The base unit price as a PriceModel instance.\r\n */\r\n getBaseUnitPrice(): PriceModel {\r\n return this.baseUnitPrice;\r\n }\r\n\r\n /** \r\n * Returns the tax category \r\n * @returns The tax category as a TaxCategory enum value.\r\n */\r\n getTaxCategory(): string {\r\n return this.taxCategory;\r\n }\r\n\r\n /** \r\n * Returns all pricing tiers sorted by minimum quantity \r\n * @returns An array of PriceTier objects.\r\n */\r\n getTiers(): readonly PriceTier[] {\r\n return this.tiers;\r\n }\r\n\r\n getDetails(): TieredPriceData {\r\n return {\r\n baseUnitPrice: this.baseUnitPrice.getDetails(),\r\n taxCategory: this.taxCategory,\r\n tiers: this.tiers.map(tier => ({\r\n minQuantity: tier.minQuantity,\r\n unitPrice: tier.unitPrice.getDetails()\r\n }))\r\n };\r\n }\r\n\r\n /**\r\n * Returns the applicable unit price for a given quantity.\r\n *\r\n * @param quantity - Purchase quantity\r\n * @returns The unit price for the highest applicable tier\r\n *\r\n * @throws {Error}\r\n * - If quantity is less than or equal to zero\r\n * - If quantity does not meet the minimum requirement of any tier\r\n */\r\n getApplicableTier(quantity: number): PriceTier {\r\n if (quantity <= 0) {\r\n throw new InvalidQuantityError();\r\n }\r\n\r\n for (let i = this.tiers.length - 1; i >= 0; i--) {\r\n if (quantity >= this.tiers[i].minQuantity) {\r\n return this.tiers[i];\r\n }\r\n }\r\n\r\n throw new NoApplicableTierError(quantity);\r\n }\r\n\r\n /**\r\n * Returns the minimum quantity required to purchase this product.\r\n */\r\n getMinQuantity(): number {\r\n return this.tiers[0]?.minQuantity ?? 1;\r\n }\r\n\r\n /**\r\n * Returns the maximum discount percentage achievable compared to the base unit price.\r\n */\r\n getMaxDiscountPercent(): number {\r\n if (!this.tiers.length) return 0;\r\n\r\n const lowestTierPrice = this.tiers[this.tiers.length - 1].unitPrice.getAmount();\r\n const basePrice = this.baseUnitPrice.getAmount();\r\n\r\n return ((basePrice - lowestTierPrice) / basePrice) * 100;\r\n }\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/Classes/Enum.ts","../../src/Classes/Error.ts","../../src/Classes/Price.ts","../../src/Classes/TieredPrice.ts"],"names":["CurrencySymbolMap","CurrencyLocaleMap","InvalidTaxCategoryError","message","InvalidMinQuantityError","InvalidTieredPriceError","InvalidQuantityError","NoApplicableTierError","quantity","InvalidPriceAmountError","InvalidCurrencyCodeError","CurrencyMismatchError","InvalidArgumentError","PriceModel","_PriceModel","#kind","data","obj","priceModel","factor","divisor","priceModels","minPrice","currentPrice","maxPrice","amount","currency","options","locale","valueToFormat","fractionDigits","formattingOptions","error","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier","TieredPriceModel","baseUnitPrice","tiers","tier","a","b","t","hasDifferentCurrency","hasIrregularPricing","index","basePriceExceedsFirstTier","i","lowestTierPrice","basePrice"],"mappings":"aAsCO,IAAMA,CAAoB,CAAA,CAC9B,GAAiC,CAAA,QACpC,CAEaC,CAAAA,CAAAA,CAAoB,CAC9B,GAAA,CAAiC,OACpC,CAAA,CC0BO,IAAMC,CAAAA,CAAN,cAAsC,KAAM,CAC/C,WAAYC,CAAAA,CAAAA,CAAkB,4BAA8B,CAAA,CACxD,KAAM,CAAA,CAAA,oBAAA,EAAuBA,CAAO,CAAA,CAAE,CACtC,CAAA,IAAA,CAAK,IAAO,CAAA,0BAChB,CACJ,CAAA,CAEaC,EAAN,cAAsC,KAAM,CAC/C,WAAA,CAAYD,CAAkB,CAAA,6CAAA,CAA+C,CACzE,KAAA,CAAM,CAAuBA,oBAAAA,EAAAA,CAAO,CAAE,CAAA,CAAA,CACtC,IAAK,CAAA,IAAA,CAAO,0BAChB,CACJ,EAEaE,CAAN,CAAA,cAAsC,KAAM,CAC/C,WAAYF,CAAAA,CAAAA,CAAiB,CACzB,KAAA,CAAM,uBAAuBA,CAAO,CAAA,CAAE,CACtC,CAAA,IAAA,CAAK,IAAO,CAAA,0BAChB,CACJ,CAAA,CAEaG,EAAN,cAAmC,KAAM,CAC5C,WAAA,CAAYH,CAAkB,CAAA,qCAAA,CAAuC,CACjE,KAAA,CAAM,CAAoBA,iBAAAA,EAAAA,CAAO,CAAE,CAAA,CAAA,CACnC,IAAK,CAAA,IAAA,CAAO,uBAChB,CACJ,EAEaI,CAAN,CAAA,c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IAAA,CAAK,KAAM0C,CAAAA,CAAC,EAAE,WAC5B,CAAA,OAAO,IAAK,CAAA,KAAA,CAAMA,CAAC,CAAA,CAIvB,MAAM,IAAI3C,EAAsBC,CAAQ,CAC1C,CAKA,cAAA,EAAyB,CACvB,OAAO,IAAK,CAAA,KAAA,CAAM,CAAC,CAAG,EAAA,WAAA,EAAe,CACvC,CAKA,qBAAgC,EAAA,CAC9B,GAAI,CAAC,IAAK,CAAA,KAAA,CAAM,MAAQ,CAAA,OAExB,CAAA,CAAA,IAAM2C,CAAkB,CAAA,IAAA,CAAK,MAAM,IAAK,CAAA,KAAA,CAAM,MAAS,CAAA,CAAC,CAAE,CAAA,SAAA,CAAU,SAAU,EAAA,CACxEC,EAAY,IAAK,CAAA,aAAA,CAAc,SAAU,EAAA,CAE/C,OAASA,CAAAA,CAAAA,CAAYD,CAAmBC,EAAAA,CAAAA,CAAa,GACvD,CACF","file":"TieredPrice.js","sourcesContent":["/**\r\n * Represents the countries where the application operates or products are available.\r\n */\r\nexport enum OperationalCountry {\r\n /** India */ IN = 'IN',\r\n}\r\n\r\nexport enum OperationalCountryCurrency {\r\n /** India */ INR = 'INR',\r\n}\r\n\r\nexport enum OperationalLocale {\r\n /** India */ 'en-IN' = 'en-IN',\r\n /** India ( Kannada) */ 'kn-IN' = 'kn-IN'\r\n}\r\n\r\nexport enum OperationalLanguage {\r\n en = 'en',\r\n kn = 'kn'\r\n}\r\n\r\nexport const LocaleLanguageMap: Record<OperationalLocale, OperationalLanguage> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalLanguage.en,\r\n [OperationalLocale[\"kn-IN\"]]: OperationalLanguage.kn,\r\n}\r\n\r\nexport const LocaleCountryMap: Record<OperationalLocale, OperationalCountry> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalCountry.IN,\r\n [OperationalLocale[\"kn-IN\"]]: OperationalCountry.IN,\r\n}\r\n\r\n/**\r\n * Defines the supported ISO 4217 currency codes as an enumeration.\r\n */\r\nexport const CountryCurrencyMap = {\r\n /** India */[OperationalCountry.IN]: OperationalCountryCurrency.INR,\r\n};\r\n\r\nexport const CurrencySymbolMap = {\r\n [OperationalCountryCurrency.INR]: '₹',\r\n}\r\n\r\nexport const CurrencyLocaleMap = {\r\n [OperationalCountryCurrency.INR]: OperationalLocale[\"en-IN\"],\r\n}\r\n\r\n/**\r\n * Defines standard gender categories for product targeting.\r\n */\r\nexport enum GenderCategory {\r\n MALE = 'Male',\r\n FEMALE = 'Female',\r\n UNISEX = 'Unisex',\r\n KIDS = 'Kids',\r\n BOY = 'Boy',\r\n GIRL = 'Girl',\r\n GENERAL = 'General',\r\n}\r\n\r\nexport enum ImageCategory {\r\n PRIMARY = 'PRIMARY',\r\n GALLERY = 'GALLERY'\r\n}\r\n\r\nexport enum ChargeType {\r\n SHIPPING = 'SHIPPING',\r\n ADJUSTMENT = 'ADJUSTMENT'\r\n}\r\n\r\nexport enum TaxSystem {\r\n GST = 'GST',\r\n}\r\n\r\n/**\r\n * LineItemState\r\n * \r\n * INITIAL: Item added to order, not yet processed.\r\n * PROCESSING: Item is being prepared for shipment.\r\n * SHIPPED: Item dispatched to customer.\r\n * DELIVERED: Item delivered to customer.\r\n * CANCELLED: Item cancelled before shipment or delivery.\r\n * RETURN_REQUESTED: Customer requests to return item.\r\n * RETURNED: Item received back from customer.\r\n * REFUND_INITIATED: Refund initiated for item.\r\n * REFUNDED: Refund processed for item.\r\n * ON_HOLD: Item is paused due to payment, inventory, or other issues.\r\n */\r\nexport enum LineItemState {\r\n INITIAL = \"INITIAL\",\r\n PROCESSING = \"PROCESSING\",\r\n SHIPPED = \"SHIPPED\",\r\n DELIVERED = \"DELIVERED\",\r\n CANCELLED = \"CANCELLED\",\r\n RETURN_REQUESTED = \"RETURN_REQUESTED\",\r\n RETURNED = \"RETURNED\",\r\n REFUND_INITIATED = \"REFUND_INITIATED\",\r\n REFUNDED = \"REFUNDED\",\r\n ON_HOLD = \"ON_HOLD\",\r\n}","export class LineItemNotFoundError extends Error {\r\n constructor(lineItemId: string) {\r\n super(`Line item with ID '${lineItemId}' not found in the cart.`);\r\n this.name = 'LineItemNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidLineItemStateError extends Error {\r\n constructor(state: string) {\r\n super(`Invalid line item state: ${state}`);\r\n this.name = 'InvalidLineItemStateError';\r\n }\r\n}\r\n\r\nexport class DuplicateSizeError extends Error {\r\n constructor(size: string) {\r\n super(`Duplicate size found: ${size}`);\r\n this.name = 'DuplicateSizeError';\r\n }\r\n}\r\n\r\nexport class DuplicateSelectionAttributeError extends Error {\r\n constructor(attribute: string) {\r\n super(`Duplicate selection attribute found: ${attribute}`);\r\n this.name = 'DuplicateSelectionAttributeError';\r\n }\r\n}\r\n\r\nexport class ProductMismatchError extends Error {\r\n constructor(message: string = \"Product and selection attributes do not match.\") {\r\n super(`ProductMismatch: ${message}`);\r\n this.name = 'ProductMismatchError';\r\n }\r\n}\r\n\r\nexport class ProductInactiveError extends Error {\r\n constructor(message: string = \"Product is not active.\") {\r\n super(`ProductInactive: ${message}`);\r\n this.name = 'ProductInactiveError';\r\n }\r\n}\r\n\r\nexport class SelectionAttributeParseError extends Error {\r\n constructor(message: string = \"Failed to parse selection attributes key.\") {\r\n super(`SelectionAttributeParseError: ${message}`);\r\n this.name = 'SelectionAttributeParseError';\r\n }\r\n}\r\n\r\nexport class SizeMismatchError extends Error {\r\n constructor(message: string = \"Size does not match.\") {\r\n super(`SizeMismatch: ${message}`);\r\n this.name = 'SizeMismatchError';\r\n }\r\n}\r\n\r\nexport class PricingNotFoundError extends Error {\r\n constructor(message: string = \"Pricing details not available for the product\") {\r\n super(`NotFound: ${message}`);\r\n this.name = 'PricingNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxRuleError extends Error {\r\n constructor(message: string = \"Tax rule category mismatch.\") {\r\n super(`InvalidTaxRule: ${message}`);\r\n this.name = 'InvalidTaxRuleError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxCategoryError extends Error {\r\n constructor(message: string = \"Tax category is not valid.\") {\r\n super(`InvalidTaxCategory: ${message}`);\r\n this.name = 'InvalidTaxCategoryError';\r\n }\r\n}\r\n\r\nexport class InvalidMinQuantityError extends Error {\r\n constructor(message: string = \"Minimum quantity must be greater than zero.\") {\r\n super(`InvalidMinQuantity: ${message}`);\r\n this.name = 'InvalidMinQuantityError';\r\n }\r\n}\r\n\r\nexport class InvalidTieredPriceError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidTieredPrice: ${message}`);\r\n this.name = 'InvalidTieredPriceError';\r\n }\r\n}\r\n\r\nexport class InvalidQuantityError extends Error {\r\n constructor(message: string = \"Quantity must be greater than zero.\") {\r\n super(`InvalidQuantity: ${message}`);\r\n this.name = 'InvalidQuantityError';\r\n }\r\n}\r\n\r\nexport class NoApplicableTierError extends Error {\r\n constructor(quantity: number) {\r\n super(`NoApplicableTier: Quantity ${quantity} does not meet the minimum purchase requirement.`);\r\n this.name = 'NoApplicableTierError';\r\n }\r\n}\r\n\r\nexport class TaxSlabNotFoundError extends Error {\r\n constructor(message: string = \"No applicable tax slab or multiple slabs found for the given unit price.\") {\r\n super(`TaxSlabNotFound: ${message}`);\r\n this.name = 'TaxSlabNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidPriceAmountError extends Error {\r\n constructor(message: string = \"Amount cannot be negative.\") {\r\n super(`InvalidAmount: ${message}`);\r\n this.name = 'InvalidPriceAmountError';\r\n }\r\n}\r\n\r\nexport class InvalidCurrencyCodeError extends Error {\r\n constructor(message: string = \"Currency code is required.\") {\r\n super(`InvalidCurrency: ${message}`);\r\n this.name = 'InvalidCurrencyCodeError';\r\n }\r\n}\r\n\r\nexport class CurrencyMismatchError extends Error {\r\n constructor(message: string = \"Cannot perform operation on prices with different currencies.\") {\r\n super(`CurrencyMismatch: ${message}`);\r\n this.name = 'CurrencyMismatchError';\r\n }\r\n}\r\n\r\nexport class InvalidArgumentError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidArgument: ${message}`);\r\n this.name = 'InvalidArgumentError';\r\n }\r\n}\r\n\r\nexport class InvalidImageSourceError extends Error {\r\n constructor(message: string = \"Invalid image source configuration.\") {\r\n super(`InvalidImageSource: ${message}`);\r\n this.name = 'InvalidImageSourceError';\r\n }\r\n}\r\n\r\nexport class InvalidChargeError extends Error {\r\n constructor(message: string = \"Invalid charge data.\") {\r\n super(`InvalidCharge: ${message}`);\r\n this.name = 'InvalidChargeError';\r\n }\r\n}\r\n","import { CurrencyCode } from \"./Common\";\r\nimport { CurrencyLocaleMap, CurrencySymbolMap, OperationalCountryCurrency } from \"./Enum\";\r\nimport {\r\n InvalidPriceAmountError,\r\n InvalidCurrencyCodeError,\r\n CurrencyMismatchError,\r\n InvalidArgumentError\r\n} from \"./Error\";\r\n\r\nexport type PriceAttributes = {\r\n amount: number;\r\n currency: CurrencyCode;\r\n}\r\n\r\nexport type PriceData = PriceAttributes;\r\n\r\nexport default class PriceModel {\r\n #kind: string;\r\n protected amount: number;\r\n protected currency: CurrencyCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param amount - The initial price value.\r\n * @param currency - The currency code used for rounding and determining the currency symbol.\r\n * @throws {Error} If price is negative or country/currency mapping is missing.\r\n */\r\n constructor(data: PriceAttributes) {\r\n this.#kind = \"PriceModel\";\r\n if (data.amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative.\");\r\n }\r\n\r\n if (!data.currency) {\r\n throw new InvalidCurrencyCodeError(\"Currency code is required.\");\r\n }\r\n\r\n this.amount = data.amount;\r\n this.currency = data.currency;\r\n }\r\n\r\n get kind() {\r\n return this.#kind;\r\n }\r\n\r\n static isPriceModel(obj: unknown): obj is PriceModel {\r\n return typeof obj === \"object\" &&\r\n obj !== null &&\r\n (obj as any).kind === \"PriceModel\";\r\n }\r\n\r\n /**\r\n * Gets the currency associated with this price instance.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Returns the raw numeric price value.\r\n */\r\n public getAmount(): number {\r\n return this.amount;\r\n }\r\n\r\n /**\r\n *\r\n * @returns PriceData\r\n */\r\n public getDetails(): PriceData {\r\n return {\r\n amount: this.amount,\r\n currency: this.currency\r\n }\r\n }\r\n\r\n /**\r\n * Compares this price with another {@link PriceModel} instance.\r\n *\r\n * The comparison is performed using the numeric price value and is only valid\r\n * when both prices are expressed in the same currency.\r\n *\r\n * ### Comparison result:\r\n * - Returns a **negative number** if this price is **less than** `priceModel`\r\n * - Returns **zero** if both prices are **equal**\r\n * - Returns a **positive number** if this price is **greater than** `priceModel`\r\n *\r\n * @param priceModel - The {@link PriceModel} instance to compare against.\r\n *\r\n * @returns\r\n * A signed number representing the comparison result:\r\n * - `< 0` → this price is lower\r\n * - `0` → prices are equal\r\n * - `> 0` → this price is higher\r\n *\r\n * @throws {Error}\r\n * Throws an error if:\r\n * - `priceModel` is not an instance of {@link PriceModel}\r\n * - The currencies of the two prices do not match\r\n *\r\n * @example\r\n * ```ts\r\n * const a = new PriceModel(\"USD\", 100);\r\n * const b = new PriceModel(\"USD\", 150);\r\n *\r\n * a.compareTo(b); // -50\r\n * b.compareTo(a); // 50\r\n * a.compareTo(a); // 0\r\n * ```\r\n */\r\n public compareTo(priceModel: PriceModel): number {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return this.amount - priceModel.getAmount();\r\n }\r\n\r\n public add(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot add prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.amount + priceModel.getAmount(),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public subtract(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot subtract prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.amount - priceModel.getAmount(),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public multiply(factor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(factor)) {\r\n if (this.currency !== factor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot multiply prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.amount * factor.getAmount(),\r\n currency: this.currency\r\n });\r\n } else if (typeof factor === \"number\" && factor >= 0) {\r\n return new PriceModel({\r\n amount: this.amount * factor,\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a non-negative number.\");\r\n }\r\n\r\n public divide(divisor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(divisor)) {\r\n if (this.currency !== divisor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot divide prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.amount / divisor.getAmount(),\r\n currency: this.currency\r\n });\r\n } else if (typeof divisor === \"number\" && divisor > 0) {\r\n return new PriceModel({\r\n amount: this.amount / divisor,\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a positive number.\");\r\n }\r\n\r\n public min(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((minPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (minPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return minPrice.compareTo(currentPrice) < 0 ? minPrice : currentPrice;\r\n }, this);\r\n }\r\n\r\n public max(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((maxPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (maxPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return maxPrice.compareTo(currentPrice) > 0 ? maxPrice : currentPrice;\r\n }, this);\r\n }\r\n\r\n /**\r\n * Gets a zero value PriceModel for the same currency.\r\n * @returns A PriceModel instance representing zero in the same currency.\r\n */\r\n public zero(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: 0\r\n });\r\n }\r\n\r\n /**\r\n * Checks if the price is zero.\r\n * @returns True if the price is zero, false otherwise.\r\n */\r\n public isZero(): boolean {\r\n return this.amount === 0;\r\n }\r\n\r\n\r\n public round(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: this.getRoundedAmount()\r\n });\r\n }\r\n\r\n /**\r\n * Gets the rounded price value based on standard currency rules.\r\n * @returns The numeric price, rounded according to its currency's typical decimal places.\r\n */\r\n public getRoundedAmount(): number {\r\n return PriceModel.getRoundedAmount(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price stored in this instance.\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n public getFormattedString() {\r\n return PriceModel.getFormattedString(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n toString() {\r\n return this.getFormattedString();\r\n }\r\n\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the amount.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param amount - The initial amount value.\r\n * @param currency - The currency code for formatting.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the amount rounded to the next nearest integer (no decimals). Defaults to false.\r\n * @param options.style - The style of formatting, either 'currency' or 'decimal'. Defaults to 'currency'.\r\n * @param options.currencyDisplay - The display format for the currency symbol. Options are 'symbol', 'narrowSymbol', 'code', or 'name'. Defaults to 'symbol'.\r\n * @returns The formatted price string according to locale rules.\r\n * @throws {Error} If currency code is invalid.\r\n */\r\n static getFormattedString(amount: number, currency: CurrencyCode, options: {\r\n displayAsInteger?: boolean,\r\n style?: 'currency' | 'decimal',\r\n currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name'\r\n } = {\r\n displayAsInteger: false,\r\n style: 'currency',\r\n currencyDisplay: 'symbol'\r\n }): string {\r\n\r\n const locale = CurrencyLocaleMap[currency];\r\n if (!currency || !locale) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for formatting.');\r\n }\r\n\r\n let valueToFormat = amount;\r\n const fractionDigits = options.displayAsInteger ? 0 : PriceModel.getDecimalPlaces(currency);\r\n\r\n let formattingOptions: Intl.NumberFormatOptions = {\r\n style: options.style ?? 'currency',\r\n currency: currency,\r\n signDisplay: 'never',\r\n currencyDisplay: options.currencyDisplay,\r\n minimumFractionDigits: fractionDigits,\r\n maximumFractionDigits: fractionDigits,\r\n };\r\n\r\n if (options.displayAsInteger) {\r\n valueToFormat = Math.ceil(valueToFormat);\r\n }\r\n\r\n try {\r\n return new Intl.NumberFormat(locale, formattingOptions).format(valueToFormat);\r\n } catch (error) {\r\n console.error(`Error formatting price for currency \"${currency}\" and locale \"${locale}\":`, error);\r\n // Basic fallback without symbol if Intl fails completely\r\n return `${CurrencySymbolMap[currency] ?? currency} ${PriceModel.addThousandSeparators(valueToFormat.toFixed(fractionDigits))}`;\r\n }\r\n }\r\n\r\n /**\r\n * Helper method to determine standard decimal places for a currency.\r\n * @param currency - The currency code.\r\n * @returns The number of decimal places (0, 2, or 3 based on common rules).\r\n */\r\n private static getDecimalPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case OperationalCountryCurrency.INR:\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n /**\r\n * Adds basic thousand separators (commas) to a number string.\r\n * Does not handle different locale separators (e.g., periods, spaces).\r\n * @param numStr - The number string (potentially with decimals).\r\n * @returns The number string with commas added.\r\n */\r\n private static addThousandSeparators(numStr: string): string {\r\n const parts = numStr.split('.');\r\n const integerPart = parts[0];\r\n const decimalPart = parts.length > 1 ? '.' + parts[1] : '';\r\n\r\n const formattedInteger = integerPart.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\r\n return formattedInteger + decimalPart;\r\n }\r\n\r\n /**\r\n * Rounds a price value according to the standard decimal places\r\n * for the currency associated with the given country.\r\n *\r\n * @param price - The price value to round. Must be a non-negative number.\r\n * @param currency - The currency code to determine the rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the price is negative or currency is invalid.\r\n */\r\n static getRoundedAmount(amount: number, currency: CurrencyCode): number {\r\n if (amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative for rounding.\");\r\n }\r\n\r\n if (currency === undefined) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for rounding.');\r\n }\r\n\r\n const decimalPlaces = PriceModel.getDecimalPlaces(currency);\r\n const multiplier = Math.pow(10, decimalPlaces);\r\n const roundedValue = Math.round(amount * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n}","import PriceModel, { PriceData } from \"./Price\";\r\nimport {\r\n InvalidTaxCategoryError,\r\n InvalidMinQuantityError,\r\n InvalidTieredPriceError,\r\n InvalidQuantityError,\r\n NoApplicableTierError\r\n} from \"./Error\";\r\n\r\n/**\r\n * Represents a pricing tier based on a minimum purchase quantity.\r\n */\r\nexport type PriceTier = {\r\n minQuantity: number;\r\n unitPrice: PriceModel;\r\n};\r\n\r\n/**\r\n * Represents the attributes required for tiered pricing.\r\n */\r\nexport type TieredPriceAttributes = {\r\n baseUnitPrice: PriceData;\r\n taxCategory: string;\r\n\r\n /** Quantity-based pricing tiers */\r\n tiers: {\r\n minQuantity: number;\r\n unitPrice: PriceData;\r\n }[];\r\n};\r\n\r\nexport type TieredPriceData = TieredPriceAttributes;\r\n\r\nexport class TieredPriceModel {\r\n protected baseUnitPrice: PriceModel;\r\n protected taxCategory: string;\r\n protected tiers: PriceTier[];\r\n\r\n /** Constructor\r\n * Initializes the tiered pricing model with the provided attributes.\r\n * @param data - The tiered pricing attributes.\r\n *\r\n * @throws {Error}\r\n * - If the tax category is not valid\r\n * - If any tier has an invalid minimum quantity or unit price\r\n * - If the base unit price is not valid\r\n */\r\n constructor(data: TieredPriceAttributes) {\r\n const baseUnitPrice = new PriceModel(data.baseUnitPrice);\r\n\r\n if (!data.taxCategory) {\r\n throw new InvalidTaxCategoryError();\r\n }\r\n\r\n const tiers = (data.tiers ?? [])\r\n .map(tier => ({\r\n minQuantity: tier.minQuantity,\r\n unitPrice: new PriceModel(tier.unitPrice),\r\n }))\r\n .sort((a, b) => a.minQuantity - b.minQuantity);\r\n\r\n const hasInvalidMinQuantity = tiers.some(t => t.minQuantity <= 0);\r\n if (hasInvalidMinQuantity) {\r\n throw new InvalidMinQuantityError();\r\n }\r\n\r\n const hasDifferentCurrency = tiers.some(\r\n t => t.unitPrice.getCurrency() !== baseUnitPrice.getCurrency()\r\n );\r\n const hasIrregularPricing = tiers.some(\r\n (tier, index) =>\r\n index > 0 &&\r\n tier.unitPrice.compareTo(tiers[index - 1].unitPrice) > 0\r\n );\r\n const basePriceExceedsFirstTier = tiers[0]?.unitPrice.compareTo(baseUnitPrice) > 0;\r\n\r\n if (hasDifferentCurrency || hasIrregularPricing || basePriceExceedsFirstTier) {\r\n throw new InvalidTieredPriceError(\r\n \"Tiers must share the same currency and must not increase in unit price.\"\r\n );\r\n }\r\n\r\n this.baseUnitPrice = baseUnitPrice;\r\n this.taxCategory = data.taxCategory;\r\n this.tiers = tiers;\r\n }\r\n\r\n /** \r\n * Returns the base unit price \r\n * @returns The base unit price as a PriceModel instance.\r\n */\r\n getBaseUnitPrice(): PriceModel {\r\n return this.baseUnitPrice;\r\n }\r\n\r\n /** \r\n * Returns the tax category \r\n * @returns The tax category as a TaxCategory enum value.\r\n */\r\n getTaxCategory(): string {\r\n return this.taxCategory;\r\n }\r\n\r\n /** \r\n * Returns all pricing tiers sorted by minimum quantity \r\n * @returns An array of PriceTier objects.\r\n */\r\n getTiers(): readonly PriceTier[] {\r\n return this.tiers;\r\n }\r\n\r\n getDetails(): TieredPriceData {\r\n return {\r\n baseUnitPrice: this.baseUnitPrice.getDetails(),\r\n taxCategory: this.taxCategory,\r\n tiers: this.tiers.map(tier => ({\r\n minQuantity: tier.minQuantity,\r\n unitPrice: tier.unitPrice.getDetails()\r\n }))\r\n };\r\n }\r\n\r\n /**\r\n * Returns the applicable unit price for a given quantity.\r\n *\r\n * @param quantity - Purchase quantity\r\n * @returns The unit price for the highest applicable tier\r\n *\r\n * @throws {Error}\r\n * - If quantity is less than or equal to zero\r\n * - If quantity does not meet the minimum requirement of any tier\r\n */\r\n getApplicableTier(quantity: number): PriceTier {\r\n if (quantity <= 0) {\r\n throw new InvalidQuantityError();\r\n }\r\n\r\n for (let i = this.tiers.length - 1; i >= 0; i--) {\r\n if (quantity >= this.tiers[i].minQuantity) {\r\n return this.tiers[i];\r\n }\r\n }\r\n\r\n throw new NoApplicableTierError(quantity);\r\n }\r\n\r\n /**\r\n * Returns the minimum quantity required to purchase this product.\r\n */\r\n getMinQuantity(): number {\r\n return this.tiers[0]?.minQuantity ?? 1;\r\n }\r\n\r\n /**\r\n * Returns the maximum discount percentage achievable compared to the base unit price.\r\n */\r\n getMaxDiscountPercent(): number {\r\n if (!this.tiers.length) return 0;\r\n\r\n const lowestTierPrice = this.tiers[this.tiers.length - 1].unitPrice.getAmount();\r\n const basePrice = this.baseUnitPrice.getAmount();\r\n\r\n return ((basePrice - lowestTierPrice) / basePrice) * 100;\r\n }\r\n}\r\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as TieredPriceModel}from'../chunk-
|
|
1
|
+
export{a as TieredPriceModel}from'../chunk-HR5HHV6O.mjs';import'../chunk-XHGUVYQO.mjs';import'../chunk-FC4P26U3.mjs';import'../chunk-XPKK6DFA.mjs';//# sourceMappingURL=TieredPrice.mjs.map
|
|
2
2
|
//# sourceMappingURL=TieredPrice.mjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-XHGUVYQO.mjs';import {p}from'./chunk-XPKK6DFA.mjs';var n=class{taxRuleId;taxCategory;taxSystem;taxSubSystem;taxCountry;effectiveFrom;effectiveTo;constructor(e){this.taxRuleId=e.taxRuleId,this.taxSystem=e.taxSystem,this.taxSubSystem=e.taxSubSystem,this.taxCategory=e.taxCategory,this.taxCountry=e.taxCountry,this.effectiveFrom=new Date(e.effectiveFrom),this.effectiveTo=e.effectiveTo?new Date(e.effectiveTo):void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getTaxCountry(){return this.taxCountry}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),taxCountry:this.getTaxCountry(),effectiveFrom:this.effectiveFrom.toISOString(),effectiveTo:this.effectiveTo?this.effectiveTo.toISOString():void 0}}appliesTo(e,t,r=new Date){return this.taxCategory===e&&this.taxCountry===t&&this.effectiveFrom<=r&&(this.effectiveTo?this.effectiveTo>=r:!0)}static getTaxRateDisplayString(e,t,r){let i=t*100,o=i%1===0?i.toString():i.toFixed(2).replace(/\.?0+$/,"");return r?.percentageOnly?`${o}%`:e.getTaxSystem()==="GST"?`${o}% ${e.getTaxSubSystem()}`:`${o}% ${e.getTaxSystem()}`}},c=class s extends n{slabs;constructor(e){super(e),this.slabs=e.slabs.map(t=>({rate:t.rate,minUnitPrice:new a(t.minUnitPrice),maxUnitPrice:t.maxUnitPrice?new a(t.maxUnitPrice):void 0}));}getSlabs(){return this.slabs}getDetails(){return {...super.getDetails(),slabs:this.getSlabs().map(e=>({rate:e.rate,minUnitPrice:e.minUnitPrice.getDetails(),maxUnitPrice:e.maxUnitPrice?e.maxUnitPrice.getDetails():void 0}))}}getApplicableTaxRate(e){return s.getApplicableTaxRate(e,this.slabs)}calculateTax(e){let t=this.getApplicableTaxRate(e);return e.multiply(t).round()}static getApplicableTaxRate(e,t){let r=t.filter(i=>(i.minUnitPrice===void 0||e.compareTo(i.minUnitPrice)>=0)&&(i.maxUnitPrice===void 0||e.compareTo(i.maxUnitPrice)<0));if(r.length!==1)throw new p;return r[0].rate}},u=class extends n{rate;minUnitPrice;maxUnitPrice;constructor(e){super(e),this.rate=e.rate,this.minUnitPrice=new a(e.minUnitPrice),this.maxUnitPrice=e.maxUnitPrice?new a(e.maxUnitPrice):void 0;}getApplicableTaxRate(){return this.rate}calculateTax(e){let t=this.getApplicableTaxRate();return e.multiply(t).round()}getDetails(){return {...super.getDetails(),rate:this.getApplicableTaxRate(),minUnitPrice:this.minUnitPrice.getDetails(),maxUnitPrice:this.maxUnitPrice?this.maxUnitPrice.getDetails():void 0}}};export{n as a,c as b,u as c};//# sourceMappingURL=chunk-2HBQ3C6V.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-2HBQ3C6V.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/Classes/TaxRule.ts"],"names":["TaxRuleBaseModel","data","taxCategory","taxCountry","at","taxRule","rate","formateOption","percentage","rateStr","TaxRu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gClB,CAAiB,CAC5C,IACA,CAAA,YAAA,CACA,YAEV,CAAA,WAAA,CAAYC,EAA8B,CACxC,KAAA,CAAMA,CAAI,CAAA,CACV,IAAK,CAAA,IAAA,CAAOA,EAAK,IACjB,CAAA,IAAA,CAAK,YAAe,CAAA,IAAIY,CAAWZ,CAAAA,CAAAA,CAAK,YAAY,CACpD,CAAA,IAAA,CAAK,YAAeA,CAAAA,CAAAA,CAAK,YAAe,CAAA,IAAIY,EAAWZ,CAAK,CAAA,YAAY,CAAI,CAAA,KAAA,EAC9E,CAEO,oBAAA,EAA+B,CACpC,OAAO,IAAA,CAAK,IACd,CAMA,YAAaa,CAAAA,CAAAA,CAAmC,CAC9C,IAAMR,CAAAA,CAAO,IAAK,CAAA,oBAAA,EAClB,CAAA,OAAOQ,EAAU,QAASR,CAAAA,CAAI,CAAE,CAAA,KAAA,EAClC,CAEO,YAA+B,CACpC,OAAO,CACL,GAAG,KAAM,CAAA,UAAA,GACT,IAAM,CAAA,IAAA,CAAK,oBAAqB,EAAA,CAChC,YAAc,CAAA,IAAA,CAAK,aAAa,UAAW,EAAA,CAC3C,YAAc,CAAA,IAAA,CAAK,YAAe,CAAA,IAAA,CAAK,aAAa,UAAW,EAAA,CAAI,KACrE,CAAA,CACF,CACF","file":"chunk-2HBQ3C6V.mjs","sourcesContent":["import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, ISODateTimeUTC } from \"./Common\";\r\nimport { TaxSystem } from \"./Enum\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport { TaxSlabNotFoundError } from \"./Error\";\r\n\r\nexport type TaxRuleBaseAttributes = {\r\n taxRuleId: string;\r\n taxCategory: string;\r\n taxSystem: TaxSystem;\r\n taxSubSystem: string;\r\n taxCountry: CountryCode;\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n}\r\n\r\nexport type TaxRuleBaseData = TaxRuleBaseAttributes;\r\n\r\nexport class TaxRuleBaseModel {\r\n protected taxRuleId: string;\r\n protected taxCategory: string;\r\n protected taxSystem: TaxSystem;\r\n protected taxSubSystem: string;\r\n protected taxCountry: CountryCode;\r\n protected effectiveFrom: Date;\r\n protected effectiveTo?: Date;\r\n\r\n constructor(data: TaxRuleBaseAttributes) {\r\n this.taxRuleId = data.taxRuleId;\r\n this.taxSystem = data.taxSystem;\r\n this.taxSubSystem = data.taxSubSystem;\r\n this.taxCategory = data.taxCategory;\r\n this.taxCountry = data.taxCountry;\r\n this.effectiveFrom = new Date(data.effectiveFrom);\r\n this.effectiveTo = data.effectiveTo ? new Date(data.effectiveTo) : undefined;\r\n }\r\n\r\n getTaxRuleId(): string {\r\n return this.taxRuleId;\r\n }\r\n\r\n getTaxSystem(): TaxSystem {\r\n return this.taxSystem;\r\n }\r\n\r\n getTaxSubSystem(): string {\r\n return this.taxSubSystem;\r\n }\r\n\r\n getTaxCategory(): string {\r\n return this.taxCategory;\r\n }\r\n\r\n getTaxCountry(): CountryCode {\r\n return this.taxCountry;\r\n }\r\n\r\n getEffectiveFrom(): Date {\r\n return this.effectiveFrom;\r\n }\r\n\r\n getEffectiveTo(): Date | undefined {\r\n return this.effectiveTo;\r\n }\r\n\r\n getDetails(): TaxRuleBaseData {\r\n return {\r\n taxRuleId: this.getTaxRuleId(),\r\n taxSystem: this.getTaxSystem(),\r\n taxSubSystem: this.getTaxSubSystem(),\r\n taxCategory: this.getTaxCategory(),\r\n taxCountry: this.getTaxCountry(),\r\n effectiveFrom: this.effectiveFrom.toISOString(),\r\n effectiveTo: this.effectiveTo ? this.effectiveTo.toISOString() : undefined\r\n };\r\n }\r\n\r\n /**\r\n * Checks whether this tax rule is applicable for the given category and taxCountry at a specific time.\r\n * @param taxCategory - The tax category to check.\r\n * @param taxCountry - The taxCountry code to check.\r\n * @param at - The date to check effectiveness against (defaults to now).\r\n * @returns True if the rule is applicable, false otherwise.\r\n */\r\n appliesTo(taxCategory: string, taxCountry: CountryCode, at: Date = new Date()): boolean {\r\n return (\r\n this.taxCategory === taxCategory &&\r\n this.taxCountry === taxCountry &&\r\n this.effectiveFrom <= at &&\r\n (this.effectiveTo ? this.effectiveTo >= at : true)\r\n );\r\n }\r\n\r\n static getTaxRateDisplayString(taxRule: TaxRuleBaseModel, rate: number, formateOption?: {\r\n percentageOnly?: boolean;\r\n }): string {\r\n const percentage = rate * 100;\r\n // Format to remove trailing zeros if it's an integer, otherwise keep up to 2 decimal places\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n\r\n if (formateOption?.percentageOnly) {\r\n return `${rateStr}%`;\r\n }\r\n\r\n if (taxRule.getTaxSystem() === TaxSystem.GST) {\r\n return `${rateStr}% ${taxRule.getTaxSubSystem()}`;\r\n }\r\n return `${rateStr}% ${taxRule.getTaxSystem()}`;\r\n }\r\n}\r\n\r\nexport type TaxSlabData = {\r\n minUnitPrice: PriceData; // inclusive\r\n maxUnitPrice?: PriceData; // exclusive\r\n rate: number; // e.g. 0.05 = 5%\r\n};\r\n\r\nexport type TaxSlabModel = {\r\n minUnitPrice: PriceModel; // inclusive\r\n maxUnitPrice?: PriceModel; // exclusive\r\n rate: number; // e.g. 0.05 = 5%\r\n};\r\n\r\nexport type TaxSlabs = TaxSlabData[];\r\n\r\nexport type TaxRuleAttributes = TaxRuleBaseAttributes & {\r\n slabs: TaxSlabs;\r\n};\r\n\r\nexport type TaxRuleData = TaxRuleAttributes;\r\n\r\nexport class TaxRuleModel extends TaxRuleBaseModel {\r\n protected slabs: TaxSlabModel[];\r\n\r\n /**\r\n * Creates an instance of TaxRuleModel.\r\n * @param data - The initial tax rule attributes.\r\n */\r\n constructor(data: TaxRuleAttributes) {\r\n super(data)\r\n this.slabs = data.slabs.map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: new PriceModel(s.minUnitPrice),\r\n maxUnitPrice: s.maxUnitPrice ? new PriceModel(s.maxUnitPrice) : undefined,\r\n }));\r\n }\r\n\r\n getSlabs(): TaxSlabModel[] {\r\n return this.slabs;\r\n }\r\n\r\n getDetails(): TaxRuleData {\r\n return {\r\n ...super.getDetails(),\r\n slabs: this.getSlabs().map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: s.minUnitPrice.getDetails(),\r\n maxUnitPrice: s.maxUnitPrice ? s.maxUnitPrice.getDetails() : undefined,\r\n })),\r\n };\r\n }\r\n\r\n /**\r\n * Gets the applicable tax rate for the given unit price based on the slabs.\r\n * @param unitPrice - The unit price to match against slabs.\r\n * @returns The applicable tax rate as a decimal (e.g., 0.18 for 18%).\r\n */\r\n getApplicableTaxRate(unitPrice: PriceModel): number {\r\n return TaxRuleModel.getApplicableTaxRate(unitPrice, this.slabs);\r\n }\r\n\r\n /**\r\n * Calculates the tax amount for a given taxable amount.\r\n * @param unitPrice - The unit price used to determine which tax slab applies.\r\n * @returns The calculated tax amount as a PriceModel.\r\n */\r\n calculateTax(unitPrice: PriceModel): PriceModel {\r\n const rate = this.getApplicableTaxRate(unitPrice);\r\n return unitPrice.multiply(rate).round();\r\n }\r\n\r\n /**\r\n * Calculates the applicable tax rate for a given unit price.\r\n * @param unitPrice - The unit price to find the matching tax slab for.\r\n * @returns The tax rate as a decimal (e.g., 0.05 for 5%).\r\n * @throws {TaxSlabNotFoundError} If no applicable slab or multiple slabs are found.\r\n */\r\n static getApplicableTaxRate(unitPrice: PriceModel, taxSlabs: TaxSlabModel[]): number {\r\n const slabs = taxSlabs.filter(s =>\r\n (s.minUnitPrice === undefined || unitPrice.compareTo(s.minUnitPrice) >= 0) &&\r\n (s.maxUnitPrice === undefined || unitPrice.compareTo(s.maxUnitPrice) < 0)\r\n );\r\n\r\n if (slabs.length !== 1) {\r\n throw new TaxSlabNotFoundError();\r\n }\r\n\r\n return slabs[0].rate;\r\n }\r\n}\r\n\r\n\r\nexport type FixedTaxRuleAttributes = TaxRuleBaseAttributes & {\r\n rate: number;\r\n minUnitPrice: PriceData;\r\n maxUnitPrice?: PriceData;\r\n}\r\n\r\nexport type FixedTaxRuleData = FixedTaxRuleAttributes;\r\n\r\n/**\r\n * A specialized version of TaxRuleModel for fixed-rate taxes (single slab).\r\n * Ideal for components like Charges where slab-based logic is not required.\r\n */\r\nexport class FixedTaxRuleModel extends TaxRuleBaseModel {\r\n protected rate: number;\r\n protected minUnitPrice: PriceModel;\r\n protected maxUnitPrice?: PriceModel;\r\n\r\n constructor(data: FixedTaxRuleAttributes) {\r\n super(data);\r\n this.rate = data.rate;\r\n this.minUnitPrice = new PriceModel(data.minUnitPrice);\r\n this.maxUnitPrice = data.maxUnitPrice ? new PriceModel(data.maxUnitPrice) : undefined;\r\n }\r\n\r\n public getApplicableTaxRate(): number {\r\n return this.rate;\r\n }\r\n\r\n /**\r\n * Calculates the tax amount for a given taxable amount.\r\n * @returns The calculated tax amount as a PriceModel.\r\n */\r\n calculateTax(unitPrice: PriceModel): PriceModel {\r\n const rate = this.getApplicableTaxRate();\r\n return unitPrice.multiply(rate).round();\r\n }\r\n\r\n public getDetails(): FixedTaxRuleData {\r\n return {\r\n ...super.getDetails(),\r\n rate: this.getApplicableTaxRate(),\r\n minUnitPrice: this.minUnitPrice.getDetails(),\r\n maxUnitPrice: this.maxUnitPrice ? this.maxUnitPrice.getDetails() : undefined,\r\n };\r\n }\r\n}\r\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a}from'./chunk-Y5D6RHTJ.mjs';import {a as a$1}from'./chunk-XHGUVYQO.mjs';import {e}from'./chunk-FC4P26U3.mjs';import {t}from'./chunk-XPKK6DFA.mjs';import {b as b$1}from'./chunk-6KCJVEZD.mjs';var y=(t=>(t.COUPON="coupon",t.AUTOMATIC="automatic",t))(y||{}),M=(t=>(t.FLAT="flat",t.PERCENTAGE="percentage",t))(M||{}),b=(t=>(t.SHIPPING="SHIPPING",t.CUSTOMER="CUSTOMER",t))(b||{}),P=(t=>(t.ALL="all",t.FTB="ftb",t))(P||{}),p=class extends b$1{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(e,t$1=new Date){if(super(e,t$1),this.couponCode=e.couponCode,this.name=a.deepClone(e.name),this.description=a.deepClone(e.description),this.type=e.type,this.customerId=e.customerId,this.validFrom=e.validFrom&&Date.parse(e.validFrom)?new Date(e.validFrom).toISOString():t$1.toISOString(),this.validTo=e.validTo&&Date.parse(e.validTo)?new Date(e.validTo).toISOString():t$1.toISOString(),this.minCartValue=Object.keys(e.minCartValue).reduce((o,i)=>{let r=e.minCartValue[i];return r&&(o[i]=new a$1(r)),o},{}),this.maxCartDiscount=Object.keys(e.maxCartDiscount).reduce((o,i)=>{let r=e.maxCartDiscount[i];return r&&(o[i]=new a$1(r)),o},{}),this.discountMethod=e.discountMethod,this.percentageValue=e.percentageValue??0,this.percentageValue>100)throw new t("Percentage value cannot be greater than 100");this.applicableTo=e.applicableTo,this.category=e.category;}getCode(){return this.couponCode}getName(e$1){return e$1?this.name[e$1]??this.name[e[e$1]]??this.name.en:{...this.name}}getDescription(e$1){return e$1?this.description[e$1]??this.description[e[e$1]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(e){return e?this.minCartValue[e]:this.minCartValue}getMaxCartDiscount(e){return e?this.maxCartDiscount[e]:this.maxCartDiscount}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:Object.keys(this.getMinCartValue()).reduce((e,t)=>{let o=this.getMinCartValue(t);return o&&(e[t]=o.getDetails()),e},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((e,t)=>{let o=this.getMaxCartDiscount(t);return o&&(e[t]=o.getDetails()),e},{}),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(e){return this.applicableTo==="all"||this.applicableTo==="ftb"&&e}calculateApplicableCouponDiscount(e,t,o,i,r=!0){let n=new a$1({amount:0,currency:i}),s;if(r&&!this.isActive())return n;let C=this.getMinCartValue(o),c=this.getMaxCartDiscount(o);if(!C||C.compareTo(e)>0||!c)return n;let h=this.getCategory(),D=this.getDiscountMethod(),u=h==="SHIPPING"?t:e;if(u.getAmount()<=0)return n;switch(D){case"flat":let T=c;s=u.min(T);break;case"percentage":s=u.multiply(this.getPercentageValue()/100).round();break;default:return n}return s.min(c)}};export{y as a,M as b,b as c,P as d,p as e};//# sourceMappingURL=chunk-2ZQIRKRB.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-2ZQIRKRB.mjs.map
|
|
@@ -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,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,IAAO,CAAA,MAAA,CACPA,EAAA,UAAa,CAAA,YAAA,CAFHA,CAAA,CAAA,EAAA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jEG,CAGJ,CAAA,GAAIF,GAAe,CAAC,IAAA,CAAK,QAAS,EAAA,CAChC,OAAOC,CAIT,CAAA,IAAME,CAAkB,CAAA,IAAA,CAAK,gBAAgBd,CAAO,CAAA,CAC9Ce,CAAqB,CAAA,IAAA,CAAK,kBAAmBf,CAAAA,CAAO,CAQ1D,CAAA,GALI,CAACc,CAAmBA,EAAAA,CAAAA,CAAgB,SAAUN,CAAAA,CAAS,EAAI,CAK3D,EAAA,CAACO,CACH,CAAA,OAAOH,EAIT,IAAMI,CAAAA,CAAiB,IAAK,CAAA,WAAA,EACtBC,CAAAA,CAAAA,CAAiB,IAAK,CAAA,iBAAA,GAEtBC,CAAcF,CAAAA,CAAAA,GAAmB,UAA0BP,CAAAA,CAAAA,CAAeD,EAGhF,GAAIU,CAAAA,CAAY,SAAU,EAAA,EAAK,EAAG,OAAON,CAAAA,CAEzC,OAAQK,CAAAA,EACN,IAAK,MAEH,CAAA,IAAME,EAAaJ,CACnBF,CAAAA,CAAAA,CAAoBK,CAAY,CAAA,GAAA,CAAIC,CAAU,CAC9C,CAAA,MACF,IAAK,YAAA,CAEHN,EAAoBK,CAAY,CAAA,QAAA,CAAS,IAAK,CAAA,kBAAA,EAAuB,CAAA,GAAG,CAAE,CAAA,KAAA,GAC1E,MACF,QAEE,OAAON,CACX,CAKA,OAFsBC,CAAAA,CAAkB,GAAIE,CAAAA,CAAkB,CAGhE,CACF","file":"chunk-RSMXGZD4.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) {\r\n if (country) {\r\n return this.minCartValue[country];\r\n }\r\n return this.minCartValue;\r\n }\r\n\r\n /**\r\n * Gets the list of maximum discount amounts allowed for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional maximum discount caps.\r\n */\r\n getMaxCartDiscount(): { [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) {\r\n if (country) {\r\n return this.maxCartDiscount[country];\r\n }\r\n return this.maxCartDiscount;\r\n }\r\n\r\n /** Gets the discount method (FLAT or PERCENTAGE). */\r\n getDiscountMethod(): CouponDiscountMethod {\r\n return this.discountMethod;\r\n }\r\n\r\n /** Gets the percentage discount value (0-100). */\r\n getPercentageValue(): number {\r\n return this.percentageValue;\r\n }\r\n\r\n /** Gets the customer applicability rule (ALL or FTB). */\r\n getApplicableTo(): ApplicableTo {\r\n return this.applicableTo;\r\n }\r\n\r\n /** Gets the category of the coupon (SHIPPING or CUSTOMER). */\r\n getCategory(): CouponCategory {\r\n return this.category;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the coupon's details.\r\n * @returns A CouponData object.\r\n */\r\n getDetails(): CouponData {\r\n return {\r\n ...super.getDetails(),\r\n couponCode: this.getCode(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n type: this.getType(),\r\n customerId: this.getCustomerId(),\r\n validFrom: this.getValidFrom(),\r\n validTo: this.getValidTo(),\r\n minCartValue: (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}"]}
|
|
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,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,IAAO,CAAA,MAAA,CACPA,EAAA,UAAa,CAAA,YAAA,CAFHA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAKAC,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,QAAW,CAAA,UAAA,CACXA,EAAA,QAAW,CAAA,UAAA,CAFDA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAKAC,OACVA,CAAA,CAAA,GAAA,CAAM,KACNA,CAAAA,CAAAA,CAAA,IAAM,KAFIA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EA0BSC,CAAAA,CAAAA,CAAAA,CAArB,cAAyCC,GAAU,CACvC,UAAA,CAC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EACtBC,CAAAA,CAAAA,CAAiB,IAAK,CAAA,iBAAA,GAEtBC,CAAcF,CAAAA,CAAAA,GAAmB,UAA0BP,CAAAA,CAAAA,CAAeD,EAGhF,GAAIU,CAAAA,CAAY,SAAU,EAAA,EAAK,EAAG,OAAON,CAAAA,CAEzC,OAAQK,CAAAA,EACN,IAAK,MAEH,CAAA,IAAME,EAAaJ,CACnBF,CAAAA,CAAAA,CAAoBK,CAAY,CAAA,GAAA,CAAIC,CAAU,CAC9C,CAAA,MACF,IAAK,YAAA,CAEHN,EAAoBK,CAAY,CAAA,QAAA,CAAS,IAAK,CAAA,kBAAA,EAAuB,CAAA,GAAG,CAAE,CAAA,KAAA,GAC1E,MACF,QAEE,OAAON,CACX,CAKA,OAFsBC,CAAAA,CAAkB,GAAIE,CAAAA,CAAkB,CAGhE,CACF","file":"chunk-2ZQIRKRB.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) {\r\n if (country) {\r\n return this.minCartValue[country];\r\n }\r\n return this.minCartValue;\r\n }\r\n\r\n /**\r\n * Gets the list of maximum discount amounts allowed for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional maximum discount caps.\r\n */\r\n getMaxCartDiscount(): { [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) {\r\n if (country) {\r\n return this.maxCartDiscount[country];\r\n }\r\n return this.maxCartDiscount;\r\n }\r\n\r\n /** Gets the discount method (FLAT or PERCENTAGE). */\r\n getDiscountMethod(): CouponDiscountMethod {\r\n return this.discountMethod;\r\n }\r\n\r\n /** Gets the percentage discount value (0-100). */\r\n getPercentageValue(): number {\r\n return this.percentageValue;\r\n }\r\n\r\n /** Gets the customer applicability rule (ALL or FTB). */\r\n getApplicableTo(): ApplicableTo {\r\n return this.applicableTo;\r\n }\r\n\r\n /** Gets the category of the coupon (SHIPPING or CUSTOMER). */\r\n getCategory(): CouponCategory {\r\n return this.category;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the coupon's details.\r\n * @returns A CouponData object.\r\n */\r\n getDetails(): CouponData {\r\n return {\r\n ...super.getDetails(),\r\n couponCode: this.getCode(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n type: this.getType(),\r\n customerId: this.getCustomerId(),\r\n validFrom: this.getValidFrom(),\r\n validTo: this.getValidTo(),\r\n minCartValue: (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}"]}
|