b23-lib 2.1.7 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Auth/index.js +1 -1
- package/dist/Auth/index.js.map +1 -1
- package/dist/Auth/index.mjs +1 -1
- package/dist/Classes/Cart.js +2 -2
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Coupon.js +1 -1
- package/dist/Classes/Coupon.js.map +1 -1
- package/dist/Classes/Coupon.mjs +1 -1
- package/dist/Classes/Inventory.js +1 -1
- package/dist/Classes/Inventory.js.map +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/LineItem.js +1 -1
- package/dist/Classes/LineItem.js.map +1 -1
- package/dist/Classes/LineItem.mjs +1 -1
- package/dist/Classes/Order.js +2 -2
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/Price.js +1 -1
- package/dist/Classes/Price.js.map +1 -1
- package/dist/Classes/Price.mjs +1 -1
- package/dist/Classes/Product.js +1 -1
- package/dist/Classes/Product.js.map +1 -1
- package/dist/Classes/Product.mjs +1 -1
- package/dist/Classes/ShoppingContainer.js +2 -2
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/Classes/TaxRule.js +1 -1
- package/dist/Classes/TaxRule.js.map +1 -1
- package/dist/Classes/TaxRule.mjs +1 -1
- package/dist/Classes/TieredPrice.js +1 -1
- package/dist/Classes/TieredPrice.js.map +1 -1
- package/dist/Classes/TieredPrice.mjs +1 -1
- package/dist/{chunk-SFUOYZ3L.mjs → chunk-43SMYXYL.mjs} +2 -2
- package/dist/{chunk-SFUOYZ3L.mjs.map → chunk-43SMYXYL.mjs.map} +1 -1
- package/dist/{chunk-ZE7D77FR.mjs → chunk-5VI4V3SF.mjs} +2 -2
- package/dist/{chunk-ZE7D77FR.mjs.map → chunk-5VI4V3SF.mjs.map} +1 -1
- package/dist/{chunk-232FJYNB.mjs → chunk-CKJONVT3.mjs} +2 -2
- package/dist/chunk-CKJONVT3.mjs.map +1 -0
- package/dist/{chunk-TJ7AZBND.mjs → chunk-EV4HUBJL.mjs} +2 -2
- package/dist/chunk-EV4HUBJL.mjs.map +1 -0
- package/dist/{chunk-WS7ZY5ZZ.mjs → chunk-GF427QWC.mjs} +2 -2
- package/dist/{chunk-WS7ZY5ZZ.mjs.map → chunk-GF427QWC.mjs.map} +1 -1
- package/dist/{chunk-AWZ6KRLF.mjs → chunk-LEHPVA3Q.mjs} +2 -2
- package/dist/{chunk-AWZ6KRLF.mjs.map → chunk-LEHPVA3Q.mjs.map} +1 -1
- package/dist/{chunk-ARMBZF3E.mjs → chunk-RQC4PNOV.mjs} +3 -3
- package/dist/{chunk-ARMBZF3E.mjs.map → chunk-RQC4PNOV.mjs.map} +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-232FJYNB.mjs.map +0 -1
- package/dist/chunk-TJ7AZBND.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export{d as Fetch,b as Logger,c as ResponseUtility}from'./chunk-AMIRIUMH.mjs';import {b}from'./chunk-
|
|
1
|
+
export{d as Fetch,b as Logger,c as ResponseUtility}from'./chunk-AMIRIUMH.mjs';import {b}from'./chunk-LEHPVA3Q.mjs';export{a as Utils}from'./chunk-LEHPVA3Q.mjs';import'./chunk-43SMYXYL.mjs';import'./chunk-EV4HUBJL.mjs';import {l as l$1,j,a,b as b$1,c,d as d$1}from'./chunk-72DR3HF2.mjs';import'./chunk-WSUPVXRZ.mjs';import'./chunk-JHELVQYY.mjs';import'./chunk-6KCJVEZD.mjs';var d={$id:"standards",definitions:{lowercaseText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]*$"},lowercaseText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,10}$"},lowercaseText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,16}$"},lowercaseText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,30}$"},lowercaseText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,50}$"},lowercaseText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,256}$"},text:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).*$"},text10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,10}$"},text16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,16}$"},text30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,30}$"},text50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,50}$"},text256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,256}$"},requiredText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).+$"},requiredText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,10}$"},requiredText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,16}$"},requiredText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,30}$"},requiredText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,50}$"},requiredText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,256}$"},url:{type:"string",pattern:"^https://[^\\s/$.?#].[^\\s]*$",maxLength:2048},uuid:{type:"string",minLength:1,pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"},productKey:{type:"string",pattern:b.productKeyRegex.source},productSku:{type:"string",pattern:b.productSKURegex.source},taxCategory:{type:"string",enum:Object.values(l$1)},genderCategory:{type:"string",enum:Object.values(j)},price:{type:"object",properties:{amount:{type:"number",minimum:0},currency:{$ref:"#/definitions/currency"}},additionalProperties:!1,required:["amount","currency"]},color:{type:"object",properties:{name:{type:"string"},hex:{type:"string"}},additionalProperties:!1,required:["name"]},attributeValue:{oneOf:[{type:"string"},{$ref:"#/definitions/color"}]},selectionAttributes:{type:"object",properties:{color:{$ref:"#/definitions/color"}},required:["color"],additionalProperties:{$ref:"#/definitions/attributeValue"}},firstName:{$ref:"#/definitions/requiredText30"},lastName:{$ref:"#/definitions/text30"},company:{$ref:"#/definitions/text50"},phone:{type:"string",pattern:"^[0-9]{10}$"},email:{type:"string",pattern:"^[^\\s]+@[^\\s]+\\.[^\\s]+$"},addressLine1:{$ref:"#/definitions/requiredText50"},addressLine2:{$ref:"#/definitions/text50"},city:{$ref:"#/definitions/requiredText30"},postalCode:{$ref:"#/definitions/requiredText16"},state:{type:"string",enum:["AP","AR","AS","BR","CT","GA","GJ","HR","HP","JH","KA","KL","MP","MH","MN","ML","MZ","NL","OR","PB","RJ","SK","TN","TG","TR","UP","UT","WB","AN","CH","DH","LD","DL","PY","LA","JK"]},country:{type:"string",enum:Object.values(a)},currency:{type:"string",enum:Object.values(b$1)},locale:{type:"string",enum:Object.values(c)},language:{type:"string",enum:Object.values(d$1)},localeOrLanguage:{type:"string",enum:[...Object.values(c),...Object.values(d$1)]},addressType:{type:"string",enum:["shipping","billing","billing&shipping"]},address:{type:"object",properties:{firstName:{$ref:"standards#/definitions/firstName"},lastName:{$ref:"standards#/definitions/lastName"},company:{$ref:"standards#/definitions/company"},phone:{$ref:"standards#/definitions/phone"},email:{$ref:"standards#/definitions/email"},addressLine1:{$ref:"standards#/definitions/addressLine1"},addressLine2:{$ref:"standards#/definitions/addressLine2"},city:{$ref:"standards#/definitions/city"},postalCode:{$ref:"standards#/definitions/postalCode"},state:{$ref:"standards#/definitions/state"},country:{$ref:"standards#/definitions/country"}},required:["firstName","lastName","phone","email","addressLine1","postalCode","state","country"]}}};var $={getStandardSchemaDefinition(){return d}},l=$;
|
|
2
2
|
export{l as Schema};//# sourceMappingURL=index.mjs.map
|
|
3
3
|
//# sourceMappingURL=index.mjs.map
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/ShoppingContainer.ts"],"names":["BaseShoppingContainerModel","BaseModel","data","date","item","LineItemModel","AddressModel","coupon","CouponModel","Utils_default","PriceModel","key","value","zero","filteredLineItems","lineitem","subTotal","total","lineItem","shipping","couponDiscountTotal","couponTotal","nonShippingCouponTotal","couponValue","taxTotal","shippingCoupon","effectiveShipping","grandTotal","shippingDetails","applicableCoupons","shippingCoupons","otherCoupons","couponDiscounts","couponDiscount","itemDiscounts","li","code","totalDiscount","c","validItems","a","b","distributed","index","amount","taxRules","coupons","subTotalWithCouponDiscount","maxValuedCoupon","maxCoupon","currentCoupon","currentCouponValue","maxCouponValue"],"mappings":"mPA6DA,IAA8BA,CAA9B,CAAA,cAAiEC,CAAU,CAC/D,EACA,CAAA,UAAA,CACA,aACA,CAAA,WAAA,CACA,SACA,CAAA,eAAA,CACA,eACA,CAAA,cAAA,CAGA,QAGA,KAUA,CAAA,OAAA,CACA,QACA,CAAA,MAAA,CAQV,WAAYC,CAAAA,CAAAA,CAAuCC,CAAa,CAAA,IAAI,KAAQ,CAC1E,KAAA,CAAMD,CAAMC,CAAAA,CAAI,CAChB,CAAA,IAAA,CAAK,EAAKD,CAAAA,CAAAA,CAAK,GACf,IAAK,CAAA,UAAA,CAAaA,CAAK,CAAA,UAAA,CACvB,IAAK,CAAA,aAAA,CAAgBA,CAAK,CAAA,aAAA,CAC1B,IAAK,CAAA,WAAA,CAAcA,CAAK,CAAA,WAAA,CACxB,IAAK,CAAA,OAAA,CAAUA,CAAK,CAAA,OAAA,CACpB,KAAK,QAAWA,CAAAA,CAAAA,CAAK,QACrB,CAAA,IAAA,CAAK,MAASA,CAAAA,CAAAA,CAAK,MACnB,CAAA,IAAA,CAAK,WAAaA,CAAK,CAAA,SAAA,EAAa,EAAC,EAAG,GAAIE,CAAAA,CAAAA,EAAQ,IAAIC,CAAAA,CAAcD,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,CAAK,QAAQ,CAAA,CAAE,IAAI,IAAK,CAAA,KAAA,CAAM,QAAQ,CAAA,CAC1KK,CAAiBH,CAAAA,CAAAA,CAAU,iCAAkCF,CAAAA,CAAAA,CAA4B,KAAK,KAAM,CAAA,QAAA,CAAU,IAAK,CAAA,OAAA,CAAS,IAAK,CAAA,QAAQ,CAAE,CAAA,GAAA,CAAI,KAAK,KAAM,CAAA,QAAQ,CAExK,CAAA,OAAII,CAAuBC,GAAAA,CAAAA,CAClBF,CAAc,CAAA,OAAA,EAAc,GAAA,QAAA,CAAWA,CAAgBD,CAAAA,CAAAA,CAEzDE,CAAqBC,CAAAA,CAAAA,CAAiBF,CAAgBD,CAAAA,CAC/D,CAAC,CAEK1B,CAAAA,CAAAA,CAAcyB,CAAgB,CAAA,iCAAA,CAAkCD,CAA4B,CAAA,IAAA,CAAK,KAAM,CAAA,QAAA,CAAU,KAAK,OAAS,CAAA,IAAA,CAAK,QAAQ,CAAA,CAAE,GAAI,CAAA,IAAA,CAAK,KAAM,CAAA,QAAQ,EACvKxB,CAAY,CAAA,SAAA,EAAc,CAAA,CAAA,GAC5B,IAAK,CAAA,OAAA,CAAQ,IAAKyB,CAAAA,CAAe,EACjC,IAAK,CAAA,KAAA,CAAM,WAAYA,CAAAA,CAAAA,CAAgB,OAAQ,EAAC,CAAIzB,CAAAA,CAAAA,CACpD,KAAK,KAAM,CAAA,mBAAA,CAAsB,IAAK,CAAA,KAAA,CAAM,mBAAoB,CAAA,GAAA,CAAIA,CAAW,CAAA,CAC/E,KAAK,KAAM,CAAA,iBAAA,CAAoB,IAAK,CAAA,KAAA,CAAM,QAAS,CAAA,QAAA,CAASA,CAAW,CAAA,EAE3E,CACF,CACF","file":"chunk-232FJYNB.mjs","sourcesContent":["import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport AddressModel, { AddressData } from \"./Address\";\r\nimport LineItemModel, { LineItemData } from \"./LineItem\";\r\nimport { CountryCode, CurrencyCode, LocaleCode, ShippingDetails } from \"./Common\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport CouponModel, { CouponCategory, CouponData, CouponType } from \"./Coupon\";\r\nimport Utils from \"../Utils\";\r\nimport { LineItemState, TaxCategory } from \"./Enum\";\r\nimport { TaxRuleModel } from \"./TaxRule\";\r\n\r\nexport type ShoppingContainerTotal = {\r\n /** Sum of item prices before discounts & tax */\r\n subtotal: PriceData;\r\n\r\n /** Original shipping cost before coupons / promotions */\r\n shipping: PriceData;\r\n\r\n /** Shipping after coupons / promotions (>= 0) */\r\n effectiveShipping: PriceData;\r\n\r\n /** Total tax amount (all tax rules combined) */\r\n taxTotal: PriceData;\r\n\r\n /**\r\n * Coupon discounts applied\r\n * key = couponCode (or couponId)\r\n * value = discount amount (positive number)\r\n */\r\n couponTotal: Record<string, PriceData>;\r\n\r\n /** Total discount from coupons (derived, optional to store) */\r\n couponDiscountTotal: PriceData;\r\n\r\n /** Final payable amount */\r\n grandTotal: PriceData;\r\n};\r\n\r\n\r\nexport type BaseShoppingContainerAttributes = BaseAttributes & {\r\n id: string;\r\n customerId?: string;\r\n customerEmail?: string;\r\n anonymousId?: string;\r\n lineItems: LineItemData[];\r\n shippingDetails: ShippingDetails | null;\r\n shippingAddress?: AddressData | null;\r\n billingAddress?: AddressData | null;\r\n coupons: CouponData[];\r\n total: ShoppingContainerTotal;\r\n country: CountryCode;\r\n currency: CurrencyCode;\r\n locale: LocaleCode;\r\n};\r\n\r\nexport type BaseShoppingContainerData = BaseShoppingContainerAttributes & BaseData\r\n\r\n\r\n/**\r\n * Abstract base class for shopping-related containers like carts and orders.\r\n * Manages common elements such as line items, addresses, coupons, and totals.\r\n */\r\nexport default abstract class BaseShoppingContainerModel extends BaseModel {\r\n protected id: string;\r\n protected customerId?: string;\r\n protected customerEmail?: string;\r\n protected anonymousId?: string;\r\n protected lineItems: LineItemModel[];\r\n protected shippingDetails: ShippingDetails | null;\r\n protected shippingAddress: AddressModel | null;\r\n protected billingAddress: AddressModel | null;\r\n\r\n // CouponsCodes\r\n protected coupons: CouponModel[];\r\n\r\n // Cart Totals\r\n protected total: {\r\n subtotal: PriceModel;\r\n shipping: PriceModel;\r\n effectiveShipping: PriceModel;\r\n taxTotal: PriceModel;\r\n couponTotal: Record<string, PriceModel>;\r\n couponDiscountTotal: PriceModel;\r\n grandTotal: PriceModel;\r\n };\r\n\r\n protected country: CountryCode;\r\n protected currency: CurrencyCode;\r\n protected locale: LocaleCode;\r\n\r\n /**\r\n * Creates an instance of BaseShoppingContainerModel.\r\n * Initializes common properties and calculates initial base totals.\r\n * @param data - The initial attributes for the shopping container.\r\n * @param date - Optional date object for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: BaseShoppingContainerAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.customerId = data.customerId;\r\n this.customerEmail = data.customerEmail;\r\n this.anonymousId = data.anonymousId;\r\n this.country = data.country;\r\n this.currency = data.currency;\r\n this.locale = data.locale;\r\n this.lineItems = (data.lineItems ?? []).map(item => new LineItemModel(item));\r\n this.billingAddress = data.billingAddress ? new AddressModel(data.billingAddress, date) : null;\r\n this.shippingAddress = data.shippingAddress ? new AddressModel(data.shippingAddress, date) : null;\r\n this.coupons = (data.coupons ?? []).map(coupon => new CouponModel(coupon));\r\n\r\n this.shippingDetails = data.shippingDetails ? Utils.deepClone(data.shippingDetails) : null;\r\n\r\n this.total = {\r\n subtotal: new PriceModel(data.total.subtotal),\r\n shipping: new PriceModel(data.total.shipping),\r\n effectiveShipping: new PriceModel(data.total.effectiveShipping),\r\n taxTotal: new PriceModel(data.total.taxTotal),\r\n couponTotal: Object.fromEntries(\r\n Object.entries(data.total.couponTotal).map(([key, value]) => [key, new PriceModel(value)])\r\n ),\r\n couponDiscountTotal: new PriceModel(data.total.couponDiscountTotal),\r\n grandTotal: new PriceModel(data.total.grandTotal),\r\n };\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for this shopping container (cart ID or order ID).\r\n * @returns The ID string.\r\n */\r\n public getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the customer ID associated with this container, if available.\r\n * @returns The customer ID string, or undefined.\r\n */\r\n public getCustomerId(): string | undefined {\r\n return this.customerId;\r\n }\r\n\r\n /**\r\n * Gets the customer email associated with this container, if available.\r\n * @returns The customer email string, or undefined.\r\n */\r\n public getCustomerEmail(): string | undefined {\r\n return this.customerEmail;\r\n }\r\n\r\n /**\r\n * Gets the anonymous user ID associated with this container, if available.\r\n * @returns The anonymous ID string, or undefined.\r\n */\r\n public getAnonymousId(): string | undefined {\r\n return this.anonymousId;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the line items in the container.\r\n * Each item is a new LineItemModel instance created from the original's details.\r\n * @returns An array of LineItemModel instances.\r\n */\r\n public getLineItems(): LineItemModel[] {\r\n // Return new instances to prevent modification of internal state\r\n return this.lineItems.map(item => new LineItemModel(item.getDetails()));\r\n }\r\n\r\n /**\r\n * Gets current number of line items in the container.\r\n * @returns The count of line items.\r\n */\r\n public getLineItemsCount(): number {\r\n return this.lineItems.length;\r\n }\r\n\r\n /**\r\n * Gets a copy of the shipping details associated with the container.\r\n * @returns A ShippingDetails object, or null if none are set.\r\n */\r\n public getShippingDetails(): ShippingDetails | null {\r\n // Return a shallow copy if details exist\r\n return this.shippingDetails ? { ...this.shippingDetails } : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the shipping address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no shipping address is set.\r\n */\r\n public getShippingAddress(): AddressModel | null {\r\n return this.shippingAddress ? new AddressModel(this.shippingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Checks if a shipping address is associated with this container.\r\n * @returns True if a shipping address is set, false otherwise.\r\n */\r\n public hasShippingAddress(): boolean {\r\n return !!this.shippingAddress;\r\n }\r\n\r\n /**\r\n * Checks if a billing address is associated with this container.\r\n * @returns True if a billing address is set, false otherwise.\r\n */\r\n public hasBillingAddress(): boolean {\r\n return !!this.billingAddress;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the billing address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no billing address is set.\r\n */\r\n public getBillingAddress(): AddressModel | null {\r\n return this.billingAddress ? new AddressModel(this.billingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the coupons applied to the container.\r\n * Each item is a new CouponModel instance created from the original's details.\r\n * @returns An array of CouponModel instances.\r\n */\r\n public getCoupons(): CouponModel[] {\r\n return this.coupons;\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this container.\r\n * @returns The CountryCode enum value.\r\n */\r\n public getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Gets the currency code associated with this container.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Gets the locale code associated with this container.\r\n * @returns The LocaleCode enum value.\r\n */\r\n public getLocale(): LocaleCode {\r\n return this.locale;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the calculated totals for the container.\r\n * @returns An object containing shipping, subtotal, coupon, and grand totals.\r\n */\r\n public getTotal() {\r\n return this.total;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the shopping container's current state.\r\n * Includes details from the base model and specific container properties.\r\n * @returns BaseShoppingContainerData object suitable for serialization or API responses.\r\n */\r\n getDetails(): BaseShoppingContainerData {\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n customerId: this.getCustomerId(),\r\n customerEmail: this.getCustomerEmail(),\r\n anonymousId: this.getAnonymousId(),\r\n lineItems: this.getLineItems().map(item => item.getDetails()),\r\n shippingDetails: this.getShippingDetails(),\r\n shippingAddress: this.getShippingAddress()?.getDetails() || null,\r\n billingAddress: this.getBillingAddress()?.getDetails() || null,\r\n coupons: this.getCoupons().map(coupon => coupon.getDetails()),\r\n total: {\r\n subtotal: this.getTotal().subtotal.getDetails(),\r\n shipping: this.getTotal().shipping.getDetails(),\r\n effectiveShipping: this.getTotal().effectiveShipping.getDetails(),\r\n taxTotal: this.getTotal().taxTotal.getDetails(),\r\n couponTotal: Object.fromEntries(Object.entries(this.getTotal().couponTotal).map(([key, value]) => [key, value.getDetails()])),\r\n couponDiscountTotal: this.getTotal().couponDiscountTotal.getDetails(),\r\n grandTotal: this.getTotal().grandTotal.getDetails(),\r\n },\r\n country: this.getCountry(),\r\n currency: this.getCurrency(),\r\n locale: this.getLocale(),\r\n }\r\n };\r\n\r\n /**\r\n * Recalculates the total costs for the shopping container.\r\n * This includes summing line items, calculating shipping, applying coupons, and computing taxes.\r\n */\r\n public calculateTotals(): void {\r\n const zero = new PriceModel({ amount: 0, currency: this.currency });\r\n const filteredLineItems = this.lineItems.filter(lineitem => lineitem.getState() !== LineItemState.CANCELLED);\r\n const subTotal = filteredLineItems.reduce((total, lineItem) => total.add(lineItem.getTotal().subtotal), zero);\r\n\r\n const shipping = new PriceModel({ amount: this.shippingDetails?.cost || 0, currency: this.currency }).round();\r\n\r\n let couponDiscountTotal = zero;\r\n let couponTotal: Record<string, PriceModel> = {};\r\n let nonShippingCouponTotal: Record<string, PriceModel> = {};\r\n this.coupons.forEach(coupon => {\r\n const couponValue = coupon.calculateApplicableCouponDiscount(subTotal, shipping, this.country, this.currency);\r\n couponDiscountTotal = couponDiscountTotal.add(couponValue);\r\n couponTotal[coupon.getCode()] = couponValue;\r\n if (coupon.getCategory() !== CouponCategory.SHIPPING) {\r\n nonShippingCouponTotal[coupon.getCode()] = couponValue;\r\n }\r\n })\r\n this.applyDiscountsInLineItem(nonShippingCouponTotal);\r\n\r\n const taxTotal = filteredLineItems.reduce((total, lineItem) => total.add(lineItem.getTotal().taxTotal), zero);\r\n const shippingCoupon = this.coupons.find(coupon => coupon.getCategory() === CouponCategory.SHIPPING);\r\n const effectiveShipping = shippingCoupon ? shipping.subtract(couponTotal[shippingCoupon.getCode()] || zero) : shipping;\r\n\r\n const grandTotal = subTotal.add(shipping).add(taxTotal).subtract(couponDiscountTotal);\r\n\r\n this.total = {\r\n subtotal: subTotal,\r\n shipping: shipping,\r\n effectiveShipping: effectiveShipping,\r\n couponTotal: couponTotal,\r\n couponDiscountTotal: couponDiscountTotal,\r\n taxTotal: taxTotal,\r\n grandTotal: grandTotal,\r\n };\r\n }\r\n\r\n /**\r\n * Updates the shipping details and recalculates the totals.\r\n * @param shippingDetails - The new shipping details to apply.\r\n */\r\n public updateShippingDetails(shippingDetails: ShippingDetails): void {\r\n this.shippingDetails = shippingDetails;\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Applies a list of coupons to the shopping container.\r\n * Filters out invalid coupons, separates shipping and non-shipping coupons,\r\n * and distributes discounts to line items.\r\n * @param applicableCoupons - The list of coupons to attempt to apply.\r\n */\r\n public applyCoupons(applicableCoupons: CouponModel[]): void {\r\n //Apply coupons\r\n const shippingCoupons = applicableCoupons.filter(coupon => coupon.getCategory() === CouponCategory.SHIPPING);\r\n const otherCoupons = applicableCoupons.filter(coupon => coupon.getCategory() !== CouponCategory.SHIPPING);\r\n\r\n this.coupons = [];\r\n this.total.couponDiscountTotal = this.total.subtotal.zero();\r\n this.total.couponTotal = {};\r\n // Apply non shipping coupons\r\n otherCoupons.length && this.applyNonShippingCoupons(otherCoupons);\r\n this.applyDiscountsInLineItem(this.total.couponTotal);\r\n\r\n // Apply shipping coupons\r\n shippingCoupons.length && this.applyShippingCoupons(shippingCoupons);\r\n\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Distributes the total discount amount among the line items.\r\n * @param couponTotal - A record of coupon codes and their calculated discount amounts.\r\n */\r\n private applyDiscountsInLineItem(couponTotal: Record<string, PriceModel>) {\r\n const couponDiscounts: [string, PriceModel][] = Array.from(Object.entries(couponTotal))\r\n .filter(couponDiscount => !couponDiscount[1].isZero());\r\n\r\n const itemDiscounts = new Map<string, { coupon: CouponModel, amount: PriceModel }[]>();\r\n this.lineItems.forEach(li => itemDiscounts.set(li.getId(), []));\r\n\r\n couponDiscounts.forEach(([code, totalDiscount]) => {\r\n const coupon = this.coupons.find(c => c.getCode() === code);\r\n if (!coupon || totalDiscount.isZero()) return;\r\n\r\n const validItems = this.lineItems\r\n .filter(li => li.getState() !== LineItemState.CANCELLED && !li.getTotal().subtotal.isZero())\r\n .sort((a, b) => a.getTotal().subtotal.compareTo(b.getTotal().subtotal));\r\n\r\n let distributed = new PriceModel({ amount: 0, currency: this.currency });\r\n\r\n validItems.forEach((item, index) => {\r\n let amount: PriceModel;\r\n if (index === validItems.length - 1) {\r\n amount = totalDiscount.subtract(distributed);\r\n } else {\r\n amount = totalDiscount.multiply(item.getTotal().subtotal).divide(this.total.subtotal).round();\r\n }\r\n distributed = distributed.add(amount);\r\n itemDiscounts.get(item.getId())?.push({ coupon, amount });\r\n });\r\n });\r\n\r\n this.lineItems.forEach(lineItem => {\r\n if (lineItem.getState() === LineItemState.CANCELLED || this.total.subtotal.isZero()) {\r\n lineItem.updateDiscounts([]);\r\n } else {\r\n lineItem.updateDiscounts(itemDiscounts.get(lineItem.getId()) || []);\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Updates the tax rules for all line items and recalculates totals.\r\n * @param taxRules - A record of tax rules keyed by tax category.\r\n */\r\n public updateTax(taxRules: Record<TaxCategory, TaxRuleModel>): void {\r\n this.lineItems.forEach(lineItem => {\r\n lineItem.updateTax(taxRules[lineItem.getPricing().taxCategory]);\r\n });\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Selects and applies the best applicable non-shipping coupon.\r\n * Currently supports applying only a single coupon of type COUPON.\r\n * @param applicableCoupons - List of available non-shipping coupons.\r\n */\r\n private applyNonShippingCoupons(applicableCoupons: CouponModel[]) {\r\n const coupons = applicableCoupons.filter(coupon => coupon.getType() === CouponType.COUPON);\r\n if (coupons.length === 1) {\r\n const couponValue = coupons[0].calculateApplicableCouponDiscount(this.total.subtotal, this.total.shipping, this.country, this.currency);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(coupons[0]);\r\n this.total.couponTotal[coupons[0].getCode()] = couponValue;\r\n this.total.couponDiscountTotal = couponValue;\r\n }\r\n }\r\n // Todo: Add support to other type in future like promotion\r\n }\r\n\r\n /**\r\n * Selects and applies the best applicable shipping coupon.\r\n * @param applicableCoupons - List of available shipping coupons.\r\n */\r\n private applyShippingCoupons(applicableCoupons: CouponModel[]) {\r\n if (this.total.shipping.getAmount() > 0 && applicableCoupons.length > 0) {\r\n const subTotalWithCouponDiscount = this.total.subtotal.subtract(this.total.couponDiscountTotal);\r\n\r\n const maxValuedCoupon = applicableCoupons.reduce((maxCoupon, currentCoupon) => {\r\n if (!maxCoupon) return currentCoupon;\r\n\r\n const currentCouponValue = currentCoupon.calculateApplicableCouponDiscount(subTotalWithCouponDiscount, this.total.shipping, this.country, this.currency).min(this.total.shipping);\r\n const maxCouponValue = maxCoupon.calculateApplicableCouponDiscount(subTotalWithCouponDiscount, this.total.shipping, this.country, this.currency).min(this.total.shipping);\r\n\r\n if (currentCouponValue === maxCouponValue) {\r\n return currentCoupon.getType() === 'coupon' ? currentCoupon : maxCoupon;\r\n }\r\n return currentCouponValue > maxCouponValue ? currentCoupon : maxCoupon;\r\n });\r\n\r\n const couponValue = maxValuedCoupon.calculateApplicableCouponDiscount(subTotalWithCouponDiscount, this.total.shipping, this.country, this.currency).min(this.total.shipping);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(maxValuedCoupon);\r\n this.total.couponTotal[maxValuedCoupon.getCode()] = couponValue;\r\n this.total.couponDiscountTotal = this.total.couponDiscountTotal.add(couponValue);\r\n this.total.effectiveShipping = this.total.shipping.subtract(couponValue);\r\n }\r\n }\r\n }\r\n}\r\n\r\n\r\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/Price.ts"],"names":["PriceModel","_PriceModel","#kind","data","InvalidPriceAmountError","InvalidCurrencyCodeError","obj","priceModel","CurrencyMismatchError","InvalidArgumentError","factor","divisor","priceModels","minPrice","currentPrice","maxPrice","amount","currency","options","locale","CurrencyLocaleMap","valueToFormat","fractionDigits","formattingOptions","error","CurrencySymbolMap","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier"],"mappings":"kFAgBA,IAAqBA,EAArB,MAAqBC,GAAW,CAC9BC,EAAAA,CACU,OACA,QAQV,CAAA,WAAA,CAAYC,CAAuB,CAAA,CAEjC,GADA,IAAKD,CAAAA,EAAAA,CAAQ,aACTC,CAAK,CAAA,MAAA,CAAS,EAChB,MAAM,IAAIC,CAAwB,CAAA,4BAA4B,EAGhE,GAAI,CAACD,CAAK,CAAA,QAAA,CACR,MAAM,IAAIE,CAAAA,CAAyB,4BAA4B,CAAA,CAGjE,KAAK,MAASF,CAAAA,CAAAA,CAAK,OACnB,IAAK,CAAA,QAAA,CAAWA,EAAK,SACvB,CAEA,IAAI,IAAA,EAAO,CACT,OAAO,IAAA,CAAKD,EACd,CAEA,OAAO,YAAaI,CAAAA,CAAAA,CAAiC,CACnD,OAAO,OAAOA,CAAQ,EAAA,QAAA,EACtBA,IAAQ,IACPA,EAAAA,CAAAA,CAAY,OAAS,YACxB,CAMO,WAA4B,EAAA,CACjC,OAAO,IAAK,CAAA,QACd,CAKO,SAAA,EAAoB,CACzB,OAAO,IAAA,CAAK,MACd,CAMO,YAAwB,CAC7B,OAAO,CACL,MAAQ,CAAA,IAAA,CAAK,OACb,QAAU,CAAA,IAAA,CAAK,QACjB,CACF,CAoCO,SAAUC,CAAAA,CAAAA,CAAgC,CAC/C,GAAKN,IAAW,YAAaM,CAAAA,CAAU,CAEhC,CAAA,CAAA,GAAI,KAAK,QAAaA,GAAAA,CAAAA,CAAW,aACtC,CAAA,MAAM,IAAIC,CAAsB,CAAA,gDAAgD,CAFhF,CAAA,KAAA,MAAM,IAAIC,CAAqB,CAAA,gCAAgC,CAKjE,CAAA,OAAO,KAAK,MAASF,CAAAA,CAAAA,CAAW,SAAU,EAC5C,CAEO,GAAIA,CA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GAAIa,MAAa,KACf,CAAA,CAAA,MAAM,IAAIZ,CAAyB,CAAA,qCAAqC,CAG1E,CAAA,IAAMyB,EAAgB7B,GAAW,CAAA,gBAAA,CAAiBgB,GAAQ,CACpDc,CAAAA,CAAAA,CAAa,KAAK,GAAI,CAAA,EAAA,CAAID,CAAa,CAAA,CAG7C,OAFqB,IAAK,CAAA,KAAA,CAAMd,EAASe,CAAU,CAAA,CAAIA,CAGzD,CACF","file":"chunk-TJ7AZBND.mjs","sourcesContent":["import { CurrencyCode } from \"./Common\";\r\nimport { CurrencyLocaleMap, CurrencySymbolMap, OperationalCountryCurrency } from \"./Enum\";\r\nimport {\r\n InvalidPriceAmountError,\r\n InvalidCurrencyCodeError,\r\n CurrencyMismatchError,\r\n InvalidArgumentError\r\n} from \"./Error\";\r\n\r\nexport type PriceAttributes = {\r\n amount: number;\r\n currency: CurrencyCode;\r\n}\r\n\r\nexport type PriceData = PriceAttributes;\r\n\r\nexport default class PriceModel {\r\n #kind: string;\r\n protected amount: number;\r\n protected currency: CurrencyCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param amount - The initial price value.\r\n * @param currency - The currency code used for rounding and determining the currency symbol.\r\n * @throws {Error} If price is negative or country/currency mapping is missing.\r\n */\r\n constructor(data: PriceAttributes) {\r\n this.#kind = \"PriceModel\";\r\n if (data.amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative.\");\r\n }\r\n\r\n if (!data.currency) {\r\n throw new InvalidCurrencyCodeError(\"Currency code is required.\");\r\n }\r\n\r\n this.amount = data.amount;\r\n this.currency = data.currency;\r\n }\r\n\r\n get kind() {\r\n return this.#kind;\r\n }\r\n\r\n static isPriceModel(obj: unknown): obj is PriceModel {\r\n return typeof obj === \"object\" &&\r\n obj !== null &&\r\n (obj as any).kind === \"PriceModel\";\r\n }\r\n\r\n /**\r\n * Gets the currency associated with this price instance.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Returns the raw numeric price value.\r\n */\r\n public getAmount(): number {\r\n return this.amount;\r\n }\r\n\r\n /**\r\n *\r\n * @returns PriceData\r\n */\r\n public getDetails(): PriceData {\r\n return {\r\n amount: this.amount,\r\n currency: this.currency\r\n }\r\n }\r\n\r\n /**\r\n * Compares this price with another {@link PriceModel} instance.\r\n *\r\n * The comparison is performed using the numeric price value and is only valid\r\n * when both prices are expressed in the same currency.\r\n *\r\n * ### Comparison result:\r\n * - Returns a **negative number** if this price is **less than** `priceModel`\r\n * - Returns **zero** if both prices are **equal**\r\n * - Returns a **positive number** if this price is **greater than** `priceModel`\r\n *\r\n * @param priceModel - The {@link PriceModel} instance to compare against.\r\n *\r\n * @returns\r\n * A signed number representing the comparison result:\r\n * - `< 0` → this price is lower\r\n * - `0` → prices are equal\r\n * - `> 0` → this price is higher\r\n *\r\n * @throws {Error}\r\n * Throws an error if:\r\n * - `priceModel` is not an instance of {@link PriceModel}\r\n * - The currencies of the two prices do not match\r\n *\r\n * @example\r\n * ```ts\r\n * const a = new PriceModel(\"USD\", 100);\r\n * const b = new PriceModel(\"USD\", 150);\r\n *\r\n * a.compareTo(b); // -50\r\n * b.compareTo(a); // 50\r\n * a.compareTo(a); // 0\r\n * ```\r\n */\r\n public compareTo(priceModel: PriceModel): number {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return this.amount - priceModel.getAmount();\r\n }\r\n\r\n public add(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot add prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.amount + priceModel.getAmount(),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public subtract(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot subtract prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.amount - priceModel.getAmount(),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public multiply(factor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(factor)) {\r\n if (this.currency !== factor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot multiply prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.amount * factor.getAmount(),\r\n currency: this.currency\r\n });\r\n } else if (typeof factor === \"number\" && factor >= 0) {\r\n return new PriceModel({\r\n amount: this.amount * factor,\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a non-negative number.\");\r\n }\r\n\r\n public divide(divisor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(divisor)) {\r\n if (this.currency !== divisor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot divide prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.amount / divisor.getAmount(),\r\n currency: this.currency\r\n });\r\n } else if (typeof divisor === \"number\" && divisor > 0) {\r\n return new PriceModel({\r\n amount: this.amount / divisor,\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a positive number.\");\r\n }\r\n\r\n public min(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((minPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (minPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return minPrice.compareTo(currentPrice) < 0 ? minPrice : currentPrice;\r\n });\r\n }\r\n\r\n public max(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((maxPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (maxPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return maxPrice.compareTo(currentPrice) > 0 ? maxPrice : currentPrice;\r\n });\r\n }\r\n\r\n /**\r\n * Gets a zero value PriceModel for the same currency.\r\n * @returns A PriceModel instance representing zero in the same currency.\r\n */\r\n public zero(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: 0\r\n });\r\n }\r\n\r\n /**\r\n * Checks if the price is zero.\r\n * @returns True if the price is zero, false otherwise.\r\n */\r\n public isZero(): boolean {\r\n return this.amount === 0;\r\n }\r\n\r\n\r\n public round(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: this.getRoundedAmount()\r\n });\r\n }\r\n /**\r\n * Gets the rounded price value based on standard currency rules.\r\n * @returns The numeric price, rounded according to its currency's typical decimal places.\r\n */\r\n public getRoundedAmount(): number {\r\n return PriceModel.getRoundedAmount(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price stored in this instance.\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n public getFormattedString() {\r\n return PriceModel.getFormattedString(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n toString() {\r\n return this.getFormattedString();\r\n }\r\n\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the amount.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param amount - The initial amount value.\r\n * @param currency - The currency code for formatting.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the amount rounded to the next nearest integer (no decimals). Defaults to false.\r\n * @param options.style - The style of formatting, either 'currency' or 'decimal'. Defaults to 'currency'.\r\n * @param options.currencyDisplay - The display format for the currency symbol. Options are 'symbol', 'narrowSymbol', 'code', or 'name'. Defaults to 'symbol'.\r\n * @returns The formatted price string according to locale rules.\r\n * @throws {Error} If currency code is invalid.\r\n */\r\n static getFormattedString(amount: number, currency: CurrencyCode, options: {\r\n displayAsInteger?: boolean,\r\n style?: 'currency' | 'decimal',\r\n currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name'\r\n } = {\r\n displayAsInteger: false,\r\n style: 'currency',\r\n currencyDisplay: 'symbol'\r\n }): string {\r\n\r\n const locale = CurrencyLocaleMap[currency];\r\n if (!currency || !locale) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for formatting.');\r\n }\r\n\r\n let valueToFormat = amount;\r\n const fractionDigits = options.displayAsInteger ? 0 : PriceModel.getDecimalPlaces(currency);\r\n\r\n let formattingOptions: Intl.NumberFormatOptions = {\r\n style: options.style ?? 'currency',\r\n currency: currency,\r\n signDisplay: 'never',\r\n currencyDisplay: options.currencyDisplay,\r\n minimumFractionDigits: fractionDigits,\r\n maximumFractionDigits: fractionDigits,\r\n };\r\n\r\n if (options.displayAsInteger) {\r\n valueToFormat = Math.ceil(valueToFormat);\r\n }\r\n\r\n try {\r\n return new Intl.NumberFormat(locale, formattingOptions).format(valueToFormat);\r\n } catch (error) {\r\n console.error(`Error formatting price for currency \"${currency}\" and locale \"${locale}\":`, error);\r\n // Basic fallback without symbol if Intl fails completely\r\n return `${CurrencySymbolMap[currency] ?? currency} ${PriceModel.addThousandSeparators(valueToFormat.toFixed(fractionDigits))}`;\r\n }\r\n }\r\n\r\n /**\r\n * Helper method to determine standard decimal places for a currency.\r\n * @param currency - The currency code.\r\n * @returns The number of decimal places (0, 2, or 3 based on common rules).\r\n */\r\n private static getDecimalPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case OperationalCountryCurrency.INR:\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n /**\r\n * Adds basic thousand separators (commas) to a number string.\r\n * Does not handle different locale separators (e.g., periods, spaces).\r\n * @param numStr - The number string (potentially with decimals).\r\n * @returns The number string with commas added.\r\n */\r\n private static addThousandSeparators(numStr: string): string {\r\n const parts = numStr.split('.');\r\n const integerPart = parts[0];\r\n const decimalPart = parts.length > 1 ? '.' + parts[1] : '';\r\n\r\n const formattedInteger = integerPart.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\r\n return formattedInteger + decimalPart;\r\n }\r\n\r\n /**\r\n * Rounds a price value according to the standard decimal places\r\n * for the currency associated with the given country.\r\n *\r\n * @param price - The price value to round. Must be a non-negative number.\r\n * @param currency - The currency code to determine the rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the price is negative or currency is invalid.\r\n */\r\n static getRoundedAmount(amount: number, currency: CurrencyCode): number {\r\n if (amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative for rounding.\");\r\n }\r\n\r\n if (currency === undefined) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for rounding.');\r\n }\r\n\r\n const decimalPlaces = PriceModel.getDecimalPlaces(currency);\r\n const multiplier = Math.pow(10, decimalPlaces);\r\n const roundedValue = Math.round(amount * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n}"]}
|