b23-lib 3.10.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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.js +1 -1
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Charge.d.mts +23 -7
- package/dist/Classes/Charge.d.ts +23 -7
- 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/Inventory.js +1 -1
- package/dist/Classes/Inventory.js.map +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/Invoice.d.mts +44 -10
- package/dist/Classes/Invoice.d.ts +44 -10
- package/dist/Classes/Invoice.js +1 -1
- package/dist/Classes/Invoice.js.map +1 -1
- package/dist/Classes/Invoice.mjs +1 -1
- package/dist/Classes/Invoice.mjs.map +1 -1
- package/dist/Classes/LineItem.d.mts +28 -8
- package/dist/Classes/LineItem.d.ts +28 -8
- package/dist/Classes/LineItem.js +1 -1
- package/dist/Classes/LineItem.js.map +1 -1
- package/dist/Classes/LineItem.mjs +1 -1
- package/dist/Classes/Order.js +1 -1
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/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 +55 -26
- package/dist/Classes/ShoppingContainer.d.ts +55 -26
- 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/TieredPrice.js +1 -1
- package/dist/Classes/TieredPrice.js.map +1 -1
- package/dist/Classes/TieredPrice.mjs +1 -1
- package/dist/{chunk-MBR2GRKU.mjs → chunk-3SUQYXIJ.mjs} +2 -2
- package/dist/{chunk-MBR2GRKU.mjs.map → chunk-3SUQYXIJ.mjs.map} +1 -1
- package/dist/chunk-A2PC4S2X.mjs +2 -0
- package/dist/chunk-A2PC4S2X.mjs.map +1 -0
- package/dist/chunk-LE4HS2A6.mjs +2 -0
- package/dist/chunk-LE4HS2A6.mjs.map +1 -0
- package/dist/chunk-MWDQACOC.mjs +2 -0
- package/dist/chunk-MWDQACOC.mjs.map +1 -0
- package/dist/{chunk-4PTWJI6J.mjs → chunk-XXKEHCV5.mjs} +2 -2
- package/dist/chunk-XXKEHCV5.mjs.map +1 -0
- package/dist/chunk-YDSXBMNW.mjs +2 -0
- package/dist/chunk-YDSXBMNW.mjs.map +1 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-4PTWJI6J.mjs.map +0 -1
- package/dist/chunk-5N2HRXWJ.mjs +0 -2
- package/dist/chunk-5N2HRXWJ.mjs.map +0 -1
- package/dist/chunk-MPKIC2MS.mjs +0 -2
- package/dist/chunk-MPKIC2MS.mjs.map +0 -1
- package/dist/chunk-NXDEYUDI.mjs +0 -2
- package/dist/chunk-NXDEYUDI.mjs.map +0 -1
- package/dist/chunk-SZLAIOMF.mjs +0 -2
- package/dist/chunk-SZLAIOMF.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {b as b$3}from'./chunk-XZFALA7N.mjs';export{d as Fetch,b as Logger,c as ResponseUtility}from'./chunk-XZFALA7N.mjs';import {f,b as b$2}from'./chunk-
|
|
1
|
+
import {b as b$3}from'./chunk-XZFALA7N.mjs';export{d as Fetch,b as Logger,c as ResponseUtility}from'./chunk-XZFALA7N.mjs';import {f,b as b$2}from'./chunk-XXKEHCV5.mjs';export{a as Utils}from'./chunk-XXKEHCV5.mjs';import'./chunk-7RAIVZKB.mjs';import'./chunk-UIQH5QIR.mjs';import {q,j,a,b as b$1,c,d as d$1}from'./chunk-PL5HGCWN.mjs';import'./chunk-O6BLQQO7.mjs';import'./chunk-UXZBULDS.mjs';var m={$id:"standards",definitions:{lowercaseText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]*$"},lowercaseText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,10}$"},lowercaseText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,16}$"},lowercaseText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,30}$"},lowercaseText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,50}$"},lowercaseText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,256}$"},text:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).*$"},text10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,10}$"},text16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,16}$"},text30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,30}$"},text50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,50}$"},text256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,256}$"},requiredText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).+$"},requiredText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,10}$"},requiredText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,16}$"},requiredText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,30}$"},requiredText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,50}$"},requiredText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,256}$"},url:{type:"string",pattern:"^https://[^\\s/$.?#].[^\\s]*$",maxLength:2048},uuid:{type:"string",minLength:1,pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"},productKey:{type:"string",pattern:f.productKeyRegex.source},productSku:{type:"string",pattern:f.productSKURegex.source},productType:{type:"string",enum:Object.values(q)},genderCategory:{type:"string",enum:Object.values(j)},price:{type:"object",properties:{amount:{type:"number",minimum:0},currency:{$ref:"#/definitions/currency"}},additionalProperties:!1,required:["amount","currency"]},color:{type:"object",properties:{name:{type:"string"},hex:{type:"string"}},additionalProperties:!1,required:["name"]},attributeValue:{oneOf:[{type:"string"},{$ref:"#/definitions/color"}]},selectionAttributes:{type:"object",properties:{color:{$ref:"#/definitions/color"}},required:["color"],additionalProperties:{$ref:"#/definitions/attributeValue"}},firstName:{$ref:"#/definitions/requiredText30"},lastName:{$ref:"#/definitions/text30"},company:{$ref:"#/definitions/text50"},phone:{type:"string",pattern:"^[0-9]{10}$"},e164Phone:{type:"string",pattern:"^\\+[1-9]\\d{1,14}$"},email:{type:"string",pattern:"^[^\\s]+@[^\\s]+\\.[^\\s]+$"},addressLine1:{$ref:"#/definitions/requiredText50"},addressLine2:{$ref:"#/definitions/text50"},city:{$ref:"#/definitions/requiredText30"},postalCode:{$ref:"#/definitions/requiredText16"},state:{type:"string",enum:["AP","AR","AS","BR","CT","GA","GJ","HR","HP","JH","KA","KL","MP","MH","MN","ML","MZ","NL","OR","PB","RJ","SK","TN","TG","TR","UP","UT","WB","AN","CH","DH","LD","DL","PY","LA","JK"]},country:{type:"string",enum:Object.values(a)},currency:{type:"string",enum:Object.values(b$1)},locale:{type:"string",enum:Object.values(c)},language:{type:"string",enum:Object.values(d$1)},localeOrLanguage:{type:"string",enum:[...Object.values(c),...Object.values(d$1)]},addressType:{type:"string",enum:["shipping","billing","billing&shipping"]},address:{type:"object",properties:{firstName:{$ref:"standards#/definitions/firstName"},lastName:{$ref:"standards#/definitions/lastName"},company:{$ref:"standards#/definitions/company"},phone:{$ref:"standards#/definitions/phone"},email:{$ref:"standards#/definitions/email"},addressLine1:{$ref:"standards#/definitions/addressLine1"},addressLine2:{$ref:"standards#/definitions/addressLine2"},city:{$ref:"standards#/definitions/city"},postalCode:{$ref:"standards#/definitions/postalCode"},state:{$ref:"standards#/definitions/state"},country:{$ref:"standards#/definitions/country"}},required:["firstName","lastName","phone","email","addressLine1","postalCode","state","country"]}}};var g={$id:"TieredPrices",definitions:{pricingType:{enum:Object.values(b$2)},tier:{type:"object",properties:{enabled:{type:"boolean"},minQuantity:{type:"integer",minimum:1},unitPrice:{$ref:"standards#/definitions/price"}},required:["minQuantity","unitPrice"]},volumeTieredPrice:{type:"object",properties:{type:{const:"volume"},currency:{$ref:"standards#/definitions/currency"},baseUnitPrice:{$ref:"standards#/definitions/price"},taxCategory:{$ref:"standards#/definitions/requiredText"},isTaxInclusive:{type:"boolean"},tiers:{type:"array",items:{$ref:"TieredPrices#/definitions/tier"}}},required:["taxCategory","baseUnitPrice"]},selectionTieredPrice:{type:"object",properties:{type:{const:"selection"},currency:{$ref:"standards#/definitions/currency"},taxCategory:{$ref:"standards#/definitions/requiredText"},isTaxInclusive:{type:"boolean"},selections:{type:"array",items:{type:"object",properties:{selectionAttributes:{$ref:"standards#/definitions/selectionAttributes"},baseUnitPrice:{$ref:"standards#/definitions/price"},tiers:{type:"array",items:{$ref:"TieredPrices#/definitions/tier"}}},required:["selectionAttributes","baseUnitPrice"]}}},required:["type","taxCategory","currency"]},tieredPrice:{anyOf:[{$ref:"TieredPrices#/definitions/volumeTieredPrice"},{$ref:"TieredPrices#/definitions/selectionTieredPrice"}]}}};var T={getStandardSchemaDefinition(){return m},getTieredPriceSchemaDefinition(){return g}},b=T;var d=class{cache=new Map;maxSize;ttl;cleanupInterval;constructor(e=1e3,t=5*60*1e3){if(!Number.isFinite(e)||e<1)throw new RangeError("maxSize must be a finite number greater than or equal to 1.");if(!Number.isFinite(t)||t<1)throw new RangeError("ttl must be a finite number greater than or equal to 1.");this.maxSize=e,this.ttl=t,this.cleanupInterval=setInterval(()=>this.cleanup(),60*1e3),this.cleanupInterval.unref&&this.cleanupInterval.unref();}cleanup(){let e=Date.now();for(let[t,r]of this.cache.entries())e>=r.expiry&&this.cache.delete(t);}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r);}this.cache.set(e,{value:t,expiry:Date.now()+this.ttl});}get(e){let t=this.cache.get(e);if(t){if(Date.now()>=t.expiry){this.cache.delete(e);return}return this.cache.delete(e),b$3.logMessage("MemoryCache.get",`Successfully read cache data for key: ${e}`),this.cache.set(e,t),t.value}}dispose(){clearInterval(this.cleanupInterval);}},P=d;
|
|
2
2
|
export{P as MemoryCache,b as Schema};//# sourceMappingURL=index.mjs.map
|
|
3
3
|
//# sourceMappingURL=index.mjs.map
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
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","i","unsafeStringify","arr","offset","parse","v","parse_default","stringToBytes","str","bytes","DNS","URL","v35","name","version","hashfunc","generateUUID","value","namespace","buf","_namespace","native_default","v4","options","rnds","v4_default","sha1","sha1_default","v5","v5_default","Utils","key","selectionAttributes","ProductModel","searchId","selectionAttributesKey","obj","Utils_default","_ProductModel","BaseModel","SelectionAttributeParseError","attributes","parts","part","error","data","date","acc","country","TieredPriceModel","uniqueSelectionAttributes","variant","DuplicateSelectionAttributeError","ImageInfoModel","image","locale","LocaleLanguageMap","searchKey","match","category","baseDetails","img","allowedAttributeValues","providedValue","c","size","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","throwOnNotFound","InvalidPricingTypeError"],"mappings":"yPACA,IAAMA,CAAY,CAAA,IAAI,WAAW,GAAG,CAAA,CAEhCC,CAAUD,CAAAA,CAAAA,CAAU,OACT,SAARE,CAAAA,EAAuB,CAC5B,OAAID,CAAAA,CAAUD,EAAU,MAAS,CAAA,EAAA,GAC/BG,CAAO,CAAA,cAAA,CAAeH,CAAS,CAC/BC,CAAAA,CAAAA,CAAU,CAGLD,CAAAA,CAAAA,CAAAA,CAAU,MAAMC,CAASA,CAAAA,CAAAA,EAAW,EAAE,CAC/C,CCXA,IAAOG,CAAAA,CAAQ,sHCEf,SAASC,CAAAA,CAASC,EAAM,CACtB,OAAO,OAAOA,CAAAA,EAAS,UAAYF,CAAM,CAAA,IAAA,CAAKE,CAAI,CACpD,CAEA,IAAOC,CAAAA,CAAQF,CCAf,CAAA,IAAMG,EAAY,EAAC,CAEnB,QAASC,CAAI,CAAA,CAAA,CAAGA,EAAI,GAAK,CAAA,EAAEA,CACzBD,CAAAA,CAAAA,CAAU,MAAMC,CAAI,CAAA,GAAA,EAAO,SAAS,EAAE,CAAA,CAAE,MAAM,CAAC,CAAC,CAG3C,CAAA,SAASC,EAAgBC,CAAKC,CAAAA,CAAAA,CAAS,EAAG,CAG/C,OAAOJ,EAAUG,CAAIC,CAAAA,CAAAA,CAAS,CAAC,CAAC,EAAIJ,CAAUG,CAAAA,CAAAA,CAAIC,CAAS,C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ds8Pool = 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 { CountryCode, 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 VolumenTieredPriceAttributes = {\n type?: PricingType.VOLUME;\n taxCategory: string;\n isTaxInclusive?: boolean;\n currency?: CurrencyCode;\n baseUnitPrice: PriceData;\n tiers: PriceTierAttributes[];\n}\n\nexport type SelectionTieredPriceAttributes = {\n type: PricingType.SELECTION;\n taxCategory: string;\n isTaxInclusive?: boolean;\n currency: CurrencyCode;\n selections: (Omit<SelectionPricingData, 'tiers'> & { tiers?: PriceTierAttributes[] })[];\n}\n\nexport type TieredPriceAttributes = VolumenTieredPriceAttributes | SelectionTieredPriceAttributes;\n\nexport type VolumenTieredPriceData = {\n type: PricingType.VOLUME;\n taxCategory: string;\n isTaxInclusive: boolean;\n currency: CurrencyCode;\n baseUnitPrice: PriceData;\n tiers: PriceTierData[];\n};\n\nexport type SelectionTieredPriceData = {\n type: PricingType.SELECTION;\n taxCategory: string;\n isTaxInclusive: boolean;\n currency: CurrencyCode;\n selections: SelectionPricingData[];\n}\n\nexport type TieredPriceData = VolumenTieredPriceData | SelectionTieredPriceData;\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 isPriceAvailable(selectionAttributes?: SelectionAttributes): boolean;\n abstract getBaseUnitPrice(selectionAttributes?: SelectionAttributes): PriceModel;\n abstract getDetails(): TieredPriceData;\n abstract getCurrency(): CurrencyCode;\n abstract getApplicableUnitPrice(quantity: number, selectionAttributes?: SelectionAttributes): PriceModel;\n abstract getMinQuantity(selectionAttributes?: SelectionAttributes): number;\n abstract getMaxDiscountPercent(selectionAttributes?: SelectionAttributes): number;\n abstract getTiers(selectionAttributes?: SelectionAttributes): PriceTier[];\n abstract getMinPrice(selectionAttributes?: SelectionAttributes): PriceModel | null;\n abstract getMaxPrice(selectionAttributes?: SelectionAttributes): PriceModel | null;\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 isPriceAvailable(): boolean {\n return this.tiers.filter(t => t.enabled).length > 0;\n }\n\n getBaseUnitPrice(): PriceModel {\n return this.baseUnitPrice;\n }\n\n getCurrency(): CurrencyCode {\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 getMinPrice(): PriceModel | null {\n const enabledTiers = this.tiers.filter(tier => tier.enabled);\n return enabledTiers.length ? enabledTiers[enabledTiers.length - 1].unitPrice : null;\n }\n\n getMaxPrice(): PriceModel | null {\n const enabledTiers = this.tiers.filter(tier => tier.enabled);\n return enabledTiers.length ? enabledTiers[0].unitPrice : null;\n }\n\n getTiers(): PriceTier[] {\n return this.tiers.map(tier => ({\n enabled: tier.enabled,\n minQuantity: tier.minQuantity,\n unitPrice: tier.unitPrice\n }));\n }\n\n getDetails(): VolumenTieredPriceData {\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, throwOnNotFound = false): SelectionPricing | null {\n const key = ProductModel.generateSelectionAttributesKey(selectionAttributes);\n const match = this.selections.find(\n s => ProductModel.generateSelectionAttributesKey(s.selectionAttributes) === key\n );\n if (!match && throwOnNotFound) {\n throw new InvalidTieredPriceError(\"No pricing configuration found for selection variant.\");\n }\n return match ?? null;\n }\n\n isPriceAvailable(selectionAttributes?: SelectionAttributes): boolean {\n if(!selectionAttributes) {\n console.warn('Selection attributes are required to check price availability for selection pricing.');\n return false;\n }\n const match = this.findMatch(selectionAttributes);\n return match ? match.tiers.filter(t => t.enabled).length > 0 : false;\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 const match = this.findMatch(selectionAttributes, true)!;\n return match.baseUnitPrice;\n }\n\n getCurrency(): CurrencyCode {\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, true)!;\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, true)!;\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, true)!;\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 getTiers(selectionAttributes?: SelectionAttributes): PriceTier[] {\n if (!selectionAttributes) {\n throw new InvalidPricingTypeError(\"Selection attributes are required to get tiers for selection pricing.\");\n }\n const match = this.findMatch(selectionAttributes, true)!;\n return match.tiers.map(tier => ({\n enabled: tier.enabled,\n minQuantity: tier.minQuantity,\n unitPrice: tier.unitPrice\n }));\n }\n\n getMinPrice(selectionAttributes?: SelectionAttributes): PriceModel | null {\n if (!selectionAttributes) {\n throw new InvalidPricingTypeError(\"Selection attributes are required to get min price for selection pricing.\");\n }\n const match = this.findMatch(selectionAttributes);\n if (!match) return null;\n const enabledTiers = match.tiers.filter(t => t.enabled);\n return enabledTiers.length ? enabledTiers[enabledTiers.length - 1].unitPrice : null;\n }\n\n getMaxPrice(selectionAttributes?: SelectionAttributes): PriceModel | null {\n if (!selectionAttributes) {\n throw new InvalidPricingTypeError(\"Selection attributes are required to get max price for selection pricing.\");\n }\n const match = this.findMatch(selectionAttributes);\n if (!match) return null;\n const enabledTiers = match.tiers.filter(t => t.enabled);\n return enabledTiers.length ? enabledTiers[0].unitPrice : null;\n }\n\n getDetails(): SelectionTieredPriceData {\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"]}
|
package/dist/chunk-5N2HRXWJ.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
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-4PTWJI6J.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-5N2HRXWJ.mjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-5N2HRXWJ.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
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,C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,CAAC,CAACD,CAAAA,CAAGC,CAAC,CAAA,GAAM,CAACD,CAAG,CAAA,CAC5F,IAAMC,CAAAA,CAAAA,CAAE,IACR,CAAA,aAAA,CAAeA,CAAE,CAAA,aAAA,CAAc,UAAW,EAAA,CAC1C,SAAWA,CAAAA,CAAAA,CAAE,SAAU,CAAA,UAAA,GACvB,MAAQA,CAAAA,CAAAA,CAAE,MACV,CAAA,SAAA,CAAWA,CAAE,CAAA,SACd,CAAC,CAAC,CAAC,CAAA,CACH,QAAU,CAAA,IAAA,CAAK,KAAM,CAAA,QAAA,CAAS,UAAW,EAAA,CACzC,UAAY,CAAA,IAAA,CAAK,KAAM,CAAA,UAAA,CAAW,UAAW,EAC9C,CACA,CAAA,YAAA,CAAc,IAAK,CAAA,kBAAA,EACpB,CAED,CACD","file":"chunk-5N2HRXWJ.mjs","sourcesContent":["import { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\nimport Utils from \"../Utils\";\r\nimport { LocaleCode, LocalizedString } from \"./Common\";\r\nimport { ChargeImpact, ChargeType, LocaleLanguageMap, TaxSystem } from \"./Enum\";\r\nimport { InvalidChargeTaxRuleError, InvalidChargeError, InvalidTaxRuleError } from \"./Error\";\r\nimport { 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"]}
|
package/dist/chunk-MPKIC2MS.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
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 +0,0 @@
|
|
|
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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,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"]}
|
package/dist/chunk-NXDEYUDI.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {a as a$4,b as b$1}from'./chunk-MPKIC2MS.mjs';import {a as a$3}from'./chunk-EZ35IKUA.mjs';import {a as a$1,c}from'./chunk-4PTWJI6J.mjs';import {b}from'./chunk-7RAIVZKB.mjs';import {a as a$2}from'./chunk-UIQH5QIR.mjs';import {e,o}from'./chunk-PL5HGCWN.mjs';import {d,c as c$1,f,g,i,j,k,b as b$2}from'./chunk-O6BLQQO7.mjs';import {a}from'./chunk-UXZBULDS.mjs';var I=class extends a{id;productKey;sku;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;productType;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,this.sku=t.sku,this.selectionAttributes=a$1.deepClone(t.selectionAttributes),this.name=a$1.deepClone(t.name),this.specifications=a$1.deepClone(t.specifications),this.primaryImage=new b(t.primaryImage),this.subItems=a$1.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new d(i.size);e.add(i.size);}),this.pricing={unitPrice:new a$2(t.pricing.unitPrice),tierPricing:c.create(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(i=>new a$3(i))},this.validateTaxRules(this.pricing.applicableTaxRule),this.state=t.state??"INITIAL",this.productType=t.productType??"GOODS",this.total={quantity:t.total.quantity,unitPrice:new a$2(t.total.unitPrice),subtotal:new a$2(t.total.subtotal),discountTotal:new a$2(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([i,a])=>[i,new a$2(a)])),netUnitPrice:new a$2(t.total.netUnitPrice),netSubtotal:new a$2(t.total.netSubtotal),taxTotal:new a$2(t.total.taxTotal),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([i,a])=>[i,{rate:a.rate,taxableUnitPrice:new a$2(a.taxableUnitPrice),taxPerUnit:new a$2(a.taxPerUnit),taxAmount:new a$2(a.taxAmount),system:a.system,subSystem:a.subSystem}])),grandTotal:new a$2(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSku(){return this.sku}getSelectionAttributes(){return a$1.deepClone(this.selectionAttributes)}getName(t){return t?a$1.deepClone(this.name[t]??this.name[e[t]]??this.name.en):a$1.deepClone(this.name)}getSpecifications(t){return t?a$1.deepClone(this.specifications[t]??this.specifications[e[t]]??this.specifications.en):a$1.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return a$1.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getState(){return this.state}getProductType(){return this.productType}getTotal(){return {quantity:this.total.quantity,unitPrice:this.total.unitPrice,subtotal:this.total.subtotal,discountTotal:this.total.discountTotal,discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([t,e])=>[t,e])),netUnitPrice:this.total.netUnitPrice,netSubtotal:this.total.netSubtotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableUnitPrice:e.taxableUnitPrice,taxPerUnit:e.taxPerUnit,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),grandTotal:this.total.grandTotal}}getDetails(){let t=this.getPricing(),e=this.getTotal();return {id:this.getId(),productKey:this.getProductKey(),sku:this.getSku(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:t.unitPrice.getDetails(),tierPricing:t.tierPricing.getDetails(),taxCategory:t.taxCategory,applicableTaxRule:t.applicableTaxRule.map(i=>i.getDetails())},state:this.getState(),productType:this.getProductType(),total:{quantity:e.quantity,unitPrice:e.unitPrice.getDetails(),subtotal:e.subtotal.getDetails(),discountTotal:e.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(e.discountBreakdown).map(([i,a])=>[i,a.getDetails()])),netUnitPrice:e.netUnitPrice.getDetails(),netSubtotal:e.netSubtotal.getDetails(),taxTotal:e.taxTotal.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(e.taxBreakdown).map(([i,a])=>[i,{rate:a.rate,taxableUnitPrice:a.taxableUnitPrice.getDetails(),taxPerUnit:a.taxPerUnit.getDetails(),taxAmount:a.taxAmount.getDetails(),system:a.system,subSystem:a.subSystem}])),grandTotal:e.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}validateTaxRules(t){let e=new Set;for(let i=0;i<t.length;i++){let a=t[i].getTaxRuleId();if(e.has(a))throw new c$1("Duplicate tax rule ID found: "+a);e.add(a);}}addSubItems(t,e){t.forEach(i=>{let a=this.subItems.find(u=>u.size===i.size);a?a.quantity=e?a.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity>0),this.calculateTotals();}updateProductData(t,e,i$1){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new f;if(!t.getIsActive())throw new g;this.subItems.forEach(c=>{if(!t.validateSize(c.size))throw new i});let a=t.getPriceDetails(e);if(!a||a.getCurrency()!==i$1)throw new j;this.name=t.getName(),this.specifications=t.getSpecifications(),this.sku=t.getSku(this.selectionAttributes),this.primaryImage=t.getImages(this.selectionAttributes).primary;let u=this.subItems.reduce((c,p)=>c+p.quantity,0),b=a.getApplicableUnitPrice(u,this.selectionAttributes);this.productType=t.getProductType(),this.pricing={unitPrice:b,tierPricing:a,taxCategory:a.getTaxCategory(),applicableTaxRule:this.pricing.applicableTaxRule},this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discountBreakdown=e,this.calculateTotals();}updateTax(t){t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new k}),this.validateTaxRules(t),this.pricing.applicableTaxRule=t,this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((s,n)=>s+n.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,unitPrice:t,subtotal:t,discountTotal:t,discountBreakdown:{},netUnitPrice:t,netSubtotal:t,taxTotal:t,taxBreakdown:{},grandTotal:t};return}let i=this.pricing.tierPricing.getApplicableUnitPrice(e,this.selectionAttributes),a=i.multiply(e),u=Object.values(this.total.discountBreakdown).reduce((s,n)=>s.add(n),t),b=a.subtract(u),c=e>0?b.divide(e):t,p={},d=t,P=i,S=a,h=b,l=c;this.pricing.tierPricing.getIsTaxInclusive()?(P=a$4(i,this.pricing.applicableTaxRule),S=P.multiply(e),c.getAmount()>0&&(l=a$4(c,this.pricing.applicableTaxRule),h=l.multiply(e),b$1(l,c,this.pricing.applicableTaxRule).forEach(n=>{let g=n.taxAmount.multiply(e).round(),m=this.pricing.applicableTaxRule.find(O=>O.getTaxRuleId()===n.ruleId);p[n.ruleId]={rate:n.rate,taxableUnitPrice:l,taxPerUnit:n.taxAmount,taxAmount:g,system:m.getTaxSystem(),subSystem:m.getTaxSubSystem()},d=d.add(g);}))):this.pricing.applicableTaxRule.forEach(s=>{let n=s.getApplicableTaxRate(l),g=s.calculateTax(l),m=g.multiply(e).round();p[s.getTaxRuleId()]={rate:n,taxableUnitPrice:l,taxPerUnit:g,taxAmount:m,system:s.getTaxSystem(),subSystem:s.getTaxSubSystem()},d=d.add(m);});let v=h.add(d);this.total={quantity:e,unitPrice:P,subtotal:S,discountTotal:u,discountBreakdown:this.total.discountBreakdown,netUnitPrice:l,netSubtotal:h,taxTotal:d,taxBreakdown:p,grandTotal:v};}updateState(t){if(this.state in o)this.state!==t&&(this.state=t);else throw new b$2(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.sku="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new b({sources:{original:""}}),this.subItems=[],this.productType="GOODS",this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[]},this.total={quantity:0,unitPrice:t,subtotal:t,discountTotal:t,discountBreakdown:{},netUnitPrice:t,netSubtotal:t,taxTotal:t,taxBreakdown:{},grandTotal:t};}};export{I as a};//# sourceMappingURL=chunk-NXDEYUDI.mjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-NXDEYUDI.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/LineItem.ts"],"names":["LineItemModel","CustomFieldModel","data","Utils_default","ImageInfoModel","uniqueSelectionAttributes","item","DuplicateSizeError","PriceModel","TieredPriceModel","rule","TaxRuleModel","couponCode","discount","taxRuleId","taxBreakdown","locale","LocaleLanguageMap","pricing","total","taxRules","uniqueTaxRule","currentTaxRuleId","InvalidLineItemTaxRuleError","subItems","addQuantity","subItem","existingSubItem","sub","product","cartCountry","cartCurrency","ProductMismatchError","ProductInactiveError","SizeMismatchError","productPricing","PricingNotFoundError","quantity","sum","s","unitPrice","appliedDiscounts","lineItemDiscounts","taxRule","InvalidTaxRuleError","zero","totalQuantity","tierUnitPrice","initialSubTotal","totalDiscount","initialNetSubtotal","initialNetUnitPrice","taxTotal","finalUnitPrice","finalSubTotal","finalNetSubtotal","finalNetUnitPrice","extractExclusiveBase","calculateDistributedTaxes","dt","taxAmount","r","rate","taxPerUnit","grandTotal","newState","LineItemState","InvalidLineItemStateError"],"mappings":"6WA8GA,IAAqBA,EAArB,cAA2CC,CAAiB,CAChD,EAAA,CACA,WACA,GACA,CAAA,mBAAA,CAEA,IACA,CAAA,cAAA,CACA,aACA,QACA,CAAA,OAAA,CAEA,MACA,WACA,CAAA,KAAA,CAMV,YAAYC,CAA0B,CAAA,CACpC,KAAMA,CAAAA,CAAI,EACV,IAAK,CAAA,EAAA,CAAKA,EAAK,EACf,CAAA,IAAA,CAAK,WAAaA,CAAK,CAAA,UAAA,CACvB,IAAK,CAAA,GAAA,CAAMA,EAAK,GAChB,CAAA,IAAA,CAAK,oBAAsBC,GAAM,CAAA,SAAA,CAAUD,EAAK,mBAAmB,CAAA,CAEnE,IAAK,CAAA,IAAA,CAAOC,IAAM,SAAUD,CAAAA,CAAAA,CAAK,IAAI,CACrC,CAAA,IAAA,CAAK,eAAiBC,GAAM,CAAA,SAAA,CAAUD,CAAK,CAAA,cAAc,EACzD,IAAK,CAAA,YAAA,CAAe,IAAIE,CAAeF,CAAAA,CAAAA,CAAK,YAAY,CACxD,CAAA,IAAA,CAAK,QAAWC,CAAAA,GAAAA,CAAM,UAAUD,CAAK,CAAA,QAAQ,EAE7C,IAAIG,CAAAA,CAA4B,IAAI,GACpC,CAAA,IAAA,CAAK,QAAS,CAAA,OAAA,CAAQC,GAAQ,CAC5B,GAAID,EAA0B,GAAIC,CAAAA,CAAAA,CAAK,IAAI,CACzC,CAAA,MAAM,IAAIC,CAAAA,CAAmBD,EAAK,IAAI,CAAA,CAExCD,EAA0B,GAAIC,CAAAA,CAAAA,CAAK,IAAI,EACzC,CAAC,CAED,CAAA,IAAA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A,CAC1B,YAAa,IAAK,CAAA,OAAA,CAAQ,WAC1B,CAAA,iBAAA,CAAmB,EACrB,CAAA,CACA,KAAK,KAAQ,CAAA,CACX,SAAU,CACV,CAAA,SAAA,CAAWA,CACX,CAAA,QAAA,CAAUA,EACV,aAAeA,CAAAA,CAAAA,CACf,kBAAmB,EAAC,CACpB,aAAcA,CACd,CAAA,WAAA,CAAaA,CACb,CAAA,QAAA,CAAUA,EACV,YAAc,CAAA,GACd,UAAYA,CAAAA,CACd,EACF,CACF","file":"chunk-NXDEYUDI.mjs","sourcesContent":["import Utils from \"../Utils\";\r\nimport { Color, CountryCode, CurrencyCode, LocaleCode, LocalizedString, LocalizedValue } from \"./Common\";\r\nimport CouponModel from \"./Coupon\";\r\nimport { LineItemState, LocaleLanguageMap, TaxSystem, ProductType } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport ProductModel, { ProductSelectionAttributes, ProductSpecification, SelectionAttributes } from \"./Product\";\r\nimport { TaxRuleData, TaxRuleModel } from \"./TaxRule\";\r\nimport { TieredPriceData, TieredPriceModel } from \"./TieredPrice\";\r\nimport {\r\n DuplicateSizeError,\r\n ProductMismatchError,\r\n ProductInactiveError,\r\n SizeMismatchError,\r\n PricingNotFoundError,\r\n InvalidTaxRuleError,\r\n InvalidLineItemStateError,\r\n InvalidLineItemTaxRuleError\r\n} from \"./Error\";\r\nimport { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\nimport { extractExclusiveBase, calculateDistributedTaxes } from \"../Utils/TaxMath\";\r\n\r\nexport type SubItem = {\r\n size: string | 'ONESIZE';\r\n quantity: number;\r\n};\r\n\r\nexport type LineItemPricing = {\r\n unitPrice: PriceData;\r\n tierPricing: TieredPriceData;\r\n taxCategory: string;\r\n applicableTaxRule: TaxRuleData[];\r\n};\r\n\r\nexport type LineItemPricingModel = {\r\n unitPrice: PriceModel;\r\n tierPricing: TieredPriceModel;\r\n taxCategory: string;\r\n applicableTaxRule: TaxRuleModel[];\r\n};\r\n\r\nexport type LineItemTaxBreakdown = {\r\n rate: number; // 0.09 for 9%\r\n taxableUnitPrice: PriceData; // effectiveUnitPrice used for calculation\r\n taxPerUnit: PriceData; // tax on single unit\r\n taxAmount: PriceData; // taxPerUnit × quantity (total tax)\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type LineItemTaxBreakdownModel = {\r\n rate: number;\r\n taxableUnitPrice: PriceModel;\r\n taxPerUnit: PriceModel;\r\n taxAmount: PriceModel;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type LineItemTotals = {\r\n quantity: number;\r\n unitPrice: PriceData; // original unit price (from tier pricing)\r\n subtotal: PriceData; // unitPrice × quantity\r\n discountTotal: PriceData; // sum of all discounts\r\n discountBreakdown: Record<string, PriceData>; // couponCode -> discount mapping\r\n netUnitPrice: PriceData; // unit price after discounts\r\n netSubtotal: PriceData; // subtotal - totalDiscount (taxable amount)\r\n taxTotal: PriceData; // sum of all tax amounts\r\n taxBreakdown: Record<string, LineItemTaxBreakdown>; // tax breakdown by tax rule\r\n grandTotal: PriceData; // effectiveSubtotal + taxTotal\r\n};\r\n\r\nexport type LineItemTotalsModel = {\r\n quantity: number;\r\n unitPrice: PriceModel;\r\n subtotal: PriceModel;\r\n discountTotal: PriceModel;\r\n discountBreakdown: Record<string, PriceModel>;\r\n netUnitPrice: PriceModel;\r\n netSubtotal: PriceModel;\r\n taxTotal: PriceModel;\r\n taxBreakdown: Record<string, LineItemTaxBreakdownModel>;\r\n grandTotal: PriceModel;\r\n};\r\n\r\nexport type LineItemAttributes = CustomFieldAttributes & {\r\n id: string;\r\n\r\n productKey: string;\r\n sku: string;\r\n selectionAttributes: SelectionAttributes;\r\n\r\n name: LocalizedString;\r\n specifications: LocalizedValue<ProductSpecification>;\r\n primaryImage: ImageInfoData;\r\n\r\n subItems: SubItem[];\r\n\r\n pricing: LineItemPricing;\r\n\r\n state?: LineItemState;\r\n productType?: ProductType;\r\n total: LineItemTotals;\r\n}\r\n\r\nexport type LineItemData = Required<LineItemAttributes>;\r\n\r\n/**\r\n * Represents a line item within a shopping cart.\r\n */\r\nexport default class LineItemModel extends CustomFieldModel {\r\n protected id: string;\r\n protected productKey: string;\r\n protected sku: string;\r\n protected selectionAttributes: SelectionAttributes;\r\n\r\n protected name: LocalizedString;\r\n protected specifications: LocalizedValue<ProductSpecification>;\r\n protected primaryImage: ImageInfoModel;\r\n protected subItems: SubItem[];\r\n protected pricing: LineItemPricingModel;\r\n\r\n protected state: LineItemState;\r\n protected productType: ProductType;\r\n protected total: LineItemTotalsModel;\r\n\r\n /**\r\n * Creates an instance of LineItemModel.\r\n * @param data - The initial line item attributes.\r\n */\r\n constructor(data: LineItemAttributes) {\r\n super(data);\r\n this.id = data.id;\r\n this.productKey = data.productKey;\r\n this.sku = data.sku;\r\n this.selectionAttributes = Utils.deepClone(data.selectionAttributes);\r\n\r\n this.name = Utils.deepClone(data.name);\r\n this.specifications = Utils.deepClone(data.specifications);\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.subItems = Utils.deepClone(data.subItems);\r\n\r\n let uniqueSelectionAttributes = new Set();\r\n this.subItems.forEach(item => {\r\n if (uniqueSelectionAttributes.has(item.size)) {\r\n throw new DuplicateSizeError(item.size);\r\n }\r\n uniqueSelectionAttributes.add(item.size);\r\n });\r\n\r\n this.pricing = {\r\n unitPrice: new PriceModel(data.pricing.unitPrice),\r\n tierPricing: TieredPriceModel.create(data.pricing.tierPricing),\r\n taxCategory: data.pricing.taxCategory,\r\n applicableTaxRule: data.pricing.applicableTaxRule.map(rule => new TaxRuleModel(rule)),\r\n }\r\n this.validateTaxRules(this.pricing.applicableTaxRule);\r\n\r\n this.state = data.state ?? LineItemState.INITIAL;\r\n this.productType = data.productType ?? ProductType.GOODS;\r\n\r\n this.total = {\r\n quantity: data.total.quantity,\r\n unitPrice: new PriceModel(data.total.unitPrice),\r\n subtotal: new PriceModel(data.total.subtotal),\r\n discountTotal: new PriceModel(data.total.discountTotal),\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(data.total.discountBreakdown).map(([couponCode, discount]) => [\r\n couponCode,\r\n new PriceModel(discount),\r\n ])\r\n ),\r\n netUnitPrice: new PriceModel(data.total.netUnitPrice),\r\n netSubtotal: new PriceModel(data.total.netSubtotal),\r\n taxTotal: new PriceModel(data.total.taxTotal),\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(data.total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n taxRuleId,\r\n {\r\n rate: taxBreakdown.rate,\r\n taxableUnitPrice: new PriceModel(taxBreakdown.taxableUnitPrice),\r\n taxPerUnit: new PriceModel(taxBreakdown.taxPerUnit),\r\n taxAmount: new PriceModel(taxBreakdown.taxAmount),\r\n system: taxBreakdown.system,\r\n subSystem: taxBreakdown.subSystem\r\n }\r\n ])\r\n ),\r\n grandTotal: new PriceModel(data.total.grandTotal),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the unique identifier of the line item.\r\n * @returns The unique ID string.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the product key associated with this line item.\r\n * @returns The product key string.\r\n */\r\n getProductKey(): string {\r\n return this.productKey;\r\n }\r\n\r\n /**\r\n * Gets the SKU of the line item.\r\n * @returns The SKU string.\r\n */\r\n getSku(): string {\r\n return this.sku;\r\n }\r\n\r\n /**\r\n * Gets the selection attributes (e.g., size, color) for this line item.\r\n * @returns A copy of the selection attributes object.\r\n */\r\n getSelectionAttributes(): SelectionAttributes {\r\n return Utils.deepClone(this.selectionAttributes);\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 Utils.deepClone(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 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 | undefined\r\n getSpecifications(locale?: LocaleCode): LocalizedValue<ProductSpecification> | ProductSpecification | undefined {\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 image information model for this line item.\r\n * @returns The ImageInfoModel instance.\r\n */\r\n getImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /**\r\n * Gets the sub-items (size/quantity breakdown).\r\n * @returns A copy of the array of SubItems.\r\n */\r\n getSubItems(): SubItem[] {\r\n return Utils.deepClone(this.subItems);\r\n }\r\n\r\n /**\r\n * Gets the total quantity for this line item across all sub-items.\r\n * @returns The total quantity as a number.\r\n */\r\n getTotalQuantity(): number {\r\n return this.total.quantity;\r\n }\r\n\r\n /**\r\n * Gets the pricing information model for this line item.\r\n * @returns An object containing unit price, tiered pricing, tax category, and tax details.\r\n */\r\n getPricing() {\r\n return {\r\n unitPrice: this.pricing.unitPrice,\r\n tierPricing: this.pricing.tierPricing,\r\n taxCategory: this.pricing.taxCategory,\r\n applicableTaxRule: [...this.pricing.applicableTaxRule],\r\n };\r\n }\r\n\r\n /**\r\n * Gets the current state of the line item.\r\n * @returns The LineItemState enum value.\r\n */\r\n getState() {\r\n return this.state;\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 total price for this line item (including all sub-items).\r\n * @returns An object containing line item totals including subtotal, tax, discounts, and grand total.\r\n */\r\n getTotal(): LineItemTotalsModel {\r\n return {\r\n quantity: this.total.quantity,\r\n unitPrice: this.total.unitPrice,\r\n subtotal: this.total.subtotal,\r\n discountTotal: this.total.discountTotal,\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(this.total.discountBreakdown).map(([couponCode, discount]) => [\r\n couponCode,\r\n discount,\r\n ])\r\n ),\r\n netUnitPrice: this.total.netUnitPrice,\r\n netSubtotal: this.total.netSubtotal,\r\n taxTotal: this.total.taxTotal,\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n taxRuleId,\r\n {\r\n rate: taxBreakdown.rate,\r\n taxableUnitPrice: taxBreakdown.taxableUnitPrice,\r\n taxPerUnit: taxBreakdown.taxPerUnit,\r\n taxAmount: taxBreakdown.taxAmount,\r\n system: taxBreakdown.system,\r\n subSystem: taxBreakdown.subSystem\r\n }\r\n ])\r\n ),\r\n grandTotal: this.total.grandTotal,\r\n };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the line item's details.\r\n * @returns LineItemData.\r\n */\r\n getDetails(): LineItemData {\r\n const pricing = this.getPricing();\r\n const total = this.getTotal();\r\n return {\r\n id: this.getId(),\r\n productKey: this.getProductKey(),\r\n sku: this.getSku(),\r\n selectionAttributes: this.getSelectionAttributes(),\r\n name: this.getName(),\r\n specifications: this.getSpecifications(),\r\n primaryImage: this.getImage().getDetails(),\r\n subItems: this.getSubItems(),\r\n pricing: {\r\n unitPrice: pricing.unitPrice.getDetails(),\r\n tierPricing: pricing.tierPricing.getDetails(),\r\n taxCategory: pricing.taxCategory,\r\n applicableTaxRule: pricing.applicableTaxRule.map(rule => rule.getDetails()),\r\n },\r\n state: this.getState(),\r\n productType: this.getProductType(),\r\n total: {\r\n quantity: total.quantity,\r\n unitPrice: total.unitPrice.getDetails(),\r\n subtotal: total.subtotal.getDetails(),\r\n discountTotal: total.discountTotal.getDetails(),\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(total.discountBreakdown).map(([couponCode, discount]) => [\r\n couponCode,\r\n discount.getDetails(),\r\n ])\r\n ),\r\n netUnitPrice: total.netUnitPrice.getDetails(),\r\n netSubtotal: total.netSubtotal.getDetails(),\r\n taxTotal: total.taxTotal.getDetails(),\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n taxRuleId,\r\n {\r\n rate: taxBreakdown.rate,\r\n taxableUnitPrice: taxBreakdown.taxableUnitPrice.getDetails(),\r\n taxPerUnit: taxBreakdown.taxPerUnit.getDetails(),\r\n taxAmount: taxBreakdown.taxAmount.getDetails(),\r\n system: taxBreakdown.system,\r\n subSystem: taxBreakdown.subSystem\r\n }\r\n ])\r\n ),\r\n grandTotal: total.grandTotal.getDetails(),\r\n },\r\n customFields: this.getAllCustomFields()\r\n };\r\n }\r\n\r\n /**\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 {InvalidLineItemTaxRuleError} Duplicate tax rule IDs will results in error.\r\n\t */\r\n private validateTaxRules(taxRules: TaxRuleModel[]): void {\r\n const uniqueTaxRule = new Set();\r\n for (let i = 0; i < taxRules.length; i++) {\r\n const currentTaxRuleId = taxRules[i].getTaxRuleId();\r\n if (uniqueTaxRule.has(currentTaxRuleId)) {\r\n throw new InvalidLineItemTaxRuleError(\"Duplicate tax rule ID found: \" + currentTaxRuleId);\r\n } else {\r\n uniqueTaxRule.add(currentTaxRuleId);\r\n }\r\n }\r\n }\r\n /**\r\n * Adds or updates sub-items (e.g., sizes with quantities) to the line item.\r\n * If a sub-item with the same size already exists, its quantity is either\r\n * updated by adding the new quantity or replaced entirely, based on the `addQuantity` flag.\r\n * Sub-items with a resulting quantity of 0 are removed.\r\n * @param subItems - An array of `SubItem` objects to add or update.\r\n * @param addQuantity - If true, adds the quantity from `subItem` to the existing quantity.\r\n * If false, replaces the existing quantity with the one from `subItem`.\r\n */\r\n addSubItems(subItems: SubItem[], addQuantity: boolean): void {\r\n subItems.forEach(subItem => {\r\n const existingSubItem = this.subItems.find(item => item.size === subItem.size);\r\n if (existingSubItem) {\r\n existingSubItem.quantity = addQuantity ? existingSubItem.quantity + subItem.quantity : subItem.quantity;\r\n } else {\r\n this.subItems.push(subItem);\r\n }\r\n })\r\n this.subItems = this.subItems.filter(sub => sub.quantity > 0);\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the line item with the latest product data (price, image, name, specifications).\r\n * Validates that the product matches the line item's selection and is active.\r\n * @param product - The product model to update from.\r\n * @param cartCountry - The country code for pricing context.\r\n * @param cartCurrency - The currency code for pricing context.\r\n * @throws {Error} If product mismatch, inactive, size mismatch, or pricing missing.\r\n */\r\n public updateProductData(product: ProductModel, cartCountry: CountryCode, cartCurrency: CurrencyCode): void {\r\n if (this.productKey !== product.getKey() || !product.validateSelectionAttribute(this.selectionAttributes)) {\r\n throw new ProductMismatchError();\r\n } else if (!product.getIsActive()) {\r\n throw new ProductInactiveError();\r\n }\r\n\r\n this.subItems.forEach(subItem => {\r\n if (!product.validateSize(subItem.size)) {\r\n throw new SizeMismatchError();\r\n }\r\n });\r\n\r\n const productPricing = product.getPriceDetails(cartCountry);\r\n if (!productPricing || productPricing.getCurrency() !== cartCurrency) {\r\n throw new PricingNotFoundError();\r\n }\r\n this.name = product.getName();\r\n this.specifications = product.getSpecifications();\r\n this.sku = product.getSku(this.selectionAttributes) as string;\r\n this.primaryImage = product.getImages(this.selectionAttributes).primary;\r\n\r\n const quantity = this.subItems.reduce((sum, s) => sum + s.quantity, 0);\r\n \r\n const unitPrice = productPricing.getApplicableUnitPrice(quantity, this.selectionAttributes);\r\n\r\n\r\n this.productType = product.getProductType();\r\n\r\n this.pricing = {\r\n unitPrice: unitPrice,\r\n tierPricing: productPricing,\r\n taxCategory: productPricing.getTaxCategory(),\r\n applicableTaxRule: this.pricing.applicableTaxRule\r\n }\r\n\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the discounts applied to this line item and recalculates totals.\r\n * @param appliedDiscounts - List of coupons and their allocated discount amounts.\r\n */\r\n public updateDiscounts(appliedDiscounts: { coupon: CouponModel, amount: PriceModel }[]): void {\r\n let lineItemDiscounts = {} as Record<string, PriceModel>;\r\n appliedDiscounts.forEach(discount => {\r\n lineItemDiscounts[discount.coupon.getCode()] = discount.amount;\r\n });\r\n\r\n this.total.discountBreakdown = lineItemDiscounts;\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the tax rule for this line item and recalculates totals.\r\n * @param taxRule - The new tax rule to apply.\r\n * @throws {Error} If the tax rule category does not match the item's tax category.\r\n */\r\n public updateTax(taxRules: TaxRuleModel[]): void {\r\n taxRules.forEach(taxRule => {\r\n if (!taxRule.appliesTo(this.pricing.taxCategory, taxRule.getCountry())) {\r\n throw new InvalidTaxRuleError();\r\n }\r\n });\r\n\r\n this.validateTaxRules(taxRules);\r\n this.pricing.applicableTaxRule = taxRules;\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Recalculates the line item totals based on current quantity, unit price, discounts, and tax rates.\r\n */\r\n public calculateTotals(): void {\r\n const zero = this.pricing.unitPrice.zero();\r\n const totalQuantity = this.subItems.reduce((sum, s) => sum + s.quantity, 0);\r\n\r\n if (this.state === LineItemState.CANCELLED) {\r\n this.total = {\r\n quantity: 0,\r\n unitPrice: zero,\r\n subtotal: zero,\r\n discountTotal: zero,\r\n discountBreakdown: {},\r\n netUnitPrice: zero,\r\n netSubtotal: zero,\r\n taxTotal: zero,\r\n taxBreakdown: {},\r\n grandTotal: zero\r\n };\r\n return;\r\n }\r\n\r\n const tierUnitPrice = this.pricing.tierPricing.getApplicableUnitPrice(totalQuantity, this.selectionAttributes);\r\n \r\n // Initial totals are treated as inclusive if the product is tax inclusive\r\n const initialSubTotal = tierUnitPrice.multiply(totalQuantity);\r\n const totalDiscount = Object.values(this.total.discountBreakdown).reduce((sum, s) => sum.add(s), zero);\r\n const initialNetSubtotal = initialSubTotal.subtract(totalDiscount);\r\n const initialNetUnitPrice = totalQuantity > 0 ? initialNetSubtotal.divide(totalQuantity) : zero;\r\n\r\n const taxBreakdown: Record<string, LineItemTaxBreakdownModel> = {};\r\n let taxTotal = zero;\r\n \r\n let finalUnitPrice = tierUnitPrice;\r\n let finalSubTotal = initialSubTotal;\r\n let finalNetSubtotal = initialNetSubtotal;\r\n let finalNetUnitPrice = initialNetUnitPrice;\r\n\r\n if (this.pricing.tierPricing.getIsTaxInclusive()) {\r\n // 1. Reverse calculate unit price for the base fields\r\n finalUnitPrice = extractExclusiveBase(tierUnitPrice, this.pricing.applicableTaxRule);\r\n finalSubTotal = finalUnitPrice.multiply(totalQuantity);\r\n\r\n // 2. Reverse calculate net unit price and distribute taxes perfectly\r\n if (initialNetUnitPrice.getAmount() > 0) {\r\n finalNetUnitPrice = extractExclusiveBase(initialNetUnitPrice, this.pricing.applicableTaxRule);\r\n finalNetSubtotal = finalNetUnitPrice.multiply(totalQuantity);\r\n\r\n const distributedTaxes = calculateDistributedTaxes(finalNetUnitPrice, initialNetUnitPrice, this.pricing.applicableTaxRule);\r\n \r\n distributedTaxes.forEach(dt => {\r\n const taxAmount = dt.taxAmount.multiply(totalQuantity).round();\r\n const taxRule = this.pricing.applicableTaxRule.find(r => r.getTaxRuleId() === dt.ruleId)!;\r\n \r\n taxBreakdown[dt.ruleId] = {\r\n rate: dt.rate,\r\n taxableUnitPrice: finalNetUnitPrice,\r\n taxPerUnit: dt.taxAmount,\r\n taxAmount: taxAmount,\r\n system: taxRule.getTaxSystem(),\r\n subSystem: taxRule.getTaxSubSystem()\r\n };\r\n taxTotal = taxTotal.add(taxAmount);\r\n });\r\n }\r\n } else {\r\n // Standard exclusive tax calculation\r\n this.pricing.applicableTaxRule.forEach(taxRule => {\r\n const rate = taxRule.getApplicableTaxRate(finalNetUnitPrice);\r\n const taxPerUnit = taxRule.calculateTax(finalNetUnitPrice);\r\n const taxAmount = taxPerUnit.multiply(totalQuantity).round();\r\n taxBreakdown[taxRule.getTaxRuleId()] = {\r\n rate: rate,\r\n taxableUnitPrice: finalNetUnitPrice,\r\n taxPerUnit: taxPerUnit,\r\n taxAmount: taxAmount,\r\n system: taxRule.getTaxSystem(),\r\n subSystem: taxRule.getTaxSubSystem()\r\n };\r\n taxTotal = taxTotal.add(taxAmount);\r\n });\r\n }\r\n\r\n const grandTotal = finalNetSubtotal.add(taxTotal);\r\n\r\n this.total = {\r\n quantity: totalQuantity,\r\n unitPrice: finalUnitPrice,\r\n subtotal: finalSubTotal,\r\n discountTotal: totalDiscount,\r\n discountBreakdown: this.total.discountBreakdown,\r\n netUnitPrice: finalNetUnitPrice,\r\n netSubtotal: finalNetSubtotal,\r\n taxTotal: taxTotal,\r\n taxBreakdown: taxBreakdown,\r\n grandTotal: grandTotal\r\n };\r\n }\r\n\r\n /**\r\n * Updates the line item's state.\r\n * @param newState \r\n */\r\n public updateState(newState: LineItemState): void {\r\n if (this.state in LineItemState) {\r\n if (this.state !== newState) {\r\n this.state = newState;\r\n }\r\n } else {\r\n throw new InvalidLineItemStateError(newState);\r\n }\r\n }\r\n\r\n /**\r\n * Resets the line item's properties to their default empty or initial state.\r\n * Useful for clearing out line item data without creating a new instance.\r\n * Recalculates total quantity and price total afterwards (which will be zero).\r\n */\r\n clearLineItem(): void {\r\n const zero = this.pricing.unitPrice.zero()\r\n this.id = '';\r\n this.productKey = '';\r\n this.sku = '';\r\n this.selectionAttributes = { color: { name: '' } };\r\n this.name = { en: '' };\r\n this.primaryImage = new ImageInfoModel({ sources: { original: '' } });\r\n this.subItems = [];\r\n this.productType = ProductType.GOODS;\r\n this.pricing = {\r\n unitPrice: zero,\r\n tierPricing: this.pricing.tierPricing,\r\n taxCategory: this.pricing.taxCategory,\r\n applicableTaxRule: []\r\n }\r\n this.total = {\r\n quantity: 0,\r\n unitPrice: zero,\r\n subtotal: zero,\r\n discountTotal: zero,\r\n discountBreakdown: {},\r\n netUnitPrice: zero,\r\n netSubtotal: zero,\r\n taxTotal: zero,\r\n taxBreakdown: {},\r\n grandTotal: zero\r\n };\r\n }\r\n}\r\n"]}
|
package/dist/chunk-SZLAIOMF.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {a}from'./chunk-NXDEYUDI.mjs';import {e}from'./chunk-MBR2GRKU.mjs';import {b as b$1}from'./chunk-HX32EJ3F.mjs';import {a as a$1}from'./chunk-5N2HRXWJ.mjs';import {a as a$2}from'./chunk-4PTWJI6J.mjs';import {a as a$3}from'./chunk-UIQH5QIR.mjs';import {b}from'./chunk-UXZBULDS.mjs';var B=class extends b{id;customerId;customerEmail;anonymousId;lineItems;charges;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;#t;constructor(t,e$1=new Date,a$4={checkCouponExpiry:!0}){super(t,e$1),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(o=>new a(o)),this.charges=(t.charges??[]).map(o=>new a$1(o)),this.billingAddress=t.billingAddress?new b$1(t.billingAddress,e$1):null,this.shippingAddress=t.shippingAddress?new b$1(t.shippingAddress,e$1):null,this.coupons=(t.coupons??[]).map(o=>new e(o)),this.shippingDetails=t.shippingDetails?a$2.deepClone(t.shippingDetails):null,this.total={lineItemSubtotal:new a$3(t.total.lineItemSubtotal),netLineItemSubtotal:new a$3(t.total.netLineItemSubtotal),lineItemTaxTotal:new a$3(t.total.lineItemTaxTotal),lineItemTaxBreakdown:this.mapTaxBreakdown(t.total.lineItemTaxBreakdown),additiveCharges:new a$3(t.total.additiveCharges),netAdditiveCharges:new a$3(t.total.netAdditiveCharges),additiveChargesTaxTotal:new a$3(t.total.additiveChargesTaxTotal),additiveChargesTaxBreakdown:this.mapTaxBreakdown(t.total.additiveChargesTaxBreakdown),adjustmentCharges:new a$3(t.total.adjustmentCharges),shippingCharges:new a$3(t.total.shippingCharges),netShippingCharges:new a$3(t.total.netShippingCharges),discountTotal:new a$3(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([o,n])=>[o,new a$3(n)])),taxTotal:new a$3(t.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(t.total.taxBreakdown),grandTotal:new a$3(t.total.grandTotal)},this.#t={checkCouponExpiry:a$4.checkCouponExpiry};}mapTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,a])=>[e,{system:a.system,totalAmount:new a$3(a.totalAmount),subSystems:Object.fromEntries(Object.entries(a.subSystems).map(([o,n])=>[o,new a$3(n)]))}]))}serializeTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,a])=>[e,{system:a.system,totalAmount:a.totalAmount.getDetails(),subSystems:Object.fromEntries(Object.entries(a.subSystems).map(([o,n])=>[o,n.getDetails()]))}]))}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new a(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(t=>new a$1(t.getDetails()))}addCharge(t){this.charges.push(t),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?a$2.deepClone(this.shippingDetails):null}getShippingAddress(){return this.shippingAddress?new b$1(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new b$1(this.billingAddress.getDetails()):null}getCoupons(){return [...this.coupons]}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {lineItemSubtotal:this.total.lineItemSubtotal,netLineItemSubtotal:this.total.netLineItemSubtotal,lineItemTaxTotal:this.total.lineItemTaxTotal,lineItemTaxBreakdown:Object.fromEntries(Object.entries(this.total.lineItemTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),additiveCharges:this.total.additiveCharges,netAdditiveCharges:this.total.netAdditiveCharges,additiveChargesTaxTotal:this.total.additiveChargesTaxTotal,additiveChargesTaxBreakdown:Object.fromEntries(Object.entries(this.total.additiveChargesTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),adjustmentCharges:this.total.adjustmentCharges,shippingCharges:this.total.shippingCharges,netShippingCharges:this.total.netShippingCharges,discountBreakdown:{...this.total.discountBreakdown},discountTotal:this.total.discountTotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),grandTotal:this.total.grandTotal}}getDetails(){let t=this.getTotal();return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(e=>e.getDetails()),charges:this.getCharges().map(e=>e.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(e=>e.getDetails()),total:{lineItemSubtotal:t.lineItemSubtotal.getDetails(),netLineItemSubtotal:t.netLineItemSubtotal.getDetails(),lineItemTaxTotal:t.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(t.lineItemTaxBreakdown),additiveCharges:t.additiveCharges.getDetails(),netAdditiveCharges:t.netAdditiveCharges.getDetails(),additiveChargesTaxTotal:t.additiveChargesTaxTotal.getDetails(),additiveChargesTaxBreakdown:this.serializeTaxBreakdown(t.additiveChargesTaxBreakdown),adjustmentCharges:t.adjustmentCharges.getDetails(),shippingCharges:t.shippingCharges.getDetails(),netShippingCharges:t.netShippingCharges.getDetails(),discountTotal:t.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(t.discountBreakdown).map(([e,a])=>[e,a.getDetails()])),taxTotal:t.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(t.taxBreakdown),grandTotal:t.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new a$3({amount:0,currency:this.currency}),e=this.lineItems.filter(i=>i.getState()!=="CANCELLED"),a=e.reduce((i,s)=>i.add(s.getTotal().subtotal),t),o=this.charges.filter(i=>i.getType()==="SHIPPING").reduce((i,s)=>i.add(s.getTotal().chargeAmount),t);this.total.lineItemSubtotal=a,this.total.shippingCharges=o;let n=t,l={},p={};this.coupons.forEach(i=>{let s=i.calculateApplicableCouponDiscount(a,o,this.country,this.currency,this.#t.checkCouponExpiry);n=n.add(s),l[i.getCode()]=s,i.getCategory()!=="SHIPPING"&&(p[i.getCode()]=s);}),this.total.discountTotal=n,this.total.discountBreakdown=l,this.applyDiscountsInLineItem(p);let h=this.coupons.find(i=>i.getCategory()==="SHIPPING");h?this.applyDiscountsInShippingCharges({[h.getCode()]:l[h.getCode()]||t}):this.applyDiscountsInShippingCharges({});let d=this.lineItems.reduce((i,s)=>i.add(s.getTotal().netSubtotal),t),c=this.charges.filter(i=>i.getType()==="SHIPPING").reduce((i,s)=>i.add(s.getTotal().grandTotal),t);this.total.netLineItemSubtotal=d,this.total.netShippingCharges=c;let g=this.charges.filter(i=>i.getImpact()==="ADD").reduce((i,s)=>i.add(s.getTotal().chargeAmount),t),m=this.charges.filter(i=>i.getImpact()==="ADD").reduce((i,s)=>i.add(s.getTotal().grandTotal),t),k=this.charges.filter(i=>i.getImpact()==="SUBTRACT").reduce((i,s)=>i.add(s.getTotal().grandTotal),t),f=t,C=t,I=t,b={},M={},P={},x=(i,s)=>{Object.entries(i).forEach(([O,T])=>{let u=T.system,S=T.subSystem;s[u]||(s[u]={system:u,totalAmount:t,subSystems:{}}),s[u].subSystems[S]?s[u].subSystems[S]=s[u].subSystems[S].add(T.taxAmount):s[u].subSystems[S]=T.taxAmount,s[u].totalAmount=s[u].totalAmount.add(T.taxAmount);});};e.forEach(i=>{let s=i.getTotal().taxBreakdown;s&&(x(s,M),x(s,b),C=C.add(i.getTotal().taxTotal));}),this.charges.forEach(i=>{let s=i.getTotal().taxBreakdown;s&&(x(s,P),x(s,b),I=I.add(i.getTotal().taxTotal));}),f=C.add(I);let L=d.add(C).add(m).subtract(k);this.total={lineItemSubtotal:a,netLineItemSubtotal:d,lineItemTaxTotal:C,lineItemTaxBreakdown:M,additiveCharges:g,netAdditiveCharges:m,additiveChargesTaxTotal:I,additiveChargesTaxBreakdown:P,adjustmentCharges:k,shippingCharges:o,netShippingCharges:c,discountTotal:n,discountBreakdown:l,taxTotal:f,taxBreakdown:b,grandTotal:L};}updateShippingDetails(t){this.shippingDetails=t;}applyCoupons(t){let e=t.filter(o=>o.getCategory()==="SHIPPING"),a=t.filter(o=>o.getCategory()!=="SHIPPING");this.coupons=[],this.total.discountTotal=this.total.lineItemSubtotal.zero(),this.total.discountBreakdown={},a.length&&this.applyNonShippingCoupons(a),this.applyDiscountsInLineItem(this.total.discountBreakdown),e.length&&this.applyShippingCoupons(e),this.calculateTotals();}applyDiscountsInLineItem(t){let e=Array.from(Object.entries(t)).filter(o=>!o[1].isZero()),a=new Map;this.lineItems.forEach(o=>a.set(o.getId(),[])),e.forEach(([o,n])=>{let l=this.coupons.find(d=>d.getCode()===o);if(!l||n.isZero())return;let p=this.lineItems.filter(d=>d.getState()!=="CANCELLED"&&!d.getTotal().subtotal.isZero()).sort((d,c)=>d.getTotal().subtotal.compareTo(c.getTotal().subtotal)),h=new a$3({amount:0,currency:this.currency});p.forEach((d,c)=>{let g;c===p.length-1?g=n.subtract(h):g=n.multiply(d.getTotal().subtotal).divide(this.total.lineItemSubtotal).round(),h=h.add(g),a.get(d.getId())?.push({coupon:l,amount:g});});}),this.lineItems.forEach(o=>{o.getState()==="CANCELLED"||this.total.lineItemSubtotal.isZero()?o.updateDiscounts([]):o.updateDiscounts(a.get(o.getId())||[]);});}applyDiscountsInShippingCharges(t){let e=Array.from(Object.entries(t)).filter(n=>!n[1].isZero()),a=this.charges.filter(n=>n.getType()==="SHIPPING"),o=new Map;a.forEach(n=>o.set(n.getId(),[])),e.forEach(([n,l])=>{let p=this.coupons.find(c=>c.getCode()===n);if(!p||l.isZero())return;let h=a.sort((c,g)=>c.getTotal().grandTotal.compareTo(g.getTotal().grandTotal)),d=new a$3({amount:0,currency:this.currency});h.forEach((c,g)=>{let m;g===h.length-1?m=l.subtract(d):m=l.multiply(c.getTotal().chargeAmount).divide(this.total.shippingCharges).round(),d=d.add(m),o.get(c.getId())?.push({coupon:p,amount:m});});}),a.forEach(n=>{n.updateDiscounts(o.get(n.getId())||[]);});}applyNonShippingCoupons(t){let e=t.filter(a=>a.getType()==="coupon");if(e.length===1){let a=e[0].calculateApplicableCouponDiscount(this.total.lineItemSubtotal,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry);a.getAmount()>0&&(this.coupons.push(e[0]),this.total.discountTotal=a,this.total.discountBreakdown[e[0].getCode()]=a);}}applyShippingCoupons(t){if(this.total.shippingCharges.getAmount()>0&&t.length>0){let e=this.total.lineItemSubtotal.subtract(this.total.discountTotal),a=t.reduce((n,l)=>{if(!n)return l;let p=l.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry).min(this.total.shippingCharges),h=n.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry).min(this.total.shippingCharges);return p.compareTo(h)===0?l.getType()==="coupon"?l:n:p.compareTo(h)>0?l:n}),o=a.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry).min(this.total.shippingCharges);o.getAmount()>0&&(this.coupons.push(a),this.total.discountTotal=this.total.discountTotal.add(o),this.total.discountBreakdown[a.getCode()]=o);}}};export{B as a};//# sourceMappingURL=chunk-SZLAIOMF.mjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-SZLAIOMF.mjs.map
|