b23-lib 3.1.1 → 3.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Classes/Cart.js +1 -1
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Charge.d.mts +2 -2
- package/dist/Classes/Charge.d.ts +2 -2
- package/dist/Classes/Charge.js +1 -1
- package/dist/Classes/Charge.js.map +1 -1
- package/dist/Classes/Charge.mjs +1 -1
- package/dist/Classes/Order.js +1 -1
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/ShoppingContainer.js +1 -1
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/chunk-3E2NHQJJ.mjs +2 -0
- package/dist/chunk-3E2NHQJJ.mjs.map +1 -0
- package/dist/{chunk-HJI3OWBL.mjs → chunk-D6USZIYC.mjs} +2 -2
- package/dist/{chunk-HJI3OWBL.mjs.map → chunk-D6USZIYC.mjs.map} +1 -1
- package/package.json +1 -1
- package/dist/chunk-SMIP43M4.mjs +0 -2
- package/dist/chunk-SMIP43M4.mjs.map +0 -1
package/dist/Classes/Cart.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var wt=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var wt__default=/*#__PURE__*/_interopDefault(wt);var q=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}},W=class extends Error{constructor(t){super(`Invalid line item state: ${t}`),this.name="InvalidLineItemStateError";}},_=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},tt=class extends Error{constructor(t){super(`Duplicate selection attribute found: ${t}`),this.name="DuplicateSelectionAttributeError";}},et=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},it=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},D=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},rt=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},nt=class extends Error{constructor(t="Pricing details not available for the product"){super(`NotFound: ${t}`),this.name="PricingNotFoundError";}},F=class extends Error{constructor(t="Tax rule category mismatch."){super(`InvalidTaxRule: ${t}`),this.name="InvalidTaxRuleError";}},ot=class extends Error{constructor(t="Tax category is not valid."){super(`InvalidTaxCategory: ${t}`),this.name="InvalidTaxCategoryError";}},st=class extends Error{constructor(t="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${t}`),this.name="InvalidMinQuantityError";}},at=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},ct=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},lt=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var Q=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},z=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},L=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},A=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},H=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}},Z=class extends Error{constructor(t="Invalid charge data."){super(`InvalidCharge: ${t}`),this.name="InvalidChargeError";}},Y=class extends Error{constructor(t="Invalid charge tax rule."){super(`InvalidChargeTaxRule: ${t}`),this.name="InvalidChargeTaxRuleError";}};var dt=new Uint8Array(256),ut=dt.length;function ht(){return ut>dt.length-16&&(wt__default.default.randomFillSync(dt),ut=0),dt.slice(ut,ut+=16)}var ft=/^(?:[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 Lt(n){return typeof n=="string"&&ft.test(n)}var It=Lt;var f=[];for(let n=0;n<256;++n)f.push((n+256).toString(16).slice(1));function gt(n,t=0){return f[n[t+0]]+f[n[t+1]]+f[n[t+2]]+f[n[t+3]]+"-"+f[n[t+4]]+f[n[t+5]]+"-"+f[n[t+6]]+f[n[t+7]]+"-"+f[n[t+8]]+f[n[t+9]]+"-"+f[n[t+10]]+f[n[t+11]]+f[n[t+12]]+f[n[t+13]]+f[n[t+14]]+f[n[t+15]]}function vt(n){if(!It(n))throw TypeError("Invalid UUID");let t,e=new Uint8Array(16);return e[0]=(t=parseInt(n.slice(0,8),16))>>>24,e[1]=t>>>16&255,e[2]=t>>>8&255,e[3]=t&255,e[4]=(t=parseInt(n.slice(9,13),16))>>>8,e[5]=t&255,e[6]=(t=parseInt(n.slice(14,18),16))>>>8,e[7]=t&255,e[8]=(t=parseInt(n.slice(19,23),16))>>>8,e[9]=t&255,e[10]=(t=parseInt(n.slice(24,36),16))/1099511627776&255,e[11]=t/4294967296&255,e[12]=t>>>24&255,e[13]=t>>>16&255,e[14]=t>>>8&255,e[15]=t&255,e}var At=vt;function Et(n){n=unescape(encodeURIComponent(n));let t=[];for(let e=0;e<n.length;++e)t.push(n.charCodeAt(e));return t}var Bt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Rt="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function yt(n,t,e){function i(r,o,a,d){var g;if(typeof r=="string"&&(r=Et(r)),typeof o=="string"&&(o=At(o)),((g=o)===null||g===void 0?void 0:g.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+r.length);if(c.set(o),c.set(r,o.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,a){d=d||0;for(let u=0;u<16;++u)a[d+u]=c[u];return a}return gt(c)}try{i.name=n;}catch{}return i.DNS=Bt,i.URL=Rt,i}var bt={randomUUID:wt__default.default.randomUUID};function kt(n,t,e){if(bt.randomUUID&&!t&&!n)return bt.randomUUID();n=n||{};let i=n.random||(n.rng||ht)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){e=e||0;for(let r=0;r<16;++r)t[e+r]=i[r];return t}return gt(i)}var Ct=kt;function Ut(n){return Array.isArray(n)?n=Buffer.from(n):typeof n=="string"&&(n=Buffer.from(n,"utf8")),wt__default.default.createHash("sha1").update(n).digest()}var St=Ut;var Ft=yt("v5",80,St),xt=Ft;var zt={isUUID:n=>/^[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(n),isEmail:n=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(n),isURL:n=>/^(http|https):\/\/[^ "]+$/.test(n),generateUUID:(n,t)=>t&&n?xt(n,t):Ct(),generateSearchId:(n,t)=>`${n}#${E.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:n=>{let[t,e]=n.split("#");return {key:t,selectionAttributes:E.parseSelectionAttributesKey(e)}},deepClone(n){return structuredClone(n)}},m=zt;var Pt=n=>structuredClone(n),B=class{customFields;constructor(t,e=new Date){this.customFields={...t.customFields};}getCustomField(t){let e=this.customFields[t];return e==null?e:Pt(e)}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return Pt(this.customFields)}},M=class extends B{version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){super(t),this.version=t.version??1,this.createdAt=t.createdAt&&!isNaN(Date.parse(t.createdAt))?new Date(t.createdAt).toISOString():e.toISOString(),this.modifiedAt=t.modifiedAt&&!isNaN(Date.parse(t.modifiedAt))?new Date(t.modifiedAt).toISOString():e.toISOString(),this.modifiedBy={...t.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(t,e,i,r){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:r};}};var S={"en-IN":"en","kn-IN":"kn"};var Dt={INR:"\u20B9"},Mt={INR:"en-IN"};var pt=(u=>(u.INITIAL="INITIAL",u.PROCESSING="PROCESSING",u.SHIPPED="SHIPPED",u.DELIVERED="DELIVERED",u.CANCELLED="CANCELLED",u.RETURN_REQUESTED="RETURN_REQUESTED",u.RETURNED="RETURNED",u.REFUND_INITIATED="REFUND_INITIATED",u.REFUNDED="REFUNDED",u.ON_HOLD="ON_HOLD",u))(pt||{});var R=class{sources;alt;order;label;constructor(t){if(this.sources={...t.sources},this.alt=t.alt,this.order=t.order,this.label=t.label,!this.sources.original)throw new H("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(t){return this.sources[t]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(t){this.alt=t;}setOrder(t){this.order=t;}setLabel(t){this.label=t;}setSource(t,e){if(e===void 0){if(t==="original")throw new H("Cannot remove the 'original' image source.");delete this.sources[t];}else this.sources[t]=e;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var s=class n{#t;amount;currency;constructor(t){if(this.#t="PriceModel",t.amount<0)throw new Q("Amount cannot be negative.");if(!t.currency)throw new z("Currency code is required.");this.currency=t.currency,this.amount=parseFloat(t.amount.toFixed(n.getPrecisionPlaces(this.currency)));}get kind(){return this.#t}static isPriceModel(t){return typeof t=="object"&&t!==null&&t.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}getPreciseAmount(t){return parseFloat(t.toFixed(n.getPrecisionPlaces(this.currency)))}compareTo(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new L("Cannot compare prices in different currencies.")}else throw new A("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-t.getAmount())}add(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new L("Cannot add prices in different currencies.")}else throw new A("Must be a PriceModel instance.");return new n({amount:this.getPreciseAmount(this.amount+t.getAmount()),currency:this.currency})}subtract(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new L("Cannot subtract prices in different currencies.")}else throw new A("Must be a PriceModel instance.");return new n({amount:this.getPreciseAmount(this.amount-t.getAmount()),currency:this.currency})}multiply(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new L("Cannot multiply prices in different currencies.");return new n({amount:this.getPreciseAmount(this.amount*t.getAmount()),currency:this.currency})}else if(typeof t=="number"&&t>=0)return new n({amount:this.getPreciseAmount(this.amount*t),currency:this.currency});throw new A("Must be a non-negative number.")}divide(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new L("Cannot divide prices in different currencies.");return new n({amount:this.getPreciseAmount(this.amount/t.getAmount()),currency:this.currency})}else if(typeof t=="number"&&t>0)return new n({amount:this.getPreciseAmount(this.amount/t),currency:this.currency});throw new A("Must be a positive number.")}min(...t){if(t.length===0)throw new A("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(n.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new L("Cannot compare prices in different currencies.")}else throw new A("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i},this)}max(...t){if(t.length===0)throw new A("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(n.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new L("Cannot compare prices in different currencies.")}else throw new A("Must be a PriceModel instance.");return e.compareTo(i)>0?e:i},this)}zero(){return new n({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new n({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return n.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return n.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(t,e,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let r=Mt[e];if(!e||!r)throw new z("Invalid currency code for formatting.");let o=t,a=i.displayAsInteger?0:n.getDecimalPlaces(e),d={style:i.style??"currency",currency:e,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(r,d).format(o)}catch(g){return console.error(`Error formatting price for currency "${e}" and locale "${r}":`,g),`${Dt[e]??e} ${n.addThousandSeparators(o.toFixed(a))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static getPrecisionPlaces(t){switch(t){case"INR":default:return 6}}static addThousandSeparators(t){let e=t.split("."),i=e[0],r=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+r}static getRoundedAmount(t,e){if(t<0)throw new Q("Amount cannot be negative for rounding.");if(e===void 0)throw new z("Invalid currency code for rounding.");let i=n.getDecimalPlaces(e),r=Math.pow(10,i);return Math.round(t*r)/r}};var j=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new s(t.baseUnitPrice);if(!t.taxCategory)throw new ot;let i=(t.tiers??[]).map(g=>({minQuantity:g.minQuantity,unitPrice:new s(g.unitPrice)})).sort((g,c)=>g.minQuantity-c.minQuantity);if(i.some(g=>g.minQuantity<=0))throw new st;let o=i.some(g=>g.unitPrice.getCurrency()!==e.getCurrency()),a=i.some((g,c)=>c>0&&g.unitPrice.compareTo(i[c-1].unitPrice)>0),d=i[0]?.unitPrice.compareTo(e)>0;if(o||a||d)throw new at("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=e,this.taxCategory=t.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice}))}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}}getApplicableTier(t){if(t<=0)throw new ct;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity){let i=this.tiers[e];return {minQuantity:i.minQuantity,unitPrice:i.unitPrice}}throw new lt(t)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let t=this.tiers[this.tiers.length-1].unitPrice.getAmount(),e=this.baseUnitPrice.getAmount();return (e-t)/e*100}};var E=class n extends M{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(t){if(typeof t!="object")throw new D("Selection attributes must be an object");return Object.keys(t).filter(i=>t[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>t[i].name?`${i}:c+${t[i].name}`:`${i}:${t[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(t){try{let e={},i=t.split("|");for(let r of i){let[o,a]=r.split(":");a.startsWith("c+")?e[o]={name:a.slice(2)}:e[o]=a;}return e}catch(e){throw new D(e?.message)}}constructor(t,e=new Date){super(t,e),this.id=t.id,this.key=t.key,this.name={...t.name},this.description={...t.description},this.slug={...t.slug},this.brand=t.brand,this.pricing=Object.keys(t.pricing).reduce((r,o)=>(t.pricing[o]&&(r[o]=new j(t.pricing[o])),r),{}),this.targetGender=t.targetGender,this.attributes=m.deepClone(t.attributes),this.specifications=m.deepClone(t.specifications),this.categories=m.deepClone(t.categories);let i=new Set;this.variants=(t.variants||[]).map(r=>{if(!r.selectionAttributes||typeof r.selectionAttributes!="object")throw new D("Selection attributes are required");this.checkSelectionAttributes(r.selectionAttributes);let o=n.generateSelectionAttributesKey(r.selectionAttributes);if(i.has(o))throw new tt(o);return i.add(o),{sku:r.sku,selectionAttributes:r.selectionAttributes,images:{primary:new R(r.images.primary),gallery:(r.images.gallery||[]).map(a=>new R(a))}}}),this.isActive=t.isActive,this.searchTags=t.searchTags?m.deepClone(t.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(t){return t?this.name[t]??this.name[S[t]]??this.name.en:m.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[S[t]]??this.description.en:m.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[S[t]]??this.slug.en:m.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:{...this.pricing}}getAttributes(){return m.deepClone(this.attributes)}getVariants(){return this.variants.map(t=>({sku:t.sku,selectionAttributes:m.deepClone(t.selectionAttributes),images:{primary:t.images.primary,gallery:[...t.images.gallery]}}))}getImagesBySelectionAttributes(t){let e=n.generateSelectionAttributesKey(t),i=this.variants.find(r=>n.generateSelectionAttributesKey(r.selectionAttributes)===e);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(t,e){switch(e){case"PRIMARY":return this.getImagesBySelectionAttributes(t)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(t)?.gallery??[];default:return this.getImagesBySelectionAttributes(t)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return m.deepClone(this.categories)}getSpecifications(t){return t?m.deepClone(this.specifications[t]??this.specifications[S[t]]??this.specifications.en):m.deepClone(this.specifications)}getSearchTags(t){return t?m.deepClone(this.searchTags[t]??this.searchTags[S[t]]??this.searchTags.en):m.deepClone(this.searchTags)}getDetails(){let t=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((e,i)=>(this.pricing[i]&&(e[i]=this.pricing[i]?.getDetails()),e),{}),attributes:this.getAttributes(),variants:this.variants.map(e=>({sku:e.sku,selectionAttributes:m.deepClone(e.selectionAttributes),images:{primary:e.images.primary.getDetails(),gallery:e.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...t}}checkSelectionAttributes(t){if(!t||typeof t!="object")throw new D("Selection attributes are required");Object.keys(this.attributes).forEach(e=>{if(e.toLowerCase()==="size")return;let i=this.attributes[e],r=t[e];if(r===void 0)throw new D(`Selection attribute '${e}' is missing`);if(typeof i=="string"){if(typeof r!="string"||i!==r)throw new D(`Selection attribute '${e}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof r!="string"||!i.includes(r))throw new D(`Selection attribute '${e}' is invalid`)}else if(typeof r!="object"||!("name"in r)||i.findIndex(o=>o.name===r.name)<0)throw new D(`Selection attribute '${e}' is invalid`)}});}validateSelectionAttribute(t){let e=n.generateSelectionAttributesKey(t);return this.variants.some(i=>n.generateSelectionAttributesKey(i.selectionAttributes)===e)}validateSize(t){return this.attributes.size.includes(t)}};var O=class extends M{id;firstName;lastName;company;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(t,e=new Date){super(t,e),this.id=t.id,this.firstName=t.firstName,this.lastName=t.lastName||"",this.company=t.company||"",this.phone=t.phone,this.email=t.email,this.addressLine1=t.addressLine1,this.addressLine2=t.addressLine2||"",this.city=t.city,this.postalCode=t.postalCode,this.state=t.state,this.country=t.country,this.isBillingAddress=t.isBillingAddress,this.isShippingAddress=t.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),company:this.getCompany(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getCompany(){return this.company}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(t){return t==="shipping"||t==="billing&shipping"}static checkIfBillingAddress(t){return t==="billing"||t==="billing&shipping"}};var $=class extends B{taxRuleId;taxCategory;taxSystem;taxSubSystem;country;rate;minPrice;maxPrice;excludeMin;excludeMax;effectiveFrom;effectiveTo;constructor(t){super(t),this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxSubSystem=t.taxSubSystem,this.taxCategory=t.taxCategory,this.country=t.country,this.rate=t.rate,this.minPrice=new s(t.minPrice),this.maxPrice=t.maxPrice?new s(t.maxPrice):void 0,this.excludeMin=t.excludeMin??!1,this.excludeMax=t.excludeMax??!1,this.effectiveFrom=new Date(t.effectiveFrom).toISOString(),this.effectiveTo=t.effectiveTo?new Date(t.effectiveTo).toISOString():void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getRate(){return this.rate}getMinPrice(){return this.minPrice}getMaxPrice(){return this.maxPrice}getExcludeMin(){return this.excludeMin}getExcludeMax(){return this.excludeMax}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),rate:this.getRate(),minPrice:this.getMinPrice().getDetails(),maxPrice:this.getMaxPrice()?.getDetails(),excludeMin:this.getExcludeMin(),excludeMax:this.getExcludeMax(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0,customFields:this.getAllCustomFields()}}appliesTo(t,e,i,r=new Date){let o=!i||(this.excludeMin?this.minPrice.compareTo(i)<0:this.minPrice.compareTo(i)<=0)&&(this.maxPrice?this.excludeMax?this.maxPrice.compareTo(i)>0:this.maxPrice.compareTo(i)>=0:!0);return this.taxCategory===t&&this.country===e&&o&&Date.parse(this.effectiveFrom)<=r.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=r.getTime():!0)}getApplicableTaxRate(t){return this.appliesTo(this.taxCategory,this.country,t)?this.rate:0}calculateTax(t){return this.appliesTo(this.taxCategory,this.country,t)?t.multiply(this.rate):t.zero()}static getTaxRateDisplayString(t,e,i){let r=e*100,o=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,"");return i?.percentageOnly?`${o}%`:t.getTaxSystem()==="GST"?`${t.getTaxSubSystem()} ${o}%`:`${t.getTaxSystem()} ${o}%`}};var V=class extends B{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=m.deepClone(t.selectionAttributes),this.name=m.deepClone(t.name),this.specifications=m.deepClone(t.specifications),this.primaryImage=new R(t.primaryImage),this.subItems=m.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new _(i.size);e.add(i.size);}),this.pricing={unitPrice:new s(t.pricing.unitPrice),tierPricing:new j(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(i=>new $(i))},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,unitPrice:new s(t.total.unitPrice),subtotal:new s(t.total.subtotal),discountTotal:new s(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([i,r])=>[i,new s(r)])),netUnitPrice:new s(t.total.netUnitPrice),netSubtotal:new s(t.total.netSubtotal),taxTotal:new s(t.total.taxTotal),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:new s(r.taxableUnitPrice),taxPerUnit:new s(r.taxPerUnit),taxAmount:new s(r.taxAmount),system:r.system,subSystem:r.subSystem}])),grandTotal:new s(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return m.deepClone(this.selectionAttributes)}getName(t){return t?m.deepClone(this.name[t]??this.name[S[t]]??this.name.en):m.deepClone(this.name)}getSpecifications(t){return t?m.deepClone(this.specifications[t]??this.specifications[S[t]]??this.specifications.en):m.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return m.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getState(){return this.state}getTotal(){return {quantity:this.total.quantity,unitPrice:this.total.unitPrice,subtotal:this.total.subtotal,discountTotal:this.total.discountTotal,discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([t,e])=>[t,e])),netUnitPrice:this.total.netUnitPrice,netSubtotal:this.total.netSubtotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableUnitPrice:e.taxableUnitPrice,taxPerUnit:e.taxPerUnit,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),grandTotal:this.total.grandTotal}}getDetails(){let t=this.getPricing(),e=this.getTotal();return {id:this.getId(),productKey:this.getProductKey(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:t.unitPrice.getDetails(),tierPricing:t.tierPricing.getDetails(),taxCategory:t.taxCategory,applicableTaxRule:t.applicableTaxRule.map(i=>i.getDetails())},state:this.getState(),total:{quantity:e.quantity,unitPrice:e.unitPrice.getDetails(),subtotal:e.subtotal.getDetails(),discountTotal:e.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(e.discountBreakdown).map(([i,r])=>[i,r.getDetails()])),netUnitPrice:e.netUnitPrice.getDetails(),netSubtotal:e.netSubtotal.getDetails(),taxTotal:e.taxTotal.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(e.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:r.taxableUnitPrice.getDetails(),taxPerUnit:r.taxPerUnit.getDetails(),taxAmount:r.taxAmount.getDetails(),system:r.system,subSystem:r.subSystem}])),grandTotal:e.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(o=>o.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity>0),this.calculateTotals();}updateProductData(t,e,i){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new et;if(!t.getIsActive())throw new it;this.subItems.forEach(d=>{if(!t.validateSize(d.size))throw new rt});let r=t.getPriceDetails(e);if(!r||r.getBaseUnitPrice().getCurrency()!==i)throw new nt;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let o=this.subItems.reduce((d,g)=>d+g.quantity,0),{unitPrice:a}=r.getApplicableTier(o);this.pricing={unitPrice:a,tierPricing:r,taxCategory:r.getTaxCategory(),applicableTaxRule:this.pricing.applicableTaxRule},this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discountBreakdown=e,this.calculateTotals();}updateTax(t){t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new F}),this.pricing.applicableTaxRule=t,this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((h,C)=>h+C.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,unitPrice:t,subtotal:t,discountTotal:t,discountBreakdown:{},netUnitPrice:t,netSubtotal:t,taxTotal:t,taxBreakdown:{},grandTotal:t};return}let{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),r=i.multiply(e),o=Object.values(this.total.discountBreakdown).reduce((h,C)=>h.add(C),t),a=r.subtract(o),d=e>0?a.divide(e):t,g={},c=t;this.pricing.applicableTaxRule.forEach(h=>{let C=h.getApplicableTaxRate(d),I=h.calculateTax(d),P=I.multiply(e).round();g[h.getTaxRuleId()]={rate:C,taxableUnitPrice:d,taxPerUnit:I,taxAmount:P,system:h.getTaxSystem(),subSystem:h.getTaxSubSystem()},c=c.add(P);});let u=a.add(c);this.total={quantity:e,unitPrice:i,subtotal:r,discountTotal:o,discountBreakdown:this.total.discountBreakdown,netUnitPrice:d,netSubtotal:a,taxTotal:c,taxBreakdown:g,grandTotal:u};}updateState(t){if(this.state in pt)this.state!==t&&(this.state=t);else throw new W(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new R({sources:{original:""}}),this.subItems=[],this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[]},this.total={quantity:0,unitPrice:t,subtotal:t,discountTotal:t,discountBreakdown:{},netUnitPrice:t,netSubtotal:t,taxTotal:t,taxBreakdown:{},grandTotal:t};}};var J=class extends M{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(t,e=new Date){if(super(t,e),this.couponCode=t.couponCode,this.name=m.deepClone(t.name),this.description=m.deepClone(t.description),this.type=t.type,this.customerId=t.customerId,this.validFrom=t.validFrom&&Date.parse(t.validFrom)?new Date(t.validFrom).toISOString():e.toISOString(),this.validTo=t.validTo&&Date.parse(t.validTo)?new Date(t.validTo).toISOString():e.toISOString(),this.minCartValue=Object.keys(t.minCartValue).reduce((i,r)=>{let o=t.minCartValue[r];return o&&(i[r]=new s(o)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,r)=>{let o=t.maxCartDiscount[r];return o&&(i[r]=new s(o)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new A("Percentage value cannot be greater than 100");this.applicableTo=t.applicableTo,this.category=t.category;}getCode(){return this.couponCode}getName(t){return t?this.name[t]??this.name[S[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[S[t]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(t){return t?this.minCartValue[t]:{...this.minCartValue}}getMaxCartDiscount(t){return t?this.maxCartDiscount[t]:{...this.maxCartDiscount}}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:Object.keys(this.getMinCartValue()).reduce((t,e)=>{let i=this.getMinCartValue(e);return i&&(t[e]=i.getDetails()),t},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((t,e)=>{let i=this.getMaxCartDiscount(e);return i&&(t[e]=i.getDetails()),t},{}),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(t){return this.applicableTo==="all"||this.applicableTo==="ftb"&&t}calculateApplicableCouponDiscount(t,e,i,r,o=!0){let a=new s({amount:0,currency:r}),d;if(o&&!this.isActive())return a;let g=this.getMinCartValue(i),c=this.getMaxCartDiscount(i);if(!g||g.compareTo(t)>0||!c)return a;let u=this.getCategory(),h=this.getDiscountMethod(),C=u==="SHIPPING"?e:t;if(C.getAmount()<=0)return a;switch(h){case"flat":let P=c;d=C.min(P);break;case"percentage":d=C.multiply(this.getPercentageValue()/100).round();break;default:return a}return d.min(c)}};var G=class extends B{id;name;type;category;impact;pricing;lineItemId;total;constructor(t){if(super(t),this.id=t.id,this.name=t.name,this.type=t.type,this.category=t.category,this.impact=t.impact,this.lineItemId=t.lineItemId,this.pricing={chargeAmount:new s(t.pricing.chargeAmount),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(e=>new $(e))},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new Z("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={chargeAmount:new s(t.total.chargeAmount),discountTotal:new s(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([e,i])=>[e,new s(i)])),netChargeAmount:new s(t.total.netChargeAmount),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxableAmount:new s(i.taxableAmount),taxAmount:new s(i.taxAmount),system:i.system,subSystem:i.subSystem}])),taxTotal:new s(t.total.taxTotal),grandTotal:new s(t.total.grandTotal)};}getId(){return this.id}getName(t){return t?m.deepClone(this.name[t]??this.name[S[t]]??this.name.en):m.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getPricing(){return {chargeAmount:this.pricing.chargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {chargeAmount:this.total.chargeAmount,discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},netChargeAmount:this.total.netChargeAmount,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableAmount:e.taxableAmount,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(t){if(this.type==="ADJUSTMENT"&&t.length>0)throw new Z("Adjustment charges cannot apply tax rules.");t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new F}),this.validateTaxRules(t),this.pricing.applicableTaxRule=t,this.calculateTotals();}validateTaxRules(t){if(this.impact==="SUBTRACT"&&t.some(e=>e.getRate()>0))throw new Y("Subtractive charges cannot have positive tax rates.");for(let e=0;e<t.length;e++)for(let i=e+1;i<t.length;i++){let r=t[e],o=t[i],a=r.getMinPrice(),d=r.getMaxPrice(),g=r.getExcludeMin(),c=r.getExcludeMax(),u=o.getMinPrice(),h=o.getMaxPrice(),C=o.getExcludeMin(),I=o.getExcludeMax(),P=(()=>{if(!d)return !1;let y=d.compareTo(u);return y<0||y===0&&(c||C)})(),w=(()=>{if(!h)return !1;let y=h.compareTo(a);return y<0||y===0&&(I||g)})();if(!(P||w)&&!(a.compareTo(u)===0&&g===C&&c===I&&(!d&&!h||d&&h&&d.compareTo(h)===0)))throw new Y(`Overlapping rules found: [${r.getTaxRuleId()}: ${g?"(":"["}${a.getAmount()}-${d?.getAmount()??"Infinity"}${c?")":"]"}] and [${o.getTaxRuleId()}: ${C?"(":"["}${u.getAmount()}-${h?.getAmount()??"Infinity"}${I?")":"]"}]`)}}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discountBreakdown=e,this.calculateTotals();}calculateTotals(){let t=this.pricing.chargeAmount.zero(),e=this.pricing.chargeAmount,i=Object.values(this.total.discountBreakdown).reduce((x,y)=>x.add(y),t),r=e.subtract(i),o={},a=this.pricing.applicableTaxRule.reduce((x,y)=>x+y.getApplicableTaxRate(r),0);if(a<=0){this.total={chargeAmount:e,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:r,taxTotal:t,taxBreakdown:{},grandTotal:r};return}let d=e.getCurrency(),g=e.getAmount(),c=1e3,u=s.getRoundedAmount(g/(1+a),d),h=u,C=Number.POSITIVE_INFINITY;for(let x=0;x<c;x++){let y=new s({amount:u,currency:d}),U=this.pricing.applicableTaxRule.sort((l,p)=>p.getApplicableTaxRate(y)-l.getApplicableTaxRate(y)).map(l=>s.getRoundedAmount(u*l.getApplicableTaxRate(y),d)).reduce((l,p)=>l+p,0),v=u+U-g,mt=this.pricing.applicableTaxRule.reduce((l,p)=>l+p.getApplicableTaxRate(y),0);if(Math.abs(v)<Math.abs(C)&&(C=v,h=u),v===0||(u=u-v/(1+mt),u<0||u>g))break}let I=new s({amount:h,currency:d}),P=t;this.pricing.applicableTaxRule.sort((x,y)=>y.getApplicableTaxRate(I)-x.getApplicableTaxRate(I)).forEach(x=>{let y=x.getApplicableTaxRate(I),K=s.getRoundedAmount(h*y,d),U=new s({amount:K,currency:d});o[x.getTaxRuleId()]={rate:y,taxableAmount:I,taxAmount:U,system:x.getTaxSystem(),subSystem:x.getTaxSubSystem()},P=P.add(U);});let w=e;this.total={chargeAmount:e,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:w,taxBreakdown:o,taxTotal:P,grandTotal:w};}getDetails(){return {id:this.id,name:m.deepClone(this.name),type:this.type,category:this.category,pricing:{chargeAmount:this.pricing.chargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(e=>e.getDetails())},impact:this.impact,lineItemId:this.lineItemId,total:{chargeAmount:this.total.chargeAmount.getDetails(),discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([e,i])=>[e,i.getDetails()])),netChargeAmount:this.total.netChargeAmount.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxableAmount:i.taxableAmount.getDetails(),taxAmount:i.taxAmount.getDetails(),system:i.system,subSystem:i.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};var X=class extends M{id;customerId;customerEmail;anonymousId;lineItems;charges;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,e=new Date){super(t,e),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(i=>new V(i)),this.charges=(t.charges??[]).map(i=>new G(i)),this.billingAddress=t.billingAddress?new O(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new O(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new J(i)),this.shippingDetails=t.shippingDetails?m.deepClone(t.shippingDetails):null,this.total={lineItemSubtotal:new s(t.total.lineItemSubtotal),netLineItemSubtotal:new s(t.total.netLineItemSubtotal),lineItemTaxTotal:new s(t.total.lineItemTaxTotal),lineItemTaxBreakdown:this.mapTaxBreakdown(t.total.lineItemTaxBreakdown),additiveCharges:new s(t.total.additiveCharges),netAdditiveCharges:new s(t.total.netAdditiveCharges),additiveChargesTaxTotal:new s(t.total.additiveChargesTaxTotal),additiveChargesTaxBreakdown:this.mapTaxBreakdown(t.total.additiveChargesTaxBreakdown),adjustmentCharges:new s(t.total.adjustmentCharges),shippingCharges:new s(t.total.shippingCharges),netShippingCharges:new s(t.total.netShippingCharges),discountTotal:new s(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([i,r])=>[i,new s(r)])),taxTotal:new s(t.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(t.total.taxBreakdown),grandTotal:new s(t.total.grandTotal)};}mapTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,i])=>[e,{system:i.system,totalAmount:new s(i.totalAmount),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,o])=>[r,new s(o)]))}]))}serializeTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,i])=>[e,{system:i.system,totalAmount:i.totalAmount.getDetails(),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,o])=>[r,o.getDetails()]))}]))}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new V(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(t=>new G(t.getDetails()))}addCharge(t){this.charges.push(t),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?m.deepClone(this.shippingDetails):null}getShippingAddress(){return this.shippingAddress?new O(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new O(this.billingAddress.getDetails()):null}getCoupons(){return [...this.coupons]}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {lineItemSubtotal:this.total.lineItemSubtotal,netLineItemSubtotal:this.total.netLineItemSubtotal,lineItemTaxTotal:this.total.lineItemTaxTotal,lineItemTaxBreakdown:Object.fromEntries(Object.entries(this.total.lineItemTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),additiveCharges:this.total.additiveCharges,netAdditiveCharges:this.total.netAdditiveCharges,additiveChargesTaxTotal:this.total.additiveChargesTaxTotal,additiveChargesTaxBreakdown:Object.fromEntries(Object.entries(this.total.additiveChargesTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),adjustmentCharges:this.total.adjustmentCharges,shippingCharges:this.total.shippingCharges,netShippingCharges:this.total.netShippingCharges,discountBreakdown:{...this.total.discountBreakdown},discountTotal:this.total.discountTotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),grandTotal:this.total.grandTotal}}getDetails(){let t=this.getTotal();return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(e=>e.getDetails()),charges:this.getCharges().map(e=>e.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(e=>e.getDetails()),total:{lineItemSubtotal:t.lineItemSubtotal.getDetails(),netLineItemSubtotal:t.netLineItemSubtotal.getDetails(),lineItemTaxTotal:t.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(t.lineItemTaxBreakdown),additiveCharges:t.additiveCharges.getDetails(),netAdditiveCharges:t.netAdditiveCharges.getDetails(),additiveChargesTaxTotal:t.additiveChargesTaxTotal.getDetails(),additiveChargesTaxBreakdown:this.serializeTaxBreakdown(t.additiveChargesTaxBreakdown),adjustmentCharges:t.adjustmentCharges.getDetails(),shippingCharges:t.shippingCharges.getDetails(),netShippingCharges:t.netShippingCharges.getDetails(),discountTotal:t.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(t.discountBreakdown).map(([e,i])=>[e,i.getDetails()])),taxTotal:t.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(t.taxBreakdown),grandTotal:t.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new s({amount:0,currency:this.currency}),e=this.lineItems.filter(l=>l.getState()!=="CANCELLED"),i=e.reduce((l,p)=>l.add(p.getTotal().subtotal),t),r=this.charges.filter(l=>l.getType()==="SHIPPING").reduce((l,p)=>l.add(p.getTotal().chargeAmount),t);this.total.lineItemSubtotal=i,this.total.shippingCharges=r;let o=t,a={},d={};this.coupons.forEach(l=>{let p=l.calculateApplicableCouponDiscount(i,r,this.country,this.currency);o=o.add(p),a[l.getCode()]=p,l.getCategory()!=="SHIPPING"&&(d[l.getCode()]=p);}),this.total.discountTotal=o,this.total.discountBreakdown=a,this.applyDiscountsInLineItem(d);let g=this.coupons.find(l=>l.getCategory()==="SHIPPING");g?this.applyDiscountsInShippingCharges({[g.getCode()]:a[g.getCode()]||t}):this.applyDiscountsInShippingCharges({});let c=this.lineItems.reduce((l,p)=>l.add(p.getTotal().netSubtotal),t),u=this.charges.filter(l=>l.getType()==="SHIPPING").reduce((l,p)=>l.add(p.getTotal().grandTotal),t);this.total.netLineItemSubtotal=c,this.total.netShippingCharges=u;let h=this.charges.filter(l=>l.getImpact()==="ADD").reduce((l,p)=>l.add(p.getTotal().chargeAmount),t),C=this.charges.filter(l=>l.getImpact()==="ADD").reduce((l,p)=>l.add(p.getTotal().grandTotal),t),I=this.charges.filter(l=>l.getImpact()==="SUBTRACT").reduce((l,p)=>l.add(p.getTotal().grandTotal),t),P=t,w=t,x=t,y={},K={},U={},v=(l,p)=>{Object.entries(l).forEach(([Kt,N])=>{let T=N.system,k=N.subSystem;p[T]||(p[T]={system:T,totalAmount:t,subSystems:{}}),p[T].subSystems[k]?p[T].subSystems[k]=p[T].subSystems[k].add(N.taxAmount):p[T].subSystems[k]=N.taxAmount,p[T].totalAmount=p[T].totalAmount.add(N.taxAmount),y[T]||(y[T]={system:T,totalAmount:t,subSystems:{}}),y[T].subSystems[k]?y[T].subSystems[k]=y[T].subSystems[k].add(N.taxAmount):y[T].subSystems[k]=N.taxAmount,y[T].totalAmount=y[T].totalAmount.add(N.taxAmount);});};e.forEach(l=>{let p=l.getTotal().taxBreakdown;p&&(v(p,K),v(p,y),w=w.add(l.getTotal().taxTotal));}),this.charges.forEach(l=>{let p=l.getTotal().taxBreakdown;p&&(v(p,U),v(p,y),x=x.add(l.getTotal().taxTotal));}),P=w.add(x);let mt=c.add(w).add(C).subtract(I);this.total={lineItemSubtotal:i,netLineItemSubtotal:c,lineItemTaxTotal:w,lineItemTaxBreakdown:K,additiveCharges:h,netAdditiveCharges:C,additiveChargesTaxTotal:x,additiveChargesTaxBreakdown:U,adjustmentCharges:I,shippingCharges:r,netShippingCharges:u,discountTotal:o,discountBreakdown:a,taxTotal:P,taxBreakdown:y,grandTotal:mt};}updateShippingDetails(t){this.shippingDetails=t;}applyCoupons(t){let e=t.filter(r=>r.getCategory()==="SHIPPING"),i=t.filter(r=>r.getCategory()!=="SHIPPING");this.coupons=[],this.total.discountTotal=this.total.lineItemSubtotal.zero(),this.total.discountBreakdown={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.discountBreakdown),e.length&&this.applyShippingCoupons(e),this.calculateTotals();}applyDiscountsInLineItem(t){let e=Array.from(Object.entries(t)).filter(r=>!r[1].isZero()),i=new Map;this.lineItems.forEach(r=>i.set(r.getId(),[])),e.forEach(([r,o])=>{let a=this.coupons.find(c=>c.getCode()===r);if(!a||o.isZero())return;let d=this.lineItems.filter(c=>c.getState()!=="CANCELLED"&&!c.getTotal().subtotal.isZero()).sort((c,u)=>c.getTotal().subtotal.compareTo(u.getTotal().subtotal)),g=new s({amount:0,currency:this.currency});d.forEach((c,u)=>{let h;u===d.length-1?h=o.subtract(g):h=o.multiply(c.getTotal().subtotal).divide(this.total.lineItemSubtotal).round(),g=g.add(h),i.get(c.getId())?.push({coupon:a,amount:h});});}),this.lineItems.forEach(r=>{r.getState()==="CANCELLED"||this.total.lineItemSubtotal.isZero()?r.updateDiscounts([]):r.updateDiscounts(i.get(r.getId())||[]);});}applyDiscountsInShippingCharges(t){let e=Array.from(Object.entries(t)).filter(o=>!o[1].isZero()),i=this.charges.filter(o=>o.getType()==="SHIPPING"),r=new Map;i.forEach(o=>r.set(o.getId(),[])),e.forEach(([o,a])=>{let d=this.coupons.find(u=>u.getCode()===o);if(!d||a.isZero())return;let g=i.sort((u,h)=>u.getTotal().grandTotal.compareTo(h.getTotal().grandTotal)),c=new s({amount:0,currency:this.currency});g.forEach((u,h)=>{let C;h===g.length-1?C=a.subtract(c):C=a.multiply(u.getTotal().chargeAmount).divide(this.total.shippingCharges).round(),c=c.add(C),r.get(u.getId())?.push({coupon:d,amount:C});});}),i.forEach(o=>{o.updateDiscounts(r.get(o.getId())||[]);});}applyNonShippingCoupons(t){let e=t.filter(i=>i.getType()==="coupon");if(e.length===1){let i=e[0].calculateApplicableCouponDiscount(this.total.lineItemSubtotal,this.total.shippingCharges,this.country,this.currency);i.getAmount()>0&&(this.coupons.push(e[0]),this.total.discountTotal=i,this.total.discountBreakdown[e[0].getCode()]=i);}}applyShippingCoupons(t){if(this.total.shippingCharges.getAmount()>0&&t.length>0){let e=this.total.lineItemSubtotal.subtract(this.total.discountTotal),i=t.reduce((o,a)=>{if(!o)return a;let d=a.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency).min(this.total.shippingCharges),g=o.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency).min(this.total.shippingCharges);return d.compareTo(g)===0?a.getType()==="coupon"?a:o:d.compareTo(g)>0?a:o}),r=i.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency).min(this.total.shippingCharges);r.getAmount()>0&&(this.coupons.push(i),this.total.discountTotal=this.total.discountTotal.add(r),this.total.discountBreakdown[i.getCode()]=r);}}};var Vt=(r=>(r.ACTIVE="ACTIVE",r.FROZEN="FROZEN",r.MERGED="MERGED",r.ORDERED="ORDERED",r))(Vt||{}),Gt={expiresAtInSeconds:120*24*60*60},Tt=class extends X{state;expireAt;config;constructor(t,e=new Date,i=Gt){super(t,e),this.state=t.state,this.expireAt=t.expireAt&&typeof t.expireAt=="number"?t.expireAt:Math.floor(e.getTime()/1e3)+i.expiresAtInSeconds,this.config=i;}getState(){return this.state}getExpireAt(){return this.expireAt}isActive(){let t=Math.ceil(Date.now()/1e3);return this.state==="ACTIVE"&&this.expireAt>t}clearCartItems(){this.lineItems=[],this.charges=[],this.coupons=[],this.shippingDetails=null,this.calculateTotals();}validateLineItems(t){this.lineItems=this.lineItems.map(e=>{try{e.updateProductData(t[e.getProductKey()],this.country,this.currency);}catch(i){console.error(`Error recalculating line item ${e.getId()}:`,i),e.clearLineItem();}return e}).filter(e=>e.getId()),this.calculateTotals();}addLineItem(t){let e=t.getProductKey(),i=t.getSelectionAttributes(),r=E.generateSelectionAttributesKey(i),o=this.lineItems.findIndex(a=>a.getProductKey()===e&&E.generateSelectionAttributesKey(a.getSelectionAttributes())===r);return o>=0?this.lineItems[o].addSubItems(t.getSubItems(),!0):this.lineItems.push(t),this.calculateTotals(),o>=0?o:this.lineItems.length-1}updateLineItem(t,e,i){let r=this.lineItems,o=r.findIndex(a=>a.getId()===t);if(o<0)throw new q(t);return r[o].addSubItems([{size:e,quantity:i}],!1),this.calculateTotals(),o}removeLineItem(t){let i=this.lineItems.findIndex(r=>r.getId()===t);if(i<0)throw new q(t);return this.lineItems.splice(i,1),this.charges=this.charges.filter(r=>r.getLineItemId()!==t),this.calculateTotals(),i}getDetails(){return {...super.getDetails(),state:this.getState(),expireAt:this.getExpireAt()}}};exports.CartState=Vt;exports.DEFAULT_CART_CONFIG=Gt;exports.default=Tt;//# sourceMappingURL=Cart.js.map
|
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var wt=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var wt__default=/*#__PURE__*/_interopDefault(wt);var q=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}},W=class extends Error{constructor(t){super(`Invalid line item state: ${t}`),this.name="InvalidLineItemStateError";}},_=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},tt=class extends Error{constructor(t){super(`Duplicate selection attribute found: ${t}`),this.name="DuplicateSelectionAttributeError";}},et=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},it=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},D=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},rt=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},nt=class extends Error{constructor(t="Pricing details not available for the product"){super(`NotFound: ${t}`),this.name="PricingNotFoundError";}},F=class extends Error{constructor(t="Tax rule category mismatch."){super(`InvalidTaxRule: ${t}`),this.name="InvalidTaxRuleError";}},ot=class extends Error{constructor(t="Tax category is not valid."){super(`InvalidTaxCategory: ${t}`),this.name="InvalidTaxCategoryError";}},st=class extends Error{constructor(t="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${t}`),this.name="InvalidMinQuantityError";}},at=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},ct=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},lt=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var Q=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},z=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},L=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},A=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},H=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}},Z=class extends Error{constructor(t="Invalid charge data."){super(`InvalidCharge: ${t}`),this.name="InvalidChargeError";}},Y=class extends Error{constructor(t="Invalid charge tax rule."){super(`InvalidChargeTaxRule: ${t}`),this.name="InvalidChargeTaxRuleError";}};var dt=new Uint8Array(256),ut=dt.length;function ht(){return ut>dt.length-16&&(wt__default.default.randomFillSync(dt),ut=0),dt.slice(ut,ut+=16)}var ft=/^(?:[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 Lt(n){return typeof n=="string"&&ft.test(n)}var It=Lt;var f=[];for(let n=0;n<256;++n)f.push((n+256).toString(16).slice(1));function gt(n,t=0){return f[n[t+0]]+f[n[t+1]]+f[n[t+2]]+f[n[t+3]]+"-"+f[n[t+4]]+f[n[t+5]]+"-"+f[n[t+6]]+f[n[t+7]]+"-"+f[n[t+8]]+f[n[t+9]]+"-"+f[n[t+10]]+f[n[t+11]]+f[n[t+12]]+f[n[t+13]]+f[n[t+14]]+f[n[t+15]]}function vt(n){if(!It(n))throw TypeError("Invalid UUID");let t,e=new Uint8Array(16);return e[0]=(t=parseInt(n.slice(0,8),16))>>>24,e[1]=t>>>16&255,e[2]=t>>>8&255,e[3]=t&255,e[4]=(t=parseInt(n.slice(9,13),16))>>>8,e[5]=t&255,e[6]=(t=parseInt(n.slice(14,18),16))>>>8,e[7]=t&255,e[8]=(t=parseInt(n.slice(19,23),16))>>>8,e[9]=t&255,e[10]=(t=parseInt(n.slice(24,36),16))/1099511627776&255,e[11]=t/4294967296&255,e[12]=t>>>24&255,e[13]=t>>>16&255,e[14]=t>>>8&255,e[15]=t&255,e}var At=vt;function Et(n){n=unescape(encodeURIComponent(n));let t=[];for(let e=0;e<n.length;++e)t.push(n.charCodeAt(e));return t}var Bt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Rt="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function yt(n,t,e){function i(r,o,a,d){var g;if(typeof r=="string"&&(r=Et(r)),typeof o=="string"&&(o=At(o)),((g=o)===null||g===void 0?void 0:g.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+r.length);if(c.set(o),c.set(r,o.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,a){d=d||0;for(let u=0;u<16;++u)a[d+u]=c[u];return a}return gt(c)}try{i.name=n;}catch{}return i.DNS=Bt,i.URL=Rt,i}var bt={randomUUID:wt__default.default.randomUUID};function kt(n,t,e){if(bt.randomUUID&&!t&&!n)return bt.randomUUID();n=n||{};let i=n.random||(n.rng||ht)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){e=e||0;for(let r=0;r<16;++r)t[e+r]=i[r];return t}return gt(i)}var Ct=kt;function Ut(n){return Array.isArray(n)?n=Buffer.from(n):typeof n=="string"&&(n=Buffer.from(n,"utf8")),wt__default.default.createHash("sha1").update(n).digest()}var St=Ut;var Ft=yt("v5",80,St),xt=Ft;var zt={isUUID:n=>/^[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(n),isEmail:n=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(n),isURL:n=>/^(http|https):\/\/[^ "]+$/.test(n),generateUUID:(n,t)=>t&&n?xt(n,t):Ct(),generateSearchId:(n,t)=>`${n}#${E.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:n=>{let[t,e]=n.split("#");return {key:t,selectionAttributes:E.parseSelectionAttributesKey(e)}},deepClone(n){return structuredClone(n)}},m=zt;var Pt=n=>structuredClone(n),B=class{customFields;constructor(t,e=new Date){this.customFields={...t.customFields};}getCustomField(t){let e=this.customFields[t];return e==null?e:Pt(e)}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return Pt(this.customFields)}},M=class extends B{version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){super(t),this.version=t.version??1,this.createdAt=t.createdAt&&!isNaN(Date.parse(t.createdAt))?new Date(t.createdAt).toISOString():e.toISOString(),this.modifiedAt=t.modifiedAt&&!isNaN(Date.parse(t.modifiedAt))?new Date(t.modifiedAt).toISOString():e.toISOString(),this.modifiedBy={...t.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(t,e,i,r){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:r};}};var S={"en-IN":"en","kn-IN":"kn"};var Dt={INR:"\u20B9"},Mt={INR:"en-IN"};var pt=(u=>(u.INITIAL="INITIAL",u.PROCESSING="PROCESSING",u.SHIPPED="SHIPPED",u.DELIVERED="DELIVERED",u.CANCELLED="CANCELLED",u.RETURN_REQUESTED="RETURN_REQUESTED",u.RETURNED="RETURNED",u.REFUND_INITIATED="REFUND_INITIATED",u.REFUNDED="REFUNDED",u.ON_HOLD="ON_HOLD",u))(pt||{});var R=class{sources;alt;order;label;constructor(t){if(this.sources={...t.sources},this.alt=t.alt,this.order=t.order,this.label=t.label,!this.sources.original)throw new H("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(t){return this.sources[t]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(t){this.alt=t;}setOrder(t){this.order=t;}setLabel(t){this.label=t;}setSource(t,e){if(e===void 0){if(t==="original")throw new H("Cannot remove the 'original' image source.");delete this.sources[t];}else this.sources[t]=e;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var s=class n{#t;amount;currency;constructor(t){if(this.#t="PriceModel",t.amount<0)throw new Q("Amount cannot be negative.");if(!t.currency)throw new z("Currency code is required.");this.currency=t.currency,this.amount=parseFloat(t.amount.toFixed(n.getPrecisionPlaces(this.currency)));}get kind(){return this.#t}static isPriceModel(t){return typeof t=="object"&&t!==null&&t.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}getPreciseAmount(t){return parseFloat(t.toFixed(n.getPrecisionPlaces(this.currency)))}compareTo(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new L("Cannot compare prices in different currencies.")}else throw new A("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-t.getAmount())}add(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new L("Cannot add prices in different currencies.")}else throw new A("Must be a PriceModel instance.");return new n({amount:this.getPreciseAmount(this.amount+t.getAmount()),currency:this.currency})}subtract(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new L("Cannot subtract prices in different currencies.")}else throw new A("Must be a PriceModel instance.");return new n({amount:this.getPreciseAmount(this.amount-t.getAmount()),currency:this.currency})}multiply(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new L("Cannot multiply prices in different currencies.");return new n({amount:this.getPreciseAmount(this.amount*t.getAmount()),currency:this.currency})}else if(typeof t=="number"&&t>=0)return new n({amount:this.getPreciseAmount(this.amount*t),currency:this.currency});throw new A("Must be a non-negative number.")}divide(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new L("Cannot divide prices in different currencies.");return new n({amount:this.getPreciseAmount(this.amount/t.getAmount()),currency:this.currency})}else if(typeof t=="number"&&t>0)return new n({amount:this.getPreciseAmount(this.amount/t),currency:this.currency});throw new A("Must be a positive number.")}min(...t){if(t.length===0)throw new A("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(n.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new L("Cannot compare prices in different currencies.")}else throw new A("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i},this)}max(...t){if(t.length===0)throw new A("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(n.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new L("Cannot compare prices in different currencies.")}else throw new A("Must be a PriceModel instance.");return e.compareTo(i)>0?e:i},this)}zero(){return new n({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new n({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return n.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return n.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(t,e,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let r=Mt[e];if(!e||!r)throw new z("Invalid currency code for formatting.");let o=t,a=i.displayAsInteger?0:n.getDecimalPlaces(e),d={style:i.style??"currency",currency:e,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(r,d).format(o)}catch(g){return console.error(`Error formatting price for currency "${e}" and locale "${r}":`,g),`${Dt[e]??e} ${n.addThousandSeparators(o.toFixed(a))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static getPrecisionPlaces(t){switch(t){case"INR":default:return 6}}static addThousandSeparators(t){let e=t.split("."),i=e[0],r=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+r}static getRoundedAmount(t,e){if(t<0)throw new Q("Amount cannot be negative for rounding.");if(e===void 0)throw new z("Invalid currency code for rounding.");let i=n.getDecimalPlaces(e),r=Math.pow(10,i);return Math.round(t*r)/r}};var j=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new s(t.baseUnitPrice);if(!t.taxCategory)throw new ot;let i=(t.tiers??[]).map(g=>({minQuantity:g.minQuantity,unitPrice:new s(g.unitPrice)})).sort((g,c)=>g.minQuantity-c.minQuantity);if(i.some(g=>g.minQuantity<=0))throw new st;let o=i.some(g=>g.unitPrice.getCurrency()!==e.getCurrency()),a=i.some((g,c)=>c>0&&g.unitPrice.compareTo(i[c-1].unitPrice)>0),d=i[0]?.unitPrice.compareTo(e)>0;if(o||a||d)throw new at("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=e,this.taxCategory=t.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice}))}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}}getApplicableTier(t){if(t<=0)throw new ct;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity){let i=this.tiers[e];return {minQuantity:i.minQuantity,unitPrice:i.unitPrice}}throw new lt(t)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let t=this.tiers[this.tiers.length-1].unitPrice.getAmount(),e=this.baseUnitPrice.getAmount();return (e-t)/e*100}};var E=class n extends M{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(t){if(typeof t!="object")throw new D("Selection attributes must be an object");return Object.keys(t).filter(i=>t[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>t[i].name?`${i}:c+${t[i].name}`:`${i}:${t[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(t){try{let e={},i=t.split("|");for(let r of i){let[o,a]=r.split(":");a.startsWith("c+")?e[o]={name:a.slice(2)}:e[o]=a;}return e}catch(e){throw new D(e?.message)}}constructor(t,e=new Date){super(t,e),this.id=t.id,this.key=t.key,this.name={...t.name},this.description={...t.description},this.slug={...t.slug},this.brand=t.brand,this.pricing=Object.keys(t.pricing).reduce((r,o)=>(t.pricing[o]&&(r[o]=new j(t.pricing[o])),r),{}),this.targetGender=t.targetGender,this.attributes=m.deepClone(t.attributes),this.specifications=m.deepClone(t.specifications),this.categories=m.deepClone(t.categories);let i=new Set;this.variants=(t.variants||[]).map(r=>{if(!r.selectionAttributes||typeof r.selectionAttributes!="object")throw new D("Selection attributes are required");this.checkSelectionAttributes(r.selectionAttributes);let o=n.generateSelectionAttributesKey(r.selectionAttributes);if(i.has(o))throw new tt(o);return i.add(o),{sku:r.sku,selectionAttributes:r.selectionAttributes,images:{primary:new R(r.images.primary),gallery:(r.images.gallery||[]).map(a=>new R(a))}}}),this.isActive=t.isActive,this.searchTags=t.searchTags?m.deepClone(t.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(t){return t?this.name[t]??this.name[S[t]]??this.name.en:m.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[S[t]]??this.description.en:m.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[S[t]]??this.slug.en:m.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:{...this.pricing}}getAttributes(){return m.deepClone(this.attributes)}getVariants(){return this.variants.map(t=>({sku:t.sku,selectionAttributes:m.deepClone(t.selectionAttributes),images:{primary:t.images.primary,gallery:[...t.images.gallery]}}))}getImagesBySelectionAttributes(t){let e=n.generateSelectionAttributesKey(t),i=this.variants.find(r=>n.generateSelectionAttributesKey(r.selectionAttributes)===e);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(t,e){switch(e){case"PRIMARY":return this.getImagesBySelectionAttributes(t)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(t)?.gallery??[];default:return this.getImagesBySelectionAttributes(t)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return m.deepClone(this.categories)}getSpecifications(t){return t?m.deepClone(this.specifications[t]??this.specifications[S[t]]??this.specifications.en):m.deepClone(this.specifications)}getSearchTags(t){return t?m.deepClone(this.searchTags[t]??this.searchTags[S[t]]??this.searchTags.en):m.deepClone(this.searchTags)}getDetails(){let t=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((e,i)=>(this.pricing[i]&&(e[i]=this.pricing[i]?.getDetails()),e),{}),attributes:this.getAttributes(),variants:this.variants.map(e=>({sku:e.sku,selectionAttributes:m.deepClone(e.selectionAttributes),images:{primary:e.images.primary.getDetails(),gallery:e.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...t}}checkSelectionAttributes(t){if(!t||typeof t!="object")throw new D("Selection attributes are required");Object.keys(this.attributes).forEach(e=>{if(e.toLowerCase()==="size")return;let i=this.attributes[e],r=t[e];if(r===void 0)throw new D(`Selection attribute '${e}' is missing`);if(typeof i=="string"){if(typeof r!="string"||i!==r)throw new D(`Selection attribute '${e}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof r!="string"||!i.includes(r))throw new D(`Selection attribute '${e}' is invalid`)}else if(typeof r!="object"||!("name"in r)||i.findIndex(o=>o.name===r.name)<0)throw new D(`Selection attribute '${e}' is invalid`)}});}validateSelectionAttribute(t){let e=n.generateSelectionAttributesKey(t);return this.variants.some(i=>n.generateSelectionAttributesKey(i.selectionAttributes)===e)}validateSize(t){return this.attributes.size.includes(t)}};var O=class extends M{id;firstName;lastName;company;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(t,e=new Date){super(t,e),this.id=t.id,this.firstName=t.firstName,this.lastName=t.lastName||"",this.company=t.company||"",this.phone=t.phone,this.email=t.email,this.addressLine1=t.addressLine1,this.addressLine2=t.addressLine2||"",this.city=t.city,this.postalCode=t.postalCode,this.state=t.state,this.country=t.country,this.isBillingAddress=t.isBillingAddress,this.isShippingAddress=t.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),company:this.getCompany(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getCompany(){return this.company}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(t){return t==="shipping"||t==="billing&shipping"}static checkIfBillingAddress(t){return t==="billing"||t==="billing&shipping"}};var $=class extends B{taxRuleId;taxCategory;taxSystem;taxSubSystem;country;rate;minPrice;maxPrice;excludeMin;excludeMax;effectiveFrom;effectiveTo;constructor(t){super(t),this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxSubSystem=t.taxSubSystem,this.taxCategory=t.taxCategory,this.country=t.country,this.rate=t.rate,this.minPrice=new s(t.minPrice),this.maxPrice=t.maxPrice?new s(t.maxPrice):void 0,this.excludeMin=t.excludeMin??!1,this.excludeMax=t.excludeMax??!1,this.effectiveFrom=new Date(t.effectiveFrom).toISOString(),this.effectiveTo=t.effectiveTo?new Date(t.effectiveTo).toISOString():void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getRate(){return this.rate}getMinPrice(){return this.minPrice}getMaxPrice(){return this.maxPrice}getExcludeMin(){return this.excludeMin}getExcludeMax(){return this.excludeMax}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),rate:this.getRate(),minPrice:this.getMinPrice().getDetails(),maxPrice:this.getMaxPrice()?.getDetails(),excludeMin:this.getExcludeMin(),excludeMax:this.getExcludeMax(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0,customFields:this.getAllCustomFields()}}appliesTo(t,e,i,r=new Date){let o=!i||(this.excludeMin?this.minPrice.compareTo(i)<0:this.minPrice.compareTo(i)<=0)&&(this.maxPrice?this.excludeMax?this.maxPrice.compareTo(i)>0:this.maxPrice.compareTo(i)>=0:!0);return this.taxCategory===t&&this.country===e&&o&&Date.parse(this.effectiveFrom)<=r.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=r.getTime():!0)}getApplicableTaxRate(t){return this.appliesTo(this.taxCategory,this.country,t)?this.rate:0}calculateTax(t){return this.appliesTo(this.taxCategory,this.country,t)?t.multiply(this.rate):t.zero()}static getTaxRateDisplayString(t,e,i){let r=e*100,o=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,"");return i?.percentageOnly?`${o}%`:t.getTaxSystem()==="GST"?`${t.getTaxSubSystem()} ${o}%`:`${t.getTaxSystem()} ${o}%`}};var V=class extends B{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=m.deepClone(t.selectionAttributes),this.name=m.deepClone(t.name),this.specifications=m.deepClone(t.specifications),this.primaryImage=new R(t.primaryImage),this.subItems=m.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new _(i.size);e.add(i.size);}),this.pricing={unitPrice:new s(t.pricing.unitPrice),tierPricing:new j(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(i=>new $(i))},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,unitPrice:new s(t.total.unitPrice),subtotal:new s(t.total.subtotal),discountTotal:new s(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([i,r])=>[i,new s(r)])),netUnitPrice:new s(t.total.netUnitPrice),netSubtotal:new s(t.total.netSubtotal),taxTotal:new s(t.total.taxTotal),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:new s(r.taxableUnitPrice),taxPerUnit:new s(r.taxPerUnit),taxAmount:new s(r.taxAmount),system:r.system,subSystem:r.subSystem}])),grandTotal:new s(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return m.deepClone(this.selectionAttributes)}getName(t){return t?m.deepClone(this.name[t]??this.name[S[t]]??this.name.en):m.deepClone(this.name)}getSpecifications(t){return t?m.deepClone(this.specifications[t]??this.specifications[S[t]]??this.specifications.en):m.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return m.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getState(){return this.state}getTotal(){return {quantity:this.total.quantity,unitPrice:this.total.unitPrice,subtotal:this.total.subtotal,discountTotal:this.total.discountTotal,discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([t,e])=>[t,e])),netUnitPrice:this.total.netUnitPrice,netSubtotal:this.total.netSubtotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableUnitPrice:e.taxableUnitPrice,taxPerUnit:e.taxPerUnit,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),grandTotal:this.total.grandTotal}}getDetails(){let t=this.getPricing(),e=this.getTotal();return {id:this.getId(),productKey:this.getProductKey(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:t.unitPrice.getDetails(),tierPricing:t.tierPricing.getDetails(),taxCategory:t.taxCategory,applicableTaxRule:t.applicableTaxRule.map(i=>i.getDetails())},state:this.getState(),total:{quantity:e.quantity,unitPrice:e.unitPrice.getDetails(),subtotal:e.subtotal.getDetails(),discountTotal:e.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(e.discountBreakdown).map(([i,r])=>[i,r.getDetails()])),netUnitPrice:e.netUnitPrice.getDetails(),netSubtotal:e.netSubtotal.getDetails(),taxTotal:e.taxTotal.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(e.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:r.taxableUnitPrice.getDetails(),taxPerUnit:r.taxPerUnit.getDetails(),taxAmount:r.taxAmount.getDetails(),system:r.system,subSystem:r.subSystem}])),grandTotal:e.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(o=>o.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity>0),this.calculateTotals();}updateProductData(t,e,i){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new et;if(!t.getIsActive())throw new it;this.subItems.forEach(d=>{if(!t.validateSize(d.size))throw new rt});let r=t.getPriceDetails(e);if(!r||r.getBaseUnitPrice().getCurrency()!==i)throw new nt;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let o=this.subItems.reduce((d,g)=>d+g.quantity,0),{unitPrice:a}=r.getApplicableTier(o);this.pricing={unitPrice:a,tierPricing:r,taxCategory:r.getTaxCategory(),applicableTaxRule:this.pricing.applicableTaxRule},this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discountBreakdown=e,this.calculateTotals();}updateTax(t){t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new F}),this.pricing.applicableTaxRule=t,this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((h,C)=>h+C.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,unitPrice:t,subtotal:t,discountTotal:t,discountBreakdown:{},netUnitPrice:t,netSubtotal:t,taxTotal:t,taxBreakdown:{},grandTotal:t};return}let{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),r=i.multiply(e),o=Object.values(this.total.discountBreakdown).reduce((h,C)=>h.add(C),t),a=r.subtract(o),d=e>0?a.divide(e):t,g={},c=t;this.pricing.applicableTaxRule.forEach(h=>{let C=h.getApplicableTaxRate(d),I=h.calculateTax(d),P=I.multiply(e).round();g[h.getTaxRuleId()]={rate:C,taxableUnitPrice:d,taxPerUnit:I,taxAmount:P,system:h.getTaxSystem(),subSystem:h.getTaxSubSystem()},c=c.add(P);});let u=a.add(c);this.total={quantity:e,unitPrice:i,subtotal:r,discountTotal:o,discountBreakdown:this.total.discountBreakdown,netUnitPrice:d,netSubtotal:a,taxTotal:c,taxBreakdown:g,grandTotal:u};}updateState(t){if(this.state in pt)this.state!==t&&(this.state=t);else throw new W(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new R({sources:{original:""}}),this.subItems=[],this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[]},this.total={quantity:0,unitPrice:t,subtotal:t,discountTotal:t,discountBreakdown:{},netUnitPrice:t,netSubtotal:t,taxTotal:t,taxBreakdown:{},grandTotal:t};}};var J=class extends M{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(t,e=new Date){if(super(t,e),this.couponCode=t.couponCode,this.name=m.deepClone(t.name),this.description=m.deepClone(t.description),this.type=t.type,this.customerId=t.customerId,this.validFrom=t.validFrom&&Date.parse(t.validFrom)?new Date(t.validFrom).toISOString():e.toISOString(),this.validTo=t.validTo&&Date.parse(t.validTo)?new Date(t.validTo).toISOString():e.toISOString(),this.minCartValue=Object.keys(t.minCartValue).reduce((i,r)=>{let o=t.minCartValue[r];return o&&(i[r]=new s(o)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,r)=>{let o=t.maxCartDiscount[r];return o&&(i[r]=new s(o)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new A("Percentage value cannot be greater than 100");this.applicableTo=t.applicableTo,this.category=t.category;}getCode(){return this.couponCode}getName(t){return t?this.name[t]??this.name[S[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[S[t]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(t){return t?this.minCartValue[t]:{...this.minCartValue}}getMaxCartDiscount(t){return t?this.maxCartDiscount[t]:{...this.maxCartDiscount}}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:Object.keys(this.getMinCartValue()).reduce((t,e)=>{let i=this.getMinCartValue(e);return i&&(t[e]=i.getDetails()),t},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((t,e)=>{let i=this.getMaxCartDiscount(e);return i&&(t[e]=i.getDetails()),t},{}),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(t){return this.applicableTo==="all"||this.applicableTo==="ftb"&&t}calculateApplicableCouponDiscount(t,e,i,r,o=!0){let a=new s({amount:0,currency:r}),d;if(o&&!this.isActive())return a;let g=this.getMinCartValue(i),c=this.getMaxCartDiscount(i);if(!g||g.compareTo(t)>0||!c)return a;let u=this.getCategory(),h=this.getDiscountMethod(),C=u==="SHIPPING"?e:t;if(C.getAmount()<=0)return a;switch(h){case"flat":let P=c;d=C.min(P);break;case"percentage":d=C.multiply(this.getPercentageValue()/100).round();break;default:return a}return d.min(c)}};var G=class extends B{id;name;type;category;impact;pricing;lineItemId;total;constructor(t){if(super(t),this.id=t.id,this.name=t.name,this.type=t.type,this.category=t.category,this.impact=t.impact,this.lineItemId=t.lineItemId,this.pricing={baseChargeAmount:new s(t.pricing.baseChargeAmount),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(e=>new $(e))},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new Z("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={chargeAmount:new s(t.total.chargeAmount),discountTotal:new s(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([e,i])=>[e,new s(i)])),netChargeAmount:new s(t.total.netChargeAmount),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxableAmount:new s(i.taxableAmount),taxAmount:new s(i.taxAmount),system:i.system,subSystem:i.subSystem}])),taxTotal:new s(t.total.taxTotal),grandTotal:new s(t.total.grandTotal)};}getId(){return this.id}getName(t){return t?m.deepClone(this.name[t]??this.name[S[t]]??this.name.en):m.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getPricing(){return {baseChargeAmount:this.pricing.baseChargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {chargeAmount:this.total.chargeAmount,discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},netChargeAmount:this.total.netChargeAmount,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableAmount:e.taxableAmount,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(t){if(this.type==="ADJUSTMENT"&&t.length>0)throw new Z("Adjustment charges cannot apply tax rules.");t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new F}),this.validateTaxRules(t),this.pricing.applicableTaxRule=t,this.calculateTotals();}validateTaxRules(t){if(this.impact==="SUBTRACT"&&t.some(e=>e.getRate()>0))throw new Y("Subtractive charges cannot have positive tax rates.");for(let e=0;e<t.length;e++)for(let i=e+1;i<t.length;i++){let r=t[e],o=t[i],a=r.getMinPrice(),d=r.getMaxPrice(),g=r.getExcludeMin(),c=r.getExcludeMax(),u=o.getMinPrice(),h=o.getMaxPrice(),C=o.getExcludeMin(),I=o.getExcludeMax(),P=(()=>{if(!d)return !1;let y=d.compareTo(u);return y<0||y===0&&(c||C)})(),w=(()=>{if(!h)return !1;let y=h.compareTo(a);return y<0||y===0&&(I||g)})();if(!(P||w)&&!(a.compareTo(u)===0&&g===C&&c===I&&(!d&&!h||d&&h&&d.compareTo(h)===0)))throw new Y(`Overlapping rules found: [${r.getTaxRuleId()}: ${g?"(":"["}${a.getAmount()}-${d?.getAmount()??"Infinity"}${c?")":"]"}] and [${o.getTaxRuleId()}: ${C?"(":"["}${u.getAmount()}-${h?.getAmount()??"Infinity"}${I?")":"]"}]`)}}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discountBreakdown=e,this.calculateTotals();}calculateTotals(){let t=this.pricing.baseChargeAmount.zero(),e=this.pricing.baseChargeAmount,i=Object.values(this.total.discountBreakdown).reduce((x,y)=>x.add(y),t),r=e.subtract(i),o={},a=this.pricing.applicableTaxRule.reduce((x,y)=>x+y.getApplicableTaxRate(r),0);if(a<=0){this.total={chargeAmount:e,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:r,taxTotal:t,taxBreakdown:{},grandTotal:r};return}let d=e.getCurrency(),g=e.getAmount(),c=1e3,u=s.getRoundedAmount(g/(1+a),d),h=u,C=Number.POSITIVE_INFINITY;for(let x=0;x<c;x++){let y=new s({amount:u,currency:d}),U=this.pricing.applicableTaxRule.sort((l,p)=>p.getApplicableTaxRate(y)-l.getApplicableTaxRate(y)).map(l=>s.getRoundedAmount(u*l.getApplicableTaxRate(y),d)).reduce((l,p)=>l+p,0),v=u+U-g,mt=this.pricing.applicableTaxRule.reduce((l,p)=>l+p.getApplicableTaxRate(y),0);if(Math.abs(v)<Math.abs(C)&&(C=v,h=u),v===0||(u=u-v/(1+mt),u<0||u>g))break}let I=new s({amount:h,currency:d}),P=t;this.pricing.applicableTaxRule.sort((x,y)=>y.getApplicableTaxRate(I)-x.getApplicableTaxRate(I)).forEach(x=>{let y=x.getApplicableTaxRate(I),K=s.getRoundedAmount(h*y,d),U=new s({amount:K,currency:d});o[x.getTaxRuleId()]={rate:y,taxableAmount:I,taxAmount:U,system:x.getTaxSystem(),subSystem:x.getTaxSubSystem()},P=P.add(U);});let w=e;this.total={chargeAmount:e,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:w,taxBreakdown:o,taxTotal:P,grandTotal:w};}getDetails(){return {id:this.id,name:m.deepClone(this.name),type:this.type,category:this.category,pricing:{baseChargeAmount:this.pricing.baseChargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(e=>e.getDetails())},impact:this.impact,lineItemId:this.lineItemId,total:{chargeAmount:this.total.chargeAmount.getDetails(),discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([e,i])=>[e,i.getDetails()])),netChargeAmount:this.total.netChargeAmount.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxableAmount:i.taxableAmount.getDetails(),taxAmount:i.taxAmount.getDetails(),system:i.system,subSystem:i.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};var X=class extends M{id;customerId;customerEmail;anonymousId;lineItems;charges;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,e=new Date){super(t,e),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(i=>new V(i)),this.charges=(t.charges??[]).map(i=>new G(i)),this.billingAddress=t.billingAddress?new O(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new O(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new J(i)),this.shippingDetails=t.shippingDetails?m.deepClone(t.shippingDetails):null,this.total={lineItemSubtotal:new s(t.total.lineItemSubtotal),netLineItemSubtotal:new s(t.total.netLineItemSubtotal),lineItemTaxTotal:new s(t.total.lineItemTaxTotal),lineItemTaxBreakdown:this.mapTaxBreakdown(t.total.lineItemTaxBreakdown),additiveCharges:new s(t.total.additiveCharges),netAdditiveCharges:new s(t.total.netAdditiveCharges),additiveChargesTaxTotal:new s(t.total.additiveChargesTaxTotal),additiveChargesTaxBreakdown:this.mapTaxBreakdown(t.total.additiveChargesTaxBreakdown),adjustmentCharges:new s(t.total.adjustmentCharges),shippingCharges:new s(t.total.shippingCharges),netShippingCharges:new s(t.total.netShippingCharges),discountTotal:new s(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([i,r])=>[i,new s(r)])),taxTotal:new s(t.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(t.total.taxBreakdown),grandTotal:new s(t.total.grandTotal)};}mapTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,i])=>[e,{system:i.system,totalAmount:new s(i.totalAmount),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,o])=>[r,new s(o)]))}]))}serializeTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,i])=>[e,{system:i.system,totalAmount:i.totalAmount.getDetails(),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,o])=>[r,o.getDetails()]))}]))}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new V(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(t=>new G(t.getDetails()))}addCharge(t){this.charges.push(t),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?m.deepClone(this.shippingDetails):null}getShippingAddress(){return this.shippingAddress?new O(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new O(this.billingAddress.getDetails()):null}getCoupons(){return [...this.coupons]}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {lineItemSubtotal:this.total.lineItemSubtotal,netLineItemSubtotal:this.total.netLineItemSubtotal,lineItemTaxTotal:this.total.lineItemTaxTotal,lineItemTaxBreakdown:Object.fromEntries(Object.entries(this.total.lineItemTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),additiveCharges:this.total.additiveCharges,netAdditiveCharges:this.total.netAdditiveCharges,additiveChargesTaxTotal:this.total.additiveChargesTaxTotal,additiveChargesTaxBreakdown:Object.fromEntries(Object.entries(this.total.additiveChargesTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),adjustmentCharges:this.total.adjustmentCharges,shippingCharges:this.total.shippingCharges,netShippingCharges:this.total.netShippingCharges,discountBreakdown:{...this.total.discountBreakdown},discountTotal:this.total.discountTotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),grandTotal:this.total.grandTotal}}getDetails(){let t=this.getTotal();return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(e=>e.getDetails()),charges:this.getCharges().map(e=>e.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(e=>e.getDetails()),total:{lineItemSubtotal:t.lineItemSubtotal.getDetails(),netLineItemSubtotal:t.netLineItemSubtotal.getDetails(),lineItemTaxTotal:t.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(t.lineItemTaxBreakdown),additiveCharges:t.additiveCharges.getDetails(),netAdditiveCharges:t.netAdditiveCharges.getDetails(),additiveChargesTaxTotal:t.additiveChargesTaxTotal.getDetails(),additiveChargesTaxBreakdown:this.serializeTaxBreakdown(t.additiveChargesTaxBreakdown),adjustmentCharges:t.adjustmentCharges.getDetails(),shippingCharges:t.shippingCharges.getDetails(),netShippingCharges:t.netShippingCharges.getDetails(),discountTotal:t.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(t.discountBreakdown).map(([e,i])=>[e,i.getDetails()])),taxTotal:t.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(t.taxBreakdown),grandTotal:t.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new s({amount:0,currency:this.currency}),e=this.lineItems.filter(l=>l.getState()!=="CANCELLED"),i=e.reduce((l,p)=>l.add(p.getTotal().subtotal),t),r=this.charges.filter(l=>l.getType()==="SHIPPING").reduce((l,p)=>l.add(p.getTotal().chargeAmount),t);this.total.lineItemSubtotal=i,this.total.shippingCharges=r;let o=t,a={},d={};this.coupons.forEach(l=>{let p=l.calculateApplicableCouponDiscount(i,r,this.country,this.currency);o=o.add(p),a[l.getCode()]=p,l.getCategory()!=="SHIPPING"&&(d[l.getCode()]=p);}),this.total.discountTotal=o,this.total.discountBreakdown=a,this.applyDiscountsInLineItem(d);let g=this.coupons.find(l=>l.getCategory()==="SHIPPING");g?this.applyDiscountsInShippingCharges({[g.getCode()]:a[g.getCode()]||t}):this.applyDiscountsInShippingCharges({});let c=this.lineItems.reduce((l,p)=>l.add(p.getTotal().netSubtotal),t),u=this.charges.filter(l=>l.getType()==="SHIPPING").reduce((l,p)=>l.add(p.getTotal().grandTotal),t);this.total.netLineItemSubtotal=c,this.total.netShippingCharges=u;let h=this.charges.filter(l=>l.getImpact()==="ADD").reduce((l,p)=>l.add(p.getTotal().chargeAmount),t),C=this.charges.filter(l=>l.getImpact()==="ADD").reduce((l,p)=>l.add(p.getTotal().grandTotal),t),I=this.charges.filter(l=>l.getImpact()==="SUBTRACT").reduce((l,p)=>l.add(p.getTotal().grandTotal),t),P=t,w=t,x=t,y={},K={},U={},v=(l,p)=>{Object.entries(l).forEach(([Kt,N])=>{let T=N.system,k=N.subSystem;p[T]||(p[T]={system:T,totalAmount:t,subSystems:{}}),p[T].subSystems[k]?p[T].subSystems[k]=p[T].subSystems[k].add(N.taxAmount):p[T].subSystems[k]=N.taxAmount,p[T].totalAmount=p[T].totalAmount.add(N.taxAmount),y[T]||(y[T]={system:T,totalAmount:t,subSystems:{}}),y[T].subSystems[k]?y[T].subSystems[k]=y[T].subSystems[k].add(N.taxAmount):y[T].subSystems[k]=N.taxAmount,y[T].totalAmount=y[T].totalAmount.add(N.taxAmount);});};e.forEach(l=>{let p=l.getTotal().taxBreakdown;p&&(v(p,K),v(p,y),w=w.add(l.getTotal().taxTotal));}),this.charges.forEach(l=>{let p=l.getTotal().taxBreakdown;p&&(v(p,U),v(p,y),x=x.add(l.getTotal().taxTotal));}),P=w.add(x);let mt=c.add(w).add(C).subtract(I);this.total={lineItemSubtotal:i,netLineItemSubtotal:c,lineItemTaxTotal:w,lineItemTaxBreakdown:K,additiveCharges:h,netAdditiveCharges:C,additiveChargesTaxTotal:x,additiveChargesTaxBreakdown:U,adjustmentCharges:I,shippingCharges:r,netShippingCharges:u,discountTotal:o,discountBreakdown:a,taxTotal:P,taxBreakdown:y,grandTotal:mt};}updateShippingDetails(t){this.shippingDetails=t;}applyCoupons(t){let e=t.filter(r=>r.getCategory()==="SHIPPING"),i=t.filter(r=>r.getCategory()!=="SHIPPING");this.coupons=[],this.total.discountTotal=this.total.lineItemSubtotal.zero(),this.total.discountBreakdown={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.discountBreakdown),e.length&&this.applyShippingCoupons(e),this.calculateTotals();}applyDiscountsInLineItem(t){let e=Array.from(Object.entries(t)).filter(r=>!r[1].isZero()),i=new Map;this.lineItems.forEach(r=>i.set(r.getId(),[])),e.forEach(([r,o])=>{let a=this.coupons.find(c=>c.getCode()===r);if(!a||o.isZero())return;let d=this.lineItems.filter(c=>c.getState()!=="CANCELLED"&&!c.getTotal().subtotal.isZero()).sort((c,u)=>c.getTotal().subtotal.compareTo(u.getTotal().subtotal)),g=new s({amount:0,currency:this.currency});d.forEach((c,u)=>{let h;u===d.length-1?h=o.subtract(g):h=o.multiply(c.getTotal().subtotal).divide(this.total.lineItemSubtotal).round(),g=g.add(h),i.get(c.getId())?.push({coupon:a,amount:h});});}),this.lineItems.forEach(r=>{r.getState()==="CANCELLED"||this.total.lineItemSubtotal.isZero()?r.updateDiscounts([]):r.updateDiscounts(i.get(r.getId())||[]);});}applyDiscountsInShippingCharges(t){let e=Array.from(Object.entries(t)).filter(o=>!o[1].isZero()),i=this.charges.filter(o=>o.getType()==="SHIPPING"),r=new Map;i.forEach(o=>r.set(o.getId(),[])),e.forEach(([o,a])=>{let d=this.coupons.find(u=>u.getCode()===o);if(!d||a.isZero())return;let g=i.sort((u,h)=>u.getTotal().grandTotal.compareTo(h.getTotal().grandTotal)),c=new s({amount:0,currency:this.currency});g.forEach((u,h)=>{let C;h===g.length-1?C=a.subtract(c):C=a.multiply(u.getTotal().chargeAmount).divide(this.total.shippingCharges).round(),c=c.add(C),r.get(u.getId())?.push({coupon:d,amount:C});});}),i.forEach(o=>{o.updateDiscounts(r.get(o.getId())||[]);});}applyNonShippingCoupons(t){let e=t.filter(i=>i.getType()==="coupon");if(e.length===1){let i=e[0].calculateApplicableCouponDiscount(this.total.lineItemSubtotal,this.total.shippingCharges,this.country,this.currency);i.getAmount()>0&&(this.coupons.push(e[0]),this.total.discountTotal=i,this.total.discountBreakdown[e[0].getCode()]=i);}}applyShippingCoupons(t){if(this.total.shippingCharges.getAmount()>0&&t.length>0){let e=this.total.lineItemSubtotal.subtract(this.total.discountTotal),i=t.reduce((o,a)=>{if(!o)return a;let d=a.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency).min(this.total.shippingCharges),g=o.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency).min(this.total.shippingCharges);return d.compareTo(g)===0?a.getType()==="coupon"?a:o:d.compareTo(g)>0?a:o}),r=i.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency).min(this.total.shippingCharges);r.getAmount()>0&&(this.coupons.push(i),this.total.discountTotal=this.total.discountTotal.add(r),this.total.discountBreakdown[i.getCode()]=r);}}};var Vt=(r=>(r.ACTIVE="ACTIVE",r.FROZEN="FROZEN",r.MERGED="MERGED",r.ORDERED="ORDERED",r))(Vt||{}),Gt={expiresAtInSeconds:120*24*60*60},Tt=class extends X{state;expireAt;config;constructor(t,e=new Date,i=Gt){super(t,e),this.state=t.state,this.expireAt=t.expireAt&&typeof t.expireAt=="number"?t.expireAt:Math.floor(e.getTime()/1e3)+i.expiresAtInSeconds,this.config=i;}getState(){return this.state}getExpireAt(){return this.expireAt}isActive(){let t=Math.ceil(Date.now()/1e3);return this.state==="ACTIVE"&&this.expireAt>t}clearCartItems(){this.lineItems=[],this.charges=[],this.coupons=[],this.shippingDetails=null,this.calculateTotals();}validateLineItems(t){this.lineItems=this.lineItems.map(e=>{try{e.updateProductData(t[e.getProductKey()],this.country,this.currency);}catch(i){console.error(`Error recalculating line item ${e.getId()}:`,i),e.clearLineItem();}return e}).filter(e=>e.getId()),this.calculateTotals();}addLineItem(t){let e=t.getProductKey(),i=t.getSelectionAttributes(),r=E.generateSelectionAttributesKey(i),o=this.lineItems.findIndex(a=>a.getProductKey()===e&&E.generateSelectionAttributesKey(a.getSelectionAttributes())===r);return o>=0?this.lineItems[o].addSubItems(t.getSubItems(),!0):this.lineItems.push(t),this.calculateTotals(),o>=0?o:this.lineItems.length-1}updateLineItem(t,e,i){let r=this.lineItems,o=r.findIndex(a=>a.getId()===t);if(o<0)throw new q(t);return r[o].addSubItems([{size:e,quantity:i}],!1),this.calculateTotals(),o}removeLineItem(t){let i=this.lineItems.findIndex(r=>r.getId()===t);if(i<0)throw new q(t);return this.lineItems.splice(i,1),this.charges=this.charges.filter(r=>r.getLineItemId()!==t),this.calculateTotals(),i}getDetails(){return {...super.getDetails(),state:this.getState(),expireAt:this.getExpireAt()}}};exports.CartState=Vt;exports.DEFAULT_CART_CONFIG=Gt;exports.default=Tt;//# sourceMappingURL=Cart.js.map
|
|
2
2
|
//# sourceMappingURL=Cart.js.map
|