b23-lib 3.9.5 → 3.9.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 (67) hide show
  1. package/dist/Auth/index.js +1 -1
  2. package/dist/Auth/index.js.map +1 -1
  3. package/dist/Auth/index.mjs +1 -1
  4. package/dist/Classes/Cart.d.mts +1 -1
  5. package/dist/Classes/Cart.d.ts +1 -1
  6. package/dist/Classes/Cart.js +1 -1
  7. package/dist/Classes/Cart.js.map +1 -1
  8. package/dist/Classes/Cart.mjs +1 -1
  9. package/dist/Classes/Charge.js +1 -1
  10. package/dist/Classes/Charge.js.map +1 -1
  11. package/dist/Classes/Charge.mjs +1 -1
  12. package/dist/Classes/Coupon.js +1 -1
  13. package/dist/Classes/Coupon.js.map +1 -1
  14. package/dist/Classes/Coupon.mjs +1 -1
  15. package/dist/Classes/Inventory.d.mts +1 -1
  16. package/dist/Classes/Inventory.d.ts +1 -1
  17. package/dist/Classes/Inventory.js +1 -1
  18. package/dist/Classes/Inventory.js.map +1 -1
  19. package/dist/Classes/Inventory.mjs +1 -1
  20. package/dist/Classes/Invoice.d.mts +1 -1
  21. package/dist/Classes/Invoice.d.ts +1 -1
  22. package/dist/Classes/LineItem.d.mts +1 -1
  23. package/dist/Classes/LineItem.d.ts +1 -1
  24. package/dist/Classes/LineItem.js +1 -1
  25. package/dist/Classes/LineItem.js.map +1 -1
  26. package/dist/Classes/LineItem.mjs +1 -1
  27. package/dist/Classes/Order.d.mts +1 -1
  28. package/dist/Classes/Order.d.ts +1 -1
  29. package/dist/Classes/Order.js +1 -1
  30. package/dist/Classes/Order.js.map +1 -1
  31. package/dist/Classes/Order.mjs +1 -1
  32. package/dist/Classes/Product.d.mts +1 -1
  33. package/dist/Classes/Product.d.ts +1 -1
  34. package/dist/Classes/Product.js +1 -1
  35. package/dist/Classes/Product.js.map +1 -1
  36. package/dist/Classes/Product.mjs +1 -1
  37. package/dist/Classes/ShoppingContainer.d.mts +1 -1
  38. package/dist/Classes/ShoppingContainer.d.ts +1 -1
  39. package/dist/Classes/ShoppingContainer.js +1 -1
  40. package/dist/Classes/ShoppingContainer.js.map +1 -1
  41. package/dist/Classes/ShoppingContainer.mjs +1 -1
  42. package/dist/Classes/TieredPrice.d.mts +1 -1
  43. package/dist/Classes/TieredPrice.d.ts +1 -1
  44. package/dist/Classes/TieredPrice.js +1 -1
  45. package/dist/Classes/TieredPrice.js.map +1 -1
  46. package/dist/Classes/TieredPrice.mjs +1 -1
  47. package/dist/{TieredPrice-DhFaSgL8.d.ts → TieredPrice-BnozYepN.d.ts} +7 -1
  48. package/dist/{TieredPrice-CuMNmrzq.d.mts → TieredPrice-CpedXDSI.d.mts} +7 -1
  49. package/dist/{chunk-BHPYMPAX.mjs → chunk-4GDSMVWZ.mjs} +2 -2
  50. package/dist/{chunk-BHPYMPAX.mjs.map → chunk-4GDSMVWZ.mjs.map} +1 -1
  51. package/dist/{chunk-Z3IGFT5Q.mjs → chunk-FSJ32AZ7.mjs} +2 -2
  52. package/dist/{chunk-Z3IGFT5Q.mjs.map → chunk-FSJ32AZ7.mjs.map} +1 -1
  53. package/dist/{chunk-ORSFINNO.mjs → chunk-FUGUGFHM.mjs} +2 -2
  54. package/dist/{chunk-ORSFINNO.mjs.map → chunk-FUGUGFHM.mjs.map} +1 -1
  55. package/dist/{chunk-2A22PHHR.mjs → chunk-JL3NMYBT.mjs} +2 -2
  56. package/dist/{chunk-2A22PHHR.mjs.map → chunk-JL3NMYBT.mjs.map} +1 -1
  57. package/dist/chunk-QH6GGZEG.mjs +2 -0
  58. package/dist/chunk-QH6GGZEG.mjs.map +1 -0
  59. package/dist/index.d.mts +80 -77
  60. package/dist/index.d.ts +80 -77
  61. package/dist/index.js +2 -2
  62. package/dist/index.js.map +1 -1
  63. package/dist/index.mjs +2 -2
  64. package/dist/index.mjs.map +1 -1
  65. package/package.json +1 -1
  66. package/dist/chunk-E33TTQZM.mjs +0 -2
  67. package/dist/chunk-E33TTQZM.mjs.map +0 -1
@@ -1,2 +1,2 @@
1
- 'use strict';var Re=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Re__default=/*#__PURE__*/_interopDefault(Re);var Ae=n=>structuredClone(n),R=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:Ae(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return Ae(this.customFields)}},M=class extends R{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.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(e,t,i,r){this.modifiedBy={id:e,authType:t,requestId:i,lambdaName:r};}};var N=class extends M{id;firstName;lastName;company;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(e,t=new Date){super(e,t),this.id=e.id,this.firstName=e.firstName,this.lastName=e.lastName||"",this.company=e.company||"",this.phone=e.phone,this.email=e.email,this.addressLine1=e.addressLine1,this.addressLine2=e.addressLine2||"",this.city=e.city,this.postalCode=e.postalCode,this.state=e.state,this.country=e.country,this.isBillingAddress=e.isBillingAddress,this.isShippingAddress=e.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(e){return e==="shipping"||e==="billing&shipping"}static checkIfBillingAddress(e){return e==="billing"||e==="billing&shipping"}};var re=new Uint8Array(256),ie=re.length;function ye(){return ie>re.length-16&&(Re__default.default.randomFillSync(re),ie=0),re.slice(ie,ie+=16)}var Se=/^(?:[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 Be(n){return typeof n=="string"&&Se.test(n)}var De=Be;var f=[];for(let n=0;n<256;++n)f.push((n+256).toString(16).slice(1));function ne(n,e=0){return f[n[e+0]]+f[n[e+1]]+f[n[e+2]]+f[n[e+3]]+"-"+f[n[e+4]]+f[n[e+5]]+"-"+f[n[e+6]]+f[n[e+7]]+"-"+f[n[e+8]]+f[n[e+9]]+"-"+f[n[e+10]]+f[n[e+11]]+f[n[e+12]]+f[n[e+13]]+f[n[e+14]]+f[n[e+15]]}function ke(n){if(!De(n))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(n.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(n.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(n.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(n.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(n.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var Me=ke;function Ne(n){n=unescape(encodeURIComponent(n));let e=[];for(let t=0;t<n.length;++t)e.push(n.charCodeAt(t));return e}var Ue="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Oe="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function be(n,e,t){function i(r,o,a,c){var u;if(typeof r=="string"&&(r=Ne(r)),typeof o=="string"&&(o=Me(o)),((u=o)===null||u===void 0?void 0:u.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let s=new Uint8Array(16+r.length);if(s.set(o),s.set(r,o.length),s=t(s),s[6]=s[6]&15|e,s[8]=s[8]&63|128,a){c=c||0;for(let d=0;d<16;++d)a[c+d]=s[d];return a}return ne(s)}try{i.name=n;}catch{}return i.DNS=Ue,i.URL=Oe,i}var Te={randomUUID:Re__default.default.randomUUID};function ze(n,e,t){if(Te.randomUUID&&!e&&!n)return Te.randomUUID();n=n||{};let i=n.random||(n.rng||ye)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(let r=0;r<16;++r)e[t+r]=i[r];return e}return ne(i)}var xe=ze;function Ve(n){return Array.isArray(n)?n=Buffer.from(n):typeof n=="string"&&(n=Buffer.from(n,"utf8")),Re__default.default.createHash("sha1").update(n).digest()}var we=Ve;var $e=be("v5",80,we),Ce=$e;var P={"en-IN":"en","kn-IN":"kn"};var Ee={INR:"\u20B9"},ve={INR:"en-IN"};var oe=(g=>(g.INITIAL="INITIAL",g.PROCESSING="PROCESSING",g.SHIPPED="SHIPPED",g.DELIVERED="DELIVERED",g.CANCELLED="CANCELLED",g.RETURN_REQUESTED="RETURN_REQUESTED",g.RETURNED="RETURNED",g.UNDELIVERED="UNDELIVERED",g.REFUND_INITIATED="REFUND_INITIATED",g.REFUNDED="REFUNDED",g.ON_HOLD="ON_HOLD",g))(oe||{});var se=class extends Error{constructor(e){super(`Invalid line item state: ${e}`),this.name="InvalidLineItemStateError";}},ae=class extends Error{constructor(e){super(`InvalidLineItemTaxRule: ${e}`),this.name="InvalidLineItemTaxRuleError";}},ce=class extends Error{constructor(e){super(`Duplicate size found: ${e}`),this.name="DuplicateSizeError";}},le=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}},ue=class extends Error{constructor(e="Product and selection attributes do not match."){super(`ProductMismatch: ${e}`),this.name="ProductMismatchError";}},de=class extends Error{constructor(e="Product is not active."){super(`ProductInactive: ${e}`),this.name="ProductInactiveError";}},w=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}},ge=class extends Error{constructor(e="Size does not match."){super(`SizeMismatch: ${e}`),this.name="SizeMismatchError";}},pe=class extends Error{constructor(e="Pricing details not available for the product"){super(`NotFound: ${e}`),this.name="PricingNotFoundError";}},z=class extends Error{constructor(e="Tax rule category mismatch."){super(`InvalidTaxRule: ${e}`),this.name="InvalidTaxRuleError";}},me=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},K=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},U=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},H=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},Z=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var Y=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},j=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},E=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},I=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},J=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}},X=class extends Error{constructor(e="Invalid charge data."){super(`InvalidCharge: ${e}`),this.name="InvalidChargeError";}},V=class extends Error{constructor(e="Invalid charge tax rule."){super(`InvalidChargeTaxRule: ${e}`),this.name="InvalidChargeTaxRuleError";}},O=class extends Error{constructor(e="Invalid pricing type."){super(`InvalidPricingType: ${e}`),this.name="InvalidPricingTypeError";}};var B=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw new J("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,t){if(t===void 0){if(e==="original")throw new J("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=t;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var l=class n{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new Y("Amount cannot be negative.");if(!e.currency)throw new j("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(n.getPrecisionPlaces(this.currency)));}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}getPreciseAmount(e){return parseFloat(e.toFixed(n.getPrecisionPlaces(this.currency)))}compareTo(e){if(n.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new E("Cannot compare prices in different currencies.")}else throw new I("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(n.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new E("Cannot add prices in different currencies.")}else throw new I("Must be a PriceModel instance.");return new n({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(n.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new E("Cannot subtract prices in different currencies.")}else throw new I("Must be a PriceModel instance.");return new n({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(n.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new E("Cannot multiply prices in different currencies.");return new n({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new n({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new I("Must be a non-negative number.")}divide(e){if(n.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new E("Cannot divide prices in different currencies.");return new n({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new n({amount:this.getPreciseAmount(this.amount/e),currency:this.currency});throw new I("Must be a positive number.")}min(...e){if(e.length===0)throw new I("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(n.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new E("Cannot compare prices in different currencies.")}else throw new I("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i},this)}max(...e){if(e.length===0)throw new I("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(n.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new E("Cannot compare prices in different currencies.")}else throw new I("Must be a PriceModel instance.");return t.compareTo(i)>0?t:i},this)}zero(){return new n({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new n({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return n.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return n.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,t,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let r=ve[t];if(!t||!r)throw new j("Invalid currency code for formatting.");let o=e,a=i.displayAsInteger?0:n.getDecimalPlaces(t),c={style:i.style??"currency",currency:t,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(r,c).format(o)}catch(u){return console.error(`Error formatting price for currency "${t}" and locale "${r}":`,u),`${Ee[t]??t} ${n.addThousandSeparators(o.toFixed(a))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static getPrecisionPlaces(e){switch(e){case"INR":default:return 6}}static addThousandSeparators(e){let t=e.split("."),i=t[0],r=t.length>1?"."+t[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+r}static getRoundedAmount(e,t){if(e<0)throw new Y("Amount cannot be negative for rounding.");if(t===void 0)throw new j("Invalid currency code for rounding.");let i=n.getDecimalPlaces(t),r=Math.pow(10,i);return Math.round(e*r)/r}static getSmallestUnit(e){let t=n.getDecimalPlaces(e);return 1/Math.pow(10,t)}};var F=class{type;taxCategory;isTaxInclusive;static create(e){return e.type==="selection"?new Pe(e):new fe(e)}constructor(e){if(!e.taxCategory)throw new me;this.taxCategory=e.taxCategory,this.isTaxInclusive=e.isTaxInclusive??!1,this.type=e.type??"volume";}getType(){return this.type}getTaxCategory(){return this.taxCategory}getIsTaxInclusive(){return this.isTaxInclusive}},fe=class extends F{baseUnitPrice;tiers;currency;constructor(e){if(super(e),this.type="volume",!e.baseUnitPrice)throw new U("Base unit price is required for volume pricing.");this.baseUnitPrice=new l(e.baseUnitPrice),this.currency=e.currency??this.baseUnitPrice.getCurrency();let t=(e.tiers??[]).map(c=>({enabled:c.enabled??!0,minQuantity:c.minQuantity,unitPrice:new l(c.unitPrice)})).sort((c,u)=>c.minQuantity-u.minQuantity);if(t.some(c=>c.minQuantity<=0))throw new K;let r=this.baseUnitPrice.getCurrency()!==this.currency||t.some(c=>c.unitPrice.getCurrency()!==this.currency),o=t.some((c,u)=>u>0&&c.unitPrice.compareTo(t[u-1].unitPrice)>0),a=t[0]?.unitPrice.compareTo(this.baseUnitPrice)>0;if(r||o||a)throw new U("Tiers must share the same currency and must not increase in unit price.");this.tiers=t;}isPriceAvailable(){return this.tiers.filter(e=>e.enabled).length>0}getBaseUnitPrice(){return this.baseUnitPrice}getCurrency(){return this.baseUnitPrice.getCurrency()}getApplicableUnitPrice(e){if(e<=0)throw new H;let t=this.tiers.filter(i=>i.enabled);for(let i=t.length-1;i>=0;i--){let r=t[i];if(e>=r.minQuantity)return r.unitPrice}throw new Z(e)}getMinQuantity(){return this.tiers.filter(t=>t.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(){let e=this.tiers.filter(o=>o.enabled);if(!e.length)return 0;let t=Math.min(...e.map(o=>o.unitPrice.getAmount())),i=this.baseUnitPrice.getAmount(),r=(i-t)/i*100;return r>0?r:0}getTiers(){return this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,baseUnitPrice:this.baseUnitPrice.getDetails(),tiers:this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}},Pe=class extends F{currency;selections;constructor(e){super(e),this.type="selection",this.currency=e.currency,this.selections=(e.selections??[]).map(t=>{if(!t.baseUnitPrice)throw new U("Base unit price is required for each selection.");let i=new l(t.baseUnitPrice),r=(t.tiers??[]).map(s=>({enabled:s.enabled??!0,minQuantity:s.minQuantity??1,unitPrice:new l(s.unitPrice)})).sort((s,d)=>s.minQuantity-d.minQuantity);if(r.some(s=>s.minQuantity<=0))throw new K;let a=i.getCurrency()!==this.currency||r.some(s=>s.unitPrice.getCurrency()!==this.currency),c=r.some((s,d)=>d>0&&s.unitPrice.compareTo(r[d-1].unitPrice)>0),u=r[0]?.unitPrice.compareTo(i)>0;if(a||c||u)throw new U("Tiers must share the same currency and must not increase in unit price within the same selection.");return {selectionAttributes:{...t.selectionAttributes},baseUnitPrice:i,tiers:r}});}findMatch(e){let t=k.generateSelectionAttributesKey(e),i=this.selections.find(r=>k.generateSelectionAttributesKey(r.selectionAttributes)===t);if(!i)throw new U("No pricing configuration found for selection variant.");return i}isPriceAvailable(e){try{return e?this.findMatch(e).tiers.filter(t=>t.enabled).length>0:(console.warn("Selection attributes are required to check price availability for selection pricing."),!1)}catch{return !1}}getBaseUnitPrice(e){if(!e)throw new O("Selection attributes are required to get base unit price for selection pricing.");return this.findMatch(e).baseUnitPrice}getCurrency(){return this.currency}getApplicableUnitPrice(e,t){if(e<=0)throw new H;if(!t)throw new O("Selection attributes are required to get applicable unit price for selection pricing.");let r=this.findMatch(t).tiers.filter(o=>o.enabled);for(let o=r.length-1;o>=0;o--){let a=r[o];if(e>=a.minQuantity)return a.unitPrice}throw new Z(e)}getMinQuantity(e){if(!e)throw new O("Selection attributes are required to get min quantity for selection pricing.");return this.findMatch(e).tiers.filter(r=>r.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(e){if(!e)throw new O("Selection attributes are required to get max discount for selection pricing.");let t=this.findMatch(e),i=t.tiers.filter(c=>c.enabled);if(!i.length)return 0;let r=Math.min(...i.map(c=>c.unitPrice.getAmount())),o=t.baseUnitPrice.getAmount(),a=(o-r)/o*100;return a>0?a:0}getTiers(e){if(!e)throw new O("Selection attributes are required to get tiers for selection pricing.");return this.findMatch(e).tiers.map(i=>({enabled:i.enabled,minQuantity:i.minQuantity,unitPrice:i.unitPrice}))}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,selections:this.selections.map(e=>({selectionAttributes:e.selectionAttributes,baseUnitPrice:e.baseUnitPrice.getDetails(),...e.tiers.length>0?{tiers:e.tiers.map(t=>({enabled:t.enabled,minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}:{}}))}}};var k=class n extends M{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;productType;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new w("Selection attributes must be an object");return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let t={},i=e.split("|");for(let r of i){let[o,a]=r.split(":");a.startsWith("c+")?t[o]={name:a.slice(2)}:t[o]=a;}return t}catch(t){throw new w(t?.message)}}constructor(e,t=new Date){super(e,t),this.id=e.id,this.key=e.key,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((r,o)=>(e.pricing[o]&&(r[o]=F.create(e.pricing[o])),r),{}),this.targetGender=e.targetGender,this.attributes=m.deepClone(e.attributes),this.specifications=m.deepClone(e.specifications),this.categories=m.deepClone(e.categories),this.productType=e.productType??"GOODS";let i=new Set;this.variants=(e.variants||[]).map(r=>{if(!r.selectionAttributes||typeof r.selectionAttributes!="object")throw new w("Selection attributes are required");this.checkSelectionAttributes(r.selectionAttributes);let o=n.generateSelectionAttributesKey(r.selectionAttributes);if(i.has(o))throw new le(o);return i.add(o),{sku:r.sku,selectionAttributes:r.selectionAttributes,images:{primary:new B(r.images.primary),gallery:(r.images.gallery||[]).map(a=>new B(a))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?m.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[P[e]]??this.name.en:m.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[P[e]]??this.description.en:m.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[P[e]]??this.slug.en:m.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return m.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:m.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let t=n.generateSelectionAttributesKey(e),i=this.variants.find(r=>n.generateSelectionAttributesKey(r.selectionAttributes)===t);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,t){switch(t){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return m.deepClone(this.categories)}getProductType(){return this.productType}getSpecifications(e){return e?m.deepClone(this.specifications[e]??this.specifications[P[e]]??this.specifications.en):m.deepClone(this.specifications)}getSearchTags(e){return e?m.deepClone(this.searchTags[e]??this.searchTags[P[e]]??this.searchTags.en):m.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((t,i)=>(this.pricing[i]&&(t[i]=this.pricing[i]?.getDetails()),t),{}),attributes:this.getAttributes(),variants:this.variants.map(t=>({sku:t.sku,selectionAttributes:m.deepClone(t.selectionAttributes),images:{primary:t.images.primary.getDetails(),gallery:t.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),productType:this.getProductType(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new w("Selection attributes are required");Object.keys(this.attributes).forEach(t=>{if(t.toLowerCase()==="size")return;let i=this.attributes[t],r=e[t];if(r===void 0)throw new w(`Selection attribute '${t}' is missing`);if(typeof i=="string"){if(typeof r!="string"||i!==r)throw new w(`Selection attribute '${t}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof r!="string"||!i.includes(r))throw new w(`Selection attribute '${t}' is invalid`)}else if(typeof r!="object"||!("name"in r)||i.findIndex(o=>o.name===r.name)<0)throw new w(`Selection attribute '${t}' is invalid`)}});}getSku(e){let t=n.generateSelectionAttributesKey(e);return this.variants.find(r=>n.generateSelectionAttributesKey(r.selectionAttributes)===t)?.sku}validateSelectionAttribute(e){let t=n.generateSelectionAttributesKey(e);return this.variants.some(i=>n.generateSelectionAttributesKey(i.selectionAttributes)===t)}validateSize(e){return this.attributes.size.includes(e)}};var qe={isUUID:n=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n),isEmail:n=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(n),isURL:n=>/^(http|https):\/\/[^ "]+$/.test(n),generateUUID:(n,e)=>e&&n?Ce(n,e):xe(),generateSearchId:(n,e)=>`${n}#${k.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:n=>{let[e,t]=n.split("#");return {key:e,selectionAttributes:k.parseSelectionAttributesKey(t)}},deepClone(n){return structuredClone(n)}},m=qe;var $=class extends R{taxRuleId;taxCategory;taxSystem;taxSubSystem;country;rate;minPrice;maxPrice;excludeMin;excludeMax;effectiveFrom;effectiveTo;constructor(e){super(e),this.taxRuleId=e.taxRuleId,this.taxSystem=e.taxSystem,this.taxSubSystem=e.taxSubSystem,this.taxCategory=e.taxCategory,this.country=e.country,this.rate=e.rate,this.minPrice=new l(e.minPrice),this.maxPrice=e.maxPrice?new l(e.maxPrice):void 0,this.excludeMin=e.excludeMin??!1,this.excludeMax=e.excludeMax??!1,this.effectiveFrom=new Date(e.effectiveFrom).toISOString(),this.effectiveTo=e.effectiveTo?new Date(e.effectiveTo).toISOString():void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getRate(){return this.rate}getMinPrice(){return this.minPrice}getMaxPrice(){return this.maxPrice}getExcludeMin(){return this.excludeMin}getExcludeMax(){return this.excludeMax}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),rate:this.getRate(),minPrice:this.getMinPrice().getDetails(),maxPrice:this.getMaxPrice()?.getDetails(),excludeMin:this.getExcludeMin(),excludeMax:this.getExcludeMax(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0,customFields:this.getAllCustomFields()}}appliesTo(e,t,i,r=new Date){let o=!i||(this.excludeMin?this.minPrice.compareTo(i)<0:this.minPrice.compareTo(i)<=0)&&(this.maxPrice?this.excludeMax?this.maxPrice.compareTo(i)>0:this.maxPrice.compareTo(i)>=0:!0);return this.taxCategory===e&&this.country===t&&o&&Date.parse(this.effectiveFrom)<=r.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=r.getTime():!0)}getApplicableTaxRate(e){return this.appliesTo(this.taxCategory,this.country,e)?this.rate:0}calculateTax(e){return this.appliesTo(this.taxCategory,this.country,e)?e.multiply(this.rate):e.zero()}static getTaxRateDisplayString(e,t,i){let r=t*100,o=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,"");return i?.percentageOnly?`${o}%`:e.getTaxSystem()==="GST"?`${e.getTaxSubSystem()} ${o}%`:`${e.getTaxSystem()} ${o}%`}};var W=(n,e)=>{let t=e.reduce((s,d)=>s+d.getApplicableTaxRate(n),0);if(t<=0)return n;let i=n.divide(1+t).round().getAmount(),r=n.getCurrency(),o=n.getAmount(),a=i,c=Number.POSITIVE_INFINITY,u=1e4;for(let s=0;s<u;s++){let d=new l({amount:i,currency:r}),y=e.sort((b,C)=>C.getApplicableTaxRate(d)-b.getApplicableTaxRate(d)).map(b=>d.multiply(b.getApplicableTaxRate(d)).round().getAmount()).reduce((b,C)=>b+C,0),T=i+y-o,A=e.reduce((b,C)=>b+C.getApplicableTaxRate(d),0);if(Math.abs(T)<Math.abs(c)&&(c=T,a=i),T===0)break;i=i-T/(1+A);}if(Math.abs(c)>l.getSmallestUnit(r))throw new Error("Failed to converge on a valid tax exclusive base.");return new l({amount:a,currency:r})},he=(n,e,t)=>{let i=n.zero(),r=[...t].sort((o,a)=>a.getApplicableTaxRate(n)-o.getApplicableTaxRate(n));return r.map((o,a)=>{let c=o.getApplicableTaxRate(n),u;return a===r.length-1?u=e.subtract(n).subtract(i):u=n.multiply(c).round(),i=i.add(u),{ruleId:o.getTaxRuleId(),taxAmount:u,rate:c}})};var G=class extends R{id;productKey;sku;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;productType;total;constructor(e){super(e),this.id=e.id,this.productKey=e.productKey,this.sku=e.sku,this.selectionAttributes=m.deepClone(e.selectionAttributes),this.name=m.deepClone(e.name),this.specifications=m.deepClone(e.specifications),this.primaryImage=new B(e.primaryImage),this.subItems=m.deepClone(e.subItems);let t=new Set;this.subItems.forEach(i=>{if(t.has(i.size))throw new ce(i.size);t.add(i.size);}),this.pricing={unitPrice:new l(e.pricing.unitPrice),tierPricing:F.create(e.pricing.tierPricing),taxCategory:e.pricing.taxCategory,applicableTaxRule:e.pricing.applicableTaxRule.map(i=>new $(i))},this.validateTaxRules(this.pricing.applicableTaxRule),this.state=e.state??"INITIAL",this.productType=e.productType??"GOODS",this.total={quantity:e.total.quantity,unitPrice:new l(e.total.unitPrice),subtotal:new l(e.total.subtotal),discountTotal:new l(e.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(e.total.discountBreakdown).map(([i,r])=>[i,new l(r)])),netUnitPrice:new l(e.total.netUnitPrice),netSubtotal:new l(e.total.netSubtotal),taxTotal:new l(e.total.taxTotal),taxBreakdown:Object.fromEntries(Object.entries(e.total.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:new l(r.taxableUnitPrice),taxPerUnit:new l(r.taxPerUnit),taxAmount:new l(r.taxAmount),system:r.system,subSystem:r.subSystem}])),grandTotal:new l(e.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSku(){return this.sku}getSelectionAttributes(){return m.deepClone(this.selectionAttributes)}getName(e){return e?m.deepClone(this.name[e]??this.name[P[e]]??this.name.en):m.deepClone(this.name)}getSpecifications(e){return e?m.deepClone(this.specifications[e]??this.specifications[P[e]]??this.specifications.en):m.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return m.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getState(){return this.state}getProductType(){return this.productType}getTotal(){return {quantity:this.total.quantity,unitPrice:this.total.unitPrice,subtotal:this.total.subtotal,discountTotal:this.total.discountTotal,discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([e,t])=>[e,t])),netUnitPrice:this.total.netUnitPrice,netSubtotal:this.total.netSubtotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,t])=>[e,{rate:t.rate,taxableUnitPrice:t.taxableUnitPrice,taxPerUnit:t.taxPerUnit,taxAmount:t.taxAmount,system:t.system,subSystem:t.subSystem}])),grandTotal:this.total.grandTotal}}getDetails(){let e=this.getPricing(),t=this.getTotal();return {id:this.getId(),productKey:this.getProductKey(),sku:this.getSku(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:e.unitPrice.getDetails(),tierPricing:e.tierPricing.getDetails(),taxCategory:e.taxCategory,applicableTaxRule:e.applicableTaxRule.map(i=>i.getDetails())},state:this.getState(),productType:this.getProductType(),total:{quantity:t.quantity,unitPrice:t.unitPrice.getDetails(),subtotal:t.subtotal.getDetails(),discountTotal:t.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(t.discountBreakdown).map(([i,r])=>[i,r.getDetails()])),netUnitPrice:t.netUnitPrice.getDetails(),netSubtotal:t.netSubtotal.getDetails(),taxTotal:t.taxTotal.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(t.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:r.taxableUnitPrice.getDetails(),taxPerUnit:r.taxPerUnit.getDetails(),taxAmount:r.taxAmount.getDetails(),system:r.system,subSystem:r.subSystem}])),grandTotal:t.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}validateTaxRules(e){let t=new Set;for(let i=0;i<e.length;i++){let r=e[i].getTaxRuleId();if(t.has(r))throw new ae("Duplicate tax rule ID found: "+r);t.add(r);}}addSubItems(e,t){e.forEach(i=>{let r=this.subItems.find(o=>o.size===i.size);r?r.quantity=t?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity>0),this.calculateTotals();}updateProductData(e,t,i){if(this.productKey!==e.getKey()||!e.validateSelectionAttribute(this.selectionAttributes))throw new ue;if(!e.getIsActive())throw new de;this.subItems.forEach(c=>{if(!e.validateSize(c.size))throw new ge});let r=e.getPriceDetails(t);if(!r||r.getCurrency()!==i)throw new pe;this.name=e.getName(),this.specifications=e.getSpecifications(),this.sku=e.getSku(this.selectionAttributes),this.primaryImage=e.getImages(this.selectionAttributes).primary;let o=this.subItems.reduce((c,u)=>c+u.quantity,0),a=r.getApplicableUnitPrice(o,this.selectionAttributes);this.productType=e.getProductType(),this.pricing={unitPrice:a,tierPricing:r,taxCategory:r.getTaxCategory(),applicableTaxRule:this.pricing.applicableTaxRule},this.calculateTotals();}updateDiscounts(e){let t={};e.forEach(i=>{t[i.coupon.getCode()]=i.amount;}),this.total.discountBreakdown=t,this.calculateTotals();}updateTax(e){e.forEach(t=>{if(!t.appliesTo(this.pricing.taxCategory,t.getCountry()))throw new z}),this.validateTaxRules(e),this.pricing.applicableTaxRule=e,this.calculateTotals();}calculateTotals(){let e=this.pricing.unitPrice.zero(),t=this.subItems.reduce((b,C)=>b+C.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,unitPrice:e,subtotal:e,discountTotal:e,discountBreakdown:{},netUnitPrice:e,netSubtotal:e,taxTotal:e,taxBreakdown:{},grandTotal:e};return}let i=this.pricing.tierPricing.getApplicableUnitPrice(t,this.selectionAttributes),r=i.multiply(t),o=Object.values(this.total.discountBreakdown).reduce((b,C)=>b.add(C),e),a=r.subtract(o),c=t>0?a.divide(t):e,u={},s=e,d=i,g=r,y=a,T=c;this.pricing.tierPricing.getIsTaxInclusive()?(d=W(i,this.pricing.applicableTaxRule),g=d.multiply(t),c.getAmount()>0&&(T=W(c,this.pricing.applicableTaxRule),y=T.multiply(t),he(T,c,this.pricing.applicableTaxRule).forEach(C=>{let S=C.taxAmount.multiply(t).round(),v=this.pricing.applicableTaxRule.find(D=>D.getTaxRuleId()===C.ruleId);u[C.ruleId]={rate:C.rate,taxableUnitPrice:T,taxPerUnit:C.taxAmount,taxAmount:S,system:v.getTaxSystem(),subSystem:v.getTaxSubSystem()},s=s.add(S);}))):this.pricing.applicableTaxRule.forEach(b=>{let C=b.getApplicableTaxRate(T),S=b.calculateTax(T),v=S.multiply(t).round();u[b.getTaxRuleId()]={rate:C,taxableUnitPrice:T,taxPerUnit:S,taxAmount:v,system:b.getTaxSystem(),subSystem:b.getTaxSubSystem()},s=s.add(v);});let A=y.add(s);this.total={quantity:t,unitPrice:d,subtotal:g,discountTotal:o,discountBreakdown:this.total.discountBreakdown,netUnitPrice:T,netSubtotal:y,taxTotal:s,taxBreakdown:u,grandTotal:A};}updateState(e){if(this.state in oe)this.state!==e&&(this.state=e);else throw new se(e)}clearLineItem(){let e=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.sku="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new B({sources:{original:""}}),this.subItems=[],this.productType="GOODS",this.pricing={unitPrice:e,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[]},this.total={quantity:0,unitPrice:e,subtotal:e,discountTotal:e,discountBreakdown:{},netUnitPrice:e,netSubtotal:e,taxTotal:e,taxBreakdown:{},grandTotal:e};}};var _=class extends M{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(e,t=new Date){if(super(e,t),this.couponCode=e.couponCode,this.name=m.deepClone(e.name),this.description=m.deepClone(e.description),this.type=e.type,this.customerId=e.customerId,this.validFrom=e.validFrom&&Date.parse(e.validFrom)?new Date(e.validFrom).toISOString():t.toISOString(),this.validTo=e.validTo&&Date.parse(e.validTo)?new Date(e.validTo).toISOString():t.toISOString(),this.minCartValue=Object.keys(e.minCartValue).reduce((i,r)=>{let o=e.minCartValue[r];return o&&(i[r]=new l(o)),i},{}),this.maxCartDiscount=Object.keys(e.maxCartDiscount).reduce((i,r)=>{let o=e.maxCartDiscount[r];return o&&(i[r]=new l(o)),i},{}),this.discountMethod=e.discountMethod,this.percentageValue=e.percentageValue??0,this.percentageValue>100)throw new I("Percentage value cannot be greater than 100");this.applicableTo=e.applicableTo,this.category=e.category;}getCode(){return this.couponCode}getName(e){return e?this.name[e]??this.name[P[e]]??this.name.en:{...this.name}}getDescription(e){return e?this.description[e]??this.description[P[e]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(e){return e?this.minCartValue[e]:{...this.minCartValue}}getMaxCartDiscount(e){return e?this.maxCartDiscount[e]:{...this.maxCartDiscount}}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:Object.keys(this.getMinCartValue()).reduce((e,t)=>{let i=this.getMinCartValue(t);return i&&(e[t]=i.getDetails()),e},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((e,t)=>{let i=this.getMaxCartDiscount(t);return i&&(e[t]=i.getDetails()),e},{}),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(e){return this.applicableTo==="all"||this.applicableTo==="ftb"&&e}calculateApplicableCouponDiscount(e,t,i,r,o=!0){let a=new l({amount:0,currency:r}),c;if(o&&!this.isActive())return a;let u=this.getMinCartValue(i),s=this.getMaxCartDiscount(i);if(!u||u.compareTo(e)>0||!s)return a;let d=this.getCategory(),g=this.getDiscountMethod(),y=d==="SHIPPING"?t:e;if(y.getAmount()<=0)return a;switch(g){case"flat":let A=s;c=y.min(A);break;case"percentage":c=y.multiply(this.getPercentageValue()/100).round();break;default:return a}return c.min(s)}};var q=class extends R{id;name;type;category;impact;pricing;lineItemId;total;constructor(e){if(super(e),this.id=e.id,this.name=e.name,this.type=e.type,this.category=e.category,this.impact=e.impact,this.lineItemId=e.lineItemId,this.pricing={baseChargeAmount:new l(e.pricing.baseChargeAmount),taxCategory:e.pricing.taxCategory,applicableTaxRule:e.pricing.applicableTaxRule.map(t=>new $(t))},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new X("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={chargeAmount:new l(e.total.chargeAmount),discountTotal:new l(e.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(e.total.discountBreakdown).map(([t,i])=>[t,new l(i)])),netChargeAmount:new l(e.total.netChargeAmount),taxBreakdown:Object.fromEntries(Object.entries(e.total.taxBreakdown).map(([t,i])=>[t,{rate:i.rate,taxableAmount:new l(i.taxableAmount),taxAmount:new l(i.taxAmount),system:i.system,subSystem:i.subSystem}])),taxTotal:new l(e.total.taxTotal),grandTotal:new l(e.total.grandTotal)};}getId(){return this.id}getName(e){return e?m.deepClone(this.name[e]??this.name[P[e]]??this.name.en):m.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getPricing(){return {baseChargeAmount:this.pricing.baseChargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {chargeAmount:this.total.chargeAmount,discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},netChargeAmount:this.total.netChargeAmount,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,t])=>[e,{rate:t.rate,taxableAmount:t.taxableAmount,taxAmount:t.taxAmount,system:t.system,subSystem:t.subSystem}])),grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(e){if(this.type==="ADJUSTMENT"&&e.length>0)throw new X("Adjustment charges cannot apply tax rules.");e.forEach(t=>{if(!t.appliesTo(this.pricing.taxCategory,t.getCountry()))throw new z}),this.validateTaxRules(e),this.pricing.applicableTaxRule=e,this.calculateTotals();}validateTaxRules(e){if(this.impact==="SUBTRACT"&&e.some(i=>i.getRate()>0))throw new V("Subtractive charges cannot have positive tax rates.");let t=new Set;for(let i=0;i<e.length;i++){let r=e[i].getTaxRuleId();if(t.has(r))throw new V("Duplicate tax rule ID found: "+r);t.add(r);for(let o=i+1;o<e.length;o++){let a=e[i],c=e[o],u=a.getMinPrice(),s=a.getMaxPrice(),d=a.getExcludeMin(),g=a.getExcludeMax(),y=c.getMinPrice(),T=c.getMaxPrice(),A=c.getExcludeMin(),b=c.getExcludeMax(),C=(()=>{if(!s)return !1;let D=s.compareTo(y);return D<0||D===0&&(g||A)})(),S=(()=>{if(!T)return !1;let D=T.compareTo(u);return D<0||D===0&&(b||d)})();if(!(C||S)&&!(u.compareTo(y)===0&&d===A&&g===b&&(!s&&!T||s&&T&&s.compareTo(T)===0)))throw new V(`Overlapping rules found: [${a.getTaxRuleId()}: ${d?"(":"["}${u.getAmount()}-${s?.getAmount()??"Infinity"}${g?")":"]"}] and [${c.getTaxRuleId()}: ${A?"(":"["}${y.getAmount()}-${T?.getAmount()??"Infinity"}${b?")":"]"}]`)}}}updateDiscounts(e){let t={};e.forEach(i=>{t[i.coupon.getCode()]=i.amount;}),this.total.discountBreakdown=t,this.calculateTotals();}calculateTotals(){let e=this.pricing.baseChargeAmount.zero(),t=this.pricing.baseChargeAmount,i=Object.values(this.total.discountBreakdown).reduce((g,y)=>g.add(y),e),r=t.subtract(i),o={};if(this.pricing.applicableTaxRule.reduce((g,y)=>g+y.getApplicableTaxRate(r),0)<=0){this.total={chargeAmount:t,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:r,taxTotal:e,taxBreakdown:{},grandTotal:r};return}let c=W(r,this.pricing.applicableTaxRule),u=he(c,r,this.pricing.applicableTaxRule),s=e;u.forEach(g=>{let y=this.pricing.applicableTaxRule.find(T=>T.getTaxRuleId()===g.ruleId);o[g.ruleId]={rate:g.rate,taxableAmount:c,taxAmount:g.taxAmount,system:y.getTaxSystem(),subSystem:y.getTaxSubSystem()},s=s.add(g.taxAmount);});let d=r;this.total={chargeAmount:t,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:r,taxBreakdown:o,taxTotal:s,grandTotal:d};}getDetails(){return {id:this.id,name:m.deepClone(this.name),type:this.type,category:this.category,pricing:{baseChargeAmount:this.pricing.baseChargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(t=>t.getDetails())},impact:this.impact,lineItemId:this.lineItemId,total:{chargeAmount:this.total.chargeAmount.getDetails(),discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([t,i])=>[t,i.getDetails()])),netChargeAmount:this.total.netChargeAmount.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,i])=>[t,{rate:i.rate,taxableAmount:i.taxableAmount.getDetails(),taxAmount:i.taxAmount.getDetails(),system:i.system,subSystem:i.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};var Ie=class extends M{id;customerId;customerEmail;anonymousId;lineItems;charges;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;#e;constructor(e,t=new Date,i={checkCouponExpiry:!0}){super(e,t),this.id=e.id,this.customerId=e.customerId,this.customerEmail=e.customerEmail,this.anonymousId=e.anonymousId,this.country=e.country,this.currency=e.currency,this.locale=e.locale,this.lineItems=(e.lineItems??[]).map(r=>new G(r)),this.charges=(e.charges??[]).map(r=>new q(r)),this.billingAddress=e.billingAddress?new N(e.billingAddress,t):null,this.shippingAddress=e.shippingAddress?new N(e.shippingAddress,t):null,this.coupons=(e.coupons??[]).map(r=>new _(r)),this.shippingDetails=e.shippingDetails?m.deepClone(e.shippingDetails):null,this.total={lineItemSubtotal:new l(e.total.lineItemSubtotal),netLineItemSubtotal:new l(e.total.netLineItemSubtotal),lineItemTaxTotal:new l(e.total.lineItemTaxTotal),lineItemTaxBreakdown:this.mapTaxBreakdown(e.total.lineItemTaxBreakdown),additiveCharges:new l(e.total.additiveCharges),netAdditiveCharges:new l(e.total.netAdditiveCharges),additiveChargesTaxTotal:new l(e.total.additiveChargesTaxTotal),additiveChargesTaxBreakdown:this.mapTaxBreakdown(e.total.additiveChargesTaxBreakdown),adjustmentCharges:new l(e.total.adjustmentCharges),shippingCharges:new l(e.total.shippingCharges),netShippingCharges:new l(e.total.netShippingCharges),discountTotal:new l(e.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(e.total.discountBreakdown).map(([r,o])=>[r,new l(o)])),taxTotal:new l(e.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(e.total.taxBreakdown),grandTotal:new l(e.total.grandTotal)},this.#e={checkCouponExpiry:i.checkCouponExpiry};}mapTaxBreakdown(e){return Object.fromEntries(Object.entries(e||{}).map(([t,i])=>[t,{system:i.system,totalAmount:new l(i.totalAmount),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,o])=>[r,new l(o)]))}]))}serializeTaxBreakdown(e){return Object.fromEntries(Object.entries(e||{}).map(([t,i])=>[t,{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(e=>new G(e.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(e=>new q(e.getDetails()))}addCharge(e){this.charges.push(e),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?m.deepClone(this.shippingDetails):null}getShippingAddress(){return this.shippingAddress?new N(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new N(this.billingAddress.getDetails()):null}getCoupons(){return [...this.coupons]}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {lineItemSubtotal:this.total.lineItemSubtotal,netLineItemSubtotal:this.total.netLineItemSubtotal,lineItemTaxTotal:this.total.lineItemTaxTotal,lineItemTaxBreakdown:Object.fromEntries(Object.entries(this.total.lineItemTaxBreakdown).map(([e,t])=>[e,{system:t.system,totalAmount:t.totalAmount,subSystems:{...t.subSystems}}])),additiveCharges:this.total.additiveCharges,netAdditiveCharges:this.total.netAdditiveCharges,additiveChargesTaxTotal:this.total.additiveChargesTaxTotal,additiveChargesTaxBreakdown:Object.fromEntries(Object.entries(this.total.additiveChargesTaxBreakdown).map(([e,t])=>[e,{system:t.system,totalAmount:t.totalAmount,subSystems:{...t.subSystems}}])),adjustmentCharges:this.total.adjustmentCharges,shippingCharges:this.total.shippingCharges,netShippingCharges:this.total.netShippingCharges,discountBreakdown:{...this.total.discountBreakdown},discountTotal:this.total.discountTotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,t])=>[e,{system:t.system,totalAmount:t.totalAmount,subSystems:{...t.subSystems}}])),grandTotal:this.total.grandTotal}}getDetails(){let e=this.getTotal();return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(t=>t.getDetails()),charges:this.getCharges().map(t=>t.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(t=>t.getDetails()),total:{lineItemSubtotal:e.lineItemSubtotal.getDetails(),netLineItemSubtotal:e.netLineItemSubtotal.getDetails(),lineItemTaxTotal:e.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(e.lineItemTaxBreakdown),additiveCharges:e.additiveCharges.getDetails(),netAdditiveCharges:e.netAdditiveCharges.getDetails(),additiveChargesTaxTotal:e.additiveChargesTaxTotal.getDetails(),additiveChargesTaxBreakdown:this.serializeTaxBreakdown(e.additiveChargesTaxBreakdown),adjustmentCharges:e.adjustmentCharges.getDetails(),shippingCharges:e.shippingCharges.getDetails(),netShippingCharges:e.netShippingCharges.getDetails(),discountTotal:e.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(e.discountBreakdown).map(([t,i])=>[t,i.getDetails()])),taxTotal:e.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(e.taxBreakdown),grandTotal:e.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let e=new l({amount:0,currency:this.currency}),t=this.lineItems.filter(p=>p.getState()!=="CANCELLED"),i=t.reduce((p,h)=>p.add(h.getTotal().subtotal),e),r=this.charges.filter(p=>p.getType()==="SHIPPING").reduce((p,h)=>p.add(h.getTotal().chargeAmount),e);this.total.lineItemSubtotal=i,this.total.shippingCharges=r;let o=e,a={},c={};this.coupons.forEach(p=>{let h=p.calculateApplicableCouponDiscount(i,r,this.country,this.currency,this.#e.checkCouponExpiry);o=o.add(h),a[p.getCode()]=h,p.getCategory()!=="SHIPPING"&&(c[p.getCode()]=h);}),this.total.discountTotal=o,this.total.discountBreakdown=a,this.applyDiscountsInLineItem(c);let u=this.coupons.find(p=>p.getCategory()==="SHIPPING");u?this.applyDiscountsInShippingCharges({[u.getCode()]:a[u.getCode()]||e}):this.applyDiscountsInShippingCharges({});let s=this.lineItems.reduce((p,h)=>p.add(h.getTotal().netSubtotal),e),d=this.charges.filter(p=>p.getType()==="SHIPPING").reduce((p,h)=>p.add(h.getTotal().grandTotal),e);this.total.netLineItemSubtotal=s,this.total.netShippingCharges=d;let g=this.charges.filter(p=>p.getImpact()==="ADD").reduce((p,h)=>p.add(h.getTotal().chargeAmount),e),y=this.charges.filter(p=>p.getImpact()==="ADD").reduce((p,h)=>p.add(h.getTotal().grandTotal),e),T=this.charges.filter(p=>p.getImpact()==="SUBTRACT").reduce((p,h)=>p.add(h.getTotal().grandTotal),e),A=e,b=e,C=e,S={},v={},D={},ee=(p,h)=>{Object.entries(p).forEach(([He,Q])=>{let L=Q.system,te=Q.subSystem;h[L]||(h[L]={system:L,totalAmount:e,subSystems:{}}),h[L].subSystems[te]?h[L].subSystems[te]=h[L].subSystems[te].add(Q.taxAmount):h[L].subSystems[te]=Q.taxAmount,h[L].totalAmount=h[L].totalAmount.add(Q.taxAmount);});};t.forEach(p=>{let h=p.getTotal().taxBreakdown;h&&(ee(h,v),ee(h,S),b=b.add(p.getTotal().taxTotal));}),this.charges.forEach(p=>{let h=p.getTotal().taxBreakdown;h&&(ee(h,D),ee(h,S),C=C.add(p.getTotal().taxTotal));}),A=b.add(C);let Le=s.add(b).add(y).subtract(T);this.total={lineItemSubtotal:i,netLineItemSubtotal:s,lineItemTaxTotal:b,lineItemTaxBreakdown:v,additiveCharges:g,netAdditiveCharges:y,additiveChargesTaxTotal:C,additiveChargesTaxBreakdown:D,adjustmentCharges:T,shippingCharges:r,netShippingCharges:d,discountTotal:o,discountBreakdown:a,taxTotal:A,taxBreakdown:S,grandTotal:Le};}updateShippingDetails(e){this.shippingDetails=e;}applyCoupons(e){let t=e.filter(r=>r.getCategory()==="SHIPPING"),i=e.filter(r=>r.getCategory()!=="SHIPPING");this.coupons=[],this.total.discountTotal=this.total.lineItemSubtotal.zero(),this.total.discountBreakdown={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.discountBreakdown),t.length&&this.applyShippingCoupons(t),this.calculateTotals();}applyDiscountsInLineItem(e){let t=Array.from(Object.entries(e)).filter(r=>!r[1].isZero()),i=new Map;this.lineItems.forEach(r=>i.set(r.getId(),[])),t.forEach(([r,o])=>{let a=this.coupons.find(s=>s.getCode()===r);if(!a||o.isZero())return;let c=this.lineItems.filter(s=>s.getState()!=="CANCELLED"&&!s.getTotal().subtotal.isZero()).sort((s,d)=>s.getTotal().subtotal.compareTo(d.getTotal().subtotal)),u=new l({amount:0,currency:this.currency});c.forEach((s,d)=>{let g;d===c.length-1?g=o.subtract(u):g=o.multiply(s.getTotal().subtotal).divide(this.total.lineItemSubtotal).round(),u=u.add(g),i.get(s.getId())?.push({coupon:a,amount:g});});}),this.lineItems.forEach(r=>{r.getState()==="CANCELLED"||this.total.lineItemSubtotal.isZero()?r.updateDiscounts([]):r.updateDiscounts(i.get(r.getId())||[]);});}applyDiscountsInShippingCharges(e){let t=Array.from(Object.entries(e)).filter(o=>!o[1].isZero()),i=this.charges.filter(o=>o.getType()==="SHIPPING"),r=new Map;i.forEach(o=>r.set(o.getId(),[])),t.forEach(([o,a])=>{let c=this.coupons.find(d=>d.getCode()===o);if(!c||a.isZero())return;let u=i.sort((d,g)=>d.getTotal().grandTotal.compareTo(g.getTotal().grandTotal)),s=new l({amount:0,currency:this.currency});u.forEach((d,g)=>{let y;g===u.length-1?y=a.subtract(s):y=a.multiply(d.getTotal().chargeAmount).divide(this.total.shippingCharges).round(),s=s.add(y),r.get(d.getId())?.push({coupon:c,amount:y});});}),i.forEach(o=>{o.updateDiscounts(r.get(o.getId())||[]);});}applyNonShippingCoupons(e){let t=e.filter(i=>i.getType()==="coupon");if(t.length===1){let i=t[0].calculateApplicableCouponDiscount(this.total.lineItemSubtotal,this.total.shippingCharges,this.country,this.currency,this.#e.checkCouponExpiry);i.getAmount()>0&&(this.coupons.push(t[0]),this.total.discountTotal=i,this.total.discountBreakdown[t[0].getCode()]=i);}}applyShippingCoupons(e){if(this.total.shippingCharges.getAmount()>0&&e.length>0){let t=this.total.lineItemSubtotal.subtract(this.total.discountTotal),i=e.reduce((o,a)=>{if(!o)return a;let c=a.calculateApplicableCouponDiscount(t,this.total.shippingCharges,this.country,this.currency,this.#e.checkCouponExpiry).min(this.total.shippingCharges),u=o.calculateApplicableCouponDiscount(t,this.total.shippingCharges,this.country,this.currency,this.#e.checkCouponExpiry).min(this.total.shippingCharges);return c.compareTo(u)===0?a.getType()==="coupon"?a:o:c.compareTo(u)>0?a:o}),r=i.calculateApplicableCouponDiscount(t,this.total.shippingCharges,this.country,this.currency,this.#e.checkCouponExpiry).min(this.total.shippingCharges);r.getAmount()>0&&(this.coupons.push(i),this.total.discountTotal=this.total.discountTotal.add(r),this.total.discountBreakdown[i.getCode()]=r);}}};module.exports=Ie;//# sourceMappingURL=ShoppingContainer.js.map
1
+ 'use strict';var Re=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Re__default=/*#__PURE__*/_interopDefault(Re);var Ae=n=>structuredClone(n),B=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:Ae(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return Ae(this.customFields)}},M=class extends B{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.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(e,t,i,r){this.modifiedBy={id:e,authType:t,requestId:i,lambdaName:r};}};var U=class extends M{id;firstName;lastName;company;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(e,t=new Date){super(e,t),this.id=e.id,this.firstName=e.firstName,this.lastName=e.lastName||"",this.company=e.company||"",this.phone=e.phone,this.email=e.email,this.addressLine1=e.addressLine1,this.addressLine2=e.addressLine2||"",this.city=e.city,this.postalCode=e.postalCode,this.state=e.state,this.country=e.country,this.isBillingAddress=e.isBillingAddress,this.isShippingAddress=e.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(e){return e==="shipping"||e==="billing&shipping"}static checkIfBillingAddress(e){return e==="billing"||e==="billing&shipping"}};var re=new Uint8Array(256),ie=re.length;function ye(){return ie>re.length-16&&(Re__default.default.randomFillSync(re),ie=0),re.slice(ie,ie+=16)}var Se=/^(?:[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 Be(n){return typeof n=="string"&&Se.test(n)}var De=Be;var f=[];for(let n=0;n<256;++n)f.push((n+256).toString(16).slice(1));function ne(n,e=0){return f[n[e+0]]+f[n[e+1]]+f[n[e+2]]+f[n[e+3]]+"-"+f[n[e+4]]+f[n[e+5]]+"-"+f[n[e+6]]+f[n[e+7]]+"-"+f[n[e+8]]+f[n[e+9]]+"-"+f[n[e+10]]+f[n[e+11]]+f[n[e+12]]+f[n[e+13]]+f[n[e+14]]+f[n[e+15]]}function ke(n){if(!De(n))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(n.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(n.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(n.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(n.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(n.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var Me=ke;function Ne(n){n=unescape(encodeURIComponent(n));let e=[];for(let t=0;t<n.length;++t)e.push(n.charCodeAt(t));return e}var Ue="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Oe="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function be(n,e,t){function i(r,o,a,c){var u;if(typeof r=="string"&&(r=Ne(r)),typeof o=="string"&&(o=Me(o)),((u=o)===null||u===void 0?void 0:u.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let s=new Uint8Array(16+r.length);if(s.set(o),s.set(r,o.length),s=t(s),s[6]=s[6]&15|e,s[8]=s[8]&63|128,a){c=c||0;for(let d=0;d<16;++d)a[c+d]=s[d];return a}return ne(s)}try{i.name=n;}catch{}return i.DNS=Ue,i.URL=Oe,i}var Te={randomUUID:Re__default.default.randomUUID};function ze(n,e,t){if(Te.randomUUID&&!e&&!n)return Te.randomUUID();n=n||{};let i=n.random||(n.rng||ye)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(let r=0;r<16;++r)e[t+r]=i[r];return e}return ne(i)}var xe=ze;function Ve(n){return Array.isArray(n)?n=Buffer.from(n):typeof n=="string"&&(n=Buffer.from(n,"utf8")),Re__default.default.createHash("sha1").update(n).digest()}var we=Ve;var $e=be("v5",80,we),Ce=$e;var P={"en-IN":"en","kn-IN":"kn"};var Ee={INR:"\u20B9"},ve={INR:"en-IN"};var oe=(g=>(g.INITIAL="INITIAL",g.PROCESSING="PROCESSING",g.SHIPPED="SHIPPED",g.DELIVERED="DELIVERED",g.CANCELLED="CANCELLED",g.RETURN_REQUESTED="RETURN_REQUESTED",g.RETURNED="RETURNED",g.UNDELIVERED="UNDELIVERED",g.REFUND_INITIATED="REFUND_INITIATED",g.REFUNDED="REFUNDED",g.ON_HOLD="ON_HOLD",g))(oe||{});var se=class extends Error{constructor(e){super(`Invalid line item state: ${e}`),this.name="InvalidLineItemStateError";}},ae=class extends Error{constructor(e){super(`InvalidLineItemTaxRule: ${e}`),this.name="InvalidLineItemTaxRuleError";}},ce=class extends Error{constructor(e){super(`Duplicate size found: ${e}`),this.name="DuplicateSizeError";}},le=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}},ue=class extends Error{constructor(e="Product and selection attributes do not match."){super(`ProductMismatch: ${e}`),this.name="ProductMismatchError";}},de=class extends Error{constructor(e="Product is not active."){super(`ProductInactive: ${e}`),this.name="ProductInactiveError";}},w=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}},ge=class extends Error{constructor(e="Size does not match."){super(`SizeMismatch: ${e}`),this.name="SizeMismatchError";}},pe=class extends Error{constructor(e="Pricing details not available for the product"){super(`NotFound: ${e}`),this.name="PricingNotFoundError";}},z=class extends Error{constructor(e="Tax rule category mismatch."){super(`InvalidTaxRule: ${e}`),this.name="InvalidTaxRuleError";}},me=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},K=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},O=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},H=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},Z=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var Y=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},j=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},E=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},I=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},J=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}},X=class extends Error{constructor(e="Invalid charge data."){super(`InvalidCharge: ${e}`),this.name="InvalidChargeError";}},V=class extends Error{constructor(e="Invalid charge tax rule."){super(`InvalidChargeTaxRule: ${e}`),this.name="InvalidChargeTaxRuleError";}},v=class extends Error{constructor(e="Invalid pricing type."){super(`InvalidPricingType: ${e}`),this.name="InvalidPricingTypeError";}};var k=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw new J("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,t){if(t===void 0){if(e==="original")throw new J("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=t;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var l=class n{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new Y("Amount cannot be negative.");if(!e.currency)throw new j("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(n.getPrecisionPlaces(this.currency)));}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}getPreciseAmount(e){return parseFloat(e.toFixed(n.getPrecisionPlaces(this.currency)))}compareTo(e){if(n.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new E("Cannot compare prices in different currencies.")}else throw new I("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(n.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new E("Cannot add prices in different currencies.")}else throw new I("Must be a PriceModel instance.");return new n({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(n.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new E("Cannot subtract prices in different currencies.")}else throw new I("Must be a PriceModel instance.");return new n({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(n.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new E("Cannot multiply prices in different currencies.");return new n({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new n({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new I("Must be a non-negative number.")}divide(e){if(n.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new E("Cannot divide prices in different currencies.");return new n({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new n({amount:this.getPreciseAmount(this.amount/e),currency:this.currency});throw new I("Must be a positive number.")}min(...e){if(e.length===0)throw new I("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(n.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new E("Cannot compare prices in different currencies.")}else throw new I("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i},this)}max(...e){if(e.length===0)throw new I("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(n.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new E("Cannot compare prices in different currencies.")}else throw new I("Must be a PriceModel instance.");return t.compareTo(i)>0?t:i},this)}zero(){return new n({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new n({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return n.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return n.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,t,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let r=ve[t];if(!t||!r)throw new j("Invalid currency code for formatting.");let o=e,a=i.displayAsInteger?0:n.getDecimalPlaces(t),c={style:i.style??"currency",currency:t,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(r,c).format(o)}catch(u){return console.error(`Error formatting price for currency "${t}" and locale "${r}":`,u),`${Ee[t]??t} ${n.addThousandSeparators(o.toFixed(a))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static getPrecisionPlaces(e){switch(e){case"INR":default:return 6}}static addThousandSeparators(e){let t=e.split("."),i=t[0],r=t.length>1?"."+t[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+r}static getRoundedAmount(e,t){if(e<0)throw new Y("Amount cannot be negative for rounding.");if(t===void 0)throw new j("Invalid currency code for rounding.");let i=n.getDecimalPlaces(t),r=Math.pow(10,i);return Math.round(e*r)/r}static getSmallestUnit(e){let t=n.getDecimalPlaces(e);return 1/Math.pow(10,t)}};var F=class{type;taxCategory;isTaxInclusive;static create(e){return e.type==="selection"?new Pe(e):new fe(e)}constructor(e){if(!e.taxCategory)throw new me;this.taxCategory=e.taxCategory,this.isTaxInclusive=e.isTaxInclusive??!1,this.type=e.type??"volume";}getType(){return this.type}getTaxCategory(){return this.taxCategory}getIsTaxInclusive(){return this.isTaxInclusive}},fe=class extends F{baseUnitPrice;tiers;currency;constructor(e){if(super(e),this.type="volume",!e.baseUnitPrice)throw new O("Base unit price is required for volume pricing.");this.baseUnitPrice=new l(e.baseUnitPrice),this.currency=e.currency??this.baseUnitPrice.getCurrency();let t=(e.tiers??[]).map(c=>({enabled:c.enabled??!0,minQuantity:c.minQuantity,unitPrice:new l(c.unitPrice)})).sort((c,u)=>c.minQuantity-u.minQuantity);if(t.some(c=>c.minQuantity<=0))throw new K;let r=this.baseUnitPrice.getCurrency()!==this.currency||t.some(c=>c.unitPrice.getCurrency()!==this.currency),o=t.some((c,u)=>u>0&&c.unitPrice.compareTo(t[u-1].unitPrice)>0),a=t[0]?.unitPrice.compareTo(this.baseUnitPrice)>0;if(r||o||a)throw new O("Tiers must share the same currency and must not increase in unit price.");this.tiers=t;}isPriceAvailable(){return this.tiers.filter(e=>e.enabled).length>0}getBaseUnitPrice(){return this.baseUnitPrice}getCurrency(){return this.baseUnitPrice.getCurrency()}getApplicableUnitPrice(e){if(e<=0)throw new H;let t=this.tiers.filter(i=>i.enabled);for(let i=t.length-1;i>=0;i--){let r=t[i];if(e>=r.minQuantity)return r.unitPrice}throw new Z(e)}getMinQuantity(){return this.tiers.filter(t=>t.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(){let e=this.tiers.filter(o=>o.enabled);if(!e.length)return 0;let t=Math.min(...e.map(o=>o.unitPrice.getAmount())),i=this.baseUnitPrice.getAmount(),r=(i-t)/i*100;return r>0?r:0}getMinPrice(){let e=this.tiers.filter(t=>t.enabled);return e.length?e[e.length-1].unitPrice:null}getMaxPrice(){let e=this.tiers.filter(t=>t.enabled);return e.length?e[0].unitPrice:null}getTiers(){return this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,baseUnitPrice:this.baseUnitPrice.getDetails(),tiers:this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}},Pe=class extends F{currency;selections;constructor(e){super(e),this.type="selection",this.currency=e.currency,this.selections=(e.selections??[]).map(t=>{if(!t.baseUnitPrice)throw new O("Base unit price is required for each selection.");let i=new l(t.baseUnitPrice),r=(t.tiers??[]).map(s=>({enabled:s.enabled??!0,minQuantity:s.minQuantity??1,unitPrice:new l(s.unitPrice)})).sort((s,d)=>s.minQuantity-d.minQuantity);if(r.some(s=>s.minQuantity<=0))throw new K;let a=i.getCurrency()!==this.currency||r.some(s=>s.unitPrice.getCurrency()!==this.currency),c=r.some((s,d)=>d>0&&s.unitPrice.compareTo(r[d-1].unitPrice)>0),u=r[0]?.unitPrice.compareTo(i)>0;if(a||c||u)throw new O("Tiers must share the same currency and must not increase in unit price within the same selection.");return {selectionAttributes:{...t.selectionAttributes},baseUnitPrice:i,tiers:r}});}findMatch(e,t=!1){let i=N.generateSelectionAttributesKey(e),r=this.selections.find(o=>N.generateSelectionAttributesKey(o.selectionAttributes)===i);if(!r&&t)throw new O("No pricing configuration found for selection variant.");return r??null}isPriceAvailable(e){if(!e)return console.warn("Selection attributes are required to check price availability for selection pricing."),!1;let t=this.findMatch(e);return t?t.tiers.filter(i=>i.enabled).length>0:!1}getBaseUnitPrice(e){if(!e)throw new v("Selection attributes are required to get base unit price for selection pricing.");return this.findMatch(e,!0).baseUnitPrice}getCurrency(){return this.currency}getApplicableUnitPrice(e,t){if(e<=0)throw new H;if(!t)throw new v("Selection attributes are required to get applicable unit price for selection pricing.");let r=this.findMatch(t,!0).tiers.filter(o=>o.enabled);for(let o=r.length-1;o>=0;o--){let a=r[o];if(e>=a.minQuantity)return a.unitPrice}throw new Z(e)}getMinQuantity(e){if(!e)throw new v("Selection attributes are required to get min quantity for selection pricing.");return this.findMatch(e,!0).tiers.filter(r=>r.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(e){if(!e)throw new v("Selection attributes are required to get max discount for selection pricing.");let t=this.findMatch(e,!0),i=t.tiers.filter(c=>c.enabled);if(!i.length)return 0;let r=Math.min(...i.map(c=>c.unitPrice.getAmount())),o=t.baseUnitPrice.getAmount(),a=(o-r)/o*100;return a>0?a:0}getTiers(e){if(!e)throw new v("Selection attributes are required to get tiers for selection pricing.");return this.findMatch(e,!0).tiers.map(i=>({enabled:i.enabled,minQuantity:i.minQuantity,unitPrice:i.unitPrice}))}getMinPrice(e){if(!e)throw new v("Selection attributes are required to get min price for selection pricing.");let t=this.findMatch(e);if(!t)return null;let i=t.tiers.filter(r=>r.enabled);return i.length?i[i.length-1].unitPrice:null}getMaxPrice(e){if(!e)throw new v("Selection attributes are required to get max price for selection pricing.");let t=this.findMatch(e);if(!t)return null;let i=t.tiers.filter(r=>r.enabled);return i.length?i[0].unitPrice:null}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,selections:this.selections.map(e=>({selectionAttributes:e.selectionAttributes,baseUnitPrice:e.baseUnitPrice.getDetails(),...e.tiers.length>0?{tiers:e.tiers.map(t=>({enabled:t.enabled,minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}:{}}))}}};var N=class n extends M{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;productType;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new w("Selection attributes must be an object");return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let t={},i=e.split("|");for(let r of i){let[o,a]=r.split(":");a.startsWith("c+")?t[o]={name:a.slice(2)}:t[o]=a;}return t}catch(t){throw new w(t?.message)}}constructor(e,t=new Date){super(e,t),this.id=e.id,this.key=e.key,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((r,o)=>(e.pricing[o]&&(r[o]=F.create(e.pricing[o])),r),{}),this.targetGender=e.targetGender,this.attributes=m.deepClone(e.attributes),this.specifications=m.deepClone(e.specifications),this.categories=m.deepClone(e.categories),this.productType=e.productType??"GOODS";let i=new Set;this.variants=(e.variants||[]).map(r=>{if(!r.selectionAttributes||typeof r.selectionAttributes!="object")throw new w("Selection attributes are required");this.checkSelectionAttributes(r.selectionAttributes);let o=n.generateSelectionAttributesKey(r.selectionAttributes);if(i.has(o))throw new le(o);return i.add(o),{sku:r.sku,selectionAttributes:r.selectionAttributes,images:{primary:new k(r.images.primary),gallery:(r.images.gallery||[]).map(a=>new k(a))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?m.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[P[e]]??this.name.en:m.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[P[e]]??this.description.en:m.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[P[e]]??this.slug.en:m.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return m.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:m.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let t=n.generateSelectionAttributesKey(e),i=this.variants.find(r=>n.generateSelectionAttributesKey(r.selectionAttributes)===t);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,t){switch(t){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return m.deepClone(this.categories)}getProductType(){return this.productType}getSpecifications(e){return e?m.deepClone(this.specifications[e]??this.specifications[P[e]]??this.specifications.en):m.deepClone(this.specifications)}getSearchTags(e){return e?m.deepClone(this.searchTags[e]??this.searchTags[P[e]]??this.searchTags.en):m.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((t,i)=>(this.pricing[i]&&(t[i]=this.pricing[i]?.getDetails()),t),{}),attributes:this.getAttributes(),variants:this.variants.map(t=>({sku:t.sku,selectionAttributes:m.deepClone(t.selectionAttributes),images:{primary:t.images.primary.getDetails(),gallery:t.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),productType:this.getProductType(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new w("Selection attributes are required");Object.keys(this.attributes).forEach(t=>{if(t.toLowerCase()==="size")return;let i=this.attributes[t],r=e[t];if(r===void 0)throw new w(`Selection attribute '${t}' is missing`);if(typeof i=="string"){if(typeof r!="string"||i!==r)throw new w(`Selection attribute '${t}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof r!="string"||!i.includes(r))throw new w(`Selection attribute '${t}' is invalid`)}else if(typeof r!="object"||!("name"in r)||i.findIndex(o=>o.name===r.name)<0)throw new w(`Selection attribute '${t}' is invalid`)}});}getSku(e){let t=n.generateSelectionAttributesKey(e);return this.variants.find(r=>n.generateSelectionAttributesKey(r.selectionAttributes)===t)?.sku}validateSelectionAttribute(e){let t=n.generateSelectionAttributesKey(e);return this.variants.some(i=>n.generateSelectionAttributesKey(i.selectionAttributes)===t)}validateSize(e){return this.attributes.size.includes(e)}};var qe={isUUID:n=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n),isEmail:n=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(n),isURL:n=>/^(http|https):\/\/[^ "]+$/.test(n),generateUUID:(n,e)=>e&&n?Ce(n,e):xe(),generateSearchId:(n,e)=>`${n}#${N.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:n=>{let[e,t]=n.split("#");return {key:e,selectionAttributes:N.parseSelectionAttributesKey(t)}},deepClone(n){return structuredClone(n)}},m=qe;var $=class extends B{taxRuleId;taxCategory;taxSystem;taxSubSystem;country;rate;minPrice;maxPrice;excludeMin;excludeMax;effectiveFrom;effectiveTo;constructor(e){super(e),this.taxRuleId=e.taxRuleId,this.taxSystem=e.taxSystem,this.taxSubSystem=e.taxSubSystem,this.taxCategory=e.taxCategory,this.country=e.country,this.rate=e.rate,this.minPrice=new l(e.minPrice),this.maxPrice=e.maxPrice?new l(e.maxPrice):void 0,this.excludeMin=e.excludeMin??!1,this.excludeMax=e.excludeMax??!1,this.effectiveFrom=new Date(e.effectiveFrom).toISOString(),this.effectiveTo=e.effectiveTo?new Date(e.effectiveTo).toISOString():void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getRate(){return this.rate}getMinPrice(){return this.minPrice}getMaxPrice(){return this.maxPrice}getExcludeMin(){return this.excludeMin}getExcludeMax(){return this.excludeMax}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),rate:this.getRate(),minPrice:this.getMinPrice().getDetails(),maxPrice:this.getMaxPrice()?.getDetails(),excludeMin:this.getExcludeMin(),excludeMax:this.getExcludeMax(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0,customFields:this.getAllCustomFields()}}appliesTo(e,t,i,r=new Date){let o=!i||(this.excludeMin?this.minPrice.compareTo(i)<0:this.minPrice.compareTo(i)<=0)&&(this.maxPrice?this.excludeMax?this.maxPrice.compareTo(i)>0:this.maxPrice.compareTo(i)>=0:!0);return this.taxCategory===e&&this.country===t&&o&&Date.parse(this.effectiveFrom)<=r.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=r.getTime():!0)}getApplicableTaxRate(e){return this.appliesTo(this.taxCategory,this.country,e)?this.rate:0}calculateTax(e){return this.appliesTo(this.taxCategory,this.country,e)?e.multiply(this.rate):e.zero()}static getTaxRateDisplayString(e,t,i){let r=t*100,o=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,"");return i?.percentageOnly?`${o}%`:e.getTaxSystem()==="GST"?`${e.getTaxSubSystem()} ${o}%`:`${e.getTaxSystem()} ${o}%`}};var W=(n,e)=>{let t=e.reduce((s,d)=>s+d.getApplicableTaxRate(n),0);if(t<=0)return n;let i=n.divide(1+t).round().getAmount(),r=n.getCurrency(),o=n.getAmount(),a=i,c=Number.POSITIVE_INFINITY,u=1e4;for(let s=0;s<u;s++){let d=new l({amount:i,currency:r}),y=e.sort((b,C)=>C.getApplicableTaxRate(d)-b.getApplicableTaxRate(d)).map(b=>d.multiply(b.getApplicableTaxRate(d)).round().getAmount()).reduce((b,C)=>b+C,0),T=i+y-o,A=e.reduce((b,C)=>b+C.getApplicableTaxRate(d),0);if(Math.abs(T)<Math.abs(c)&&(c=T,a=i),T===0)break;i=i-T/(1+A);}if(Math.abs(c)>l.getSmallestUnit(r))throw new Error("Failed to converge on a valid tax exclusive base.");return new l({amount:a,currency:r})},he=(n,e,t)=>{let i=n.zero(),r=[...t].sort((o,a)=>a.getApplicableTaxRate(n)-o.getApplicableTaxRate(n));return r.map((o,a)=>{let c=o.getApplicableTaxRate(n),u;return a===r.length-1?u=e.subtract(n).subtract(i):u=n.multiply(c).round(),i=i.add(u),{ruleId:o.getTaxRuleId(),taxAmount:u,rate:c}})};var G=class extends B{id;productKey;sku;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;productType;total;constructor(e){super(e),this.id=e.id,this.productKey=e.productKey,this.sku=e.sku,this.selectionAttributes=m.deepClone(e.selectionAttributes),this.name=m.deepClone(e.name),this.specifications=m.deepClone(e.specifications),this.primaryImage=new k(e.primaryImage),this.subItems=m.deepClone(e.subItems);let t=new Set;this.subItems.forEach(i=>{if(t.has(i.size))throw new ce(i.size);t.add(i.size);}),this.pricing={unitPrice:new l(e.pricing.unitPrice),tierPricing:F.create(e.pricing.tierPricing),taxCategory:e.pricing.taxCategory,applicableTaxRule:e.pricing.applicableTaxRule.map(i=>new $(i))},this.validateTaxRules(this.pricing.applicableTaxRule),this.state=e.state??"INITIAL",this.productType=e.productType??"GOODS",this.total={quantity:e.total.quantity,unitPrice:new l(e.total.unitPrice),subtotal:new l(e.total.subtotal),discountTotal:new l(e.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(e.total.discountBreakdown).map(([i,r])=>[i,new l(r)])),netUnitPrice:new l(e.total.netUnitPrice),netSubtotal:new l(e.total.netSubtotal),taxTotal:new l(e.total.taxTotal),taxBreakdown:Object.fromEntries(Object.entries(e.total.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:new l(r.taxableUnitPrice),taxPerUnit:new l(r.taxPerUnit),taxAmount:new l(r.taxAmount),system:r.system,subSystem:r.subSystem}])),grandTotal:new l(e.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSku(){return this.sku}getSelectionAttributes(){return m.deepClone(this.selectionAttributes)}getName(e){return e?m.deepClone(this.name[e]??this.name[P[e]]??this.name.en):m.deepClone(this.name)}getSpecifications(e){return e?m.deepClone(this.specifications[e]??this.specifications[P[e]]??this.specifications.en):m.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return m.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getState(){return this.state}getProductType(){return this.productType}getTotal(){return {quantity:this.total.quantity,unitPrice:this.total.unitPrice,subtotal:this.total.subtotal,discountTotal:this.total.discountTotal,discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([e,t])=>[e,t])),netUnitPrice:this.total.netUnitPrice,netSubtotal:this.total.netSubtotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,t])=>[e,{rate:t.rate,taxableUnitPrice:t.taxableUnitPrice,taxPerUnit:t.taxPerUnit,taxAmount:t.taxAmount,system:t.system,subSystem:t.subSystem}])),grandTotal:this.total.grandTotal}}getDetails(){let e=this.getPricing(),t=this.getTotal();return {id:this.getId(),productKey:this.getProductKey(),sku:this.getSku(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:e.unitPrice.getDetails(),tierPricing:e.tierPricing.getDetails(),taxCategory:e.taxCategory,applicableTaxRule:e.applicableTaxRule.map(i=>i.getDetails())},state:this.getState(),productType:this.getProductType(),total:{quantity:t.quantity,unitPrice:t.unitPrice.getDetails(),subtotal:t.subtotal.getDetails(),discountTotal:t.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(t.discountBreakdown).map(([i,r])=>[i,r.getDetails()])),netUnitPrice:t.netUnitPrice.getDetails(),netSubtotal:t.netSubtotal.getDetails(),taxTotal:t.taxTotal.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(t.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:r.taxableUnitPrice.getDetails(),taxPerUnit:r.taxPerUnit.getDetails(),taxAmount:r.taxAmount.getDetails(),system:r.system,subSystem:r.subSystem}])),grandTotal:t.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}validateTaxRules(e){let t=new Set;for(let i=0;i<e.length;i++){let r=e[i].getTaxRuleId();if(t.has(r))throw new ae("Duplicate tax rule ID found: "+r);t.add(r);}}addSubItems(e,t){e.forEach(i=>{let r=this.subItems.find(o=>o.size===i.size);r?r.quantity=t?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity>0),this.calculateTotals();}updateProductData(e,t,i){if(this.productKey!==e.getKey()||!e.validateSelectionAttribute(this.selectionAttributes))throw new ue;if(!e.getIsActive())throw new de;this.subItems.forEach(c=>{if(!e.validateSize(c.size))throw new ge});let r=e.getPriceDetails(t);if(!r||r.getCurrency()!==i)throw new pe;this.name=e.getName(),this.specifications=e.getSpecifications(),this.sku=e.getSku(this.selectionAttributes),this.primaryImage=e.getImages(this.selectionAttributes).primary;let o=this.subItems.reduce((c,u)=>c+u.quantity,0),a=r.getApplicableUnitPrice(o,this.selectionAttributes);this.productType=e.getProductType(),this.pricing={unitPrice:a,tierPricing:r,taxCategory:r.getTaxCategory(),applicableTaxRule:this.pricing.applicableTaxRule},this.calculateTotals();}updateDiscounts(e){let t={};e.forEach(i=>{t[i.coupon.getCode()]=i.amount;}),this.total.discountBreakdown=t,this.calculateTotals();}updateTax(e){e.forEach(t=>{if(!t.appliesTo(this.pricing.taxCategory,t.getCountry()))throw new z}),this.validateTaxRules(e),this.pricing.applicableTaxRule=e,this.calculateTotals();}calculateTotals(){let e=this.pricing.unitPrice.zero(),t=this.subItems.reduce((b,C)=>b+C.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,unitPrice:e,subtotal:e,discountTotal:e,discountBreakdown:{},netUnitPrice:e,netSubtotal:e,taxTotal:e,taxBreakdown:{},grandTotal:e};return}let i=this.pricing.tierPricing.getApplicableUnitPrice(t,this.selectionAttributes),r=i.multiply(t),o=Object.values(this.total.discountBreakdown).reduce((b,C)=>b.add(C),e),a=r.subtract(o),c=t>0?a.divide(t):e,u={},s=e,d=i,g=r,y=a,T=c;this.pricing.tierPricing.getIsTaxInclusive()?(d=W(i,this.pricing.applicableTaxRule),g=d.multiply(t),c.getAmount()>0&&(T=W(c,this.pricing.applicableTaxRule),y=T.multiply(t),he(T,c,this.pricing.applicableTaxRule).forEach(C=>{let S=C.taxAmount.multiply(t).round(),L=this.pricing.applicableTaxRule.find(D=>D.getTaxRuleId()===C.ruleId);u[C.ruleId]={rate:C.rate,taxableUnitPrice:T,taxPerUnit:C.taxAmount,taxAmount:S,system:L.getTaxSystem(),subSystem:L.getTaxSubSystem()},s=s.add(S);}))):this.pricing.applicableTaxRule.forEach(b=>{let C=b.getApplicableTaxRate(T),S=b.calculateTax(T),L=S.multiply(t).round();u[b.getTaxRuleId()]={rate:C,taxableUnitPrice:T,taxPerUnit:S,taxAmount:L,system:b.getTaxSystem(),subSystem:b.getTaxSubSystem()},s=s.add(L);});let A=y.add(s);this.total={quantity:t,unitPrice:d,subtotal:g,discountTotal:o,discountBreakdown:this.total.discountBreakdown,netUnitPrice:T,netSubtotal:y,taxTotal:s,taxBreakdown:u,grandTotal:A};}updateState(e){if(this.state in oe)this.state!==e&&(this.state=e);else throw new se(e)}clearLineItem(){let e=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.sku="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new k({sources:{original:""}}),this.subItems=[],this.productType="GOODS",this.pricing={unitPrice:e,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[]},this.total={quantity:0,unitPrice:e,subtotal:e,discountTotal:e,discountBreakdown:{},netUnitPrice:e,netSubtotal:e,taxTotal:e,taxBreakdown:{},grandTotal:e};}};var _=class extends M{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(e,t=new Date){if(super(e,t),this.couponCode=e.couponCode,this.name=m.deepClone(e.name),this.description=m.deepClone(e.description),this.type=e.type,this.customerId=e.customerId,this.validFrom=e.validFrom&&Date.parse(e.validFrom)?new Date(e.validFrom).toISOString():t.toISOString(),this.validTo=e.validTo&&Date.parse(e.validTo)?new Date(e.validTo).toISOString():t.toISOString(),this.minCartValue=Object.keys(e.minCartValue).reduce((i,r)=>{let o=e.minCartValue[r];return o&&(i[r]=new l(o)),i},{}),this.maxCartDiscount=Object.keys(e.maxCartDiscount).reduce((i,r)=>{let o=e.maxCartDiscount[r];return o&&(i[r]=new l(o)),i},{}),this.discountMethod=e.discountMethod,this.percentageValue=e.percentageValue??0,this.percentageValue>100)throw new I("Percentage value cannot be greater than 100");this.applicableTo=e.applicableTo,this.category=e.category;}getCode(){return this.couponCode}getName(e){return e?this.name[e]??this.name[P[e]]??this.name.en:{...this.name}}getDescription(e){return e?this.description[e]??this.description[P[e]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(e){return e?this.minCartValue[e]:{...this.minCartValue}}getMaxCartDiscount(e){return e?this.maxCartDiscount[e]:{...this.maxCartDiscount}}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:Object.keys(this.getMinCartValue()).reduce((e,t)=>{let i=this.getMinCartValue(t);return i&&(e[t]=i.getDetails()),e},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((e,t)=>{let i=this.getMaxCartDiscount(t);return i&&(e[t]=i.getDetails()),e},{}),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(e){return this.applicableTo==="all"||this.applicableTo==="ftb"&&e}calculateApplicableCouponDiscount(e,t,i,r,o=!0){let a=new l({amount:0,currency:r}),c;if(o&&!this.isActive())return a;let u=this.getMinCartValue(i),s=this.getMaxCartDiscount(i);if(!u||u.compareTo(e)>0||!s)return a;let d=this.getCategory(),g=this.getDiscountMethod(),y=d==="SHIPPING"?t:e;if(y.getAmount()<=0)return a;switch(g){case"flat":let A=s;c=y.min(A);break;case"percentage":c=y.multiply(this.getPercentageValue()/100).round();break;default:return a}return c.min(s)}};var q=class extends B{id;name;type;category;impact;pricing;lineItemId;total;constructor(e){if(super(e),this.id=e.id,this.name=e.name,this.type=e.type,this.category=e.category,this.impact=e.impact,this.lineItemId=e.lineItemId,this.pricing={baseChargeAmount:new l(e.pricing.baseChargeAmount),taxCategory:e.pricing.taxCategory,applicableTaxRule:e.pricing.applicableTaxRule.map(t=>new $(t))},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new X("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={chargeAmount:new l(e.total.chargeAmount),discountTotal:new l(e.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(e.total.discountBreakdown).map(([t,i])=>[t,new l(i)])),netChargeAmount:new l(e.total.netChargeAmount),taxBreakdown:Object.fromEntries(Object.entries(e.total.taxBreakdown).map(([t,i])=>[t,{rate:i.rate,taxableAmount:new l(i.taxableAmount),taxAmount:new l(i.taxAmount),system:i.system,subSystem:i.subSystem}])),taxTotal:new l(e.total.taxTotal),grandTotal:new l(e.total.grandTotal)};}getId(){return this.id}getName(e){return e?m.deepClone(this.name[e]??this.name[P[e]]??this.name.en):m.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getPricing(){return {baseChargeAmount:this.pricing.baseChargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {chargeAmount:this.total.chargeAmount,discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},netChargeAmount:this.total.netChargeAmount,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,t])=>[e,{rate:t.rate,taxableAmount:t.taxableAmount,taxAmount:t.taxAmount,system:t.system,subSystem:t.subSystem}])),grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(e){if(this.type==="ADJUSTMENT"&&e.length>0)throw new X("Adjustment charges cannot apply tax rules.");e.forEach(t=>{if(!t.appliesTo(this.pricing.taxCategory,t.getCountry()))throw new z}),this.validateTaxRules(e),this.pricing.applicableTaxRule=e,this.calculateTotals();}validateTaxRules(e){if(this.impact==="SUBTRACT"&&e.some(i=>i.getRate()>0))throw new V("Subtractive charges cannot have positive tax rates.");let t=new Set;for(let i=0;i<e.length;i++){let r=e[i].getTaxRuleId();if(t.has(r))throw new V("Duplicate tax rule ID found: "+r);t.add(r);for(let o=i+1;o<e.length;o++){let a=e[i],c=e[o],u=a.getMinPrice(),s=a.getMaxPrice(),d=a.getExcludeMin(),g=a.getExcludeMax(),y=c.getMinPrice(),T=c.getMaxPrice(),A=c.getExcludeMin(),b=c.getExcludeMax(),C=(()=>{if(!s)return !1;let D=s.compareTo(y);return D<0||D===0&&(g||A)})(),S=(()=>{if(!T)return !1;let D=T.compareTo(u);return D<0||D===0&&(b||d)})();if(!(C||S)&&!(u.compareTo(y)===0&&d===A&&g===b&&(!s&&!T||s&&T&&s.compareTo(T)===0)))throw new V(`Overlapping rules found: [${a.getTaxRuleId()}: ${d?"(":"["}${u.getAmount()}-${s?.getAmount()??"Infinity"}${g?")":"]"}] and [${c.getTaxRuleId()}: ${A?"(":"["}${y.getAmount()}-${T?.getAmount()??"Infinity"}${b?")":"]"}]`)}}}updateDiscounts(e){let t={};e.forEach(i=>{t[i.coupon.getCode()]=i.amount;}),this.total.discountBreakdown=t,this.calculateTotals();}calculateTotals(){let e=this.pricing.baseChargeAmount.zero(),t=this.pricing.baseChargeAmount,i=Object.values(this.total.discountBreakdown).reduce((g,y)=>g.add(y),e),r=t.subtract(i),o={};if(this.pricing.applicableTaxRule.reduce((g,y)=>g+y.getApplicableTaxRate(r),0)<=0){this.total={chargeAmount:t,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:r,taxTotal:e,taxBreakdown:{},grandTotal:r};return}let c=W(r,this.pricing.applicableTaxRule),u=he(c,r,this.pricing.applicableTaxRule),s=e;u.forEach(g=>{let y=this.pricing.applicableTaxRule.find(T=>T.getTaxRuleId()===g.ruleId);o[g.ruleId]={rate:g.rate,taxableAmount:c,taxAmount:g.taxAmount,system:y.getTaxSystem(),subSystem:y.getTaxSubSystem()},s=s.add(g.taxAmount);});let d=r;this.total={chargeAmount:t,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:r,taxBreakdown:o,taxTotal:s,grandTotal:d};}getDetails(){return {id:this.id,name:m.deepClone(this.name),type:this.type,category:this.category,pricing:{baseChargeAmount:this.pricing.baseChargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(t=>t.getDetails())},impact:this.impact,lineItemId:this.lineItemId,total:{chargeAmount:this.total.chargeAmount.getDetails(),discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([t,i])=>[t,i.getDetails()])),netChargeAmount:this.total.netChargeAmount.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,i])=>[t,{rate:i.rate,taxableAmount:i.taxableAmount.getDetails(),taxAmount:i.taxAmount.getDetails(),system:i.system,subSystem:i.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};var Ie=class extends M{id;customerId;customerEmail;anonymousId;lineItems;charges;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;#e;constructor(e,t=new Date,i={checkCouponExpiry:!0}){super(e,t),this.id=e.id,this.customerId=e.customerId,this.customerEmail=e.customerEmail,this.anonymousId=e.anonymousId,this.country=e.country,this.currency=e.currency,this.locale=e.locale,this.lineItems=(e.lineItems??[]).map(r=>new G(r)),this.charges=(e.charges??[]).map(r=>new q(r)),this.billingAddress=e.billingAddress?new U(e.billingAddress,t):null,this.shippingAddress=e.shippingAddress?new U(e.shippingAddress,t):null,this.coupons=(e.coupons??[]).map(r=>new _(r)),this.shippingDetails=e.shippingDetails?m.deepClone(e.shippingDetails):null,this.total={lineItemSubtotal:new l(e.total.lineItemSubtotal),netLineItemSubtotal:new l(e.total.netLineItemSubtotal),lineItemTaxTotal:new l(e.total.lineItemTaxTotal),lineItemTaxBreakdown:this.mapTaxBreakdown(e.total.lineItemTaxBreakdown),additiveCharges:new l(e.total.additiveCharges),netAdditiveCharges:new l(e.total.netAdditiveCharges),additiveChargesTaxTotal:new l(e.total.additiveChargesTaxTotal),additiveChargesTaxBreakdown:this.mapTaxBreakdown(e.total.additiveChargesTaxBreakdown),adjustmentCharges:new l(e.total.adjustmentCharges),shippingCharges:new l(e.total.shippingCharges),netShippingCharges:new l(e.total.netShippingCharges),discountTotal:new l(e.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(e.total.discountBreakdown).map(([r,o])=>[r,new l(o)])),taxTotal:new l(e.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(e.total.taxBreakdown),grandTotal:new l(e.total.grandTotal)},this.#e={checkCouponExpiry:i.checkCouponExpiry};}mapTaxBreakdown(e){return Object.fromEntries(Object.entries(e||{}).map(([t,i])=>[t,{system:i.system,totalAmount:new l(i.totalAmount),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,o])=>[r,new l(o)]))}]))}serializeTaxBreakdown(e){return Object.fromEntries(Object.entries(e||{}).map(([t,i])=>[t,{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(e=>new G(e.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(e=>new q(e.getDetails()))}addCharge(e){this.charges.push(e),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?m.deepClone(this.shippingDetails):null}getShippingAddress(){return this.shippingAddress?new U(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new U(this.billingAddress.getDetails()):null}getCoupons(){return [...this.coupons]}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {lineItemSubtotal:this.total.lineItemSubtotal,netLineItemSubtotal:this.total.netLineItemSubtotal,lineItemTaxTotal:this.total.lineItemTaxTotal,lineItemTaxBreakdown:Object.fromEntries(Object.entries(this.total.lineItemTaxBreakdown).map(([e,t])=>[e,{system:t.system,totalAmount:t.totalAmount,subSystems:{...t.subSystems}}])),additiveCharges:this.total.additiveCharges,netAdditiveCharges:this.total.netAdditiveCharges,additiveChargesTaxTotal:this.total.additiveChargesTaxTotal,additiveChargesTaxBreakdown:Object.fromEntries(Object.entries(this.total.additiveChargesTaxBreakdown).map(([e,t])=>[e,{system:t.system,totalAmount:t.totalAmount,subSystems:{...t.subSystems}}])),adjustmentCharges:this.total.adjustmentCharges,shippingCharges:this.total.shippingCharges,netShippingCharges:this.total.netShippingCharges,discountBreakdown:{...this.total.discountBreakdown},discountTotal:this.total.discountTotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,t])=>[e,{system:t.system,totalAmount:t.totalAmount,subSystems:{...t.subSystems}}])),grandTotal:this.total.grandTotal}}getDetails(){let e=this.getTotal();return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(t=>t.getDetails()),charges:this.getCharges().map(t=>t.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(t=>t.getDetails()),total:{lineItemSubtotal:e.lineItemSubtotal.getDetails(),netLineItemSubtotal:e.netLineItemSubtotal.getDetails(),lineItemTaxTotal:e.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(e.lineItemTaxBreakdown),additiveCharges:e.additiveCharges.getDetails(),netAdditiveCharges:e.netAdditiveCharges.getDetails(),additiveChargesTaxTotal:e.additiveChargesTaxTotal.getDetails(),additiveChargesTaxBreakdown:this.serializeTaxBreakdown(e.additiveChargesTaxBreakdown),adjustmentCharges:e.adjustmentCharges.getDetails(),shippingCharges:e.shippingCharges.getDetails(),netShippingCharges:e.netShippingCharges.getDetails(),discountTotal:e.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(e.discountBreakdown).map(([t,i])=>[t,i.getDetails()])),taxTotal:e.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(e.taxBreakdown),grandTotal:e.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let e=new l({amount:0,currency:this.currency}),t=this.lineItems.filter(p=>p.getState()!=="CANCELLED"),i=t.reduce((p,h)=>p.add(h.getTotal().subtotal),e),r=this.charges.filter(p=>p.getType()==="SHIPPING").reduce((p,h)=>p.add(h.getTotal().chargeAmount),e);this.total.lineItemSubtotal=i,this.total.shippingCharges=r;let o=e,a={},c={};this.coupons.forEach(p=>{let h=p.calculateApplicableCouponDiscount(i,r,this.country,this.currency,this.#e.checkCouponExpiry);o=o.add(h),a[p.getCode()]=h,p.getCategory()!=="SHIPPING"&&(c[p.getCode()]=h);}),this.total.discountTotal=o,this.total.discountBreakdown=a,this.applyDiscountsInLineItem(c);let u=this.coupons.find(p=>p.getCategory()==="SHIPPING");u?this.applyDiscountsInShippingCharges({[u.getCode()]:a[u.getCode()]||e}):this.applyDiscountsInShippingCharges({});let s=this.lineItems.reduce((p,h)=>p.add(h.getTotal().netSubtotal),e),d=this.charges.filter(p=>p.getType()==="SHIPPING").reduce((p,h)=>p.add(h.getTotal().grandTotal),e);this.total.netLineItemSubtotal=s,this.total.netShippingCharges=d;let g=this.charges.filter(p=>p.getImpact()==="ADD").reduce((p,h)=>p.add(h.getTotal().chargeAmount),e),y=this.charges.filter(p=>p.getImpact()==="ADD").reduce((p,h)=>p.add(h.getTotal().grandTotal),e),T=this.charges.filter(p=>p.getImpact()==="SUBTRACT").reduce((p,h)=>p.add(h.getTotal().grandTotal),e),A=e,b=e,C=e,S={},L={},D={},ee=(p,h)=>{Object.entries(p).forEach(([He,Q])=>{let R=Q.system,te=Q.subSystem;h[R]||(h[R]={system:R,totalAmount:e,subSystems:{}}),h[R].subSystems[te]?h[R].subSystems[te]=h[R].subSystems[te].add(Q.taxAmount):h[R].subSystems[te]=Q.taxAmount,h[R].totalAmount=h[R].totalAmount.add(Q.taxAmount);});};t.forEach(p=>{let h=p.getTotal().taxBreakdown;h&&(ee(h,L),ee(h,S),b=b.add(p.getTotal().taxTotal));}),this.charges.forEach(p=>{let h=p.getTotal().taxBreakdown;h&&(ee(h,D),ee(h,S),C=C.add(p.getTotal().taxTotal));}),A=b.add(C);let Le=s.add(b).add(y).subtract(T);this.total={lineItemSubtotal:i,netLineItemSubtotal:s,lineItemTaxTotal:b,lineItemTaxBreakdown:L,additiveCharges:g,netAdditiveCharges:y,additiveChargesTaxTotal:C,additiveChargesTaxBreakdown:D,adjustmentCharges:T,shippingCharges:r,netShippingCharges:d,discountTotal:o,discountBreakdown:a,taxTotal:A,taxBreakdown:S,grandTotal:Le};}updateShippingDetails(e){this.shippingDetails=e;}applyCoupons(e){let t=e.filter(r=>r.getCategory()==="SHIPPING"),i=e.filter(r=>r.getCategory()!=="SHIPPING");this.coupons=[],this.total.discountTotal=this.total.lineItemSubtotal.zero(),this.total.discountBreakdown={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.discountBreakdown),t.length&&this.applyShippingCoupons(t),this.calculateTotals();}applyDiscountsInLineItem(e){let t=Array.from(Object.entries(e)).filter(r=>!r[1].isZero()),i=new Map;this.lineItems.forEach(r=>i.set(r.getId(),[])),t.forEach(([r,o])=>{let a=this.coupons.find(s=>s.getCode()===r);if(!a||o.isZero())return;let c=this.lineItems.filter(s=>s.getState()!=="CANCELLED"&&!s.getTotal().subtotal.isZero()).sort((s,d)=>s.getTotal().subtotal.compareTo(d.getTotal().subtotal)),u=new l({amount:0,currency:this.currency});c.forEach((s,d)=>{let g;d===c.length-1?g=o.subtract(u):g=o.multiply(s.getTotal().subtotal).divide(this.total.lineItemSubtotal).round(),u=u.add(g),i.get(s.getId())?.push({coupon:a,amount:g});});}),this.lineItems.forEach(r=>{r.getState()==="CANCELLED"||this.total.lineItemSubtotal.isZero()?r.updateDiscounts([]):r.updateDiscounts(i.get(r.getId())||[]);});}applyDiscountsInShippingCharges(e){let t=Array.from(Object.entries(e)).filter(o=>!o[1].isZero()),i=this.charges.filter(o=>o.getType()==="SHIPPING"),r=new Map;i.forEach(o=>r.set(o.getId(),[])),t.forEach(([o,a])=>{let c=this.coupons.find(d=>d.getCode()===o);if(!c||a.isZero())return;let u=i.sort((d,g)=>d.getTotal().grandTotal.compareTo(g.getTotal().grandTotal)),s=new l({amount:0,currency:this.currency});u.forEach((d,g)=>{let y;g===u.length-1?y=a.subtract(s):y=a.multiply(d.getTotal().chargeAmount).divide(this.total.shippingCharges).round(),s=s.add(y),r.get(d.getId())?.push({coupon:c,amount:y});});}),i.forEach(o=>{o.updateDiscounts(r.get(o.getId())||[]);});}applyNonShippingCoupons(e){let t=e.filter(i=>i.getType()==="coupon");if(t.length===1){let i=t[0].calculateApplicableCouponDiscount(this.total.lineItemSubtotal,this.total.shippingCharges,this.country,this.currency,this.#e.checkCouponExpiry);i.getAmount()>0&&(this.coupons.push(t[0]),this.total.discountTotal=i,this.total.discountBreakdown[t[0].getCode()]=i);}}applyShippingCoupons(e){if(this.total.shippingCharges.getAmount()>0&&e.length>0){let t=this.total.lineItemSubtotal.subtract(this.total.discountTotal),i=e.reduce((o,a)=>{if(!o)return a;let c=a.calculateApplicableCouponDiscount(t,this.total.shippingCharges,this.country,this.currency,this.#e.checkCouponExpiry).min(this.total.shippingCharges),u=o.calculateApplicableCouponDiscount(t,this.total.shippingCharges,this.country,this.currency,this.#e.checkCouponExpiry).min(this.total.shippingCharges);return c.compareTo(u)===0?a.getType()==="coupon"?a:o:c.compareTo(u)>0?a:o}),r=i.calculateApplicableCouponDiscount(t,this.total.shippingCharges,this.country,this.currency,this.#e.checkCouponExpiry).min(this.total.shippingCharges);r.getAmount()>0&&(this.coupons.push(i),this.total.discountTotal=this.total.discountTotal.add(r),this.total.discountBreakdown[i.getCode()]=r);}}};module.exports=Ie;//# sourceMappingURL=ShoppingContainer.js.map
2
2
  //# sourceMappingURL=ShoppingContainer.js.map