b23-lib 1.7.24 → 1.7.25
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/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/Order.d.mts +30 -3
- package/dist/Classes/Order.d.ts +30 -3
- package/dist/Classes/Order.js +1 -1
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/Order.mjs.map +1 -1
- package/dist/Classes/Price.d.mts +12 -3
- package/dist/Classes/Price.d.ts +12 -3
- 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/ShoppingContainer.js +1 -1
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/{chunk-JMO7QKIT.mjs → chunk-ADECAEML.mjs} +2 -2
- package/dist/{chunk-JMO7QKIT.mjs.map → chunk-ADECAEML.mjs.map} +1 -1
- package/dist/chunk-GCT7VOSM.mjs +2 -0
- package/dist/chunk-GCT7VOSM.mjs.map +1 -0
- package/dist/chunk-Z6YNOEGK.mjs +2 -0
- package/dist/chunk-Z6YNOEGK.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-VJ64OPJY.mjs +0 -2
- package/dist/chunk-VJ64OPJY.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/Classes/Order.ts"],"names":["OrderState","OrderModel","BaseShoppingContainerModel","data","date"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../../src/Classes/Order.ts"],"names":["OrderState","OrderLineItemState","OrderModel","BaseShoppingContainerModel","data","date","item","currentStateMap","lineItemId","LineItemNotFoundError"],"mappings":"8RAMYA,IAAAA,CAAAA,CAAAA,CAAAA,CA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EACZ,CAAA,aAAA,CAAe,IAAK,CAAA,oBAAA,EACtB,CACF,CACF","file":"Order.mjs","sourcesContent":["import AddressModel from \"./Address\";\r\nimport { LineItemNotFoundError } from \"./Cart\";\r\nimport { ISODateTime } from \"./Common\";\r\nimport { PaymentStatus } from \"./Payment\";\r\nimport BaseShoppingContainerModel, { BaseShoppingContainerAttributes, BaseShoppingContainerData } from \"./ShoppingContainer\";\r\n\r\nexport enum OrderState {\r\n PENDING_PAYMENT = \"PENDING_PAYMENT\",\r\n PROCESSING = \"PROCESSING\",\r\n SHIPPED = \"SHIPPED\",\r\n PARTIALLY_SHIPPED = \"PARTIALLY_SHIPPED\",\r\n DELIVERED = \"DELIVERED\",\r\n CANCELLED = \"CANCELLED\",\r\n RETURNED = \"RETURNED\",\r\n REFUNDED = \"REFUNDED\",\r\n}\r\n\r\nexport enum OrderLineItemState {\r\n INITIAL = \"INITIAL\",\r\n PROCESSING = \"PROCESSING\",\r\n SHIPPED = \"SHIPPED\",\r\n DELIVERED = \"DELIVERED\",\r\n CANCELLED = \"CANCELLED\",\r\n}\r\n\r\nexport type OrderLineItemStateMap = Record<string, {\r\n state:OrderLineItemState;\r\n reason?: string;\r\n transitionAt: ISODateTime;\r\n}>;\r\n\r\n/**\r\n * Input attributes for creating an OrderModel.\r\n * Extends CartAttributes but requires/adds order-specific fields.\r\n */\r\nexport type OrderAttributes = Required<Omit<BaseShoppingContainerAttributes, 'anonymousId'>> & {\r\n anonymousId?: string;\r\n orderNumber: string;\r\n cartId: string;\r\n paymentStatus: PaymentStatus;\r\n holdReason?: string;\r\n state: OrderState;\r\n LineItemState: OrderLineItemStateMap;\r\n};\r\n\r\n/**\r\n * Output data structure for an OrderModel.\r\n */\r\nexport type OrderData = BaseShoppingContainerData & OrderAttributes;\r\n\r\n\r\nexport default class OrderModel extends BaseShoppingContainerModel {\r\n protected orderNumber: string;\r\n protected cartId: string;\r\n protected paymentStatus: PaymentStatus;\r\n protected holdReason: string;\r\n protected state: OrderState;\r\n protected LineItemState: OrderLineItemStateMap;\r\n\r\n /**\r\n * Creates an instance of OrderModel.\r\n * @param data - The initial order attributes, including cart data.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n * @param config - Optional cart configuration (might be less relevant for orders).\r\n */\r\n constructor(data: OrderAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.orderNumber = data.orderNumber;\r\n this.cartId = data.cartId;\r\n this.paymentStatus = data.paymentStatus;\r\n this.holdReason = data.holdReason || '';\r\n this.state = data.state;\r\n \r\n this.LineItemState = {};\r\n data.lineItems.forEach(item => {\r\n const currentStateMap = this.LineItemState[item.id];\r\n \r\n this.LineItemState[item.id] = {\r\n state: currentStateMap?.state || OrderLineItemState.INITIAL,\r\n reason: currentStateMap?.reason || '',\r\n transitionAt: currentStateMap?.transitionAt || this.createdAt,\r\n };\r\n });\r\n }\r\n\r\n /**\r\n * Gets the user-facing order number.\r\n * @returns The order number string.\r\n */\r\n public getOrderNumber(): string {\r\n return this.orderNumber;\r\n }\r\n\r\n /**\r\n * Gets the ID of the cart from which this order was created.\r\n * @returns The cart ID string.\r\n */\r\n public getCartId(): string {\r\n return this.cartId;\r\n }\r\n\r\n /**\r\n * Gets the current payment status of the order.\r\n * @returns The PaymentStatus enum value.\r\n */\r\n public getPaymentStatus(): PaymentStatus {\r\n return this.paymentStatus;\r\n }\r\n\r\n /**\r\n * Gets the reason why the order might be on hold, if any.\r\n * @returns The hold reason string (empty if not on hold or no reason specified).\r\n */\r\n public getHoldReason(): string {\r\n return this.holdReason;\r\n }\r\n\r\n /**\r\n * Gets the current state of the order (e.g., PROCESSING, SHIPPED).\r\n * @returns The OrderState enum value.\r\n */\r\n public getState(): OrderState {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the map tracking the state of each line item in the order.\r\n * The keys are line item IDs, and the values contain the state, reason, and transition timestamp.\r\n * @returns The OrderLineItemStateMap.\r\n */\r\n public getLineItemsStateMap(): OrderLineItemStateMap {\r\n return { ...this.LineItemState };\r\n }\r\n\r\n /**\r\n * Gets the current state of a specific line item within the order.\r\n * @param lineItemId - The ID of the line item whose state is requested.\r\n * @returns The OrderLineItemState enum value for the specified line item.\r\n * @throws {LineItemNotFoundError} If no line item with the given ID exists in the order's state map.\r\n */\r\n public getLineItemState(lineItemId: string): OrderLineItemState {\r\n if (!this.LineItemState[lineItemId]){\r\n throw new LineItemNotFoundError(lineItemId)\r\n }\r\n return this.LineItemState[lineItemId].state;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the order's current state.\r\n * Includes all cart details plus order-specific information.\r\n * @returns OrderData object suitable for serialization or API responses.\r\n */\r\n getDetails(): OrderData {\r\n return {\r\n ...super.getDetails(),\r\n customerId: this.getCustomerId() as string,\r\n customerEmail: this.getCustomerEmail() as string,\r\n shippingAddress: (this.getShippingAddress() as AddressModel).getDetails(),\r\n billingAddress: (this.getBillingAddress() as AddressModel).getDetails(),\r\n orderNumber: this.getOrderNumber(),\r\n cartId: this.getCartId(),\r\n paymentStatus: this.getPaymentStatus(),\r\n holdReason: this.getHoldReason(),\r\n state: this.getState(),\r\n LineItemState: this.getLineItemsStateMap()\r\n }\r\n }\r\n}\r\n"]}
|
package/dist/Classes/Price.d.mts
CHANGED
|
@@ -22,15 +22,25 @@ declare class PriceModel {
|
|
|
22
22
|
* @returns The numeric price, rounded according to its currency's typical decimal places.
|
|
23
23
|
*/
|
|
24
24
|
getRoundedPrice(): number;
|
|
25
|
+
/**
|
|
26
|
+
* Gets a locale-aware formatted display string for the price stored in this instance.
|
|
27
|
+
* Uses the static `PriceModel.getFormattedString` method for the actual formatting.
|
|
28
|
+
* @param locale - The locale code (e.g., 'en-IN') to use for formatting rules.
|
|
29
|
+
* @returns The formatted price string according to locale rules.
|
|
30
|
+
* @throws {Error} If the currency mapping for the instance's country is not found (via the static method).
|
|
31
|
+
*/
|
|
32
|
+
getFormattedString(locale: LocaleCode): string;
|
|
25
33
|
/**
|
|
26
34
|
* Gets a locale-aware formatted display string for the price.
|
|
27
35
|
* Uses Intl.NumberFormat for accurate formatting based on locale and currency.
|
|
28
|
-
* @param
|
|
36
|
+
* @param price - The initial price value.
|
|
37
|
+
* @param country - The country code used for rounding and determining the currency symbol.
|
|
38
|
+
* @param locale - The locale code (e.g., 'en-IN') to use for formatting rules.
|
|
29
39
|
* @param options - Configuration options for formatting.
|
|
30
40
|
* @param options.displayAsInteger - If true, the formatted string will show the price rounded to the nearest integer (no decimals). Defaults to false.
|
|
31
41
|
* @returns The formatted price string according to locale rules.
|
|
32
42
|
*/
|
|
33
|
-
getFormattedString(locale: LocaleCode, options?: {
|
|
43
|
+
static getFormattedString(price: number, country: CountryCode, locale: LocaleCode, options?: {
|
|
34
44
|
displayAsInteger?: boolean;
|
|
35
45
|
currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name';
|
|
36
46
|
}): string;
|
|
@@ -65,7 +75,6 @@ declare class PriceModel {
|
|
|
65
75
|
* @returns The currency code (e.g., 'INR') as a string, or undefined if the mapping doesn't exist.
|
|
66
76
|
*/
|
|
67
77
|
static getCurrency(country: CountryCode): string;
|
|
68
|
-
static getFormattedStringToDisplay(price: number, country: CountryCode, locale: LocaleCode): string;
|
|
69
78
|
}
|
|
70
79
|
|
|
71
80
|
export { PriceModel as default };
|
package/dist/Classes/Price.d.ts
CHANGED
|
@@ -22,15 +22,25 @@ declare class PriceModel {
|
|
|
22
22
|
* @returns The numeric price, rounded according to its currency's typical decimal places.
|
|
23
23
|
*/
|
|
24
24
|
getRoundedPrice(): number;
|
|
25
|
+
/**
|
|
26
|
+
* Gets a locale-aware formatted display string for the price stored in this instance.
|
|
27
|
+
* Uses the static `PriceModel.getFormattedString` method for the actual formatting.
|
|
28
|
+
* @param locale - The locale code (e.g., 'en-IN') to use for formatting rules.
|
|
29
|
+
* @returns The formatted price string according to locale rules.
|
|
30
|
+
* @throws {Error} If the currency mapping for the instance's country is not found (via the static method).
|
|
31
|
+
*/
|
|
32
|
+
getFormattedString(locale: LocaleCode): string;
|
|
25
33
|
/**
|
|
26
34
|
* Gets a locale-aware formatted display string for the price.
|
|
27
35
|
* Uses Intl.NumberFormat for accurate formatting based on locale and currency.
|
|
28
|
-
* @param
|
|
36
|
+
* @param price - The initial price value.
|
|
37
|
+
* @param country - The country code used for rounding and determining the currency symbol.
|
|
38
|
+
* @param locale - The locale code (e.g., 'en-IN') to use for formatting rules.
|
|
29
39
|
* @param options - Configuration options for formatting.
|
|
30
40
|
* @param options.displayAsInteger - If true, the formatted string will show the price rounded to the nearest integer (no decimals). Defaults to false.
|
|
31
41
|
* @returns The formatted price string according to locale rules.
|
|
32
42
|
*/
|
|
33
|
-
getFormattedString(locale: LocaleCode, options?: {
|
|
43
|
+
static getFormattedString(price: number, country: CountryCode, locale: LocaleCode, options?: {
|
|
34
44
|
displayAsInteger?: boolean;
|
|
35
45
|
currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name';
|
|
36
46
|
}): string;
|
|
@@ -65,7 +75,6 @@ declare class PriceModel {
|
|
|
65
75
|
* @returns The currency code (e.g., 'INR') as a string, or undefined if the mapping doesn't exist.
|
|
66
76
|
*/
|
|
67
77
|
static getCurrency(country: CountryCode): string;
|
|
68
|
-
static getFormattedStringToDisplay(price: number, country: CountryCode, locale: LocaleCode): string;
|
|
69
78
|
}
|
|
70
79
|
|
|
71
80
|
export { PriceModel as default };
|
package/dist/Classes/Price.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var a={IN:"INR"},m={INR:"\u20B9"};var d=class u{price;country;constructor(r,e){if(this.country=e,r<0)throw new Error("InvalidPrice: Price cannot be negative.");this.price=r;}getCountry(){return this.country}getRoundedPrice(){return u.getRoundedPrice(this.price,this.country)}getFormattedString(r){return u.getFormattedString(this.price,this.country,r)}static getFormattedString(r,e,t,o={}){let c=o.displayAsInteger??!1,n=a[e];if(n===void 0)throw new Error("Currency mapping not found for CountryCode");let i=r,s=c?0:u.getDecimalPlaces(n),l={style:"currency",currency:n,signDisplay:"never",currencyDisplay:o.currencyDisplay,minimumFractionDigits:s,maximumFractionDigits:s};c&&(i=Math.round(i));try{return new Intl.NumberFormat(t,l).format(i)}catch(y){return console.error(`Error formatting price for locale "${t}" and currency "${n}":`,y),`${m[n]??n} ${u.addThousandSeparators(i.toFixed(s))}`}}static getDecimalPlaces(r){switch(r){case"INR":default:return 2}}static addThousandSeparators(r){let e=r.split("."),t=e[0],o=e.length>1?"."+e[1]:"";return t.replace(/\B(?=(\d{3})+(?!\d))/g,",")+o}static getRoundedPrice(r,e){if(r<0)throw new Error("Price cannot be negative for rounding.");let t=a[e];if(t===void 0)throw new Error(`Currency mapping not found for CountryCode: ${e}`);let o=u.getDecimalPlaces(t),c=Math.pow(10,o);return Math.round(r*c)/c}static getCurrency(r){return a[r]}};module.exports=d;//# sourceMappingURL=Price.js.map
|
|
2
2
|
//# sourceMappingURL=Price.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/Classes/Enum.ts","../../src/Classes/Price.ts"],"names":["CountryCurrencyMap","CurrencySymbolMap","PriceModel","_PriceModel","price","country","locale","options","displayAsInteger","currency","valueToFormat","fractionDigits","formattingOptions","error","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier"],"mappings":"aAkBO,IAAMA,CAAqB,CAAA,CAClB,EAAwB,CAAA,KACxC,CAEaC,CAAAA,CAAAA,CAAoB,CAC9B,GAAA,CAAiC,QACpC,CAAA,CCrBqBC,IAAAA,CAAAA,CAArB,MAAqBC,CAAW,CACpB,KAAA,CACA,OAQV,CAAA,WAAA,CAAYC,CAAeC,CAAAA,CAAAA,CAAsB,CAG/C,GAFA,IAAK,CAAA,OAAA,CAAUA,CAEZD,CAAAA,CAAAA,CAAQ,CACT,CAAA,MAAM,IAAI,KAAM,CAAA,yCAAyC,CAG3D,CAAA,IAAA,CAAK,KAAQA,CAAAA,EACf,CAOO,UAAA,EAA0B,CAC/B,OAAO,IAAK,CAAA,OACd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\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}\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\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}","import { CountryCode, CurrencyCode, LocaleCode } from \"./Common\"; // Assuming these are in Common.ts\r\nimport { CountryCurrencyMap, CurrencySymbolMap } from \"./Enum\"; // Ensure these maps exist\r\n\r\nexport default class PriceModel {\r\n protected price: number;\r\n protected country: CountryCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param price - The initial price value.\r\n * @param country - The country 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(price: number, country: CountryCode) {\r\n this.country = country;\r\n\r\n if(price < 0) {\r\n throw new Error(\"InvalidPrice: Price cannot be negative.\");\r\n }\r\n\r\n this.price = price\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this price instance.\r\n * The country code is used for determining currency and formatting rules.\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 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 getRoundedPrice(): number {\r\n return PriceModel.getRoundedPrice(this.price, this.country);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param locale - The locale code (e.g., 'en-US', 'de-DE', 'en-IN') to use for formatting rules.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the price rounded to the nearest integer (no decimals). Defaults to false.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n public getFormattedString(locale: LocaleCode, options: { displayAsInteger?: boolean, currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name' } = {}): string {\r\n const displayAsInteger = options.displayAsInteger ?? false;\r\n const currency: CurrencyCode | undefined = CountryCurrencyMap[this.country];\r\n\r\n if (currency === undefined) {\r\n throw new Error('Currency mapping not found for CountryCode');\r\n }\r\n\r\n let valueToFormat = this.price;\r\n const fractionDigits = displayAsInteger ? 0 : PriceModel.getDecimalPlaces(currency);\r\n\r\n let formattingOptions: Intl.NumberFormatOptions = {\r\n 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 (displayAsInteger) {\r\n valueToFormat = Math.round(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 locale \"${locale}\" and currency \"${currency}\":`, 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 '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 country - The country code to determine the currency and rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the country code is not found in the CountryCurrencyMap or price is negative.\r\n */\r\n static getRoundedPrice(price: number, country: CountryCode): number {\r\n if (price < 0) {\r\n throw new Error(\"Price cannot be negative for rounding.\");\r\n }\r\n\r\n const currency: CurrencyCode | undefined = CountryCurrencyMap[country];\r\n if (currency === undefined) {\r\n throw new Error(`Currency mapping not found for CountryCode: ${country}`);\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(price * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n\r\n /**\r\n * Static method to retrieve the currency code associated with a given country code.\r\n * Uses the `CountryCurrencyMap` to find the corresponding currency.\r\n *\r\n * @param country - The country code (e.g., 'IN') for which to find the currency.\r\n * @returns The currency code (e.g., 'INR') as a string, or undefined if the mapping doesn't exist.\r\n */\r\n static getCurrency(country: CountryCode): string {\r\n return CountryCurrencyMap[country];\r\n }\r\n\r\n static getFormattedStringToDisplay(price: number, country: CountryCode, locale: LocaleCode){\r\n return new PriceModel(price, country).getFormattedString(locale);\r\n }\r\n\r\n}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/Classes/Enum.ts","../../src/Classes/Price.ts"],"names":["CountryCurrencyMap","CurrencySymbolMap","PriceModel","_PriceModel","price","country","locale","options","displayAsInteger","currency","valueToFormat","fractionDigits","formattingOptions","error","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier"],"mappings":"aAkBO,IAAMA,CAAqB,CAAA,CAClB,EAAwB,CAAA,KACxC,CAEaC,CAAAA,CAAAA,CAAoB,CAC9B,GAAA,CAAiC,QACpC,CAAA,CCrBqBC,IAAAA,CAAAA,CAArB,MAAqBC,CAAW,CACpB,KAAA,CACA,OAQV,CAAA,WAAA,CAAYC,CAAeC,CAAAA,CAAAA,CAAsB,CAG/C,GAFA,IAAK,CAAA,OAAA,CAAUA,CAEZD,CAAAA,CAAAA,CAAQ,CACT,CAAA,MAAM,IAAI,KAAM,CAAA,yCAAyC,CAG3D,CAAA,IAAA,CAAK,KAAQA,CAAAA,EACf,CAOO,UAAA,EAA0B,CAC/B,OAAO,IAAK,CAAA,OACd,CAMO,eAAA,EAA0B,CAC/B,OAAOD,EAAW,eAAgB,CAAA,IAAA,CAAK,KAAO,CAAA,IAAA,CAAK,OAAO,CAC5D,CASO,kBAAA,CAAmBG,CAAmB,CAAA,CAC3C,OAAOH,CAAAA,CAAW,kBAAmB,CAAA,IAAA,CAAK,KAAO,CAAA,IAAA,CAAK,QAASG,CAAM,CACvE,CAYA,OAAO,kBAAmBF,CAAAA,CAAAA,CAAeC,CAAsBC,CAAAA,CAAAA,CAAoBC,CAAyG,CAAA,EAAY,CAAA,CACtM,IAAMC,CAAAA,CAAmBD,CAAQ,CAAA,gBAAA,EAAoB,CAC/CE,CAAAA,CAAAA,CAAAA,CAAqCT,CAAmBK,CAAAA,CAAO,CAErE,CAAA,GAAII,CAAa,GAAA,KAAA,CAAA,CACf,MAAM,IAAI,KAAM,CAAA,4CAA4C,CAG9D,CAAA,IAAIC,CAAgBN,CAAAA,CAAAA,CACdO,EAAiBH,CAAmB,CAAA,CAAA,CAAIL,CAAW,CAAA,gBAAA,CAAiBM,CAAQ,CAAA,CA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CAAQ,CACV,CAAA,MAAM,IAAI,KAAA,CAAM,wCAAwC,CAAA,CAG1D,IAAMK,CAAAA,CAAqCT,CAAmBK,CAAAA,CAAO,CACrE,CAAA,GAAII,CAAa,GAAA,KAAA,CAAA,CACf,MAAM,IAAI,KAAA,CAAM,CAA+CJ,4CAAAA,EAAAA,CAAO,CAAE,CAAA,CAAA,CAG1E,IAAMa,CAAAA,CAAgBf,CAAW,CAAA,gBAAA,CAAiBM,CAAQ,CAAA,CACpDU,CAAa,CAAA,IAAA,CAAK,GAAI,CAAA,EAAA,CAAID,CAAa,CAG7C,CAAA,OAFqB,IAAK,CAAA,KAAA,CAAMd,CAAQe,CAAAA,CAAU,CAAIA,CAAAA,CAGxD,CASA,OAAO,WAAYd,CAAAA,CAAAA,CAA8B,CAC/C,OAAOL,CAAmBK,CAAAA,CAAO,CACnC,CAEF","file":"Price.js","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}\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\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}","import { CountryCode, CurrencyCode, LocaleCode } from \"./Common\"; // Assuming these are in Common.ts\r\nimport { CountryCurrencyMap, CurrencySymbolMap } from \"./Enum\"; // Ensure these maps exist\r\n\r\nexport default class PriceModel {\r\n protected price: number;\r\n protected country: CountryCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param price - The initial price value.\r\n * @param country - The country 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(price: number, country: CountryCode) {\r\n this.country = country;\r\n\r\n if(price < 0) {\r\n throw new Error(\"InvalidPrice: Price cannot be negative.\");\r\n }\r\n\r\n this.price = price\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this price instance.\r\n * The country code is used for determining currency and formatting rules.\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 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 getRoundedPrice(): number {\r\n return PriceModel.getRoundedPrice(this.price, this.country);\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 * @param locale - The locale code (e.g., 'en-IN') to use for formatting rules.\r\n * @returns The formatted price string according to locale rules.\r\n * @throws {Error} If the currency mapping for the instance's country is not found (via the static method).\r\n */\r\n public getFormattedString(locale: LocaleCode){\r\n return PriceModel.getFormattedString(this.price, this.country, locale);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param price - The initial price value.\r\n * @param country - The country code used for rounding and determining the currency symbol.\r\n * @param locale - The locale code (e.g., 'en-IN') to use for formatting rules.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the price rounded to the nearest integer (no decimals). Defaults to false.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n static getFormattedString(price: number, country: CountryCode, locale: LocaleCode, options: { displayAsInteger?: boolean, currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name' } = {}): string {\r\n const displayAsInteger = options.displayAsInteger ?? false;\r\n const currency: CurrencyCode | undefined = CountryCurrencyMap[country];\r\n\r\n if (currency === undefined) {\r\n throw new Error('Currency mapping not found for CountryCode');\r\n }\r\n\r\n let valueToFormat = price;\r\n const fractionDigits = displayAsInteger ? 0 : PriceModel.getDecimalPlaces(currency);\r\n\r\n let formattingOptions: Intl.NumberFormatOptions = {\r\n 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 (displayAsInteger) {\r\n valueToFormat = Math.round(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 locale \"${locale}\" and currency \"${currency}\":`, 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 '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 country - The country code to determine the currency and rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the country code is not found in the CountryCurrencyMap or price is negative.\r\n */\r\n static getRoundedPrice(price: number, country: CountryCode): number {\r\n if (price < 0) {\r\n throw new Error(\"Price cannot be negative for rounding.\");\r\n }\r\n\r\n const currency: CurrencyCode | undefined = CountryCurrencyMap[country];\r\n if (currency === undefined) {\r\n throw new Error(`Currency mapping not found for CountryCode: ${country}`);\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(price * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n\r\n /**\r\n * Static method to retrieve the currency code associated with a given country code.\r\n * Uses the `CountryCurrencyMap` to find the corresponding currency.\r\n *\r\n * @param country - The country code (e.g., 'IN') for which to find the currency.\r\n * @returns The currency code (e.g., 'INR') as a string, or undefined if the mapping doesn't exist.\r\n */\r\n static getCurrency(country: CountryCode): string {\r\n return CountryCurrencyMap[country];\r\n }\r\n\r\n}"]}
|
package/dist/Classes/Price.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as default}from'../chunk-
|
|
1
|
+
export{a as default}from'../chunk-GCT7VOSM.mjs';import'../chunk-65X54TKF.mjs';//# sourceMappingURL=Price.mjs.map
|
|
2
2
|
//# sourceMappingURL=Price.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var u=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){this.customFields={...t.customFields},this.version=t.version??1,this.createdAt=t.createdAt&&!isNaN(Date.parse(t.createdAt))?new Date(t.createdAt).toISOString():e.toISOString(),this.modifiedAt=t.modifiedAt&&!isNaN(Date.parse(t.modifiedAt))?new Date(t.modifiedAt).toISOString():e.toISOString(),this.modifiedBy={...t.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(t,e,i,r){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:r};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}};var l=class extends u{id;firstName;lastName;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(t,e=new Date){super(t,e),this.id=t.id,this.firstName=t.firstName,this.lastName=t.lastName||"",this.phone=t.phone,this.email=t.email,this.addressLine1=t.addressLine1,this.addressLine2=t.addressLine2||"",this.city=t.city,this.postalCode=t.postalCode,this.state=t.state,this.country=t.country,this.isBillingAddress=t.isBillingAddress,this.isShippingAddress=t.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),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}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(t){return t==="shipping"||t==="billing&shipping"}static checkIfBillingAddress(t){return t==="billing"||t==="billing&shipping"}};var d=class{sources;alt;order;label;constructor(t){if(this.sources={...t.sources},this.alt=t.alt,this.order=t.order,this.label=t.label,!this.sources.original)throw "ImageInfoModel cannot be created without an 'original' source URL."}getSources(){return {...this.sources}}getSource(t){return this.sources[t]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(t){this.alt=t;}setOrder(t){this.order=t;}setLabel(t){this.label=t;}setSource(t,e){if(e===void 0){if(t==="original")throw "Cannot remove the 'original' image source.";delete this.sources[t];}else this.sources[t]=e;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var p=class{id;productKey;variantId;name;attributes;primaryImage;subItems;totalQuantity;basePrice;priceTotals;priceTiers;constructor(t){this.id=t.id,this.productKey=t.productKey,this.variantId=t.variantId,this.name={...t.name},this.attributes={...t.attributes},this.primaryImage=new d(t.primaryImage),this.subItems=t.subItems.map(e=>({...e})),this.basePrice={...t.basePrice},this.priceTiers=t.priceTiers.map(e=>({...e})),this.totalQuantity=0,this.priceTotals={subtotal:0,mrpTotal:0},this.recalculateTotalQuantity(),this.recalculatePriceTotal();}getId(){return this.id}getProductKey(){return this.productKey}getVariantId(){return this.variantId}getName(t){return t?this.name[t]??this.name.en:{...this.name}}getAttributes(){return {...this.attributes}}getImage(){return this.primaryImage}getSubItems(){return this.subItems.map(t=>({...t}))}getTotalQuantity(){return this.totalQuantity}getBasePrice(){return {...this.basePrice}}getPriceTotals(){return {...this.priceTotals}}getPriceTiers(){return this.priceTiers.map(t=>({...t}))}recalculateTotalQuantity(){this.totalQuantity=this.subItems.reduce((t,e)=>t+e.quantity,0);}recalculatePriceTotal(){let t=this.totalQuantity,e=this.basePrice.unitPrice,i=null;for(let r of this.priceTiers.sort((s,a)=>a.minQuantity-s.minQuantity))if(t>=r.minQuantity){i=r;break}i&&(e=i.unitPrice),this.priceTotals.mrpTotal=this.basePrice.unitPrice*t,this.priceTotals.subtotal=e*t;}getDetails(){return {id:this.getId(),productKey:this.getProductKey(),variantId:this.getVariantId(),name:this.getName(),attributes:this.getAttributes(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),totalQuantity:this.getTotalQuantity(),basePrice:this.getBasePrice(),priceTotals:this.getPriceTotals(),priceTiers:this.getPriceTiers()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(s=>s.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity),this.recalculateTotalQuantity(),this.recalculatePriceTotal();}clearLineItem(){this.id="",this.productKey="",this.variantId="",this.name={en:""},this.attributes={color:{name:"",hex:""}},this.primaryImage=new d({sources:{original:""}}),this.subItems=[],this.recalculateTotalQuantity(),this.recalculatePriceTotal();}};var m={IN:"INR"},I={INR:"\u20B9"};var o=class n{price;country;constructor(t,e){if(this.country=e,t<0)throw new Error("InvalidPrice: Price cannot be negative.");this.price=t;}getCountry(){return this.country}getRoundedPrice(){return n.getRoundedPrice(this.price,this.country)}getFormattedString(t,e={}){let i=e.displayAsInteger??!1,r=m[this.country];if(r===void 0)throw new Error("Currency mapping not found for CountryCode");let s=this.price,a=i?0:n.getDecimalPlaces(r),h={style:"currency",currency:r,signDisplay:"never",currencyDisplay:e.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};i&&(s=Math.round(s));try{return new Intl.NumberFormat(t,h).format(s)}catch(y){return console.error(`Error formatting price for locale "${t}" and currency "${r}":`,y),`${I[r]??r} ${n.addThousandSeparators(s.toFixed(a))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),i=e[0],r=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+r}static getRoundedPrice(t,e){if(t<0)throw new Error("Price cannot be negative for rounding.");let i=m[e];if(i===void 0)throw new Error(`Currency mapping not found for CountryCode: ${e}`);let r=n.getDecimalPlaces(i),s=Math.pow(10,r);return Math.round(t*s)/s}static getCurrency(t){return m[t]}static getFormattedStringToDisplay(t,e,i){return new n(t,e).getFormattedString(i)}};var g=class extends u{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(t,e=new Date){super(t,e),this.couponCode=t.couponCode,this.name={...t.name},this.description={...t.description},this.type=t.type,this.customerId=t.customerId,this.validFrom=t.validFrom&&Date.parse(t.validFrom)?new Date(t.validFrom).toISOString():e.toISOString(),this.validTo=t.validTo&&Date.parse(t.validTo)?new Date(t.validTo).toISOString():e.toISOString(),this.minCartValue=t.minCartValue.map(i=>({...i})),this.maxCartDiscount=t.maxCartDiscount.map(i=>({...i})),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.applicableTo=t.applicableTo,this.category=t.category;}getCode(){return this.couponCode}getName(t){return t?this.name[t]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(t){return t?this.minCartValue.find(e=>e.country===t):this.minCartValue}getMaxCartDiscount(t){return t?this.maxCartDiscount.find(e=>e.country===t):this.maxCartDiscount}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:this.getMinCartValue(),maxCartDiscount:this.getMaxCartDiscount(),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(t){return this.applicableTo==="all"||this.applicableTo==="ftb"&&t}};var b=class extends u{id;customerId;customerEmail;anonymousId;lineItems;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,e=new Date){super(t,e),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(i=>new p(i)),this.billingAddress=t.billingAddress?new l(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new l(t.shippingAddress,e):null,this.coupons=(t.coupons||[]).map(i=>new g(i)),this.shippingDetails=t.shippingDetails?{...t.shippingDetails}:null,this.total={shipping:t.total?.shipping||0,effectiveShipping:t.total?.effectiveShipping||t.total?.shipping||0,subtotal:0,mrpTotal:0,couponTotal:t.total?.couponTotal||{},grandTotal:t.total?.grandTotal||0},this.recalculateBaseTotals();}recalculateBaseTotals(){this.total.subtotal=o.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=o.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().mrpTotal,0),this.country);}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new p(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new l(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new l(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons.map(t=>new g(t.getDetails()))}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {...this.total,couponTotal:{...this.total.couponTotal}}}calculateApplicableCouponDiscount(t){if(!t.isActive())return 0;let e=t.getMinCartValue(this.country),i=t.getMaxCartDiscount(this.country);if(!e||this.total.subtotal<e.price||!i||i.price<0)return 0;let r=t.getCategory(),s=t.getDiscountMethod(),a=0,h=r==="SHIPPING"?this.total.shipping:this.total.subtotal;if(h<=0)return 0;switch(s){case"flat":let C=i?.price??0;a=Math.min(h,C);break;case"percentage":a=h*(t.getPercentageValue()/100);break;default:return 0}let y=Math.min(a,i.price);return o.getRoundedPrice(Math.max(0,y),this.country)}recalculateCouponTotals(){this.total.couponTotal={};let t=0;return this.coupons.forEach(e=>{let i=this.calculateApplicableCouponDiscount(e);i>0&&(this.total.couponTotal[e.getCode()]=i,t+=i);}),o.getRoundedPrice(t,this.country)}updateCartTotals(){this.total.subtotal=o.getRoundedPrice(this.lineItems.reduce((r,s)=>r+s.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=o.getRoundedPrice(this.lineItems.reduce((r,s)=>r+s.getPriceTotals().mrpTotal,0),this.country),this.recalculateCouponTotals();let t=this.coupons.filter(r=>r.getCategory()==="SHIPPING").reduce((r,s)=>r+(this.total.couponTotal[s.getCode()]??0),0);this.total.effectiveShipping=o.getRoundedPrice(Math.max(0,this.total.shipping-t),this.country);let e=this.coupons.filter(r=>r.getCategory()!=="SHIPPING").reduce((r,s)=>r+(this.total.couponTotal[s.getCode()]??0),0),i=this.total.subtotal+this.total.effectiveShipping;this.total.grandTotal=o.getRoundedPrice(Math.max(0,i-e),this.country);}setShippingDetails(t){this.shippingDetails=t?{...t}:null,this.total.shipping=o.getRoundedPrice(this.shippingDetails?.estimatedCost??0,this.country),this.updateCartTotals();}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:this.getTotal(),country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}};module.exports=b;//# sourceMappingURL=ShoppingContainer.js.map
|
|
1
|
+
'use strict';var u=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){this.customFields={...t.customFields},this.version=t.version??1,this.createdAt=t.createdAt&&!isNaN(Date.parse(t.createdAt))?new Date(t.createdAt).toISOString():e.toISOString(),this.modifiedAt=t.modifiedAt&&!isNaN(Date.parse(t.modifiedAt))?new Date(t.modifiedAt).toISOString():e.toISOString(),this.modifiedBy={...t.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(t,e,i,r){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:r};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}};var c=class extends u{id;firstName;lastName;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(t,e=new Date){super(t,e),this.id=t.id,this.firstName=t.firstName,this.lastName=t.lastName||"",this.phone=t.phone,this.email=t.email,this.addressLine1=t.addressLine1,this.addressLine2=t.addressLine2||"",this.city=t.city,this.postalCode=t.postalCode,this.state=t.state,this.country=t.country,this.isBillingAddress=t.isBillingAddress,this.isShippingAddress=t.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),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}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(t){return t==="shipping"||t==="billing&shipping"}static checkIfBillingAddress(t){return t==="billing"||t==="billing&shipping"}};var p=class{sources;alt;order;label;constructor(t){if(this.sources={...t.sources},this.alt=t.alt,this.order=t.order,this.label=t.label,!this.sources.original)throw "ImageInfoModel cannot be created without an 'original' source URL."}getSources(){return {...this.sources}}getSource(t){return this.sources[t]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(t){this.alt=t;}setOrder(t){this.order=t;}setLabel(t){this.label=t;}setSource(t,e){if(e===void 0){if(t==="original")throw "Cannot remove the 'original' image source.";delete this.sources[t];}else this.sources[t]=e;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var g=class{id;productKey;variantId;name;attributes;primaryImage;subItems;totalQuantity;basePrice;priceTotals;priceTiers;constructor(t){this.id=t.id,this.productKey=t.productKey,this.variantId=t.variantId,this.name={...t.name},this.attributes={...t.attributes},this.primaryImage=new p(t.primaryImage),this.subItems=t.subItems.map(e=>({...e})),this.basePrice={...t.basePrice},this.priceTiers=t.priceTiers.map(e=>({...e})),this.totalQuantity=0,this.priceTotals={subtotal:0,mrpTotal:0},this.recalculateTotalQuantity(),this.recalculatePriceTotal();}getId(){return this.id}getProductKey(){return this.productKey}getVariantId(){return this.variantId}getName(t){return t?this.name[t]??this.name.en:{...this.name}}getAttributes(){return {...this.attributes}}getImage(){return this.primaryImage}getSubItems(){return this.subItems.map(t=>({...t}))}getTotalQuantity(){return this.totalQuantity}getBasePrice(){return {...this.basePrice}}getPriceTotals(){return {...this.priceTotals}}getPriceTiers(){return this.priceTiers.map(t=>({...t}))}recalculateTotalQuantity(){this.totalQuantity=this.subItems.reduce((t,e)=>t+e.quantity,0);}recalculatePriceTotal(){let t=this.totalQuantity,e=this.basePrice.unitPrice,i=null;for(let r of this.priceTiers.sort((s,o)=>o.minQuantity-s.minQuantity))if(t>=r.minQuantity){i=r;break}i&&(e=i.unitPrice),this.priceTotals.mrpTotal=this.basePrice.unitPrice*t,this.priceTotals.subtotal=e*t;}getDetails(){return {id:this.getId(),productKey:this.getProductKey(),variantId:this.getVariantId(),name:this.getName(),attributes:this.getAttributes(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),totalQuantity:this.getTotalQuantity(),basePrice:this.getBasePrice(),priceTotals:this.getPriceTotals(),priceTiers:this.getPriceTiers()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(s=>s.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity),this.recalculateTotalQuantity(),this.recalculatePriceTotal();}clearLineItem(){this.id="",this.productKey="",this.variantId="",this.name={en:""},this.attributes={color:{name:"",hex:""}},this.primaryImage=new p({sources:{original:""}}),this.subItems=[],this.recalculateTotalQuantity(),this.recalculatePriceTotal();}};var y={IN:"INR"},C={INR:"\u20B9"};var n=class a{price;country;constructor(t,e){if(this.country=e,t<0)throw new Error("InvalidPrice: Price cannot be negative.");this.price=t;}getCountry(){return this.country}getRoundedPrice(){return a.getRoundedPrice(this.price,this.country)}getFormattedString(t){return a.getFormattedString(this.price,this.country,t)}static getFormattedString(t,e,i,r={}){let s=r.displayAsInteger??!1,o=y[e];if(o===void 0)throw new Error("Currency mapping not found for CountryCode");let l=t,m=s?0:a.getDecimalPlaces(o),b={style:"currency",currency:o,signDisplay:"never",currencyDisplay:r.currencyDisplay,minimumFractionDigits:m,maximumFractionDigits:m};s&&(l=Math.round(l));try{return new Intl.NumberFormat(i,b).format(l)}catch(A){return console.error(`Error formatting price for locale "${i}" and currency "${o}":`,A),`${C[o]??o} ${a.addThousandSeparators(l.toFixed(m))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),i=e[0],r=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+r}static getRoundedPrice(t,e){if(t<0)throw new Error("Price cannot be negative for rounding.");let i=y[e];if(i===void 0)throw new Error(`Currency mapping not found for CountryCode: ${e}`);let r=a.getDecimalPlaces(i),s=Math.pow(10,r);return Math.round(t*s)/s}static getCurrency(t){return y[t]}};var h=class extends u{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(t,e=new Date){super(t,e),this.couponCode=t.couponCode,this.name={...t.name},this.description={...t.description},this.type=t.type,this.customerId=t.customerId,this.validFrom=t.validFrom&&Date.parse(t.validFrom)?new Date(t.validFrom).toISOString():e.toISOString(),this.validTo=t.validTo&&Date.parse(t.validTo)?new Date(t.validTo).toISOString():e.toISOString(),this.minCartValue=t.minCartValue.map(i=>({...i})),this.maxCartDiscount=t.maxCartDiscount.map(i=>({...i})),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.applicableTo=t.applicableTo,this.category=t.category;}getCode(){return this.couponCode}getName(t){return t?this.name[t]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(t){return t?this.minCartValue.find(e=>e.country===t):this.minCartValue}getMaxCartDiscount(t){return t?this.maxCartDiscount.find(e=>e.country===t):this.maxCartDiscount}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:this.getMinCartValue(),maxCartDiscount:this.getMaxCartDiscount(),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(t){return this.applicableTo==="all"||this.applicableTo==="ftb"&&t}};var I=class extends u{id;customerId;customerEmail;anonymousId;lineItems;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,e=new Date){super(t,e),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(i=>new g(i)),this.billingAddress=t.billingAddress?new c(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new c(t.shippingAddress,e):null,this.coupons=(t.coupons||[]).map(i=>new h(i)),this.shippingDetails=t.shippingDetails?{...t.shippingDetails}:null,this.total={shipping:t.total?.shipping||0,effectiveShipping:t.total?.effectiveShipping||t.total?.shipping||0,subtotal:0,mrpTotal:0,couponTotal:t.total?.couponTotal||{},grandTotal:t.total?.grandTotal||0},this.recalculateBaseTotals();}recalculateBaseTotals(){this.total.subtotal=n.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=n.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().mrpTotal,0),this.country);}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new g(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new c(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new c(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons.map(t=>new h(t.getDetails()))}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {...this.total,couponTotal:{...this.total.couponTotal}}}calculateApplicableCouponDiscount(t){if(!t.isActive())return 0;let e=t.getMinCartValue(this.country),i=t.getMaxCartDiscount(this.country);if(!e||this.total.subtotal<e.price||!i||i.price<0)return 0;let r=t.getCategory(),s=t.getDiscountMethod(),o=0,l=r==="SHIPPING"?this.total.shipping:this.total.subtotal;if(l<=0)return 0;switch(s){case"flat":let b=i?.price??0;o=Math.min(l,b);break;case"percentage":o=l*(t.getPercentageValue()/100);break;default:return 0}let m=Math.min(o,i.price);return n.getRoundedPrice(Math.max(0,m),this.country)}recalculateCouponTotals(){this.total.couponTotal={};let t=0;return this.coupons.forEach(e=>{let i=this.calculateApplicableCouponDiscount(e);i>0&&(this.total.couponTotal[e.getCode()]=i,t+=i);}),n.getRoundedPrice(t,this.country)}updateCartTotals(){this.total.subtotal=n.getRoundedPrice(this.lineItems.reduce((r,s)=>r+s.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=n.getRoundedPrice(this.lineItems.reduce((r,s)=>r+s.getPriceTotals().mrpTotal,0),this.country),this.recalculateCouponTotals();let t=this.coupons.filter(r=>r.getCategory()==="SHIPPING").reduce((r,s)=>r+(this.total.couponTotal[s.getCode()]??0),0);this.total.effectiveShipping=n.getRoundedPrice(Math.max(0,this.total.shipping-t),this.country);let e=this.coupons.filter(r=>r.getCategory()!=="SHIPPING").reduce((r,s)=>r+(this.total.couponTotal[s.getCode()]??0),0),i=this.total.subtotal+this.total.effectiveShipping;this.total.grandTotal=n.getRoundedPrice(Math.max(0,i-e),this.country);}setShippingDetails(t){this.shippingDetails=t?{...t}:null,this.total.shipping=n.getRoundedPrice(this.shippingDetails?.estimatedCost??0,this.country),this.updateCartTotals();}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:this.getTotal(),country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}};module.exports=I;//# sourceMappingURL=ShoppingContainer.js.map
|
|
2
2
|
//# sourceMappingURL=ShoppingContainer.js.map
|