b23-lib 3.8.0 → 3.9.1
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 +1 -1
- package/dist/Auth/index.js.map +1 -1
- package/dist/Auth/index.mjs +1 -1
- package/dist/Auth/index.mjs.map +1 -1
- package/dist/Classes/Cart.d.mts +1 -2
- package/dist/Classes/Cart.d.ts +1 -2
- 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.js +1 -1
- package/dist/Classes/Charge.js.map +1 -1
- package/dist/Classes/Charge.mjs +1 -1
- package/dist/Classes/Coupon.js +1 -1
- package/dist/Classes/Coupon.js.map +1 -1
- package/dist/Classes/Coupon.mjs +1 -1
- package/dist/Classes/Error.d.mts +4 -1
- package/dist/Classes/Error.d.ts +4 -1
- package/dist/Classes/Error.js +1 -1
- package/dist/Classes/Error.js.map +1 -1
- package/dist/Classes/Error.mjs +1 -1
- package/dist/Classes/ImageInfo.js.map +1 -1
- package/dist/Classes/ImageInfo.mjs +1 -1
- package/dist/Classes/Inventory.d.mts +1 -2
- package/dist/Classes/Inventory.d.ts +1 -2
- package/dist/Classes/Inventory.js +1 -1
- package/dist/Classes/Inventory.js.map +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/Inventory.mjs.map +1 -1
- package/dist/Classes/Invoice.d.mts +1 -2
- package/dist/Classes/Invoice.d.ts +1 -2
- package/dist/Classes/Invoice.js.map +1 -1
- package/dist/Classes/Invoice.mjs +1 -1
- package/dist/Classes/LineItem.d.mts +1 -2
- package/dist/Classes/LineItem.d.ts +1 -2
- 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.d.mts +1 -2
- package/dist/Classes/Order.d.ts +1 -2
- 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/Order.mjs.map +1 -1
- package/dist/Classes/Price.js.map +1 -1
- package/dist/Classes/Price.mjs +1 -1
- package/dist/Classes/Product.d.mts +5 -257
- package/dist/Classes/Product.d.ts +5 -257
- package/dist/Classes/Product.js +1 -1
- package/dist/Classes/Product.js.map +1 -1
- package/dist/Classes/Product.mjs +1 -1
- package/dist/Classes/ShoppingContainer.d.mts +1 -2
- package/dist/Classes/ShoppingContainer.d.ts +1 -2
- 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/TaxRule.js +1 -1
- package/dist/Classes/TaxRule.js.map +1 -1
- package/dist/Classes/TaxRule.mjs +1 -1
- package/dist/Classes/TieredPrice.d.mts +5 -81
- package/dist/Classes/TieredPrice.d.ts +5 -81
- package/dist/Classes/TieredPrice.js +1 -1
- package/dist/Classes/TieredPrice.js.map +1 -1
- package/dist/Classes/TieredPrice.mjs +1 -1
- package/dist/Product-BywRotdH.d.mts +367 -0
- package/dist/Product-mtVUKzNI.d.ts +367 -0
- package/dist/chunk-4QU5WW6U.mjs +2 -0
- package/dist/chunk-4QU5WW6U.mjs.map +1 -0
- package/dist/chunk-7B5TAYNA.mjs +2 -0
- package/dist/chunk-7B5TAYNA.mjs.map +1 -0
- package/dist/{chunk-2B2XI6FG.mjs → chunk-7RAIVZKB.mjs} +2 -2
- package/dist/{chunk-2B2XI6FG.mjs.map → chunk-7RAIVZKB.mjs.map} +1 -1
- package/dist/{chunk-C3METQSR.mjs → chunk-EZ35IKUA.mjs} +2 -2
- package/dist/{chunk-C3METQSR.mjs.map → chunk-EZ35IKUA.mjs.map} +1 -1
- package/dist/{chunk-TU4HOP63.mjs → chunk-MPKIC2MS.mjs} +2 -2
- package/dist/{chunk-TU4HOP63.mjs.map → chunk-MPKIC2MS.mjs.map} +1 -1
- package/dist/{chunk-R5DM7WCD.mjs → chunk-O6BLQQO7.mjs} +2 -2
- package/dist/chunk-O6BLQQO7.mjs.map +1 -0
- package/dist/chunk-PNTRHKEH.mjs +2 -0
- package/dist/chunk-PNTRHKEH.mjs.map +1 -0
- package/dist/{chunk-PAOHRZCC.mjs → chunk-Q7FOHAQD.mjs} +2 -2
- package/dist/{chunk-PAOHRZCC.mjs.map → chunk-Q7FOHAQD.mjs.map} +1 -1
- package/dist/{chunk-AWKAKL2Y.mjs → chunk-REP6D3WD.mjs} +2 -2
- package/dist/{chunk-AWKAKL2Y.mjs.map → chunk-REP6D3WD.mjs.map} +1 -1
- package/dist/{chunk-VO7ZE5C3.mjs → chunk-UIQH5QIR.mjs} +2 -2
- package/dist/{chunk-VO7ZE5C3.mjs.map → chunk-UIQH5QIR.mjs.map} +1 -1
- package/dist/index.d.mts +1 -2
- package/dist/index.d.ts +1 -2
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-DURMXVHZ.mjs +0 -2
- package/dist/chunk-DURMXVHZ.mjs.map +0 -1
- package/dist/chunk-ID3CEA7W.mjs +0 -2
- package/dist/chunk-ID3CEA7W.mjs.map +0 -1
- package/dist/chunk-LJEJAR35.mjs +0 -2
- package/dist/chunk-LJEJAR35.mjs.map +0 -1
- package/dist/chunk-R5DM7WCD.mjs.map +0 -1
- package/dist/chunk-USMLRWT6.mjs +0 -2
- package/dist/chunk-USMLRWT6.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../node_modules/uuid/dist/esm-node/rng.js","../node_modules/uuid/dist/esm-node/regex.js","../node_modules/uuid/dist/esm-node/validate.js","../node_modules/uuid/dist/esm-node/stringify.js","../node_modules/uuid/dist/esm-node/parse.js","../node_modules/uuid/dist/esm-node/v35.js","../node_modules/uuid/dist/esm-node/native.js","../node_modules/uuid/dist/esm-node/v4.js","../node_modules/uuid/dist/esm-node/sha1.js","../node_modules/uuid/dist/esm-node/v5.js","../src/Utils/index.ts","../src/Classes/Product.ts","../src/Classes/TieredPrice.ts"],"names":["rnds8Pool","poolPtr","rng","crypto","regex_default","validate","uuid","validate_default","byteToHex","unsafeStringify","arr","offset","parse","v","parse_default","stringToBytes","str","bytes","i","DNS","URL","v35","name","version","hashfunc","generateUUID","value","namespace","buf","_namespace","native_default","v4","options","rnds","v4_default","sha1","sha1_default","v5","v5_default","Utils","key","selectionAttributes","ProductModel","searchId","selectionAttributesKey","obj","Utils_default","_ProductModel","BaseModel","SelectionAttributeParseError","attributes","parts","part","error","data","date","acc","country","TieredPriceModel","uniqueSelectionAttributes","variant","DuplicateSelectionAttributeError","ImageInfoModel","image","locale","LocaleLanguageMap","searchKey","match","category","baseDetails","img","allowedAttributeValues","providedValue","c","size","PricingType","SelectionTieredPriceModel","VolumeTieredPriceModel","InvalidTaxCategoryError","InvalidTieredPriceError","PriceModel","tiers","tier","a","b","t","InvalidMinQuantityError","hasDifferentCurrency","hasIrregularPricing","index","basePriceExceedsFirstTier","quantity","InvalidQuantityError","enabledTiers","NoApplicableTierError","minTierPrice","basePrice","discount","selection","baseUnitPrice","s","InvalidPricingTypeError"],"mappings":"kPACA,IAAMA,CAAAA,CAAY,IAAI,UAAW,CAAA,GAAG,CAEhCC,CAAAA,CAAAA,CAAUD,EAAU,MACT,CAAA,SAARE,CAAuB,EAAA,CAC5B,OAAID,CAAUD,CAAAA,CAAAA,CAAU,MAAS,CAAA,EAAA,GAC/BG,CAAO,CAAA,cAAA,CAAeH,CAAS,CAAA,CAC/BC,EAAU,CAGLD,CAAAA,CAAAA,CAAAA,CAAU,KAAMC,CAAAA,CAAAA,CAASA,GAAW,EAAE,CAC/C,CCXA,IAAOG,EAAQ,qHCEf,CAAA,SAASC,CAASC,CAAAA,CAAAA,CAAM,CACtB,OAAO,OAAOA,CAAAA,EAAS,UAAYF,CAAM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ACF,CACF","file":"chunk-7B5TAYNA.mjs","sourcesContent":["import crypto from 'crypto';\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\n\nlet poolPtr = rnds8Pool.length;\nexport default function rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n crypto.randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}","export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\n\nexport function unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];\n}\n\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import validate from './validate.js';\n\nfunction parse(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n let v;\n const arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nexport default parse;","import { unsafeStringify } from './stringify.js';\nimport parse from './parse.js';\n\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n const bytes = [];\n\n for (let i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n\n return bytes;\n}\n\nexport const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexport const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nexport default function v35(name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n var _namespace;\n\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n\n if (typeof namespace === 'string') {\n namespace = parse(namespace);\n }\n\n if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n } // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n\n\n let bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n\n return buf;\n }\n\n return unsafeStringify(bytes);\n } // Function#name is not settable on some platforms (#270)\n\n\n try {\n generateUUID.name = name; // eslint-disable-next-line no-empty\n } catch (err) {} // For CommonJS default export support\n\n\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","import crypto from 'crypto';\nexport default {\n randomUUID: crypto.randomUUID\n};","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\n\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n\n options = options || {};\n const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return unsafeStringify(rnds);\n}\n\nexport default v4;","import crypto from 'crypto';\n\nfunction sha1(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n\n return crypto.createHash('sha1').update(bytes).digest();\n}\n\nexport default sha1;","import v35 from './v35.js';\nimport sha1 from './sha1.js';\nconst v5 = v35('v5', 0x50, sha1);\nexport default v5;","import { v4 as uuidv4, v5 as uuidv5 } from 'uuid';\r\nimport ProductModel, { SelectionAttributes } from '../Classes/Product';\r\n\r\nconst Utils = {\r\n isUUID: (value: string): boolean => {\r\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\r\n return uuidRegex.test(value);\r\n },\r\n\r\n isEmail: (value: string): boolean => {\r\n const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;\r\n return emailRegex.test(value);\r\n },\r\n\r\n isURL: (value: string): boolean => {\r\n const urlRegex = /^(http|https):\\/\\/[^ \"]+$/;\r\n return urlRegex.test(value);\r\n },\r\n \r\n generateUUID: (value?: string, namespace?: string) => {\r\n if(namespace && value){\r\n return uuidv5(value, namespace);\r\n }\r\n return uuidv4();\r\n },\r\n\r\n generateSearchId: (key: string, selectionAttributes: SelectionAttributes) => {\r\n return `${key}#${ProductModel.generateSelectionAttributesKey(selectionAttributes)}`;\r\n },\r\n\r\n getKeyfromSearchId: (searchId: string) => {\r\n const [key, selectionAttributesKey] = searchId.split('#');\r\n return {\r\n key,\r\n selectionAttributes: ProductModel.parseSelectionAttributesKey(selectionAttributesKey)\r\n }\r\n },\r\n\r\n /**\r\n * Deep clones an object using `structuredClone`. Don't use this on a class instance.\r\n * @param obj - The object to clone.\r\n * @returns A deep clone of the object.\r\n */\r\n deepClone<T>(obj: T): T {\r\n return structuredClone(obj);\r\n }\r\n}\r\n\r\nexport default Utils;\r\n","import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { Color, LocalizedString, CountryCode, LocaleCode, LocalizedValue, Prettify } from './Common';\r\nimport { GenderCategory, ImageCategory, LocaleLanguageMap, ProductType } from \"./Enum\";\r\nimport { DuplicateSelectionAttributeError, DuplicateSizeError, SelectionAttributeParseError } from \"./Error\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport { TieredPriceModel, TieredPriceAttributes, TieredPriceData } from \"./TieredPrice\";\r\n\r\nexport type ProductSelectionAttributes = Prettify<{\r\n color: Color[];\r\n size: string[];\r\n} & {\r\n [key: string]: string | string[] | Color[];\r\n}>;\r\n\r\nexport type SelectionAttributes = {\r\n color: Color;\r\n [key: string]: string | Color;\r\n};\r\n\r\nexport type VariantData = {\r\n sku: string;\r\n selectionAttributes: SelectionAttributes;\r\n images: {\r\n primary: ImageInfoData;\r\n gallery: ImageInfoData[];\r\n };\r\n};\r\n\r\nexport type VariantModel = {\r\n sku: string;\r\n selectionAttributes: SelectionAttributes;\r\n images: {\r\n primary: ImageInfoModel;\r\n gallery: ImageInfoModel[];\r\n };\r\n};\r\n\r\n\r\nexport type ProductSpecification = { [key: string]: string | string[] };\r\n\r\nexport type ProductAttributes = BaseAttributes & {\r\n id: string;\r\n key: string;\r\n\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n slug: LocalizedString;\r\n brand: string;\r\n\r\n pricing: {\r\n [country in CountryCode]?: TieredPriceAttributes;\r\n };\r\n\r\n targetGender: GenderCategory;\r\n attributes: ProductSelectionAttributes;\r\n specifications: LocalizedValue<ProductSpecification>;\r\n categories: string[];\r\n productType?: ProductType;\r\n\r\n variants: VariantData[];\r\n\r\n // Metadata\r\n isActive: boolean;\r\n searchTags?: LocalizedValue<string[]>;\r\n};\r\n\r\nexport type ProductData = Required<ProductAttributes>\r\n\r\nexport default class ProductModel extends BaseModel {\r\n protected id: string;\r\n protected key: string;\r\n\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected slug: LocalizedString;\r\n protected brand: string;\r\n\r\n protected pricing: {\r\n [country in CountryCode]?: TieredPriceModel;\r\n };\r\n\r\n protected variants: VariantModel[];\r\n\r\n protected targetGender: GenderCategory;\r\n protected attributes: ProductSelectionAttributes;\r\n protected specifications: LocalizedValue<ProductSpecification>;\r\n protected categories: string[];\r\n protected productType: ProductType;\r\n\r\n // Metadata\r\n protected isActive: boolean;\r\n\r\n protected searchTags: LocalizedValue<string[]>;\r\n\r\n static productKeyRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n static productSKURegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n\r\n /**\r\n * Generates a unique key for checking uniqueness for a given selection attributes.\r\n * Excludes 'size' from the key generation.\r\n * @param selectionAttributes - The selection attributes.\r\n * @returns A string key representing the unique attribute combination.\r\n */\r\n static generateSelectionAttributesKey(selectionAttributes: SelectionAttributes): string {\r\n if (typeof selectionAttributes !== 'object') {\r\n throw new SelectionAttributeParseError('Selection attributes must be an object');\r\n }\r\n\r\n const sortedKeys = Object.keys(selectionAttributes)\r\n .filter(key => selectionAttributes[key] !== undefined && key.toLowerCase() !== 'size')\r\n .sort()\r\n\r\n return sortedKeys.map(key => {\r\n if ((selectionAttributes[key] as Color).name) {\r\n return `${key}:c+${(selectionAttributes[key] as Color).name}`;\r\n }\r\n return `${key}:${selectionAttributes[key]}`;\r\n }).join('|').toLowerCase();\r\n }\r\n\r\n /**\r\n * Parses a selection attributes key into an object.\r\n * @param key - The selection attributes key to parse.\r\n * @returns An object containing the parsed selection attributes.\r\n */\r\n static parseSelectionAttributesKey(key: string): SelectionAttributes {\r\n try {\r\n const attributes: SelectionAttributes = {} as unknown as SelectionAttributes;\r\n const parts = key.split('|');\r\n for (const part of parts) {\r\n const [key, value] = part.split(':');\r\n if (value.startsWith('c+')) {\r\n attributes[key] = { name: value.slice(2) } as Color;\r\n } else {\r\n attributes[key] = value;\r\n }\r\n }\r\n return attributes;\r\n } catch (error: any) {\r\n throw new SelectionAttributeParseError(error?.message);\r\n }\r\n }\r\n\r\n /**\r\n * Creates an instance of ProductModel.\r\n * Initializes properties based on the provided data, creating copies where necessary.\r\n * @param data - The initial product attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: ProductAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n\r\n this.id = data.id;\r\n this.key = data.key;\r\n\r\n this.name = { ...data.name };\r\n this.description = { ...data.description };\r\n this.slug = { ...data.slug };\r\n this.brand = data.brand;\r\n\r\n this.pricing = (Object.keys(data.pricing) as CountryCode[]).reduce((acc, country) => {\r\n if (data.pricing[country]) {\r\n acc[country] = TieredPriceModel.create(data.pricing[country] as TieredPriceAttributes);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: TieredPriceModel });\r\n\r\n this.targetGender = data.targetGender;\r\n this.attributes = Utils.deepClone(data.attributes);\r\n this.specifications = Utils.deepClone(data.specifications);\r\n this.categories = Utils.deepClone(data.categories);\r\n this.productType = data.productType ?? ProductType.GOODS;\r\n\r\n const uniqueSelectionAttributes = new Set<string>();\r\n this.variants = (data.variants || []).map(variant => {\r\n if (!variant.selectionAttributes || typeof variant.selectionAttributes !== 'object') {\r\n throw new SelectionAttributeParseError('Selection attributes are required');\r\n }\r\n\r\n this.checkSelectionAttributes(variant.selectionAttributes);\r\n const key = ProductModel.generateSelectionAttributesKey(variant.selectionAttributes);\r\n if (uniqueSelectionAttributes.has(key)) {\r\n throw new DuplicateSelectionAttributeError(key);\r\n }\r\n uniqueSelectionAttributes.add(key);\r\n return {\r\n sku: variant.sku,\r\n selectionAttributes: variant.selectionAttributes,\r\n images: {\r\n primary: new ImageInfoModel(variant.images.primary),\r\n gallery: (variant.images.gallery || []).map(image => new ImageInfoModel(image))\r\n }\r\n };\r\n });\r\n\r\n this.isActive = data.isActive;\r\n this.searchTags = data.searchTags ? Utils.deepClone(data.searchTags) : { en: [] };\r\n }\r\n\r\n /**\r\n * Gets the base Product ID.\r\n * @returns Product ID.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the user-friendly product key.\r\n * @returns Product Key.\r\n */\r\n getKey(): string {\r\n return this.key;\r\n }\r\n\r\n /**\r\n * Gets the full localized product name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the product name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return Utils.deepClone(this.name);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product description object.\r\n * @returns A copy of the LocalizedString object for the description.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the product description for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The description string for the specified locale.\r\n */\r\n getDescription(locale: LocaleCode): string\r\n getDescription(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.description[locale] ?? this.description[LocaleLanguageMap[locale]] ?? this.description.en;\r\n } else {\r\n return Utils.deepClone(this.description);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product slug object.\r\n * @returns A copy of the LocalizedString object for the slug.\r\n */\r\n getSlug(): LocalizedString\r\n /**\r\n * Gets the product slug for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The slug string for the specified locale.\r\n */\r\n getSlug(locale: LocaleCode): string\r\n getSlug(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.slug[locale] ?? this.slug[LocaleLanguageMap[locale]] ?? this.slug.en;\r\n } else {\r\n return Utils.deepClone(this.slug);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the brand associated with the product.\r\n * @returns The brand name string.\r\n */\r\n getBrand(): string {\r\n return this.brand;\r\n }\r\n\r\n /**\r\n * Gets the tiered price details for the product.\r\n * @returns Pricing details mapped by country.\r\n */\r\n getPriceDetails(): { [country in CountryCode]?: TieredPriceModel }\r\n /**\r\n * Gets the tiered price details for a specific country.\r\n * @param country - The country code.\r\n * @returns The tiered price model for the country, or null if not found.\r\n */\r\n getPriceDetails(country: CountryCode): TieredPriceModel | null\r\n getPriceDetails(country?: CountryCode): { [country in CountryCode]?: TieredPriceModel } | TieredPriceModel | null {\r\n if (country) {\r\n return this.pricing[country] ?? null;\r\n }\r\n return { ...this.pricing };\r\n }\r\n\r\n /**\r\n * Gets the variant-specific attributes (color, sizes). Returns copies.\r\n * @returns Product Attributes.\r\n */\r\n getAttributes(): ProductSelectionAttributes {\r\n return Utils.deepClone(this.attributes);\r\n }\r\n\r\n\r\n /**\r\n * Gets the variant-specific attributes (color, sizes). Returns copies.\r\n * @returns Product Attributes.\r\n */\r\n getVariants(): VariantModel[] {\r\n return this.variants.map(variant => ({\r\n sku: variant.sku,\r\n selectionAttributes: Utils.deepClone(variant.selectionAttributes),\r\n images: {\r\n primary: variant.images.primary,\r\n gallery: [...variant.images.gallery]\r\n }\r\n }));\r\n }\r\n\r\n /**\r\n * Gets the images for a specific selection attribute combination.\r\n * @param selectionAttributes - The selection attributes to search for.\r\n * @returns The matching image set or null if not found.\r\n */\r\n private getImagesBySelectionAttributes(selectionAttributes: SelectionAttributes): { primary: ImageInfoModel; gallery: ImageInfoModel[] } | null {\r\n const searchKey = ProductModel.generateSelectionAttributesKey(selectionAttributes);\r\n\r\n const match = this.variants.find(variant =>\r\n ProductModel.generateSelectionAttributesKey(variant.selectionAttributes) === searchKey\r\n );\r\n\r\n return match ? {\r\n primary: match.images.primary,\r\n gallery: [...match.images.gallery]\r\n } : null;\r\n }\r\n\r\n /**\r\n * Gets the images for a specific selection attribute combination.\r\n * @param selectionAttributes - The selection attributes to search for.\r\n * @returns The matching image set or null if not found.\r\n */\r\n getImages(selectionAttributes: SelectionAttributes): { primary: ImageInfoModel; gallery: ImageInfoModel[] }\r\n getImages(selectionAttributes: SelectionAttributes, category: ImageCategory.PRIMARY): ImageInfoModel\r\n getImages(selectionAttributes: SelectionAttributes, category: ImageCategory.GALLERY): ImageInfoModel[]\r\n getImages(selectionAttributes: SelectionAttributes, category?: ImageCategory): { primary: ImageInfoModel; gallery: ImageInfoModel[] } | ImageInfoModel | ImageInfoModel[] {\r\n switch (category) {\r\n case ImageCategory.PRIMARY:\r\n return this.getImagesBySelectionAttributes(selectionAttributes)?.primary ?? this.variants[0]?.images?.primary;\r\n case ImageCategory.GALLERY:\r\n return this.getImagesBySelectionAttributes(selectionAttributes)?.gallery ?? [];\r\n default:\r\n return this.getImagesBySelectionAttributes(selectionAttributes) ?? { primary: this.variants[0]?.images?.primary, gallery: [] };\r\n }\r\n }\r\n\r\n\r\n /**\r\n * Checks if the product is active.\r\n * @returns True if the product is active, false otherwise.\r\n */\r\n getIsActive(): boolean {\r\n return this.isActive;\r\n }\r\n\r\n /**\r\n * Gets the target gender category for the product.\r\n * @returns The GenderCategory enum value.\r\n */\r\n getTargetGender(): GenderCategory {\r\n return this.targetGender;\r\n }\r\n\r\n /**\r\n * Gets the list of categories the product belongs to. Returns a copy.\r\n * @returns An array of category.\r\n */\r\n getCategories(): string[] {\r\n return Utils.deepClone(this.categories);\r\n }\r\n\r\n /**\r\n * Gets the product type.\r\n * @returns ProductType.\r\n */\r\n getProductType(): ProductType {\r\n return this.productType;\r\n }\r\n\r\n /**\r\n * Gets the full localized product specifications object.\r\n * @returns Product Specifications\r\n */\r\n getSpecifications(): LocalizedValue<ProductSpecification>\r\n /**\r\n * Gets the product specifications for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The ProductSpecification object for the specified locale, or undefined if not found.\r\n */\r\n getSpecifications(locale: LocaleCode): ProductSpecification\r\n getSpecifications(locale?: LocaleCode): LocalizedValue<ProductSpecification> | ProductSpecification {\r\n if (locale) {\r\n return Utils.deepClone(this.specifications[locale] ?? this.specifications[LocaleLanguageMap[locale]] ?? this.specifications.en);\r\n } else {\r\n return Utils.deepClone(this.specifications);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the localized list of search tags. Returns a copy.\r\n * @returns Localized array of search tags.\r\n */\r\n getSearchTags(): LocalizedValue<string[]>\r\n /**\r\n * Gets the search tags for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The array of search tags for the specified locale, or undefined if not found.\r\n */\r\n getSearchTags(locale: LocaleCode): string[]\r\n getSearchTags(locale?: LocaleCode): LocalizedValue<string[]> | string[] {\r\n if (locale) {\r\n return Utils.deepClone(this.searchTags[locale] ?? this.searchTags[LocaleLanguageMap[locale]] ?? this.searchTags.en);\r\n } else {\r\n return Utils.deepClone(this.searchTags);\r\n }\r\n }\r\n\r\n /**\r\n *\r\n * @returns ProductData\r\n */\r\n getDetails(): ProductData {\r\n const baseDetails = super.getDetails();\r\n return {\r\n id: this.getId(),\r\n key: this.getKey(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n slug: this.getSlug(),\r\n brand: this.getBrand(),\r\n pricing: (Object.keys(this.pricing) as CountryCode[]).reduce((acc, country) => {\r\n if (this.pricing[country]) {\r\n acc[country] = this.pricing[country]?.getDetails();\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]: TieredPriceData }),\r\n attributes: this.getAttributes(),\r\n variants: this.variants.map(v => ({\r\n sku: v.sku,\r\n selectionAttributes: Utils.deepClone(v.selectionAttributes),\r\n images: {\r\n primary: v.images.primary.getDetails(),\r\n gallery: v.images.gallery.map(img => img.getDetails())\r\n }\r\n })),\r\n isActive: this.getIsActive(),\r\n targetGender: this.getTargetGender(),\r\n categories: this.getCategories(),\r\n productType: this.getProductType(),\r\n specifications: this.getSpecifications(),\r\n searchTags: this.getSearchTags(),\r\n ...baseDetails\r\n };\r\n }\r\n\r\n /**\r\n * Checks if the provided selection attributes are valid for the product.\r\n * @param selectionAttributes The selection attributes to validate.\r\n * @throws {SelectionAttributeParseError} If the selection attributes are invalid.\r\n */\r\n checkSelectionAttributes(selectionAttributes: SelectionAttributes): void {\r\n if (!selectionAttributes || typeof selectionAttributes !== 'object') {\r\n throw new SelectionAttributeParseError('Selection attributes are required');\r\n }\r\n\r\n Object.keys(this.attributes).forEach(key => {\r\n if(key.toLowerCase() === 'size') return;\r\n \r\n const allowedAttributeValues = this.attributes[key];\r\n const providedValue = selectionAttributes[key];\r\n\r\n if (providedValue === undefined) {\r\n throw new SelectionAttributeParseError(`Selection attribute '${key}' is missing`);\r\n }\r\n\r\n if (typeof allowedAttributeValues === 'string') {\r\n if (typeof providedValue !== 'string' || allowedAttributeValues !== providedValue) {\r\n throw new SelectionAttributeParseError(`Selection attribute '${key}' is invalid`);\r\n }\r\n } else if (Array.isArray(allowedAttributeValues)) {\r\n if (allowedAttributeValues.length > 0 && typeof allowedAttributeValues[0] === 'string') {\r\n if (typeof providedValue !== 'string' || !(allowedAttributeValues as string[]).includes(providedValue)) {\r\n throw new SelectionAttributeParseError(`Selection attribute '${key}' is invalid`);\r\n }\r\n } else {\r\n // Color validation\r\n if (\r\n typeof providedValue !== 'object' ||\r\n !('name' in providedValue) ||\r\n (allowedAttributeValues as Color[]).findIndex(c => c.name === (providedValue as Color).name) < 0\r\n ) {\r\n throw new SelectionAttributeParseError(`Selection attribute '${key}' is invalid`);\r\n }\r\n }\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Gets the SKU of the variant matching the selection attributes.\r\n * @param selectionAttributes - The selection attributes to search for.\r\n * @returns The SKU string, or undefined if no matching variant is found.\r\n */\r\n public getSku(selectionAttributes: SelectionAttributes): string | undefined {\r\n const searchKey = ProductModel.generateSelectionAttributesKey(selectionAttributes);\r\n const match = this.variants.find(variant =>\r\n ProductModel.generateSelectionAttributesKey(variant.selectionAttributes) === searchKey\r\n );\r\n return match?.sku;\r\n }\r\n\r\n /**\r\n * Validates if the provided selection attributes exist for this product.\r\n * @param selectionAttributes - The attributes to validate.\r\n * @returns True if a valid selection attribute exists, false otherwise.\r\n */\r\n validateSelectionAttribute(selectionAttributes: SelectionAttributes): boolean {\r\n const searchKey = ProductModel.generateSelectionAttributesKey(selectionAttributes);\r\n\r\n return this.variants.some(variant => ProductModel.generateSelectionAttributesKey(variant.selectionAttributes) === searchKey);\r\n }\r\n\r\n /**\r\n * Validates if a specific size is available for this product.\r\n * @param size - The size to check.\r\n * @returns True if the size exists in the product's attributes, false otherwise.\r\n */\r\n validateSize(size: string): boolean {\r\n return this.attributes.size.includes(size);\r\n }\r\n}\r\n","import PriceModel, { PriceData } from \"./Price\";\nimport type { SelectionAttributes } from \"./Product\";\nimport ProductModel from \"./Product\";\nimport {\n InvalidTaxCategoryError,\n InvalidMinQuantityError,\n InvalidTieredPriceError,\n InvalidQuantityError,\n InvalidPricingTypeError,\n NoApplicableTierError\n} from \"./Error\";\nimport { CurrencyCode, Prettify } from \"./Common\";\n\nexport enum PricingType {\n VOLUME = 'volume',\n SELECTION = 'selection',\n}\n\n/**\n * Represents a pricing tier based on a minimum purchase quantity.\n */\nexport type PriceTier = {\n enabled: boolean;\n minQuantity: number;\n unitPrice: PriceModel;\n};\n\nexport type PriceTierData = {\n enabled: boolean;\n minQuantity: number;\n unitPrice: PriceData;\n};\n\n/**\n * Represents the configuration for a specific selection variant.\n */\nexport type SelectionPricingData = {\n selectionAttributes: SelectionAttributes;\n baseUnitPrice: PriceData;\n tiers?: PriceTierData[];\n};\n\nexport type SelectionPricing = {\n selectionAttributes: SelectionAttributes;\n baseUnitPrice: PriceModel;\n tiers: PriceTier[];\n};\n\nexport type PriceTierAttributes = Prettify<Omit<PriceTierData, 'enabled'> & { enabled?: boolean }>;\n\n/**\n * Represents the attributes required for tiered pricing.\n */\nexport type TieredPriceAttributes = Prettify<{\n taxCategory: string;\n isTaxInclusive?: boolean;\n} & ({\n currency?: CurrencyCode;\n type?: PricingType.VOLUME;\n baseUnitPrice: PriceData;\n tiers?: PriceTierAttributes[];\n} | {\n currency: CurrencyCode;\n type: PricingType.SELECTION;\n selections: (Omit<SelectionPricingData, 'tiers'> & { tiers?: PriceTierAttributes[] })[];\n})>;\n\nexport type TieredPriceData = Prettify<{\n taxCategory: string;\n isTaxInclusive: boolean;\n currency: CurrencyCode;\n} & ({\n type?: PricingType.VOLUME;\n baseUnitPrice: PriceData;\n tiers: PriceTierData[];\n} | {\n type: PricingType.SELECTION;\n selections: SelectionPricingData[];\n})>;\n\nexport abstract class TieredPriceModel {\n protected type: PricingType;\n protected taxCategory: string;\n protected isTaxInclusive: boolean;\n\n /** \n * Factory method to instantiate the correct concrete TieredPriceModel implementation.\n */\n static create(data: TieredPriceAttributes): TieredPriceModel {\n if (data.type === PricingType.SELECTION) {\n return new SelectionTieredPriceModel(data);\n }\n return new VolumeTieredPriceModel(data);\n }\n\n constructor(data: TieredPriceAttributes) {\n if (!data.taxCategory) {\n throw new InvalidTaxCategoryError();\n }\n this.taxCategory = data.taxCategory;\n this.isTaxInclusive = data.isTaxInclusive ?? false;\n this.type = data.type ?? PricingType.VOLUME;\n }\n\n getType(): PricingType {\n return this.type;\n }\n\n getTaxCategory(): string {\n return this.taxCategory;\n }\n\n getIsTaxInclusive(): boolean {\n return this.isTaxInclusive;\n }\n\n abstract getBaseUnitPrice(selectionAttributes?: SelectionAttributes): PriceModel;\n abstract getDetails(): TieredPriceData;\n abstract getCurrency(): string;\n abstract getApplicableUnitPrice(quantity: number, selectionAttributes?: SelectionAttributes): PriceModel;\n abstract getMinQuantity(selectionAttributes?: SelectionAttributes): number;\n abstract getMaxDiscountPercent(selectionAttributes?: SelectionAttributes): number;\n}\n\nexport class VolumeTieredPriceModel extends TieredPriceModel {\n protected baseUnitPrice: PriceModel;\n protected tiers: PriceTier[];\n protected currency: CurrencyCode;\n\n constructor(data: Extract<TieredPriceAttributes, { type?: PricingType.VOLUME }>) {\n super(data);\n this.type = PricingType.VOLUME;\n \n if (!data.baseUnitPrice) {\n throw new InvalidTieredPriceError(\"Base unit price is required for volume pricing.\");\n }\n this.baseUnitPrice = new PriceModel(data.baseUnitPrice);\n this.currency = data.currency ?? this.baseUnitPrice.getCurrency();\n\n const tiers = (data.tiers ?? [])\n .map(tier => ({\n enabled: tier.enabled ?? true,\n minQuantity: tier.minQuantity,\n unitPrice: new PriceModel(tier.unitPrice),\n }))\n .sort((a, b) => a.minQuantity - b.minQuantity);\n\n const hasInvalidMinQuantity = tiers.some(t => t.minQuantity <= 0);\n if (hasInvalidMinQuantity) {\n throw new InvalidMinQuantityError();\n }\n\n const hasDifferentCurrency = this.baseUnitPrice.getCurrency() !== this.currency || tiers.some(\n t => t.unitPrice.getCurrency() !== this.currency\n );\n const hasIrregularPricing = tiers.some(\n (tier, index) =>\n index > 0 &&\n tier.unitPrice.compareTo(tiers[index - 1].unitPrice) > 0\n );\n const basePriceExceedsFirstTier = tiers[0]?.unitPrice.compareTo(this.baseUnitPrice) > 0;\n\n if (hasDifferentCurrency || hasIrregularPricing || basePriceExceedsFirstTier) {\n throw new InvalidTieredPriceError(\n \"Tiers must share the same currency and must not increase in unit price.\"\n );\n }\n\n this.tiers = tiers;\n }\n\n getBaseUnitPrice(): PriceModel {\n return this.baseUnitPrice;\n }\n\n getCurrency(): string {\n return this.baseUnitPrice.getCurrency();\n }\n\n getApplicableUnitPrice(quantity: number): PriceModel {\n if (quantity <= 0) {\n throw new InvalidQuantityError();\n }\n\n const enabledTiers = this.tiers.filter(t => t.enabled);\n for (let i = enabledTiers.length - 1; i >= 0; i--) {\n const tier = enabledTiers[i];\n if (quantity >= tier.minQuantity) {\n return tier.unitPrice;\n }\n }\n\n throw new NoApplicableTierError(quantity);\n }\n\n getMinQuantity(): number {\n const enabledTiers = this.tiers.filter(tier => tier.enabled);\n return enabledTiers[0]?.minQuantity ?? 1;\n }\n\n getMaxDiscountPercent(): number {\n const enabledTiers = this.tiers.filter(tier => tier.enabled);\n if (!enabledTiers.length) return 0;\n \n const minTierPrice = Math.min(...enabledTiers.map(t => t.unitPrice.getAmount()));\n const basePrice = this.baseUnitPrice.getAmount();\n \n const discount = ((basePrice - minTierPrice) / basePrice) * 100;\n return discount > 0 ? discount : 0;\n }\n\n getDetails(): TieredPriceData {\n return {\n type: this.type as PricingType.VOLUME,\n taxCategory: this.taxCategory,\n isTaxInclusive: this.isTaxInclusive,\n currency: this.currency,\n baseUnitPrice: this.baseUnitPrice.getDetails(),\n tiers: this.tiers.map(tier => ({\n enabled: tier.enabled,\n minQuantity: tier.minQuantity,\n unitPrice: tier.unitPrice.getDetails()\n }))\n };\n }\n}\n\nexport class SelectionTieredPriceModel extends TieredPriceModel {\n protected currency: CurrencyCode;\n protected selections: SelectionPricing[];\n\n constructor(data: Extract<TieredPriceAttributes, { type: PricingType.SELECTION }>) {\n super(data);\n this.type = PricingType.SELECTION;\n this.currency = data.currency;\n\n this.selections = (data.selections ?? []).map(selection => {\n if (!selection.baseUnitPrice) {\n throw new InvalidTieredPriceError(\"Base unit price is required for each selection.\");\n }\n const baseUnitPrice = new PriceModel(selection.baseUnitPrice);\n\n const tiers = (selection.tiers ?? [])\n .map(tier => ({\n enabled: tier.enabled ?? true,\n minQuantity: tier.minQuantity ?? 1,\n unitPrice: new PriceModel(tier.unitPrice),\n }))\n .sort((a, b) => a.minQuantity - b.minQuantity);\n\n const hasInvalidMinQuantity = tiers.some(t => t.minQuantity <= 0);\n if (hasInvalidMinQuantity) {\n throw new InvalidMinQuantityError();\n }\n\n const hasDifferentCurrency = baseUnitPrice.getCurrency() !== this.currency || tiers.some(\n t => t.unitPrice.getCurrency() !== this.currency\n );\n const hasIrregularPricing = tiers.some(\n (tier, index) =>\n index > 0 &&\n tier.unitPrice.compareTo(tiers[index - 1].unitPrice) > 0\n );\n const basePriceExceedsFirstTier = tiers[0]?.unitPrice.compareTo(baseUnitPrice) > 0;\n\n if (hasDifferentCurrency || hasIrregularPricing || basePriceExceedsFirstTier) {\n throw new InvalidTieredPriceError(\n \"Tiers must share the same currency and must not increase in unit price within the same selection.\"\n );\n }\n\n return {\n selectionAttributes: { ...selection.selectionAttributes },\n baseUnitPrice,\n tiers\n };\n });\n }\n\n protected findMatch(selectionAttributes: SelectionAttributes): SelectionPricing {\n const key = ProductModel.generateSelectionAttributesKey(selectionAttributes);\n const match = this.selections.find(\n s => ProductModel.generateSelectionAttributesKey(s.selectionAttributes) === key\n );\n if (!match) {\n throw new InvalidTieredPriceError(`No pricing configuration found for selection variant.`);\n }\n return match;\n }\n\n getBaseUnitPrice(selectionAttributes?: SelectionAttributes): PriceModel {\n if (!selectionAttributes) {\n throw new InvalidPricingTypeError(\"Selection attributes are required to get base unit price for selection pricing.\");\n }\n return this.findMatch(selectionAttributes).baseUnitPrice;\n }\n\n getCurrency(): string {\n return this.currency;\n }\n\n getApplicableUnitPrice(quantity: number, selectionAttributes?: SelectionAttributes): PriceModel {\n if (quantity <= 0) {\n throw new InvalidQuantityError();\n }\n if (!selectionAttributes) {\n throw new InvalidPricingTypeError(\"Selection attributes are required to get applicable unit price for selection pricing.\");\n }\n \n const match = this.findMatch(selectionAttributes);\n\n const enabledTiers = match.tiers.filter(t => t.enabled);\n for (let i = enabledTiers.length - 1; i >= 0; i--) {\n const tier = enabledTiers[i];\n if (quantity >= tier.minQuantity) {\n return tier.unitPrice;\n }\n }\n throw new NoApplicableTierError(quantity);\n }\n\n getMinQuantity(selectionAttributes?: SelectionAttributes): number {\n if (!selectionAttributes) {\n throw new InvalidPricingTypeError(\"Selection attributes are required to get min quantity for selection pricing.\");\n }\n const match = this.findMatch(selectionAttributes);\n const enabledTiers = match.tiers.filter(t => t.enabled);\n return enabledTiers[0]?.minQuantity ?? 1;\n }\n\n getMaxDiscountPercent(selectionAttributes?: SelectionAttributes): number {\n if (!selectionAttributes) {\n throw new InvalidPricingTypeError(\"Selection attributes are required to get max discount for selection pricing.\");\n }\n const match = this.findMatch(selectionAttributes);\n\n const enabledTiers = match.tiers.filter(t => t.enabled);\n if (!enabledTiers.length) return 0;\n\n const minTierPrice = Math.min(...enabledTiers.map(t => t.unitPrice.getAmount()));\n const basePrice = match.baseUnitPrice.getAmount();\n \n const discount = ((basePrice - minTierPrice) / basePrice) * 100;\n return discount > 0 ? discount : 0;\n }\n\n getDetails(): TieredPriceData {\n return {\n type: this.type as PricingType.SELECTION,\n taxCategory: this.taxCategory,\n isTaxInclusive: this.isTaxInclusive,\n currency: this.currency,\n selections: this.selections.map(selection => ({\n selectionAttributes: selection.selectionAttributes,\n baseUnitPrice: selection.baseUnitPrice.getDetails(),\n ...(selection.tiers.length > 0 ? {\n tiers: selection.tiers.map(tier => ({\n enabled: tier.enabled,\n minQuantity: tier.minQuantity,\n unitPrice: tier.unitPrice.getDetails()\n }))\n } : {})\n }))\n };\n }\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {v}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {v}from'./chunk-O6BLQQO7.mjs';var n=(t=>(t.THUMBNAIL="thumbnail",t.SMALL="small",t.MEDIUM="medium",t.LARGE="large",t.ORIGINAL="original",t))(n||{}),i=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw new v("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,s){if(s===void 0){if(e==="original")throw new v("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=s;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};export{n as a,i as b};//# sourceMappingURL=chunk-7RAIVZKB.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-7RAIVZKB.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/ImageInfo.ts"],"names":["ImageResolution","ImageInfoModel","data","InvalidImageSourceError","resolutionKey","altText","order","label","url"],"mappings":"qCAAO,IAAKA,OACVA,CAAA,CAAA,SAAA,CAAY,WACZA,CAAAA,CAAAA,CAAA,MAAQ,OACRA,CAAAA,CAAAA,CAAA,MAAS,CAAA,QAAA,CACTA,EAAA,KAA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,UAAA,EAA4B,CAC1B,OAAO,CACL,OAAS,CAAA,IAAA,CAAK,YACd,CAAA,GAAA,CAAK,KAAK,MAAO,EAAA,CACjB,KAAO,CAAA,IAAA,CAAK,UACZ,CAAA,KAAA,CAAO,KAAK,QAAS,EACvB,CACF,CACF","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../src/Classes/ImageInfo.ts"],"names":["ImageResolution","ImageInfoModel","data","InvalidImageSourceError","resolutionKey","altText","order","label","url"],"mappings":"qCAAO,IAAKA,OACVA,CAAA,CAAA,SAAA,CAAY,WACZA,CAAAA,CAAAA,CAAA,MAAQ,OACRA,CAAAA,CAAAA,CAAA,MAAS,CAAA,QAAA,CACTA,EAAA,KAAQ,CAAA,OAAA,CACRA,EAAA,QAAW,CAAA,UAAA,CALDA,OAAA,EAsBSC,CAAAA,CAAAA,CAAAA,CAArB,KAAoC,CACxB,QACA,GACA,CAAA,KAAA,CACA,KAMV,CAAA,WAAA,CAAYC,EAA0B,CAMpC,GALA,IAAK,CAAA,OAAA,CAAU,CAAE,GAAGA,CAAAA,CAAK,OAAQ,CACjC,CAAA,IAAA,CAAK,IAAMA,CAAK,CAAA,GAAA,CAChB,IAAK,CAAA,KAAA,CAAQA,EAAK,KAClB,CAAA,IAAA,CAAK,KAAQA,CAAAA,CAAAA,CAAK,MAEd,CAAC,IAAA,CAAK,OAAQ,CAAA,QAAA,CAChB,MAAM,IAAIC,CAAAA,CAAwB,oEAAoE,CAE1G,CAMA,YAAa,CACX,OAAO,CAAE,GAAG,KAAK,OAAQ,CAC3B,CAOA,SAAUC,CAAAA,CAAAA,CAAwC,CAChD,OAAO,IAAA,CAAK,OAAQA,CAAAA,CAAa,GAAK,IAAK,CAAA,OAAA,CAAQ,QACrD,CAKA,MAAA,EAA6B,CAC3B,OAAO,IAAA,CAAK,GACd,CAKA,UAA+B,CAC7B,OAAO,IAAK,CAAA,KACd,CAKA,QAA+B,EAAA,CAC7B,OAAO,IAAA,CAAK,KACd,CAMA,MAAA,CAAOC,EAAmC,CACxC,IAAA,CAAK,IAAMA,EAEb,CAMA,QAASC,CAAAA,CAAAA,CAAiC,CACxC,IAAK,CAAA,KAAA,CAAQA,EACf,CAMA,QAAA,CAASC,EAAiC,CACxC,IAAA,CAAK,KAAQA,CAAAA,EACf,CAOA,SAAUH,CAAAA,CAAAA,CAAgCI,EAA+B,CACvE,GAAIA,IAAQ,KAAW,CAAA,CAAA,CAErB,GAAIJ,CAAAA,GAAkB,WACpB,MAAM,IAAID,CAAwB,CAAA,4CAA4C,EAEhF,OAAO,IAAA,CAAK,OAAQC,CAAAA,CAAa,EACnC,CACE,KAAA,IAAA,CAAK,QAAQA,CAAa,CAAA,CAAII,EAElC,CAKA,UAAA,EAA4B,CAC1B,OAAO,CACL,OAAS,CAAA,IAAA,CAAK,YACd,CAAA,GAAA,CAAK,KAAK,MAAO,EAAA,CACjB,KAAO,CAAA,IAAA,CAAK,UACZ,CAAA,KAAA,CAAO,KAAK,QAAS,EACvB,CACF,CACF","file":"chunk-7RAIVZKB.mjs","sourcesContent":["export enum ImageResolution {\r\n THUMBNAIL = 'thumbnail',\r\n SMALL = 'small',\r\n MEDIUM = 'medium',\r\n LARGE = 'large',\r\n ORIGINAL = 'original',\r\n}\r\n\r\nimport { InvalidImageSourceError } from \"./Error\";\r\n\r\nexport type ImageInfoAttribute = {\r\n sources: { [key in ImageResolution]?: string } & { original: string };\r\n alt?: string;\r\n order?: number;\r\n label?: string;\r\n};\r\n\r\nexport type ImageInfoData = ImageInfoAttribute;\r\n\r\n/**\r\n * Represents and manages structured image data, including multiple resolutions.\r\n */\r\nexport default class ImageInfoModel {\r\n protected sources: { [key in ImageResolution]?: string } & { original: string };\r\n protected alt?: string;\r\n protected order?: number;\r\n protected label?: string;\r\n\r\n /**\r\n * Creates an instance of ImageInfoModel.\r\n * @param data - The initial image data.\r\n */\r\n constructor(data: ImageInfoAttribute) {\r\n this.sources = { ...data.sources };\r\n this.alt = data.alt;\r\n this.order = data.order;\r\n this.label = data.label;\r\n\r\n if (!this.sources.original) {\r\n throw new InvalidImageSourceError(\"ImageInfoModel cannot be created without an 'original' source URL.\");\r\n }\r\n }\r\n\r\n /**\r\n * Gets the sources object containing URLs for different resolutions.\r\n * Returns a copy to prevent external modification.\r\n */\r\n getSources() {\r\n return { ...this.sources };\r\n }\r\n\r\n /**\r\n * Gets the URL for a specific resolution key.\r\n * @param resolutionKey - The key of the desired resolution (e.g., 'thumbnail', 'medium').\r\n * @returns The URL string if the key doesn't exist, otherwise original image URL will be returned.\r\n */\r\n getSource(resolutionKey: ImageResolution): string {\r\n return this.sources[resolutionKey] || this.sources.original;\r\n }\r\n\r\n /**\r\n * Gets the alternative text for the image.\r\n */\r\n getAlt(): string | undefined {\r\n return this.alt;\r\n }\r\n\r\n /**\r\n * Gets the display order number for the image.\r\n */\r\n getOrder(): number | undefined {\r\n return this.order;\r\n }\r\n\r\n /**\r\n * Gets the display label or caption for the image.\r\n */\r\n getLabel(): string | undefined {\r\n return this.label;\r\n }\r\n\r\n /**\r\n * Sets the alternative text for the image.\r\n * @param altText - The new alt text.\r\n */\r\n setAlt(altText: string | undefined): void {\r\n this.alt = altText;\r\n // Potentially add logic here to trigger updates if needed\r\n }\r\n\r\n /**\r\n * Sets the display order for the image.\r\n * @param order - The new order number.\r\n */\r\n setOrder(order: number | undefined): void {\r\n this.order = order;\r\n }\r\n\r\n /**\r\n * Sets the display label for the image.\r\n * @param label - The new label text.\r\n */\r\n setLabel(label: string | undefined): void {\r\n this.label = label;\r\n }\r\n\r\n /**\r\n * Updates or adds a URL for a specific resolution.\r\n * @param resolutionKey - The key of the resolution to update/add.\r\n * @param url - The URL for the resolution. Set to undefined to remove.\r\n */\r\n setSource(resolutionKey: ImageResolution, url: string | undefined): void {\r\n if (url === undefined) {\r\n // Prevent deleting the 'original' key if it's required\r\n if (resolutionKey === 'original') {\r\n throw new InvalidImageSourceError(\"Cannot remove the 'original' image source.\");\r\n }\r\n delete this.sources[resolutionKey];\r\n } else {\r\n this.sources[resolutionKey] = url;\r\n }\r\n }\r\n\r\n /**\r\n * Returns a plain JavaScript object representation of the image info.\r\n */\r\n getDetails(): ImageInfoData {\r\n return {\r\n sources: this.getSources(),\r\n alt: this.getAlt(),\r\n order: this.getOrder(),\r\n label: this.getLabel(),\r\n };\r\n }\r\n}"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-UIQH5QIR.mjs';import {a}from'./chunk-UXZBULDS.mjs';var n=class extends a{taxRuleId;taxCategory;taxSystem;taxSubSystem;country;rate;minPrice;maxPrice;excludeMin;excludeMax;effectiveFrom;effectiveTo;constructor(e){super(e),this.taxRuleId=e.taxRuleId,this.taxSystem=e.taxSystem,this.taxSubSystem=e.taxSubSystem,this.taxCategory=e.taxCategory,this.country=e.country,this.rate=e.rate,this.minPrice=new a$1(e.minPrice),this.maxPrice=e.maxPrice?new a$1(e.maxPrice):void 0,this.excludeMin=e.excludeMin??!1,this.excludeMax=e.excludeMax??!1,this.effectiveFrom=new Date(e.effectiveFrom).toISOString(),this.effectiveTo=e.effectiveTo?new Date(e.effectiveTo).toISOString():void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getRate(){return this.rate}getMinPrice(){return this.minPrice}getMaxPrice(){return this.maxPrice}getExcludeMin(){return this.excludeMin}getExcludeMax(){return this.excludeMax}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),rate:this.getRate(),minPrice:this.getMinPrice().getDetails(),maxPrice:this.getMaxPrice()?.getDetails(),excludeMin:this.getExcludeMin(),excludeMax:this.getExcludeMax(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0,customFields:this.getAllCustomFields()}}appliesTo(e,o,t,i=new Date){let r=!t||(this.excludeMin?this.minPrice.compareTo(t)<0:this.minPrice.compareTo(t)<=0)&&(this.maxPrice?this.excludeMax?this.maxPrice.compareTo(t)>0:this.maxPrice.compareTo(t)>=0:!0);return this.taxCategory===e&&this.country===o&&r&&Date.parse(this.effectiveFrom)<=i.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=i.getTime():!0)}getApplicableTaxRate(e){return this.appliesTo(this.taxCategory,this.country,e)?this.rate:0}calculateTax(e){return this.appliesTo(this.taxCategory,this.country,e)?e.multiply(this.rate):e.zero()}static getTaxRateDisplayString(e,o,t){let i=o*100,r=i%1===0?i.toString():i.toFixed(2).replace(/\.?0+$/,"");return t?.percentageOnly?`${r}%`:e.getTaxSystem()==="GST"?`${e.getTaxSubSystem()} ${r}%`:`${e.getTaxSystem()} ${r}%`}};export{n as a};//# sourceMappingURL=chunk-EZ35IKUA.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-EZ35IKUA.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/TaxRule.ts"],"names":["TaxRuleModel","CustomFieldModel","data","PriceModel","taxCategory","country","price","at","isPriceInRange","taxRule","rate","formateOption","percentage","rateStr"],"mappings":"iFAsBaA,IAAAA,CAAAA,CAAN,cAA2BC,CAAiB,CACvC,UACA,WACA,CAAA,SAAA,CACA,aACA,OACA,CAAA,IAAA,CACA,SACA,QACA,CAAA,UAAA,CACA,WACA,aACA,CAAA,WAAA,CAEV,YAAYC,CAAyB,CAAA,CACnC,MAAMA,CAAI,CAAA,CACV,KAAK,SAAYA,CAAAA,CAAAA,CAAK,UACtB,IAAK,CAAA,SAAA,CAAYA,EAAK,SACtB,CAAA,IAAA,CAAK,aAAeA,CAAK,CAAA,YAAA,CACzB,KAAK,WAAcA,CAAAA,CA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,IAAA,CAEP,CACT,CAOA,YAAA,CAAaA,EAA+B,CAC1C,OAAI,KAAK,SAAU,CAAA,IAAA,CAAK,YAAa,IAAK,CAAA,OAAA,CAASA,CAAK,CAIjDA,CAAAA,CAAAA,CAAM,SAAS,IAAK,CAAA,IAAI,EAHtBA,CAAM,CAAA,IAAA,EAIjB,CAGA,OAAO,uBAAA,CAAwBG,EAAuBC,CAAcC,CAAAA,CAAAA,CAEzD,CACT,IAAMC,CAAAA,CAAaF,EAAO,GAEpBG,CAAAA,CAAAA,CAAUD,EAAa,CAAM,GAAA,CAAA,CAAIA,EAAW,QAAS,EAAA,CAAIA,EAAW,OAAQ,CAAA,CAAC,EAAE,OAAQ,CAAA,QAAA,CAAU,EAAE,CAEzG,CAAA,OAAID,GAAe,cACV,CAAA,CAAA,EAAGE,CAAO,CAGfJ,CAAAA,CAAAA,CAAAA,CAAAA,CAAQ,cAAmB,GAAA,KAAA,CACtB,GAAGA,CAAQ,CAAA,eAAA,EAAiB,CAAII,CAAAA,EAAAA,CAAO,IAEzC,CAAGJ,EAAAA,CAAAA,CAAQ,cAAc,CAAA,CAAA,EAAII,CAAO,CAAA,CAAA,CAC7C,CACF","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../src/Classes/TaxRule.ts"],"names":["TaxRuleModel","CustomFieldModel","data","PriceModel","taxCategory","country","price","at","isPriceInRange","taxRule","rate","formateOption","percentage","rateStr"],"mappings":"iFAsBaA,IAAAA,CAAAA,CAAN,cAA2BC,CAAiB,CACvC,UACA,WACA,CAAA,SAAA,CACA,aACA,OACA,CAAA,IAAA,CACA,SACA,QACA,CAAA,UAAA,CACA,WACA,aACA,CAAA,WAAA,CAEV,YAAYC,CAAyB,CAAA,CACnC,MAAMA,CAAI,CAAA,CACV,KAAK,SAAYA,CAAAA,CAAAA,CAAK,UACtB,IAAK,CAAA,SAAA,CAAYA,EAAK,SACtB,CAAA,IAAA,CAAK,aAAeA,CAAK,CAAA,YAAA,CACzB,KAAK,WAAcA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IAAK,CAAA,IAAA,CAEP,CACT,CAOA,YAAA,CAAaA,EAA+B,CAC1C,OAAI,KAAK,SAAU,CAAA,IAAA,CAAK,YAAa,IAAK,CAAA,OAAA,CAASA,CAAK,CAIjDA,CAAAA,CAAAA,CAAM,SAAS,IAAK,CAAA,IAAI,EAHtBA,CAAM,CAAA,IAAA,EAIjB,CAGA,OAAO,uBAAA,CAAwBG,EAAuBC,CAAcC,CAAAA,CAAAA,CAEzD,CACT,IAAMC,CAAAA,CAAaF,EAAO,GAEpBG,CAAAA,CAAAA,CAAUD,EAAa,CAAM,GAAA,CAAA,CAAIA,EAAW,QAAS,EAAA,CAAIA,EAAW,OAAQ,CAAA,CAAC,EAAE,OAAQ,CAAA,QAAA,CAAU,EAAE,CAEzG,CAAA,OAAID,GAAe,cACV,CAAA,CAAA,EAAGE,CAAO,CAGfJ,CAAAA,CAAAA,CAAAA,CAAAA,CAAQ,cAAmB,GAAA,KAAA,CACtB,GAAGA,CAAQ,CAAA,eAAA,EAAiB,CAAII,CAAAA,EAAAA,CAAO,IAEzC,CAAGJ,EAAAA,CAAAA,CAAQ,cAAc,CAAA,CAAA,EAAII,CAAO,CAAA,CAAA,CAC7C,CACF","file":"chunk-EZ35IKUA.mjs","sourcesContent":["import { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\nimport { CountryCode, ISODateTimeUTC, Prettify } from \"./Common\";\r\nimport { TaxSystem } from \"./Enum\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\n\r\nexport type TaxRuleAttributes = Prettify<CustomFieldAttributes & {\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 minPrice: PriceData;\r\n maxPrice?: PriceData;\r\n excludeMin?: boolean;\r\n excludeMax?: boolean;\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n}>;\r\n\r\nexport type TaxRuleData = TaxRuleAttributes;\r\n\r\nexport class TaxRuleModel extends CustomFieldModel {\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 rate: number;\r\n protected minPrice: PriceModel;\r\n protected maxPrice?: PriceModel;\r\n protected excludeMin: boolean;\r\n protected excludeMax: boolean;\r\n protected effectiveFrom: ISODateTimeUTC;\r\n protected effectiveTo?: ISODateTimeUTC;\r\n\r\n constructor(data: TaxRuleAttributes) {\r\n super(data);\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.rate = data.rate;\r\n this.minPrice = new PriceModel(data.minPrice);\r\n this.maxPrice = data.maxPrice ? new PriceModel(data.maxPrice) : undefined;\r\n this.excludeMin = data.excludeMin ?? false;\r\n this.excludeMax = data.excludeMax ?? false;\r\n this.effectiveFrom = new Date(data.effectiveFrom).toISOString();\r\n this.effectiveTo = data.effectiveTo ? new Date(data.effectiveTo).toISOString() : 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 getRate(): number {\r\n return this.rate;\r\n }\r\n\r\n getMinPrice(): PriceModel {\r\n return this.minPrice;\r\n }\r\n\r\n getMaxPrice(): PriceModel | undefined {\r\n return this.maxPrice;\r\n }\r\n\r\n getExcludeMin(): boolean {\r\n return this.excludeMin;\r\n }\r\n\r\n getExcludeMax(): boolean {\r\n return this.excludeMax;\r\n }\r\n\r\n getEffectiveFrom(): string {\r\n return this.effectiveFrom;\r\n }\r\n\r\n getEffectiveTo(): string | undefined {\r\n return this.effectiveTo;\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 rate: this.getRate(),\r\n minPrice: this.getMinPrice().getDetails(),\r\n maxPrice: this.getMaxPrice()?.getDetails(),\r\n excludeMin: this.getExcludeMin(),\r\n excludeMax: this.getExcludeMax(),\r\n effectiveFrom: this.effectiveFrom,\r\n effectiveTo: this.effectiveTo ? this.effectiveTo : undefined,\r\n customFields: this.getAllCustomFields(),\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 price - The price to check against the rule's price range (optional).\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, price?: PriceModel, at: Date = new Date()): boolean {\r\n const isPriceInRange = !price || (\r\n (this.excludeMin ? this.minPrice.compareTo(price) < 0 : this.minPrice.compareTo(price) <= 0) &&\r\n (this.maxPrice\r\n ? (this.excludeMax ? this.maxPrice.compareTo(price) > 0 : this.maxPrice.compareTo(price) >= 0)\r\n : true\r\n )\r\n );\r\n\r\n return (\r\n this.taxCategory === taxCategory &&\r\n this.country === country &&\r\n isPriceInRange &&\r\n Date.parse(this.effectiveFrom) <= at.getTime() &&\r\n (this.effectiveTo ? Date.parse(this.effectiveTo) >= at.getTime() : true)\r\n );\r\n }\r\n\r\n /**\r\n * Gets the applicable tax rate for a given price. Returns the tax rate if the rule applies, otherwise returns 0.\r\n * @param price - The price to check against the tax rule.\r\n * @returns The applicable tax rate as a decimal (e.g., 0.18 for 18%).\r\n */\r\n getApplicableTaxRate(price: PriceModel): number {\r\n if(this.appliesTo(this.taxCategory, this.country, price)) {\r\n return this.rate;\r\n }\r\n return 0;\r\n }\r\n\r\n /**\r\n * Calculates the tax amount for a given taxable amount.\r\n * @param price - The price used to determine the tax amount.\r\n * @returns The calculated tax amount as a PriceModel. Returns zero if the tax rule does not apply.\r\n */\r\n calculateTax(price: PriceModel): PriceModel {\r\n if(!this.appliesTo(this.taxCategory, this.country, price)) {\r\n return price.zero(); // Return zero tax if the rule does not apply\r\n }\r\n\r\n return price.multiply(this.rate);\r\n }\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 `${taxRule.getTaxSubSystem()} ${rateStr}%`;\r\n }\r\n return `${taxRule.getTaxSystem()} ${rateStr}%`;\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-UIQH5QIR.mjs';var I=(t,u)=>{let d=u.reduce((x,a)=>x+a.getApplicableTaxRate(t),0);if(d<=0)return t;let e=t.divide(1+d).round().getAmount(),o=t.getCurrency(),l=t.getAmount(),c=e,n=Number.POSITIVE_INFINITY,i=1e4;for(let x=0;x<i;x++){let a$1=new a({amount:e,currency:o}),b=u.sort((r,s)=>s.getApplicableTaxRate(a$1)-r.getApplicableTaxRate(a$1)).map(r=>a$1.multiply(r.getApplicableTaxRate(a$1)).round().getAmount()).reduce((r,s)=>r+s,0),m=e+b-l,T=u.reduce((r,s)=>r+s.getApplicableTaxRate(a$1),0);if(Math.abs(m)<Math.abs(n)&&(n=m,c=e),m===0)break;e=e-m/(1+T);}if(Math.abs(n)>a.getSmallestUnit(o))throw new Error("Failed to converge on a valid tax exclusive base.");return new a({amount:c,currency:o})},M=(t,u,d)=>{let e=t.zero(),o=[...d].sort((l,c)=>c.getApplicableTaxRate(t)-l.getApplicableTaxRate(t));return o.map((l,c)=>{let n=l.getApplicableTaxRate(t),i;return c===o.length-1?i=u.subtract(t).subtract(e):i=t.multiply(n).round(),e=e.add(i),{ruleId:l.getTaxRuleId(),taxAmount:i,rate:n}})};export{I as a,M as b};//# sourceMappingURL=chunk-MPKIC2MS.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-MPKIC2MS.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Utils/TaxMath.ts"],"names":["extractExclusiveBase","grossValue","applicableTaxRules","totalRate","sum","r","baseValue","currency","grossAmount","bestBaseValue","bestDiff","maxIterations","i","currentTaxableBase","PriceModel","taxSum","a","b","rule","v","diff","currentTotalRate","calculateDistributedTaxes","baseModel","grossModel","distributedTax","sortedRules","index","ruleRate","taxAmount"],"mappings":"qCAGaA,IAAAA,CAAAA,CAAuB,CAChCC,CAAAA,CACAC,CACa,GAAA,CACb,IAAMC,CAAAA,CAAYD,CAAmB,CAAA,MAAA,CAAO,CAACE,CAAAA,CAAKC,CAAMD,GAAAA,CAAAA,CAAMC,CAAE,CAAA,oBAAA,CAAqBJ,CAAU,CAAA,CAAG,CAAC,CAAA,CAEnG,GAAIE,CAAAA,EAAa,CACb,CAAA,OAAOF,CAGX,CAAA,IAAIK,CAAYL,CAAAA,CAAAA,CAAW,MAAO,CAAA,CAAA,CAAIE,CAAS,CAAA,CAAE,KAAM,EAAA,CAAE,SAAU,EAAA,CAC7DI,CAAWN,CAAAA,CAAAA,CAAW,WAAY,EAAA,CAClCO,CAAcP,CAAAA,CAAAA,CAAW,SAAU,EAAA,CAErCQ,CAAgBH,CAAAA,CAAAA,CAChBI,CAAW,CAAA,MAAA,CAAO,iBAChBC,CA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AA,CACxD,MAAM,IAAI,KAAM,CAAA,mDAAmD,CAGvE,CAAA,OAAO,IAAIO,CAAAA,CAAW,CAAE,MAAA,CAAQL,CAAe,CAAA,QAAA,CAAAF,CAAS,CAAC,CAC7D,CAAA,CAEae,CAA4B,CAAA,CACrCC,CACAC,CAAAA,CAAAA,CACAtB,CAC4D,GAAA,CAC5D,IAAIuB,CAAAA,CAAiBF,CAAU,CAAA,IAAA,EAEzBG,CAAAA,CAAAA,CAAc,CAAC,GAAGxB,CAAkB,CAAA,CAAE,IACxC,CAAA,CAACc,EAAGC,CAAMA,GAAAA,CAAAA,CAAE,oBAAqBM,CAAAA,CAAS,CAAIP,CAAAA,CAAAA,CAAE,oBAAqBO,CAAAA,CAAS,CAClF,CAAA,CAEA,OAAOG,CAAAA,CAAY,GAAI,CAAA,CAACR,CAAMS,CAAAA,CAAAA,GAAU,CACpC,IAAMC,CAAWV,CAAAA,CAAAA,CAAK,oBAAqBK,CAAAA,CAAS,CAChDM,CAAAA,CAAAA,CAEJ,OAAIF,CAAAA,GAAUD,CAAY,CAAA,MAAA,CAAS,CAC/BG,CAAAA,CAAAA,CAAYL,CAAW,CAAA,QAAA,CAASD,CAAS,CAAA,CAAE,QAASE,CAAAA,CAAc,CAElEI,CAAAA,CAAAA,CAAYN,CAAU,CAAA,QAAA,CAASK,CAAQ,CAAA,CAAE,KAAM,EAAA,CAGnDH,CAAiBA,CAAAA,CAAAA,CAAe,GAAII,CAAAA,CAAS,CAEtC,CAAA,CACH,MAAQX,CAAAA,CAAAA,CAAK,YAAa,EAAA,CAC1B,SAAAW,CAAAA,CAAAA,CACA,IAAMD,CAAAA,CACV,CACJ,CAAC,CACL","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../src/Utils/TaxMath.ts"],"names":["extractExclusiveBase","grossValue","applicableTaxRules","totalRate","sum","r","baseValue","currency","grossAmount","bestBaseValue","bestDiff","maxIterations","i","currentTaxableBase","PriceModel","taxSum","a","b","rule","v","diff","currentTotalRate","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M,CAAAA,CAAAA,CAEJ,OAAIF,CAAAA,GAAUD,CAAY,CAAA,MAAA,CAAS,CAC/BG,CAAAA,CAAAA,CAAYL,CAAW,CAAA,QAAA,CAASD,CAAS,CAAA,CAAE,QAASE,CAAAA,CAAc,CAElEI,CAAAA,CAAAA,CAAYN,CAAU,CAAA,QAAA,CAASK,CAAQ,CAAA,CAAE,KAAM,EAAA,CAGnDH,CAAiBA,CAAAA,CAAAA,CAAe,GAAII,CAAAA,CAAS,CAEtC,CAAA,CACH,MAAQX,CAAAA,CAAAA,CAAK,YAAa,EAAA,CAC1B,SAAAW,CAAAA,CAAAA,CACA,IAAMD,CAAAA,CACV,CACJ,CAAC,CACL","file":"chunk-MPKIC2MS.mjs","sourcesContent":["import PriceModel from \"../Classes/Price\";\nimport { TaxRuleModel } from \"../Classes/TaxRule\";\n\nexport const extractExclusiveBase = (\n grossValue: PriceModel,\n applicableTaxRules: TaxRuleModel[]\n): PriceModel => {\n const totalRate = applicableTaxRules.reduce((sum, r) => sum + r.getApplicableTaxRate(grossValue), 0);\n \n if (totalRate <= 0) {\n return grossValue;\n }\n \n let baseValue = grossValue.divide(1 + totalRate).round().getAmount();\n const currency = grossValue.getCurrency();\n const grossAmount = grossValue.getAmount();\n\n let bestBaseValue = baseValue;\n let bestDiff = Number.POSITIVE_INFINITY;\n const maxIterations = 10000;\n\n for (let i = 0; i < maxIterations; i++) {\n const currentTaxableBase = new PriceModel({ amount: baseValue, currency });\n const taxes = applicableTaxRules\n .sort((a, b) => b.getApplicableTaxRate(currentTaxableBase) - a.getApplicableTaxRate(currentTaxableBase))\n .map(rule => currentTaxableBase.multiply(rule.getApplicableTaxRate(currentTaxableBase)).round().getAmount());\n\n const taxSum = taxes.reduce((sum, v) => sum + v, 0);\n const diff = (baseValue + taxSum) - grossAmount;\n\n const currentTotalRate = applicableTaxRules.reduce((sum, r) => sum + r.getApplicableTaxRate(currentTaxableBase), 0);\n\n if (Math.abs(diff) < Math.abs(bestDiff)) {\n bestDiff = diff;\n bestBaseValue = baseValue;\n }\n\n if (diff === 0) break;\n baseValue = baseValue - diff / (1 + currentTotalRate);\n }\n\n if (Math.abs(bestDiff) > PriceModel.getSmallestUnit(currency)) {\n throw new Error(\"Failed to converge on a valid tax exclusive base.\");\n }\n\n return new PriceModel({ amount: bestBaseValue, currency });\n}\n\nexport const calculateDistributedTaxes = (\n baseModel: PriceModel,\n grossModel: PriceModel,\n applicableTaxRules: TaxRuleModel[]\n): { ruleId: string, taxAmount: PriceModel, rate: number }[] => {\n let distributedTax = baseModel.zero();\n \n const sortedRules = [...applicableTaxRules].sort(\n (a, b) => b.getApplicableTaxRate(baseModel) - a.getApplicableTaxRate(baseModel)\n );\n\n return sortedRules.map((rule, index) => {\n const ruleRate = rule.getApplicableTaxRate(baseModel);\n let taxAmount: PriceModel;\n \n if (index === sortedRules.length - 1) {\n taxAmount = grossModel.subtract(baseModel).subtract(distributedTax);\n } else {\n taxAmount = baseModel.multiply(ruleRate).round();\n }\n \n distributedTax = distributedTax.add(taxAmount);\n \n return {\n ruleId: rule.getTaxRuleId(),\n taxAmount,\n rate: ruleRate\n };\n });\n};\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=class extends Error{constructor(r){super(`Line item with ID '${r}' not found in the cart.`),this.name="LineItemNotFoundError";}},s=class extends Error{constructor(r){super(`Invalid line item state: ${r}`),this.name="InvalidLineItemStateError";}},n=class extends Error{constructor(r){super(`InvalidLineItemTaxRule: ${r}`),this.name="InvalidLineItemTaxRuleError";}},o=class extends Error{constructor(r){super(`Duplicate size found: ${r}`),this.name="DuplicateSizeError";}},
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
var e=class extends Error{constructor(r){super(`Line item with ID '${r}' not found in the cart.`),this.name="LineItemNotFoundError";}},s=class extends Error{constructor(r){super(`Invalid line item state: ${r}`),this.name="InvalidLineItemStateError";}},n=class extends Error{constructor(r){super(`InvalidLineItemTaxRule: ${r}`),this.name="InvalidLineItemTaxRuleError";}},o=class extends Error{constructor(r){super(`Duplicate size found: ${r}`),this.name="DuplicateSizeError";}},i=class extends Error{constructor(r){super(`Duplicate selection attribute found: ${r}`),this.name="DuplicateSelectionAttributeError";}},a=class extends Error{constructor(r="Product and selection attributes do not match."){super(`ProductMismatch: ${r}`),this.name="ProductMismatchError";}},c=class extends Error{constructor(r="Product is not active."){super(`ProductInactive: ${r}`),this.name="ProductInactiveError";}},u=class extends Error{constructor(r="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${r}`),this.name="SelectionAttributeParseError";}},l=class extends Error{constructor(r="Size does not match."){super(`SizeMismatch: ${r}`),this.name="SizeMismatchError";}},p=class extends Error{constructor(r="Pricing details not available for the product"){super(`NotFound: ${r}`),this.name="PricingNotFoundError";}},d=class extends Error{constructor(r="Tax rule category mismatch."){super(`InvalidTaxRule: ${r}`),this.name="InvalidTaxRuleError";}},x=class extends Error{constructor(r="Tax category is not valid."){super(`InvalidTaxCategory: ${r}`),this.name="InvalidTaxCategoryError";}},m=class extends Error{constructor(r="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${r}`),this.name="InvalidMinQuantityError";}},h=class extends Error{constructor(r){super(`InvalidTieredPrice: ${r}`),this.name="InvalidTieredPriceError";}},g=class extends Error{constructor(r="Quantity must be greater than zero."){super(`InvalidQuantity: ${r}`),this.name="InvalidQuantityError";}},E=class extends Error{constructor(r){super(`NoApplicableTier: Quantity ${r} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}},$=class extends Error{constructor(r="No applicable tax slab or multiple slabs found for the given unit price."){super(`TaxSlabNotFound: ${r}`),this.name="TaxSlabNotFoundError";}},v=class extends Error{constructor(r="Amount cannot be negative."){super(`InvalidAmount: ${r}`),this.name="InvalidPriceAmountError";}},I=class extends Error{constructor(r="Currency code is required."){super(`InvalidCurrency: ${r}`),this.name="InvalidCurrencyCodeError";}},b=class extends Error{constructor(r="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${r}`),this.name="CurrencyMismatchError";}},y=class extends Error{constructor(r){super(`InvalidArgument: ${r}`),this.name="InvalidArgumentError";}},f=class extends Error{constructor(r="Invalid image source configuration."){super(`InvalidImageSource: ${r}`),this.name="InvalidImageSourceError";}},T=class extends Error{constructor(r="Invalid charge data."){super(`InvalidCharge: ${r}`),this.name="InvalidChargeError";}},P=class extends Error{constructor(r="Invalid charge tax rule."){super(`InvalidChargeTaxRule: ${r}`),this.name="InvalidChargeTaxRuleError";}},C=class extends Error{constructor(r="Invalid pricing type."){super(`InvalidPricingType: ${r}`),this.name="InvalidPricingTypeError";}};export{e as a,s as b,n as c,o as d,i as e,a as f,c as g,u as h,l as i,p as j,d as k,x as l,m,h as n,g as o,E as p,$ as q,v as r,I as s,b as t,y as u,f as v,T as w,P as x,C as y};//# sourceMappingURL=chunk-O6BLQQO7.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-O6BLQQO7.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/Classes/Error.ts"],"names":["LineItemNotFoundError","lineItemId","InvalidLineItemStateError","state","InvalidLineItemTaxRuleError","message","DuplicateSizeError","size","DuplicateSelectionAttributeError","attribute","ProductMismatchError","ProductInactiveError","SelectionAttributeParseError","SizeMismatchError","PricingNotFoundError","InvalidTaxRuleError","InvalidTaxCategoryError","InvalidMinQuantityError","InvalidTieredPriceError","InvalidQuantityError","NoApplicableTierError","quantity","TaxSlabNotFoundError","InvalidPriceAmountError","InvalidCurrencyCodeError","CurrencyMismatchError","InvalidArgumentError","InvalidImageSourceError","InvalidChargeError","InvalidChargeTaxRuleError","InvalidPricingTypeError"],"mappings":"AAAaA,IAAAA,CAAAA,CAAN,cAAoC,KAAM,CAC7C,YAAYC,CAAoB,CAAA,CAC5B,KAAM,CAAA,CAAA,mBAAA,EAAsBA,CAAU,CAAA,wBAAA,CAA0B,EAChE,IAAK,CAAA,IAAA,CAAO,wBAChB,CACJ,CAEaC,CAAAA,CAAAA,CAAN,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CAAM,uBAAuBA,CAAO,CAAA,CAAE,CACtC,CAAA,IAAA,CAAK,IAAO,CAAA,0BAChB,CACJ,CAEauB,CAAAA,CAAAA,CAAN,cAAiC,KAAM,CAC1C,WAAA,CAAYvB,EAAkB,sBAAwB,CAAA,CAClD,KAAM,CAAA,CAAA,eAAA,EAAkBA,CAAO,CAAA,CAAE,EACjC,IAAK,CAAA,IAAA,CAAO,qBAChB,CACJ,CAEawB,CAAAA,CAAAA,CAAN,cAAwC,KAAM,CACjD,WAAYxB,CAAAA,CAAAA,CAAkB,0BAA4B,CAAA,CACtD,MAAM,CAAyBA,sBAAAA,EAAAA,CAAO,CAAE,CAAA,CAAA,CACxC,IAAK,CAAA,IAAA,CAAO,4BAChB,CACJ,CAAA,CAEayB,CAAN,CAAA,cAAsC,KAAM,CAC/C,YAAYzB,CAAkB,CAAA,uBAAA,CAAyB,CACnD,KAAA,CAAM,CAAuBA,oBAAAA,EAAAA,CAAO,EAAE,CACtC,CAAA,IAAA,CAAK,IAAO,CAAA,0BAChB,CACJ","file":"chunk-O6BLQQO7.mjs","sourcesContent":["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 InvalidLineItemTaxRuleError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidLineItemTaxRule: ${message}`);\r\n this.name = 'InvalidLineItemTaxRuleError';\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\r\nexport class InvalidChargeTaxRuleError extends Error {\r\n constructor(message: string = \"Invalid charge tax rule.\") {\r\n super(`InvalidChargeTaxRule: ${message}`);\r\n this.name = 'InvalidChargeTaxRuleError';\r\n }\r\n}\r\n\r\nexport class InvalidPricingTypeError extends Error {\r\n constructor(message: string = \"Invalid pricing type.\") {\r\n super(`InvalidPricingType: ${message}`);\r\n this.name = 'InvalidPricingTypeError';\r\n }\r\n}\r\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a as a$4,b}from'./chunk-MPKIC2MS.mjs';import {a as a$2}from'./chunk-EZ35IKUA.mjs';import {a as a$3}from'./chunk-7B5TAYNA.mjs';import {a as a$1}from'./chunk-UIQH5QIR.mjs';import {e}from'./chunk-PL5HGCWN.mjs';import {w,k,x}from'./chunk-O6BLQQO7.mjs';import {a}from'./chunk-UXZBULDS.mjs';var A=class extends a{id;name;type;category;impact;pricing;lineItemId;total;constructor(t){if(super(t),this.id=t.id,this.name=t.name,this.type=t.type,this.category=t.category,this.impact=t.impact,this.lineItemId=t.lineItemId,this.pricing={baseChargeAmount:new a$1(t.pricing.baseChargeAmount),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(e=>new a$2(e))},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new w("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={chargeAmount:new a$1(t.total.chargeAmount),discountTotal:new a$1(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([e,a])=>[e,new a$1(a)])),netChargeAmount:new a$1(t.total.netChargeAmount),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([e,a])=>[e,{rate:a.rate,taxableAmount:new a$1(a.taxableAmount),taxAmount:new a$1(a.taxAmount),system:a.system,subSystem:a.subSystem}])),taxTotal:new a$1(t.total.taxTotal),grandTotal:new a$1(t.total.grandTotal)};}getId(){return this.id}getName(t){return t?a$3.deepClone(this.name[t]??this.name[e[t]]??this.name.en):a$3.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getPricing(){return {baseChargeAmount:this.pricing.baseChargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {chargeAmount:this.total.chargeAmount,discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},netChargeAmount:this.total.netChargeAmount,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableAmount:e.taxableAmount,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(t){if(this.type==="ADJUSTMENT"&&t.length>0)throw new w("Adjustment charges cannot apply tax rules.");t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new k}),this.validateTaxRules(t),this.pricing.applicableTaxRule=t,this.calculateTotals();}validateTaxRules(t){if(this.impact==="SUBTRACT"&&t.some(a=>a.getRate()>0))throw new x("Subtractive charges cannot have positive tax rates.");let e=new Set;for(let a=0;a<t.length;a++){let r=t[a].getTaxRuleId();if(e.has(r))throw new x("Duplicate tax rule ID found: "+r);e.add(r);for(let g=a+1;g<t.length;g++){let u=t[a],l=t[g],m=u.getMinPrice(),i=u.getMaxPrice(),p=u.getExcludeMin(),o=u.getExcludeMax(),n=l.getMinPrice(),c=l.getMaxPrice(),T=l.getExcludeMin(),b=l.getExcludeMax(),D=(()=>{if(!i)return !1;let d=i.compareTo(n);return d<0||d===0&&(o||T)})(),B=(()=>{if(!c)return !1;let d=c.compareTo(m);return d<0||d===0&&(b||p)})();if(!(D||B)&&!(m.compareTo(n)===0&&p===T&&o===b&&(!i&&!c||i&&c&&i.compareTo(c)===0)))throw new x(`Overlapping rules found: [${u.getTaxRuleId()}: ${p?"(":"["}${m.getAmount()}-${i?.getAmount()??"Infinity"}${o?")":"]"}] and [${l.getTaxRuleId()}: ${T?"(":"["}${n.getAmount()}-${c?.getAmount()??"Infinity"}${b?")":"]"}]`)}}}updateDiscounts(t){let e={};t.forEach(a=>{e[a.coupon.getCode()]=a.amount;}),this.total.discountBreakdown=e,this.calculateTotals();}calculateTotals(){let t=this.pricing.baseChargeAmount.zero(),e=this.pricing.baseChargeAmount,a=Object.values(this.total.discountBreakdown).reduce((o,n)=>o.add(n),t),r=e.subtract(a),g={};if(this.pricing.applicableTaxRule.reduce((o,n)=>o+n.getApplicableTaxRate(r),0)<=0){this.total={chargeAmount:e,discountTotal:a,discountBreakdown:this.total.discountBreakdown,netChargeAmount:r,taxTotal:t,taxBreakdown:{},grandTotal:r};return}let l=a$4(r,this.pricing.applicableTaxRule),m=b(l,r,this.pricing.applicableTaxRule),i=t;m.forEach(o=>{let n=this.pricing.applicableTaxRule.find(c=>c.getTaxRuleId()===o.ruleId);g[o.ruleId]={rate:o.rate,taxableAmount:l,taxAmount:o.taxAmount,system:n.getTaxSystem(),subSystem:n.getTaxSubSystem()},i=i.add(o.taxAmount);});let p=r;this.total={chargeAmount:e,discountTotal:a,discountBreakdown:this.total.discountBreakdown,netChargeAmount:r,taxBreakdown:g,taxTotal:i,grandTotal:p};}getDetails(){return {id:this.id,name:a$3.deepClone(this.name),type:this.type,category:this.category,pricing:{baseChargeAmount:this.pricing.baseChargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(e=>e.getDetails())},impact:this.impact,lineItemId:this.lineItemId,total:{chargeAmount:this.total.chargeAmount.getDetails(),discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([e,a])=>[e,a.getDetails()])),netChargeAmount:this.total.netChargeAmount.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,a])=>[e,{rate:a.rate,taxableAmount:a.taxableAmount.getDetails(),taxAmount:a.taxAmount.getDetails(),system:a.system,subSystem:a.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};export{A as a};//# sourceMappingURL=chunk-PNTRHKEH.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-PNTRHKEH.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/Classes/Charge.ts"],"names":["ChargeModel","CustomFieldModel","data","PriceModel","r","TaxRuleModel","InvalidChargeError","discountId","discount","taxRuleId","taxBreakdown","locale","Utils_default","LocaleLanguageMap","key","value","taxRules","taxRule","InvalidTaxRuleError","InvalidChargeTaxRuleError","uniqueTaxRule","i","currentTaxRuleId","j","r1","r2","r1Min","r1Max","r1ExcludeMin","r1ExcludeMax","r2Min","r2Max","r2ExcludeMin","r2ExcludeMax","r1EndsBeforeR2Starts","compare","r2EndsBeforeR1Starts","appliedDiscounts","chargeDiscounts","zero","baseChargeAmount","totalDiscount","sum","s","netChargeAmount","taxableBase","extractExclusiveBase","distributedTaxes","calculateDistributedTaxes","taxTotal","dt","grandTotal","k","v"],"mappings":"qSA6FqBA,IAAAA,CAAAA,CAArB,cAAyCC,CAAiB,CAC/C,EAAA,CACA,IACA,CAAA,IAAA,CACA,QACA,CAAA,MAAA,CACA,OACA,CAAA,UAAA,CACA,KAEV,CAAA,WAAA,CAAYC,EAAwB,CAenC,GAdA,KAAMA,CAAAA,CAAI,CACV,CAAA,IAAA,CAAK,EAAKA,CAAAA,CAAAA,CAAK,EACf,CAAA,IAAA,CAAK,IAAOA,CAAAA,CAAAA,CAAK,IACjB,CAAA,IAAA,CAAK,KAAOA,CAAK,CAAA,IAAA,CACjB,IAAK,CAAA,QAAA,CAAWA,CAAK,CAAA,QAAA,CACrB,IAAK,CAAA,MAAA,CAASA,CAAK,CAAA,MAAA,CACnB,IAAK,CAAA,UAAA,CAAaA,CAAK,CAAA,UAAA,CACvB,KAAK,OAAU,CAAA,CACd,gBAAkB,CAAA,IAAIC,GAAWD,CAAAA,CAAAA,CAAK,OAAQ,CAAA,gB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ustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\nimport Utils from \"../Utils\";\r\nimport { LocaleCode, LocalizedString } from \"./Common\";\r\nimport { ChargeImpact, ChargeType, LocaleLanguageMap, TaxSystem } from \"./Enum\";\r\nimport { InvalidChargeTaxRuleError, InvalidChargeError, InvalidTaxRuleError } from \"./Error\";\r\nimport { extractExclusiveBase, calculateDistributedTaxes } from \"../Utils/TaxMath\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport { TaxRuleData, TaxRuleModel } from \"./TaxRule\";\r\nimport CouponModel from \"./Coupon\";\r\n\r\nexport type ChargePricing = {\r\n /** Tax-inclusive original charge amount before any discounts. Always non-negative. */\r\n baseChargeAmount: PriceData;\r\n /** Tax category of the charge. */\r\n taxCategory: string;\r\n /** Tax rules applicable to the charge. */\r\n applicableTaxRule: TaxRuleData[];\r\n};\r\n\r\nexport type ChargePricingModel = {\r\n /** Tax-inclusive original charge amount before any discounts. Always non-negative. */\r\n baseChargeAmount: PriceModel;\r\n /** Tax category of the charge. */\r\n taxCategory: string;\r\n /** Tax rules applicable to the charge. */\r\n applicableTaxRule: TaxRuleModel[];\r\n};\r\n\r\nexport type ChargeTaxBreakdown = {\r\n /** Tax rate: e.g., 0.09 for 9% */\r\n rate: number;\r\n /** Reverse-calculated pre-tax base from the netChargeAmount (post-discount) */\r\n taxableAmount: PriceData;\r\n /** Tax portion for this rule (netChargeAmount - taxableAmount) */\r\n taxAmount: PriceData;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type ChargeTaxBreakdownModel = {\r\n rate: number;\r\n taxableAmount: PriceModel;\r\n taxAmount: PriceModel;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type ChargeTotals = {\r\n /** Tax-inclusive original charge amount before discounts (copied from pricing) */\r\n chargeAmount: PriceData;\r\n /** Coupon code -> discount amount mapping */\r\n discountBreakdown: Record<string, PriceData>;\r\n /** Sum of all discounts */\r\n discountTotal: PriceData;\r\n /** chargeAmount - totalDiscount → final tax-inclusive payable amount after discounts */\r\n netChargeAmount: PriceData;\r\n /** Sum of all taxAmount values */\r\n taxTotal: PriceData;\r\n /** Tax breakdown per rule/category (reverse-calculated from netChargeAmount) */\r\n taxBreakdown: Record<string, ChargeTaxBreakdown>;\r\n /** Final payable/contribution amount. Equals netChargeAmount (tax-inclusive after discounts). */\r\n grandTotal: PriceData;\r\n};\r\n\r\nexport type ChargeTotalsModel = {\r\n chargeAmount: PriceModel;\r\n discountTotal: PriceModel;\r\n discountBreakdown: Record<string, PriceModel>;\r\n netChargeAmount: PriceModel;\r\n taxTotal: PriceModel;\r\n taxBreakdown: Record<string, ChargeTaxBreakdownModel>;\r\n grandTotal: PriceModel; // Equals netChargeAmount\r\n};\r\n\r\nexport type ChargeAttributes = CustomFieldAttributes & {\r\n id: string;\r\n name: LocalizedString;\r\n type: ChargeType;\r\n category: string;\r\n impact: ChargeImpact; // ADD or SUBTRACT\r\n pricing: ChargePricing;\r\n lineItemId?: string;\r\n total: ChargeTotals;\r\n};\r\n\r\nexport type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId'> & {\r\n\tlineItemId?: string;\r\n};\r\n\r\n/**\r\n * Represents an additional charge (or discount if amount is negative) in a shopping container.\r\n * Supports its own tax rules.\r\n */\r\nexport default class ChargeModel extends CustomFieldModel {\r\n\tprotected id: string;\r\n\tprotected name: LocalizedString;\r\n\tprotected type: ChargeType;\r\n\tprotected category: string;\r\n\tprotected impact: ChargeImpact;\r\n\tprotected pricing: ChargePricingModel;\r\n\tprotected lineItemId?: string;\r\n\tprotected total: ChargeTotalsModel;\r\n\r\n\tconstructor(data: ChargeAttributes) {\r\n\t\tsuper(data);\r\n\t\tthis.id = data.id;\r\n\t\tthis.name = data.name;\r\n\t\tthis.type = data.type;\r\n\t\tthis.category = data.category;\r\n\t\tthis.impact = data.impact;\r\n\t\tthis.lineItemId = data.lineItemId;\r\n\t\tthis.pricing = {\r\n\t\t\tbaseChargeAmount: new PriceModel(data.pricing.baseChargeAmount),\r\n\t\t\ttaxCategory: data.pricing.taxCategory,\r\n\t\t\tapplicableTaxRule: data.pricing.applicableTaxRule.map(r => new TaxRuleModel(r))\r\n\t\t};\r\n\r\n\t\tthis.validateTaxRules(this.pricing.applicableTaxRule);\r\n\t\tif(this.impact === ChargeImpact.SUBTRACT && this.type !== ChargeType.ADJUSTMENT) {\r\n\t\t\tthrow new InvalidChargeError('SUBTRACT impact is only allowed for ADJUSTMENT charge');\r\n\t\t}\r\n\r\n\t\tthis.total = {\r\n\t\t\tchargeAmount: new PriceModel(data.total.chargeAmount),\r\n\t\t\tdiscountTotal: new PriceModel(data.total.discountTotal),\r\n\t\t\tdiscountBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(data.total.discountBreakdown).map(([discountId, discount]) => [\r\n\t\t\t\t\tdiscountId,\r\n\t\t\t\t\tnew PriceModel(discount)\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\tnetChargeAmount: new PriceModel(data.total.netChargeAmount),\r\n\t\t\ttaxBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(data.total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n\t\t\t\t\ttaxRuleId,\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\trate: taxBreakdown.rate,\r\n\t\t\t\t\t\ttaxableAmount: new PriceModel(taxBreakdown.taxableAmount),\r\n\t\t\t\t\t\ttaxAmount: new PriceModel(taxBreakdown.taxAmount),\r\n\t\t\t\t\t\tsystem: taxBreakdown.system,\r\n\t\t\t\t\t\tsubSystem: taxBreakdown.subSystem\r\n\t\t\t\t\t}\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\ttaxTotal: new PriceModel(data.total.taxTotal),\r\n\t\t\tgrandTotal: new PriceModel(data.total.grandTotal),\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the unique identifier of the charge.\r\n\t * @returns \r\n\t */\r\n\tpublic getId(): string { return this.id; }\r\n\r\n\r\n\t/**\r\n\t * Gets the full localized product name object.\r\n\t * @returns A copy of the LocalizedString object for the name.\r\n\t */\r\n\tgetName(): LocalizedString\r\n\t/**\r\n\t * Gets the product name for a specific locale, falling back to English ('en').\r\n\t * @param locale - The desired locale code.\r\n\t * @returns The name string for the specified locale.\r\n\t */\r\n\tgetName(locale: LocaleCode): string\r\n\tgetName(locale?: LocaleCode): LocalizedString | string {\r\n\t\tif (locale) {\r\n\t\t\treturn Utils.deepClone(this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en);\r\n\t\t} else {\r\n\t\t\treturn Utils.deepClone(this.name);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the charge category.\r\n\t * @returns The category string.\r\n\t */\r\n\tpublic getCategory(): string { return this.category; }\r\n\r\n\t/**\r\n\t * Gets the charge type.\r\n\t * @returns The charge type enum value.\r\n\t */\r\n\tpublic getType(): ChargeType { return this.type; }\r\n\t/**\r\n\t * Gets the charge impact (add or subtract).\r\n\t * @returns The charge impact.\r\n\t */\r\n\tpublic getImpact(): ChargeImpact { return this.impact; }\r\n\r\n\t/**\r\n\t * Gets the related line item id, if any.\r\n\t * @returns The line item id or undefined.\r\n\t */\r\n\tpublic getLineItemId(): string | undefined { return this.lineItemId; }\r\n\r\n\t/**\r\n\t * Gets the pricing details (models) for this charge.\r\n\t * @returns Pricing details including price, tax category, and tax rules.\r\n\t */\r\n\tpublic getPricing(): ChargePricingModel {\r\n\t\treturn {\r\n\t\t\tbaseChargeAmount: this.pricing.baseChargeAmount,\r\n\t\t\ttaxCategory: this.pricing.taxCategory,\r\n\t\t\tapplicableTaxRule: [...this.pricing.applicableTaxRule]\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the computed totals for this charge.\r\n\t * @returns Totals including discounts, taxes, and grand total.\r\n\t */\r\n\tpublic getTotal(): ChargeTotalsModel {\r\n\t\treturn {\r\n\t\t\tchargeAmount: this.total.chargeAmount,\r\n\t\t\tdiscountTotal: this.total.discountTotal,\r\n\t\t\tdiscountBreakdown: { ...this.total.discountBreakdown },\r\n\t\t\tnetChargeAmount: this.total.netChargeAmount,\r\n\t\t\ttaxTotal: this.total.taxTotal,\r\n\t\t\ttaxBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(this.total.taxBreakdown).map(([key, value]) => [\r\n\t\t\t\t\tkey,\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\trate: value.rate,\r\n\t\t\t\t\t\ttaxableAmount: value.taxableAmount,\r\n\t\t\t\t\t\ttaxAmount: value.taxAmount,\r\n\t\t\t\t\t\tsystem: value.system,\r\n\t\t\t\t\t\tsubSystem: value.subSystem\r\n\t\t\t\t\t}\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\tgrandTotal: this.total.grandTotal,\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the applicable tax rules for this charge.\r\n\t * @returns A list of tax rules.\r\n\t */\r\n\tpublic getApplicableTaxRules(): TaxRuleModel[] {\r\n\t\treturn [...this.pricing.applicableTaxRule];\r\n\t}\r\n\r\n\t/**\r\n\t * Updates the tax rule for this line item and recalculates totals.\r\n\t * @param taxRule - The new tax rule to apply.\r\n\t * @throws {Error} If the tax rule category does not match the item's tax category.\r\n\t */\r\n\tpublic updateTax(taxRules: TaxRuleModel[]): void {\r\n\t\tif (this.type === ChargeType.ADJUSTMENT && taxRules.length > 0) {\r\n\t\t\tthrow new InvalidChargeError(\"Adjustment charges cannot apply tax rules.\");\r\n\t\t}\r\n\t\ttaxRules.forEach(taxRule => {\r\n\t\t\tif (!taxRule.appliesTo(this.pricing.taxCategory, taxRule.getCountry())) {\r\n\t\t\t\tthrow new InvalidTaxRuleError();\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\t// Remove the old taxableUnitPrice calculation - no longer needed\r\n\t\tthis.validateTaxRules(taxRules);\r\n\t\tthis.pricing.applicableTaxRule = taxRules;\r\n\t\tthis.calculateTotals();\r\n\t}\r\n\r\n\t/**\r\n\t * Validates that there are no overlapping price brackets for any tax rules within the charge.\r\n\t * @param taxRules - The list of tax rules to validate.\r\n\t * @throws {InvalidChargeTaxRuleError} If any rules have positive tax rates with SUBTRACT impact or if duplicate rule IDs are found.\r\n\t * @throws {InvalidChargeTaxRuleError} Duplicate tax rule IDs will results in error.\r\n\t * @throws {CoincidingTaxBracketError} If any overlapping rules are found.\r\n\t */\r\n\tprivate validateTaxRules(taxRules: TaxRuleModel[]): void {\r\n\t\tif(this.impact === ChargeImpact.SUBTRACT) {\r\n\t\t\tif(taxRules.some(taxRule => taxRule.getRate() > 0)) {\r\n\t\t\t\tthrow new InvalidChargeTaxRuleError(\"Subtractive charges cannot have positive tax rates.\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst uniqueTaxRule = new Set();\r\n\t\tfor (let i = 0; i < taxRules.length; i++) {\r\n\t\t\tconst currentTaxRuleId = taxRules[i].getTaxRuleId();\r\n\t\t\tif(uniqueTaxRule.has(currentTaxRuleId)){\r\n\t\t\t\tthrow new InvalidChargeTaxRuleError(\"Duplicate tax rule ID found: \" + currentTaxRuleId);\r\n\t\t\t} else {\r\n\t\t\t\tuniqueTaxRule.add(currentTaxRuleId);\r\n\t\t\t}\r\n\r\n\t\t\tfor (let j = i + 1; j < taxRules.length; j++) {\r\n\t\t\t\tconst r1 = taxRules[i];\r\n\t\t\t\tconst r2 = taxRules[j];\r\n\r\n\t\t\t\tconst r1Min = r1.getMinPrice();\r\n\t\t\t\tconst r1Max = r1.getMaxPrice();\r\n\t\t\t\tconst r1ExcludeMin = r1.getExcludeMin();\r\n\t\t\t\tconst r1ExcludeMax = r1.getExcludeMax();\r\n\t\t\t\tconst r2Min = r2.getMinPrice();\r\n\t\t\t\tconst r2Max = r2.getMaxPrice();\r\n\t\t\t\tconst r2ExcludeMin = r2.getExcludeMin();\r\n\t\t\t\tconst r2ExcludeMax = r2.getExcludeMax();\r\n\r\n\t\t\t\t// Two ranges are disjoint if one ends strictly before the other starts.\r\n\t\t\t\t// If they only touch at one point, disjoint only when either side excludes that point.\r\n\t\t\t\tconst r1EndsBeforeR2Starts = (() => {\r\n\t\t\t\t\tif (!r1Max) return false;\r\n\t\t\t\t\tconst compare = r1Max.compareTo(r2Min);\r\n\t\t\t\t\treturn compare < 0 || (compare === 0 && (r1ExcludeMax || r2ExcludeMin));\r\n\t\t\t\t})();\r\n\t\t\t\tconst r2EndsBeforeR1Starts = (() => {\r\n\t\t\t\t\tif (!r2Max) return false;\r\n\t\t\t\t\tconst compare = r2Max.compareTo(r1Min);\r\n\t\t\t\t\treturn compare < 0 || (compare === 0 && (r2ExcludeMax || r1ExcludeMin));\r\n\t\t\t\t})();\r\n\t\t\t\tconst overlap = !(r1EndsBeforeR2Starts || r2EndsBeforeR1Starts);\r\n\r\n\t\t\t\tif (overlap) {\r\n\t\t\t\t\t// Exception: Allow overlapping rules if they have the exact same price bracket (slab)\r\n\t\t\t\t\tconst sameSlab = r1Min.compareTo(r2Min) === 0 &&\r\n\t\t\t\t\t\tr1ExcludeMin === r2ExcludeMin &&\r\n\t\t\t\t\t\tr1ExcludeMax === r2ExcludeMax &&\r\n\t\t\t\t\t\t((!r1Max && !r2Max) || (r1Max && r2Max && r1Max.compareTo(r2Max) === 0));\r\n\r\n\t\t\t\t\tif (!sameSlab) {\r\n\t\t\t\t\t\tthrow new InvalidChargeTaxRuleError(\r\n\t\t\t\t\t\t\t`Overlapping rules found: [${r1.getTaxRuleId()}: ${r1ExcludeMin ? \"(\" : \"[\"}${r1Min.getAmount()}-${r1Max?.getAmount() ?? \"Infinity\"}${r1ExcludeMax ? \")\" : \"]\"}] and [${r2.getTaxRuleId()}: ${r2ExcludeMin ? \"(\" : \"[\"}${r2Min.getAmount()}-${r2Max?.getAmount() ?? \"Infinity\"}${r2ExcludeMax ? \")\" : \"]\"}]`\r\n\t\t\t\t\t\t);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Updates the discounts applied to this line item and recalculates totals.\r\n\t * @param appliedDiscounts - List of coupons and their allocated discount amounts.\r\n\t*/\r\n\tpublic updateDiscounts(appliedDiscounts: { coupon: CouponModel, amount: PriceModel }[]): void {\r\n\t\tlet chargeDiscounts = {} as Record<string, PriceModel>;\r\n\t\tappliedDiscounts.forEach(discount => {\r\n\t\t\tchargeDiscounts[discount.coupon.getCode()] = discount.amount;\r\n\t\t});\r\n\r\n\t\tthis.total.discountBreakdown = chargeDiscounts;\r\n\t\tthis.calculateTotals();\r\n\t}\r\n\r\n\t/**\r\n\t * Recalculates totals for this charge based on pricing and discounts.\r\n\t */\r\n\tpublic calculateTotals(): void {\r\n\t\tconst zero = this.pricing.baseChargeAmount.zero();\r\n\t\tconst baseChargeAmount = this.pricing.baseChargeAmount;\r\n\r\n\t\tconst totalDiscount = Object.values(this.total.discountBreakdown).reduce((sum, s) => sum.add(s), zero);\r\n\t\tconst netChargeAmount = baseChargeAmount.subtract(totalDiscount);\r\n\r\n\t\tconst taxBreakdown: Record<string, ChargeTaxBreakdownModel> = {};\r\n\r\n\t\t// 1. Calculate total rate for inclusive back-calculation\r\n\t\tconst totalRate = this.pricing.applicableTaxRule.reduce((sum, r) => sum + r.getApplicableTaxRate(netChargeAmount), 0);\r\n\r\n\t\tif (totalRate <= 0) {\r\n\t\t\tthis.total = {\r\n\t\t\t\tchargeAmount: baseChargeAmount,\r\n\t\t\t\tdiscountTotal: totalDiscount,\r\n\t\t\t\tdiscountBreakdown: this.total.discountBreakdown,\r\n\t\t\t\tnetChargeAmount: netChargeAmount,\r\n\t\t\t\ttaxTotal: zero,\r\n\t\t\t\ttaxBreakdown: {},\r\n\t\t\t\tgrandTotal: netChargeAmount\r\n\t\t\t};\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// 2. Extract exclusive base using TaxMath utility\r\n\t\tconst taxableBase = extractExclusiveBase(netChargeAmount, this.pricing.applicableTaxRule);\r\n\r\n\t\t// 3. Compute tax amounts per rule based on final taxable base\r\n\t\tconst distributedTaxes = calculateDistributedTaxes(taxableBase, netChargeAmount, this.pricing.applicableTaxRule);\r\n\t\tlet taxTotal = zero;\r\n\t\tdistributedTaxes.forEach(dt => {\r\n\t\t\tconst taxRule = this.pricing.applicableTaxRule.find(r => r.getTaxRuleId() === dt.ruleId)!;\r\n\t\t\ttaxBreakdown[dt.ruleId] = {\r\n\t\t\t\trate: dt.rate,\r\n\t\t\t\ttaxableAmount: taxableBase,\r\n\t\t\t\ttaxAmount: dt.taxAmount,\r\n\t\t\t\tsystem: taxRule.getTaxSystem(),\r\n\t\t\t\tsubSystem: taxRule.getTaxSubSystem()\r\n\t\t\t};\r\n\t\t\ttaxTotal = taxTotal.add(dt.taxAmount);\r\n\t\t});\r\n\r\n\t\tconst grandTotal = netChargeAmount;\r\n\t\tthis.total = {\r\n\t\t\tchargeAmount: baseChargeAmount,\r\n\t\t\tdiscountTotal: totalDiscount,\r\n\t\t\tdiscountBreakdown: this.total.discountBreakdown,\r\n\t\t\tnetChargeAmount: netChargeAmount,\r\n\t\t\ttaxBreakdown: taxBreakdown,\r\n\t\t\ttaxTotal: taxTotal,\r\n\t\t\tgrandTotal: grandTotal\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets a plain data object representing this charge.\r\n\t * @returns ChargeData for serialization.\r\n\t */\r\n\tpublic getDetails(): ChargeData {\r\n\t\tconst details: ChargeData = {\r\n\t\t\tid: this.id,\r\n\t\t\tname: Utils.deepClone(this.name),\r\n\t\t\ttype: this.type,\r\n\t\t\tcategory: this.category,\r\n\t\t\tpricing: {\r\n\t\t\t\tbaseChargeAmount: this.pricing.baseChargeAmount.getDetails(),\r\n\t\t\t\ttaxCategory: this.pricing.taxCategory,\r\n\t\t\t\tapplicableTaxRule: this.pricing.applicableTaxRule.map(r => r.getDetails())\r\n\t\t\t},\r\n\t\t\timpact: this.impact,\r\n\t\t\tlineItemId: this.lineItemId,\r\n\t\t\ttotal: {\r\n\t\t\t\tchargeAmount: this.total.chargeAmount.getDetails(),\r\n\t\t\t\tdiscountTotal: this.total.discountTotal.getDetails(),\r\n\t\t\t\tdiscountBreakdown: Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([k, v]) => [k, v.getDetails()])),\r\n\t\t\t\tnetChargeAmount: this.total.netChargeAmount.getDetails(),\r\n\t\t\t\ttaxBreakdown: Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([k, v]) => [k, {\r\n\t\t\t\t\trate: v.rate,\r\n\t\t\t\t\ttaxableAmount: v.taxableAmount.getDetails(),\r\n\t\t\t\t\ttaxAmount: v.taxAmount.getDetails(),\r\n\t\t\t\t\tsystem: v.system,\r\n\t\t\t\t\tsubSystem: v.subSystem\r\n\t\t\t\t}])),\r\n\t\t\t\ttaxTotal: this.total.taxTotal.getDetails(),\r\n\t\t\t\tgrandTotal: this.total.grandTotal.getDetails()\r\n\t\t\t},\r\n\t\t\tcustomFields: this.getAllCustomFields()\r\n\t\t};\r\n\t\treturn details;\r\n\t}\r\n}\r\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a}from'./chunk-7B5TAYNA.mjs';import {a as a$1}from'./chunk-UIQH5QIR.mjs';import {e}from'./chunk-PL5HGCWN.mjs';import {u}from'./chunk-O6BLQQO7.mjs';import {b as b$1}from'./chunk-UXZBULDS.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=new Date){if(super(e,t),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.toISOString(),this.validTo=e.validTo&&Date.parse(e.validTo)?new Date(e.validTo).toISOString():t.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 u("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-Q7FOHAQD.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-Q7FOHAQD.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,OACVA,CAAA,CAAA,IAAA,CAAO,MACPA,CAAAA,CAAAA,CAAA,WAAa,YAFHA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAKAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,CAAA,CAAA,QAAA,CAAW,UACXA,CAAAA,CAAAA,CAAA,SAAW,UAFDA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAKAC,CAAAA,CA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AgBd,CAAAA,CAAO,CAC9Ce,CAAAA,CAAAA,CAAqB,IAAK,CAAA,kBAAA,CAAmBf,CAAO,CAAA,CAQ1D,GALI,CAACc,CAAAA,EAAmBA,CAAgB,CAAA,SAAA,CAAUN,CAAS,CAAI,CAAA,CAAA,EAK3D,CAACO,CAAAA,CACH,OAAOH,CAIT,CAAA,IAAMI,CAAiB,CAAA,IAAA,CAAK,WAAY,EAAA,CAClCC,CAAiB,CAAA,IAAA,CAAK,mBAEtBC,CAAAA,CAAAA,CAAcF,CAAmB,GAAA,UAAA,CAA0BP,EAAeD,CAGhF,CAAA,GAAIU,CAAY,CAAA,SAAA,IAAe,CAAG,CAAA,OAAON,CAEzC,CAAA,OAAQK,CAAgB,EACtB,IAAK,MAAA,CAEH,IAAME,CAAaJ,CAAAA,CAAAA,CACnBF,CAAoBK,CAAAA,CAAAA,CAAY,IAAIC,CAAU,CAAA,CAC9C,MACF,IAAK,aAEHN,CAAoBK,CAAAA,CAAAA,CAAY,QAAS,CAAA,IAAA,CAAK,oBAAuB,CAAA,GAAG,CAAE,CAAA,KAAA,GAC1E,MACF,QAEE,OAAON,CACX,CAKA,OAFsBC,CAAAA,CAAkB,GAAIE,CAAAA,CAAkB,CAGhE,CACF","file":"chunk-PAOHRZCC.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}\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,OACVA,CAAA,CAAA,IAAA,CAAO,MACPA,CAAAA,CAAAA,CAAA,WAAa,YAFHA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAKAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,CAAA,CAAA,QAAA,CAAW,UACXA,CAAAA,CAAAA,CAAA,SAAW,UAFDA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAKAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,EAAA,GAAM,CAAA,KAAA,CACNA,CAAA,CAAA,GAAA,CAAM,MAFIA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CA0BSC,CAArB,CAAA,cAAyCC,GAAU,CACvC,UACA,CAAA,IAAA,CACA,YACA,IACA,CAAA,UAAA,CACA,SACA,CAAA,OAAA,CACA,aAGA,eAGA,CAAA,cAAA,CACA,eACA,CA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,CAAK,mBAEtBC,CAAAA,CAAAA,CAAcF,CAAmB,GAAA,UAAA,CAA0BP,EAAeD,CAGhF,CAAA,GAAIU,CAAY,CAAA,SAAA,IAAe,CAAG,CAAA,OAAON,CAEzC,CAAA,OAAQK,CAAgB,EACtB,IAAK,MAAA,CAEH,IAAME,CAAaJ,CAAAA,CAAAA,CACnBF,CAAoBK,CAAAA,CAAAA,CAAY,IAAIC,CAAU,CAAA,CAC9C,MACF,IAAK,aAEHN,CAAoBK,CAAAA,CAAAA,CAAY,QAAS,CAAA,IAAA,CAAK,oBAAuB,CAAA,GAAG,CAAE,CAAA,KAAA,GAC1E,MACF,QAEE,OAAON,CACX,CAKA,OAFsBC,CAAAA,CAAkB,GAAIE,CAAAA,CAAkB,CAGhE,CACF","file":"chunk-Q7FOHAQD.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}\r\n"]}
|