b23-lib 2.1.7 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Auth/index.js +1 -1
- package/dist/Auth/index.js.map +1 -1
- package/dist/Auth/index.mjs +1 -1
- package/dist/Classes/Cart.js +2 -2
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Coupon.js +1 -1
- package/dist/Classes/Coupon.js.map +1 -1
- package/dist/Classes/Coupon.mjs +1 -1
- package/dist/Classes/Inventory.js +1 -1
- package/dist/Classes/Inventory.js.map +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/LineItem.js +1 -1
- package/dist/Classes/LineItem.js.map +1 -1
- package/dist/Classes/LineItem.mjs +1 -1
- package/dist/Classes/Order.js +2 -2
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/Price.js +1 -1
- package/dist/Classes/Price.js.map +1 -1
- package/dist/Classes/Price.mjs +1 -1
- package/dist/Classes/Product.js +1 -1
- package/dist/Classes/Product.js.map +1 -1
- package/dist/Classes/Product.mjs +1 -1
- package/dist/Classes/ShoppingContainer.js +2 -2
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/Classes/TaxRule.js +1 -1
- package/dist/Classes/TaxRule.js.map +1 -1
- package/dist/Classes/TaxRule.mjs +1 -1
- package/dist/Classes/TieredPrice.js +1 -1
- package/dist/Classes/TieredPrice.js.map +1 -1
- package/dist/Classes/TieredPrice.mjs +1 -1
- package/dist/{chunk-SFUOYZ3L.mjs → chunk-43SMYXYL.mjs} +2 -2
- package/dist/{chunk-SFUOYZ3L.mjs.map → chunk-43SMYXYL.mjs.map} +1 -1
- package/dist/{chunk-ZE7D77FR.mjs → chunk-5VI4V3SF.mjs} +2 -2
- package/dist/{chunk-ZE7D77FR.mjs.map → chunk-5VI4V3SF.mjs.map} +1 -1
- package/dist/{chunk-232FJYNB.mjs → chunk-CKJONVT3.mjs} +2 -2
- package/dist/chunk-CKJONVT3.mjs.map +1 -0
- package/dist/{chunk-TJ7AZBND.mjs → chunk-EV4HUBJL.mjs} +2 -2
- package/dist/chunk-EV4HUBJL.mjs.map +1 -0
- package/dist/{chunk-WS7ZY5ZZ.mjs → chunk-GF427QWC.mjs} +2 -2
- package/dist/{chunk-WS7ZY5ZZ.mjs.map → chunk-GF427QWC.mjs.map} +1 -1
- package/dist/{chunk-AWZ6KRLF.mjs → chunk-LEHPVA3Q.mjs} +2 -2
- package/dist/{chunk-AWZ6KRLF.mjs.map → chunk-LEHPVA3Q.mjs.map} +1 -1
- package/dist/{chunk-ARMBZF3E.mjs → chunk-RQC4PNOV.mjs} +3 -3
- package/dist/{chunk-ARMBZF3E.mjs.map → chunk-RQC4PNOV.mjs.map} +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-232FJYNB.mjs.map +0 -1
- package/dist/chunk-TJ7AZBND.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/TieredPrice.ts"],"names":["TieredPriceModel","data","baseUnitPrice","PriceModel","InvalidTaxCategoryError","tiers","tier","a","b","t","InvalidMinQuantityError","hasDifferentCurrency","hasIrregularPricing","index","basePriceExceedsFirstTier","InvalidTieredPriceError","quantity","InvalidQuantityError","i","NoApplicableTierError","lowestTierPrice","basePrice"],"mappings":"kFAkCaA,IAAAA,CAAAA,CAAN,KAAuB,CAClB,aACA,CAAA,WAAA,CACA,KAWV,CAAA,WAAA,CAAYC,CAA6B,CAAA,CACvC,IAAMC,CAAAA,CAAgB,IAAIC,CAAAA,CAAWF,CAAK,CAAA,aAAa,CAEvD,CAAA,GAAI,CAACA,CAAAA,CAAK,WACR,CAAA,MAAM,IAAIG,CAAAA,CAGZ,IAAMC,CA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":["TieredPriceModel","data","baseUnitPrice","PriceModel","InvalidTaxCategoryError","tiers","tier","a","b","t","InvalidMinQuantityError","hasDifferentCurrency","hasIrregularPricing","index","basePriceExceedsFirstTier","InvalidTieredPriceError","quantity","InvalidQuantityError","i","NoApplicableTierError","lowestTierPrice","basePrice"],"mappings":"kFAkCaA,IAAAA,CAAAA,CAAN,KAAuB,CAClB,aACA,CAAA,WAAA,CACA,KAWV,CAAA,WAAA,CAAYC,CAA6B,CAAA,CACvC,IAAMC,CAAAA,CAAgB,IAAIC,CAAAA,CAAWF,CAAK,CAAA,aAAa,CAEvD,CAAA,GAAI,CAACA,CAAAA,CAAK,WACR,CAAA,MAAM,IAAIG,CAAAA,CAGZ,IAAMC,CAAAA,CAAAA,CAASJ,CAAK,CAAA,KAAA,EAAS,EAAC,EAC3B,GAAIK,CAAAA,CAAAA,GAAS,CACZ,WAAA,CAAaA,CAAK,CAAA,WAAA,CAClB,SAAW,CAAA,IAAIH,CAAWG,CAAAA,CAAAA,CAAK,SAAS,CAC1C,CAAE,CAAA,CAAA,CACD,IAAK,CAAA,CAACC,CAAGC,CAAAA,CAAAA,GAAMD,CAAE,CAAA,WAAA,CAAcC,CAAE,CAAA,WAAW,CAG/C,CAAA,GAD8BH,CAAM,CAAA,IAAA,CAAKI,CAAKA,EAAAA,CAAAA,CAAE,WAAe,EAAA,CAAC,CAE9D,CAAA,MAAM,IAAIC,CAGZ,CAAA,IAAMC,GAAuBN,CAAAA,CAAAA,CAAM,IACjCI,CAAAA,CAAAA,EAAKA,CAAE,CAAA,SAAA,CAAU,WAAY,EAAA,GAAMP,CAAc,CAAA,WAAA,EACnD,CAAA,CACMU,CAAsBP,CAAAA,CAAAA,CAAM,IAChC,CAAA,CAACC,CAAMO,CAAAA,CAAAA,GACLA,CAAQ,CAAA,CAAA,EACRP,CAAK,CAAA,SAAA,CAAU,SAAUD,CAAAA,CAAAA,CAAMQ,CAAQ,CAAA,CAAC,CAAE,CAAA,SAAS,CAAI,CAAA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AAA,CAAM,CAAC,CAAA,EAAG,WAAe,EAAA,CACvC,CAKA,qBAAA,EAAgC,CAC9B,GAAI,CAAC,IAAA,CAAK,KAAM,CAAA,MAAA,CAAQ,OAAO,CAAA,CAE/B,IAAMI,CAAAA,CAAkB,IAAK,CAAA,KAAA,CAAM,IAAK,CAAA,KAAA,CAAM,MAAS,CAAA,CAAC,CAAE,CAAA,SAAA,CAAU,SAAU,EAAA,CACxEC,CAAY,CAAA,IAAA,CAAK,aAAc,CAAA,SAAA,EAErC,CAAA,OAAA,CAASA,CAAYD,CAAAA,CAAAA,EAAmBC,CAAa,CAAA,GACvD,CACF","file":"chunk-43SMYXYL.mjs","sourcesContent":["import { TaxCategory } from \"./Enum\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport {\r\n InvalidTaxCategoryError,\r\n InvalidMinQuantityError,\r\n InvalidTieredPriceError,\r\n InvalidQuantityError,\r\n NoApplicableTierError\r\n} from \"./Error\";\r\n\r\n/**\r\n * Represents a pricing tier based on a minimum purchase quantity.\r\n */\r\nexport type PriceTier = {\r\n minQuantity: number;\r\n unitPrice: PriceModel;\r\n};\r\n\r\n/**\r\n * Represents the attributes required for tiered pricing.\r\n */\r\nexport type TieredPriceAttributes = {\r\n baseUnitPrice: PriceData;\r\n taxCategory: TaxCategory;\r\n\r\n /** Quantity-based pricing tiers */\r\n tiers: {\r\n minQuantity: number;\r\n unitPrice: PriceData;\r\n }[];\r\n};\r\n\r\nexport type TieredPriceData = TieredPriceAttributes;\r\n\r\nexport class TieredPriceModel {\r\n protected baseUnitPrice: PriceModel;\r\n protected taxCategory: TaxCategory;\r\n protected tiers: PriceTier[];\r\n\r\n /** Constructor\r\n * Initializes the tiered pricing model with the provided attributes.\r\n * @param data - The tiered pricing attributes.\r\n *\r\n * @throws {Error}\r\n * - If the tax category is not valid\r\n * - If any tier has an invalid minimum quantity or unit price\r\n * - If the base unit price is not valid\r\n */\r\n constructor(data: TieredPriceAttributes) {\r\n const baseUnitPrice = new PriceModel(data.baseUnitPrice);\r\n\r\n if (!data.taxCategory) {\r\n throw new InvalidTaxCategoryError();\r\n }\r\n\r\n const tiers = (data.tiers ?? [])\r\n .map(tier => ({\r\n minQuantity: tier.minQuantity,\r\n unitPrice: new PriceModel(tier.unitPrice),\r\n }))\r\n .sort((a, b) => a.minQuantity - b.minQuantity);\r\n\r\n const hasInvalidMinQuantity = tiers.some(t => t.minQuantity <= 0);\r\n if (hasInvalidMinQuantity) {\r\n throw new InvalidMinQuantityError();\r\n }\r\n\r\n const hasDifferentCurrency = tiers.some(\r\n t => t.unitPrice.getCurrency() !== baseUnitPrice.getCurrency()\r\n );\r\n const hasIrregularPricing = tiers.some(\r\n (tier, index) =>\r\n index > 0 &&\r\n tier.unitPrice.compareTo(tiers[index - 1].unitPrice) > 0\r\n );\r\n const basePriceExceedsFirstTier = tiers[0]?.unitPrice.compareTo(baseUnitPrice) > 0;\r\n\r\n if (hasDifferentCurrency || hasIrregularPricing || basePriceExceedsFirstTier) {\r\n throw new InvalidTieredPriceError(\r\n \"Tiers must share the same currency and must not increase in unit price.\"\r\n );\r\n }\r\n\r\n this.baseUnitPrice = baseUnitPrice;\r\n this.taxCategory = data.taxCategory;\r\n this.tiers = tiers;\r\n }\r\n\r\n /** \r\n * Returns the base unit price \r\n * @returns The base unit price as a PriceModel instance.\r\n */\r\n getBaseUnitPrice(): PriceModel {\r\n return this.baseUnitPrice;\r\n }\r\n\r\n /** \r\n * Returns the tax category \r\n * @returns The tax category as a TaxCategory enum value.\r\n */\r\n getTaxCategory(): TaxCategory {\r\n return this.taxCategory;\r\n }\r\n\r\n /** \r\n * Returns all pricing tiers sorted by minimum quantity \r\n * @returns An array of PriceTier objects.\r\n */\r\n getTiers(): readonly PriceTier[] {\r\n return this.tiers;\r\n }\r\n\r\n getDetails(): TieredPriceData {\r\n return {\r\n baseUnitPrice: this.baseUnitPrice.getDetails(),\r\n taxCategory: this.taxCategory,\r\n tiers: this.tiers.map(tier => ({\r\n minQuantity: tier.minQuantity,\r\n unitPrice: tier.unitPrice.getDetails()\r\n }))\r\n };\r\n }\r\n\r\n /**\r\n * Returns the applicable unit price for a given quantity.\r\n *\r\n * @param quantity - Purchase quantity\r\n * @returns The unit price for the highest applicable tier\r\n *\r\n * @throws {Error}\r\n * - If quantity is less than or equal to zero\r\n * - If quantity does not meet the minimum requirement of any tier\r\n */\r\n getApplicableTier(quantity: number): PriceTier {\r\n if (quantity <= 0) {\r\n throw new InvalidQuantityError();\r\n }\r\n\r\n for (let i = this.tiers.length - 1; i >= 0; i--) {\r\n if (quantity >= this.tiers[i].minQuantity) {\r\n return this.tiers[i];\r\n }\r\n }\r\n\r\n throw new NoApplicableTierError(quantity);\r\n }\r\n\r\n /**\r\n * Returns the minimum quantity required to purchase this product.\r\n */\r\n getMinQuantity(): number {\r\n return this.tiers[0]?.minQuantity ?? 1;\r\n }\r\n\r\n /**\r\n * Returns the maximum discount percentage achievable compared to the base unit price.\r\n */\r\n getMaxDiscountPercent(): number {\r\n if (!this.tiers.length) return 0;\r\n\r\n const lowestTierPrice = this.tiers[this.tiers.length - 1].unitPrice.getAmount();\r\n const basePrice = this.baseUnitPrice.getAmount();\r\n\r\n return ((basePrice - lowestTierPrice) / basePrice) * 100;\r\n }\r\n}\r\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {c as c$1}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {c as c$1}from'./chunk-RQC4PNOV.mjs';import {a as a$1}from'./chunk-LEHPVA3Q.mjs';import {a as a$3}from'./chunk-43SMYXYL.mjs';import {a as a$2}from'./chunk-EV4HUBJL.mjs';import {e,n}from'./chunk-72DR3HF2.mjs';import {b}from'./chunk-WSUPVXRZ.mjs';import {c,e as e$1,f,h,i,j,b as b$1}from'./chunk-JHELVQYY.mjs';import {a}from'./chunk-6KCJVEZD.mjs';var p=class extends a{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=a$1.deepClone(t.selectionAttributes),this.name=a$1.deepClone(t.name),this.specifications=a$1.deepClone(t.specifications),this.primaryImage=new b(t.primaryImage),this.subItems=a$1.deepClone(t.subItems);let i=new Set;this.subItems.forEach(e=>{if(i.has(e.size))throw new c(e.size);i.add(e.size);}),this.pricing={unitPrice:new a$2(t.pricing.unitPrice),tierPricing:new a$3(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,tax:{taxRuleId:t.pricing.tax.taxRuleId,taxSystem:t.pricing.tax.taxSystem,country:t.pricing.tax.country,rate:t.pricing.tax.rate,taxSlabs:t.pricing.tax.taxSlabs.map(e=>({rate:e.rate,minUnitPrice:new a$2(e.minUnitPrice),maxUnitPrice:e.maxUnitPrice?new a$2(e.maxUnitPrice):void 0}))}},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,subtotal:new a$2(t.total.subtotal),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([e,a])=>[e,new a$2(a)])),taxableAmount:new a$2(t.total.taxableAmount),taxTotal:new a$2(t.total.taxTotal),grandTotal:new a$2(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return a$1.deepClone(this.selectionAttributes)}getName(t){return t?a$1.deepClone(this.name[t]??this.name[e[t]]??this.name.en):a$1.deepClone(this.name)}getSpecifications(t){return t?a$1.deepClone(this.specifications[t]??this.specifications[e[t]]??this.specifications.en):a$1.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return a$1.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:{taxRuleId:this.pricing.tax.taxRuleId,taxSystem:this.pricing.tax.taxSystem,country:this.pricing.tax.country,rate:this.pricing.tax.rate,taxSlabs:this.pricing.tax.taxSlabs}}}getState(){return this.state}getTotal(){return {quantity:this.total.quantity,subtotal:this.total.subtotal,taxableAmount:this.total.taxableAmount,taxTotal:this.total.taxTotal,discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,i])=>[t,i])),grandTotal:this.total.grandTotal}}getDetails(){return {id:this.getId(),productKey:this.getProductKey(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:this.getPricing().unitPrice.getDetails(),tierPricing:this.getPricing().tierPricing.getDetails(),taxCategory:this.getPricing().taxCategory,tax:{taxRuleId:this.getPricing().tax.taxRuleId,taxSystem:this.getPricing().tax.taxSystem,country:this.getPricing().tax.country,rate:this.getPricing().tax.rate,taxSlabs:this.getPricing().tax.taxSlabs.map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0}))}},state:this.getState(),total:{quantity:this.getTotal().quantity,subtotal:this.getTotal().subtotal.getDetails(),taxableAmount:this.getTotal().taxableAmount.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),discounts:Object.fromEntries(Object.entries(this.getTotal().discounts).map(([t,i])=>[t,i.getDetails()])),grandTotal:this.getTotal().grandTotal.getDetails()},customFields:this.getAllCustomFields()}}addSubItems(t,i){t.forEach(e=>{let a=this.subItems.find(s=>s.size===e.size);a?a.quantity=i?a.quantity+e.quantity:e.quantity:this.subItems.push(e);}),this.subItems=this.subItems.filter(e=>e.quantity>0),this.calculateTotals();}updateProductData(t,i$1,e){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new e$1;if(!t.getIsActive())throw new f;this.subItems.forEach(c=>{if(!t.validateSize(c.size))throw new h});let a=t.getPriceDetails(i$1);if(!a||a.getBaseUnitPrice().getCurrency()!==e)throw new i;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let s=this.subItems.reduce((c,l)=>c+l.quantity,0),{unitPrice:n}=a.getApplicableTier(s);this.pricing={unitPrice:n,tierPricing:a,taxCategory:a.getTaxCategory(),tax:this.pricing.tax},this.calculateTotals();}updateDiscounts(t){let i={};t.forEach(e=>{i[e.coupon.getCode()]=e.amount;}),this.total.discounts=i,this.calculateTotals();}updateTax(t){if(!t.appliesTo(this.pricing.taxCategory,this.pricing.tax.country))throw new j;let i=this.total.quantity>0?this.total.taxableAmount.divide(this.total.quantity):this.total.taxableAmount.zero();this.pricing.tax={taxRuleId:t.getTaxRuleId(),taxSystem:t.getTaxSystem(),country:t.getCountry(),rate:t.getApplicableTaxRate(i),taxSlabs:t.getSlabs()},this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),i=this.subItems.reduce((u,g)=>u+g.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,subtotal:t,taxableAmount:t,taxTotal:t,discounts:{},grandTotal:t};return}let{unitPrice:e}=this.pricing.tierPricing.getApplicableTier(i),a=e.multiply(i),s=Object.values(this.total.discounts).reduce((u,g)=>u.add(g),t),n=a.subtract(s),c=i>0?n.divide(i):t,l=c$1.getApplicableTaxRate(c,this.pricing.tax.taxSlabs),h=n.multiply(l).round(),D=a.subtract(s).add(h);this.total={quantity:i,subtotal:a,taxableAmount:n,taxTotal:h,discounts:this.total.discounts,grandTotal:D};}updateState(t){if(this.state in n)this.state!==t&&(this.state=t);else throw new b$1(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new b({sources:{original:""}}),this.subItems=[],this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:this.pricing.tax},this.total={quantity:0,subtotal:t,taxableAmount:t,taxTotal:t,discounts:{},grandTotal:t};}};export{p as a};//# sourceMappingURL=chunk-5VI4V3SF.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-5VI4V3SF.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/LineItem.ts"],"names":["LineItemModel","CustomFieldModel","data","Utils_default","ImageInfoModel","uniqueSelectionAttributes","item","DuplicateSizeError","PriceModel","TieredPriceModel","s","couponCode","discount","locale","LocaleLanguageMap","subItems","addQuantity","subItem","existingSubItem","sub","product","cartCountry","cartCurrency","ProductMismatchError","ProductInactiveError","SizeMismatchError","productPricing","PricingNotFoundError","quantity","sum","unitPrice","appliedDiscounts","lineItemDiscounts","taxRule","InvalidTaxRuleError","taxableUnitPrice","zero","totalQuantity","subTotal","discounts","taxableAmount","unitTaxbleAmount","taxRate","TaxRuleModel","taxTotal","grandTotal","newState","LineItemState","InvalidLineItemStateError"],"mappings":"gWAsEA,IAAqBA,CAArB,CAAA,cAA2CC,CAAiB,CAChD,EACA,CAAA,UAAA,CACA,mBAEA,CAAA,IAAA,CACA,cACA,CAAA,YAAA,CACA,QACA,CAAA,OAAA,CAaA,MACA,KAcV,CAAA,WAAA,CAAYC,CAA0B,CAAA,CACpC,KAAMA,CAAAA,CAAI,CACV,CAAA,IAAA,CAAK,EAAKA,CAAAA,CAAAA,CAAK,EACf,CAAA,IAAA,CAAK,UAAaA,CAAAA,CAAAA,CAAK,UACvB,CAAA,IAAA,CAAK,oBAAsBC,GAAM,CAAA,SAAA,CAAUD,CAAK,CAAA,mBAAmB,CAEnE,CAAA,IAAA,CAAK,IAAOC,CAAAA,GAAAA,CAAM,SAAUD,CAAAA,CAAAA,CAAK,IAAI,CAAA,CACrC,IAAK,CAAA,cAAA,CAAiBC,GAAM,CAAA,SAAA,CAAUD,EAAK,cAAc,CAAA,CACzD,IAAK,CAAA,YAAA,CAAe,IAAIE,CAAAA,CAAeF,CAAK,CAAA,YAAY,EACxD,IAAK,CAAA,QAAA,CAAWC,GAAM,CAAA,SAAA,CAAUD,CAAK,CAAA,QAAQ,CAE7C,CAAA,IAAIG,EAA4B,IAAI,GAAA,CACpC,IAAK,CAAA,QAAA,CAAS,OAAQC,CAAAA,CAAAA,EAAQ,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GAAUD,CACjB,GAAA,IAAA,CAAK,MAAQA,CAGf,CAAA,CAAA,KAAA,MAAM,IAAIE,GAAAA,CAA0BF,CAAQ,CAEhD,CAOA,aAAA,EAAsB,CACpB,IAAMV,CAAAA,CAAO,IAAK,CAAA,OAAA,CAAQ,SAAU,CAAA,IAAA,EACpC,CAAA,IAAA,CAAK,GAAK,EACV,CAAA,IAAA,CAAK,UAAa,CAAA,EAAA,CAClB,IAAK,CAAA,mBAAA,CAAsB,CAAE,KAAA,CAAO,CAAE,IAAA,CAAM,EAAG,CAAE,CACjD,CAAA,IAAA,CAAK,IAAO,CAAA,CAAE,GAAI,EAAG,CAAA,CACrB,IAAK,CAAA,YAAA,CAAe,IAAIhC,CAAAA,CAAe,CAAE,OAAA,CAAS,CAAE,QAAU,CAAA,EAAG,CAAE,CAAC,CACpE,CAAA,IAAA,CAAK,QAAW,CAAA,GAChB,IAAK,CAAA,OAAA,CAAU,CACb,SAAA,CAAWgC,CACX,CAAA,WAAA,CAAa,IAAK,CAAA,OAAA,CAAQ,WAC1B,CAAA,WAAA,CAAa,IAAK,CAAA,OAAA,CAAQ,WAC1B,CAAA,GAAA,CAAK,IAAK,CAAA,OAAA,CAAQ,GACpB,CACA,CAAA,IAAA,CAAK,KAAQ,CAAA,CACX,QAAU,CAAA,CAAA,CACV,QAAUA,CAAAA,CAAAA,CACV,cAAeA,CACf,CAAA,QAAA,CAAUA,CACV,CAAA,SAAA,CAAW,EAAC,CACZ,UAAYA,CAAAA,CACd,EACF,CACF","file":"chunk-ZE7D77FR.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, TaxCategory, TaxSystem } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport ProductModel, { ProductSelectionAttributes, ProductSpecification, SelectionAttributes } from \"./Product\";\r\nimport { TaxRuleModel, TaxSlabModel, TaxSlabs } 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} from \"./Error\";\r\nimport { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\n\r\nexport type SubItem = {\r\n size: string | 'ONESIZE';\r\n quantity: number;\r\n};\r\n\r\nexport type LineItemPricing = {\r\n unitPrice: PriceData;\r\n tierPricing: TieredPriceData;\r\n taxCategory: TaxCategory;\r\n tax: {\r\n taxRuleId: string;\r\n taxSystem: TaxSystem;\r\n country: CountryCode;\r\n rate: number;\r\n taxSlabs: TaxSlabs;\r\n };\r\n};\r\n\r\nexport type LineItemTotals = {\r\n quantity: number;\r\n subtotal: PriceData;\r\n discounts: Record<string, PriceData>; // couponCode -> discount mapping\r\n taxableAmount: PriceData; // subtotal - discount\r\n taxTotal: PriceData;\r\n grandTotal: PriceData;\r\n};\r\n\r\nexport type LineItemAttributes = CustomFieldAttributes & {\r\n id: string;\r\n\r\n productKey: string;\r\n selectionAttributes: SelectionAttributes;\r\n\r\n name: LocalizedString;\r\n specifications: LocalizedValue<ProductSpecification>;\r\n primaryImage: ImageInfoData;\r\n\r\n subItems: SubItem[];\r\n\r\n pricing: LineItemPricing;\r\n\r\n state?: LineItemState;\r\n total: LineItemTotals;\r\n}\r\n\r\nexport type LineItemData = Required<LineItemAttributes>;\r\n\r\n/**\r\n * Represents a line item within a shopping cart.\r\n */\r\nexport default class LineItemModel extends CustomFieldModel {\r\n protected id: string;\r\n protected productKey: string;\r\n protected selectionAttributes: SelectionAttributes;\r\n\r\n protected name: LocalizedString;\r\n protected specifications: LocalizedValue<ProductSpecification>;\r\n protected primaryImage: ImageInfoModel;\r\n protected subItems: SubItem[];\r\n protected pricing: {\r\n unitPrice: PriceModel;\r\n tierPricing: TieredPriceModel;\r\n taxCategory: TaxCategory;\r\n tax: {\r\n taxRuleId: string;\r\n taxSystem: TaxSystem;\r\n country: CountryCode;\r\n taxSlabs: TaxSlabModel[];\r\n rate: number;\r\n };\r\n };\r\n\r\n protected state: LineItemState;\r\n protected total: {\r\n quantity: number;\r\n subtotal: PriceModel;\r\n discounts: Record<string, PriceModel>;\r\n taxableAmount: PriceModel; // subtotal - discount\r\n\r\n taxTotal: PriceModel;\r\n grandTotal: PriceModel;\r\n };\r\n\r\n /**\r\n * Creates an instance of LineItemModel.\r\n * @param data - The initial line item attributes.\r\n */\r\n constructor(data: LineItemAttributes) {\r\n super(data);\r\n this.id = data.id;\r\n this.productKey = data.productKey;\r\n this.selectionAttributes = Utils.deepClone(data.selectionAttributes);\r\n\r\n this.name = Utils.deepClone(data.name);\r\n this.specifications = Utils.deepClone(data.specifications);\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.subItems = Utils.deepClone(data.subItems);\r\n\r\n let uniqueSelectionAttributes = new Set();\r\n this.subItems.forEach(item => {\r\n if (uniqueSelectionAttributes.has(item.size)) {\r\n throw new DuplicateSizeError(item.size);\r\n }\r\n uniqueSelectionAttributes.add(item.size);\r\n });\r\n\r\n this.pricing = {\r\n unitPrice: new PriceModel(data.pricing.unitPrice),\r\n tierPricing: new TieredPriceModel(data.pricing.tierPricing),\r\n taxCategory: data.pricing.taxCategory,\r\n tax: {\r\n taxRuleId: data.pricing.tax.taxRuleId,\r\n taxSystem: data.pricing.tax.taxSystem,\r\n country: data.pricing.tax.country,\r\n rate: data.pricing.tax.rate,\r\n taxSlabs: data.pricing.tax.taxSlabs.map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: new PriceModel(s.minUnitPrice),\r\n maxUnitPrice: s.maxUnitPrice ? new PriceModel(s.maxUnitPrice) : undefined,\r\n })),\r\n },\r\n }\r\n\r\n this.state = data.state ?? LineItemState.INITIAL;\r\n\r\n this.total = {\r\n quantity: data.total.quantity,\r\n subtotal: new PriceModel(data.total.subtotal),\r\n discounts: Object.fromEntries(\r\n Object.entries(data.total.discounts).map(([couponCode, discount]) => [\r\n couponCode,\r\n new PriceModel(discount),\r\n ])\r\n ),\r\n taxableAmount: new PriceModel(data.total.taxableAmount),\r\n taxTotal: new PriceModel(data.total.taxTotal),\r\n grandTotal: new PriceModel(data.total.grandTotal),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the unique identifier of the line item.\r\n * @returns The unique ID string.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the product key associated with this line item.\r\n * @returns The product key string.\r\n */\r\n getProductKey(): string {\r\n return this.productKey;\r\n }\r\n\r\n /**\r\n * Gets the selection attributes (e.g., size, color) for this line item.\r\n * @returns A copy of the selection attributes object.\r\n */\r\n getSelectionAttributes(): SelectionAttributes {\r\n return Utils.deepClone(this.selectionAttributes);\r\n }\r\n\r\n /**\r\n * Gets the full localized product name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the product name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return Utils.deepClone(this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en);\r\n } else {\r\n return Utils.deepClone(this.name);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product specifications object.\r\n * @returns Product Specifications\r\n */\r\n getSpecifications(): LocalizedValue<ProductSpecification>\r\n /**\r\n * Gets the product specifications for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The ProductSpecification object for the specified locale, or undefined if not found.\r\n */\r\n getSpecifications(locale: LocaleCode): ProductSpecification | undefined\r\n getSpecifications(locale?: LocaleCode): LocalizedValue<ProductSpecification> | ProductSpecification | undefined {\r\n if (locale) {\r\n return Utils.deepClone(this.specifications[locale] ?? this.specifications[LocaleLanguageMap[locale]] ?? this.specifications.en);\r\n } else {\r\n return Utils.deepClone(this.specifications);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the image information model for this line item.\r\n * @returns The ImageInfoModel instance.\r\n */\r\n getImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /**\r\n * Gets the sub-items (size/quantity breakdown).\r\n * @returns A copy of the array of SubItems.\r\n */\r\n getSubItems(): SubItem[] {\r\n return Utils.deepClone(this.subItems);\r\n }\r\n\r\n /**\r\n * Gets the total quantity for this line item across all sub-items.\r\n * @returns The total quantity as a number.\r\n */\r\n getTotalQuantity(): number {\r\n return this.total.quantity;\r\n }\r\n\r\n /**\r\n * Gets the pricing information model for this line item.\r\n * @returns An object containing unit price, tiered pricing, tax category, and tax details.\r\n */\r\n getPricing() {\r\n return {\r\n unitPrice: this.pricing.unitPrice,\r\n tierPricing: this.pricing.tierPricing,\r\n taxCategory: this.pricing.taxCategory,\r\n tax: {\r\n taxRuleId: this.pricing.tax.taxRuleId,\r\n taxSystem: this.pricing.tax.taxSystem,\r\n country: this.pricing.tax.country,\r\n rate: this.pricing.tax.rate,\r\n taxSlabs: this.pricing.tax.taxSlabs,\r\n }\r\n };\r\n }\r\n\r\n /**\r\n * Gets the current state of the line item.\r\n * @returns The LineItemState enum value.\r\n */\r\n getState() {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the total price for this line item (including all sub-items).\r\n * @returns An object containing line item totals including subtotal, tax, discounts, and grand total.\r\n */\r\n getTotal() {\r\n return {\r\n quantity: this.total.quantity,\r\n subtotal: this.total.subtotal,\r\n taxableAmount: this.total.taxableAmount,\r\n taxTotal: this.total.taxTotal,\r\n discounts: Object.fromEntries(\r\n Object.entries(this.total.discounts).map(([couponCode, discount]) => [\r\n couponCode,\r\n discount,\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 return {\r\n id: this.getId(),\r\n productKey: this.getProductKey(),\r\n selectionAttributes: this.getSelectionAttributes(),\r\n name: this.getName(),\r\n specifications: this.getSpecifications(),\r\n primaryImage: this.getImage().getDetails(),\r\n subItems: this.getSubItems(),\r\n pricing: {\r\n unitPrice: this.getPricing().unitPrice.getDetails(),\r\n tierPricing: this.getPricing().tierPricing.getDetails(),\r\n taxCategory: this.getPricing().taxCategory,\r\n tax: {\r\n taxRuleId: this.getPricing().tax.taxRuleId,\r\n taxSystem: this.getPricing().tax.taxSystem,\r\n country: this.getPricing().tax.country,\r\n rate: this.getPricing().tax.rate,\r\n taxSlabs: this.getPricing().tax.taxSlabs.map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: s.minUnitPrice.getDetails(),\r\n maxUnitPrice: s.maxUnitPrice ? s.maxUnitPrice.getDetails() : undefined,\r\n })),\r\n }\r\n },\r\n state: this.getState(),\r\n total: {\r\n quantity: this.getTotal().quantity,\r\n subtotal: this.getTotal().subtotal.getDetails(),\r\n taxableAmount: this.getTotal().taxableAmount.getDetails(),\r\n taxTotal: this.getTotal().taxTotal.getDetails(),\r\n discounts: Object.fromEntries(\r\n Object.entries(this.getTotal().discounts).map(([couponCode, discount]) => [\r\n couponCode,\r\n discount.getDetails(),\r\n ])\r\n ),\r\n grandTotal: this.getTotal().grandTotal.getDetails(),\r\n },\r\n customFields: this.getAllCustomFields()\r\n };\r\n }\r\n\r\n /**\r\n * Adds or updates sub-items (e.g., sizes with quantities) to the line item.\r\n * If a sub-item with the same size already exists, its quantity is either\r\n * updated by adding the new quantity or replaced entirely, based on the `addQuantity` flag.\r\n * Sub-items with a resulting quantity of 0 are removed.\r\n * @param subItems - An array of `SubItem` objects to add or update.\r\n * @param addQuantity - If true, adds the quantity from `subItem` to the existing quantity.\r\n * If false, replaces the existing quantity with the one from `subItem`.\r\n */\r\n addSubItems(subItems: SubItem[], addQuantity: boolean): void {\r\n subItems.forEach(subItem => {\r\n const existingSubItem = this.subItems.find(item => item.size === subItem.size);\r\n if (existingSubItem) {\r\n existingSubItem.quantity = addQuantity ? existingSubItem.quantity + subItem.quantity : subItem.quantity;\r\n } else {\r\n this.subItems.push(subItem);\r\n }\r\n })\r\n this.subItems = this.subItems.filter(sub => sub.quantity > 0);\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the line item with the latest product data (price, image, name, specifications).\r\n * Validates that the product matches the line item's selection and is active.\r\n * @param product - The product model to update from.\r\n * @param cartCountry - The country code for pricing context.\r\n * @param cartCurrency - The currency code for pricing context.\r\n * @throws {Error} If product mismatch, inactive, size mismatch, or pricing missing.\r\n */\r\n public updateProductData(product: ProductModel, cartCountry: CountryCode, cartCurrency: CurrencyCode): void {\r\n if (this.productKey !== product.getKey() || !product.validateSelectionAttribute(this.selectionAttributes)) {\r\n throw new ProductMismatchError();\r\n } else if (!product.getIsActive()) {\r\n throw new ProductInactiveError();\r\n }\r\n\r\n this.subItems.forEach(subItem => {\r\n if (!product.validateSize(subItem.size)) {\r\n throw new SizeMismatchError();\r\n }\r\n });\r\n\r\n const productPricing = product.getPriceDetails(cartCountry);\r\n if (!productPricing || productPricing.getBaseUnitPrice().getCurrency() !== cartCurrency) {\r\n throw new PricingNotFoundError();\r\n }\r\n this.name = product.getName();\r\n this.specifications = product.getSpecifications();\r\n this.primaryImage = product.getImages(this.selectionAttributes).primary;\r\n\r\n const quantity = this.subItems.reduce((sum, s) => sum + s.quantity, 0);\r\n const { unitPrice } = productPricing.getApplicableTier(quantity);\r\n\r\n this.pricing = {\r\n unitPrice: unitPrice,\r\n tierPricing: productPricing,\r\n taxCategory: productPricing.getTaxCategory(),\r\n tax: this.pricing.tax\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.discounts = 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(taxRule: TaxRuleModel): void {\r\n if (!taxRule.appliesTo(this.pricing.taxCategory, this.pricing.tax.country)) {\r\n throw new InvalidTaxRuleError();\r\n }\r\n\r\n const taxableUnitPrice = this.total.quantity > 0 ? \r\n this.total.taxableAmount.divide(this.total.quantity) \r\n : \r\n this.total.taxableAmount.zero();\r\n\r\n this.pricing.tax = {\r\n taxRuleId: taxRule.getTaxRuleId(),\r\n taxSystem: taxRule.getTaxSystem(),\r\n country: taxRule.getCountry(),\r\n rate: taxRule.getApplicableTaxRate(taxableUnitPrice),\r\n taxSlabs: taxRule.getSlabs(),\r\n };\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 subtotal: zero,\r\n taxableAmount: zero,\r\n taxTotal: zero,\r\n discounts: {},\r\n grandTotal: zero\r\n };\r\n return;\r\n }\r\n\r\n const { unitPrice } = this.pricing.tierPricing.getApplicableTier(totalQuantity);\r\n const subTotal = unitPrice.multiply(totalQuantity);\r\n const discounts = Object.values(this.total.discounts).reduce((sum, s) => sum.add(s), zero);\r\n const taxableAmount = subTotal.subtract(discounts);\r\n const unitTaxbleAmount = totalQuantity > 0 ? taxableAmount.divide(totalQuantity) : zero;\r\n const taxRate = TaxRuleModel.getApplicableTaxRate(unitTaxbleAmount, this.pricing.tax.taxSlabs);\r\n const taxTotal = taxableAmount.multiply(taxRate).round();\r\n const grandTotal = subTotal.subtract(discounts).add(taxTotal);\r\n\r\n this.total = {\r\n quantity: totalQuantity,\r\n subtotal: subTotal,\r\n taxableAmount: taxableAmount,\r\n taxTotal: taxTotal,\r\n discounts: this.total.discounts,\r\n grandTotal: grandTotal\r\n }\r\n }\r\n\r\n /**\r\n * Updates the line item's state.\r\n * @param newState \r\n */\r\n public updateState(newState: LineItemState): void {\r\n if(this.state in LineItemState) {\r\n if (this.state !== newState) {\r\n this.state = newState;\r\n }\r\n } else {\r\n throw new InvalidLineItemStateError(newState);\r\n }\r\n }\r\n\r\n /**\r\n * Resets the line item's properties to their default empty or initial state.\r\n * Useful for clearing out line item data without creating a new instance.\r\n * Recalculates total quantity and price total afterwards (which will be zero).\r\n */\r\n clearLineItem(): void {\r\n const zero = this.pricing.unitPrice.zero()\r\n this.id = '';\r\n this.productKey = '';\r\n this.selectionAttributes = { color: { name: '' } };\r\n this.name = { en: '' };\r\n this.primaryImage = new ImageInfoModel({ sources: { original: '' } });\r\n this.subItems = [];\r\n this.pricing = {\r\n unitPrice: zero,\r\n tierPricing: this.pricing.tierPricing,\r\n taxCategory: this.pricing.taxCategory,\r\n tax: this.pricing.tax\r\n }\r\n this.total = {\r\n quantity: 0,\r\n subtotal: zero,\r\n taxableAmount: zero,\r\n taxTotal: zero,\r\n discounts: {},\r\n grandTotal: zero\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","s","couponCode","discount","locale","LocaleLanguageMap","subItems","addQuantity","subItem","existingSubItem","sub","product","cartCountry","cartCurrency","ProductMismatchError","ProductInactiveError","SizeMismatchError","productPricing","PricingNotFoundError","quantity","sum","unitPrice","appliedDiscounts","lineItemDiscounts","taxRule","InvalidTaxRuleError","taxableUnitPrice","zero","totalQuantity","subTotal","discounts","taxableAmount","unitTaxbleAmount","taxRate","TaxRuleModel","taxTotal","grandTotal","newState","LineItemState","InvalidLineItemStateError"],"mappings":"gWAsEA,IAAqBA,CAArB,CAAA,cAA2CC,CAAiB,CAChD,EACA,CAAA,UAAA,CACA,mBAEA,CAAA,IAAA,CACA,cACA,CAAA,YAAA,CACA,QACA,CAAA,OAAA,CAaA,MACA,KAcV,CAAA,WAAA,CAAYC,CAA0B,CAAA,CACpC,KAAMA,CAAAA,CAAI,CACV,CAAA,IAAA,CAAK,EAAKA,CAAAA,CAAAA,CAAK,EACf,CAAA,IAAA,CAAK,UAAaA,CAAAA,CAAAA,CAAK,UACvB,CAAA,IAAA,CAAK,oBAAsBC,GAAM,CAAA,SAAA,CAAUD,CAAK,CAAA,mBAAmB,CAEnE,CAAA,IAAA,CAAK,IAAOC,CAAAA,GAAAA,CAAM,SAAUD,CAAAA,CAAAA,CAAK,IAAI,CAAA,CACrC,IAAK,CAAA,cAAA,CAAiBC,GAAM,CAAA,SAAA,CAAUD,EAAK,cAAc,CAAA,CACzD,IAAK,CAAA,YAAA,CAAe,IAAIE,CAAAA,CAAeF,CAAK,CAAA,YAAY,EACxD,IAAK,CAAA,QAAA,CAAWC,GAAM,CAAA,SAAA,CAAUD,CAAK,CAAA,QAAQ,CAE7C,CAAA,IAAIG,EAA4B,IAAI,GAAA,CACpC,IAAK,CAAA,QAAA,CAAS,OAAQC,CAAAA,CAAAA,EAAQ,CAC5B,GAAID,CAA0B,CAAA,GAAA,CAAIC,CAAK,CAAA,IAAI,CACzC,CAAA,MAAM,IAAIC,CAAAA,CAAmBD,EAAK,IAAI,CAAA,CAExCD,CAA0B,CAAA,GAAA,CAAIC,CAAK,CAAA,IAAI,EACzC,CAAC,EAED,IAAK,CAAA,OAAA,CAAU,CACb,SAAA,CAAW,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ACV,CAAA,IAAA,CAAK,UAAa,CAAA,EAAA,CAClB,IAAK,CAAA,mBAAA,CAAsB,CAAE,KAAA,CAAO,CAAE,IAAA,CAAM,EAAG,CAAE,CACjD,CAAA,IAAA,CAAK,IAAO,CAAA,CAAE,GAAI,EAAG,CAAA,CACrB,IAAK,CAAA,YAAA,CAAe,IAAIhC,CAAAA,CAAe,CAAE,OAAA,CAAS,CAAE,QAAU,CAAA,EAAG,CAAE,CAAC,CACpE,CAAA,IAAA,CAAK,QAAW,CAAA,GAChB,IAAK,CAAA,OAAA,CAAU,CACb,SAAA,CAAWgC,CACX,CAAA,WAAA,CAAa,IAAK,CAAA,OAAA,CAAQ,WAC1B,CAAA,WAAA,CAAa,IAAK,CAAA,OAAA,CAAQ,WAC1B,CAAA,GAAA,CAAK,IAAK,CAAA,OAAA,CAAQ,GACpB,CACA,CAAA,IAAA,CAAK,KAAQ,CAAA,CACX,QAAU,CAAA,CAAA,CACV,QAAUA,CAAAA,CAAAA,CACV,cAAeA,CACf,CAAA,QAAA,CAAUA,CACV,CAAA,SAAA,CAAW,EAAC,CACZ,UAAYA,CAAAA,CACd,EACF,CACF","file":"chunk-5VI4V3SF.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, TaxCategory, TaxSystem } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport ProductModel, { ProductSelectionAttributes, ProductSpecification, SelectionAttributes } from \"./Product\";\r\nimport { TaxRuleModel, TaxSlabModel, TaxSlabs } 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} from \"./Error\";\r\nimport { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\n\r\nexport type SubItem = {\r\n size: string | 'ONESIZE';\r\n quantity: number;\r\n};\r\n\r\nexport type LineItemPricing = {\r\n unitPrice: PriceData;\r\n tierPricing: TieredPriceData;\r\n taxCategory: TaxCategory;\r\n tax: {\r\n taxRuleId: string;\r\n taxSystem: TaxSystem;\r\n country: CountryCode;\r\n rate: number;\r\n taxSlabs: TaxSlabs;\r\n };\r\n};\r\n\r\nexport type LineItemTotals = {\r\n quantity: number;\r\n subtotal: PriceData;\r\n discounts: Record<string, PriceData>; // couponCode -> discount mapping\r\n taxableAmount: PriceData; // subtotal - discount\r\n taxTotal: PriceData;\r\n grandTotal: PriceData;\r\n};\r\n\r\nexport type LineItemAttributes = CustomFieldAttributes & {\r\n id: string;\r\n\r\n productKey: string;\r\n selectionAttributes: SelectionAttributes;\r\n\r\n name: LocalizedString;\r\n specifications: LocalizedValue<ProductSpecification>;\r\n primaryImage: ImageInfoData;\r\n\r\n subItems: SubItem[];\r\n\r\n pricing: LineItemPricing;\r\n\r\n state?: LineItemState;\r\n total: LineItemTotals;\r\n}\r\n\r\nexport type LineItemData = Required<LineItemAttributes>;\r\n\r\n/**\r\n * Represents a line item within a shopping cart.\r\n */\r\nexport default class LineItemModel extends CustomFieldModel {\r\n protected id: string;\r\n protected productKey: string;\r\n protected selectionAttributes: SelectionAttributes;\r\n\r\n protected name: LocalizedString;\r\n protected specifications: LocalizedValue<ProductSpecification>;\r\n protected primaryImage: ImageInfoModel;\r\n protected subItems: SubItem[];\r\n protected pricing: {\r\n unitPrice: PriceModel;\r\n tierPricing: TieredPriceModel;\r\n taxCategory: TaxCategory;\r\n tax: {\r\n taxRuleId: string;\r\n taxSystem: TaxSystem;\r\n country: CountryCode;\r\n taxSlabs: TaxSlabModel[];\r\n rate: number;\r\n };\r\n };\r\n\r\n protected state: LineItemState;\r\n protected total: {\r\n quantity: number;\r\n subtotal: PriceModel;\r\n discounts: Record<string, PriceModel>;\r\n taxableAmount: PriceModel; // subtotal - discount\r\n\r\n taxTotal: PriceModel;\r\n grandTotal: PriceModel;\r\n };\r\n\r\n /**\r\n * Creates an instance of LineItemModel.\r\n * @param data - The initial line item attributes.\r\n */\r\n constructor(data: LineItemAttributes) {\r\n super(data);\r\n this.id = data.id;\r\n this.productKey = data.productKey;\r\n this.selectionAttributes = Utils.deepClone(data.selectionAttributes);\r\n\r\n this.name = Utils.deepClone(data.name);\r\n this.specifications = Utils.deepClone(data.specifications);\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.subItems = Utils.deepClone(data.subItems);\r\n\r\n let uniqueSelectionAttributes = new Set();\r\n this.subItems.forEach(item => {\r\n if (uniqueSelectionAttributes.has(item.size)) {\r\n throw new DuplicateSizeError(item.size);\r\n }\r\n uniqueSelectionAttributes.add(item.size);\r\n });\r\n\r\n this.pricing = {\r\n unitPrice: new PriceModel(data.pricing.unitPrice),\r\n tierPricing: new TieredPriceModel(data.pricing.tierPricing),\r\n taxCategory: data.pricing.taxCategory,\r\n tax: {\r\n taxRuleId: data.pricing.tax.taxRuleId,\r\n taxSystem: data.pricing.tax.taxSystem,\r\n country: data.pricing.tax.country,\r\n rate: data.pricing.tax.rate,\r\n taxSlabs: data.pricing.tax.taxSlabs.map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: new PriceModel(s.minUnitPrice),\r\n maxUnitPrice: s.maxUnitPrice ? new PriceModel(s.maxUnitPrice) : undefined,\r\n })),\r\n },\r\n }\r\n\r\n this.state = data.state ?? LineItemState.INITIAL;\r\n\r\n this.total = {\r\n quantity: data.total.quantity,\r\n subtotal: new PriceModel(data.total.subtotal),\r\n discounts: Object.fromEntries(\r\n Object.entries(data.total.discounts).map(([couponCode, discount]) => [\r\n couponCode,\r\n new PriceModel(discount),\r\n ])\r\n ),\r\n taxableAmount: new PriceModel(data.total.taxableAmount),\r\n taxTotal: new PriceModel(data.total.taxTotal),\r\n grandTotal: new PriceModel(data.total.grandTotal),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the unique identifier of the line item.\r\n * @returns The unique ID string.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the product key associated with this line item.\r\n * @returns The product key string.\r\n */\r\n getProductKey(): string {\r\n return this.productKey;\r\n }\r\n\r\n /**\r\n * Gets the selection attributes (e.g., size, color) for this line item.\r\n * @returns A copy of the selection attributes object.\r\n */\r\n getSelectionAttributes(): SelectionAttributes {\r\n return Utils.deepClone(this.selectionAttributes);\r\n }\r\n\r\n /**\r\n * Gets the full localized product name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the product name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return Utils.deepClone(this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en);\r\n } else {\r\n return Utils.deepClone(this.name);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product specifications object.\r\n * @returns Product Specifications\r\n */\r\n getSpecifications(): LocalizedValue<ProductSpecification>\r\n /**\r\n * Gets the product specifications for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The ProductSpecification object for the specified locale, or undefined if not found.\r\n */\r\n getSpecifications(locale: LocaleCode): ProductSpecification | undefined\r\n getSpecifications(locale?: LocaleCode): LocalizedValue<ProductSpecification> | ProductSpecification | undefined {\r\n if (locale) {\r\n return Utils.deepClone(this.specifications[locale] ?? this.specifications[LocaleLanguageMap[locale]] ?? this.specifications.en);\r\n } else {\r\n return Utils.deepClone(this.specifications);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the image information model for this line item.\r\n * @returns The ImageInfoModel instance.\r\n */\r\n getImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /**\r\n * Gets the sub-items (size/quantity breakdown).\r\n * @returns A copy of the array of SubItems.\r\n */\r\n getSubItems(): SubItem[] {\r\n return Utils.deepClone(this.subItems);\r\n }\r\n\r\n /**\r\n * Gets the total quantity for this line item across all sub-items.\r\n * @returns The total quantity as a number.\r\n */\r\n getTotalQuantity(): number {\r\n return this.total.quantity;\r\n }\r\n\r\n /**\r\n * Gets the pricing information model for this line item.\r\n * @returns An object containing unit price, tiered pricing, tax category, and tax details.\r\n */\r\n getPricing() {\r\n return {\r\n unitPrice: this.pricing.unitPrice,\r\n tierPricing: this.pricing.tierPricing,\r\n taxCategory: this.pricing.taxCategory,\r\n tax: {\r\n taxRuleId: this.pricing.tax.taxRuleId,\r\n taxSystem: this.pricing.tax.taxSystem,\r\n country: this.pricing.tax.country,\r\n rate: this.pricing.tax.rate,\r\n taxSlabs: this.pricing.tax.taxSlabs,\r\n }\r\n };\r\n }\r\n\r\n /**\r\n * Gets the current state of the line item.\r\n * @returns The LineItemState enum value.\r\n */\r\n getState() {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the total price for this line item (including all sub-items).\r\n * @returns An object containing line item totals including subtotal, tax, discounts, and grand total.\r\n */\r\n getTotal() {\r\n return {\r\n quantity: this.total.quantity,\r\n subtotal: this.total.subtotal,\r\n taxableAmount: this.total.taxableAmount,\r\n taxTotal: this.total.taxTotal,\r\n discounts: Object.fromEntries(\r\n Object.entries(this.total.discounts).map(([couponCode, discount]) => [\r\n couponCode,\r\n discount,\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 return {\r\n id: this.getId(),\r\n productKey: this.getProductKey(),\r\n selectionAttributes: this.getSelectionAttributes(),\r\n name: this.getName(),\r\n specifications: this.getSpecifications(),\r\n primaryImage: this.getImage().getDetails(),\r\n subItems: this.getSubItems(),\r\n pricing: {\r\n unitPrice: this.getPricing().unitPrice.getDetails(),\r\n tierPricing: this.getPricing().tierPricing.getDetails(),\r\n taxCategory: this.getPricing().taxCategory,\r\n tax: {\r\n taxRuleId: this.getPricing().tax.taxRuleId,\r\n taxSystem: this.getPricing().tax.taxSystem,\r\n country: this.getPricing().tax.country,\r\n rate: this.getPricing().tax.rate,\r\n taxSlabs: this.getPricing().tax.taxSlabs.map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: s.minUnitPrice.getDetails(),\r\n maxUnitPrice: s.maxUnitPrice ? s.maxUnitPrice.getDetails() : undefined,\r\n })),\r\n }\r\n },\r\n state: this.getState(),\r\n total: {\r\n quantity: this.getTotal().quantity,\r\n subtotal: this.getTotal().subtotal.getDetails(),\r\n taxableAmount: this.getTotal().taxableAmount.getDetails(),\r\n taxTotal: this.getTotal().taxTotal.getDetails(),\r\n discounts: Object.fromEntries(\r\n Object.entries(this.getTotal().discounts).map(([couponCode, discount]) => [\r\n couponCode,\r\n discount.getDetails(),\r\n ])\r\n ),\r\n grandTotal: this.getTotal().grandTotal.getDetails(),\r\n },\r\n customFields: this.getAllCustomFields()\r\n };\r\n }\r\n\r\n /**\r\n * Adds or updates sub-items (e.g., sizes with quantities) to the line item.\r\n * If a sub-item with the same size already exists, its quantity is either\r\n * updated by adding the new quantity or replaced entirely, based on the `addQuantity` flag.\r\n * Sub-items with a resulting quantity of 0 are removed.\r\n * @param subItems - An array of `SubItem` objects to add or update.\r\n * @param addQuantity - If true, adds the quantity from `subItem` to the existing quantity.\r\n * If false, replaces the existing quantity with the one from `subItem`.\r\n */\r\n addSubItems(subItems: SubItem[], addQuantity: boolean): void {\r\n subItems.forEach(subItem => {\r\n const existingSubItem = this.subItems.find(item => item.size === subItem.size);\r\n if (existingSubItem) {\r\n existingSubItem.quantity = addQuantity ? existingSubItem.quantity + subItem.quantity : subItem.quantity;\r\n } else {\r\n this.subItems.push(subItem);\r\n }\r\n })\r\n this.subItems = this.subItems.filter(sub => sub.quantity > 0);\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the line item with the latest product data (price, image, name, specifications).\r\n * Validates that the product matches the line item's selection and is active.\r\n * @param product - The product model to update from.\r\n * @param cartCountry - The country code for pricing context.\r\n * @param cartCurrency - The currency code for pricing context.\r\n * @throws {Error} If product mismatch, inactive, size mismatch, or pricing missing.\r\n */\r\n public updateProductData(product: ProductModel, cartCountry: CountryCode, cartCurrency: CurrencyCode): void {\r\n if (this.productKey !== product.getKey() || !product.validateSelectionAttribute(this.selectionAttributes)) {\r\n throw new ProductMismatchError();\r\n } else if (!product.getIsActive()) {\r\n throw new ProductInactiveError();\r\n }\r\n\r\n this.subItems.forEach(subItem => {\r\n if (!product.validateSize(subItem.size)) {\r\n throw new SizeMismatchError();\r\n }\r\n });\r\n\r\n const productPricing = product.getPriceDetails(cartCountry);\r\n if (!productPricing || productPricing.getBaseUnitPrice().getCurrency() !== cartCurrency) {\r\n throw new PricingNotFoundError();\r\n }\r\n this.name = product.getName();\r\n this.specifications = product.getSpecifications();\r\n this.primaryImage = product.getImages(this.selectionAttributes).primary;\r\n\r\n const quantity = this.subItems.reduce((sum, s) => sum + s.quantity, 0);\r\n const { unitPrice } = productPricing.getApplicableTier(quantity);\r\n\r\n this.pricing = {\r\n unitPrice: unitPrice,\r\n tierPricing: productPricing,\r\n taxCategory: productPricing.getTaxCategory(),\r\n tax: this.pricing.tax\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.discounts = 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(taxRule: TaxRuleModel): void {\r\n if (!taxRule.appliesTo(this.pricing.taxCategory, this.pricing.tax.country)) {\r\n throw new InvalidTaxRuleError();\r\n }\r\n\r\n const taxableUnitPrice = this.total.quantity > 0 ? \r\n this.total.taxableAmount.divide(this.total.quantity) \r\n : \r\n this.total.taxableAmount.zero();\r\n\r\n this.pricing.tax = {\r\n taxRuleId: taxRule.getTaxRuleId(),\r\n taxSystem: taxRule.getTaxSystem(),\r\n country: taxRule.getCountry(),\r\n rate: taxRule.getApplicableTaxRate(taxableUnitPrice),\r\n taxSlabs: taxRule.getSlabs(),\r\n };\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 subtotal: zero,\r\n taxableAmount: zero,\r\n taxTotal: zero,\r\n discounts: {},\r\n grandTotal: zero\r\n };\r\n return;\r\n }\r\n\r\n const { unitPrice } = this.pricing.tierPricing.getApplicableTier(totalQuantity);\r\n const subTotal = unitPrice.multiply(totalQuantity);\r\n const discounts = Object.values(this.total.discounts).reduce((sum, s) => sum.add(s), zero);\r\n const taxableAmount = subTotal.subtract(discounts);\r\n const unitTaxbleAmount = totalQuantity > 0 ? taxableAmount.divide(totalQuantity) : zero;\r\n const taxRate = TaxRuleModel.getApplicableTaxRate(unitTaxbleAmount, this.pricing.tax.taxSlabs);\r\n const taxTotal = taxableAmount.multiply(taxRate).round();\r\n const grandTotal = subTotal.subtract(discounts).add(taxTotal);\r\n\r\n this.total = {\r\n quantity: totalQuantity,\r\n subtotal: subTotal,\r\n taxableAmount: taxableAmount,\r\n taxTotal: taxTotal,\r\n discounts: this.total.discounts,\r\n grandTotal: grandTotal\r\n }\r\n }\r\n\r\n /**\r\n * Updates the line item's state.\r\n * @param newState \r\n */\r\n public updateState(newState: LineItemState): void {\r\n if(this.state in LineItemState) {\r\n if (this.state !== newState) {\r\n this.state = newState;\r\n }\r\n } else {\r\n throw new InvalidLineItemStateError(newState);\r\n }\r\n }\r\n\r\n /**\r\n * Resets the line item's properties to their default empty or initial state.\r\n * Useful for clearing out line item data without creating a new instance.\r\n * Recalculates total quantity and price total afterwards (which will be zero).\r\n */\r\n clearLineItem(): void {\r\n const zero = this.pricing.unitPrice.zero()\r\n this.id = '';\r\n this.productKey = '';\r\n this.selectionAttributes = { color: { name: '' } };\r\n this.name = { en: '' };\r\n this.primaryImage = new ImageInfoModel({ sources: { original: '' } });\r\n this.subItems = [];\r\n this.pricing = {\r\n unitPrice: zero,\r\n tierPricing: this.pricing.tierPricing,\r\n taxCategory: this.pricing.taxCategory,\r\n tax: this.pricing.tax\r\n }\r\n this.total = {\r\n quantity: 0,\r\n subtotal: zero,\r\n taxableAmount: zero,\r\n taxTotal: zero,\r\n discounts: {},\r\n grandTotal: zero\r\n };\r\n }\r\n}"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a}from'./chunk-5VI4V3SF.mjs';import {b as b$1}from'./chunk-YSUBOEFT.mjs';import {e}from'./chunk-GF427QWC.mjs';import {a as a$1}from'./chunk-LEHPVA3Q.mjs';import {a as a$2}from'./chunk-EV4HUBJL.mjs';import {b}from'./chunk-6KCJVEZD.mjs';var D=class extends b{id;customerId;customerEmail;anonymousId;lineItems;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,i=new Date){super(t,i),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.billingAddress=t.billingAddress?new b$1(t.billingAddress,i):null,this.shippingAddress=t.shippingAddress?new b$1(t.shippingAddress,i):null,this.coupons=(t.coupons??[]).map(o=>new e(o)),this.shippingDetails=t.shippingDetails?a$1.deepClone(t.shippingDetails):null,this.total={subtotal:new a$2(t.total.subtotal),shipping:new a$2(t.total.shipping),effectiveShipping:new a$2(t.total.effectiveShipping),taxTotal:new a$2(t.total.taxTotal),couponTotal:Object.fromEntries(Object.entries(t.total.couponTotal).map(([o,e])=>[o,new a$2(e)])),couponDiscountTotal:new a$2(t.total.couponDiscountTotal),grandTotal:new a$2(t.total.grandTotal)};}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}getShippingDetails(){return this.shippingDetails?{...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 this.total}getDetails(){return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(t=>t.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(t=>t.getDetails()),total:{subtotal:this.getTotal().subtotal.getDetails(),shipping:this.getTotal().shipping.getDetails(),effectiveShipping:this.getTotal().effectiveShipping.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),couponTotal:Object.fromEntries(Object.entries(this.getTotal().couponTotal).map(([t,i])=>[t,i.getDetails()])),couponDiscountTotal:this.getTotal().couponDiscountTotal.getDetails(),grandTotal:this.getTotal().grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new a$2({amount:0,currency:this.currency}),i=this.lineItems.filter(r=>r.getState()!=="CANCELLED"),o=i.reduce((r,c)=>r.add(c.getTotal().subtotal),t),e=new a$2({amount:this.shippingDetails?.cost||0,currency:this.currency}).round(),s=t,n={},u={};this.coupons.forEach(r=>{let c=r.calculateApplicableCouponDiscount(o,e,this.country,this.currency);s=s.add(c),n[r.getCode()]=c,r.getCategory()!=="SHIPPING"&&(u[r.getCode()]=c);}),this.applyDiscountsInLineItem(u);let p=i.reduce((r,c)=>r.add(c.getTotal().taxTotal),t),l=this.coupons.find(r=>r.getCategory()==="SHIPPING"),h=l?e.subtract(n[l.getCode()]||t):e,g=o.add(e).add(p).subtract(s);this.total={subtotal:o,shipping:e,effectiveShipping:h,couponTotal:n,couponDiscountTotal:s,taxTotal:p,grandTotal:g};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let i=t.filter(e=>e.getCategory()==="SHIPPING"),o=t.filter(e=>e.getCategory()!=="SHIPPING");this.coupons=[],this.total.couponDiscountTotal=this.total.subtotal.zero(),this.total.couponTotal={},o.length&&this.applyNonShippingCoupons(o),this.applyDiscountsInLineItem(this.total.couponTotal),i.length&&this.applyShippingCoupons(i),this.calculateTotals();}applyDiscountsInLineItem(t){let i=Array.from(Object.entries(t)).filter(e=>!e[1].isZero()),o=new Map;this.lineItems.forEach(e=>o.set(e.getId(),[])),i.forEach(([e,s])=>{let n=this.coupons.find(l=>l.getCode()===e);if(!n||s.isZero())return;let u=this.lineItems.filter(l=>l.getState()!=="CANCELLED"&&!l.getTotal().subtotal.isZero()).sort((l,h)=>l.getTotal().subtotal.compareTo(h.getTotal().subtotal)),p=new a$2({amount:0,currency:this.currency});u.forEach((l,h)=>{let g;h===u.length-1?g=s.subtract(p):g=s.multiply(l.getTotal().subtotal).divide(this.total.subtotal).round(),p=p.add(g),o.get(l.getId())?.push({coupon:n,amount:g});});}),this.lineItems.forEach(e=>{e.getState()==="CANCELLED"||this.total.subtotal.isZero()?e.updateDiscounts([]):e.updateDiscounts(o.get(e.getId())||[]);});}updateTax(t){this.lineItems.forEach(i=>{i.updateTax(t[i.getPricing().taxCategory]);}),this.calculateTotals();}applyNonShippingCoupons(t){let i=t.filter(o=>o.getType()==="coupon");if(i.length===1){let o=i[0].calculateApplicableCouponDiscount(this.total.subtotal,this.total.shipping,this.country,this.currency);o.getAmount()>0&&(this.coupons.push(i[0]),this.total.couponTotal[i[0].getCode()]=o,this.total.couponDiscountTotal=o);}}applyShippingCoupons(t){if(this.total.shipping.getAmount()>0&&t.length>0){let i=this.total.subtotal.subtract(this.total.couponDiscountTotal),o=t.reduce((s,n)=>{if(!s)return n;let u=n.calculateApplicableCouponDiscount(i,this.total.shipping,this.country,this.currency).min(this.total.shipping),p=s.calculateApplicableCouponDiscount(i,this.total.shipping,this.country,this.currency).min(this.total.shipping);return u===p?n.getType()==="coupon"?n:s:u.compareTo(p)>0?n:s}),e=o.calculateApplicableCouponDiscount(i,this.total.shipping,this.country,this.currency).min(this.total.shipping);e.getAmount()>0&&(this.coupons.push(o),this.total.couponTotal[o.getCode()]=e,this.total.couponDiscountTotal=this.total.couponDiscountTotal.add(e),this.total.effectiveShipping=this.total.shipping.subtract(e));}}};export{D as a};//# sourceMappingURL=chunk-CKJONVT3.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-CKJONVT3.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/Classes/ShoppingContainer.ts"],"names":["BaseShoppingContainerModel","BaseModel","data","date","item","LineItemModel","AddressModel","coupon","CouponModel","Utils_default","PriceModel","key","value","zero","filteredLineItems","lineitem","subTotal","total","lineItem","shipping","couponDiscountTotal","couponTotal","nonShippingCouponTotal","couponValue","taxTotal","shippingCoupon","effectiveShipping","grandTotal","shippingDetails","applicableCoupons","shippingCoupons","otherCoupons","couponDiscounts","couponDiscount","itemDiscounts","li","code","totalDiscount","c","validItems","a","b","distributed","index","amount","taxRules","coupons","subTotalWithCouponDiscount","maxValuedCoupon","maxCoupon","currentCoupon","currentCouponValue","maxCouponValue"],"mappings":"mPA6DA,IAA8BA,CAA9B,CAAA,cAAiEC,CAAU,CAC/D,EACA,CAAA,UAAA,CACA,aACA,CAAA,WAAA,CACA,SACA,CAAA,eAAA,CACA,eACA,CAAA,cAAA,CAGA,QAGA,KAUA,CAAA,OAAA,CACA,QACA,CAAA,MAAA,CAQV,WAAYC,CAAAA,CAAAA,CAAuCC,CAAa,CAAA,IAAI,KAAQ,CAC1E,KAAA,CAAMD,CAAMC,CAAAA,CAAI,CAChB,CAAA,IAAA,CAAK,EAAKD,CAAAA,CAAAA,CAAK,GACf,IAAK,CAAA,UAAA,CAAaA,CAAK,CAAA,UAAA,CACvB,IAAK,CAAA,aAAA,CAAgBA,CAAK,CAAA,aAAA,CAC1B,IAAK,CAAA,WAAA,CAAcA,CAAK,CAAA,WAAA,CACxB,IAAK,CAAA,OAAA,CAAUA,CAAK,CAAA,OAAA,CACpB,KAAK,QAAWA,CAAAA,CAAAA,CAAK,QACrB,CAAA,IAAA,CAAK,MAASA,CAAAA,CAAAA,CAAK,MACnB,CAAA,IAAA,CAAK,WAAaA,CAAK,CAAA,SAAA,EAAa,EAAC,EAAG,GAAIE,CAAAA,CAAAA,EAAQ,IAAIC,CAAAA,CAAcD,CAAI,CAAC,CAAA,CAC3E,IAAK,CAAA,cAAA,CAAiBF,CAAK,CAAA,cAAA,CAAiB,IAAII,GAAAA,CAAaJ,CAAK,CAAA,cAAA,CAAgBC,CAAI,CAAA,CAAI,IAC1F,CAAA,IAAA,CAAK,eAAkBD,CAAAA,CAAAA,CAAK,gBAAkB,IAAII,GAAAA,CAAaJ,CAAK,CAAA,eAAA,CAAiBC,CAAI,CAAA,CAAI,IAC7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,GAAuBC,CAClBF,CAAAA,CAAAA,CAAc,OAAQ,EAAA,GAAM,QAAWA,CAAAA,CAAAA,CAAgBD,CAEzDE,CAAAA,CAAAA,CAAmB,SAAUC,CAAAA,CAAc,CAAI,CAAA,CAAA,CAAIF,CAAgBD,CAAAA,CAC5E,CAAC,CAEK1B,CAAAA,CAAAA,CAAcyB,CAAgB,CAAA,iCAAA,CAAkCD,CAA4B,CAAA,IAAA,CAAK,KAAM,CAAA,QAAA,CAAU,KAAK,OAAS,CAAA,IAAA,CAAK,QAAQ,CAAA,CAAE,GAAI,CAAA,IAAA,CAAK,KAAM,CAAA,QAAQ,EACvKxB,CAAY,CAAA,SAAA,EAAc,CAAA,CAAA,GAC5B,IAAK,CAAA,OAAA,CAAQ,IAAKyB,CAAAA,CAAe,EACjC,IAAK,CAAA,KAAA,CAAM,WAAYA,CAAAA,CAAAA,CAAgB,OAAQ,EAAC,CAAIzB,CAAAA,CAAAA,CACpD,KAAK,KAAM,CAAA,mBAAA,CAAsB,IAAK,CAAA,KAAA,CAAM,mBAAoB,CAAA,GAAA,CAAIA,CAAW,CAAA,CAC/E,KAAK,KAAM,CAAA,iBAAA,CAAoB,IAAK,CAAA,KAAA,CAAM,QAAS,CAAA,QAAA,CAASA,CAAW,CAAA,EAE3E,CACF,CACF","file":"chunk-CKJONVT3.mjs","sourcesContent":["import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport AddressModel, { AddressData } from \"./Address\";\r\nimport LineItemModel, { LineItemData } from \"./LineItem\";\r\nimport { CountryCode, CurrencyCode, LocaleCode, ShippingDetails } from \"./Common\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport CouponModel, { CouponCategory, CouponData, CouponType } from \"./Coupon\";\r\nimport Utils from \"../Utils\";\r\nimport { LineItemState, TaxCategory } from \"./Enum\";\r\nimport { TaxRuleModel } from \"./TaxRule\";\r\n\r\nexport type ShoppingContainerTotal = {\r\n /** Sum of item prices before discounts & tax */\r\n subtotal: PriceData;\r\n\r\n /** Original shipping cost before coupons / promotions */\r\n shipping: PriceData;\r\n\r\n /** Shipping after coupons / promotions (>= 0) */\r\n effectiveShipping: PriceData;\r\n\r\n /** Total tax amount (all tax rules combined) */\r\n taxTotal: PriceData;\r\n\r\n /**\r\n * Coupon discounts applied\r\n * key = couponCode (or couponId)\r\n * value = discount amount (positive number)\r\n */\r\n couponTotal: Record<string, PriceData>;\r\n\r\n /** Total discount from coupons (derived, optional to store) */\r\n couponDiscountTotal: PriceData;\r\n\r\n /** Final payable amount */\r\n grandTotal: PriceData;\r\n};\r\n\r\n\r\nexport type BaseShoppingContainerAttributes = BaseAttributes & {\r\n id: string;\r\n customerId?: string;\r\n customerEmail?: string;\r\n anonymousId?: string;\r\n lineItems: LineItemData[];\r\n shippingDetails: ShippingDetails | null;\r\n shippingAddress?: AddressData | null;\r\n billingAddress?: AddressData | null;\r\n coupons: CouponData[];\r\n total: ShoppingContainerTotal;\r\n country: CountryCode;\r\n currency: CurrencyCode;\r\n locale: LocaleCode;\r\n};\r\n\r\nexport type BaseShoppingContainerData = BaseShoppingContainerAttributes & BaseData\r\n\r\n\r\n/**\r\n * Abstract base class for shopping-related containers like carts and orders.\r\n * Manages common elements such as line items, addresses, coupons, and totals.\r\n */\r\nexport default abstract class BaseShoppingContainerModel extends BaseModel {\r\n protected id: string;\r\n protected customerId?: string;\r\n protected customerEmail?: string;\r\n protected anonymousId?: string;\r\n protected lineItems: LineItemModel[];\r\n protected shippingDetails: ShippingDetails | null;\r\n protected shippingAddress: AddressModel | null;\r\n protected billingAddress: AddressModel | null;\r\n\r\n // CouponsCodes\r\n protected coupons: CouponModel[];\r\n\r\n // Cart Totals\r\n protected total: {\r\n subtotal: PriceModel;\r\n shipping: PriceModel;\r\n effectiveShipping: PriceModel;\r\n taxTotal: PriceModel;\r\n couponTotal: Record<string, PriceModel>;\r\n couponDiscountTotal: PriceModel;\r\n grandTotal: PriceModel;\r\n };\r\n\r\n protected country: CountryCode;\r\n protected currency: CurrencyCode;\r\n protected locale: LocaleCode;\r\n\r\n /**\r\n * Creates an instance of BaseShoppingContainerModel.\r\n * Initializes common properties and calculates initial base totals.\r\n * @param data - The initial attributes for the shopping container.\r\n * @param date - Optional date object for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: BaseShoppingContainerAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.customerId = data.customerId;\r\n this.customerEmail = data.customerEmail;\r\n this.anonymousId = data.anonymousId;\r\n this.country = data.country;\r\n this.currency = data.currency;\r\n this.locale = data.locale;\r\n this.lineItems = (data.lineItems ?? []).map(item => new LineItemModel(item));\r\n this.billingAddress = data.billingAddress ? new AddressModel(data.billingAddress, date) : null;\r\n this.shippingAddress = data.shippingAddress ? new AddressModel(data.shippingAddress, date) : null;\r\n this.coupons = (data.coupons ?? []).map(coupon => new CouponModel(coupon));\r\n\r\n this.shippingDetails = data.shippingDetails ? Utils.deepClone(data.shippingDetails) : null;\r\n\r\n this.total = {\r\n subtotal: new PriceModel(data.total.subtotal),\r\n shipping: new PriceModel(data.total.shipping),\r\n effectiveShipping: new PriceModel(data.total.effectiveShipping),\r\n taxTotal: new PriceModel(data.total.taxTotal),\r\n couponTotal: Object.fromEntries(\r\n Object.entries(data.total.couponTotal).map(([key, value]) => [key, new PriceModel(value)])\r\n ),\r\n couponDiscountTotal: new PriceModel(data.total.couponDiscountTotal),\r\n grandTotal: new PriceModel(data.total.grandTotal),\r\n };\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for this shopping container (cart ID or order ID).\r\n * @returns The ID string.\r\n */\r\n public getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the customer ID associated with this container, if available.\r\n * @returns The customer ID string, or undefined.\r\n */\r\n public getCustomerId(): string | undefined {\r\n return this.customerId;\r\n }\r\n\r\n /**\r\n * Gets the customer email associated with this container, if available.\r\n * @returns The customer email string, or undefined.\r\n */\r\n public getCustomerEmail(): string | undefined {\r\n return this.customerEmail;\r\n }\r\n\r\n /**\r\n * Gets the anonymous user ID associated with this container, if available.\r\n * @returns The anonymous ID string, or undefined.\r\n */\r\n public getAnonymousId(): string | undefined {\r\n return this.anonymousId;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the line items in the container.\r\n * Each item is a new LineItemModel instance created from the original's details.\r\n * @returns An array of LineItemModel instances.\r\n */\r\n public getLineItems(): LineItemModel[] {\r\n // Return new instances to prevent modification of internal state\r\n return this.lineItems.map(item => new LineItemModel(item.getDetails()));\r\n }\r\n\r\n /**\r\n * Gets current number of line items in the container.\r\n * @returns The count of line items.\r\n */\r\n public getLineItemsCount(): number {\r\n return this.lineItems.length;\r\n }\r\n\r\n /**\r\n * Gets a copy of the shipping details associated with the container.\r\n * @returns A ShippingDetails object, or null if none are set.\r\n */\r\n public getShippingDetails(): ShippingDetails | null {\r\n // Return a shallow copy if details exist\r\n return this.shippingDetails ? { ...this.shippingDetails } : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the shipping address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no shipping address is set.\r\n */\r\n public getShippingAddress(): AddressModel | null {\r\n return this.shippingAddress ? new AddressModel(this.shippingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Checks if a shipping address is associated with this container.\r\n * @returns True if a shipping address is set, false otherwise.\r\n */\r\n public hasShippingAddress(): boolean {\r\n return !!this.shippingAddress;\r\n }\r\n\r\n /**\r\n * Checks if a billing address is associated with this container.\r\n * @returns True if a billing address is set, false otherwise.\r\n */\r\n public hasBillingAddress(): boolean {\r\n return !!this.billingAddress;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the billing address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no billing address is set.\r\n */\r\n public getBillingAddress(): AddressModel | null {\r\n return this.billingAddress ? new AddressModel(this.billingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the coupons applied to the container.\r\n * Each item is a new CouponModel instance created from the original's details.\r\n * @returns An array of CouponModel instances.\r\n */\r\n public getCoupons(): CouponModel[] {\r\n return this.coupons;\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this container.\r\n * @returns The CountryCode enum value.\r\n */\r\n public getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Gets the currency code associated with this container.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Gets the locale code associated with this container.\r\n * @returns The LocaleCode enum value.\r\n */\r\n public getLocale(): LocaleCode {\r\n return this.locale;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the calculated totals for the container.\r\n * @returns An object containing shipping, subtotal, coupon, and grand totals.\r\n */\r\n public getTotal() {\r\n return this.total;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the shopping container's current state.\r\n * Includes details from the base model and specific container properties.\r\n * @returns BaseShoppingContainerData object suitable for serialization or API responses.\r\n */\r\n getDetails(): BaseShoppingContainerData {\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n customerId: this.getCustomerId(),\r\n customerEmail: this.getCustomerEmail(),\r\n anonymousId: this.getAnonymousId(),\r\n lineItems: this.getLineItems().map(item => item.getDetails()),\r\n shippingDetails: this.getShippingDetails(),\r\n shippingAddress: this.getShippingAddress()?.getDetails() || null,\r\n billingAddress: this.getBillingAddress()?.getDetails() || null,\r\n coupons: this.getCoupons().map(coupon => coupon.getDetails()),\r\n total: {\r\n subtotal: this.getTotal().subtotal.getDetails(),\r\n shipping: this.getTotal().shipping.getDetails(),\r\n effectiveShipping: this.getTotal().effectiveShipping.getDetails(),\r\n taxTotal: this.getTotal().taxTotal.getDetails(),\r\n couponTotal: Object.fromEntries(Object.entries(this.getTotal().couponTotal).map(([key, value]) => [key, value.getDetails()])),\r\n couponDiscountTotal: this.getTotal().couponDiscountTotal.getDetails(),\r\n grandTotal: this.getTotal().grandTotal.getDetails(),\r\n },\r\n country: this.getCountry(),\r\n currency: this.getCurrency(),\r\n locale: this.getLocale(),\r\n }\r\n };\r\n\r\n /**\r\n * Recalculates the total costs for the shopping container.\r\n * This includes summing line items, calculating shipping, applying coupons, and computing taxes.\r\n */\r\n public calculateTotals(): void {\r\n const zero = new PriceModel({ amount: 0, currency: this.currency });\r\n const filteredLineItems = this.lineItems.filter(lineitem => lineitem.getState() !== LineItemState.CANCELLED);\r\n const subTotal = filteredLineItems.reduce((total, lineItem) => total.add(lineItem.getTotal().subtotal), zero);\r\n\r\n const shipping = new PriceModel({ amount: this.shippingDetails?.cost || 0, currency: this.currency }).round();\r\n\r\n let couponDiscountTotal = zero;\r\n let couponTotal: Record<string, PriceModel> = {};\r\n let nonShippingCouponTotal: Record<string, PriceModel> = {};\r\n this.coupons.forEach(coupon => {\r\n const couponValue = coupon.calculateApplicableCouponDiscount(subTotal, shipping, this.country, this.currency);\r\n couponDiscountTotal = couponDiscountTotal.add(couponValue);\r\n couponTotal[coupon.getCode()] = couponValue;\r\n if (coupon.getCategory() !== CouponCategory.SHIPPING) {\r\n nonShippingCouponTotal[coupon.getCode()] = couponValue;\r\n }\r\n })\r\n this.applyDiscountsInLineItem(nonShippingCouponTotal);\r\n\r\n const taxTotal = filteredLineItems.reduce((total, lineItem) => total.add(lineItem.getTotal().taxTotal), zero);\r\n const shippingCoupon = this.coupons.find(coupon => coupon.getCategory() === CouponCategory.SHIPPING);\r\n const effectiveShipping = shippingCoupon ? shipping.subtract(couponTotal[shippingCoupon.getCode()] || zero) : shipping;\r\n\r\n const grandTotal = subTotal.add(shipping).add(taxTotal).subtract(couponDiscountTotal);\r\n\r\n this.total = {\r\n subtotal: subTotal,\r\n shipping: shipping,\r\n effectiveShipping: effectiveShipping,\r\n couponTotal: couponTotal,\r\n couponDiscountTotal: couponDiscountTotal,\r\n taxTotal: taxTotal,\r\n grandTotal: grandTotal,\r\n };\r\n }\r\n\r\n /**\r\n * Updates the shipping details and recalculates the totals.\r\n * @param shippingDetails - The new shipping details to apply.\r\n */\r\n public updateShippingDetails(shippingDetails: ShippingDetails): void {\r\n this.shippingDetails = shippingDetails;\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Applies a list of coupons to the shopping container.\r\n * Filters out invalid coupons, separates shipping and non-shipping coupons,\r\n * and distributes discounts to line items.\r\n * @param applicableCoupons - The list of coupons to attempt to apply.\r\n */\r\n public applyCoupons(applicableCoupons: CouponModel[]): void {\r\n //Apply coupons\r\n const shippingCoupons = applicableCoupons.filter(coupon => coupon.getCategory() === CouponCategory.SHIPPING);\r\n const otherCoupons = applicableCoupons.filter(coupon => coupon.getCategory() !== CouponCategory.SHIPPING);\r\n\r\n this.coupons = [];\r\n this.total.couponDiscountTotal = this.total.subtotal.zero();\r\n this.total.couponTotal = {};\r\n // Apply non shipping coupons\r\n otherCoupons.length && this.applyNonShippingCoupons(otherCoupons);\r\n this.applyDiscountsInLineItem(this.total.couponTotal);\r\n\r\n // Apply shipping coupons\r\n shippingCoupons.length && this.applyShippingCoupons(shippingCoupons);\r\n\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Distributes the total discount amount among the line items.\r\n * @param couponTotal - A record of coupon codes and their calculated discount amounts.\r\n */\r\n private applyDiscountsInLineItem(couponTotal: Record<string, PriceModel>) {\r\n const couponDiscounts: [string, PriceModel][] = Array.from(Object.entries(couponTotal))\r\n .filter(couponDiscount => !couponDiscount[1].isZero());\r\n\r\n const itemDiscounts = new Map<string, { coupon: CouponModel, amount: PriceModel }[]>();\r\n this.lineItems.forEach(li => itemDiscounts.set(li.getId(), []));\r\n\r\n couponDiscounts.forEach(([code, totalDiscount]) => {\r\n const coupon = this.coupons.find(c => c.getCode() === code);\r\n if (!coupon || totalDiscount.isZero()) return;\r\n\r\n const validItems = this.lineItems\r\n .filter(li => li.getState() !== LineItemState.CANCELLED && !li.getTotal().subtotal.isZero())\r\n .sort((a, b) => a.getTotal().subtotal.compareTo(b.getTotal().subtotal));\r\n\r\n let distributed = new PriceModel({ amount: 0, currency: this.currency });\r\n\r\n validItems.forEach((item, index) => {\r\n let amount: PriceModel;\r\n if (index === validItems.length - 1) {\r\n amount = totalDiscount.subtract(distributed);\r\n } else {\r\n amount = totalDiscount.multiply(item.getTotal().subtotal).divide(this.total.subtotal).round();\r\n }\r\n distributed = distributed.add(amount);\r\n itemDiscounts.get(item.getId())?.push({ coupon, amount });\r\n });\r\n });\r\n\r\n this.lineItems.forEach(lineItem => {\r\n if (lineItem.getState() === LineItemState.CANCELLED || this.total.subtotal.isZero()) {\r\n lineItem.updateDiscounts([]);\r\n } else {\r\n lineItem.updateDiscounts(itemDiscounts.get(lineItem.getId()) || []);\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Updates the tax rules for all line items and recalculates totals.\r\n * @param taxRules - A record of tax rules keyed by tax category.\r\n */\r\n public updateTax(taxRules: Record<TaxCategory, TaxRuleModel>): void {\r\n this.lineItems.forEach(lineItem => {\r\n lineItem.updateTax(taxRules[lineItem.getPricing().taxCategory]);\r\n });\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Selects and applies the best applicable non-shipping coupon.\r\n * Currently supports applying only a single coupon of type COUPON.\r\n * @param applicableCoupons - List of available non-shipping coupons.\r\n */\r\n private applyNonShippingCoupons(applicableCoupons: CouponModel[]) {\r\n const coupons = applicableCoupons.filter(coupon => coupon.getType() === CouponType.COUPON);\r\n if (coupons.length === 1) {\r\n const couponValue = coupons[0].calculateApplicableCouponDiscount(this.total.subtotal, this.total.shipping, this.country, this.currency);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(coupons[0]);\r\n this.total.couponTotal[coupons[0].getCode()] = couponValue;\r\n this.total.couponDiscountTotal = couponValue;\r\n }\r\n }\r\n // Todo: Add support to other type in future like promotion\r\n }\r\n\r\n /**\r\n * Selects and applies the best applicable shipping coupon.\r\n * @param applicableCoupons - List of available shipping coupons.\r\n */\r\n private applyShippingCoupons(applicableCoupons: CouponModel[]) {\r\n if (this.total.shipping.getAmount() > 0 && applicableCoupons.length > 0) {\r\n const subTotalWithCouponDiscount = this.total.subtotal.subtract(this.total.couponDiscountTotal);\r\n\r\n const maxValuedCoupon = applicableCoupons.reduce((maxCoupon, currentCoupon) => {\r\n if (!maxCoupon) return currentCoupon;\r\n\r\n const currentCouponValue = currentCoupon.calculateApplicableCouponDiscount(subTotalWithCouponDiscount, this.total.shipping, this.country, this.currency).min(this.total.shipping);\r\n const maxCouponValue = maxCoupon.calculateApplicableCouponDiscount(subTotalWithCouponDiscount, this.total.shipping, this.country, this.currency).min(this.total.shipping);\r\n\r\n if (currentCouponValue === maxCouponValue) {\r\n return currentCoupon.getType() === 'coupon' ? currentCoupon : maxCoupon;\r\n }\r\n return currentCouponValue.compareTo(maxCouponValue) > 0 ? currentCoupon : maxCoupon;\r\n });\r\n\r\n const couponValue = maxValuedCoupon.calculateApplicableCouponDiscount(subTotalWithCouponDiscount, this.total.shipping, this.country, this.currency).min(this.total.shipping);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(maxValuedCoupon);\r\n this.total.couponTotal[maxValuedCoupon.getCode()] = couponValue;\r\n this.total.couponDiscountTotal = this.total.couponDiscountTotal.add(couponValue);\r\n this.total.effectiveShipping = this.total.shipping.subtract(couponValue);\r\n }\r\n }\r\n }\r\n}\r\n\r\n\r\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {i,h}from'./chunk-72DR3HF2.mjs';import {q,r,s,t}from'./chunk-JHELVQYY.mjs';var d=class t$1{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new q("Amount cannot be negative.");if(!e.currency)throw new r("Currency code is required.");this.amount=e.amount,this.currency=e.currency;}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(e){if(t$1.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot compare prices in different currencies.")}else throw new t("Must be a PriceModel instance.");return this.amount-e.getAmount()}add(e){if(t$1.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot add prices in different currencies.")}else throw new t("Must be a PriceModel instance.");return new t$1({amount:this.amount+e.getAmount(),currency:this.currency})}subtract(e){if(t$1.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot subtract prices in different currencies.")}else throw new t("Must be a PriceModel instance.");return new t$1({amount:this.amount-e.getAmount(),currency:this.currency})}multiply(e){if(t$1.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot multiply prices in different currencies.");return new t$1({amount:this.amount*e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new t$1({amount:this.amount*e,currency:this.currency});throw new t("Must be a non-negative number.")}divide(e){if(t$1.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot divide prices in different currencies.");return new t$1({amount:this.amount/e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>0)return new t$1({amount:this.amount/e,currency:this.currency});throw new t("Must be a positive number.")}min(...e){if(e.length===0)throw new t("Must provide at least one PriceModel.");return e.reduce((r,n)=>{if(t$1.isPriceModel(n)){if(r.getCurrency()!==n.getCurrency())throw new s("Cannot compare prices in different currencies.")}else throw new t("Must be a PriceModel instance.");return r.compareTo(n)<0?r:n})}max(...e){if(e.length===0)throw new t("Must provide at least one PriceModel.");return e.reduce((r,n)=>{if(t$1.isPriceModel(n)){if(r.getCurrency()!==n.getCurrency())throw new s("Cannot compare prices in different currencies.")}else throw new t("Must be a PriceModel instance.");return r.compareTo(n)>0?r:n})}zero(){return new t$1({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new t$1({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return t$1.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return t$1.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,r$1,n={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let c=i[r$1];if(!r$1||!c)throw new r("Invalid currency code for formatting.");let o=e,
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {i,h}from'./chunk-72DR3HF2.mjs';import {q,r,s,t}from'./chunk-JHELVQYY.mjs';var d=class t$1{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new q("Amount cannot be negative.");if(!e.currency)throw new r("Currency code is required.");this.amount=e.amount,this.currency=e.currency;}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(e){if(t$1.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot compare prices in different currencies.")}else throw new t("Must be a PriceModel instance.");return this.amount-e.getAmount()}add(e){if(t$1.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot add prices in different currencies.")}else throw new t("Must be a PriceModel instance.");return new t$1({amount:this.amount+e.getAmount(),currency:this.currency})}subtract(e){if(t$1.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot subtract prices in different currencies.")}else throw new t("Must be a PriceModel instance.");return new t$1({amount:this.amount-e.getAmount(),currency:this.currency})}multiply(e){if(t$1.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot multiply prices in different currencies.");return new t$1({amount:this.amount*e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new t$1({amount:this.amount*e,currency:this.currency});throw new t("Must be a non-negative number.")}divide(e){if(t$1.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot divide prices in different currencies.");return new t$1({amount:this.amount/e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>0)return new t$1({amount:this.amount/e,currency:this.currency});throw new t("Must be a positive number.")}min(...e){if(e.length===0)throw new t("Must provide at least one PriceModel.");return e.reduce((r,n)=>{if(t$1.isPriceModel(n)){if(r.getCurrency()!==n.getCurrency())throw new s("Cannot compare prices in different currencies.")}else throw new t("Must be a PriceModel instance.");return r.compareTo(n)<0?r:n},this)}max(...e){if(e.length===0)throw new t("Must provide at least one PriceModel.");return e.reduce((r,n)=>{if(t$1.isPriceModel(n)){if(r.getCurrency()!==n.getCurrency())throw new s("Cannot compare prices in different currencies.")}else throw new t("Must be a PriceModel instance.");return r.compareTo(n)>0?r:n},this)}zero(){return new t$1({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new t$1({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return t$1.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return t$1.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,r$1,n={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let c=i[r$1];if(!r$1||!c)throw new r("Invalid currency code for formatting.");let o=e,a=n.displayAsInteger?0:t$1.getDecimalPlaces(r$1),h$1={style:n.style??"currency",currency:r$1,signDisplay:"never",currencyDisplay:n.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};n.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(c,h$1).format(o)}catch(g){return console.error(`Error formatting price for currency "${r$1}" and locale "${c}":`,g),`${h[r$1]??r$1} ${t$1.addThousandSeparators(o.toFixed(a))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static addThousandSeparators(e){let r=e.split("."),n=r[0],c=r.length>1?"."+r[1]:"";return n.replace(/\B(?=(\d{3})+(?!\d))/g,",")+c}static getRoundedAmount(e,r$1){if(e<0)throw new q("Amount cannot be negative for rounding.");if(r$1===void 0)throw new r("Invalid currency code for rounding.");let n=t$1.getDecimalPlaces(r$1),c=Math.pow(10,n);return Math.round(e*c)/c}};export{d as a};//# sourceMappingURL=chunk-EV4HUBJL.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-EV4HUBJL.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/Classes/Price.ts"],"names":["PriceModel","_PriceModel","#kind","data","InvalidPriceAmountError","InvalidCurrencyCodeError","obj","priceModel","CurrencyMismatchError","InvalidArgumentError","factor","divisor","priceModels","minPrice","currentPrice","maxPrice","amount","currency","options","locale","CurrencyLocaleMap","valueToFormat","fractionDigits","formattingOptions","error","CurrencySymbolMap","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier"],"mappings":"kFAgBA,IAAqBA,EAArB,MAAqBC,GAAW,CAC9BC,EAAAA,CACU,OACA,QAQV,CAAA,WAAA,CAAYC,CAAuB,CAAA,CAEjC,GADA,IAAKD,CAAAA,EAAAA,CAAQ,aACTC,CAAK,CAAA,MAAA,CAAS,EAChB,MAAM,IAAIC,CAAwB,CAAA,4BAA4B,EAGhE,GAAI,CAACD,CAAK,CAAA,QAAA,CACR,MAAM,IAAIE,CAAAA,CAAyB,4BAA4B,CAAA,CAGjE,KAAK,MAASF,CAAAA,CAAAA,CAAK,OACnB,IAAK,CAAA,QAAA,CAAWA,EAAK,SACvB,CAEA,IAAI,IAAA,EAAO,CACT,OAAO,IAAA,CAAKD,EACd,CAEA,OAAO,YAAaI,CAAAA,CAAAA,CAAiC,CACnD,OAAO,OAAOA,CAAQ,EAAA,QAAA,EACtBA,IAAQ,IACPA,EAAAA,CAAAA,CAAY,OAAS,YACxB,CAMO,WAA4B,EAAA,CACjC,OAAO,IAAK,CAAA,QACd,CAKO,SAAoB,EAAA,CACzB,OAAO,IAAK,CAAA,MACd,CAMO,UAAA,EAAwB,CAC7B,OAAO,CACL,OAAQ,IAAK,CAAA,MAAA,CACb,SAAU,IAAK,CAAA,QACjB,CACF,CAoCO,UAAUC,CAAgC,CAAA,CAC/C,GAAKN,GAAAA,CAAW,aAAaM,CAAU,CAAA,CAAA,CAEhC,GAAI,IAAA,CAAK,WAAaA,CAAW,CAAA,WAAA,GACtC,MAAM,IAAIC,EAAsB,gDAAgD,CAAA,CAAA,KAF1E,MAAA,IAAIC,EAAqB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A,CAAM,CAAA,CAAC,EAAI,EAGxD,CAAA,OADyBC,EAAY,OAAQ,CAAA,uBAAA,CAAyB,GAAG,CAC/CC,CAAAA,CAC5B,CAWA,OAAO,iBAAiBb,CAAgBC,CAAAA,GAAAA,CAAgC,CACtE,GAAID,EAAS,CACX,CAAA,MAAM,IAAIZ,CAAAA,CAAwB,yCAAyC,CAG7E,CAAA,GAAIa,MAAa,KACf,CAAA,CAAA,MAAM,IAAIZ,CAAyB,CAAA,qCAAqC,CAG1E,CAAA,IAAMyB,EAAgB7B,GAAW,CAAA,gBAAA,CAAiBgB,GAAQ,CACpDc,CAAAA,CAAAA,CAAa,KAAK,GAAI,CAAA,EAAA,CAAID,CAAa,CAAA,CAG7C,OAFqB,IAAK,CAAA,KAAA,CAAMd,EAASe,CAAU,CAAA,CAAIA,CAGzD,CACF","file":"chunk-EV4HUBJL.mjs","sourcesContent":["import { CurrencyCode } from \"./Common\";\r\nimport { CurrencyLocaleMap, CurrencySymbolMap, OperationalCountryCurrency } from \"./Enum\";\r\nimport {\r\n InvalidPriceAmountError,\r\n InvalidCurrencyCodeError,\r\n CurrencyMismatchError,\r\n InvalidArgumentError\r\n} from \"./Error\";\r\n\r\nexport type PriceAttributes = {\r\n amount: number;\r\n currency: CurrencyCode;\r\n}\r\n\r\nexport type PriceData = PriceAttributes;\r\n\r\nexport default class PriceModel {\r\n #kind: string;\r\n protected amount: number;\r\n protected currency: CurrencyCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param amount - The initial price value.\r\n * @param currency - The currency code used for rounding and determining the currency symbol.\r\n * @throws {Error} If price is negative or country/currency mapping is missing.\r\n */\r\n constructor(data: PriceAttributes) {\r\n this.#kind = \"PriceModel\";\r\n if (data.amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative.\");\r\n }\r\n\r\n if (!data.currency) {\r\n throw new InvalidCurrencyCodeError(\"Currency code is required.\");\r\n }\r\n\r\n this.amount = data.amount;\r\n this.currency = data.currency;\r\n }\r\n\r\n get kind() {\r\n return this.#kind;\r\n }\r\n\r\n static isPriceModel(obj: unknown): obj is PriceModel {\r\n return typeof obj === \"object\" &&\r\n obj !== null &&\r\n (obj as any).kind === \"PriceModel\";\r\n }\r\n\r\n /**\r\n * Gets the currency associated with this price instance.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Returns the raw numeric price value.\r\n */\r\n public getAmount(): number {\r\n return this.amount;\r\n }\r\n\r\n /**\r\n *\r\n * @returns PriceData\r\n */\r\n public getDetails(): PriceData {\r\n return {\r\n amount: this.amount,\r\n currency: this.currency\r\n }\r\n }\r\n\r\n /**\r\n * Compares this price with another {@link PriceModel} instance.\r\n *\r\n * The comparison is performed using the numeric price value and is only valid\r\n * when both prices are expressed in the same currency.\r\n *\r\n * ### Comparison result:\r\n * - Returns a **negative number** if this price is **less than** `priceModel`\r\n * - Returns **zero** if both prices are **equal**\r\n * - Returns a **positive number** if this price is **greater than** `priceModel`\r\n *\r\n * @param priceModel - The {@link PriceModel} instance to compare against.\r\n *\r\n * @returns\r\n * A signed number representing the comparison result:\r\n * - `< 0` → this price is lower\r\n * - `0` → prices are equal\r\n * - `> 0` → this price is higher\r\n *\r\n * @throws {Error}\r\n * Throws an error if:\r\n * - `priceModel` is not an instance of {@link PriceModel}\r\n * - The currencies of the two prices do not match\r\n *\r\n * @example\r\n * ```ts\r\n * const a = new PriceModel(\"USD\", 100);\r\n * const b = new PriceModel(\"USD\", 150);\r\n *\r\n * a.compareTo(b); // -50\r\n * b.compareTo(a); // 50\r\n * a.compareTo(a); // 0\r\n * ```\r\n */\r\n public compareTo(priceModel: PriceModel): number {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return this.amount - priceModel.getAmount();\r\n }\r\n\r\n public add(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot add prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.amount + priceModel.getAmount(),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public subtract(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot subtract prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.amount - priceModel.getAmount(),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public multiply(factor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(factor)) {\r\n if (this.currency !== factor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot multiply prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.amount * factor.getAmount(),\r\n currency: this.currency\r\n });\r\n } else if (typeof factor === \"number\" && factor >= 0) {\r\n return new PriceModel({\r\n amount: this.amount * factor,\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a non-negative number.\");\r\n }\r\n\r\n public divide(divisor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(divisor)) {\r\n if (this.currency !== divisor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot divide prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.amount / divisor.getAmount(),\r\n currency: this.currency\r\n });\r\n } else if (typeof divisor === \"number\" && divisor > 0) {\r\n return new PriceModel({\r\n amount: this.amount / divisor,\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a positive number.\");\r\n }\r\n\r\n public min(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((minPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (minPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return minPrice.compareTo(currentPrice) < 0 ? minPrice : currentPrice;\r\n }, this);\r\n }\r\n\r\n public max(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((maxPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (maxPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return maxPrice.compareTo(currentPrice) > 0 ? maxPrice : currentPrice;\r\n }, this);\r\n }\r\n\r\n /**\r\n * Gets a zero value PriceModel for the same currency.\r\n * @returns A PriceModel instance representing zero in the same currency.\r\n */\r\n public zero(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: 0\r\n });\r\n }\r\n\r\n /**\r\n * Checks if the price is zero.\r\n * @returns True if the price is zero, false otherwise.\r\n */\r\n public isZero(): boolean {\r\n return this.amount === 0;\r\n }\r\n\r\n\r\n public round(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: this.getRoundedAmount()\r\n });\r\n }\r\n /**\r\n * Gets the rounded price value based on standard currency rules.\r\n * @returns The numeric price, rounded according to its currency's typical decimal places.\r\n */\r\n public getRoundedAmount(): number {\r\n return PriceModel.getRoundedAmount(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price stored in this instance.\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n public getFormattedString() {\r\n return PriceModel.getFormattedString(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n toString() {\r\n return this.getFormattedString();\r\n }\r\n\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the amount.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param amount - The initial amount value.\r\n * @param currency - The currency code for formatting.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the amount rounded to the next nearest integer (no decimals). Defaults to false.\r\n * @param options.style - The style of formatting, either 'currency' or 'decimal'. Defaults to 'currency'.\r\n * @param options.currencyDisplay - The display format for the currency symbol. Options are 'symbol', 'narrowSymbol', 'code', or 'name'. Defaults to 'symbol'.\r\n * @returns The formatted price string according to locale rules.\r\n * @throws {Error} If currency code is invalid.\r\n */\r\n static getFormattedString(amount: number, currency: CurrencyCode, options: {\r\n displayAsInteger?: boolean,\r\n style?: 'currency' | 'decimal',\r\n currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name'\r\n } = {\r\n displayAsInteger: false,\r\n style: 'currency',\r\n currencyDisplay: 'symbol'\r\n }): string {\r\n\r\n const locale = CurrencyLocaleMap[currency];\r\n if (!currency || !locale) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for formatting.');\r\n }\r\n\r\n let valueToFormat = amount;\r\n const fractionDigits = options.displayAsInteger ? 0 : PriceModel.getDecimalPlaces(currency);\r\n\r\n let formattingOptions: Intl.NumberFormatOptions = {\r\n style: options.style ?? 'currency',\r\n currency: currency,\r\n signDisplay: 'never',\r\n currencyDisplay: options.currencyDisplay,\r\n minimumFractionDigits: fractionDigits,\r\n maximumFractionDigits: fractionDigits,\r\n };\r\n\r\n if (options.displayAsInteger) {\r\n valueToFormat = Math.ceil(valueToFormat);\r\n }\r\n\r\n try {\r\n return new Intl.NumberFormat(locale, formattingOptions).format(valueToFormat);\r\n } catch (error) {\r\n console.error(`Error formatting price for currency \"${currency}\" and locale \"${locale}\":`, error);\r\n // Basic fallback without symbol if Intl fails completely\r\n return `${CurrencySymbolMap[currency] ?? currency} ${PriceModel.addThousandSeparators(valueToFormat.toFixed(fractionDigits))}`;\r\n }\r\n }\r\n\r\n /**\r\n * Helper method to determine standard decimal places for a currency.\r\n * @param currency - The currency code.\r\n * @returns The number of decimal places (0, 2, or 3 based on common rules).\r\n */\r\n private static getDecimalPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case OperationalCountryCurrency.INR:\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n /**\r\n * Adds basic thousand separators (commas) to a number string.\r\n * Does not handle different locale separators (e.g., periods, spaces).\r\n * @param numStr - The number string (potentially with decimals).\r\n * @returns The number string with commas added.\r\n */\r\n private static addThousandSeparators(numStr: string): string {\r\n const parts = numStr.split('.');\r\n const integerPart = parts[0];\r\n const decimalPart = parts.length > 1 ? '.' + parts[1] : '';\r\n\r\n const formattedInteger = integerPart.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\r\n return formattedInteger + decimalPart;\r\n }\r\n\r\n /**\r\n * Rounds a price value according to the standard decimal places\r\n * for the currency associated with the given country.\r\n *\r\n * @param price - The price value to round. Must be a non-negative number.\r\n * @param currency - The currency code to determine the rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the price is negative or currency is invalid.\r\n */\r\n static getRoundedAmount(amount: number, currency: CurrencyCode): number {\r\n if (amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative for rounding.\");\r\n }\r\n\r\n if (currency === undefined) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for rounding.');\r\n }\r\n\r\n const decimalPlaces = PriceModel.getDecimalPlaces(currency);\r\n const multiplier = Math.pow(10, decimalPlaces);\r\n const roundedValue = Math.round(amount * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n}"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a}from'./chunk-LEHPVA3Q.mjs';import {a as a$1}from'./chunk-EV4HUBJL.mjs';import {e}from'./chunk-72DR3HF2.mjs';import {t}from'./chunk-JHELVQYY.mjs';import {b as b$1}from'./chunk-6KCJVEZD.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$1=new Date){if(super(e,t$1),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$1.toISOString(),this.validTo=e.validTo&&Date.parse(e.validTo)?new Date(e.validTo).toISOString():t$1.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 t("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-GF427QWC.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-GF427QWC.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,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,IAAO,CAAA,MAAA,CACPA,EAAA,UAAa,CAAA,YAAA,CAFHA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAKAC,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,QAAW,CAAA,UAAA,CACXA,EAAA,QAAW,CAAA,UAAA,CAFDA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAKAC,OACVA,CAAA,CAAA,GAAA,CAAM,KACNA,CAAAA,CAAAA,CAAA,IAAM,KAFIA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EA0BSC,CAAAA,CAAAA,CAAAA,CAArB,cAAyCC,GAAU,CACvC,UAAA,CACA,KACA,WACA,CAAA,IAAA,CACA,UACA,CAAA,SAAA,CACA,QACA,YAGA,CAAA,eAAA,CAGA,cACA,CAAA,eAAA,CACA,aACA,QAOV,CAAA,WAAA,CAAYC,CAAuBC,CAAAA,GAAAA,CAAa,IAAI,IAAA,CAAQ,CA0B1D,GAzBA,MAAMD,CAAMC,CAAAA,GAAI,CAEhB,CAAA,IAAA,CAAK,WAAaD,CAAK,CAAA,UAAA,CACvB,IAAK,CAAA,IAAA,CAAOE,EAAM,SAAUF,CAAAA,CAAAA,CAAK,IAAI,CAAA,CACr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AAA,QAAA,CAAS,IAAK,CAAA,kBAAA,EAAuB,CAAA,GAAG,CAAE,CAAA,KAAA,GAC1E,MACF,QAEE,OAAON,CACX,CAKA,OAFsBC,CAAAA,CAAkB,GAAIE,CAAAA,CAAkB,CAGhE,CACF","file":"chunk-WS7ZY5ZZ.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 // Ensure minCartValueReq exists and subtotal meets the requirement\r\n if (!minCartValueReq || minCartValueReq.compareTo(cartValue) > 0) {\r\n return zeroDiscount;\r\n }\r\n\r\n // Ensure maxCartDiscountCap exists and is non-negative (price-model throws error when amount < 0)\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}"]}
|
|
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,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AAA,CAAAA,CAAwBC,CAAuB,CAAA,CAAA,CAAA,CAAkB,CAC/K,IAAIC,CAAAA,CAA2B,IAAIV,GAAAA,CAAW,CAAE,MAAQ,CAAA,CAAA,CAAG,QAAAQ,CAAAA,CAAS,CAAC,CAAA,CACjEG,CAGJ,CAAA,GAAIF,GAAe,CAAC,IAAA,CAAK,QAAS,EAAA,CAChC,OAAOC,CAIT,CAAA,IAAME,CAAkB,CAAA,IAAA,CAAK,gBAAgBd,CAAO,CAAA,CAC9Ce,CAAqB,CAAA,IAAA,CAAK,kBAAmBf,CAAAA,CAAO,CAQ1D,CAAA,GALI,CAACc,CAAmBA,EAAAA,CAAAA,CAAgB,SAAUN,CAAAA,CAAS,EAAI,CAK3D,EAAA,CAACO,CACH,CAAA,OAAOH,EAIT,IAAMI,CAAAA,CAAiB,IAAK,CAAA,WAAA,EACtBC,CAAAA,CAAAA,CAAiB,IAAK,CAAA,iBAAA,GAEtBC,CAAcF,CAAAA,CAAAA,GAAmB,UAA0BP,CAAAA,CAAAA,CAAeD,EAGhF,GAAIU,CAAAA,CAAY,SAAU,EAAA,EAAK,EAAG,OAAON,CAAAA,CAEzC,OAAQK,CAAAA,EACN,IAAK,MAEH,CAAA,IAAME,EAAaJ,CACnBF,CAAAA,CAAAA,CAAoBK,CAAY,CAAA,GAAA,CAAIC,CAAU,CAC9C,CAAA,MACF,IAAK,YAAA,CAEHN,EAAoBK,CAAY,CAAA,QAAA,CAAS,IAAK,CAAA,kBAAA,EAAuB,CAAA,GAAG,CAAE,CAAA,KAAA,GAC1E,MACF,QAEE,OAAON,CACX,CAKA,OAFsBC,CAAAA,CAAkB,GAAIE,CAAAA,CAAkB,CAGhE,CACF","file":"chunk-GF427QWC.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}"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-43SMYXYL.mjs';import {e}from'./chunk-72DR3HF2.mjs';import {b as b$2}from'./chunk-WSUPVXRZ.mjs';import {g,d}from'./chunk-JHELVQYY.mjs';import {b as b$1}from'./chunk-6KCJVEZD.mjs';import K from'crypto';var y=new Uint8Array(256),h=y.length;function I(){return h>y.length-16&&(K.randomFillSync(y),h=0),y.slice(h,h+=16)}var z=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function $(t){return typeof t=="string"&&z.test(t)}var U=$;var n=[];for(let t=0;t<256;++t)n.push((t+256).toString(16).slice(1));function b(t,e=0){return n[t[e+0]]+n[t[e+1]]+n[t[e+2]]+n[t[e+3]]+"-"+n[t[e+4]]+n[t[e+5]]+"-"+n[t[e+6]]+n[t[e+7]]+"-"+n[t[e+8]]+n[t[e+9]]+"-"+n[t[e+10]]+n[t[e+11]]+n[t[e+12]]+n[t[e+13]]+n[t[e+14]]+n[t[e+15]]}function k(t){if(!U(t))throw TypeError("Invalid UUID");let e,i=new Uint8Array(16);return i[0]=(e=parseInt(t.slice(0,8),16))>>>24,i[1]=e>>>16&255,i[2]=e>>>8&255,i[3]=e&255,i[4]=(e=parseInt(t.slice(9,13),16))>>>8,i[5]=e&255,i[6]=(e=parseInt(t.slice(14,18),16))>>>8,i[7]=e&255,i[8]=(e=parseInt(t.slice(19,23),16))>>>8,i[9]=e&255,i[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,i[11]=e/4294967296&255,i[12]=e>>>24&255,i[13]=e>>>16&255,i[14]=e>>>8&255,i[15]=e&255,i}var M=k;function V(t){t=unescape(encodeURIComponent(t));let e=[];for(let i=0;i<t.length;++i)e.push(t.charCodeAt(i));return e}var G="6ba7b810-9dad-11d1-80b4-00c04fd430c8",B="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function x(t,e,i){function r(o,s,u,S){var A;if(typeof o=="string"&&(o=V(o)),typeof s=="string"&&(s=M(s)),((A=s)===null||A===void 0?void 0:A.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let g=new Uint8Array(16+o.length);if(g.set(s),g.set(o,s.length),g=i(g),g[6]=g[6]&15|e,g[8]=g[8]&63|128,u){S=S||0;for(let m=0;m<16;++m)u[S+m]=g[m];return u}return b(g)}try{r.name=t;}catch{}return r.DNS=G,r.URL=B,r}var L={randomUUID:K.randomUUID};function j(t,e,i){if(L.randomUUID&&!e&&!t)return L.randomUUID();t=t||{};let r=t.random||(t.rng||I)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){i=i||0;for(let o=0;o<16;++o)e[i+o]=r[o];return e}return b(r)}var D=j;function Z(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),K.createHash("sha1").update(t).digest()}var R=Z;var q=x("v5",80,R),P=q;var O={isUUID:t=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t),isEmail:t=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t),isURL:t=>/^(http|https):\/\/[^ "]+$/.test(t),generateUUID:(t,e)=>e&&t?P(t,e):D(),generateSearchId:(t,e)=>`${t}#${f.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:t=>{let[e,i]=t.split("#");return {key:e,selectionAttributes:f.parseSelectionAttributesKey(i)}},deepClone(t){return structuredClone(t)}},a=O;var f=class t extends b$1{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new g("Selection attributes must be an object");return Object.keys(e).filter(r=>e[r]!==void 0&&r.toLowerCase()!=="size").sort().map(r=>e[r].name?`${r}:c+${e[r].name}`:`${r}:${e[r]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let i={},r=e.split("|");for(let o of r){let[s,u]=o.split(":");u.startsWith("c+")?i[s]={name:u.slice(2)}:i[s]=u;}return i}catch(i){throw new g(i?.message)}}constructor(e,i=new Date){super(e,i),this.id=e.id,this.key=e.key,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((o,s)=>(e.pricing[s]&&(o[s]=new a$1(e.pricing[s])),o),{}),this.targetGender=e.targetGender,this.attributes=a.deepClone(e.attributes),this.specifications=a.deepClone(e.specifications),this.categories=a.deepClone(e.categories);let r=new Set;this.variants=(e.variants||[]).map(o=>{if(!o.selectionAttributes||typeof o.selectionAttributes!="object")throw new g("Selection attributes are required");this.checkSelectionAttributes(o.selectionAttributes);let s=t.generateSelectionAttributesKey(o.selectionAttributes);if(r.has(s))throw new d(s);return r.add(s),{sku:o.sku,selectionAttributes:o.selectionAttributes,images:{primary:new b$2(o.images.primary),gallery:(o.images.gallery||[]).map(u=>new b$2(u))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?a.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e$1){return e$1?this.name[e$1]??this.name[e[e$1]]??this.name.en:a.deepClone(this.name)}getDescription(e$1){return e$1?this.description[e$1]??this.description[e[e$1]]??this.description.en:a.deepClone(this.description)}getSlug(e$1){return e$1?this.slug[e$1]??this.slug[e[e$1]]??this.slug.en:a.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:this.pricing}getAttributes(){return a.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:e.selectionAttributes,images:{primary:e.images.primary,gallery:e.images.gallery}}))}getImagesBySelectionAttributes(e){let i=t.generateSelectionAttributesKey(e),r=this.variants.find(o=>t.generateSelectionAttributesKey(o.selectionAttributes)===i);return r?r.images:null}getImages(e,i){switch(i){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return a.deepClone(this.categories)}getSpecifications(e$1){return e$1?a.deepClone(this.specifications[e$1]??this.specifications[e[e$1]]??this.specifications.en):a.deepClone(this.specifications)}getSearchTags(e$1){return e$1?a.deepClone(this.searchTags[e$1]??this.searchTags[e[e$1]]??this.searchTags.en):a.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((i,r)=>(this.pricing[r]&&(i[r]=this.pricing[r]?.getDetails()),i),{}),attributes:this.getAttributes(),variants:this.variants.map(i=>({sku:i.sku,selectionAttributes:a.deepClone(i.selectionAttributes),images:{primary:i.images.primary.getDetails(),gallery:i.images.gallery.map(r=>r.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new g("Selection attributes are required");Object.keys(this.attributes).forEach(i=>{if(i.toLowerCase()==="size")return;let r=this.attributes[i],o=e[i];if(o===void 0)throw new g(`Selection attribute '${i}' is missing`);if(typeof r=="string"){if(typeof o!="string"||r!==o)throw new g(`Selection attribute '${i}' is invalid`)}else if(Array.isArray(r)){if(r.length>0&&typeof r[0]=="string"){if(typeof o!="string"||!r.includes(o))throw new g(`Selection attribute '${i}' is invalid`)}else if(typeof o!="object"||!("name"in o)||r.findIndex(s=>s.name===o.name)<0)throw new g(`Selection attribute '${i}' is invalid`)}});}validateSelectionAttribute(e){let i=t.generateSelectionAttributesKey(e);return this.variants.some(r=>t.generateSelectionAttributesKey(r.selectionAttributes)===i)}validateSize(e){return this.attributes.size.includes(e)}};export{a,f as b};//# sourceMappingURL=chunk-LEHPVA3Q.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-LEHPVA3Q.mjs.map
|