b23-lib 2.0.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Auth/index.js +1 -1
- package/dist/Auth/index.js.map +1 -1
- package/dist/Auth/index.mjs +1 -1
- package/dist/Auth/index.mjs.map +1 -1
- package/dist/Classes/Address.d.mts +1 -1
- package/dist/Classes/Address.d.ts +1 -1
- package/dist/Classes/Address.js.map +1 -1
- package/dist/Classes/Address.mjs +1 -1
- package/dist/Classes/Base.d.mts +5 -5
- package/dist/Classes/Base.d.ts +5 -5
- package/dist/Classes/Base.js.map +1 -1
- package/dist/Classes/Base.mjs +1 -1
- package/dist/Classes/Cart.d.mts +27 -12
- package/dist/Classes/Cart.d.ts +27 -12
- package/dist/Classes/Cart.js +1 -1
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Cart.mjs.map +1 -1
- package/dist/Classes/Common.d.mts +2 -93
- package/dist/Classes/Common.d.ts +2 -93
- package/dist/Classes/Coupon.d.mts +33 -15
- package/dist/Classes/Coupon.d.ts +33 -15
- 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/Customer.d.mts +2 -2
- package/dist/Classes/Customer.d.ts +2 -2
- package/dist/Classes/Customer.js.map +1 -1
- package/dist/Classes/Customer.mjs +1 -1
- package/dist/Classes/Customer.mjs.map +1 -1
- package/dist/Classes/CustomerAddress.d.mts +1 -1
- package/dist/Classes/CustomerAddress.d.ts +1 -1
- package/dist/Classes/CustomerAddress.js.map +1 -1
- package/dist/Classes/CustomerAddress.mjs +1 -1
- package/dist/Classes/Enum.d.mts +43 -2
- package/dist/Classes/Enum.d.ts +43 -2
- 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 +59 -0
- package/dist/Classes/Error.d.ts +59 -0
- package/dist/Classes/Error.js +2 -0
- package/dist/Classes/Error.js.map +1 -0
- package/dist/Classes/Error.mjs +2 -0
- package/dist/Classes/Error.mjs.map +1 -0
- package/dist/Classes/ImageInfo.js +1 -1
- package/dist/Classes/ImageInfo.js.map +1 -1
- package/dist/Classes/ImageInfo.mjs +1 -1
- package/dist/Classes/Inventory.d.mts +25 -6
- package/dist/Classes/Inventory.d.ts +25 -6
- package/dist/Classes/Inventory.js +1 -1
- package/dist/Classes/Inventory.js.map +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/Inventory.mjs.map +1 -1
- package/dist/Classes/LineItem.d.mts +140 -58
- package/dist/Classes/LineItem.d.ts +140 -58
- package/dist/Classes/LineItem.js +1 -1
- package/dist/Classes/LineItem.js.map +1 -1
- package/dist/Classes/LineItem.mjs +1 -1
- package/dist/Classes/Order.d.mts +7 -51
- package/dist/Classes/Order.d.ts +7 -51
- package/dist/Classes/Order.js +1 -1
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/Order.mjs.map +1 -1
- package/dist/Classes/Payment.d.mts +4 -4
- package/dist/Classes/Payment.d.ts +4 -4
- package/dist/Classes/Payment.js.map +1 -1
- package/dist/Classes/Payment.mjs +1 -1
- package/dist/Classes/Payment.mjs.map +1 -1
- package/dist/Classes/Price.d.mts +1 -82
- package/dist/Classes/Price.d.ts +1 -82
- 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.d.mts +103 -85
- package/dist/Classes/Product.d.ts +103 -85
- 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/Product.mjs.map +1 -1
- package/dist/Classes/ShoppingContainer.d.mts +79 -63
- package/dist/Classes/ShoppingContainer.d.ts +79 -63
- package/dist/Classes/ShoppingContainer.js +1 -1
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/Classes/TaxRule.d.mts +63 -0
- package/dist/Classes/TaxRule.d.ts +63 -0
- package/dist/Classes/TaxRule.js +2 -0
- package/dist/Classes/TaxRule.js.map +1 -0
- package/dist/Classes/TaxRule.mjs +2 -0
- package/dist/Classes/TaxRule.mjs.map +1 -0
- package/dist/Classes/TieredPrice.d.mts +75 -0
- package/dist/Classes/TieredPrice.d.ts +75 -0
- package/dist/Classes/TieredPrice.js +2 -0
- package/dist/Classes/TieredPrice.js.map +1 -0
- package/dist/Classes/TieredPrice.mjs +2 -0
- package/dist/Classes/TieredPrice.mjs.map +1 -0
- package/dist/Common-D-UoxwM0.d.ts +210 -0
- package/dist/Common-FbQ5-3QN.d.mts +210 -0
- package/dist/chunk-2SGUPNWZ.mjs +2 -0
- package/dist/chunk-2SGUPNWZ.mjs.map +1 -0
- package/dist/chunk-54RUAXYE.mjs +2 -0
- package/dist/chunk-54RUAXYE.mjs.map +1 -0
- package/dist/{chunk-ATUUYYQT.mjs → chunk-55SOBG62.mjs} +2 -2
- package/dist/chunk-55SOBG62.mjs.map +1 -0
- package/dist/{chunk-H5GPM4LA.mjs → chunk-5KD2EW7O.mjs} +2 -2
- package/dist/{chunk-H5GPM4LA.mjs.map → chunk-5KD2EW7O.mjs.map} +1 -1
- package/dist/chunk-72DR3HF2.mjs +2 -0
- package/dist/chunk-72DR3HF2.mjs.map +1 -0
- package/dist/chunk-AMIRIUMH.mjs +2 -0
- package/dist/chunk-AMIRIUMH.mjs.map +1 -0
- package/dist/chunk-CEGQFFYZ.mjs +2 -0
- package/dist/chunk-CEGQFFYZ.mjs.map +1 -0
- package/dist/chunk-EP7WVZXC.mjs +2 -0
- package/dist/chunk-EP7WVZXC.mjs.map +1 -0
- package/dist/chunk-KWH7GE23.mjs +2 -0
- package/dist/chunk-KWH7GE23.mjs.map +1 -0
- package/dist/chunk-LNIZAPER.mjs +2 -0
- package/dist/chunk-LNIZAPER.mjs.map +1 -0
- package/dist/chunk-NJKSUUOB.mjs +2 -0
- package/dist/chunk-NJKSUUOB.mjs.map +1 -0
- package/dist/chunk-NUTKOIGY.mjs +2 -0
- package/dist/chunk-NUTKOIGY.mjs.map +1 -0
- package/dist/chunk-RBROVHJ4.mjs +2 -0
- package/dist/chunk-RBROVHJ4.mjs.map +1 -0
- package/dist/index.d.mts +9 -6
- package/dist/index.d.ts +9 -6
- 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 +1 -1
- package/dist/chunk-6PDP4ETM.mjs +0 -2
- package/dist/chunk-6PDP4ETM.mjs.map +0 -1
- package/dist/chunk-ATUUYYQT.mjs.map +0 -1
- package/dist/chunk-CKUUUEWT.mjs +0 -2
- package/dist/chunk-CKUUUEWT.mjs.map +0 -1
- package/dist/chunk-DKI6BDWK.mjs +0 -2
- package/dist/chunk-DKI6BDWK.mjs.map +0 -1
- package/dist/chunk-K3AXPTGG.mjs +0 -2
- package/dist/chunk-K3AXPTGG.mjs.map +0 -1
- package/dist/chunk-LMMJSJTO.mjs +0 -2
- package/dist/chunk-LMMJSJTO.mjs.map +0 -1
- package/dist/chunk-RWBNLNQ6.mjs +0 -2
- package/dist/chunk-RWBNLNQ6.mjs.map +0 -1
- package/dist/chunk-V4H3X4PI.mjs +0 -2
- package/dist/chunk-V4H3X4PI.mjs.map +0 -1
- package/dist/chunk-WOMA746Z.mjs +0 -2
- package/dist/chunk-WOMA746Z.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/Classes/Base.ts"],"names":["BaseModel","data","date","id","authType","requestId","lambdaName","fieldName","value"],"mappings":"AA4BqBA,IAAAA,CAAAA,CAArB,KAA+B,CACnB,YAAA,CACA,QACA,SACA,CAAA,UAAA,CACA,WAQV,WAAYC,CAAAA,CAAAA,CAAsBC,EAAa,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E,EAAaC,CAAqBC,CAAAA,CAAAA,CAAoBC,EAA2B,CAC7F,IAAA,CAAK,WAAa,CAChB,EAAA,CAAAH,EACA,QAAAC,CAAAA,CAAAA,CACA,UAAAC,CACA,CAAA,UAAA,CAAAC,CACF,EACF,CAOA,cAAeC,CAAAA,CAAAA,CAAwB,CACrC,OAAO,KAAK,YAAaA,CAAAA,CAAS,GAAK,IACzC,CAQA,eAAeA,CAAmBC,CAAAA,CAAAA,CAAkB,CAClD,IAAA,CAAK,YAAaD,CAAAA,CAAS,EAAIC,EACjC,CAMA,oBAAmC,CACjC,OAAO,CAAE,GAAG,IAAA,CAAK,YAAa,CAChC,CACF","file":"chunk-55SOBG62.mjs","sourcesContent":["import { AuthType } from \"../Auth\";\r\nimport { ISODateTimeUTC } from \"./Common\";\r\n\r\nexport interface CustomFields {\r\n [key: string]: any;\r\n}\r\n\r\nexport type ModifiedBy = {\r\n id?: string;\r\n authType?: string;\r\n requestId?: string;\r\n lambdaName?: string;\r\n}\r\n\r\nexport type BaseAttributes = {\r\n customFields?: CustomFields;\r\n version?: number;\r\n createdAt?: ISODateTimeUTC;\r\n modifiedAt?: ISODateTimeUTC;\r\n modifiedBy?: ModifiedBy;\r\n};\r\n\r\nexport type BaseData = Required<BaseAttributes>;\r\n\r\n/**\r\n * Provides common foundational properties and methods for other data models.\r\n * Handles tracking of custom fields, versioning, and timestamps.\r\n */\r\nexport default class BaseModel {\r\n protected customFields: CustomFields;\r\n protected version: number;\r\n protected createdAt: ISODateTimeUTC;\r\n protected modifiedAt: ISODateTimeUTC;\r\n protected modifiedBy: ModifiedBy;\r\n\r\n /**\r\n * Creates an instance of BaseModel.\r\n * Initializes common properties like timestamps, version, and custom fields.\r\n * @param data - Optional initial attributes for the base model.\r\n * @param date - Optional date object to use for default timestamps (defaults to current time).\r\n */\r\n constructor(data: BaseAttributes, date: Date = new Date()) {\r\n this.customFields = { ...data.customFields };\r\n this.version = data.version ?? 1;\r\n this.createdAt = data.createdAt && !isNaN(Date.parse(data.createdAt))\r\n ?\r\n new Date(data.createdAt).toISOString()\r\n :\r\n date.toISOString();\r\n this.modifiedAt = data.modifiedAt && !isNaN(Date.parse(data.modifiedAt))\r\n ? new Date(data.modifiedAt).toISOString()\r\n : date.toISOString();\r\n\r\n this.modifiedBy = { ...data.modifiedBy };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the base model's current state.\r\n * @returns BaseData object containing common properties.\r\n */\r\n getDetails(): BaseData {\r\n return {\r\n customFields: this.getAllCustomFields(), // Use getter to return a copy\r\n version: this.getVersion(),\r\n createdAt: this.getCreatedAt(),\r\n modifiedAt: this.getModifiedAt(),\r\n modifiedBy: this.getModifiedBy(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the current version number of the model instance.\r\n * @returns The version number.\r\n */\r\n getVersion(): number {\r\n return this.version;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as an ISO 8601 string.\r\n * @returns The creation timestamp string.\r\n */\r\n getCreatedAt(): string {\r\n return this.createdAt;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as a Unix epoch time (milliseconds).\r\n * @returns The creation time in milliseconds since the epoch.\r\n */\r\n getCreatedAtTime(): number {\r\n return new Date(this.createdAt).getTime();\r\n }\r\n\r\n\r\n /**\r\n * Gets the last modification timestamp as an ISO 8601 string.\r\n * @returns The last modification timestamp string.\r\n */\r\n getModifiedAt(): string {\r\n return this.modifiedAt;\r\n }\r\n\r\n /**\r\n * Gets the last modification timestamp as a Unix epoch time (milliseconds).\r\n * @returns The last modification time in milliseconds since the epoch.\r\n */\r\n getModifiedAtTime(): number {\r\n return new Date(this.modifiedAt).getTime();\r\n }\r\n\r\n /**\r\n * Gets the identifier of the user or process that last modified the instance.\r\n * @returns\r\n */\r\n getModifiedBy(): ModifiedBy {\r\n return { ...this.modifiedBy };\r\n }\r\n\r\n /**\r\n * Sets the identifier of the user or process that last modified the instance.\r\n * @param modifiedBy - The identifier string.\r\n */\r\n setModifiedBy(id?: string, authType?: AuthType, requestId?: string, lambdaName?: string): void {\r\n this.modifiedBy = {\r\n id,\r\n authType,\r\n requestId,\r\n lambdaName,\r\n };\r\n }\r\n\r\n /**\r\n * Retrieves the value of a specific custom field.\r\n * @param fieldName - The name (key) of the custom field to retrieve.\r\n * @returns The value of the custom field, or null if the field does not exist.\r\n */\r\n getCustomField(fieldName: string): any {\r\n return this.customFields[fieldName] ?? null;\r\n }\r\n\r\n /**\r\n * Sets the value of a specific custom field.\r\n * Also updates the modification timestamp and increments the version.\r\n * @param fieldName - The name (key) of the custom field to set.\r\n * @param value - The value to assign to the custom field.\r\n */\r\n setCustomField(fieldName: string, value: any): void {\r\n this.customFields[fieldName] = value;\r\n }\r\n\r\n /**\r\n * Retrieves a shallow copy of all custom fields associated with the instance.\r\n * @returns An object containing all custom fields.\r\n */\r\n getAllCustomFields(): CustomFields {\r\n return { ...this.customFields };\r\n }\r\n}\r\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a}from'./chunk-55SOBG62.mjs';var n=(e=>(e.BILLING="billing",e.SHIPPING="shipping",e.BILLING_AND_SHIPPING="billing&shipping",e.NONE="none",e))(n||{}),t=class extends a{id;firstName;lastName;company;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(s,r=new Date){super(s,r),this.id=s.id,this.firstName=s.firstName,this.lastName=s.lastName||"",this.company=s.company||"",this.phone=s.phone,this.email=s.email,this.addressLine1=s.addressLine1,this.addressLine2=s.addressLine2||"",this.city=s.city,this.postalCode=s.postalCode,this.state=s.state,this.country=s.country,this.isBillingAddress=s.isBillingAddress,this.isShippingAddress=s.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),company:this.getCompany(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getCompany(){return this.company}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(s){return s==="shipping"||s==="billing&shipping"}static checkIfBillingAddress(s){return s==="billing"||s==="billing&shipping"}};export{n as a,t as b};//# sourceMappingURL=chunk-5KD2EW7O.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-5KD2EW7O.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/Address.ts"],"names":["AddressType","AddressModel","BaseModel","data","date","addressType"],"mappings":"qCAEO,IAAKA,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,OAAU,CAAA,SAAA,CACVA,EAAA,QAAW,CAAA,UAAA,CACXA,CAAA,CAAA,oBAAA,CAAuB,kBACvBA,CAAAA,CAAAA,CAAA,IAAO,CAAA,MAAA,CAJGA,OAAA,EA8BSC,CAAAA,CAAAA,CAAAA,CAArB,cAA0CC,CAAU,CACxC,EAAA,CACA,SACA,CAAA,QAAA,CACA,QACA,KACA,CAAA,KAAA,CACA,YACA,CAAA,YAAA,CACA,IACA,CAAA,UAAA,CACA,KACA,CAAA,OAAA,CACA,iBACA,iBAOV,CAAA,WAAA,CAAYC,CAAyBC,CAAAA,CAAAA,CAAa,IAAI,IAAA,CAAQ,CAC5D,KAAA,CAAMD,EAAMC,CAAI,CAAA,CAChB,IAAK,CAAA,EAAA,CAAKD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A,mBAAA,EACvB,CAAA,iBAAA,CAAmB,IAAK,CAAA,oBAAA,EAC1B,CACF,CAMA,KAAgB,EAAA,CACd,OAAO,IAAA,CAAK,EACd,CAMA,YAAuB,EAAA,CACrB,OAAO,IAAK,CAAA,SACd,CAMA,WAAA,EAAsB,CACpB,OAAO,IAAK,CAAA,QACd,CAMA,UAAqB,EAAA,CACnB,OAAO,IAAA,CAAK,OACd,CAMA,QAAmB,EAAA,CACjB,OAAO,IAAK,CAAA,KACd,CAMA,QAAA,EAAmB,CACjB,OAAO,IAAK,CAAA,KACd,CAMA,eAA0B,EAAA,CACxB,OAAO,IAAA,CAAK,YACd,CAOA,eAAA,EAA0B,CACxB,OAAO,KAAK,YACd,CAMA,OAAkB,EAAA,CAChB,OAAO,IAAA,CAAK,IACd,CAMA,eAAwB,CACtB,OAAO,IAAK,CAAA,UACd,CAMA,QAAA,EAAmB,CACjB,OAAO,KAAK,KACd,CAMA,UAAqB,EAAA,CACnB,OAAO,IAAA,CAAK,OACd,CAMA,qBAA+B,CAC7B,OAAO,IAAK,CAAA,gBACd,CAMA,oBAAA,EAAgC,CAC9B,OAAO,KAAK,iBACd,CAMA,cAA8B,EAAA,CAC5B,OAAI,IAAA,CAAK,gBAAoB,EAAA,IAAA,CAAK,kBACzB,kBACE,CAAA,IAAA,CAAK,gBACP,CAAA,SAAA,CACE,IAAK,CAAA,iBAAA,CACP,UAEA,CAAA,MAEX,CAOA,OAAO,sBAAA,CAAuBE,CAAmC,CAAA,CAC/D,OAAOA,CAAAA,GAAgB,UAAwBA,EAAAA,CAAAA,GAAgB,kBACjE,CAOA,OAAO,qBAAsBA,CAAAA,CAAAA,CAAmC,CAC9D,OAAOA,CAAAA,GAAgB,SAAuBA,EAAAA,CAAAA,GAAgB,kBAChE,CACF","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../src/Classes/Address.ts"],"names":["AddressType","AddressModel","BaseModel","data","date","addressType"],"mappings":"qCAEO,IAAKA,CACVA,CAAAA,CAA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,EAAA,CAC5B,OAAI,IAAA,CAAK,gBAAoB,EAAA,IAAA,CAAK,kBACzB,kBACE,CAAA,IAAA,CAAK,gBACP,CAAA,SAAA,CACE,IAAK,CAAA,iBAAA,CACP,UAEA,CAAA,MAEX,CAOA,OAAO,sBAAA,CAAuBE,CAAmC,CAAA,CAC/D,OAAOA,CAAAA,GAAgB,UAAwBA,EAAAA,CAAAA,GAAgB,kBACjE,CAOA,OAAO,qBAAsBA,CAAAA,CAAAA,CAAmC,CAC9D,OAAOA,CAAAA,GAAgB,SAAuBA,EAAAA,CAAAA,GAAgB,kBAChE,CACF","file":"chunk-5KD2EW7O.mjs","sourcesContent":["import BaseModel, { BaseAttributes } from \"./Base\";\r\n\r\nexport enum AddressType {\r\n BILLING = \"billing\",\r\n SHIPPING = \"shipping\",\r\n BILLING_AND_SHIPPING = \"billing&shipping\",\r\n NONE = \"none\",\r\n}\r\n\r\nexport type AddressAttributes = BaseAttributes & {\r\n id: string;\r\n firstName: string;\r\n lastName?: string;\r\n company?: string;\r\n phone: string;\r\n email: string;\r\n addressLine1: string;\r\n addressLine2?: string;\r\n city: string;\r\n postalCode: string\r\n state: string;\r\n country: string;\r\n isBillingAddress: boolean;\r\n isShippingAddress: boolean;\r\n};\r\n\r\nexport type AddressData = Required<AddressAttributes>;\r\n\r\n/**\r\n * Represents a physical address associated with a customer or order.\r\n * Handles both billing and shipping address types.\r\n */\r\nexport default class AddressModel extends BaseModel {\r\n protected id: string;\r\n protected firstName: string;\r\n protected lastName: string;\r\n protected company: string;\r\n protected phone: string;\r\n protected email: string;\r\n protected addressLine1: string;\r\n protected addressLine2: string;\r\n protected city: string;\r\n protected postalCode: string\r\n protected state: string;\r\n protected country: string;\r\n protected isBillingAddress: boolean;\r\n protected isShippingAddress: boolean;\r\n\r\n /**\r\n * Creates an instance of AddressModel.\r\n * @param data - The initial address attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: AddressAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.firstName = data.firstName;\r\n this.lastName = data.lastName || '';\r\n this.company = data.company || '';\r\n this.phone = data.phone;\r\n this.email = data.email;\r\n this.addressLine1 = data.addressLine1;\r\n this.addressLine2 = data.addressLine2 || '';\r\n this.city = data.city;\r\n this.postalCode = data.postalCode;\r\n this.state = data.state;\r\n this.country = data.country;\r\n this.isBillingAddress = data.isBillingAddress;\r\n this.isShippingAddress = data.isShippingAddress;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the address's current state.\r\n * Includes all address fields and base model fields.\r\n * @returns AddressData object suitable for serialization or API responses.\r\n */\r\n getDetails(): AddressData {\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n firstName: this.getFirstName(),\r\n lastName: this.getLastName(),\r\n company: this.getCompany(),\r\n phone: this.getPhone(),\r\n email: this.getEmail(),\r\n addressLine1: this.getAddressLine1(),\r\n addressLine2: this.getAddressLine2(),\r\n city: this.getCity(),\r\n postalCode: this.getPostalCode(),\r\n state: this.getState(),\r\n country: this.getCountry(),\r\n isBillingAddress: this.getIsBillingAddress(),\r\n isShippingAddress: this.getIsShippingAddress(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for the address.\r\n * @returns The address ID.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the first name associated with the address.\r\n * @returns The first name.\r\n */\r\n getFirstName(): string {\r\n return this.firstName;\r\n }\r\n\r\n /**\r\n * Gets the last name associated with the address.\r\n * @returns The last name.\r\n */\r\n getLastName(): string {\r\n return this.lastName;\r\n }\r\n\r\n /**\r\n * Gets the company name associated with the address.\r\n * @returns The company name.\r\n */\r\n getCompany(): string {\r\n return this.company;\r\n }\r\n\r\n /**\r\n * Gets the phone number associated with the address.\r\n * @returns The phone number.\r\n */\r\n getPhone(): string {\r\n return this.phone;\r\n }\r\n\r\n /**\r\n * Gets the email address associated with the address.\r\n * @returns The email address.\r\n */\r\n getEmail(): string {\r\n return this.email;\r\n }\r\n\r\n /**\r\n * Gets the primary address line (e.g., street address).\r\n * @returns The first address line.\r\n */\r\n getAddressLine1(): string {\r\n return this.addressLine1;\r\n }\r\n\r\n /**\r\n * Gets the secondary address line (e.g., apartment, suite).\r\n * Returns an empty string if not provided.\r\n * @returns The second address line or an empty string.\r\n */\r\n getAddressLine2(): string {\r\n return this.addressLine2;\r\n }\r\n\r\n /**\r\n * Gets the city name.\r\n * @returns The city.\r\n */\r\n getCity(): string {\r\n return this.city;\r\n }\r\n\r\n /**\r\n * Gets the postal code (e.g., ZIP code).\r\n * @returns The postal code.\r\n */\r\n getPostalCode(): string {\r\n return this.postalCode;\r\n }\r\n\r\n /**\r\n * Gets the state, province, or region.\r\n * @returns The state.\r\n */\r\n getState(): string {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the country name or code.\r\n * @returns The country.\r\n */\r\n getCountry(): string {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Checks if this address is designated as a billing address.\r\n * @returns True if it's a billing address, false otherwise.\r\n */\r\n getIsBillingAddress(): boolean {\r\n return this.isBillingAddress;\r\n }\r\n\r\n /**\r\n * Checks if this address is designated as a shipping address.\r\n * @returns True if it's a shipping address, false otherwise.\r\n */\r\n getIsShippingAddress(): boolean {\r\n return this.isShippingAddress;\r\n }\r\n\r\n /**\r\n * Determines the type of the address based on its billing and shipping flags.\r\n * @returns The AddressType enum value representing the address's role.\r\n */\r\n getAddressType(): AddressType {\r\n if (this.isBillingAddress && this.isShippingAddress) {\r\n return AddressType.BILLING_AND_SHIPPING;\r\n } else if (this.isBillingAddress) {\r\n return AddressType.BILLING;\r\n } else if (this.isShippingAddress) {\r\n return AddressType.SHIPPING;\r\n } else {\r\n return AddressType.NONE;\r\n }\r\n }\r\n\r\n /**\r\n * Static method to check if a given AddressType includes shipping.\r\n * @param addressType - The address type to check.\r\n * @returns True if the type is SHIPPING or BILLING_AND_SHIPPING.\r\n */\r\n static checkIfShippingAddress(addressType: AddressType): boolean {\r\n return addressType === AddressType.SHIPPING || addressType === AddressType.BILLING_AND_SHIPPING;\r\n }\r\n\r\n /**\r\n * Static method to check if a given AddressType includes billing.\r\n * @param addressType - The address type to check.\r\n * @returns True if the type is BILLING or BILLING_AND_SHIPPING.\r\n */\r\n static checkIfBillingAddress(addressType: AddressType): boolean {\r\n return addressType === AddressType.BILLING || addressType === AddressType.BILLING_AND_SHIPPING;\r\n }\r\n}"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
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
|
|
@@ -0,0 +1 @@
|
|
|
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,CAFKA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAKCC,EAAoE,CAC9E,OAAA,CAA6B,IAC7B,CAAA,OAAA,CAA6B,IAChC,CAAA,CAEaC,CAAkE,CAAA,CAC3E,QAA6B,IAC9B,CAAA,OAAA,CAA6B,IAChC,CAAA,CAKaC,CAAqB,CAAA,CAClB,EAAwB,CAAA,KACxC,EAEaC,CAAoB,CAAA,CAC9B,GAAiC,CAAA,QACpC,CAEaC,CAAAA,CAAAA,CAAoB,CAC9B,GAAA,CAAiC,OACpC,CAKYC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,CAAA,CAAA,IAAA,CAAO,MACPA,CAAAA,CAAAA,CAAA,MAAS,CAAA,QAAA,CACTA,EAAA,MAAS,CAAA,QAAA,CACTA,CAAA,CAAA,IAAA,CAAO,MACPA,CAAAA,CAAAA,CAAA,GAAM,CAAA,KAAA,CACNA,CAAA,CAAA,IAAA,CAAO,MACPA,CAAAA,CAAAA,CAAA,OAAU,CAAA,SAAA,CAPAA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAUAC,OACVA,CAAA,CAAA,OAAA,CAAU,SACVA,CAAAA,CAAAA,CAAA,OAAU,CAAA,SAAA,CAFAA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAKAC,OACVA,CAAA,CAAA,OAAA,CAAU,SACVA,CAAAA,CAAAA,CAAA,MAAS,CAAA,QAAA,CAFCA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAKAC,OACVA,CAAA,CAAA,GAAA,CAAM,KADIA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAkBAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,CAAA,CAAA,OAAA,CAAU,UACVA,CAAA,CAAA,UAAA,CAAa,YACbA,CAAAA,CAAAA,CAAA,OAAU,CAAA,SAAA,CACVA,CAAA,CAAA,SAAA,CAAY,YACZA,CAAA,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}"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import S from'util';var i=Object.freeze({INVALID_UUID:"Invalid UUID",INVALID_EMAIL:"Invalid Email",INVALID_TOKEN:"Invalid Token",TOKEN_EXPIRED:"Token Expired",INVALID_VERIFIER:"Invalid Verifier",INVALID_PERMISSIONS:"Invalid Permissions",INVALID_AUTH_TYPE:"Invalid Authorization Type",USER_PRIVATE_KEY_NOT_FOUND:"User Private Key Not Found",USER_PUBLIC_KEY_NOT_FOUND:"User Public Key Not Found",ANONYMOUS_PRIVATE_KEY_NOT_FOUND:"Anonymous Private Key Not Found",ANONYMOUS_PUBLIC_KEY_NOT_FOUND:"Anonymous Public Key Not Found",SYSTEM_PRIVATE_KEY_NOT_FOUND:"System Private Key Not Found",SYSTEM_PUBLIC_KEY_NOT_FOUND:"System Public Key Not Found",ADMIN_PRIVATE_KEY_NOT_FOUND:"Admin Private Key Not Found",ADMIN_PUBLIC_KEY_NOT_FOUND:"Admin Public Key Not Found",SECRET_TOKEN_NOT_FOUND:"Secret Token Not Found",ANONYMOUS_SESSION_NOT_ALLOWED:"Anonymous Session Not Allowed",USER_SESSION_NOT_ALLOWED:"User Session Not Allowed",SYSTEM_SESSION_NOT_ALLOWED:"System Session Not Allowed",CDN_SESSION_NOT_ALLOWED:"CDN Session Not Allowed",INTERNAL_SERVER_ERROR:"Internal Server Error",SOMETHING_WENT_WRONG:"Something went wrong",AUTH_CONTEXT_NOT_INITIALIZED:"Auth Context not Initialized"});var a={logException:(s,t)=>{console.error(`Exception Occurred in Function: ${s}, Error: ${a.inspect(t)}`);},logError:(s,t)=>{console.error(`Error Occurred in Function: ${s}, Error: ${a.inspect(t)}`);},logWarning:(s,t)=>{console.warn(`Warning in Function: ${s} - ${a.inspect(t)}`);},logMessage:(s,t)=>{console.log(`Message in Function: ${s} - ${a.inspect(t)}`);},logInvalidPayload:(s,t)=>{console.error(`Invalid Payload received for Function: ${s}, Error: ${a.inspect(t)}`);},inspect:s=>typeof s=="string"?s:S.inspect(s)},o=a;var y={handleException:(s,t,r)=>{t.knownError?(t.logError&&o.logError(s,t),r.status(t.status).json({status:t.status,error:t.error})):t.status&&t.error?(o.logException(s,t),r.status(t.status).json({error:t.errorMessage||JSON.stringify(t.error),status:t.status})):(o.logException(s,t),r.status(500).json({status:500,error:i.INTERNAL_SERVER_ERROR}));},generateResponse:(s,t,r)=>({status:s,data:t,error:r}),generateError:(s,t,r=!0,E=!1)=>({status:s,error:t,knownError:r,logError:E})},P=y;var p=async(s,t,r="GET",E={},_)=>{let c={method:r,headers:{"Content-Type":"application/json",...E}};r!=="GET"&&_&&(c.body=JSON.stringify(_));let n=`${s}${t?"/"+t:""}`,O=n.includes("api.xetile.com")||n.includes("localhost");try{let e=await fetch(n,c);if(!e.ok){let u,N=await e.text();try{u=JSON.parse(N);}catch{u={status:e.status,error:N||e.statusText},o.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${n}. Raw text: ${N}`);}throw {status:e.status,statusText:e.statusText,error:u}}let I=await e.json();return o.logMessage("Fetch",`API call successful: URL-${n}, Status- ${e.status}`),{status:e.status,statusText:e.statusText,data:O?I.data:I}}catch(e){throw o.logError("Fetch",`API call failed: URL-${n}, Status- ${e.status||500}, Error- ${o.inspect(e.error||e)}`),{status:e.status||500,statusText:e.statusText||i.INTERNAL_SERVER_ERROR,error:e.error||{status:e.status||500,error:e.statusText||i.SOMETHING_WENT_WRONG}}}},$=p;export{i as a,o as b,P as c,$ as d};//# sourceMappingURL=chunk-AMIRIUMH.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-AMIRIUMH.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/enums/ErrorTypes.ts","../src/Logger/index.ts","../src/Utils/response.ts","../src/Utils/fetch.ts"],"names":["ErrorTypes_default","Logger","functionName","error","message","errorMessage","context","util","Logger_default","ResponseUtility","res","status","data","knownError","logError","response_default","Fetch","baseURL","endpoint","method","headers","payload","options","completeURL","isInternalAPI","response","errorBody","errorText","body","err","fetch_default"],"mappings":"oBAAOA,IAAAA,CAAAA,CAAQ,MAAO,CAAA,MAAA,CAAO,CACzB,YAAA,CAAc,eACd,aAAe,CAAA,eAAA,CACf,aAAe,CAAA,eAAA,CACf,aAAe,CAAA,eAAA,CACf,iBAAkB,kBAClB,CAAA,mBAAA,CAAqB,qBACrB,CAAA,iBAAA,CAAmB,4BACnB,CAAA,0BAAA,CAA4B,4BAC5B,CAAA,yBAAA,CAA2B,2BAC3B,CAAA,+BAAA,CAAiC,iCACjC,CAAA,8BAAA,CAAgC,gCAChC,CAAA,4BAAA,CAA8B,+BAC9B,2BAA6B,CAAA,6BAAA,CAC7B,2BAA6B,CAAA,6BAAA,CAC7B,0BAA4B,CAAA,4BAAA,CAC5B,uBAAwB,wBACxB,CAAA,6BAAA,CAA+B,+BAC/B,CAAA,wBAAA,CAA0B,0BAC1B,CAAA,0BAAA,CAA4B,6BAC5B,uBAAyB,CAAA,yBAAA,CACzB,qBAAuB,CAAA,uBAAA,CACvB,oBAAsB,CAAA,sBAAA,CACtB,4BAA8B,CAAA,8BAClC,CAAC,ECvBD,IAAMC,EAAS,CACb,YAAA,CAAc,CAACC,CAAAA,CAAsBC,CAAe,GAAA,CAClD,QAAQ,KAAM,CAAA,CAAA,gCAAA,EAAmCD,CAAY,CAAA,SAAA,EAAYD,CAAO,CAAA,OAAA,CAAQE,CAAK,CAAC,CAAA,CAAE,EAClG,CAAA,CAEA,QAAU,CAAA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CAASC,MAAAA,CAAAA,CAAU,CAEjB,MAAArB,CAAO,CAAA,QAAA,CAAS,QAAS,CAAwBe,qBAAAA,EAAAA,CAAW,CAAaM,UAAAA,EAAAA,CAAAA,CAAI,MAAU,EAAA,GAAG,CAAYrB,SAAAA,EAAAA,CAAAA,CAAO,OAAQqB,CAAAA,CAAAA,CAAI,KAASA,EAAAA,CAAG,CAAC,CAAA,CAAE,EAClI,CACJ,MAAA,CAAQA,CAAI,CAAA,MAAA,EAAU,GACtB,CAAA,UAAA,CAAYA,CAAI,CAAA,UAAA,EAAc7B,CAAW,CAAA,qBAAA,CACzC,KAAO6B,CAAAA,CAAAA,CAAI,KAAS,EAAA,CAClB,OAAQA,CAAI,CAAA,MAAA,EAAU,GACtB,CAAA,KAAA,CAAOA,CAAI,CAAA,UAAA,EAAc7B,CAAW,CAAA,oBACtC,CACF,CACF,CACF,CAAA,CAEO8B,CAAQd,CAAAA","file":"chunk-AMIRIUMH.mjs","sourcesContent":["export default Object.freeze({\r\n INVALID_UUID: \"Invalid UUID\",\r\n INVALID_EMAIL: \"Invalid Email\",\r\n INVALID_TOKEN: \"Invalid Token\",\r\n TOKEN_EXPIRED: \"Token Expired\",\r\n INVALID_VERIFIER: \"Invalid Verifier\",\r\n INVALID_PERMISSIONS: \"Invalid Permissions\",\r\n INVALID_AUTH_TYPE: \"Invalid Authorization Type\",\r\n USER_PRIVATE_KEY_NOT_FOUND: \"User Private Key Not Found\",\r\n USER_PUBLIC_KEY_NOT_FOUND: \"User Public Key Not Found\",\r\n ANONYMOUS_PRIVATE_KEY_NOT_FOUND: \"Anonymous Private Key Not Found\",\r\n ANONYMOUS_PUBLIC_KEY_NOT_FOUND: \"Anonymous Public Key Not Found\",\r\n SYSTEM_PRIVATE_KEY_NOT_FOUND: \"System Private Key Not Found\",\r\n SYSTEM_PUBLIC_KEY_NOT_FOUND: \"System Public Key Not Found\",\r\n ADMIN_PRIVATE_KEY_NOT_FOUND: \"Admin Private Key Not Found\",\r\n ADMIN_PUBLIC_KEY_NOT_FOUND: \"Admin Public Key Not Found\",\r\n SECRET_TOKEN_NOT_FOUND: \"Secret Token Not Found\",\r\n ANONYMOUS_SESSION_NOT_ALLOWED: \"Anonymous Session Not Allowed\",\r\n USER_SESSION_NOT_ALLOWED: \"User Session Not Allowed\",\r\n SYSTEM_SESSION_NOT_ALLOWED: \"System Session Not Allowed\",\r\n CDN_SESSION_NOT_ALLOWED: \"CDN Session Not Allowed\",\r\n INTERNAL_SERVER_ERROR: \"Internal Server Error\",\r\n SOMETHING_WENT_WRONG: 'Something went wrong',\r\n AUTH_CONTEXT_NOT_INITIALIZED: 'Auth Context not Initialized'\r\n})","import util from 'util';\r\nconst Logger = {\r\n logException: (functionName: string, error: any) => {\r\n console.error(`Exception Occurred in Function: ${functionName}, Error: ${Logger.inspect(error)}`);\r\n },\r\n\r\n logError: (functionName: string, error: any) => {\r\n console.error(`Error Occurred in Function: ${functionName}, Error: ${Logger.inspect(error)}`);\r\n },\r\n\r\n logWarning: (functionName: string, message: any) => {\r\n console.warn(`Warning in Function: ${functionName} - ${Logger.inspect(message)}`);\r\n },\r\n\r\n logMessage: (functionName: string, message: any) => {\r\n console.log(`Message in Function: ${functionName} - ${Logger.inspect(message)}`);\r\n },\r\n\r\n logInvalidPayload: (functionName: string, errorMessage: string) => {\r\n console.error(`Invalid Payload received for Function: ${functionName}, Error: ${Logger.inspect(errorMessage)}`);\r\n },\r\n\r\n inspect: (context: any) => {\r\n return (typeof context === \"string\" ? context : util.inspect(context));\r\n }\r\n}\r\n\r\nexport default Logger;","import ErrorTypes from \"../enums/ErrorTypes\";\r\nimport Logger from \"../Logger\";\r\n\r\nexport const ResponseUtility = {\r\n handleException: (functionName: string, error: any, res: any) => {\r\n if (error.knownError) {\r\n error.logError && Logger.logError(functionName, error);\r\n res.status(error.status).json({\r\n status: error.status,\r\n error: error.error\r\n });\r\n } else if(error.status && error.error) {\r\n Logger.logException(functionName, error);\r\n res.status(error.status).json({\r\n error: error.errorMessage || JSON.stringify(error.error),\r\n status: error.status,\r\n });\r\n } else {\r\n Logger.logException(functionName, error);\r\n res.status(500).json({\r\n status: 500,\r\n error: ErrorTypes.INTERNAL_SERVER_ERROR\r\n })\r\n }\r\n },\r\n\r\n generateResponse: (status: number, data?: any, error?: string) => {\r\n return {\r\n status,\r\n data,\r\n error\r\n }\r\n },\r\n\r\n generateError: (status: number, error: string, knownError: Boolean = true, logError: boolean = false) => {\r\n return {\r\n status,\r\n error,\r\n knownError,\r\n logError\r\n }\r\n }\r\n}\r\n\r\nexport default ResponseUtility;","\"use client\";\r\n\r\nimport ErrorTypes from \"../enums/ErrorTypes\";\r\nimport Logger from \"../Logger\";\r\n\r\nexport type ErrorType = {\r\n status: number;\r\n statusText: string;\r\n error: any;\r\n};\r\n\r\nexport type SuccessType = {\r\n status: number;\r\n statusText: string;\r\n data: any;\r\n};\r\n\r\n/**\r\n * Makes an HTTP request to the specified endpoint using the provided parameters.\r\n *\r\n * @param {string} baseURL - The base URL of the API.\r\n * @param {string} endpoint - The specific endpoint to call.\r\n * @param {'GET' | 'POST' | 'PATCH' | 'DELETE'} [method='GET'] - The HTTP method to use for the request.\r\n * @param {Record<string, string>} [headers={}] - Additional headers to include in the request.\r\n * @param {any} [payload] - The payload to send with the request, if applicable.\r\n * @returns {Promise<SuccessType>} - A promise that resolves to the response data if the request is successful.\r\n * @throws {ErrorType} - Throws an error if the request fails.\r\n */\r\nconst Fetch = async (\r\n baseURL: string,\r\n endpoint: string,\r\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE' = 'GET',\r\n headers: Record<string, string> = {},\r\n payload?: any,\r\n): Promise<SuccessType> => {\r\n const options: RequestInit = {\r\n method,\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n ...headers,\r\n },\r\n };\r\n\r\n if (method !== 'GET' && payload) {\r\n options.body = JSON.stringify(payload);\r\n }\r\n\r\n const completeURL = `${baseURL}${endpoint ? ('/' + endpoint) : ''}`;\r\n const isInternalAPI = completeURL.includes('api.xetile.com') || completeURL.includes('localhost');\r\n \r\n try {\r\n const response: any = await fetch(completeURL, options);\r\n\r\n if (!response.ok) {\r\n let errorBody: any;\r\n const errorText = await response.text();\r\n\r\n try {\r\n errorBody = JSON.parse(errorText);\r\n } catch (parseError) {\r\n errorBody = {\r\n status: response.status,\r\n error: errorText || response.statusText\r\n };\r\n Logger.logWarning('Fetch', `Failed to parse error response body as JSON for URL-${completeURL}. Raw text: ${errorText}`);\r\n }\r\n\r\n throw {\r\n status: response.status,\r\n statusText: response.statusText,\r\n error: errorBody\r\n } as ErrorType;\r\n }\r\n\r\n const body = await response.json();\r\n\r\n Logger.logMessage('Fetch', `API call successful: URL-${completeURL}, Status- ${response.status}`);\r\n return {\r\n status: response.status,\r\n statusText: response.statusText,\r\n data: isInternalAPI ? body.data : body,\r\n } as SuccessType;\r\n } catch (err: any) {\r\n \r\n Logger.logError('Fetch', `API call failed: URL-${completeURL}, Status- ${err.status || 500}, Error- ${Logger.inspect(err.error || err)}`);\r\n throw {\r\n status: err.status || 500,\r\n statusText: err.statusText || ErrorTypes.INTERNAL_SERVER_ERROR,\r\n error: err.error || {\r\n status: err.status || 500,\r\n error: err.statusText || ErrorTypes.SOMETHING_WENT_WRONG,\r\n }\r\n } as ErrorType;\r\n }\r\n};\r\n\r\nexport default Fetch;\r\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a as a$3}from'./chunk-EP7WVZXC.mjs';import {a}from'./chunk-LNIZAPER.mjs';import {a as a$2}from'./chunk-KWH7GE23.mjs';import {a as a$1}from'./chunk-54RUAXYE.mjs';import {e}from'./chunk-72DR3HF2.mjs';import {b}from'./chunk-NUTKOIGY.mjs';import {b as b$1,c,d,f,g,h}from'./chunk-NJKSUUOB.mjs';var m=class{id;productKey;selectionAttribute;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){this.id=t.id,this.productKey=t.productKey,this.selectionAttribute=a.deepClone(t.selectionAttribute),this.name=a.deepClone(t.name),this.specifications=a.deepClone(t.specifications),this.primaryImage=new b(t.primaryImage),this.subItems=a.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new b$1(i.size);e.add(i.size);}),this.pricing={unitPrice:new a$1(t.pricing.unitPrice),tierPricing:new a$2(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:a.deepClone(t.pricing.tax.taxSlabs)}},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,subtotal:new a$1(t.total.subtotal),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,a])=>[i,new a$1(a)])),taxableAmount:new a$1(t.total.taxableAmount),taxTotal:new a$1(t.total.taxTotal),grandTotal:new a$1(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttribute(){return a.deepClone(this.selectionAttribute)}getName(t){return t?a.deepClone(this.name[t]??this.name[e[t]]??this.name.en):a.deepClone(this.name)}getSpecifications(t){return t?a.deepClone(this.specifications[t]??this.specifications[e[t]]??this.specifications.en):a.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return a.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:a.deepClone(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,e])=>[t,e])),grandTotal:this.total.grandTotal}}getDetails(){return {id:this.getId(),productKey:this.getProductKey(),selectionAttribute:this.getSelectionAttribute(),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:this.getPricing().tax},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,e])=>[t,e.getDetails()])),grandTotal:this.getTotal().grandTotal.getDetails()}}}addSubItems(t,e){t.forEach(i=>{let a=this.subItems.find(n=>n.size===i.size);a?a.quantity=e?a.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity>=0),this.calculateTotals();}updateProductData(t,e,i){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttribute))throw new c;if(!t.getIsActive())throw new d;this.subItems.forEach(c=>{if(!t.validateSize(c.size))throw new f});let a=t.getPriceDetails(e);if(!a||a.getBaseUnitPrice().getCurrency()!==i)throw new g;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttribute).primary;let n=this.subItems.reduce((c,l)=>c+l.quantity,0),{unitPrice:s}=a.getApplicableTier(n);this.pricing={unitPrice:s,tierPricing:a,taxCategory:a.getTaxCategory(),tax:this.pricing.tax},this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discounts=e,this.calculateTotals();}updateTax(t){if(!t.appliesTo(this.pricing.taxCategory,this.pricing.tax.country))throw new h;let e=this.total.taxableAmount.divide(this.total.quantity);this.pricing.tax={taxRuleId:t.getTaxRuleId(),taxSystem:t.getTaxSystem(),country:t.getCountry(),rate:t.getApplicableTaxRate(e),taxSlabs:t.getSlabs()},this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((u,g)=>u+g.quantity,0),{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),a=i.multiply(e),n=Object.values(this.total.discounts).reduce((u,g)=>u.add(g),t),s=a.subtract(n),c=s.divide(e),l=a$3.getApplicableTaxRate(c,this.pricing.tax.taxSlabs),h=s.multiply(l).round(),C=a.subtract(n).add(h);this.total={quantity:e,subtotal:a,taxableAmount:s,taxTotal:h,discounts:this.total.discounts,grandTotal:C};}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttribute={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{m as a};//# sourceMappingURL=chunk-CEGQFFYZ.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-CEGQFFYZ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/Classes/LineItem.ts"],"names":["LineItemModel","data","Utils_default","ImageInfoModel","uniqueSelectionAttributes","item","DuplicateSizeError","PriceModel","TieredPriceModel","couponCode","discount","locale","LocaleLanguageMap","subItems","addQuantity","subItem","existingSubItem","sub","product","cartCountry","cartCurrency","ProductMismatchError","ProductInactiveError","SizeMismatchError","productPricing","PricingNotFoundError","quantity","sum","s","unitPrice","appliedDiscounts","lineItemDiscounts","taxRule","InvalidTaxRuleError","taxableUnitPrice","zero","totalQuantity","subTotal","discounts","taxableAmount","unitTaxbleAmount","taxRate","TaxRuleModel","taxTotal","grandTotal"],"mappings":"ySAoEqBA,IAAAA,CAAAA,CAArB,KAAmC,CACvB,EACA,CAAA,UAAA,CACA,kBAEA,CAAA,IAAA,CACA,cACA,CAAA,YAAA,CACA,QACA,CAAA,OAAA,CAaA,KACA,CAAA,KAAA,CAcV,YAAYC,CAA0B,CAAA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,SAAA,CAAWgC,CACX,CAAA,WAAA,CAAa,KAAK,OAAQ,CAAA,WAAA,CAC1B,WAAa,CAAA,IAAA,CAAK,OAAQ,CAAA,WAAA,CAC1B,GAAK,CAAA,IAAA,CAAK,OAAQ,CAAA,GACpB,CACA,CAAA,IAAA,CAAK,KAAQ,CAAA,CACX,QAAU,CAAA,CAAA,CACV,QAAUA,CAAAA,CAAAA,CACV,aAAeA,CAAAA,CAAAA,CACf,QAAUA,CAAAA,CAAAA,CACV,SAAW,CAAA,EACX,CAAA,UAAA,CAAYA,CACd,EACF,CACF","file":"chunk-CEGQFFYZ.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, 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} from \"./Error\";\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 = {\r\n id: string;\r\n\r\n productKey: string;\r\n selectionAttribute: 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 {\r\n protected id: string;\r\n protected productKey: string;\r\n protected selectionAttribute: 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: TaxSlabs;\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 this.id = data.id;\r\n this.productKey = data.productKey;\r\n this.selectionAttribute = Utils.deepClone(data.selectionAttribute);\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: Utils.deepClone(data.pricing.tax.taxSlabs),\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 getSelectionAttribute(): SelectionAttributes {\r\n return Utils.deepClone(this.selectionAttribute);\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: Utils.deepClone(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 selectionAttribute: this.getSelectionAttribute(),\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: this.getPricing().tax\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 };\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.selectionAttribute)) {\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.selectionAttribute).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.taxableAmount.divide(this.total.quantity);\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 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 = taxableAmount.divide(totalQuantity);\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 * 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.selectionAttribute = { 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}"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-LNIZAPER.mjs';import {n}from'./chunk-NJKSUUOB.mjs';import {a}from'./chunk-55SOBG62.mjs';var x=class u extends a{taxRuleId;taxSystem;taxCategory;country;slabs;effectiveFrom;effectiveTo;constructor(e,t=new Date){super(e,t),this.taxRuleId=e.taxRuleId,this.taxSystem=e.taxSystem,this.taxCategory=e.taxCategory,this.country=e.country,this.slabs=a$1.deepClone(e.slabs),this.effectiveFrom=new Date(e.effectiveFrom),this.effectiveTo=e.effectiveTo?new Date(e.effectiveTo):void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getSlabs(){return a$1.deepClone(this.slabs)}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),slabs:this.getSlabs(),effectiveFrom:this.effectiveFrom.toISOString(),effectiveTo:this.effectiveTo?this.effectiveTo.toISOString():void 0,...super.getDetails()}}appliesTo(e,t,r=new Date){return this.taxCategory===e&&this.country===t&&this.effectiveFrom<=r&&(this.effectiveTo?this.effectiveTo>=r:!0)}getApplicableTaxRate(e){return u.getApplicableTaxRate(e,this.slabs)}static getApplicableTaxRate(e,t){let r=e.getAmount(),o=t.filter(i=>(i.minUnitPrice===void 0||r>=i.minUnitPrice)&&(i.maxUnitPrice===void 0||r<i.maxUnitPrice));if(o.length!==1)throw new n;return o[0].rate}};export{x as a};//# sourceMappingURL=chunk-EP7WVZXC.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-EP7WVZXC.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/Classes/TaxRule.ts"],"names":["TaxRuleModel","_TaxRuleModel","BaseModel","data","date","Utils_default","taxCategory","country","at","unitPrice","taxSlabs","price","slabs","s","TaxSlabNotFoundError"],"mappings":"sHA8BaA,IAAAA,CAAAA,CAAN,MAAMC,CAAqBC,SAAAA,CAAU,CAChC,SACA,CAAA,SAAA,CACA,WACA,CAAA,OAAA,CACA,KACA,CAAA,aAAA,CACA,YAOV,WAAYC,CAAAA,CAAAA,CAAyBC,CAAa,CAAA,IAAI,IAAQ,CAAA,CAC5D,MAAMD,CAAMC,CAAAA,CAAI,CAChB,CAAA,IAAA,CAAK,SAAYD,CAAAA,CAAAA,CAAK,UACtB,IAAK,CAAA,SAAA,CAAYA,EAAK,SACtB,CAAA,IAAA,CAAK,YAAcA,CAAK,CAAA,WAAA,CACxB,IAAK,CAAA,OAAA,CAAUA,CAAK,CAAA,OAAA,CACpB,KAAK,KAAQE,CAAAA,GAAAA,CAAM,SAAUF,CAAAA,CAAAA,CAAK,KAAK,CAAA,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AA,CAAqBA,CAAuBC,CAAAA,CAAAA,CAA4B,CAC7E,IAAMC,EAAQF,CAAU,CAAA,SAAA,EAElBG,CAAAA,CAAAA,CAAQF,CAAS,CAAA,MAAA,CAAOG,IAC3BA,CAAE,CAAA,YAAA,GAAiB,KAAaF,CAAAA,EAAAA,CAAAA,EAASE,CAAE,CAAA,YAAA,IAC3CA,EAAE,YAAiB,GAAA,KAAA,CAAA,EAAaF,CAAQE,CAAAA,CAAAA,CAAE,YAC7C,CAAA,CAAA,CAEA,GAAID,CAAM,CAAA,MAAA,GAAW,CACnB,CAAA,MAAM,IAAIE,CAAAA,CAGZ,OAAOF,CAAM,CAAA,CAAC,CAAE,CAAA,IAClB,CACF","file":"chunk-EP7WVZXC.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 from \"./Price\";\r\nimport { TaxSlabNotFoundError } from \"./Error\";\r\n\r\nexport type TaxSlab = {\r\n minUnitPrice: number; // inclusive\r\n maxUnitPrice?: number; // exclusive\r\n rate: number; // e.g. 0.05 = 5%\r\n};\r\n\r\nexport type TaxSlabs = TaxSlab[];\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: TaxSlab[];\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 = Utils.deepClone(data.slabs);\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(): TaxSlab[] {\r\n return Utils.deepClone(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(),\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 static getApplicableTaxRate(unitPrice: PriceModel, taxSlabs: TaxSlabs): number {\r\n const price = unitPrice.getAmount();\r\n\r\n const slabs = taxSlabs.filter(s =>\r\n (s.minUnitPrice === undefined || price >= s.minUnitPrice) &&\r\n (s.maxUnitPrice === undefined || price < s.maxUnitPrice)\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"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-54RUAXYE.mjs';import {i,j,k,l,m}from'./chunk-NJKSUUOB.mjs';var y=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new a(t.baseUnitPrice);if(!t.taxCategory)throw new i;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 j;let m=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||g||h)throw new k("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 l;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity)return this.tiers[e];throw new m(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-KWH7GE23.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-KWH7GE23.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
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,C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,CAYA,iBAAA,CAAkBU,CAA6B,CAAA,CAC7C,GAAIA,CAAAA,EAAY,CACd,CAAA,MAAM,IAAIC,CAAAA,CAGZ,IAASC,IAAAA,CAAAA,CAAI,IAAK,CAAA,KAAA,CAAM,MAAS,CAAA,CAAA,CAAGA,CAAK,EAAA,CAAA,CAAGA,CAC1C,EAAA,CAAA,GAAIF,CAAY,EAAA,IAAA,CAAK,KAAME,CAAAA,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-KWH7GE23.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"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-KWH7GE23.mjs';import {e as e$1}from'./chunk-72DR3HF2.mjs';import {b}from'./chunk-NUTKOIGY.mjs';import {e}from'./chunk-NJKSUUOB.mjs';import {a}from'./chunk-55SOBG62.mjs';import R from'crypto';var h=new Uint8Array(256),m=h.length;function A(){return m>h.length-16&&(R.randomFillSync(h),m=0),h.slice(m,m+=16)}var z=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function w(t){return typeof t=="string"&&z.test(t)}var U=w;var o=[];for(let t=0;t<256;++t)o.push((t+256).toString(16).slice(1));function y(t,e=0){return o[t[e+0]]+o[t[e+1]]+o[t[e+2]]+o[t[e+3]]+"-"+o[t[e+4]]+o[t[e+5]]+"-"+o[t[e+6]]+o[t[e+7]]+"-"+o[t[e+8]]+o[t[e+9]]+"-"+o[t[e+10]]+o[t[e+11]]+o[t[e+12]]+o[t[e+13]]+o[t[e+14]]+o[t[e+15]]}function G(t){if(!U(t))throw TypeError("Invalid UUID");let e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}var M=G;function K(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var V="6ba7b810-9dad-11d1-80b4-00c04fd430c8",B="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function I(t,e,r){function i(n,l,u,S){var b;if(typeof n=="string"&&(n=K(n)),typeof l=="string"&&(l=M(l)),((b=l)===null||b===void 0?void 0:b.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let g=new Uint8Array(16+n.length);if(g.set(l),g.set(n,l.length),g=r(g),g[6]=g[6]&15|e,g[8]=g[8]&63|128,u){S=S||0;for(let f=0;f<16;++f)u[S+f]=g[f];return u}return y(g)}try{i.name=t;}catch{}return i.DNS=V,i.URL=B,i}var x={randomUUID:R.randomUUID};function E(t,e,r){if(x.randomUUID&&!e&&!t)return x.randomUUID();t=t||{};let i=t.random||(t.rng||A)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){r=r||0;for(let n=0;n<16;++n)e[r+n]=i[n];return e}return y(i)}var L=E;function j(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),R.createHash("sha1").update(t).digest()}var k=j;var Y=I("v5",80,k),v=Y;var Z={isUUID:t=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t),isEmail:t=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t),isURL:t=>/^(http|https):\/\/[^ "]+$/.test(t),generateUUID:(t,e)=>e&&t?v(t,e):L(),generateSearchId:(t,e)=>`${t}#${p.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:t=>{let[e,r]=t.split("#");return {key:e,selectionAttribute:r}},deepClone(t){return structuredClone(t)}},s=Z;var p=class t extends a{id;key;sku;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|")}static parseSelectionAttributesKey(e$1){try{let r={},i=e$1.split("|");for(let n of i){let[l,u]=n.split(":");u.startsWith("c+")?r[l]={name:u.slice(2)}:r[l]=u;}return r}catch(r){throw new e(r?.message)}}constructor(e,r=new Date){super(e,r),this.id=e.id,this.key=e.key,this.sku=e.sku,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((i,n)=>(e.pricing[n]&&(i[n]=new a$1(e.pricing[n])),i),{}),this.targetGender=e.targetGender,this.attributes=s.deepClone(e.attributes),this.specifications=s.deepClone(e.specifications),this.categories=s.deepClone(e.categories),this.variants=(e.variants||[]).map(i=>({selectionAttributes:i.selectionAttributes,images:{primary:new b(i.images.primary),gallery:(i.images.gallery||[]).map(n=>new b(n))}})),this.isActive=e.isActive,this.searchTags=e.searchTags?s.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getSku(){return this.sku}getName(e){return e?this.name[e]??this.name[e$1[e]]??this.name.en:s.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[e$1[e]]??this.description.en:s.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[e$1[e]]??this.slug.en:s.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:this.pricing}getAttributes(){return s.deepClone(this.attributes)}getImagesBySelectionAttributes(e){let r=t.generateSelectionAttributesKey(e),i=this.variants.find(n=>t.generateSelectionAttributesKey(n.selectionAttributes)===r);return i?i.images:null}getImages(e,r){switch(r){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return s.deepClone(this.categories)}getSpecifications(e){return e?s.deepClone(this.specifications[e]??this.specifications[e$1[e]]??this.specifications.en):s.deepClone(this.specifications)}getSearchTags(e){return e?s.deepClone(this.searchTags[e]??this.searchTags[e$1[e]]??this.searchTags.en):s.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),sku:this.getSku(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((r,i)=>(this.pricing[i]&&(r[i]=this.pricing[i]?.getDetails()),r),{}),attributes:this.getAttributes(),variants:this.variants.map(r=>({selectionAttributes:s.deepClone(r.selectionAttributes),images:{primary:r.images.primary.getDetails(),gallery:r.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}validateSelectionAttribute(e){let r=t.generateSelectionAttributesKey(e);return this.variants.some(i=>t.generateSelectionAttributesKey(i.selectionAttributes)===r)}validateSize(e){return this.attributes.size.includes(e)}};export{s as a,p as b};//# sourceMappingURL=chunk-LNIZAPER.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-LNIZAPER.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../node_modules/uuid/dist/esm-node/rng.js","../node_modules/uuid/dist/esm-node/regex.js","../node_modules/uuid/dist/esm-node/validate.js","../node_modules/uuid/dist/esm-node/stringify.js","../node_modules/uuid/dist/esm-node/parse.js","../node_modules/uuid/dist/esm-node/v35.js","../node_modules/uuid/dist/esm-node/native.js","../node_modules/uuid/dist/esm-node/v4.js","../node_modules/uuid/dist/esm-node/sha1.js","../node_modules/uuid/dist/esm-node/v5.js","../src/Utils/index.ts","../src/Classes/Product.ts"],"names":["rnds8Pool","poolPtr","rng","crypto","regex_default","validate","uuid","validate_default","byteToHex","i","unsafeStringify","arr","offset","parse","v","parse_default","stringToBytes","str","bytes","DNS","URL","v35","name","version","hashfunc","generateUUID","value","namespace","buf","_namespace","native_default","v4","options","rnds","v4_default","sha1","sha1_default","v5","v5_default","Utils","key","selectionAttribute","ProductModel","searchId","obj","Utils_default","_ProductModel","BaseModel","selectionAttributes","attributes","parts","part","error","SelectionAttributeParseError","data","date","acc","country","TieredPriceModel","variant","ImageInfoModel","image","locale","LocaleLanguageMap","searchKey","match","category","baseDetails","img","size"],"mappings":"6NACA,IAAMA,EAAY,IAAI,UAAA,CAAW,GAAG,CAEhCC,CAAAA,CAAAA,CAAUD,CAAU,CAAA,MAAA,CACT,SAARE,CAAuB,EAAA,CAC5B,OAAID,CAAUD,CAAAA,CAAAA,CAAU,OAAS,EAC/BG,GAAAA,CAAAA,CAAO,cAAeH,CAAAA,CAAS,EAC/BC,CAAU,CAAA,CAAA,CAAA,CAGLD,EAAU,KAAMC,CAAAA,CAAAA,CAASA,GAAW,EAAE,CAC/C,CCXA,IAAOG,EAAQ,qHCEf,CAAA,SAASC,EAASC,CAAM,CAAA,CACtB,OAAO,OAAOA,CAAAA,EAAS,QAAYF,EAAAA,CAAAA,CAAM,KAAKE,CAAI,CACpD,CAEA,IAAOC,CAAAA,CAAQF,ECAf,IAAMG,CAAAA,CAAY,EAAC,CAEnB,QAASC,CAAI,CAAA,CAAA,CAAGA,EAAI,GAAK,CAAA,EAAEA,EACzBD,CAAU,CAAA,IAAA,CAAA,CAAMC,CAAI,CAAA,GAAA,EAAO,SAAS,EAAE,CAAA,CAAE,MAAM,CAAC,CAAC,EAG3C,SAASC,CAAAA,CAAgBC,EAAKC,CAAS,CAAA,CAAA,CAAG,CAG/C,OAAOJ,CAAAA,CAAUG,EAAIC,CAAS,CAAA,CAAC,CAAC,CAAIJ,CAAAA,CAAAA,CAAUG,CAAIC,CAAAA,CAAAA,CAAS,CAAC,CAAC,CAAA,CAAIJ,EAAUG,CAAIC,CAAAA,CAAAA,CAAS,CAAC,CAAC,CAAA,CAAIJ,CAAUG,CAAAA,CAAAA,CAAIC,EAAS,CAAC,CAAC,EAAI,GAAMJ,CAAAA,CAAAA,CAAUG,EAAIC,CAAS,C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BAA+BE,CAAAA,CAAmB,EAEjF,OAAO,IAAA,CAAK,QAAS,CAAA,IAAA,CAAKW,GAAWb,CAAa,CAAA,8BAAA,CAA+Ba,EAAQ,mBAAmB,CAAA,GAAMK,CAAS,CAC7H,CAOA,aAAaK,CAAuB,CAAA,CAClC,OAAO,IAAK,CAAA,UAAA,CAAW,KAAK,QAASA,CAAAA,CAAI,CAC3C,CACF","file":"chunk-LNIZAPER.mjs","sourcesContent":["import crypto from 'crypto';\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\n\nlet poolPtr = rnds8Pool.length;\nexport default function rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n crypto.randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}","export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\n\nexport function unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];\n}\n\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import validate from './validate.js';\n\nfunction parse(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n let v;\n const arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nexport default parse;","import { unsafeStringify } from './stringify.js';\nimport parse from './parse.js';\n\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n const bytes = [];\n\n for (let i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n\n return bytes;\n}\n\nexport const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexport const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nexport default function v35(name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n var _namespace;\n\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n\n if (typeof namespace === 'string') {\n namespace = parse(namespace);\n }\n\n if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n } // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n\n\n let bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n\n return buf;\n }\n\n return unsafeStringify(bytes);\n } // Function#name is not settable on some platforms (#270)\n\n\n try {\n generateUUID.name = name; // eslint-disable-next-line no-empty\n } catch (err) {} // For CommonJS default export support\n\n\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","import crypto from 'crypto';\nexport default {\n randomUUID: crypto.randomUUID\n};","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\n\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n\n options = options || {};\n const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return unsafeStringify(rnds);\n}\n\nexport default v4;","import crypto from 'crypto';\n\nfunction sha1(bytes) {\n if (Array.isArray(bytes)) {\n bytes = Buffer.from(bytes);\n } else if (typeof bytes === 'string') {\n bytes = Buffer.from(bytes, 'utf8');\n }\n\n return crypto.createHash('sha1').update(bytes).digest();\n}\n\nexport default sha1;","import v35 from './v35.js';\nimport sha1 from './sha1.js';\nconst v5 = v35('v5', 0x50, sha1);\nexport default v5;","import { v4 as uuidv4, v5 as uuidv5 } from 'uuid';\r\nimport ProductModel, { SelectionAttributes } from '../Classes/Product';\r\n\r\nconst Utils = {\r\n isUUID: (value: string): boolean => {\r\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\r\n return uuidRegex.test(value);\r\n },\r\n\r\n isEmail: (value: string): boolean => {\r\n const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;\r\n return emailRegex.test(value);\r\n },\r\n\r\n isURL: (value: string): boolean => {\r\n const urlRegex = /^(http|https):\\/\\/[^ \"]+$/;\r\n return urlRegex.test(value);\r\n },\r\n \r\n generateUUID: (value?: string, namespace?: string) => {\r\n if(namespace && value){\r\n return uuidv5(value, namespace);\r\n }\r\n return uuidv4();\r\n },\r\n\r\n generateSearchId: (key: string, selectionAttribute: SelectionAttributes) => {\r\n return `${key}#${ProductModel.generateSelectionAttributesKey(selectionAttribute)}`;\r\n },\r\n\r\n getKeyfromSearchId: (searchId: string) => {\r\n const [key, selectionAttribute] = searchId.split('#');\r\n return {\r\n key,\r\n selectionAttribute\r\n }\r\n },\r\n\r\n deepClone<T>(obj: T): T {\r\n return structuredClone(obj);\r\n }\r\n}\r\n\r\nexport default Utils;\r\n","import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { Color, LocalizedString, CountryCode, LocaleCode, LocalizedValue, Prettify } from './Common';\r\nimport { GenderCategory, ImageCategory, LocaleLanguageMap } from \"./Enum\";\r\nimport { SelectionAttributeParseError } from \"./Error\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport { TieredPriceModel, TieredPriceAttributes, TieredPriceData } from \"./TieredPrice\";\r\n\r\nexport type ProductSelectionAttributes = Prettify<{\r\n color: Color[];\r\n size: string[];\r\n} & {\r\n [key: string]: string | string[] | Color[];\r\n}>;\r\n\r\nexport type SelectionAttributes = {\r\n color: Color;\r\n [key: string]: string | Color;\r\n};\r\n\r\nexport type VariantData = {\r\n selectionAttributes: SelectionAttributes;\r\n images: {\r\n primary: ImageInfoData;\r\n gallery: ImageInfoData[];\r\n };\r\n};\r\n\r\nexport type VariantModel = {\r\n selectionAttributes: SelectionAttributes;\r\n images: {\r\n primary: ImageInfoModel;\r\n gallery: ImageInfoModel[];\r\n };\r\n};\r\n\r\n\r\nexport type ProductSpecification = { [key: string]: string | string[] };\r\n\r\nexport type ProductAttributes = BaseAttributes & {\r\n id: string;\r\n key: string;\r\n sku: string;\r\n\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n slug: LocalizedString;\r\n brand: string;\r\n\r\n pricing: {\r\n [country in CountryCode]?: TieredPriceAttributes;\r\n };\r\n\r\n targetGender: GenderCategory;\r\n attributes: ProductSelectionAttributes;\r\n specifications: LocalizedValue<ProductSpecification>;\r\n categories: string[];\r\n\r\n variants: VariantData[];\r\n\r\n // Metadata\r\n isActive: boolean;\r\n searchTags?: LocalizedValue<string[]>;\r\n};\r\n\r\nexport type ProductData = Required<ProductAttributes>\r\n\r\nexport default class ProductModel extends BaseModel {\r\n protected id: string;\r\n protected key: string;\r\n protected sku: string;\r\n\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected slug: LocalizedString;\r\n protected brand: string;\r\n\r\n protected pricing: {\r\n [country in CountryCode]?: TieredPriceModel;\r\n };\r\n\r\n protected variants: VariantModel[];\r\n\r\n protected targetGender: GenderCategory;\r\n protected attributes: ProductSelectionAttributes;\r\n protected specifications: LocalizedValue<ProductSpecification>;\r\n protected categories: string[];\r\n\r\n // Metadata\r\n protected isActive: boolean;\r\n\r\n protected searchTags: LocalizedValue<string[]>;\r\n\r\n static productKeyRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n\r\n /**\r\n * Generates a unique key for checking uniqueness for a given selection attributes.\r\n * Excludes 'size' from the key generation.\r\n * @param selectionAttributes - The selection attributes.\r\n * @returns A string key representing the unique attribute combination.\r\n */\r\n static generateSelectionAttributesKey(selectionAttributes: SelectionAttributes): string {\r\n const sortedKeys = Object.keys(selectionAttributes)\r\n .filter(key => selectionAttributes[key] !== undefined && key.toLowerCase() !== 'size')\r\n .sort()\r\n\r\n return sortedKeys.map(key => {\r\n if ((selectionAttributes[key] as Color).name) {\r\n return `${key}:c+${(selectionAttributes[key] as Color).name}`;\r\n }\r\n return `${key}:${selectionAttributes[key]}`;\r\n }).join('|');\r\n }\r\n\r\n /**\r\n * Parses a selection attributes key into an object.\r\n * @param key - The selection attributes key to parse.\r\n * @returns An object containing the parsed selection attributes.\r\n */\r\n static parseSelectionAttributesKey(key: string): SelectionAttributes {\r\n try {\r\n const attributes: SelectionAttributes = {} as unknown as SelectionAttributes;\r\n const parts = key.split('|');\r\n for (const part of parts) {\r\n const [key, value] = part.split(':');\r\n if (value.startsWith('c+')) {\r\n attributes[key] = { name: value.slice(2) } as Color;\r\n } else {\r\n attributes[key] = value;\r\n }\r\n }\r\n return attributes;\r\n } catch (error: any) {\r\n throw new SelectionAttributeParseError(error?.message);\r\n }\r\n }\r\n\r\n /**\r\n * Creates an instance of ProductModel.\r\n * Initializes properties based on the provided data, creating copies where necessary.\r\n * @param data - The initial product attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: ProductAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n\r\n this.id = data.id;\r\n this.key = data.key;\r\n this.sku = data.sku;\r\n\r\n this.name = { ...data.name };\r\n this.description = { ...data.description };\r\n this.slug = { ...data.slug };\r\n this.brand = data.brand;\r\n\r\n this.pricing = (Object.keys(data.pricing) as CountryCode[]).reduce((acc, country) => {\r\n if (data.pricing[country]) {\r\n acc[country] = new TieredPriceModel(data.pricing[country]);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: TieredPriceModel });\r\n\r\n this.targetGender = data.targetGender;\r\n this.attributes = Utils.deepClone(data.attributes);\r\n this.specifications = Utils.deepClone(data.specifications);\r\n this.categories = Utils.deepClone(data.categories);\r\n\r\n this.variants = (data.variants || []).map(variant => ({\r\n selectionAttributes: variant.selectionAttributes,\r\n images: {\r\n primary: new ImageInfoModel(variant.images.primary),\r\n gallery: (variant.images.gallery || []).map(image => new ImageInfoModel(image))\r\n }\r\n }));\r\n\r\n this.isActive = data.isActive;\r\n this.searchTags = data.searchTags ? Utils.deepClone(data.searchTags) : { en: [] };\r\n }\r\n\r\n /**\r\n * Gets the base Product ID.\r\n * @returns Product ID.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the user-friendly product key.\r\n * @returns Product Key.\r\n */\r\n getKey(): string {\r\n return this.key;\r\n }\r\n\r\n /**\r\n * Gets the SKU for the product.\r\n * @returns SKU string.\r\n */\r\n getSku(): string {\r\n return this.sku;\r\n }\r\n\r\n /**\r\n * Gets the full localized product name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the product name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return Utils.deepClone(this.name);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product description object.\r\n * @returns A copy of the LocalizedString object for the description.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the product description for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The description string for the specified locale.\r\n */\r\n getDescription(locale: LocaleCode): string\r\n getDescription(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.description[locale] ?? this.description[LocaleLanguageMap[locale]] ?? this.description.en;\r\n } else {\r\n return Utils.deepClone(this.description);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product slug object.\r\n * @returns A copy of the LocalizedString object for the slug.\r\n */\r\n getSlug(): LocalizedString\r\n /**\r\n * Gets the product slug for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The slug string for the specified locale.\r\n */\r\n getSlug(locale: LocaleCode): string\r\n getSlug(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.slug[locale] ?? this.slug[LocaleLanguageMap[locale]] ?? this.slug.en;\r\n } else {\r\n return Utils.deepClone(this.slug);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the brand associated with the product.\r\n * @returns The brand name string.\r\n */\r\n getBrand(): string {\r\n return this.brand;\r\n }\r\n\r\n /**\r\n * Gets the tiered price details for the product.\r\n * @returns Pricing details mapped by country.\r\n */\r\n getPriceDetails(): { [country in CountryCode]?: TieredPriceModel }\r\n /**\r\n * Gets the tiered price details for a specific country.\r\n * @param country - The country code.\r\n * @returns The tiered price model for the country, or null if not found.\r\n */\r\n getPriceDetails(country: CountryCode): TieredPriceModel | null\r\n getPriceDetails(country?: CountryCode): { [country in CountryCode]?: TieredPriceModel } | TieredPriceModel | null {\r\n if (country) {\r\n return this.pricing[country] ?? null;\r\n }\r\n return this.pricing;\r\n }\r\n\r\n /**\r\n * Gets the variant-specific attributes (color, sizes). Returns copies.\r\n * @returns Product Attributes.\r\n */\r\n getAttributes(): ProductSelectionAttributes {\r\n return Utils.deepClone(this.attributes);\r\n }\r\n\r\n\r\n /**\r\n * Gets the images for a specific selection attribute combination.\r\n * @param selectionAttributes - The selection attributes to search for.\r\n * @returns The matching image set or null if not found.\r\n */\r\n private getImagesBySelectionAttributes(selectionAttributes: SelectionAttributes): { primary: ImageInfoModel; gallery: ImageInfoModel[] } | null {\r\n const searchKey = ProductModel.generateSelectionAttributesKey(selectionAttributes);\r\n\r\n const match = this.variants.find(variant =>\r\n ProductModel.generateSelectionAttributesKey(variant.selectionAttributes) === searchKey\r\n );\r\n\r\n return match ? match.images : null;\r\n }\r\n\r\n /**\r\n * Gets the images for a specific selection attribute combination.\r\n * @param selectionAttributes - The selection attributes to search for.\r\n * @returns The matching image set or null if not found.\r\n */\r\n getImages(selectionAttributes: SelectionAttributes): { primary: ImageInfoModel; gallery: ImageInfoModel[] }\r\n getImages(selectionAttributes: SelectionAttributes, category: ImageCategory.PRIMARY): ImageInfoModel\r\n getImages(selectionAttributes: SelectionAttributes, category: ImageCategory.GALLERY): ImageInfoModel[]\r\n getImages(selectionAttributes: SelectionAttributes, category?: ImageCategory): { primary: ImageInfoModel; gallery: ImageInfoModel[] } | ImageInfoModel | ImageInfoModel[] {\r\n switch (category) {\r\n case ImageCategory.PRIMARY:\r\n return this.getImagesBySelectionAttributes(selectionAttributes)?.primary ?? this.variants[0]?.images?.primary;\r\n case ImageCategory.GALLERY:\r\n return this.getImagesBySelectionAttributes(selectionAttributes)?.gallery ?? [];\r\n default:\r\n return this.getImagesBySelectionAttributes(selectionAttributes) ?? { primary: this.variants[0]?.images?.primary, gallery: [] };\r\n }\r\n }\r\n\r\n\r\n /**\r\n * Checks if the product is active.\r\n * @returns True if the product is active, false otherwise.\r\n */\r\n getIsActive(): boolean {\r\n return this.isActive;\r\n }\r\n\r\n /**\r\n * Gets the target gender category for the product.\r\n * @returns The GenderCategory enum value.\r\n */\r\n getTargetGender(): GenderCategory {\r\n return this.targetGender;\r\n }\r\n\r\n /**\r\n * Gets the list of categories the product belongs to. Returns a copy.\r\n * @returns An array of category.\r\n */\r\n getCategories(): string[] {\r\n return Utils.deepClone(this.categories);\r\n }\r\n\r\n /**\r\n * Gets the full localized product specifications object.\r\n * @returns Product Specifications\r\n */\r\n getSpecifications(): LocalizedValue<ProductSpecification>\r\n /**\r\n * Gets the product specifications for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The ProductSpecification object for the specified locale, or undefined if not found.\r\n */\r\n getSpecifications(locale: LocaleCode): ProductSpecification | 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 localized list of search tags. Returns a copy.\r\n * @returns Localized array of search tags.\r\n */\r\n getSearchTags(): LocalizedValue<string[]>\r\n /**\r\n * Gets the search tags for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The array of search tags for the specified locale, or undefined if not found.\r\n */\r\n getSearchTags(locale: LocaleCode): string[] | undefined\r\n getSearchTags(locale?: LocaleCode): LocalizedValue<string[]> | string[] | undefined {\r\n if (locale) {\r\n return Utils.deepClone(this.searchTags[locale] ?? this.searchTags[LocaleLanguageMap[locale]] ?? this.searchTags.en);\r\n } else {\r\n return Utils.deepClone(this.searchTags);\r\n }\r\n }\r\n\r\n /**\r\n *\r\n * @returns ProductData\r\n */\r\n getDetails(): ProductData {\r\n const baseDetails = super.getDetails();\r\n return {\r\n id: this.getId(),\r\n key: this.getKey(),\r\n sku: this.getSku(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n slug: this.getSlug(),\r\n brand: this.getBrand(),\r\n pricing: (Object.keys(this.pricing) as CountryCode[]).reduce((acc, country) => {\r\n if (this.pricing[country]) {\r\n acc[country] = this.pricing[country]?.getDetails();\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]: TieredPriceData }),\r\n attributes: this.getAttributes(),\r\n variants: this.variants.map(v => ({\r\n selectionAttributes: Utils.deepClone(v.selectionAttributes),\r\n images: {\r\n primary: v.images.primary.getDetails(),\r\n gallery: v.images.gallery.map(img => img.getDetails())\r\n }\r\n })),\r\n isActive: this.getIsActive(),\r\n targetGender: this.getTargetGender(),\r\n categories: this.getCategories(),\r\n specifications: this.getSpecifications(),\r\n searchTags: this.getSearchTags(),\r\n ...baseDetails\r\n };\r\n }\r\n\r\n\r\n /**\r\n * Validates if the provided selection attributes exist for this product.\r\n * @param selectionAttributes - The attributes to validate.\r\n * @returns True if a valid selection attribute exists, false otherwise.\r\n */\r\n validateSelectionAttribute(selectionAttributes: SelectionAttributes): boolean {\r\n const searchKey = ProductModel.generateSelectionAttributesKey(selectionAttributes);\r\n\r\n return this.variants.some(variant => ProductModel.generateSelectionAttributesKey(variant.selectionAttributes) === searchKey);\r\n }\r\n\r\n /**\r\n * Validates if a specific size is available for this product.\r\n * @param size - The size to check.\r\n * @returns True if the size exists in the product's attributes, false otherwise.\r\n */\r\n validateSize(size: string): boolean {\r\n return this.attributes.size.includes(size);\r\n }\r\n}"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e=class extends Error{constructor(r){super(`Line item with ID '${r}' not found in the cart.`),this.name="LineItemNotFoundError";}},s=class extends Error{constructor(r){super(`Duplicate size found: ${r}`),this.name="DuplicateSizeError";}},n=class extends Error{constructor(r="Product and selection attributes do not match."){super(`ProductMismatch: ${r}`),this.name="ProductMismatchError";}},o=class extends Error{constructor(r="Product is not active."){super(`ProductInactive: ${r}`),this.name="ProductInactiveError";}},i=class extends Error{constructor(r="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${r}`),this.name="SelectionAttributeParseError";}},a=class extends Error{constructor(r="Size does not match."){super(`SizeMismatch: ${r}`),this.name="SizeMismatchError";}},c=class extends Error{constructor(r="Pricing details not available for the product"){super(`NotFound: ${r}`),this.name="PricingNotFoundError";}},u=class extends Error{constructor(r="Tax rule category mismatch."){super(`InvalidTaxRule: ${r}`),this.name="InvalidTaxRuleError";}},p=class extends Error{constructor(r="Tax category is not valid."){super(`InvalidTaxCategory: ${r}`),this.name="InvalidTaxCategoryError";}},d=class extends Error{constructor(r="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${r}`),this.name="InvalidMinQuantityError";}},l=class extends Error{constructor(r){super(`InvalidTieredPrice: ${r}`),this.name="InvalidTieredPriceError";}},m=class extends Error{constructor(r="Quantity must be greater than zero."){super(`InvalidQuantity: ${r}`),this.name="InvalidQuantityError";}},x=class extends Error{constructor(r){super(`NoApplicableTier: Quantity ${r} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}},h=class extends Error{constructor(r="No applicable tax slab or multiple slabs found for the given unit price."){super(`TaxSlabNotFound: ${r}`),this.name="TaxSlabNotFoundError";}},g=class extends Error{constructor(r="Amount cannot be negative."){super(`InvalidAmount: ${r}`),this.name="InvalidPriceAmountError";}},E=class extends Error{constructor(r="Currency code is required."){super(`InvalidCurrency: ${r}`),this.name="InvalidCurrencyCodeError";}},$=class extends Error{constructor(r="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${r}`),this.name="CurrencyMismatchError";}},v=class extends Error{constructor(r){super(`InvalidArgument: ${r}`),this.name="InvalidArgumentError";}},b=class extends Error{constructor(r="Invalid image source configuration."){super(`InvalidImageSource: ${r}`),this.name="InvalidImageSourceError";}};export{e as a,s as b,n as c,o as d,i as e,a as f,c as g,u as h,p as i,d as j,l as k,m as l,x as m,h as n,g as o,E as p,$ as q,v as r,b as s};//# sourceMappingURL=chunk-NJKSUUOB.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-NJKSUUOB.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/Classes/Error.ts"],"names":["LineItemNotFoundError","lineItemId","DuplicateSizeError","size","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,WAAA,CAAYC,EAAoB,CAC5B,KAAA,CAAM,CAAsBA,mBAAAA,EAAAA,CAAU,0BAA0B,CAChE,CAAA,IAAA,CAAK,KAAO,wBAChB,CACJ,EAEaC,CAAN,CAAA,cAAiC,KAAM,CAC1C,YAAYC,CAAc,CAAA,CACtB,KAAM,CAAA,CAAA,sBAAA,EAAyBA,CAAI,CAAE,CAAA,CAAA,CACrC,IAAK,CAAA,IAAA,CAAO,qBAChB,CACJ,CAAA,CAEaC,EAAN,cAAmC,KAAM,CAC5C,WAAYC,CAAAA,CAAAA,CAAkB,gDAAkD,CAAA,CAC5E,MAAM,CAAoBA,iBAAAA,EAAAA,CAAO,CAAE,CAAA,CAAA,CACnC,KAAK,IAAO,CAAA,uBAChB,CACJ,CAAA,CAEaC,EAAN,cAAmC,KAAM,CAC5C,WAAYD,CAAAA,CAAAA,CAAkB,yBAA0B,CACpD,KAAA,CAAM,CAAoBA,iBAAAA,EAAAA,CAAO,EAAE,CACnC,CAAA,IAAA,CAAK,IAAO,CAAA,uBAChB,CACJ,CAEaE,CAAAA,CAAAA,CAAN,cAA2C,KAAM,CACpD,WAAYF,CAAAA,CAAAA,CAAkB,4CAA6C,CACvE,KAAA,CAAM,iCAAiCA,CAAO,CAAA,CAAE,CAChD,CAAA,IAAA,CAAK,KAAO,+BAChB,CACJ,CAEaG,CAAAA,CAAAA,CAAN,cAAgC,KAAM,CACzC,WAAYH,CAAAA,CAAAA,CAAkB,uBAAwB,CAClD,KAAA,CAAM,iBAAiBA,CAAO,CAAA,CAAE,EAChC,IAAK,CAAA,IAAA,CAAO,oBAChB,CACJ,EAEaI,CAAN,CAAA,cAAmC,KAAM,CAC5C,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,EAAkB,0EAA4E,CAAA,CACtG,MAAM,CAAoBA,iBAAAA,EAAAA,CAAO,CAAE,CAAA,CAAA,CACnC,KAAK,IAAO,CAAA,uBAChB,CACJ,CAEaa,CAAAA,CAAAA,CAAN,cAAsC,KAAM,CAC/C,WAAYb,CAAAA,CAAAA,CAAkB,6BAA8B,CACxD,KAAA,CAAM,CAAkBA,eAAAA,EAAAA,CAAO,EAAE,CACjC,CAAA,IAAA,CAAK,IAAO,CAAA,0BAChB,CACJ,CAEac,CAAAA,CAAAA,CAAN,cAAuC,KAAM,CAChD,YAAYd,CAAkB,CAAA,4BAAA,CAA8B,CACxD,KAAA,CAAM,oBAAoBA,CAAO,CAAA,CAAE,CACnC,CAAA,IAAA,CAAK,KAAO,2BAChB,CACJ,CAEae,CAAAA,CAAAA,CAAN,cAAoC,KAAM,CAC7C,YAAYf,CAAkB,CAAA,+DAAA,CAAiE,CAC3F,KAAM,CAAA,CAAA,kBAAA,EAAqBA,CAAO,CAAA,CAAE,EACpC,IAAK,CAAA,IAAA,CAAO,wBAChB,CACJ,EAEagB,CAAN,CAAA,cAAmC,KAAM,CAC5C,YAAYhB,CAAiB,CAAA,CACzB,MAAM,CAAoBA,iBAAAA,EAAAA,CAAO,EAAE,CACnC,CAAA,IAAA,CAAK,IAAO,CAAA,uBAChB,CACJ,CAEaiB,CAAAA,CAAAA,CAAN,cAAsC,KAAM,CAC/C,YAAYjB,CAAkB,CAAA,qCAAA,CAAuC,CACjE,KAAA,CAAM,uBAAuBA,CAAO,CAAA,CAAE,EACtC,IAAK,CAAA,IAAA,CAAO,0BAChB,CACJ","file":"chunk-NJKSUUOB.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 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 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}"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {s}from'./chunk-NJKSUUOB.mjs';var n=(t=>(t.THUMBNAIL="thumbnail",t.SMALL="small",t.MEDIUM="medium",t.LARGE="large",t.ORIGINAL="original",t))(n||{}),i=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw new s("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,s$1){if(s$1===void 0){if(e==="original")throw new s("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=s$1;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};export{n as a,i as b};//# sourceMappingURL=chunk-NUTKOIGY.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-NUTKOIGY.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/Classes/ImageInfo.ts"],"names":["ImageResolution","ImageInfoModel","data","InvalidImageSourceError","resolutionKey","altText","order","label","url"],"mappings":"qCAAO,IAAKA,OACVA,CAAA,CAAA,SAAA,CAAY,WACZA,CAAAA,CAAAA,CAAA,MAAQ,OACRA,CAAAA,CAAAA,CAAA,MAAS,CAAA,QAAA,CACTA,EAAA,KAAQ,CAAA,OAAA,CACRA,EAAA,QAAW,CAAA,UAAA,CALDA,OAAA,EAsBSC,CAAAA,CAAAA,CAAAA,CAArB,KAAoC,CACxB,QACA,GACA,CAAA,KAAA,CACA,KAMV,CAAA,WAAA,CAAYC,EAA0B,CAMpC,GALA,IAAK,CAAA,OAAA,CAAU,CAAE,GAAGA,CAAAA,CAAK,OAAQ,CACjC,CAAA,IAAA,CAAK,IAAMA,CAAK,CAAA,GAAA,CAChB,IAAK,CAAA,KAAA,CAAQA,EAAK,KAClB,CAAA,IAAA,CAAK,KAAQA,CAAAA,CAAAA,CAAK,MAEd,CAAC,IAAA,CAAK,OAAQ,CAAA,QAAA,CAChB,MAAM,IAAIC,CAAAA,CAAwB,oEAAoE,CAE1G,CAMA,YAAa,CACX,OAAO,CAAE,GAAG,KAAK,OAAQ,CAC3B,CAOA,SAAUC,CAAAA,CAAAA,CAAwC,CAChD,OAAO,IAAA,CAAK,OAAQA,CAAAA,CAAa,GAAK,IAAK,CAAA,OAAA,CAAQ,QACrD,CAKA,MAAA,EAA6B,CAC3B,OAAO,IAAA,CAAK,GACd,CAKA,UAA+B,CAC7B,OAAO,IAAK,CAAA,KACd,CAKA,QAA+B,EAAA,CAC7B,OAAO,IAAA,CAAK,KACd,CAMA,MAAA,CAAOC,EAAmC,CACxC,IAAA,CAAK,IAAMA,EAEb,CAMA,QAASC,CAAAA,CAAAA,CAAiC,CACxC,IAAK,CAAA,KAAA,CAAQA,EACf,CAMA,QAAA,CAASC,EAAiC,CACxC,IAAA,CAAK,KAAQA,CAAAA,EACf,CAOA,SAAUH,CAAAA,CAAAA,CAAgCI,IAA+B,CACvE,GAAIA,MAAQ,KAAW,CAAA,CAAA,CAErB,GAAIJ,CAAAA,GAAkB,WACpB,MAAM,IAAID,CAAwB,CAAA,4CAA4C,EAEhF,OAAO,IAAA,CAAK,OAAQC,CAAAA,CAAa,EACnC,CACE,KAAA,IAAA,CAAK,QAAQA,CAAa,CAAA,CAAII,IAElC,CAKA,UAAA,EAA4B,CAC1B,OAAO,CACL,OAAS,CAAA,IAAA,CAAK,YACd,CAAA,GAAA,CAAK,KAAK,MAAO,EAAA,CACjB,KAAO,CAAA,IAAA,CAAK,UACZ,CAAA,KAAA,CAAO,KAAK,QAAS,EACvB,CACF,CACF","file":"chunk-NUTKOIGY.mjs","sourcesContent":["export enum ImageResolution {\r\n THUMBNAIL = 'thumbnail',\r\n SMALL = 'small',\r\n MEDIUM = 'medium',\r\n LARGE = 'large',\r\n ORIGINAL = 'original',\r\n}\r\n\r\nimport { InvalidImageSourceError } from \"./Error\";\r\n\r\nexport type ImageInfoAttribute = {\r\n sources: { [key in ImageResolution]?: string } & { original: string };\r\n alt?: string;\r\n order?: number;\r\n label?: string;\r\n};\r\n\r\nexport type ImageInfoData = ImageInfoAttribute;\r\n\r\n/**\r\n * Represents and manages structured image data, including multiple resolutions.\r\n */\r\nexport default class ImageInfoModel {\r\n protected sources: { [key in ImageResolution]?: string } & { original: string };\r\n protected alt?: string;\r\n protected order?: number;\r\n protected label?: string;\r\n\r\n /**\r\n * Creates an instance of ImageInfoModel.\r\n * @param data - The initial image data.\r\n */\r\n constructor(data: ImageInfoAttribute) {\r\n this.sources = { ...data.sources };\r\n this.alt = data.alt;\r\n this.order = data.order;\r\n this.label = data.label;\r\n\r\n if (!this.sources.original) {\r\n throw new InvalidImageSourceError(\"ImageInfoModel cannot be created without an 'original' source URL.\");\r\n }\r\n }\r\n\r\n /**\r\n * Gets the sources object containing URLs for different resolutions.\r\n * Returns a copy to prevent external modification.\r\n */\r\n getSources() {\r\n return { ...this.sources };\r\n }\r\n\r\n /**\r\n * Gets the URL for a specific resolution key.\r\n * @param resolutionKey - The key of the desired resolution (e.g., 'thumbnail', 'medium').\r\n * @returns The URL string if the key doesn't exist, otherwise original image URL will be returned.\r\n */\r\n getSource(resolutionKey: ImageResolution): string {\r\n return this.sources[resolutionKey] || this.sources.original;\r\n }\r\n\r\n /**\r\n * Gets the alternative text for the image.\r\n */\r\n getAlt(): string | undefined {\r\n return this.alt;\r\n }\r\n\r\n /**\r\n * Gets the display order number for the image.\r\n */\r\n getOrder(): number | undefined {\r\n return this.order;\r\n }\r\n\r\n /**\r\n * Gets the display label or caption for the image.\r\n */\r\n getLabel(): string | undefined {\r\n return this.label;\r\n }\r\n\r\n /**\r\n * Sets the alternative text for the image.\r\n * @param altText - The new alt text.\r\n */\r\n setAlt(altText: string | undefined): void {\r\n this.alt = altText;\r\n // Potentially add logic here to trigger updates if needed\r\n }\r\n\r\n /**\r\n * Sets the display order for the image.\r\n * @param order - The new order number.\r\n */\r\n setOrder(order: number | undefined): void {\r\n this.order = order;\r\n }\r\n\r\n /**\r\n * Sets the display label for the image.\r\n * @param label - The new label text.\r\n */\r\n setLabel(label: string | undefined): void {\r\n this.label = label;\r\n }\r\n\r\n /**\r\n * Updates or adds a URL for a specific resolution.\r\n * @param resolutionKey - The key of the resolution to update/add.\r\n * @param url - The URL for the resolution. Set to undefined to remove.\r\n */\r\n setSource(resolutionKey: ImageResolution, url: string | undefined): void {\r\n if (url === undefined) {\r\n // Prevent deleting the 'original' key if it's required\r\n if (resolutionKey === 'original') {\r\n throw new InvalidImageSourceError(\"Cannot remove the 'original' image source.\");\r\n }\r\n delete this.sources[resolutionKey];\r\n } else {\r\n this.sources[resolutionKey] = url;\r\n }\r\n }\r\n\r\n /**\r\n * Returns a plain JavaScript object representation of the image info.\r\n */\r\n getDetails(): ImageInfoData {\r\n return {\r\n sources: this.getSources(),\r\n alt: this.getAlt(),\r\n order: this.getOrder(),\r\n label: this.getLabel(),\r\n };\r\n }\r\n}"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-CEGQFFYZ.mjs';import {b}from'./chunk-5KD2EW7O.mjs';import {e}from'./chunk-2SGUPNWZ.mjs';import {a as a$2}from'./chunk-LNIZAPER.mjs';import {a as a$3}from'./chunk-54RUAXYE.mjs';import {a}from'./chunk-55SOBG62.mjs';var D=class extends a{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$1(o)),this.billingAddress=t.billingAddress?new b(t.billingAddress,i):null,this.shippingAddress=t.shippingAddress?new b(t.shippingAddress,i):null,this.coupons=(t.coupons??[]).map(o=>new e(o)),this.shippingDetails=t.shippingDetails?a$2.deepClone(t.shippingDetails):null,this.total={subtotal:new a$3(t.total.subtotal),shipping:new a$3(t.total.shipping),effectiveShipping:new a$3(t.total.effectiveShipping),taxTotal:new a$3(t.total.taxTotal),couponTotal:Object.fromEntries(Object.entries(t.total.couponTotal).map(([o,e])=>[o,new a$3(e)])),couponDiscountTotal:new a$3(t.total.couponDiscountTotal),grandTotal:new a$3(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$1(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new b(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new b(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$3({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$3({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)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$3({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-RBROVHJ4.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-RBROVHJ4.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
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,CAAA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,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-RBROVHJ4.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) 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/index.d.mts
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
import { OperationalCountry, OperationalCountryCurrency, OperationalLocale, OperationalLanguage } from './Classes/Enum.mjs';
|
|
2
|
+
import { SelectionAttributes } from './Classes/Product.mjs';
|
|
3
|
+
import './Classes/Base.mjs';
|
|
4
|
+
import './Auth/index.mjs';
|
|
5
|
+
import './Common-FbQ5-3QN.mjs';
|
|
6
|
+
import './Classes/ImageInfo.mjs';
|
|
7
|
+
import './Classes/TieredPrice.mjs';
|
|
2
8
|
|
|
3
9
|
declare const Schema: {
|
|
4
10
|
getStandardSchemaDefinition(): {
|
|
@@ -90,10 +96,6 @@ declare const Schema: {
|
|
|
90
96
|
type: string;
|
|
91
97
|
pattern: string;
|
|
92
98
|
};
|
|
93
|
-
variantId: {
|
|
94
|
-
type: string;
|
|
95
|
-
pattern: string;
|
|
96
|
-
};
|
|
97
99
|
firstName: {
|
|
98
100
|
$ref: string;
|
|
99
101
|
};
|
|
@@ -199,11 +201,12 @@ declare const Utils: {
|
|
|
199
201
|
isEmail: (value: string) => boolean;
|
|
200
202
|
isURL: (value: string) => boolean;
|
|
201
203
|
generateUUID: (value?: string, namespace?: string) => string;
|
|
202
|
-
generateSearchId: (key: string,
|
|
204
|
+
generateSearchId: (key: string, selectionAttribute: SelectionAttributes) => string;
|
|
203
205
|
getKeyfromSearchId: (searchId: string) => {
|
|
204
206
|
key: string;
|
|
205
|
-
|
|
207
|
+
selectionAttribute: string;
|
|
206
208
|
};
|
|
209
|
+
deepClone<T>(obj: T): T;
|
|
207
210
|
};
|
|
208
211
|
|
|
209
212
|
declare const ResponseUtility: {
|