b23-lib 3.2.2 → 3.2.3

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.
@@ -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,CACf,IAAK,CAAA,UAAA,CAAaA,CAAK,CAAA,UAAA,CACvB,IAAK,CAAA,aAAA,CAAgBA,CAAK,CAAA,aAAA,CAC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A,CAAAA,CAAgB,OAAQ,EAAC,CAAI1C,CAAAA,CAAAA,EAE9D,CACF,CACF","file":"chunk-MJGCYQ53.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,CACpB,IAAK,CAAA,QAAA,CAAWA,CAAK,CAAA,QAAA,CACrB,IAAK,CAAA,MAAA,CAASA,CAAK,CAAA,MAAA,CACnB,IAAK,C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A,CAAK,OAAS,CAAA,IAAA,CAAK,QAAQ,CAAA,CAAE,GAAI,CAAA,IAAA,CAAK,KAAM,CAAA,eAAe,CACjL4C,CAAAA,CAAAA,CAAiBH,CAAU,CAAA,iCAAA,CAAkCzC,CAAqB,CAAA,IAAA,CAAK,KAAM,CAAA,eAAA,CAAiB,IAAK,CAAA,OAAA,CAAS,IAAK,CAAA,QAAQ,CAAE,CAAA,GAAA,CAAI,IAAK,CAAA,KAAA,CAAM,eAAe,CAE/K,CAAA,OAAI2C,CAAmB,CAAA,SAAA,CAAUC,CAAc,CAAA,GAAM,CAC5CF,CAAAA,CAAAA,CAAc,OAAQ,EAAA,GAAM,QAAoBA,CAAAA,CAAAA,CAAgBD,CAElEE,CAAAA,CAAAA,CAAmB,SAAUC,CAAAA,CAAc,CAAI,CAAA,CAAA,CAAIF,CAAgBD,CAAAA,CAC5E,CAAC,CAAA,CAEK3C,CAAc0C,CAAAA,CAAAA,CAAgB,iCAAkCxC,CAAAA,CAAAA,CAAqB,IAAK,CAAA,KAAA,CAAM,eAAiB,CAAA,IAAA,CAAK,OAAS,CAAA,IAAA,CAAK,QAAQ,CAAE,CAAA,GAAA,CAAI,IAAK,CAAA,KAAA,CAAM,eAAe,CAAA,CAC9KF,CAAY,CAAA,SAAA,EAAc,CAAA,CAAA,GAC5B,IAAK,CAAA,OAAA,CAAQ,IAAK0C,CAAAA,CAAe,CACjC,CAAA,IAAA,CAAK,KAAM,CAAA,aAAA,CAAgB,IAAK,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-B5JKMVLT.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,2 +1,2 @@
1
- import {a as a$2}from'./chunk-SOZHGHMY.mjs';import {a as a$3}from'./chunk-QGIQ3MH6.mjs';import {a as a$1}from'./chunk-LI5JQ6UC.mjs';import {e}from'./chunk-QK4XJ3GB.mjs';import {w,k,x}from'./chunk-R5DM7WCD.mjs';import {a}from'./chunk-UXZBULDS.mjs';var I=class extends a{id;name;type;category;impact;pricing;lineItemId;total;constructor(t){if(super(t),this.id=t.id,this.name=t.name,this.type=t.type,this.category=t.category,this.impact=t.impact,this.lineItemId=t.lineItemId,this.pricing={baseChargeAmount:new a$1(t.pricing.baseChargeAmount),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(e=>new a$2(e))},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new w("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={chargeAmount:new a$1(t.total.chargeAmount),discountTotal:new a$1(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([e,a])=>[e,new a$1(a)])),netChargeAmount:new a$1(t.total.netChargeAmount),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([e,a])=>[e,{rate:a.rate,taxableAmount:new a$1(a.taxableAmount),taxAmount:new a$1(a.taxAmount),system:a.system,subSystem:a.subSystem}])),taxTotal:new a$1(t.total.taxTotal),grandTotal:new a$1(t.total.grandTotal)};}getId(){return this.id}getName(t){return t?a$3.deepClone(this.name[t]??this.name[e[t]]??this.name.en):a$3.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getPricing(){return {baseChargeAmount:this.pricing.baseChargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {chargeAmount:this.total.chargeAmount,discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},netChargeAmount:this.total.netChargeAmount,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableAmount:e.taxableAmount,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(t){if(this.type==="ADJUSTMENT"&&t.length>0)throw new w("Adjustment charges cannot apply tax rules.");t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new k}),this.validateTaxRules(t),this.pricing.applicableTaxRule=t,this.calculateTotals();}validateTaxRules(t){if(this.impact==="SUBTRACT"&&t.some(a=>a.getRate()>0))throw new x("Subtractive charges cannot have positive tax rates.");let e=new Set;for(let a=0;a<t.length;a++){let g=t[a].getTaxRuleId();if(e.has(g))throw new x("Duplicate tax rule ID found: "+g);e.add(g);for(let T=a+1;T<t.length;T++){let u=t[a],s=t[T],d=u.getMinPrice(),p=u.getMaxPrice(),n=u.getExcludeMin(),m=u.getExcludeMax(),b=s.getMinPrice(),l=s.getMaxPrice(),h=s.getExcludeMin(),A=s.getExcludeMax(),r=(()=>{if(!p)return !1;let c=p.compareTo(b);return c<0||c===0&&(m||h)})(),i=(()=>{if(!l)return !1;let c=l.compareTo(d);return c<0||c===0&&(A||n)})();if(!(r||i)&&!(d.compareTo(b)===0&&n===h&&m===A&&(!p&&!l||p&&l&&p.compareTo(l)===0)))throw new x(`Overlapping rules found: [${u.getTaxRuleId()}: ${n?"(":"["}${d.getAmount()}-${p?.getAmount()??"Infinity"}${m?")":"]"}] and [${s.getTaxRuleId()}: ${h?"(":"["}${b.getAmount()}-${l?.getAmount()??"Infinity"}${A?")":"]"}]`)}}}updateDiscounts(t){let e={};t.forEach(a=>{e[a.coupon.getCode()]=a.amount;}),this.total.discountBreakdown=e,this.calculateTotals();}calculateTotals(){let t=this.pricing.baseChargeAmount.zero(),e=this.pricing.baseChargeAmount,a=Object.values(this.total.discountBreakdown).reduce((r,i)=>r.add(i),t),g=e.subtract(a),T={},u=this.pricing.applicableTaxRule.reduce((r,i)=>r+i.getApplicableTaxRate(g),0);if(u<=0){this.total={chargeAmount:e,discountTotal:a,discountBreakdown:this.total.discountBreakdown,netChargeAmount:g,taxTotal:t,taxBreakdown:{},grandTotal:g};return}let s=e.getCurrency(),d=e.getAmount(),p=1e3,n=a$1.getRoundedAmount(d/(1+u),s),m=n,b=Number.POSITIVE_INFINITY;for(let r=0;r<p;r++){let i=new a$1({amount:n,currency:s}),c=this.pricing.applicableTaxRule.sort((x,C)=>C.getApplicableTaxRate(i)-x.getApplicableTaxRate(i)).map(x=>a$1.getRoundedAmount(n*x.getApplicableTaxRate(i),s)).reduce((x,C)=>x+C,0),y=n+c-d,k=this.pricing.applicableTaxRule.reduce((x,C)=>x+C.getApplicableTaxRate(i),0);if(Math.abs(y)<Math.abs(b)&&(b=y,m=n),y===0||(n=n-y/(1+k),n<0||n>d))break}let l=new a$1({amount:m,currency:s}),h=t;this.pricing.applicableTaxRule.sort((r,i)=>i.getApplicableTaxRate(l)-r.getApplicableTaxRate(l)).forEach(r=>{let i=r.getApplicableTaxRate(l),f=a$1.getRoundedAmount(m*i,s),c=new a$1({amount:f,currency:s});T[r.getTaxRuleId()]={rate:i,taxableAmount:l,taxAmount:c,system:r.getTaxSystem(),subSystem:r.getTaxSubSystem()},h=h.add(c);});let A=g;this.total={chargeAmount:e,discountTotal:a,discountBreakdown:this.total.discountBreakdown,netChargeAmount:g,taxBreakdown:T,taxTotal:h,grandTotal:A};}getDetails(){return {id:this.id,name:a$3.deepClone(this.name),type:this.type,category:this.category,pricing:{baseChargeAmount:this.pricing.baseChargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(e=>e.getDetails())},impact:this.impact,lineItemId:this.lineItemId,total:{chargeAmount:this.total.chargeAmount.getDetails(),discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([e,a])=>[e,a.getDetails()])),netChargeAmount:this.total.netChargeAmount.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,a])=>[e,{rate:a.rate,taxableAmount:a.taxableAmount.getDetails(),taxAmount:a.taxAmount.getDetails(),system:a.system,subSystem:a.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};export{I as a};//# sourceMappingURL=chunk-XJPFHEW3.mjs.map
2
- //# sourceMappingURL=chunk-XJPFHEW3.mjs.map
1
+ import {a as a$2}from'./chunk-SOZHGHMY.mjs';import {a as a$3}from'./chunk-MHLRJ4IJ.mjs';import {a as a$1}from'./chunk-LI5JQ6UC.mjs';import {e}from'./chunk-QK4XJ3GB.mjs';import {w,k,x}from'./chunk-R5DM7WCD.mjs';import {a}from'./chunk-UXZBULDS.mjs';var I=class extends a{id;name;type;category;impact;pricing;lineItemId;total;constructor(t){if(super(t),this.id=t.id,this.name=t.name,this.type=t.type,this.category=t.category,this.impact=t.impact,this.lineItemId=t.lineItemId,this.pricing={baseChargeAmount:new a$1(t.pricing.baseChargeAmount),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(e=>new a$2(e))},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new w("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={chargeAmount:new a$1(t.total.chargeAmount),discountTotal:new a$1(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([e,a])=>[e,new a$1(a)])),netChargeAmount:new a$1(t.total.netChargeAmount),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([e,a])=>[e,{rate:a.rate,taxableAmount:new a$1(a.taxableAmount),taxAmount:new a$1(a.taxAmount),system:a.system,subSystem:a.subSystem}])),taxTotal:new a$1(t.total.taxTotal),grandTotal:new a$1(t.total.grandTotal)};}getId(){return this.id}getName(t){return t?a$3.deepClone(this.name[t]??this.name[e[t]]??this.name.en):a$3.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getPricing(){return {baseChargeAmount:this.pricing.baseChargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {chargeAmount:this.total.chargeAmount,discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},netChargeAmount:this.total.netChargeAmount,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableAmount:e.taxableAmount,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(t){if(this.type==="ADJUSTMENT"&&t.length>0)throw new w("Adjustment charges cannot apply tax rules.");t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new k}),this.validateTaxRules(t),this.pricing.applicableTaxRule=t,this.calculateTotals();}validateTaxRules(t){if(this.impact==="SUBTRACT"&&t.some(a=>a.getRate()>0))throw new x("Subtractive charges cannot have positive tax rates.");let e=new Set;for(let a=0;a<t.length;a++){let g=t[a].getTaxRuleId();if(e.has(g))throw new x("Duplicate tax rule ID found: "+g);e.add(g);for(let T=a+1;T<t.length;T++){let u=t[a],s=t[T],d=u.getMinPrice(),p=u.getMaxPrice(),n=u.getExcludeMin(),m=u.getExcludeMax(),b=s.getMinPrice(),l=s.getMaxPrice(),h=s.getExcludeMin(),A=s.getExcludeMax(),r=(()=>{if(!p)return !1;let c=p.compareTo(b);return c<0||c===0&&(m||h)})(),i=(()=>{if(!l)return !1;let c=l.compareTo(d);return c<0||c===0&&(A||n)})();if(!(r||i)&&!(d.compareTo(b)===0&&n===h&&m===A&&(!p&&!l||p&&l&&p.compareTo(l)===0)))throw new x(`Overlapping rules found: [${u.getTaxRuleId()}: ${n?"(":"["}${d.getAmount()}-${p?.getAmount()??"Infinity"}${m?")":"]"}] and [${s.getTaxRuleId()}: ${h?"(":"["}${b.getAmount()}-${l?.getAmount()??"Infinity"}${A?")":"]"}]`)}}}updateDiscounts(t){let e={};t.forEach(a=>{e[a.coupon.getCode()]=a.amount;}),this.total.discountBreakdown=e,this.calculateTotals();}calculateTotals(){let t=this.pricing.baseChargeAmount.zero(),e=this.pricing.baseChargeAmount,a=Object.values(this.total.discountBreakdown).reduce((r,i)=>r.add(i),t),g=e.subtract(a),T={},u=this.pricing.applicableTaxRule.reduce((r,i)=>r+i.getApplicableTaxRate(g),0);if(u<=0){this.total={chargeAmount:e,discountTotal:a,discountBreakdown:this.total.discountBreakdown,netChargeAmount:g,taxTotal:t,taxBreakdown:{},grandTotal:g};return}let s=e.getCurrency(),d=e.getAmount(),p=1e3,n=a$1.getRoundedAmount(d/(1+u),s),m=n,b=Number.POSITIVE_INFINITY;for(let r=0;r<p;r++){let i=new a$1({amount:n,currency:s}),c=this.pricing.applicableTaxRule.sort((x,C)=>C.getApplicableTaxRate(i)-x.getApplicableTaxRate(i)).map(x=>a$1.getRoundedAmount(n*x.getApplicableTaxRate(i),s)).reduce((x,C)=>x+C,0),y=n+c-d,k=this.pricing.applicableTaxRule.reduce((x,C)=>x+C.getApplicableTaxRate(i),0);if(Math.abs(y)<Math.abs(b)&&(b=y,m=n),y===0||(n=n-y/(1+k),n<0||n>d))break}let l=new a$1({amount:m,currency:s}),h=t;this.pricing.applicableTaxRule.sort((r,i)=>i.getApplicableTaxRate(l)-r.getApplicableTaxRate(l)).forEach(r=>{let i=r.getApplicableTaxRate(l),f=a$1.getRoundedAmount(m*i,s),c=new a$1({amount:f,currency:s});T[r.getTaxRuleId()]={rate:i,taxableAmount:l,taxAmount:c,system:r.getTaxSystem(),subSystem:r.getTaxSubSystem()},h=h.add(c);});let A=g;this.total={chargeAmount:e,discountTotal:a,discountBreakdown:this.total.discountBreakdown,netChargeAmount:g,taxBreakdown:T,taxTotal:h,grandTotal:A};}getDetails(){return {id:this.id,name:a$3.deepClone(this.name),type:this.type,category:this.category,pricing:{baseChargeAmount:this.pricing.baseChargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(e=>e.getDetails())},impact:this.impact,lineItemId:this.lineItemId,total:{chargeAmount:this.total.chargeAmount.getDetails(),discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([e,a])=>[e,a.getDetails()])),netChargeAmount:this.total.netChargeAmount.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,a])=>[e,{rate:a.rate,taxableAmount:a.taxableAmount.getDetails(),taxAmount:a.taxAmount.getDetails(),system:a.system,subSystem:a.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};export{I as a};//# sourceMappingURL=chunk-BSDPFVRK.mjs.map
2
+ //# sourceMappingURL=chunk-BSDPFVRK.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Classes/Charge.ts"],"names":["ChargeModel","CustomFieldModel","data","PriceModel","r","TaxRuleModel","InvalidChargeError","discountId","discount","taxRuleId","taxBreakdown","locale","Utils_default","LocaleLanguageMap","key","value","taxRules","taxRule","InvalidTaxRuleError","InvalidChargeTaxRuleError","uniqueTaxRule","i","currentTaxRuleId","j","r1","r2","r1Min","r1Max","r1ExcludeMin","r1ExcludeMax","r2Min","r2Max","r2ExcludeMin","r2ExcludeMax","r1EndsBeforeR2Starts","compare","r2EndsBeforeR1Starts","appliedDiscounts","chargeDiscounts","zero","baseChargeAmount","totalDiscount","sum","s","netChargeAmount","totalRate","currency","grossValue","maxIterations","baseValue","bestBaseValue","bestDiff","currentTaxableBase","taxSum","a","b","rule","v","diff","currentTotalRate","taxableBase","distributedTax","rate","taxAmountValue","taxAmount","grandTotal","k"],"mappings":"uPA4FA,IAAqBA,CAArB,CAAA,cAAyCC,CAAiB,CAC/C,EACA,CAAA,IAAA,CACA,IACA,CAAA,QAAA,CACA,MACA,CAAA,OAAA,CACA,UACA,CAAA,KAAA,CAEV,YAAYC,CAAwB,CAAA,CAenC,GAdA,KAAA,CAAMA,CAAI,CAAA,CACV,IAAK,CAAA,EAAA,CAAKA,CAAK,CAAA,EAAA,CACf,IAAK,CAAA,IA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A,CAAiB,IAAK,CAAA,KAAA,CAAM,eAAgB,CAAA,UAAA,EAC5C,CAAA,YAAA,CAAc,MAAO,CAAA,WAAA,CAAY,MAAO,CAAA,OAAA,CAAQ,KAAK,KAAM,CAAA,YAAY,CAAE,CAAA,GAAA,CAAI,CAAC,CAACS,CAAGT,CAAAA,CAAC,IAAM,CAACS,CAAAA,CAAG,CAC5F,IAAA,CAAMT,CAAE,CAAA,IAAA,CACR,aAAeA,CAAAA,CAAAA,CAAE,cAAc,UAAW,EAAA,CAC1C,SAAWA,CAAAA,CAAAA,CAAE,SAAU,CAAA,UAAA,EACvB,CAAA,MAAA,CAAQA,CAAE,CAAA,MAAA,CACV,SAAWA,CAAAA,CAAAA,CAAE,SACd,CAAC,CAAC,CAAC,EACH,QAAU,CAAA,IAAA,CAAK,KAAM,CAAA,QAAA,CAAS,UAAW,EAAA,CACzC,UAAY,CAAA,IAAA,CAAK,MAAM,UAAW,CAAA,UAAA,EACnC,CAAA,CACA,YAAc,CAAA,IAAA,CAAK,kBAAmB,EACvC,CAED,CACD","file":"chunk-XJPFHEW3.mjs","sourcesContent":["import { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\nimport Utils from \"../Utils\";\r\nimport { LocaleCode, LocalizedString } from \"./Common\";\r\nimport { ChargeImpact, ChargeType, LocaleLanguageMap, TaxSystem } from \"./Enum\";\r\nimport { InvalidChargeTaxRuleError, InvalidChargeError, InvalidTaxRuleError } from \"./Error\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport { TaxRuleData, TaxRuleModel } from \"./TaxRule\";\r\nimport CouponModel from \"./Coupon\";\r\n\r\nexport type ChargePricing = {\r\n /** Tax-inclusive original charge amount before any discounts. Always non-negative. */\r\n baseChargeAmount: PriceData;\r\n /** Tax category of the charge. */\r\n taxCategory: string;\r\n /** Tax rules applicable to the charge. */\r\n applicableTaxRule: TaxRuleData[];\r\n};\r\n\r\nexport type ChargePricingModel = {\r\n /** Tax-inclusive original charge amount before any discounts. Always non-negative. */\r\n baseChargeAmount: PriceModel;\r\n /** Tax category of the charge. */\r\n taxCategory: string;\r\n /** Tax rules applicable to the charge. */\r\n applicableTaxRule: TaxRuleModel[];\r\n};\r\n\r\nexport type ChargeTaxBreakdown = {\r\n /** Tax rate: e.g., 0.09 for 9% */\r\n rate: number;\r\n /** Reverse-calculated pre-tax base from the netChargeAmount (post-discount) */\r\n taxableAmount: PriceData;\r\n /** Tax portion for this rule (netChargeAmount - taxableAmount) */\r\n taxAmount: PriceData;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type ChargeTaxBreakdownModel = {\r\n rate: number;\r\n taxableAmount: PriceModel;\r\n taxAmount: PriceModel;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type ChargeTotals = {\r\n /** Tax-inclusive original charge amount before discounts (copied from pricing) */\r\n chargeAmount: PriceData;\r\n /** Coupon code -> discount amount mapping */\r\n discountBreakdown: Record<string, PriceData>;\r\n /** Sum of all discounts */\r\n discountTotal: PriceData;\r\n /** chargeAmount - totalDiscount → final tax-inclusive payable amount after discounts */\r\n netChargeAmount: PriceData;\r\n /** Sum of all taxAmount values */\r\n taxTotal: PriceData;\r\n /** Tax breakdown per rule/category (reverse-calculated from netChargeAmount) */\r\n taxBreakdown: Record<string, ChargeTaxBreakdown>;\r\n /** Final payable/contribution amount. Equals netChargeAmount (tax-inclusive after discounts). */\r\n grandTotal: PriceData;\r\n};\r\n\r\nexport type ChargeTotalsModel = {\r\n chargeAmount: PriceModel;\r\n discountTotal: PriceModel;\r\n discountBreakdown: Record<string, PriceModel>;\r\n netChargeAmount: PriceModel;\r\n taxTotal: PriceModel;\r\n taxBreakdown: Record<string, ChargeTaxBreakdownModel>;\r\n grandTotal: PriceModel; // Equals netChargeAmount\r\n};\r\n\r\nexport type ChargeAttributes = CustomFieldAttributes & {\r\n id: string;\r\n name: LocalizedString;\r\n type: ChargeType;\r\n category: string;\r\n impact: ChargeImpact; // ADD or SUBTRACT\r\n pricing: ChargePricing;\r\n lineItemId?: string;\r\n total: ChargeTotals;\r\n};\r\n\r\nexport type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId'> & {\r\n\tlineItemId?: string;\r\n};\r\n\r\n/**\r\n * Represents an additional charge (or discount if amount is negative) in a shopping container.\r\n * Supports its own tax rules.\r\n */\r\nexport default class ChargeModel extends CustomFieldModel {\r\n\tprotected id: string;\r\n\tprotected name: LocalizedString;\r\n\tprotected type: ChargeType;\r\n\tprotected category: string;\r\n\tprotected impact: ChargeImpact;\r\n\tprotected pricing: ChargePricingModel;\r\n\tprotected lineItemId?: string;\r\n\tprotected total: ChargeTotalsModel;\r\n\r\n\tconstructor(data: ChargeAttributes) {\r\n\t\tsuper(data);\r\n\t\tthis.id = data.id;\r\n\t\tthis.name = data.name;\r\n\t\tthis.type = data.type;\r\n\t\tthis.category = data.category;\r\n\t\tthis.impact = data.impact;\r\n\t\tthis.lineItemId = data.lineItemId;\r\n\t\tthis.pricing = {\r\n\t\t\tbaseChargeAmount: new PriceModel(data.pricing.baseChargeAmount),\r\n\t\t\ttaxCategory: data.pricing.taxCategory,\r\n\t\t\tapplicableTaxRule: data.pricing.applicableTaxRule.map(r => new TaxRuleModel(r))\r\n\t\t};\r\n\r\n\t\tthis.validateTaxRules(this.pricing.applicableTaxRule);\r\n\t\tif(this.impact === ChargeImpact.SUBTRACT && this.type !== ChargeType.ADJUSTMENT) {\r\n\t\t\tthrow new InvalidChargeError('SUBTRACT impact is only allowed for ADJUSTMENT charge');\r\n\t\t}\r\n\r\n\t\tthis.total = {\r\n\t\t\tchargeAmount: new PriceModel(data.total.chargeAmount),\r\n\t\t\tdiscountTotal: new PriceModel(data.total.discountTotal),\r\n\t\t\tdiscountBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(data.total.discountBreakdown).map(([discountId, discount]) => [\r\n\t\t\t\t\tdiscountId,\r\n\t\t\t\t\tnew PriceModel(discount)\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\tnetChargeAmount: new PriceModel(data.total.netChargeAmount),\r\n\t\t\ttaxBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(data.total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n\t\t\t\t\ttaxRuleId,\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\trate: taxBreakdown.rate,\r\n\t\t\t\t\t\ttaxableAmount: new PriceModel(taxBreakdown.taxableAmount),\r\n\t\t\t\t\t\ttaxAmount: new PriceModel(taxBreakdown.taxAmount),\r\n\t\t\t\t\t\tsystem: taxBreakdown.system,\r\n\t\t\t\t\t\tsubSystem: taxBreakdown.subSystem\r\n\t\t\t\t\t}\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\ttaxTotal: new PriceModel(data.total.taxTotal),\r\n\t\t\tgrandTotal: new PriceModel(data.total.grandTotal),\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the unique identifier of the charge.\r\n\t * @returns \r\n\t */\r\n\tpublic getId(): string { return this.id; }\r\n\r\n\r\n\t/**\r\n\t * Gets the full localized product name object.\r\n\t * @returns A copy of the LocalizedString object for the name.\r\n\t */\r\n\tgetName(): LocalizedString\r\n\t/**\r\n\t * Gets the product name for a specific locale, falling back to English ('en').\r\n\t * @param locale - The desired locale code.\r\n\t * @returns The name string for the specified locale.\r\n\t */\r\n\tgetName(locale: LocaleCode): string\r\n\tgetName(locale?: LocaleCode): LocalizedString | string {\r\n\t\tif (locale) {\r\n\t\t\treturn Utils.deepClone(this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en);\r\n\t\t} else {\r\n\t\t\treturn Utils.deepClone(this.name);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the charge category.\r\n\t * @returns The category string.\r\n\t */\r\n\tpublic getCategory(): string { return this.category; }\r\n\r\n\t/**\r\n\t * Gets the charge type.\r\n\t * @returns The charge type enum value.\r\n\t */\r\n\tpublic getType(): ChargeType { return this.type; }\r\n\t/**\r\n\t * Gets the charge impact (add or subtract).\r\n\t * @returns The charge impact.\r\n\t */\r\n\tpublic getImpact(): ChargeImpact { return this.impact; }\r\n\r\n\t/**\r\n\t * Gets the related line item id, if any.\r\n\t * @returns The line item id or undefined.\r\n\t */\r\n\tpublic getLineItemId(): string | undefined { return this.lineItemId; }\r\n\r\n\t/**\r\n\t * Gets the pricing details (models) for this charge.\r\n\t * @returns Pricing details including price, tax category, and tax rules.\r\n\t */\r\n\tpublic getPricing(): ChargePricingModel {\r\n\t\treturn {\r\n\t\t\tbaseChargeAmount: this.pricing.baseChargeAmount,\r\n\t\t\ttaxCategory: this.pricing.taxCategory,\r\n\t\t\tapplicableTaxRule: [...this.pricing.applicableTaxRule]\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the computed totals for this charge.\r\n\t * @returns Totals including discounts, taxes, and grand total.\r\n\t */\r\n\tpublic getTotal(): ChargeTotalsModel {\r\n\t\treturn {\r\n\t\t\tchargeAmount: this.total.chargeAmount,\r\n\t\t\tdiscountTotal: this.total.discountTotal,\r\n\t\t\tdiscountBreakdown: { ...this.total.discountBreakdown },\r\n\t\t\tnetChargeAmount: this.total.netChargeAmount,\r\n\t\t\ttaxTotal: this.total.taxTotal,\r\n\t\t\ttaxBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(this.total.taxBreakdown).map(([key, value]) => [\r\n\t\t\t\t\tkey,\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\trate: value.rate,\r\n\t\t\t\t\t\ttaxableAmount: value.taxableAmount,\r\n\t\t\t\t\t\ttaxAmount: value.taxAmount,\r\n\t\t\t\t\t\tsystem: value.system,\r\n\t\t\t\t\t\tsubSystem: value.subSystem\r\n\t\t\t\t\t}\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\tgrandTotal: this.total.grandTotal,\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the applicable tax rules for this charge.\r\n\t * @returns A list of tax rules.\r\n\t */\r\n\tpublic getApplicableTaxRules(): TaxRuleModel[] {\r\n\t\treturn [...this.pricing.applicableTaxRule];\r\n\t}\r\n\r\n\t/**\r\n\t * Updates the tax rule for this line item and recalculates totals.\r\n\t * @param taxRule - The new tax rule to apply.\r\n\t * @throws {Error} If the tax rule category does not match the item's tax category.\r\n\t */\r\n\tpublic updateTax(taxRules: TaxRuleModel[]): void {\r\n\t\tif (this.type === ChargeType.ADJUSTMENT && taxRules.length > 0) {\r\n\t\t\tthrow new InvalidChargeError(\"Adjustment charges cannot apply tax rules.\");\r\n\t\t}\r\n\t\ttaxRules.forEach(taxRule => {\r\n\t\t\tif (!taxRule.appliesTo(this.pricing.taxCategory, taxRule.getCountry())) {\r\n\t\t\t\tthrow new InvalidTaxRuleError();\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\t// Remove the old taxableUnitPrice calculation - no longer needed\r\n\t\tthis.validateTaxRules(taxRules);\r\n\t\tthis.pricing.applicableTaxRule = taxRules;\r\n\t\tthis.calculateTotals();\r\n\t}\r\n\r\n\t/**\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 {InvalidChargeTaxRuleError} If any rules have positive tax rates with SUBTRACT impact or if duplicate rule IDs are found.\r\n\t * @throws {InvalidChargeTaxRuleError} Duplicate tax rule IDs will results in error.\r\n\t * @throws {CoincidingTaxBracketError} If any overlapping rules are found.\r\n\t */\r\n\tprivate validateTaxRules(taxRules: TaxRuleModel[]): void {\r\n\t\tif(this.impact === ChargeImpact.SUBTRACT) {\r\n\t\t\tif(taxRules.some(taxRule => taxRule.getRate() > 0)) {\r\n\t\t\t\tthrow new InvalidChargeTaxRuleError(\"Subtractive charges cannot have positive tax rates.\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst uniqueTaxRule = new Set();\r\n\t\tfor (let i = 0; i < taxRules.length; i++) {\r\n\t\t\tconst currentTaxRuleId = taxRules[i].getTaxRuleId();\r\n\t\t\tif(uniqueTaxRule.has(currentTaxRuleId)){\r\n\t\t\t\tthrow new InvalidChargeTaxRuleError(\"Duplicate tax rule ID found: \" + currentTaxRuleId);\r\n\t\t\t} else {\r\n\t\t\t\tuniqueTaxRule.add(currentTaxRuleId);\r\n\t\t\t}\r\n\r\n\t\t\tfor (let j = i + 1; j < taxRules.length; j++) {\r\n\t\t\t\tconst r1 = taxRules[i];\r\n\t\t\t\tconst r2 = taxRules[j];\r\n\r\n\t\t\t\tconst r1Min = r1.getMinPrice();\r\n\t\t\t\tconst r1Max = r1.getMaxPrice();\r\n\t\t\t\tconst r1ExcludeMin = r1.getExcludeMin();\r\n\t\t\t\tconst r1ExcludeMax = r1.getExcludeMax();\r\n\t\t\t\tconst r2Min = r2.getMinPrice();\r\n\t\t\t\tconst r2Max = r2.getMaxPrice();\r\n\t\t\t\tconst r2ExcludeMin = r2.getExcludeMin();\r\n\t\t\t\tconst r2ExcludeMax = r2.getExcludeMax();\r\n\r\n\t\t\t\t// Two ranges are disjoint if one ends strictly before the other starts.\r\n\t\t\t\t// If they only touch at one point, disjoint only when either side excludes that point.\r\n\t\t\t\tconst r1EndsBeforeR2Starts = (() => {\r\n\t\t\t\t\tif (!r1Max) return false;\r\n\t\t\t\t\tconst compare = r1Max.compareTo(r2Min);\r\n\t\t\t\t\treturn compare < 0 || (compare === 0 && (r1ExcludeMax || r2ExcludeMin));\r\n\t\t\t\t})();\r\n\t\t\t\tconst r2EndsBeforeR1Starts = (() => {\r\n\t\t\t\t\tif (!r2Max) return false;\r\n\t\t\t\t\tconst compare = r2Max.compareTo(r1Min);\r\n\t\t\t\t\treturn compare < 0 || (compare === 0 && (r2ExcludeMax || r1ExcludeMin));\r\n\t\t\t\t})();\r\n\t\t\t\tconst overlap = !(r1EndsBeforeR2Starts || r2EndsBeforeR1Starts);\r\n\r\n\t\t\t\tif (overlap) {\r\n\t\t\t\t\t// Exception: Allow overlapping rules if they have the exact same price bracket (slab)\r\n\t\t\t\t\tconst sameSlab = r1Min.compareTo(r2Min) === 0 &&\r\n\t\t\t\t\t\tr1ExcludeMin === r2ExcludeMin &&\r\n\t\t\t\t\t\tr1ExcludeMax === r2ExcludeMax &&\r\n\t\t\t\t\t\t((!r1Max && !r2Max) || (r1Max && r2Max && r1Max.compareTo(r2Max) === 0));\r\n\r\n\t\t\t\t\tif (!sameSlab) {\r\n\t\t\t\t\t\tthrow new InvalidChargeTaxRuleError(\r\n\t\t\t\t\t\t\t`Overlapping rules found: [${r1.getTaxRuleId()}: ${r1ExcludeMin ? \"(\" : \"[\"}${r1Min.getAmount()}-${r1Max?.getAmount() ?? \"Infinity\"}${r1ExcludeMax ? \")\" : \"]\"}] and [${r2.getTaxRuleId()}: ${r2ExcludeMin ? \"(\" : \"[\"}${r2Min.getAmount()}-${r2Max?.getAmount() ?? \"Infinity\"}${r2ExcludeMax ? \")\" : \"]\"}]`\r\n\t\t\t\t\t\t);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t\t* Updates the discounts applied to this line item and recalculates totals.\r\n\t\t* @param appliedDiscounts - List of coupons and their allocated discount amounts.\r\n\t*/\r\n\tpublic updateDiscounts(appliedDiscounts: { coupon: CouponModel, amount: PriceModel }[]): void {\r\n\t\tlet chargeDiscounts = {} as Record<string, PriceModel>;\r\n\t\tappliedDiscounts.forEach(discount => {\r\n\t\t\tchargeDiscounts[discount.coupon.getCode()] = discount.amount;\r\n\t\t});\r\n\r\n\t\tthis.total.discountBreakdown = chargeDiscounts;\r\n\t\tthis.calculateTotals();\r\n\t}\r\n\r\n\t/**\r\n\t * Recalculates totals for this charge based on pricing and discounts.\r\n\t */\r\n\tpublic calculateTotals(): void {\r\n\t\tconst zero = this.pricing.baseChargeAmount.zero();\r\n\t\tconst baseChargeAmount = this.pricing.baseChargeAmount;\r\n\r\n\t\tconst totalDiscount = Object.values(this.total.discountBreakdown).reduce((sum, s) => sum.add(s), zero);\r\n\t\tconst netChargeAmount = baseChargeAmount.subtract(totalDiscount);\r\n\r\n\t\tconst taxBreakdown: Record<string, ChargeTaxBreakdownModel> = {};\r\n\r\n\t\t// 1. Calculate total rate for inclusive back-calculation\r\n\t\tconst totalRate = this.pricing.applicableTaxRule.reduce((sum, r) => sum + r.getApplicableTaxRate(netChargeAmount), 0);\r\n\r\n\t\tif (totalRate <= 0) {\r\n\t\t\tthis.total = {\r\n\t\t\t\tchargeAmount: baseChargeAmount,\r\n\t\t\t\tdiscountTotal: totalDiscount,\r\n\t\t\t\tdiscountBreakdown: this.total.discountBreakdown,\r\n\t\t\t\tnetChargeAmount: netChargeAmount,\r\n\t\t\t\ttaxTotal: zero,\r\n\t\t\t\ttaxBreakdown: {},\r\n\t\t\t\tgrandTotal: netChargeAmount\r\n\t\t\t};\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// 2. Iteratively find a taxable base so that base + sum(rounded taxes) == gross\r\n\t\tconst currency = baseChargeAmount.getCurrency();\r\n\t\tconst grossValue = baseChargeAmount.getAmount();\r\n\t\tconst maxIterations = 1000;\r\n\r\n\t\tlet baseValue = PriceModel.getRoundedAmount(grossValue / (1 + totalRate), currency);\r\n\t\tlet bestBaseValue = baseValue;\r\n\t\tlet bestDiff = Number.POSITIVE_INFINITY;\r\n\r\n\t\tfor (let i = 0; i < maxIterations; i++) {\r\n\t\t\tconst currentTaxableBase = new PriceModel({ amount: baseValue, currency });\r\n\t\t\tconst taxes = this.pricing.applicableTaxRule\r\n\t\t\t\t.sort((a, b) => b.getApplicableTaxRate(currentTaxableBase) - a.getApplicableTaxRate(currentTaxableBase))\r\n\t\t\t\t.map(rule =>\r\n\t\t\t\t\tPriceModel.getRoundedAmount(baseValue * rule.getApplicableTaxRate(currentTaxableBase), currency)\r\n\t\t\t\t);\r\n\r\n\t\t\tconst taxSum = taxes.reduce((sum, v) => sum + v, 0);\r\n\t\t\tconst diff = (baseValue + taxSum) - grossValue;\r\n\r\n\t\t\tconst currentTotalRate = this.pricing.applicableTaxRule.reduce((sum, r) => sum + r.getApplicableTaxRate(currentTaxableBase), 0);\r\n\r\n\t\t\tif (Math.abs(diff) < Math.abs(bestDiff)) {\r\n\t\t\t\tbestDiff = diff;\r\n\t\t\t\tbestBaseValue = baseValue;\r\n\t\t\t}\r\n\r\n\t\t\tif (diff === 0) break;\r\n\t\t\tbaseValue = baseValue - diff / (1 + currentTotalRate); // Adjust base value based on the difference\r\n\t\t\tif (baseValue < 0 || baseValue > grossValue) break;\r\n\t\t}\r\n\r\n\t\tconst taxableBase = new PriceModel({ amount: bestBaseValue, currency });\r\n\r\n\t\t// 3. Compute tax amounts per rule based on final taxable base\r\n\t\tlet distributedTax = zero;\r\n\t\tthis.pricing.applicableTaxRule\r\n\t\t\t.sort((a, b) => b.getApplicableTaxRate(taxableBase) - a.getApplicableTaxRate(taxableBase))\r\n\t\t\t.forEach((taxRule) => {\r\n\t\t\t\tconst rate = taxRule.getApplicableTaxRate(taxableBase);\r\n\t\t\t\tconst taxAmountValue = PriceModel.getRoundedAmount(bestBaseValue * rate, currency);\r\n\t\t\t\tconst taxAmount = new PriceModel({ amount: taxAmountValue, currency });\r\n\r\n\t\t\t\ttaxBreakdown[taxRule.getTaxRuleId()] = {\r\n\t\t\t\t\trate: rate,\r\n\t\t\t\t\ttaxableAmount: taxableBase,\r\n\t\t\t\t\ttaxAmount: taxAmount,\r\n\t\t\t\t\tsystem: taxRule.getTaxSystem(),\r\n\t\t\t\t\tsubSystem: taxRule.getTaxSubSystem()\r\n\t\t\t\t};\r\n\t\t\t\tdistributedTax = distributedTax.add(taxAmount);\r\n\t\t\t});\r\n\r\n\t\tconst grandTotal = netChargeAmount;\r\n\t\tthis.total = {\r\n\t\t\tchargeAmount: baseChargeAmount,\r\n\t\t\tdiscountTotal: totalDiscount,\r\n\t\t\tdiscountBreakdown: this.total.discountBreakdown,\r\n\t\t\tnetChargeAmount: netChargeAmount,\r\n\t\t\ttaxBreakdown: taxBreakdown,\r\n\t\t\ttaxTotal: distributedTax,\r\n\t\t\tgrandTotal: grandTotal\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets a plain data object representing this charge.\r\n\t * @returns ChargeData for serialization.\r\n\t */\r\n\tpublic getDetails(): ChargeData {\r\n\t\tconst details: ChargeData = {\r\n\t\t\tid: this.id,\r\n\t\t\tname: Utils.deepClone(this.name),\r\n\t\t\ttype: this.type,\r\n\t\t\tcategory: this.category,\r\n\t\t\tpricing: {\r\n\t\t\t\tbaseChargeAmount: this.pricing.baseChargeAmount.getDetails(),\r\n\t\t\t\ttaxCategory: this.pricing.taxCategory,\r\n\t\t\t\tapplicableTaxRule: this.pricing.applicableTaxRule.map(r => r.getDetails())\r\n\t\t\t},\r\n\t\t\timpact: this.impact,\r\n\t\t\tlineItemId: this.lineItemId,\r\n\t\t\ttotal: {\r\n\t\t\t\tchargeAmount: this.total.chargeAmount.getDetails(),\r\n\t\t\t\tdiscountTotal: this.total.discountTotal.getDetails(),\r\n\t\t\t\tdiscountBreakdown: Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([k, v]) => [k, v.getDetails()])),\r\n\t\t\t\tnetChargeAmount: this.total.netChargeAmount.getDetails(),\r\n\t\t\t\ttaxBreakdown: Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([k, v]) => [k, {\r\n\t\t\t\t\trate: v.rate,\r\n\t\t\t\t\ttaxableAmount: v.taxableAmount.getDetails(),\r\n\t\t\t\t\ttaxAmount: v.taxAmount.getDetails(),\r\n\t\t\t\t\tsystem: v.system,\r\n\t\t\t\t\tsubSystem: v.subSystem\r\n\t\t\t\t}])),\r\n\t\t\t\ttaxTotal: this.total.taxTotal.getDetails(),\r\n\t\t\t\tgrandTotal: this.total.grandTotal.getDetails()\r\n\t\t\t},\r\n\t\t\tcustomFields: this.getAllCustomFields()\r\n\t\t};\r\n\t\treturn details;\r\n\t}\r\n}\r\n"]}
1
+ {"version":3,"sources":["../src/Classes/Charge.ts"],"names":["ChargeModel","CustomFieldModel","data","PriceModel","r","TaxRuleModel","InvalidChargeError","discountId","discount","taxRuleId","taxBreakdown","locale","Utils_default","LocaleLanguageMap","key","value","taxRules","taxRule","InvalidTaxRuleError","InvalidChargeTaxRuleError","uniqueTaxRule","i","currentTaxRuleId","j","r1","r2","r1Min","r1Max","r1ExcludeMin","r1ExcludeMax","r2Min","r2Max","r2ExcludeMin","r2ExcludeMax","r1EndsBeforeR2Starts","compare","r2EndsBeforeR1Starts","appliedDiscounts","chargeDiscounts","zero","baseChargeAmount","totalDiscount","sum","s","netChargeAmount","totalRate","currency","grossValue","maxIterations","baseValue","bestBaseValue","bestDiff","currentTaxableBase","taxSum","a","b","rule","v","diff","currentTotalRate","taxableBase","distributedTax","rate","taxAmountValue","taxAmount","grandTotal","k"],"mappings":"uPA4FA,IAAqBA,CAArB,CAAA,cAAyCC,CAAiB,CAC/C,EACA,CAAA,IAAA,CACA,IACA,CAAA,QAAA,CACA,MACA,CAAA,OAAA,CACA,UACA,CAAA,KAAA,CAEV,YAAYC,CAAwB,CAAA,CAenC,GAdA,KAAA,CAAMA,CAAI,CAAA,CACV,IAAK,CAAA,EAAA,CAAKA,CAAK,CAAA,EAAA,CACf,IAAK,CAAA,IAAA,CAAOA,CAAK,CAAA,IAAA,CACjB,IAAK,CAAA,IAAA,CAAOA,EAAK,IACjB,CAAA,IAAA,CAAK,QAAWA,CAAAA,CAAAA,CAAK,QACrB,CAAA,IAAA,CAAK,MAASA,CAAAA,CAAAA,CAAK,MACnB,CAAA,IAAA,CAAK,UAAaA,CAAAA,CAAAA,CAAK,UACvB,CAAA,IAAA,CAAK,OAAU,CAAA,CACd,iBAAkB,IAAIC,GAAAA,CAAWD,CAAK,CAAA,OAAA,CAAQ,gBAAgB,CAAA,CAC9D,WAAaA,CAAAA,CAAAA,CAAK,QAAQ,WAC1B,CAAA,iBAAA,CAAmBA,CAAK,CAAA,OAAA,CAAQ,iBAAkB,CAAA,GAAA,CAAIE,CAAK,EAAA,IAAIC,IAAaD,C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U,CAAA,IAAA,CAAK,KAAM,CAAA,QAAA,CAAS,UAAW,EAAA,CACzC,UAAY,CAAA,IAAA,CAAK,MAAM,UAAW,CAAA,UAAA,EACnC,CAAA,CACA,YAAc,CAAA,IAAA,CAAK,kBAAmB,EACvC,CAED,CACD","file":"chunk-BSDPFVRK.mjs","sourcesContent":["import { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\nimport Utils from \"../Utils\";\r\nimport { LocaleCode, LocalizedString } from \"./Common\";\r\nimport { ChargeImpact, ChargeType, LocaleLanguageMap, TaxSystem } from \"./Enum\";\r\nimport { InvalidChargeTaxRuleError, InvalidChargeError, InvalidTaxRuleError } from \"./Error\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport { TaxRuleData, TaxRuleModel } from \"./TaxRule\";\r\nimport CouponModel from \"./Coupon\";\r\n\r\nexport type ChargePricing = {\r\n /** Tax-inclusive original charge amount before any discounts. Always non-negative. */\r\n baseChargeAmount: PriceData;\r\n /** Tax category of the charge. */\r\n taxCategory: string;\r\n /** Tax rules applicable to the charge. */\r\n applicableTaxRule: TaxRuleData[];\r\n};\r\n\r\nexport type ChargePricingModel = {\r\n /** Tax-inclusive original charge amount before any discounts. Always non-negative. */\r\n baseChargeAmount: PriceModel;\r\n /** Tax category of the charge. */\r\n taxCategory: string;\r\n /** Tax rules applicable to the charge. */\r\n applicableTaxRule: TaxRuleModel[];\r\n};\r\n\r\nexport type ChargeTaxBreakdown = {\r\n /** Tax rate: e.g., 0.09 for 9% */\r\n rate: number;\r\n /** Reverse-calculated pre-tax base from the netChargeAmount (post-discount) */\r\n taxableAmount: PriceData;\r\n /** Tax portion for this rule (netChargeAmount - taxableAmount) */\r\n taxAmount: PriceData;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type ChargeTaxBreakdownModel = {\r\n rate: number;\r\n taxableAmount: PriceModel;\r\n taxAmount: PriceModel;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type ChargeTotals = {\r\n /** Tax-inclusive original charge amount before discounts (copied from pricing) */\r\n chargeAmount: PriceData;\r\n /** Coupon code -> discount amount mapping */\r\n discountBreakdown: Record<string, PriceData>;\r\n /** Sum of all discounts */\r\n discountTotal: PriceData;\r\n /** chargeAmount - totalDiscount → final tax-inclusive payable amount after discounts */\r\n netChargeAmount: PriceData;\r\n /** Sum of all taxAmount values */\r\n taxTotal: PriceData;\r\n /** Tax breakdown per rule/category (reverse-calculated from netChargeAmount) */\r\n taxBreakdown: Record<string, ChargeTaxBreakdown>;\r\n /** Final payable/contribution amount. Equals netChargeAmount (tax-inclusive after discounts). */\r\n grandTotal: PriceData;\r\n};\r\n\r\nexport type ChargeTotalsModel = {\r\n chargeAmount: PriceModel;\r\n discountTotal: PriceModel;\r\n discountBreakdown: Record<string, PriceModel>;\r\n netChargeAmount: PriceModel;\r\n taxTotal: PriceModel;\r\n taxBreakdown: Record<string, ChargeTaxBreakdownModel>;\r\n grandTotal: PriceModel; // Equals netChargeAmount\r\n};\r\n\r\nexport type ChargeAttributes = CustomFieldAttributes & {\r\n id: string;\r\n name: LocalizedString;\r\n type: ChargeType;\r\n category: string;\r\n impact: ChargeImpact; // ADD or SUBTRACT\r\n pricing: ChargePricing;\r\n lineItemId?: string;\r\n total: ChargeTotals;\r\n};\r\n\r\nexport type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId'> & {\r\n\tlineItemId?: string;\r\n};\r\n\r\n/**\r\n * Represents an additional charge (or discount if amount is negative) in a shopping container.\r\n * Supports its own tax rules.\r\n */\r\nexport default class ChargeModel extends CustomFieldModel {\r\n\tprotected id: string;\r\n\tprotected name: LocalizedString;\r\n\tprotected type: ChargeType;\r\n\tprotected category: string;\r\n\tprotected impact: ChargeImpact;\r\n\tprotected pricing: ChargePricingModel;\r\n\tprotected lineItemId?: string;\r\n\tprotected total: ChargeTotalsModel;\r\n\r\n\tconstructor(data: ChargeAttributes) {\r\n\t\tsuper(data);\r\n\t\tthis.id = data.id;\r\n\t\tthis.name = data.name;\r\n\t\tthis.type = data.type;\r\n\t\tthis.category = data.category;\r\n\t\tthis.impact = data.impact;\r\n\t\tthis.lineItemId = data.lineItemId;\r\n\t\tthis.pricing = {\r\n\t\t\tbaseChargeAmount: new PriceModel(data.pricing.baseChargeAmount),\r\n\t\t\ttaxCategory: data.pricing.taxCategory,\r\n\t\t\tapplicableTaxRule: data.pricing.applicableTaxRule.map(r => new TaxRuleModel(r))\r\n\t\t};\r\n\r\n\t\tthis.validateTaxRules(this.pricing.applicableTaxRule);\r\n\t\tif(this.impact === ChargeImpact.SUBTRACT && this.type !== ChargeType.ADJUSTMENT) {\r\n\t\t\tthrow new InvalidChargeError('SUBTRACT impact is only allowed for ADJUSTMENT charge');\r\n\t\t}\r\n\r\n\t\tthis.total = {\r\n\t\t\tchargeAmount: new PriceModel(data.total.chargeAmount),\r\n\t\t\tdiscountTotal: new PriceModel(data.total.discountTotal),\r\n\t\t\tdiscountBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(data.total.discountBreakdown).map(([discountId, discount]) => [\r\n\t\t\t\t\tdiscountId,\r\n\t\t\t\t\tnew PriceModel(discount)\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\tnetChargeAmount: new PriceModel(data.total.netChargeAmount),\r\n\t\t\ttaxBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(data.total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n\t\t\t\t\ttaxRuleId,\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\trate: taxBreakdown.rate,\r\n\t\t\t\t\t\ttaxableAmount: new PriceModel(taxBreakdown.taxableAmount),\r\n\t\t\t\t\t\ttaxAmount: new PriceModel(taxBreakdown.taxAmount),\r\n\t\t\t\t\t\tsystem: taxBreakdown.system,\r\n\t\t\t\t\t\tsubSystem: taxBreakdown.subSystem\r\n\t\t\t\t\t}\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\ttaxTotal: new PriceModel(data.total.taxTotal),\r\n\t\t\tgrandTotal: new PriceModel(data.total.grandTotal),\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the unique identifier of the charge.\r\n\t * @returns \r\n\t */\r\n\tpublic getId(): string { return this.id; }\r\n\r\n\r\n\t/**\r\n\t * Gets the full localized product name object.\r\n\t * @returns A copy of the LocalizedString object for the name.\r\n\t */\r\n\tgetName(): LocalizedString\r\n\t/**\r\n\t * Gets the product name for a specific locale, falling back to English ('en').\r\n\t * @param locale - The desired locale code.\r\n\t * @returns The name string for the specified locale.\r\n\t */\r\n\tgetName(locale: LocaleCode): string\r\n\tgetName(locale?: LocaleCode): LocalizedString | string {\r\n\t\tif (locale) {\r\n\t\t\treturn Utils.deepClone(this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en);\r\n\t\t} else {\r\n\t\t\treturn Utils.deepClone(this.name);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the charge category.\r\n\t * @returns The category string.\r\n\t */\r\n\tpublic getCategory(): string { return this.category; }\r\n\r\n\t/**\r\n\t * Gets the charge type.\r\n\t * @returns The charge type enum value.\r\n\t */\r\n\tpublic getType(): ChargeType { return this.type; }\r\n\t/**\r\n\t * Gets the charge impact (add or subtract).\r\n\t * @returns The charge impact.\r\n\t */\r\n\tpublic getImpact(): ChargeImpact { return this.impact; }\r\n\r\n\t/**\r\n\t * Gets the related line item id, if any.\r\n\t * @returns The line item id or undefined.\r\n\t */\r\n\tpublic getLineItemId(): string | undefined { return this.lineItemId; }\r\n\r\n\t/**\r\n\t * Gets the pricing details (models) for this charge.\r\n\t * @returns Pricing details including price, tax category, and tax rules.\r\n\t */\r\n\tpublic getPricing(): ChargePricingModel {\r\n\t\treturn {\r\n\t\t\tbaseChargeAmount: this.pricing.baseChargeAmount,\r\n\t\t\ttaxCategory: this.pricing.taxCategory,\r\n\t\t\tapplicableTaxRule: [...this.pricing.applicableTaxRule]\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the computed totals for this charge.\r\n\t * @returns Totals including discounts, taxes, and grand total.\r\n\t */\r\n\tpublic getTotal(): ChargeTotalsModel {\r\n\t\treturn {\r\n\t\t\tchargeAmount: this.total.chargeAmount,\r\n\t\t\tdiscountTotal: this.total.discountTotal,\r\n\t\t\tdiscountBreakdown: { ...this.total.discountBreakdown },\r\n\t\t\tnetChargeAmount: this.total.netChargeAmount,\r\n\t\t\ttaxTotal: this.total.taxTotal,\r\n\t\t\ttaxBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(this.total.taxBreakdown).map(([key, value]) => [\r\n\t\t\t\t\tkey,\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\trate: value.rate,\r\n\t\t\t\t\t\ttaxableAmount: value.taxableAmount,\r\n\t\t\t\t\t\ttaxAmount: value.taxAmount,\r\n\t\t\t\t\t\tsystem: value.system,\r\n\t\t\t\t\t\tsubSystem: value.subSystem\r\n\t\t\t\t\t}\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\tgrandTotal: this.total.grandTotal,\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the applicable tax rules for this charge.\r\n\t * @returns A list of tax rules.\r\n\t */\r\n\tpublic getApplicableTaxRules(): TaxRuleModel[] {\r\n\t\treturn [...this.pricing.applicableTaxRule];\r\n\t}\r\n\r\n\t/**\r\n\t * Updates the tax rule for this line item and recalculates totals.\r\n\t * @param taxRule - The new tax rule to apply.\r\n\t * @throws {Error} If the tax rule category does not match the item's tax category.\r\n\t */\r\n\tpublic updateTax(taxRules: TaxRuleModel[]): void {\r\n\t\tif (this.type === ChargeType.ADJUSTMENT && taxRules.length > 0) {\r\n\t\t\tthrow new InvalidChargeError(\"Adjustment charges cannot apply tax rules.\");\r\n\t\t}\r\n\t\ttaxRules.forEach(taxRule => {\r\n\t\t\tif (!taxRule.appliesTo(this.pricing.taxCategory, taxRule.getCountry())) {\r\n\t\t\t\tthrow new InvalidTaxRuleError();\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\t// Remove the old taxableUnitPrice calculation - no longer needed\r\n\t\tthis.validateTaxRules(taxRules);\r\n\t\tthis.pricing.applicableTaxRule = taxRules;\r\n\t\tthis.calculateTotals();\r\n\t}\r\n\r\n\t/**\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 {InvalidChargeTaxRuleError} If any rules have positive tax rates with SUBTRACT impact or if duplicate rule IDs are found.\r\n\t * @throws {InvalidChargeTaxRuleError} Duplicate tax rule IDs will results in error.\r\n\t * @throws {CoincidingTaxBracketError} If any overlapping rules are found.\r\n\t */\r\n\tprivate validateTaxRules(taxRules: TaxRuleModel[]): void {\r\n\t\tif(this.impact === ChargeImpact.SUBTRACT) {\r\n\t\t\tif(taxRules.some(taxRule => taxRule.getRate() > 0)) {\r\n\t\t\t\tthrow new InvalidChargeTaxRuleError(\"Subtractive charges cannot have positive tax rates.\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst uniqueTaxRule = new Set();\r\n\t\tfor (let i = 0; i < taxRules.length; i++) {\r\n\t\t\tconst currentTaxRuleId = taxRules[i].getTaxRuleId();\r\n\t\t\tif(uniqueTaxRule.has(currentTaxRuleId)){\r\n\t\t\t\tthrow new InvalidChargeTaxRuleError(\"Duplicate tax rule ID found: \" + currentTaxRuleId);\r\n\t\t\t} else {\r\n\t\t\t\tuniqueTaxRule.add(currentTaxRuleId);\r\n\t\t\t}\r\n\r\n\t\t\tfor (let j = i + 1; j < taxRules.length; j++) {\r\n\t\t\t\tconst r1 = taxRules[i];\r\n\t\t\t\tconst r2 = taxRules[j];\r\n\r\n\t\t\t\tconst r1Min = r1.getMinPrice();\r\n\t\t\t\tconst r1Max = r1.getMaxPrice();\r\n\t\t\t\tconst r1ExcludeMin = r1.getExcludeMin();\r\n\t\t\t\tconst r1ExcludeMax = r1.getExcludeMax();\r\n\t\t\t\tconst r2Min = r2.getMinPrice();\r\n\t\t\t\tconst r2Max = r2.getMaxPrice();\r\n\t\t\t\tconst r2ExcludeMin = r2.getExcludeMin();\r\n\t\t\t\tconst r2ExcludeMax = r2.getExcludeMax();\r\n\r\n\t\t\t\t// Two ranges are disjoint if one ends strictly before the other starts.\r\n\t\t\t\t// If they only touch at one point, disjoint only when either side excludes that point.\r\n\t\t\t\tconst r1EndsBeforeR2Starts = (() => {\r\n\t\t\t\t\tif (!r1Max) return false;\r\n\t\t\t\t\tconst compare = r1Max.compareTo(r2Min);\r\n\t\t\t\t\treturn compare < 0 || (compare === 0 && (r1ExcludeMax || r2ExcludeMin));\r\n\t\t\t\t})();\r\n\t\t\t\tconst r2EndsBeforeR1Starts = (() => {\r\n\t\t\t\t\tif (!r2Max) return false;\r\n\t\t\t\t\tconst compare = r2Max.compareTo(r1Min);\r\n\t\t\t\t\treturn compare < 0 || (compare === 0 && (r2ExcludeMax || r1ExcludeMin));\r\n\t\t\t\t})();\r\n\t\t\t\tconst overlap = !(r1EndsBeforeR2Starts || r2EndsBeforeR1Starts);\r\n\r\n\t\t\t\tif (overlap) {\r\n\t\t\t\t\t// Exception: Allow overlapping rules if they have the exact same price bracket (slab)\r\n\t\t\t\t\tconst sameSlab = r1Min.compareTo(r2Min) === 0 &&\r\n\t\t\t\t\t\tr1ExcludeMin === r2ExcludeMin &&\r\n\t\t\t\t\t\tr1ExcludeMax === r2ExcludeMax &&\r\n\t\t\t\t\t\t((!r1Max && !r2Max) || (r1Max && r2Max && r1Max.compareTo(r2Max) === 0));\r\n\r\n\t\t\t\t\tif (!sameSlab) {\r\n\t\t\t\t\t\tthrow new InvalidChargeTaxRuleError(\r\n\t\t\t\t\t\t\t`Overlapping rules found: [${r1.getTaxRuleId()}: ${r1ExcludeMin ? \"(\" : \"[\"}${r1Min.getAmount()}-${r1Max?.getAmount() ?? \"Infinity\"}${r1ExcludeMax ? \")\" : \"]\"}] and [${r2.getTaxRuleId()}: ${r2ExcludeMin ? \"(\" : \"[\"}${r2Min.getAmount()}-${r2Max?.getAmount() ?? \"Infinity\"}${r2ExcludeMax ? \")\" : \"]\"}]`\r\n\t\t\t\t\t\t);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t\t* Updates the discounts applied to this line item and recalculates totals.\r\n\t\t* @param appliedDiscounts - List of coupons and their allocated discount amounts.\r\n\t*/\r\n\tpublic updateDiscounts(appliedDiscounts: { coupon: CouponModel, amount: PriceModel }[]): void {\r\n\t\tlet chargeDiscounts = {} as Record<string, PriceModel>;\r\n\t\tappliedDiscounts.forEach(discount => {\r\n\t\t\tchargeDiscounts[discount.coupon.getCode()] = discount.amount;\r\n\t\t});\r\n\r\n\t\tthis.total.discountBreakdown = chargeDiscounts;\r\n\t\tthis.calculateTotals();\r\n\t}\r\n\r\n\t/**\r\n\t * Recalculates totals for this charge based on pricing and discounts.\r\n\t */\r\n\tpublic calculateTotals(): void {\r\n\t\tconst zero = this.pricing.baseChargeAmount.zero();\r\n\t\tconst baseChargeAmount = this.pricing.baseChargeAmount;\r\n\r\n\t\tconst totalDiscount = Object.values(this.total.discountBreakdown).reduce((sum, s) => sum.add(s), zero);\r\n\t\tconst netChargeAmount = baseChargeAmount.subtract(totalDiscount);\r\n\r\n\t\tconst taxBreakdown: Record<string, ChargeTaxBreakdownModel> = {};\r\n\r\n\t\t// 1. Calculate total rate for inclusive back-calculation\r\n\t\tconst totalRate = this.pricing.applicableTaxRule.reduce((sum, r) => sum + r.getApplicableTaxRate(netChargeAmount), 0);\r\n\r\n\t\tif (totalRate <= 0) {\r\n\t\t\tthis.total = {\r\n\t\t\t\tchargeAmount: baseChargeAmount,\r\n\t\t\t\tdiscountTotal: totalDiscount,\r\n\t\t\t\tdiscountBreakdown: this.total.discountBreakdown,\r\n\t\t\t\tnetChargeAmount: netChargeAmount,\r\n\t\t\t\ttaxTotal: zero,\r\n\t\t\t\ttaxBreakdown: {},\r\n\t\t\t\tgrandTotal: netChargeAmount\r\n\t\t\t};\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// 2. Iteratively find a taxable base so that base + sum(rounded taxes) == gross\r\n\t\tconst currency = baseChargeAmount.getCurrency();\r\n\t\tconst grossValue = baseChargeAmount.getAmount();\r\n\t\tconst maxIterations = 1000;\r\n\r\n\t\tlet baseValue = PriceModel.getRoundedAmount(grossValue / (1 + totalRate), currency);\r\n\t\tlet bestBaseValue = baseValue;\r\n\t\tlet bestDiff = Number.POSITIVE_INFINITY;\r\n\r\n\t\tfor (let i = 0; i < maxIterations; i++) {\r\n\t\t\tconst currentTaxableBase = new PriceModel({ amount: baseValue, currency });\r\n\t\t\tconst taxes = this.pricing.applicableTaxRule\r\n\t\t\t\t.sort((a, b) => b.getApplicableTaxRate(currentTaxableBase) - a.getApplicableTaxRate(currentTaxableBase))\r\n\t\t\t\t.map(rule =>\r\n\t\t\t\t\tPriceModel.getRoundedAmount(baseValue * rule.getApplicableTaxRate(currentTaxableBase), currency)\r\n\t\t\t\t);\r\n\r\n\t\t\tconst taxSum = taxes.reduce((sum, v) => sum + v, 0);\r\n\t\t\tconst diff = (baseValue + taxSum) - grossValue;\r\n\r\n\t\t\tconst currentTotalRate = this.pricing.applicableTaxRule.reduce((sum, r) => sum + r.getApplicableTaxRate(currentTaxableBase), 0);\r\n\r\n\t\t\tif (Math.abs(diff) < Math.abs(bestDiff)) {\r\n\t\t\t\tbestDiff = diff;\r\n\t\t\t\tbestBaseValue = baseValue;\r\n\t\t\t}\r\n\r\n\t\t\tif (diff === 0) break;\r\n\t\t\tbaseValue = baseValue - diff / (1 + currentTotalRate); // Adjust base value based on the difference\r\n\t\t\tif (baseValue < 0 || baseValue > grossValue) break;\r\n\t\t}\r\n\r\n\t\tconst taxableBase = new PriceModel({ amount: bestBaseValue, currency });\r\n\r\n\t\t// 3. Compute tax amounts per rule based on final taxable base\r\n\t\tlet distributedTax = zero;\r\n\t\tthis.pricing.applicableTaxRule\r\n\t\t\t.sort((a, b) => b.getApplicableTaxRate(taxableBase) - a.getApplicableTaxRate(taxableBase))\r\n\t\t\t.forEach((taxRule) => {\r\n\t\t\t\tconst rate = taxRule.getApplicableTaxRate(taxableBase);\r\n\t\t\t\tconst taxAmountValue = PriceModel.getRoundedAmount(bestBaseValue * rate, currency);\r\n\t\t\t\tconst taxAmount = new PriceModel({ amount: taxAmountValue, currency });\r\n\r\n\t\t\t\ttaxBreakdown[taxRule.getTaxRuleId()] = {\r\n\t\t\t\t\trate: rate,\r\n\t\t\t\t\ttaxableAmount: taxableBase,\r\n\t\t\t\t\ttaxAmount: taxAmount,\r\n\t\t\t\t\tsystem: taxRule.getTaxSystem(),\r\n\t\t\t\t\tsubSystem: taxRule.getTaxSubSystem()\r\n\t\t\t\t};\r\n\t\t\t\tdistributedTax = distributedTax.add(taxAmount);\r\n\t\t\t});\r\n\r\n\t\tconst grandTotal = netChargeAmount;\r\n\t\tthis.total = {\r\n\t\t\tchargeAmount: baseChargeAmount,\r\n\t\t\tdiscountTotal: totalDiscount,\r\n\t\t\tdiscountBreakdown: this.total.discountBreakdown,\r\n\t\t\tnetChargeAmount: netChargeAmount,\r\n\t\t\ttaxBreakdown: taxBreakdown,\r\n\t\t\ttaxTotal: distributedTax,\r\n\t\t\tgrandTotal: grandTotal\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets a plain data object representing this charge.\r\n\t * @returns ChargeData for serialization.\r\n\t */\r\n\tpublic getDetails(): ChargeData {\r\n\t\tconst details: ChargeData = {\r\n\t\t\tid: this.id,\r\n\t\t\tname: Utils.deepClone(this.name),\r\n\t\t\ttype: this.type,\r\n\t\t\tcategory: this.category,\r\n\t\t\tpricing: {\r\n\t\t\t\tbaseChargeAmount: this.pricing.baseChargeAmount.getDetails(),\r\n\t\t\t\ttaxCategory: this.pricing.taxCategory,\r\n\t\t\t\tapplicableTaxRule: this.pricing.applicableTaxRule.map(r => r.getDetails())\r\n\t\t\t},\r\n\t\t\timpact: this.impact,\r\n\t\t\tlineItemId: this.lineItemId,\r\n\t\t\ttotal: {\r\n\t\t\t\tchargeAmount: this.total.chargeAmount.getDetails(),\r\n\t\t\t\tdiscountTotal: this.total.discountTotal.getDetails(),\r\n\t\t\t\tdiscountBreakdown: Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([k, v]) => [k, v.getDetails()])),\r\n\t\t\t\tnetChargeAmount: this.total.netChargeAmount.getDetails(),\r\n\t\t\t\ttaxBreakdown: Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([k, v]) => [k, {\r\n\t\t\t\t\trate: v.rate,\r\n\t\t\t\t\ttaxableAmount: v.taxableAmount.getDetails(),\r\n\t\t\t\t\ttaxAmount: v.taxAmount.getDetails(),\r\n\t\t\t\t\tsystem: v.system,\r\n\t\t\t\t\tsubSystem: v.subSystem\r\n\t\t\t\t}])),\r\n\t\t\t\ttaxTotal: this.total.taxTotal.getDetails(),\r\n\t\t\t\tgrandTotal: this.total.grandTotal.getDetails()\r\n\t\t\t},\r\n\t\t\tcustomFields: this.getAllCustomFields()\r\n\t\t};\r\n\t\treturn details;\r\n\t}\r\n}\r\n"]}
@@ -1,2 +1,2 @@
1
- import {a as a$1}from'./chunk-FCRJAAPY.mjs';import {e as e$1}from'./chunk-QK4XJ3GB.mjs';import {b as b$2}from'./chunk-2B2XI6FG.mjs';import {h as h$1,e}from'./chunk-R5DM7WCD.mjs';import {b as b$1}from'./chunk-UXZBULDS.mjs';import K from'crypto';var y=new Uint8Array(256),h=y.length;function I(){return h>y.length-16&&(K.randomFillSync(y),h=0),y.slice(h,h+=16)}var z=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function $(t){return typeof t=="string"&&z.test(t)}var U=$;var n=[];for(let t=0;t<256;++t)n.push((t+256).toString(16).slice(1));function b(t,e=0){return n[t[e+0]]+n[t[e+1]]+n[t[e+2]]+n[t[e+3]]+"-"+n[t[e+4]]+n[t[e+5]]+"-"+n[t[e+6]]+n[t[e+7]]+"-"+n[t[e+8]]+n[t[e+9]]+"-"+n[t[e+10]]+n[t[e+11]]+n[t[e+12]]+n[t[e+13]]+n[t[e+14]]+n[t[e+15]]}function k(t){if(!U(t))throw TypeError("Invalid UUID");let e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}var M=k;function V(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var G="6ba7b810-9dad-11d1-80b4-00c04fd430c8",B="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function x(t,e,r){function i(o,s,u,S){var A;if(typeof o=="string"&&(o=V(o)),typeof s=="string"&&(s=M(s)),((A=s)===null||A===void 0?void 0:A.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let g=new Uint8Array(16+o.length);if(g.set(s),g.set(o,s.length),g=r(g),g[6]=g[6]&15|e,g[8]=g[8]&63|128,u){S=S||0;for(let m=0;m<16;++m)u[S+m]=g[m];return u}return b(g)}try{i.name=t;}catch{}return i.DNS=G,i.URL=B,i}var L={randomUUID:K.randomUUID};function j(t,e,r){if(L.randomUUID&&!e&&!t)return L.randomUUID();t=t||{};let i=t.random||(t.rng||I)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){r=r||0;for(let o=0;o<16;++o)e[r+o]=i[o];return e}return b(i)}var D=j;function Z(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),K.createHash("sha1").update(t).digest()}var R=Z;var q=x("v5",80,R),P=q;var O={isUUID:t=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t),isEmail:t=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t),isURL:t=>/^(http|https):\/\/[^ "]+$/.test(t),generateUUID:(t,e)=>e&&t?P(t,e):D(),generateSearchId:(t,e)=>`${t}#${f.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:t=>{let[e,r]=t.split("#");return {key:e,selectionAttributes:f.parseSelectionAttributesKey(r)}},deepClone(t){return structuredClone(t)}},a=O;var f=class t extends b$1{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new h$1("Selection attributes must be an object");return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let r={},i=e.split("|");for(let o of i){let[s,u]=o.split(":");u.startsWith("c+")?r[s]={name:u.slice(2)}:r[s]=u;}return r}catch(r){throw new h$1(r?.message)}}constructor(e$1,r=new Date){super(e$1,r),this.id=e$1.id,this.key=e$1.key,this.name={...e$1.name},this.description={...e$1.description},this.slug={...e$1.slug},this.brand=e$1.brand,this.pricing=Object.keys(e$1.pricing).reduce((o,s)=>(e$1.pricing[s]&&(o[s]=new a$1(e$1.pricing[s])),o),{}),this.targetGender=e$1.targetGender,this.attributes=a.deepClone(e$1.attributes),this.specifications=a.deepClone(e$1.specifications),this.categories=a.deepClone(e$1.categories);let i=new Set;this.variants=(e$1.variants||[]).map(o=>{if(!o.selectionAttributes||typeof o.selectionAttributes!="object")throw new h$1("Selection attributes are required");this.checkSelectionAttributes(o.selectionAttributes);let s=t.generateSelectionAttributesKey(o.selectionAttributes);if(i.has(s))throw new e(s);return i.add(s),{sku:o.sku,selectionAttributes:o.selectionAttributes,images:{primary:new b$2(o.images.primary),gallery:(o.images.gallery||[]).map(u=>new b$2(u))}}}),this.isActive=e$1.isActive,this.searchTags=e$1.searchTags?a.deepClone(e$1.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[e$1[e]]??this.name.en:a.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[e$1[e]]??this.description.en:a.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[e$1[e]]??this.slug.en:a.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return a.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:a.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let r=t.generateSelectionAttributesKey(e),i=this.variants.find(o=>t.generateSelectionAttributesKey(o.selectionAttributes)===r);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,r){switch(r){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return a.deepClone(this.categories)}getSpecifications(e){return e?a.deepClone(this.specifications[e]??this.specifications[e$1[e]]??this.specifications.en):a.deepClone(this.specifications)}getSearchTags(e){return e?a.deepClone(this.searchTags[e]??this.searchTags[e$1[e]]??this.searchTags.en):a.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((r,i)=>(this.pricing[i]&&(r[i]=this.pricing[i]?.getDetails()),r),{}),attributes:this.getAttributes(),variants:this.variants.map(r=>({sku:r.sku,selectionAttributes:a.deepClone(r.selectionAttributes),images:{primary:r.images.primary.getDetails(),gallery:r.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new h$1("Selection attributes are required");Object.keys(this.attributes).forEach(r=>{if(r.toLowerCase()==="size")return;let i=this.attributes[r],o=e[r];if(o===void 0)throw new h$1(`Selection attribute '${r}' is missing`);if(typeof i=="string"){if(typeof o!="string"||i!==o)throw new h$1(`Selection attribute '${r}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof o!="string"||!i.includes(o))throw new h$1(`Selection attribute '${r}' is invalid`)}else if(typeof o!="object"||!("name"in o)||i.findIndex(s=>s.name===o.name)<0)throw new h$1(`Selection attribute '${r}' is invalid`)}});}validateSelectionAttribute(e){let r=t.generateSelectionAttributesKey(e);return this.variants.some(i=>t.generateSelectionAttributesKey(i.selectionAttributes)===r)}validateSize(e){return this.attributes.size.includes(e)}};export{a,f as b};//# sourceMappingURL=chunk-QGIQ3MH6.mjs.map
2
- //# sourceMappingURL=chunk-QGIQ3MH6.mjs.map
1
+ import {a as a$1}from'./chunk-FCRJAAPY.mjs';import {b as b$2}from'./chunk-2B2XI6FG.mjs';import {e as e$1}from'./chunk-QK4XJ3GB.mjs';import {h as h$1,e}from'./chunk-R5DM7WCD.mjs';import {b as b$1}from'./chunk-UXZBULDS.mjs';import K from'crypto';var y=new Uint8Array(256),h=y.length;function I(){return h>y.length-16&&(K.randomFillSync(y),h=0),y.slice(h,h+=16)}var z=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function $(t){return typeof t=="string"&&z.test(t)}var U=$;var n=[];for(let t=0;t<256;++t)n.push((t+256).toString(16).slice(1));function b(t,e=0){return n[t[e+0]]+n[t[e+1]]+n[t[e+2]]+n[t[e+3]]+"-"+n[t[e+4]]+n[t[e+5]]+"-"+n[t[e+6]]+n[t[e+7]]+"-"+n[t[e+8]]+n[t[e+9]]+"-"+n[t[e+10]]+n[t[e+11]]+n[t[e+12]]+n[t[e+13]]+n[t[e+14]]+n[t[e+15]]}function k(t){if(!U(t))throw TypeError("Invalid UUID");let e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}var M=k;function V(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var G="6ba7b810-9dad-11d1-80b4-00c04fd430c8",B="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function x(t,e,r){function i(o,s,u,S){var A;if(typeof o=="string"&&(o=V(o)),typeof s=="string"&&(s=M(s)),((A=s)===null||A===void 0?void 0:A.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let g=new Uint8Array(16+o.length);if(g.set(s),g.set(o,s.length),g=r(g),g[6]=g[6]&15|e,g[8]=g[8]&63|128,u){S=S||0;for(let m=0;m<16;++m)u[S+m]=g[m];return u}return b(g)}try{i.name=t;}catch{}return i.DNS=G,i.URL=B,i}var L={randomUUID:K.randomUUID};function j(t,e,r){if(L.randomUUID&&!e&&!t)return L.randomUUID();t=t||{};let i=t.random||(t.rng||I)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){r=r||0;for(let o=0;o<16;++o)e[r+o]=i[o];return e}return b(i)}var D=j;function Z(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),K.createHash("sha1").update(t).digest()}var R=Z;var q=x("v5",80,R),P=q;var O={isUUID:t=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t),isEmail:t=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t),isURL:t=>/^(http|https):\/\/[^ "]+$/.test(t),generateUUID:(t,e)=>e&&t?P(t,e):D(),generateSearchId:(t,e)=>`${t}#${f.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:t=>{let[e,r]=t.split("#");return {key:e,selectionAttributes:f.parseSelectionAttributesKey(r)}},deepClone(t){return structuredClone(t)}},a=O;var f=class t extends b$1{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new h$1("Selection attributes must be an object");return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let r={},i=e.split("|");for(let o of i){let[s,u]=o.split(":");u.startsWith("c+")?r[s]={name:u.slice(2)}:r[s]=u;}return r}catch(r){throw new h$1(r?.message)}}constructor(e$1,r=new Date){super(e$1,r),this.id=e$1.id,this.key=e$1.key,this.name={...e$1.name},this.description={...e$1.description},this.slug={...e$1.slug},this.brand=e$1.brand,this.pricing=Object.keys(e$1.pricing).reduce((o,s)=>(e$1.pricing[s]&&(o[s]=new a$1(e$1.pricing[s])),o),{}),this.targetGender=e$1.targetGender,this.attributes=a.deepClone(e$1.attributes),this.specifications=a.deepClone(e$1.specifications),this.categories=a.deepClone(e$1.categories);let i=new Set;this.variants=(e$1.variants||[]).map(o=>{if(!o.selectionAttributes||typeof o.selectionAttributes!="object")throw new h$1("Selection attributes are required");this.checkSelectionAttributes(o.selectionAttributes);let s=t.generateSelectionAttributesKey(o.selectionAttributes);if(i.has(s))throw new e(s);return i.add(s),{sku:o.sku,selectionAttributes:o.selectionAttributes,images:{primary:new b$2(o.images.primary),gallery:(o.images.gallery||[]).map(u=>new b$2(u))}}}),this.isActive=e$1.isActive,this.searchTags=e$1.searchTags?a.deepClone(e$1.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[e$1[e]]??this.name.en:a.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[e$1[e]]??this.description.en:a.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[e$1[e]]??this.slug.en:a.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return a.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:a.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let r=t.generateSelectionAttributesKey(e),i=this.variants.find(o=>t.generateSelectionAttributesKey(o.selectionAttributes)===r);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,r){switch(r){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return a.deepClone(this.categories)}getSpecifications(e){return e?a.deepClone(this.specifications[e]??this.specifications[e$1[e]]??this.specifications.en):a.deepClone(this.specifications)}getSearchTags(e){return e?a.deepClone(this.searchTags[e]??this.searchTags[e$1[e]]??this.searchTags.en):a.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((r,i)=>(this.pricing[i]&&(r[i]=this.pricing[i]?.getDetails()),r),{}),attributes:this.getAttributes(),variants:this.variants.map(r=>({sku:r.sku,selectionAttributes:a.deepClone(r.selectionAttributes),images:{primary:r.images.primary.getDetails(),gallery:r.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new h$1("Selection attributes are required");Object.keys(this.attributes).forEach(r=>{if(r.toLowerCase()==="size")return;let i=this.attributes[r],o=e[r];if(o===void 0)throw new h$1(`Selection attribute '${r}' is missing`);if(typeof i=="string"){if(typeof o!="string"||i!==o)throw new h$1(`Selection attribute '${r}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof o!="string"||!i.includes(o))throw new h$1(`Selection attribute '${r}' is invalid`)}else if(typeof o!="object"||!("name"in o)||i.findIndex(s=>s.name===o.name)<0)throw new h$1(`Selection attribute '${r}' is invalid`)}});}validateSelectionAttribute(e){let r=t.generateSelectionAttributesKey(e);return this.variants.some(i=>t.generateSelectionAttributesKey(i.selectionAttributes)===r)}validateSize(e){return this.attributes.size.includes(e)}};export{a,f as b};//# sourceMappingURL=chunk-MHLRJ4IJ.mjs.map
2
+ //# sourceMappingURL=chunk-MHLRJ4IJ.mjs.map