b23-lib 2.2.0 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Auth/index.js +1 -1
- package/dist/Auth/index.js.map +1 -1
- package/dist/Auth/index.mjs +1 -1
- package/dist/Classes/Cart.d.mts +1 -0
- package/dist/Classes/Cart.d.ts +1 -0
- package/dist/Classes/Cart.js +1 -2
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Cart.mjs.map +1 -1
- package/dist/Classes/Charge.d.mts +99 -0
- package/dist/Classes/Charge.d.ts +99 -0
- package/dist/Classes/Charge.js +2 -0
- package/dist/Classes/Charge.js.map +1 -0
- package/dist/Classes/Charge.mjs +2 -0
- package/dist/Classes/Charge.mjs.map +1 -0
- package/dist/Classes/Coupon.js +1 -1
- package/dist/Classes/Coupon.js.map +1 -1
- package/dist/Classes/Coupon.mjs +1 -1
- package/dist/Classes/Enum.d.mts +4 -4
- package/dist/Classes/Enum.d.ts +4 -4
- package/dist/Classes/Enum.js +1 -1
- package/dist/Classes/Enum.js.map +1 -1
- package/dist/Classes/Enum.mjs +1 -1
- package/dist/Classes/Error.d.mts +4 -1
- package/dist/Classes/Error.d.ts +4 -1
- package/dist/Classes/Error.js +1 -1
- package/dist/Classes/Error.js.map +1 -1
- package/dist/Classes/Error.mjs +1 -1
- package/dist/Classes/ImageInfo.js.map +1 -1
- package/dist/Classes/ImageInfo.mjs +1 -1
- package/dist/Classes/Inventory.js +1 -1
- package/dist/Classes/Inventory.js.map +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/LineItem.d.mts +46 -48
- package/dist/Classes/LineItem.d.ts +46 -48
- package/dist/Classes/LineItem.js +1 -2
- package/dist/Classes/LineItem.js.map +1 -1
- package/dist/Classes/LineItem.mjs +1 -1
- package/dist/Classes/Order.d.mts +1 -1
- package/dist/Classes/Order.d.ts +1 -1
- package/dist/Classes/Order.js +1 -2
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/Order.mjs.map +1 -1
- package/dist/Classes/Price.js +1 -1
- package/dist/Classes/Price.js.map +1 -1
- package/dist/Classes/Price.mjs +1 -1
- package/dist/Classes/Product.js +1 -1
- package/dist/Classes/Product.js.map +1 -1
- package/dist/Classes/Product.mjs +1 -1
- package/dist/Classes/ShoppingContainer.d.mts +98 -40
- package/dist/Classes/ShoppingContainer.d.ts +98 -40
- package/dist/Classes/ShoppingContainer.js +1 -2
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/Classes/TaxCategoryModel.d.mts +42 -0
- package/dist/Classes/TaxCategoryModel.d.ts +42 -0
- package/dist/Classes/TaxCategoryModel.js +2 -0
- package/dist/Classes/TaxCategoryModel.js.map +1 -0
- package/dist/Classes/TaxCategoryModel.mjs +2 -0
- package/dist/Classes/TaxCategoryModel.mjs.map +1 -0
- package/dist/Classes/TaxRule.d.mts +59 -79
- package/dist/Classes/TaxRule.d.ts +59 -79
- package/dist/Classes/TaxRule.js +1 -2
- package/dist/Classes/TaxRule.js.map +1 -1
- package/dist/Classes/TaxRule.mjs +1 -1
- package/dist/Classes/TieredPrice.d.mts +4 -4
- package/dist/Classes/TieredPrice.d.ts +4 -4
- package/dist/Classes/TieredPrice.js +1 -1
- package/dist/Classes/TieredPrice.js.map +1 -1
- package/dist/Classes/TieredPrice.mjs +1 -1
- package/dist/{chunk-EV4HUBJL.mjs → chunk-6X5O25W5.mjs} +2 -2
- package/dist/chunk-6X5O25W5.mjs.map +1 -0
- package/dist/chunk-FC4P26U3.mjs +2 -0
- package/dist/chunk-FC4P26U3.mjs.map +1 -0
- package/dist/chunk-IIPG3DTO.mjs +2 -0
- package/dist/chunk-IIPG3DTO.mjs.map +1 -0
- package/dist/{chunk-LEHPVA3Q.mjs → chunk-JE7BAYI5.mjs} +2 -2
- package/dist/{chunk-LEHPVA3Q.mjs.map → chunk-JE7BAYI5.mjs.map} +1 -1
- package/dist/chunk-KKQLCW6A.mjs +2 -0
- package/dist/chunk-KKQLCW6A.mjs.map +1 -0
- package/dist/chunk-PTIPDRB4.mjs +2 -0
- package/dist/chunk-PTIPDRB4.mjs.map +1 -0
- package/dist/{chunk-GF427QWC.mjs → chunk-RSMXGZD4.mjs} +2 -2
- package/dist/{chunk-GF427QWC.mjs.map → chunk-RSMXGZD4.mjs.map} +1 -1
- package/dist/{chunk-WSUPVXRZ.mjs → chunk-RSTZJZSQ.mjs} +2 -2
- package/dist/{chunk-WSUPVXRZ.mjs.map → chunk-RSTZJZSQ.mjs.map} +1 -1
- package/dist/chunk-U7DES3CI.mjs +2 -0
- package/dist/chunk-U7DES3CI.mjs.map +1 -0
- package/dist/{chunk-JHELVQYY.mjs → chunk-XPKK6DFA.mjs} +2 -2
- package/dist/chunk-XPKK6DFA.mjs.map +1 -0
- package/dist/chunk-XXETAAL4.mjs +2 -0
- package/dist/chunk-XXETAAL4.mjs.map +1 -0
- package/dist/index.d.mts +1 -5
- package/dist/index.d.ts +1 -5
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +21 -1
- package/dist/chunk-43SMYXYL.mjs +0 -2
- package/dist/chunk-43SMYXYL.mjs.map +0 -1
- package/dist/chunk-5VI4V3SF.mjs +0 -2
- package/dist/chunk-5VI4V3SF.mjs.map +0 -1
- package/dist/chunk-72DR3HF2.mjs +0 -2
- package/dist/chunk-72DR3HF2.mjs.map +0 -1
- package/dist/chunk-CKJONVT3.mjs +0 -2
- package/dist/chunk-CKJONVT3.mjs.map +0 -1
- package/dist/chunk-EV4HUBJL.mjs.map +0 -1
- package/dist/chunk-JHELVQYY.mjs.map +0 -1
- package/dist/chunk-RQC4PNOV.mjs +0 -3
- package/dist/chunk-RQC4PNOV.mjs.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as default}from'../chunk-
|
|
1
|
+
export{a as default}from'../chunk-IIPG3DTO.mjs';import'../chunk-XXETAAL4.mjs';import'../chunk-JE7BAYI5.mjs';import'../chunk-U7DES3CI.mjs';import'../chunk-6X5O25W5.mjs';import'../chunk-FC4P26U3.mjs';import'../chunk-RSTZJZSQ.mjs';import'../chunk-XPKK6DFA.mjs';import'../chunk-6KCJVEZD.mjs';//# sourceMappingURL=LineItem.mjs.map
|
|
2
2
|
//# sourceMappingURL=LineItem.mjs.map
|
package/dist/Classes/Order.d.mts
CHANGED
|
@@ -11,6 +11,7 @@ import './ImageInfo.mjs';
|
|
|
11
11
|
import './Product.mjs';
|
|
12
12
|
import './TieredPrice.mjs';
|
|
13
13
|
import './TaxRule.mjs';
|
|
14
|
+
import './Charge.mjs';
|
|
14
15
|
|
|
15
16
|
/**
|
|
16
17
|
* PLACED: Order created, awaiting payment.
|
|
@@ -59,7 +60,6 @@ declare class OrderModel extends BaseShoppingContainerModel {
|
|
|
59
60
|
* Creates an instance of OrderModel.
|
|
60
61
|
* @param data - The initial order attributes, including cart data.
|
|
61
62
|
* @param date - Optional date for setting creation/modification times (defaults to now).
|
|
62
|
-
* @param config - Optional cart configuration (might be less relevant for orders).
|
|
63
63
|
*/
|
|
64
64
|
constructor(data: OrderAttributes, date?: Date);
|
|
65
65
|
/**
|
package/dist/Classes/Order.d.ts
CHANGED
|
@@ -11,6 +11,7 @@ import './ImageInfo.js';
|
|
|
11
11
|
import './Product.js';
|
|
12
12
|
import './TieredPrice.js';
|
|
13
13
|
import './TaxRule.js';
|
|
14
|
+
import './Charge.js';
|
|
14
15
|
|
|
15
16
|
/**
|
|
16
17
|
* PLACED: Order created, awaiting payment.
|
|
@@ -59,7 +60,6 @@ declare class OrderModel extends BaseShoppingContainerModel {
|
|
|
59
60
|
* Creates an instance of OrderModel.
|
|
60
61
|
* @param data - The initial order attributes, including cart data.
|
|
61
62
|
* @param date - Optional date for setting creation/modification times (defaults to now).
|
|
62
|
-
* @param config - Optional cart configuration (might be less relevant for orders).
|
|
63
63
|
*/
|
|
64
64
|
constructor(data: OrderAttributes, date?: Date);
|
|
65
65
|
/**
|
package/dist/Classes/Order.js
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var ht=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ht__default=/*#__PURE__*/_interopDefault(ht);var U=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}},O=class extends Error{constructor(t){super(`Invalid line item state: ${t}`),this.name="InvalidLineItemStateError";}},B=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},F=class extends Error{constructor(t){super(`Duplicate selection attribute found: ${t}`),this.name="DuplicateSelectionAttributeError";}},z=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},$=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},x=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},G=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},V=class extends Error{constructor(t="Pricing details not available for the product"){super(`NotFound: ${t}`),this.name="PricingNotFoundError";}},k=class extends Error{constructor(t="Tax rule category mismatch."){super(`InvalidTaxRule: ${t}`),this.name="InvalidTaxRuleError";}},q=class extends Error{constructor(t="Tax category is not valid."){super(`InvalidTaxCategory: ${t}`),this.name="InvalidTaxCategoryError";}},K=class extends Error{constructor(t="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${t}`),this.name="InvalidMinQuantityError";}},j=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},Q=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},H=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}},Y=class extends Error{constructor(t="No applicable tax slab or multiple slabs found for the given unit price."){super(`TaxSlabNotFound: ${t}`),this.name="TaxSlabNotFoundError";}},w=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},P=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},S=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},f=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},E=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}};var v=class{customFields;constructor(t,e=new Date){this.customFields={...t.customFields};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}},b=class extends v{version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){super(t),this.version=t.version??1,this.createdAt=t.createdAt&&!isNaN(Date.parse(t.createdAt))?new Date(t.createdAt).toISOString():e.toISOString(),this.modifiedAt=t.modifiedAt&&!isNaN(Date.parse(t.modifiedAt))?new Date(t.modifiedAt).toISOString():e.toISOString(),this.modifiedBy={...t.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(t,e,i,n){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:n};}};var A=class extends b{id;firstName;lastName;company;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(t,e=new Date){super(t,e),this.id=t.id,this.firstName=t.firstName,this.lastName=t.lastName||"",this.company=t.company||"",this.phone=t.phone,this.email=t.email,this.addressLine1=t.addressLine1,this.addressLine2=t.addressLine2||"",this.city=t.city,this.postalCode=t.postalCode,this.state=t.state,this.country=t.country,this.isBillingAddress=t.isBillingAddress,this.isShippingAddress=t.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),company:this.getCompany(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getCompany(){return this.company}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(t){return t==="shipping"||t==="billing&shipping"}static checkIfBillingAddress(t){return t==="billing"||t==="billing&shipping"}};var X=new Uint8Array(256),Z=X.length;function tt(){return Z>X.length-16&&(ht__default.default.randomFillSync(X),Z=0),X.slice(Z,Z+=16)}var at=/^(?:[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 yt(r){return typeof r=="string"&&at.test(r)}var ct=yt;var h=[];for(let r=0;r<256;++r)h.push((r+256).toString(16).slice(1));function W(r,t=0){return h[r[t+0]]+h[r[t+1]]+h[r[t+2]]+h[r[t+3]]+"-"+h[r[t+4]]+h[r[t+5]]+"-"+h[r[t+6]]+h[r[t+7]]+"-"+h[r[t+8]]+h[r[t+9]]+"-"+h[r[t+10]]+h[r[t+11]]+h[r[t+12]]+h[r[t+13]]+h[r[t+14]]+h[r[t+15]]}function ft(r){if(!ct(r))throw TypeError("Invalid UUID");let t,e=new Uint8Array(16);return e[0]=(t=parseInt(r.slice(0,8),16))>>>24,e[1]=t>>>16&255,e[2]=t>>>8&255,e[3]=t&255,e[4]=(t=parseInt(r.slice(9,13),16))>>>8,e[5]=t&255,e[6]=(t=parseInt(r.slice(14,18),16))>>>8,e[7]=t&255,e[8]=(t=parseInt(r.slice(19,23),16))>>>8,e[9]=t&255,e[10]=(t=parseInt(r.slice(24,36),16))/1099511627776&255,e[11]=t/4294967296&255,e[12]=t>>>24&255,e[13]=t>>>16&255,e[14]=t>>>8&255,e[15]=t&255,e}var ut=ft;function bt(r){r=unescape(encodeURIComponent(r));let t=[];for(let e=0;e<r.length;++e)t.push(r.charCodeAt(e));return t}var Ct="6ba7b810-9dad-11d1-80b4-00c04fd430c8",xt="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function et(r,t,e){function i(n,s,o,c){var u;if(typeof n=="string"&&(n=bt(n)),typeof s=="string"&&(s=ut(s)),((u=s)===null||u===void 0?void 0:u.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+n.length);if(a.set(s),a.set(n,s.length),a=e(a),a[6]=a[6]&15|t,a[8]=a[8]&63|128,o){c=c||0;for(let g=0;g<16;++g)o[c+g]=a[g];return o}return W(a)}try{i.name=r;}catch{}return i.DNS=Ct,i.URL=xt,i}var it={randomUUID:ht__default.default.randomUUID};function Tt(r,t,e){if(it.randomUUID&&!t&&!r)return it.randomUUID();r=r||{};let i=r.random||(r.rng||tt)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){e=e||0;for(let n=0;n<16;++n)t[e+n]=i[n];return t}return W(i)}var rt=Tt;function At(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),ht__default.default.createHash("sha1").update(r).digest()}var lt=At;var Pt=et("v5",80,lt),nt=Pt;var C={"en-IN":"en","kn-IN":"kn"};var dt={INR:"\u20B9"},gt={INR:"en-IN"};var J=(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.REFUND_INITIATED="REFUND_INITIATED",g.REFUNDED="REFUNDED",g.ON_HOLD="ON_HOLD",g))(J||{});var T=class{sources;alt;order;label;constructor(t){if(this.sources={...t.sources},this.alt=t.alt,this.order=t.order,this.label=t.label,!this.sources.original)throw new E("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(t){return this.sources[t]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(t){this.alt=t;}setOrder(t){this.order=t;}setLabel(t){this.label=t;}setSource(t,e){if(e===void 0){if(t==="original")throw new E("Cannot remove the 'original' image source.");delete this.sources[t];}else this.sources[t]=e;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var l=class r{#t;amount;currency;constructor(t){if(this.#t="PriceModel",t.amount<0)throw new w("Amount cannot be negative.");if(!t.currency)throw new P("Currency code is required.");this.amount=t.amount,this.currency=t.currency;}get kind(){return this.#t}static isPriceModel(t){return typeof t=="object"&&t!==null&&t.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(t){if(r.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new S("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return this.amount-t.getAmount()}add(t){if(r.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new S("Cannot add prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return new r({amount:this.amount+t.getAmount(),currency:this.currency})}subtract(t){if(r.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new S("Cannot subtract prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return new r({amount:this.amount-t.getAmount(),currency:this.currency})}multiply(t){if(r.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new S("Cannot multiply prices in different currencies.");return new r({amount:this.amount*t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>=0)return new r({amount:this.amount*t,currency:this.currency});throw new f("Must be a non-negative number.")}divide(t){if(r.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new S("Cannot divide prices in different currencies.");return new r({amount:this.amount/t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>0)return new r({amount:this.amount/t,currency:this.currency});throw new f("Must be a positive number.")}min(...t){if(t.length===0)throw new f("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(r.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new S("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i},this)}max(...t){if(t.length===0)throw new f("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(r.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new S("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return e.compareTo(i)>0?e:i},this)}zero(){return new r({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new r({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return r.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return r.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(t,e,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=gt[e];if(!e||!n)throw new P("Invalid currency code for formatting.");let s=t,o=i.displayAsInteger?0:r.getDecimalPlaces(e),c={style:i.style??"currency",currency:e,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:o,maximumFractionDigits:o};i.displayAsInteger&&(s=Math.ceil(s));try{return new Intl.NumberFormat(n,c).format(s)}catch(u){return console.error(`Error formatting price for currency "${e}" and locale "${n}":`,u),`${dt[e]??e} ${r.addThousandSeparators(s.toFixed(o))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),i=e[0],n=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(t,e){if(t<0)throw new w("Amount cannot be negative for rounding.");if(e===void 0)throw new P("Invalid currency code for rounding.");let i=r.getDecimalPlaces(e),n=Math.pow(10,i);return Math.round(t*n)/n}};var D=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new l(t.baseUnitPrice);if(!t.taxCategory)throw new q;let i=(t.tiers??[]).map(u=>({minQuantity:u.minQuantity,unitPrice:new l(u.unitPrice)})).sort((u,a)=>u.minQuantity-a.minQuantity);if(i.some(u=>u.minQuantity<=0))throw new K;let s=i.some(u=>u.unitPrice.getCurrency()!==e.getCurrency()),o=i.some((u,a)=>a>0&&u.unitPrice.compareTo(i[a-1].unitPrice)>0),c=i[0]?.unitPrice.compareTo(e)>0;if(s||o||c)throw new j("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=e,this.taxCategory=t.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}}getApplicableTier(t){if(t<=0)throw new Q;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity)return this.tiers[e];throw new H(t)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let t=this.tiers[this.tiers.length-1].unitPrice.getAmount(),e=this.baseUnitPrice.getAmount();return (e-t)/e*100}};var M=class r extends b{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(t){if(typeof t!="object")throw new x("Selection attributes must be an object");return Object.keys(t).filter(i=>t[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>t[i].name?`${i}:c+${t[i].name}`:`${i}:${t[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(t){try{let e={},i=t.split("|");for(let n of i){let[s,o]=n.split(":");o.startsWith("c+")?e[s]={name:o.slice(2)}:e[s]=o;}return e}catch(e){throw new x(e?.message)}}constructor(t,e=new Date){super(t,e),this.id=t.id,this.key=t.key,this.name={...t.name},this.description={...t.description},this.slug={...t.slug},this.brand=t.brand,this.pricing=Object.keys(t.pricing).reduce((n,s)=>(t.pricing[s]&&(n[s]=new D(t.pricing[s])),n),{}),this.targetGender=t.targetGender,this.attributes=d.deepClone(t.attributes),this.specifications=d.deepClone(t.specifications),this.categories=d.deepClone(t.categories);let i=new Set;this.variants=(t.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new x("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let s=r.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(s))throw new F(s);return i.add(s),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new T(n.images.primary),gallery:(n.images.gallery||[]).map(o=>new T(o))}}}),this.isActive=t.isActive,this.searchTags=t.searchTags?d.deepClone(t.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(t){return t?this.name[t]??this.name[C[t]]??this.name.en:d.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[C[t]]??this.description.en:d.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[C[t]]??this.slug.en:d.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:this.pricing}getAttributes(){return d.deepClone(this.attributes)}getVariants(){return this.variants.map(t=>({sku:t.sku,selectionAttributes:t.selectionAttributes,images:{primary:t.images.primary,gallery:t.images.gallery}}))}getImagesBySelectionAttributes(t){let e=r.generateSelectionAttributesKey(t),i=this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===e);return i?i.images:null}getImages(t,e){switch(e){case"PRIMARY":return this.getImagesBySelectionAttributes(t)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(t)?.gallery??[];default:return this.getImagesBySelectionAttributes(t)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return d.deepClone(this.categories)}getSpecifications(t){return t?d.deepClone(this.specifications[t]??this.specifications[C[t]]??this.specifications.en):d.deepClone(this.specifications)}getSearchTags(t){return t?d.deepClone(this.searchTags[t]??this.searchTags[C[t]]??this.searchTags.en):d.deepClone(this.searchTags)}getDetails(){let t=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((e,i)=>(this.pricing[i]&&(e[i]=this.pricing[i]?.getDetails()),e),{}),attributes:this.getAttributes(),variants:this.variants.map(e=>({sku:e.sku,selectionAttributes:d.deepClone(e.selectionAttributes),images:{primary:e.images.primary.getDetails(),gallery:e.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...t}}checkSelectionAttributes(t){if(!t||typeof t!="object")throw new x("Selection attributes are required");Object.keys(this.attributes).forEach(e=>{if(e.toLowerCase()==="size")return;let i=this.attributes[e],n=t[e];if(n===void 0)throw new x(`Selection attribute '${e}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new x(`Selection attribute '${e}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new x(`Selection attribute '${e}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(s=>s.name===n.name)<0)throw new x(`Selection attribute '${e}' is invalid`)}});}validateSelectionAttribute(t){let e=r.generateSelectionAttributesKey(t);return this.variants.some(i=>r.generateSelectionAttributesKey(i.selectionAttributes)===e)}validateSize(t){return this.attributes.size.includes(t)}};var Dt={isUUID:r=>/^[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(r),isEmail:r=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r),isURL:r=>/^(http|https):\/\/[^ "]+$/.test(r),generateUUID:(r,t)=>t&&r?nt(r,t):rt(),generateSearchId:(r,t)=>`${r}#${M.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:r=>{let[t,e]=r.split("#");return {key:t,selectionAttributes:M.parseSelectionAttributesKey(e)}},deepClone(r){return structuredClone(r)}},d=Dt;var st=class{getBreakdown(t,e,i){let n=t*100,s=n%1===0?n.toString():n.toFixed(2).replace(/\.?0+$/,"");if(e==="IN"&&i?.merchantState&&i?.customerState)if(i.merchantState.toLowerCase().trim()===i.customerState.toLowerCase().trim()){let o=n/2%1===0?(n/2).toString():(n/2).toFixed(2).replace(/\.?0+$/,"");return {totalRate:t,label:`${o}% CGST + ${o}% SGST`,components:[{rate:t/2,label:`${o}% CGST`,type:"CGST"},{rate:t/2,label:`${o}% SGST`,type:"SGST"}]}}else return {totalRate:t,label:`${s}% IGST`,components:[{rate:t,label:`${s}% IGST`,type:"IGST"}]};return {totalRate:t,label:`${s}% GST`,components:[{rate:t,label:`${s}% GST`,type:"GST"}]}}getLongName(){return "Goods and Services Tax"}},pt={GST:new st},_=class r extends b{taxRuleId;taxSystem;taxCategory;country;slabs;effectiveFrom;effectiveTo;constructor(t,e=new Date){super(t,e),this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxCategory=t.taxCategory,this.country=t.country,this.slabs=t.slabs.map(i=>({rate:i.rate,minUnitPrice:new l(i.minUnitPrice),maxUnitPrice:i.maxUnitPrice?new l(i.maxUnitPrice):void 0})),this.effectiveFrom=new Date(t.effectiveFrom),this.effectiveTo=t.effectiveTo?new Date(t.effectiveTo):void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getSlabs(){return this.slabs}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),slabs:this.getSlabs().map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0})),effectiveFrom:this.effectiveFrom.toISOString(),effectiveTo:this.effectiveTo?this.effectiveTo.toISOString():void 0,...super.getDetails()}}appliesTo(t,e,i=new Date){return this.taxCategory===t&&this.country===e&&this.effectiveFrom<=i&&(this.effectiveTo?this.effectiveTo>=i:!0)}getApplicableTaxRate(t){return r.getApplicableTaxRate(t,this.slabs)}getTaxRateDisplayString(t,e){let i=this.getApplicableTaxRate(t);return r.getTaxRateDisplayString(i,{taxSystem:this.taxSystem,merchantState:e?.merchantState,customerState:e?.customerState})}getTaxRateBreakdown(t,e){let i=this.getApplicableTaxRate(t),n=pt[this.taxSystem];if(n)return n.getBreakdown(i,this.country,e);let s=i*100,c=`${s%1===0?s.toString():s.toFixed(2).replace(/\.?0+$/,"")}% ${this.taxSystem}`;return {totalRate:i,label:c,components:[{rate:i,label:c,type:this.taxSystem}]}}getFormattedTaxRate(t,e={}){let n=this.getApplicableTaxRate(t)*100,s=n%1===0?n.toString():n.toFixed(2).replace(/\.?0+$/,""),o=e.variant||"short",c="";switch(o){case"percentageOnly":c=`${s}%`;break;case"detailed":let u=this.getTaxRateBreakdown(t,e),a=e.separator||(e.multiline?`
|
|
2
|
-
`:" + ");c=u.components.map(m=>m.label).join(a);break;case"long":let g=pt[this.taxSystem],y=g?g.getLongName(this.country):this.taxSystem.toString();c=`${s}% ${y}`;break;case"short":default:c=`${s}% ${this.taxSystem}`;break}return e.includeTaxesSuffix&&(c+=" (Incl. Taxes)"),c}static getApplicableTaxRate(t,e){let i=e.filter(n=>(n.minUnitPrice===void 0||t.compareTo(n.minUnitPrice)>=0)&&(n.maxUnitPrice===void 0||t.compareTo(n.maxUnitPrice)<0));if(i.length!==1)throw new Y;return i[0].rate}static getTaxRateDisplayString(t,e){let i=t*100,n=i%1===0?i.toString():i.toFixed(2).replace(/\.?0+$/,"");if(e.taxSystem==="GST"&&e.merchantState&&e.customerState)if(e.merchantState.toLowerCase().trim()===e.customerState.toLowerCase().trim()){let s=i/2%1===0?(i/2).toString():(i/2).toFixed(2).replace(/\.?0+$/,"");return `${s}% CGST + ${s}% SGST`}else return `${n}% IGST`;return e.taxSystem?`${n}% ${e.taxSystem}`:`${n}%`}};var L=class extends v{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=d.deepClone(t.selectionAttributes),this.name=d.deepClone(t.name),this.specifications=d.deepClone(t.specifications),this.primaryImage=new T(t.primaryImage),this.subItems=d.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new B(i.size);e.add(i.size);}),this.pricing={unitPrice:new l(t.pricing.unitPrice),tierPricing:new D(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,tax:{taxRuleId:t.pricing.tax.taxRuleId,taxSystem:t.pricing.tax.taxSystem,country:t.pricing.tax.country,rate:t.pricing.tax.rate,taxSlabs:t.pricing.tax.taxSlabs.map(i=>({rate:i.rate,minUnitPrice:new l(i.minUnitPrice),maxUnitPrice:i.maxUnitPrice?new l(i.maxUnitPrice):void 0}))}},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,subtotal:new l(t.total.subtotal),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,n])=>[i,new l(n)])),taxableAmount:new l(t.total.taxableAmount),taxTotal:new l(t.total.taxTotal),grandTotal:new l(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return d.deepClone(this.selectionAttributes)}getName(t){return t?d.deepClone(this.name[t]??this.name[C[t]]??this.name.en):d.deepClone(this.name)}getSpecifications(t){return t?d.deepClone(this.specifications[t]??this.specifications[C[t]]??this.specifications.en):d.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return d.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:{taxRuleId:this.pricing.tax.taxRuleId,taxSystem:this.pricing.tax.taxSystem,country:this.pricing.tax.country,rate:this.pricing.tax.rate,taxSlabs:this.pricing.tax.taxSlabs}}}getState(){return this.state}getTotal(){return {quantity:this.total.quantity,subtotal:this.total.subtotal,taxableAmount:this.total.taxableAmount,taxTotal:this.total.taxTotal,discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,e])=>[t,e])),grandTotal:this.total.grandTotal}}getDetails(){return {id:this.getId(),productKey:this.getProductKey(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:this.getPricing().unitPrice.getDetails(),tierPricing:this.getPricing().tierPricing.getDetails(),taxCategory:this.getPricing().taxCategory,tax:{taxRuleId:this.getPricing().tax.taxRuleId,taxSystem:this.getPricing().tax.taxSystem,country:this.getPricing().tax.country,rate:this.getPricing().tax.rate,taxSlabs:this.getPricing().tax.taxSlabs.map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0}))}},state:this.getState(),total:{quantity:this.getTotal().quantity,subtotal:this.getTotal().subtotal.getDetails(),taxableAmount:this.getTotal().taxableAmount.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),discounts:Object.fromEntries(Object.entries(this.getTotal().discounts).map(([t,e])=>[t,e.getDetails()])),grandTotal:this.getTotal().grandTotal.getDetails()},customFields:this.getAllCustomFields()}}addSubItems(t,e){t.forEach(i=>{let n=this.subItems.find(s=>s.size===i.size);n?n.quantity=e?n.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity>0),this.calculateTotals();}updateProductData(t,e,i){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new z;if(!t.getIsActive())throw new $;this.subItems.forEach(c=>{if(!t.validateSize(c.size))throw new G});let n=t.getPriceDetails(e);if(!n||n.getBaseUnitPrice().getCurrency()!==i)throw new V;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let s=this.subItems.reduce((c,u)=>c+u.quantity,0),{unitPrice:o}=n.getApplicableTier(s);this.pricing={unitPrice:o,tierPricing:n,taxCategory:n.getTaxCategory(),tax:this.pricing.tax},this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discounts=e,this.calculateTotals();}updateTax(t){if(!t.appliesTo(this.pricing.taxCategory,this.pricing.tax.country))throw new k;let e=this.total.quantity>0?this.total.taxableAmount.divide(this.total.quantity):this.total.taxableAmount.zero();this.pricing.tax={taxRuleId:t.getTaxRuleId(),taxSystem:t.getTaxSystem(),country:t.getCountry(),rate:t.getApplicableTaxRate(e),taxSlabs:t.getSlabs()},this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((y,m)=>y+m.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,subtotal:t,taxableAmount:t,taxTotal:t,discounts:{},grandTotal:t};return}let{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),n=i.multiply(e),s=Object.values(this.total.discounts).reduce((y,m)=>y.add(m),t),o=n.subtract(s),c=e>0?o.divide(e):t,u=_.getApplicableTaxRate(c,this.pricing.tax.taxSlabs),a=o.multiply(u).round(),g=n.subtract(s).add(a);this.total={quantity:e,subtotal:n,taxableAmount:o,taxTotal:a,discounts:this.total.discounts,grandTotal:g};}updateState(t){if(this.state in J)this.state!==t&&(this.state=t);else throw new O(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new T({sources:{original:""}}),this.subItems=[],this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:this.pricing.tax},this.total={quantity:0,subtotal:t,taxableAmount:t,taxTotal:t,discounts:{},grandTotal:t};}};var N=class extends b{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(t,e=new Date){if(super(t,e),this.couponCode=t.couponCode,this.name=d.deepClone(t.name),this.description=d.deepClone(t.description),this.type=t.type,this.customerId=t.customerId,this.validFrom=t.validFrom&&Date.parse(t.validFrom)?new Date(t.validFrom).toISOString():e.toISOString(),this.validTo=t.validTo&&Date.parse(t.validTo)?new Date(t.validTo).toISOString():e.toISOString(),this.minCartValue=Object.keys(t.minCartValue).reduce((i,n)=>{let s=t.minCartValue[n];return s&&(i[n]=new l(s)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,n)=>{let s=t.maxCartDiscount[n];return s&&(i[n]=new l(s)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new f("Percentage value cannot be greater than 100");this.applicableTo=t.applicableTo,this.category=t.category;}getCode(){return this.couponCode}getName(t){return t?this.name[t]??this.name[C[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[C[t]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(t){return t?this.minCartValue[t]:this.minCartValue}getMaxCartDiscount(t){return t?this.maxCartDiscount[t]:this.maxCartDiscount}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:Object.keys(this.getMinCartValue()).reduce((t,e)=>{let i=this.getMinCartValue(e);return i&&(t[e]=i.getDetails()),t},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((t,e)=>{let i=this.getMaxCartDiscount(e);return i&&(t[e]=i.getDetails()),t},{}),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(t){return this.applicableTo==="all"||this.applicableTo==="ftb"&&t}calculateApplicableCouponDiscount(t,e,i,n,s=!0){let o=new l({amount:0,currency:n}),c;if(s&&!this.isActive())return o;let u=this.getMinCartValue(i),a=this.getMaxCartDiscount(i);if(!u||u.compareTo(t)>0||!a)return o;let g=this.getCategory(),y=this.getDiscountMethod(),m=g==="SHIPPING"?e:t;if(m.getAmount()<=0)return o;switch(y){case"flat":let mt=a;c=m.min(mt);break;case"percentage":c=m.multiply(this.getPercentageValue()/100).round();break;default:return o}return c.min(a)}};var R=class extends b{id;customerId;customerEmail;anonymousId;lineItems;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,e=new Date){super(t,e),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(i=>new L(i)),this.billingAddress=t.billingAddress?new A(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new A(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new N(i)),this.shippingDetails=t.shippingDetails?d.deepClone(t.shippingDetails):null,this.total={subtotal:new l(t.total.subtotal),shipping:new l(t.total.shipping),effectiveShipping:new l(t.total.effectiveShipping),taxTotal:new l(t.total.taxTotal),couponTotal:Object.fromEntries(Object.entries(t.total.couponTotal).map(([i,n])=>[i,new l(n)])),couponDiscountTotal:new l(t.total.couponDiscountTotal),grandTotal:new l(t.total.grandTotal)};}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new L(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new A(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new A(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return this.total}getDetails(){return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(t=>t.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(t=>t.getDetails()),total:{subtotal:this.getTotal().subtotal.getDetails(),shipping:this.getTotal().shipping.getDetails(),effectiveShipping:this.getTotal().effectiveShipping.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),couponTotal:Object.fromEntries(Object.entries(this.getTotal().couponTotal).map(([t,e])=>[t,e.getDetails()])),couponDiscountTotal:this.getTotal().couponDiscountTotal.getDetails(),grandTotal:this.getTotal().grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new l({amount:0,currency:this.currency}),e=this.lineItems.filter(m=>m.getState()!=="CANCELLED"),i=e.reduce((m,I)=>m.add(I.getTotal().subtotal),t),n=new l({amount:this.shippingDetails?.cost||0,currency:this.currency}).round(),s=t,o={},c={};this.coupons.forEach(m=>{let I=m.calculateApplicableCouponDiscount(i,n,this.country,this.currency);s=s.add(I),o[m.getCode()]=I,m.getCategory()!=="SHIPPING"&&(c[m.getCode()]=I);}),this.applyDiscountsInLineItem(c);let u=e.reduce((m,I)=>m.add(I.getTotal().taxTotal),t),a=this.coupons.find(m=>m.getCategory()==="SHIPPING"),g=a?n.subtract(o[a.getCode()]||t):n,y=i.add(n).add(u).subtract(s);this.total={subtotal:i,shipping:n,effectiveShipping:g,couponTotal:o,couponDiscountTotal:s,taxTotal:u,grandTotal:y};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let e=t.filter(n=>n.getCategory()==="SHIPPING"),i=t.filter(n=>n.getCategory()!=="SHIPPING");this.coupons=[],this.total.couponDiscountTotal=this.total.subtotal.zero(),this.total.couponTotal={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.couponTotal),e.length&&this.applyShippingCoupons(e),this.calculateTotals();}applyDiscountsInLineItem(t){let e=Array.from(Object.entries(t)).filter(n=>!n[1].isZero()),i=new Map;this.lineItems.forEach(n=>i.set(n.getId(),[])),e.forEach(([n,s])=>{let o=this.coupons.find(a=>a.getCode()===n);if(!o||s.isZero())return;let c=this.lineItems.filter(a=>a.getState()!=="CANCELLED"&&!a.getTotal().subtotal.isZero()).sort((a,g)=>a.getTotal().subtotal.compareTo(g.getTotal().subtotal)),u=new l({amount:0,currency:this.currency});c.forEach((a,g)=>{let y;g===c.length-1?y=s.subtract(u):y=s.multiply(a.getTotal().subtotal).divide(this.total.subtotal).round(),u=u.add(y),i.get(a.getId())?.push({coupon:o,amount:y});});}),this.lineItems.forEach(n=>{n.getState()==="CANCELLED"||this.total.subtotal.isZero()?n.updateDiscounts([]):n.updateDiscounts(i.get(n.getId())||[]);});}updateTax(t){this.lineItems.forEach(e=>{e.updateTax(t[e.getPricing().taxCategory]);}),this.calculateTotals();}applyNonShippingCoupons(t){let e=t.filter(i=>i.getType()==="coupon");if(e.length===1){let i=e[0].calculateApplicableCouponDiscount(this.total.subtotal,this.total.shipping,this.country,this.currency);i.getAmount()>0&&(this.coupons.push(e[0]),this.total.couponTotal[e[0].getCode()]=i,this.total.couponDiscountTotal=i);}}applyShippingCoupons(t){if(this.total.shipping.getAmount()>0&&t.length>0){let e=this.total.subtotal.subtract(this.total.couponDiscountTotal),i=t.reduce((s,o)=>{if(!s)return o;let c=o.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping),u=s.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping);return c===u?o.getType()==="coupon"?o:s:c.compareTo(u)>0?o:s}),n=i.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping);n.getAmount()>0&&(this.coupons.push(i),this.total.couponTotal[i.getCode()]=n,this.total.couponDiscountTotal=this.total.couponDiscountTotal.add(n),this.total.effectiveShipping=this.total.shipping.subtract(n));}}};var Mt=(s=>(s.PLACED="PLACED",s.PENDING_PAYMENT="PENDING_PAYMENT",s.PROCESSING="PROCESSING",s.CANCELLED="CANCELLED",s.COMPLETED="COMPLETED",s))(Mt||{}),ot=class extends R{orderNumber;cartId;paymentStatus;holdReason;state;constructor(t,e=new Date){super(t,e),this.orderNumber=t.orderNumber,this.cartId=t.cartId,this.paymentStatus=t.paymentStatus,this.holdReason=t.holdReason||"",this.state=t.state;}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getShippingAddress(){return this.shippingAddress}getBillingAddress(){return this.billingAddress}getOrderNumber(){return this.orderNumber}getCartId(){return this.cartId}getPaymentStatus(){return this.paymentStatus}getHoldReason(){return this.holdReason}getState(){return this.state}getLineItemState(t){let e=this.getLineItems().find(i=>i.getId()===t);if(!e)throw new U(t);return e.getState()}getDetails(){return {...super.getDetails(),orderNumber:this.getOrderNumber(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),shippingAddress:this.getShippingAddress().getDetails(),billingAddress:this.getBillingAddress().getDetails(),cartId:this.getCartId(),paymentStatus:this.getPaymentStatus(),holdReason:this.getHoldReason(),state:this.getState()}}};exports.OrderState=Mt;exports.default=ot;//# sourceMappingURL=Order.js.map
|
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var Dt=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Dt__default=/*#__PURE__*/_interopDefault(Dt);var H=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}},Q=class extends Error{constructor(t){super(`Invalid line item state: ${t}`),this.name="InvalidLineItemStateError";}},Z=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},Y=class extends Error{constructor(t){super(`Duplicate selection attribute found: ${t}`),this.name="DuplicateSelectionAttributeError";}},J=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},W=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},A=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},X=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},_=class extends Error{constructor(t="Pricing details not available for the product"){super(`NotFound: ${t}`),this.name="PricingNotFoundError";}},tt=class extends Error{constructor(t="Tax rule category mismatch."){super(`InvalidTaxRule: ${t}`),this.name="InvalidTaxRuleError";}},et=class extends Error{constructor(t="Tax category is not valid."){super(`InvalidTaxCategory: ${t}`),this.name="InvalidTaxCategoryError";}},it=class extends Error{constructor(t="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${t}`),this.name="InvalidMinQuantityError";}},rt=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},st=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},ot=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}},nt=class extends Error{constructor(t="No applicable tax slab or multiple slabs found for the given unit price."){super(`TaxSlabNotFound: ${t}`),this.name="TaxSlabNotFoundError";}},V=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},B=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},w=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},C=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},G=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}};var N=class{customFields;constructor(t,e=new Date){this.customFields={...t.customFields};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}},M=class extends N{version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){super(t),this.version=t.version??1,this.createdAt=t.createdAt&&!isNaN(Date.parse(t.createdAt))?new Date(t.createdAt).toISOString():e.toISOString(),this.modifiedAt=t.modifiedAt&&!isNaN(Date.parse(t.modifiedAt))?new Date(t.modifiedAt).toISOString():e.toISOString(),this.modifiedBy={...t.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(t,e,i,r){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:r};}};var v=class extends M{id;firstName;lastName;company;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(t,e=new Date){super(t,e),this.id=t.id,this.firstName=t.firstName,this.lastName=t.lastName||"",this.company=t.company||"",this.phone=t.phone,this.email=t.email,this.addressLine1=t.addressLine1,this.addressLine2=t.addressLine2||"",this.city=t.city,this.postalCode=t.postalCode,this.state=t.state,this.country=t.country,this.isBillingAddress=t.isBillingAddress,this.isShippingAddress=t.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),company:this.getCompany(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getCompany(){return this.company}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(t){return t==="shipping"||t==="billing&shipping"}static checkIfBillingAddress(t){return t==="billing"||t==="billing&shipping"}};var ct=new Uint8Array(256),at=ct.length;function gt(){return at>ct.length-16&&(Dt__default.default.randomFillSync(ct),at=0),ct.slice(at,at+=16)}var ft=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function At(s){return typeof s=="string"&&ft.test(s)}var xt=At;var T=[];for(let s=0;s<256;++s)T.push((s+256).toString(16).slice(1));function lt(s,t=0){return T[s[t+0]]+T[s[t+1]]+T[s[t+2]]+T[s[t+3]]+"-"+T[s[t+4]]+T[s[t+5]]+"-"+T[s[t+6]]+T[s[t+7]]+"-"+T[s[t+8]]+T[s[t+9]]+"-"+T[s[t+10]]+T[s[t+11]]+T[s[t+12]]+T[s[t+13]]+T[s[t+14]]+T[s[t+15]]}function Mt(s){if(!xt(s))throw TypeError("Invalid UUID");let t,e=new Uint8Array(16);return e[0]=(t=parseInt(s.slice(0,8),16))>>>24,e[1]=t>>>16&255,e[2]=t>>>8&255,e[3]=t&255,e[4]=(t=parseInt(s.slice(9,13),16))>>>8,e[5]=t&255,e[6]=(t=parseInt(s.slice(14,18),16))>>>8,e[7]=t&255,e[8]=(t=parseInt(s.slice(19,23),16))>>>8,e[9]=t&255,e[10]=(t=parseInt(s.slice(24,36),16))/1099511627776&255,e[11]=t/4294967296&255,e[12]=t>>>24&255,e[13]=t>>>16&255,e[14]=t>>>8&255,e[15]=t&255,e}var Tt=Mt;function wt(s){s=unescape(encodeURIComponent(s));let t=[];for(let e=0;e<s.length;++e)t.push(s.charCodeAt(e));return t}var Lt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Rt="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function pt(s,t,e){function i(r,o,a,u){var l;if(typeof r=="string"&&(r=wt(r)),typeof o=="string"&&(o=Tt(o)),((l=o)===null||l===void 0?void 0:l.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+r.length);if(c.set(o),c.set(r,o.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,a){u=u||0;for(let d=0;d<16;++d)a[u+d]=c[d];return a}return lt(c)}try{i.name=s;}catch{}return i.DNS=Lt,i.URL=Rt,i}var mt={randomUUID:Dt__default.default.randomUUID};function vt(s,t,e){if(mt.randomUUID&&!t&&!s)return mt.randomUUID();s=s||{};let i=s.random||(s.rng||gt)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){e=e||0;for(let r=0;r<16;++r)t[e+r]=i[r];return t}return lt(i)}var ht=vt;function Bt(s){return Array.isArray(s)?s=Buffer.from(s):typeof s=="string"&&(s=Buffer.from(s,"utf8")),Dt__default.default.createHash("sha1").update(s).digest()}var Ct=Bt;var Ut=pt("v5",80,Ct),yt=Ut;var I={"en-IN":"en","kn-IN":"kn"};var St={INR:"\u20B9"},It={INR:"en-IN"};var ut=(d=>(d.INITIAL="INITIAL",d.PROCESSING="PROCESSING",d.SHIPPED="SHIPPED",d.DELIVERED="DELIVERED",d.CANCELLED="CANCELLED",d.RETURN_REQUESTED="RETURN_REQUESTED",d.RETURNED="RETURNED",d.REFUND_INITIATED="REFUND_INITIATED",d.REFUNDED="REFUNDED",d.ON_HOLD="ON_HOLD",d))(ut||{});var L=class{sources;alt;order;label;constructor(t){if(this.sources={...t.sources},this.alt=t.alt,this.order=t.order,this.label=t.label,!this.sources.original)throw new G("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(t){return this.sources[t]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(t){this.alt=t;}setOrder(t){this.order=t;}setLabel(t){this.label=t;}setSource(t,e){if(e===void 0){if(t==="original")throw new G("Cannot remove the 'original' image source.");delete this.sources[t];}else this.sources[t]=e;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var n=class s{#t;amount;currency;constructor(t){if(this.#t="PriceModel",t.amount<0)throw new V("Amount cannot be negative.");if(!t.currency)throw new B("Currency code is required.");this.amount=t.amount,this.currency=t.currency;}get kind(){return this.#t}static isPriceModel(t){return typeof t=="object"&&t!==null&&t.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot compare prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return this.amount-t.getAmount()}add(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot add prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return new s({amount:this.amount+t.getAmount(),currency:this.currency})}subtract(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot subtract prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return new s({amount:this.amount-t.getAmount(),currency:this.currency})}multiply(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot multiply prices in different currencies.");return new s({amount:this.amount*t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>=0)return new s({amount:this.amount*t,currency:this.currency});throw new C("Must be a non-negative number.")}divide(t){if(s.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new w("Cannot divide prices in different currencies.");return new s({amount:this.amount/t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>0)return new s({amount:this.amount/t,currency:this.currency});throw new C("Must be a positive number.")}min(...t){if(t.length===0)throw new C("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(s.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new w("Cannot compare prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i},this)}max(...t){if(t.length===0)throw new C("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(s.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new w("Cannot compare prices in different currencies.")}else throw new C("Must be a PriceModel instance.");return e.compareTo(i)>0?e:i},this)}zero(){return new s({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new s({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return s.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return s.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(t,e,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let r=It[e];if(!e||!r)throw new B("Invalid currency code for formatting.");let o=t,a=i.displayAsInteger?0:s.getDecimalPlaces(e),u={style:i.style??"currency",currency:e,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(r,u).format(o)}catch(l){return console.error(`Error formatting price for currency "${e}" and locale "${r}":`,l),`${St[e]??e} ${s.addThousandSeparators(o.toFixed(a))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),i=e[0],r=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+r}static getRoundedAmount(t,e){if(t<0)throw new V("Amount cannot be negative for rounding.");if(e===void 0)throw new B("Invalid currency code for rounding.");let i=s.getDecimalPlaces(e),r=Math.pow(10,i);return Math.round(t*r)/r}};var U=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new n(t.baseUnitPrice);if(!t.taxCategory)throw new et;let i=(t.tiers??[]).map(l=>({minQuantity:l.minQuantity,unitPrice:new n(l.unitPrice)})).sort((l,c)=>l.minQuantity-c.minQuantity);if(i.some(l=>l.minQuantity<=0))throw new it;let o=i.some(l=>l.unitPrice.getCurrency()!==e.getCurrency()),a=i.some((l,c)=>c>0&&l.unitPrice.compareTo(i[c-1].unitPrice)>0),u=i[0]?.unitPrice.compareTo(e)>0;if(o||a||u)throw new rt("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=e,this.taxCategory=t.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}}getApplicableTier(t){if(t<=0)throw new st;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity)return this.tiers[e];throw new ot(t)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let t=this.tiers[this.tiers.length-1].unitPrice.getAmount(),e=this.baseUnitPrice.getAmount();return (e-t)/e*100}};var O=class s extends M{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(t){if(typeof t!="object")throw new A("Selection attributes must be an object");return Object.keys(t).filter(i=>t[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>t[i].name?`${i}:c+${t[i].name}`:`${i}:${t[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(t){try{let e={},i=t.split("|");for(let r of i){let[o,a]=r.split(":");a.startsWith("c+")?e[o]={name:a.slice(2)}:e[o]=a;}return e}catch(e){throw new A(e?.message)}}constructor(t,e=new Date){super(t,e),this.id=t.id,this.key=t.key,this.name={...t.name},this.description={...t.description},this.slug={...t.slug},this.brand=t.brand,this.pricing=Object.keys(t.pricing).reduce((r,o)=>(t.pricing[o]&&(r[o]=new U(t.pricing[o])),r),{}),this.targetGender=t.targetGender,this.attributes=g.deepClone(t.attributes),this.specifications=g.deepClone(t.specifications),this.categories=g.deepClone(t.categories);let i=new Set;this.variants=(t.variants||[]).map(r=>{if(!r.selectionAttributes||typeof r.selectionAttributes!="object")throw new A("Selection attributes are required");this.checkSelectionAttributes(r.selectionAttributes);let o=s.generateSelectionAttributesKey(r.selectionAttributes);if(i.has(o))throw new Y(o);return i.add(o),{sku:r.sku,selectionAttributes:r.selectionAttributes,images:{primary:new L(r.images.primary),gallery:(r.images.gallery||[]).map(a=>new L(a))}}}),this.isActive=t.isActive,this.searchTags=t.searchTags?g.deepClone(t.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(t){return t?this.name[t]??this.name[I[t]]??this.name.en:g.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[I[t]]??this.description.en:g.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[I[t]]??this.slug.en:g.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:this.pricing}getAttributes(){return g.deepClone(this.attributes)}getVariants(){return this.variants.map(t=>({sku:t.sku,selectionAttributes:t.selectionAttributes,images:{primary:t.images.primary,gallery:t.images.gallery}}))}getImagesBySelectionAttributes(t){let e=s.generateSelectionAttributesKey(t),i=this.variants.find(r=>s.generateSelectionAttributesKey(r.selectionAttributes)===e);return i?i.images:null}getImages(t,e){switch(e){case"PRIMARY":return this.getImagesBySelectionAttributes(t)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(t)?.gallery??[];default:return this.getImagesBySelectionAttributes(t)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return g.deepClone(this.categories)}getSpecifications(t){return t?g.deepClone(this.specifications[t]??this.specifications[I[t]]??this.specifications.en):g.deepClone(this.specifications)}getSearchTags(t){return t?g.deepClone(this.searchTags[t]??this.searchTags[I[t]]??this.searchTags.en):g.deepClone(this.searchTags)}getDetails(){let t=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((e,i)=>(this.pricing[i]&&(e[i]=this.pricing[i]?.getDetails()),e),{}),attributes:this.getAttributes(),variants:this.variants.map(e=>({sku:e.sku,selectionAttributes:g.deepClone(e.selectionAttributes),images:{primary:e.images.primary.getDetails(),gallery:e.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...t}}checkSelectionAttributes(t){if(!t||typeof t!="object")throw new A("Selection attributes are required");Object.keys(this.attributes).forEach(e=>{if(e.toLowerCase()==="size")return;let i=this.attributes[e],r=t[e];if(r===void 0)throw new A(`Selection attribute '${e}' is missing`);if(typeof i=="string"){if(typeof r!="string"||i!==r)throw new A(`Selection attribute '${e}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof r!="string"||!i.includes(r))throw new A(`Selection attribute '${e}' is invalid`)}else if(typeof r!="object"||!("name"in r)||i.findIndex(o=>o.name===r.name)<0)throw new A(`Selection attribute '${e}' is invalid`)}});}validateSelectionAttribute(t){let e=s.generateSelectionAttributesKey(t);return this.variants.some(i=>s.generateSelectionAttributesKey(i.selectionAttributes)===e)}validateSize(t){return this.attributes.size.includes(t)}};var Ot={isUUID:s=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(s),isEmail:s=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(s),isURL:s=>/^(http|https):\/\/[^ "]+$/.test(s),generateUUID:(s,t)=>t&&s?yt(s,t):ht(),generateSearchId:(s,t)=>`${s}#${O.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:s=>{let[t,e]=s.split("#");return {key:t,selectionAttributes:O.parseSelectionAttributesKey(e)}},deepClone(s){return structuredClone(s)}},g=Ot;var $=class s{taxRuleId;taxCategory;taxSystem;taxSubSystem;country;slabs;effectiveFrom;effectiveTo;constructor(t){this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxSubSystem=t.taxSubSystem,this.taxCategory=t.taxCategory,this.country=t.country,this.slabs=t.slabs.map(e=>({rate:e.rate,minUnitPrice:new n(e.minUnitPrice),maxUnitPrice:e.maxUnitPrice?new n(e.maxUnitPrice):void 0})),this.effectiveFrom=new Date(t.effectiveFrom),this.effectiveTo=t.effectiveTo?new Date(t.effectiveTo):void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getSlabs(){return this.slabs}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),slabs:this.getSlabs().map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0})),effectiveFrom:this.effectiveFrom.toISOString(),effectiveTo:this.effectiveTo?this.effectiveTo.toISOString():void 0}}appliesTo(t,e,i=new Date){return this.taxCategory===t&&this.country===e&&this.effectiveFrom<=i&&(this.effectiveTo?this.effectiveTo>=i:!0)}getApplicableTaxRate(t){return s.getApplicableTaxRate(t,this.slabs)}calculateTax(t){let e=this.getApplicableTaxRate(t);return t.multiply(e).round()}static getApplicableTaxRate(t,e){let i=e.filter(r=>(r.minUnitPrice===void 0||t.compareTo(r.minUnitPrice)>=0)&&(r.maxUnitPrice===void 0||t.compareTo(r.maxUnitPrice)<0));if(i.length!==1)throw new nt;return i[0].rate}static getTaxRateDisplayString(t,e,i){let r=e*100,o=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,"");return i.percentageOnly?`${o}%`:t.getTaxSystem()==="GST"?`${o}% ${t.getTaxSubSystem()}`:`${o}% ${t.getTaxSystem()}`}},dt=class extends ${rate;constructor(t){super({taxRuleId:t.taxRuleId,taxSystem:t.taxSystem,taxSubSystem:t.taxSubSystem,taxCategory:t.taxCategory,country:t.country,effectiveFrom:t.effectiveFrom,effectiveTo:t.effectiveTo,slabs:[{minUnitPrice:{amount:0,currency:"INR"},rate:t.rate}]}),this.rate=t.rate;}getApplicableTaxRate(){return this.slabs[0].rate}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),rate:this.getApplicableTaxRate(),slabs:this.getSlabs().map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0})),effectiveFrom:this.effectiveFrom.toISOString(),effectiveTo:this.effectiveTo?this.effectiveTo.toISOString():void 0}}};var k=class extends N{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=g.deepClone(t.selectionAttributes),this.name=g.deepClone(t.name),this.specifications=g.deepClone(t.specifications),this.primaryImage=new L(t.primaryImage),this.subItems=g.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new Z(i.size);e.add(i.size);}),this.pricing={unitPrice:new n(t.pricing.unitPrice),tierPricing:new U(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(i=>new $(i))},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,unitPrice:new n(t.total.unitPrice),subtotal:new n(t.total.subtotal),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,r])=>[i,new n(r)])),totalDiscount:new n(t.total.totalDiscount),netUnitPrice:new n(t.total.netUnitPrice),netSubtotal:new n(t.total.netSubtotal),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:new n(r.taxableUnitPrice),taxPerUnit:new n(r.taxPerUnit),amount:new n(r.amount),system:r.system,subSystem:r.subSystem}])),taxTotal:new n(t.total.taxTotal),grandTotal:new n(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return g.deepClone(this.selectionAttributes)}getName(t){return t?g.deepClone(this.name[t]??this.name[I[t]]??this.name.en):g.deepClone(this.name)}getSpecifications(t){return t?g.deepClone(this.specifications[t]??this.specifications[I[t]]??this.specifications.en):g.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return g.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule}}getState(){return this.state}getTotal(){return {quantity:this.total.quantity,unitPrice:this.total.unitPrice,subtotal:this.total.subtotal,discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,e])=>[t,e])),totalDiscount:this.total.totalDiscount,netUnitPrice:this.total.netUnitPrice,netSubtotal:this.total.netSubtotal,taxBreakdown:this.total.taxBreakdown,taxTotal:this.total.taxTotal,grandTotal:this.total.grandTotal}}getDetails(){let t=this.getPricing(),e=this.getTotal();return {id:this.getId(),productKey:this.getProductKey(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:t.unitPrice.getDetails(),tierPricing:t.tierPricing.getDetails(),taxCategory:t.taxCategory,applicableTaxRule:t.applicableTaxRule.map(i=>i.getDetails())},state:this.getState(),total:{quantity:e.quantity,unitPrice:e.unitPrice.getDetails(),subtotal:e.subtotal.getDetails(),discounts:Object.fromEntries(Object.entries(e.discounts).map(([i,r])=>[i,r.getDetails()])),totalDiscount:e.totalDiscount.getDetails(),netUnitPrice:e.netUnitPrice.getDetails(),netSubtotal:e.netSubtotal.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(e.taxBreakdown).map(([i,r])=>[i,{rate:r.rate,taxableUnitPrice:r.taxableUnitPrice.getDetails(),taxPerUnit:r.taxPerUnit.getDetails(),amount:r.amount.getDetails(),system:r.system,subSystem:r.subSystem}])),taxTotal:e.taxTotal.getDetails(),grandTotal:e.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(o=>o.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity>0),this.calculateTotals();}updateProductData(t,e,i){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new J;if(!t.getIsActive())throw new W;this.subItems.forEach(u=>{if(!t.validateSize(u.size))throw new X});let r=t.getPriceDetails(e);if(!r||r.getBaseUnitPrice().getCurrency()!==i)throw new _;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let o=this.subItems.reduce((u,l)=>u+l.quantity,0),{unitPrice:a}=r.getApplicableTier(o);this.pricing={unitPrice:a,tierPricing:r,taxCategory:r.getTaxCategory(),applicableTaxRule:this.pricing.applicableTaxRule},this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discounts=e,this.calculateTotals();}updateTax(t){t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new tt}),this.pricing.applicableTaxRule=t,this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((h,f)=>h+f.quantity,0);if(this.state==="CANCELLED"){this.total={quantity:0,unitPrice:t,subtotal:t,discounts:{},totalDiscount:t,netUnitPrice:t,netSubtotal:t,taxBreakdown:{},taxTotal:t,grandTotal:t};return}let{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),r=i.multiply(e),o=Object.values(this.total.discounts).reduce((h,f)=>h.add(f),t),a=r.subtract(o),u=e>0?a.divide(e):t,l={},c=t;this.pricing.applicableTaxRule.forEach(h=>{let f=h.getApplicableTaxRate(u),P=h.calculateTax(u),D=P.multiply(e);l[h.getTaxRuleId()]={rate:f,taxableUnitPrice:u,taxPerUnit:P,amount:D,system:h.getTaxSystem(),subSystem:h.getTaxSubSystem()},c=c.add(D);});let d=a.add(c);this.total={quantity:e,unitPrice:i,subtotal:r,discounts:this.total.discounts,totalDiscount:o,netUnitPrice:u,netSubtotal:a,taxBreakdown:l,taxTotal:c,grandTotal:d};}updateState(t){if(this.state in ut)this.state!==t&&(this.state=t);else throw new Q(t)}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new L({sources:{original:""}}),this.subItems=[],this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,applicableTaxRule:[]},this.total={quantity:0,unitPrice:t,subtotal:t,discounts:{},totalDiscount:t,netUnitPrice:t,netSubtotal:t,taxBreakdown:{},taxTotal:t,grandTotal:t};}};var j=class extends M{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(t,e=new Date){if(super(t,e),this.couponCode=t.couponCode,this.name=g.deepClone(t.name),this.description=g.deepClone(t.description),this.type=t.type,this.customerId=t.customerId,this.validFrom=t.validFrom&&Date.parse(t.validFrom)?new Date(t.validFrom).toISOString():e.toISOString(),this.validTo=t.validTo&&Date.parse(t.validTo)?new Date(t.validTo).toISOString():e.toISOString(),this.minCartValue=Object.keys(t.minCartValue).reduce((i,r)=>{let o=t.minCartValue[r];return o&&(i[r]=new n(o)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,r)=>{let o=t.maxCartDiscount[r];return o&&(i[r]=new n(o)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new C("Percentage value cannot be greater than 100");this.applicableTo=t.applicableTo,this.category=t.category;}getCode(){return this.couponCode}getName(t){return t?this.name[t]??this.name[I[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[I[t]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(t){return t?this.minCartValue[t]:this.minCartValue}getMaxCartDiscount(t){return t?this.maxCartDiscount[t]:this.maxCartDiscount}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:Object.keys(this.getMinCartValue()).reduce((t,e)=>{let i=this.getMinCartValue(e);return i&&(t[e]=i.getDetails()),t},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((t,e)=>{let i=this.getMaxCartDiscount(e);return i&&(t[e]=i.getDetails()),t},{}),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(t){return this.applicableTo==="all"||this.applicableTo==="ftb"&&t}calculateApplicableCouponDiscount(t,e,i,r,o=!0){let a=new n({amount:0,currency:r}),u;if(o&&!this.isActive())return a;let l=this.getMinCartValue(i),c=this.getMaxCartDiscount(i);if(!l||l.compareTo(t)>0||!c)return a;let d=this.getCategory(),h=this.getDiscountMethod(),f=d==="SHIPPING"?e:t;if(f.getAmount()<=0)return a;switch(h){case"flat":let D=c;u=f.min(D);break;case"percentage":u=f.multiply(this.getPercentageValue()/100).round();break;default:return a}return u.min(c)}};var F=class extends N{id;name;category;lineItemId;chargeType;pricing;total;constructor(t){super(t),this.id=t.id,this.name=t.name,this.category=t.category,this.lineItemId=t.lineItemId,this.chargeType=t.chargeType,this.pricing={price:new n(t.pricing.price),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(e=>new dt(e))},this.total={price:new n(t.total.price),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([e,i])=>[e,new n(i)])),totalDiscount:new n(t.total.totalDiscount),netPrice:new n(t.total.netPrice),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxablePrice:new n(i.taxablePrice),amount:new n(i.amount),system:i.system,subSystem:i.subSystem}])),taxTotal:new n(t.total.taxTotal),grandTotal:new n(t.total.grandTotal)};}getId(){return this.id}getName(){return this.name}getCategory(){return this.category}getChargeType(){return this.chargeType}getLineItemId(){return this.lineItemId}getPricing(){return this.pricing}getTotal(){return this.total}getApplicableTaxRules(){return this.pricing.applicableTaxRule}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discounts=e,this.calculateTotals();}calculateTotals(){let t=this.pricing.price.zero(),e=this.pricing.price,i=Object.values(this.total.discounts).reduce((b,S)=>b.add(S),t),r=e.subtract(i),o={},a=this.pricing.applicableTaxRule.reduce((b,S)=>b+S.getApplicableTaxRate(),0),u=r.divide(1+a).round(),l=r.subtract(u),c=t,d=this.pricing.applicableTaxRule.reduce((b,S)=>S.getApplicableTaxRate()>b.getApplicableTaxRate()?S:b),h=d.getTaxRuleId();this.pricing.applicableTaxRule.forEach(b=>{if(b.getTaxRuleId()===h)return;let S=b.getApplicableTaxRate(),z=l.multiply(S).divide(a).round();o[b.getTaxRuleId()]={rate:S,taxablePrice:u,amount:z,system:b.getTaxSystem(),subSystem:b.getTaxSubSystem()},c=c.add(z);});let f=l.subtract(c);o[h]={rate:d.getApplicableTaxRate(),taxablePrice:u,amount:f,system:d.getTaxSystem(),subSystem:d.getTaxSubSystem()};let P=u,D=r;this.total={price:e,discounts:this.total.discounts,netPrice:P,totalDiscount:i,taxBreakdown:o,taxTotal:l,grandTotal:D};}updateTax(t){this.pricing.applicableTaxRule=t,this.calculateTotals();}getDetails(){return {id:this.id,name:g.deepClone(this.name),category:this.category,lineItemId:this.lineItemId,chargeType:this.chargeType,pricing:{price:this.pricing.price.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(e=>e.getDetails())},total:{price:this.total.price.getDetails(),discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([e,i])=>[e,i.getDetails()])),totalDiscount:this.total.totalDiscount.getDetails(),netPrice:this.total.netPrice.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,i])=>[e,{rate:i.rate,taxablePrice:i.taxablePrice.getDetails(),amount:i.amount.getDetails(),system:i.system,subSystem:i.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};var q=class extends M{id;customerId;customerEmail;anonymousId;lineItems;charges;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,e=new Date){super(t,e),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(i=>new k(i)),this.charges=(t.charges??[]).map(i=>new F(i)),this.billingAddress=t.billingAddress?new v(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new v(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new j(i)),this.shippingDetails=t.shippingDetails?g.deepClone(t.shippingDetails):null,this.total={subtotal:new n(t.total.subtotal),netSubtotal:new n(t.total.netSubtotal),lineItemTaxTotal:new n(t.total.lineItemTaxTotal||{amount:0,currency:t.currency}),lineItemTaxBreakdown:this.mapTaxBreakdown(t.total.lineItemTaxBreakdown||{}),chargesTotal:new n(t.total.chargesTotal||{amount:0,currency:t.currency}),shippingCharge:new n(t.total.shippingCharge),netShippingCharge:new n(t.total.netShippingCharge),chargeTaxTotal:new n(t.total.chargeTaxTotal||{amount:0,currency:t.currency}),chargeTaxBreakdown:this.mapTaxBreakdown(t.total.chargeTaxBreakdown||{}),taxTotal:new n(t.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(t.total.taxBreakdown),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,r])=>[i,new n(r)])),totalDiscount:new n(t.total.totalDiscount),grandTotal:new n(t.total.grandTotal)};}mapTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,i])=>[e,{system:i.system,totalAmount:new n(i.totalAmount),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,o])=>[r,new n(o)]))}]))}serializeTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,i])=>[e,{system:i.system,totalAmount:i.totalAmount.getDetails(),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([r,o])=>[r,o.getDetails()]))}]))}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new k(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(t=>new F(t.getDetails()))}addCharge(t){this.charges.push(t),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new v(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new v(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return this.total}getDetails(){let t=this.getTotal();return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(e=>e.getDetails()),charges:this.getCharges().map(e=>e.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(e=>e.getDetails()),total:{subtotal:t.subtotal.getDetails(),netSubtotal:t.netSubtotal.getDetails(),lineItemTaxTotal:t.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(t.lineItemTaxBreakdown),chargesTotal:t.chargesTotal.getDetails(),shippingCharge:t.shippingCharge.getDetails(),netShippingCharge:t.netShippingCharge.getDetails(),chargeTaxTotal:t.chargeTaxTotal.getDetails(),chargeTaxBreakdown:this.serializeTaxBreakdown(t.chargeTaxBreakdown),taxTotal:t.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(t.taxBreakdown),discounts:Object.fromEntries(Object.entries(t.discounts).map(([e,i])=>[e,i.getDetails()])),totalDiscount:t.totalDiscount.getDetails(),grandTotal:t.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new n({amount:0,currency:this.currency}),e=this.lineItems.filter(p=>p.getState()!=="CANCELLED"),i=e.reduce((p,m)=>p.add(m.getTotal().subtotal),t),r=e.reduce((p,m)=>p.add(m.getTotal().netSubtotal),t),o=this.charges.filter(p=>p.getChargeType()==="SHIPPING").reduce((p,m)=>p.add(m.getTotal().price),t),a=t,u={},l={};this.coupons.forEach(p=>{let m=p.calculateApplicableCouponDiscount(i,o,this.country,this.currency);a=a.add(m),u[p.getCode()]=m,p.getCategory()!=="SHIPPING"&&(l[p.getCode()]=m);}),this.applyDiscountsInLineItem(l);let c=this.coupons.find(p=>p.getCategory()==="SHIPPING");c&&this.applyDiscuountsInShippingCharges({[c.getCode()]:u[c.getCode()]||t});let d=this.charges.reduce((p,m)=>p.add(m.getTotal().grandTotal),t),h=this.charges.filter(p=>p.getChargeType()==="SHIPPING").reduce((p,m)=>p.add(m.getTotal().grandTotal),t),f=t,P=t,D=t,b={},S={},z={},K=(p,m)=>{Object.entries(p).forEach(([Ft,R])=>{let x=R.system,E=R.subSystem;m[x]||(m[x]={system:x,totalAmount:t,subSystems:{}}),m[x].subSystems[E]?m[x].subSystems[E]=m[x].subSystems[E].add(R.amount):m[x].subSystems[E]=R.amount,m[x].totalAmount=m[x].totalAmount.add(R.amount),b[x]||(b[x]={system:x,totalAmount:t,subSystems:{}}),b[x].subSystems[E]?b[x].subSystems[E]=b[x].subSystems[E].add(R.amount):b[x].subSystems[E]=R.amount,b[x].totalAmount=b[x].totalAmount.add(R.amount);});};e.forEach(p=>{let m=p.getTotal().taxBreakdown;m&&(K(m,S),K(m,b),P=P.add(p.getTotal().taxTotal));}),this.charges.forEach(p=>{let m=p.getTotal().taxBreakdown;m&&(K(m,z),K(m,b),D=D.add(p.getTotal().taxTotal));}),f=P.add(D);let Pt=r.add(P).add(d);this.total={subtotal:i,netSubtotal:r,lineItemTaxTotal:P,lineItemTaxBreakdown:S,chargesTotal:d,shippingCharge:o,netShippingCharge:h,chargeTaxTotal:D,chargeTaxBreakdown:z,taxTotal:f,taxBreakdown:b,discounts:u,totalDiscount:a,grandTotal:Pt};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let e=t.filter(r=>r.getCategory()==="SHIPPING"),i=t.filter(r=>r.getCategory()!=="SHIPPING");this.coupons=[],this.total.totalDiscount=this.total.subtotal.zero(),this.total.discounts={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.discounts),e.length&&this.applyShippingCoupons(e),this.calculateTotals();}applyDiscountsInLineItem(t){let e=Array.from(Object.entries(t)).filter(r=>!r[1].isZero()),i=new Map;this.lineItems.forEach(r=>i.set(r.getId(),[])),e.forEach(([r,o])=>{let a=this.coupons.find(c=>c.getCode()===r);if(!a||o.isZero())return;let u=this.lineItems.filter(c=>c.getState()!=="CANCELLED"&&!c.getTotal().subtotal.isZero()).sort((c,d)=>c.getTotal().subtotal.compareTo(d.getTotal().subtotal)),l=new n({amount:0,currency:this.currency});u.forEach((c,d)=>{let h;d===u.length-1?h=o.subtract(l):h=o.multiply(c.getTotal().subtotal).divide(this.total.subtotal).round(),l=l.add(h),i.get(c.getId())?.push({coupon:a,amount:h});});}),this.lineItems.forEach(r=>{r.getState()==="CANCELLED"||this.total.subtotal.isZero()?r.updateDiscounts([]):r.updateDiscounts(i.get(r.getId())||[]);});}applyDiscuountsInShippingCharges(t){let e=Array.from(Object.entries(t)).filter(o=>!o[1].isZero()),i=this.charges.filter(o=>o.getChargeType()==="SHIPPING"),r=new Map;i.forEach(o=>r.set(o.getId(),[])),e.forEach(([o,a])=>{let u=this.coupons.find(d=>d.getCode()===o);if(!u||a.isZero())return;let l=i.sort((d,h)=>d.getTotal().grandTotal.compareTo(h.getTotal().grandTotal)),c=new n({amount:0,currency:this.currency});l.forEach((d,h)=>{let f;h===l.length-1?f=a.subtract(c):f=a.multiply(d.getTotal().grandTotal).divide(this.total.subtotal).round(),c=c.add(f),r.get(d.getId())?.push({coupon:u,amount:f});});}),i.forEach(o=>{o.updateDiscounts(r.get(o.getId())||[]);});}updateTax(t,e={}){this.lineItems.forEach(i=>{let r=t[i.getId()];r&&i.updateTax(r);}),this.charges.forEach(i=>{let r=e[i.getId()];r&&i.updateTax(r);}),this.calculateTotals();}applyNonShippingCoupons(t){let e=t.filter(i=>i.getType()==="coupon");if(e.length===1){let i=e[0].calculateApplicableCouponDiscount(this.total.subtotal,this.total.shippingCharge,this.country,this.currency);i.getAmount()>0&&(this.coupons.push(e[0]),this.total.discounts[e[0].getCode()]=i,this.total.totalDiscount=i);}}applyShippingCoupons(t){if(this.total.shippingCharge.getAmount()>0&&t.length>0){let e=this.total.subtotal.subtract(this.total.totalDiscount),i=t.reduce((o,a)=>{if(!o)return a;let u=a.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge),l=o.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge);return u===l?a.getType()==="coupon"?a:o:u.compareTo(l)>0?a:o}),r=i.calculateApplicableCouponDiscount(e,this.total.shippingCharge,this.country,this.currency).min(this.total.shippingCharge);r.getAmount()>0&&(this.coupons.push(i),this.total.discounts[i.getCode()]=r,this.total.totalDiscount=this.total.totalDiscount.add(r),this.total.netShippingCharge=this.total.shippingCharge.subtract(r));}}};var kt=(o=>(o.PLACED="PLACED",o.PENDING_PAYMENT="PENDING_PAYMENT",o.PROCESSING="PROCESSING",o.CANCELLED="CANCELLED",o.COMPLETED="COMPLETED",o))(kt||{}),bt=class extends q{orderNumber;cartId;paymentStatus;holdReason;state;constructor(t,e=new Date){super(t,e),this.orderNumber=t.orderNumber,this.cartId=t.cartId,this.paymentStatus=t.paymentStatus,this.holdReason=t.holdReason||"",this.state=t.state;}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getShippingAddress(){return this.shippingAddress}getBillingAddress(){return this.billingAddress}getOrderNumber(){return this.orderNumber}getCartId(){return this.cartId}getPaymentStatus(){return this.paymentStatus}getHoldReason(){return this.holdReason}getState(){return this.state}getLineItemState(t){let e=this.getLineItems().find(i=>i.getId()===t);if(!e)throw new H(t);return e.getState()}getDetails(){return {...super.getDetails(),orderNumber:this.getOrderNumber(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),shippingAddress:this.getShippingAddress().getDetails(),billingAddress:this.getBillingAddress().getDetails(),cartId:this.getCartId(),paymentStatus:this.getPaymentStatus(),holdReason:this.getHoldReason(),state:this.getState()}}};exports.OrderState=kt;exports.default=bt;//# sourceMappingURL=Order.js.map
|
|
3
2
|
//# sourceMappingURL=Order.js.map
|