b23-lib 3.9.8 → 3.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Auth/index.js +1 -1
- package/dist/Auth/index.js.map +1 -1
- package/dist/Auth/index.mjs +1 -1
- package/dist/Classes/Cart.d.mts +1 -1
- package/dist/Classes/Cart.d.ts +1 -1
- package/dist/Classes/Cart.js +1 -1
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Charge.js.map +1 -1
- package/dist/Classes/Charge.mjs +1 -1
- package/dist/Classes/Coupon.js +1 -1
- package/dist/Classes/Coupon.js.map +1 -1
- package/dist/Classes/Coupon.mjs +1 -1
- package/dist/Classes/Inventory.d.mts +1 -1
- package/dist/Classes/Inventory.d.ts +1 -1
- package/dist/Classes/Inventory.js +1 -1
- package/dist/Classes/Inventory.js.map +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/Invoice.d.mts +1 -1
- package/dist/Classes/Invoice.d.ts +1 -1
- package/dist/Classes/LineItem.d.mts +1 -1
- package/dist/Classes/LineItem.d.ts +1 -1
- package/dist/Classes/LineItem.js +1 -1
- package/dist/Classes/LineItem.js.map +1 -1
- package/dist/Classes/LineItem.mjs +1 -1
- package/dist/Classes/Order.d.mts +1 -1
- package/dist/Classes/Order.d.ts +1 -1
- package/dist/Classes/Order.js +1 -1
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/Product.d.mts +1 -1
- package/dist/Classes/Product.d.ts +1 -1
- package/dist/Classes/Product.js +1 -1
- package/dist/Classes/Product.js.map +1 -1
- package/dist/Classes/Product.mjs +1 -1
- package/dist/Classes/ShoppingContainer.d.mts +1 -1
- package/dist/Classes/ShoppingContainer.d.ts +1 -1
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/Classes/TieredPrice.d.mts +1 -1
- package/dist/Classes/TieredPrice.d.ts +1 -1
- package/dist/Classes/TieredPrice.js +1 -1
- package/dist/Classes/TieredPrice.js.map +1 -1
- package/dist/Classes/TieredPrice.mjs +1 -1
- package/dist/{TieredPrice-D512SmTC.d.ts → TieredPrice-BDkfC-bt.d.ts} +12 -8
- package/dist/{TieredPrice-DtpmvAJJ.d.mts → TieredPrice-Cs3iLEWQ.d.mts} +12 -8
- package/dist/{chunk-KFXRFY63.mjs → chunk-4PTWJI6J.mjs} +2 -2
- package/dist/{chunk-KFXRFY63.mjs.map → chunk-4PTWJI6J.mjs.map} +1 -1
- package/dist/{chunk-A34BAO7J.mjs → chunk-5N2HRXWJ.mjs} +2 -2
- package/dist/{chunk-A34BAO7J.mjs.map → chunk-5N2HRXWJ.mjs.map} +1 -1
- package/dist/{chunk-UO6WBOEX.mjs → chunk-MBR2GRKU.mjs} +2 -2
- package/dist/{chunk-UO6WBOEX.mjs.map → chunk-MBR2GRKU.mjs.map} +1 -1
- package/dist/{chunk-56TRG5UD.mjs → chunk-NXDEYUDI.mjs} +2 -2
- package/dist/{chunk-56TRG5UD.mjs.map → chunk-NXDEYUDI.mjs.map} +1 -1
- package/dist/{chunk-6IGPC7FH.mjs → chunk-SZLAIOMF.mjs} +2 -2
- package/dist/{chunk-6IGPC7FH.mjs.map → chunk-SZLAIOMF.mjs.map} +1 -1
- package/dist/chunk-XZFALA7N.mjs +2 -0
- package/dist/chunk-XZFALA7N.mjs.map +1 -0
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-AMIRIUMH.mjs +0 -2
- package/dist/chunk-AMIRIUMH.mjs.map +0 -1
|
@@ -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","taxableBase","extractExclusiveBase","distributedTaxes","calculateDistributedTaxes","taxTotal","dt","grandTotal","k","v"],"mappings":"qSA6FqBA,IAAAA,CAAAA,CAArB,cAAyCC,CAAiB,CAC/C,EAAA,CACA,IACA,CAAA,IAAA,CACA,QACA,CAAA,MAAA,CACA,OACA,CAAA,UAAA,CACA,KAEV,CAAA,WAAA,CAAYC,EAAwB,CAenC,GAdA,KAAMA,CAAAA,CAAI,CACV,CAAA,IAAA,CAAK,EAAKA,CAAAA,CAAAA,CAAK,EACf,CAAA,IAAA,CAAK,IAAOA,CAAAA,CAAAA,CAAK,IACjB,CAAA,IAAA,CAAK,KAAOA,CAAK,CAAA,IAAA,CACjB,IAAK,CAAA,QAAA,CAAWA,CAAK,CAAA,QAAA,CACrB,IAAK,CAAA,MAAA,CAASA,CAAK,CAAA,MAAA,CACnB,IAAK,CAAA,UAAA,CAAaA,CAAK,CAAA,UAAA,CACvB,KAAK,OAAU,CAAA,CACd,gBAAkB,CAAA,IAAIC,GAAWD,CAAAA,CAAAA,CAAK,OAAQ,CAAA,gBAAgB,CAC9D,CAAA,WAAA,CAAaA,CAAK,CAAA,OAAA,CAAQ,WAC1B,CAAA,iBAAA,CAAmBA,EAAK,OAAQ,CAAA,iBAAA,CAAkB,GAAIE,CAAAA,CAAAA,EAAK,IAAIC,GAAAA,CAAaD,CAAC,CAAC,CAC/E,CAAA,CAEA,IAAK,CAAA,gBAAA,CAAiB,IAAK,CAAA,OAAA,CAAQ,iBAAiB,CACjD,CA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,YACxC,CAAA,iBAAA,CAAmB,MAAO,CAAA,WAAA,CAAY,MAAO,CAAA,OAAA,CAAQ,IAAK,CAAA,KAAA,CAAM,iBAAiB,CAAA,CAAE,GAAI,CAAA,CAAC,CAACgD,CAAAA,CAAGC,CAAC,CAAA,GAAM,CAACD,CAAAA,CAAGC,CAAE,CAAA,UAAA,EAAY,CAAC,CAAC,CAAA,CACvH,eAAiB,CAAA,IAAA,CAAK,KAAM,CAAA,eAAA,CAAgB,UAAW,EAAA,CACvD,aAAc,MAAO,CAAA,WAAA,CAAY,MAAO,CAAA,OAAA,CAAQ,IAAK,CAAA,KAAA,CAAM,YAAY,CAAA,CAAE,GAAI,CAAA,CAAC,CAACD,CAAAA,CAAGC,CAAC,CAAA,GAAM,CAACD,CAAG,CAAA,CAC5F,IAAMC,CAAAA,CAAAA,CAAE,IACR,CAAA,aAAA,CAAeA,CAAE,CAAA,aAAA,CAAc,UAAW,EAAA,CAC1C,SAAWA,CAAAA,CAAAA,CAAE,SAAU,CAAA,UAAA,GACvB,MAAQA,CAAAA,CAAAA,CAAE,MACV,CAAA,SAAA,CAAWA,CAAE,CAAA,SACd,CAAC,CAAC,CAAC,CAAA,CACH,QAAU,CAAA,IAAA,CAAK,KAAM,CAAA,QAAA,CAAS,UAAW,EAAA,CACzC,UAAY,CAAA,IAAA,CAAK,KAAM,CAAA,UAAA,CAAW,UAAW,EAC9C,CACA,CAAA,YAAA,CAAc,IAAK,CAAA,kBAAA,EACpB,CAED,CACD","file":"chunk-A34BAO7J.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 { extractExclusiveBase, calculateDistributedTaxes } from \"../Utils/TaxMath\";\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 * Updates the discounts applied to this line item and recalculates totals.\r\n\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. Extract exclusive base using TaxMath utility\r\n\t\tconst taxableBase = extractExclusiveBase(netChargeAmount, this.pricing.applicableTaxRule);\r\n\r\n\t\t// 3. Compute tax amounts per rule based on final taxable base\r\n\t\tconst distributedTaxes = calculateDistributedTaxes(taxableBase, netChargeAmount, this.pricing.applicableTaxRule);\r\n\t\tlet taxTotal = zero;\r\n\t\tdistributedTaxes.forEach(dt => {\r\n\t\t\tconst taxRule = this.pricing.applicableTaxRule.find(r => r.getTaxRuleId() === dt.ruleId)!;\r\n\t\t\ttaxBreakdown[dt.ruleId] = {\r\n\t\t\t\trate: dt.rate,\r\n\t\t\t\ttaxableAmount: taxableBase,\r\n\t\t\t\ttaxAmount: dt.taxAmount,\r\n\t\t\t\tsystem: taxRule.getTaxSystem(),\r\n\t\t\t\tsubSystem: taxRule.getTaxSubSystem()\r\n\t\t\t};\r\n\t\t\ttaxTotal = taxTotal.add(dt.taxAmount);\r\n\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: taxTotal,\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","taxableBase","extractExclusiveBase","distributedTaxes","calculateDistributedTaxes","taxTotal","dt","grandTotal","k","v"],"mappings":"qSA6FqBA,IAAAA,CAAAA,CAArB,cAAyCC,CAAiB,CAC/C,EAAA,CACA,IACA,CAAA,IAAA,CACA,QACA,CAAA,MAAA,CACA,OACA,CAAA,UAAA,CACA,KAEV,CAAA,WAAA,CAAYC,EAAwB,CAenC,GAdA,KAAMA,CAAAA,CAAI,CACV,CAAA,IAAA,CAAK,EAAKA,CAAAA,CAAAA,CAAK,EACf,CAAA,IAAA,CAAK,IAAOA,CAAAA,CAAAA,CAAK,IACjB,CAAA,IAAA,CAAK,KAAOA,CAAK,CAAA,IAAA,CACjB,IAAK,CAAA,QAAA,CA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AA,IAAA,CAAK,KAAM,CAAA,QAAA,CAAS,UAAW,EAAA,CACzC,UAAY,CAAA,IAAA,CAAK,KAAM,CAAA,UAAA,CAAW,UAAW,EAC9C,CACA,CAAA,YAAA,CAAc,IAAK,CAAA,kBAAA,EACpB,CAED,CACD","file":"chunk-5N2HRXWJ.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 { extractExclusiveBase, calculateDistributedTaxes } from \"../Utils/TaxMath\";\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 * Updates the discounts applied to this line item and recalculates totals.\r\n\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. Extract exclusive base using TaxMath utility\r\n\t\tconst taxableBase = extractExclusiveBase(netChargeAmount, this.pricing.applicableTaxRule);\r\n\r\n\t\t// 3. Compute tax amounts per rule based on final taxable base\r\n\t\tconst distributedTaxes = calculateDistributedTaxes(taxableBase, netChargeAmount, this.pricing.applicableTaxRule);\r\n\t\tlet taxTotal = zero;\r\n\t\tdistributedTaxes.forEach(dt => {\r\n\t\t\tconst taxRule = this.pricing.applicableTaxRule.find(r => r.getTaxRuleId() === dt.ruleId)!;\r\n\t\t\ttaxBreakdown[dt.ruleId] = {\r\n\t\t\t\trate: dt.rate,\r\n\t\t\t\ttaxableAmount: taxableBase,\r\n\t\t\t\ttaxAmount: dt.taxAmount,\r\n\t\t\t\tsystem: taxRule.getTaxSystem(),\r\n\t\t\t\tsubSystem: taxRule.getTaxSubSystem()\r\n\t\t\t};\r\n\t\t\ttaxTotal = taxTotal.add(dt.taxAmount);\r\n\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: taxTotal,\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}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a}from'./chunk-4PTWJI6J.mjs';import {a as a$1}from'./chunk-UIQH5QIR.mjs';import {e}from'./chunk-PL5HGCWN.mjs';import {u}from'./chunk-O6BLQQO7.mjs';import {b as b$1}from'./chunk-UXZBULDS.mjs';var y=(t=>(t.COUPON="coupon",t.AUTOMATIC="automatic",t))(y||{}),M=(t=>(t.FLAT="flat",t.PERCENTAGE="percentage",t))(M||{}),b=(t=>(t.SHIPPING="SHIPPING",t.CUSTOMER="CUSTOMER",t))(b||{}),P=(t=>(t.ALL="all",t.FTB="ftb",t))(P||{}),p=class extends b$1{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(e,t=new Date){if(super(e,t),this.couponCode=e.couponCode,this.name=a.deepClone(e.name),this.description=a.deepClone(e.description),this.type=e.type,this.customerId=e.customerId,this.validFrom=e.validFrom&&Date.parse(e.validFrom)?new Date(e.validFrom).toISOString():t.toISOString(),this.validTo=e.validTo&&Date.parse(e.validTo)?new Date(e.validTo).toISOString():t.toISOString(),this.minCartValue=Object.keys(e.minCartValue).reduce((o,i)=>{let r=e.minCartValue[i];return r&&(o[i]=new a$1(r)),o},{}),this.maxCartDiscount=Object.keys(e.maxCartDiscount).reduce((o,i)=>{let r=e.maxCartDiscount[i];return r&&(o[i]=new a$1(r)),o},{}),this.discountMethod=e.discountMethod,this.percentageValue=e.percentageValue??0,this.percentageValue>100)throw new u("Percentage value cannot be greater than 100");this.applicableTo=e.applicableTo,this.category=e.category;}getCode(){return this.couponCode}getName(e$1){return e$1?this.name[e$1]??this.name[e[e$1]]??this.name.en:{...this.name}}getDescription(e$1){return e$1?this.description[e$1]??this.description[e[e$1]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(e){return e?this.minCartValue[e]:{...this.minCartValue}}getMaxCartDiscount(e){return e?this.maxCartDiscount[e]:{...this.maxCartDiscount}}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:Object.keys(this.getMinCartValue()).reduce((e,t)=>{let o=this.getMinCartValue(t);return o&&(e[t]=o.getDetails()),e},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((e,t)=>{let o=this.getMaxCartDiscount(t);return o&&(e[t]=o.getDetails()),e},{}),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(e){return this.applicableTo==="all"||this.applicableTo==="ftb"&&e}calculateApplicableCouponDiscount(e,t,o,i,r=!0){let n=new a$1({amount:0,currency:i}),s;if(r&&!this.isActive())return n;let C=this.getMinCartValue(o),c=this.getMaxCartDiscount(o);if(!C||C.compareTo(e)>0||!c)return n;let h=this.getCategory(),D=this.getDiscountMethod(),u=h==="SHIPPING"?t:e;if(u.getAmount()<=0)return n;switch(D){case"flat":let T=c;s=u.min(T);break;case"percentage":s=u.multiply(this.getPercentageValue()/100).round();break;default:return n}return s.min(c)}};export{y as a,M as b,b as c,P as d,p as e};//# sourceMappingURL=chunk-MBR2GRKU.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-MBR2GRKU.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/Coupon.ts"],"names":["CouponType","CouponDiscountMethod","CouponCategory","ApplicableTo","CouponModel","BaseModel","data","date","Utils_default","acc","country","priceData","PriceModel","InvalidArgumentError","locale","LocaleLanguageMap","priceModel","ftbCustomer","cartValue","shippingCost","currency","checkExpiry","zeroDiscount","potentialDiscount","minCartValueReq","maxCartDiscountCap","couponCategory","discountMethod","targetValue","flatAmount"],"mappings":"uMAOO,IAAKA,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,MAAS,CAAA,QAAA,CACTA,EAAA,SAAY,CAAA,WAAA,CAFFA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAKAC,OACVA,CAAA,CAAA,IAAA,CAAO,MACPA,CAAAA,CAAAA,CAAA,WAAa,YAFHA,CAAAA,C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,CAA2B,CAAA,IAAIV,IAAW,CAAE,MAAA,CAAQ,CAAG,CAAA,QAAA,CAAAQ,CAAS,CAAC,CACjEG,CAAAA,CAAAA,CAGJ,GAAIF,CAAe,EAAA,CAAC,IAAK,CAAA,QAAA,GACvB,OAAOC,CAAAA,CAIT,IAAME,CAAAA,CAAkB,KAAK,eAAgBd,CAAAA,CAAO,CAC9Ce,CAAAA,CAAAA,CAAqB,IAAK,CAAA,kBAAA,CAAmBf,CAAO,CAAA,CAQ1D,GALI,CAACc,CAAAA,EAAmBA,CAAgB,CAAA,SAAA,CAAUN,CAAS,CAAI,CAAA,CAAA,EAK3D,CAACO,CAAAA,CACH,OAAOH,CAIT,CAAA,IAAMI,CAAiB,CAAA,IAAA,CAAK,WAAY,EAAA,CAClCC,CAAiB,CAAA,IAAA,CAAK,mBAEtBC,CAAAA,CAAAA,CAAcF,CAAmB,GAAA,UAAA,CAA0BP,EAAeD,CAGhF,CAAA,GAAIU,CAAY,CAAA,SAAA,IAAe,CAAG,CAAA,OAAON,CAEzC,CAAA,OAAQK,CAAgB,EACtB,IAAK,MAAA,CAEH,IAAME,CAAaJ,CAAAA,CAAAA,CACnBF,CAAoBK,CAAAA,CAAAA,CAAY,IAAIC,CAAU,CAAA,CAC9C,MACF,IAAK,aAEHN,CAAoBK,CAAAA,CAAAA,CAAY,QAAS,CAAA,IAAA,CAAK,oBAAuB,CAAA,GAAG,CAAE,CAAA,KAAA,GAC1E,MACF,QAEE,OAAON,CACX,CAKA,OAFsBC,CAAAA,CAAkB,GAAIE,CAAAA,CAAkB,CAGhE,CACF","file":"chunk-UO6WBOEX.mjs","sourcesContent":["import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, CurrencyCode, ISODateTimeUTC, LocaleCode, LocalizedString, RegionalPrice } from \"./Common\";\r\nimport { LocaleLanguageMap } from \"./Enum\";\r\nimport { InvalidArgumentError } from \"./Error\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\n\r\nexport enum CouponType {\r\n COUPON = \"coupon\",\r\n AUTOMATIC = \"automatic\",\r\n}\r\n\r\nexport enum CouponDiscountMethod {\r\n FLAT = \"flat\",\r\n PERCENTAGE = \"percentage\",\r\n}\r\n\r\nexport enum CouponCategory {\r\n SHIPPING = \"SHIPPING\",\r\n CUSTOMER = \"CUSTOMER\",\r\n}\r\n\r\nexport enum ApplicableTo {\r\n ALL = \"all\",\r\n FTB = \"ftb\",\r\n}\r\n\r\nexport type CouponAttribute = BaseAttributes & {\r\n couponCode: string;\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n type: CouponType;\r\n customerId?: string;\r\n validFrom: ISODateTimeUTC;\r\n validTo: ISODateTimeUTC;\r\n minCartValue: RegionalPrice;\r\n maxCartDiscount: RegionalPrice;\r\n discountMethod: CouponDiscountMethod;\r\n percentageValue?: number;\r\n applicableTo: ApplicableTo;\r\n category: CouponCategory;\r\n};\r\n\r\nexport type CouponData = Required<CouponAttribute>\r\n\r\n/**\r\n * Represents a discount coupon, extending BaseModel.\r\n */\r\nexport default class CouponModel extends BaseModel {\r\n protected couponCode: string;\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected type: CouponType;\r\n protected customerId?: string;\r\n protected validFrom: ISODateTimeUTC;\r\n protected validTo: ISODateTimeUTC;\r\n protected minCartValue: {\r\n [country in CountryCode]?: PriceModel;\r\n };\r\n protected maxCartDiscount: {\r\n [country in CountryCode]?: PriceModel;\r\n };\r\n protected discountMethod: CouponDiscountMethod;\r\n protected percentageValue: number;\r\n protected applicableTo: ApplicableTo;\r\n protected category: CouponCategory;\r\n\r\n /**\r\n * Creates an instance of CouponModel.\r\n * @param data - The initial coupon attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: CouponAttribute, date: Date = new Date()) {\r\n super(data, date);\r\n\r\n this.couponCode = data.couponCode;\r\n this.name = Utils.deepClone(data.name);\r\n this.description = Utils.deepClone(data.description);\r\n this.type = data.type;\r\n this.customerId = data.customerId;\r\n this.validFrom = data.validFrom && Date.parse(data.validFrom) ? new Date(data.validFrom).toISOString() : date.toISOString();\r\n this.validTo = data.validTo && Date.parse(data.validTo) ? new Date(data.validTo).toISOString() : date.toISOString();\r\n this.minCartValue = (Object.keys(data.minCartValue) as CountryCode[]).reduce((acc, country) => {\r\n const priceData = data.minCartValue[country] as PriceData;\r\n if (priceData) {\r\n acc[country] = new PriceModel(priceData);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: PriceModel });\r\n this.maxCartDiscount = (Object.keys(data.maxCartDiscount) as CountryCode[]).reduce((acc, country) => {\r\n const priceData = data.maxCartDiscount[country] as PriceData;\r\n if (priceData) {\r\n acc[country] = new PriceModel(priceData);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: PriceModel });\r\n this.discountMethod = data.discountMethod;\r\n this.percentageValue = data.percentageValue ?? 0;\r\n if (this.percentageValue > 100) {\r\n throw new InvalidArgumentError('Percentage value cannot be greater than 100');\r\n }\r\n\r\n this.applicableTo = data.applicableTo;\r\n this.category = data.category;\r\n }\r\n\r\n /** Gets the unique coupon code. */\r\n getCode(): string {\r\n return this.couponCode;\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the coupon name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon description object.\r\n * @returns A copy of the LocalizedString object for the description, or undefined.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the coupon description for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The description string for the specified locale.\r\n */\r\n getDescription(locale: LocaleCode): string\r\n getDescription(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.description[locale] ?? this.description[LocaleLanguageMap[locale]] ?? this.description.en;\r\n } else {\r\n return { ...this.description };\r\n }\r\n }\r\n\r\n /** Gets the type of coupon (COUPON or AUTOMATIC). */\r\n getType(): CouponType {\r\n return this.type;\r\n }\r\n\r\n /** Gets the specific customer ID this coupon is limited to, if any. */\r\n getCustomerId(): string {\r\n return this.customerId ?? '';\r\n }\r\n\r\n /** Gets the ISO date string from when the coupon is valid. */\r\n getValidFrom(): ISODateTimeUTC {\r\n return this.validFrom;\r\n }\r\n\r\n /** Gets the ISO date string until when the coupon is valid. */\r\n getValidTo(): ISODateTimeUTC {\r\n return this.validTo;\r\n }\r\n\r\n /**\r\n * Gets the list of minimum cart values required for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional minimum cart values.\r\n */\r\n getMinCartValue(): { [country in CountryCode]?: PriceModel }\r\n\r\n /**\r\n * Gets the minimum cart value required for the coupon for a specific country.\r\n * @param country - The country code to filter the minimum value for.\r\n * @returns The regional minimum cart value for the specified country, or undefined if not set for that country.\r\n */\r\n getMinCartValue(country: CountryCode): PriceModel | undefined\r\n getMinCartValue(country?: CountryCode) {\r\n if (country) {\r\n return this.minCartValue[country];\r\n }\r\n return { ...this.minCartValue };\r\n }\r\n\r\n /**\r\n * Gets the list of maximum discount amounts allowed for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional maximum discount caps.\r\n */\r\n getMaxCartDiscount(): { [country in CountryCode]?: PriceModel }\r\n /**\r\n * Gets the maximum discount amount allowed for the coupon for a specific country.\r\n * @param country - The country code to filter the maximum discount for.\r\n * @returns The regional maximum discount cap for the specified country, or undefined if not set for that country.\r\n */\r\n getMaxCartDiscount(country: CountryCode): PriceModel | undefined\r\n getMaxCartDiscount(country?: CountryCode) {\r\n if (country) {\r\n return this.maxCartDiscount[country];\r\n }\r\n return { ...this.maxCartDiscount };\r\n }\r\n\r\n /** Gets the discount method (FLAT or PERCENTAGE). */\r\n getDiscountMethod(): CouponDiscountMethod {\r\n return this.discountMethod;\r\n }\r\n\r\n /** Gets the percentage discount value (0-100). */\r\n getPercentageValue(): number {\r\n return this.percentageValue;\r\n }\r\n\r\n /** Gets the customer applicability rule (ALL or FTB). */\r\n getApplicableTo(): ApplicableTo {\r\n return this.applicableTo;\r\n }\r\n\r\n /** Gets the category of the coupon (SHIPPING or CUSTOMER). */\r\n getCategory(): CouponCategory {\r\n return this.category;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the coupon's details.\r\n * @returns A CouponData object.\r\n */\r\n getDetails(): CouponData {\r\n return {\r\n ...super.getDetails(),\r\n couponCode: this.getCode(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n type: this.getType(),\r\n customerId: this.getCustomerId(),\r\n validFrom: this.getValidFrom(),\r\n validTo: this.getValidTo(),\r\n minCartValue: (Object.keys(this.getMinCartValue()) as CountryCode[]).reduce((acc, country) => {\r\n const priceModel = this.getMinCartValue(country);\r\n if (priceModel) {\r\n acc[country] = priceModel.getDetails();\r\n }\r\n return acc;\r\n }, {} as RegionalPrice),\r\n maxCartDiscount: (Object.keys(this.getMaxCartDiscount()) as CountryCode[]).reduce((acc, country) => {\r\n const priceModel = this.getMaxCartDiscount(country);\r\n if (priceModel) {\r\n acc[country] = priceModel.getDetails();\r\n }\r\n return acc;\r\n }, {} as RegionalPrice),\r\n discountMethod: this.getDiscountMethod(),\r\n percentageValue: this.getPercentageValue(),\r\n applicableTo: this.getApplicableTo(),\r\n category: this.getCategory(),\r\n };\r\n }\r\n\r\n /**\r\n * Checks if the coupon is currently active based on its validity dates.\r\n * @returns True if the coupon is currently within its validity period, false otherwise.\r\n */\r\n isActive(): boolean {\r\n return new Date(this.validFrom) <= new Date() && new Date(this.validTo) >= new Date();\r\n }\r\n\r\n\r\n /**\r\n * Checks if the coupon is applicable to a customer based on their status (e.g., first-time buyer).\r\n * @param ftbCustomer - A boolean indicating whether the customer is a first-time buyer.\r\n * @returns True if the coupon's applicability rule matches the customer's status, false otherwise.\r\n */\r\n isApplicableTo(ftbCustomer: boolean): boolean {\r\n return this.applicableTo === ApplicableTo.ALL || (this.applicableTo === ApplicableTo.FTB && ftbCustomer);\r\n }\r\n\r\n /**\r\n * Calculates the discount value for a given coupon based on the current container state.\r\n * Returns 0 if the coupon is invalid, expired, or not applicable based on cart value or target category.\r\n * @param cartValue - The cart subtotal as a PriceModel.\r\n * @param shippingCost - The cart shipping cost.\r\n * @param country - The country code.\r\n * @param currency - The currency code.\r\n * @returns The calculated discount amount (rounded according to country rules).\r\n */\r\n public calculateApplicableCouponDiscount(cartValue: PriceModel, shippingCost: PriceModel, country: CountryCode, currency: CurrencyCode, checkExpiry: boolean = true): PriceModel {\r\n let zeroDiscount: PriceModel = new PriceModel({ amount: 0, currency });\r\n let potentialDiscount: PriceModel;\r\n\r\n // 1. Basic validation (active)\r\n if (checkExpiry && !this.isActive()) {\r\n return zeroDiscount;\r\n }\r\n\r\n // 2. Check regional requirements (min cart value, max discount)\r\n const minCartValueReq = this.getMinCartValue(country);\r\n const maxCartDiscountCap = this.getMaxCartDiscount(country);\r\n\r\n // If minCartValueReq is not set or the cart value is less than the minimum required, return zero discount\r\n if (!minCartValueReq || minCartValueReq.compareTo(cartValue) > 0) {\r\n return zeroDiscount;\r\n }\r\n\r\n // If maxCartDiscountCap is not set, return zero discount\r\n if (!maxCartDiscountCap) {\r\n return zeroDiscount;\r\n }\r\n\r\n // 3. Calculate potential discount based on method and category\r\n const couponCategory = this.getCategory();\r\n const discountMethod = this.getDiscountMethod();\r\n // Determine the value the coupon applies to (shipping cost or subtotal)\r\n const targetValue = couponCategory === CouponCategory.SHIPPING ? shippingCost : cartValue;\r\n\r\n // No discount if the target value is zero or less\r\n if (targetValue.getAmount() <= 0) return zeroDiscount;\r\n\r\n switch (discountMethod) {\r\n case CouponDiscountMethod.FLAT:\r\n // Flat discount is capped by the target value itself and the max discount cap\r\n const flatAmount = maxCartDiscountCap; // Use cap as the flat amount source? Or coupon.value? Needs clarification. Assuming cap IS the flat amount here.\r\n potentialDiscount = targetValue.min(flatAmount);\r\n break;\r\n case CouponDiscountMethod.PERCENTAGE:\r\n // Calculate percentage discount based on the target value\r\n potentialDiscount = targetValue.multiply(this.getPercentageValue() / 100).round();\r\n break;\r\n default:\r\n // Unknown discount method\r\n return zeroDiscount;\r\n }\r\n\r\n // 4. Apply maximum discount cap to the calculated potential discount\r\n const finalDiscount = potentialDiscount.min(maxCartDiscountCap);\r\n\r\n return finalDiscount;\r\n }\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/Classes/Coupon.ts"],"names":["CouponType","CouponDiscountMethod","CouponCategory","ApplicableTo","CouponModel","BaseModel","data","date","Utils_default","acc","country","priceData","PriceModel","InvalidArgumentError","locale","LocaleLanguageMap","priceModel","ftbCustomer","cartValue","shippingCost","currency","checkExpiry","zeroDiscount","potentialDiscount","minCartValueReq","maxCartDiscountCap","couponCategory","discountMethod","targetValue","flatAmount"],"mappings":"uMAOO,IAAKA,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,MAAS,CAAA,QAAA,CACTA,EAAA,SAAY,CAAA,WAAA,CAFFA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAKAC,OACVA,CAAA,CAAA,IAAA,CAAO,MACPA,CAAAA,CAAAA,CAAA,WAAa,YAFHA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAKAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,CAAA,CAAA,QAAA,CAAW,UACXA,CAAAA,CAAAA,CAAA,SAAW,UAFDA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAKAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,EAAA,GAAM,CAAA,KAAA,CACNA,CAAA,C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,CAAO,CAAA,CAQ1D,GALI,CAACc,CAAAA,EAAmBA,CAAgB,CAAA,SAAA,CAAUN,CAAS,CAAI,CAAA,CAAA,EAK3D,CAACO,CAAAA,CACH,OAAOH,CAIT,CAAA,IAAMI,CAAiB,CAAA,IAAA,CAAK,WAAY,EAAA,CAClCC,CAAiB,CAAA,IAAA,CAAK,mBAEtBC,CAAAA,CAAAA,CAAcF,CAAmB,GAAA,UAAA,CAA0BP,EAAeD,CAGhF,CAAA,GAAIU,CAAY,CAAA,SAAA,IAAe,CAAG,CAAA,OAAON,CAEzC,CAAA,OAAQK,CAAgB,EACtB,IAAK,MAAA,CAEH,IAAME,CAAaJ,CAAAA,CAAAA,CACnBF,CAAoBK,CAAAA,CAAAA,CAAY,IAAIC,CAAU,CAAA,CAC9C,MACF,IAAK,aAEHN,CAAoBK,CAAAA,CAAAA,CAAY,QAAS,CAAA,IAAA,CAAK,oBAAuB,CAAA,GAAG,CAAE,CAAA,KAAA,GAC1E,MACF,QAEE,OAAON,CACX,CAKA,OAFsBC,CAAAA,CAAkB,GAAIE,CAAAA,CAAkB,CAGhE,CACF","file":"chunk-MBR2GRKU.mjs","sourcesContent":["import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, CurrencyCode, ISODateTimeUTC, LocaleCode, LocalizedString, RegionalPrice } from \"./Common\";\r\nimport { LocaleLanguageMap } from \"./Enum\";\r\nimport { InvalidArgumentError } from \"./Error\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\n\r\nexport enum CouponType {\r\n COUPON = \"coupon\",\r\n AUTOMATIC = \"automatic\",\r\n}\r\n\r\nexport enum CouponDiscountMethod {\r\n FLAT = \"flat\",\r\n PERCENTAGE = \"percentage\",\r\n}\r\n\r\nexport enum CouponCategory {\r\n SHIPPING = \"SHIPPING\",\r\n CUSTOMER = \"CUSTOMER\",\r\n}\r\n\r\nexport enum ApplicableTo {\r\n ALL = \"all\",\r\n FTB = \"ftb\",\r\n}\r\n\r\nexport type CouponAttribute = BaseAttributes & {\r\n couponCode: string;\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n type: CouponType;\r\n customerId?: string;\r\n validFrom: ISODateTimeUTC;\r\n validTo: ISODateTimeUTC;\r\n minCartValue: RegionalPrice;\r\n maxCartDiscount: RegionalPrice;\r\n discountMethod: CouponDiscountMethod;\r\n percentageValue?: number;\r\n applicableTo: ApplicableTo;\r\n category: CouponCategory;\r\n};\r\n\r\nexport type CouponData = Required<CouponAttribute>\r\n\r\n/**\r\n * Represents a discount coupon, extending BaseModel.\r\n */\r\nexport default class CouponModel extends BaseModel {\r\n protected couponCode: string;\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected type: CouponType;\r\n protected customerId?: string;\r\n protected validFrom: ISODateTimeUTC;\r\n protected validTo: ISODateTimeUTC;\r\n protected minCartValue: {\r\n [country in CountryCode]?: PriceModel;\r\n };\r\n protected maxCartDiscount: {\r\n [country in CountryCode]?: PriceModel;\r\n };\r\n protected discountMethod: CouponDiscountMethod;\r\n protected percentageValue: number;\r\n protected applicableTo: ApplicableTo;\r\n protected category: CouponCategory;\r\n\r\n /**\r\n * Creates an instance of CouponModel.\r\n * @param data - The initial coupon attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: CouponAttribute, date: Date = new Date()) {\r\n super(data, date);\r\n\r\n this.couponCode = data.couponCode;\r\n this.name = Utils.deepClone(data.name);\r\n this.description = Utils.deepClone(data.description);\r\n this.type = data.type;\r\n this.customerId = data.customerId;\r\n this.validFrom = data.validFrom && Date.parse(data.validFrom) ? new Date(data.validFrom).toISOString() : date.toISOString();\r\n this.validTo = data.validTo && Date.parse(data.validTo) ? new Date(data.validTo).toISOString() : date.toISOString();\r\n this.minCartValue = (Object.keys(data.minCartValue) as CountryCode[]).reduce((acc, country) => {\r\n const priceData = data.minCartValue[country] as PriceData;\r\n if (priceData) {\r\n acc[country] = new PriceModel(priceData);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: PriceModel });\r\n this.maxCartDiscount = (Object.keys(data.maxCartDiscount) as CountryCode[]).reduce((acc, country) => {\r\n const priceData = data.maxCartDiscount[country] as PriceData;\r\n if (priceData) {\r\n acc[country] = new PriceModel(priceData);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: PriceModel });\r\n this.discountMethod = data.discountMethod;\r\n this.percentageValue = data.percentageValue ?? 0;\r\n if (this.percentageValue > 100) {\r\n throw new InvalidArgumentError('Percentage value cannot be greater than 100');\r\n }\r\n\r\n this.applicableTo = data.applicableTo;\r\n this.category = data.category;\r\n }\r\n\r\n /** Gets the unique coupon code. */\r\n getCode(): string {\r\n return this.couponCode;\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the coupon name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon description object.\r\n * @returns A copy of the LocalizedString object for the description, or undefined.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the coupon description for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The description string for the specified locale.\r\n */\r\n getDescription(locale: LocaleCode): string\r\n getDescription(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.description[locale] ?? this.description[LocaleLanguageMap[locale]] ?? this.description.en;\r\n } else {\r\n return { ...this.description };\r\n }\r\n }\r\n\r\n /** Gets the type of coupon (COUPON or AUTOMATIC). */\r\n getType(): CouponType {\r\n return this.type;\r\n }\r\n\r\n /** Gets the specific customer ID this coupon is limited to, if any. */\r\n getCustomerId(): string {\r\n return this.customerId ?? '';\r\n }\r\n\r\n /** Gets the ISO date string from when the coupon is valid. */\r\n getValidFrom(): ISODateTimeUTC {\r\n return this.validFrom;\r\n }\r\n\r\n /** Gets the ISO date string until when the coupon is valid. */\r\n getValidTo(): ISODateTimeUTC {\r\n return this.validTo;\r\n }\r\n\r\n /**\r\n * Gets the list of minimum cart values required for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional minimum cart values.\r\n */\r\n getMinCartValue(): { [country in CountryCode]?: PriceModel }\r\n\r\n /**\r\n * Gets the minimum cart value required for the coupon for a specific country.\r\n * @param country - The country code to filter the minimum value for.\r\n * @returns The regional minimum cart value for the specified country, or undefined if not set for that country.\r\n */\r\n getMinCartValue(country: CountryCode): PriceModel | undefined\r\n getMinCartValue(country?: CountryCode) {\r\n if (country) {\r\n return this.minCartValue[country];\r\n }\r\n return { ...this.minCartValue };\r\n }\r\n\r\n /**\r\n * Gets the list of maximum discount amounts allowed for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional maximum discount caps.\r\n */\r\n getMaxCartDiscount(): { [country in CountryCode]?: PriceModel }\r\n /**\r\n * Gets the maximum discount amount allowed for the coupon for a specific country.\r\n * @param country - The country code to filter the maximum discount for.\r\n * @returns The regional maximum discount cap for the specified country, or undefined if not set for that country.\r\n */\r\n getMaxCartDiscount(country: CountryCode): PriceModel | undefined\r\n getMaxCartDiscount(country?: CountryCode) {\r\n if (country) {\r\n return this.maxCartDiscount[country];\r\n }\r\n return { ...this.maxCartDiscount };\r\n }\r\n\r\n /** Gets the discount method (FLAT or PERCENTAGE). */\r\n getDiscountMethod(): CouponDiscountMethod {\r\n return this.discountMethod;\r\n }\r\n\r\n /** Gets the percentage discount value (0-100). */\r\n getPercentageValue(): number {\r\n return this.percentageValue;\r\n }\r\n\r\n /** Gets the customer applicability rule (ALL or FTB). */\r\n getApplicableTo(): ApplicableTo {\r\n return this.applicableTo;\r\n }\r\n\r\n /** Gets the category of the coupon (SHIPPING or CUSTOMER). */\r\n getCategory(): CouponCategory {\r\n return this.category;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the coupon's details.\r\n * @returns A CouponData object.\r\n */\r\n getDetails(): CouponData {\r\n return {\r\n ...super.getDetails(),\r\n couponCode: this.getCode(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n type: this.getType(),\r\n customerId: this.getCustomerId(),\r\n validFrom: this.getValidFrom(),\r\n validTo: this.getValidTo(),\r\n minCartValue: (Object.keys(this.getMinCartValue()) as CountryCode[]).reduce((acc, country) => {\r\n const priceModel = this.getMinCartValue(country);\r\n if (priceModel) {\r\n acc[country] = priceModel.getDetails();\r\n }\r\n return acc;\r\n }, {} as RegionalPrice),\r\n maxCartDiscount: (Object.keys(this.getMaxCartDiscount()) as CountryCode[]).reduce((acc, country) => {\r\n const priceModel = this.getMaxCartDiscount(country);\r\n if (priceModel) {\r\n acc[country] = priceModel.getDetails();\r\n }\r\n return acc;\r\n }, {} as RegionalPrice),\r\n discountMethod: this.getDiscountMethod(),\r\n percentageValue: this.getPercentageValue(),\r\n applicableTo: this.getApplicableTo(),\r\n category: this.getCategory(),\r\n };\r\n }\r\n\r\n /**\r\n * Checks if the coupon is currently active based on its validity dates.\r\n * @returns True if the coupon is currently within its validity period, false otherwise.\r\n */\r\n isActive(): boolean {\r\n return new Date(this.validFrom) <= new Date() && new Date(this.validTo) >= new Date();\r\n }\r\n\r\n\r\n /**\r\n * Checks if the coupon is applicable to a customer based on their status (e.g., first-time buyer).\r\n * @param ftbCustomer - A boolean indicating whether the customer is a first-time buyer.\r\n * @returns True if the coupon's applicability rule matches the customer's status, false otherwise.\r\n */\r\n isApplicableTo(ftbCustomer: boolean): boolean {\r\n return this.applicableTo === ApplicableTo.ALL || (this.applicableTo === ApplicableTo.FTB && ftbCustomer);\r\n }\r\n\r\n /**\r\n * Calculates the discount value for a given coupon based on the current container state.\r\n * Returns 0 if the coupon is invalid, expired, or not applicable based on cart value or target category.\r\n * @param cartValue - The cart subtotal as a PriceModel.\r\n * @param shippingCost - The cart shipping cost.\r\n * @param country - The country code.\r\n * @param currency - The currency code.\r\n * @returns The calculated discount amount (rounded according to country rules).\r\n */\r\n public calculateApplicableCouponDiscount(cartValue: PriceModel, shippingCost: PriceModel, country: CountryCode, currency: CurrencyCode, checkExpiry: boolean = true): PriceModel {\r\n let zeroDiscount: PriceModel = new PriceModel({ amount: 0, currency });\r\n let potentialDiscount: PriceModel;\r\n\r\n // 1. Basic validation (active)\r\n if (checkExpiry && !this.isActive()) {\r\n return zeroDiscount;\r\n }\r\n\r\n // 2. Check regional requirements (min cart value, max discount)\r\n const minCartValueReq = this.getMinCartValue(country);\r\n const maxCartDiscountCap = this.getMaxCartDiscount(country);\r\n\r\n // If minCartValueReq is not set or the cart value is less than the minimum required, return zero discount\r\n if (!minCartValueReq || minCartValueReq.compareTo(cartValue) > 0) {\r\n return zeroDiscount;\r\n }\r\n\r\n // If maxCartDiscountCap is not set, return zero discount\r\n if (!maxCartDiscountCap) {\r\n return zeroDiscount;\r\n }\r\n\r\n // 3. Calculate potential discount based on method and category\r\n const couponCategory = this.getCategory();\r\n const discountMethod = this.getDiscountMethod();\r\n // Determine the value the coupon applies to (shipping cost or subtotal)\r\n const targetValue = couponCategory === CouponCategory.SHIPPING ? shippingCost : cartValue;\r\n\r\n // No discount if the target value is zero or less\r\n if (targetValue.getAmount() <= 0) return zeroDiscount;\r\n\r\n switch (discountMethod) {\r\n case CouponDiscountMethod.FLAT:\r\n // Flat discount is capped by the target value itself and the max discount cap\r\n const flatAmount = maxCartDiscountCap; // Use cap as the flat amount source? Or coupon.value? Needs clarification. Assuming cap IS the flat amount here.\r\n potentialDiscount = targetValue.min(flatAmount);\r\n break;\r\n case CouponDiscountMethod.PERCENTAGE:\r\n // Calculate percentage discount based on the target value\r\n potentialDiscount = targetValue.multiply(this.getPercentageValue() / 100).round();\r\n break;\r\n default:\r\n // Unknown discount method\r\n return zeroDiscount;\r\n }\r\n\r\n // 4. Apply maximum discount cap to the calculated potential discount\r\n const finalDiscount = potentialDiscount.min(maxCartDiscountCap);\r\n\r\n return finalDiscount;\r\n }\r\n}\r\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$4,b as b$1}from'./chunk-MPKIC2MS.mjs';import {a as a$3}from'./chunk-EZ35IKUA.mjs';import {a as a$1,c}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a as a$4,b as b$1}from'./chunk-MPKIC2MS.mjs';import {a as a$3}from'./chunk-EZ35IKUA.mjs';import {a as a$1,c}from'./chunk-4PTWJI6J.mjs';import {b}from'./chunk-7RAIVZKB.mjs';import {a as a$2}from'./chunk-UIQH5QIR.mjs';import {e,o}from'./chunk-PL5HGCWN.mjs';import {d,c as c$1,f,g,i,j,k,b as b$2}from'./chunk-O6BLQQO7.mjs';import {a}from'./chunk-UXZBULDS.mjs';var I=class extends a{id;productKey;sku;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;productType;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,this.sku=t.sku,this.selectionAttributes=a$1.deepClone(t.selectionAttributes),this.name=a$1.deepClone(t.name),this.specifications=a$1.deepClone(t.specifications),this.primaryImage=new b(t.primaryImage),this.subItems=a$1.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new d(i.size);e.add(i.size);}),this.pricing={unitPrice:new a$2(t.pricing.unitPrice),tierPricing:c.create(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(i=>new a$3(i))},this.validateTaxRules(this.pricing.applicableTaxRule),this.state=t.state??"INITIAL",this.productType=t.productType??"GOODS",this.total={quantity:t.total.quantity,unitPrice:new a$2(t.total.unitPrice),subtotal:new a$2(t.total.subtotal),discountTotal:new a$2(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([i,a])=>[i,new a$2(a)])),netUnitPrice:new a$2(t.total.netUnitPrice),netSubtotal:new a$2(t.total.netSubtotal),taxTotal:new a$2(t.total.taxTotal),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([i,a])=>[i,{rate:a.rate,taxableUnitPrice:new a$2(a.taxableUnitPrice),taxPerUnit:new a$2(a.taxPerUnit),taxAmount:new a$2(a.taxAmount),system:a.system,subSystem:a.subSystem}])),grandTotal:new a$2(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSku(){return this.sku}getSelectionAttributes(){return a$1.deepClone(this.selectionAttributes)}getName(t){return t?a$1.deepClone(this.name[t]??this.name[e[t]]??this.name.en):a$1.deepClone(this.name)}getSpecifications(t){return t?a$1.deepClone(this.specifications[t]??this.specifications[e[t]]??this.specifications.en):a$1.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return a$1.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getState(){return this.state}getProductType(){return this.productType}getTotal(){return {quantity:this.total.quantity,unitPrice:this.total.unitPrice,subtotal:this.total.subtotal,discountTotal:this.total.discountTotal,discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([t,e])=>[t,e])),netUnitPrice:this.total.netUnitPrice,netSubtotal:this.total.netSubtotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableUnitPrice:e.taxableUnitPrice,taxPerUnit:e.taxPerUnit,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),grandTotal:this.total.grandTotal}}getDetails(){let t=this.getPricing(),e=this.getTotal();return {id:this.getId(),productKey:this.getProductKey(),sku:this.getSku(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:t.unitPrice.getDetails(),tierPricing:t.tierPricing.getDetails(),taxCategory:t.taxCategory,applicableTaxRule:t.applicableTaxRule.map(i=>i.getDetails())},state:this.getState(),productType:this.getProductType(),total:{quantity:e.quantity,unitPrice:e.unitPrice.getDetails(),subtotal:e.subtotal.getDetails(),discountTotal:e.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(e.discountBreakdown).map(([i,a])=>[i,a.getDetails()])),netUnitPrice:e.netUnitPrice.getDetails(),netSubtotal:e.netSubtotal.getDetails(),taxTotal:e.taxTotal.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(e.taxBreakdown).map(([i,a])=>[i,{rate:a.rate,taxableUnitPrice:a.taxableUnitPrice.getDetails(),taxPerUnit:a.taxPerUnit.getDetails(),taxAmount:a.taxAmount.getDetails(),system:a.system,subSystem:a.subSystem}])),grandTotal:e.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}validateTaxRules(t){let e=new Set;for(let i=0;i<t.length;i++){let a=t[i].getTaxRuleId();if(e.has(a))throw new c$1("Duplicate tax rule ID found: "+a);e.add(a);}}addSubItems(t,e){t.forEach(i=>{let a=this.subItems.find(u=>u.size===i.size);a?a.quantity=e?a.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity>0),this.calculateTotals();}updateProductData(t,e,i$1){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new f;if(!t.getIsActive())throw new g;this.subItems.forEach(c=>{if(!t.validateSize(c.size))throw new i});let a=t.getPriceDetails(e);if(!a||a.getCurrency()!==i$1)throw new j;this.name=t.getName(),this.specifications=t.getSpecifications(),this.sku=t.getSku(this.selectionAttributes),this.primaryImage=t.getImages(this.selectionAttributes).primary;let u=this.subItems.reduce((c,p)=>c+p.quantity,0),b=a.getApplicableUnitPrice(u,this.selectionAttributes);this.productType=t.getProductType(),this.pricing={unitPrice:b,tierPricing:a,taxCategory:a.getTaxCategory(),applicableTaxRule:this.pricing.applicableTaxRule},this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discountBreakdown=e,this.calculateTotals();}updateTax(t){t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new k}),this.validateTaxRules(t),this.pricing.applicableTaxRule=t,this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((s,n)=>s+n.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,unitPrice:t,subtotal:t,discountTotal:t,discountBreakdown:{},netUnitPrice:t,netSubtotal:t,taxTotal:t,taxBreakdown:{},grandTotal:t};return}let i=this.pricing.tierPricing.getApplicableUnitPrice(e,this.selectionAttributes),a=i.multiply(e),u=Object.values(this.total.discountBreakdown).reduce((s,n)=>s.add(n),t),b=a.subtract(u),c=e>0?b.divide(e):t,p={},d=t,P=i,S=a,h=b,l=c;this.pricing.tierPricing.getIsTaxInclusive()?(P=a$4(i,this.pricing.applicableTaxRule),S=P.multiply(e),c.getAmount()>0&&(l=a$4(c,this.pricing.applicableTaxRule),h=l.multiply(e),b$1(l,c,this.pricing.applicableTaxRule).forEach(n=>{let g=n.taxAmount.multiply(e).round(),m=this.pricing.applicableTaxRule.find(O=>O.getTaxRuleId()===n.ruleId);p[n.ruleId]={rate:n.rate,taxableUnitPrice:l,taxPerUnit:n.taxAmount,taxAmount:g,system:m.getTaxSystem(),subSystem:m.getTaxSubSystem()},d=d.add(g);}))):this.pricing.applicableTaxRule.forEach(s=>{let n=s.getApplicableTaxRate(l),g=s.calculateTax(l),m=g.multiply(e).round();p[s.getTaxRuleId()]={rate:n,taxableUnitPrice:l,taxPerUnit:g,taxAmount:m,system:s.getTaxSystem(),subSystem:s.getTaxSubSystem()},d=d.add(m);});let v=h.add(d);this.total={quantity:e,unitPrice:P,subtotal:S,discountTotal:u,discountBreakdown:this.total.discountBreakdown,netUnitPrice:l,netSubtotal:h,taxTotal:d,taxBreakdown:p,grandTotal:v};}updateState(t){if(this.state in o)this.state!==t&&(this.state=t);else throw new b$2(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.sku="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new b({sources:{original:""}}),this.subItems=[],this.productType="GOODS",this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[]},this.total={quantity:0,unitPrice:t,subtotal:t,discountTotal:t,discountBreakdown:{},netUnitPrice:t,netSubtotal:t,taxTotal:t,taxBreakdown:{},grandTotal:t};}};export{I as a};//# sourceMappingURL=chunk-NXDEYUDI.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-NXDEYUDI.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/LineItem.ts"],"names":["LineItemModel","CustomFieldModel","data","Utils_default","ImageInfoModel","uniqueSelectionAttributes","item","DuplicateSizeError","PriceModel","TieredPriceModel","rule","TaxRuleModel","couponCode","discount","taxRuleId","taxBreakdown","locale","LocaleLanguageMap","pricing","total","taxRules","uniqueTaxRule","currentTaxRuleId","InvalidLineItemTaxRuleError","subItems","addQuantity","subItem","existingSubItem","sub","product","cartCountry","cartCurrency","ProductMismatchError","ProductInactiveError","SizeMismatchError","productPricing","PricingNotFoundError","quantity","sum","s","unitPrice","appliedDiscounts","lineItemDiscounts","taxRule","InvalidTaxRuleError","zero","totalQuantity","tierUnitPrice","initialSubTotal","totalDiscount","initialNetSubtotal","initialNetUnitPrice","taxTotal","finalUnitPrice","finalSubTotal","finalNetSubtotal","finalNetUnitPrice","extractExclusiveBase","calculateDistributedTaxes","dt","taxAmount","r","rate","taxPerUnit","grandTotal","newState","LineItemState","InvalidLineItemStateError"],"mappings":"6WA8GA,IAAqBA,EAArB,cAA2CC,CAAiB,CAChD,EAAA,CACA,WACA,GACA,CAAA,mBA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","file":"chunk-56TRG5UD.mjs","sourcesContent":["import Utils from \"../Utils\";\r\nimport { Color, CountryCode, CurrencyCode, LocaleCode, LocalizedString, LocalizedValue } from \"./Common\";\r\nimport CouponModel from \"./Coupon\";\r\nimport { LineItemState, LocaleLanguageMap, TaxSystem, ProductType } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport ProductModel, { ProductSelectionAttributes, ProductSpecification, SelectionAttributes } from \"./Product\";\r\nimport { TaxRuleData, TaxRuleModel } from \"./TaxRule\";\r\nimport { TieredPriceData, TieredPriceModel } from \"./TieredPrice\";\r\nimport {\r\n DuplicateSizeError,\r\n ProductMismatchError,\r\n ProductInactiveError,\r\n SizeMismatchError,\r\n PricingNotFoundError,\r\n InvalidTaxRuleError,\r\n InvalidLineItemStateError,\r\n InvalidLineItemTaxRuleError\r\n} from \"./Error\";\r\nimport { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\nimport { extractExclusiveBase, calculateDistributedTaxes } from \"../Utils/TaxMath\";\r\n\r\nexport type SubItem = {\r\n size: string | 'ONESIZE';\r\n quantity: number;\r\n};\r\n\r\nexport type LineItemPricing = {\r\n unitPrice: PriceData;\r\n tierPricing: TieredPriceData;\r\n taxCategory: string;\r\n applicableTaxRule: TaxRuleData[];\r\n};\r\n\r\nexport type LineItemPricingModel = {\r\n unitPrice: PriceModel;\r\n tierPricing: TieredPriceModel;\r\n taxCategory: string;\r\n applicableTaxRule: TaxRuleModel[];\r\n};\r\n\r\nexport type LineItemTaxBreakdown = {\r\n rate: number; // 0.09 for 9%\r\n taxableUnitPrice: PriceData; // effectiveUnitPrice used for calculation\r\n taxPerUnit: PriceData; // tax on single unit\r\n taxAmount: PriceData; // taxPerUnit × quantity (total tax)\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type LineItemTaxBreakdownModel = {\r\n rate: number;\r\n taxableUnitPrice: PriceModel;\r\n taxPerUnit: PriceModel;\r\n taxAmount: PriceModel;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type LineItemTotals = {\r\n quantity: number;\r\n unitPrice: PriceData; // original unit price (from tier pricing)\r\n subtotal: PriceData; // unitPrice × quantity\r\n discountTotal: PriceData; // sum of all discounts\r\n discountBreakdown: Record<string, PriceData>; // couponCode -> discount mapping\r\n netUnitPrice: PriceData; // unit price after discounts\r\n netSubtotal: PriceData; // subtotal - totalDiscount (taxable amount)\r\n taxTotal: PriceData; // sum of all tax amounts\r\n taxBreakdown: Record<string, LineItemTaxBreakdown>; // tax breakdown by tax rule\r\n grandTotal: PriceData; // effectiveSubtotal + taxTotal\r\n};\r\n\r\nexport type LineItemTotalsModel = {\r\n quantity: number;\r\n unitPrice: PriceModel;\r\n subtotal: PriceModel;\r\n discountTotal: PriceModel;\r\n discountBreakdown: Record<string, PriceModel>;\r\n netUnitPrice: PriceModel;\r\n netSubtotal: PriceModel;\r\n taxTotal: PriceModel;\r\n taxBreakdown: Record<string, LineItemTaxBreakdownModel>;\r\n grandTotal: PriceModel;\r\n};\r\n\r\nexport type LineItemAttributes = CustomFieldAttributes & {\r\n id: string;\r\n\r\n productKey: string;\r\n sku: string;\r\n selectionAttributes: SelectionAttributes;\r\n\r\n name: LocalizedString;\r\n specifications: LocalizedValue<ProductSpecification>;\r\n primaryImage: ImageInfoData;\r\n\r\n subItems: SubItem[];\r\n\r\n pricing: LineItemPricing;\r\n\r\n state?: LineItemState;\r\n productType?: ProductType;\r\n total: LineItemTotals;\r\n}\r\n\r\nexport type LineItemData = Required<LineItemAttributes>;\r\n\r\n/**\r\n * Represents a line item within a shopping cart.\r\n */\r\nexport default class LineItemModel extends CustomFieldModel {\r\n protected id: string;\r\n protected productKey: string;\r\n protected sku: string;\r\n protected selectionAttributes: SelectionAttributes;\r\n\r\n protected name: LocalizedString;\r\n protected specifications: LocalizedValue<ProductSpecification>;\r\n protected primaryImage: ImageInfoModel;\r\n protected subItems: SubItem[];\r\n protected pricing: LineItemPricingModel;\r\n\r\n protected state: LineItemState;\r\n protected productType: ProductType;\r\n protected total: LineItemTotalsModel;\r\n\r\n /**\r\n * Creates an instance of LineItemModel.\r\n * @param data - The initial line item attributes.\r\n */\r\n constructor(data: LineItemAttributes) {\r\n super(data);\r\n this.id = data.id;\r\n this.productKey = data.productKey;\r\n this.sku = data.sku;\r\n this.selectionAttributes = Utils.deepClone(data.selectionAttributes);\r\n\r\n this.name = Utils.deepClone(data.name);\r\n this.specifications = Utils.deepClone(data.specifications);\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.subItems = Utils.deepClone(data.subItems);\r\n\r\n let uniqueSelectionAttributes = new Set();\r\n this.subItems.forEach(item => {\r\n if (uniqueSelectionAttributes.has(item.size)) {\r\n throw new DuplicateSizeError(item.size);\r\n }\r\n uniqueSelectionAttributes.add(item.size);\r\n });\r\n\r\n this.pricing = {\r\n unitPrice: new PriceModel(data.pricing.unitPrice),\r\n tierPricing: TieredPriceModel.create(data.pricing.tierPricing),\r\n taxCategory: data.pricing.taxCategory,\r\n applicableTaxRule: data.pricing.applicableTaxRule.map(rule => new TaxRuleModel(rule)),\r\n }\r\n this.validateTaxRules(this.pricing.applicableTaxRule);\r\n\r\n this.state = data.state ?? LineItemState.INITIAL;\r\n this.productType = data.productType ?? ProductType.GOODS;\r\n\r\n this.total = {\r\n quantity: data.total.quantity,\r\n unitPrice: new PriceModel(data.total.unitPrice),\r\n subtotal: new PriceModel(data.total.subtotal),\r\n discountTotal: new PriceModel(data.total.discountTotal),\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(data.total.discountBreakdown).map(([couponCode, discount]) => [\r\n couponCode,\r\n new PriceModel(discount),\r\n ])\r\n ),\r\n netUnitPrice: new PriceModel(data.total.netUnitPrice),\r\n netSubtotal: new PriceModel(data.total.netSubtotal),\r\n taxTotal: new PriceModel(data.total.taxTotal),\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(data.total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n taxRuleId,\r\n {\r\n rate: taxBreakdown.rate,\r\n taxableUnitPrice: new PriceModel(taxBreakdown.taxableUnitPrice),\r\n taxPerUnit: new PriceModel(taxBreakdown.taxPerUnit),\r\n taxAmount: new PriceModel(taxBreakdown.taxAmount),\r\n system: taxBreakdown.system,\r\n subSystem: taxBreakdown.subSystem\r\n }\r\n ])\r\n ),\r\n grandTotal: new PriceModel(data.total.grandTotal),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the unique identifier of the line item.\r\n * @returns The unique ID string.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the product key associated with this line item.\r\n * @returns The product key string.\r\n */\r\n getProductKey(): string {\r\n return this.productKey;\r\n }\r\n\r\n /**\r\n * Gets the SKU of the line item.\r\n * @returns The SKU string.\r\n */\r\n getSku(): string {\r\n return this.sku;\r\n }\r\n\r\n /**\r\n * Gets the selection attributes (e.g., size, color) for this line item.\r\n * @returns A copy of the selection attributes object.\r\n */\r\n getSelectionAttributes(): SelectionAttributes {\r\n return Utils.deepClone(this.selectionAttributes);\r\n }\r\n\r\n /**\r\n * Gets the full localized product name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the product name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return Utils.deepClone(this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en);\r\n } else {\r\n return Utils.deepClone(this.name);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product specifications object.\r\n * @returns Product Specifications\r\n */\r\n getSpecifications(): LocalizedValue<ProductSpecification>\r\n /**\r\n * Gets the product specifications for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The ProductSpecification object for the specified locale, or undefined if not found.\r\n */\r\n getSpecifications(locale: LocaleCode): ProductSpecification | undefined\r\n getSpecifications(locale?: LocaleCode): LocalizedValue<ProductSpecification> | ProductSpecification | undefined {\r\n if (locale) {\r\n return Utils.deepClone(this.specifications[locale] ?? this.specifications[LocaleLanguageMap[locale]] ?? this.specifications.en);\r\n } else {\r\n return Utils.deepClone(this.specifications);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the image information model for this line item.\r\n * @returns The ImageInfoModel instance.\r\n */\r\n getImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /**\r\n * Gets the sub-items (size/quantity breakdown).\r\n * @returns A copy of the array of SubItems.\r\n */\r\n getSubItems(): SubItem[] {\r\n return Utils.deepClone(this.subItems);\r\n }\r\n\r\n /**\r\n * Gets the total quantity for this line item across all sub-items.\r\n * @returns The total quantity as a number.\r\n */\r\n getTotalQuantity(): number {\r\n return this.total.quantity;\r\n }\r\n\r\n /**\r\n * Gets the pricing information model for this line item.\r\n * @returns An object containing unit price, tiered pricing, tax category, and tax details.\r\n */\r\n getPricing() {\r\n return {\r\n unitPrice: this.pricing.unitPrice,\r\n tierPricing: this.pricing.tierPricing,\r\n taxCategory: this.pricing.taxCategory,\r\n applicableTaxRule: [...this.pricing.applicableTaxRule],\r\n };\r\n }\r\n\r\n /**\r\n * Gets the current state of the line item.\r\n * @returns The LineItemState enum value.\r\n */\r\n getState() {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the product type.\r\n * @returns ProductType.\r\n */\r\n getProductType(): ProductType {\r\n return this.productType;\r\n }\r\n\r\n /**\r\n * Gets the total price for this line item (including all sub-items).\r\n * @returns An object containing line item totals including subtotal, tax, discounts, and grand total.\r\n */\r\n getTotal(): LineItemTotalsModel {\r\n return {\r\n quantity: this.total.quantity,\r\n unitPrice: this.total.unitPrice,\r\n subtotal: this.total.subtotal,\r\n discountTotal: this.total.discountTotal,\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(this.total.discountBreakdown).map(([couponCode, discount]) => [\r\n couponCode,\r\n discount,\r\n ])\r\n ),\r\n netUnitPrice: this.total.netUnitPrice,\r\n netSubtotal: this.total.netSubtotal,\r\n taxTotal: this.total.taxTotal,\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n taxRuleId,\r\n {\r\n rate: taxBreakdown.rate,\r\n taxableUnitPrice: taxBreakdown.taxableUnitPrice,\r\n taxPerUnit: taxBreakdown.taxPerUnit,\r\n taxAmount: taxBreakdown.taxAmount,\r\n system: taxBreakdown.system,\r\n subSystem: taxBreakdown.subSystem\r\n }\r\n ])\r\n ),\r\n grandTotal: this.total.grandTotal,\r\n };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the line item's details.\r\n * @returns LineItemData.\r\n */\r\n getDetails(): LineItemData {\r\n const pricing = this.getPricing();\r\n const total = this.getTotal();\r\n return {\r\n id: this.getId(),\r\n productKey: this.getProductKey(),\r\n sku: this.getSku(),\r\n selectionAttributes: this.getSelectionAttributes(),\r\n name: this.getName(),\r\n specifications: this.getSpecifications(),\r\n primaryImage: this.getImage().getDetails(),\r\n subItems: this.getSubItems(),\r\n pricing: {\r\n unitPrice: pricing.unitPrice.getDetails(),\r\n tierPricing: pricing.tierPricing.getDetails(),\r\n taxCategory: pricing.taxCategory,\r\n applicableTaxRule: pricing.applicableTaxRule.map(rule => rule.getDetails()),\r\n },\r\n state: this.getState(),\r\n productType: this.getProductType(),\r\n total: {\r\n quantity: total.quantity,\r\n unitPrice: total.unitPrice.getDetails(),\r\n subtotal: total.subtotal.getDetails(),\r\n discountTotal: total.discountTotal.getDetails(),\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(total.discountBreakdown).map(([couponCode, discount]) => [\r\n couponCode,\r\n discount.getDetails(),\r\n ])\r\n ),\r\n netUnitPrice: total.netUnitPrice.getDetails(),\r\n netSubtotal: total.netSubtotal.getDetails(),\r\n taxTotal: total.taxTotal.getDetails(),\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n taxRuleId,\r\n {\r\n rate: taxBreakdown.rate,\r\n taxableUnitPrice: taxBreakdown.taxableUnitPrice.getDetails(),\r\n taxPerUnit: taxBreakdown.taxPerUnit.getDetails(),\r\n taxAmount: taxBreakdown.taxAmount.getDetails(),\r\n system: taxBreakdown.system,\r\n subSystem: taxBreakdown.subSystem\r\n }\r\n ])\r\n ),\r\n grandTotal: total.grandTotal.getDetails(),\r\n },\r\n customFields: this.getAllCustomFields()\r\n };\r\n }\r\n\r\n /**\r\n\t * Validates that there are no overlapping price brackets for any tax rules within the charge.\r\n\t * @param taxRules - The list of tax rules to validate.\r\n\t * @throws {InvalidLineItemTaxRuleError} Duplicate tax rule IDs will results in error.\r\n\t */\r\n private validateTaxRules(taxRules: TaxRuleModel[]): void {\r\n const uniqueTaxRule = new Set();\r\n for (let i = 0; i < taxRules.length; i++) {\r\n const currentTaxRuleId = taxRules[i].getTaxRuleId();\r\n if (uniqueTaxRule.has(currentTaxRuleId)) {\r\n throw new InvalidLineItemTaxRuleError(\"Duplicate tax rule ID found: \" + currentTaxRuleId);\r\n } else {\r\n uniqueTaxRule.add(currentTaxRuleId);\r\n }\r\n }\r\n }\r\n /**\r\n * Adds or updates sub-items (e.g., sizes with quantities) to the line item.\r\n * If a sub-item with the same size already exists, its quantity is either\r\n * updated by adding the new quantity or replaced entirely, based on the `addQuantity` flag.\r\n * Sub-items with a resulting quantity of 0 are removed.\r\n * @param subItems - An array of `SubItem` objects to add or update.\r\n * @param addQuantity - If true, adds the quantity from `subItem` to the existing quantity.\r\n * If false, replaces the existing quantity with the one from `subItem`.\r\n */\r\n addSubItems(subItems: SubItem[], addQuantity: boolean): void {\r\n subItems.forEach(subItem => {\r\n const existingSubItem = this.subItems.find(item => item.size === subItem.size);\r\n if (existingSubItem) {\r\n existingSubItem.quantity = addQuantity ? existingSubItem.quantity + subItem.quantity : subItem.quantity;\r\n } else {\r\n this.subItems.push(subItem);\r\n }\r\n })\r\n this.subItems = this.subItems.filter(sub => sub.quantity > 0);\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the line item with the latest product data (price, image, name, specifications).\r\n * Validates that the product matches the line item's selection and is active.\r\n * @param product - The product model to update from.\r\n * @param cartCountry - The country code for pricing context.\r\n * @param cartCurrency - The currency code for pricing context.\r\n * @throws {Error} If product mismatch, inactive, size mismatch, or pricing missing.\r\n */\r\n public updateProductData(product: ProductModel, cartCountry: CountryCode, cartCurrency: CurrencyCode): void {\r\n if (this.productKey !== product.getKey() || !product.validateSelectionAttribute(this.selectionAttributes)) {\r\n throw new ProductMismatchError();\r\n } else if (!product.getIsActive()) {\r\n throw new ProductInactiveError();\r\n }\r\n\r\n this.subItems.forEach(subItem => {\r\n if (!product.validateSize(subItem.size)) {\r\n throw new SizeMismatchError();\r\n }\r\n });\r\n\r\n const productPricing = product.getPriceDetails(cartCountry);\r\n if (!productPricing || productPricing.getCurrency() !== cartCurrency) {\r\n throw new PricingNotFoundError();\r\n }\r\n this.name = product.getName();\r\n this.specifications = product.getSpecifications();\r\n this.sku = product.getSku(this.selectionAttributes) as string;\r\n this.primaryImage = product.getImages(this.selectionAttributes).primary;\r\n\r\n const quantity = this.subItems.reduce((sum, s) => sum + s.quantity, 0);\r\n \r\n const unitPrice = productPricing.getApplicableUnitPrice(quantity, this.selectionAttributes);\r\n\r\n\r\n this.productType = product.getProductType();\r\n\r\n this.pricing = {\r\n unitPrice: unitPrice,\r\n tierPricing: productPricing,\r\n taxCategory: productPricing.getTaxCategory(),\r\n applicableTaxRule: this.pricing.applicableTaxRule\r\n }\r\n\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the discounts applied to this line item and recalculates totals.\r\n * @param appliedDiscounts - List of coupons and their allocated discount amounts.\r\n */\r\n public updateDiscounts(appliedDiscounts: { coupon: CouponModel, amount: PriceModel }[]): void {\r\n let lineItemDiscounts = {} as Record<string, PriceModel>;\r\n appliedDiscounts.forEach(discount => {\r\n lineItemDiscounts[discount.coupon.getCode()] = discount.amount;\r\n });\r\n\r\n this.total.discountBreakdown = lineItemDiscounts;\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the tax rule for this line item and recalculates totals.\r\n * @param taxRule - The new tax rule to apply.\r\n * @throws {Error} If the tax rule category does not match the item's tax category.\r\n */\r\n public updateTax(taxRules: TaxRuleModel[]): void {\r\n taxRules.forEach(taxRule => {\r\n if (!taxRule.appliesTo(this.pricing.taxCategory, taxRule.getCountry())) {\r\n throw new InvalidTaxRuleError();\r\n }\r\n });\r\n\r\n this.validateTaxRules(taxRules);\r\n this.pricing.applicableTaxRule = taxRules;\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Recalculates the line item totals based on current quantity, unit price, discounts, and tax rates.\r\n */\r\n public calculateTotals(): void {\r\n const zero = this.pricing.unitPrice.zero();\r\n const totalQuantity = this.subItems.reduce((sum, s) => sum + s.quantity, 0);\r\n\r\n if (this.state === LineItemState.CANCELLED) {\r\n this.total = {\r\n quantity: 0,\r\n unitPrice: zero,\r\n subtotal: zero,\r\n discountTotal: zero,\r\n discountBreakdown: {},\r\n netUnitPrice: zero,\r\n netSubtotal: zero,\r\n taxTotal: zero,\r\n taxBreakdown: {},\r\n grandTotal: zero\r\n };\r\n return;\r\n }\r\n\r\n const tierUnitPrice = this.pricing.tierPricing.getApplicableUnitPrice(totalQuantity, this.selectionAttributes);\r\n \r\n // Initial totals are treated as inclusive if the product is tax inclusive\r\n const initialSubTotal = tierUnitPrice.multiply(totalQuantity);\r\n const totalDiscount = Object.values(this.total.discountBreakdown).reduce((sum, s) => sum.add(s), zero);\r\n const initialNetSubtotal = initialSubTotal.subtract(totalDiscount);\r\n const initialNetUnitPrice = totalQuantity > 0 ? initialNetSubtotal.divide(totalQuantity) : zero;\r\n\r\n const taxBreakdown: Record<string, LineItemTaxBreakdownModel> = {};\r\n let taxTotal = zero;\r\n \r\n let finalUnitPrice = tierUnitPrice;\r\n let finalSubTotal = initialSubTotal;\r\n let finalNetSubtotal = initialNetSubtotal;\r\n let finalNetUnitPrice = initialNetUnitPrice;\r\n\r\n if (this.pricing.tierPricing.getIsTaxInclusive()) {\r\n // 1. Reverse calculate unit price for the base fields\r\n finalUnitPrice = extractExclusiveBase(tierUnitPrice, this.pricing.applicableTaxRule);\r\n finalSubTotal = finalUnitPrice.multiply(totalQuantity);\r\n\r\n // 2. Reverse calculate net unit price and distribute taxes perfectly\r\n if (initialNetUnitPrice.getAmount() > 0) {\r\n finalNetUnitPrice = extractExclusiveBase(initialNetUnitPrice, this.pricing.applicableTaxRule);\r\n finalNetSubtotal = finalNetUnitPrice.multiply(totalQuantity);\r\n\r\n const distributedTaxes = calculateDistributedTaxes(finalNetUnitPrice, initialNetUnitPrice, this.pricing.applicableTaxRule);\r\n \r\n distributedTaxes.forEach(dt => {\r\n const taxAmount = dt.taxAmount.multiply(totalQuantity).round();\r\n const taxRule = this.pricing.applicableTaxRule.find(r => r.getTaxRuleId() === dt.ruleId)!;\r\n \r\n taxBreakdown[dt.ruleId] = {\r\n rate: dt.rate,\r\n taxableUnitPrice: finalNetUnitPrice,\r\n taxPerUnit: dt.taxAmount,\r\n taxAmount: taxAmount,\r\n system: taxRule.getTaxSystem(),\r\n subSystem: taxRule.getTaxSubSystem()\r\n };\r\n taxTotal = taxTotal.add(taxAmount);\r\n });\r\n }\r\n } else {\r\n // Standard exclusive tax calculation\r\n this.pricing.applicableTaxRule.forEach(taxRule => {\r\n const rate = taxRule.getApplicableTaxRate(finalNetUnitPrice);\r\n const taxPerUnit = taxRule.calculateTax(finalNetUnitPrice);\r\n const taxAmount = taxPerUnit.multiply(totalQuantity).round();\r\n taxBreakdown[taxRule.getTaxRuleId()] = {\r\n rate: rate,\r\n taxableUnitPrice: finalNetUnitPrice,\r\n taxPerUnit: taxPerUnit,\r\n taxAmount: taxAmount,\r\n system: taxRule.getTaxSystem(),\r\n subSystem: taxRule.getTaxSubSystem()\r\n };\r\n taxTotal = taxTotal.add(taxAmount);\r\n });\r\n }\r\n\r\n const grandTotal = finalNetSubtotal.add(taxTotal);\r\n\r\n this.total = {\r\n quantity: totalQuantity,\r\n unitPrice: finalUnitPrice,\r\n subtotal: finalSubTotal,\r\n discountTotal: totalDiscount,\r\n discountBreakdown: this.total.discountBreakdown,\r\n netUnitPrice: finalNetUnitPrice,\r\n netSubtotal: finalNetSubtotal,\r\n taxTotal: taxTotal,\r\n taxBreakdown: taxBreakdown,\r\n grandTotal: grandTotal\r\n };\r\n }\r\n\r\n /**\r\n * Updates the line item's state.\r\n * @param newState \r\n */\r\n public updateState(newState: LineItemState): void {\r\n if (this.state in LineItemState) {\r\n if (this.state !== newState) {\r\n this.state = newState;\r\n }\r\n } else {\r\n throw new InvalidLineItemStateError(newState);\r\n }\r\n }\r\n\r\n /**\r\n * Resets the line item's properties to their default empty or initial state.\r\n * Useful for clearing out line item data without creating a new instance.\r\n * Recalculates total quantity and price total afterwards (which will be zero).\r\n */\r\n clearLineItem(): void {\r\n const zero = this.pricing.unitPrice.zero()\r\n this.id = '';\r\n this.productKey = '';\r\n this.sku = '';\r\n this.selectionAttributes = { color: { name: '' } };\r\n this.name = { en: '' };\r\n this.primaryImage = new ImageInfoModel({ sources: { original: '' } });\r\n this.subItems = [];\r\n this.productType = ProductType.GOODS;\r\n this.pricing = {\r\n unitPrice: zero,\r\n tierPricing: this.pricing.tierPricing,\r\n taxCategory: this.pricing.taxCategory,\r\n applicableTaxRule: []\r\n }\r\n this.total = {\r\n quantity: 0,\r\n unitPrice: zero,\r\n subtotal: zero,\r\n discountTotal: zero,\r\n discountBreakdown: {},\r\n netUnitPrice: zero,\r\n netSubtotal: zero,\r\n taxTotal: zero,\r\n taxBreakdown: {},\r\n grandTotal: zero\r\n };\r\n }\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/Classes/LineItem.ts"],"names":["LineItemModel","CustomFieldModel","data","Utils_default","ImageInfoModel","uniqueSelectionAttributes","item","DuplicateSizeError","PriceModel","TieredPriceModel","rule","TaxRuleModel","couponCode","discount","taxRuleId","taxBreakdown","locale","LocaleLanguageMap","pricing","total","taxRules","uniqueTaxRule","currentTaxRuleId","InvalidLineItemTaxRuleError","subItems","addQuantity","subItem","existingSubItem","sub","product","cartCountry","cartCurrency","ProductMismatchError","ProductInactiveError","SizeMismatchError","productPricing","PricingNotFoundError","quantity","sum","s","unitPrice","appliedDiscounts","lineItemDiscounts","taxRule","InvalidTaxRuleError","zero","totalQuantity","tierUnitPrice","initialSubTotal","totalDiscount","initialNetSubtotal","initialNetUnitPrice","taxTotal","finalUnitPrice","finalSubTotal","finalNetSubtotal","finalNetUnitPrice","extractExclusiveBase","calculateDistributedTaxes","dt","taxAmount","r","rate","taxPerUnit","grandTotal","newState","LineItemState","InvalidLineItemStateError"],"mappings":"6WA8GA,IAAqBA,EAArB,cAA2CC,CAAiB,CAChD,EAAA,CACA,WACA,GACA,CAAA,mBAAA,CAEA,IACA,CAAA,cAAA,CACA,aACA,QACA,CAAA,OAAA,CAEA,MACA,WACA,CAAA,KAAA,CAMV,YAAYC,CAA0B,CAAA,CACpC,KAAMA,CAAAA,CAAI,EACV,IAAK,CAAA,EAAA,CAAKA,EAAK,EACf,CAAA,IAAA,CAAK,WAAaA,CAAK,CAAA,UAAA,CACvB,IAAK,CAAA,GAAA,CAAMA,EAAK,GAChB,CAAA,IAAA,CAAK,oBAAsBC,GAAM,CAAA,SAAA,CAAUD,EAAK,mBAAmB,CAAA,CAEnE,IAAK,CAAA,IAAA,CAAOC,IAAM,SAAUD,CAAAA,CAAAA,CAAK,IAAI,CACrC,CAAA,IAAA,CAAK,eAAiBC,GAAM,CAAA,SAAA,CAAUD,CAAK,CAAA,cAAc,EACzD,IAAK,CAAA,YAAA,CAAe,IAAIE,CAAeF,CAAAA,CAAAA,CAAK,YAAY,CACxD,CAAA,IAAA,CAAK,QAAWC,CAAAA,GAAAA,CAAM,UAAUD,CAAK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AAA,CAAK,KAAO,CAAE,EAAA,CAAI,EAAG,CAAA,CACrB,KAAK,YAAe,CAAA,IAAIzC,EAAe,CAAE,OAAA,CAAS,CAAE,QAAU,CAAA,EAAG,CAAE,CAAC,EACpE,IAAK,CAAA,QAAA,CAAW,EAChB,CAAA,IAAA,CAAK,YAAc,OACnB,CAAA,IAAA,CAAK,OAAU,CAAA,CACb,UAAWyC,CACX,CAAA,WAAA,CAAa,KAAK,OAAQ,CAAA,WAAA,CAC1B,YAAa,IAAK,CAAA,OAAA,CAAQ,WAC1B,CAAA,iBAAA,CAAmB,EACrB,CAAA,CACA,KAAK,KAAQ,CAAA,CACX,SAAU,CACV,CAAA,SAAA,CAAWA,CACX,CAAA,QAAA,CAAUA,EACV,aAAeA,CAAAA,CAAAA,CACf,kBAAmB,EAAC,CACpB,aAAcA,CACd,CAAA,WAAA,CAAaA,CACb,CAAA,QAAA,CAAUA,EACV,YAAc,CAAA,GACd,UAAYA,CAAAA,CACd,EACF,CACF","file":"chunk-NXDEYUDI.mjs","sourcesContent":["import Utils from \"../Utils\";\r\nimport { Color, CountryCode, CurrencyCode, LocaleCode, LocalizedString, LocalizedValue } from \"./Common\";\r\nimport CouponModel from \"./Coupon\";\r\nimport { LineItemState, LocaleLanguageMap, TaxSystem, ProductType } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport ProductModel, { ProductSelectionAttributes, ProductSpecification, SelectionAttributes } from \"./Product\";\r\nimport { TaxRuleData, TaxRuleModel } from \"./TaxRule\";\r\nimport { TieredPriceData, TieredPriceModel } from \"./TieredPrice\";\r\nimport {\r\n DuplicateSizeError,\r\n ProductMismatchError,\r\n ProductInactiveError,\r\n SizeMismatchError,\r\n PricingNotFoundError,\r\n InvalidTaxRuleError,\r\n InvalidLineItemStateError,\r\n InvalidLineItemTaxRuleError\r\n} from \"./Error\";\r\nimport { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\nimport { extractExclusiveBase, calculateDistributedTaxes } from \"../Utils/TaxMath\";\r\n\r\nexport type SubItem = {\r\n size: string | 'ONESIZE';\r\n quantity: number;\r\n};\r\n\r\nexport type LineItemPricing = {\r\n unitPrice: PriceData;\r\n tierPricing: TieredPriceData;\r\n taxCategory: string;\r\n applicableTaxRule: TaxRuleData[];\r\n};\r\n\r\nexport type LineItemPricingModel = {\r\n unitPrice: PriceModel;\r\n tierPricing: TieredPriceModel;\r\n taxCategory: string;\r\n applicableTaxRule: TaxRuleModel[];\r\n};\r\n\r\nexport type LineItemTaxBreakdown = {\r\n rate: number; // 0.09 for 9%\r\n taxableUnitPrice: PriceData; // effectiveUnitPrice used for calculation\r\n taxPerUnit: PriceData; // tax on single unit\r\n taxAmount: PriceData; // taxPerUnit × quantity (total tax)\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type LineItemTaxBreakdownModel = {\r\n rate: number;\r\n taxableUnitPrice: PriceModel;\r\n taxPerUnit: PriceModel;\r\n taxAmount: PriceModel;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type LineItemTotals = {\r\n quantity: number;\r\n unitPrice: PriceData; // original unit price (from tier pricing)\r\n subtotal: PriceData; // unitPrice × quantity\r\n discountTotal: PriceData; // sum of all discounts\r\n discountBreakdown: Record<string, PriceData>; // couponCode -> discount mapping\r\n netUnitPrice: PriceData; // unit price after discounts\r\n netSubtotal: PriceData; // subtotal - totalDiscount (taxable amount)\r\n taxTotal: PriceData; // sum of all tax amounts\r\n taxBreakdown: Record<string, LineItemTaxBreakdown>; // tax breakdown by tax rule\r\n grandTotal: PriceData; // effectiveSubtotal + taxTotal\r\n};\r\n\r\nexport type LineItemTotalsModel = {\r\n quantity: number;\r\n unitPrice: PriceModel;\r\n subtotal: PriceModel;\r\n discountTotal: PriceModel;\r\n discountBreakdown: Record<string, PriceModel>;\r\n netUnitPrice: PriceModel;\r\n netSubtotal: PriceModel;\r\n taxTotal: PriceModel;\r\n taxBreakdown: Record<string, LineItemTaxBreakdownModel>;\r\n grandTotal: PriceModel;\r\n};\r\n\r\nexport type LineItemAttributes = CustomFieldAttributes & {\r\n id: string;\r\n\r\n productKey: string;\r\n sku: string;\r\n selectionAttributes: SelectionAttributes;\r\n\r\n name: LocalizedString;\r\n specifications: LocalizedValue<ProductSpecification>;\r\n primaryImage: ImageInfoData;\r\n\r\n subItems: SubItem[];\r\n\r\n pricing: LineItemPricing;\r\n\r\n state?: LineItemState;\r\n productType?: ProductType;\r\n total: LineItemTotals;\r\n}\r\n\r\nexport type LineItemData = Required<LineItemAttributes>;\r\n\r\n/**\r\n * Represents a line item within a shopping cart.\r\n */\r\nexport default class LineItemModel extends CustomFieldModel {\r\n protected id: string;\r\n protected productKey: string;\r\n protected sku: string;\r\n protected selectionAttributes: SelectionAttributes;\r\n\r\n protected name: LocalizedString;\r\n protected specifications: LocalizedValue<ProductSpecification>;\r\n protected primaryImage: ImageInfoModel;\r\n protected subItems: SubItem[];\r\n protected pricing: LineItemPricingModel;\r\n\r\n protected state: LineItemState;\r\n protected productType: ProductType;\r\n protected total: LineItemTotalsModel;\r\n\r\n /**\r\n * Creates an instance of LineItemModel.\r\n * @param data - The initial line item attributes.\r\n */\r\n constructor(data: LineItemAttributes) {\r\n super(data);\r\n this.id = data.id;\r\n this.productKey = data.productKey;\r\n this.sku = data.sku;\r\n this.selectionAttributes = Utils.deepClone(data.selectionAttributes);\r\n\r\n this.name = Utils.deepClone(data.name);\r\n this.specifications = Utils.deepClone(data.specifications);\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.subItems = Utils.deepClone(data.subItems);\r\n\r\n let uniqueSelectionAttributes = new Set();\r\n this.subItems.forEach(item => {\r\n if (uniqueSelectionAttributes.has(item.size)) {\r\n throw new DuplicateSizeError(item.size);\r\n }\r\n uniqueSelectionAttributes.add(item.size);\r\n });\r\n\r\n this.pricing = {\r\n unitPrice: new PriceModel(data.pricing.unitPrice),\r\n tierPricing: TieredPriceModel.create(data.pricing.tierPricing),\r\n taxCategory: data.pricing.taxCategory,\r\n applicableTaxRule: data.pricing.applicableTaxRule.map(rule => new TaxRuleModel(rule)),\r\n }\r\n this.validateTaxRules(this.pricing.applicableTaxRule);\r\n\r\n this.state = data.state ?? LineItemState.INITIAL;\r\n this.productType = data.productType ?? ProductType.GOODS;\r\n\r\n this.total = {\r\n quantity: data.total.quantity,\r\n unitPrice: new PriceModel(data.total.unitPrice),\r\n subtotal: new PriceModel(data.total.subtotal),\r\n discountTotal: new PriceModel(data.total.discountTotal),\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(data.total.discountBreakdown).map(([couponCode, discount]) => [\r\n couponCode,\r\n new PriceModel(discount),\r\n ])\r\n ),\r\n netUnitPrice: new PriceModel(data.total.netUnitPrice),\r\n netSubtotal: new PriceModel(data.total.netSubtotal),\r\n taxTotal: new PriceModel(data.total.taxTotal),\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(data.total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n taxRuleId,\r\n {\r\n rate: taxBreakdown.rate,\r\n taxableUnitPrice: new PriceModel(taxBreakdown.taxableUnitPrice),\r\n taxPerUnit: new PriceModel(taxBreakdown.taxPerUnit),\r\n taxAmount: new PriceModel(taxBreakdown.taxAmount),\r\n system: taxBreakdown.system,\r\n subSystem: taxBreakdown.subSystem\r\n }\r\n ])\r\n ),\r\n grandTotal: new PriceModel(data.total.grandTotal),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the unique identifier of the line item.\r\n * @returns The unique ID string.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the product key associated with this line item.\r\n * @returns The product key string.\r\n */\r\n getProductKey(): string {\r\n return this.productKey;\r\n }\r\n\r\n /**\r\n * Gets the SKU of the line item.\r\n * @returns The SKU string.\r\n */\r\n getSku(): string {\r\n return this.sku;\r\n }\r\n\r\n /**\r\n * Gets the selection attributes (e.g., size, color) for this line item.\r\n * @returns A copy of the selection attributes object.\r\n */\r\n getSelectionAttributes(): SelectionAttributes {\r\n return Utils.deepClone(this.selectionAttributes);\r\n }\r\n\r\n /**\r\n * Gets the full localized product name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the product name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return Utils.deepClone(this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en);\r\n } else {\r\n return Utils.deepClone(this.name);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product specifications object.\r\n * @returns Product Specifications\r\n */\r\n getSpecifications(): LocalizedValue<ProductSpecification>\r\n /**\r\n * Gets the product specifications for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The ProductSpecification object for the specified locale, or undefined if not found.\r\n */\r\n getSpecifications(locale: LocaleCode): ProductSpecification | undefined\r\n getSpecifications(locale?: LocaleCode): LocalizedValue<ProductSpecification> | ProductSpecification | undefined {\r\n if (locale) {\r\n return Utils.deepClone(this.specifications[locale] ?? this.specifications[LocaleLanguageMap[locale]] ?? this.specifications.en);\r\n } else {\r\n return Utils.deepClone(this.specifications);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the image information model for this line item.\r\n * @returns The ImageInfoModel instance.\r\n */\r\n getImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /**\r\n * Gets the sub-items (size/quantity breakdown).\r\n * @returns A copy of the array of SubItems.\r\n */\r\n getSubItems(): SubItem[] {\r\n return Utils.deepClone(this.subItems);\r\n }\r\n\r\n /**\r\n * Gets the total quantity for this line item across all sub-items.\r\n * @returns The total quantity as a number.\r\n */\r\n getTotalQuantity(): number {\r\n return this.total.quantity;\r\n }\r\n\r\n /**\r\n * Gets the pricing information model for this line item.\r\n * @returns An object containing unit price, tiered pricing, tax category, and tax details.\r\n */\r\n getPricing() {\r\n return {\r\n unitPrice: this.pricing.unitPrice,\r\n tierPricing: this.pricing.tierPricing,\r\n taxCategory: this.pricing.taxCategory,\r\n applicableTaxRule: [...this.pricing.applicableTaxRule],\r\n };\r\n }\r\n\r\n /**\r\n * Gets the current state of the line item.\r\n * @returns The LineItemState enum value.\r\n */\r\n getState() {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the product type.\r\n * @returns ProductType.\r\n */\r\n getProductType(): ProductType {\r\n return this.productType;\r\n }\r\n\r\n /**\r\n * Gets the total price for this line item (including all sub-items).\r\n * @returns An object containing line item totals including subtotal, tax, discounts, and grand total.\r\n */\r\n getTotal(): LineItemTotalsModel {\r\n return {\r\n quantity: this.total.quantity,\r\n unitPrice: this.total.unitPrice,\r\n subtotal: this.total.subtotal,\r\n discountTotal: this.total.discountTotal,\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(this.total.discountBreakdown).map(([couponCode, discount]) => [\r\n couponCode,\r\n discount,\r\n ])\r\n ),\r\n netUnitPrice: this.total.netUnitPrice,\r\n netSubtotal: this.total.netSubtotal,\r\n taxTotal: this.total.taxTotal,\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n taxRuleId,\r\n {\r\n rate: taxBreakdown.rate,\r\n taxableUnitPrice: taxBreakdown.taxableUnitPrice,\r\n taxPerUnit: taxBreakdown.taxPerUnit,\r\n taxAmount: taxBreakdown.taxAmount,\r\n system: taxBreakdown.system,\r\n subSystem: taxBreakdown.subSystem\r\n }\r\n ])\r\n ),\r\n grandTotal: this.total.grandTotal,\r\n };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the line item's details.\r\n * @returns LineItemData.\r\n */\r\n getDetails(): LineItemData {\r\n const pricing = this.getPricing();\r\n const total = this.getTotal();\r\n return {\r\n id: this.getId(),\r\n productKey: this.getProductKey(),\r\n sku: this.getSku(),\r\n selectionAttributes: this.getSelectionAttributes(),\r\n name: this.getName(),\r\n specifications: this.getSpecifications(),\r\n primaryImage: this.getImage().getDetails(),\r\n subItems: this.getSubItems(),\r\n pricing: {\r\n unitPrice: pricing.unitPrice.getDetails(),\r\n tierPricing: pricing.tierPricing.getDetails(),\r\n taxCategory: pricing.taxCategory,\r\n applicableTaxRule: pricing.applicableTaxRule.map(rule => rule.getDetails()),\r\n },\r\n state: this.getState(),\r\n productType: this.getProductType(),\r\n total: {\r\n quantity: total.quantity,\r\n unitPrice: total.unitPrice.getDetails(),\r\n subtotal: total.subtotal.getDetails(),\r\n discountTotal: total.discountTotal.getDetails(),\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(total.discountBreakdown).map(([couponCode, discount]) => [\r\n couponCode,\r\n discount.getDetails(),\r\n ])\r\n ),\r\n netUnitPrice: total.netUnitPrice.getDetails(),\r\n netSubtotal: total.netSubtotal.getDetails(),\r\n taxTotal: total.taxTotal.getDetails(),\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n taxRuleId,\r\n {\r\n rate: taxBreakdown.rate,\r\n taxableUnitPrice: taxBreakdown.taxableUnitPrice.getDetails(),\r\n taxPerUnit: taxBreakdown.taxPerUnit.getDetails(),\r\n taxAmount: taxBreakdown.taxAmount.getDetails(),\r\n system: taxBreakdown.system,\r\n subSystem: taxBreakdown.subSystem\r\n }\r\n ])\r\n ),\r\n grandTotal: total.grandTotal.getDetails(),\r\n },\r\n customFields: this.getAllCustomFields()\r\n };\r\n }\r\n\r\n /**\r\n\t * Validates that there are no overlapping price brackets for any tax rules within the charge.\r\n\t * @param taxRules - The list of tax rules to validate.\r\n\t * @throws {InvalidLineItemTaxRuleError} Duplicate tax rule IDs will results in error.\r\n\t */\r\n private validateTaxRules(taxRules: TaxRuleModel[]): void {\r\n const uniqueTaxRule = new Set();\r\n for (let i = 0; i < taxRules.length; i++) {\r\n const currentTaxRuleId = taxRules[i].getTaxRuleId();\r\n if (uniqueTaxRule.has(currentTaxRuleId)) {\r\n throw new InvalidLineItemTaxRuleError(\"Duplicate tax rule ID found: \" + currentTaxRuleId);\r\n } else {\r\n uniqueTaxRule.add(currentTaxRuleId);\r\n }\r\n }\r\n }\r\n /**\r\n * Adds or updates sub-items (e.g., sizes with quantities) to the line item.\r\n * If a sub-item with the same size already exists, its quantity is either\r\n * updated by adding the new quantity or replaced entirely, based on the `addQuantity` flag.\r\n * Sub-items with a resulting quantity of 0 are removed.\r\n * @param subItems - An array of `SubItem` objects to add or update.\r\n * @param addQuantity - If true, adds the quantity from `subItem` to the existing quantity.\r\n * If false, replaces the existing quantity with the one from `subItem`.\r\n */\r\n addSubItems(subItems: SubItem[], addQuantity: boolean): void {\r\n subItems.forEach(subItem => {\r\n const existingSubItem = this.subItems.find(item => item.size === subItem.size);\r\n if (existingSubItem) {\r\n existingSubItem.quantity = addQuantity ? existingSubItem.quantity + subItem.quantity : subItem.quantity;\r\n } else {\r\n this.subItems.push(subItem);\r\n }\r\n })\r\n this.subItems = this.subItems.filter(sub => sub.quantity > 0);\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the line item with the latest product data (price, image, name, specifications).\r\n * Validates that the product matches the line item's selection and is active.\r\n * @param product - The product model to update from.\r\n * @param cartCountry - The country code for pricing context.\r\n * @param cartCurrency - The currency code for pricing context.\r\n * @throws {Error} If product mismatch, inactive, size mismatch, or pricing missing.\r\n */\r\n public updateProductData(product: ProductModel, cartCountry: CountryCode, cartCurrency: CurrencyCode): void {\r\n if (this.productKey !== product.getKey() || !product.validateSelectionAttribute(this.selectionAttributes)) {\r\n throw new ProductMismatchError();\r\n } else if (!product.getIsActive()) {\r\n throw new ProductInactiveError();\r\n }\r\n\r\n this.subItems.forEach(subItem => {\r\n if (!product.validateSize(subItem.size)) {\r\n throw new SizeMismatchError();\r\n }\r\n });\r\n\r\n const productPricing = product.getPriceDetails(cartCountry);\r\n if (!productPricing || productPricing.getCurrency() !== cartCurrency) {\r\n throw new PricingNotFoundError();\r\n }\r\n this.name = product.getName();\r\n this.specifications = product.getSpecifications();\r\n this.sku = product.getSku(this.selectionAttributes) as string;\r\n this.primaryImage = product.getImages(this.selectionAttributes).primary;\r\n\r\n const quantity = this.subItems.reduce((sum, s) => sum + s.quantity, 0);\r\n \r\n const unitPrice = productPricing.getApplicableUnitPrice(quantity, this.selectionAttributes);\r\n\r\n\r\n this.productType = product.getProductType();\r\n\r\n this.pricing = {\r\n unitPrice: unitPrice,\r\n tierPricing: productPricing,\r\n taxCategory: productPricing.getTaxCategory(),\r\n applicableTaxRule: this.pricing.applicableTaxRule\r\n }\r\n\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the discounts applied to this line item and recalculates totals.\r\n * @param appliedDiscounts - List of coupons and their allocated discount amounts.\r\n */\r\n public updateDiscounts(appliedDiscounts: { coupon: CouponModel, amount: PriceModel }[]): void {\r\n let lineItemDiscounts = {} as Record<string, PriceModel>;\r\n appliedDiscounts.forEach(discount => {\r\n lineItemDiscounts[discount.coupon.getCode()] = discount.amount;\r\n });\r\n\r\n this.total.discountBreakdown = lineItemDiscounts;\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the tax rule for this line item and recalculates totals.\r\n * @param taxRule - The new tax rule to apply.\r\n * @throws {Error} If the tax rule category does not match the item's tax category.\r\n */\r\n public updateTax(taxRules: TaxRuleModel[]): void {\r\n taxRules.forEach(taxRule => {\r\n if (!taxRule.appliesTo(this.pricing.taxCategory, taxRule.getCountry())) {\r\n throw new InvalidTaxRuleError();\r\n }\r\n });\r\n\r\n this.validateTaxRules(taxRules);\r\n this.pricing.applicableTaxRule = taxRules;\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Recalculates the line item totals based on current quantity, unit price, discounts, and tax rates.\r\n */\r\n public calculateTotals(): void {\r\n const zero = this.pricing.unitPrice.zero();\r\n const totalQuantity = this.subItems.reduce((sum, s) => sum + s.quantity, 0);\r\n\r\n if (this.state === LineItemState.CANCELLED) {\r\n this.total = {\r\n quantity: 0,\r\n unitPrice: zero,\r\n subtotal: zero,\r\n discountTotal: zero,\r\n discountBreakdown: {},\r\n netUnitPrice: zero,\r\n netSubtotal: zero,\r\n taxTotal: zero,\r\n taxBreakdown: {},\r\n grandTotal: zero\r\n };\r\n return;\r\n }\r\n\r\n const tierUnitPrice = this.pricing.tierPricing.getApplicableUnitPrice(totalQuantity, this.selectionAttributes);\r\n \r\n // Initial totals are treated as inclusive if the product is tax inclusive\r\n const initialSubTotal = tierUnitPrice.multiply(totalQuantity);\r\n const totalDiscount = Object.values(this.total.discountBreakdown).reduce((sum, s) => sum.add(s), zero);\r\n const initialNetSubtotal = initialSubTotal.subtract(totalDiscount);\r\n const initialNetUnitPrice = totalQuantity > 0 ? initialNetSubtotal.divide(totalQuantity) : zero;\r\n\r\n const taxBreakdown: Record<string, LineItemTaxBreakdownModel> = {};\r\n let taxTotal = zero;\r\n \r\n let finalUnitPrice = tierUnitPrice;\r\n let finalSubTotal = initialSubTotal;\r\n let finalNetSubtotal = initialNetSubtotal;\r\n let finalNetUnitPrice = initialNetUnitPrice;\r\n\r\n if (this.pricing.tierPricing.getIsTaxInclusive()) {\r\n // 1. Reverse calculate unit price for the base fields\r\n finalUnitPrice = extractExclusiveBase(tierUnitPrice, this.pricing.applicableTaxRule);\r\n finalSubTotal = finalUnitPrice.multiply(totalQuantity);\r\n\r\n // 2. Reverse calculate net unit price and distribute taxes perfectly\r\n if (initialNetUnitPrice.getAmount() > 0) {\r\n finalNetUnitPrice = extractExclusiveBase(initialNetUnitPrice, this.pricing.applicableTaxRule);\r\n finalNetSubtotal = finalNetUnitPrice.multiply(totalQuantity);\r\n\r\n const distributedTaxes = calculateDistributedTaxes(finalNetUnitPrice, initialNetUnitPrice, this.pricing.applicableTaxRule);\r\n \r\n distributedTaxes.forEach(dt => {\r\n const taxAmount = dt.taxAmount.multiply(totalQuantity).round();\r\n const taxRule = this.pricing.applicableTaxRule.find(r => r.getTaxRuleId() === dt.ruleId)!;\r\n \r\n taxBreakdown[dt.ruleId] = {\r\n rate: dt.rate,\r\n taxableUnitPrice: finalNetUnitPrice,\r\n taxPerUnit: dt.taxAmount,\r\n taxAmount: taxAmount,\r\n system: taxRule.getTaxSystem(),\r\n subSystem: taxRule.getTaxSubSystem()\r\n };\r\n taxTotal = taxTotal.add(taxAmount);\r\n });\r\n }\r\n } else {\r\n // Standard exclusive tax calculation\r\n this.pricing.applicableTaxRule.forEach(taxRule => {\r\n const rate = taxRule.getApplicableTaxRate(finalNetUnitPrice);\r\n const taxPerUnit = taxRule.calculateTax(finalNetUnitPrice);\r\n const taxAmount = taxPerUnit.multiply(totalQuantity).round();\r\n taxBreakdown[taxRule.getTaxRuleId()] = {\r\n rate: rate,\r\n taxableUnitPrice: finalNetUnitPrice,\r\n taxPerUnit: taxPerUnit,\r\n taxAmount: taxAmount,\r\n system: taxRule.getTaxSystem(),\r\n subSystem: taxRule.getTaxSubSystem()\r\n };\r\n taxTotal = taxTotal.add(taxAmount);\r\n });\r\n }\r\n\r\n const grandTotal = finalNetSubtotal.add(taxTotal);\r\n\r\n this.total = {\r\n quantity: totalQuantity,\r\n unitPrice: finalUnitPrice,\r\n subtotal: finalSubTotal,\r\n discountTotal: totalDiscount,\r\n discountBreakdown: this.total.discountBreakdown,\r\n netUnitPrice: finalNetUnitPrice,\r\n netSubtotal: finalNetSubtotal,\r\n taxTotal: taxTotal,\r\n taxBreakdown: taxBreakdown,\r\n grandTotal: grandTotal\r\n };\r\n }\r\n\r\n /**\r\n * Updates the line item's state.\r\n * @param newState \r\n */\r\n public updateState(newState: LineItemState): void {\r\n if (this.state in LineItemState) {\r\n if (this.state !== newState) {\r\n this.state = newState;\r\n }\r\n } else {\r\n throw new InvalidLineItemStateError(newState);\r\n }\r\n }\r\n\r\n /**\r\n * Resets the line item's properties to their default empty or initial state.\r\n * Useful for clearing out line item data without creating a new instance.\r\n * Recalculates total quantity and price total afterwards (which will be zero).\r\n */\r\n clearLineItem(): void {\r\n const zero = this.pricing.unitPrice.zero()\r\n this.id = '';\r\n this.productKey = '';\r\n this.sku = '';\r\n this.selectionAttributes = { color: { name: '' } };\r\n this.name = { en: '' };\r\n this.primaryImage = new ImageInfoModel({ sources: { original: '' } });\r\n this.subItems = [];\r\n this.productType = ProductType.GOODS;\r\n this.pricing = {\r\n unitPrice: zero,\r\n tierPricing: this.pricing.tierPricing,\r\n taxCategory: this.pricing.taxCategory,\r\n applicableTaxRule: []\r\n }\r\n this.total = {\r\n quantity: 0,\r\n unitPrice: zero,\r\n subtotal: zero,\r\n discountTotal: zero,\r\n discountBreakdown: {},\r\n netUnitPrice: zero,\r\n netSubtotal: zero,\r\n taxTotal: zero,\r\n taxBreakdown: {},\r\n grandTotal: zero\r\n };\r\n }\r\n}\r\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-56TRG5UD.mjs';import {b as b$1}from'./chunk-HX32EJ3F.mjs';import {a as a$1}from'./chunk-A34BAO7J.mjs';import {e}from'./chunk-UO6WBOEX.mjs';import {a as a$2}from'./chunk-KFXRFY63.mjs';import {a as a$3}from'./chunk-UIQH5QIR.mjs';import {b}from'./chunk-UXZBULDS.mjs';var B=class extends b{id;customerId;customerEmail;anonymousId;lineItems;charges;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;#t;constructor(t,e$1=new Date,a$4={checkCouponExpiry:!0}){super(t,e$1),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(o=>new a(o)),this.charges=(t.charges??[]).map(o=>new a$1(o)),this.billingAddress=t.billingAddress?new b$1(t.billingAddress,e$1):null,this.shippingAddress=t.shippingAddress?new b$1(t.shippingAddress,e$1):null,this.coupons=(t.coupons??[]).map(o=>new e(o)),this.shippingDetails=t.shippingDetails?a$2.deepClone(t.shippingDetails):null,this.total={lineItemSubtotal:new a$3(t.total.lineItemSubtotal),netLineItemSubtotal:new a$3(t.total.netLineItemSubtotal),lineItemTaxTotal:new a$3(t.total.lineItemTaxTotal),lineItemTaxBreakdown:this.mapTaxBreakdown(t.total.lineItemTaxBreakdown),additiveCharges:new a$3(t.total.additiveCharges),netAdditiveCharges:new a$3(t.total.netAdditiveCharges),additiveChargesTaxTotal:new a$3(t.total.additiveChargesTaxTotal),additiveChargesTaxBreakdown:this.mapTaxBreakdown(t.total.additiveChargesTaxBreakdown),adjustmentCharges:new a$3(t.total.adjustmentCharges),shippingCharges:new a$3(t.total.shippingCharges),netShippingCharges:new a$3(t.total.netShippingCharges),discountTotal:new a$3(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([o,n])=>[o,new a$3(n)])),taxTotal:new a$3(t.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(t.total.taxBreakdown),grandTotal:new a$3(t.total.grandTotal)},this.#t={checkCouponExpiry:a$4.checkCouponExpiry};}mapTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,a])=>[e,{system:a.system,totalAmount:new a$3(a.totalAmount),subSystems:Object.fromEntries(Object.entries(a.subSystems).map(([o,n])=>[o,new a$3(n)]))}]))}serializeTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,a])=>[e,{system:a.system,totalAmount:a.totalAmount.getDetails(),subSystems:Object.fromEntries(Object.entries(a.subSystems).map(([o,n])=>[o,n.getDetails()]))}]))}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new a(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(t=>new a$1(t.getDetails()))}addCharge(t){this.charges.push(t),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?a$2.deepClone(this.shippingDetails):null}getShippingAddress(){return this.shippingAddress?new b$1(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new b$1(this.billingAddress.getDetails()):null}getCoupons(){return [...this.coupons]}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {lineItemSubtotal:this.total.lineItemSubtotal,netLineItemSubtotal:this.total.netLineItemSubtotal,lineItemTaxTotal:this.total.lineItemTaxTotal,lineItemTaxBreakdown:Object.fromEntries(Object.entries(this.total.lineItemTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),additiveCharges:this.total.additiveCharges,netAdditiveCharges:this.total.netAdditiveCharges,additiveChargesTaxTotal:this.total.additiveChargesTaxTotal,additiveChargesTaxBreakdown:Object.fromEntries(Object.entries(this.total.additiveChargesTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),adjustmentCharges:this.total.adjustmentCharges,shippingCharges:this.total.shippingCharges,netShippingCharges:this.total.netShippingCharges,discountBreakdown:{...this.total.discountBreakdown},discountTotal:this.total.discountTotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),grandTotal:this.total.grandTotal}}getDetails(){let t=this.getTotal();return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(e=>e.getDetails()),charges:this.getCharges().map(e=>e.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(e=>e.getDetails()),total:{lineItemSubtotal:t.lineItemSubtotal.getDetails(),netLineItemSubtotal:t.netLineItemSubtotal.getDetails(),lineItemTaxTotal:t.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(t.lineItemTaxBreakdown),additiveCharges:t.additiveCharges.getDetails(),netAdditiveCharges:t.netAdditiveCharges.getDetails(),additiveChargesTaxTotal:t.additiveChargesTaxTotal.getDetails(),additiveChargesTaxBreakdown:this.serializeTaxBreakdown(t.additiveChargesTaxBreakdown),adjustmentCharges:t.adjustmentCharges.getDetails(),shippingCharges:t.shippingCharges.getDetails(),netShippingCharges:t.netShippingCharges.getDetails(),discountTotal:t.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(t.discountBreakdown).map(([e,a])=>[e,a.getDetails()])),taxTotal:t.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(t.taxBreakdown),grandTotal:t.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new a$3({amount:0,currency:this.currency}),e=this.lineItems.filter(i=>i.getState()!=="CANCELLED"),a=e.reduce((i,s)=>i.add(s.getTotal().subtotal),t),o=this.charges.filter(i=>i.getType()==="SHIPPING").reduce((i,s)=>i.add(s.getTotal().chargeAmount),t);this.total.lineItemSubtotal=a,this.total.shippingCharges=o;let n=t,l={},p={};this.coupons.forEach(i=>{let s=i.calculateApplicableCouponDiscount(a,o,this.country,this.currency,this.#t.checkCouponExpiry);n=n.add(s),l[i.getCode()]=s,i.getCategory()!=="SHIPPING"&&(p[i.getCode()]=s);}),this.total.discountTotal=n,this.total.discountBreakdown=l,this.applyDiscountsInLineItem(p);let h=this.coupons.find(i=>i.getCategory()==="SHIPPING");h?this.applyDiscountsInShippingCharges({[h.getCode()]:l[h.getCode()]||t}):this.applyDiscountsInShippingCharges({});let d=this.lineItems.reduce((i,s)=>i.add(s.getTotal().netSubtotal),t),c=this.charges.filter(i=>i.getType()==="SHIPPING").reduce((i,s)=>i.add(s.getTotal().grandTotal),t);this.total.netLineItemSubtotal=d,this.total.netShippingCharges=c;let g=this.charges.filter(i=>i.getImpact()==="ADD").reduce((i,s)=>i.add(s.getTotal().chargeAmount),t),m=this.charges.filter(i=>i.getImpact()==="ADD").reduce((i,s)=>i.add(s.getTotal().grandTotal),t),k=this.charges.filter(i=>i.getImpact()==="SUBTRACT").reduce((i,s)=>i.add(s.getTotal().grandTotal),t),f=t,C=t,I=t,b={},M={},P={},x=(i,s)=>{Object.entries(i).forEach(([O,T])=>{let u=T.system,S=T.subSystem;s[u]||(s[u]={system:u,totalAmount:t,subSystems:{}}),s[u].subSystems[S]?s[u].subSystems[S]=s[u].subSystems[S].add(T.taxAmount):s[u].subSystems[S]=T.taxAmount,s[u].totalAmount=s[u].totalAmount.add(T.taxAmount);});};e.forEach(i=>{let s=i.getTotal().taxBreakdown;s&&(x(s,M),x(s,b),C=C.add(i.getTotal().taxTotal));}),this.charges.forEach(i=>{let s=i.getTotal().taxBreakdown;s&&(x(s,P),x(s,b),I=I.add(i.getTotal().taxTotal));}),f=C.add(I);let L=d.add(C).add(m).subtract(k);this.total={lineItemSubtotal:a,netLineItemSubtotal:d,lineItemTaxTotal:C,lineItemTaxBreakdown:M,additiveCharges:g,netAdditiveCharges:m,additiveChargesTaxTotal:I,additiveChargesTaxBreakdown:P,adjustmentCharges:k,shippingCharges:o,netShippingCharges:c,discountTotal:n,discountBreakdown:l,taxTotal:f,taxBreakdown:b,grandTotal:L};}updateShippingDetails(t){this.shippingDetails=t;}applyCoupons(t){let e=t.filter(o=>o.getCategory()==="SHIPPING"),a=t.filter(o=>o.getCategory()!=="SHIPPING");this.coupons=[],this.total.discountTotal=this.total.lineItemSubtotal.zero(),this.total.discountBreakdown={},a.length&&this.applyNonShippingCoupons(a),this.applyDiscountsInLineItem(this.total.discountBreakdown),e.length&&this.applyShippingCoupons(e),this.calculateTotals();}applyDiscountsInLineItem(t){let e=Array.from(Object.entries(t)).filter(o=>!o[1].isZero()),a=new Map;this.lineItems.forEach(o=>a.set(o.getId(),[])),e.forEach(([o,n])=>{let l=this.coupons.find(d=>d.getCode()===o);if(!l||n.isZero())return;let p=this.lineItems.filter(d=>d.getState()!=="CANCELLED"&&!d.getTotal().subtotal.isZero()).sort((d,c)=>d.getTotal().subtotal.compareTo(c.getTotal().subtotal)),h=new a$3({amount:0,currency:this.currency});p.forEach((d,c)=>{let g;c===p.length-1?g=n.subtract(h):g=n.multiply(d.getTotal().subtotal).divide(this.total.lineItemSubtotal).round(),h=h.add(g),a.get(d.getId())?.push({coupon:l,amount:g});});}),this.lineItems.forEach(o=>{o.getState()==="CANCELLED"||this.total.lineItemSubtotal.isZero()?o.updateDiscounts([]):o.updateDiscounts(a.get(o.getId())||[]);});}applyDiscountsInShippingCharges(t){let e=Array.from(Object.entries(t)).filter(n=>!n[1].isZero()),a=this.charges.filter(n=>n.getType()==="SHIPPING"),o=new Map;a.forEach(n=>o.set(n.getId(),[])),e.forEach(([n,l])=>{let p=this.coupons.find(c=>c.getCode()===n);if(!p||l.isZero())return;let h=a.sort((c,g)=>c.getTotal().grandTotal.compareTo(g.getTotal().grandTotal)),d=new a$3({amount:0,currency:this.currency});h.forEach((c,g)=>{let m;g===h.length-1?m=l.subtract(d):m=l.multiply(c.getTotal().chargeAmount).divide(this.total.shippingCharges).round(),d=d.add(m),o.get(c.getId())?.push({coupon:p,amount:m});});}),a.forEach(n=>{n.updateDiscounts(o.get(n.getId())||[]);});}applyNonShippingCoupons(t){let e=t.filter(a=>a.getType()==="coupon");if(e.length===1){let a=e[0].calculateApplicableCouponDiscount(this.total.lineItemSubtotal,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry);a.getAmount()>0&&(this.coupons.push(e[0]),this.total.discountTotal=a,this.total.discountBreakdown[e[0].getCode()]=a);}}applyShippingCoupons(t){if(this.total.shippingCharges.getAmount()>0&&t.length>0){let e=this.total.lineItemSubtotal.subtract(this.total.discountTotal),a=t.reduce((n,l)=>{if(!n)return l;let p=l.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry).min(this.total.shippingCharges),h=n.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry).min(this.total.shippingCharges);return p.compareTo(h)===0?l.getType()==="coupon"?l:n:p.compareTo(h)>0?l:n}),o=a.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry).min(this.total.shippingCharges);o.getAmount()>0&&(this.coupons.push(a),this.total.discountTotal=this.total.discountTotal.add(o),this.total.discountBreakdown[a.getCode()]=o);}}};export{B as a};//# sourceMappingURL=chunk-6IGPC7FH.mjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a}from'./chunk-NXDEYUDI.mjs';import {e}from'./chunk-MBR2GRKU.mjs';import {b as b$1}from'./chunk-HX32EJ3F.mjs';import {a as a$1}from'./chunk-5N2HRXWJ.mjs';import {a as a$2}from'./chunk-4PTWJI6J.mjs';import {a as a$3}from'./chunk-UIQH5QIR.mjs';import {b}from'./chunk-UXZBULDS.mjs';var B=class extends b{id;customerId;customerEmail;anonymousId;lineItems;charges;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;#t;constructor(t,e$1=new Date,a$4={checkCouponExpiry:!0}){super(t,e$1),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(o=>new a(o)),this.charges=(t.charges??[]).map(o=>new a$1(o)),this.billingAddress=t.billingAddress?new b$1(t.billingAddress,e$1):null,this.shippingAddress=t.shippingAddress?new b$1(t.shippingAddress,e$1):null,this.coupons=(t.coupons??[]).map(o=>new e(o)),this.shippingDetails=t.shippingDetails?a$2.deepClone(t.shippingDetails):null,this.total={lineItemSubtotal:new a$3(t.total.lineItemSubtotal),netLineItemSubtotal:new a$3(t.total.netLineItemSubtotal),lineItemTaxTotal:new a$3(t.total.lineItemTaxTotal),lineItemTaxBreakdown:this.mapTaxBreakdown(t.total.lineItemTaxBreakdown),additiveCharges:new a$3(t.total.additiveCharges),netAdditiveCharges:new a$3(t.total.netAdditiveCharges),additiveChargesTaxTotal:new a$3(t.total.additiveChargesTaxTotal),additiveChargesTaxBreakdown:this.mapTaxBreakdown(t.total.additiveChargesTaxBreakdown),adjustmentCharges:new a$3(t.total.adjustmentCharges),shippingCharges:new a$3(t.total.shippingCharges),netShippingCharges:new a$3(t.total.netShippingCharges),discountTotal:new a$3(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([o,n])=>[o,new a$3(n)])),taxTotal:new a$3(t.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(t.total.taxBreakdown),grandTotal:new a$3(t.total.grandTotal)},this.#t={checkCouponExpiry:a$4.checkCouponExpiry};}mapTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,a])=>[e,{system:a.system,totalAmount:new a$3(a.totalAmount),subSystems:Object.fromEntries(Object.entries(a.subSystems).map(([o,n])=>[o,new a$3(n)]))}]))}serializeTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,a])=>[e,{system:a.system,totalAmount:a.totalAmount.getDetails(),subSystems:Object.fromEntries(Object.entries(a.subSystems).map(([o,n])=>[o,n.getDetails()]))}]))}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new a(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(t=>new a$1(t.getDetails()))}addCharge(t){this.charges.push(t),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?a$2.deepClone(this.shippingDetails):null}getShippingAddress(){return this.shippingAddress?new b$1(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new b$1(this.billingAddress.getDetails()):null}getCoupons(){return [...this.coupons]}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {lineItemSubtotal:this.total.lineItemSubtotal,netLineItemSubtotal:this.total.netLineItemSubtotal,lineItemTaxTotal:this.total.lineItemTaxTotal,lineItemTaxBreakdown:Object.fromEntries(Object.entries(this.total.lineItemTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),additiveCharges:this.total.additiveCharges,netAdditiveCharges:this.total.netAdditiveCharges,additiveChargesTaxTotal:this.total.additiveChargesTaxTotal,additiveChargesTaxBreakdown:Object.fromEntries(Object.entries(this.total.additiveChargesTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),adjustmentCharges:this.total.adjustmentCharges,shippingCharges:this.total.shippingCharges,netShippingCharges:this.total.netShippingCharges,discountBreakdown:{...this.total.discountBreakdown},discountTotal:this.total.discountTotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),grandTotal:this.total.grandTotal}}getDetails(){let t=this.getTotal();return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(e=>e.getDetails()),charges:this.getCharges().map(e=>e.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(e=>e.getDetails()),total:{lineItemSubtotal:t.lineItemSubtotal.getDetails(),netLineItemSubtotal:t.netLineItemSubtotal.getDetails(),lineItemTaxTotal:t.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(t.lineItemTaxBreakdown),additiveCharges:t.additiveCharges.getDetails(),netAdditiveCharges:t.netAdditiveCharges.getDetails(),additiveChargesTaxTotal:t.additiveChargesTaxTotal.getDetails(),additiveChargesTaxBreakdown:this.serializeTaxBreakdown(t.additiveChargesTaxBreakdown),adjustmentCharges:t.adjustmentCharges.getDetails(),shippingCharges:t.shippingCharges.getDetails(),netShippingCharges:t.netShippingCharges.getDetails(),discountTotal:t.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(t.discountBreakdown).map(([e,a])=>[e,a.getDetails()])),taxTotal:t.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(t.taxBreakdown),grandTotal:t.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new a$3({amount:0,currency:this.currency}),e=this.lineItems.filter(i=>i.getState()!=="CANCELLED"),a=e.reduce((i,s)=>i.add(s.getTotal().subtotal),t),o=this.charges.filter(i=>i.getType()==="SHIPPING").reduce((i,s)=>i.add(s.getTotal().chargeAmount),t);this.total.lineItemSubtotal=a,this.total.shippingCharges=o;let n=t,l={},p={};this.coupons.forEach(i=>{let s=i.calculateApplicableCouponDiscount(a,o,this.country,this.currency,this.#t.checkCouponExpiry);n=n.add(s),l[i.getCode()]=s,i.getCategory()!=="SHIPPING"&&(p[i.getCode()]=s);}),this.total.discountTotal=n,this.total.discountBreakdown=l,this.applyDiscountsInLineItem(p);let h=this.coupons.find(i=>i.getCategory()==="SHIPPING");h?this.applyDiscountsInShippingCharges({[h.getCode()]:l[h.getCode()]||t}):this.applyDiscountsInShippingCharges({});let d=this.lineItems.reduce((i,s)=>i.add(s.getTotal().netSubtotal),t),c=this.charges.filter(i=>i.getType()==="SHIPPING").reduce((i,s)=>i.add(s.getTotal().grandTotal),t);this.total.netLineItemSubtotal=d,this.total.netShippingCharges=c;let g=this.charges.filter(i=>i.getImpact()==="ADD").reduce((i,s)=>i.add(s.getTotal().chargeAmount),t),m=this.charges.filter(i=>i.getImpact()==="ADD").reduce((i,s)=>i.add(s.getTotal().grandTotal),t),k=this.charges.filter(i=>i.getImpact()==="SUBTRACT").reduce((i,s)=>i.add(s.getTotal().grandTotal),t),f=t,C=t,I=t,b={},M={},P={},x=(i,s)=>{Object.entries(i).forEach(([O,T])=>{let u=T.system,S=T.subSystem;s[u]||(s[u]={system:u,totalAmount:t,subSystems:{}}),s[u].subSystems[S]?s[u].subSystems[S]=s[u].subSystems[S].add(T.taxAmount):s[u].subSystems[S]=T.taxAmount,s[u].totalAmount=s[u].totalAmount.add(T.taxAmount);});};e.forEach(i=>{let s=i.getTotal().taxBreakdown;s&&(x(s,M),x(s,b),C=C.add(i.getTotal().taxTotal));}),this.charges.forEach(i=>{let s=i.getTotal().taxBreakdown;s&&(x(s,P),x(s,b),I=I.add(i.getTotal().taxTotal));}),f=C.add(I);let L=d.add(C).add(m).subtract(k);this.total={lineItemSubtotal:a,netLineItemSubtotal:d,lineItemTaxTotal:C,lineItemTaxBreakdown:M,additiveCharges:g,netAdditiveCharges:m,additiveChargesTaxTotal:I,additiveChargesTaxBreakdown:P,adjustmentCharges:k,shippingCharges:o,netShippingCharges:c,discountTotal:n,discountBreakdown:l,taxTotal:f,taxBreakdown:b,grandTotal:L};}updateShippingDetails(t){this.shippingDetails=t;}applyCoupons(t){let e=t.filter(o=>o.getCategory()==="SHIPPING"),a=t.filter(o=>o.getCategory()!=="SHIPPING");this.coupons=[],this.total.discountTotal=this.total.lineItemSubtotal.zero(),this.total.discountBreakdown={},a.length&&this.applyNonShippingCoupons(a),this.applyDiscountsInLineItem(this.total.discountBreakdown),e.length&&this.applyShippingCoupons(e),this.calculateTotals();}applyDiscountsInLineItem(t){let e=Array.from(Object.entries(t)).filter(o=>!o[1].isZero()),a=new Map;this.lineItems.forEach(o=>a.set(o.getId(),[])),e.forEach(([o,n])=>{let l=this.coupons.find(d=>d.getCode()===o);if(!l||n.isZero())return;let p=this.lineItems.filter(d=>d.getState()!=="CANCELLED"&&!d.getTotal().subtotal.isZero()).sort((d,c)=>d.getTotal().subtotal.compareTo(c.getTotal().subtotal)),h=new a$3({amount:0,currency:this.currency});p.forEach((d,c)=>{let g;c===p.length-1?g=n.subtract(h):g=n.multiply(d.getTotal().subtotal).divide(this.total.lineItemSubtotal).round(),h=h.add(g),a.get(d.getId())?.push({coupon:l,amount:g});});}),this.lineItems.forEach(o=>{o.getState()==="CANCELLED"||this.total.lineItemSubtotal.isZero()?o.updateDiscounts([]):o.updateDiscounts(a.get(o.getId())||[]);});}applyDiscountsInShippingCharges(t){let e=Array.from(Object.entries(t)).filter(n=>!n[1].isZero()),a=this.charges.filter(n=>n.getType()==="SHIPPING"),o=new Map;a.forEach(n=>o.set(n.getId(),[])),e.forEach(([n,l])=>{let p=this.coupons.find(c=>c.getCode()===n);if(!p||l.isZero())return;let h=a.sort((c,g)=>c.getTotal().grandTotal.compareTo(g.getTotal().grandTotal)),d=new a$3({amount:0,currency:this.currency});h.forEach((c,g)=>{let m;g===h.length-1?m=l.subtract(d):m=l.multiply(c.getTotal().chargeAmount).divide(this.total.shippingCharges).round(),d=d.add(m),o.get(c.getId())?.push({coupon:p,amount:m});});}),a.forEach(n=>{n.updateDiscounts(o.get(n.getId())||[]);});}applyNonShippingCoupons(t){let e=t.filter(a=>a.getType()==="coupon");if(e.length===1){let a=e[0].calculateApplicableCouponDiscount(this.total.lineItemSubtotal,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry);a.getAmount()>0&&(this.coupons.push(e[0]),this.total.discountTotal=a,this.total.discountBreakdown[e[0].getCode()]=a);}}applyShippingCoupons(t){if(this.total.shippingCharges.getAmount()>0&&t.length>0){let e=this.total.lineItemSubtotal.subtract(this.total.discountTotal),a=t.reduce((n,l)=>{if(!n)return l;let p=l.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry).min(this.total.shippingCharges),h=n.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry).min(this.total.shippingCharges);return p.compareTo(h)===0?l.getType()==="coupon"?l:n:p.compareTo(h)>0?l:n}),o=a.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry).min(this.total.shippingCharges);o.getAmount()>0&&(this.coupons.push(a),this.total.discountTotal=this.total.discountTotal.add(o),this.total.discountBreakdown[a.getCode()]=o);}}};export{B as a};//# sourceMappingURL=chunk-SZLAIOMF.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-SZLAIOMF.mjs.map
|