b23-lib 3.1.2 → 3.1.4
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 +1 -1
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Charge.d.mts +2 -0
- package/dist/Classes/Charge.d.ts +2 -0
- package/dist/Classes/Charge.js +1 -1
- package/dist/Classes/Charge.js.map +1 -1
- package/dist/Classes/Charge.mjs +1 -1
- package/dist/Classes/Coupon.js +1 -1
- package/dist/Classes/Coupon.js.map +1 -1
- package/dist/Classes/Coupon.mjs +1 -1
- package/dist/Classes/Error.d.mts +4 -1
- package/dist/Classes/Error.d.ts +4 -1
- package/dist/Classes/Error.js +1 -1
- package/dist/Classes/Error.js.map +1 -1
- package/dist/Classes/Error.mjs +1 -1
- package/dist/Classes/ImageInfo.js.map +1 -1
- package/dist/Classes/ImageInfo.mjs +1 -1
- package/dist/Classes/Inventory.js +1 -1
- package/dist/Classes/Inventory.js.map +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/LineItem.d.mts +14 -7
- package/dist/Classes/LineItem.d.ts +14 -7
- package/dist/Classes/LineItem.js +1 -1
- package/dist/Classes/LineItem.js.map +1 -1
- package/dist/Classes/LineItem.mjs +1 -1
- package/dist/Classes/Order.js +1 -1
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/Price.js.map +1 -1
- package/dist/Classes/Price.mjs +1 -1
- package/dist/Classes/Product.js.map +1 -1
- package/dist/Classes/Product.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/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-WUIJ47N2.mjs → chunk-2B2XI6FG.mjs} +2 -2
- package/dist/{chunk-WUIJ47N2.mjs.map → chunk-2B2XI6FG.mjs.map} +1 -1
- package/dist/{chunk-D6USZIYC.mjs → chunk-6BROF5JI.mjs} +2 -2
- package/dist/{chunk-D6USZIYC.mjs.map → chunk-6BROF5JI.mjs.map} +1 -1
- package/dist/chunk-DYBLLXII.mjs +2 -0
- package/dist/chunk-DYBLLXII.mjs.map +1 -0
- package/dist/{chunk-JZC4DEOP.mjs → chunk-FCRJAAPY.mjs} +2 -2
- package/dist/{chunk-JZC4DEOP.mjs.map → chunk-FCRJAAPY.mjs.map} +1 -1
- package/dist/{chunk-3UMWQ7S7.mjs → chunk-LI5JQ6UC.mjs} +2 -2
- package/dist/{chunk-3UMWQ7S7.mjs.map → chunk-LI5JQ6UC.mjs.map} +1 -1
- package/dist/chunk-PWWKQNF7.mjs +2 -0
- package/dist/{chunk-TVTIUN4Z.mjs.map → chunk-PWWKQNF7.mjs.map} +1 -1
- package/dist/chunk-QGIQ3MH6.mjs +2 -0
- package/dist/{chunk-2TK2CILF.mjs.map → chunk-QGIQ3MH6.mjs.map} +1 -1
- package/dist/chunk-R5DM7WCD.mjs +2 -0
- package/dist/chunk-R5DM7WCD.mjs.map +1 -0
- package/dist/chunk-WTA42ELE.mjs +2 -0
- package/dist/chunk-WTA42ELE.mjs.map +1 -0
- package/dist/{chunk-SB2JSWLD.mjs → chunk-X27KEKNB.mjs} +2 -2
- package/dist/{chunk-SB2JSWLD.mjs.map → chunk-X27KEKNB.mjs.map} +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-2TK2CILF.mjs +0 -2
- package/dist/chunk-3E2NHQJJ.mjs +0 -2
- package/dist/chunk-3E2NHQJJ.mjs.map +0 -1
- package/dist/chunk-SJRXYUH2.mjs +0 -2
- package/dist/chunk-SJRXYUH2.mjs.map +0 -1
- package/dist/chunk-TVTIUN4Z.mjs +0 -2
- package/dist/chunk-ZFMHX4TM.mjs +0 -2
- package/dist/chunk-ZFMHX4TM.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/ShoppingContainer.ts"],"names":["BaseShoppingContainerModel","BaseModel","data","date","item","LineItemModel","charge","ChargeModel","AddressModel","coupon","CouponModel","Utils_default","PriceModel","key","value","breakdown","systemKey","systemValue","subKey","subValue","totals","zero","filteredLineItems","lineitem","lineItemSubtotal","total","lineItem","shippingCharges","discountTotal","discountBreakdown","nonShippingCouponTotal","couponValue","shippingCoupon","netLineItemSubtotal","netShippingCharges","additiveCharges","netAdditiveCharges","adjustmentCharges","taxTotal","lineItemTaxTotal","additiveChargesTaxTotal","taxBreakdown","lineItemTaxBreakdown","additiveChargesTaxBreakdown","mergeTax","sourceBreakdown","targetBreakdown","ruleId","system","subsystem","lineItemTaxes","chargeTaxes","grandTotal","shippingDetails","applicableCoupons","shippingCoupons","otherCoupons","couponTotal","couponDiscounts","couponDiscount","itemDiscounts","li","code","c","validItems","a","b","distributed","index","amount","chargeDiscounts","validCharges","coupons","maxValuedCoupon","maxCoupon","currentCoupon","currentCouponValue","maxCouponValue"],"mappings":"+RAkIA,IAA8BA,CAA9B,CAAA,cAAiEC,CAAU,CAC/D,EACA,CAAA,UAAA,CACA,aACA,CAAA,WAAA,CACA,SACA,CAAA,OAAA,CACA,eACA,CAAA,eAAA,CACA,cAGA,CAAA,OAAA,CAGA,KAEA,CAAA,OAAA,CACA,QACA,CAAA,MAAA,CAQV,WAAYC,CAAAA,CAAAA,CAAuCC,GAAa,CAAA,IAAI,IAAQ,CAAA,CAC1E,KAAMD,CAAAA,CAAAA,CAAMC,GAAI,CAAA,CAChB,IAAK,CAAA,EAAA,CAAKD,CAAK,CAAA,EAAA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,CAAA,KAAA,CAAM,aAAc,CAAA,GAAA,CAAI1C,CAAW,CAAA,CACnE,IAAK,CAAA,KAAA,CAAM,iBAAkB0C,CAAAA,CAAAA,CAAgB,OAAQ,EAAC,CAAI1C,CAAAA,CAAAA,EAE9D,CACF,CACF","file":"chunk-D6USZIYC.mjs","sourcesContent":["import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport AddressModel, { AddressData } from \"./Address\";\r\nimport LineItemModel, { LineItemData, LineItemTaxBreakdown, LineItemTaxBreakdownModel } 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 { ChargeImpact, ChargeType, LineItemState, TaxSystem } from \"./Enum\";\r\nimport ChargeModel, { ChargeData, ChargeTaxBreakdownModel } from \"./Charge\";\r\n\r\n/**\r\n * Breakdown of a specific tax system (e.g., GST, VAT) for the entire container.\r\n * Groups taxes by system and then by specific rule/subsystem.\r\n */\r\nexport type TaxSystemBreakdown = {\r\n /** Name of the tax system (e.g., GST) */\r\n system: TaxSystem;\r\n /** Total tax amount collected for this system across all line items and charges */\r\n totalAmount: PriceData;\r\n /** Detailed breakdown by rule/subsystem to total tax amount (e.g., CGST, SGST) */\r\n subSystems: Record<string, PriceData>;\r\n};\r\n\r\n/**\r\n * Internal model for tax system breakdown using PriceModel instances.\r\n */\r\nexport type TaxSystemBreakdownModel = {\r\n system: TaxSystem;\r\n totalAmount: PriceModel;\r\n subSystems: Record<string, PriceModel>;\r\n};\r\n\r\nexport type ShoppingContainerTaxBreakdownModel = Record<string, TaxSystemBreakdownModel>;\r\n\r\n/**\r\n * Comprehensive totals for a shopping container, logically grouped by source.\r\n */\r\nexport type ShoppingContainerTotal = {\r\n // --- Item Totals ---\r\n /** Sum of all line item prices before any discounts or taxes */\r\n lineItemSubtotal: PriceData;\r\n /** Total item subtotal after item-level discounts have been applied (taxable base for items) */\r\n netLineItemSubtotal: PriceData;\r\n /** Total tax collected specifically from line items */\r\n lineItemTaxTotal: PriceData;\r\n /** Granular tax breakdown for all line items */\r\n lineItemTaxBreakdown: Record<string, TaxSystemBreakdown>;\r\n\r\n // --- Charge Totals ---\r\n /** Sum of pre-discount chargeAmount for additive charges (tax-inclusive) */\r\n additiveCharges: PriceData;\r\n /** Sum of post-discount netChargeAmount for additive charges – final payable (tax-inclusive) */\r\n netAdditiveCharges: PriceData;\r\n /** Tax reverse-calculated from additive charges only */\r\n additiveChargesTaxTotal: PriceData;\r\n /** Granular tax breakdown from additive charges */\r\n additiveChargesTaxBreakdown: Record<string, TaxSystemBreakdown>;\r\n\r\n /** Sum of post-discount netChargeAmount for subtractive charges – absolute amount to subtract */\r\n adjustmentCharges: PriceData;\r\n\r\n /** Pre-discount shipping gross (tax-inclusive, part of additive charges) */\r\n shippingCharges: PriceData;\r\n /** Shipping cost after any shipping-specific discounts */\r\n netShippingCharges: PriceData;\r\n\r\n // --- Aggregate Totals ---\r\n /** Combined total tax (lineItemTaxTotal + chargeTaxTotal) */\r\n taxTotal: PriceData;\r\n /** Combined granular tax breakdown for the entire container */\r\n taxBreakdown: Record<string, TaxSystemBreakdown>;\r\n /** Sum of all coupon discounts applied to the container */\r\n discountTotal: PriceData;\r\n /** Map of applied coupon codes to their calculated discount amounts */\r\n discountBreakdown: Record<string, PriceData>;\r\n /** Final total amount to be paid (NetSubtotal + ChargesTotal + TaxTotal - (any remaining discounts)) */\r\n grandTotal: PriceData;\r\n};\r\n\r\n/**\r\n * Internal model version of ShoppingContainerTotal using PriceModel instances.\r\n */\r\nexport type ShoppingContainerTotalModel = {\r\n lineItemSubtotal: PriceModel;\r\n netLineItemSubtotal: PriceModel;\r\n lineItemTaxTotal: PriceModel;\r\n lineItemTaxBreakdown: Record<string, TaxSystemBreakdownModel>;\r\n\r\n additiveCharges: PriceModel;\r\n netAdditiveCharges: PriceModel;\r\n additiveChargesTaxTotal: PriceModel;\r\n additiveChargesTaxBreakdown: Record<string, TaxSystemBreakdownModel>;\r\n\r\n adjustmentCharges: PriceModel;\r\n\r\n shippingCharges: PriceModel;\r\n netShippingCharges: PriceModel;\r\n\r\n taxTotal: PriceModel;\r\n taxBreakdown: Record<string, TaxSystemBreakdownModel>;\r\n discountTotal: PriceModel;\r\n discountBreakdown: Record<string, PriceModel>;\r\n grandTotal: PriceModel;\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 charges: ChargeData[];\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 charges: ChargeModel[];\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: ShoppingContainerTotalModel;\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.charges = (data.charges ?? []).map(charge => new ChargeModel(charge));\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 lineItemSubtotal: new PriceModel(data.total.lineItemSubtotal),\r\n netLineItemSubtotal: new PriceModel(data.total.netLineItemSubtotal),\r\n lineItemTaxTotal: new PriceModel(data.total.lineItemTaxTotal),\r\n lineItemTaxBreakdown: this.mapTaxBreakdown(data.total.lineItemTaxBreakdown),\r\n\r\n additiveCharges: new PriceModel(data.total.additiveCharges),\r\n netAdditiveCharges: new PriceModel(data.total.netAdditiveCharges),\r\n additiveChargesTaxTotal: new PriceModel(data.total.additiveChargesTaxTotal),\r\n\r\n additiveChargesTaxBreakdown: this.mapTaxBreakdown(data.total.additiveChargesTaxBreakdown),\r\n adjustmentCharges: new PriceModel(data.total.adjustmentCharges),\r\n shippingCharges: new PriceModel(data.total.shippingCharges),\r\n netShippingCharges: new PriceModel(data.total.netShippingCharges),\r\n\r\n discountTotal: new PriceModel(data.total.discountTotal),\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(data.total.discountBreakdown).map(([key, value]) => [key, new PriceModel(value)])\r\n ),\r\n\r\n taxTotal: new PriceModel(data.total.taxTotal),\r\n taxBreakdown: this.mapTaxBreakdown(data.total.taxBreakdown),\r\n grandTotal: new PriceModel(data.total.grandTotal),\r\n };\r\n }\r\n\r\n private mapTaxBreakdown(breakdown: Record<string, TaxSystemBreakdown>): Record<string, TaxSystemBreakdownModel> {\r\n return Object.fromEntries(\r\n Object.entries(breakdown || {}).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: new PriceModel(systemValue.totalAmount),\r\n subSystems: Object.fromEntries(\r\n Object.entries(systemValue.subSystems).map(([subKey, subValue]) => [\r\n subKey,\r\n new PriceModel(subValue)\r\n ])\r\n )\r\n }\r\n ])\r\n );\r\n }\r\n\r\n private serializeTaxBreakdown(breakdown: Record<string, TaxSystemBreakdownModel>): Record<string, TaxSystemBreakdown> {\r\n return Object.fromEntries(\r\n Object.entries(breakdown || {}).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount.getDetails(),\r\n subSystems: Object.fromEntries(\r\n Object.entries(systemValue.subSystems).map(([subKey, subValue]) => [\r\n subKey,\r\n subValue.getDetails()\r\n ])\r\n )\r\n }\r\n ])\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 defensive copy of the charges in the container.\r\n * @returns An array of ChargeModel instances.\r\n */\r\n public getCharges(): ChargeModel[] {\r\n return this.charges.map(charge => new ChargeModel(charge.getDetails()));\r\n }\r\n\r\n /**\r\n * Adds a new charge to the container and recalculates totals.\r\n * @param charge - The charge to add.\r\n */\r\n public addCharge(charge: ChargeModel): void {\r\n this.charges.push(charge);\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Clears all charges from the container and recalculates totals.\r\n */\r\n public clearCharges(): void {\r\n this.charges = [];\r\n this.calculateTotals();\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 this.shippingDetails ? Utils.deepClone(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 {\r\n lineItemSubtotal: this.total.lineItemSubtotal,\r\n netLineItemSubtotal: this.total.netLineItemSubtotal,\r\n lineItemTaxTotal: this.total.lineItemTaxTotal,\r\n lineItemTaxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.lineItemTaxBreakdown).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount,\r\n subSystems: { ...systemValue.subSystems }\r\n }\r\n ])\r\n ),\r\n additiveCharges: this.total.additiveCharges,\r\n netAdditiveCharges : this.total.netAdditiveCharges,\r\n additiveChargesTaxTotal: this.total.additiveChargesTaxTotal,\r\n additiveChargesTaxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.additiveChargesTaxBreakdown).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount,\r\n subSystems: { ...systemValue.subSystems }\r\n }\r\n ])\r\n ),\r\n adjustmentCharges: this.total.adjustmentCharges,\r\n shippingCharges: this.total.shippingCharges,\r\n netShippingCharges: this.total.netShippingCharges,\r\n discountBreakdown: { ...this.total.discountBreakdown },\r\n discountTotal: this.total.discountTotal,\r\n taxTotal: this.total.taxTotal,\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.taxBreakdown).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount,\r\n subSystems: { ...systemValue.subSystems }\r\n }\r\n ])\r\n ),\r\n grandTotal: this.total.grandTotal,\r\n };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the 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 const totals = this.getTotal();\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 charges: this.getCharges().map(charge => charge.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 // Item Totals\r\n lineItemSubtotal: totals.lineItemSubtotal.getDetails(),\r\n netLineItemSubtotal: totals.netLineItemSubtotal.getDetails(),\r\n lineItemTaxTotal: totals.lineItemTaxTotal.getDetails(),\r\n lineItemTaxBreakdown: this.serializeTaxBreakdown(totals.lineItemTaxBreakdown),\r\n\r\n // Charge Totals\r\n additiveCharges: totals.additiveCharges.getDetails(),\r\n netAdditiveCharges: totals.netAdditiveCharges.getDetails(),\r\n additiveChargesTaxTotal: totals.additiveChargesTaxTotal.getDetails(),\r\n additiveChargesTaxBreakdown: this.serializeTaxBreakdown(totals.additiveChargesTaxBreakdown),\r\n\r\n adjustmentCharges: totals.adjustmentCharges.getDetails(),\r\n\r\n shippingCharges: totals.shippingCharges.getDetails(),\r\n netShippingCharges: totals.netShippingCharges.getDetails(),\r\n\r\n // Aggregate Totals\r\n discountTotal: totals.discountTotal.getDetails(),\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(totals.discountBreakdown).map(([key, value]) => [key, value.getDetails()])\r\n ),\r\n taxTotal: totals.taxTotal.getDetails(),\r\n taxBreakdown: this.serializeTaxBreakdown(totals.taxBreakdown),\r\n grandTotal: totals.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 \r\n // 1. Calculate LineItem subtotals and Shipping Cost\r\n const filteredLineItems = this.lineItems.filter(lineitem => lineitem.getState() !== LineItemState.CANCELLED);\r\n const lineItemSubtotal = filteredLineItems.reduce((total, lineItem) => total.add(lineItem.getTotal().subtotal), zero);\r\n const shippingCharges = this.charges\r\n .filter(charge => charge.getType() === ChargeType.SHIPPING)\r\n .reduce((total, charge) => total.add(charge.getTotal().chargeAmount), zero);\r\n\r\n // 1.1 Assign lineitemSubTotal and shipping charges to total, which will be used for coupon calculations\r\n this.total.lineItemSubtotal = lineItemSubtotal;\r\n this.total.shippingCharges = shippingCharges;\r\n\r\n // 2. Calculate coupon values based on gross subtotal & shipping\r\n let discountTotal = zero;\r\n let discountBreakdown: Record<string, PriceModel> = {};\r\n let nonShippingCouponTotal: Record<string, PriceModel> = {};\r\n this.coupons.forEach(coupon => {\r\n const couponValue = coupon.calculateApplicableCouponDiscount(lineItemSubtotal, shippingCharges, this.country, this.currency);\r\n discountTotal = discountTotal.add(couponValue);\r\n discountBreakdown[coupon.getCode()] = couponValue;\r\n if (coupon.getCategory() !== CouponCategory.SHIPPING) {\r\n nonShippingCouponTotal[coupon.getCode()] = couponValue;\r\n }\r\n })\r\n\r\n // 2.1. Assign discount total and breakdown to total\r\n this.total.discountTotal = discountTotal;\r\n this.total.discountBreakdown = discountBreakdown;\r\n\r\n // 3. Apply discounts at lineitem and shipping charges\r\n this.applyDiscountsInLineItem(nonShippingCouponTotal);\r\n\r\n const shippingCoupon = this.coupons.find(coupon => coupon.getCategory() === CouponCategory.SHIPPING);\r\n if(shippingCoupon) {\r\n this.applyDiscountsInShippingCharges({[shippingCoupon.getCode()] : discountBreakdown[shippingCoupon.getCode()] || zero});\r\n } else {\r\n // If no shipping coupon, ensure any previous discounts on shipping charges are cleared\r\n this.applyDiscountsInShippingCharges({});\r\n }\r\n\r\n // 3.1 Calculate net lineitemSubtotal and net shipping after discount\r\n const netLineItemSubtotal = this.lineItems.reduce((total, lineItem) => total.add(lineItem.getTotal().netSubtotal), zero);\r\n const netShippingCharges = this.charges\r\n .filter(charge => charge.getType() === ChargeType.SHIPPING)\r\n .reduce((total, charge) => total.add(charge.getTotal().grandTotal), zero);\r\n\r\n // 3.2 Assign net lineitemSubtotal and net shipping to total\r\n this.total.netLineItemSubtotal = netLineItemSubtotal;\r\n this.total.netShippingCharges = netShippingCharges;\r\n\r\n // 4. Calculate charges and net charges after discount\r\n const additiveCharges = this.charges\r\n .filter(charge => charge.getImpact() === ChargeImpact.ADD)\r\n .reduce((total, charge) => total.add(charge.getTotal().chargeAmount), zero);\r\n const netAdditiveCharges = this.charges\r\n .filter(charge => charge.getImpact() === ChargeImpact.ADD)\r\n .reduce((total, charge) => total.add(charge.getTotal().grandTotal), zero);\r\n const adjustmentCharges = this.charges\r\n .filter(charge => charge.getImpact() === ChargeImpact.SUBTRACT)\r\n .reduce((total, charge) => total.add(charge.getTotal().grandTotal), zero);\r\n\r\n // 5. Aggregate Taxes & Grand Total from all items and charges\r\n let taxTotal = zero;\r\n let lineItemTaxTotal = zero;\r\n let additiveChargesTaxTotal = zero;\r\n\r\n const taxBreakdown: ShoppingContainerTaxBreakdownModel = {};\r\n const lineItemTaxBreakdown: ShoppingContainerTaxBreakdownModel = {};\r\n const additiveChargesTaxBreakdown: ShoppingContainerTaxBreakdownModel = {};\r\n\r\n // Helper to merge tax breakdowns into hierarchical structure\r\n const mergeTax = (\r\n sourceBreakdown: Record<string, LineItemTaxBreakdownModel | ChargeTaxBreakdownModel>,\r\n targetBreakdown: ShoppingContainerTaxBreakdownModel\r\n ) => {\r\n Object.entries(sourceBreakdown).forEach(([ruleId, breakdown]) => {\r\n const system = breakdown.system;\r\n const subsystem = breakdown.subSystem;\r\n\r\n // Populate Target Breakdown\r\n if (!targetBreakdown[system]) {\r\n targetBreakdown[system] = { system, totalAmount: zero, subSystems: {} };\r\n }\r\n if (!targetBreakdown[system].subSystems[subsystem]) {\r\n targetBreakdown[system].subSystems[subsystem] = breakdown.taxAmount;\r\n } else {\r\n targetBreakdown[system].subSystems[subsystem] = targetBreakdown[system].subSystems[subsystem].add(breakdown.taxAmount);\r\n }\r\n targetBreakdown[system].totalAmount = targetBreakdown[system].totalAmount.add(breakdown.taxAmount);\r\n\r\n // Populate Combined taxBreakdown\r\n if (!taxBreakdown[system]) {\r\n taxBreakdown[system] = { system, totalAmount: zero, subSystems: {} };\r\n }\r\n if (!taxBreakdown[system].subSystems[subsystem]) {\r\n taxBreakdown[system].subSystems[subsystem] = breakdown.taxAmount;\r\n } else {\r\n taxBreakdown[system].subSystems[subsystem] = taxBreakdown[system].subSystems[subsystem].add(breakdown.taxAmount);\r\n }\r\n taxBreakdown[system].totalAmount = taxBreakdown[system].totalAmount.add(breakdown.taxAmount);\r\n });\r\n };\r\n\r\n // 5.1 Merge line item taxes\r\n filteredLineItems.forEach(lineItem => {\r\n const lineItemTaxes = lineItem.getTotal().taxBreakdown;\r\n if (lineItemTaxes) {\r\n mergeTax(lineItemTaxes, lineItemTaxBreakdown);\r\n mergeTax(lineItemTaxes, taxBreakdown);\r\n lineItemTaxTotal = lineItemTaxTotal.add(lineItem.getTotal().taxTotal);\r\n }\r\n });\r\n\r\n // 5.2 Merge charge taxes\r\n this.charges.forEach(charge => {\r\n const chargeTaxes = charge.getTotal().taxBreakdown;\r\n if (chargeTaxes) {\r\n mergeTax(chargeTaxes, additiveChargesTaxBreakdown);\r\n mergeTax(chargeTaxes, taxBreakdown);\r\n additiveChargesTaxTotal = additiveChargesTaxTotal.add(charge.getTotal().taxTotal);\r\n }\r\n });\r\n\r\n // 5.3 Calculate total tax\r\n taxTotal = lineItemTaxTotal.add(additiveChargesTaxTotal);\r\n\r\n // 6. Final Grand Total: netLineItemSubtotal + lineItemTaxTotal + netAdditiveCharges (includes netShippingCharges) - adjustmentCharges\r\n const grandTotal = netLineItemSubtotal.add(lineItemTaxTotal).add(netAdditiveCharges).subtract(adjustmentCharges);\r\n\r\n\r\n // 7. Reconstruct total object\r\n this.total = {\r\n lineItemSubtotal: lineItemSubtotal,\r\n netLineItemSubtotal: netLineItemSubtotal,\r\n lineItemTaxTotal: lineItemTaxTotal,\r\n lineItemTaxBreakdown: lineItemTaxBreakdown,\r\n\r\n additiveCharges: additiveCharges,\r\n netAdditiveCharges: netAdditiveCharges,\r\n additiveChargesTaxTotal: additiveChargesTaxTotal,\r\n additiveChargesTaxBreakdown: additiveChargesTaxBreakdown,\r\n\r\n adjustmentCharges: adjustmentCharges,\r\n shippingCharges: shippingCharges,\r\n netShippingCharges: netShippingCharges,\r\n\r\n discountTotal: discountTotal,\r\n discountBreakdown: discountBreakdown,\r\n taxTotal: taxTotal,\r\n taxBreakdown: taxBreakdown,\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 }\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.discountTotal = this.total.lineItemSubtotal.zero();\r\n this.total.discountBreakdown = {};\r\n // Apply non shipping coupons\r\n otherCoupons.length && this.applyNonShippingCoupons(otherCoupons);\r\n this.applyDiscountsInLineItem(this.total.discountBreakdown);\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, discountTotal]) => {\r\n const coupon = this.coupons.find(c => c.getCode() === code);\r\n if (!coupon || discountTotal.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 = discountTotal.subtract(distributed);\r\n } else {\r\n amount = discountTotal.multiply(item.getTotal().subtotal).divide(this.total.lineItemSubtotal).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.lineItemSubtotal.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 private applyDiscountsInShippingCharges(couponTotal: Record<string, PriceModel>) {\r\n const couponDiscounts: [string, PriceModel][] = Array.from(Object.entries(couponTotal))\r\n .filter(couponDiscount => !couponDiscount[1].isZero());\r\n const shippingCharges = this.charges.filter(charge => charge.getType() === ChargeType.SHIPPING);\r\n\r\n const chargeDiscounts = new Map<string, { coupon: CouponModel, amount: PriceModel }[]>();\r\n shippingCharges.forEach(li => chargeDiscounts.set(li.getId(), []));\r\n\r\n couponDiscounts.forEach(([code, discountTotal]) => {\r\n const coupon = this.coupons.find(c => c.getCode() === code);\r\n if (!coupon || discountTotal.isZero()) return;\r\n\r\n const validCharges = shippingCharges\r\n .sort((a, b) => a.getTotal().grandTotal.compareTo(b.getTotal().grandTotal));\r\n\r\n let distributed = new PriceModel({ amount: 0, currency: this.currency });\r\n\r\n validCharges.forEach((charge, index) => {\r\n let amount: PriceModel;\r\n if (index === validCharges.length - 1) {\r\n amount = discountTotal.subtract(distributed);\r\n } else {\r\n amount = discountTotal.multiply(charge.getTotal().chargeAmount).divide(this.total.shippingCharges).round();\r\n }\r\n distributed = distributed.add(amount);\r\n chargeDiscounts.get(charge.getId())?.push({ coupon, amount });\r\n });\r\n });\r\n\r\n shippingCharges.forEach(charge => {\r\n charge.updateDiscounts(chargeDiscounts.get(charge.getId()) || []);\r\n });\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.lineItemSubtotal, this.total.shippingCharges, this.country, this.currency);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(coupons[0]);\r\n this.total.discountTotal = couponValue;\r\n this.total.discountBreakdown[coupons[0].getCode()] = 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.shippingCharges.getAmount() > 0 && applicableCoupons.length > 0) {\r\n const netLineItemSubtotal = this.total.lineItemSubtotal.subtract(this.total.discountTotal);\r\n\r\n const maxValuedCoupon = applicableCoupons.reduce((maxCoupon, currentCoupon) => {\r\n if (!maxCoupon) return currentCoupon;\r\n\r\n const currentCouponValue = currentCoupon.calculateApplicableCouponDiscount(netLineItemSubtotal, this.total.shippingCharges, this.country, this.currency).min(this.total.shippingCharges);\r\n const maxCouponValue = maxCoupon.calculateApplicableCouponDiscount(netLineItemSubtotal, this.total.shippingCharges, this.country, this.currency).min(this.total.shippingCharges);\r\n\r\n if (currentCouponValue.compareTo(maxCouponValue) === 0) {\r\n return currentCoupon.getType() === CouponType.COUPON ? currentCoupon : maxCoupon;\r\n }\r\n return currentCouponValue.compareTo(maxCouponValue) > 0 ? currentCoupon : maxCoupon;\r\n });\r\n\r\n const couponValue = maxValuedCoupon.calculateApplicableCouponDiscount(netLineItemSubtotal, this.total.shippingCharges, this.country, this.currency).min(this.total.shippingCharges);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(maxValuedCoupon);\r\n this.total.discountTotal = this.total.discountTotal.add(couponValue);\r\n this.total.discountBreakdown[maxValuedCoupon.getCode()] = couponValue;\r\n }\r\n }\r\n }\r\n}\r\n\r\n\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/Classes/ShoppingContainer.ts"],"names":["BaseShoppingContainerModel","BaseModel","data","date","item","LineItemModel","charge","ChargeModel","AddressModel","coupon","CouponModel","Utils_default","PriceModel","key","value","breakdown","systemKey","systemValue","subKey","subValue","totals","zero","filteredLineItems","lineitem","lineItemSubtotal","total","lineItem","shippingCharges","discountTotal","discountBreakdown","nonShippingCouponTotal","couponValue","shippingCoupon","netLineItemSubtotal","netShippingCharges","additiveCharges","netAdditiveCharges","adjustmentCharges","taxTotal","lineItemTaxTotal","additiveChargesTaxTotal","taxBreakdown","lineItemTaxBreakdown","additiveChargesTaxBreakdown","mergeTax","sourceBreakdown","targetBreakdown","ruleId","system","subsystem","lineItemTaxes","chargeTaxes","grandTotal","shippingDetails","applicableCoupons","shippingCoupons","otherCoupons","couponTotal","couponDiscounts","couponDiscount","itemDiscounts","li","code","c","validItems","a","b","distributed","index","amount","chargeDiscounts","validCharges","coupons","maxValuedCoupon","maxCoupon","currentCoupon","currentCouponValue","maxCouponValue"],"mappings":"+RAkIA,IAA8BA,CAA9B,CAAA,cAAiEC,CAAU,CAC/D,EACA,CAAA,UAAA,CACA,aACA,CAAA,WAAA,CACA,SACA,CAAA,OAAA,CACA,eACA,CAAA,eAAA,CACA,cAGA,CAAA,OAAA,CAGA,KAEA,CAAA,OAAA,CACA,QACA,CAAA,MAAA,CAQV,WAAYC,CAAAA,CAAAA,CAAuCC,GAAa,CAAA,IAAI,IAAQ,CAAA,CAC1E,KAAMD,CAAAA,CAAAA,CAAMC,GAAI,CAAA,CAChB,IAAK,CAAA,EAAA,CAAKD,CAAK,CAAA,EAAA,CACf,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,C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Content":["import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport AddressModel, { AddressData } from \"./Address\";\r\nimport LineItemModel, { LineItemData, LineItemTaxBreakdown, LineItemTaxBreakdownModel } 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 { ChargeImpact, ChargeType, LineItemState, TaxSystem } from \"./Enum\";\r\nimport ChargeModel, { ChargeData, ChargeTaxBreakdownModel } from \"./Charge\";\r\n\r\n/**\r\n * Breakdown of a specific tax system (e.g., GST, VAT) for the entire container.\r\n * Groups taxes by system and then by specific rule/subsystem.\r\n */\r\nexport type TaxSystemBreakdown = {\r\n /** Name of the tax system (e.g., GST) */\r\n system: TaxSystem;\r\n /** Total tax amount collected for this system across all line items and charges */\r\n totalAmount: PriceData;\r\n /** Detailed breakdown by rule/subsystem to total tax amount (e.g., CGST, SGST) */\r\n subSystems: Record<string, PriceData>;\r\n};\r\n\r\n/**\r\n * Internal model for tax system breakdown using PriceModel instances.\r\n */\r\nexport type TaxSystemBreakdownModel = {\r\n system: TaxSystem;\r\n totalAmount: PriceModel;\r\n subSystems: Record<string, PriceModel>;\r\n};\r\n\r\nexport type ShoppingContainerTaxBreakdownModel = Record<string, TaxSystemBreakdownModel>;\r\n\r\n/**\r\n * Comprehensive totals for a shopping container, logically grouped by source.\r\n */\r\nexport type ShoppingContainerTotal = {\r\n // --- Item Totals ---\r\n /** Sum of all line item prices before any discounts or taxes */\r\n lineItemSubtotal: PriceData;\r\n /** Total item subtotal after item-level discounts have been applied (taxable base for items) */\r\n netLineItemSubtotal: PriceData;\r\n /** Total tax collected specifically from line items */\r\n lineItemTaxTotal: PriceData;\r\n /** Granular tax breakdown for all line items */\r\n lineItemTaxBreakdown: Record<string, TaxSystemBreakdown>;\r\n\r\n // --- Charge Totals ---\r\n /** Sum of pre-discount chargeAmount for additive charges (tax-inclusive) */\r\n additiveCharges: PriceData;\r\n /** Sum of post-discount netChargeAmount for additive charges – final payable (tax-inclusive) */\r\n netAdditiveCharges: PriceData;\r\n /** Tax reverse-calculated from additive charges only */\r\n additiveChargesTaxTotal: PriceData;\r\n /** Granular tax breakdown from additive charges */\r\n additiveChargesTaxBreakdown: Record<string, TaxSystemBreakdown>;\r\n\r\n /** Sum of post-discount netChargeAmount for subtractive charges – absolute amount to subtract */\r\n adjustmentCharges: PriceData;\r\n\r\n /** Pre-discount shipping gross (tax-inclusive, part of additive charges) */\r\n shippingCharges: PriceData;\r\n /** Shipping cost after any shipping-specific discounts */\r\n netShippingCharges: PriceData;\r\n\r\n // --- Aggregate Totals ---\r\n /** Combined total tax (lineItemTaxTotal + chargeTaxTotal) */\r\n taxTotal: PriceData;\r\n /** Combined granular tax breakdown for the entire container */\r\n taxBreakdown: Record<string, TaxSystemBreakdown>;\r\n /** Sum of all coupon discounts applied to the container */\r\n discountTotal: PriceData;\r\n /** Map of applied coupon codes to their calculated discount amounts */\r\n discountBreakdown: Record<string, PriceData>;\r\n /** Final total amount to be paid (NetSubtotal + ChargesTotal + TaxTotal - (any remaining discounts)) */\r\n grandTotal: PriceData;\r\n};\r\n\r\n/**\r\n * Internal model version of ShoppingContainerTotal using PriceModel instances.\r\n */\r\nexport type ShoppingContainerTotalModel = {\r\n lineItemSubtotal: PriceModel;\r\n netLineItemSubtotal: PriceModel;\r\n lineItemTaxTotal: PriceModel;\r\n lineItemTaxBreakdown: Record<string, TaxSystemBreakdownModel>;\r\n\r\n additiveCharges: PriceModel;\r\n netAdditiveCharges: PriceModel;\r\n additiveChargesTaxTotal: PriceModel;\r\n additiveChargesTaxBreakdown: Record<string, TaxSystemBreakdownModel>;\r\n\r\n adjustmentCharges: PriceModel;\r\n\r\n shippingCharges: PriceModel;\r\n netShippingCharges: PriceModel;\r\n\r\n taxTotal: PriceModel;\r\n taxBreakdown: Record<string, TaxSystemBreakdownModel>;\r\n discountTotal: PriceModel;\r\n discountBreakdown: Record<string, PriceModel>;\r\n grandTotal: PriceModel;\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 charges: ChargeData[];\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 charges: ChargeModel[];\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: ShoppingContainerTotalModel;\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.charges = (data.charges ?? []).map(charge => new ChargeModel(charge));\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 lineItemSubtotal: new PriceModel(data.total.lineItemSubtotal),\r\n netLineItemSubtotal: new PriceModel(data.total.netLineItemSubtotal),\r\n lineItemTaxTotal: new PriceModel(data.total.lineItemTaxTotal),\r\n lineItemTaxBreakdown: this.mapTaxBreakdown(data.total.lineItemTaxBreakdown),\r\n\r\n additiveCharges: new PriceModel(data.total.additiveCharges),\r\n netAdditiveCharges: new PriceModel(data.total.netAdditiveCharges),\r\n additiveChargesTaxTotal: new PriceModel(data.total.additiveChargesTaxTotal),\r\n\r\n additiveChargesTaxBreakdown: this.mapTaxBreakdown(data.total.additiveChargesTaxBreakdown),\r\n adjustmentCharges: new PriceModel(data.total.adjustmentCharges),\r\n shippingCharges: new PriceModel(data.total.shippingCharges),\r\n netShippingCharges: new PriceModel(data.total.netShippingCharges),\r\n\r\n discountTotal: new PriceModel(data.total.discountTotal),\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(data.total.discountBreakdown).map(([key, value]) => [key, new PriceModel(value)])\r\n ),\r\n\r\n taxTotal: new PriceModel(data.total.taxTotal),\r\n taxBreakdown: this.mapTaxBreakdown(data.total.taxBreakdown),\r\n grandTotal: new PriceModel(data.total.grandTotal),\r\n };\r\n }\r\n\r\n private mapTaxBreakdown(breakdown: Record<string, TaxSystemBreakdown>): Record<string, TaxSystemBreakdownModel> {\r\n return Object.fromEntries(\r\n Object.entries(breakdown || {}).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: new PriceModel(systemValue.totalAmount),\r\n subSystems: Object.fromEntries(\r\n Object.entries(systemValue.subSystems).map(([subKey, subValue]) => [\r\n subKey,\r\n new PriceModel(subValue)\r\n ])\r\n )\r\n }\r\n ])\r\n );\r\n }\r\n\r\n private serializeTaxBreakdown(breakdown: Record<string, TaxSystemBreakdownModel>): Record<string, TaxSystemBreakdown> {\r\n return Object.fromEntries(\r\n Object.entries(breakdown || {}).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount.getDetails(),\r\n subSystems: Object.fromEntries(\r\n Object.entries(systemValue.subSystems).map(([subKey, subValue]) => [\r\n subKey,\r\n subValue.getDetails()\r\n ])\r\n )\r\n }\r\n ])\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 defensive copy of the charges in the container.\r\n * @returns An array of ChargeModel instances.\r\n */\r\n public getCharges(): ChargeModel[] {\r\n return this.charges.map(charge => new ChargeModel(charge.getDetails()));\r\n }\r\n\r\n /**\r\n * Adds a new charge to the container and recalculates totals.\r\n * @param charge - The charge to add.\r\n */\r\n public addCharge(charge: ChargeModel): void {\r\n this.charges.push(charge);\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Clears all charges from the container and recalculates totals.\r\n */\r\n public clearCharges(): void {\r\n this.charges = [];\r\n this.calculateTotals();\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 this.shippingDetails ? Utils.deepClone(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 {\r\n lineItemSubtotal: this.total.lineItemSubtotal,\r\n netLineItemSubtotal: this.total.netLineItemSubtotal,\r\n lineItemTaxTotal: this.total.lineItemTaxTotal,\r\n lineItemTaxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.lineItemTaxBreakdown).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount,\r\n subSystems: { ...systemValue.subSystems }\r\n }\r\n ])\r\n ),\r\n additiveCharges: this.total.additiveCharges,\r\n netAdditiveCharges : this.total.netAdditiveCharges,\r\n additiveChargesTaxTotal: this.total.additiveChargesTaxTotal,\r\n additiveChargesTaxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.additiveChargesTaxBreakdown).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount,\r\n subSystems: { ...systemValue.subSystems }\r\n }\r\n ])\r\n ),\r\n adjustmentCharges: this.total.adjustmentCharges,\r\n shippingCharges: this.total.shippingCharges,\r\n netShippingCharges: this.total.netShippingCharges,\r\n discountBreakdown: { ...this.total.discountBreakdown },\r\n discountTotal: this.total.discountTotal,\r\n taxTotal: this.total.taxTotal,\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.taxBreakdown).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount,\r\n subSystems: { ...systemValue.subSystems }\r\n }\r\n ])\r\n ),\r\n grandTotal: this.total.grandTotal,\r\n };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the 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 const totals = this.getTotal();\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 charges: this.getCharges().map(charge => charge.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 // Item Totals\r\n lineItemSubtotal: totals.lineItemSubtotal.getDetails(),\r\n netLineItemSubtotal: totals.netLineItemSubtotal.getDetails(),\r\n lineItemTaxTotal: totals.lineItemTaxTotal.getDetails(),\r\n lineItemTaxBreakdown: this.serializeTaxBreakdown(totals.lineItemTaxBreakdown),\r\n\r\n // Charge Totals\r\n additiveCharges: totals.additiveCharges.getDetails(),\r\n netAdditiveCharges: totals.netAdditiveCharges.getDetails(),\r\n additiveChargesTaxTotal: totals.additiveChargesTaxTotal.getDetails(),\r\n additiveChargesTaxBreakdown: this.serializeTaxBreakdown(totals.additiveChargesTaxBreakdown),\r\n\r\n adjustmentCharges: totals.adjustmentCharges.getDetails(),\r\n\r\n shippingCharges: totals.shippingCharges.getDetails(),\r\n netShippingCharges: totals.netShippingCharges.getDetails(),\r\n\r\n // Aggregate Totals\r\n discountTotal: totals.discountTotal.getDetails(),\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(totals.discountBreakdown).map(([key, value]) => [key, value.getDetails()])\r\n ),\r\n taxTotal: totals.taxTotal.getDetails(),\r\n taxBreakdown: this.serializeTaxBreakdown(totals.taxBreakdown),\r\n grandTotal: totals.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 \r\n // 1. Calculate LineItem subtotals and Shipping Cost\r\n const filteredLineItems = this.lineItems.filter(lineitem => lineitem.getState() !== LineItemState.CANCELLED);\r\n const lineItemSubtotal = filteredLineItems.reduce((total, lineItem) => total.add(lineItem.getTotal().subtotal), zero);\r\n const shippingCharges = this.charges\r\n .filter(charge => charge.getType() === ChargeType.SHIPPING)\r\n .reduce((total, charge) => total.add(charge.getTotal().chargeAmount), zero);\r\n\r\n // 1.1 Assign lineitemSubTotal and shipping charges to total, which will be used for coupon calculations\r\n this.total.lineItemSubtotal = lineItemSubtotal;\r\n this.total.shippingCharges = shippingCharges;\r\n\r\n // 2. Calculate coupon values based on gross subtotal & shipping\r\n let discountTotal = zero;\r\n let discountBreakdown: Record<string, PriceModel> = {};\r\n let nonShippingCouponTotal: Record<string, PriceModel> = {};\r\n this.coupons.forEach(coupon => {\r\n const couponValue = coupon.calculateApplicableCouponDiscount(lineItemSubtotal, shippingCharges, this.country, this.currency);\r\n discountTotal = discountTotal.add(couponValue);\r\n discountBreakdown[coupon.getCode()] = couponValue;\r\n if (coupon.getCategory() !== CouponCategory.SHIPPING) {\r\n nonShippingCouponTotal[coupon.getCode()] = couponValue;\r\n }\r\n })\r\n\r\n // 2.1. Assign discount total and breakdown to total\r\n this.total.discountTotal = discountTotal;\r\n this.total.discountBreakdown = discountBreakdown;\r\n\r\n // 3. Apply discounts at lineitem and shipping charges\r\n this.applyDiscountsInLineItem(nonShippingCouponTotal);\r\n\r\n const shippingCoupon = this.coupons.find(coupon => coupon.getCategory() === CouponCategory.SHIPPING);\r\n if(shippingCoupon) {\r\n this.applyDiscountsInShippingCharges({[shippingCoupon.getCode()] : discountBreakdown[shippingCoupon.getCode()] || zero});\r\n } else {\r\n // If no shipping coupon, ensure any previous discounts on shipping charges are cleared\r\n this.applyDiscountsInShippingCharges({});\r\n }\r\n\r\n // 3.1 Calculate net lineitemSubtotal and net shipping after discount\r\n const netLineItemSubtotal = this.lineItems.reduce((total, lineItem) => total.add(lineItem.getTotal().netSubtotal), zero);\r\n const netShippingCharges = this.charges\r\n .filter(charge => charge.getType() === ChargeType.SHIPPING)\r\n .reduce((total, charge) => total.add(charge.getTotal().grandTotal), zero);\r\n\r\n // 3.2 Assign net lineitemSubtotal and net shipping to total\r\n this.total.netLineItemSubtotal = netLineItemSubtotal;\r\n this.total.netShippingCharges = netShippingCharges;\r\n\r\n // 4. Calculate charges and net charges after discount\r\n const additiveCharges = this.charges\r\n .filter(charge => charge.getImpact() === ChargeImpact.ADD)\r\n .reduce((total, charge) => total.add(charge.getTotal().chargeAmount), zero);\r\n const netAdditiveCharges = this.charges\r\n .filter(charge => charge.getImpact() === ChargeImpact.ADD)\r\n .reduce((total, charge) => total.add(charge.getTotal().grandTotal), zero);\r\n const adjustmentCharges = this.charges\r\n .filter(charge => charge.getImpact() === ChargeImpact.SUBTRACT)\r\n .reduce((total, charge) => total.add(charge.getTotal().grandTotal), zero);\r\n\r\n // 5. Aggregate Taxes & Grand Total from all items and charges\r\n let taxTotal = zero;\r\n let lineItemTaxTotal = zero;\r\n let additiveChargesTaxTotal = zero;\r\n\r\n const taxBreakdown: ShoppingContainerTaxBreakdownModel = {};\r\n const lineItemTaxBreakdown: ShoppingContainerTaxBreakdownModel = {};\r\n const additiveChargesTaxBreakdown: ShoppingContainerTaxBreakdownModel = {};\r\n\r\n // Helper to merge tax breakdowns into hierarchical structure\r\n const mergeTax = (\r\n sourceBreakdown: Record<string, LineItemTaxBreakdownModel | ChargeTaxBreakdownModel>,\r\n targetBreakdown: ShoppingContainerTaxBreakdownModel\r\n ) => {\r\n Object.entries(sourceBreakdown).forEach(([ruleId, breakdown]) => {\r\n const system = breakdown.system;\r\n const subsystem = breakdown.subSystem;\r\n\r\n // Populate Target Breakdown\r\n if (!targetBreakdown[system]) {\r\n targetBreakdown[system] = { system, totalAmount: zero, subSystems: {} };\r\n }\r\n if (!targetBreakdown[system].subSystems[subsystem]) {\r\n targetBreakdown[system].subSystems[subsystem] = breakdown.taxAmount;\r\n } else {\r\n targetBreakdown[system].subSystems[subsystem] = targetBreakdown[system].subSystems[subsystem].add(breakdown.taxAmount);\r\n }\r\n targetBreakdown[system].totalAmount = targetBreakdown[system].totalAmount.add(breakdown.taxAmount);\r\n\r\n // Populate Combined taxBreakdown\r\n if (!taxBreakdown[system]) {\r\n taxBreakdown[system] = { system, totalAmount: zero, subSystems: {} };\r\n }\r\n if (!taxBreakdown[system].subSystems[subsystem]) {\r\n taxBreakdown[system].subSystems[subsystem] = breakdown.taxAmount;\r\n } else {\r\n taxBreakdown[system].subSystems[subsystem] = taxBreakdown[system].subSystems[subsystem].add(breakdown.taxAmount);\r\n }\r\n taxBreakdown[system].totalAmount = taxBreakdown[system].totalAmount.add(breakdown.taxAmount);\r\n });\r\n };\r\n\r\n // 5.1 Merge line item taxes\r\n filteredLineItems.forEach(lineItem => {\r\n const lineItemTaxes = lineItem.getTotal().taxBreakdown;\r\n if (lineItemTaxes) {\r\n mergeTax(lineItemTaxes, lineItemTaxBreakdown);\r\n mergeTax(lineItemTaxes, taxBreakdown);\r\n lineItemTaxTotal = lineItemTaxTotal.add(lineItem.getTotal().taxTotal);\r\n }\r\n });\r\n\r\n // 5.2 Merge charge taxes\r\n this.charges.forEach(charge => {\r\n const chargeTaxes = charge.getTotal().taxBreakdown;\r\n if (chargeTaxes) {\r\n mergeTax(chargeTaxes, additiveChargesTaxBreakdown);\r\n mergeTax(chargeTaxes, taxBreakdown);\r\n additiveChargesTaxTotal = additiveChargesTaxTotal.add(charge.getTotal().taxTotal);\r\n }\r\n });\r\n\r\n // 5.3 Calculate total tax\r\n taxTotal = lineItemTaxTotal.add(additiveChargesTaxTotal);\r\n\r\n // 6. Final Grand Total: netLineItemSubtotal + lineItemTaxTotal + netAdditiveCharges (includes netShippingCharges) - adjustmentCharges\r\n const grandTotal = netLineItemSubtotal.add(lineItemTaxTotal).add(netAdditiveCharges).subtract(adjustmentCharges);\r\n\r\n\r\n // 7. Reconstruct total object\r\n this.total = {\r\n lineItemSubtotal: lineItemSubtotal,\r\n netLineItemSubtotal: netLineItemSubtotal,\r\n lineItemTaxTotal: lineItemTaxTotal,\r\n lineItemTaxBreakdown: lineItemTaxBreakdown,\r\n\r\n additiveCharges: additiveCharges,\r\n netAdditiveCharges: netAdditiveCharges,\r\n additiveChargesTaxTotal: additiveChargesTaxTotal,\r\n additiveChargesTaxBreakdown: additiveChargesTaxBreakdown,\r\n\r\n adjustmentCharges: adjustmentCharges,\r\n shippingCharges: shippingCharges,\r\n netShippingCharges: netShippingCharges,\r\n\r\n discountTotal: discountTotal,\r\n discountBreakdown: discountBreakdown,\r\n taxTotal: taxTotal,\r\n taxBreakdown: taxBreakdown,\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 }\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.discountTotal = this.total.lineItemSubtotal.zero();\r\n this.total.discountBreakdown = {};\r\n // Apply non shipping coupons\r\n otherCoupons.length && this.applyNonShippingCoupons(otherCoupons);\r\n this.applyDiscountsInLineItem(this.total.discountBreakdown);\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, discountTotal]) => {\r\n const coupon = this.coupons.find(c => c.getCode() === code);\r\n if (!coupon || discountTotal.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 = discountTotal.subtract(distributed);\r\n } else {\r\n amount = discountTotal.multiply(item.getTotal().subtotal).divide(this.total.lineItemSubtotal).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.lineItemSubtotal.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 private applyDiscountsInShippingCharges(couponTotal: Record<string, PriceModel>) {\r\n const couponDiscounts: [string, PriceModel][] = Array.from(Object.entries(couponTotal))\r\n .filter(couponDiscount => !couponDiscount[1].isZero());\r\n const shippingCharges = this.charges.filter(charge => charge.getType() === ChargeType.SHIPPING);\r\n\r\n const chargeDiscounts = new Map<string, { coupon: CouponModel, amount: PriceModel }[]>();\r\n shippingCharges.forEach(li => chargeDiscounts.set(li.getId(), []));\r\n\r\n couponDiscounts.forEach(([code, discountTotal]) => {\r\n const coupon = this.coupons.find(c => c.getCode() === code);\r\n if (!coupon || discountTotal.isZero()) return;\r\n\r\n const validCharges = shippingCharges\r\n .sort((a, b) => a.getTotal().grandTotal.compareTo(b.getTotal().grandTotal));\r\n\r\n let distributed = new PriceModel({ amount: 0, currency: this.currency });\r\n\r\n validCharges.forEach((charge, index) => {\r\n let amount: PriceModel;\r\n if (index === validCharges.length - 1) {\r\n amount = discountTotal.subtract(distributed);\r\n } else {\r\n amount = discountTotal.multiply(charge.getTotal().chargeAmount).divide(this.total.shippingCharges).round();\r\n }\r\n distributed = distributed.add(amount);\r\n chargeDiscounts.get(charge.getId())?.push({ coupon, amount });\r\n });\r\n });\r\n\r\n shippingCharges.forEach(charge => {\r\n charge.updateDiscounts(chargeDiscounts.get(charge.getId()) || []);\r\n });\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.lineItemSubtotal, this.total.shippingCharges, this.country, this.currency);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(coupons[0]);\r\n this.total.discountTotal = couponValue;\r\n this.total.discountBreakdown[coupons[0].getCode()] = 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.shippingCharges.getAmount() > 0 && applicableCoupons.length > 0) {\r\n const netLineItemSubtotal = this.total.lineItemSubtotal.subtract(this.total.discountTotal);\r\n\r\n const maxValuedCoupon = applicableCoupons.reduce((maxCoupon, currentCoupon) => {\r\n if (!maxCoupon) return currentCoupon;\r\n\r\n const currentCouponValue = currentCoupon.calculateApplicableCouponDiscount(netLineItemSubtotal, this.total.shippingCharges, this.country, this.currency).min(this.total.shippingCharges);\r\n const maxCouponValue = maxCoupon.calculateApplicableCouponDiscount(netLineItemSubtotal, this.total.shippingCharges, this.country, this.currency).min(this.total.shippingCharges);\r\n\r\n if (currentCouponValue.compareTo(maxCouponValue) === 0) {\r\n return currentCoupon.getType() === CouponType.COUPON ? currentCoupon : maxCoupon;\r\n }\r\n return currentCouponValue.compareTo(maxCouponValue) > 0 ? currentCoupon : maxCoupon;\r\n });\r\n\r\n const couponValue = maxValuedCoupon.calculateApplicableCouponDiscount(netLineItemSubtotal, this.total.shippingCharges, this.country, this.currency).min(this.total.shippingCharges);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(maxValuedCoupon);\r\n this.total.discountTotal = this.total.discountTotal.add(couponValue);\r\n this.total.discountBreakdown[maxValuedCoupon.getCode()] = couponValue;\r\n }\r\n }\r\n }\r\n}\r\n\r\n\r\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a as a$4}from'./chunk-X27KEKNB.mjs';import {a as a$1}from'./chunk-QGIQ3MH6.mjs';import {a as a$3}from'./chunk-FCRJAAPY.mjs';import {a as a$2}from'./chunk-LI5JQ6UC.mjs';import {e,o}from'./chunk-QK4XJ3GB.mjs';import {b as b$1}from'./chunk-2B2XI6FG.mjs';import {d,c,f,g,i,j,k,b as b$2}from'./chunk-R5DM7WCD.mjs';import {a}from'./chunk-UXZBULDS.mjs';var b=class extends a{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=a$1.deepClone(t.selectionAttributes),this.name=a$1.deepClone(t.name),this.specifications=a$1.deepClone(t.specifications),this.primaryImage=new b$1(t.primaryImage),this.subItems=a$1.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new d(i.size);e.add(i.size);}),this.pricing={unitPrice:new a$2(t.pricing.unitPrice),tierPricing:new a$3(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(i=>new a$4(i))},this.validateTaxRules(this.pricing.applicableTaxRule),this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,unitPrice:new a$2(t.total.unitPrice),subtotal:new a$2(t.total.subtotal),discountTotal:new a$2(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([i,a])=>[i,new a$2(a)])),netUnitPrice:new a$2(t.total.netUnitPrice),netSubtotal:new a$2(t.total.netSubtotal),taxTotal:new a$2(t.total.taxTotal),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([i,a])=>[i,{rate:a.rate,taxableUnitPrice:new a$2(a.taxableUnitPrice),taxPerUnit:new a$2(a.taxPerUnit),taxAmount:new a$2(a.taxAmount),system:a.system,subSystem:a.subSystem}])),grandTotal:new a$2(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return a$1.deepClone(this.selectionAttributes)}getName(t){return t?a$1.deepClone(this.name[t]??this.name[e[t]]??this.name.en):a$1.deepClone(this.name)}getSpecifications(t){return t?a$1.deepClone(this.specifications[t]??this.specifications[e[t]]??this.specifications.en):a$1.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return a$1.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getState(){return this.state}getTotal(){return {quantity:this.total.quantity,unitPrice:this.total.unitPrice,subtotal:this.total.subtotal,discountTotal:this.total.discountTotal,discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([t,e])=>[t,e])),netUnitPrice:this.total.netUnitPrice,netSubtotal:this.total.netSubtotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableUnitPrice:e.taxableUnitPrice,taxPerUnit:e.taxPerUnit,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),grandTotal:this.total.grandTotal}}getDetails(){let t=this.getPricing(),e=this.getTotal();return {id:this.getId(),productKey:this.getProductKey(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:t.unitPrice.getDetails(),tierPricing:t.tierPricing.getDetails(),taxCategory:t.taxCategory,applicableTaxRule:t.applicableTaxRule.map(i=>i.getDetails())},state:this.getState(),total:{quantity:e.quantity,unitPrice:e.unitPrice.getDetails(),subtotal:e.subtotal.getDetails(),discountTotal:e.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(e.discountBreakdown).map(([i,a])=>[i,a.getDetails()])),netUnitPrice:e.netUnitPrice.getDetails(),netSubtotal:e.netSubtotal.getDetails(),taxTotal:e.taxTotal.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(e.taxBreakdown).map(([i,a])=>[i,{rate:a.rate,taxableUnitPrice:a.taxableUnitPrice.getDetails(),taxPerUnit:a.taxPerUnit.getDetails(),taxAmount:a.taxAmount.getDetails(),system:a.system,subSystem:a.subSystem}])),grandTotal:e.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}validateTaxRules(t){let e=new Set;for(let i=0;i<t.length;i++){let a=t[i].getTaxRuleId();if(e.has(a))throw new c("Duplicate tax rule ID found: "+a);e.add(a);}}addSubItems(t,e){t.forEach(i=>{let a=this.subItems.find(c=>c.size===i.size);a?a.quantity=e?a.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity>0),this.calculateTotals();}updateProductData(t,e,i$1){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new f;if(!t.getIsActive())throw new g;this.subItems.forEach(s=>{if(!t.validateSize(s.size))throw new i});let a=t.getPriceDetails(e);if(!a||a.getBaseUnitPrice().getCurrency()!==i$1)throw new j;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let c=this.subItems.reduce((s,d)=>s+d.quantity,0),{unitPrice:l}=a.getApplicableTier(c);this.pricing={unitPrice:l,tierPricing:a,taxCategory:a.getTaxCategory(),applicableTaxRule:this.pricing.applicableTaxRule},this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discountBreakdown=e,this.calculateTotals();}updateTax(t){t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new k}),this.validateTaxRules(t),this.pricing.applicableTaxRule=t,this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((o,u)=>o+u.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,unitPrice:t,subtotal:t,discountTotal:t,discountBreakdown:{},netUnitPrice:t,netSubtotal:t,taxTotal:t,taxBreakdown:{},grandTotal:t};return}let{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),a=i.multiply(e),c=Object.values(this.total.discountBreakdown).reduce((o,u)=>o.add(u),t),l=a.subtract(c),s=e>0?l.divide(e):t,d={},g=t;this.pricing.applicableTaxRule.forEach(o=>{let u=o.getApplicableTaxRate(s),P=o.calculateTax(s),h=P.multiply(e).round();d[o.getTaxRuleId()]={rate:u,taxableUnitPrice:s,taxPerUnit:P,taxAmount:h,system:o.getTaxSystem(),subSystem:o.getTaxSubSystem()},g=g.add(h);});let U=l.add(g);this.total={quantity:e,unitPrice:i,subtotal:a,discountTotal:c,discountBreakdown:this.total.discountBreakdown,netUnitPrice:s,netSubtotal:l,taxTotal:g,taxBreakdown:d,grandTotal:U};}updateState(t){if(this.state in o)this.state!==t&&(this.state=t);else throw new b$2(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new b$1({sources:{original:""}}),this.subItems=[],this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[]},this.total={quantity:0,unitPrice:t,subtotal:t,discountTotal:t,discountBreakdown:{},netUnitPrice:t,netSubtotal:t,taxTotal:t,taxBreakdown:{},grandTotal:t};}};export{b as a};//# sourceMappingURL=chunk-DYBLLXII.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-DYBLLXII.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/Classes/LineItem.ts"],"names":["LineItemModel","CustomFieldModel","data","Utils_default","ImageInfoModel","uniqueSelectionAttributes","item","DuplicateSizeError","PriceModel","TieredPriceModel","rule","TaxRuleModel","couponCode","discount","taxRuleId","taxBreakdown","locale","LocaleLanguageMap","pricing","total","taxRules","uniqueTaxRule","currentTaxRuleId","InvalidLineItemTaxRuleError","subItems","addQuantity","subItem","existingSubItem","sub","product","cartCountry","cartCurrency","ProductMismatchError","ProductInactiveError","SizeMismatchError","productPricing","PricingNotFoundError","quantity","sum","s","unitPrice","appliedDiscounts","lineItemDiscounts","taxRule","InvalidTaxRuleError","zero","totalQuantity","subTotal","totalDiscount","netSubtotal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CAAAA,CAAAA,CACX,WAAa,CAAA,IAAA,CAAK,QAAQ,WAC1B,CAAA,WAAA,CAAa,IAAK,CAAA,OAAA,CAAQ,YAC1B,iBAAmB,CAAA,EACrB,CAAA,CACA,KAAK,KAAQ,CAAA,CACX,QAAU,CAAA,CAAA,CACV,UAAWA,CACX,CAAA,QAAA,CAAUA,CACV,CAAA,aAAA,CAAeA,EACf,iBAAmB,CAAA,EACnB,CAAA,YAAA,CAAcA,EACd,WAAaA,CAAAA,CAAAA,CACb,QAAUA,CAAAA,CAAAA,CACV,aAAc,EAAC,CACf,UAAYA,CAAAA,CACd,EACF,CACF","file":"chunk-DYBLLXII.mjs","sourcesContent":["import Utils from \"../Utils\";\r\nimport { Color, CountryCode, CurrencyCode, LocaleCode, LocalizedString, LocalizedValue } from \"./Common\";\r\nimport CouponModel from \"./Coupon\";\r\nimport { LineItemState, LocaleLanguageMap, TaxSystem } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport ProductModel, { ProductSelectionAttributes, ProductSpecification, SelectionAttributes } from \"./Product\";\r\nimport { TaxRuleData, TaxRuleModel } from \"./TaxRule\";\r\nimport { TieredPriceData, TieredPriceModel } from \"./TieredPrice\";\r\nimport {\r\n DuplicateSizeError,\r\n ProductMismatchError,\r\n ProductInactiveError,\r\n SizeMismatchError,\r\n PricingNotFoundError,\r\n InvalidTaxRuleError,\r\n InvalidLineItemStateError,\r\n InvalidLineItemTaxRuleError\r\n} from \"./Error\";\r\nimport { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\n\r\nexport type SubItem = {\r\n size: string | 'ONESIZE';\r\n quantity: number;\r\n};\r\n\r\nexport type LineItemPricing = {\r\n unitPrice: PriceData;\r\n tierPricing: TieredPriceData;\r\n taxCategory: string;\r\n applicableTaxRule: TaxRuleData[];\r\n};\r\n\r\nexport type LineItemPricingModel = {\r\n unitPrice: PriceModel;\r\n tierPricing: TieredPriceModel;\r\n taxCategory: string;\r\n applicableTaxRule: TaxRuleModel[];\r\n};\r\n\r\nexport type LineItemTaxBreakdown = {\r\n rate: number; // 0.09 for 9%\r\n taxableUnitPrice: PriceData; // effectiveUnitPrice used for calculation\r\n taxPerUnit: PriceData; // tax on single unit\r\n taxAmount: PriceData; // taxPerUnit × quantity (total tax)\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type LineItemTaxBreakdownModel = {\r\n rate: number;\r\n taxableUnitPrice: PriceModel;\r\n taxPerUnit: PriceModel;\r\n taxAmount: PriceModel;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type LineItemTotals = {\r\n quantity: number;\r\n unitPrice: PriceData; // original unit price (from tier pricing)\r\n subtotal: PriceData; // unitPrice × quantity\r\n discountTotal: PriceData; // sum of all discounts\r\n discountBreakdown: Record<string, PriceData>; // couponCode -> discount mapping\r\n netUnitPrice: PriceData; // unit price after discounts\r\n netSubtotal: PriceData; // subtotal - totalDiscount (taxable amount)\r\n taxTotal: PriceData; // sum of all tax amounts\r\n taxBreakdown: Record<string, LineItemTaxBreakdown>; // tax breakdown by tax rule\r\n grandTotal: PriceData; // effectiveSubtotal + taxTotal\r\n};\r\n\r\nexport type LineItemTotalsModel = {\r\n quantity: number;\r\n unitPrice: PriceModel;\r\n subtotal: PriceModel;\r\n discountTotal: PriceModel;\r\n discountBreakdown: Record<string, PriceModel>;\r\n netUnitPrice: PriceModel;\r\n netSubtotal: PriceModel;\r\n taxTotal: PriceModel;\r\n taxBreakdown: Record<string, LineItemTaxBreakdownModel>;\r\n grandTotal: PriceModel;\r\n};\r\n\r\nexport type LineItemAttributes = CustomFieldAttributes & {\r\n id: string;\r\n\r\n productKey: string;\r\n selectionAttributes: SelectionAttributes;\r\n\r\n name: LocalizedString;\r\n specifications: LocalizedValue<ProductSpecification>;\r\n primaryImage: ImageInfoData;\r\n\r\n subItems: SubItem[];\r\n\r\n pricing: LineItemPricing;\r\n\r\n state?: LineItemState;\r\n total: LineItemTotals;\r\n}\r\n\r\nexport type LineItemData = Required<LineItemAttributes>;\r\n\r\n/**\r\n * Represents a line item within a shopping cart.\r\n */\r\nexport default class LineItemModel extends CustomFieldModel {\r\n protected id: string;\r\n protected productKey: string;\r\n protected selectionAttributes: SelectionAttributes;\r\n\r\n protected name: LocalizedString;\r\n protected specifications: LocalizedValue<ProductSpecification>;\r\n protected primaryImage: ImageInfoModel;\r\n protected subItems: SubItem[];\r\n protected pricing: LineItemPricingModel;\r\n\r\n protected state: LineItemState;\r\n protected total: LineItemTotalsModel;\r\n\r\n /**\r\n * Creates an instance of LineItemModel.\r\n * @param data - The initial line item attributes.\r\n */\r\n constructor(data: LineItemAttributes) {\r\n super(data);\r\n this.id = data.id;\r\n this.productKey = data.productKey;\r\n this.selectionAttributes = Utils.deepClone(data.selectionAttributes);\r\n\r\n this.name = Utils.deepClone(data.name);\r\n this.specifications = Utils.deepClone(data.specifications);\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.subItems = Utils.deepClone(data.subItems);\r\n\r\n let uniqueSelectionAttributes = new Set();\r\n this.subItems.forEach(item => {\r\n if (uniqueSelectionAttributes.has(item.size)) {\r\n throw new DuplicateSizeError(item.size);\r\n }\r\n uniqueSelectionAttributes.add(item.size);\r\n });\r\n\r\n this.pricing = {\r\n unitPrice: new PriceModel(data.pricing.unitPrice),\r\n tierPricing: new TieredPriceModel(data.pricing.tierPricing),\r\n taxCategory: data.pricing.taxCategory,\r\n applicableTaxRule: data.pricing.applicableTaxRule.map(rule => new TaxRuleModel(rule)),\r\n }\r\n this.validateTaxRules(this.pricing.applicableTaxRule);\r\n\r\n this.state = data.state ?? LineItemState.INITIAL;\r\n\r\n this.total = {\r\n quantity: data.total.quantity,\r\n unitPrice: new PriceModel(data.total.unitPrice),\r\n subtotal: new PriceModel(data.total.subtotal),\r\n discountTotal: new PriceModel(data.total.discountTotal),\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(data.total.discountBreakdown).map(([couponCode, discount]) => [\r\n couponCode,\r\n new PriceModel(discount),\r\n ])\r\n ),\r\n netUnitPrice: new PriceModel(data.total.netUnitPrice),\r\n netSubtotal: new PriceModel(data.total.netSubtotal),\r\n taxTotal: new PriceModel(data.total.taxTotal),\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(data.total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n taxRuleId,\r\n {\r\n rate: taxBreakdown.rate,\r\n taxableUnitPrice: new PriceModel(taxBreakdown.taxableUnitPrice),\r\n taxPerUnit: new PriceModel(taxBreakdown.taxPerUnit),\r\n taxAmount: new PriceModel(taxBreakdown.taxAmount),\r\n system: taxBreakdown.system,\r\n subSystem: taxBreakdown.subSystem\r\n }\r\n ])\r\n ),\r\n grandTotal: new PriceModel(data.total.grandTotal),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the unique identifier of the line item.\r\n * @returns The unique ID string.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the product key associated with this line item.\r\n * @returns The product key string.\r\n */\r\n getProductKey(): string {\r\n return this.productKey;\r\n }\r\n\r\n /**\r\n * Gets the selection attributes (e.g., size, color) for this line item.\r\n * @returns A copy of the selection attributes object.\r\n */\r\n getSelectionAttributes(): SelectionAttributes {\r\n return Utils.deepClone(this.selectionAttributes);\r\n }\r\n\r\n /**\r\n * Gets the full localized product name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the product name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return Utils.deepClone(this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en);\r\n } else {\r\n return Utils.deepClone(this.name);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product specifications object.\r\n * @returns Product Specifications\r\n */\r\n getSpecifications(): LocalizedValue<ProductSpecification>\r\n /**\r\n * Gets the product specifications for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The ProductSpecification object for the specified locale, or undefined if not found.\r\n */\r\n getSpecifications(locale: LocaleCode): ProductSpecification | undefined\r\n getSpecifications(locale?: LocaleCode): LocalizedValue<ProductSpecification> | ProductSpecification | undefined {\r\n if (locale) {\r\n return Utils.deepClone(this.specifications[locale] ?? this.specifications[LocaleLanguageMap[locale]] ?? this.specifications.en);\r\n } else {\r\n return Utils.deepClone(this.specifications);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the image information model for this line item.\r\n * @returns The ImageInfoModel instance.\r\n */\r\n getImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /**\r\n * Gets the sub-items (size/quantity breakdown).\r\n * @returns A copy of the array of SubItems.\r\n */\r\n getSubItems(): SubItem[] {\r\n return Utils.deepClone(this.subItems);\r\n }\r\n\r\n /**\r\n * Gets the total quantity for this line item across all sub-items.\r\n * @returns The total quantity as a number.\r\n */\r\n getTotalQuantity(): number {\r\n return this.total.quantity;\r\n }\r\n\r\n /**\r\n * Gets the pricing information model for this line item.\r\n * @returns An object containing unit price, tiered pricing, tax category, and tax details.\r\n */\r\n getPricing() {\r\n return {\r\n unitPrice: this.pricing.unitPrice,\r\n tierPricing: this.pricing.tierPricing,\r\n taxCategory: this.pricing.taxCategory,\r\n applicableTaxRule: [...this.pricing.applicableTaxRule],\r\n };\r\n }\r\n\r\n /**\r\n * Gets the current state of the line item.\r\n * @returns The LineItemState enum value.\r\n */\r\n getState() {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the total price for this line item (including all sub-items).\r\n * @returns An object containing line item totals including subtotal, tax, discounts, and grand total.\r\n */\r\n getTotal(): LineItemTotalsModel {\r\n return {\r\n quantity: this.total.quantity,\r\n unitPrice: this.total.unitPrice,\r\n subtotal: this.total.subtotal,\r\n discountTotal: this.total.discountTotal,\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(this.total.discountBreakdown).map(([couponCode, discount]) => [\r\n couponCode,\r\n discount,\r\n ])\r\n ),\r\n netUnitPrice: this.total.netUnitPrice,\r\n netSubtotal: this.total.netSubtotal,\r\n taxTotal: this.total.taxTotal,\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n taxRuleId,\r\n {\r\n rate: taxBreakdown.rate,\r\n taxableUnitPrice: taxBreakdown.taxableUnitPrice,\r\n taxPerUnit: taxBreakdown.taxPerUnit,\r\n taxAmount: taxBreakdown.taxAmount,\r\n system: taxBreakdown.system,\r\n subSystem: taxBreakdown.subSystem\r\n }\r\n ])\r\n ),\r\n grandTotal: this.total.grandTotal,\r\n };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the line item's details.\r\n * @returns LineItemData.\r\n */\r\n getDetails(): LineItemData {\r\n const pricing = this.getPricing();\r\n const total = this.getTotal();\r\n return {\r\n id: this.getId(),\r\n productKey: this.getProductKey(),\r\n selectionAttributes: this.getSelectionAttributes(),\r\n name: this.getName(),\r\n specifications: this.getSpecifications(),\r\n primaryImage: this.getImage().getDetails(),\r\n subItems: this.getSubItems(),\r\n pricing: {\r\n unitPrice: pricing.unitPrice.getDetails(),\r\n tierPricing: pricing.tierPricing.getDetails(),\r\n taxCategory: pricing.taxCategory,\r\n applicableTaxRule: pricing.applicableTaxRule.map(rule => rule.getDetails()),\r\n },\r\n state: this.getState(),\r\n total: {\r\n quantity: total.quantity,\r\n unitPrice: total.unitPrice.getDetails(),\r\n subtotal: total.subtotal.getDetails(),\r\n discountTotal: total.discountTotal.getDetails(),\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(total.discountBreakdown).map(([couponCode, discount]) => [\r\n couponCode,\r\n discount.getDetails(),\r\n ])\r\n ),\r\n netUnitPrice: total.netUnitPrice.getDetails(),\r\n netSubtotal: total.netSubtotal.getDetails(),\r\n taxTotal: total.taxTotal.getDetails(),\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n taxRuleId,\r\n {\r\n rate: taxBreakdown.rate,\r\n taxableUnitPrice: taxBreakdown.taxableUnitPrice.getDetails(),\r\n taxPerUnit: taxBreakdown.taxPerUnit.getDetails(),\r\n taxAmount: taxBreakdown.taxAmount.getDetails(),\r\n system: taxBreakdown.system,\r\n subSystem: taxBreakdown.subSystem\r\n }\r\n ])\r\n ),\r\n grandTotal: total.grandTotal.getDetails(),\r\n },\r\n customFields: this.getAllCustomFields()\r\n };\r\n }\r\n\r\n /**\r\n\t * Validates that there are no overlapping price brackets for any tax rules within the charge.\r\n\t * @param taxRules - The list of tax rules to validate.\r\n\t * @throws {InvalidLineItemTaxRuleError} Duplicate tax rule IDs will results in error.\r\n\t */\r\n private validateTaxRules(taxRules: TaxRuleModel[]): void {\r\n const uniqueTaxRule = new Set();\r\n for (let i = 0; i < taxRules.length; i++) {\r\n const currentTaxRuleId = taxRules[i].getTaxRuleId();\r\n if (uniqueTaxRule.has(currentTaxRuleId)) {\r\n throw new InvalidLineItemTaxRuleError(\"Duplicate tax rule ID found: \" + currentTaxRuleId);\r\n } else {\r\n uniqueTaxRule.add(currentTaxRuleId);\r\n }\r\n }\r\n }\r\n /**\r\n * Adds or updates sub-items (e.g., sizes with quantities) to the line item.\r\n * If a sub-item with the same size already exists, its quantity is either\r\n * updated by adding the new quantity or replaced entirely, based on the `addQuantity` flag.\r\n * Sub-items with a resulting quantity of 0 are removed.\r\n * @param subItems - An array of `SubItem` objects to add or update.\r\n * @param addQuantity - If true, adds the quantity from `subItem` to the existing quantity.\r\n * If false, replaces the existing quantity with the one from `subItem`.\r\n */\r\n addSubItems(subItems: SubItem[], addQuantity: boolean): void {\r\n subItems.forEach(subItem => {\r\n const existingSubItem = this.subItems.find(item => item.size === subItem.size);\r\n if (existingSubItem) {\r\n existingSubItem.quantity = addQuantity ? existingSubItem.quantity + subItem.quantity : subItem.quantity;\r\n } else {\r\n this.subItems.push(subItem);\r\n }\r\n })\r\n this.subItems = this.subItems.filter(sub => sub.quantity > 0);\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the line item with the latest product data (price, image, name, specifications).\r\n * Validates that the product matches the line item's selection and is active.\r\n * @param product - The product model to update from.\r\n * @param cartCountry - The country code for pricing context.\r\n * @param cartCurrency - The currency code for pricing context.\r\n * @throws {Error} If product mismatch, inactive, size mismatch, or pricing missing.\r\n */\r\n public updateProductData(product: ProductModel, cartCountry: CountryCode, cartCurrency: CurrencyCode): void {\r\n if (this.productKey !== product.getKey() || !product.validateSelectionAttribute(this.selectionAttributes)) {\r\n throw new ProductMismatchError();\r\n } else if (!product.getIsActive()) {\r\n throw new ProductInactiveError();\r\n }\r\n\r\n this.subItems.forEach(subItem => {\r\n if (!product.validateSize(subItem.size)) {\r\n throw new SizeMismatchError();\r\n }\r\n });\r\n\r\n const productPricing = product.getPriceDetails(cartCountry);\r\n if (!productPricing || productPricing.getBaseUnitPrice().getCurrency() !== cartCurrency) {\r\n throw new PricingNotFoundError();\r\n }\r\n this.name = product.getName();\r\n this.specifications = product.getSpecifications();\r\n this.primaryImage = product.getImages(this.selectionAttributes).primary;\r\n\r\n const quantity = this.subItems.reduce((sum, s) => sum + s.quantity, 0);\r\n const { unitPrice } = productPricing.getApplicableTier(quantity);\r\n\r\n this.pricing = {\r\n unitPrice: unitPrice,\r\n tierPricing: productPricing,\r\n taxCategory: productPricing.getTaxCategory(),\r\n applicableTaxRule: this.pricing.applicableTaxRule\r\n }\r\n\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the discounts applied to this line item and recalculates totals.\r\n * @param appliedDiscounts - List of coupons and their allocated discount amounts.\r\n */\r\n public updateDiscounts(appliedDiscounts: { coupon: CouponModel, amount: PriceModel }[]): void {\r\n let lineItemDiscounts = {} as Record<string, PriceModel>;\r\n appliedDiscounts.forEach(discount => {\r\n lineItemDiscounts[discount.coupon.getCode()] = discount.amount;\r\n });\r\n\r\n this.total.discountBreakdown = lineItemDiscounts;\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the tax rule for this line item and recalculates totals.\r\n * @param taxRule - The new tax rule to apply.\r\n * @throws {Error} If the tax rule category does not match the item's tax category.\r\n */\r\n public updateTax(taxRules: TaxRuleModel[]): void {\r\n taxRules.forEach(taxRule => {\r\n if (!taxRule.appliesTo(this.pricing.taxCategory, taxRule.getCountry())) {\r\n throw new InvalidTaxRuleError();\r\n }\r\n });\r\n\r\n this.validateTaxRules(taxRules);\r\n this.pricing.applicableTaxRule = taxRules;\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Recalculates the line item totals based on current quantity, unit price, discounts, and tax rates.\r\n */\r\n public calculateTotals(): void {\r\n const zero = this.pricing.unitPrice.zero();\r\n const totalQuantity = this.subItems.reduce((sum, s) => sum + s.quantity, 0);\r\n\r\n if (this.state === LineItemState.CANCELLED) {\r\n this.total = {\r\n quantity: 0,\r\n unitPrice: zero,\r\n subtotal: zero,\r\n discountTotal: zero,\r\n discountBreakdown: {},\r\n netUnitPrice: zero,\r\n netSubtotal: zero,\r\n taxTotal: zero,\r\n taxBreakdown: {},\r\n grandTotal: zero\r\n };\r\n return;\r\n }\r\n\r\n const { unitPrice } = this.pricing.tierPricing.getApplicableTier(totalQuantity);\r\n const subTotal = unitPrice.multiply(totalQuantity);\r\n const totalDiscount = Object.values(this.total.discountBreakdown).reduce((sum, s) => sum.add(s), zero);\r\n const netSubtotal = subTotal.subtract(totalDiscount);\r\n const netUnitPrice = totalQuantity > 0 ? netSubtotal.divide(totalQuantity) : zero;\r\n\r\n // Calculate tax for each applicable rule\r\n const taxBreakdown: Record<string, LineItemTaxBreakdownModel> = {};\r\n let taxTotal = zero;\r\n this.pricing.applicableTaxRule.forEach(taxRule => {\r\n const rate = taxRule.getApplicableTaxRate(netUnitPrice);\r\n const taxPerUnit = taxRule.calculateTax(netUnitPrice);\r\n const taxAmount = taxPerUnit.multiply(totalQuantity).round();\r\n taxBreakdown[taxRule.getTaxRuleId()] = {\r\n rate: rate,\r\n taxableUnitPrice: netUnitPrice,\r\n taxPerUnit: taxPerUnit,\r\n taxAmount: taxAmount,\r\n system: taxRule.getTaxSystem(),\r\n subSystem: taxRule.getTaxSubSystem()\r\n };\r\n taxTotal = taxTotal.add(taxAmount);\r\n });\r\n\r\n const grandTotal = netSubtotal.add(taxTotal);\r\n\r\n this.total = {\r\n quantity: totalQuantity,\r\n unitPrice: unitPrice,\r\n subtotal: subTotal,\r\n discountTotal: totalDiscount,\r\n discountBreakdown: this.total.discountBreakdown,\r\n netUnitPrice: netUnitPrice,\r\n netSubtotal: netSubtotal,\r\n taxTotal: taxTotal,\r\n taxBreakdown: taxBreakdown,\r\n grandTotal: grandTotal\r\n };\r\n }\r\n\r\n /**\r\n * Updates the line item's state.\r\n * @param newState \r\n */\r\n public updateState(newState: LineItemState): void {\r\n if (this.state in LineItemState) {\r\n if (this.state !== newState) {\r\n this.state = newState;\r\n }\r\n } else {\r\n throw new InvalidLineItemStateError(newState);\r\n }\r\n }\r\n\r\n /**\r\n * Resets the line item's properties to their default empty or initial state.\r\n * Useful for clearing out line item data without creating a new instance.\r\n * Recalculates total quantity and price total afterwards (which will be zero).\r\n */\r\n clearLineItem(): void {\r\n const zero = this.pricing.unitPrice.zero()\r\n this.id = '';\r\n this.productKey = '';\r\n this.selectionAttributes = { color: { name: '' } };\r\n this.name = { en: '' };\r\n this.primaryImage = new ImageInfoModel({ sources: { original: '' } });\r\n this.subItems = [];\r\n this.pricing = {\r\n unitPrice: zero,\r\n tierPricing: this.pricing.tierPricing,\r\n taxCategory: this.pricing.taxCategory,\r\n applicableTaxRule: []\r\n }\r\n this.total = {\r\n quantity: 0,\r\n unitPrice: zero,\r\n subtotal: zero,\r\n discountTotal: zero,\r\n discountBreakdown: {},\r\n netUnitPrice: zero,\r\n netSubtotal: zero,\r\n taxTotal: zero,\r\n taxBreakdown: {},\r\n grandTotal: zero\r\n };\r\n }\r\n}\r\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a}from'./chunk-LI5JQ6UC.mjs';import {l,m as m$1,n,o,p}from'./chunk-R5DM7WCD.mjs';var m=class{baseUnitPrice;taxCategory;tiers;constructor(t){let i=new a(t.baseUnitPrice);if(!t.taxCategory)throw new l;let r=(t.tiers??[]).map(e=>({minQuantity:e.minQuantity,unitPrice:new a(e.unitPrice)})).sort((e,n)=>e.minQuantity-n.minQuantity);if(r.some(e=>e.minQuantity<=0))throw new m$1;let y=r.some(e=>e.unitPrice.getCurrency()!==i.getCurrency()),g=r.some((e,n)=>n>0&&e.unitPrice.compareTo(r[n-1].unitPrice)>0),h=r[0]?.unitPrice.compareTo(i)>0;if(y||g||h)throw new n("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=i,this.taxCategory=t.taxCategory,this.tiers=r;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice}))}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}}getApplicableTier(t){if(t<=0)throw new o;for(let i=this.tiers.length-1;i>=0;i--)if(t>=this.tiers[i].minQuantity){let r=this.tiers[i];return {minQuantity:r.minQuantity,unitPrice:r.unitPrice}}throw new p(t)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let t=this.tiers[this.tiers.length-1].unitPrice.getAmount(),i=this.baseUnitPrice.getAmount();return (i-t)/i*100}};export{m as a};//# sourceMappingURL=chunk-FCRJAAPY.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-FCRJAAPY.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/TieredPrice.ts"],"names":["TieredPriceModel","data","baseUnitPrice","PriceModel","InvalidTaxCategoryError","tiers","tier","a","b","t","InvalidMinQuantityError","hasDifferentCurrency","hasIrregularPricing","index","basePriceExceedsFirstTier","InvalidTieredPriceError","quantity","InvalidQuantityError","NoApplicableTierError","lowestTierPrice","basePrice"],"mappings":"yFAiCO,IAAMA,CAAN,CAAA,KAAuB,CAClB,aAAA,CACA,WACA,CAAA,KAAA,CAWV,WAAYC,CAAAA,CAAAA,CAA6B,CACvC,IAAMC,CAAgB,CAAA,IAAIC,EAAWF,CAAK,CAAA,aAAa,CAEvD,CAAA,GAAI,CAACA,CAAAA,CAAK,WACR,CAAA,MAAM,IAAIG,CAAAA,CAGZ,IAAMC,CAAAA,CAAAA,CAASJ,CAAK,CAAA,KAAA,EAAS,EAAC,EAC3B,IAAIK,CAAS,GAAA,CACZ,WAAaA,CAAAA,CAAAA,CAAK,WAClB,CAAA,SAAA,CAAW,IAAIH,CAAAA,CAAWG,CAAK,CAAA,SAAS,CAC1C,CAAA,CAAE,CACD,CAAA,IAAA,CAAK,CAACC,CAAAA,CAAGC,IAAMD,CAAE,CAAA,WAAA,CAAcC,CAAE,CAAA,WAAW,CAG/C,CAAA,GAD8BH,CAAM,CAAA,IAAA,CAAKI,GAAKA,CAAE,CAAA,WAAA,EAAe,CAAC,CAAA,CAE9D,MAAM,IAAIC,
|
|
1
|
+
{"version":3,"sources":["../src/Classes/TieredPrice.ts"],"names":["TieredPriceModel","data","baseUnitPrice","PriceModel","InvalidTaxCategoryError","tiers","tier","a","b","t","InvalidMinQuantityError","hasDifferentCurrency","hasIrregularPricing","index","basePriceExceedsFirstTier","InvalidTieredPriceError","quantity","InvalidQuantityError","NoApplicableTierError","lowestTierPrice","basePrice"],"mappings":"yFAiCO,IAAMA,CAAN,CAAA,KAAuB,CAClB,aAAA,CACA,WACA,CAAA,KAAA,CAWV,WAAYC,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G,CAAkB,CAAA,IAAA,CAAK,MAAM,IAAK,CAAA,KAAA,CAAM,MAAS,CAAA,CAAC,CAAE,CAAA,SAAA,CAAU,SAAU,EAAA,CACxEC,EAAY,IAAK,CAAA,aAAA,CAAc,SAAU,EAAA,CAE/C,OAASA,CAAAA,CAAAA,CAAYD,CAAmBC,EAAAA,CAAAA,CAAa,GACvD,CACF","file":"chunk-FCRJAAPY.mjs","sourcesContent":["import PriceModel, { PriceData } from \"./Price\";\r\nimport {\r\n InvalidTaxCategoryError,\r\n InvalidMinQuantityError,\r\n InvalidTieredPriceError,\r\n InvalidQuantityError,\r\n NoApplicableTierError\r\n} from \"./Error\";\r\n\r\n/**\r\n * Represents a pricing tier based on a minimum purchase quantity.\r\n */\r\nexport type PriceTier = {\r\n minQuantity: number;\r\n unitPrice: PriceModel;\r\n};\r\n\r\n/**\r\n * Represents the attributes required for tiered pricing.\r\n */\r\nexport type TieredPriceAttributes = {\r\n baseUnitPrice: PriceData;\r\n taxCategory: string;\r\n\r\n /** Quantity-based pricing tiers */\r\n tiers: {\r\n minQuantity: number;\r\n unitPrice: PriceData;\r\n }[];\r\n};\r\n\r\nexport type TieredPriceData = TieredPriceAttributes;\r\n\r\nexport class TieredPriceModel {\r\n protected baseUnitPrice: PriceModel;\r\n protected taxCategory: string;\r\n protected tiers: PriceTier[];\r\n\r\n /** Constructor\r\n * Initializes the tiered pricing model with the provided attributes.\r\n * @param data - The tiered pricing attributes.\r\n *\r\n * @throws {Error}\r\n * - If the tax category is not valid\r\n * - If any tier has an invalid minimum quantity or unit price\r\n * - If the base unit price is not valid\r\n */\r\n constructor(data: TieredPriceAttributes) {\r\n const baseUnitPrice = new PriceModel(data.baseUnitPrice);\r\n\r\n if (!data.taxCategory) {\r\n throw new InvalidTaxCategoryError();\r\n }\r\n\r\n const tiers = (data.tiers ?? [])\r\n .map(tier => ({\r\n minQuantity: tier.minQuantity,\r\n unitPrice: new PriceModel(tier.unitPrice),\r\n }))\r\n .sort((a, b) => a.minQuantity - b.minQuantity);\r\n\r\n const hasInvalidMinQuantity = tiers.some(t => t.minQuantity <= 0);\r\n if (hasInvalidMinQuantity) {\r\n throw new InvalidMinQuantityError();\r\n }\r\n\r\n const hasDifferentCurrency = tiers.some(\r\n t => t.unitPrice.getCurrency() !== baseUnitPrice.getCurrency()\r\n );\r\n const hasIrregularPricing = tiers.some(\r\n (tier, index) =>\r\n index > 0 &&\r\n tier.unitPrice.compareTo(tiers[index - 1].unitPrice) > 0\r\n );\r\n const basePriceExceedsFirstTier = tiers[0]?.unitPrice.compareTo(baseUnitPrice) > 0;\r\n\r\n if (hasDifferentCurrency || hasIrregularPricing || basePriceExceedsFirstTier) {\r\n throw new InvalidTieredPriceError(\r\n \"Tiers must share the same currency and must not increase in unit price.\"\r\n );\r\n }\r\n\r\n this.baseUnitPrice = baseUnitPrice;\r\n this.taxCategory = data.taxCategory;\r\n this.tiers = tiers;\r\n }\r\n\r\n /** \r\n * Returns the base unit price \r\n * @returns The base unit price as a PriceModel instance.\r\n */\r\n getBaseUnitPrice(): PriceModel {\r\n return this.baseUnitPrice;\r\n }\r\n\r\n /** \r\n * Returns the tax category \r\n * @returns The tax category as a TaxCategory enum value.\r\n */\r\n getTaxCategory(): string {\r\n return this.taxCategory;\r\n }\r\n\r\n /** \r\n * Returns all pricing tiers sorted by minimum quantity \r\n * @returns An array of PriceTier objects.\r\n */\r\n getTiers(): readonly PriceTier[] {\n return this.tiers.map(tier => ({\n minQuantity: tier.minQuantity,\n unitPrice: tier.unitPrice\n }));\n }\n\r\n getDetails(): TieredPriceData {\r\n return {\r\n baseUnitPrice: this.baseUnitPrice.getDetails(),\r\n taxCategory: this.taxCategory,\r\n tiers: this.tiers.map(tier => ({\r\n minQuantity: tier.minQuantity,\r\n unitPrice: tier.unitPrice.getDetails()\r\n }))\r\n };\r\n }\r\n\r\n /**\r\n * Returns the applicable unit price for a given quantity.\r\n *\r\n * @param quantity - Purchase quantity\r\n * @returns The unit price for the highest applicable tier\r\n *\r\n * @throws {Error}\r\n * - If quantity is less than or equal to zero\r\n * - If quantity does not meet the minimum requirement of any tier\r\n */\r\n getApplicableTier(quantity: number): PriceTier {\n if (quantity <= 0) {\r\n throw new InvalidQuantityError();\r\n }\r\n\r\n for (let i = this.tiers.length - 1; i >= 0; i--) {\r\n if (quantity >= this.tiers[i].minQuantity) {\r\n const tier = this.tiers[i];\n return { minQuantity: tier.minQuantity, unitPrice: tier.unitPrice };\n }\n }\n\r\n throw new NoApplicableTierError(quantity);\r\n }\r\n\r\n /**\r\n * Returns the minimum quantity required to purchase this product.\r\n */\r\n getMinQuantity(): number {\r\n return this.tiers[0]?.minQuantity ?? 1;\r\n }\r\n\r\n /**\r\n * Returns the maximum discount percentage achievable compared to the base unit price.\r\n */\r\n getMaxDiscountPercent(): number {\r\n if (!this.tiers.length) return 0;\r\n\r\n const lowestTierPrice = this.tiers[this.tiers.length - 1].unitPrice.getAmount();\r\n const basePrice = this.baseUnitPrice.getAmount();\r\n\r\n return ((basePrice - lowestTierPrice) / basePrice) * 100;\r\n }\r\n}\r\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {i,h}from'./chunk-QK4XJ3GB.mjs';import {
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {i,h}from'./chunk-QK4XJ3GB.mjs';import {r,s,t,u}from'./chunk-R5DM7WCD.mjs';var m=class r$1{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new r("Amount cannot be negative.");if(!e.currency)throw new s("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(r$1.getPrecisionPlaces(this.currency)));}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}getPreciseAmount(e){return parseFloat(e.toFixed(r$1.getPrecisionPlaces(this.currency)))}compareTo(e){if(r$1.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new t("Cannot compare prices in different currencies.")}else throw new u("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(r$1.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new t("Cannot add prices in different currencies.")}else throw new u("Must be a PriceModel instance.");return new r$1({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(r$1.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new t("Cannot subtract prices in different currencies.")}else throw new u("Must be a PriceModel instance.");return new r$1({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(r$1.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new t("Cannot multiply prices in different currencies.");return new r$1({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new r$1({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new u("Must be a non-negative number.")}divide(e){if(r$1.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new t("Cannot divide prices in different currencies.");return new r$1({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new r$1({amount:this.getPreciseAmount(this.amount/e),currency:this.currency});throw new u("Must be a positive number.")}min(...e){if(e.length===0)throw new u("Must provide at least one PriceModel.");return e.reduce((t$1,n)=>{if(r$1.isPriceModel(n)){if(t$1.getCurrency()!==n.getCurrency())throw new t("Cannot compare prices in different currencies.")}else throw new u("Must be a PriceModel instance.");return t$1.compareTo(n)<0?t$1:n},this)}max(...e){if(e.length===0)throw new u("Must provide at least one PriceModel.");return e.reduce((t$1,n)=>{if(r$1.isPriceModel(n)){if(t$1.getCurrency()!==n.getCurrency())throw new t("Cannot compare prices in different currencies.")}else throw new u("Must be a PriceModel instance.");return t$1.compareTo(n)>0?t$1:n},this)}zero(){return new r$1({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new r$1({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return r$1.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return r$1.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,t,n={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let c=i[t];if(!t||!c)throw new s("Invalid currency code for formatting.");let o=e,a=n.displayAsInteger?0:r$1.getDecimalPlaces(t),h$1={style:n.style??"currency",currency:t,signDisplay:"never",currencyDisplay:n.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};n.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(c,h$1).format(o)}catch(g){return console.error(`Error formatting price for currency "${t}" and locale "${c}":`,g),`${h[t]??t} ${r$1.addThousandSeparators(o.toFixed(a))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static getPrecisionPlaces(e){switch(e){case"INR":default:return 6}}static addThousandSeparators(e){let t=e.split("."),n=t[0],c=t.length>1?"."+t[1]:"";return n.replace(/\B(?=(\d{3})+(?!\d))/g,",")+c}static getRoundedAmount(e,t){if(e<0)throw new r("Amount cannot be negative for rounding.");if(t===void 0)throw new s("Invalid currency code for rounding.");let n=r$1.getDecimalPlaces(t),c=Math.pow(10,n);return Math.round(e*c)/c}};export{m as a};//# sourceMappingURL=chunk-LI5JQ6UC.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-LI5JQ6UC.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/Price.ts"],"names":["PriceModel","_PriceModel","#kind","data","InvalidPriceAmountError","InvalidCurrencyCodeError","obj","amount","priceModel","CurrencyMismatchError","InvalidArgumentError","factor","divisor","priceModels","minPrice","currentPrice","maxPrice","currency","options","locale","CurrencyLocaleMap","valueToFormat","fractionDigits","formattingOptions","error","CurrencySymbolMap","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier"],"mappings":"kFAgBA,IAAqBA,EAArB,MAAqBC,GAAW,CAC9BC,EACU,CAAA,MAAA,CACA,SAQV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uBAAyB,CAAA,GAAG,EAC/CC,CAC5B,CAWA,OAAO,gBAAiBtB,CAAAA,CAAAA,CAAgBU,EAAgC,CACtE,GAAIV,EAAS,CACX,CAAA,MAAM,IAAIH,CAAwB,CAAA,yCAAyC,EAG7E,GAAIa,CAAAA,GAAa,OACf,MAAM,IAAIZ,EAAyB,qCAAqC,CAAA,CAG1E,IAAMyB,CAAgB7B,CAAAA,GAAAA,CAAW,iBAAiBgB,CAAQ,CAAA,CACpDc,EAAa,IAAK,CAAA,GAAA,CAAI,GAAID,CAAa,CAAA,CAG7C,OAFqB,IAAK,CAAA,KAAA,CAAMvB,EAASwB,CAAU,CAAA,CAAIA,CAGzD,CACF","file":"chunk-3UMWQ7S7.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.currency = data.currency;\r\n this.amount = parseFloat(data.amount.toFixed(PriceModel.getPrecisionPlaces(this.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 public getPreciseAmount(amount: number): number {\r\n return parseFloat(amount.toFixed(PriceModel.getPrecisionPlaces(this.currency)));\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.getPreciseAmount(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.getPreciseAmount((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.getPreciseAmount(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.getPreciseAmount(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.getPreciseAmount(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.getPreciseAmount(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.getPreciseAmount(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 }, this);\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 }, this);\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 /**\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 * Helper method to determine standard precision places for a currency.\r\n * @param currency - The currency code.\r\n * @return The number of precision places (0, 2, or 3 based on common rules).\r\n */ \r\n private static getPrecisionPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case OperationalCountryCurrency.INR:\r\n default:\r\n return 6;\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}"]}
|
|
1
|
+
{"version":3,"sources":["../src/Classes/Price.ts"],"names":["PriceModel","_PriceModel","#kind","data","InvalidPriceAmountError","InvalidCurrencyCodeError","obj","amount","priceModel","CurrencyMismatchError","InvalidArgumentError","factor","divisor","priceModels","minPrice","currentPrice","maxPrice","currency","options","locale","CurrencyLocaleMap","valueToFormat","fractionDigits","formattingOptions","error","CurrencySymbolMap","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier"],"mappings":"kFAgBA,IAAqBA,EAArB,MAAqBC,GAAW,CAC9BC,EACU,CAAA,MAAA,CACA,SAQV,WAAYC,CAAAA,CAAAA,CAAuB,CAEjC,GADA,IAAA,CAAKD,GAAQ,YACTC,CAAAA,CAAAA,CAAK,OAAS,CAChB,CAAA,MAAM,IAAIC,CAAwB,CAAA,4BAA4B,CAGhE,CAAA,GAAI,CAACD,CAAK,CAAA,QAAA,CACR,MAAM,IAAIE,CAAAA,CAAyB,4BAA4B,CAGjE,CAAA,IAAA,CAAK,SAAWF,CAAK,CAAA,QAAA,CACrB,KAAK,MAAS,CAAA,UAAA,CAAWA,EAAK,MAAO,CAAA,OAAA,CAAQF,IAAW,kBAAmB,CAAA,IAAA,CAAK,QAAQ,CAAC,CAAC,EAC5F,CAEA,IAAI,IAAO,EAAA,CACT,O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-LI5JQ6UC.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.currency = data.currency;\r\n this.amount = parseFloat(data.amount.toFixed(PriceModel.getPrecisionPlaces(this.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 public getPreciseAmount(amount: number): number {\r\n return parseFloat(amount.toFixed(PriceModel.getPrecisionPlaces(this.currency)));\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.getPreciseAmount(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.getPreciseAmount((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.getPreciseAmount(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.getPreciseAmount(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.getPreciseAmount(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.getPreciseAmount(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.getPreciseAmount(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 }, this);\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 }, this);\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 /**\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 * Helper method to determine standard precision places for a currency.\r\n * @param currency - The currency code.\r\n * @return The number of precision places (0, 2, or 3 based on common rules).\r\n */ \r\n private static getPrecisionPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case OperationalCountryCurrency.INR:\r\n default:\r\n return 6;\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}"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-QGIQ3MH6.mjs';import {a as a$1}from'./chunk-LI5JQ6UC.mjs';import {e}from'./chunk-QK4XJ3GB.mjs';import {u}from'./chunk-R5DM7WCD.mjs';import {b as b$1}from'./chunk-UXZBULDS.mjs';var y=(t=>(t.COUPON="coupon",t.AUTOMATIC="automatic",t))(y||{}),M=(t=>(t.FLAT="flat",t.PERCENTAGE="percentage",t))(M||{}),b=(t=>(t.SHIPPING="SHIPPING",t.CUSTOMER="CUSTOMER",t))(b||{}),P=(t=>(t.ALL="all",t.FTB="ftb",t))(P||{}),p=class extends b$1{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(e,t=new Date){if(super(e,t),this.couponCode=e.couponCode,this.name=a.deepClone(e.name),this.description=a.deepClone(e.description),this.type=e.type,this.customerId=e.customerId,this.validFrom=e.validFrom&&Date.parse(e.validFrom)?new Date(e.validFrom).toISOString():t.toISOString(),this.validTo=e.validTo&&Date.parse(e.validTo)?new Date(e.validTo).toISOString():t.toISOString(),this.minCartValue=Object.keys(e.minCartValue).reduce((o,i)=>{let r=e.minCartValue[i];return r&&(o[i]=new a$1(r)),o},{}),this.maxCartDiscount=Object.keys(e.maxCartDiscount).reduce((o,i)=>{let r=e.maxCartDiscount[i];return r&&(o[i]=new a$1(r)),o},{}),this.discountMethod=e.discountMethod,this.percentageValue=e.percentageValue??0,this.percentageValue>100)throw new u("Percentage value cannot be greater than 100");this.applicableTo=e.applicableTo,this.category=e.category;}getCode(){return this.couponCode}getName(e$1){return e$1?this.name[e$1]??this.name[e[e$1]]??this.name.en:{...this.name}}getDescription(e$1){return e$1?this.description[e$1]??this.description[e[e$1]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(e){return e?this.minCartValue[e]:{...this.minCartValue}}getMaxCartDiscount(e){return e?this.maxCartDiscount[e]:{...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:Object.keys(this.getMinCartValue()).reduce((e,t)=>{let o=this.getMinCartValue(t);return o&&(e[t]=o.getDetails()),e},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((e,t)=>{let o=this.getMaxCartDiscount(t);return o&&(e[t]=o.getDetails()),e},{}),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(e){return this.applicableTo==="all"||this.applicableTo==="ftb"&&e}calculateApplicableCouponDiscount(e,t,o,i,r=!0){let n=new a$1({amount:0,currency:i}),s;if(r&&!this.isActive())return n;let C=this.getMinCartValue(o),c=this.getMaxCartDiscount(o);if(!C||C.compareTo(e)>0||!c)return n;let h=this.getCategory(),D=this.getDiscountMethod(),u=h==="SHIPPING"?t:e;if(u.getAmount()<=0)return n;switch(D){case"flat":let T=c;s=u.min(T);break;case"percentage":s=u.multiply(this.getPercentageValue()/100).round();break;default:return n}return s.min(c)}};export{y as a,M as b,b as c,P as d,p as e};//# sourceMappingURL=chunk-PWWKQNF7.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-PWWKQNF7.mjs.map
|