b23-lib 2.1.7 → 3.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/Classes/Cart.d.mts +1 -0
- package/dist/Classes/Cart.d.ts +1 -0
- package/dist/Classes/Cart.js +1 -2
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Cart.mjs.map +1 -1
- package/dist/Classes/Charge.d.mts +99 -0
- package/dist/Classes/Charge.d.ts +99 -0
- package/dist/Classes/Charge.js +2 -0
- package/dist/Classes/Charge.js.map +1 -0
- package/dist/Classes/Charge.mjs +2 -0
- package/dist/Classes/Charge.mjs.map +1 -0
- 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/Enum.d.mts +4 -4
- package/dist/Classes/Enum.d.ts +4 -4
- package/dist/Classes/Enum.js +1 -1
- package/dist/Classes/Enum.js.map +1 -1
- package/dist/Classes/Enum.mjs +1 -1
- package/dist/Classes/Error.d.mts +4 -1
- package/dist/Classes/Error.d.ts +4 -1
- package/dist/Classes/Error.js +1 -1
- package/dist/Classes/Error.js.map +1 -1
- package/dist/Classes/Error.mjs +1 -1
- package/dist/Classes/ImageInfo.js.map +1 -1
- package/dist/Classes/ImageInfo.mjs +1 -1
- package/dist/Classes/Inventory.js +1 -1
- package/dist/Classes/Inventory.js.map +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/LineItem.d.mts +46 -48
- package/dist/Classes/LineItem.d.ts +46 -48
- package/dist/Classes/LineItem.js +1 -2
- package/dist/Classes/LineItem.js.map +1 -1
- package/dist/Classes/LineItem.mjs +1 -1
- package/dist/Classes/Order.d.mts +1 -1
- package/dist/Classes/Order.d.ts +1 -1
- package/dist/Classes/Order.js +1 -2
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/Order.mjs.map +1 -1
- package/dist/Classes/Price.js +1 -1
- package/dist/Classes/Price.js.map +1 -1
- package/dist/Classes/Price.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 +98 -40
- package/dist/Classes/ShoppingContainer.d.ts +98 -40
- package/dist/Classes/ShoppingContainer.js +1 -2
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/Classes/TaxCategoryModel.d.mts +42 -0
- package/dist/Classes/TaxCategoryModel.d.ts +42 -0
- package/dist/Classes/TaxCategoryModel.js +2 -0
- package/dist/Classes/TaxCategoryModel.js.map +1 -0
- package/dist/Classes/TaxCategoryModel.mjs +2 -0
- package/dist/Classes/TaxCategoryModel.mjs.map +1 -0
- package/dist/Classes/TaxRule.d.mts +59 -79
- package/dist/Classes/TaxRule.d.ts +59 -79
- package/dist/Classes/TaxRule.js +1 -2
- package/dist/Classes/TaxRule.js.map +1 -1
- package/dist/Classes/TaxRule.mjs +1 -1
- package/dist/Classes/TieredPrice.d.mts +4 -4
- package/dist/Classes/TieredPrice.d.ts +4 -4
- 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-TJ7AZBND.mjs → chunk-6X5O25W5.mjs} +2 -2
- package/dist/chunk-6X5O25W5.mjs.map +1 -0
- package/dist/chunk-FC4P26U3.mjs +2 -0
- package/dist/chunk-FC4P26U3.mjs.map +1 -0
- package/dist/chunk-IIPG3DTO.mjs +2 -0
- package/dist/chunk-IIPG3DTO.mjs.map +1 -0
- package/dist/{chunk-AWZ6KRLF.mjs → chunk-JE7BAYI5.mjs} +2 -2
- package/dist/{chunk-AWZ6KRLF.mjs.map → chunk-JE7BAYI5.mjs.map} +1 -1
- package/dist/chunk-KKQLCW6A.mjs +2 -0
- package/dist/chunk-KKQLCW6A.mjs.map +1 -0
- package/dist/chunk-PTIPDRB4.mjs +2 -0
- package/dist/chunk-PTIPDRB4.mjs.map +1 -0
- package/dist/{chunk-WS7ZY5ZZ.mjs → chunk-RSMXGZD4.mjs} +2 -2
- package/dist/{chunk-WS7ZY5ZZ.mjs.map → chunk-RSMXGZD4.mjs.map} +1 -1
- package/dist/{chunk-WSUPVXRZ.mjs → chunk-RSTZJZSQ.mjs} +2 -2
- package/dist/{chunk-WSUPVXRZ.mjs.map → chunk-RSTZJZSQ.mjs.map} +1 -1
- package/dist/chunk-U7DES3CI.mjs +2 -0
- package/dist/chunk-U7DES3CI.mjs.map +1 -0
- package/dist/{chunk-JHELVQYY.mjs → chunk-XPKK6DFA.mjs} +2 -2
- package/dist/chunk-XPKK6DFA.mjs.map +1 -0
- package/dist/chunk-XXETAAL4.mjs +2 -0
- package/dist/chunk-XXETAAL4.mjs.map +1 -0
- package/dist/index.d.mts +1 -5
- package/dist/index.d.ts +1 -5
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +11 -1
- package/dist/chunk-232FJYNB.mjs +0 -2
- package/dist/chunk-232FJYNB.mjs.map +0 -1
- package/dist/chunk-72DR3HF2.mjs +0 -2
- package/dist/chunk-72DR3HF2.mjs.map +0 -1
- package/dist/chunk-ARMBZF3E.mjs +0 -3
- package/dist/chunk-ARMBZF3E.mjs.map +0 -1
- package/dist/chunk-JHELVQYY.mjs.map +0 -1
- package/dist/chunk-SFUOYZ3L.mjs +0 -2
- package/dist/chunk-SFUOYZ3L.mjs.map +0 -1
- package/dist/chunk-TJ7AZBND.mjs.map +0 -1
- package/dist/chunk-ZE7D77FR.mjs +0 -2
- package/dist/chunk-ZE7D77FR.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export{d as Fetch,b as Logger,c as ResponseUtility}from'./chunk-AMIRIUMH.mjs';import {b}from'./chunk-
|
|
2
|
-
export{
|
|
1
|
+
export{d as Fetch,b as Logger,c as ResponseUtility}from'./chunk-AMIRIUMH.mjs';import {b}from'./chunk-JE7BAYI5.mjs';export{a as Utils}from'./chunk-JE7BAYI5.mjs';import'./chunk-U7DES3CI.mjs';import'./chunk-6X5O25W5.mjs';import {j,a,b as b$1,c as c$1,d}from'./chunk-FC4P26U3.mjs';import'./chunk-RSTZJZSQ.mjs';import'./chunk-XPKK6DFA.mjs';import'./chunk-6KCJVEZD.mjs';var p={$id:"standards",definitions:{lowercaseText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]*$"},lowercaseText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,10}$"},lowercaseText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,16}$"},lowercaseText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,30}$"},lowercaseText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,50}$"},lowercaseText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,256}$"},text:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).*$"},text10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,10}$"},text16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,16}$"},text30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,30}$"},text50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,50}$"},text256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,256}$"},requiredText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).+$"},requiredText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,10}$"},requiredText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,16}$"},requiredText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,30}$"},requiredText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,50}$"},requiredText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,256}$"},url:{type:"string",pattern:"^https://[^\\s/$.?#].[^\\s]*$",maxLength:2048},uuid:{type:"string",minLength:1,pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"},productKey:{type:"string",pattern:b.productKeyRegex.source},productSku:{type:"string",pattern:b.productSKURegex.source},genderCategory:{type:"string",enum:Object.values(j)},price:{type:"object",properties:{amount:{type:"number",minimum:0},currency:{$ref:"#/definitions/currency"}},additionalProperties:!1,required:["amount","currency"]},color:{type:"object",properties:{name:{type:"string"},hex:{type:"string"}},additionalProperties:!1,required:["name"]},attributeValue:{oneOf:[{type:"string"},{$ref:"#/definitions/color"}]},selectionAttributes:{type:"object",properties:{color:{$ref:"#/definitions/color"}},required:["color"],additionalProperties:{$ref:"#/definitions/attributeValue"}},firstName:{$ref:"#/definitions/requiredText30"},lastName:{$ref:"#/definitions/text30"},company:{$ref:"#/definitions/text50"},phone:{type:"string",pattern:"^[0-9]{10}$"},email:{type:"string",pattern:"^[^\\s]+@[^\\s]+\\.[^\\s]+$"},addressLine1:{$ref:"#/definitions/requiredText50"},addressLine2:{$ref:"#/definitions/text50"},city:{$ref:"#/definitions/requiredText30"},postalCode:{$ref:"#/definitions/requiredText16"},state:{type:"string",enum:["AP","AR","AS","BR","CT","GA","GJ","HR","HP","JH","KA","KL","MP","MH","MN","ML","MZ","NL","OR","PB","RJ","SK","TN","TG","TR","UP","UT","WB","AN","CH","DH","LD","DL","PY","LA","JK"]},country:{type:"string",enum:Object.values(a)},currency:{type:"string",enum:Object.values(b$1)},locale:{type:"string",enum:Object.values(c$1)},language:{type:"string",enum:Object.values(d)},localeOrLanguage:{type:"string",enum:[...Object.values(c$1),...Object.values(d)]},addressType:{type:"string",enum:["shipping","billing","billing&shipping"]},address:{type:"object",properties:{firstName:{$ref:"standards#/definitions/firstName"},lastName:{$ref:"standards#/definitions/lastName"},company:{$ref:"standards#/definitions/company"},phone:{$ref:"standards#/definitions/phone"},email:{$ref:"standards#/definitions/email"},addressLine1:{$ref:"standards#/definitions/addressLine1"},addressLine2:{$ref:"standards#/definitions/addressLine2"},city:{$ref:"standards#/definitions/city"},postalCode:{$ref:"standards#/definitions/postalCode"},state:{$ref:"standards#/definitions/state"},country:{$ref:"standards#/definitions/country"}},required:["firstName","lastName","phone","email","addressLine1","postalCode","state","country"]}}};var $={getStandardSchemaDefinition(){return p}},c=$;
|
|
2
|
+
export{c as Schema};//# sourceMappingURL=index.mjs.map
|
|
3
3
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Schema/definition.ts","../src/Schema/index.ts"],"names":["definition_default","ProductModel","TaxCategory","GenderCategory","OperationalCountry","OperationalCountryCurrency","OperationalLocale","OperationalLanguage","Schema","Schema_default"],"mappings":"qXAGA,IAAOA,CAAQ,CAAA,CACb,GAAO,CAAA,WAAA,CACP,WAAe,CAAA,CACX,aAAiB,CAAA,CACb,IAAQ,CAAA,QAAA,CACR,OAAW,CAAA,2BACf,CACA,CAAA,eAAA,CAAmB,CACf,IAAA,CAAQ,QACR,CAAA,OAAA,CAAW,gCACf,CAAA,CACA,eAAmB,CAAA,CACf,IAAQ,CAAA,QAAA,CACR,OAAW,CAAA,gCACf,CACA,CAAA,eAAA,CAAmB,CACf,IAAA,CAAQ,QACR,CAAA,OAAA,CAAW,gCACf,CAAA,CACA,eAAmB,CAAA,CACf,IAAQ,CAAA,QAAA,CACR,OAAW,CAAA,gCACf,CACA,CAAA,gBAAA,CAAoB,CAChB,IAAA,CAAQ,QACR,CAAA,OAAA,CAAW,iCACf,CAAA,CACA,IAAQ,CAAA,CACJ,IAAQ,C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AQ,CAAA,CAAC,GAAG,MAAA,CAAO,MAAOD,CAAAA,CAAiB,CAAG,CAAA,GAAG,MAAO,CAAA,MAAA,CAAOC,GAAmB,CAAC,CACxF,CACA,CAAA,WAAA,CAAe,CACX,IAAA,CAAQ,QACR,CAAA,IAAA,CAAQ,CAAC,UAAA,CAAY,SAAW,CAAA,kBAAkB,CACtD,CAAA,CACA,OAAW,CAAA,CACP,IAAQ,CAAA,QAAA,CACR,UAAc,CAAA,CACV,SAAa,CAAA,CAAC,IAAQ,CAAA,kCAAkC,CACxD,CAAA,QAAA,CAAY,CAAE,IAAA,CAAQ,iCAAkC,CAAA,CACxD,OAAW,CAAA,CAAE,KAAQ,gCAAiC,CAAA,CACtD,KAAS,CAAA,CAAE,IAAQ,CAAA,8BAA+B,CAClD,CAAA,KAAA,CAAS,CAAE,IAAA,CAAQ,8BAA+B,CAAA,CAClD,YAAgB,CAAA,CAAE,IAAQ,CAAA,qCAAsC,CAChE,CAAA,YAAA,CAAgB,CAAE,IAAA,CAAQ,qCAAsC,CAAA,CAChE,IAAQ,CAAA,CAAE,IAAQ,CAAA,6BAA8B,CAChD,CAAA,UAAA,CAAc,CAAE,IAAA,CAAQ,mCAAoC,CAAA,CAC5D,MAAS,CAAE,IAAA,CAAQ,8BAA+B,CAAA,CAClD,OAAW,CAAA,CAAE,IAAQ,CAAA,gCAAiC,CAC1D,CAAA,CACA,QAAY,CAAA,CAAC,WAAa,CAAA,UAAA,CAAY,OAAS,CAAA,OAAA,CAAS,cAAgB,CAAA,YAAA,CAAc,OAAS,CAAA,SAAS,CAC5G,CACJ,CACF,CAAA,CC7MMC,IAAAA,CAAAA,CAAS,CACb,2BAAA,EAA8B,CAC5B,OAAOR,CACT,CACF,EAEOS,CAAQD,CAAAA","file":"index.mjs","sourcesContent":["import { GenderCategory, OperationalCountry, OperationalCountryCurrency, OperationalLanguage, OperationalLocale, TaxCategory } from \"../Classes/Enum\";\r\nimport ProductModel from \"../Classes/Product\";\r\n\r\nexport default {\r\n \"$id\": \"standards\",\r\n \"definitions\": {\r\n \"lowercaseText\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$)[a-z]*$\"\r\n },\r\n \"lowercaseText10\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$)[a-z]{0,10}$\"\r\n },\r\n \"lowercaseText16\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$)[a-z]{0,16}$\"\r\n },\r\n \"lowercaseText30\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$)[a-z]{0,30}$\"\r\n },\r\n \"lowercaseText50\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$)[a-z]{0,50}$\"\r\n },\r\n \"lowercaseText256\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$)[a-z]{0,256}$\"\r\n },\r\n \"text\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).*$\"\r\n },\r\n \"text10\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{0,10}$\"\r\n },\r\n \"text16\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{0,16}$\"\r\n },\r\n \"text30\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{0,30}$\"\r\n },\r\n \"text50\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{0,50}$\"\r\n },\r\n \"text256\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{0,256}$\"\r\n },\r\n \"requiredText\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).+$\"\r\n },\r\n \"requiredText10\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{1,10}$\"\r\n },\r\n \"requiredText16\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{1,16}$\"\r\n },\r\n \"requiredText30\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{1,30}$\"\r\n },\r\n \"requiredText50\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{1,50}$\"\r\n },\r\n \"requiredText256\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{1,256}$\"\r\n },\r\n \"url\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^https://[^\\\\s/$.?#].[^\\\\s]*$\",\r\n \"maxLength\": 2048\r\n },\r\n \"uuid\": {\r\n \"type\": \"string\",\r\n \"minLength\": 1,\r\n \"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}$\"\r\n },\r\n \"productKey\": {\r\n \"type\": \"string\",\r\n \"pattern\": ProductModel.productKeyRegex.source\r\n },\r\n \"productSku\": {\r\n \"type\": \"string\",\r\n \"pattern\": ProductModel.productSKURegex.source\r\n },\r\n \"taxCategory\": {\r\n \"type\": \"string\",\r\n \"enum\": Object.values(TaxCategory)\r\n },\r\n \"genderCategory\": {\r\n \"type\": \"string\",\r\n \"enum\": Object.values(GenderCategory)\r\n },\r\n \"price\": {\r\n \"type\": \"object\",\r\n \"properties\": {\r\n \"amount\": { \"type\": \"number\", \"minimum\": 0 },\r\n \"currency\": { \"$ref\": \"#/definitions/currency\" }\r\n },\r\n \"additionalProperties\": false,\r\n \"required\": [\"amount\", \"currency\"]\r\n },\r\n \"color\": {\r\n \"type\": \"object\",\r\n \"properties\": {\r\n \"name\": {\r\n \"type\": \"string\"\r\n },\r\n \"hex\": {\r\n \"type\": \"string\"\r\n }\r\n },\r\n \"additionalProperties\": false,\r\n \"required\": [\r\n \"name\"\r\n ]\r\n },\r\n \"attributeValue\": {\r\n \"oneOf\": [\r\n { \"type\": \"string\" },\r\n {\r\n \"$ref\": \"#/definitions/color\"\r\n }\r\n ]\r\n },\r\n \"selectionAttributes\": {\r\n \"type\": \"object\",\r\n \"properties\": {\r\n \"color\": { \"$ref\": \"#/definitions/color\" }\r\n },\r\n \"required\": [\"color\"],\r\n \"additionalProperties\": {\r\n \"$ref\": \"#/definitions/attributeValue\"\r\n }\r\n },\r\n \"firstName\": { \"$ref\": \"#/definitions/requiredText30\" },\r\n \"lastName\": { \"$ref\": \"#/definitions/text30\" },\r\n \"company\": { \"$ref\": \"#/definitions/text50\" },\r\n \"phone\": { \r\n \"type\" : \"string\",\r\n \"pattern\": \"^[0-9]{10}$\"\r\n },\r\n \"email\": { \r\n \"type\" : \"string\",\r\n \"pattern\": \"^[^\\\\s]+@[^\\\\s]+\\\\.[^\\\\s]+$\"\r\n },\r\n \"addressLine1\": { \"$ref\": \"#/definitions/requiredText50\" },\r\n \"addressLine2\": { \"$ref\": \"#/definitions/text50\" },\r\n \"city\": { \"$ref\": \"#/definitions/requiredText30\" },\r\n \"postalCode\": { \"$ref\": \"#/definitions/requiredText16\" },\r\n \"state\": {\r\n \"type\": \"string\",\r\n \"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\"]\r\n },\r\n \"country\": {\r\n \"type\": \"string\",\r\n \"enum\": Object.values(OperationalCountry)\r\n },\r\n \"currency\": {\r\n \"type\": \"string\",\r\n \"enum\": Object.values(OperationalCountryCurrency)\r\n },\r\n \"locale\": {\r\n \"type\": \"string\",\r\n \"enum\": Object.values(OperationalLocale)\r\n },\r\n \"language\": {\r\n \"type\": \"string\",\r\n \"enum\": Object.values(OperationalLanguage)\r\n },\r\n \"localeOrLanguage\": {\r\n \"type\": \"string\",\r\n \"enum\": [...Object.values(OperationalLocale), ...Object.values(OperationalLanguage)]\r\n },\r\n \"addressType\": {\r\n \"type\": \"string\",\r\n \"enum\": [\"shipping\", \"billing\", \"billing&shipping\"]\r\n },\r\n \"address\": {\r\n \"type\": \"object\",\r\n \"properties\": {\r\n \"firstName\": {\"$ref\": \"standards#/definitions/firstName\"},\r\n \"lastName\": { \"$ref\": \"standards#/definitions/lastName\" },\r\n \"company\": { \"$ref\": \"standards#/definitions/company\" },\r\n \"phone\": { \"$ref\": \"standards#/definitions/phone\" },\r\n \"email\": { \"$ref\": \"standards#/definitions/email\" },\r\n \"addressLine1\": { \"$ref\": \"standards#/definitions/addressLine1\" },\r\n \"addressLine2\": { \"$ref\": \"standards#/definitions/addressLine2\" },\r\n \"city\": { \"$ref\": \"standards#/definitions/city\" },\r\n \"postalCode\": { \"$ref\": \"standards#/definitions/postalCode\" },\r\n \"state\": { \"$ref\": \"standards#/definitions/state\" },\r\n \"country\": { \"$ref\": \"standards#/definitions/country\" }\r\n },\r\n \"required\": [\"firstName\", \"lastName\", \"phone\", \"email\", \"addressLine1\", \"postalCode\", \"state\", \"country\"]\r\n }\r\n }\r\n}","import SchemaDefinitions from './definition';\r\n\r\nconst Schema = {\r\n getStandardSchemaDefinition() {\r\n return SchemaDefinitions;\r\n }\r\n}\r\n\r\nexport default Schema;\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/Schema/definition.ts","../src/Schema/index.ts"],"names":["definition_default","ProductModel","GenderCategory","OperationalCountry","OperationalCountryCurrency","OperationalLocale","OperationalLanguage","Schema","Schema_default"],"mappings":"4WAGA,IAAOA,CAAQ,CAAA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AAA,CAClD,OAAW,CAAA,CAAE,IAAQ,CAAA,gCAAiC,CAC1D,CAAA,CACA,QAAY,CAAA,CAAC,WAAa,CAAA,UAAA,CAAY,OAAS,CAAA,OAAA,CAAS,cAAgB,CAAA,YAAA,CAAc,OAAS,CAAA,SAAS,CAC5G,CACJ,CACF,CAAA,CCzMMC,IAAAA,CAAAA,CAAS,CACb,2BAAA,EAA8B,CAC5B,OAAOP,CACT,CACF,EAEOQ,CAAQD,CAAAA","file":"index.mjs","sourcesContent":["import { GenderCategory, OperationalCountry, OperationalCountryCurrency, OperationalLanguage, OperationalLocale } from \"../Classes/Enum\";\r\nimport ProductModel from \"../Classes/Product\";\r\n\r\nexport default {\r\n \"$id\": \"standards\",\r\n \"definitions\": {\r\n \"lowercaseText\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$)[a-z]*$\"\r\n },\r\n \"lowercaseText10\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$)[a-z]{0,10}$\"\r\n },\r\n \"lowercaseText16\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$)[a-z]{0,16}$\"\r\n },\r\n \"lowercaseText30\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$)[a-z]{0,30}$\"\r\n },\r\n \"lowercaseText50\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$)[a-z]{0,50}$\"\r\n },\r\n \"lowercaseText256\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$)[a-z]{0,256}$\"\r\n },\r\n \"text\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).*$\"\r\n },\r\n \"text10\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{0,10}$\"\r\n },\r\n \"text16\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{0,16}$\"\r\n },\r\n \"text30\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{0,30}$\"\r\n },\r\n \"text50\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{0,50}$\"\r\n },\r\n \"text256\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{0,256}$\"\r\n },\r\n \"requiredText\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).+$\"\r\n },\r\n \"requiredText10\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{1,10}$\"\r\n },\r\n \"requiredText16\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{1,16}$\"\r\n },\r\n \"requiredText30\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{1,30}$\"\r\n },\r\n \"requiredText50\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{1,50}$\"\r\n },\r\n \"requiredText256\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^(?!\\\\s)(?!.*\\\\s$).{1,256}$\"\r\n },\r\n \"url\": {\r\n \"type\": \"string\",\r\n \"pattern\": \"^https://[^\\\\s/$.?#].[^\\\\s]*$\",\r\n \"maxLength\": 2048\r\n },\r\n \"uuid\": {\r\n \"type\": \"string\",\r\n \"minLength\": 1,\r\n \"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}$\"\r\n },\r\n \"productKey\": {\r\n \"type\": \"string\",\r\n \"pattern\": ProductModel.productKeyRegex.source\r\n },\r\n \"productSku\": {\r\n \"type\": \"string\",\r\n \"pattern\": ProductModel.productSKURegex.source\r\n },\r\n \"genderCategory\": {\r\n \"type\": \"string\",\r\n \"enum\": Object.values(GenderCategory)\r\n },\r\n \"price\": {\r\n \"type\": \"object\",\r\n \"properties\": {\r\n \"amount\": { \"type\": \"number\", \"minimum\": 0 },\r\n \"currency\": { \"$ref\": \"#/definitions/currency\" }\r\n },\r\n \"additionalProperties\": false,\r\n \"required\": [\"amount\", \"currency\"]\r\n },\r\n \"color\": {\r\n \"type\": \"object\",\r\n \"properties\": {\r\n \"name\": {\r\n \"type\": \"string\"\r\n },\r\n \"hex\": {\r\n \"type\": \"string\"\r\n }\r\n },\r\n \"additionalProperties\": false,\r\n \"required\": [\r\n \"name\"\r\n ]\r\n },\r\n \"attributeValue\": {\r\n \"oneOf\": [\r\n { \"type\": \"string\" },\r\n {\r\n \"$ref\": \"#/definitions/color\"\r\n }\r\n ]\r\n },\r\n \"selectionAttributes\": {\r\n \"type\": \"object\",\r\n \"properties\": {\r\n \"color\": { \"$ref\": \"#/definitions/color\" }\r\n },\r\n \"required\": [\"color\"],\r\n \"additionalProperties\": {\r\n \"$ref\": \"#/definitions/attributeValue\"\r\n }\r\n },\r\n \"firstName\": { \"$ref\": \"#/definitions/requiredText30\" },\r\n \"lastName\": { \"$ref\": \"#/definitions/text30\" },\r\n \"company\": { \"$ref\": \"#/definitions/text50\" },\r\n \"phone\": { \r\n \"type\" : \"string\",\r\n \"pattern\": \"^[0-9]{10}$\"\r\n },\r\n \"email\": { \r\n \"type\" : \"string\",\r\n \"pattern\": \"^[^\\\\s]+@[^\\\\s]+\\\\.[^\\\\s]+$\"\r\n },\r\n \"addressLine1\": { \"$ref\": \"#/definitions/requiredText50\" },\r\n \"addressLine2\": { \"$ref\": \"#/definitions/text50\" },\r\n \"city\": { \"$ref\": \"#/definitions/requiredText30\" },\r\n \"postalCode\": { \"$ref\": \"#/definitions/requiredText16\" },\r\n \"state\": {\r\n \"type\": \"string\",\r\n \"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\"]\r\n },\r\n \"country\": {\r\n \"type\": \"string\",\r\n \"enum\": Object.values(OperationalCountry)\r\n },\r\n \"currency\": {\r\n \"type\": \"string\",\r\n \"enum\": Object.values(OperationalCountryCurrency)\r\n },\r\n \"locale\": {\r\n \"type\": \"string\",\r\n \"enum\": Object.values(OperationalLocale)\r\n },\r\n \"language\": {\r\n \"type\": \"string\",\r\n \"enum\": Object.values(OperationalLanguage)\r\n },\r\n \"localeOrLanguage\": {\r\n \"type\": \"string\",\r\n \"enum\": [...Object.values(OperationalLocale), ...Object.values(OperationalLanguage)]\r\n },\r\n \"addressType\": {\r\n \"type\": \"string\",\r\n \"enum\": [\"shipping\", \"billing\", \"billing&shipping\"]\r\n },\r\n \"address\": {\r\n \"type\": \"object\",\r\n \"properties\": {\r\n \"firstName\": {\"$ref\": \"standards#/definitions/firstName\"},\r\n \"lastName\": { \"$ref\": \"standards#/definitions/lastName\" },\r\n \"company\": { \"$ref\": \"standards#/definitions/company\" },\r\n \"phone\": { \"$ref\": \"standards#/definitions/phone\" },\r\n \"email\": { \"$ref\": \"standards#/definitions/email\" },\r\n \"addressLine1\": { \"$ref\": \"standards#/definitions/addressLine1\" },\r\n \"addressLine2\": { \"$ref\": \"standards#/definitions/addressLine2\" },\r\n \"city\": { \"$ref\": \"standards#/definitions/city\" },\r\n \"postalCode\": { \"$ref\": \"standards#/definitions/postalCode\" },\r\n \"state\": { \"$ref\": \"standards#/definitions/state\" },\r\n \"country\": { \"$ref\": \"standards#/definitions/country\" }\r\n },\r\n \"required\": [\"firstName\", \"lastName\", \"phone\", \"email\", \"addressLine1\", \"postalCode\", \"state\", \"country\"]\r\n }\r\n }\r\n}","import SchemaDefinitions from './definition';\r\n\r\nconst Schema = {\r\n getStandardSchemaDefinition() {\r\n return SchemaDefinitions;\r\n }\r\n}\r\n\r\nexport default Schema;\r\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "b23-lib",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0",
|
|
4
4
|
"description": "This repo hold common classes, type and util functiona",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.mjs",
|
|
@@ -136,6 +136,16 @@
|
|
|
136
136
|
"default": "./dist/Classes/LineItem.js"
|
|
137
137
|
}
|
|
138
138
|
},
|
|
139
|
+
"./charge": {
|
|
140
|
+
"import": {
|
|
141
|
+
"types": "./dist/Classes/Charge.d.mts",
|
|
142
|
+
"default": "./dist/Classes/Charge.mjs"
|
|
143
|
+
},
|
|
144
|
+
"require": {
|
|
145
|
+
"types": "./dist/Classes/Charge.d.ts",
|
|
146
|
+
"default": "./dist/Classes/Charge.js"
|
|
147
|
+
}
|
|
148
|
+
},
|
|
139
149
|
"./order": {
|
|
140
150
|
"import": {
|
|
141
151
|
"types": "./dist/Classes/Order.d.mts",
|
package/dist/chunk-232FJYNB.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {a}from'./chunk-ZE7D77FR.mjs';import {b as b$1}from'./chunk-YSUBOEFT.mjs';import {e}from'./chunk-WS7ZY5ZZ.mjs';import {a as a$1}from'./chunk-AWZ6KRLF.mjs';import {a as a$2}from'./chunk-TJ7AZBND.mjs';import {b}from'./chunk-6KCJVEZD.mjs';var D=class extends b{id;customerId;customerEmail;anonymousId;lineItems;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,i=new Date){super(t,i),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.billingAddress=t.billingAddress?new b$1(t.billingAddress,i):null,this.shippingAddress=t.shippingAddress?new b$1(t.shippingAddress,i):null,this.coupons=(t.coupons??[]).map(o=>new e(o)),this.shippingDetails=t.shippingDetails?a$1.deepClone(t.shippingDetails):null,this.total={subtotal:new a$2(t.total.subtotal),shipping:new a$2(t.total.shipping),effectiveShipping:new a$2(t.total.effectiveShipping),taxTotal:new a$2(t.total.taxTotal),couponTotal:Object.fromEntries(Object.entries(t.total.couponTotal).map(([o,e])=>[o,new a$2(e)])),couponDiscountTotal:new a$2(t.total.couponDiscountTotal),grandTotal:new a$2(t.total.grandTotal)};}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}getShippingDetails(){return this.shippingDetails?{...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 this.total}getDetails(){return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(t=>t.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(t=>t.getDetails()),total:{subtotal:this.getTotal().subtotal.getDetails(),shipping:this.getTotal().shipping.getDetails(),effectiveShipping:this.getTotal().effectiveShipping.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),couponTotal:Object.fromEntries(Object.entries(this.getTotal().couponTotal).map(([t,i])=>[t,i.getDetails()])),couponDiscountTotal:this.getTotal().couponDiscountTotal.getDetails(),grandTotal:this.getTotal().grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new a$2({amount:0,currency:this.currency}),i=this.lineItems.filter(r=>r.getState()!=="CANCELLED"),o=i.reduce((r,c)=>r.add(c.getTotal().subtotal),t),e=new a$2({amount:this.shippingDetails?.cost||0,currency:this.currency}).round(),s=t,n={},u={};this.coupons.forEach(r=>{let c=r.calculateApplicableCouponDiscount(o,e,this.country,this.currency);s=s.add(c),n[r.getCode()]=c,r.getCategory()!=="SHIPPING"&&(u[r.getCode()]=c);}),this.applyDiscountsInLineItem(u);let p=i.reduce((r,c)=>r.add(c.getTotal().taxTotal),t),l=this.coupons.find(r=>r.getCategory()==="SHIPPING"),h=l?e.subtract(n[l.getCode()]||t):e,g=o.add(e).add(p).subtract(s);this.total={subtotal:o,shipping:e,effectiveShipping:h,couponTotal:n,couponDiscountTotal:s,taxTotal:p,grandTotal:g};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let i=t.filter(e=>e.getCategory()==="SHIPPING"),o=t.filter(e=>e.getCategory()!=="SHIPPING");this.coupons=[],this.total.couponDiscountTotal=this.total.subtotal.zero(),this.total.couponTotal={},o.length&&this.applyNonShippingCoupons(o),this.applyDiscountsInLineItem(this.total.couponTotal),i.length&&this.applyShippingCoupons(i),this.calculateTotals();}applyDiscountsInLineItem(t){let i=Array.from(Object.entries(t)).filter(e=>!e[1].isZero()),o=new Map;this.lineItems.forEach(e=>o.set(e.getId(),[])),i.forEach(([e,s])=>{let n=this.coupons.find(l=>l.getCode()===e);if(!n||s.isZero())return;let u=this.lineItems.filter(l=>l.getState()!=="CANCELLED"&&!l.getTotal().subtotal.isZero()).sort((l,h)=>l.getTotal().subtotal.compareTo(h.getTotal().subtotal)),p=new a$2({amount:0,currency:this.currency});u.forEach((l,h)=>{let g;h===u.length-1?g=s.subtract(p):g=s.multiply(l.getTotal().subtotal).divide(this.total.subtotal).round(),p=p.add(g),o.get(l.getId())?.push({coupon:n,amount:g});});}),this.lineItems.forEach(e=>{e.getState()==="CANCELLED"||this.total.subtotal.isZero()?e.updateDiscounts([]):e.updateDiscounts(o.get(e.getId())||[]);});}updateTax(t){this.lineItems.forEach(i=>{i.updateTax(t[i.getPricing().taxCategory]);}),this.calculateTotals();}applyNonShippingCoupons(t){let i=t.filter(o=>o.getType()==="coupon");if(i.length===1){let o=i[0].calculateApplicableCouponDiscount(this.total.subtotal,this.total.shipping,this.country,this.currency);o.getAmount()>0&&(this.coupons.push(i[0]),this.total.couponTotal[i[0].getCode()]=o,this.total.couponDiscountTotal=o);}}applyShippingCoupons(t){if(this.total.shipping.getAmount()>0&&t.length>0){let i=this.total.subtotal.subtract(this.total.couponDiscountTotal),o=t.reduce((s,n)=>{if(!s)return n;let u=n.calculateApplicableCouponDiscount(i,this.total.shipping,this.country,this.currency).min(this.total.shipping),p=s.calculateApplicableCouponDiscount(i,this.total.shipping,this.country,this.currency).min(this.total.shipping);return u===p?n.getType()==="coupon"?n:s:u>p?n:s}),e=o.calculateApplicableCouponDiscount(i,this.total.shipping,this.country,this.currency).min(this.total.shipping);e.getAmount()>0&&(this.coupons.push(o),this.total.couponTotal[o.getCode()]=e,this.total.couponDiscountTotal=this.total.couponDiscountTotal.add(e),this.total.effectiveShipping=this.total.shipping.subtract(e));}}};export{D as a};//# sourceMappingURL=chunk-232FJYNB.mjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-232FJYNB.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/ShoppingContainer.ts"],"names":["BaseShoppingContainerModel","BaseModel","data","date","item","LineItemModel","AddressModel","coupon","CouponModel","Utils_default","PriceModel","key","value","zero","filteredLineItems","lineitem","subTotal","total","lineItem","shipping","couponDiscountTotal","couponTotal","nonShippingCouponTotal","couponValue","taxTotal","shippingCoupon","effectiveShipping","grandTotal","shippingDetails","applicableCoupons","shippingCoupons","otherCoupons","couponDiscounts","couponDiscount","itemDiscounts","li","code","totalDiscount","c","validItems","a","b","distributed","index","amount","taxRules","coupons","subTotalWithCouponDiscount","maxValuedCoupon","maxCoupon","currentCoupon","currentCouponValue","maxCouponValue"],"mappings":"mPA6DA,IAA8BA,CAA9B,CAAA,cAAiEC,CAAU,CAC/D,EACA,CAAA,UAAA,CACA,aACA,CAAA,WAAA,CACA,SACA,CAAA,eAAA,CACA,eACA,CAAA,cAAA,CAGA,QAGA,KAUA,CAAA,OAAA,CACA,QACA,CAAA,MAAA,CAQV,WAAYC,CAAAA,CAAAA,CAAuCC,CAAa,CAAA,IAAI,KAAQ,CAC1E,KAAA,CAAMD,CAAMC,CAAAA,CAAI,CAChB,CAAA,IAAA,CAAK,EAAKD,CAAAA,CAAAA,CAAK,GACf,IAAK,CAAA,UAAA,CAAaA,CAAK,CAAA,UAAA,CACvB,IAAK,CAAA,aAAA,CAAgBA,CAAK,CAAA,aAAA,CAC1B,IAAK,CAAA,WAAA,CAAcA,CAAK,CAAA,WAAA,CACxB,IAAK,CAAA,OAAA,CAAUA,CAAK,CAAA,OAAA,CACpB,KAAK,QAAWA,CAAAA,CAAAA,CAAK,QACrB,CAAA,IAAA,CAAK,MAASA,CAAAA,CAAAA,CAAK,MACnB,CAAA,IAAA,CAAK,WAAaA,CAAK,CAAA,SAAA,EAAa,EAAC,EAAG,GAAIE,CAAAA,CAAAA,EAAQ,IAAIC,CAAAA,CAAcD,CAAI,CAAC,CAAA,CAC3E,IAAK,CAAA,cAAA,CAAiBF,CAAK,CAAA,cAAA,CAAiB,IAAII,GAAAA,CAAaJ,CAAK,CAAA,cAAA,CAAgBC,CAAI,CAAA,CAAI,IAC1F,CAAA,IAAA,CAAK,eAAkBD,CAAAA,CAAAA,CAAK,gBAAkB,IAAII,GAAAA,CAAaJ,CAAK,CAAA,eAAA,CAAiBC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,QAAQ,CAExK,CAAA,OAAII,CAAuBC,GAAAA,CAAAA,CAClBF,CAAc,CAAA,OAAA,EAAc,GAAA,QAAA,CAAWA,CAAgBD,CAAAA,CAAAA,CAEzDE,CAAqBC,CAAAA,CAAAA,CAAiBF,CAAgBD,CAAAA,CAC/D,CAAC,CAEK1B,CAAAA,CAAAA,CAAcyB,CAAgB,CAAA,iCAAA,CAAkCD,CAA4B,CAAA,IAAA,CAAK,KAAM,CAAA,QAAA,CAAU,KAAK,OAAS,CAAA,IAAA,CAAK,QAAQ,CAAA,CAAE,GAAI,CAAA,IAAA,CAAK,KAAM,CAAA,QAAQ,EACvKxB,CAAY,CAAA,SAAA,EAAc,CAAA,CAAA,GAC5B,IAAK,CAAA,OAAA,CAAQ,IAAKyB,CAAAA,CAAe,EACjC,IAAK,CAAA,KAAA,CAAM,WAAYA,CAAAA,CAAAA,CAAgB,OAAQ,EAAC,CAAIzB,CAAAA,CAAAA,CACpD,KAAK,KAAM,CAAA,mBAAA,CAAsB,IAAK,CAAA,KAAA,CAAM,mBAAoB,CAAA,GAAA,CAAIA,CAAW,CAAA,CAC/E,KAAK,KAAM,CAAA,iBAAA,CAAoB,IAAK,CAAA,KAAA,CAAM,QAAS,CAAA,QAAA,CAASA,CAAW,CAAA,EAE3E,CACF,CACF","file":"chunk-232FJYNB.mjs","sourcesContent":["import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport AddressModel, { AddressData } from \"./Address\";\r\nimport LineItemModel, { LineItemData } from \"./LineItem\";\r\nimport { CountryCode, CurrencyCode, LocaleCode, ShippingDetails } from \"./Common\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport CouponModel, { CouponCategory, CouponData, CouponType } from \"./Coupon\";\r\nimport Utils from \"../Utils\";\r\nimport { LineItemState, TaxCategory } from \"./Enum\";\r\nimport { TaxRuleModel } from \"./TaxRule\";\r\n\r\nexport type ShoppingContainerTotal = {\r\n /** Sum of item prices before discounts & tax */\r\n subtotal: PriceData;\r\n\r\n /** Original shipping cost before coupons / promotions */\r\n shipping: PriceData;\r\n\r\n /** Shipping after coupons / promotions (>= 0) */\r\n effectiveShipping: PriceData;\r\n\r\n /** Total tax amount (all tax rules combined) */\r\n taxTotal: PriceData;\r\n\r\n /**\r\n * Coupon discounts applied\r\n * key = couponCode (or couponId)\r\n * value = discount amount (positive number)\r\n */\r\n couponTotal: Record<string, PriceData>;\r\n\r\n /** Total discount from coupons (derived, optional to store) */\r\n couponDiscountTotal: PriceData;\r\n\r\n /** Final payable amount */\r\n grandTotal: PriceData;\r\n};\r\n\r\n\r\nexport type BaseShoppingContainerAttributes = BaseAttributes & {\r\n id: string;\r\n customerId?: string;\r\n customerEmail?: string;\r\n anonymousId?: string;\r\n lineItems: LineItemData[];\r\n shippingDetails: ShippingDetails | null;\r\n shippingAddress?: AddressData | null;\r\n billingAddress?: AddressData | null;\r\n coupons: CouponData[];\r\n total: ShoppingContainerTotal;\r\n country: CountryCode;\r\n currency: CurrencyCode;\r\n locale: LocaleCode;\r\n};\r\n\r\nexport type BaseShoppingContainerData = BaseShoppingContainerAttributes & BaseData\r\n\r\n\r\n/**\r\n * Abstract base class for shopping-related containers like carts and orders.\r\n * Manages common elements such as line items, addresses, coupons, and totals.\r\n */\r\nexport default abstract class BaseShoppingContainerModel extends BaseModel {\r\n protected id: string;\r\n protected customerId?: string;\r\n protected customerEmail?: string;\r\n protected anonymousId?: string;\r\n protected lineItems: LineItemModel[];\r\n protected shippingDetails: ShippingDetails | null;\r\n protected shippingAddress: AddressModel | null;\r\n protected billingAddress: AddressModel | null;\r\n\r\n // CouponsCodes\r\n protected coupons: CouponModel[];\r\n\r\n // Cart Totals\r\n protected total: {\r\n subtotal: PriceModel;\r\n shipping: PriceModel;\r\n effectiveShipping: PriceModel;\r\n taxTotal: PriceModel;\r\n couponTotal: Record<string, PriceModel>;\r\n couponDiscountTotal: PriceModel;\r\n grandTotal: PriceModel;\r\n };\r\n\r\n protected country: CountryCode;\r\n protected currency: CurrencyCode;\r\n protected locale: LocaleCode;\r\n\r\n /**\r\n * Creates an instance of BaseShoppingContainerModel.\r\n * Initializes common properties and calculates initial base totals.\r\n * @param data - The initial attributes for the shopping container.\r\n * @param date - Optional date object for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: BaseShoppingContainerAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.customerId = data.customerId;\r\n this.customerEmail = data.customerEmail;\r\n this.anonymousId = data.anonymousId;\r\n this.country = data.country;\r\n this.currency = data.currency;\r\n this.locale = data.locale;\r\n this.lineItems = (data.lineItems ?? []).map(item => new LineItemModel(item));\r\n this.billingAddress = data.billingAddress ? new AddressModel(data.billingAddress, date) : null;\r\n this.shippingAddress = data.shippingAddress ? new AddressModel(data.shippingAddress, date) : null;\r\n this.coupons = (data.coupons ?? []).map(coupon => new CouponModel(coupon));\r\n\r\n this.shippingDetails = data.shippingDetails ? Utils.deepClone(data.shippingDetails) : null;\r\n\r\n this.total = {\r\n subtotal: new PriceModel(data.total.subtotal),\r\n shipping: new PriceModel(data.total.shipping),\r\n effectiveShipping: new PriceModel(data.total.effectiveShipping),\r\n taxTotal: new PriceModel(data.total.taxTotal),\r\n couponTotal: Object.fromEntries(\r\n Object.entries(data.total.couponTotal).map(([key, value]) => [key, new PriceModel(value)])\r\n ),\r\n couponDiscountTotal: new PriceModel(data.total.couponDiscountTotal),\r\n grandTotal: new PriceModel(data.total.grandTotal),\r\n };\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for this shopping container (cart ID or order ID).\r\n * @returns The ID string.\r\n */\r\n public getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the customer ID associated with this container, if available.\r\n * @returns The customer ID string, or undefined.\r\n */\r\n public getCustomerId(): string | undefined {\r\n return this.customerId;\r\n }\r\n\r\n /**\r\n * Gets the customer email associated with this container, if available.\r\n * @returns The customer email string, or undefined.\r\n */\r\n public getCustomerEmail(): string | undefined {\r\n return this.customerEmail;\r\n }\r\n\r\n /**\r\n * Gets the anonymous user ID associated with this container, if available.\r\n * @returns The anonymous ID string, or undefined.\r\n */\r\n public getAnonymousId(): string | undefined {\r\n return this.anonymousId;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the line items in the container.\r\n * Each item is a new LineItemModel instance created from the original's details.\r\n * @returns An array of LineItemModel instances.\r\n */\r\n public getLineItems(): LineItemModel[] {\r\n // Return new instances to prevent modification of internal state\r\n return this.lineItems.map(item => new LineItemModel(item.getDetails()));\r\n }\r\n\r\n /**\r\n * Gets current number of line items in the container.\r\n * @returns The count of line items.\r\n */\r\n public getLineItemsCount(): number {\r\n return this.lineItems.length;\r\n }\r\n\r\n /**\r\n * Gets a copy of the shipping details associated with the container.\r\n * @returns A ShippingDetails object, or null if none are set.\r\n */\r\n public getShippingDetails(): ShippingDetails | null {\r\n // Return a shallow copy if details exist\r\n return this.shippingDetails ? { ...this.shippingDetails } : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the shipping address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no shipping address is set.\r\n */\r\n public getShippingAddress(): AddressModel | null {\r\n return this.shippingAddress ? new AddressModel(this.shippingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Checks if a shipping address is associated with this container.\r\n * @returns True if a shipping address is set, false otherwise.\r\n */\r\n public hasShippingAddress(): boolean {\r\n return !!this.shippingAddress;\r\n }\r\n\r\n /**\r\n * Checks if a billing address is associated with this container.\r\n * @returns True if a billing address is set, false otherwise.\r\n */\r\n public hasBillingAddress(): boolean {\r\n return !!this.billingAddress;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the billing address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no billing address is set.\r\n */\r\n public getBillingAddress(): AddressModel | null {\r\n return this.billingAddress ? new AddressModel(this.billingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the coupons applied to the container.\r\n * Each item is a new CouponModel instance created from the original's details.\r\n * @returns An array of CouponModel instances.\r\n */\r\n public getCoupons(): CouponModel[] {\r\n return this.coupons;\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this container.\r\n * @returns The CountryCode enum value.\r\n */\r\n public getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Gets the currency code associated with this container.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Gets the locale code associated with this container.\r\n * @returns The LocaleCode enum value.\r\n */\r\n public getLocale(): LocaleCode {\r\n return this.locale;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the calculated totals for the container.\r\n * @returns An object containing shipping, subtotal, coupon, and grand totals.\r\n */\r\n public getTotal() {\r\n return this.total;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the shopping container's current state.\r\n * Includes details from the base model and specific container properties.\r\n * @returns BaseShoppingContainerData object suitable for serialization or API responses.\r\n */\r\n getDetails(): BaseShoppingContainerData {\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n customerId: this.getCustomerId(),\r\n customerEmail: this.getCustomerEmail(),\r\n anonymousId: this.getAnonymousId(),\r\n lineItems: this.getLineItems().map(item => item.getDetails()),\r\n shippingDetails: this.getShippingDetails(),\r\n shippingAddress: this.getShippingAddress()?.getDetails() || null,\r\n billingAddress: this.getBillingAddress()?.getDetails() || null,\r\n coupons: this.getCoupons().map(coupon => coupon.getDetails()),\r\n total: {\r\n subtotal: this.getTotal().subtotal.getDetails(),\r\n shipping: this.getTotal().shipping.getDetails(),\r\n effectiveShipping: this.getTotal().effectiveShipping.getDetails(),\r\n taxTotal: this.getTotal().taxTotal.getDetails(),\r\n couponTotal: Object.fromEntries(Object.entries(this.getTotal().couponTotal).map(([key, value]) => [key, value.getDetails()])),\r\n couponDiscountTotal: this.getTotal().couponDiscountTotal.getDetails(),\r\n grandTotal: this.getTotal().grandTotal.getDetails(),\r\n },\r\n country: this.getCountry(),\r\n currency: this.getCurrency(),\r\n locale: this.getLocale(),\r\n }\r\n };\r\n\r\n /**\r\n * Recalculates the total costs for the shopping container.\r\n * This includes summing line items, calculating shipping, applying coupons, and computing taxes.\r\n */\r\n public calculateTotals(): void {\r\n const zero = new PriceModel({ amount: 0, currency: this.currency });\r\n const filteredLineItems = this.lineItems.filter(lineitem => lineitem.getState() !== LineItemState.CANCELLED);\r\n const subTotal = filteredLineItems.reduce((total, lineItem) => total.add(lineItem.getTotal().subtotal), zero);\r\n\r\n const shipping = new PriceModel({ amount: this.shippingDetails?.cost || 0, currency: this.currency }).round();\r\n\r\n let couponDiscountTotal = zero;\r\n let couponTotal: Record<string, PriceModel> = {};\r\n let nonShippingCouponTotal: Record<string, PriceModel> = {};\r\n this.coupons.forEach(coupon => {\r\n const couponValue = coupon.calculateApplicableCouponDiscount(subTotal, shipping, this.country, this.currency);\r\n couponDiscountTotal = couponDiscountTotal.add(couponValue);\r\n couponTotal[coupon.getCode()] = couponValue;\r\n if (coupon.getCategory() !== CouponCategory.SHIPPING) {\r\n nonShippingCouponTotal[coupon.getCode()] = couponValue;\r\n }\r\n })\r\n this.applyDiscountsInLineItem(nonShippingCouponTotal);\r\n\r\n const taxTotal = filteredLineItems.reduce((total, lineItem) => total.add(lineItem.getTotal().taxTotal), zero);\r\n const shippingCoupon = this.coupons.find(coupon => coupon.getCategory() === CouponCategory.SHIPPING);\r\n const effectiveShipping = shippingCoupon ? shipping.subtract(couponTotal[shippingCoupon.getCode()] || zero) : shipping;\r\n\r\n const grandTotal = subTotal.add(shipping).add(taxTotal).subtract(couponDiscountTotal);\r\n\r\n this.total = {\r\n subtotal: subTotal,\r\n shipping: shipping,\r\n effectiveShipping: effectiveShipping,\r\n couponTotal: couponTotal,\r\n couponDiscountTotal: couponDiscountTotal,\r\n taxTotal: taxTotal,\r\n grandTotal: grandTotal,\r\n };\r\n }\r\n\r\n /**\r\n * Updates the shipping details and recalculates the totals.\r\n * @param shippingDetails - The new shipping details to apply.\r\n */\r\n public updateShippingDetails(shippingDetails: ShippingDetails): void {\r\n this.shippingDetails = shippingDetails;\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Applies a list of coupons to the shopping container.\r\n * Filters out invalid coupons, separates shipping and non-shipping coupons,\r\n * and distributes discounts to line items.\r\n * @param applicableCoupons - The list of coupons to attempt to apply.\r\n */\r\n public applyCoupons(applicableCoupons: CouponModel[]): void {\r\n //Apply coupons\r\n const shippingCoupons = applicableCoupons.filter(coupon => coupon.getCategory() === CouponCategory.SHIPPING);\r\n const otherCoupons = applicableCoupons.filter(coupon => coupon.getCategory() !== CouponCategory.SHIPPING);\r\n\r\n this.coupons = [];\r\n this.total.couponDiscountTotal = this.total.subtotal.zero();\r\n this.total.couponTotal = {};\r\n // Apply non shipping coupons\r\n otherCoupons.length && this.applyNonShippingCoupons(otherCoupons);\r\n this.applyDiscountsInLineItem(this.total.couponTotal);\r\n\r\n // Apply shipping coupons\r\n shippingCoupons.length && this.applyShippingCoupons(shippingCoupons);\r\n\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Distributes the total discount amount among the line items.\r\n * @param couponTotal - A record of coupon codes and their calculated discount amounts.\r\n */\r\n private applyDiscountsInLineItem(couponTotal: Record<string, PriceModel>) {\r\n const couponDiscounts: [string, PriceModel][] = Array.from(Object.entries(couponTotal))\r\n .filter(couponDiscount => !couponDiscount[1].isZero());\r\n\r\n const itemDiscounts = new Map<string, { coupon: CouponModel, amount: PriceModel }[]>();\r\n this.lineItems.forEach(li => itemDiscounts.set(li.getId(), []));\r\n\r\n couponDiscounts.forEach(([code, totalDiscount]) => {\r\n const coupon = this.coupons.find(c => c.getCode() === code);\r\n if (!coupon || totalDiscount.isZero()) return;\r\n\r\n const validItems = this.lineItems\r\n .filter(li => li.getState() !== LineItemState.CANCELLED && !li.getTotal().subtotal.isZero())\r\n .sort((a, b) => a.getTotal().subtotal.compareTo(b.getTotal().subtotal));\r\n\r\n let distributed = new PriceModel({ amount: 0, currency: this.currency });\r\n\r\n validItems.forEach((item, index) => {\r\n let amount: PriceModel;\r\n if (index === validItems.length - 1) {\r\n amount = totalDiscount.subtract(distributed);\r\n } else {\r\n amount = totalDiscount.multiply(item.getTotal().subtotal).divide(this.total.subtotal).round();\r\n }\r\n distributed = distributed.add(amount);\r\n itemDiscounts.get(item.getId())?.push({ coupon, amount });\r\n });\r\n });\r\n\r\n this.lineItems.forEach(lineItem => {\r\n if (lineItem.getState() === LineItemState.CANCELLED || this.total.subtotal.isZero()) {\r\n lineItem.updateDiscounts([]);\r\n } else {\r\n lineItem.updateDiscounts(itemDiscounts.get(lineItem.getId()) || []);\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Updates the tax rules for all line items and recalculates totals.\r\n * @param taxRules - A record of tax rules keyed by tax category.\r\n */\r\n public updateTax(taxRules: Record<TaxCategory, TaxRuleModel>): void {\r\n this.lineItems.forEach(lineItem => {\r\n lineItem.updateTax(taxRules[lineItem.getPricing().taxCategory]);\r\n });\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Selects and applies the best applicable non-shipping coupon.\r\n * Currently supports applying only a single coupon of type COUPON.\r\n * @param applicableCoupons - List of available non-shipping coupons.\r\n */\r\n private applyNonShippingCoupons(applicableCoupons: CouponModel[]) {\r\n const coupons = applicableCoupons.filter(coupon => coupon.getType() === CouponType.COUPON);\r\n if (coupons.length === 1) {\r\n const couponValue = coupons[0].calculateApplicableCouponDiscount(this.total.subtotal, this.total.shipping, this.country, this.currency);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(coupons[0]);\r\n this.total.couponTotal[coupons[0].getCode()] = couponValue;\r\n this.total.couponDiscountTotal = couponValue;\r\n }\r\n }\r\n // Todo: Add support to other type in future like promotion\r\n }\r\n\r\n /**\r\n * Selects and applies the best applicable shipping coupon.\r\n * @param applicableCoupons - List of available shipping coupons.\r\n */\r\n private applyShippingCoupons(applicableCoupons: CouponModel[]) {\r\n if (this.total.shipping.getAmount() > 0 && applicableCoupons.length > 0) {\r\n const subTotalWithCouponDiscount = this.total.subtotal.subtract(this.total.couponDiscountTotal);\r\n\r\n const maxValuedCoupon = applicableCoupons.reduce((maxCoupon, currentCoupon) => {\r\n if (!maxCoupon) return currentCoupon;\r\n\r\n const currentCouponValue = currentCoupon.calculateApplicableCouponDiscount(subTotalWithCouponDiscount, this.total.shipping, this.country, this.currency).min(this.total.shipping);\r\n const maxCouponValue = maxCoupon.calculateApplicableCouponDiscount(subTotalWithCouponDiscount, this.total.shipping, this.country, this.currency).min(this.total.shipping);\r\n\r\n if (currentCouponValue === maxCouponValue) {\r\n return currentCoupon.getType() === 'coupon' ? currentCoupon : maxCoupon;\r\n }\r\n return currentCouponValue > maxCouponValue ? currentCoupon : maxCoupon;\r\n });\r\n\r\n const couponValue = maxValuedCoupon.calculateApplicableCouponDiscount(subTotalWithCouponDiscount, this.total.shipping, this.country, this.currency).min(this.total.shipping);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(maxValuedCoupon);\r\n this.total.couponTotal[maxValuedCoupon.getCode()] = couponValue;\r\n this.total.couponDiscountTotal = this.total.couponDiscountTotal.add(couponValue);\r\n this.total.effectiveShipping = this.total.shipping.subtract(couponValue);\r\n }\r\n }\r\n }\r\n}\r\n\r\n\r\n"]}
|
package/dist/chunk-72DR3HF2.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var p=(o=>(o.IN="IN",o))(p||{}),I=(o=>(o.INR="INR",o))(I||{}),r=(R=>(R["en-IN"]="en-IN",R["kn-IN"]="kn-IN",R))(r||{}),l=(n=>(n.en="en",n.kn="kn",n))(l||{}),x={"en-IN":"en","kn-IN":"kn"},T={"en-IN":"IN","kn-IN":"IN"},U={IN:"INR"},M={INR:"\u20B9"},P={INR:"en-IN"},u=(N=>(N.MALE="Male",N.FEMALE="Female",N.UNISEX="Unisex",N.KIDS="Kids",N.BOY="Boy",N.GIRL="Girl",N.GENERAL="General",N))(u||{}),D=(n=>(n.PRIMARY="PRIMARY",n.GALLERY="GALLERY",n))(D||{}),c=(n=>(n.APPAREL="apparel",n.EXEMPT="exempt",n))(c||{}),L=(o=>(o.GST="GST",o))(L||{}),a=(E=>(E.INITIAL="INITIAL",E.PROCESSING="PROCESSING",E.SHIPPED="SHIPPED",E.DELIVERED="DELIVERED",E.CANCELLED="CANCELLED",E.RETURN_REQUESTED="RETURN_REQUESTED",E.RETURNED="RETURNED",E.REFUND_INITIATED="REFUND_INITIATED",E.REFUNDED="REFUNDED",E.ON_HOLD="ON_HOLD",E))(a||{});export{p as a,I as b,r as c,l as d,x as e,T as f,U as g,M as h,P as i,u as j,D as k,c as l,L as m,a as n};//# sourceMappingURL=chunk-72DR3HF2.mjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-72DR3HF2.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/Enum.ts"],"names":["OperationalCountry","OperationalCountryCurrency","OperationalLocale","OperationalLanguage","LocaleLanguageMap","LocaleCountryMap","CountryCurrencyMap","CurrencySymbolMap","CurrencyLocaleMap","GenderCategory","ImageCategory","TaxCategory","TaxSystem","LineItemState"],"mappings":"AAGO,IAAKA,CACGA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,EAAK,CAAA,IAAA,CADRA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAIAC,CACGA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,GAAM,CAAA,KAAA,CADTA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAIAC,OACGA,CAAA,CAAA,OAAA,CAAA,CAAU,OACCA,CAAAA,CAAAA,CAAA,OAAU,CAAA,CAAA,OAAA,CAFxBA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAKAC,OACVA,CAAA,CAAA,EAAA,CAAK,IACLA,CAAAA,CAAAA,CAAA,EAAK,CAAA,IAAA,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AAA,CAAA,SAAA,CAAY,WACZA,CAAAA,CAAAA,CAAA,gBAAmB,CAAA,kBAAA,CACnBA,CAAA,CAAA,QAAA,CAAW,WACXA,CAAA,CAAA,gBAAA,CAAmB,kBACnBA,CAAAA,CAAAA,CAAA,QAAW,CAAA,UAAA,CACXA,CAAA,CAAA,OAAA,CAAU,UAVAA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA","file":"chunk-72DR3HF2.mjs","sourcesContent":["/**\r\n * Represents the countries where the application operates or products are available.\r\n */\r\nexport enum OperationalCountry {\r\n /** India */ IN = 'IN',\r\n}\r\n \r\nexport enum OperationalCountryCurrency {\r\n /** India */ INR = 'INR',\r\n}\r\n\r\nexport enum OperationalLocale {\r\n /** India */ 'en-IN' = 'en-IN',\r\n /** India ( Kannada) */ 'kn-IN' = 'kn-IN'\r\n}\r\n\r\nexport enum OperationalLanguage {\r\n en = 'en',\r\n kn = 'kn'\r\n}\r\n\r\nexport const LocaleLanguageMap: Record<OperationalLocale, OperationalLanguage> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalLanguage.en,\r\n [OperationalLocale[\"kn-IN\"]]: OperationalLanguage.kn,\r\n}\r\n\r\nexport const LocaleCountryMap: Record<OperationalLocale, OperationalCountry> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalCountry.IN,\r\n [OperationalLocale[\"kn-IN\"]]: OperationalCountry.IN,\r\n}\r\n\r\n/**\r\n * Defines the supported ISO 4217 currency codes as an enumeration.\r\n */\r\nexport const CountryCurrencyMap = {\r\n /** India */ [OperationalCountry.IN]: OperationalCountryCurrency.INR,\r\n};\r\n\r\nexport const CurrencySymbolMap = {\r\n [OperationalCountryCurrency.INR]: '₹',\r\n}\r\n\r\nexport const CurrencyLocaleMap = {\r\n [OperationalCountryCurrency.INR]: OperationalLocale[\"en-IN\"],\r\n}\r\n\r\n/**\r\n * Defines standard gender categories for product targeting.\r\n */\r\nexport enum GenderCategory {\r\n MALE = 'Male',\r\n FEMALE = 'Female',\r\n UNISEX = 'Unisex',\r\n KIDS = 'Kids',\r\n BOY = 'Boy',\r\n GIRL = 'Girl',\r\n GENERAL = 'General',\r\n}\r\n\r\nexport enum ImageCategory {\r\n PRIMARY = 'PRIMARY',\r\n GALLERY = 'GALLERY'\r\n}\r\n\r\nexport enum TaxCategory {\r\n APPAREL = 'apparel',\r\n EXEMPT = 'exempt'\r\n}\r\n\r\nexport enum TaxSystem {\r\n GST = 'GST',\r\n}\r\n\r\n/**\r\n * LineItemState\r\n * \r\n * INITIAL: Item added to order, not yet processed.\r\n * PROCESSING: Item is being prepared for shipment.\r\n * SHIPPED: Item dispatched to customer.\r\n * DELIVERED: Item delivered to customer.\r\n * CANCELLED: Item cancelled before shipment or delivery.\r\n * RETURN_REQUESTED: Customer requests to return item.\r\n * RETURNED: Item received back from customer.\r\n * REFUND_INITIATED: Refund initiated for item.\r\n * REFUNDED: Refund processed for item.\r\n * ON_HOLD: Item is paused due to payment, inventory, or other issues.\r\n */\r\nexport enum LineItemState {\r\n INITIAL = \"INITIAL\",\r\n PROCESSING = \"PROCESSING\",\r\n SHIPPED = \"SHIPPED\",\r\n DELIVERED = \"DELIVERED\",\r\n CANCELLED = \"CANCELLED\",\r\n RETURN_REQUESTED = \"RETURN_REQUESTED\",\r\n RETURNED = \"RETURNED\",\r\n REFUND_INITIATED = \"REFUND_INITIATED\",\r\n REFUNDED = \"REFUNDED\",\r\n ON_HOLD = \"ON_HOLD\",\r\n}"]}
|
package/dist/chunk-ARMBZF3E.mjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import {a}from'./chunk-TJ7AZBND.mjs';import {p}from'./chunk-JHELVQYY.mjs';import {b}from'./chunk-6KCJVEZD.mjs';var m=class{getBreakdown(t,a,e){let r=t*100,i=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,"");if(a==="IN"&&e?.merchantState&&e?.customerState)if(e.merchantState.toLowerCase().trim()===e.customerState.toLowerCase().trim()){let o=r/2%1===0?(r/2).toString():(r/2).toFixed(2).replace(/\.?0+$/,"");return {totalRate:t,label:`${o}% CGST + ${o}% SGST`,components:[{rate:t/2,label:`${o}% CGST`,type:"CGST"},{rate:t/2,label:`${o}% SGST`,type:"SGST"}]}}else return {totalRate:t,label:`${i}% IGST`,components:[{rate:t,label:`${i}% IGST`,type:"IGST"}]};return {totalRate:t,label:`${i}% GST`,components:[{rate:t,label:`${i}% GST`,type:"GST"}]}}getLongName(){return "Goods and Services Tax"}},T={GST:new m},g=class s extends b{taxRuleId;taxSystem;taxCategory;country;slabs;effectiveFrom;effectiveTo;constructor(t,a$1=new Date){super(t,a$1),this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxCategory=t.taxCategory,this.country=t.country,this.slabs=t.slabs.map(e=>({rate:e.rate,minUnitPrice:new a(e.minUnitPrice),maxUnitPrice:e.maxUnitPrice?new a(e.maxUnitPrice):void 0})),this.effectiveFrom=new Date(t.effectiveFrom),this.effectiveTo=t.effectiveTo?new Date(t.effectiveTo):void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getSlabs(){return this.slabs}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),slabs:this.getSlabs().map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0})),effectiveFrom:this.effectiveFrom.toISOString(),effectiveTo:this.effectiveTo?this.effectiveTo.toISOString():void 0,...super.getDetails()}}appliesTo(t,a,e=new Date){return this.taxCategory===t&&this.country===a&&this.effectiveFrom<=e&&(this.effectiveTo?this.effectiveTo>=e:!0)}getApplicableTaxRate(t){return s.getApplicableTaxRate(t,this.slabs)}getTaxRateDisplayString(t,a){let e=this.getApplicableTaxRate(t);return s.getTaxRateDisplayString(e,{taxSystem:this.taxSystem,merchantState:a?.merchantState,customerState:a?.customerState})}getTaxRateBreakdown(t,a){let e=this.getApplicableTaxRate(t),r=T[this.taxSystem];if(r)return r.getBreakdown(e,this.country,a);let i=e*100,n=`${i%1===0?i.toString():i.toFixed(2).replace(/\.?0+$/,"")}% ${this.taxSystem}`;return {totalRate:e,label:n,components:[{rate:e,label:n,type:this.taxSystem}]}}getFormattedTaxRate(t,a={}){let r=this.getApplicableTaxRate(t)*100,i=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,""),o=a.variant||"short",n="";switch(o){case"percentageOnly":n=`${i}%`;break;case"detailed":let u=this.getTaxRateBreakdown(t,a),y=a.separator||(a.multiline?`
|
|
2
|
-
`:" + ");n=u.components.map(f=>f.label).join(y);break;case"long":let l=T[this.taxSystem],p=l?l.getLongName(this.country):this.taxSystem.toString();n=`${i}% ${p}`;break;case"short":default:n=`${i}% ${this.taxSystem}`;break}return a.includeTaxesSuffix&&(n+=" (Incl. Taxes)"),n}static getApplicableTaxRate(t,a){let e=a.filter(r=>(r.minUnitPrice===void 0||t.compareTo(r.minUnitPrice)>=0)&&(r.maxUnitPrice===void 0||t.compareTo(r.maxUnitPrice)<0));if(e.length!==1)throw new p;return e[0].rate}static getTaxRateDisplayString(t,a){let e=t*100,r=e%1===0?e.toString():e.toFixed(2).replace(/\.?0+$/,"");if(a.taxSystem==="GST"&&a.merchantState&&a.customerState)if(a.merchantState.toLowerCase().trim()===a.customerState.toLowerCase().trim()){let i=e/2%1===0?(e/2).toString():(e/2).toFixed(2).replace(/\.?0+$/,"");return `${i}% CGST + ${i}% SGST`}else return `${r}% IGST`;return a.taxSystem?`${r}% ${a.taxSystem}`:`${r}%`}};export{m as a,T as b,g as c};//# sourceMappingURL=chunk-ARMBZF3E.mjs.map
|
|
3
|
-
//# sourceMappingURL=chunk-ARMBZF3E.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/TaxRule.ts"],"names":["GSTFormatter","rate","country","options","percentage","rateStr","splitRate","TaxFormatterRegistry","TaxRuleModel","_TaxRuleModel","BaseModel","data","date","s","PriceModel","taxCategory","at","unitPrice","formatter","label","variant","result","breakdown","separator","c","systemLongName","taxSlabs","slabs","TaxSlabNotFoundError"],"mappings":"+GAsDO,IAAMA,CAAN,CAAA,KAAkD,CACvD,YAAA,CAAaC,CAAcC,CAAAA,CAAAA,CAAsBC,CAAkD,CAAA,CACjG,IAAMC,CAAAA,CAAaH,CAAO,CAAA,GAAA,CACpBI,CAAUD,CAAAA,CAAAA,CAAa,CAAM,GAAA,CAAA,CAAIA,CAAW,CAAA,QAAA,EAAaA,CAAAA,CAAAA,CAAW,OAAQ,CAAA,CAAC,CAAE,CAAA,OAAA,CAAQ,QAAU,CAAA,EAAE,CAEzG,CAAA,GAAIF,IAAY,IAAQC,EAAAA,CAAAA,EAAS,aAAiBA,EAAAA,CAAAA,EAAS,aACzD,CAAA,GAAIA,CAAQ,CAAA,aAAA,CAAc,WAAY,EAAA,CAAE,IAAK,EAAA,GAAMA,CAAQ,CAAA,aAAA,CAAc,WAAY,EAAA,CAAE,IAAK,EAAA,CAAG,CAC7F,IAAMG,CAAaF,CAAAA,CAAAA,CAAa,CAAK,CAAA,CAAA,GAAM,CAAKA,CAAAA,CAAAA,CAAAA,CAAa,CAAG,EAAA,QAAA,EAAcA,CAAAA,CAAAA,CAAAA,CAAa,CAAG,EAAA,OAAA,CAAQ,CAAC,CAAE,CAAA,OAAA,CAAQ,QAAU,CAAA,EAAE,CAC7H,CAAA,OAAO,CACL,SAAA,CAAWH,CACX,CAAA,KAAA,CAAO,CAAGK,EAAAA,CAAS,CAAYA,SAAAA,EAAAA,CAAS,CACxC,MAAA,CAAA,CAAA,UAAA,CAAY,CACV,CAAE,IAAML,CAAAA,CAAAA,CAAO,CAAG,CAAA,KAAA,CAAO,CAAGK,EAAAA,CAAS,CAAU,MAAA,CAAA,CAAA,IAAA,CAAM,MAAO,CAAA,CAC5D,CAAE,IAAA,CAAML,CAAO,CAAA,CAAA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AA,CAAAA,CAAAA,CAAa,GAAG,OAAQ,CAAA,CAAC,EAAE,OAAQ,CAAA,QAAA,CAAU,EAAE,CAC7H,CAAA,OAAO,GAAGE,CAAS,CAAA,SAAA,EAAYA,CAAS,CAC1C,MAAA,CAAA,CAAA,YACS,CAAGD,EAAAA,CAAO,SAIrB,OAAOF,CAAAA,CAAQ,UAAY,CAAGE,EAAAA,CAAO,KAAKF,CAAQ,CAAA,SAAS,GAAK,CAAGE,EAAAA,CAAO,GAC5E,CACF","file":"chunk-ARMBZF3E.mjs","sourcesContent":["import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, ISODateTimeUTC } from \"./Common\";\r\nimport { TaxCategory, TaxSystem } from \"./Enum\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport { TaxSlabNotFoundError } from \"./Error\";\r\n\r\nexport type TaxSlabData = {\r\n minUnitPrice: PriceData; // inclusive\r\n maxUnitPrice?: PriceData; // exclusive\r\n rate: number; // e.g. 0.05 = 5%\r\n};\r\n\r\nexport type TaxSlabModel = {\r\n minUnitPrice: PriceModel; // inclusive\r\n maxUnitPrice?: PriceModel; // exclusive\r\n rate: number; // e.g. 0.05 = 5%\r\n};\r\n\r\nexport type TaxSlabs = TaxSlabData[];\r\n\r\nexport type TaxRateBreakdown = {\r\n totalRate: number;\r\n label: string;\r\n components: {\r\n rate: number;\r\n label: string;\r\n type: 'IGST' | 'CGST' | 'SGST' | 'GST' | string;\r\n }[];\r\n};\r\n\r\nexport type TaxFormattingVariant = 'short' | 'long' | 'detailed' | 'percentageOnly';\r\n\r\nexport interface TaxFormattingOptions {\r\n variant?: TaxFormattingVariant;\r\n includeTaxesSuffix?: boolean; // e.g. \"(Incl. Taxes)\"\r\n merchantState?: string;\r\n customerState?: string;\r\n multiline?: boolean;\r\n separator?: string; // custom separator, overrides multiline if provided\r\n}\r\n\r\n/**\r\n * Interface for tax system specific formatting logic.\r\n */\r\nexport interface ITaxSystemFormatter {\r\n getBreakdown(rate: number, country: CountryCode, options?: TaxFormattingOptions): TaxRateBreakdown;\r\n getLongName(country: CountryCode): string;\r\n}\r\n\r\n/**\r\n * Formatter for GST (Goods and Services Tax).\r\n * Handles India-specific components (CGST/SGST/IGST).\r\n */\r\nexport class GSTFormatter implements ITaxSystemFormatter {\r\n getBreakdown(rate: number, country: CountryCode, options?: TaxFormattingOptions): TaxRateBreakdown {\r\n const percentage = rate * 100;\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n\r\n if (country === 'IN' && options?.merchantState && options?.customerState) {\r\n if (options.merchantState.toLowerCase().trim() === options.customerState.toLowerCase().trim()) {\r\n const splitRate = (percentage / 2) % 1 === 0 ? (percentage / 2).toString() : (percentage / 2).toFixed(2).replace(/\\.?0+$/, '');\r\n return {\r\n totalRate: rate,\r\n label: `${splitRate}% CGST + ${splitRate}% SGST`,\r\n components: [\r\n { rate: rate / 2, label: `${splitRate}% CGST`, type: 'CGST' },\r\n { rate: rate / 2, label: `${splitRate}% SGST`, type: 'SGST' }\r\n ]\r\n };\r\n } else {\r\n return {\r\n totalRate: rate,\r\n label: `${rateStr}% IGST`,\r\n components: [{ rate: rate, label: `${rateStr}% IGST`, type: 'IGST' }]\r\n };\r\n }\r\n }\r\n\r\n return {\r\n totalRate: rate,\r\n label: `${rateStr}% GST`,\r\n components: [{ rate: rate, label: `${rateStr}% GST`, type: 'GST' }]\r\n };\r\n }\r\n\r\n getLongName(): string {\r\n return 'Goods and Services Tax';\r\n }\r\n}\r\n\r\n/**\r\n * Registry to manage and provide tax formatters.\r\n */\r\nexport const TaxFormatterRegistry: Record<string, ITaxSystemFormatter> = {\r\n [TaxSystem.GST]: new GSTFormatter(),\r\n};\r\n\r\nexport type TaxRuleAttributes = {\r\n taxRuleId: string;\r\n taxSystem: TaxSystem;\r\n taxCategory: TaxCategory;\r\n country: CountryCode;\r\n slabs: TaxSlabs;\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n} & BaseAttributes;\r\n\r\nexport type TaxRuleData = Required<Omit<TaxRuleAttributes, 'effectiveFrom' | 'effectiveTo'>> & {\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n};\r\n\r\nexport class TaxRuleModel extends BaseModel {\r\n protected taxRuleId: string;\r\n protected taxSystem: TaxSystem;\r\n protected taxCategory: TaxCategory;\r\n protected country: CountryCode;\r\n protected slabs: TaxSlabModel[];\r\n protected effectiveFrom: Date;\r\n protected effectiveTo?: Date;\r\n\r\n /**\r\n * Creates an instance of TaxRuleModel.\r\n * @param data - The initial tax rule attributes.\r\n * @param date - Optional date for creation/modification (defaults to now).\r\n */\r\n constructor(data: TaxRuleAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.taxRuleId = data.taxRuleId;\r\n this.taxSystem = data.taxSystem;\r\n this.taxCategory = data.taxCategory;\r\n this.country = data.country;\r\n this.slabs = data.slabs.map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: new PriceModel(s.minUnitPrice),\r\n maxUnitPrice: s.maxUnitPrice ? new PriceModel(s.maxUnitPrice) : undefined,\r\n }));\r\n this.effectiveFrom = new Date(data.effectiveFrom);\r\n this.effectiveTo = data.effectiveTo ? new Date(data.effectiveTo) : undefined;\r\n }\r\n\r\n getTaxRuleId(): string {\r\n return this.taxRuleId;\r\n }\r\n\r\n getTaxSystem(): TaxSystem {\r\n return this.taxSystem;\r\n }\r\n\r\n getTaxCategory(): TaxCategory {\r\n return this.taxCategory;\r\n }\r\n\r\n getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n getSlabs(): TaxSlabModel[] {\r\n return this.slabs;\r\n }\r\n\r\n getDetails(): TaxRuleData {\r\n return {\r\n taxRuleId: this.getTaxRuleId(),\r\n taxSystem: this.getTaxSystem(),\r\n taxCategory: this.getTaxCategory(),\r\n country: this.getCountry(),\r\n slabs: this.getSlabs().map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: s.minUnitPrice.getDetails(),\r\n maxUnitPrice: s.maxUnitPrice ? s.maxUnitPrice.getDetails() : undefined,\r\n })),\r\n effectiveFrom: this.effectiveFrom.toISOString(),\r\n effectiveTo: this.effectiveTo ? this.effectiveTo.toISOString() : undefined,\r\n ...super.getDetails()\r\n };\r\n }\r\n\r\n /**\r\n * Checks whether this tax rule is applicable for the given category and country at a specific time.\r\n * @param taxCategory - The tax category to check.\r\n * @param country - The country code to check.\r\n * @param at - The date to check effectiveness against (defaults to now).\r\n * @returns True if the rule is applicable, false otherwise.\r\n */\r\n appliesTo(taxCategory: TaxCategory, country: CountryCode, at: Date = new Date()): boolean {\r\n return (\r\n this.taxCategory === taxCategory &&\r\n this.country === country &&\r\n this.effectiveFrom <= at &&\r\n (this.effectiveTo ? this.effectiveTo >= at : true)\r\n );\r\n }\r\n\r\n /**\r\n * Calculates the applicable tax rate for a given unit price.\r\n * @param unitPrice - The unit price to find the matching tax slab for.\r\n * @returns The tax rate as a decimal (e.g., 0.05 for 5%).\r\n * @throws {TaxSlabNotFoundError} If no applicable slab or multiple slabs are found.\r\n */\r\n getApplicableTaxRate(unitPrice: PriceModel): number {\r\n return TaxRuleModel.getApplicableTaxRate(unitPrice, this.slabs);\r\n }\r\n\r\n /**\r\n * Returns a user-friendly string representation of the applicable tax rate.\r\n * Handles legal IGST/CGST/SGST formatting for India if states are provided.\r\n * @param unitPrice - The unit price to find the matching tax slab for.\r\n * @param options - Optional states to determine IGST vs CGST/SGST.\r\n * @returns A string like \"18% IGST\", \"9% CGST + 9% SGST\", or \"5% GST\".\r\n */\r\n getTaxRateDisplayString(unitPrice: PriceModel, options?: { merchantState?: string, customerState?: string }): string {\r\n const rate = this.getApplicableTaxRate(unitPrice);\r\n return TaxRuleModel.getTaxRateDisplayString(rate, {\r\n taxSystem: this.taxSystem,\r\n merchantState: options?.merchantState,\r\n customerState: options?.customerState\r\n });\r\n }\r\n\r\n /**\r\n * Returns a detailed breakdown of the tax rate into its components (e.g., CGST/SGST).\r\n */\r\n getTaxRateBreakdown(unitPrice: PriceModel, options?: TaxFormattingOptions): TaxRateBreakdown {\r\n const rate = this.getApplicableTaxRate(unitPrice);\r\n const formatter = TaxFormatterRegistry[this.taxSystem];\r\n if (formatter) {\r\n return formatter.getBreakdown(rate, this.country, options);\r\n }\r\n\r\n // Default fallback\r\n const percentage = rate * 100;\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n const label = `${rateStr}% ${this.taxSystem}`;\r\n return {\r\n totalRate: rate,\r\n label: label,\r\n components: [{ rate, label, type: this.taxSystem }]\r\n };\r\n }\r\n\r\n /**\r\n * Formats a tax rate based on versatile options for UI use cases.\r\n */\r\n getFormattedTaxRate(unitPrice: PriceModel, options: TaxFormattingOptions = {}): string {\r\n const rate = this.getApplicableTaxRate(unitPrice);\r\n const percentage = rate * 100;\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n const variant = options.variant || 'short';\r\n let result = '';\r\n\r\n switch (variant) {\r\n case 'percentageOnly':\r\n result = `${rateStr}%`;\r\n break;\r\n case 'detailed':\r\n const breakdown = this.getTaxRateBreakdown(unitPrice, options);\r\n const separator = options.separator || (options.multiline ? '\\n' : ' + ');\r\n result = breakdown.components.map(c => c.label).join(separator);\r\n break;\r\n case 'long':\r\n const formatter = TaxFormatterRegistry[this.taxSystem];\r\n const systemLongName = formatter ? formatter.getLongName(this.country) : this.taxSystem.toString();\r\n result = `${rateStr}% ${systemLongName}`;\r\n break;\r\n case 'short':\r\n default:\r\n result = `${rateStr}% ${this.taxSystem}`;\r\n break;\r\n }\r\n\r\n if (options.includeTaxesSuffix) {\r\n result += ' (Incl. Taxes)';\r\n }\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Static method to find the applicable tax rate from a list of slabs.\r\n */\r\n static getApplicableTaxRate(unitPrice: PriceModel, taxSlabs: TaxSlabModel[]): number {\r\n const slabs = taxSlabs.filter(s =>\r\n (s.minUnitPrice === undefined || unitPrice.compareTo(s.minUnitPrice) >= 0) &&\r\n (s.maxUnitPrice === undefined || unitPrice.compareTo(s.maxUnitPrice) < 0)\r\n );\r\n\r\n if (slabs.length !== 1) {\r\n throw new TaxSlabNotFoundError();\r\n }\r\n\r\n return slabs[0].rate;\r\n }\r\n\r\n /**\r\n * Static method to format a tax rate as a display string.\r\n * Handles legal IGST/CGST/SGST formatting for India if states are provided.\r\n * @param rate - The tax rate as a decimal (e.g., 0.18).\r\n * @param options - Configuration for tax system name and states.\r\n * @returns A formatted string.\r\n */\r\n static getTaxRateDisplayString(rate: number, options: {\r\n taxSystem?: string,\r\n merchantState?: string,\r\n customerState?: string\r\n }): string {\r\n const percentage = rate * 100;\r\n // Format to remove trailing zeros if it's an integer, otherwise keep up to 2 decimal places\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n\r\n if (options.taxSystem === TaxSystem.GST && options.merchantState && options.customerState) {\r\n if (options.merchantState.toLowerCase().trim() === options.customerState.toLowerCase().trim()) {\r\n const splitRate = (percentage / 2) % 1 === 0 ? (percentage / 2).toString() : (percentage / 2).toFixed(2).replace(/\\.?0+$/, '');\r\n return `${splitRate}% CGST + ${splitRate}% SGST`;\r\n } else {\r\n return `${rateStr}% IGST`;\r\n }\r\n }\r\n\r\n return options.taxSystem ? `${rateStr}% ${options.taxSystem}` : `${rateStr}%`;\r\n }\r\n}\r\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/Error.ts"],"names":["LineItemNotFoundError","lineItemId","InvalidLineItemStateError","state","DuplicateSizeError","size","DuplicateSelectionAttributeError","attribute","ProductMismatchError","message","ProductInactiveError","SelectionAttributeParseError","SizeMismatchError","PricingNotFoundError","InvalidTaxRuleError","InvalidTaxCategoryError","InvalidMinQuantityError","InvalidTieredPriceError","InvalidQuantityError","NoApplicableTierError","quantity","TaxSlabNotFoundError","InvalidPriceAmountError","InvalidCurrencyCodeError","CurrencyMismatchError","InvalidArgumentError","InvalidImageSourceError"],"mappings":"AAAO,IAAMA,EAAN,cAAoC,KAAM,CAC7C,WAAYC,CAAAA,CAAAA,CAAoB,CAC5B,KAAM,CAAA,CAAA,mBAAA,EAAsBA,CAAU,CAA0B,wBAAA,CAAA,CAAA,CAChE,KAAK,IAAO,CAAA,wBAChB,CACJ,CAEaC,CAAAA,CAAAA,CAAN,cAAwC,KAAM,CACjD,WAAYC,CAAAA,CAAAA,CAAe,CACvB,KAAM,CAAA,CAAA,yBAAA,EAA4BA,CAAK,CAAE,CAAA,CAAA,CACzC,KAAK,IAAO,CAAA,4BAChB,CACJ,CAEaC,CAAAA,CAAAA,CAAN,cAAiC,KAAM,CAC1C,YAAYC,CAAc,CAAA,CACtB,MAAM,CAAyBA,sBAAAA,EAAAA,CAAI,CAAE,CAAA,CAAA,CACrC,KAAK,IAAO,CAAA,qBAChB,CACJ,CAEaC,CAAAA,CAAAA,CAAN,cAA+C,KAAM,CACxD,YAAYC,CAAmB,CAAA,CAC3B,MAAM,CAAwCA,qCAAAA,EAAAA,CAAS,EAAE,CACzD,CAAA,IAAA,CAAK,KAAO,mCAChB,CACJ,EAEaC,CAAN,CAAA,cAAmC,KAAM,CAC5C,WAAA,CAAYC,EAAkB,gDAAkD,CAAA,CAC5E,MAAM,CAAoBA,iBAAAA,EAAAA,CAAO,EAAE,CACnC,CAAA,IAAA,CAAK,KAAO,uBAChB,CACJ,EAEaC,CAAN,CAAA,cAAmC,KAAM,CAC5C,WAAA,CAAYD,CAAkB,CAAA,wBAAA,CAA0B,CACpD,KAAM,CAAA,CAAA,iBAAA,EAAoBA,CAAO,CAAE,CAAA,CAAA,CACnC,KAAK,IAAO,CAAA,uBAChB,CACJ,CAEaE,CAAAA,CAAAA,CAAN,cAA2C,KAAM,CACpD,YAAYF,CAAkB,CAAA,2CAAA,CAA6C,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ACtC,IAAK,CAAA,IAAA,CAAO,0BAChB,CACJ","file":"chunk-JHELVQYY.mjs","sourcesContent":["export class LineItemNotFoundError extends Error {\r\n constructor(lineItemId: string) {\r\n super(`Line item with ID '${lineItemId}' not found in the cart.`);\r\n this.name = 'LineItemNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidLineItemStateError extends Error {\r\n constructor(state: string) {\r\n super(`Invalid line item state: ${state}`);\r\n this.name = 'InvalidLineItemStateError';\r\n }\r\n}\r\n\r\nexport class DuplicateSizeError extends Error {\r\n constructor(size: string) {\r\n super(`Duplicate size found: ${size}`);\r\n this.name = 'DuplicateSizeError';\r\n }\r\n}\r\n\r\nexport class DuplicateSelectionAttributeError extends Error {\r\n constructor(attribute: string) {\r\n super(`Duplicate selection attribute found: ${attribute}`);\r\n this.name = 'DuplicateSelectionAttributeError';\r\n }\r\n}\r\n\r\nexport class ProductMismatchError extends Error {\r\n constructor(message: string = \"Product and selection attributes do not match.\") {\r\n super(`ProductMismatch: ${message}`);\r\n this.name = 'ProductMismatchError';\r\n }\r\n}\r\n\r\nexport class ProductInactiveError extends Error {\r\n constructor(message: string = \"Product is not active.\") {\r\n super(`ProductInactive: ${message}`);\r\n this.name = 'ProductInactiveError';\r\n }\r\n}\r\n\r\nexport class SelectionAttributeParseError extends Error {\r\n constructor(message: string = \"Failed to parse selection attributes key.\") {\r\n super(`SelectionAttributeParseError: ${message}`);\r\n this.name = 'SelectionAttributeParseError';\r\n }\r\n}\r\n\r\nexport class SizeMismatchError extends Error {\r\n constructor(message: string = \"Size does not match.\") {\r\n super(`SizeMismatch: ${message}`);\r\n this.name = 'SizeMismatchError';\r\n }\r\n}\r\n\r\nexport class PricingNotFoundError extends Error {\r\n constructor(message: string = \"Pricing details not available for the product\") {\r\n super(`NotFound: ${message}`);\r\n this.name = 'PricingNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxRuleError extends Error {\r\n constructor(message: string = \"Tax rule category mismatch.\") {\r\n super(`InvalidTaxRule: ${message}`);\r\n this.name = 'InvalidTaxRuleError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxCategoryError extends Error {\r\n constructor(message: string = \"Tax category is not valid.\") {\r\n super(`InvalidTaxCategory: ${message}`);\r\n this.name = 'InvalidTaxCategoryError';\r\n }\r\n}\r\n\r\nexport class InvalidMinQuantityError extends Error {\r\n constructor(message: string = \"Minimum quantity must be greater than zero.\") {\r\n super(`InvalidMinQuantity: ${message}`);\r\n this.name = 'InvalidMinQuantityError';\r\n }\r\n}\r\n\r\nexport class InvalidTieredPriceError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidTieredPrice: ${message}`);\r\n this.name = 'InvalidTieredPriceError';\r\n }\r\n}\r\n\r\nexport class InvalidQuantityError extends Error {\r\n constructor(message: string = \"Quantity must be greater than zero.\") {\r\n super(`InvalidQuantity: ${message}`);\r\n this.name = 'InvalidQuantityError';\r\n }\r\n}\r\n\r\nexport class NoApplicableTierError extends Error {\r\n constructor(quantity: number) {\r\n super(`NoApplicableTier: Quantity ${quantity} does not meet the minimum purchase requirement.`);\r\n this.name = 'NoApplicableTierError';\r\n }\r\n}\r\n\r\nexport class TaxSlabNotFoundError extends Error {\r\n constructor(message: string = \"No applicable tax slab or multiple slabs found for the given unit price.\") {\r\n super(`TaxSlabNotFound: ${message}`);\r\n this.name = 'TaxSlabNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidPriceAmountError extends Error {\r\n constructor(message: string = \"Amount cannot be negative.\") {\r\n super(`InvalidAmount: ${message}`);\r\n this.name = 'InvalidPriceAmountError';\r\n }\r\n}\r\n\r\nexport class InvalidCurrencyCodeError extends Error {\r\n constructor(message: string = \"Currency code is required.\") {\r\n super(`InvalidCurrency: ${message}`);\r\n this.name = 'InvalidCurrencyCodeError';\r\n }\r\n}\r\n\r\nexport class CurrencyMismatchError extends Error {\r\n constructor(message: string = \"Cannot perform operation on prices with different currencies.\") {\r\n super(`CurrencyMismatch: ${message}`);\r\n this.name = 'CurrencyMismatchError';\r\n }\r\n}\r\n\r\nexport class InvalidArgumentError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidArgument: ${message}`);\r\n this.name = 'InvalidArgumentError';\r\n }\r\n}\r\n\r\nexport class InvalidImageSourceError extends Error {\r\n constructor(message: string = \"Invalid image source configuration.\") {\r\n super(`InvalidImageSource: ${message}`);\r\n this.name = 'InvalidImageSourceError';\r\n }\r\n}"]}
|
package/dist/chunk-SFUOYZ3L.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {a}from'./chunk-TJ7AZBND.mjs';import {k,l,m,n,o}from'./chunk-JHELVQYY.mjs';var y=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new a(t.baseUnitPrice);if(!t.taxCategory)throw new k;let r=(t.tiers??[]).map(i=>({minQuantity:i.minQuantity,unitPrice:new a(i.unitPrice)})).sort((i,n)=>i.minQuantity-n.minQuantity);if(r.some(i=>i.minQuantity<=0))throw new l;let m$1=r.some(i=>i.unitPrice.getCurrency()!==e.getCurrency()),g=r.some((i,n)=>n>0&&i.unitPrice.compareTo(r[n-1].unitPrice)>0),h=r[0]?.unitPrice.compareTo(e)>0;if(m$1||g||h)throw new m("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=e,this.taxCategory=t.taxCategory,this.tiers=r;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}}getApplicableTier(t){if(t<=0)throw new n;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity)return this.tiers[e];throw new o(t)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let t=this.tiers[this.tiers.length-1].unitPrice.getAmount(),e=this.baseUnitPrice.getAmount();return (e-t)/e*100}};export{y as a};//# sourceMappingURL=chunk-SFUOYZ3L.mjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-SFUOYZ3L.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/TieredPrice.ts"],"names":["TieredPriceModel","data","baseUnitPrice","PriceModel","InvalidTaxCategoryError","tiers","tier","a","b","t","InvalidMinQuantityError","hasDifferentCurrency","hasIrregularPricing","index","basePriceExceedsFirstTier","InvalidTieredPriceError","quantity","InvalidQuantityError","i","NoApplicableTierError","lowestTierPrice","basePrice"],"mappings":"kFAkCaA,IAAAA,CAAAA,CAAN,KAAuB,CAClB,aACA,CAAA,WAAA,CACA,KAWV,CAAA,WAAA,CAAYC,CAA6B,CAAA,CACvC,IAAMC,CAAAA,CAAgB,IAAIC,CAAAA,CAAWF,CAAK,CAAA,aAAa,CAEvD,CAAA,GAAI,CAACA,CAAAA,CAAK,WACR,CAAA,MAAM,IAAIG,CAAAA,CAGZ,IAAMC,CAAAA,CAAAA,CAASJ,CAAK,CAAA,KAAA,EAAS,EAAC,EAC3B,GAAIK,CAAAA,CAAAA,GAAS,CACZ,WAAA,CAAaA,CAAK,CAAA,WAAA,CAClB,SAAW,CAAA,IAAIH,CAAWG,CAAAA,CAAAA,CAAK,SAAS,CAC1C,CAAE,CAAA,CAAA,CACD,IAAK,CAAA,CAACC,CAAGC,CAAAA,CAAAA,GAAMD,CAAE,CAAA,WAAA,CAAcC,CAAE,CAAA,WAAW,CAG/C,CAAA,GAD8BH,CAAM,CAAA,IAAA,CAAKI,CAAKA,EAAAA,CAAAA,CAAE,WAAe,EAAA,CAAC,CAE9D,CAAA,MAAM,IAAIC,CAGZ,CAAA,IAAMC,GAAuBN,CAAAA,CAAAA,CAAM,IACjCI,CAAAA,CAAAA,EAAKA,CAAE,CAAA,SAAA,CAAU,WAAY,EAAA,GAAMP,CAAc,CAAA,WAAA,EACnD,CAAA,CACMU,CAAsBP,CAAAA,CAAAA,CAAM,I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,CAAC,CAAE,CAAA,WAAA,CAC5B,OAAO,IAAA,CAAK,KAAMA,CAAAA,CAAC,CAIvB,CAAA,MAAM,IAAIC,CAAAA,CAAsBH,CAAQ,CAC1C,CAKA,cAAA,EAAyB,CACvB,OAAO,IAAK,CAAA,KAAA,CAAM,CAAC,CAAA,EAAG,WAAe,EAAA,CACvC,CAKA,qBAAA,EAAgC,CAC9B,GAAI,CAAC,IAAA,CAAK,KAAM,CAAA,MAAA,CAAQ,OAAO,CAAA,CAE/B,IAAMI,CAAAA,CAAkB,IAAK,CAAA,KAAA,CAAM,IAAK,CAAA,KAAA,CAAM,MAAS,CAAA,CAAC,CAAE,CAAA,SAAA,CAAU,SAAU,EAAA,CACxEC,CAAY,CAAA,IAAA,CAAK,aAAc,CAAA,SAAA,EAErC,CAAA,OAAA,CAASA,CAAYD,CAAAA,CAAAA,EAAmBC,CAAa,CAAA,GACvD,CACF","file":"chunk-SFUOYZ3L.mjs","sourcesContent":["import { TaxCategory } from \"./Enum\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport {\r\n InvalidTaxCategoryError,\r\n InvalidMinQuantityError,\r\n InvalidTieredPriceError,\r\n InvalidQuantityError,\r\n NoApplicableTierError\r\n} from \"./Error\";\r\n\r\n/**\r\n * Represents a pricing tier based on a minimum purchase quantity.\r\n */\r\nexport type PriceTier = {\r\n minQuantity: number;\r\n unitPrice: PriceModel;\r\n};\r\n\r\n/**\r\n * Represents the attributes required for tiered pricing.\r\n */\r\nexport type TieredPriceAttributes = {\r\n baseUnitPrice: PriceData;\r\n taxCategory: TaxCategory;\r\n\r\n /** Quantity-based pricing tiers */\r\n tiers: {\r\n minQuantity: number;\r\n unitPrice: PriceData;\r\n }[];\r\n};\r\n\r\nexport type TieredPriceData = TieredPriceAttributes;\r\n\r\nexport class TieredPriceModel {\r\n protected baseUnitPrice: PriceModel;\r\n protected taxCategory: TaxCategory;\r\n protected tiers: PriceTier[];\r\n\r\n /** Constructor\r\n * Initializes the tiered pricing model with the provided attributes.\r\n * @param data - The tiered pricing attributes.\r\n *\r\n * @throws {Error}\r\n * - If the tax category is not valid\r\n * - If any tier has an invalid minimum quantity or unit price\r\n * - If the base unit price is not valid\r\n */\r\n constructor(data: TieredPriceAttributes) {\r\n const baseUnitPrice = new PriceModel(data.baseUnitPrice);\r\n\r\n if (!data.taxCategory) {\r\n throw new InvalidTaxCategoryError();\r\n }\r\n\r\n const tiers = (data.tiers ?? [])\r\n .map(tier => ({\r\n minQuantity: tier.minQuantity,\r\n unitPrice: new PriceModel(tier.unitPrice),\r\n }))\r\n .sort((a, b) => a.minQuantity - b.minQuantity);\r\n\r\n const hasInvalidMinQuantity = tiers.some(t => t.minQuantity <= 0);\r\n if (hasInvalidMinQuantity) {\r\n throw new InvalidMinQuantityError();\r\n }\r\n\r\n const hasDifferentCurrency = tiers.some(\r\n t => t.unitPrice.getCurrency() !== baseUnitPrice.getCurrency()\r\n );\r\n const hasIrregularPricing = tiers.some(\r\n (tier, index) =>\r\n index > 0 &&\r\n tier.unitPrice.compareTo(tiers[index - 1].unitPrice) > 0\r\n );\r\n const basePriceExceedsFirstTier = tiers[0]?.unitPrice.compareTo(baseUnitPrice) > 0;\r\n\r\n if (hasDifferentCurrency || hasIrregularPricing || basePriceExceedsFirstTier) {\r\n throw new InvalidTieredPriceError(\r\n \"Tiers must share the same currency and must not increase in unit price.\"\r\n );\r\n }\r\n\r\n this.baseUnitPrice = baseUnitPrice;\r\n this.taxCategory = data.taxCategory;\r\n this.tiers = tiers;\r\n }\r\n\r\n /** \r\n * Returns the base unit price \r\n * @returns The base unit price as a PriceModel instance.\r\n */\r\n getBaseUnitPrice(): PriceModel {\r\n return this.baseUnitPrice;\r\n }\r\n\r\n /** \r\n * Returns the tax category \r\n * @returns The tax category as a TaxCategory enum value.\r\n */\r\n getTaxCategory(): TaxCategory {\r\n return this.taxCategory;\r\n }\r\n\r\n /** \r\n * Returns all pricing tiers sorted by minimum quantity \r\n * @returns An array of PriceTier objects.\r\n */\r\n getTiers(): readonly PriceTier[] {\r\n return this.tiers;\r\n }\r\n\r\n getDetails(): TieredPriceData {\r\n return {\r\n baseUnitPrice: this.baseUnitPrice.getDetails(),\r\n taxCategory: this.taxCategory,\r\n tiers: this.tiers.map(tier => ({\r\n minQuantity: tier.minQuantity,\r\n unitPrice: tier.unitPrice.getDetails()\r\n }))\r\n };\r\n }\r\n\r\n /**\r\n * Returns the applicable unit price for a given quantity.\r\n *\r\n * @param quantity - Purchase quantity\r\n * @returns The unit price for the highest applicable tier\r\n *\r\n * @throws {Error}\r\n * - If quantity is less than or equal to zero\r\n * - If quantity does not meet the minimum requirement of any tier\r\n */\r\n getApplicableTier(quantity: number): PriceTier {\r\n if (quantity <= 0) {\r\n throw new InvalidQuantityError();\r\n }\r\n\r\n for (let i = this.tiers.length - 1; i >= 0; i--) {\r\n if (quantity >= this.tiers[i].minQuantity) {\r\n return this.tiers[i];\r\n }\r\n }\r\n\r\n throw new NoApplicableTierError(quantity);\r\n }\r\n\r\n /**\r\n * Returns the minimum quantity required to purchase this product.\r\n */\r\n getMinQuantity(): number {\r\n return this.tiers[0]?.minQuantity ?? 1;\r\n }\r\n\r\n /**\r\n * Returns the maximum discount percentage achievable compared to the base unit price.\r\n */\r\n getMaxDiscountPercent(): number {\r\n if (!this.tiers.length) return 0;\r\n\r\n const lowestTierPrice = this.tiers[this.tiers.length - 1].unitPrice.getAmount();\r\n const basePrice = this.baseUnitPrice.getAmount();\r\n\r\n return ((basePrice - lowestTierPrice) / basePrice) * 100;\r\n }\r\n}\r\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/Price.ts"],"names":["PriceModel","_PriceModel","#kind","data","InvalidPriceAmountError","InvalidCurrencyCodeError","obj","priceModel","CurrencyMismatchError","InvalidArgumentError","factor","divisor","priceModels","minPrice","currentPrice","maxPrice","amount","currency","options","locale","CurrencyLocaleMap","valueToFormat","fractionDigits","formattingOptions","error","CurrencySymbolMap","numStr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A,CAAiBgB,GAAQ,CACpDc,CAAAA,CAAAA,CAAa,KAAK,GAAI,CAAA,EAAA,CAAID,CAAa,CAAA,CAG7C,OAFqB,IAAK,CAAA,KAAA,CAAMd,EAASe,CAAU,CAAA,CAAIA,CAGzD,CACF","file":"chunk-TJ7AZBND.mjs","sourcesContent":["import { CurrencyCode } from \"./Common\";\r\nimport { CurrencyLocaleMap, CurrencySymbolMap, OperationalCountryCurrency } from \"./Enum\";\r\nimport {\r\n InvalidPriceAmountError,\r\n InvalidCurrencyCodeError,\r\n CurrencyMismatchError,\r\n InvalidArgumentError\r\n} from \"./Error\";\r\n\r\nexport type PriceAttributes = {\r\n amount: number;\r\n currency: CurrencyCode;\r\n}\r\n\r\nexport type PriceData = PriceAttributes;\r\n\r\nexport default class PriceModel {\r\n #kind: string;\r\n protected amount: number;\r\n protected currency: CurrencyCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param amount - The initial price value.\r\n * @param currency - The currency code used for rounding and determining the currency symbol.\r\n * @throws {Error} If price is negative or country/currency mapping is missing.\r\n */\r\n constructor(data: PriceAttributes) {\r\n this.#kind = \"PriceModel\";\r\n if (data.amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative.\");\r\n }\r\n\r\n if (!data.currency) {\r\n throw new InvalidCurrencyCodeError(\"Currency code is required.\");\r\n }\r\n\r\n this.amount = data.amount;\r\n this.currency = data.currency;\r\n }\r\n\r\n get kind() {\r\n return this.#kind;\r\n }\r\n\r\n static isPriceModel(obj: unknown): obj is PriceModel {\r\n return typeof obj === \"object\" &&\r\n obj !== null &&\r\n (obj as any).kind === \"PriceModel\";\r\n }\r\n\r\n /**\r\n * Gets the currency associated with this price instance.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Returns the raw numeric price value.\r\n */\r\n public getAmount(): number {\r\n return this.amount;\r\n }\r\n\r\n /**\r\n *\r\n * @returns PriceData\r\n */\r\n public getDetails(): PriceData {\r\n return {\r\n amount: this.amount,\r\n currency: this.currency\r\n }\r\n }\r\n\r\n /**\r\n * Compares this price with another {@link PriceModel} instance.\r\n *\r\n * The comparison is performed using the numeric price value and is only valid\r\n * when both prices are expressed in the same currency.\r\n *\r\n * ### Comparison result:\r\n * - Returns a **negative number** if this price is **less than** `priceModel`\r\n * - Returns **zero** if both prices are **equal**\r\n * - Returns a **positive number** if this price is **greater than** `priceModel`\r\n *\r\n * @param priceModel - The {@link PriceModel} instance to compare against.\r\n *\r\n * @returns\r\n * A signed number representing the comparison result:\r\n * - `< 0` → this price is lower\r\n * - `0` → prices are equal\r\n * - `> 0` → this price is higher\r\n *\r\n * @throws {Error}\r\n * Throws an error if:\r\n * - `priceModel` is not an instance of {@link PriceModel}\r\n * - The currencies of the two prices do not match\r\n *\r\n * @example\r\n * ```ts\r\n * const a = new PriceModel(\"USD\", 100);\r\n * const b = new PriceModel(\"USD\", 150);\r\n *\r\n * a.compareTo(b); // -50\r\n * b.compareTo(a); // 50\r\n * a.compareTo(a); // 0\r\n * ```\r\n */\r\n public compareTo(priceModel: PriceModel): number {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return this.amount - priceModel.getAmount();\r\n }\r\n\r\n public add(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot add prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.amount + priceModel.getAmount(),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public subtract(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot subtract prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.amount - priceModel.getAmount(),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public multiply(factor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(factor)) {\r\n if (this.currency !== factor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot multiply prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.amount * factor.getAmount(),\r\n currency: this.currency\r\n });\r\n } else if (typeof factor === \"number\" && factor >= 0) {\r\n return new PriceModel({\r\n amount: this.amount * factor,\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a non-negative number.\");\r\n }\r\n\r\n public divide(divisor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(divisor)) {\r\n if (this.currency !== divisor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot divide prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.amount / divisor.getAmount(),\r\n currency: this.currency\r\n });\r\n } else if (typeof divisor === \"number\" && divisor > 0) {\r\n return new PriceModel({\r\n amount: this.amount / divisor,\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a positive number.\");\r\n }\r\n\r\n public min(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((minPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (minPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return minPrice.compareTo(currentPrice) < 0 ? minPrice : currentPrice;\r\n });\r\n }\r\n\r\n public max(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((maxPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (maxPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return maxPrice.compareTo(currentPrice) > 0 ? maxPrice : currentPrice;\r\n });\r\n }\r\n\r\n /**\r\n * Gets a zero value PriceModel for the same currency.\r\n * @returns A PriceModel instance representing zero in the same currency.\r\n */\r\n public zero(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: 0\r\n });\r\n }\r\n\r\n /**\r\n * Checks if the price is zero.\r\n * @returns True if the price is zero, false otherwise.\r\n */\r\n public isZero(): boolean {\r\n return this.amount === 0;\r\n }\r\n\r\n\r\n public round(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: this.getRoundedAmount()\r\n });\r\n }\r\n /**\r\n * Gets the rounded price value based on standard currency rules.\r\n * @returns The numeric price, rounded according to its currency's typical decimal places.\r\n */\r\n public getRoundedAmount(): number {\r\n return PriceModel.getRoundedAmount(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price stored in this instance.\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n public getFormattedString() {\r\n return PriceModel.getFormattedString(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n toString() {\r\n return this.getFormattedString();\r\n }\r\n\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the amount.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param amount - The initial amount value.\r\n * @param currency - The currency code for formatting.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the amount rounded to the next nearest integer (no decimals). Defaults to false.\r\n * @param options.style - The style of formatting, either 'currency' or 'decimal'. Defaults to 'currency'.\r\n * @param options.currencyDisplay - The display format for the currency symbol. Options are 'symbol', 'narrowSymbol', 'code', or 'name'. Defaults to 'symbol'.\r\n * @returns The formatted price string according to locale rules.\r\n * @throws {Error} If currency code is invalid.\r\n */\r\n static getFormattedString(amount: number, currency: CurrencyCode, options: {\r\n displayAsInteger?: boolean,\r\n style?: 'currency' | 'decimal',\r\n currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name'\r\n } = {\r\n displayAsInteger: false,\r\n style: 'currency',\r\n currencyDisplay: 'symbol'\r\n }): string {\r\n\r\n const locale = CurrencyLocaleMap[currency];\r\n if (!currency || !locale) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for formatting.');\r\n }\r\n\r\n let valueToFormat = amount;\r\n const fractionDigits = options.displayAsInteger ? 0 : PriceModel.getDecimalPlaces(currency);\r\n\r\n let formattingOptions: Intl.NumberFormatOptions = {\r\n style: options.style ?? 'currency',\r\n currency: currency,\r\n signDisplay: 'never',\r\n currencyDisplay: options.currencyDisplay,\r\n minimumFractionDigits: fractionDigits,\r\n maximumFractionDigits: fractionDigits,\r\n };\r\n\r\n if (options.displayAsInteger) {\r\n valueToFormat = Math.ceil(valueToFormat);\r\n }\r\n\r\n try {\r\n return new Intl.NumberFormat(locale, formattingOptions).format(valueToFormat);\r\n } catch (error) {\r\n console.error(`Error formatting price for currency \"${currency}\" and locale \"${locale}\":`, error);\r\n // Basic fallback without symbol if Intl fails completely\r\n return `${CurrencySymbolMap[currency] ?? currency} ${PriceModel.addThousandSeparators(valueToFormat.toFixed(fractionDigits))}`;\r\n }\r\n }\r\n\r\n /**\r\n * Helper method to determine standard decimal places for a currency.\r\n * @param currency - The currency code.\r\n * @returns The number of decimal places (0, 2, or 3 based on common rules).\r\n */\r\n private static getDecimalPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case OperationalCountryCurrency.INR:\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n /**\r\n * Adds basic thousand separators (commas) to a number string.\r\n * Does not handle different locale separators (e.g., periods, spaces).\r\n * @param numStr - The number string (potentially with decimals).\r\n * @returns The number string with commas added.\r\n */\r\n private static addThousandSeparators(numStr: string): string {\r\n const parts = numStr.split('.');\r\n const integerPart = parts[0];\r\n const decimalPart = parts.length > 1 ? '.' + parts[1] : '';\r\n\r\n const formattedInteger = integerPart.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\r\n return formattedInteger + decimalPart;\r\n }\r\n\r\n /**\r\n * Rounds a price value according to the standard decimal places\r\n * for the currency associated with the given country.\r\n *\r\n * @param price - The price value to round. Must be a non-negative number.\r\n * @param currency - The currency code to determine the rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the price is negative or currency is invalid.\r\n */\r\n static getRoundedAmount(amount: number, currency: CurrencyCode): number {\r\n if (amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative for rounding.\");\r\n }\r\n\r\n if (currency === undefined) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for rounding.');\r\n }\r\n\r\n const decimalPlaces = PriceModel.getDecimalPlaces(currency);\r\n const multiplier = Math.pow(10, decimalPlaces);\r\n const roundedValue = Math.round(amount * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n}"]}
|
package/dist/chunk-ZE7D77FR.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {c as c$1}from'./chunk-ARMBZF3E.mjs';import {a as a$1}from'./chunk-AWZ6KRLF.mjs';import {a as a$3}from'./chunk-SFUOYZ3L.mjs';import {a as a$2}from'./chunk-TJ7AZBND.mjs';import {e,n}from'./chunk-72DR3HF2.mjs';import {b}from'./chunk-WSUPVXRZ.mjs';import {c,e as e$1,f,h,i,j,b as b$1}from'./chunk-JHELVQYY.mjs';import {a}from'./chunk-6KCJVEZD.mjs';var p=class extends a{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,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 i=new Set;this.subItems.forEach(e=>{if(i.has(e.size))throw new c(e.size);i.add(e.size);}),this.pricing={unitPrice:new a$2(t.pricing.unitPrice),tierPricing:new a$3(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,tax:{taxRuleId:t.pricing.tax.taxRuleId,taxSystem:t.pricing.tax.taxSystem,country:t.pricing.tax.country,rate:t.pricing.tax.rate,taxSlabs:t.pricing.tax.taxSlabs.map(e=>({rate:e.rate,minUnitPrice:new a$2(e.minUnitPrice),maxUnitPrice:e.maxUnitPrice?new a$2(e.maxUnitPrice):void 0}))}},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,subtotal:new a$2(t.total.subtotal),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([e,a])=>[e,new a$2(a)])),taxableAmount:new a$2(t.total.taxableAmount),taxTotal:new a$2(t.total.taxTotal),grandTotal:new a$2(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}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,tax:{taxRuleId:this.pricing.tax.taxRuleId,taxSystem:this.pricing.tax.taxSystem,country:this.pricing.tax.country,rate:this.pricing.tax.rate,taxSlabs:this.pricing.tax.taxSlabs}}}getState(){return this.state}getTotal(){return {quantity:this.total.quantity,subtotal:this.total.subtotal,taxableAmount:this.total.taxableAmount,taxTotal:this.total.taxTotal,discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,i])=>[t,i])),grandTotal:this.total.grandTotal}}getDetails(){return {id:this.getId(),productKey:this.getProductKey(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:this.getPricing().unitPrice.getDetails(),tierPricing:this.getPricing().tierPricing.getDetails(),taxCategory:this.getPricing().taxCategory,tax:{taxRuleId:this.getPricing().tax.taxRuleId,taxSystem:this.getPricing().tax.taxSystem,country:this.getPricing().tax.country,rate:this.getPricing().tax.rate,taxSlabs:this.getPricing().tax.taxSlabs.map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0}))}},state:this.getState(),total:{quantity:this.getTotal().quantity,subtotal:this.getTotal().subtotal.getDetails(),taxableAmount:this.getTotal().taxableAmount.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),discounts:Object.fromEntries(Object.entries(this.getTotal().discounts).map(([t,i])=>[t,i.getDetails()])),grandTotal:this.getTotal().grandTotal.getDetails()},customFields:this.getAllCustomFields()}}addSubItems(t,i){t.forEach(e=>{let a=this.subItems.find(s=>s.size===e.size);a?a.quantity=i?a.quantity+e.quantity:e.quantity:this.subItems.push(e);}),this.subItems=this.subItems.filter(e=>e.quantity>0),this.calculateTotals();}updateProductData(t,i$1,e){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new e$1;if(!t.getIsActive())throw new f;this.subItems.forEach(c=>{if(!t.validateSize(c.size))throw new h});let a=t.getPriceDetails(i$1);if(!a||a.getBaseUnitPrice().getCurrency()!==e)throw new i;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let s=this.subItems.reduce((c,l)=>c+l.quantity,0),{unitPrice:n}=a.getApplicableTier(s);this.pricing={unitPrice:n,tierPricing:a,taxCategory:a.getTaxCategory(),tax:this.pricing.tax},this.calculateTotals();}updateDiscounts(t){let i={};t.forEach(e=>{i[e.coupon.getCode()]=e.amount;}),this.total.discounts=i,this.calculateTotals();}updateTax(t){if(!t.appliesTo(this.pricing.taxCategory,this.pricing.tax.country))throw new j;let i=this.total.quantity>0?this.total.taxableAmount.divide(this.total.quantity):this.total.taxableAmount.zero();this.pricing.tax={taxRuleId:t.getTaxRuleId(),taxSystem:t.getTaxSystem(),country:t.getCountry(),rate:t.getApplicableTaxRate(i),taxSlabs:t.getSlabs()},this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),i=this.subItems.reduce((u,g)=>u+g.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,subtotal:t,taxableAmount:t,taxTotal:t,discounts:{},grandTotal:t};return}let{unitPrice:e}=this.pricing.tierPricing.getApplicableTier(i),a=e.multiply(i),s=Object.values(this.total.discounts).reduce((u,g)=>u.add(g),t),n=a.subtract(s),c=i>0?n.divide(i):t,l=c$1.getApplicableTaxRate(c,this.pricing.tax.taxSlabs),h=n.multiply(l).round(),D=a.subtract(s).add(h);this.total={quantity:i,subtotal:a,taxableAmount:n,taxTotal:h,discounts:this.total.discounts,grandTotal:D};}updateState(t){if(this.state in n)this.state!==t&&(this.state=t);else throw new b$1(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new b({sources:{original:""}}),this.subItems=[],this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:this.pricing.tax},this.total={quantity:0,subtotal:t,taxableAmount:t,taxTotal:t,discounts:{},grandTotal:t};}};export{p as a};//# sourceMappingURL=chunk-ZE7D77FR.mjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-ZE7D77FR.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","s","couponCode","discount","locale","LocaleLanguageMap","subItems","addQuantity","subItem","existingSubItem","sub","product","cartCountry","cartCurrency","ProductMismatchError","ProductInactiveError","SizeMismatchError","productPricing","PricingNotFoundError","quantity","sum","unitPrice","appliedDiscounts","lineItemDiscounts","taxRule","InvalidTaxRuleError","taxableUnitPrice","zero","totalQuantity","subTotal","discounts","taxableAmount","unitTaxbleAmount","taxRate","TaxRuleModel","taxTotal","grandTotal","newState","LineItemState","InvalidLineItemStateError"],"mappings":"gWAsEA,IAAqBA,CAArB,CAAA,cAA2CC,CAAiB,CAChD,EACA,CAAA,UAAA,CACA,mBAEA,CAAA,IAAA,CACA,cACA,CAAA,YAAA,CACA,QACA,CAAA,OAAA,CAaA,MACA,KAcV,CAAA,WAAA,CAAYC,CAA0B,CAAA,CACpC,KAAMA,CAAAA,CAAI,CACV,CAAA,IAAA,CAAK,EAAKA,CAAAA,CAAAA,CAAK,EACf,CAAA,IAAA,CAAK,UAAaA,CAAAA,CAAAA,CAAK,UACvB,CAAA,IAAA,CAAK,oBAAsBC,GAAM,CAAA,SAAA,CAAUD,CAAK,CAAA,mBAAmB,CAEnE,CAAA,IAAA,CAAK,IAAOC,CAAAA,GAAAA,CAAM,SAAUD,CAAAA,CAAAA,CAAK,IAAI,CAAA,CACrC,IAAK,CAAA,cAAA,CAAiBC,GAAM,CAAA,SAAA,CAAUD,EAAK,cAAc,CAAA,CACzD,IAAK,CAAA,YAAA,CAAe,IAAIE,CAAAA,CAAeF,CAAK,CAAA,YAAY,EACxD,IAAK,C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W,CAAA,IAAA,CAAK,MAAM,SACtB,CAAA,UAAA,CAAYC,CACd,EACF,CAMO,WAAA,CAAYC,CAA+B,CAAA,CAChD,GAAG,IAAA,CAAK,KAASC,IAAAA,CAAAA,CACX,IAAK,CAAA,KAAA,GAAUD,CACjB,GAAA,IAAA,CAAK,MAAQA,CAGf,CAAA,CAAA,KAAA,MAAM,IAAIE,GAAAA,CAA0BF,CAAQ,CAEhD,CAOA,aAAA,EAAsB,CACpB,IAAMV,CAAAA,CAAO,IAAK,CAAA,OAAA,CAAQ,SAAU,CAAA,IAAA,EACpC,CAAA,IAAA,CAAK,GAAK,EACV,CAAA,IAAA,CAAK,UAAa,CAAA,EAAA,CAClB,IAAK,CAAA,mBAAA,CAAsB,CAAE,KAAA,CAAO,CAAE,IAAA,CAAM,EAAG,CAAE,CACjD,CAAA,IAAA,CAAK,IAAO,CAAA,CAAE,GAAI,EAAG,CAAA,CACrB,IAAK,CAAA,YAAA,CAAe,IAAIhC,CAAAA,CAAe,CAAE,OAAA,CAAS,CAAE,QAAU,CAAA,EAAG,CAAE,CAAC,CACpE,CAAA,IAAA,CAAK,QAAW,CAAA,GAChB,IAAK,CAAA,OAAA,CAAU,CACb,SAAA,CAAWgC,CACX,CAAA,WAAA,CAAa,IAAK,CAAA,OAAA,CAAQ,WAC1B,CAAA,WAAA,CAAa,IAAK,CAAA,OAAA,CAAQ,WAC1B,CAAA,GAAA,CAAK,IAAK,CAAA,OAAA,CAAQ,GACpB,CACA,CAAA,IAAA,CAAK,KAAQ,CAAA,CACX,QAAU,CAAA,CAAA,CACV,QAAUA,CAAAA,CAAAA,CACV,cAAeA,CACf,CAAA,QAAA,CAAUA,CACV,CAAA,SAAA,CAAW,EAAC,CACZ,UAAYA,CAAAA,CACd,EACF,CACF","file":"chunk-ZE7D77FR.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, TaxCategory, TaxSystem } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport ProductModel, { ProductSelectionAttributes, ProductSpecification, SelectionAttributes } from \"./Product\";\r\nimport { TaxRuleModel, TaxSlabModel, TaxSlabs } 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} from \"./Error\";\r\nimport { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\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: TaxCategory;\r\n tax: {\r\n taxRuleId: string;\r\n taxSystem: TaxSystem;\r\n country: CountryCode;\r\n rate: number;\r\n taxSlabs: TaxSlabs;\r\n };\r\n};\r\n\r\nexport type LineItemTotals = {\r\n quantity: number;\r\n subtotal: PriceData;\r\n discounts: Record<string, PriceData>; // couponCode -> discount mapping\r\n taxableAmount: PriceData; // subtotal - discount\r\n taxTotal: PriceData;\r\n grandTotal: PriceData;\r\n};\r\n\r\nexport type LineItemAttributes = CustomFieldAttributes & {\r\n id: string;\r\n\r\n productKey: 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 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 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: {\r\n unitPrice: PriceModel;\r\n tierPricing: TieredPriceModel;\r\n taxCategory: TaxCategory;\r\n tax: {\r\n taxRuleId: string;\r\n taxSystem: TaxSystem;\r\n country: CountryCode;\r\n taxSlabs: TaxSlabModel[];\r\n rate: number;\r\n };\r\n };\r\n\r\n protected state: LineItemState;\r\n protected total: {\r\n quantity: number;\r\n subtotal: PriceModel;\r\n discounts: Record<string, PriceModel>;\r\n taxableAmount: PriceModel; // subtotal - discount\r\n\r\n taxTotal: PriceModel;\r\n grandTotal: PriceModel;\r\n };\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.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: new TieredPriceModel(data.pricing.tierPricing),\r\n taxCategory: data.pricing.taxCategory,\r\n tax: {\r\n taxRuleId: data.pricing.tax.taxRuleId,\r\n taxSystem: data.pricing.tax.taxSystem,\r\n country: data.pricing.tax.country,\r\n rate: data.pricing.tax.rate,\r\n taxSlabs: data.pricing.tax.taxSlabs.map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: new PriceModel(s.minUnitPrice),\r\n maxUnitPrice: s.maxUnitPrice ? new PriceModel(s.maxUnitPrice) : undefined,\r\n })),\r\n },\r\n }\r\n\r\n this.state = data.state ?? LineItemState.INITIAL;\r\n\r\n this.total = {\r\n quantity: data.total.quantity,\r\n subtotal: new PriceModel(data.total.subtotal),\r\n discounts: Object.fromEntries(\r\n Object.entries(data.total.discounts).map(([couponCode, discount]) => [\r\n couponCode,\r\n new PriceModel(discount),\r\n ])\r\n ),\r\n taxableAmount: new PriceModel(data.total.taxableAmount),\r\n taxTotal: new PriceModel(data.total.taxTotal),\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 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 tax: {\r\n taxRuleId: this.pricing.tax.taxRuleId,\r\n taxSystem: this.pricing.tax.taxSystem,\r\n country: this.pricing.tax.country,\r\n rate: this.pricing.tax.rate,\r\n taxSlabs: this.pricing.tax.taxSlabs,\r\n }\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 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() {\r\n return {\r\n quantity: this.total.quantity,\r\n subtotal: this.total.subtotal,\r\n taxableAmount: this.total.taxableAmount,\r\n taxTotal: this.total.taxTotal,\r\n discounts: Object.fromEntries(\r\n Object.entries(this.total.discounts).map(([couponCode, discount]) => [\r\n couponCode,\r\n discount,\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 return {\r\n id: this.getId(),\r\n productKey: this.getProductKey(),\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: this.getPricing().unitPrice.getDetails(),\r\n tierPricing: this.getPricing().tierPricing.getDetails(),\r\n taxCategory: this.getPricing().taxCategory,\r\n tax: {\r\n taxRuleId: this.getPricing().tax.taxRuleId,\r\n taxSystem: this.getPricing().tax.taxSystem,\r\n country: this.getPricing().tax.country,\r\n rate: this.getPricing().tax.rate,\r\n taxSlabs: this.getPricing().tax.taxSlabs.map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: s.minUnitPrice.getDetails(),\r\n maxUnitPrice: s.maxUnitPrice ? s.maxUnitPrice.getDetails() : undefined,\r\n })),\r\n }\r\n },\r\n state: this.getState(),\r\n total: {\r\n quantity: this.getTotal().quantity,\r\n subtotal: this.getTotal().subtotal.getDetails(),\r\n taxableAmount: this.getTotal().taxableAmount.getDetails(),\r\n taxTotal: this.getTotal().taxTotal.getDetails(),\r\n discounts: Object.fromEntries(\r\n Object.entries(this.getTotal().discounts).map(([couponCode, discount]) => [\r\n couponCode,\r\n discount.getDetails(),\r\n ])\r\n ),\r\n grandTotal: this.getTotal().grandTotal.getDetails(),\r\n },\r\n customFields: this.getAllCustomFields()\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.getBaseUnitPrice().getCurrency() !== cartCurrency) {\r\n throw new PricingNotFoundError();\r\n }\r\n this.name = product.getName();\r\n this.specifications = product.getSpecifications();\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 const { unitPrice } = productPricing.getApplicableTier(quantity);\r\n\r\n this.pricing = {\r\n unitPrice: unitPrice,\r\n tierPricing: productPricing,\r\n taxCategory: productPricing.getTaxCategory(),\r\n tax: this.pricing.tax\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.discounts = 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(taxRule: TaxRuleModel): void {\r\n if (!taxRule.appliesTo(this.pricing.taxCategory, this.pricing.tax.country)) {\r\n throw new InvalidTaxRuleError();\r\n }\r\n\r\n const taxableUnitPrice = this.total.quantity > 0 ? \r\n this.total.taxableAmount.divide(this.total.quantity) \r\n : \r\n this.total.taxableAmount.zero();\r\n\r\n this.pricing.tax = {\r\n taxRuleId: taxRule.getTaxRuleId(),\r\n taxSystem: taxRule.getTaxSystem(),\r\n country: taxRule.getCountry(),\r\n rate: taxRule.getApplicableTaxRate(taxableUnitPrice),\r\n taxSlabs: taxRule.getSlabs(),\r\n };\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 subtotal: zero,\r\n taxableAmount: zero,\r\n taxTotal: zero,\r\n discounts: {},\r\n grandTotal: zero\r\n };\r\n return;\r\n }\r\n\r\n const { unitPrice } = this.pricing.tierPricing.getApplicableTier(totalQuantity);\r\n const subTotal = unitPrice.multiply(totalQuantity);\r\n const discounts = Object.values(this.total.discounts).reduce((sum, s) => sum.add(s), zero);\r\n const taxableAmount = subTotal.subtract(discounts);\r\n const unitTaxbleAmount = totalQuantity > 0 ? taxableAmount.divide(totalQuantity) : zero;\r\n const taxRate = TaxRuleModel.getApplicableTaxRate(unitTaxbleAmount, this.pricing.tax.taxSlabs);\r\n const taxTotal = taxableAmount.multiply(taxRate).round();\r\n const grandTotal = subTotal.subtract(discounts).add(taxTotal);\r\n\r\n this.total = {\r\n quantity: totalQuantity,\r\n subtotal: subTotal,\r\n taxableAmount: taxableAmount,\r\n taxTotal: taxTotal,\r\n discounts: this.total.discounts,\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.selectionAttributes = { color: { name: '' } };\r\n this.name = { en: '' };\r\n this.primaryImage = new ImageInfoModel({ sources: { original: '' } });\r\n this.subItems = [];\r\n this.pricing = {\r\n unitPrice: zero,\r\n tierPricing: this.pricing.tierPricing,\r\n taxCategory: this.pricing.taxCategory,\r\n tax: this.pricing.tax\r\n }\r\n this.total = {\r\n quantity: 0,\r\n subtotal: zero,\r\n taxableAmount: zero,\r\n taxTotal: zero,\r\n discounts: {},\r\n grandTotal: zero\r\n };\r\n }\r\n}"]}
|