b23-lib 3.0.5 → 3.0.6

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.
Files changed (41) hide show
  1. package/dist/Classes/Cart.js +1 -1
  2. package/dist/Classes/Cart.js.map +1 -1
  3. package/dist/Classes/Cart.mjs +1 -1
  4. package/dist/Classes/Charge.js +1 -1
  5. package/dist/Classes/Charge.js.map +1 -1
  6. package/dist/Classes/Charge.mjs +1 -1
  7. package/dist/Classes/LineItem.js +1 -1
  8. package/dist/Classes/LineItem.js.map +1 -1
  9. package/dist/Classes/LineItem.mjs +1 -1
  10. package/dist/Classes/Order.js +1 -1
  11. package/dist/Classes/Order.js.map +1 -1
  12. package/dist/Classes/Order.mjs +1 -1
  13. package/dist/Classes/ShoppingContainer.js +1 -1
  14. package/dist/Classes/ShoppingContainer.js.map +1 -1
  15. package/dist/Classes/ShoppingContainer.mjs +1 -1
  16. package/dist/Classes/TaxRule.d.mts +4 -8
  17. package/dist/Classes/TaxRule.d.ts +4 -8
  18. package/dist/Classes/TaxRule.js +1 -1
  19. package/dist/Classes/TaxRule.js.map +1 -1
  20. package/dist/Classes/TaxRule.mjs +1 -1
  21. package/dist/{chunk-GF3OGUDE.mjs → chunk-52Y5EI7O.mjs} +2 -2
  22. package/dist/chunk-52Y5EI7O.mjs.map +1 -0
  23. package/dist/chunk-6VRUVGN3.mjs +2 -0
  24. package/dist/chunk-6VRUVGN3.mjs.map +1 -0
  25. package/dist/{chunk-4KMF3LE7.mjs → chunk-DLLGHKS5.mjs} +2 -2
  26. package/dist/chunk-DLLGHKS5.mjs.map +1 -0
  27. package/dist/chunk-YKRWZ24N.mjs +2 -0
  28. package/dist/chunk-YKRWZ24N.mjs.map +1 -0
  29. package/package.json +1 -11
  30. package/dist/Classes/TaxCategory.d.mts +0 -42
  31. package/dist/Classes/TaxCategory.d.ts +0 -42
  32. package/dist/Classes/TaxCategory.js +0 -2
  33. package/dist/Classes/TaxCategory.js.map +0 -1
  34. package/dist/Classes/TaxCategory.mjs +0 -2
  35. package/dist/Classes/TaxCategory.mjs.map +0 -1
  36. package/dist/chunk-2HBQ3C6V.mjs +0 -2
  37. package/dist/chunk-2HBQ3C6V.mjs.map +0 -1
  38. package/dist/chunk-4KMF3LE7.mjs.map +0 -1
  39. package/dist/chunk-GF3OGUDE.mjs.map +0 -1
  40. package/dist/chunk-SNDTKUMW.mjs +0 -2
  41. package/dist/chunk-SNDTKUMW.mjs.map +0 -1
@@ -1,2 +1,2 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var At=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var At__default=/*#__PURE__*/_interopDefault(At);var G=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}},Q=class extends Error{constructor(t){super(`Invalid line item state: ${t}`),this.name="InvalidLineItemStateError";}},Z=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},Y=class extends Error{constructor(t){super(`Duplicate selection attribute found: ${t}`),this.name="DuplicateSelectionAttributeError";}},J=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},W=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},A=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},X=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},_=class extends Error{constructor(t="Pricing details not available for the product"){super(`NotFound: ${t}`),this.name="PricingNotFoundError";}},U=class extends Error{constructor(t="Tax rule category mismatch."){super(`InvalidTaxRule: ${t}`),this.name="InvalidTaxRuleError";}},tt=class extends Error{constructor(t="Tax category is not valid."){super(`InvalidTaxCategory: ${t}`),this.name="InvalidTaxCategoryError";}},et=class extends Error{constructor(t="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${t}`),this.name="InvalidMinQuantityError";}},it=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},rt=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},ot=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}},st=class extends Error{constructor(t="No applicable tax slab or multiple slabs found for the given unit price."){super(`TaxSlabNotFound: ${t}`),this.name="TaxSlabNotFoundError";}},$=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},O=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},w=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},C=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},j=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}};var at=new Uint8Array(256),nt=at.length;function pt(){return nt>at.length-16&&(At__default.default.randomFillSync(at),nt=0),at.slice(nt,nt+=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 Mt(o){return typeof o=="string"&&ft.test(o)}var Tt=Mt;var T=[];for(let o=0;o<256;++o)T.push((o+256).toString(16).slice(1));function ct(o,t=0){return T[o[t+0]]+T[o[t+1]]+T[o[t+2]]+T[o[t+3]]+"-"+T[o[t+4]]+T[o[t+5]]+"-"+T[o[t+6]]+T[o[t+7]]+"-"+T[o[t+8]]+T[o[t+9]]+"-"+T[o[t+10]]+T[o[t+11]]+T[o[t+12]]+T[o[t+13]]+T[o[t+14]]+T[o[t+15]]}function wt(o){if(!Tt(o))throw TypeError("Invalid UUID");let t,e=new Uint8Array(16);return e[0]=(t=parseInt(o.slice(0,8),16))>>>24,e[1]=t>>>16&255,e[2]=t>>>8&255,e[3]=t&255,e[4]=(t=parseInt(o.slice(9,13),16))>>>8,e[5]=t&255,e[6]=(t=parseInt(o.slice(14,18),16))>>>8,e[7]=t&255,e[8]=(t=parseInt(o.slice(19,23),16))>>>8,e[9]=t&255,e[10]=(t=parseInt(o.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 Ct=wt;function Lt(o){o=unescape(encodeURIComponent(o));let t=[];for(let e=0;e<o.length;++e)t.push(o.charCodeAt(e));return t}var Rt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Et="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function mt(o,t,e){function i(r,s,a,u){var l;if(typeof r=="string"&&(r=Lt(r)),typeof s=="string"&&(s=Ct(s)),((l=s)===null||l===void 0?void 0:l.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(s),c.set(r,s.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,a){u=u||0;for(let d=0;d<16;++d)a[u+d]=c[d];return a}return ct(c)}try{i.name=o;}catch{}return i.DNS=Rt,i.URL=Et,i}var ht={randomUUID:At__default.default.randomUUID};function Bt(o,t,e){if(ht.randomUUID&&!t&&!o)return ht.randomUUID();o=o||{};let i=o.random||(o.rng||pt)();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 ct(i)}var yt=Bt;function Ut(o){return Array.isArray(o)?o=Buffer.from(o):typeof o=="string"&&(o=Buffer.from(o,"utf8")),At__default.default.createHash("sha1").update(o).digest()}var It=Ut;var Ot=mt("v5",80,It),bt=Ot;var kt={isUUID:o=>/^[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(o),isEmail:o=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(o),isURL:o=>/^(http|https):\/\/[^ "]+$/.test(o),generateUUID:(o,t)=>t&&o?bt(o,t):yt(),generateSearchId:(o,t)=>`${o}#${L.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:o=>{let[t,e]=o.split("#");return {key:t,selectionAttributes:L.parseSelectionAttributesKey(e)}},deepClone(o){return structuredClone(o)}},g=kt;var N=class{customFields;constructor(t,e=new Date){this.customFields={...t.customFields};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}},M=class extends N{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 P={"en-IN":"en","kn-IN":"kn"};var Pt={INR:"\u20B9"},St={INR:"en-IN"};var lt=(d=>(d.INITIAL="INITIAL",d.PROCESSING="PROCESSING",d.SHIPPED="SHIPPED",d.DELIVERED="DELIVERED",d.CANCELLED="CANCELLED",d.RETURN_REQUESTED="RETURN_REQUESTED",d.RETURNED="RETURNED",d.REFUND_INITIATED="REFUND_INITIATED",d.REFUNDED="REFUNDED",d.ON_HOLD="ON_HOLD",d))(lt||{});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 j("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 j("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 n=class o{#t;amount;currency;constructor(t){if(this.#t="PriceModel",t.amount<0)throw new $("Amount cannot be negative.");if(!t.currency)throw new O("Currency code is required.");this.amount=t.amount,this.currency=t.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}}compareTo(t){if(o.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot compare prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return this.amount-t.getAmount()}add(t){if(o.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot add prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return new o({amount:this.amount+t.getAmount(),currency:this.currency})}subtract(t){if(o.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot subtract prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return new o({amount:this.amount-t.getAmount(),currency:this.currency})}multiply(t){if(o.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot multiply prices in different currencies.");return new o({amount:this.amount*t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>=0)return new o({amount:this.amount*t,currency:this.currency});throw new C("Must be a non-negative number.")}divide(t){if(o.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot divide prices in different currencies.");return new o({amount:this.amount/t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>0)return new o({amount:this.amount/t,currency:this.currency});throw new C("Must be a positive number.")}min(...t){if(t.length===0)throw new C("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(o.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new w("Cannot compare prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i},this)}max(...t){if(t.length===0)throw new C("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(o.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new w("Cannot compare prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return e.compareTo(i)>0?e:i},this)}zero(){return new o({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new o({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return o.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return o.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(t,e,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let r=St[e];if(!e||!r)throw new O("Invalid currency code for formatting.");let s=t,a=i.displayAsInteger?0:o.getDecimalPlaces(e),u={style:i.style??"currency",currency:e,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};i.displayAsInteger&&(s=Math.ceil(s));try{return new Intl.NumberFormat(r,u).format(s)}catch(l){return console.error(`Error formatting price for currency "${e}" and locale "${r}":`,l),`${Pt[e]??e} ${o.addThousandSeparators(s.toFixed(a))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}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 $("Amount cannot be negative for rounding.");if(e===void 0)throw new O("Invalid currency code for rounding.");let i=o.getDecimalPlaces(e),r=Math.pow(10,i);return Math.round(t*r)/r}};var k=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new n(t.baseUnitPrice);if(!t.taxCategory)throw new tt;let i=(t.tiers??[]).map(l=>({minQuantity:l.minQuantity,unitPrice:new n(l.unitPrice)})).sort((l,c)=>l.minQuantity-c.minQuantity);if(i.some(l=>l.minQuantity<=0))throw new et;let s=i.some(l=>l.unitPrice.getCurrency()!==e.getCurrency()),a=i.some((l,c)=>c>0&&l.unitPrice.compareTo(i[c-1].unitPrice)>0),u=i[0]?.unitPrice.compareTo(e)>0;if(s||a||u)throw new it("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}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 rt;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity)return this.tiers[e];throw new ot(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 L=class o 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 A("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[s,a]=r.split(":");a.startsWith("c+")?e[s]={name:a.slice(2)}:e[s]=a;}return e}catch(e){throw new A(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,s)=>(t.pricing[s]&&(r[s]=new k(t.pricing[s])),r),{}),this.targetGender=t.targetGender,this.attributes=g.deepClone(t.attributes),this.specifications=g.deepClone(t.specifications),this.categories=g.deepClone(t.categories);let i=new Set;this.variants=(t.variants||[]).map(r=>{if(!r.selectionAttributes||typeof r.selectionAttributes!="object")throw new A("Selection attributes are required");this.checkSelectionAttributes(r.selectionAttributes);let s=o.generateSelectionAttributesKey(r.selectionAttributes);if(i.has(s))throw new Y(s);return i.add(s),{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?g.deepClone(t.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(t){return t?this.name[t]??this.name[P[t]]??this.name.en:g.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[P[t]]??this.description.en:g.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[P[t]]??this.slug.en:g.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:this.pricing}getAttributes(){return g.deepClone(this.attributes)}getVariants(){return this.variants.map(t=>({sku:t.sku,selectionAttributes:t.selectionAttributes,images:{primary:t.images.primary,gallery:t.images.gallery}}))}getImagesBySelectionAttributes(t){let e=o.generateSelectionAttributesKey(t),i=this.variants.find(r=>o.generateSelectionAttributesKey(r.selectionAttributes)===e);return i?i.images: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 g.deepClone(this.categories)}getSpecifications(t){return t?g.deepClone(this.specifications[t]??this.specifications[P[t]]??this.specifications.en):g.deepClone(this.specifications)}getSearchTags(t){return t?g.deepClone(this.searchTags[t]??this.searchTags[P[t]]??this.searchTags.en):g.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:g.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 A("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 A(`Selection attribute '${e}' is missing`);if(typeof i=="string"){if(typeof r!="string"||i!==r)throw new A(`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 A(`Selection attribute '${e}' is invalid`)}else if(typeof r!="object"||!("name"in r)||i.findIndex(s=>s.name===r.name)<0)throw new A(`Selection attribute '${e}' is invalid`)}});}validateSelectionAttribute(t){let e=o.generateSelectionAttributesKey(t);return this.variants.some(i=>o.generateSelectionAttributesKey(i.selectionAttributes)===e)}validateSize(t){return this.attributes.size.includes(t)}};var B=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 ut=class{taxRuleId;taxCategory;taxSystem;taxSubSystem;taxCountry;effectiveFrom;effectiveTo;constructor(t){this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxSubSystem=t.taxSubSystem,this.taxCategory=t.taxCategory,this.taxCountry=t.taxCountry,this.effectiveFrom=new Date(t.effectiveFrom),this.effectiveTo=t.effectiveTo?new Date(t.effectiveTo):void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getTaxCountry(){return this.taxCountry}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),taxCountry:this.getTaxCountry(),effectiveFrom:this.effectiveFrom.toISOString(),effectiveTo:this.effectiveTo?this.effectiveTo.toISOString():void 0}}appliesTo(t,e,i=new Date){return this.taxCategory===t&&this.taxCountry===e&&this.effectiveFrom<=i&&(this.effectiveTo?this.effectiveTo>=i:!0)}static getTaxRateDisplayString(t,e,i){let r=e*100,s=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,"");return i?.percentageOnly?`${s}%`:t.getTaxSystem()==="GST"?`${s}% ${t.getTaxSubSystem()}`:`${s}% ${t.getTaxSystem()}`}},dt=class o extends ut{slabs;constructor(t){super(t),this.slabs=t.slabs.map(e=>({rate:e.rate,minUnitPrice:new n(e.minUnitPrice),maxUnitPrice:e.maxUnitPrice?new n(e.maxUnitPrice):void 0}));}getSlabs(){return this.slabs}getDetails(){return {...super.getDetails(),slabs:this.getSlabs().map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0}))}}getApplicableTaxRate(t){return o.getApplicableTaxRate(t,this.slabs)}calculateTax(t){let e=this.getApplicableTaxRate(t);return t.multiply(e).round()}static getApplicableTaxRate(t,e){let i=e.filter(r=>(r.minUnitPrice===void 0||t.compareTo(r.minUnitPrice)>=0)&&(r.maxUnitPrice===void 0||t.compareTo(r.maxUnitPrice)<0));if(i.length!==1)throw new st;return i[0].rate}},gt=class extends ut{rate;minUnitPrice;maxUnitPrice;constructor(t){super(t),this.rate=t.rate,this.minUnitPrice=new n(t.minUnitPrice),this.maxUnitPrice=t.maxUnitPrice?new n(t.maxUnitPrice):void 0;}getApplicableTaxRate(){return this.rate}calculateTax(t){let e=this.getApplicableTaxRate();return t.multiply(e).round()}getDetails(){return {...super.getDetails(),rate:this.getApplicableTaxRate(),minUnitPrice:this.minUnitPrice.getDetails(),maxUnitPrice:this.maxUnitPrice?this.maxUnitPrice.getDetails():void 0}}};var F=class extends N{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=g.deepClone(t.selectionAttributes),this.name=g.deepClone(t.name),this.specifications=g.deepClone(t.specifications),this.primaryImage=new R(t.primaryImage),this.subItems=g.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new Z(i.size);e.add(i.size);}),this.pricing={unitPrice:new n(t.pricing.unitPrice),tierPricing:new k(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(i=>new dt(i))},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,unitPrice:new n(t.total.unitPrice),subtotal:new n(t.total.subtotal),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,r])=>[i,new n(r)])),totalDiscount:new n(t.total.totalDiscount),netUnitPrice:new n(t.total.netUnitPrice),netSubtotal:new n(t.total.netSubtotal),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:new n(r.taxableUnitPrice),taxPerUnit:new n(r.taxPerUnit),amount:new n(r.amount),system:r.system,subSystem:r.subSystem}])),taxTotal:new n(t.total.taxTotal),grandTotal:new n(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return g.deepClone(this.selectionAttributes)}getName(t){return t?g.deepClone(this.name[t]??this.name[P[t]]??this.name.en):g.deepClone(this.name)}getSpecifications(t){return t?g.deepClone(this.specifications[t]??this.specifications[P[t]]??this.specifications.en):g.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return g.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,discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,e])=>[t,e])),totalDiscount:this.total.totalDiscount,netUnitPrice:this.total.netUnitPrice,netSubtotal:this.total.netSubtotal,taxBreakdown:this.total.taxBreakdown,taxTotal:this.total.taxTotal,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(),discounts:Object.fromEntries(Object.entries(e.discounts).map(([i,r])=>[i,r.getDetails()])),totalDiscount:e.totalDiscount.getDetails(),netUnitPrice:e.netUnitPrice.getDetails(),netSubtotal:e.netSubtotal.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(e.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:r.taxableUnitPrice.getDetails(),taxPerUnit:r.taxPerUnit.getDetails(),amount:r.amount.getDetails(),system:r.system,subSystem:r.subSystem}])),taxTotal:e.taxTotal.getDetails(),grandTotal:e.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(s=>s.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 J;if(!t.getIsActive())throw new W;this.subItems.forEach(u=>{if(!t.validateSize(u.size))throw new X});let r=t.getPriceDetails(e);if(!r||r.getBaseUnitPrice().getCurrency()!==i)throw new _;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let s=this.subItems.reduce((u,l)=>u+l.quantity,0),{unitPrice:a}=r.getApplicableTier(s);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.discounts=e,this.calculateTotals();}updateTax(t){t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getTaxCountry()))throw new U}),this.pricing.applicableTaxRule=t,this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((h,x)=>h+x.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,unitPrice:t,subtotal:t,discounts:{},totalDiscount:t,netUnitPrice:t,netSubtotal:t,taxBreakdown:{},taxTotal:t,grandTotal:t};return}let{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),r=i.multiply(e),s=Object.values(this.total.discounts).reduce((h,x)=>h.add(x),t),a=r.subtract(s),u=e>0?a.divide(e):t,l={},c=t;this.pricing.applicableTaxRule.forEach(h=>{let x=h.getApplicableTaxRate(u),S=h.calculateTax(u),D=S.multiply(e);l[h.getTaxRuleId()]={rate:x,taxableUnitPrice:u,taxPerUnit:S,amount:D,system:h.getTaxSystem(),subSystem:h.getTaxSubSystem()},c=c.add(D);});let d=a.add(c);this.total={quantity:e,unitPrice:i,subtotal:r,discounts:this.total.discounts,totalDiscount:s,netUnitPrice:u,netSubtotal:a,taxBreakdown:l,taxTotal:c,grandTotal:d};}updateState(t){if(this.state in lt)this.state!==t&&(this.state=t);else throw new Q(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,discounts:{},totalDiscount:t,netUnitPrice:t,netSubtotal:t,taxBreakdown:{},taxTotal:t,grandTotal:t};}};var K=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=g.deepClone(t.name),this.description=g.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 s=t.minCartValue[r];return s&&(i[r]=new n(s)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,r)=>{let s=t.maxCartDiscount[r];return s&&(i[r]=new n(s)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new C("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[P[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[P[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,s=!0){let a=new n({amount:0,currency:r}),u;if(s&&!this.isActive())return a;let l=this.getMinCartValue(i),c=this.getMaxCartDiscount(i);if(!l||l.compareTo(t)>0||!c)return a;let d=this.getCategory(),h=this.getDiscountMethod(),x=d==="SHIPPING"?e:t;if(x.getAmount()<=0)return a;switch(h){case"flat":let D=c;u=x.min(D);break;case"percentage":u=x.multiply(this.getPercentageValue()/100).round();break;default:return a}return u.min(c)}};var z=class extends N{id;name;category;lineItemId;chargeType;pricing;total;constructor(t){super(t),this.id=t.id,this.name=t.name,this.category=t.category,this.lineItemId=t.lineItemId,this.chargeType=t.chargeType,this.pricing={price:new n(t.pricing.price),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(e=>new gt(e))},this.total={price:new n(t.total.price),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([e,i])=>[e,new n(i)])),totalDiscount:new n(t.total.totalDiscount),netPrice:new n(t.total.netPrice),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxablePrice:new n(i.taxablePrice),amount:new n(i.amount),system:i.system,subSystem:i.subSystem}])),taxTotal:new n(t.total.taxTotal),grandTotal:new n(t.total.grandTotal)};}getId(){return this.id}getName(){return this.name}getCategory(){return this.category}getChargeType(){return this.chargeType}getLineItemId(){return this.lineItemId}getPricing(){return this.pricing}getTotal(){return this.total}getApplicableTaxRules(){return this.pricing.applicableTaxRule}updateTax(t){t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getTaxCountry()))throw new U}),this.pricing.applicableTaxRule=t,this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discounts=e,this.calculateTotals();}calculateTotals(){let t=this.pricing.price.zero(),e=this.pricing.price,i=Object.values(this.total.discounts).reduce((b,I)=>b.add(I),t),r=e.subtract(i),s={},a=this.pricing.applicableTaxRule.reduce((b,I)=>b+I.getApplicableTaxRate(),0),u=r.divide(1+a).round(),l=r.subtract(u),c=t,d=this.pricing.applicableTaxRule.reduce((b,I)=>I.getApplicableTaxRate()>b.getApplicableTaxRate()?I:b),h=d.getTaxRuleId();this.pricing.applicableTaxRule.forEach(b=>{if(b.getTaxRuleId()===h)return;let I=b.getApplicableTaxRate(),V=l.multiply(I).divide(a).round();s[b.getTaxRuleId()]={rate:I,taxablePrice:u,amount:V,system:b.getTaxSystem(),subSystem:b.getTaxSubSystem()},c=c.add(V);});let x=l.subtract(c);s[h]={rate:d.getApplicableTaxRate(),taxablePrice:u,amount:x,system:d.getTaxSystem(),subSystem:d.getTaxSubSystem()};let S=u,D=r;this.total={price:e,discounts:this.total.discounts,netPrice:S,totalDiscount:i,taxBreakdown:s,taxTotal:l,grandTotal:D};}getDetails(){return {id:this.id,name:g.deepClone(this.name),category:this.category,lineItemId:this.lineItemId,chargeType:this.chargeType,pricing:{price:this.pricing.price.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(e=>e.getDetails())},total:{price:this.total.price.getDetails(),discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([e,i])=>[e,i.getDetails()])),totalDiscount:this.total.totalDiscount.getDetails(),netPrice:this.total.netPrice.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxablePrice:i.taxablePrice.getDetails(),amount:i.amount.getDetails(),system:i.system,subSystem:i.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};var q=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 F(i)),this.charges=(t.charges??[]).map(i=>new z(i)),this.billingAddress=t.billingAddress?new B(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new B(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new K(i)),this.shippingDetails=t.shippingDetails?g.deepClone(t.shippingDetails):null,this.total={subtotal:new n(t.total.subtotal),netSubtotal:new n(t.total.netSubtotal),lineItemTaxTotal:new n(t.total.lineItemTaxTotal||{amount:0,currency:t.currency}),lineItemTaxBreakdown:this.mapTaxBreakdown(t.total.lineItemTaxBreakdown||{}),chargesTotal:new n(t.total.chargesTotal||{amount:0,currency:t.currency}),shippingCharge:new n(t.total.shippingCharge),netShippingCharge:new n(t.total.netShippingCharge),chargeTaxTotal:new n(t.total.chargeTaxTotal||{amount:0,currency:t.currency}),chargeTaxBreakdown:this.mapTaxBreakdown(t.total.chargeTaxBreakdown||{}),taxTotal:new n(t.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(t.total.taxBreakdown),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,r])=>[i,new n(r)])),totalDiscount:new n(t.total.totalDiscount),grandTotal:new n(t.total.grandTotal)};}mapTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,i])=>[e,{system:i.system,totalAmount:new n(i.totalAmount),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,s])=>[r,new n(s)]))}]))}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,s])=>[r,s.getDetails()]))}]))}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new F(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(t=>new z(t.getDetails()))}addCharge(t){this.charges.push(t),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new B(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new B(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return this.total}getDetails(){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:{subtotal:t.subtotal.getDetails(),netSubtotal:t.netSubtotal.getDetails(),lineItemTaxTotal:t.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(t.lineItemTaxBreakdown),chargesTotal:t.chargesTotal.getDetails(),shippingCharge:t.shippingCharge.getDetails(),netShippingCharge:t.netShippingCharge.getDetails(),chargeTaxTotal:t.chargeTaxTotal.getDetails(),chargeTaxBreakdown:this.serializeTaxBreakdown(t.chargeTaxBreakdown),taxTotal:t.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(t.taxBreakdown),discounts:Object.fromEntries(Object.entries(t.discounts).map(([e,i])=>[e,i.getDetails()])),totalDiscount:t.totalDiscount.getDetails(),grandTotal:t.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new n({amount:0,currency:this.currency}),e=this.lineItems.filter(p=>p.getState()!=="CANCELLED"),i=e.reduce((p,m)=>p.add(m.getTotal().subtotal),t),r=e.reduce((p,m)=>p.add(m.getTotal().netSubtotal),t),s=this.charges.filter(p=>p.getChargeType()==="SHIPPING").reduce((p,m)=>p.add(m.getTotal().price),t),a=t,u={},l={};this.coupons.forEach(p=>{let m=p.calculateApplicableCouponDiscount(i,s,this.country,this.currency);a=a.add(m),u[p.getCode()]=m,p.getCategory()!=="SHIPPING"&&(l[p.getCode()]=m);}),this.applyDiscountsInLineItem(l);let c=this.coupons.find(p=>p.getCategory()==="SHIPPING");c&&this.applyDiscuountsInShippingCharges({[c.getCode()]:u[c.getCode()]||t});let d=this.charges.reduce((p,m)=>p.add(m.getTotal().grandTotal),t),h=this.charges.filter(p=>p.getChargeType()==="SHIPPING").reduce((p,m)=>p.add(m.getTotal().grandTotal),t),x=t,S=t,D=t,b={},I={},V={},H=(p,m)=>{Object.entries(p).forEach(([Vt,E])=>{let f=E.system,v=E.subSystem;m[f]||(m[f]={system:f,totalAmount:t,subSystems:{}}),m[f].subSystems[v]?m[f].subSystems[v]=m[f].subSystems[v].add(E.amount):m[f].subSystems[v]=E.amount,m[f].totalAmount=m[f].totalAmount.add(E.amount),b[f]||(b[f]={system:f,totalAmount:t,subSystems:{}}),b[f].subSystems[v]?b[f].subSystems[v]=b[f].subSystems[v].add(E.amount):b[f].subSystems[v]=E.amount,b[f].totalAmount=b[f].totalAmount.add(E.amount);});};e.forEach(p=>{let m=p.getTotal().taxBreakdown;m&&(H(m,I),H(m,b),S=S.add(p.getTotal().taxTotal));}),this.charges.forEach(p=>{let m=p.getTotal().taxBreakdown;m&&(H(m,V),H(m,b),D=D.add(p.getTotal().taxTotal));}),x=S.add(D);let Dt=r.add(S).add(d);this.total={subtotal:i,netSubtotal:r,lineItemTaxTotal:S,lineItemTaxBreakdown:I,chargesTotal:d,shippingCharge:s,netShippingCharge:h,chargeTaxTotal:D,chargeTaxBreakdown:V,taxTotal:x,taxBreakdown:b,discounts:u,totalDiscount:a,grandTotal:Dt};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let e=t.filter(r=>r.getCategory()==="SHIPPING"),i=t.filter(r=>r.getCategory()!=="SHIPPING");this.coupons=[],this.total.totalDiscount=this.total.subtotal.zero(),this.total.discounts={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.discounts),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,s])=>{let a=this.coupons.find(c=>c.getCode()===r);if(!a||s.isZero())return;let u=this.lineItems.filter(c=>c.getState()!=="CANCELLED"&&!c.getTotal().subtotal.isZero()).sort((c,d)=>c.getTotal().subtotal.compareTo(d.getTotal().subtotal)),l=new n({amount:0,currency:this.currency});u.forEach((c,d)=>{let h;d===u.length-1?h=s.subtract(l):h=s.multiply(c.getTotal().subtotal).divide(this.total.subtotal).round(),l=l.add(h),i.get(c.getId())?.push({coupon:a,amount:h});});}),this.lineItems.forEach(r=>{r.getState()==="CANCELLED"||this.total.subtotal.isZero()?r.updateDiscounts([]):r.updateDiscounts(i.get(r.getId())||[]);});}applyDiscuountsInShippingCharges(t){let e=Array.from(Object.entries(t)).filter(s=>!s[1].isZero()),i=this.charges.filter(s=>s.getChargeType()==="SHIPPING"),r=new Map;i.forEach(s=>r.set(s.getId(),[])),e.forEach(([s,a])=>{let u=this.coupons.find(d=>d.getCode()===s);if(!u||a.isZero())return;let l=i.sort((d,h)=>d.getTotal().grandTotal.compareTo(h.getTotal().grandTotal)),c=new n({amount:0,currency:this.currency});l.forEach((d,h)=>{let x;h===l.length-1?x=a.subtract(c):x=a.multiply(d.getTotal().grandTotal).divide(this.total.subtotal).round(),c=c.add(x),r.get(d.getId())?.push({coupon:u,amount:x});});}),i.forEach(s=>{s.updateDiscounts(r.get(s.getId())||[]);});}applyNonShippingCoupons(t){let e=t.filter(i=>i.getType()==="coupon");if(e.length===1){let i=e[0].calculateApplicableCouponDiscount(this.total.subtotal,this.total.shippingCharge,this.country,this.currency);i.getAmount()>0&&(this.coupons.push(e[0]),this.total.discounts[e[0].getCode()]=i,this.total.totalDiscount=i);}}applyShippingCoupons(t){if(this.total.shippingCharge.getAmount()>0&&t.length>0){let e=this.total.subtotal.subtract(this.total.totalDiscount),i=t.reduce((s,a)=>{if(!s)return a;let u=a.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge),l=s.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge);return u===l?a.getType()==="coupon"?a:s:u.compareTo(l)>0?a:s}),r=i.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge);r.getAmount()>0&&(this.coupons.push(i),this.total.discounts[i.getCode()]=r,this.total.totalDiscount=this.total.totalDiscount.add(r),this.total.netShippingCharge=this.total.shippingCharge.subtract(r));}}};var Ft=(r=>(r.ACTIVE="ACTIVE",r.FROZEN="FROZEN",r.MERGED="MERGED",r.ORDERED="ORDERED",r))(Ft||{}),zt={expiresAtInSeconds:120*24*60*60},xt=class extends q{state;expireAt;config;constructor(t,e=new Date,i=zt){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.coupons=[],this.shippingDetails=null,this.total.discounts={},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=L.generateSelectionAttributesKey(i),s=this.lineItems.findIndex(a=>a.getProductKey()===e&&L.generateSelectionAttributesKey(a.getSelectionAttributes())===r);return s>=0?this.lineItems[s].addSubItems(t.getSubItems(),!0):this.lineItems.push(t),this.calculateTotals(),s>=0?s:this.lineItems.length-1}updateLineItem(t,e,i){let r=this.lineItems,s=r.findIndex(a=>a.getId()===t);if(s<0)throw new G(t);return r[s].addSubItems([{size:e,quantity:i}],!1),this.calculateTotals(),s}removeLineItem(t){let i=this.lineItems.findIndex(r=>r.getId()===t);if(i<0)throw new G(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=Ft;exports.DEFAULT_CART_CONFIG=zt;exports.default=xt;//# sourceMappingURL=Cart.js.map
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var At=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var At__default=/*#__PURE__*/_interopDefault(At);var G=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}},Q=class extends Error{constructor(t){super(`Invalid line item state: ${t}`),this.name="InvalidLineItemStateError";}},Z=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},Y=class extends Error{constructor(t){super(`Duplicate selection attribute found: ${t}`),this.name="DuplicateSelectionAttributeError";}},J=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},W=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},A=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},X=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},_=class extends Error{constructor(t="Pricing details not available for the product"){super(`NotFound: ${t}`),this.name="PricingNotFoundError";}},U=class extends Error{constructor(t="Tax rule category mismatch."){super(`InvalidTaxRule: ${t}`),this.name="InvalidTaxRuleError";}},tt=class extends Error{constructor(t="Tax category is not valid."){super(`InvalidTaxCategory: ${t}`),this.name="InvalidTaxCategoryError";}},et=class extends Error{constructor(t="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${t}`),this.name="InvalidMinQuantityError";}},it=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},rt=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},st=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}},ot=class extends Error{constructor(t="No applicable tax slab or multiple slabs found for the given unit price."){super(`TaxSlabNotFound: ${t}`),this.name="TaxSlabNotFoundError";}},$=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},O=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},w=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},C=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},j=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}};var at=new Uint8Array(256),nt=at.length;function pt(){return nt>at.length-16&&(At__default.default.randomFillSync(at),nt=0),at.slice(nt,nt+=16)}var Tt=/^(?:[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 Mt(s){return typeof s=="string"&&Tt.test(s)}var ft=Mt;var f=[];for(let s=0;s<256;++s)f.push((s+256).toString(16).slice(1));function ct(s,t=0){return f[s[t+0]]+f[s[t+1]]+f[s[t+2]]+f[s[t+3]]+"-"+f[s[t+4]]+f[s[t+5]]+"-"+f[s[t+6]]+f[s[t+7]]+"-"+f[s[t+8]]+f[s[t+9]]+"-"+f[s[t+10]]+f[s[t+11]]+f[s[t+12]]+f[s[t+13]]+f[s[t+14]]+f[s[t+15]]}function wt(s){if(!ft(s))throw TypeError("Invalid UUID");let t,e=new Uint8Array(16);return e[0]=(t=parseInt(s.slice(0,8),16))>>>24,e[1]=t>>>16&255,e[2]=t>>>8&255,e[3]=t&255,e[4]=(t=parseInt(s.slice(9,13),16))>>>8,e[5]=t&255,e[6]=(t=parseInt(s.slice(14,18),16))>>>8,e[7]=t&255,e[8]=(t=parseInt(s.slice(19,23),16))>>>8,e[9]=t&255,e[10]=(t=parseInt(s.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 Ct=wt;function Lt(s){s=unescape(encodeURIComponent(s));let t=[];for(let e=0;e<s.length;++e)t.push(s.charCodeAt(e));return t}var Rt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Et="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function mt(s,t,e){function i(r,o,n,u){var l;if(typeof r=="string"&&(r=Lt(r)),typeof o=="string"&&(o=Ct(o)),((l=o)===null||l===void 0?void 0:l.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,n){u=u||0;for(let d=0;d<16;++d)n[u+d]=c[d];return n}return ct(c)}try{i.name=s;}catch{}return i.DNS=Rt,i.URL=Et,i}var ht={randomUUID:At__default.default.randomUUID};function Bt(s,t,e){if(ht.randomUUID&&!t&&!s)return ht.randomUUID();s=s||{};let i=s.random||(s.rng||pt)();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 ct(i)}var yt=Bt;function Ut(s){return Array.isArray(s)?s=Buffer.from(s):typeof s=="string"&&(s=Buffer.from(s,"utf8")),At__default.default.createHash("sha1").update(s).digest()}var It=Ut;var Ot=mt("v5",80,It),bt=Ot;var kt={isUUID:s=>/^[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(s),isEmail:s=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(s),isURL:s=>/^(http|https):\/\/[^ "]+$/.test(s),generateUUID:(s,t)=>t&&s?bt(s,t):yt(),generateSearchId:(s,t)=>`${s}#${L.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:s=>{let[t,e]=s.split("#");return {key:t,selectionAttributes:L.parseSelectionAttributesKey(e)}},deepClone(s){return structuredClone(s)}},g=kt;var N=class{customFields;constructor(t,e=new Date){this.customFields={...t.customFields};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}},M=class extends N{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 St={INR:"\u20B9"},Pt={INR:"en-IN"};var lt=(d=>(d.INITIAL="INITIAL",d.PROCESSING="PROCESSING",d.SHIPPED="SHIPPED",d.DELIVERED="DELIVERED",d.CANCELLED="CANCELLED",d.RETURN_REQUESTED="RETURN_REQUESTED",d.RETURNED="RETURNED",d.REFUND_INITIATED="REFUND_INITIATED",d.REFUNDED="REFUNDED",d.ON_HOLD="ON_HOLD",d))(lt||{});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 j("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 j("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 a=class s{#t;amount;currency;constructor(t){if(this.#t="PriceModel",t.amount<0)throw new $("Amount cannot be negative.");if(!t.currency)throw new O("Currency code is required.");this.amount=t.amount,this.currency=t.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}}compareTo(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot compare prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return this.amount-t.getAmount()}add(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot add prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return new s({amount:this.amount+t.getAmount(),currency:this.currency})}subtract(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot subtract prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return new s({amount:this.amount-t.getAmount(),currency:this.currency})}multiply(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot multiply prices in different currencies.");return new s({amount:this.amount*t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>=0)return new s({amount:this.amount*t,currency:this.currency});throw new C("Must be a non-negative number.")}divide(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot divide prices in different currencies.");return new s({amount:this.amount/t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>0)return new s({amount:this.amount/t,currency:this.currency});throw new C("Must be a positive number.")}min(...t){if(t.length===0)throw new C("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(s.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new w("Cannot compare prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i},this)}max(...t){if(t.length===0)throw new C("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(s.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new w("Cannot compare prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return e.compareTo(i)>0?e:i},this)}zero(){return new s({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new s({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return s.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return s.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(t,e,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let r=Pt[e];if(!e||!r)throw new O("Invalid currency code for formatting.");let o=t,n=i.displayAsInteger?0:s.getDecimalPlaces(e),u={style:i.style??"currency",currency:e,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:n,maximumFractionDigits:n};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(r,u).format(o)}catch(l){return console.error(`Error formatting price for currency "${e}" and locale "${r}":`,l),`${St[e]??e} ${s.addThousandSeparators(o.toFixed(n))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}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 $("Amount cannot be negative for rounding.");if(e===void 0)throw new O("Invalid currency code for rounding.");let i=s.getDecimalPlaces(e),r=Math.pow(10,i);return Math.round(t*r)/r}};var k=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new a(t.baseUnitPrice);if(!t.taxCategory)throw new tt;let i=(t.tiers??[]).map(l=>({minQuantity:l.minQuantity,unitPrice:new a(l.unitPrice)})).sort((l,c)=>l.minQuantity-c.minQuantity);if(i.some(l=>l.minQuantity<=0))throw new et;let o=i.some(l=>l.unitPrice.getCurrency()!==e.getCurrency()),n=i.some((l,c)=>c>0&&l.unitPrice.compareTo(i[c-1].unitPrice)>0),u=i[0]?.unitPrice.compareTo(e)>0;if(o||n||u)throw new it("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}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 rt;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity)return this.tiers[e];throw new st(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 L=class s 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 A("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,n]=r.split(":");n.startsWith("c+")?e[o]={name:n.slice(2)}:e[o]=n;}return e}catch(e){throw new A(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 k(t.pricing[o])),r),{}),this.targetGender=t.targetGender,this.attributes=g.deepClone(t.attributes),this.specifications=g.deepClone(t.specifications),this.categories=g.deepClone(t.categories);let i=new Set;this.variants=(t.variants||[]).map(r=>{if(!r.selectionAttributes||typeof r.selectionAttributes!="object")throw new A("Selection attributes are required");this.checkSelectionAttributes(r.selectionAttributes);let o=s.generateSelectionAttributesKey(r.selectionAttributes);if(i.has(o))throw new Y(o);return i.add(o),{sku:r.sku,selectionAttributes:r.selectionAttributes,images:{primary:new R(r.images.primary),gallery:(r.images.gallery||[]).map(n=>new R(n))}}}),this.isActive=t.isActive,this.searchTags=t.searchTags?g.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:g.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[S[t]]??this.description.en:g.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[S[t]]??this.slug.en:g.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:this.pricing}getAttributes(){return g.deepClone(this.attributes)}getVariants(){return this.variants.map(t=>({sku:t.sku,selectionAttributes:t.selectionAttributes,images:{primary:t.images.primary,gallery:t.images.gallery}}))}getImagesBySelectionAttributes(t){let e=s.generateSelectionAttributesKey(t),i=this.variants.find(r=>s.generateSelectionAttributesKey(r.selectionAttributes)===e);return i?i.images: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 g.deepClone(this.categories)}getSpecifications(t){return t?g.deepClone(this.specifications[t]??this.specifications[S[t]]??this.specifications.en):g.deepClone(this.specifications)}getSearchTags(t){return t?g.deepClone(this.searchTags[t]??this.searchTags[S[t]]??this.searchTags.en):g.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:g.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 A("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 A(`Selection attribute '${e}' is missing`);if(typeof i=="string"){if(typeof r!="string"||i!==r)throw new A(`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 A(`Selection attribute '${e}' is invalid`)}else if(typeof r!="object"||!("name"in r)||i.findIndex(o=>o.name===r.name)<0)throw new A(`Selection attribute '${e}' is invalid`)}});}validateSelectionAttribute(t){let e=s.generateSelectionAttributesKey(t);return this.variants.some(i=>s.generateSelectionAttributesKey(i.selectionAttributes)===e)}validateSize(t){return this.attributes.size.includes(t)}};var B=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 ut=class{taxRuleId;taxCategory;taxSystem;taxSubSystem;taxCountry;effectiveFrom;effectiveTo;constructor(t){this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxSubSystem=t.taxSubSystem,this.taxCategory=t.taxCategory,this.taxCountry=t.taxCountry,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}getTaxCountry(){return this.taxCountry}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),taxCountry:this.getTaxCountry(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0}}appliesTo(t,e,i=new Date){return this.taxCategory===t&&this.taxCountry===e&&Date.parse(this.effectiveFrom)<=i.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=i.getTime():!0)}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}%`}},dt=class s extends ut{slabs;constructor(t){super(t),this.slabs=t.slabs.map(e=>({rate:e.rate,minUnitPrice:new a(e.minUnitPrice),maxUnitPrice:e.maxUnitPrice?new a(e.maxUnitPrice):void 0}));}getSlabs(){return this.slabs}getDetails(){return {...super.getDetails(),slabs:this.getSlabs().map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0}))}}getApplicableTaxRate(t){return s.getApplicableTaxRate(t,this.slabs)}calculateTax(t){let e=this.getApplicableTaxRate(t);return t.multiply(e)}static getApplicableTaxRate(t,e){let i=e.filter(r=>(r.minUnitPrice===void 0||t.compareTo(r.minUnitPrice)>=0)&&(r.maxUnitPrice===void 0||t.compareTo(r.maxUnitPrice)<0));if(i.length!==1)throw new ot;return i[0].rate}},gt=class extends ut{rate;constructor(t){super(t),this.rate=t.rate;}getApplicableTaxRate(){return this.rate}calculateTax(t){let e=this.getApplicableTaxRate();return t.multiply(e)}getDetails(){return {...super.getDetails(),rate:this.getApplicableTaxRate()}}};var F=class extends N{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=g.deepClone(t.selectionAttributes),this.name=g.deepClone(t.name),this.specifications=g.deepClone(t.specifications),this.primaryImage=new R(t.primaryImage),this.subItems=g.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new Z(i.size);e.add(i.size);}),this.pricing={unitPrice:new a(t.pricing.unitPrice),tierPricing:new k(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(i=>new dt(i))},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,unitPrice:new a(t.total.unitPrice),subtotal:new a(t.total.subtotal),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,r])=>[i,new a(r)])),totalDiscount:new a(t.total.totalDiscount),netUnitPrice:new a(t.total.netUnitPrice),netSubtotal:new a(t.total.netSubtotal),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:new a(r.taxableUnitPrice),taxPerUnit:new a(r.taxPerUnit),amount:new a(r.amount),system:r.system,subSystem:r.subSystem}])),taxTotal:new a(t.total.taxTotal),grandTotal:new a(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return g.deepClone(this.selectionAttributes)}getName(t){return t?g.deepClone(this.name[t]??this.name[S[t]]??this.name.en):g.deepClone(this.name)}getSpecifications(t){return t?g.deepClone(this.specifications[t]??this.specifications[S[t]]??this.specifications.en):g.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return g.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,discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,e])=>[t,e])),totalDiscount:this.total.totalDiscount,netUnitPrice:this.total.netUnitPrice,netSubtotal:this.total.netSubtotal,taxBreakdown:this.total.taxBreakdown,taxTotal:this.total.taxTotal,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(),discounts:Object.fromEntries(Object.entries(e.discounts).map(([i,r])=>[i,r.getDetails()])),totalDiscount:e.totalDiscount.getDetails(),netUnitPrice:e.netUnitPrice.getDetails(),netSubtotal:e.netSubtotal.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(e.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:r.taxableUnitPrice.getDetails(),taxPerUnit:r.taxPerUnit.getDetails(),amount:r.amount.getDetails(),system:r.system,subSystem:r.subSystem}])),taxTotal:e.taxTotal.getDetails(),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 J;if(!t.getIsActive())throw new W;this.subItems.forEach(u=>{if(!t.validateSize(u.size))throw new X});let r=t.getPriceDetails(e);if(!r||r.getBaseUnitPrice().getCurrency()!==i)throw new _;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let o=this.subItems.reduce((u,l)=>u+l.quantity,0),{unitPrice:n}=r.getApplicableTier(o);this.pricing={unitPrice:n,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.discounts=e,this.calculateTotals();}updateTax(t){t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getTaxCountry()))throw new U}),this.pricing.applicableTaxRule=t,this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((h,x)=>h+x.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,unitPrice:t,subtotal:t,discounts:{},totalDiscount:t,netUnitPrice:t,netSubtotal:t,taxBreakdown:{},taxTotal:t,grandTotal:t};return}let{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),r=i.multiply(e),o=Object.values(this.total.discounts).reduce((h,x)=>h.add(x),t),n=r.subtract(o),u=e>0?n.divide(e):t,l={},c=t;this.pricing.applicableTaxRule.forEach(h=>{let x=h.getApplicableTaxRate(u),P=h.calculateTax(u),D=P.multiply(e).round();l[h.getTaxRuleId()]={rate:x,taxableUnitPrice:u,taxPerUnit:P,amount:D,system:h.getTaxSystem(),subSystem:h.getTaxSubSystem()},c=c.add(D);});let d=n.add(c);this.total={quantity:e,unitPrice:i,subtotal:r,discounts:this.total.discounts,totalDiscount:o,netUnitPrice:u,netSubtotal:n,taxBreakdown:l,taxTotal:c,grandTotal:d};}updateState(t){if(this.state in lt)this.state!==t&&(this.state=t);else throw new Q(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,discounts:{},totalDiscount:t,netUnitPrice:t,netSubtotal:t,taxBreakdown:{},taxTotal:t,grandTotal:t};}};var K=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=g.deepClone(t.name),this.description=g.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 a(o)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,r)=>{let o=t.maxCartDiscount[r];return o&&(i[r]=new a(o)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new C("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 n=new a({amount:0,currency:r}),u;if(o&&!this.isActive())return n;let l=this.getMinCartValue(i),c=this.getMaxCartDiscount(i);if(!l||l.compareTo(t)>0||!c)return n;let d=this.getCategory(),h=this.getDiscountMethod(),x=d==="SHIPPING"?e:t;if(x.getAmount()<=0)return n;switch(h){case"flat":let D=c;u=x.min(D);break;case"percentage":u=x.multiply(this.getPercentageValue()/100).round();break;default:return n}return u.min(c)}};var z=class extends N{id;name;category;lineItemId;chargeType;pricing;total;constructor(t){super(t),this.id=t.id,this.name=t.name,this.category=t.category,this.lineItemId=t.lineItemId,this.chargeType=t.chargeType,this.pricing={price:new a(t.pricing.price),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(e=>new gt(e))},this.total={price:new a(t.total.price),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([e,i])=>[e,new a(i)])),totalDiscount:new a(t.total.totalDiscount),netPrice:new a(t.total.netPrice),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxablePrice:new a(i.taxablePrice),amount:new a(i.amount),system:i.system,subSystem:i.subSystem}])),taxTotal:new a(t.total.taxTotal),grandTotal:new a(t.total.grandTotal)};}getId(){return this.id}getName(){return this.name}getCategory(){return this.category}getChargeType(){return this.chargeType}getLineItemId(){return this.lineItemId}getPricing(){return this.pricing}getTotal(){return this.total}getApplicableTaxRules(){return this.pricing.applicableTaxRule}updateTax(t){t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getTaxCountry()))throw new U}),this.pricing.applicableTaxRule=t,this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discounts=e,this.calculateTotals();}calculateTotals(){let t=this.pricing.price.zero(),e=this.pricing.price,i=Object.values(this.total.discounts).reduce((b,I)=>b.add(I),t),r=e.subtract(i),o={},n=this.pricing.applicableTaxRule.reduce((b,I)=>b+I.getApplicableTaxRate(),0),u=r.divide(1+n).round(),l=n>0?r.subtract(u):t,c=t,d=this.pricing.applicableTaxRule.reduce((b,I)=>I.getApplicableTaxRate()>b.getApplicableTaxRate()?I:b),h=d.getTaxRuleId();this.pricing.applicableTaxRule.forEach(b=>{if(b.getTaxRuleId()===h)return;let I=b.getApplicableTaxRate(),V=n>0?l.multiply(I).divide(n).round():t;o[b.getTaxRuleId()]={rate:I,taxablePrice:u,amount:V,system:b.getTaxSystem(),subSystem:b.getTaxSubSystem()},c=c.add(V);});let x=l.subtract(c);o[h]={rate:d.getApplicableTaxRate(),taxablePrice:u,amount:x,system:d.getTaxSystem(),subSystem:d.getTaxSubSystem()};let P=u,D=r;this.total={price:e,discounts:this.total.discounts,netPrice:P,totalDiscount:i,taxBreakdown:o,taxTotal:l,grandTotal:D};}getDetails(){return {id:this.id,name:g.deepClone(this.name),category:this.category,lineItemId:this.lineItemId,chargeType:this.chargeType,pricing:{price:this.pricing.price.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(e=>e.getDetails())},total:{price:this.total.price.getDetails(),discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([e,i])=>[e,i.getDetails()])),totalDiscount:this.total.totalDiscount.getDetails(),netPrice:this.total.netPrice.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxablePrice:i.taxablePrice.getDetails(),amount:i.amount.getDetails(),system:i.system,subSystem:i.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};var q=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 F(i)),this.charges=(t.charges??[]).map(i=>new z(i)),this.billingAddress=t.billingAddress?new B(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new B(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new K(i)),this.shippingDetails=t.shippingDetails?g.deepClone(t.shippingDetails):null,this.total={subtotal:new a(t.total.subtotal),netSubtotal:new a(t.total.netSubtotal),lineItemTaxTotal:new a(t.total.lineItemTaxTotal||{amount:0,currency:t.currency}),lineItemTaxBreakdown:this.mapTaxBreakdown(t.total.lineItemTaxBreakdown||{}),chargesTotal:new a(t.total.chargesTotal||{amount:0,currency:t.currency}),shippingCharge:new a(t.total.shippingCharge),netShippingCharge:new a(t.total.netShippingCharge),chargeTaxTotal:new a(t.total.chargeTaxTotal||{amount:0,currency:t.currency}),chargeTaxBreakdown:this.mapTaxBreakdown(t.total.chargeTaxBreakdown||{}),taxTotal:new a(t.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(t.total.taxBreakdown),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,r])=>[i,new a(r)])),totalDiscount:new a(t.total.totalDiscount),grandTotal:new a(t.total.grandTotal)};}mapTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,i])=>[e,{system:i.system,totalAmount:new a(i.totalAmount),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,o])=>[r,new a(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 F(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(t=>new z(t.getDetails()))}addCharge(t){this.charges.push(t),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new B(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new B(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return this.total}getDetails(){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:{subtotal:t.subtotal.getDetails(),netSubtotal:t.netSubtotal.getDetails(),lineItemTaxTotal:t.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(t.lineItemTaxBreakdown),chargesTotal:t.chargesTotal.getDetails(),shippingCharge:t.shippingCharge.getDetails(),netShippingCharge:t.netShippingCharge.getDetails(),chargeTaxTotal:t.chargeTaxTotal.getDetails(),chargeTaxBreakdown:this.serializeTaxBreakdown(t.chargeTaxBreakdown),taxTotal:t.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(t.taxBreakdown),discounts:Object.fromEntries(Object.entries(t.discounts).map(([e,i])=>[e,i.getDetails()])),totalDiscount:t.totalDiscount.getDetails(),grandTotal:t.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new a({amount:0,currency:this.currency}),e=this.lineItems.filter(p=>p.getState()!=="CANCELLED"),i=e.reduce((p,m)=>p.add(m.getTotal().subtotal),t),r=e.reduce((p,m)=>p.add(m.getTotal().netSubtotal),t),o=this.charges.filter(p=>p.getChargeType()==="SHIPPING").reduce((p,m)=>p.add(m.getTotal().price),t),n=t,u={},l={};this.coupons.forEach(p=>{let m=p.calculateApplicableCouponDiscount(i,o,this.country,this.currency);n=n.add(m),u[p.getCode()]=m,p.getCategory()!=="SHIPPING"&&(l[p.getCode()]=m);}),this.applyDiscountsInLineItem(l);let c=this.coupons.find(p=>p.getCategory()==="SHIPPING");c?this.applyDiscuountsInShippingCharges({[c.getCode()]:u[c.getCode()]||t}):this.applyDiscuountsInShippingCharges({});let d=this.charges.reduce((p,m)=>p.add(m.getTotal().grandTotal),t),h=this.charges.filter(p=>p.getChargeType()==="SHIPPING").reduce((p,m)=>p.add(m.getTotal().grandTotal),t),x=t,P=t,D=t,b={},I={},V={},H=(p,m)=>{Object.entries(p).forEach(([Vt,E])=>{let T=E.system,v=E.subSystem;m[T]||(m[T]={system:T,totalAmount:t,subSystems:{}}),m[T].subSystems[v]?m[T].subSystems[v]=m[T].subSystems[v].add(E.amount):m[T].subSystems[v]=E.amount,m[T].totalAmount=m[T].totalAmount.add(E.amount),b[T]||(b[T]={system:T,totalAmount:t,subSystems:{}}),b[T].subSystems[v]?b[T].subSystems[v]=b[T].subSystems[v].add(E.amount):b[T].subSystems[v]=E.amount,b[T].totalAmount=b[T].totalAmount.add(E.amount);});};e.forEach(p=>{let m=p.getTotal().taxBreakdown;m&&(H(m,I),H(m,b),P=P.add(p.getTotal().taxTotal));}),this.charges.forEach(p=>{let m=p.getTotal().taxBreakdown;m&&(H(m,V),H(m,b),D=D.add(p.getTotal().taxTotal));}),x=P.add(D);let Dt=r.add(P).add(d);this.total={subtotal:i,netSubtotal:r,lineItemTaxTotal:P,lineItemTaxBreakdown:I,chargesTotal:d,shippingCharge:o,netShippingCharge:h,chargeTaxTotal:D,chargeTaxBreakdown:V,taxTotal:x,taxBreakdown:b,discounts:u,totalDiscount:n,grandTotal:Dt};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let e=t.filter(r=>r.getCategory()==="SHIPPING"),i=t.filter(r=>r.getCategory()!=="SHIPPING");this.coupons=[],this.total.totalDiscount=this.total.subtotal.zero(),this.total.discounts={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.discounts),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 n=this.coupons.find(c=>c.getCode()===r);if(!n||o.isZero())return;let u=this.lineItems.filter(c=>c.getState()!=="CANCELLED"&&!c.getTotal().subtotal.isZero()).sort((c,d)=>c.getTotal().subtotal.compareTo(d.getTotal().subtotal)),l=new a({amount:0,currency:this.currency});u.forEach((c,d)=>{let h;d===u.length-1?h=o.subtract(l):h=o.multiply(c.getTotal().subtotal).divide(this.total.subtotal).round(),l=l.add(h),i.get(c.getId())?.push({coupon:n,amount:h});});}),this.lineItems.forEach(r=>{r.getState()==="CANCELLED"||this.total.subtotal.isZero()?r.updateDiscounts([]):r.updateDiscounts(i.get(r.getId())||[]);});}applyDiscuountsInShippingCharges(t){let e=Array.from(Object.entries(t)).filter(o=>!o[1].isZero()),i=this.charges.filter(o=>o.getChargeType()==="SHIPPING"),r=new Map;i.forEach(o=>r.set(o.getId(),[])),e.forEach(([o,n])=>{let u=this.coupons.find(d=>d.getCode()===o);if(!u||n.isZero())return;let l=i.sort((d,h)=>d.getTotal().grandTotal.compareTo(h.getTotal().grandTotal)),c=new a({amount:0,currency:this.currency});l.forEach((d,h)=>{let x;h===l.length-1?x=n.subtract(c):x=n.multiply(d.getTotal().grandTotal).divide(this.total.subtotal).round(),c=c.add(x),r.get(d.getId())?.push({coupon:u,amount:x});});}),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.subtotal,this.total.shippingCharge,this.country,this.currency);i.getAmount()>0&&(this.coupons.push(e[0]),this.total.discounts[e[0].getCode()]=i,this.total.totalDiscount=i);}}applyShippingCoupons(t){if(this.total.shippingCharge.getAmount()>0&&t.length>0){let e=this.total.subtotal.subtract(this.total.totalDiscount),i=t.reduce((o,n)=>{if(!o)return n;let u=n.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge),l=o.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge);return u===l?n.getType()==="coupon"?n:o:u.compareTo(l)>0?n:o}),r=i.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge);r.getAmount()>0&&(this.coupons.push(i),this.total.discounts[i.getCode()]=r,this.total.totalDiscount=this.total.totalDiscount.add(r),this.total.netShippingCharge=this.total.shippingCharge.subtract(r));}}};var Ft=(r=>(r.ACTIVE="ACTIVE",r.FROZEN="FROZEN",r.MERGED="MERGED",r.ORDERED="ORDERED",r))(Ft||{}),zt={expiresAtInSeconds:120*24*60*60},xt=class extends q{state;expireAt;config;constructor(t,e=new Date,i=zt){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.coupons=[],this.shippingDetails=null,this.total.discounts={},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=L.generateSelectionAttributesKey(i),o=this.lineItems.findIndex(n=>n.getProductKey()===e&&L.generateSelectionAttributesKey(n.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(n=>n.getId()===t);if(o<0)throw new G(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 G(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=Ft;exports.DEFAULT_CART_CONFIG=zt;exports.default=xt;//# sourceMappingURL=Cart.js.map
2
2
  //# sourceMappingURL=Cart.js.map