b23-lib 1.11.1 → 1.11.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Order.js +1 -1
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/Order.mjs.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/{chunk-QKV5D6JZ.mjs → chunk-O5C6Z6AY.mjs} +2 -2
- package/dist/{chunk-QKV5D6JZ.mjs.map → chunk-O5C6Z6AY.mjs.map} +1 -1
- package/dist/{chunk-4LCZLYP7.mjs → chunk-WZLKQEOJ.mjs} +2 -2
- package/dist/{chunk-4LCZLYP7.mjs.map → chunk-WZLKQEOJ.mjs.map} +1 -1
- package/package.json +1 -1
package/dist/Classes/Cart.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as CartState,c as DEFAULT_CART_CONFIG,b as LineItemNotFoundError,d as default}from'../chunk-
|
|
1
|
+
export{a as CartState,c as DEFAULT_CART_CONFIG,b as LineItemNotFoundError,d as default}from'../chunk-WZLKQEOJ.mjs';import'../chunk-O5C6Z6AY.mjs';import'../chunk-K3AXPTGG.mjs';import'../chunk-DKI6BDWK.mjs';import'../chunk-V4H3X4PI.mjs';import'../chunk-HTJJLLGW.mjs';import'../chunk-RWBNLNQ6.mjs';import'../chunk-6PDP4ETM.mjs';import'../chunk-ATUUYYQT.mjs';//# sourceMappingURL=Cart.mjs.map
|
|
2
2
|
//# sourceMappingURL=Cart.mjs.map
|
package/dist/Classes/Order.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var l=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){this.customFields={...t.customFields},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};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}};var m={"en-IN":"en","kn-IN":"kn"};var y={IN:"INR"},S={INR:"\u20B9"};var h=class extends l{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(t,e=new Date){super(t,e),this.couponCode=t.couponCode,this.name={...t.name},this.description={...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=t.minCartValue.map(i=>({...i})),this.maxCartDiscount=t.maxCartDiscount.map(i=>({...i})),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.applicableTo=t.applicableTo,this.category=t.category;}getCode(){return this.couponCode}getName(t){return t?this.name[t]??this.name[m[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[m[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.find(e=>e.country===t):this.minCartValue}getMaxCartDiscount(t){return t?this.maxCartDiscount.find(e=>e.country===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:this.getMinCartValue(),maxCartDiscount:this.getMaxCartDiscount(),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}};var n=class a{price;country;constructor(t,e){if(this.country=e,t<0)throw new Error("InvalidPrice: Price cannot be negative.");this.price=t;}getCountry(){return this.country}getRoundedPrice(){return a.getRoundedPrice(this.price,this.country)}getFormattedString(t){return a.getFormattedString(this.price,this.country,t)}static getFormattedString(t,e,i,r={}){let s=r.displayAsInteger??!1,u=y[e];if(u===void 0)throw new Error("Currency mapping not found for CountryCode");let d=t,g=s?0:a.getDecimalPlaces(u),f={style:r.style??"currency",currency:u,signDisplay:"never",currencyDisplay:r.currencyDisplay,minimumFractionDigits:g,maximumFractionDigits:g};s&&(d=Math.round(d));try{return new Intl.NumberFormat(i,f).format(d)}catch(o){return console.error(`Error formatting price for country "${e}" and currency "${u}":`,o),`${S[u]??u} ${a.addThousandSeparators(d.toFixed(g))}`}}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 getRoundedPrice(t,e){if(t<0)throw new Error("Price cannot be negative for rounding.");let i=y[e];if(i===void 0)throw new Error(`Currency mapping not found for CountryCode: ${e}`);let r=a.getDecimalPlaces(i),s=Math.pow(10,r);return Math.round(t*s)/s}static getCurrency(t){return y[t]}};var p=class extends l{id;firstName;lastName;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.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(),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}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 I=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 "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 "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 C=class{id;productKey;variantId;name;attributes;specifications;primaryImage;subItems;totalQuantity;basePrice;priceTotals;priceTiers;constructor(t){this.id=t.id,this.productKey=t.productKey,this.variantId=t.variantId,this.name={...t.name},this.attributes={...t.attributes},this.specifications={...t.specifications},this.primaryImage=new I(t.primaryImage),this.subItems=t.subItems.map(e=>({...e})),this.basePrice={...t.basePrice},this.priceTiers=t.priceTiers.map(e=>({...e})),this.totalQuantity=0,this.priceTotals={subtotal:0,mrpTotal:0},this.recalculateTotalQuantity(),this.recalculatePriceTotal();}getId(){return this.id}getProductKey(){return this.productKey}getVariantId(){return this.variantId}getName(t){return t?this.name[t]??this.name[m[t]]??this.name.en:{...this.name}}getAttributes(){return {...this.attributes}}getSpecifications(t){return t?this.specifications[t]??this.specifications[m[t]]??this.specifications.en:JSON.parse(JSON.stringify(this.specifications))}getImage(){return this.primaryImage}getSubItems(){return this.subItems.map(t=>({...t}))}getTotalQuantity(){return this.totalQuantity}getBasePrice(){return {...this.basePrice}}getPriceTotals(){return {...this.priceTotals}}getPriceTiers(){return this.priceTiers.map(t=>({...t}))}recalculateTotalQuantity(){this.totalQuantity=this.subItems.reduce((t,e)=>t+e.quantity,0);}recalculatePriceTotal(){let t=this.totalQuantity,e=this.basePrice.unitPrice,i=null;for(let r of this.priceTiers.sort((s,u)=>u.minQuantity-s.minQuantity))if(t>=r.minQuantity){i=r;break}i&&(e=i.unitPrice),this.priceTotals.mrpTotal=this.basePrice.unitPrice*t,this.priceTotals.subtotal=e*t;}getDetails(){return {id:this.getId(),productKey:this.getProductKey(),variantId:this.getVariantId(),name:this.getName(),attributes:this.getAttributes(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),totalQuantity:this.getTotalQuantity(),basePrice:this.getBasePrice(),priceTotals:this.getPriceTotals(),priceTiers:this.getPriceTiers()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(s=>s.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity),this.recalculateTotalQuantity(),this.recalculatePriceTotal();}clearLineItem(){this.id="",this.productKey="",this.variantId="",this.name={en:""},this.attributes={color:{name:"",hex:""}},this.primaryImage=new I({sources:{original:""}}),this.subItems=[],this.recalculateTotalQuantity(),this.recalculatePriceTotal();}};var b=class extends l{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 C(i)),this.billingAddress=t.billingAddress?new p(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new p(t.shippingAddress,e):null,this.coupons=(t.coupons||[]).map(i=>new h(i)),this.shippingDetails=t.shippingDetails?{...t.shippingDetails}:null,this.total={shipping:t.total?.shipping||0,effectiveShipping:t.total?.effectiveShipping??t.total?.shipping??0,subtotal:t.total?.subtotal||0,mrpTotal:t.total?.mrpTotal||0,couponTotal:t.total?.couponTotal||{},grandTotal:t.total?.grandTotal||0};}recalculateBaseTotals(){this.total.subtotal=n.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=n.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().mrpTotal,0),this.country);}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new C(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new p(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new p(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons.map(t=>new h(t.getDetails()))}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {...this.total,couponTotal:{...this.total.couponTotal}}}calculateApplicableCouponDiscount(t,e=!0){if(e&&!t.isActive())return 0;let i=t.getMinCartValue(this.country),r=t.getMaxCartDiscount(this.country);if(!i||this.total.subtotal<i.price||!r||r.price<0)return 0;let s=t.getCategory(),u=t.getDiscountMethod(),d=0,g=s==="SHIPPING"?this.total.shipping:this.total.subtotal;if(g<=0)return 0;switch(u){case"flat":let o=r?.price??0;d=Math.min(g,o);break;case"percentage":d=g*(t.getPercentageValue()/100);break;default:return 0}let f=Math.min(d,r.price);return n.getRoundedPrice(Math.max(0,f),this.country)}recalculateCouponTotals(t=!0){this.total.couponTotal={};let e=0;return this.coupons.forEach(i=>{let r=this.calculateApplicableCouponDiscount(i,t);r>0&&(this.total.couponTotal[i.getCode()]=r,e+=r);}),n.getRoundedPrice(e,this.country)}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:this.getTotal(),country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}};var A=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}};var L=(s=>(s.PLACED="PLACED",s.PENDING_PAYMENT="PENDING_PAYMENT",s.PROCESSING="PROCESSING",s.CANCELLED="CANCELLED",s.COMPLETED="COMPLETED",s))(L||{}),P=(o=>(o.INITIAL="INITIAL",o.PROCESSING="PROCESSING",o.SHIPPED="SHIPPED",o.DELIVERED="DELIVERED",o.CANCELLED="CANCELLED",o.RETURN_REQUESTED="RETURN_REQUESTED",o.RETURNED="RETURNED",o.REFUND_INITIATED="REFUND_INITIATED",o.REFUNDED="REFUNDED",o.ON_HOLD="ON_HOLD",o))(P||{}),D=class extends b{orderNumber;cartId;paymentStatus;holdReason;state;lineItemStateMap;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;let i={};t.lineItems.forEach(r=>{let s=t.lineItemStateMap?.[r.id];i[r.id]={state:s?.state||"INITIAL",reason:s?.reason||"",transitionAt:s?.transitionAt||this.createdAt};}),this.lineItemStateMap=i,this.recalculateOrderBaseTotals();}recalculateOrderBaseTotals(){this.total.subtotal=n.getRoundedPrice(this.lineItems.filter(t=>!["CANCELLED","REFUND_INITIATED","REFUNDED"].includes(this.lineItemStateMap[t.getId()]?.state)).reduce((t,e)=>t+e.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=n.getRoundedPrice(this.lineItems.filter(t=>!["CANCELLED","REFUND_INITIATED","REFUNDED"].includes(this.lineItemStateMap[t.getId()]?.state)).reduce((t,e)=>t+e.getPriceTotals().mrpTotal,0),this.country);}updateOrderTotals(){this.recalculateOrderBaseTotals(),this.recalculateCouponTotals(!1);let t=this.coupons.filter(r=>r.getCategory()==="SHIPPING").reduce((r,s)=>r+(this.total.couponTotal[s.getCode()]??0),0);this.total.effectiveShipping=n.getRoundedPrice(Math.max(0,this.total.shipping-t),this.country);let e=this.coupons.filter(r=>r.getCategory()!=="SHIPPING").reduce((r,s)=>r+(this.total.couponTotal[s.getCode()]??0),0),i=this.total.subtotal+this.total.effectiveShipping;this.total.grandTotal=n.getRoundedPrice(Math.max(0,i-e),this.country);}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}getLineItemsStateMap(){return {...this.lineItemStateMap}}getLineItemState(t){if(!this.lineItemStateMap[t])throw new A(t);return this.lineItemStateMap[t].state}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(),lineItemStateMap:this.getLineItemsStateMap()}}};exports.OrderLineItemState=P;exports.OrderState=L;exports.default=D;//# sourceMappingURL=Order.js.map
|
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var l=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){this.customFields={...t.customFields},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};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}};var h={"en-IN":"en","kn-IN":"kn"};var y={IN:"INR"},S={INR:"\u20B9"};var m=class extends l{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(t,e=new Date){super(t,e),this.couponCode=t.couponCode,this.name={...t.name},this.description={...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=t.minCartValue.map(i=>({...i})),this.maxCartDiscount=t.maxCartDiscount.map(i=>({...i})),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.applicableTo=t.applicableTo,this.category=t.category;}getCode(){return this.couponCode}getName(t){return t?this.name[t]??this.name[h[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[h[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.find(e=>e.country===t):this.minCartValue}getMaxCartDiscount(t){return t?this.maxCartDiscount.find(e=>e.country===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:this.getMinCartValue(),maxCartDiscount:this.getMaxCartDiscount(),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}};var n=class a{price;country;constructor(t,e){if(this.country=e,t<0)throw new Error("InvalidPrice: Price cannot be negative.");this.price=t;}getCountry(){return this.country}getRoundedPrice(){return a.getRoundedPrice(this.price,this.country)}getFormattedString(t){return a.getFormattedString(this.price,this.country,t)}static getFormattedString(t,e,i,r={}){let s=r.displayAsInteger??!1,u=y[e];if(u===void 0)throw new Error("Currency mapping not found for CountryCode");let d=t,g=s?0:a.getDecimalPlaces(u),f={style:r.style??"currency",currency:u,signDisplay:"never",currencyDisplay:r.currencyDisplay,minimumFractionDigits:g,maximumFractionDigits:g};s&&(d=Math.round(d));try{return new Intl.NumberFormat(i,f).format(d)}catch(o){return console.error(`Error formatting price for country "${e}" and currency "${u}":`,o),`${S[u]??u} ${a.addThousandSeparators(d.toFixed(g))}`}}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 getRoundedPrice(t,e){if(t<0)throw new Error("Price cannot be negative for rounding.");let i=y[e];if(i===void 0)throw new Error(`Currency mapping not found for CountryCode: ${e}`);let r=a.getDecimalPlaces(i),s=Math.pow(10,r);return Math.round(t*s)/s}static getCurrency(t){return y[t]}};var p=class extends l{id;firstName;lastName;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.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(),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}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 I=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 "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 "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 C=class{id;productKey;variantId;name;attributes;specifications;primaryImage;subItems;totalQuantity;basePrice;priceTotals;priceTiers;constructor(t){this.id=t.id,this.productKey=t.productKey,this.variantId=t.variantId,this.name={...t.name},this.attributes={...t.attributes},this.specifications={...t.specifications},this.primaryImage=new I(t.primaryImage),this.subItems=t.subItems.map(e=>({...e})),this.basePrice={...t.basePrice},this.priceTiers=t.priceTiers.map(e=>({...e})),this.totalQuantity=0,this.priceTotals={subtotal:0,mrpTotal:0},this.recalculateTotalQuantity(),this.recalculatePriceTotal();}getId(){return this.id}getProductKey(){return this.productKey}getVariantId(){return this.variantId}getName(t){return t?this.name[t]??this.name[h[t]]??this.name.en:{...this.name}}getAttributes(){return {...this.attributes}}getSpecifications(t){return t?this.specifications[t]??this.specifications[h[t]]??this.specifications.en:JSON.parse(JSON.stringify(this.specifications))}getImage(){return this.primaryImage}getSubItems(){return this.subItems.map(t=>({...t}))}getTotalQuantity(){return this.totalQuantity}getBasePrice(){return {...this.basePrice}}getPriceTotals(){return {...this.priceTotals}}getPriceTiers(){return this.priceTiers.map(t=>({...t}))}recalculateTotalQuantity(){this.totalQuantity=this.subItems.reduce((t,e)=>t+e.quantity,0);}recalculatePriceTotal(){let t=this.totalQuantity,e=this.basePrice.unitPrice,i=null;for(let r of this.priceTiers.sort((s,u)=>u.minQuantity-s.minQuantity))if(t>=r.minQuantity){i=r;break}i&&(e=i.unitPrice),this.priceTotals.mrpTotal=this.basePrice.unitPrice*t,this.priceTotals.subtotal=e*t;}getDetails(){return {id:this.getId(),productKey:this.getProductKey(),variantId:this.getVariantId(),name:this.getName(),attributes:this.getAttributes(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),totalQuantity:this.getTotalQuantity(),basePrice:this.getBasePrice(),priceTotals:this.getPriceTotals(),priceTiers:this.getPriceTiers()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(s=>s.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity),this.recalculateTotalQuantity(),this.recalculatePriceTotal();}clearLineItem(){this.id="",this.productKey="",this.variantId="",this.name={en:""},this.attributes={color:{name:"",hex:""}},this.primaryImage=new I({sources:{original:""}}),this.subItems=[],this.recalculateTotalQuantity(),this.recalculatePriceTotal();}};var b=class extends l{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 C(i)),this.billingAddress=t.billingAddress?new p(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new p(t.shippingAddress,e):null,this.coupons=(t.coupons||[]).map(i=>new m(i)),this.shippingDetails=t.shippingDetails?{...t.shippingDetails}:null,this.total={shipping:t.total?.shipping||0,effectiveShipping:t.total?.effectiveShipping??t.total?.shipping??0,subtotal:t.total?.subtotal||0,mrpTotal:t.total?.mrpTotal||0,couponTotal:t.total?.couponTotal||{},grandTotal:t.total?.grandTotal||0};}recalculateBaseTotals(){this.total.subtotal=n.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=n.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().mrpTotal,0),this.country);}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new C(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new p(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new p(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons.map(t=>new m(t.getDetails()))}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {...this.total,couponTotal:{...this.total.couponTotal}}}calculateApplicableCouponDiscount(t,e=!0){if(e&&!t.isActive())return 0;let i=t.getMinCartValue(this.country),r=t.getMaxCartDiscount(this.country);if(!i||this.total.subtotal<i.price||!r||r.price<0)return 0;let s=t.getCategory(),u=t.getDiscountMethod(),d=0,g=s==="SHIPPING"?this.total.shipping:this.total.subtotal;if(g<=0)return 0;switch(u){case"flat":let o=r?.price??0;d=Math.min(g,o);break;case"percentage":d=g*(t.getPercentageValue()/100);break;default:return 0}let f=Math.min(d,r.price);return n.getRoundedPrice(Math.max(0,f),this.country)}recalculateCouponTotals(t=!0){this.total.couponTotal={};let e=0;return this.coupons.forEach(i=>{let r=this.calculateApplicableCouponDiscount(i,t);r>0&&(this.total.couponTotal[i.getCode()]=r,e+=r);}),n.getRoundedPrice(e,this.country)}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:this.getTotal(),country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}};var A=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}};var L=(s=>(s.PLACED="PLACED",s.PENDING_PAYMENT="PENDING_PAYMENT",s.PROCESSING="PROCESSING",s.CANCELLED="CANCELLED",s.COMPLETED="COMPLETED",s))(L||{}),P=(o=>(o.INITIAL="INITIAL",o.PROCESSING="PROCESSING",o.SHIPPED="SHIPPED",o.DELIVERED="DELIVERED",o.CANCELLED="CANCELLED",o.RETURN_REQUESTED="RETURN_REQUESTED",o.RETURNED="RETURNED",o.REFUND_INITIATED="REFUND_INITIATED",o.REFUNDED="REFUNDED",o.ON_HOLD="ON_HOLD",o))(P||{}),D=class extends b{orderNumber;cartId;paymentStatus;holdReason;state;lineItemStateMap;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;let i={};t.lineItems.forEach(r=>{let s=t.lineItemStateMap?.[r.id];i[r.id]={state:s?.state||"INITIAL",reason:s?.reason||"",transitionAt:s?.transitionAt||this.createdAt};}),this.lineItemStateMap=i,this.recalculateOrderBaseTotals();}recalculateOrderBaseTotals(){let t=this.lineItems.filter(e=>this.lineItemStateMap[e.getId()]?.state!=="CANCELLED");this.total.subtotal=n.getRoundedPrice(t.reduce((e,i)=>e+i.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=n.getRoundedPrice(t.reduce((e,i)=>e+i.getPriceTotals().mrpTotal,0),this.country);}updateOrderTotals(){this.recalculateOrderBaseTotals(),this.recalculateCouponTotals(!1);let t=this.coupons.filter(r=>r.getCategory()==="SHIPPING").reduce((r,s)=>r+(this.total.couponTotal[s.getCode()]??0),0);this.total.effectiveShipping=n.getRoundedPrice(Math.max(0,this.total.shipping-t),this.country);let e=this.coupons.filter(r=>r.getCategory()!=="SHIPPING").reduce((r,s)=>r+(this.total.couponTotal[s.getCode()]??0),0),i=this.total.subtotal+this.total.effectiveShipping;this.total.grandTotal=n.getRoundedPrice(Math.max(0,i-e),this.country);}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}getLineItemsStateMap(){return {...this.lineItemStateMap}}getLineItemState(t){if(!this.lineItemStateMap[t])throw new A(t);return this.lineItemStateMap[t].state}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(),lineItemStateMap:this.getLineItemsStateMap()}}};exports.OrderLineItemState=P;exports.OrderState=L;exports.default=D;//# sourceMappingURL=Order.js.map
|
|
2
2
|
//# sourceMappingURL=Order.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/Classes/Base.ts","../../src/Classes/Enum.ts","../../src/Classes/Coupon.ts","../../src/Classes/Price.ts","../../src/Classes/Address.ts","../../src/Classes/ImageInfo.ts","../../src/Classes/LineItem.ts","../../src/Classes/ShoppingContainer.ts","../../src/Classes/Cart.ts","../../src/Classes/Order.ts"],"names":["BaseModel","data","date","id","authType","requestId","lambdaName","fieldName","value","LocaleLanguageMap","CountryCurrencyMap","CurrencySymbolMap","CouponModel","price","locale","country","ftbCustomer","PriceModel","_PriceModel","options","displayAsInteger","currency","valueToFormat","fractionDigits","formattingOptions","error","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier","AddressModel","addressType","ImageInfoModel","resolutionKey","altText","order","label","url","LineItemModel","item","tier","sum","quantity","unitPrice","applicableTier","a","b","subItems","addQuantity","subItem","existingSubItem","sub","BaseShoppingContainerModel","coupon","checkExpiry","minCartValueReq","maxCartDiscountCap","couponCategory","discountMethod","potentialDiscount","targetValue","flatAmount","finalDiscount","totalDiscount","discount","LineItemNotFoundError","lineItemId","OrderState","OrderLineItemState","OrderModel","newLineItemStateMap","currentStateMap","shippingCouponDiscount","c","nonShippingCouponDiscount","grossTotal"],"mappings":"sEA4BA,IAAqBA,EAArB,KAA+B,CACnB,YACA,CAAA,OAAA,CACA,UACA,UACA,CAAA,UAAA,CAQV,WAAYC,CAAAA,CAAAA,CAAsBC,EAAa,IAAI,IAAA,CAAQ,CACzD,IAAK,CAAA,YAAA,CAAe,CAAE,GAAGD,CAAAA,CAAK,YAAa,CAAA,CAC3C,KAAK,OAAUA,CAAAA,CAAAA,CAAK,SAAW,CAC/B,CAAA,IAAA,CAAK,UAAYA,CAAK,CAAA,SAAA,EAAa,CAAC,KAAA,CAAM,KAAK,KAAMA,CAAAA,CAAAA,CAAK,SAAS,CAAC,CAAA,CAElE,IAAI,IAAKA,CAAAA,CAAAA,CAAK,SAAS,CAAA,CAAE,aAEzBC,CAAAA,CAAAA,CAAK,aACP,CAAA,IAAA,CAAK,WAAaD,CAAK,CAAA,UAAA,EAAc,CAAC,KAAA,CAAM,KAAK,KAAMA,CAAAA,CAAAA,CAAK,UAAU,CAAC,CAAA,CACnE,IAAI,IAAKA,CAAAA,CAAAA,CAAK,UAAU,CAAA,CAAE,aAC1BC,CAAAA,CAAAA,CAAK,aAET,CAAA,IAAA,CAAK,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,CAAU,CAE5C,CAAA,OAAO,KAAK,gBAAiBA,CAAAA,CAAU,EAAE,KAC3C,CAOA,UAAwB,EAAA,CACtB,OAAO,CACL,GAAG,MAAM,UAAW,EAAA,CACpB,YAAa,IAAK,CAAA,cAAA,EAClB,CAAA,UAAA,CAAY,KAAK,aAAc,EAAA,CAC/B,cAAe,IAAK,CAAA,gBAAA,GACpB,eAAiB,CAAA,IAAA,CAAK,kBAAmB,EAAA,CAAE,YAC3C,CAAA,cAAA,CAAgB,KAAK,iBAAkB,EAAA,CAAE,YACzC,CAAA,MAAA,CAAQ,IAAK,CAAA,SAAA,GACb,aAAe,CAAA,IAAA,CAAK,kBACpB,CAAA,UAAA,CAAY,KAAK,aAAc,EAAA,CAC/B,KAAO,CAAA,IAAA,CAAK,UACZ,CAAA,gBAAA,CAAkB,KAAK,oBAAqB,EAC9C,CACF,CACF","file":"Order.js","sourcesContent":["import { AuthType } from \"../Auth\";\r\nimport { ISODateTime } from \"./Common\";\r\n\r\nexport interface CustomFields {\r\n [key: string]: any;\r\n}\r\n\r\nexport type ModifiedBy = {\r\n id?: string;\r\n authType?: string;\r\n requestId?: string;\r\n lambdaName?: string;\r\n}\r\n\r\nexport type BaseAttributes = {\r\n customFields?: CustomFields;\r\n version?: number;\r\n createdAt?: ISODateTime;\r\n modifiedAt?: ISODateTime;\r\n modifiedBy?: ModifiedBy;\r\n};\r\n\r\nexport type BaseData = Required<BaseAttributes>;\r\n\r\n/**\r\n * Provides common foundational properties and methods for other data models.\r\n * Handles tracking of custom fields, versioning, and timestamps.\r\n */\r\nexport default class BaseModel {\r\n protected customFields: CustomFields;\r\n protected version: number;\r\n protected createdAt: ISODateTime;\r\n protected modifiedAt: ISODateTime;\r\n protected modifiedBy: ModifiedBy;\r\n\r\n /**\r\n * Creates an instance of BaseModel.\r\n * Initializes common properties like timestamps, version, and custom fields.\r\n * @param data - Optional initial attributes for the base model.\r\n * @param date - Optional date object to use for default timestamps (defaults to current time).\r\n */\r\n constructor(data: BaseAttributes, date: Date = new Date()) {\r\n this.customFields = { ...data.customFields };\r\n this.version = data.version ?? 1;\r\n this.createdAt = data.createdAt && !isNaN(Date.parse(data.createdAt))\r\n ?\r\n new Date(data.createdAt).toISOString()\r\n :\r\n date.toISOString();\r\n this.modifiedAt = data.modifiedAt && !isNaN(Date.parse(data.modifiedAt))\r\n ? new Date(data.modifiedAt).toISOString()\r\n : date.toISOString();\r\n\r\n this.modifiedBy = { ...data.modifiedBy };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the base model's current state.\r\n * @returns BaseData object containing common properties.\r\n */\r\n getDetails(): BaseData {\r\n return {\r\n customFields: this.getAllCustomFields(), // Use getter to return a copy\r\n version: this.getVersion(),\r\n createdAt: this.getCreatedAt(),\r\n modifiedAt: this.getModifiedAt(),\r\n modifiedBy: this.getModifiedBy(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the current version number of the model instance.\r\n * @returns The version number.\r\n */\r\n getVersion(): number {\r\n return this.version;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as an ISO 8601 string.\r\n * @returns The creation timestamp string.\r\n */\r\n getCreatedAt(): string {\r\n return this.createdAt;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as a Unix epoch time (milliseconds).\r\n * @returns The creation time in milliseconds since the epoch.\r\n */\r\n getCreatedAtTime(): number {\r\n return new Date(this.createdAt).getTime();\r\n }\r\n\r\n\r\n /**\r\n * Gets the last modification timestamp as an ISO 8601 string.\r\n * @returns The last modification timestamp string.\r\n */\r\n getModifiedAt(): string {\r\n return this.modifiedAt;\r\n }\r\n\r\n /**\r\n * Gets the last modification timestamp as a Unix epoch time (milliseconds).\r\n * @returns The last modification time in milliseconds since the epoch.\r\n */\r\n getModifiedAtTime(): number {\r\n return new Date(this.modifiedAt).getTime();\r\n }\r\n\r\n /**\r\n * Gets the identifier of the user or process that last modified the instance.\r\n * @returns\r\n */\r\n getModifiedBy(): ModifiedBy {\r\n return { ...this.modifiedBy };\r\n }\r\n\r\n /**\r\n * Sets the identifier of the user or process that last modified the instance.\r\n * @param modifiedBy - The identifier string.\r\n */\r\n setModifiedBy(id?: string, authType?: AuthType, requestId?: string, lambdaName?: string): void {\r\n this.modifiedBy = {\r\n id,\r\n authType,\r\n requestId,\r\n lambdaName,\r\n };\r\n }\r\n\r\n /**\r\n * Retrieves the value of a specific custom field.\r\n * @param fieldName - The name (key) of the custom field to retrieve.\r\n * @returns The value of the custom field, or null if the field does not exist.\r\n */\r\n getCustomField(fieldName: string): any {\r\n return this.customFields[fieldName] ?? null;\r\n }\r\n\r\n /**\r\n * Sets the value of a specific custom field.\r\n * Also updates the modification timestamp and increments the version.\r\n * @param fieldName - The name (key) of the custom field to set.\r\n * @param value - The value to assign to the custom field.\r\n */\r\n setCustomField(fieldName: string, value: any): void {\r\n this.customFields[fieldName] = value;\r\n }\r\n\r\n /**\r\n * Retrieves a shallow copy of all custom fields associated with the instance.\r\n * @returns An object containing all custom fields.\r\n */\r\n getAllCustomFields(): CustomFields {\r\n return { ...this.customFields };\r\n }\r\n}\r\n","/**\r\n * Represents the countries where the application operates or products are available.\r\n */\r\nexport enum OperationalCountry {\r\n /** India */ IN = 'IN',\r\n}\r\n \r\nexport enum OperationalCountryCurrency {\r\n /** India */ INR = 'INR',\r\n}\r\n\r\nexport enum OperationalLocale {\r\n /** India */ 'en-IN' = 'en-IN',\r\n /** India ( Kannada) */ 'kn-IN' = 'kn-IN'\r\n}\r\n\r\nexport enum OperationalLanguage {\r\n en = 'en',\r\n kn = 'kn'\r\n}\r\n\r\nexport const LocaleLanguageMap: Record<OperationalLocale, OperationalLanguage> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalLanguage.en,\r\n [OperationalLocale[\"kn-IN\"]]: OperationalLanguage.kn,\r\n}\r\n\r\nexport const LocaleCountryMap: Record<OperationalLocale, OperationalCountry> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalCountry.IN,\r\n [OperationalLocale[\"kn-IN\"]]: OperationalCountry.IN,\r\n}\r\n\r\n/**\r\n * Defines the supported ISO 4217 currency codes as an enumeration.\r\n */\r\nexport const CountryCurrencyMap = {\r\n /** India */ [OperationalCountry.IN]: OperationalCountryCurrency.INR,\r\n};\r\n\r\nexport const CurrencySymbolMap = {\r\n [OperationalCountryCurrency.INR]: '₹',\r\n}\r\n\r\n/**\r\n * Defines standard gender categories for product targeting.\r\n */\r\nexport enum GenderCategory {\r\n MALE = 'Male',\r\n FEMALE = 'Female',\r\n UNISEX = 'Unisex',\r\n KIDS = 'Kids',\r\n BOY = 'Boy',\r\n GIRL = 'Girl',\r\n}","import BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, ISODateTime, LocaleCode, LocalizedString, RegionalPrice, RegionalPriceList } from \"./Common\";\r\nimport { LocaleLanguageMap } from \"./Enum\";\r\n\r\nexport enum CouponType {\r\n COUPON = \"coupon\",\r\n AUTOMATIC = \"automatic\",\r\n}\r\n\r\nexport enum CouponDiscountMethod {\r\n FLAT = \"flat\",\r\n PERCENTAGE = \"percentage\",\r\n}\r\n\r\nexport enum CouponCategory {\r\n SHIPPING = \"SHIPPING\",\r\n CUSTOMER = \"CUSTOMER\",\r\n}\r\n\r\nexport enum ApplicableTo {\r\n ALL = \"all\",\r\n FTB = \"ftb\",\r\n}\r\n\r\nexport type CouponAttribute = BaseAttributes & {\r\n couponCode: string;\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n type: CouponType;\r\n customerId?: string;\r\n validFrom: ISODateTime;\r\n validTo: ISODateTime;\r\n minCartValue: RegionalPriceList;\r\n maxCartDiscount: RegionalPriceList;\r\n discountMethod: CouponDiscountMethod;\r\n percentageValue?: number;\r\n applicableTo: ApplicableTo;\r\n category: CouponCategory;\r\n};\r\n\r\nexport type CouponData = Required<CouponAttribute>\r\n\r\n/**\r\n * Represents a discount coupon, extending BaseModel.\r\n */\r\nexport default class CouponModel extends BaseModel {\r\n protected couponCode: string;\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected type: CouponType;\r\n protected customerId?: string;\r\n protected validFrom: ISODateTime;\r\n protected validTo: ISODateTime;\r\n protected minCartValue: RegionalPriceList;\r\n protected maxCartDiscount: RegionalPriceList;\r\n protected discountMethod: CouponDiscountMethod;\r\n protected percentageValue: number;\r\n protected applicableTo: ApplicableTo;\r\n protected category: CouponCategory;\r\n\r\n /**\r\n * Creates an instance of CouponModel.\r\n * @param data - The initial coupon attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: CouponAttribute, date: Date = new Date()) {\r\n super(data, date);\r\n\r\n this.couponCode = data.couponCode;\r\n this.name = { ...data.name };\r\n this.description = { ...data.description };\r\n this.type = data.type;\r\n this.customerId = data.customerId;\r\n this.validFrom = data.validFrom && Date.parse(data.validFrom) ? new Date(data.validFrom).toISOString() : date.toISOString();\r\n this.validTo = data.validTo && Date.parse(data.validTo) ? new Date(data.validTo).toISOString() : date.toISOString();\r\n this.minCartValue = data.minCartValue.map(price => ({ ...price }));\r\n this.maxCartDiscount = data.maxCartDiscount.map(price => ({ ...price }));\r\n this.discountMethod = data.discountMethod;\r\n this.percentageValue = data.percentageValue ?? 0;\r\n this.applicableTo = data.applicableTo;\r\n this.category = data.category;\r\n }\r\n\r\n /** Gets the unique coupon code. */\r\n getCode(): string {\r\n return this.couponCode;\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the coupon name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon description object.\r\n * @returns A copy of the LocalizedString object for the description, or undefined.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the coupon description for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The description string for the specified locale.\r\n */\r\n getDescription(locale: LocaleCode): string\r\n getDescription(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.description[locale] ?? this.description[LocaleLanguageMap[locale]] ?? this.description.en;\r\n } else {\r\n return { ...this.description };\r\n }\r\n }\r\n\r\n /** Gets the type of coupon (COUPON or AUTOMATIC). */\r\n getType(): CouponType {\r\n return this.type;\r\n }\r\n\r\n /** Gets the specific customer ID this coupon is limited to, if any. */\r\n getCustomerId(): string {\r\n return this.customerId ?? '';\r\n }\r\n\r\n /** Gets the ISO date string from when the coupon is valid. */\r\n getValidFrom(): ISODateTime {\r\n return this.validFrom;\r\n }\r\n\r\n /** Gets the ISO date string until when the coupon is valid. */\r\n getValidTo(): ISODateTime {\r\n return this.validTo;\r\n }\r\n\r\n /**\r\n * Gets the list of minimum cart values required for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional minimum cart values.\r\n */\r\n getMinCartValue(): RegionalPriceList\r\n /**\r\n * Gets the minimum cart value required for the coupon for a specific country.\r\n * @param country - The country code to filter the minimum value for.\r\n * @returns The regional minimum cart value for the specified country, or undefined if not set for that country.\r\n */\r\n getMinCartValue(country: CountryCode): RegionalPrice | undefined\r\n getMinCartValue(country?: CountryCode){\r\n if(country) {\r\n return this.minCartValue.find(price => price.country === country);\r\n }\r\n return this.minCartValue;\r\n }\r\n\r\n /**\r\n * Gets the list of maximum discount amounts allowed for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional maximum discount caps.\r\n */\r\n getMaxCartDiscount(): RegionalPriceList\r\n /**\r\n * Gets the maximum discount amount allowed for the coupon for a specific country.\r\n * @param country - The country code to filter the maximum discount for.\r\n * @returns The regional maximum discount cap for the specified country, or undefined if not set for that country.\r\n */\r\n getMaxCartDiscount(country: CountryCode): RegionalPrice | undefined\r\n getMaxCartDiscount(country?: CountryCode){\r\n if(country) {\r\n return this.maxCartDiscount.find(price => price.country === country);\r\n }\r\n return this.maxCartDiscount;\r\n }\r\n\r\n /** Gets the discount method (FLAT or PERCENTAGE). */\r\n getDiscountMethod(): CouponDiscountMethod {\r\n return this.discountMethod;\r\n }\r\n\r\n /** Gets the percentage discount value (0-100). */\r\n getPercentageValue(): number {\r\n return this.percentageValue;\r\n }\r\n\r\n /** Gets the customer applicability rule (ALL or FTB). */\r\n getApplicableTo(): ApplicableTo {\r\n return this.applicableTo;\r\n }\r\n\r\n /** Gets the category of the coupon (SHIPPING or CUSTOMER). */\r\n getCategory(): CouponCategory {\r\n return this.category;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the coupon's details.\r\n * @returns A CouponData object.\r\n */\r\n getDetails(): CouponData {\r\n return {\r\n ...super.getDetails(),\r\n couponCode: this.getCode(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n type: this.getType(),\r\n customerId: this.getCustomerId(),\r\n validFrom: this.getValidFrom(),\r\n validTo: this.getValidTo(),\r\n minCartValue: this.getMinCartValue(),\r\n maxCartDiscount: this.getMaxCartDiscount(),\r\n discountMethod: this.getDiscountMethod(),\r\n percentageValue: this.getPercentageValue(),\r\n applicableTo: this.getApplicableTo(),\r\n category: this.getCategory(),\r\n };\r\n }\r\n\r\n /**\r\n * Checks if the coupon is currently active based on its validity dates.\r\n * @returns True if the coupon is currently within its validity period, false otherwise.\r\n */\r\n isActive(): boolean {\r\n return new Date(this.validFrom) <= new Date() && new Date(this.validTo) >= new Date();\r\n }\r\n\r\n \r\n /**\r\n * Checks if the coupon is applicable to a customer based on their status (e.g., first-time buyer).\r\n * @param ftbCustomer - A boolean indicating whether the customer is a first-time buyer.\r\n * @returns True if the coupon's applicability rule matches the customer's status, false otherwise.\r\n */\r\n isApplicableTo(ftbCustomer: boolean): boolean {\r\n return this.applicableTo === ApplicableTo.ALL || (this.applicableTo === ApplicableTo.FTB && ftbCustomer);\r\n }\r\n}","import { CountryCode, CurrencyCode, LocaleCode } from \"./Common\"; // Assuming these are in Common.ts\r\nimport { CountryCurrencyMap, CurrencySymbolMap } from \"./Enum\"; // Ensure these maps exist\r\n\r\nexport default class PriceModel {\r\n protected price: number;\r\n protected country: CountryCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param price - The initial price value.\r\n * @param country - The country code used for rounding and determining the currency symbol.\r\n * @throws {Error} If price is negative or country/currency mapping is missing.\r\n */\r\n constructor(price: number, country: CountryCode) {\r\n this.country = country;\r\n\r\n if(price < 0) {\r\n throw new Error(\"InvalidPrice: Price cannot be negative.\");\r\n }\r\n\r\n this.price = price\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this price instance.\r\n * The country code is used for determining currency and formatting rules.\r\n * @returns The CountryCode enum value.\r\n */\r\n public getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Gets the rounded price value based on standard currency rules.\r\n * @returns The numeric price, rounded according to its currency's typical decimal places.\r\n */\r\n public getRoundedPrice(): number {\r\n return PriceModel.getRoundedPrice(this.price, this.country);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price stored in this instance.\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @param locale - The locale code (e.g., 'en-IN') to use for formatting rules.\r\n * @returns The formatted price string according to locale rules.\r\n * @throws {Error} If the currency mapping for the instance's country is not found (via the static method).\r\n */\r\n public getFormattedString(locale: LocaleCode){\r\n return PriceModel.getFormattedString(this.price, this.country, locale);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param price - The initial price value.\r\n * @param country - The country code used for rounding and determining the currency symbol.\r\n * @param locale - The locale code (e.g., 'en-IN') to use for formatting rules.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the price rounded to the nearest integer (no decimals). Defaults to false.\r\n * @param options.style - The style of formatting, either 'currency' or 'decimal'. Defaults to 'currency'.\r\n * @param options.currencyDisplay - The display format for the currency symbol. Options are 'symbol', 'narrowSymbol', 'code', or 'name'. Defaults to 'symbol'.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n static getFormattedString(price: number, country: CountryCode, locale?: LocaleCode, options: { displayAsInteger?: boolean, style?: 'currency' | 'decimal', currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name' } = {}): string {\r\n const displayAsInteger = options.displayAsInteger ?? false;\r\n const currency: CurrencyCode | undefined = CountryCurrencyMap[country];\r\n\r\n if (currency === undefined) {\r\n throw new Error('Currency mapping not found for CountryCode');\r\n }\r\n\r\n let valueToFormat = price;\r\n const fractionDigits = displayAsInteger ? 0 : PriceModel.getDecimalPlaces(currency);\r\n\r\n let formattingOptions: Intl.NumberFormatOptions = {\r\n style: options.style ?? 'currency',\r\n currency: currency,\r\n signDisplay: 'never',\r\n currencyDisplay: options.currencyDisplay,\r\n minimumFractionDigits: fractionDigits,\r\n maximumFractionDigits: fractionDigits,\r\n };\r\n\r\n if (displayAsInteger) {\r\n valueToFormat = Math.round(valueToFormat);\r\n }\r\n\r\n try {\r\n return new Intl.NumberFormat(locale, formattingOptions).format(valueToFormat);\r\n } catch (error) {\r\n console.error(`Error formatting price for country \"${country}\" and currency \"${currency}\":`, error);\r\n // Basic fallback without symbol if Intl fails completely\r\n return `${CurrencySymbolMap[currency] ?? currency} ${PriceModel.addThousandSeparators(valueToFormat.toFixed(fractionDigits))}`;\r\n }\r\n }\r\n\r\n /**\r\n * Helper method to determine standard decimal places for a currency.\r\n * @param currency - The currency code.\r\n * @returns The number of decimal places (0, 2, or 3 based on common rules).\r\n */\r\n private static getDecimalPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case 'INR':\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n /**\r\n * Adds basic thousand separators (commas) to a number string.\r\n * Does not handle different locale separators (e.g., periods, spaces).\r\n * @param numStr - The number string (potentially with decimals).\r\n * @returns The number string with commas added.\r\n */\r\n private static addThousandSeparators(numStr: string): string {\r\n const parts = numStr.split('.');\r\n const integerPart = parts[0];\r\n const decimalPart = parts.length > 1 ? '.' + parts[1] : '';\r\n\r\n const formattedInteger = integerPart.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\r\n return formattedInteger + decimalPart;\r\n }\r\n\r\n /**\r\n * Rounds a price value according to the standard decimal places\r\n * for the currency associated with the given country.\r\n *\r\n * @param price - The price value to round. Must be a non-negative number.\r\n * @param country - The country code to determine the currency and rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the country code is not found in the CountryCurrencyMap or price is negative.\r\n */\r\n static getRoundedPrice(price: number, country: CountryCode): number {\r\n if (price < 0) {\r\n throw new Error(\"Price cannot be negative for rounding.\");\r\n }\r\n\r\n const currency: CurrencyCode | undefined = CountryCurrencyMap[country];\r\n if (currency === undefined) {\r\n throw new Error(`Currency mapping not found for CountryCode: ${country}`);\r\n }\r\n\r\n const decimalPlaces = PriceModel.getDecimalPlaces(currency);\r\n const multiplier = Math.pow(10, decimalPlaces);\r\n const roundedValue = Math.round(price * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n\r\n /**\r\n * Static method to retrieve the currency code associated with a given country code.\r\n * Uses the `CountryCurrencyMap` to find the corresponding currency.\r\n *\r\n * @param country - The country code (e.g., 'IN') for which to find the currency.\r\n * @returns The currency code (e.g., 'INR') as a string, or undefined if the mapping doesn't exist.\r\n */\r\n static getCurrency(country: CountryCode): string {\r\n return CountryCurrencyMap[country];\r\n }\r\n\r\n}","import BaseModel, { BaseAttributes } from \"./Base\";\r\n\r\nexport enum AddressType {\r\n BILLING = \"billing\",\r\n SHIPPING = \"shipping\",\r\n BILLING_AND_SHIPPING = \"billing&shipping\",\r\n NONE = \"none\",\r\n}\r\n\r\nexport type AddressAttributes = BaseAttributes & {\r\n id: string;\r\n firstName: string;\r\n lastName?: string;\r\n phone: string;\r\n email: string;\r\n addressLine1: string;\r\n addressLine2?: string;\r\n city: string;\r\n postalCode: string\r\n state: string;\r\n country: string;\r\n isBillingAddress: boolean;\r\n isShippingAddress: boolean;\r\n};\r\n\r\nexport type AddressData = Required<AddressAttributes>;\r\n\r\n/**\r\n * Represents a physical address associated with a customer or order.\r\n * Handles both billing and shipping address types.\r\n */\r\nexport default class AddressModel extends BaseModel {\r\n protected id: string;\r\n protected firstName: string;\r\n protected lastName: string;\r\n protected phone: string;\r\n protected email: string;\r\n protected addressLine1: string;\r\n protected addressLine2: string;\r\n protected city: string;\r\n protected postalCode: string\r\n protected state: string;\r\n protected country: string;\r\n protected isBillingAddress: boolean;\r\n protected isShippingAddress: boolean;\r\n\r\n /**\r\n * Creates an instance of AddressModel.\r\n * @param data - The initial address attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: AddressAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.firstName = data.firstName;\r\n this.lastName = data.lastName || '';\r\n this.phone = data.phone;\r\n this.email = data.email;\r\n this.addressLine1 = data.addressLine1;\r\n this.addressLine2 = data.addressLine2 || '';\r\n this.city = data.city;\r\n this.postalCode = data.postalCode;\r\n this.state = data.state;\r\n this.country = data.country;\r\n this.isBillingAddress = data.isBillingAddress;\r\n this.isShippingAddress = data.isShippingAddress;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the address's current state.\r\n * Includes all address fields and base model fields.\r\n * @returns AddressData object suitable for serialization or API responses.\r\n */\r\n getDetails(): AddressData {\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n firstName: this.getFirstName(),\r\n lastName: this.getLastName(),\r\n phone: this.getPhone(),\r\n email: this.getEmail(),\r\n addressLine1: this.getAddressLine1(),\r\n addressLine2: this.getAddressLine2(),\r\n city: this.getCity(),\r\n postalCode: this.getPostalCode(),\r\n state: this.getState(),\r\n country: this.getCountry(),\r\n isBillingAddress: this.getIsBillingAddress(),\r\n isShippingAddress: this.getIsShippingAddress(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for the address.\r\n * @returns The address ID.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the first name associated with the address.\r\n * @returns The first name.\r\n */\r\n getFirstName(): string {\r\n return this.firstName;\r\n }\r\n\r\n /**\r\n * Gets the last name associated with the address.\r\n * @returns The last name.\r\n */\r\n getLastName(): string {\r\n return this.lastName;\r\n }\r\n\r\n /**\r\n * Gets the phone number associated with the address.\r\n * @returns The phone number.\r\n */\r\n getPhone(): string {\r\n return this.phone;\r\n }\r\n\r\n /**\r\n * Gets the email address associated with the address.\r\n * @returns The email address.\r\n */\r\n getEmail(): string {\r\n return this.email;\r\n }\r\n\r\n /**\r\n * Gets the primary address line (e.g., street address).\r\n * @returns The first address line.\r\n */\r\n getAddressLine1(): string {\r\n return this.addressLine1;\r\n }\r\n\r\n /**\r\n * Gets the secondary address line (e.g., apartment, suite).\r\n * Returns an empty string if not provided.\r\n * @returns The second address line or an empty string.\r\n */\r\n getAddressLine2(): string {\r\n return this.addressLine2;\r\n }\r\n\r\n /**\r\n * Gets the city name.\r\n * @returns The city.\r\n */\r\n getCity(): string {\r\n return this.city;\r\n }\r\n\r\n /**\r\n * Gets the postal code (e.g., ZIP code).\r\n * @returns The postal code.\r\n */\r\n getPostalCode(): string {\r\n return this.postalCode;\r\n }\r\n\r\n /**\r\n * Gets the state, province, or region.\r\n * @returns The state.\r\n */\r\n getState(): string {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the country name or code.\r\n * @returns The country.\r\n */\r\n getCountry(): string {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Checks if this address is designated as a billing address.\r\n * @returns True if it's a billing address, false otherwise.\r\n */\r\n getIsBillingAddress(): boolean {\r\n return this.isBillingAddress;\r\n }\r\n\r\n /**\r\n * Checks if this address is designated as a shipping address.\r\n * @returns True if it's a shipping address, false otherwise.\r\n */\r\n getIsShippingAddress(): boolean {\r\n return this.isShippingAddress;\r\n }\r\n\r\n /**\r\n * Determines the type of the address based on its billing and shipping flags.\r\n * @returns The AddressType enum value representing the address's role.\r\n */\r\n getAddressType(): AddressType {\r\n if (this.isBillingAddress && this.isShippingAddress) {\r\n return AddressType.BILLING_AND_SHIPPING;\r\n } else if (this.isBillingAddress) {\r\n return AddressType.BILLING;\r\n } else if (this.isShippingAddress) {\r\n return AddressType.SHIPPING;\r\n } else {\r\n return AddressType.NONE;\r\n }\r\n }\r\n\r\n /**\r\n * Static method to check if a given AddressType includes shipping.\r\n * @param addressType - The address type to check.\r\n * @returns True if the type is SHIPPING or BILLING_AND_SHIPPING.\r\n */\r\n static checkIfShippingAddress(addressType: AddressType): boolean {\r\n return addressType === AddressType.SHIPPING || addressType === AddressType.BILLING_AND_SHIPPING;\r\n }\r\n\r\n /**\r\n * Static method to check if a given AddressType includes billing.\r\n * @param addressType - The address type to check.\r\n * @returns True if the type is BILLING or BILLING_AND_SHIPPING.\r\n */\r\n static checkIfBillingAddress(addressType: AddressType): boolean {\r\n return addressType === AddressType.BILLING || addressType === AddressType.BILLING_AND_SHIPPING;\r\n }\r\n}","export enum ImageResolution {\r\n THUMBNAIL = 'thumbnail',\r\n SMALL = 'small',\r\n MEDIUM = 'medium',\r\n LARGE = 'large',\r\n ORIGINAL = 'original',\r\n}\r\n\r\nexport type ImageInfoAttribute = {\r\n sources: { [key in ImageResolution]?: string } & { original: string };\r\n alt?: string;\r\n order?: number;\r\n label?: string;\r\n};\r\n\r\nexport type ImageInfoData = ImageInfoAttribute;\r\n\r\n/**\r\n * Represents and manages structured image data, including multiple resolutions.\r\n */\r\nexport default class ImageInfoModel {\r\n protected sources: { [key in ImageResolution]?: string } & { original: string };\r\n protected alt?: string;\r\n protected order?: number;\r\n protected label?: string;\r\n\r\n /**\r\n * Creates an instance of ImageInfoModel.\r\n * @param data - The initial image data.\r\n */\r\n constructor(data: ImageInfoAttribute) {\r\n this.sources = { ...data.sources };\r\n this.alt = data.alt;\r\n this.order = data.order;\r\n this.label = data.label;\r\n\r\n if (!this.sources.original) {\r\n throw (\"ImageInfoModel cannot be created without an 'original' source URL.\");\r\n }\r\n }\r\n\r\n /**\r\n * Gets the sources object containing URLs for different resolutions.\r\n * Returns a copy to prevent external modification.\r\n */\r\n getSources() {\r\n return { ...this.sources };\r\n }\r\n\r\n /**\r\n * Gets the URL for a specific resolution key.\r\n * @param resolutionKey - The key of the desired resolution (e.g., 'thumbnail', 'medium').\r\n * @returns The URL string if the key doesn't exist, otherwise original image URL will be returned.\r\n */\r\n getSource(resolutionKey: ImageResolution): string{\r\n return this.sources[resolutionKey] || this.sources.original;\r\n }\r\n\r\n /**\r\n * Gets the alternative text for the image.\r\n */\r\n getAlt(): string | undefined {\r\n return this.alt;\r\n }\r\n\r\n /**\r\n * Gets the display order number for the image.\r\n */\r\n getOrder(): number | undefined {\r\n return this.order;\r\n }\r\n\r\n /**\r\n * Gets the display label or caption for the image.\r\n */\r\n getLabel(): string | undefined {\r\n return this.label;\r\n }\r\n\r\n /**\r\n * Sets the alternative text for the image.\r\n * @param altText - The new alt text.\r\n */\r\n setAlt(altText: string | undefined): void {\r\n this.alt = altText;\r\n // Potentially add logic here to trigger updates if needed\r\n }\r\n\r\n /**\r\n * Sets the display order for the image.\r\n * @param order - The new order number.\r\n */\r\n setOrder(order: number | undefined): void {\r\n this.order = order;\r\n }\r\n\r\n /**\r\n * Sets the display label for the image.\r\n * @param label - The new label text.\r\n */\r\n setLabel(label: string | undefined): void {\r\n this.label = label;\r\n }\r\n\r\n /**\r\n * Updates or adds a URL for a specific resolution.\r\n * @param resolutionKey - The key of the resolution to update/add.\r\n * @param url - The URL for the resolution. Set to undefined to remove.\r\n */\r\n setSource(resolutionKey: ImageResolution, url: string | undefined): void {\r\n if (url === undefined) {\r\n // Prevent deleting the 'original' key if it's required\r\n if (resolutionKey === 'original') {\r\n throw (\"Cannot remove the 'original' image source.\");\r\n return;\r\n }\r\n delete this.sources[resolutionKey];\r\n } else {\r\n this.sources[resolutionKey] = url;\r\n }\r\n }\r\n\r\n /**\r\n * Returns a plain JavaScript object representation of the image info.\r\n */\r\n getDetails(): ImageInfoData {\r\n return {\r\n sources: this.getSources(),\r\n alt: this.getAlt(),\r\n order: this.getOrder(),\r\n label: this.getLabel(),\r\n };\r\n }\r\n}","import { BasePrice, Color, LocaleCode, LocalizedString, PriceTier } from \"./Common\";\r\nimport { LocaleLanguageMap } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport { LocalizedProductSpecification, ProductSpecification } from \"./Product\";\r\n\r\nexport type SubItem = {\r\n size: string;\r\n quantity: number;\r\n};\r\n\r\nexport type LineItemAttributes = {\r\n id: string;\r\n productKey: string;\r\n variantId: string;\r\n name: LocalizedString;\r\n attributes: {\r\n color: Color;\r\n };\r\n specifications: LocalizedProductSpecification;\r\n primaryImage: ImageInfoData;\r\n subItems: SubItem[];\r\n basePrice: BasePrice;\r\n priceTiers: PriceTier[];\r\n}\r\n\r\nexport type LineItemData = LineItemAttributes & {\r\n totalQuantity: number;\r\n priceTotals: {\r\n subtotal: number;\r\n mrpTotal: number;\r\n };\r\n}\r\n\r\n/**\r\n * Represents a line item within a shopping cart.\r\n */\r\nexport default class LineItemModel {\r\n protected id: string;\r\n protected productKey: string;\r\n protected variantId: string;\r\n protected name: LocalizedString;\r\n protected attributes: {\r\n color: Color;\r\n };\r\n protected specifications: LocalizedProductSpecification;\r\n protected primaryImage: ImageInfoModel;\r\n protected subItems: SubItem[];\r\n protected totalQuantity: number;\r\n protected basePrice: BasePrice;\r\n protected priceTotals: {\r\n subtotal: number;\r\n mrpTotal: number;\r\n };\r\n protected priceTiers: PriceTier[];\r\n\r\n /**\r\n * Creates an instance of LineItemModel.\r\n * @param data - The initial line item attributes.\r\n */\r\n constructor(data: LineItemAttributes) {\r\n this.id = data.id;\r\n this.productKey = data.productKey;\r\n this.variantId = data.variantId;\r\n\r\n this.name = { ...data.name };\r\n this.attributes = { ...data.attributes };\r\n this.specifications = {...data.specifications };\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.subItems = data.subItems.map(item => ({ ...item }));\r\n this.basePrice = { ...data.basePrice };\r\n this.priceTiers = data.priceTiers.map(tier => ({ ...tier }));\r\n\r\n this.totalQuantity = 0;\r\n this.priceTotals = {\r\n subtotal: 0,\r\n mrpTotal: 0\r\n };\r\n\r\n this.recalculateTotalQuantity();\r\n this.recalculatePriceTotal();\r\n }\r\n\r\n /** Gets the unique identifier of the line item. */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /** Gets the product key associated with this line item. */\r\n getProductKey(): string {\r\n return this.productKey;\r\n }\r\n\r\n /** Gets the product variant ID associated with this line item. */\r\n getVariantId(): string {\r\n return this.variantId;\r\n }\r\n\r\n /**\r\n * Gets the full localized product name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the product name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if(locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n\r\n /** Gets the variant attributes. */\r\n getAttributes(): { color: Color } {\r\n return { ...this.attributes };\r\n }\r\n\r\n /**\r\n * Gets the full localized product specifications object.\r\n * @returns Product Specifications\r\n */\r\n getSpecifications(): LocalizedProductSpecification\r\n /**\r\n * Gets the product specifications for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The ProductSpecification object for the specified locale, or undefined if not found.\r\n */\r\n getSpecifications(locale: LocaleCode): ProductSpecification | undefined\r\n getSpecifications(locale?: LocaleCode): LocalizedProductSpecification | ProductSpecification | undefined {\r\n if(locale){\r\n return this.specifications[locale] ?? this.specifications[LocaleLanguageMap[locale]] ?? this.specifications.en;\r\n } else {\r\n return JSON.parse(JSON.stringify(this.specifications));\r\n }\r\n }\r\n\r\n /** Gets the image information model for this line item. */\r\n getImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /** Gets the sub-items (size/quantity breakdown). */\r\n getSubItems(): SubItem[] {\r\n return this.subItems.map(item => ({ ...item }));\r\n }\r\n\r\n /** Gets the total quantity for this line item across all sub-items. */\r\n getTotalQuantity(): number {\r\n return this.totalQuantity;\r\n }\r\n\r\n /** Gets the base price for a single unit. */\r\n getBasePrice(): BasePrice {\r\n return { ...this.basePrice };\r\n }\r\n\r\n /** Gets the calculated price details (subtotal, mrpTotal) for this line item. */\r\n getPriceTotals(): { subtotal: number; mrpTotal: number } {\r\n return { ...this.priceTotals };\r\n }\r\n\r\n /** Gets the applicable price tiers for this product variant. */\r\n getPriceTiers(): PriceTier[] {\r\n return this.priceTiers.map(tier => ({ ...tier }));\r\n }\r\n\r\n /**\r\n * Recalculates the total quantity based on the quantities in subItems.\r\n */\r\n protected recalculateTotalQuantity(): void {\r\n this.totalQuantity = this.subItems.reduce((sum, item) => sum + item.quantity, 0);\r\n }\r\n\r\n /**\r\n * Recalculates the line item's price (subtotal and mrpTotal)\r\n * based on total quantity, base price, and applicable price tiers.\r\n */\r\n protected recalculatePriceTotal(): void {\r\n const quantity = this.totalQuantity;\r\n let unitPrice = this.basePrice.unitPrice;\r\n\r\n let applicableTier = null;\r\n for (const tier of this.priceTiers.sort((a, b) => b.minQuantity - a.minQuantity)) { \r\n if (quantity >= tier.minQuantity) {\r\n applicableTier = tier;\r\n break;\r\n }\r\n }\r\n\r\n if (applicableTier) {\r\n unitPrice = applicableTier.unitPrice;\r\n }\r\n\r\n // Calculate totals\r\n this.priceTotals.mrpTotal = this.basePrice.unitPrice * quantity;\r\n this.priceTotals.subtotal = unitPrice * quantity;\r\n }\r\n\r\n\r\n /**\r\n * Gets a plain data object representing the line item's details.\r\n * @returns LineItemData.\r\n */\r\n getDetails(): LineItemData {\r\n return {\r\n id: this.getId(),\r\n productKey: this.getProductKey(),\r\n variantId: this.getVariantId(),\r\n name: this.getName(),\r\n attributes: this.getAttributes(),\r\n specifications: this.getSpecifications(),\r\n primaryImage: this.getImage().getDetails(),\r\n subItems: this.getSubItems(),\r\n totalQuantity: this.getTotalQuantity(),\r\n basePrice: this.getBasePrice(),\r\n priceTotals: this.getPriceTotals(),\r\n priceTiers: this.getPriceTiers(),\r\n };\r\n }\r\n \r\n /**\r\n * Adds or updates sub-items (e.g., sizes with quantities) to the line item.\r\n * If a sub-item with the same size already exists, its quantity is either\r\n * updated by adding the new quantity or replaced entirely, based on the `addQuantity` flag.\r\n * Sub-items with a resulting quantity of 0 are removed.\r\n * Recalculates total quantity and price totals afterwards.\r\n *\r\n * @param subItems - An array of `SubItem` objects to add or update.\r\n * @param addQuantity - If true, adds the quantity from `subItem` to the existing quantity.\r\n * If false, replaces the existing quantity with the one from `subItem`.\r\n */\r\n addSubItems(subItems: SubItem[], addQuantity: boolean): void {\r\n subItems.forEach(subItem => {\r\n const existingSubItem = this.subItems.find(item => item.size === subItem.size);\r\n if (existingSubItem) {\r\n existingSubItem.quantity = addQuantity ? existingSubItem.quantity + subItem.quantity : subItem.quantity;\r\n } else {\r\n this.subItems.push(subItem);\r\n }\r\n })\r\n this.subItems = this.subItems.filter(sub => sub.quantity);\r\n\r\n this.recalculateTotalQuantity();\r\n this.recalculatePriceTotal();\r\n }\r\n\r\n /**\r\n * Resets the line item's properties to their default empty or initial state.\r\n * Useful for clearing out line item data without creating a new instance.\r\n * Recalculates total quantity and price totals afterwards (which will be zero).\r\n */\r\n clearLineItem(): void {\r\n this.id = '';\r\n this.productKey = '';\r\n this.variantId = '';\r\n this.name = { en: '' };\r\n this.attributes = { color: { name: '', hex: '' } };\r\n this.primaryImage = new ImageInfoModel({ sources: { original: '' } });\r\n this.subItems = [];\r\n this.recalculateTotalQuantity();\r\n this.recalculatePriceTotal();\r\n }\r\n}","import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport AddressModel, { AddressData } from \"./Address\";\r\nimport LineItemModel, { LineItemData } from \"./LineItem\";\r\nimport { CountryCode, CurrencyCode, LocaleCode, ShippingDetails } from \"./Common\";\r\nimport PriceModel from \"./Price\";\r\nimport CouponModel, { CouponCategory, CouponData, CouponDiscountMethod } from \"./Coupon\";\r\n\r\nexport type ShoppingContainerTotal = {\r\n shipping?: number;\r\n effectiveShipping?: number;\r\n subtotal?: number;\r\n mrpTotal?: number;\r\n couponTotal?: { [key: string]: number };\r\n grandTotal?: number;\r\n}\r\n\r\nexport type BaseShoppingContainerAttributes = BaseAttributes & {\r\n id: string;\r\n customerId?: string;\r\n customerEmail?: string;\r\n anonymousId?: string;\r\n lineItems: LineItemData[];\r\n shippingDetails: ShippingDetails | null;\r\n shippingAddress?: AddressData | null;\r\n billingAddress?: AddressData | null;\r\n coupons?: CouponData[];\r\n total?: ShoppingContainerTotal;\r\n country: CountryCode;\r\n currency: CurrencyCode;\r\n locale: LocaleCode;\r\n};\r\n\r\nexport type BaseShoppingContainerData = Omit<BaseShoppingContainerAttributes, 'coupons' | 'total'>\r\n& BaseData\r\n& {\r\n coupons: CouponData[],\r\n total: {\r\n shipping: number,\r\n effectiveShipping: number,\r\n subtotal: number,\r\n mrpTotal: number,\r\n couponTotal: { [key: string]: number },\r\n grandTotal: number\r\n };\r\n };\r\n\r\n\r\n/**\r\n * Abstract base class for shopping-related containers like carts and orders.\r\n * Manages common elements such as line items, addresses, coupons, and totals.\r\n */\r\nexport default abstract class BaseShoppingContainerModel extends BaseModel {\r\n protected id: string;\r\n protected customerId?: string;\r\n protected customerEmail?: string;\r\n protected anonymousId?: string;\r\n protected lineItems: LineItemModel[];\r\n protected shippingDetails: ShippingDetails | null;\r\n protected shippingAddress: AddressModel | null;\r\n protected billingAddress: AddressModel | null;\r\n\r\n // CouponsCodes\r\n protected coupons: CouponModel[];\r\n\r\n // Cart Totals\r\n protected total: {\r\n shipping: number;\r\n effectiveShipping: number;\r\n subtotal: number;\r\n mrpTotal: number;\r\n couponTotal: { [key: string]: number; };\r\n grandTotal: number;\r\n };\r\n\r\n protected country: CountryCode;\r\n protected currency: CurrencyCode;\r\n protected locale: LocaleCode;\r\n\r\n /**\r\n * Creates an instance of BaseShoppingContainerModel.\r\n * Initializes common properties and calculates initial base totals.\r\n * @param data - The initial attributes for the shopping container.\r\n * @param date - Optional date object for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: BaseShoppingContainerAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.customerId = data.customerId;\r\n this.customerEmail = data.customerEmail;\r\n this.anonymousId = data.anonymousId;\r\n this.country = data.country;\r\n this.currency = data.currency;\r\n this.locale = data.locale;\r\n this.lineItems = (data.lineItems ?? []).map(item => new LineItemModel(item));\r\n this.billingAddress = data.billingAddress ? new AddressModel(data.billingAddress, date) : null;\r\n this.shippingAddress = data.shippingAddress ? new AddressModel(data.shippingAddress, date) : null;\r\n this.coupons = (data.coupons || []).map(coupon => new CouponModel(coupon));\r\n\r\n this.shippingDetails = data.shippingDetails ? { ...data.shippingDetails } : null;\r\n\r\n this.total = {\r\n shipping: data.total?.shipping || 0,\r\n effectiveShipping: data.total?.effectiveShipping ?? data.total?.shipping ?? 0,\r\n subtotal: data.total?.subtotal || 0,\r\n mrpTotal: data.total?.mrpTotal || 0,\r\n couponTotal: data.total?.couponTotal || {},\r\n grandTotal: data.total?.grandTotal || 0,\r\n };\r\n }\r\n\r\n /**\r\n * Recalculates the subtotal and mrpTotal based on the current line items.\r\n * Uses PriceModel for rounding based on the country.\r\n */\r\n protected recalculateBaseTotals(): void {\r\n this.total.subtotal = PriceModel.getRoundedPrice(this.lineItems.reduce((sum, item) => sum + item.getPriceTotals().subtotal, 0), this.country);\r\n this.total.mrpTotal = PriceModel.getRoundedPrice(this.lineItems.reduce((sum, item) => sum + item.getPriceTotals().mrpTotal, 0), this.country);\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for this shopping container (cart ID or order ID).\r\n * @returns The ID string.\r\n */\r\n public getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the customer ID associated with this container, if available.\r\n * @returns The customer ID string, or undefined.\r\n */\r\n public getCustomerId(): string | undefined {\r\n return this.customerId;\r\n }\r\n\r\n /**\r\n * Gets the customer email associated with this container, if available.\r\n * @returns The customer email string, or undefined.\r\n */\r\n public getCustomerEmail(): string | undefined {\r\n return this.customerEmail;\r\n }\r\n\r\n /**\r\n * Gets the anonymous user ID associated with this container, if available.\r\n * @returns The anonymous ID string, or undefined.\r\n */\r\n public getAnonymousId(): string | undefined {\r\n return this.anonymousId;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the line items in the container.\r\n * Each item is a new LineItemModel instance created from the original's details.\r\n * @returns An array of LineItemModel instances.\r\n */\r\n public getLineItems(): LineItemModel[] {\r\n // Return new instances to prevent modification of internal state\r\n return this.lineItems.map(item => new LineItemModel(item.getDetails()));\r\n }\r\n\r\n /**\r\n * Gets current number of line items in the container\r\n * @returns \r\n */\r\n public getLineItemsCount(): number {\r\n return this.lineItems.length;\r\n }\r\n\r\n /**\r\n * Gets a copy of the shipping details associated with the container.\r\n * @returns A ShippingDetails object, or null if none are set.\r\n */\r\n public getShippingDetails(): ShippingDetails | null {\r\n // Return a shallow copy if details exist\r\n return this.shippingDetails ? { ...this.shippingDetails } : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the shipping address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no shipping address is set.\r\n */\r\n public getShippingAddress(): AddressModel | null {\r\n return this.shippingAddress ? new AddressModel(this.shippingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Checks if a shipping address is associated with this container.\r\n * @returns True if a shipping address is set, false otherwise.\r\n */\r\n public hasShippingAddress(): boolean {\r\n return !!this.shippingAddress;\r\n }\r\n\r\n /**\r\n * Checks if a billing address is associated with this container.\r\n * @returns True if a billing address is set, false otherwise.\r\n */\r\n public hasBillingAddress(): boolean {\r\n return !!this.billingAddress;\r\n }\r\n \r\n /**\r\n * Gets a defensive copy of the billing address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no billing address is set.\r\n */\r\n public getBillingAddress(): AddressModel | null {\r\n return this.billingAddress ? new AddressModel(this.billingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the coupons applied to the container.\r\n * Each item is a new CouponModel instance created from the original's details.\r\n * @returns An array of CouponModel instances.\r\n */\r\n public getCoupons(): CouponModel[] {\r\n return this.coupons.map(coupon => new CouponModel(coupon.getDetails()));\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this container.\r\n * @returns The CountryCode enum value.\r\n */\r\n public getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Gets the currency code associated with this container.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Gets the locale code associated with this container.\r\n * @returns The LocaleCode enum value.\r\n */\r\n public getLocale(): LocaleCode {\r\n return this.locale;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the calculated totals for the container.\r\n * @returns An object containing shipping, subtotal, coupon, and grand totals.\r\n */\r\n public getTotal() {\r\n return { ...this.total, couponTotal: { ...this.total.couponTotal } };\r\n }\r\n\r\n /**\r\n * Calculates the discount value for a given coupon based on the current container state.\r\n * Returns 0 if the coupon is invalid, expired, or not applicable based on cart value or target category.\r\n * @param coupon - The CouponModel instance to evaluate.\r\n * @param checkExpiry - Whether to check the coupon's expiry status.\r\n * @returns The calculated discount amount (rounded according to country rules).\r\n */\r\n public calculateApplicableCouponDiscount(coupon: CouponModel, checkExpiry: boolean = true): number {\r\n // 1. Basic validation (active)\r\n if (checkExpiry && !coupon.isActive()) {\r\n return 0;\r\n }\r\n\r\n // 2. Check regional requirements (min cart value, max discount)\r\n const minCartValueReq = coupon.getMinCartValue(this.country);\r\n const maxCartDiscountCap = coupon.getMaxCartDiscount(this.country);\r\n\r\n // Ensure minCartValueReq exists and subtotal meets the requirement\r\n if (!minCartValueReq || this.total.subtotal < minCartValueReq.price) {\r\n return 0;\r\n }\r\n\r\n // Ensure maxCartDiscountCap exists and is non-negative\r\n if (!maxCartDiscountCap || maxCartDiscountCap.price < 0) {\r\n return 0;\r\n }\r\n\r\n // 3. Calculate potential discount based on method and category\r\n const couponCategory = coupon.getCategory();\r\n const discountMethod = coupon.getDiscountMethod();\r\n let potentialDiscount = 0;\r\n // Determine the value the coupon applies to (shipping cost or subtotal)\r\n const targetValue = couponCategory === CouponCategory.SHIPPING ? this.total.shipping : this.total.subtotal;\r\n\r\n // No discount if the target value is zero or less\r\n if (targetValue <= 0) return 0;\r\n\r\n switch (discountMethod) {\r\n case CouponDiscountMethod.FLAT:\r\n // Flat discount is capped by the target value itself and the max discount cap\r\n const flatAmount = maxCartDiscountCap?.price ?? 0; // Use cap as the flat amount source? Or coupon.value? Needs clarification. Assuming cap IS the flat amount here.\r\n potentialDiscount = Math.min(targetValue, flatAmount);\r\n break;\r\n case CouponDiscountMethod.PERCENTAGE:\r\n // Calculate percentage discount based on the target value\r\n potentialDiscount = targetValue * (coupon.getPercentageValue() / 100);\r\n break;\r\n default:\r\n // Unknown discount method\r\n return 0;\r\n }\r\n\r\n // 4. Apply maximum discount cap to the calculated potential discount\r\n const finalDiscount = Math.min(potentialDiscount, maxCartDiscountCap.price);\r\n\r\n // 5. Round the final discount, ensuring it's not negative\r\n return PriceModel.getRoundedPrice(Math.max(0, finalDiscount), this.country);\r\n }\r\n\r\n /**\r\n * Recalculates the `couponTotal` map based on currently applied coupons.\r\n * Iterates through coupons, calculates their applicable discount, and stores it.\r\n * @param checkExpiry - Whether to check the expiry status of coupons.\r\n * @returns The total discount amount from all valid and applicable coupons (rounded).\r\n */\r\n public recalculateCouponTotals(checkExpiry: boolean = true): number {\r\n this.total.couponTotal = {};\r\n let totalDiscount = 0;\r\n\r\n this.coupons.forEach(coupon => {\r\n const discount = this.calculateApplicableCouponDiscount(coupon, checkExpiry);\r\n if (discount > 0) {\r\n this.total.couponTotal[coupon.getCode()] = discount; // Store per-coupon discount\r\n totalDiscount += discount; // Accumulate total discount\r\n }\r\n });\r\n // Return the rounded total discount\r\n return PriceModel.getRoundedPrice(totalDiscount, this.country);\r\n }\r\n\r\n\r\n /**\r\n * Gets a plain data object representing the shopping container's current state.\r\n * Includes details from the base model and specific container properties.\r\n * @returns BaseShoppingContainerData object suitable for serialization or API responses.\r\n */\r\n getDetails(): BaseShoppingContainerData {\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n customerId: this.getCustomerId(),\r\n customerEmail: this.getCustomerEmail(),\r\n anonymousId: this.getAnonymousId(),\r\n lineItems: this.getLineItems().map(item => item.getDetails()),\r\n shippingDetails: this.getShippingDetails(),\r\n shippingAddress: this.getShippingAddress()?.getDetails() || null,\r\n billingAddress: this.getBillingAddress()?.getDetails() || null,\r\n coupons: this.getCoupons().map(coupon => coupon.getDetails()),\r\n total: this.getTotal(),\r\n country: this.getCountry(),\r\n currency: this.getCurrency(),\r\n locale: this.getLocale(),\r\n }\r\n };\r\n}\r\n","import { CouponCategory } from \"./Coupon\";\r\nimport LineItemModel from \"./LineItem\";\r\nimport PriceModel from \"./Price\";\r\nimport BaseShoppingContainerModel, { BaseShoppingContainerAttributes, BaseShoppingContainerData } from \"./ShoppingContainer\";\r\n\r\nexport enum CartState {\r\n ACTIVE = \"ACTIVE\",\r\n FROZEN = \"FROZEN\",\r\n MERGED = \"MERGED\",\r\n ORDERED = \"ORDERED\"\r\n}\r\n\r\nexport class LineItemNotFoundError extends Error {\r\n constructor(lineItemId: string) {\r\n super(`Line item with ID '${lineItemId}' not found in the cart.`);\r\n this.name = 'LineItemNotFoundError';\r\n }\r\n}\r\n\r\n/**\r\n * Input attributes for creating or updating a CartModel.\r\n */\r\nexport type CartAttributes = BaseShoppingContainerAttributes & { \r\n state: CartState;\r\n expireAt: number;\r\n};\r\n\r\nexport type CartData = BaseShoppingContainerData & {\r\n state: CartState;\r\n expireAt: number;\r\n};\r\n\r\nexport type CartConfig = {\r\n expiresAtInSeconds: number;\r\n}\r\n\r\nexport const DEFAULT_CART_CONFIG: CartConfig = {\r\n expiresAtInSeconds: 120 * 24 * 60 * 60\r\n}\r\n\r\nexport default class CartModel extends BaseShoppingContainerModel {\r\n protected state: CartState;\r\n protected expireAt: number;\r\n protected config: CartConfig;\r\n\r\n constructor(data: CartAttributes, date: Date = new Date(), config: CartConfig = DEFAULT_CART_CONFIG) {\r\n super(data, date);\r\n this.state = data.state;\r\n this.expireAt = data.expireAt && typeof data.expireAt === 'number' ? data.expireAt : Math.floor(date.getTime()/1000) + config.expiresAtInSeconds;\r\n this.config = config;\r\n \r\n this.updateCartTotals();\r\n }\r\n\r\n public getState(): CartState {\r\n return this.state;\r\n }\r\n\r\n public getExpireAt(): number {\r\n return this.expireAt;\r\n }\r\n\r\n public isActive(): boolean {\r\n const nowSeconds = Math.ceil(Date.now() / 1000);\r\n return this.state === CartState.ACTIVE && (this.expireAt > nowSeconds);\r\n }\r\n\r\n /**\r\n * Recalculates all container totals (subtotal, mrpTotal, coupons, shipping, grandTotal).\r\n * Should be called whenever line items, coupons, or base shipping cost change.\r\n */\r\n public updateCartTotals(): void {\r\n // 1. Calculate line item totals (subtotal, mrpTotal)\r\n this.recalculateBaseTotals();\r\n\r\n // 2. Calculate total coupon discount and update the per-coupon discount map\r\n this.recalculateCouponTotals(); // This updates this.total.couponTotal\r\n\r\n // 3. Calculate effective shipping cost after applying shipping-specific coupons\r\n const shippingCouponDiscount = this.coupons\r\n .filter(c => c.getCategory() === CouponCategory.SHIPPING)\r\n .reduce((sum, c) => sum + (this.total.couponTotal[c.getCode()] ?? 0), 0);\r\n this.total.effectiveShipping = PriceModel.getRoundedPrice(Math.max(0, this.total.shipping - shippingCouponDiscount), this.country);\r\n\r\n // 4. Calculate total discount from non-shipping coupons\r\n const nonShippingCouponDiscount = this.coupons\r\n .filter(c => c.getCategory() !== CouponCategory.SHIPPING)\r\n .reduce((sum, c) => sum + (this.total.couponTotal[c.getCode()] ?? 0), 0);\r\n\r\n // 5. Calculate final grand total: (subtotal + effective shipping) - non-shipping discounts\r\n const grossTotal = this.total.subtotal + this.total.effectiveShipping;\r\n this.total.grandTotal = PriceModel.getRoundedPrice(Math.max(0, grossTotal - nonShippingCouponDiscount), this.country);\r\n }\r\n \r\n public clearCartItems() {\r\n this.lineItems = [];\r\n this.coupons = [];\r\n this.updateCartTotals();\r\n }\r\n\r\n /**\r\n * Adds a new line item or updates the quantity of an existing one.\r\n * @param newLineItem The LineItemModel to add.\r\n * @returns The index of the added/updated line item in the internal array.\r\n */\r\n public addLineItem (newLineItem: LineItemModel) {\r\n const productKey = newLineItem.getProductKey();\r\n const variantId = newLineItem.getVariantId();\r\n let index = this.lineItems.findIndex(\r\n (item) => item.getProductKey() === productKey && item.getVariantId() === variantId\r\n );\r\n\r\n if(index >= 0){\r\n this.lineItems[index].addSubItems(newLineItem.getSubItems(), true);\r\n } else {\r\n this.lineItems.push(newLineItem);\r\n }\r\n\r\n this.updateCartTotals();\r\n return index >= 0 ? index : this.lineItems.length - 1;\r\n }\r\n\r\n /**\r\n * Updates the quantity for a specific size within a line item.\r\n * @param lineItemId The ID of the LineItemModel to update.\r\n * @param size The size identifier within the line item.\r\n * @param quantity The new quantity for the size (0 to remove).\r\n * @returns The index of the updated line item.\r\n * @throws {Error} If the line item is not found.\r\n */\r\n public updateLineItem (lineItemId: string, size: string, quantity: number) {\r\n const lineItems = this.lineItems;\r\n let index = lineItems.findIndex((item) => item.getId() === lineItemId);\r\n \r\n if(index < 0){\r\n throw new LineItemNotFoundError(lineItemId);\r\n }\r\n\r\n lineItems[index].addSubItems([{ size, quantity }], false);\r\n this.updateCartTotals();\r\n\r\n return index;\r\n }\r\n\r\n /**\r\n * Removes a line item completely from the cart.\r\n * @param lineItemId The ID of the LineItemModel to remove.\r\n * @returns The index the item previously occupied.\r\n * @throws {Error} If the line item is not found.\r\n */\r\n public removeLineItem (lineItemId: string) {\r\n const lineItems = this.lineItems;\r\n const index = lineItems.findIndex((item) => item.getId() === lineItemId);\r\n\r\n if(index < 0){\r\n throw new LineItemNotFoundError(lineItemId);\r\n }\r\n\r\n this.lineItems.splice(index, 1);\r\n this.updateCartTotals();\r\n\r\n return index;\r\n }\r\n\r\n getDetails(): CartData {\r\n return {\r\n ...super.getDetails(),\r\n state: this.getState(),\r\n expireAt: this.getExpireAt(),\r\n }\r\n }\r\n}\r\n","import AddressModel, { AddressData } from \"./Address\";\r\nimport { LineItemNotFoundError } from \"./Cart\";\r\nimport { ISODateTime } from \"./Common\";\r\nimport { CouponCategory } from \"./Coupon\";\r\nimport { PaymentStatus } from \"./Payment\";\r\nimport PriceModel from \"./Price\";\r\nimport BaseShoppingContainerModel, { BaseShoppingContainerAttributes, BaseShoppingContainerData, ShoppingContainerTotal } from \"./ShoppingContainer\";\r\n\r\n/**\r\n * PLACED: Order created, awaiting payment.\r\n * PENDING_PAYMENT: Waiting for payment confirmation.\r\n * PROCESSING: Payment received, order is being fulfilled. Stays here until all line items reach a final state.\r\n * CANCELLED: All line items are cancelled, or order is cancelled before fulfillment.\r\n * COMPLETED: All line items are delivered, returned, or refunded.\r\n */\r\nexport enum OrderState {\r\n PLACED = \"PLACED\",\r\n PENDING_PAYMENT = \"PENDING_PAYMENT\",\r\n PROCESSING = \"PROCESSING\",\r\n CANCELLED = \"CANCELLED\",\r\n COMPLETED = \"COMPLETED\"\r\n}\r\n\r\n/**\r\n * OrderLineItemState\r\n * \r\n * INITIAL: Item added to order, not yet processed.\r\n * PROCESSING: Item is being prepared for shipment.\r\n * SHIPPED: Item dispatched to customer.\r\n * DELIVERED: Item delivered to customer.\r\n * CANCELLED: Item cancelled before shipment or delivery.\r\n * RETURN_REQUESTED: Customer requests to return item.\r\n * RETURNED: Item received back from customer.\r\n * REFUND_INITIATED: Refund initiated for item.\r\n * REFUNDED: Refund processed for item.\r\n * ON_HOLD: Item is paused due to payment, inventory, or other issues.\r\n */\r\nexport enum OrderLineItemState {\r\n INITIAL = \"INITIAL\",\r\n PROCESSING = \"PROCESSING\",\r\n SHIPPED = \"SHIPPED\",\r\n DELIVERED = \"DELIVERED\",\r\n CANCELLED = \"CANCELLED\",\r\n RETURN_REQUESTED = \"RETURN_REQUESTED\",\r\n RETURNED = \"RETURNED\",\r\n REFUND_INITIATED = \"REFUND_INITIATED\",\r\n REFUNDED = \"REFUNDED\",\r\n ON_HOLD = \"ON_HOLD\",\r\n}\r\n\r\n\r\nexport type OrderLineItemStateMap = Record<string, {\r\n state:OrderLineItemState;\r\n reason?: string;\r\n transitionAt: ISODateTime;\r\n}>;\r\n\r\n/**\r\n * Input attributes for creating an OrderModel.\r\n * Extends CartAttributes but requires/adds order-specific fields.\r\n */\r\nexport type OrderAttributes = Omit<BaseShoppingContainerAttributes, 'anonymousId'> & {\r\n customerId: string;\r\n customerEmail: string;\r\n shippingAddress: AddressData;\r\n billingAddress: AddressData;\r\n anonymousId?: string;\r\n total: Required<ShoppingContainerTotal>;\r\n orderNumber: string;\r\n cartId: string;\r\n paymentStatus: PaymentStatus;\r\n holdReason?: string;\r\n state: OrderState;\r\n lineItemStateMap?: OrderLineItemStateMap;\r\n};\r\n\r\n/**\r\n * Output data structure for an OrderModel.\r\n */\r\nexport type OrderData = BaseShoppingContainerData & OrderAttributes & {\r\n holdReason: string;\r\n lineItemStateMap: OrderLineItemStateMap;\r\n};\r\n\r\n\r\nexport default class OrderModel extends BaseShoppingContainerModel {\r\n protected orderNumber: string;\r\n protected cartId: string;\r\n protected paymentStatus: PaymentStatus;\r\n protected holdReason: string;\r\n protected state: OrderState;\r\n protected lineItemStateMap: OrderLineItemStateMap;\r\n\r\n /**\r\n * Creates an instance of OrderModel.\r\n * @param data - The initial order attributes, including cart data.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n * @param config - Optional cart configuration (might be less relevant for orders).\r\n */\r\n constructor(data: OrderAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.orderNumber = data.orderNumber;\r\n this.cartId = data.cartId;\r\n this.paymentStatus = data.paymentStatus;\r\n this.holdReason = data.holdReason || '';\r\n this.state = data.state;\r\n \r\n const newLineItemStateMap: OrderLineItemStateMap = {};\r\n data.lineItems.forEach(item => {\r\n const currentStateMap = data.lineItemStateMap?.[item.id];;\r\n \r\n newLineItemStateMap[item.id] = {\r\n state: currentStateMap?.state || OrderLineItemState.INITIAL,\r\n reason: currentStateMap?.reason || '',\r\n transitionAt: currentStateMap?.transitionAt || this.createdAt,\r\n };\r\n });\r\n this.lineItemStateMap = newLineItemStateMap;\r\n\r\n this.recalculateOrderBaseTotals();\r\n }\r\n\r\n /**\r\n * Recalculates the subtotal and mrpTotal based on the current line items.\r\n * Uses PriceModel for rounding based on the country.\r\n */\r\n protected recalculateOrderBaseTotals(): void {\r\n this.total.subtotal = PriceModel.getRoundedPrice(this.lineItems\r\n .filter((item) => \r\n ![OrderLineItemState.CANCELLED, OrderLineItemState.REFUND_INITIATED, OrderLineItemState.REFUNDED].includes(this.lineItemStateMap[item.getId()]?.state)\r\n )\r\n .reduce((sum, item) => sum + item.getPriceTotals().subtotal, 0), this.country);\r\n\r\n this.total.mrpTotal = PriceModel.getRoundedPrice(this.lineItems\r\n .filter((item) => \r\n ![OrderLineItemState.CANCELLED, OrderLineItemState.REFUND_INITIATED, OrderLineItemState.REFUNDED].includes(this.lineItemStateMap[item.getId()]?.state)\r\n )\r\n .reduce((sum, item) => sum + item.getPriceTotals().mrpTotal, 0), this.country);\r\n }\r\n\r\n public updateOrderTotals(): void {\r\n // 1. Calculate line item totals (subtotal, mrpTotal)\r\n this.recalculateOrderBaseTotals();\r\n\r\n // 2. Calculate total coupon discount and update the per-coupon discount map\r\n this.recalculateCouponTotals(false);\r\n\r\n // 3. Calculate effective shipping cost after applying shipping-specific coupons\r\n const shippingCouponDiscount = this.coupons\r\n .filter(c => c.getCategory() === CouponCategory.SHIPPING)\r\n .reduce((sum, c) => sum + (this.total.couponTotal[c.getCode()] ?? 0), 0);\r\n this.total.effectiveShipping = PriceModel.getRoundedPrice(Math.max(0, this.total.shipping - shippingCouponDiscount), this.country);\r\n\r\n // 4. Calculate total discount from non-shipping coupons\r\n const nonShippingCouponDiscount = this.coupons\r\n .filter(c => c.getCategory() !== CouponCategory.SHIPPING)\r\n .reduce((sum, c) => sum + (this.total.couponTotal[c.getCode()] ?? 0), 0);\r\n\r\n // 5. Calculate final grand total: (subtotal + effective shipping) - non-shipping discounts\r\n const grossTotal = this.total.subtotal + this.total.effectiveShipping;\r\n this.total.grandTotal = PriceModel.getRoundedPrice(Math.max(0, grossTotal - nonShippingCouponDiscount), this.country);\r\n }\r\n\r\n /**\r\n * Gets the customer ID associated with this order.\r\n * Overrides the base method to guarantee a non-undefined return type for orders.\r\n * @returns The customer ID string.\r\n */\r\n public getCustomerId(): string {\r\n return this.customerId as string;\r\n }\r\n\r\n /**\r\n * Gets the customer email associated with this order.\r\n * Overrides the base method to guarantee a non-undefined return type for orders.\r\n * @returns The customer email string.\r\n */\r\n public getCustomerEmail(): string {\r\n return this.customerEmail as string;\r\n }\r\n\r\n /**\r\n * Gets the shipping address associated with the order.\r\n * Overrides the base method to guarantee a non-null return type for orders.\r\n * @returns An AddressModel instance for the shipping address.\r\n */\r\n public getShippingAddress(): AddressModel {\r\n return this.shippingAddress as AddressModel;\r\n }\r\n\r\n /**\r\n * Gets the billing address associated with the order.\r\n * Overrides the base method to guarantee a non-null return type for orders.\r\n * @returns An AddressModel instance for the billing address.\r\n */\r\n public getBillingAddress(): AddressModel {\r\n return this.billingAddress as AddressModel;\r\n }\r\n\r\n\r\n /**\r\n * Gets the user-facing order number.\r\n * @returns The order number string.\r\n */\r\n public getOrderNumber(): string {\r\n return this.orderNumber;\r\n }\r\n\r\n /**\r\n * Gets the ID of the cart from which this order was created.\r\n * @returns The cart ID string.\r\n */\r\n public getCartId(): string {\r\n return this.cartId;\r\n }\r\n\r\n /**\r\n * Gets the current payment status of the order.\r\n * @returns The PaymentStatus enum value.\r\n */\r\n public getPaymentStatus(): PaymentStatus {\r\n return this.paymentStatus;\r\n }\r\n\r\n /**\r\n * Gets the reason why the order might be on hold, if any.\r\n * @returns The hold reason string (empty if not on hold or no reason specified).\r\n */\r\n public getHoldReason(): string {\r\n return this.holdReason;\r\n }\r\n\r\n /**\r\n * Gets the current state of the order (e.g., PROCESSING, SHIPPED).\r\n * @returns The OrderState enum value.\r\n */\r\n public getState(): OrderState {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the map tracking the state of each line item in the order.\r\n * The keys are line item IDs, and the values contain the state, reason, and transition timestamp.\r\n * @returns The OrderLineItemStateMap.\r\n */\r\n public getLineItemsStateMap(): OrderLineItemStateMap {\r\n return { ...this.lineItemStateMap };\r\n }\r\n\r\n /**\r\n * Gets the current state of a specific line item within the order.\r\n * @param lineItemId - The ID of the line item whose state is requested.\r\n * @returns The OrderLineItemState enum value for the specified line item.\r\n * @throws {LineItemNotFoundError} If no line item with the given ID exists in the order's state map.\r\n */\r\n public getLineItemState(lineItemId: string): OrderLineItemState {\r\n if (!this.lineItemStateMap[lineItemId]){\r\n throw new LineItemNotFoundError(lineItemId)\r\n }\r\n return this.lineItemStateMap[lineItemId].state;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the order's current state.\r\n * Includes all cart details plus order-specific information.\r\n * @returns OrderData object suitable for serialization or API responses.\r\n */\r\n getDetails(): OrderData {\r\n return {\r\n ...super.getDetails(),\r\n orderNumber: this.getOrderNumber(),\r\n customerId: this.getCustomerId(),\r\n customerEmail: this.getCustomerEmail(),\r\n shippingAddress: this.getShippingAddress().getDetails(),\r\n billingAddress: this.getBillingAddress().getDetails(),\r\n cartId: this.getCartId(),\r\n paymentStatus: this.getPaymentStatus(),\r\n holdReason: this.getHoldReason(),\r\n state: this.getState(),\r\n lineItemStateMap: this.getLineItemsStateMap()\r\n }\r\n }\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/Classes/Base.ts","../../src/Classes/Enum.ts","../../src/Classes/Coupon.ts","../../src/Classes/Price.ts","../../src/Classes/Address.ts","../../src/Classes/ImageInfo.ts","../../src/Classes/LineItem.ts","../../src/Classes/ShoppingContainer.ts","../../src/Classes/Cart.ts","../../src/Classes/Order.ts"],"names":["BaseModel","data","date","id","authType","requestId","lambdaName","fieldName","value","LocaleLanguageMap","CountryCurrencyMap","CurrencySymbolMap","CouponModel","price","locale","country","ftbCustomer","PriceModel","_PriceModel","options","displayAsInteger","currency","valueToFormat","fractionDigits","formattingOptions","error","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier","AddressModel","addressType","ImageInfoModel","resolutionKey","altText","order","label","url","LineItemModel","item","tier","sum","quantity","unitPrice","applicableTier","a","b","subItems","addQuantity","subItem","existingSubItem","sub","BaseShoppingContainerModel","coupon","checkExpiry","minCartValueReq","maxCartDiscountCap","couponCategory","discountMethod","potentialDiscount","targetValue","flatAmount","finalDiscount","totalDiscount","discount","LineItemNotFoundError","lineItemId","OrderState","OrderLineItemState","OrderModel","newLineItemStateMap","currentStateMap","filteredLineItems","shippingCouponDiscount","c","nonShippingCouponDiscount","grossTotal"],"mappings":"sEA4BA,IAAqBA,EAArB,KAA+B,CACnB,YACA,CAAA,OAAA,CACA,UACA,UACA,CAAA,UAAA,CAQV,WAAYC,CAAAA,CAAAA,CAAsBC,EAAa,IAAI,IAAA,CAAQ,CACzD,IAAK,CAAA,YAAA,CAAe,CAAE,GAAGD,CAAAA,CAAK,YAAa,CAAA,CAC3C,KAAK,OAAUA,CAAAA,CAAAA,CAAK,SAAW,CAC/B,CAAA,IAAA,CAAK,UAAYA,CAAK,CAAA,SAAA,EAAa,CAAC,KAAA,CAAM,KAAK,KAAMA,CAAAA,CAAAA,CAAK,SAAS,CAAC,CAAA,CAElE,IAAI,IAAKA,CAAAA,CAAAA,CAAK,SAAS,CAAA,CAAE,aAEzBC,CAAAA,CAAAA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O,aAAA,EAAwB,CAC7B,OAAO,IAAA,CAAK,UACd,CAMO,QAAA,EAAuB,CAC5B,OAAO,IAAA,CAAK,KACd,CAOO,sBAA8C,CACnD,OAAO,CAAE,GAAG,KAAK,gBAAiB,CACpC,CAQO,gBAAA,CAAiBT,EAAwC,CAC9D,GAAI,CAAC,IAAK,CAAA,gBAAA,CAAiBA,CAAU,CACnC,CAAA,MAAM,IAAID,CAAAA,CAAsBC,CAAU,CAE5C,CAAA,OAAO,KAAK,gBAAiBA,CAAAA,CAAU,EAAE,KAC3C,CAOA,UAAwB,EAAA,CACtB,OAAO,CACL,GAAG,MAAM,UAAW,EAAA,CACpB,YAAa,IAAK,CAAA,cAAA,EAClB,CAAA,UAAA,CAAY,KAAK,aAAc,EAAA,CAC/B,cAAe,IAAK,CAAA,gBAAA,GACpB,eAAiB,CAAA,IAAA,CAAK,kBAAmB,EAAA,CAAE,YAC3C,CAAA,cAAA,CAAgB,KAAK,iBAAkB,EAAA,CAAE,YACzC,CAAA,MAAA,CAAQ,IAAK,CAAA,SAAA,GACb,aAAe,CAAA,IAAA,CAAK,kBACpB,CAAA,UAAA,CAAY,KAAK,aAAc,EAAA,CAC/B,KAAO,CAAA,IAAA,CAAK,UACZ,CAAA,gBAAA,CAAkB,KAAK,oBAAqB,EAC9C,CACF,CACF","file":"Order.js","sourcesContent":["import { AuthType } from \"../Auth\";\r\nimport { ISODateTime } from \"./Common\";\r\n\r\nexport interface CustomFields {\r\n [key: string]: any;\r\n}\r\n\r\nexport type ModifiedBy = {\r\n id?: string;\r\n authType?: string;\r\n requestId?: string;\r\n lambdaName?: string;\r\n}\r\n\r\nexport type BaseAttributes = {\r\n customFields?: CustomFields;\r\n version?: number;\r\n createdAt?: ISODateTime;\r\n modifiedAt?: ISODateTime;\r\n modifiedBy?: ModifiedBy;\r\n};\r\n\r\nexport type BaseData = Required<BaseAttributes>;\r\n\r\n/**\r\n * Provides common foundational properties and methods for other data models.\r\n * Handles tracking of custom fields, versioning, and timestamps.\r\n */\r\nexport default class BaseModel {\r\n protected customFields: CustomFields;\r\n protected version: number;\r\n protected createdAt: ISODateTime;\r\n protected modifiedAt: ISODateTime;\r\n protected modifiedBy: ModifiedBy;\r\n\r\n /**\r\n * Creates an instance of BaseModel.\r\n * Initializes common properties like timestamps, version, and custom fields.\r\n * @param data - Optional initial attributes for the base model.\r\n * @param date - Optional date object to use for default timestamps (defaults to current time).\r\n */\r\n constructor(data: BaseAttributes, date: Date = new Date()) {\r\n this.customFields = { ...data.customFields };\r\n this.version = data.version ?? 1;\r\n this.createdAt = data.createdAt && !isNaN(Date.parse(data.createdAt))\r\n ?\r\n new Date(data.createdAt).toISOString()\r\n :\r\n date.toISOString();\r\n this.modifiedAt = data.modifiedAt && !isNaN(Date.parse(data.modifiedAt))\r\n ? new Date(data.modifiedAt).toISOString()\r\n : date.toISOString();\r\n\r\n this.modifiedBy = { ...data.modifiedBy };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the base model's current state.\r\n * @returns BaseData object containing common properties.\r\n */\r\n getDetails(): BaseData {\r\n return {\r\n customFields: this.getAllCustomFields(), // Use getter to return a copy\r\n version: this.getVersion(),\r\n createdAt: this.getCreatedAt(),\r\n modifiedAt: this.getModifiedAt(),\r\n modifiedBy: this.getModifiedBy(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the current version number of the model instance.\r\n * @returns The version number.\r\n */\r\n getVersion(): number {\r\n return this.version;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as an ISO 8601 string.\r\n * @returns The creation timestamp string.\r\n */\r\n getCreatedAt(): string {\r\n return this.createdAt;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as a Unix epoch time (milliseconds).\r\n * @returns The creation time in milliseconds since the epoch.\r\n */\r\n getCreatedAtTime(): number {\r\n return new Date(this.createdAt).getTime();\r\n }\r\n\r\n\r\n /**\r\n * Gets the last modification timestamp as an ISO 8601 string.\r\n * @returns The last modification timestamp string.\r\n */\r\n getModifiedAt(): string {\r\n return this.modifiedAt;\r\n }\r\n\r\n /**\r\n * Gets the last modification timestamp as a Unix epoch time (milliseconds).\r\n * @returns The last modification time in milliseconds since the epoch.\r\n */\r\n getModifiedAtTime(): number {\r\n return new Date(this.modifiedAt).getTime();\r\n }\r\n\r\n /**\r\n * Gets the identifier of the user or process that last modified the instance.\r\n * @returns\r\n */\r\n getModifiedBy(): ModifiedBy {\r\n return { ...this.modifiedBy };\r\n }\r\n\r\n /**\r\n * Sets the identifier of the user or process that last modified the instance.\r\n * @param modifiedBy - The identifier string.\r\n */\r\n setModifiedBy(id?: string, authType?: AuthType, requestId?: string, lambdaName?: string): void {\r\n this.modifiedBy = {\r\n id,\r\n authType,\r\n requestId,\r\n lambdaName,\r\n };\r\n }\r\n\r\n /**\r\n * Retrieves the value of a specific custom field.\r\n * @param fieldName - The name (key) of the custom field to retrieve.\r\n * @returns The value of the custom field, or null if the field does not exist.\r\n */\r\n getCustomField(fieldName: string): any {\r\n return this.customFields[fieldName] ?? null;\r\n }\r\n\r\n /**\r\n * Sets the value of a specific custom field.\r\n * Also updates the modification timestamp and increments the version.\r\n * @param fieldName - The name (key) of the custom field to set.\r\n * @param value - The value to assign to the custom field.\r\n */\r\n setCustomField(fieldName: string, value: any): void {\r\n this.customFields[fieldName] = value;\r\n }\r\n\r\n /**\r\n * Retrieves a shallow copy of all custom fields associated with the instance.\r\n * @returns An object containing all custom fields.\r\n */\r\n getAllCustomFields(): CustomFields {\r\n return { ...this.customFields };\r\n }\r\n}\r\n","/**\r\n * Represents the countries where the application operates or products are available.\r\n */\r\nexport enum OperationalCountry {\r\n /** India */ IN = 'IN',\r\n}\r\n \r\nexport enum OperationalCountryCurrency {\r\n /** India */ INR = 'INR',\r\n}\r\n\r\nexport enum OperationalLocale {\r\n /** India */ 'en-IN' = 'en-IN',\r\n /** India ( Kannada) */ 'kn-IN' = 'kn-IN'\r\n}\r\n\r\nexport enum OperationalLanguage {\r\n en = 'en',\r\n kn = 'kn'\r\n}\r\n\r\nexport const LocaleLanguageMap: Record<OperationalLocale, OperationalLanguage> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalLanguage.en,\r\n [OperationalLocale[\"kn-IN\"]]: OperationalLanguage.kn,\r\n}\r\n\r\nexport const LocaleCountryMap: Record<OperationalLocale, OperationalCountry> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalCountry.IN,\r\n [OperationalLocale[\"kn-IN\"]]: OperationalCountry.IN,\r\n}\r\n\r\n/**\r\n * Defines the supported ISO 4217 currency codes as an enumeration.\r\n */\r\nexport const CountryCurrencyMap = {\r\n /** India */ [OperationalCountry.IN]: OperationalCountryCurrency.INR,\r\n};\r\n\r\nexport const CurrencySymbolMap = {\r\n [OperationalCountryCurrency.INR]: '₹',\r\n}\r\n\r\n/**\r\n * Defines standard gender categories for product targeting.\r\n */\r\nexport enum GenderCategory {\r\n MALE = 'Male',\r\n FEMALE = 'Female',\r\n UNISEX = 'Unisex',\r\n KIDS = 'Kids',\r\n BOY = 'Boy',\r\n GIRL = 'Girl',\r\n}","import BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, ISODateTime, LocaleCode, LocalizedString, RegionalPrice, RegionalPriceList } from \"./Common\";\r\nimport { LocaleLanguageMap } from \"./Enum\";\r\n\r\nexport enum CouponType {\r\n COUPON = \"coupon\",\r\n AUTOMATIC = \"automatic\",\r\n}\r\n\r\nexport enum CouponDiscountMethod {\r\n FLAT = \"flat\",\r\n PERCENTAGE = \"percentage\",\r\n}\r\n\r\nexport enum CouponCategory {\r\n SHIPPING = \"SHIPPING\",\r\n CUSTOMER = \"CUSTOMER\",\r\n}\r\n\r\nexport enum ApplicableTo {\r\n ALL = \"all\",\r\n FTB = \"ftb\",\r\n}\r\n\r\nexport type CouponAttribute = BaseAttributes & {\r\n couponCode: string;\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n type: CouponType;\r\n customerId?: string;\r\n validFrom: ISODateTime;\r\n validTo: ISODateTime;\r\n minCartValue: RegionalPriceList;\r\n maxCartDiscount: RegionalPriceList;\r\n discountMethod: CouponDiscountMethod;\r\n percentageValue?: number;\r\n applicableTo: ApplicableTo;\r\n category: CouponCategory;\r\n};\r\n\r\nexport type CouponData = Required<CouponAttribute>\r\n\r\n/**\r\n * Represents a discount coupon, extending BaseModel.\r\n */\r\nexport default class CouponModel extends BaseModel {\r\n protected couponCode: string;\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected type: CouponType;\r\n protected customerId?: string;\r\n protected validFrom: ISODateTime;\r\n protected validTo: ISODateTime;\r\n protected minCartValue: RegionalPriceList;\r\n protected maxCartDiscount: RegionalPriceList;\r\n protected discountMethod: CouponDiscountMethod;\r\n protected percentageValue: number;\r\n protected applicableTo: ApplicableTo;\r\n protected category: CouponCategory;\r\n\r\n /**\r\n * Creates an instance of CouponModel.\r\n * @param data - The initial coupon attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: CouponAttribute, date: Date = new Date()) {\r\n super(data, date);\r\n\r\n this.couponCode = data.couponCode;\r\n this.name = { ...data.name };\r\n this.description = { ...data.description };\r\n this.type = data.type;\r\n this.customerId = data.customerId;\r\n this.validFrom = data.validFrom && Date.parse(data.validFrom) ? new Date(data.validFrom).toISOString() : date.toISOString();\r\n this.validTo = data.validTo && Date.parse(data.validTo) ? new Date(data.validTo).toISOString() : date.toISOString();\r\n this.minCartValue = data.minCartValue.map(price => ({ ...price }));\r\n this.maxCartDiscount = data.maxCartDiscount.map(price => ({ ...price }));\r\n this.discountMethod = data.discountMethod;\r\n this.percentageValue = data.percentageValue ?? 0;\r\n this.applicableTo = data.applicableTo;\r\n this.category = data.category;\r\n }\r\n\r\n /** Gets the unique coupon code. */\r\n getCode(): string {\r\n return this.couponCode;\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the coupon name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon description object.\r\n * @returns A copy of the LocalizedString object for the description, or undefined.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the coupon description for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The description string for the specified locale.\r\n */\r\n getDescription(locale: LocaleCode): string\r\n getDescription(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.description[locale] ?? this.description[LocaleLanguageMap[locale]] ?? this.description.en;\r\n } else {\r\n return { ...this.description };\r\n }\r\n }\r\n\r\n /** Gets the type of coupon (COUPON or AUTOMATIC). */\r\n getType(): CouponType {\r\n return this.type;\r\n }\r\n\r\n /** Gets the specific customer ID this coupon is limited to, if any. */\r\n getCustomerId(): string {\r\n return this.customerId ?? '';\r\n }\r\n\r\n /** Gets the ISO date string from when the coupon is valid. */\r\n getValidFrom(): ISODateTime {\r\n return this.validFrom;\r\n }\r\n\r\n /** Gets the ISO date string until when the coupon is valid. */\r\n getValidTo(): ISODateTime {\r\n return this.validTo;\r\n }\r\n\r\n /**\r\n * Gets the list of minimum cart values required for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional minimum cart values.\r\n */\r\n getMinCartValue(): RegionalPriceList\r\n /**\r\n * Gets the minimum cart value required for the coupon for a specific country.\r\n * @param country - The country code to filter the minimum value for.\r\n * @returns The regional minimum cart value for the specified country, or undefined if not set for that country.\r\n */\r\n getMinCartValue(country: CountryCode): RegionalPrice | undefined\r\n getMinCartValue(country?: CountryCode){\r\n if(country) {\r\n return this.minCartValue.find(price => price.country === country);\r\n }\r\n return this.minCartValue;\r\n }\r\n\r\n /**\r\n * Gets the list of maximum discount amounts allowed for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional maximum discount caps.\r\n */\r\n getMaxCartDiscount(): RegionalPriceList\r\n /**\r\n * Gets the maximum discount amount allowed for the coupon for a specific country.\r\n * @param country - The country code to filter the maximum discount for.\r\n * @returns The regional maximum discount cap for the specified country, or undefined if not set for that country.\r\n */\r\n getMaxCartDiscount(country: CountryCode): RegionalPrice | undefined\r\n getMaxCartDiscount(country?: CountryCode){\r\n if(country) {\r\n return this.maxCartDiscount.find(price => price.country === country);\r\n }\r\n return this.maxCartDiscount;\r\n }\r\n\r\n /** Gets the discount method (FLAT or PERCENTAGE). */\r\n getDiscountMethod(): CouponDiscountMethod {\r\n return this.discountMethod;\r\n }\r\n\r\n /** Gets the percentage discount value (0-100). */\r\n getPercentageValue(): number {\r\n return this.percentageValue;\r\n }\r\n\r\n /** Gets the customer applicability rule (ALL or FTB). */\r\n getApplicableTo(): ApplicableTo {\r\n return this.applicableTo;\r\n }\r\n\r\n /** Gets the category of the coupon (SHIPPING or CUSTOMER). */\r\n getCategory(): CouponCategory {\r\n return this.category;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the coupon's details.\r\n * @returns A CouponData object.\r\n */\r\n getDetails(): CouponData {\r\n return {\r\n ...super.getDetails(),\r\n couponCode: this.getCode(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n type: this.getType(),\r\n customerId: this.getCustomerId(),\r\n validFrom: this.getValidFrom(),\r\n validTo: this.getValidTo(),\r\n minCartValue: this.getMinCartValue(),\r\n maxCartDiscount: this.getMaxCartDiscount(),\r\n discountMethod: this.getDiscountMethod(),\r\n percentageValue: this.getPercentageValue(),\r\n applicableTo: this.getApplicableTo(),\r\n category: this.getCategory(),\r\n };\r\n }\r\n\r\n /**\r\n * Checks if the coupon is currently active based on its validity dates.\r\n * @returns True if the coupon is currently within its validity period, false otherwise.\r\n */\r\n isActive(): boolean {\r\n return new Date(this.validFrom) <= new Date() && new Date(this.validTo) >= new Date();\r\n }\r\n\r\n \r\n /**\r\n * Checks if the coupon is applicable to a customer based on their status (e.g., first-time buyer).\r\n * @param ftbCustomer - A boolean indicating whether the customer is a first-time buyer.\r\n * @returns True if the coupon's applicability rule matches the customer's status, false otherwise.\r\n */\r\n isApplicableTo(ftbCustomer: boolean): boolean {\r\n return this.applicableTo === ApplicableTo.ALL || (this.applicableTo === ApplicableTo.FTB && ftbCustomer);\r\n }\r\n}","import { CountryCode, CurrencyCode, LocaleCode } from \"./Common\"; // Assuming these are in Common.ts\r\nimport { CountryCurrencyMap, CurrencySymbolMap } from \"./Enum\"; // Ensure these maps exist\r\n\r\nexport default class PriceModel {\r\n protected price: number;\r\n protected country: CountryCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param price - The initial price value.\r\n * @param country - The country code used for rounding and determining the currency symbol.\r\n * @throws {Error} If price is negative or country/currency mapping is missing.\r\n */\r\n constructor(price: number, country: CountryCode) {\r\n this.country = country;\r\n\r\n if(price < 0) {\r\n throw new Error(\"InvalidPrice: Price cannot be negative.\");\r\n }\r\n\r\n this.price = price\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this price instance.\r\n * The country code is used for determining currency and formatting rules.\r\n * @returns The CountryCode enum value.\r\n */\r\n public getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Gets the rounded price value based on standard currency rules.\r\n * @returns The numeric price, rounded according to its currency's typical decimal places.\r\n */\r\n public getRoundedPrice(): number {\r\n return PriceModel.getRoundedPrice(this.price, this.country);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price stored in this instance.\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @param locale - The locale code (e.g., 'en-IN') to use for formatting rules.\r\n * @returns The formatted price string according to locale rules.\r\n * @throws {Error} If the currency mapping for the instance's country is not found (via the static method).\r\n */\r\n public getFormattedString(locale: LocaleCode){\r\n return PriceModel.getFormattedString(this.price, this.country, locale);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param price - The initial price value.\r\n * @param country - The country code used for rounding and determining the currency symbol.\r\n * @param locale - The locale code (e.g., 'en-IN') to use for formatting rules.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the price rounded to the nearest integer (no decimals). Defaults to false.\r\n * @param options.style - The style of formatting, either 'currency' or 'decimal'. Defaults to 'currency'.\r\n * @param options.currencyDisplay - The display format for the currency symbol. Options are 'symbol', 'narrowSymbol', 'code', or 'name'. Defaults to 'symbol'.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n static getFormattedString(price: number, country: CountryCode, locale?: LocaleCode, options: { displayAsInteger?: boolean, style?: 'currency' | 'decimal', currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name' } = {}): string {\r\n const displayAsInteger = options.displayAsInteger ?? false;\r\n const currency: CurrencyCode | undefined = CountryCurrencyMap[country];\r\n\r\n if (currency === undefined) {\r\n throw new Error('Currency mapping not found for CountryCode');\r\n }\r\n\r\n let valueToFormat = price;\r\n const fractionDigits = displayAsInteger ? 0 : PriceModel.getDecimalPlaces(currency);\r\n\r\n let formattingOptions: Intl.NumberFormatOptions = {\r\n style: options.style ?? 'currency',\r\n currency: currency,\r\n signDisplay: 'never',\r\n currencyDisplay: options.currencyDisplay,\r\n minimumFractionDigits: fractionDigits,\r\n maximumFractionDigits: fractionDigits,\r\n };\r\n\r\n if (displayAsInteger) {\r\n valueToFormat = Math.round(valueToFormat);\r\n }\r\n\r\n try {\r\n return new Intl.NumberFormat(locale, formattingOptions).format(valueToFormat);\r\n } catch (error) {\r\n console.error(`Error formatting price for country \"${country}\" and currency \"${currency}\":`, error);\r\n // Basic fallback without symbol if Intl fails completely\r\n return `${CurrencySymbolMap[currency] ?? currency} ${PriceModel.addThousandSeparators(valueToFormat.toFixed(fractionDigits))}`;\r\n }\r\n }\r\n\r\n /**\r\n * Helper method to determine standard decimal places for a currency.\r\n * @param currency - The currency code.\r\n * @returns The number of decimal places (0, 2, or 3 based on common rules).\r\n */\r\n private static getDecimalPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case 'INR':\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n /**\r\n * Adds basic thousand separators (commas) to a number string.\r\n * Does not handle different locale separators (e.g., periods, spaces).\r\n * @param numStr - The number string (potentially with decimals).\r\n * @returns The number string with commas added.\r\n */\r\n private static addThousandSeparators(numStr: string): string {\r\n const parts = numStr.split('.');\r\n const integerPart = parts[0];\r\n const decimalPart = parts.length > 1 ? '.' + parts[1] : '';\r\n\r\n const formattedInteger = integerPart.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\r\n return formattedInteger + decimalPart;\r\n }\r\n\r\n /**\r\n * Rounds a price value according to the standard decimal places\r\n * for the currency associated with the given country.\r\n *\r\n * @param price - The price value to round. Must be a non-negative number.\r\n * @param country - The country code to determine the currency and rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the country code is not found in the CountryCurrencyMap or price is negative.\r\n */\r\n static getRoundedPrice(price: number, country: CountryCode): number {\r\n if (price < 0) {\r\n throw new Error(\"Price cannot be negative for rounding.\");\r\n }\r\n\r\n const currency: CurrencyCode | undefined = CountryCurrencyMap[country];\r\n if (currency === undefined) {\r\n throw new Error(`Currency mapping not found for CountryCode: ${country}`);\r\n }\r\n\r\n const decimalPlaces = PriceModel.getDecimalPlaces(currency);\r\n const multiplier = Math.pow(10, decimalPlaces);\r\n const roundedValue = Math.round(price * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n\r\n /**\r\n * Static method to retrieve the currency code associated with a given country code.\r\n * Uses the `CountryCurrencyMap` to find the corresponding currency.\r\n *\r\n * @param country - The country code (e.g., 'IN') for which to find the currency.\r\n * @returns The currency code (e.g., 'INR') as a string, or undefined if the mapping doesn't exist.\r\n */\r\n static getCurrency(country: CountryCode): string {\r\n return CountryCurrencyMap[country];\r\n }\r\n\r\n}","import BaseModel, { BaseAttributes } from \"./Base\";\r\n\r\nexport enum AddressType {\r\n BILLING = \"billing\",\r\n SHIPPING = \"shipping\",\r\n BILLING_AND_SHIPPING = \"billing&shipping\",\r\n NONE = \"none\",\r\n}\r\n\r\nexport type AddressAttributes = BaseAttributes & {\r\n id: string;\r\n firstName: string;\r\n lastName?: string;\r\n phone: string;\r\n email: string;\r\n addressLine1: string;\r\n addressLine2?: string;\r\n city: string;\r\n postalCode: string\r\n state: string;\r\n country: string;\r\n isBillingAddress: boolean;\r\n isShippingAddress: boolean;\r\n};\r\n\r\nexport type AddressData = Required<AddressAttributes>;\r\n\r\n/**\r\n * Represents a physical address associated with a customer or order.\r\n * Handles both billing and shipping address types.\r\n */\r\nexport default class AddressModel extends BaseModel {\r\n protected id: string;\r\n protected firstName: string;\r\n protected lastName: string;\r\n protected phone: string;\r\n protected email: string;\r\n protected addressLine1: string;\r\n protected addressLine2: string;\r\n protected city: string;\r\n protected postalCode: string\r\n protected state: string;\r\n protected country: string;\r\n protected isBillingAddress: boolean;\r\n protected isShippingAddress: boolean;\r\n\r\n /**\r\n * Creates an instance of AddressModel.\r\n * @param data - The initial address attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: AddressAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.firstName = data.firstName;\r\n this.lastName = data.lastName || '';\r\n this.phone = data.phone;\r\n this.email = data.email;\r\n this.addressLine1 = data.addressLine1;\r\n this.addressLine2 = data.addressLine2 || '';\r\n this.city = data.city;\r\n this.postalCode = data.postalCode;\r\n this.state = data.state;\r\n this.country = data.country;\r\n this.isBillingAddress = data.isBillingAddress;\r\n this.isShippingAddress = data.isShippingAddress;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the address's current state.\r\n * Includes all address fields and base model fields.\r\n * @returns AddressData object suitable for serialization or API responses.\r\n */\r\n getDetails(): AddressData {\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n firstName: this.getFirstName(),\r\n lastName: this.getLastName(),\r\n phone: this.getPhone(),\r\n email: this.getEmail(),\r\n addressLine1: this.getAddressLine1(),\r\n addressLine2: this.getAddressLine2(),\r\n city: this.getCity(),\r\n postalCode: this.getPostalCode(),\r\n state: this.getState(),\r\n country: this.getCountry(),\r\n isBillingAddress: this.getIsBillingAddress(),\r\n isShippingAddress: this.getIsShippingAddress(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for the address.\r\n * @returns The address ID.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the first name associated with the address.\r\n * @returns The first name.\r\n */\r\n getFirstName(): string {\r\n return this.firstName;\r\n }\r\n\r\n /**\r\n * Gets the last name associated with the address.\r\n * @returns The last name.\r\n */\r\n getLastName(): string {\r\n return this.lastName;\r\n }\r\n\r\n /**\r\n * Gets the phone number associated with the address.\r\n * @returns The phone number.\r\n */\r\n getPhone(): string {\r\n return this.phone;\r\n }\r\n\r\n /**\r\n * Gets the email address associated with the address.\r\n * @returns The email address.\r\n */\r\n getEmail(): string {\r\n return this.email;\r\n }\r\n\r\n /**\r\n * Gets the primary address line (e.g., street address).\r\n * @returns The first address line.\r\n */\r\n getAddressLine1(): string {\r\n return this.addressLine1;\r\n }\r\n\r\n /**\r\n * Gets the secondary address line (e.g., apartment, suite).\r\n * Returns an empty string if not provided.\r\n * @returns The second address line or an empty string.\r\n */\r\n getAddressLine2(): string {\r\n return this.addressLine2;\r\n }\r\n\r\n /**\r\n * Gets the city name.\r\n * @returns The city.\r\n */\r\n getCity(): string {\r\n return this.city;\r\n }\r\n\r\n /**\r\n * Gets the postal code (e.g., ZIP code).\r\n * @returns The postal code.\r\n */\r\n getPostalCode(): string {\r\n return this.postalCode;\r\n }\r\n\r\n /**\r\n * Gets the state, province, or region.\r\n * @returns The state.\r\n */\r\n getState(): string {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the country name or code.\r\n * @returns The country.\r\n */\r\n getCountry(): string {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Checks if this address is designated as a billing address.\r\n * @returns True if it's a billing address, false otherwise.\r\n */\r\n getIsBillingAddress(): boolean {\r\n return this.isBillingAddress;\r\n }\r\n\r\n /**\r\n * Checks if this address is designated as a shipping address.\r\n * @returns True if it's a shipping address, false otherwise.\r\n */\r\n getIsShippingAddress(): boolean {\r\n return this.isShippingAddress;\r\n }\r\n\r\n /**\r\n * Determines the type of the address based on its billing and shipping flags.\r\n * @returns The AddressType enum value representing the address's role.\r\n */\r\n getAddressType(): AddressType {\r\n if (this.isBillingAddress && this.isShippingAddress) {\r\n return AddressType.BILLING_AND_SHIPPING;\r\n } else if (this.isBillingAddress) {\r\n return AddressType.BILLING;\r\n } else if (this.isShippingAddress) {\r\n return AddressType.SHIPPING;\r\n } else {\r\n return AddressType.NONE;\r\n }\r\n }\r\n\r\n /**\r\n * Static method to check if a given AddressType includes shipping.\r\n * @param addressType - The address type to check.\r\n * @returns True if the type is SHIPPING or BILLING_AND_SHIPPING.\r\n */\r\n static checkIfShippingAddress(addressType: AddressType): boolean {\r\n return addressType === AddressType.SHIPPING || addressType === AddressType.BILLING_AND_SHIPPING;\r\n }\r\n\r\n /**\r\n * Static method to check if a given AddressType includes billing.\r\n * @param addressType - The address type to check.\r\n * @returns True if the type is BILLING or BILLING_AND_SHIPPING.\r\n */\r\n static checkIfBillingAddress(addressType: AddressType): boolean {\r\n return addressType === AddressType.BILLING || addressType === AddressType.BILLING_AND_SHIPPING;\r\n }\r\n}","export enum ImageResolution {\r\n THUMBNAIL = 'thumbnail',\r\n SMALL = 'small',\r\n MEDIUM = 'medium',\r\n LARGE = 'large',\r\n ORIGINAL = 'original',\r\n}\r\n\r\nexport type ImageInfoAttribute = {\r\n sources: { [key in ImageResolution]?: string } & { original: string };\r\n alt?: string;\r\n order?: number;\r\n label?: string;\r\n};\r\n\r\nexport type ImageInfoData = ImageInfoAttribute;\r\n\r\n/**\r\n * Represents and manages structured image data, including multiple resolutions.\r\n */\r\nexport default class ImageInfoModel {\r\n protected sources: { [key in ImageResolution]?: string } & { original: string };\r\n protected alt?: string;\r\n protected order?: number;\r\n protected label?: string;\r\n\r\n /**\r\n * Creates an instance of ImageInfoModel.\r\n * @param data - The initial image data.\r\n */\r\n constructor(data: ImageInfoAttribute) {\r\n this.sources = { ...data.sources };\r\n this.alt = data.alt;\r\n this.order = data.order;\r\n this.label = data.label;\r\n\r\n if (!this.sources.original) {\r\n throw (\"ImageInfoModel cannot be created without an 'original' source URL.\");\r\n }\r\n }\r\n\r\n /**\r\n * Gets the sources object containing URLs for different resolutions.\r\n * Returns a copy to prevent external modification.\r\n */\r\n getSources() {\r\n return { ...this.sources };\r\n }\r\n\r\n /**\r\n * Gets the URL for a specific resolution key.\r\n * @param resolutionKey - The key of the desired resolution (e.g., 'thumbnail', 'medium').\r\n * @returns The URL string if the key doesn't exist, otherwise original image URL will be returned.\r\n */\r\n getSource(resolutionKey: ImageResolution): string{\r\n return this.sources[resolutionKey] || this.sources.original;\r\n }\r\n\r\n /**\r\n * Gets the alternative text for the image.\r\n */\r\n getAlt(): string | undefined {\r\n return this.alt;\r\n }\r\n\r\n /**\r\n * Gets the display order number for the image.\r\n */\r\n getOrder(): number | undefined {\r\n return this.order;\r\n }\r\n\r\n /**\r\n * Gets the display label or caption for the image.\r\n */\r\n getLabel(): string | undefined {\r\n return this.label;\r\n }\r\n\r\n /**\r\n * Sets the alternative text for the image.\r\n * @param altText - The new alt text.\r\n */\r\n setAlt(altText: string | undefined): void {\r\n this.alt = altText;\r\n // Potentially add logic here to trigger updates if needed\r\n }\r\n\r\n /**\r\n * Sets the display order for the image.\r\n * @param order - The new order number.\r\n */\r\n setOrder(order: number | undefined): void {\r\n this.order = order;\r\n }\r\n\r\n /**\r\n * Sets the display label for the image.\r\n * @param label - The new label text.\r\n */\r\n setLabel(label: string | undefined): void {\r\n this.label = label;\r\n }\r\n\r\n /**\r\n * Updates or adds a URL for a specific resolution.\r\n * @param resolutionKey - The key of the resolution to update/add.\r\n * @param url - The URL for the resolution. Set to undefined to remove.\r\n */\r\n setSource(resolutionKey: ImageResolution, url: string | undefined): void {\r\n if (url === undefined) {\r\n // Prevent deleting the 'original' key if it's required\r\n if (resolutionKey === 'original') {\r\n throw (\"Cannot remove the 'original' image source.\");\r\n return;\r\n }\r\n delete this.sources[resolutionKey];\r\n } else {\r\n this.sources[resolutionKey] = url;\r\n }\r\n }\r\n\r\n /**\r\n * Returns a plain JavaScript object representation of the image info.\r\n */\r\n getDetails(): ImageInfoData {\r\n return {\r\n sources: this.getSources(),\r\n alt: this.getAlt(),\r\n order: this.getOrder(),\r\n label: this.getLabel(),\r\n };\r\n }\r\n}","import { BasePrice, Color, LocaleCode, LocalizedString, PriceTier } from \"./Common\";\r\nimport { LocaleLanguageMap } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport { LocalizedProductSpecification, ProductSpecification } from \"./Product\";\r\n\r\nexport type SubItem = {\r\n size: string;\r\n quantity: number;\r\n};\r\n\r\nexport type LineItemAttributes = {\r\n id: string;\r\n productKey: string;\r\n variantId: string;\r\n name: LocalizedString;\r\n attributes: {\r\n color: Color;\r\n };\r\n specifications: LocalizedProductSpecification;\r\n primaryImage: ImageInfoData;\r\n subItems: SubItem[];\r\n basePrice: BasePrice;\r\n priceTiers: PriceTier[];\r\n}\r\n\r\nexport type LineItemData = LineItemAttributes & {\r\n totalQuantity: number;\r\n priceTotals: {\r\n subtotal: number;\r\n mrpTotal: number;\r\n };\r\n}\r\n\r\n/**\r\n * Represents a line item within a shopping cart.\r\n */\r\nexport default class LineItemModel {\r\n protected id: string;\r\n protected productKey: string;\r\n protected variantId: string;\r\n protected name: LocalizedString;\r\n protected attributes: {\r\n color: Color;\r\n };\r\n protected specifications: LocalizedProductSpecification;\r\n protected primaryImage: ImageInfoModel;\r\n protected subItems: SubItem[];\r\n protected totalQuantity: number;\r\n protected basePrice: BasePrice;\r\n protected priceTotals: {\r\n subtotal: number;\r\n mrpTotal: number;\r\n };\r\n protected priceTiers: PriceTier[];\r\n\r\n /**\r\n * Creates an instance of LineItemModel.\r\n * @param data - The initial line item attributes.\r\n */\r\n constructor(data: LineItemAttributes) {\r\n this.id = data.id;\r\n this.productKey = data.productKey;\r\n this.variantId = data.variantId;\r\n\r\n this.name = { ...data.name };\r\n this.attributes = { ...data.attributes };\r\n this.specifications = {...data.specifications };\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.subItems = data.subItems.map(item => ({ ...item }));\r\n this.basePrice = { ...data.basePrice };\r\n this.priceTiers = data.priceTiers.map(tier => ({ ...tier }));\r\n\r\n this.totalQuantity = 0;\r\n this.priceTotals = {\r\n subtotal: 0,\r\n mrpTotal: 0\r\n };\r\n\r\n this.recalculateTotalQuantity();\r\n this.recalculatePriceTotal();\r\n }\r\n\r\n /** Gets the unique identifier of the line item. */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /** Gets the product key associated with this line item. */\r\n getProductKey(): string {\r\n return this.productKey;\r\n }\r\n\r\n /** Gets the product variant ID associated with this line item. */\r\n getVariantId(): string {\r\n return this.variantId;\r\n }\r\n\r\n /**\r\n * Gets the full localized product name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the product name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if(locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n\r\n /** Gets the variant attributes. */\r\n getAttributes(): { color: Color } {\r\n return { ...this.attributes };\r\n }\r\n\r\n /**\r\n * Gets the full localized product specifications object.\r\n * @returns Product Specifications\r\n */\r\n getSpecifications(): LocalizedProductSpecification\r\n /**\r\n * Gets the product specifications for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The ProductSpecification object for the specified locale, or undefined if not found.\r\n */\r\n getSpecifications(locale: LocaleCode): ProductSpecification | undefined\r\n getSpecifications(locale?: LocaleCode): LocalizedProductSpecification | ProductSpecification | undefined {\r\n if(locale){\r\n return this.specifications[locale] ?? this.specifications[LocaleLanguageMap[locale]] ?? this.specifications.en;\r\n } else {\r\n return JSON.parse(JSON.stringify(this.specifications));\r\n }\r\n }\r\n\r\n /** Gets the image information model for this line item. */\r\n getImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /** Gets the sub-items (size/quantity breakdown). */\r\n getSubItems(): SubItem[] {\r\n return this.subItems.map(item => ({ ...item }));\r\n }\r\n\r\n /** Gets the total quantity for this line item across all sub-items. */\r\n getTotalQuantity(): number {\r\n return this.totalQuantity;\r\n }\r\n\r\n /** Gets the base price for a single unit. */\r\n getBasePrice(): BasePrice {\r\n return { ...this.basePrice };\r\n }\r\n\r\n /** Gets the calculated price details (subtotal, mrpTotal) for this line item. */\r\n getPriceTotals(): { subtotal: number; mrpTotal: number } {\r\n return { ...this.priceTotals };\r\n }\r\n\r\n /** Gets the applicable price tiers for this product variant. */\r\n getPriceTiers(): PriceTier[] {\r\n return this.priceTiers.map(tier => ({ ...tier }));\r\n }\r\n\r\n /**\r\n * Recalculates the total quantity based on the quantities in subItems.\r\n */\r\n protected recalculateTotalQuantity(): void {\r\n this.totalQuantity = this.subItems.reduce((sum, item) => sum + item.quantity, 0);\r\n }\r\n\r\n /**\r\n * Recalculates the line item's price (subtotal and mrpTotal)\r\n * based on total quantity, base price, and applicable price tiers.\r\n */\r\n protected recalculatePriceTotal(): void {\r\n const quantity = this.totalQuantity;\r\n let unitPrice = this.basePrice.unitPrice;\r\n\r\n let applicableTier = null;\r\n for (const tier of this.priceTiers.sort((a, b) => b.minQuantity - a.minQuantity)) { \r\n if (quantity >= tier.minQuantity) {\r\n applicableTier = tier;\r\n break;\r\n }\r\n }\r\n\r\n if (applicableTier) {\r\n unitPrice = applicableTier.unitPrice;\r\n }\r\n\r\n // Calculate totals\r\n this.priceTotals.mrpTotal = this.basePrice.unitPrice * quantity;\r\n this.priceTotals.subtotal = unitPrice * quantity;\r\n }\r\n\r\n\r\n /**\r\n * Gets a plain data object representing the line item's details.\r\n * @returns LineItemData.\r\n */\r\n getDetails(): LineItemData {\r\n return {\r\n id: this.getId(),\r\n productKey: this.getProductKey(),\r\n variantId: this.getVariantId(),\r\n name: this.getName(),\r\n attributes: this.getAttributes(),\r\n specifications: this.getSpecifications(),\r\n primaryImage: this.getImage().getDetails(),\r\n subItems: this.getSubItems(),\r\n totalQuantity: this.getTotalQuantity(),\r\n basePrice: this.getBasePrice(),\r\n priceTotals: this.getPriceTotals(),\r\n priceTiers: this.getPriceTiers(),\r\n };\r\n }\r\n \r\n /**\r\n * Adds or updates sub-items (e.g., sizes with quantities) to the line item.\r\n * If a sub-item with the same size already exists, its quantity is either\r\n * updated by adding the new quantity or replaced entirely, based on the `addQuantity` flag.\r\n * Sub-items with a resulting quantity of 0 are removed.\r\n * Recalculates total quantity and price totals afterwards.\r\n *\r\n * @param subItems - An array of `SubItem` objects to add or update.\r\n * @param addQuantity - If true, adds the quantity from `subItem` to the existing quantity.\r\n * If false, replaces the existing quantity with the one from `subItem`.\r\n */\r\n addSubItems(subItems: SubItem[], addQuantity: boolean): void {\r\n subItems.forEach(subItem => {\r\n const existingSubItem = this.subItems.find(item => item.size === subItem.size);\r\n if (existingSubItem) {\r\n existingSubItem.quantity = addQuantity ? existingSubItem.quantity + subItem.quantity : subItem.quantity;\r\n } else {\r\n this.subItems.push(subItem);\r\n }\r\n })\r\n this.subItems = this.subItems.filter(sub => sub.quantity);\r\n\r\n this.recalculateTotalQuantity();\r\n this.recalculatePriceTotal();\r\n }\r\n\r\n /**\r\n * Resets the line item's properties to their default empty or initial state.\r\n * Useful for clearing out line item data without creating a new instance.\r\n * Recalculates total quantity and price totals afterwards (which will be zero).\r\n */\r\n clearLineItem(): void {\r\n this.id = '';\r\n this.productKey = '';\r\n this.variantId = '';\r\n this.name = { en: '' };\r\n this.attributes = { color: { name: '', hex: '' } };\r\n this.primaryImage = new ImageInfoModel({ sources: { original: '' } });\r\n this.subItems = [];\r\n this.recalculateTotalQuantity();\r\n this.recalculatePriceTotal();\r\n }\r\n}","import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport AddressModel, { AddressData } from \"./Address\";\r\nimport LineItemModel, { LineItemData } from \"./LineItem\";\r\nimport { CountryCode, CurrencyCode, LocaleCode, ShippingDetails } from \"./Common\";\r\nimport PriceModel from \"./Price\";\r\nimport CouponModel, { CouponCategory, CouponData, CouponDiscountMethod } from \"./Coupon\";\r\n\r\nexport type ShoppingContainerTotal = {\r\n shipping?: number;\r\n effectiveShipping?: number;\r\n subtotal?: number;\r\n mrpTotal?: number;\r\n couponTotal?: { [key: string]: number };\r\n grandTotal?: number;\r\n}\r\n\r\nexport type BaseShoppingContainerAttributes = BaseAttributes & {\r\n id: string;\r\n customerId?: string;\r\n customerEmail?: string;\r\n anonymousId?: string;\r\n lineItems: LineItemData[];\r\n shippingDetails: ShippingDetails | null;\r\n shippingAddress?: AddressData | null;\r\n billingAddress?: AddressData | null;\r\n coupons?: CouponData[];\r\n total?: ShoppingContainerTotal;\r\n country: CountryCode;\r\n currency: CurrencyCode;\r\n locale: LocaleCode;\r\n};\r\n\r\nexport type BaseShoppingContainerData = Omit<BaseShoppingContainerAttributes, 'coupons' | 'total'>\r\n& BaseData\r\n& {\r\n coupons: CouponData[],\r\n total: {\r\n shipping: number,\r\n effectiveShipping: number,\r\n subtotal: number,\r\n mrpTotal: number,\r\n couponTotal: { [key: string]: number },\r\n grandTotal: number\r\n };\r\n };\r\n\r\n\r\n/**\r\n * Abstract base class for shopping-related containers like carts and orders.\r\n * Manages common elements such as line items, addresses, coupons, and totals.\r\n */\r\nexport default abstract class BaseShoppingContainerModel extends BaseModel {\r\n protected id: string;\r\n protected customerId?: string;\r\n protected customerEmail?: string;\r\n protected anonymousId?: string;\r\n protected lineItems: LineItemModel[];\r\n protected shippingDetails: ShippingDetails | null;\r\n protected shippingAddress: AddressModel | null;\r\n protected billingAddress: AddressModel | null;\r\n\r\n // CouponsCodes\r\n protected coupons: CouponModel[];\r\n\r\n // Cart Totals\r\n protected total: {\r\n shipping: number;\r\n effectiveShipping: number;\r\n subtotal: number;\r\n mrpTotal: number;\r\n couponTotal: { [key: string]: number; };\r\n grandTotal: number;\r\n };\r\n\r\n protected country: CountryCode;\r\n protected currency: CurrencyCode;\r\n protected locale: LocaleCode;\r\n\r\n /**\r\n * Creates an instance of BaseShoppingContainerModel.\r\n * Initializes common properties and calculates initial base totals.\r\n * @param data - The initial attributes for the shopping container.\r\n * @param date - Optional date object for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: BaseShoppingContainerAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.customerId = data.customerId;\r\n this.customerEmail = data.customerEmail;\r\n this.anonymousId = data.anonymousId;\r\n this.country = data.country;\r\n this.currency = data.currency;\r\n this.locale = data.locale;\r\n this.lineItems = (data.lineItems ?? []).map(item => new LineItemModel(item));\r\n this.billingAddress = data.billingAddress ? new AddressModel(data.billingAddress, date) : null;\r\n this.shippingAddress = data.shippingAddress ? new AddressModel(data.shippingAddress, date) : null;\r\n this.coupons = (data.coupons || []).map(coupon => new CouponModel(coupon));\r\n\r\n this.shippingDetails = data.shippingDetails ? { ...data.shippingDetails } : null;\r\n\r\n this.total = {\r\n shipping: data.total?.shipping || 0,\r\n effectiveShipping: data.total?.effectiveShipping ?? data.total?.shipping ?? 0,\r\n subtotal: data.total?.subtotal || 0,\r\n mrpTotal: data.total?.mrpTotal || 0,\r\n couponTotal: data.total?.couponTotal || {},\r\n grandTotal: data.total?.grandTotal || 0,\r\n };\r\n }\r\n\r\n /**\r\n * Recalculates the subtotal and mrpTotal based on the current line items.\r\n * Uses PriceModel for rounding based on the country.\r\n */\r\n protected recalculateBaseTotals(): void {\r\n this.total.subtotal = PriceModel.getRoundedPrice(this.lineItems.reduce((sum, item) => sum + item.getPriceTotals().subtotal, 0), this.country);\r\n this.total.mrpTotal = PriceModel.getRoundedPrice(this.lineItems.reduce((sum, item) => sum + item.getPriceTotals().mrpTotal, 0), this.country);\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for this shopping container (cart ID or order ID).\r\n * @returns The ID string.\r\n */\r\n public getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the customer ID associated with this container, if available.\r\n * @returns The customer ID string, or undefined.\r\n */\r\n public getCustomerId(): string | undefined {\r\n return this.customerId;\r\n }\r\n\r\n /**\r\n * Gets the customer email associated with this container, if available.\r\n * @returns The customer email string, or undefined.\r\n */\r\n public getCustomerEmail(): string | undefined {\r\n return this.customerEmail;\r\n }\r\n\r\n /**\r\n * Gets the anonymous user ID associated with this container, if available.\r\n * @returns The anonymous ID string, or undefined.\r\n */\r\n public getAnonymousId(): string | undefined {\r\n return this.anonymousId;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the line items in the container.\r\n * Each item is a new LineItemModel instance created from the original's details.\r\n * @returns An array of LineItemModel instances.\r\n */\r\n public getLineItems(): LineItemModel[] {\r\n // Return new instances to prevent modification of internal state\r\n return this.lineItems.map(item => new LineItemModel(item.getDetails()));\r\n }\r\n\r\n /**\r\n * Gets current number of line items in the container\r\n * @returns \r\n */\r\n public getLineItemsCount(): number {\r\n return this.lineItems.length;\r\n }\r\n\r\n /**\r\n * Gets a copy of the shipping details associated with the container.\r\n * @returns A ShippingDetails object, or null if none are set.\r\n */\r\n public getShippingDetails(): ShippingDetails | null {\r\n // Return a shallow copy if details exist\r\n return this.shippingDetails ? { ...this.shippingDetails } : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the shipping address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no shipping address is set.\r\n */\r\n public getShippingAddress(): AddressModel | null {\r\n return this.shippingAddress ? new AddressModel(this.shippingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Checks if a shipping address is associated with this container.\r\n * @returns True if a shipping address is set, false otherwise.\r\n */\r\n public hasShippingAddress(): boolean {\r\n return !!this.shippingAddress;\r\n }\r\n\r\n /**\r\n * Checks if a billing address is associated with this container.\r\n * @returns True if a billing address is set, false otherwise.\r\n */\r\n public hasBillingAddress(): boolean {\r\n return !!this.billingAddress;\r\n }\r\n \r\n /**\r\n * Gets a defensive copy of the billing address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no billing address is set.\r\n */\r\n public getBillingAddress(): AddressModel | null {\r\n return this.billingAddress ? new AddressModel(this.billingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the coupons applied to the container.\r\n * Each item is a new CouponModel instance created from the original's details.\r\n * @returns An array of CouponModel instances.\r\n */\r\n public getCoupons(): CouponModel[] {\r\n return this.coupons.map(coupon => new CouponModel(coupon.getDetails()));\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this container.\r\n * @returns The CountryCode enum value.\r\n */\r\n public getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Gets the currency code associated with this container.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Gets the locale code associated with this container.\r\n * @returns The LocaleCode enum value.\r\n */\r\n public getLocale(): LocaleCode {\r\n return this.locale;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the calculated totals for the container.\r\n * @returns An object containing shipping, subtotal, coupon, and grand totals.\r\n */\r\n public getTotal() {\r\n return { ...this.total, couponTotal: { ...this.total.couponTotal } };\r\n }\r\n\r\n /**\r\n * Calculates the discount value for a given coupon based on the current container state.\r\n * Returns 0 if the coupon is invalid, expired, or not applicable based on cart value or target category.\r\n * @param coupon - The CouponModel instance to evaluate.\r\n * @param checkExpiry - Whether to check the coupon's expiry status.\r\n * @returns The calculated discount amount (rounded according to country rules).\r\n */\r\n public calculateApplicableCouponDiscount(coupon: CouponModel, checkExpiry: boolean = true): number {\r\n // 1. Basic validation (active)\r\n if (checkExpiry && !coupon.isActive()) {\r\n return 0;\r\n }\r\n\r\n // 2. Check regional requirements (min cart value, max discount)\r\n const minCartValueReq = coupon.getMinCartValue(this.country);\r\n const maxCartDiscountCap = coupon.getMaxCartDiscount(this.country);\r\n\r\n // Ensure minCartValueReq exists and subtotal meets the requirement\r\n if (!minCartValueReq || this.total.subtotal < minCartValueReq.price) {\r\n return 0;\r\n }\r\n\r\n // Ensure maxCartDiscountCap exists and is non-negative\r\n if (!maxCartDiscountCap || maxCartDiscountCap.price < 0) {\r\n return 0;\r\n }\r\n\r\n // 3. Calculate potential discount based on method and category\r\n const couponCategory = coupon.getCategory();\r\n const discountMethod = coupon.getDiscountMethod();\r\n let potentialDiscount = 0;\r\n // Determine the value the coupon applies to (shipping cost or subtotal)\r\n const targetValue = couponCategory === CouponCategory.SHIPPING ? this.total.shipping : this.total.subtotal;\r\n\r\n // No discount if the target value is zero or less\r\n if (targetValue <= 0) return 0;\r\n\r\n switch (discountMethod) {\r\n case CouponDiscountMethod.FLAT:\r\n // Flat discount is capped by the target value itself and the max discount cap\r\n const flatAmount = maxCartDiscountCap?.price ?? 0; // Use cap as the flat amount source? Or coupon.value? Needs clarification. Assuming cap IS the flat amount here.\r\n potentialDiscount = Math.min(targetValue, flatAmount);\r\n break;\r\n case CouponDiscountMethod.PERCENTAGE:\r\n // Calculate percentage discount based on the target value\r\n potentialDiscount = targetValue * (coupon.getPercentageValue() / 100);\r\n break;\r\n default:\r\n // Unknown discount method\r\n return 0;\r\n }\r\n\r\n // 4. Apply maximum discount cap to the calculated potential discount\r\n const finalDiscount = Math.min(potentialDiscount, maxCartDiscountCap.price);\r\n\r\n // 5. Round the final discount, ensuring it's not negative\r\n return PriceModel.getRoundedPrice(Math.max(0, finalDiscount), this.country);\r\n }\r\n\r\n /**\r\n * Recalculates the `couponTotal` map based on currently applied coupons.\r\n * Iterates through coupons, calculates their applicable discount, and stores it.\r\n * @param checkExpiry - Whether to check the expiry status of coupons.\r\n * @returns The total discount amount from all valid and applicable coupons (rounded).\r\n */\r\n public recalculateCouponTotals(checkExpiry: boolean = true): number {\r\n this.total.couponTotal = {};\r\n let totalDiscount = 0;\r\n\r\n this.coupons.forEach(coupon => {\r\n const discount = this.calculateApplicableCouponDiscount(coupon, checkExpiry);\r\n if (discount > 0) {\r\n this.total.couponTotal[coupon.getCode()] = discount; // Store per-coupon discount\r\n totalDiscount += discount; // Accumulate total discount\r\n }\r\n });\r\n // Return the rounded total discount\r\n return PriceModel.getRoundedPrice(totalDiscount, this.country);\r\n }\r\n\r\n\r\n /**\r\n * Gets a plain data object representing the shopping container's current state.\r\n * Includes details from the base model and specific container properties.\r\n * @returns BaseShoppingContainerData object suitable for serialization or API responses.\r\n */\r\n getDetails(): BaseShoppingContainerData {\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n customerId: this.getCustomerId(),\r\n customerEmail: this.getCustomerEmail(),\r\n anonymousId: this.getAnonymousId(),\r\n lineItems: this.getLineItems().map(item => item.getDetails()),\r\n shippingDetails: this.getShippingDetails(),\r\n shippingAddress: this.getShippingAddress()?.getDetails() || null,\r\n billingAddress: this.getBillingAddress()?.getDetails() || null,\r\n coupons: this.getCoupons().map(coupon => coupon.getDetails()),\r\n total: this.getTotal(),\r\n country: this.getCountry(),\r\n currency: this.getCurrency(),\r\n locale: this.getLocale(),\r\n }\r\n };\r\n}\r\n","import { CouponCategory } from \"./Coupon\";\r\nimport LineItemModel from \"./LineItem\";\r\nimport PriceModel from \"./Price\";\r\nimport BaseShoppingContainerModel, { BaseShoppingContainerAttributes, BaseShoppingContainerData } from \"./ShoppingContainer\";\r\n\r\nexport enum CartState {\r\n ACTIVE = \"ACTIVE\",\r\n FROZEN = \"FROZEN\",\r\n MERGED = \"MERGED\",\r\n ORDERED = \"ORDERED\"\r\n}\r\n\r\nexport class LineItemNotFoundError extends Error {\r\n constructor(lineItemId: string) {\r\n super(`Line item with ID '${lineItemId}' not found in the cart.`);\r\n this.name = 'LineItemNotFoundError';\r\n }\r\n}\r\n\r\n/**\r\n * Input attributes for creating or updating a CartModel.\r\n */\r\nexport type CartAttributes = BaseShoppingContainerAttributes & { \r\n state: CartState;\r\n expireAt: number;\r\n};\r\n\r\nexport type CartData = BaseShoppingContainerData & {\r\n state: CartState;\r\n expireAt: number;\r\n};\r\n\r\nexport type CartConfig = {\r\n expiresAtInSeconds: number;\r\n}\r\n\r\nexport const DEFAULT_CART_CONFIG: CartConfig = {\r\n expiresAtInSeconds: 120 * 24 * 60 * 60\r\n}\r\n\r\nexport default class CartModel extends BaseShoppingContainerModel {\r\n protected state: CartState;\r\n protected expireAt: number;\r\n protected config: CartConfig;\r\n\r\n constructor(data: CartAttributes, date: Date = new Date(), config: CartConfig = DEFAULT_CART_CONFIG) {\r\n super(data, date);\r\n this.state = data.state;\r\n this.expireAt = data.expireAt && typeof data.expireAt === 'number' ? data.expireAt : Math.floor(date.getTime()/1000) + config.expiresAtInSeconds;\r\n this.config = config;\r\n \r\n this.updateCartTotals();\r\n }\r\n\r\n public getState(): CartState {\r\n return this.state;\r\n }\r\n\r\n public getExpireAt(): number {\r\n return this.expireAt;\r\n }\r\n\r\n public isActive(): boolean {\r\n const nowSeconds = Math.ceil(Date.now() / 1000);\r\n return this.state === CartState.ACTIVE && (this.expireAt > nowSeconds);\r\n }\r\n\r\n /**\r\n * Recalculates all container totals (subtotal, mrpTotal, coupons, shipping, grandTotal).\r\n * Should be called whenever line items, coupons, or base shipping cost change.\r\n */\r\n public updateCartTotals(): void {\r\n // 1. Calculate line item totals (subtotal, mrpTotal)\r\n this.recalculateBaseTotals();\r\n\r\n // 2. Calculate total coupon discount and update the per-coupon discount map\r\n this.recalculateCouponTotals(); // This updates this.total.couponTotal\r\n\r\n // 3. Calculate effective shipping cost after applying shipping-specific coupons\r\n const shippingCouponDiscount = this.coupons\r\n .filter(c => c.getCategory() === CouponCategory.SHIPPING)\r\n .reduce((sum, c) => sum + (this.total.couponTotal[c.getCode()] ?? 0), 0);\r\n this.total.effectiveShipping = PriceModel.getRoundedPrice(Math.max(0, this.total.shipping - shippingCouponDiscount), this.country);\r\n\r\n // 4. Calculate total discount from non-shipping coupons\r\n const nonShippingCouponDiscount = this.coupons\r\n .filter(c => c.getCategory() !== CouponCategory.SHIPPING)\r\n .reduce((sum, c) => sum + (this.total.couponTotal[c.getCode()] ?? 0), 0);\r\n\r\n // 5. Calculate final grand total: (subtotal + effective shipping) - non-shipping discounts\r\n const grossTotal = this.total.subtotal + this.total.effectiveShipping;\r\n this.total.grandTotal = PriceModel.getRoundedPrice(Math.max(0, grossTotal - nonShippingCouponDiscount), this.country);\r\n }\r\n \r\n public clearCartItems() {\r\n this.lineItems = [];\r\n this.coupons = [];\r\n this.updateCartTotals();\r\n }\r\n\r\n /**\r\n * Adds a new line item or updates the quantity of an existing one.\r\n * @param newLineItem The LineItemModel to add.\r\n * @returns The index of the added/updated line item in the internal array.\r\n */\r\n public addLineItem (newLineItem: LineItemModel) {\r\n const productKey = newLineItem.getProductKey();\r\n const variantId = newLineItem.getVariantId();\r\n let index = this.lineItems.findIndex(\r\n (item) => item.getProductKey() === productKey && item.getVariantId() === variantId\r\n );\r\n\r\n if(index >= 0){\r\n this.lineItems[index].addSubItems(newLineItem.getSubItems(), true);\r\n } else {\r\n this.lineItems.push(newLineItem);\r\n }\r\n\r\n this.updateCartTotals();\r\n return index >= 0 ? index : this.lineItems.length - 1;\r\n }\r\n\r\n /**\r\n * Updates the quantity for a specific size within a line item.\r\n * @param lineItemId The ID of the LineItemModel to update.\r\n * @param size The size identifier within the line item.\r\n * @param quantity The new quantity for the size (0 to remove).\r\n * @returns The index of the updated line item.\r\n * @throws {Error} If the line item is not found.\r\n */\r\n public updateLineItem (lineItemId: string, size: string, quantity: number) {\r\n const lineItems = this.lineItems;\r\n let index = lineItems.findIndex((item) => item.getId() === lineItemId);\r\n \r\n if(index < 0){\r\n throw new LineItemNotFoundError(lineItemId);\r\n }\r\n\r\n lineItems[index].addSubItems([{ size, quantity }], false);\r\n this.updateCartTotals();\r\n\r\n return index;\r\n }\r\n\r\n /**\r\n * Removes a line item completely from the cart.\r\n * @param lineItemId The ID of the LineItemModel to remove.\r\n * @returns The index the item previously occupied.\r\n * @throws {Error} If the line item is not found.\r\n */\r\n public removeLineItem (lineItemId: string) {\r\n const lineItems = this.lineItems;\r\n const index = lineItems.findIndex((item) => item.getId() === lineItemId);\r\n\r\n if(index < 0){\r\n throw new LineItemNotFoundError(lineItemId);\r\n }\r\n\r\n this.lineItems.splice(index, 1);\r\n this.updateCartTotals();\r\n\r\n return index;\r\n }\r\n\r\n getDetails(): CartData {\r\n return {\r\n ...super.getDetails(),\r\n state: this.getState(),\r\n expireAt: this.getExpireAt(),\r\n }\r\n }\r\n}\r\n","import AddressModel, { AddressData } from \"./Address\";\r\nimport { LineItemNotFoundError } from \"./Cart\";\r\nimport { ISODateTime } from \"./Common\";\r\nimport { CouponCategory } from \"./Coupon\";\r\nimport { PaymentStatus } from \"./Payment\";\r\nimport PriceModel from \"./Price\";\r\nimport BaseShoppingContainerModel, { BaseShoppingContainerAttributes, BaseShoppingContainerData, ShoppingContainerTotal } from \"./ShoppingContainer\";\r\n\r\n/**\r\n * PLACED: Order created, awaiting payment.\r\n * PENDING_PAYMENT: Waiting for payment confirmation.\r\n * PROCESSING: Payment received, order is being fulfilled. Stays here until all line items reach a final state.\r\n * CANCELLED: All line items are cancelled, or order is cancelled before fulfillment.\r\n * COMPLETED: All line items are delivered, returned, or refunded.\r\n */\r\nexport enum OrderState {\r\n PLACED = \"PLACED\",\r\n PENDING_PAYMENT = \"PENDING_PAYMENT\",\r\n PROCESSING = \"PROCESSING\",\r\n CANCELLED = \"CANCELLED\",\r\n COMPLETED = \"COMPLETED\"\r\n}\r\n\r\n/**\r\n * OrderLineItemState\r\n * \r\n * INITIAL: Item added to order, not yet processed.\r\n * PROCESSING: Item is being prepared for shipment.\r\n * SHIPPED: Item dispatched to customer.\r\n * DELIVERED: Item delivered to customer.\r\n * CANCELLED: Item cancelled before shipment or delivery.\r\n * RETURN_REQUESTED: Customer requests to return item.\r\n * RETURNED: Item received back from customer.\r\n * REFUND_INITIATED: Refund initiated for item.\r\n * REFUNDED: Refund processed for item.\r\n * ON_HOLD: Item is paused due to payment, inventory, or other issues.\r\n */\r\nexport enum OrderLineItemState {\r\n INITIAL = \"INITIAL\",\r\n PROCESSING = \"PROCESSING\",\r\n SHIPPED = \"SHIPPED\",\r\n DELIVERED = \"DELIVERED\",\r\n CANCELLED = \"CANCELLED\",\r\n RETURN_REQUESTED = \"RETURN_REQUESTED\",\r\n RETURNED = \"RETURNED\",\r\n REFUND_INITIATED = \"REFUND_INITIATED\",\r\n REFUNDED = \"REFUNDED\",\r\n ON_HOLD = \"ON_HOLD\",\r\n}\r\n\r\n\r\nexport type OrderLineItemStateMap = Record<string, {\r\n state:OrderLineItemState;\r\n reason?: string;\r\n transitionAt: ISODateTime;\r\n}>;\r\n\r\n/**\r\n * Input attributes for creating an OrderModel.\r\n * Extends CartAttributes but requires/adds order-specific fields.\r\n */\r\nexport type OrderAttributes = Omit<BaseShoppingContainerAttributes, 'anonymousId'> & {\r\n customerId: string;\r\n customerEmail: string;\r\n shippingAddress: AddressData;\r\n billingAddress: AddressData;\r\n anonymousId?: string;\r\n total: Required<ShoppingContainerTotal>;\r\n orderNumber: string;\r\n cartId: string;\r\n paymentStatus: PaymentStatus;\r\n holdReason?: string;\r\n state: OrderState;\r\n lineItemStateMap?: OrderLineItemStateMap;\r\n};\r\n\r\n/**\r\n * Output data structure for an OrderModel.\r\n */\r\nexport type OrderData = BaseShoppingContainerData & OrderAttributes & {\r\n holdReason: string;\r\n lineItemStateMap: OrderLineItemStateMap;\r\n};\r\n\r\n\r\nexport default class OrderModel extends BaseShoppingContainerModel {\r\n protected orderNumber: string;\r\n protected cartId: string;\r\n protected paymentStatus: PaymentStatus;\r\n protected holdReason: string;\r\n protected state: OrderState;\r\n protected lineItemStateMap: OrderLineItemStateMap;\r\n\r\n /**\r\n * Creates an instance of OrderModel.\r\n * @param data - The initial order attributes, including cart data.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n * @param config - Optional cart configuration (might be less relevant for orders).\r\n */\r\n constructor(data: OrderAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.orderNumber = data.orderNumber;\r\n this.cartId = data.cartId;\r\n this.paymentStatus = data.paymentStatus;\r\n this.holdReason = data.holdReason || '';\r\n this.state = data.state;\r\n \r\n const newLineItemStateMap: OrderLineItemStateMap = {};\r\n data.lineItems.forEach(item => {\r\n const currentStateMap = data.lineItemStateMap?.[item.id];;\r\n \r\n newLineItemStateMap[item.id] = {\r\n state: currentStateMap?.state || OrderLineItemState.INITIAL,\r\n reason: currentStateMap?.reason || '',\r\n transitionAt: currentStateMap?.transitionAt || this.createdAt,\r\n };\r\n });\r\n this.lineItemStateMap = newLineItemStateMap;\r\n\r\n this.recalculateOrderBaseTotals();\r\n }\r\n\r\n /**\r\n * Recalculates the subtotal and mrpTotal based on the current line items.\r\n * Uses PriceModel for rounding based on the country.\r\n */\r\n protected recalculateOrderBaseTotals(): void {\r\n const filteredLineItems = this.lineItems.filter(item =>\r\n this.lineItemStateMap[item.getId()]?.state !== OrderLineItemState.CANCELLED\r\n );\r\n this.total.subtotal = PriceModel.getRoundedPrice(filteredLineItems\r\n .reduce((sum, item) => sum + item.getPriceTotals().subtotal, 0), this.country);\r\n\r\n this.total.mrpTotal = PriceModel.getRoundedPrice(filteredLineItems.reduce((sum, item) => sum + item.getPriceTotals().mrpTotal, 0), this.country);\r\n }\r\n\r\n public updateOrderTotals(): void {\r\n // 1. Calculate line item totals (subtotal, mrpTotal)\r\n this.recalculateOrderBaseTotals();\r\n\r\n // 2. Calculate total coupon discount and update the per-coupon discount map\r\n this.recalculateCouponTotals(false);\r\n\r\n // 3. Calculate effective shipping cost after applying shipping-specific coupons\r\n const shippingCouponDiscount = this.coupons\r\n .filter(c => c.getCategory() === CouponCategory.SHIPPING)\r\n .reduce((sum, c) => sum + (this.total.couponTotal[c.getCode()] ?? 0), 0);\r\n this.total.effectiveShipping = PriceModel.getRoundedPrice(Math.max(0, this.total.shipping - shippingCouponDiscount), this.country);\r\n\r\n // 4. Calculate total discount from non-shipping coupons\r\n const nonShippingCouponDiscount = this.coupons\r\n .filter(c => c.getCategory() !== CouponCategory.SHIPPING)\r\n .reduce((sum, c) => sum + (this.total.couponTotal[c.getCode()] ?? 0), 0);\r\n\r\n // 5. Calculate final grand total: (subtotal + effective shipping) - non-shipping discounts\r\n const grossTotal = this.total.subtotal + this.total.effectiveShipping;\r\n this.total.grandTotal = PriceModel.getRoundedPrice(Math.max(0, grossTotal - nonShippingCouponDiscount), this.country);\r\n }\r\n\r\n /**\r\n * Gets the customer ID associated with this order.\r\n * Overrides the base method to guarantee a non-undefined return type for orders.\r\n * @returns The customer ID string.\r\n */\r\n public getCustomerId(): string {\r\n return this.customerId as string;\r\n }\r\n\r\n /**\r\n * Gets the customer email associated with this order.\r\n * Overrides the base method to guarantee a non-undefined return type for orders.\r\n * @returns The customer email string.\r\n */\r\n public getCustomerEmail(): string {\r\n return this.customerEmail as string;\r\n }\r\n\r\n /**\r\n * Gets the shipping address associated with the order.\r\n * Overrides the base method to guarantee a non-null return type for orders.\r\n * @returns An AddressModel instance for the shipping address.\r\n */\r\n public getShippingAddress(): AddressModel {\r\n return this.shippingAddress as AddressModel;\r\n }\r\n\r\n /**\r\n * Gets the billing address associated with the order.\r\n * Overrides the base method to guarantee a non-null return type for orders.\r\n * @returns An AddressModel instance for the billing address.\r\n */\r\n public getBillingAddress(): AddressModel {\r\n return this.billingAddress as AddressModel;\r\n }\r\n\r\n\r\n /**\r\n * Gets the user-facing order number.\r\n * @returns The order number string.\r\n */\r\n public getOrderNumber(): string {\r\n return this.orderNumber;\r\n }\r\n\r\n /**\r\n * Gets the ID of the cart from which this order was created.\r\n * @returns The cart ID string.\r\n */\r\n public getCartId(): string {\r\n return this.cartId;\r\n }\r\n\r\n /**\r\n * Gets the current payment status of the order.\r\n * @returns The PaymentStatus enum value.\r\n */\r\n public getPaymentStatus(): PaymentStatus {\r\n return this.paymentStatus;\r\n }\r\n\r\n /**\r\n * Gets the reason why the order might be on hold, if any.\r\n * @returns The hold reason string (empty if not on hold or no reason specified).\r\n */\r\n public getHoldReason(): string {\r\n return this.holdReason;\r\n }\r\n\r\n /**\r\n * Gets the current state of the order (e.g., PROCESSING, SHIPPED).\r\n * @returns The OrderState enum value.\r\n */\r\n public getState(): OrderState {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the map tracking the state of each line item in the order.\r\n * The keys are line item IDs, and the values contain the state, reason, and transition timestamp.\r\n * @returns The OrderLineItemStateMap.\r\n */\r\n public getLineItemsStateMap(): OrderLineItemStateMap {\r\n return { ...this.lineItemStateMap };\r\n }\r\n\r\n /**\r\n * Gets the current state of a specific line item within the order.\r\n * @param lineItemId - The ID of the line item whose state is requested.\r\n * @returns The OrderLineItemState enum value for the specified line item.\r\n * @throws {LineItemNotFoundError} If no line item with the given ID exists in the order's state map.\r\n */\r\n public getLineItemState(lineItemId: string): OrderLineItemState {\r\n if (!this.lineItemStateMap[lineItemId]){\r\n throw new LineItemNotFoundError(lineItemId)\r\n }\r\n return this.lineItemStateMap[lineItemId].state;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the order's current state.\r\n * Includes all cart details plus order-specific information.\r\n * @returns OrderData object suitable for serialization or API responses.\r\n */\r\n getDetails(): OrderData {\r\n return {\r\n ...super.getDetails(),\r\n orderNumber: this.getOrderNumber(),\r\n customerId: this.getCustomerId(),\r\n customerEmail: this.getCustomerEmail(),\r\n shippingAddress: this.getShippingAddress().getDetails(),\r\n billingAddress: this.getBillingAddress().getDetails(),\r\n cartId: this.getCartId(),\r\n paymentStatus: this.getPaymentStatus(),\r\n holdReason: this.getHoldReason(),\r\n state: this.getState(),\r\n lineItemStateMap: this.getLineItemsStateMap()\r\n }\r\n }\r\n}\r\n"]}
|
package/dist/Classes/Order.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {b}from'../chunk-
|
|
1
|
+
import {b}from'../chunk-WZLKQEOJ.mjs';import {a}from'../chunk-O5C6Z6AY.mjs';import'../chunk-K3AXPTGG.mjs';import'../chunk-DKI6BDWK.mjs';import {a as a$1}from'../chunk-V4H3X4PI.mjs';import'../chunk-HTJJLLGW.mjs';import'../chunk-RWBNLNQ6.mjs';import'../chunk-6PDP4ETM.mjs';import'../chunk-ATUUYYQT.mjs';var u=(e=>(e.PLACED="PLACED",e.PENDING_PAYMENT="PENDING_PAYMENT",e.PROCESSING="PROCESSING",e.CANCELLED="CANCELLED",e.COMPLETED="COMPLETED",e))(u||{}),l=(r=>(r.INITIAL="INITIAL",r.PROCESSING="PROCESSING",r.SHIPPED="SHIPPED",r.DELIVERED="DELIVERED",r.CANCELLED="CANCELLED",r.RETURN_REQUESTED="RETURN_REQUESTED",r.RETURNED="RETURNED",r.REFUND_INITIATED="REFUND_INITIATED",r.REFUNDED="REFUNDED",r.ON_HOLD="ON_HOLD",r))(l||{}),n=class extends a{orderNumber;cartId;paymentStatus;holdReason;state;lineItemStateMap;constructor(t,i=new Date){super(t,i),this.orderNumber=t.orderNumber,this.cartId=t.cartId,this.paymentStatus=t.paymentStatus,this.holdReason=t.holdReason||"",this.state=t.state;let a={};t.lineItems.forEach(s=>{let e=t.lineItemStateMap?.[s.id];a[s.id]={state:e?.state||"INITIAL",reason:e?.reason||"",transitionAt:e?.transitionAt||this.createdAt};}),this.lineItemStateMap=a,this.recalculateOrderBaseTotals();}recalculateOrderBaseTotals(){let t=this.lineItems.filter(i=>this.lineItemStateMap[i.getId()]?.state!=="CANCELLED");this.total.subtotal=a$1.getRoundedPrice(t.reduce((i,a)=>i+a.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=a$1.getRoundedPrice(t.reduce((i,a)=>i+a.getPriceTotals().mrpTotal,0),this.country);}updateOrderTotals(){this.recalculateOrderBaseTotals(),this.recalculateCouponTotals(!1);let t=this.coupons.filter(s=>s.getCategory()==="SHIPPING").reduce((s,e)=>s+(this.total.couponTotal[e.getCode()]??0),0);this.total.effectiveShipping=a$1.getRoundedPrice(Math.max(0,this.total.shipping-t),this.country);let i=this.coupons.filter(s=>s.getCategory()!=="SHIPPING").reduce((s,e)=>s+(this.total.couponTotal[e.getCode()]??0),0),a=this.total.subtotal+this.total.effectiveShipping;this.total.grandTotal=a$1.getRoundedPrice(Math.max(0,a-i),this.country);}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}getLineItemsStateMap(){return {...this.lineItemStateMap}}getLineItemState(t){if(!this.lineItemStateMap[t])throw new b(t);return this.lineItemStateMap[t].state}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(),lineItemStateMap:this.getLineItemsStateMap()}}};export{l as OrderLineItemState,u as OrderState,n as default};//# sourceMappingURL=Order.mjs.map
|
|
2
2
|
//# sourceMappingURL=Order.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/Classes/Order.ts"],"names":["OrderState","OrderLineItemState","OrderModel","BaseShoppingContainerModel","data","date","newLineItemStateMap","item","currentStateMap","PriceModel","sum","shippingCouponDiscount","c","nonShippingCouponDiscount","grossTotal","lineItemId","LineItemNotFo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xC,OAAO,IAAA,CAAK,eACd,CAOO,iBAAkC,EAAA,CACvC,OAAO,IAAA,CAAK,cACd,CAOQ,gBAAyB,CAC/B,OAAO,IAAK,CAAA,WACd,CAMO,SAAA,EAAoB,CACzB,OAAO,IAAA,CAAK,MACd,CAMO,gBAAkC,EAAA,CACvC,OAAO,IAAK,CAAA,aACd,CAMO,aAAA,EAAwB,CAC7B,OAAO,KAAK,UACd,CAMO,QAAuB,EAAA,CAC5B,OAAO,IAAA,CAAK,KACd,CAOO,oBAAA,EAA8C,CACnD,OAAO,CAAE,GAAG,KAAK,gBAAiB,CACpC,CAQO,gBAAA,CAAiBE,CAAwC,CAAA,CAC9D,GAAI,CAAC,IAAA,CAAK,gBAAiBA,CAAAA,CAAU,CACnC,CAAA,MAAM,IAAIC,CAAAA,CAAsBD,CAAU,CAAA,CAE5C,OAAO,IAAA,CAAK,gBAAiBA,CAAAA,CAAU,EAAE,KAC3C,CAOA,UAAwB,EAAA,CACtB,OAAO,CACL,GAAG,KAAM,CAAA,UAAA,EACT,CAAA,WAAA,CAAa,IAAK,CAAA,cAAA,GAClB,UAAY,CAAA,IAAA,CAAK,aAAc,EAAA,CAC/B,aAAe,CAAA,IAAA,CAAK,gBAAiB,EAAA,CACrC,eAAiB,CAAA,IAAA,CAAK,kBAAmB,EAAA,CAAE,UAAW,EAAA,CACtD,eAAgB,IAAK,CAAA,iBAAA,EAAoB,CAAA,UAAA,EACzC,CAAA,MAAA,CAAQ,KAAK,SAAU,EAAA,CACvB,aAAe,CAAA,IAAA,CAAK,gBAAiB,EAAA,CACrC,WAAY,IAAK,CAAA,aAAA,EACjB,CAAA,KAAA,CAAO,IAAK,CAAA,QAAA,EACZ,CAAA,gBAAA,CAAkB,IAAK,CAAA,oBAAA,EACzB,CACF,CACF","file":"Order.mjs","sourcesContent":["import AddressModel, { AddressData } from \"./Address\";\r\nimport { LineItemNotFoundError } from \"./Cart\";\r\nimport { ISODateTime } from \"./Common\";\r\nimport { CouponCategory } from \"./Coupon\";\r\nimport { PaymentStatus } from \"./Payment\";\r\nimport PriceModel from \"./Price\";\r\nimport BaseShoppingContainerModel, { BaseShoppingContainerAttributes, BaseShoppingContainerData, ShoppingContainerTotal } from \"./ShoppingContainer\";\r\n\r\n/**\r\n * PLACED: Order created, awaiting payment.\r\n * PENDING_PAYMENT: Waiting for payment confirmation.\r\n * PROCESSING: Payment received, order is being fulfilled. Stays here until all line items reach a final state.\r\n * CANCELLED: All line items are cancelled, or order is cancelled before fulfillment.\r\n * COMPLETED: All line items are delivered, returned, or refunded.\r\n */\r\nexport enum OrderState {\r\n PLACED = \"PLACED\",\r\n PENDING_PAYMENT = \"PENDING_PAYMENT\",\r\n PROCESSING = \"PROCESSING\",\r\n CANCELLED = \"CANCELLED\",\r\n COMPLETED = \"COMPLETED\"\r\n}\r\n\r\n/**\r\n * OrderLineItemState\r\n * \r\n * INITIAL: Item added to order, not yet processed.\r\n * PROCESSING: Item is being prepared for shipment.\r\n * SHIPPED: Item dispatched to customer.\r\n * DELIVERED: Item delivered to customer.\r\n * CANCELLED: Item cancelled before shipment or delivery.\r\n * RETURN_REQUESTED: Customer requests to return item.\r\n * RETURNED: Item received back from customer.\r\n * REFUND_INITIATED: Refund initiated for item.\r\n * REFUNDED: Refund processed for item.\r\n * ON_HOLD: Item is paused due to payment, inventory, or other issues.\r\n */\r\nexport enum OrderLineItemState {\r\n INITIAL = \"INITIAL\",\r\n PROCESSING = \"PROCESSING\",\r\n SHIPPED = \"SHIPPED\",\r\n DELIVERED = \"DELIVERED\",\r\n CANCELLED = \"CANCELLED\",\r\n RETURN_REQUESTED = \"RETURN_REQUESTED\",\r\n RETURNED = \"RETURNED\",\r\n REFUND_INITIATED = \"REFUND_INITIATED\",\r\n REFUNDED = \"REFUNDED\",\r\n ON_HOLD = \"ON_HOLD\",\r\n}\r\n\r\n\r\nexport type OrderLineItemStateMap = Record<string, {\r\n state:OrderLineItemState;\r\n reason?: string;\r\n transitionAt: ISODateTime;\r\n}>;\r\n\r\n/**\r\n * Input attributes for creating an OrderModel.\r\n * Extends CartAttributes but requires/adds order-specific fields.\r\n */\r\nexport type OrderAttributes = Omit<BaseShoppingContainerAttributes, 'anonymousId'> & {\r\n customerId: string;\r\n customerEmail: string;\r\n shippingAddress: AddressData;\r\n billingAddress: AddressData;\r\n anonymousId?: string;\r\n total: Required<ShoppingContainerTotal>;\r\n orderNumber: string;\r\n cartId: string;\r\n paymentStatus: PaymentStatus;\r\n holdReason?: string;\r\n state: OrderState;\r\n lineItemStateMap?: OrderLineItemStateMap;\r\n};\r\n\r\n/**\r\n * Output data structure for an OrderModel.\r\n */\r\nexport type OrderData = BaseShoppingContainerData & OrderAttributes & {\r\n holdReason: string;\r\n lineItemStateMap: OrderLineItemStateMap;\r\n};\r\n\r\n\r\nexport default class OrderModel extends BaseShoppingContainerModel {\r\n protected orderNumber: string;\r\n protected cartId: string;\r\n protected paymentStatus: PaymentStatus;\r\n protected holdReason: string;\r\n protected state: OrderState;\r\n protected lineItemStateMap: OrderLineItemStateMap;\r\n\r\n /**\r\n * Creates an instance of OrderModel.\r\n * @param data - The initial order attributes, including cart data.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n * @param config - Optional cart configuration (might be less relevant for orders).\r\n */\r\n constructor(data: OrderAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.orderNumber = data.orderNumber;\r\n this.cartId = data.cartId;\r\n this.paymentStatus = data.paymentStatus;\r\n this.holdReason = data.holdReason || '';\r\n this.state = data.state;\r\n \r\n const newLineItemStateMap: OrderLineItemStateMap = {};\r\n data.lineItems.forEach(item => {\r\n const currentStateMap = data.lineItemStateMap?.[item.id];;\r\n \r\n newLineItemStateMap[item.id] = {\r\n state: currentStateMap?.state || OrderLineItemState.INITIAL,\r\n reason: currentStateMap?.reason || '',\r\n transitionAt: currentStateMap?.transitionAt || this.createdAt,\r\n };\r\n });\r\n this.lineItemStateMap = newLineItemStateMap;\r\n\r\n this.recalculateOrderBaseTotals();\r\n }\r\n\r\n /**\r\n * Recalculates the subtotal and mrpTotal based on the current line items.\r\n * Uses PriceModel for rounding based on the country.\r\n */\r\n protected recalculateOrderBaseTotals(): void {\r\n this.total.subtotal = PriceModel.getRoundedPrice(this.lineItems\r\n .filter((item) => \r\n ![OrderLineItemState.CANCELLED, OrderLineItemState.REFUND_INITIATED, OrderLineItemState.REFUNDED].includes(this.lineItemStateMap[item.getId()]?.state)\r\n )\r\n .reduce((sum, item) => sum + item.getPriceTotals().subtotal, 0), this.country);\r\n\r\n this.total.mrpTotal = PriceModel.getRoundedPrice(this.lineItems\r\n .filter((item) => \r\n ![OrderLineItemState.CANCELLED, OrderLineItemState.REFUND_INITIATED, OrderLineItemState.REFUNDED].includes(this.lineItemStateMap[item.getId()]?.state)\r\n )\r\n .reduce((sum, item) => sum + item.getPriceTotals().mrpTotal, 0), this.country);\r\n }\r\n\r\n public updateOrderTotals(): void {\r\n // 1. Calculate line item totals (subtotal, mrpTotal)\r\n this.recalculateOrderBaseTotals();\r\n\r\n // 2. Calculate total coupon discount and update the per-coupon discount map\r\n this.recalculateCouponTotals(false);\r\n\r\n // 3. Calculate effective shipping cost after applying shipping-specific coupons\r\n const shippingCouponDiscount = this.coupons\r\n .filter(c => c.getCategory() === CouponCategory.SHIPPING)\r\n .reduce((sum, c) => sum + (this.total.couponTotal[c.getCode()] ?? 0), 0);\r\n this.total.effectiveShipping = PriceModel.getRoundedPrice(Math.max(0, this.total.shipping - shippingCouponDiscount), this.country);\r\n\r\n // 4. Calculate total discount from non-shipping coupons\r\n const nonShippingCouponDiscount = this.coupons\r\n .filter(c => c.getCategory() !== CouponCategory.SHIPPING)\r\n .reduce((sum, c) => sum + (this.total.couponTotal[c.getCode()] ?? 0), 0);\r\n\r\n // 5. Calculate final grand total: (subtotal + effective shipping) - non-shipping discounts\r\n const grossTotal = this.total.subtotal + this.total.effectiveShipping;\r\n this.total.grandTotal = PriceModel.getRoundedPrice(Math.max(0, grossTotal - nonShippingCouponDiscount), this.country);\r\n }\r\n\r\n /**\r\n * Gets the customer ID associated with this order.\r\n * Overrides the base method to guarantee a non-undefined return type for orders.\r\n * @returns The customer ID string.\r\n */\r\n public getCustomerId(): string {\r\n return this.customerId as string;\r\n }\r\n\r\n /**\r\n * Gets the customer email associated with this order.\r\n * Overrides the base method to guarantee a non-undefined return type for orders.\r\n * @returns The customer email string.\r\n */\r\n public getCustomerEmail(): string {\r\n return this.customerEmail as string;\r\n }\r\n\r\n /**\r\n * Gets the shipping address associated with the order.\r\n * Overrides the base method to guarantee a non-null return type for orders.\r\n * @returns An AddressModel instance for the shipping address.\r\n */\r\n public getShippingAddress(): AddressModel {\r\n return this.shippingAddress as AddressModel;\r\n }\r\n\r\n /**\r\n * Gets the billing address associated with the order.\r\n * Overrides the base method to guarantee a non-null return type for orders.\r\n * @returns An AddressModel instance for the billing address.\r\n */\r\n public getBillingAddress(): AddressModel {\r\n return this.billingAddress as AddressModel;\r\n }\r\n\r\n\r\n /**\r\n * Gets the user-facing order number.\r\n * @returns The order number string.\r\n */\r\n public getOrderNumber(): string {\r\n return this.orderNumber;\r\n }\r\n\r\n /**\r\n * Gets the ID of the cart from which this order was created.\r\n * @returns The cart ID string.\r\n */\r\n public getCartId(): string {\r\n return this.cartId;\r\n }\r\n\r\n /**\r\n * Gets the current payment status of the order.\r\n * @returns The PaymentStatus enum value.\r\n */\r\n public getPaymentStatus(): PaymentStatus {\r\n return this.paymentStatus;\r\n }\r\n\r\n /**\r\n * Gets the reason why the order might be on hold, if any.\r\n * @returns The hold reason string (empty if not on hold or no reason specified).\r\n */\r\n public getHoldReason(): string {\r\n return this.holdReason;\r\n }\r\n\r\n /**\r\n * Gets the current state of the order (e.g., PROCESSING, SHIPPED).\r\n * @returns The OrderState enum value.\r\n */\r\n public getState(): OrderState {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the map tracking the state of each line item in the order.\r\n * The keys are line item IDs, and the values contain the state, reason, and transition timestamp.\r\n * @returns The OrderLineItemStateMap.\r\n */\r\n public getLineItemsStateMap(): OrderLineItemStateMap {\r\n return { ...this.lineItemStateMap };\r\n }\r\n\r\n /**\r\n * Gets the current state of a specific line item within the order.\r\n * @param lineItemId - The ID of the line item whose state is requested.\r\n * @returns The OrderLineItemState enum value for the specified line item.\r\n * @throws {LineItemNotFoundError} If no line item with the given ID exists in the order's state map.\r\n */\r\n public getLineItemState(lineItemId: string): OrderLineItemState {\r\n if (!this.lineItemStateMap[lineItemId]){\r\n throw new LineItemNotFoundError(lineItemId)\r\n }\r\n return this.lineItemStateMap[lineItemId].state;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the order's current state.\r\n * Includes all cart details plus order-specific information.\r\n * @returns OrderData object suitable for serialization or API responses.\r\n */\r\n getDetails(): OrderData {\r\n return {\r\n ...super.getDetails(),\r\n orderNumber: this.getOrderNumber(),\r\n customerId: this.getCustomerId(),\r\n customerEmail: this.getCustomerEmail(),\r\n shippingAddress: this.getShippingAddress().getDetails(),\r\n billingAddress: this.getBillingAddress().getDetails(),\r\n cartId: this.getCartId(),\r\n paymentStatus: this.getPaymentStatus(),\r\n holdReason: this.getHoldReason(),\r\n state: this.getState(),\r\n lineItemStateMap: this.getLineItemsStateMap()\r\n }\r\n }\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/Classes/Order.ts"],"names":["OrderState","OrderLineItemState","OrderModel","BaseShoppingContainerModel","data","date","newLineItemStateMap","item","currentStateMap","filteredLineItems","PriceModel","sum","shippingCouponDiscount","c","nonShippingCouponDiscount","grossTotal","lineItemId","LineItemNotFoundError"],"mappings":"6SAeYA,IAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,EAAA,MAAS,CAAA,QAAA,CACTA,EAAA,eAAkB,CAAA,iBAAA,CAClBA,CAAA,CAAA,UAAA,CAAa,YACbA,CAAAA,CAAAA,CAAA,UAAY,WACZA,CAAAA,CAAAA,CAAA,SAAY,CAAA,WAAA,CALFA,CAAA,CAAA,EAAA,CAAA,EAAA,EAA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,KAAA,CAAM,YACT,CAAA,WAAA,CAAa,IAAK,CAAA,cAAA,EAClB,CAAA,UAAA,CAAY,KAAK,aAAc,EAAA,CAC/B,aAAe,CAAA,IAAA,CAAK,gBAAiB,EAAA,CACrC,gBAAiB,IAAK,CAAA,kBAAA,EAAqB,CAAA,UAAA,EAC3C,CAAA,cAAA,CAAgB,KAAK,iBAAkB,EAAA,CAAE,UAAW,EAAA,CACpD,MAAQ,CAAA,IAAA,CAAK,WACb,CAAA,aAAA,CAAe,IAAK,CAAA,gBAAA,EACpB,CAAA,UAAA,CAAY,KAAK,aAAc,EAAA,CAC/B,KAAO,CAAA,IAAA,CAAK,QAAS,EAAA,CACrB,iBAAkB,IAAK,CAAA,oBAAA,EACzB,CACF,CACF","file":"Order.mjs","sourcesContent":["import AddressModel, { AddressData } from \"./Address\";\r\nimport { LineItemNotFoundError } from \"./Cart\";\r\nimport { ISODateTime } from \"./Common\";\r\nimport { CouponCategory } from \"./Coupon\";\r\nimport { PaymentStatus } from \"./Payment\";\r\nimport PriceModel from \"./Price\";\r\nimport BaseShoppingContainerModel, { BaseShoppingContainerAttributes, BaseShoppingContainerData, ShoppingContainerTotal } from \"./ShoppingContainer\";\r\n\r\n/**\r\n * PLACED: Order created, awaiting payment.\r\n * PENDING_PAYMENT: Waiting for payment confirmation.\r\n * PROCESSING: Payment received, order is being fulfilled. Stays here until all line items reach a final state.\r\n * CANCELLED: All line items are cancelled, or order is cancelled before fulfillment.\r\n * COMPLETED: All line items are delivered, returned, or refunded.\r\n */\r\nexport enum OrderState {\r\n PLACED = \"PLACED\",\r\n PENDING_PAYMENT = \"PENDING_PAYMENT\",\r\n PROCESSING = \"PROCESSING\",\r\n CANCELLED = \"CANCELLED\",\r\n COMPLETED = \"COMPLETED\"\r\n}\r\n\r\n/**\r\n * OrderLineItemState\r\n * \r\n * INITIAL: Item added to order, not yet processed.\r\n * PROCESSING: Item is being prepared for shipment.\r\n * SHIPPED: Item dispatched to customer.\r\n * DELIVERED: Item delivered to customer.\r\n * CANCELLED: Item cancelled before shipment or delivery.\r\n * RETURN_REQUESTED: Customer requests to return item.\r\n * RETURNED: Item received back from customer.\r\n * REFUND_INITIATED: Refund initiated for item.\r\n * REFUNDED: Refund processed for item.\r\n * ON_HOLD: Item is paused due to payment, inventory, or other issues.\r\n */\r\nexport enum OrderLineItemState {\r\n INITIAL = \"INITIAL\",\r\n PROCESSING = \"PROCESSING\",\r\n SHIPPED = \"SHIPPED\",\r\n DELIVERED = \"DELIVERED\",\r\n CANCELLED = \"CANCELLED\",\r\n RETURN_REQUESTED = \"RETURN_REQUESTED\",\r\n RETURNED = \"RETURNED\",\r\n REFUND_INITIATED = \"REFUND_INITIATED\",\r\n REFUNDED = \"REFUNDED\",\r\n ON_HOLD = \"ON_HOLD\",\r\n}\r\n\r\n\r\nexport type OrderLineItemStateMap = Record<string, {\r\n state:OrderLineItemState;\r\n reason?: string;\r\n transitionAt: ISODateTime;\r\n}>;\r\n\r\n/**\r\n * Input attributes for creating an OrderModel.\r\n * Extends CartAttributes but requires/adds order-specific fields.\r\n */\r\nexport type OrderAttributes = Omit<BaseShoppingContainerAttributes, 'anonymousId'> & {\r\n customerId: string;\r\n customerEmail: string;\r\n shippingAddress: AddressData;\r\n billingAddress: AddressData;\r\n anonymousId?: string;\r\n total: Required<ShoppingContainerTotal>;\r\n orderNumber: string;\r\n cartId: string;\r\n paymentStatus: PaymentStatus;\r\n holdReason?: string;\r\n state: OrderState;\r\n lineItemStateMap?: OrderLineItemStateMap;\r\n};\r\n\r\n/**\r\n * Output data structure for an OrderModel.\r\n */\r\nexport type OrderData = BaseShoppingContainerData & OrderAttributes & {\r\n holdReason: string;\r\n lineItemStateMap: OrderLineItemStateMap;\r\n};\r\n\r\n\r\nexport default class OrderModel extends BaseShoppingContainerModel {\r\n protected orderNumber: string;\r\n protected cartId: string;\r\n protected paymentStatus: PaymentStatus;\r\n protected holdReason: string;\r\n protected state: OrderState;\r\n protected lineItemStateMap: OrderLineItemStateMap;\r\n\r\n /**\r\n * Creates an instance of OrderModel.\r\n * @param data - The initial order attributes, including cart data.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n * @param config - Optional cart configuration (might be less relevant for orders).\r\n */\r\n constructor(data: OrderAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.orderNumber = data.orderNumber;\r\n this.cartId = data.cartId;\r\n this.paymentStatus = data.paymentStatus;\r\n this.holdReason = data.holdReason || '';\r\n this.state = data.state;\r\n \r\n const newLineItemStateMap: OrderLineItemStateMap = {};\r\n data.lineItems.forEach(item => {\r\n const currentStateMap = data.lineItemStateMap?.[item.id];;\r\n \r\n newLineItemStateMap[item.id] = {\r\n state: currentStateMap?.state || OrderLineItemState.INITIAL,\r\n reason: currentStateMap?.reason || '',\r\n transitionAt: currentStateMap?.transitionAt || this.createdAt,\r\n };\r\n });\r\n this.lineItemStateMap = newLineItemStateMap;\r\n\r\n this.recalculateOrderBaseTotals();\r\n }\r\n\r\n /**\r\n * Recalculates the subtotal and mrpTotal based on the current line items.\r\n * Uses PriceModel for rounding based on the country.\r\n */\r\n protected recalculateOrderBaseTotals(): void {\r\n const filteredLineItems = this.lineItems.filter(item =>\r\n this.lineItemStateMap[item.getId()]?.state !== OrderLineItemState.CANCELLED\r\n );\r\n this.total.subtotal = PriceModel.getRoundedPrice(filteredLineItems\r\n .reduce((sum, item) => sum + item.getPriceTotals().subtotal, 0), this.country);\r\n\r\n this.total.mrpTotal = PriceModel.getRoundedPrice(filteredLineItems.reduce((sum, item) => sum + item.getPriceTotals().mrpTotal, 0), this.country);\r\n }\r\n\r\n public updateOrderTotals(): void {\r\n // 1. Calculate line item totals (subtotal, mrpTotal)\r\n this.recalculateOrderBaseTotals();\r\n\r\n // 2. Calculate total coupon discount and update the per-coupon discount map\r\n this.recalculateCouponTotals(false);\r\n\r\n // 3. Calculate effective shipping cost after applying shipping-specific coupons\r\n const shippingCouponDiscount = this.coupons\r\n .filter(c => c.getCategory() === CouponCategory.SHIPPING)\r\n .reduce((sum, c) => sum + (this.total.couponTotal[c.getCode()] ?? 0), 0);\r\n this.total.effectiveShipping = PriceModel.getRoundedPrice(Math.max(0, this.total.shipping - shippingCouponDiscount), this.country);\r\n\r\n // 4. Calculate total discount from non-shipping coupons\r\n const nonShippingCouponDiscount = this.coupons\r\n .filter(c => c.getCategory() !== CouponCategory.SHIPPING)\r\n .reduce((sum, c) => sum + (this.total.couponTotal[c.getCode()] ?? 0), 0);\r\n\r\n // 5. Calculate final grand total: (subtotal + effective shipping) - non-shipping discounts\r\n const grossTotal = this.total.subtotal + this.total.effectiveShipping;\r\n this.total.grandTotal = PriceModel.getRoundedPrice(Math.max(0, grossTotal - nonShippingCouponDiscount), this.country);\r\n }\r\n\r\n /**\r\n * Gets the customer ID associated with this order.\r\n * Overrides the base method to guarantee a non-undefined return type for orders.\r\n * @returns The customer ID string.\r\n */\r\n public getCustomerId(): string {\r\n return this.customerId as string;\r\n }\r\n\r\n /**\r\n * Gets the customer email associated with this order.\r\n * Overrides the base method to guarantee a non-undefined return type for orders.\r\n * @returns The customer email string.\r\n */\r\n public getCustomerEmail(): string {\r\n return this.customerEmail as string;\r\n }\r\n\r\n /**\r\n * Gets the shipping address associated with the order.\r\n * Overrides the base method to guarantee a non-null return type for orders.\r\n * @returns An AddressModel instance for the shipping address.\r\n */\r\n public getShippingAddress(): AddressModel {\r\n return this.shippingAddress as AddressModel;\r\n }\r\n\r\n /**\r\n * Gets the billing address associated with the order.\r\n * Overrides the base method to guarantee a non-null return type for orders.\r\n * @returns An AddressModel instance for the billing address.\r\n */\r\n public getBillingAddress(): AddressModel {\r\n return this.billingAddress as AddressModel;\r\n }\r\n\r\n\r\n /**\r\n * Gets the user-facing order number.\r\n * @returns The order number string.\r\n */\r\n public getOrderNumber(): string {\r\n return this.orderNumber;\r\n }\r\n\r\n /**\r\n * Gets the ID of the cart from which this order was created.\r\n * @returns The cart ID string.\r\n */\r\n public getCartId(): string {\r\n return this.cartId;\r\n }\r\n\r\n /**\r\n * Gets the current payment status of the order.\r\n * @returns The PaymentStatus enum value.\r\n */\r\n public getPaymentStatus(): PaymentStatus {\r\n return this.paymentStatus;\r\n }\r\n\r\n /**\r\n * Gets the reason why the order might be on hold, if any.\r\n * @returns The hold reason string (empty if not on hold or no reason specified).\r\n */\r\n public getHoldReason(): string {\r\n return this.holdReason;\r\n }\r\n\r\n /**\r\n * Gets the current state of the order (e.g., PROCESSING, SHIPPED).\r\n * @returns The OrderState enum value.\r\n */\r\n public getState(): OrderState {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the map tracking the state of each line item in the order.\r\n * The keys are line item IDs, and the values contain the state, reason, and transition timestamp.\r\n * @returns The OrderLineItemStateMap.\r\n */\r\n public getLineItemsStateMap(): OrderLineItemStateMap {\r\n return { ...this.lineItemStateMap };\r\n }\r\n\r\n /**\r\n * Gets the current state of a specific line item within the order.\r\n * @param lineItemId - The ID of the line item whose state is requested.\r\n * @returns The OrderLineItemState enum value for the specified line item.\r\n * @throws {LineItemNotFoundError} If no line item with the given ID exists in the order's state map.\r\n */\r\n public getLineItemState(lineItemId: string): OrderLineItemState {\r\n if (!this.lineItemStateMap[lineItemId]){\r\n throw new LineItemNotFoundError(lineItemId)\r\n }\r\n return this.lineItemStateMap[lineItemId].state;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the order's current state.\r\n * Includes all cart details plus order-specific information.\r\n * @returns OrderData object suitable for serialization or API responses.\r\n */\r\n getDetails(): OrderData {\r\n return {\r\n ...super.getDetails(),\r\n orderNumber: this.getOrderNumber(),\r\n customerId: this.getCustomerId(),\r\n customerEmail: this.getCustomerEmail(),\r\n shippingAddress: this.getShippingAddress().getDetails(),\r\n billingAddress: this.getBillingAddress().getDetails(),\r\n cartId: this.getCartId(),\r\n paymentStatus: this.getPaymentStatus(),\r\n holdReason: this.getHoldReason(),\r\n state: this.getState(),\r\n lineItemStateMap: this.getLineItemsStateMap()\r\n }\r\n }\r\n}\r\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as default}from'../chunk-
|
|
1
|
+
export{a as default}from'../chunk-O5C6Z6AY.mjs';import'../chunk-K3AXPTGG.mjs';import'../chunk-DKI6BDWK.mjs';import'../chunk-V4H3X4PI.mjs';import'../chunk-HTJJLLGW.mjs';import'../chunk-RWBNLNQ6.mjs';import'../chunk-6PDP4ETM.mjs';import'../chunk-ATUUYYQT.mjs';//# sourceMappingURL=ShoppingContainer.mjs.map
|
|
2
2
|
//# sourceMappingURL=ShoppingContainer.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a as a$2}from'./chunk-K3AXPTGG.mjs';import {a as a$3}from'./chunk-V4H3X4PI.mjs';import {b}from'./chunk-HTJJLLGW.mjs';import {e}from'./chunk-RWBNLNQ6.mjs';import {a as a$1}from'./chunk-ATUUYYQT.mjs';var a=class extends a$1{id;customerId;customerEmail;anonymousId;lineItems;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,e$1=new Date){super(t,e$1),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 a$2(i)),this.billingAddress=t.billingAddress?new b(t.billingAddress,e$1):null,this.shippingAddress=t.shippingAddress?new b(t.shippingAddress,e$1):null,this.coupons=(t.coupons||[]).map(i=>new e(i)),this.shippingDetails=t.shippingDetails?{...t.shippingDetails}:null,this.total={shipping:t.total?.shipping||0,effectiveShipping:t.total?.effectiveShipping??t.total?.shipping??0,subtotal:t.total?.subtotal||0,mrpTotal:t.total?.mrpTotal||0,couponTotal:t.total?.couponTotal||{},grandTotal:t.total?.grandTotal||0};}recalculateBaseTotals(){this.total.subtotal=a$3.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=a$3.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().mrpTotal,0),this.country);}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new a$2(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new b(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new b(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons.map(t=>new e(t.getDetails()))}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {...this.total,couponTotal:{...this.total.couponTotal}}}calculateApplicableCouponDiscount(t,e=!0){if(e&&!t.isActive())return 0;let i=t.getMinCartValue(this.country),s=t.getMaxCartDiscount(this.country);if(!i||this.total.subtotal<i.price||!s||s.price<0)return 0;let d=t.getCategory(),g=t.getDiscountMethod(),r=0,l=d==="SHIPPING"?this.total.shipping:this.total.subtotal;if(l<=0)return 0;switch(g){case"flat":let m=s?.price??0;r=Math.min(l,m);break;case"percentage":r=l*(t.getPercentageValue()/100);break;default:return 0}let h=Math.min(r,s.price);return a$3.getRoundedPrice(Math.max(0,h),this.country)}recalculateCouponTotals(t=!0){this.total.couponTotal={};let e=0;return this.coupons.forEach(i=>{let s=this.calculateApplicableCouponDiscount(i,t);s>0&&(this.total.couponTotal[i.getCode()]=s,e+=s);}),a$3.getRoundedPrice(e,this.country)}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:this.getTotal(),country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}};export{a};//# sourceMappingURL=chunk-O5C6Z6AY.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-O5C6Z6AY.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/ShoppingContainer.ts"],"names":["BaseShoppingContainerModel","BaseModel","data","date","item","LineItemModel","AddressModel","coupon","CouponModel","PriceModel","sum","checkExpiry","minCartValueReq","maxCartDiscountCap","couponCategory","discountMethod","potentialDiscount","targetValue","flatAmount","finalDiscount","totalDiscount","discount"],"mappings":"8MAmDA,IAA8BA,CAA9B,CAAA,cAAiEC,GAAU,CAC/D,GACA,UACA,CAAA,aAAA,CACA,WACA,CAAA,SAAA,CACA,eACA,CAAA,eAAA,CACA,cAGA,CAAA,OAAA,CAGA,MASA,OACA,CAAA,QAAA,CACA,MAQV,CAAA,WAAA,CAAYC,CAAuCC,CAAAA,GAAAA,CAAa,IAAI,IAAA,CAAQ,CAC1E,KAAMD,CAAAA,CAAAA,CAAMC,GAAI,CAAA,CAChB,IAAK,CAAA,EAAA,CAAKD,CAAK,CAAA,EAAA,CACf,KAAK,UAAaA,CAAAA,CAAAA,CAAK,UACvB,CAAA,IAAA,CAAK,aAAgBA,CAAAA,CAAAA,CAAK,aAC1B,CAAA,IAAA,CAAK,YAAcA,CAAK,CAAA,WAAA,CACxB,IAAK,CAAA,OAAA,CAAUA,CAAK,CAAA,OAAA,CACpB,IAAK,CAAA,QAAA,CAAWA,EAAK,QACrB,CAAA,IAAA,CAAK,MAASA,CAAAA,CAAAA,CAAK,MACnB,CAAA,IAAA,CAAK,SAAaA,CAAAA,CAAAA,CAAAA,CAAK,WAAa,EAAC,EAAG,GAAIE,CAAAA,CAAAA,EAAQ,IAAIC,GAAcD,CAAAA,CAAI,CAAC,CAAA,CAC3E,KAAK,cAAiBF,CAAAA,CAAAA,CAAK,cAAiB,CAAA,IAAII,CAAaJ,CAAAA,C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CAAK,QAAS,EAAA,CACrB,OAAS,CAAA,IAAA,CAAK,YACd,CAAA,QAAA,CAAU,IAAK,CAAA,WAAA,GACf,MAAQ,CAAA,IAAA,CAAK,SAAU,EACzB,CACF,CACH","file":"chunk-QKV5D6JZ.mjs","sourcesContent":["import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport AddressModel, { AddressData } from \"./Address\";\r\nimport LineItemModel, { LineItemData } from \"./LineItem\";\r\nimport { CountryCode, CurrencyCode, LocaleCode, ShippingDetails } from \"./Common\";\r\nimport PriceModel from \"./Price\";\r\nimport CouponModel, { CouponCategory, CouponData, CouponDiscountMethod } from \"./Coupon\";\r\n\r\nexport type ShoppingContainerTotal = {\r\n shipping?: number;\r\n effectiveShipping?: number;\r\n subtotal?: number;\r\n mrpTotal?: number;\r\n couponTotal?: { [key: string]: number };\r\n grandTotal?: number;\r\n}\r\n\r\nexport type BaseShoppingContainerAttributes = BaseAttributes & {\r\n id: string;\r\n customerId?: string;\r\n customerEmail?: string;\r\n anonymousId?: string;\r\n lineItems: LineItemData[];\r\n shippingDetails: ShippingDetails | null;\r\n shippingAddress?: AddressData | null;\r\n billingAddress?: AddressData | null;\r\n coupons?: CouponData[];\r\n total?: ShoppingContainerTotal;\r\n country: CountryCode;\r\n currency: CurrencyCode;\r\n locale: LocaleCode;\r\n};\r\n\r\nexport type BaseShoppingContainerData = Omit<BaseShoppingContainerAttributes, 'coupons' | 'total'>\r\n& BaseData\r\n& {\r\n coupons: CouponData[],\r\n total: {\r\n shipping: number,\r\n effectiveShipping: number,\r\n subtotal: number,\r\n mrpTotal: number,\r\n couponTotal: { [key: string]: number },\r\n grandTotal: number\r\n };\r\n };\r\n\r\n\r\n/**\r\n * Abstract base class for shopping-related containers like carts and orders.\r\n * Manages common elements such as line items, addresses, coupons, and totals.\r\n */\r\nexport default abstract class BaseShoppingContainerModel extends BaseModel {\r\n protected id: string;\r\n protected customerId?: string;\r\n protected customerEmail?: string;\r\n protected anonymousId?: string;\r\n protected lineItems: LineItemModel[];\r\n protected shippingDetails: ShippingDetails | null;\r\n protected shippingAddress: AddressModel | null;\r\n protected billingAddress: AddressModel | null;\r\n\r\n // CouponsCodes\r\n protected coupons: CouponModel[];\r\n\r\n // Cart Totals\r\n protected total: {\r\n shipping: number;\r\n effectiveShipping: number;\r\n subtotal: number;\r\n mrpTotal: number;\r\n couponTotal: { [key: string]: number; };\r\n grandTotal: number;\r\n };\r\n\r\n protected country: CountryCode;\r\n protected currency: CurrencyCode;\r\n protected locale: LocaleCode;\r\n\r\n /**\r\n * Creates an instance of BaseShoppingContainerModel.\r\n * Initializes common properties and calculates initial base totals.\r\n * @param data - The initial attributes for the shopping container.\r\n * @param date - Optional date object for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: BaseShoppingContainerAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.customerId = data.customerId;\r\n this.customerEmail = data.customerEmail;\r\n this.anonymousId = data.anonymousId;\r\n this.country = data.country;\r\n this.currency = data.currency;\r\n this.locale = data.locale;\r\n this.lineItems = (data.lineItems ?? []).map(item => new LineItemModel(item));\r\n this.billingAddress = data.billingAddress ? new AddressModel(data.billingAddress, date) : null;\r\n this.shippingAddress = data.shippingAddress ? new AddressModel(data.shippingAddress, date) : null;\r\n this.coupons = (data.coupons || []).map(coupon => new CouponModel(coupon));\r\n\r\n this.shippingDetails = data.shippingDetails ? { ...data.shippingDetails } : null;\r\n\r\n this.total = {\r\n shipping: data.total?.shipping || 0,\r\n effectiveShipping: data.total?.effectiveShipping ?? data.total?.shipping ?? 0,\r\n subtotal: data.total?.subtotal || 0,\r\n mrpTotal: data.total?.mrpTotal || 0,\r\n couponTotal: data.total?.couponTotal || {},\r\n grandTotal: data.total?.grandTotal || 0,\r\n };\r\n }\r\n\r\n /**\r\n * Recalculates the subtotal and mrpTotal based on the current line items.\r\n * Uses PriceModel for rounding based on the country.\r\n */\r\n protected recalculateBaseTotals(): void {\r\n this.total.subtotal = PriceModel.getRoundedPrice(this.lineItems.reduce((sum, item) => sum + item.getPriceTotals().subtotal, 0), this.country);\r\n this.total.mrpTotal = PriceModel.getRoundedPrice(this.lineItems.reduce((sum, item) => sum + item.getPriceTotals().mrpTotal, 0), this.country);\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for this shopping container (cart ID or order ID).\r\n * @returns The ID string.\r\n */\r\n public getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the customer ID associated with this container, if available.\r\n * @returns The customer ID string, or undefined.\r\n */\r\n public getCustomerId(): string | undefined {\r\n return this.customerId;\r\n }\r\n\r\n /**\r\n * Gets the customer email associated with this container, if available.\r\n * @returns The customer email string, or undefined.\r\n */\r\n public getCustomerEmail(): string | undefined {\r\n return this.customerEmail;\r\n }\r\n\r\n /**\r\n * Gets the anonymous user ID associated with this container, if available.\r\n * @returns The anonymous ID string, or undefined.\r\n */\r\n public getAnonymousId(): string | undefined {\r\n return this.anonymousId;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the line items in the container.\r\n * Each item is a new LineItemModel instance created from the original's details.\r\n * @returns An array of LineItemModel instances.\r\n */\r\n public getLineItems(): LineItemModel[] {\r\n // Return new instances to prevent modification of internal state\r\n return this.lineItems.map(item => new LineItemModel(item.getDetails()));\r\n }\r\n\r\n /**\r\n * Gets current number of line items in the container\r\n * @returns \r\n */\r\n public getLineItemsCount(): number {\r\n return this.lineItems.length;\r\n }\r\n\r\n /**\r\n * Gets a copy of the shipping details associated with the container.\r\n * @returns A ShippingDetails object, or null if none are set.\r\n */\r\n public getShippingDetails(): ShippingDetails | null {\r\n // Return a shallow copy if details exist\r\n return this.shippingDetails ? { ...this.shippingDetails } : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the shipping address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no shipping address is set.\r\n */\r\n public getShippingAddress(): AddressModel | null {\r\n return this.shippingAddress ? new AddressModel(this.shippingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Checks if a shipping address is associated with this container.\r\n * @returns True if a shipping address is set, false otherwise.\r\n */\r\n public hasShippingAddress(): boolean {\r\n return !!this.shippingAddress;\r\n }\r\n\r\n /**\r\n * Checks if a billing address is associated with this container.\r\n * @returns True if a billing address is set, false otherwise.\r\n */\r\n public hasBillingAddress(): boolean {\r\n return !!this.billingAddress;\r\n }\r\n \r\n /**\r\n * Gets a defensive copy of the billing address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no billing address is set.\r\n */\r\n public getBillingAddress(): AddressModel | null {\r\n return this.billingAddress ? new AddressModel(this.billingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the coupons applied to the container.\r\n * Each item is a new CouponModel instance created from the original's details.\r\n * @returns An array of CouponModel instances.\r\n */\r\n public getCoupons(): CouponModel[] {\r\n return this.coupons.map(coupon => new CouponModel(coupon.getDetails()));\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this container.\r\n * @returns The CountryCode enum value.\r\n */\r\n public getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Gets the currency code associated with this container.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Gets the locale code associated with this container.\r\n * @returns The LocaleCode enum value.\r\n */\r\n public getLocale(): LocaleCode {\r\n return this.locale;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the calculated totals for the container.\r\n * @returns An object containing shipping, subtotal, coupon, and grand totals.\r\n */\r\n public getTotal() {\r\n return { ...this.total, couponTotal: { ...this.total.couponTotal } };\r\n }\r\n\r\n /**\r\n * Calculates the discount value for a given coupon based on the current container state.\r\n * Returns 0 if the coupon is invalid, expired, or not applicable based on cart value or target category.\r\n * @param coupon - The CouponModel instance to evaluate.\r\n * @param checkExpiry - Whether to check the coupon's expiry status.\r\n * @returns The calculated discount amount (rounded according to country rules).\r\n */\r\n public calculateApplicableCouponDiscount(coupon: CouponModel, checkExpiry: boolean = true): number {\r\n // 1. Basic validation (active)\r\n if (checkExpiry && !coupon.isActive()) {\r\n return 0;\r\n }\r\n\r\n // 2. Check regional requirements (min cart value, max discount)\r\n const minCartValueReq = coupon.getMinCartValue(this.country);\r\n const maxCartDiscountCap = coupon.getMaxCartDiscount(this.country);\r\n\r\n // Ensure minCartValueReq exists and subtotal meets the requirement\r\n if (!minCartValueReq || this.total.subtotal < minCartValueReq.price) {\r\n return 0;\r\n }\r\n\r\n // Ensure maxCartDiscountCap exists and is non-negative\r\n if (!maxCartDiscountCap || maxCartDiscountCap.price < 0) {\r\n return 0;\r\n }\r\n\r\n // 3. Calculate potential discount based on method and category\r\n const couponCategory = coupon.getCategory();\r\n const discountMethod = coupon.getDiscountMethod();\r\n let potentialDiscount = 0;\r\n // Determine the value the coupon applies to (shipping cost or subtotal)\r\n const targetValue = couponCategory === CouponCategory.SHIPPING ? this.total.shipping : this.total.subtotal;\r\n\r\n // No discount if the target value is zero or less\r\n if (targetValue <= 0) return 0;\r\n\r\n switch (discountMethod) {\r\n case CouponDiscountMethod.FLAT:\r\n // Flat discount is capped by the target value itself and the max discount cap\r\n const flatAmount = maxCartDiscountCap?.price ?? 0; // Use cap as the flat amount source? Or coupon.value? Needs clarification. Assuming cap IS the flat amount here.\r\n potentialDiscount = Math.min(targetValue, flatAmount);\r\n break;\r\n case CouponDiscountMethod.PERCENTAGE:\r\n // Calculate percentage discount based on the target value\r\n potentialDiscount = targetValue * (coupon.getPercentageValue() / 100);\r\n break;\r\n default:\r\n // Unknown discount method\r\n return 0;\r\n }\r\n\r\n // 4. Apply maximum discount cap to the calculated potential discount\r\n const finalDiscount = Math.min(potentialDiscount, maxCartDiscountCap.price);\r\n\r\n // 5. Round the final discount, ensuring it's not negative\r\n return PriceModel.getRoundedPrice(Math.max(0, finalDiscount), this.country);\r\n }\r\n\r\n /**\r\n * Recalculates the `couponTotal` map based on currently applied coupons.\r\n * Iterates through coupons, calculates their applicable discount, and stores it.\r\n * @param checkExpiry - Whether to check the expiry status of coupons.\r\n * @returns The total discount amount from all valid and applicable coupons (rounded).\r\n */\r\n public recalculateCouponTotals(checkExpiry: boolean = true): number {\r\n this.total.couponTotal = {};\r\n let totalDiscount = 0;\r\n\r\n this.coupons.forEach(coupon => {\r\n const discount = this.calculateApplicableCouponDiscount(coupon, checkExpiry);\r\n if (discount > 0) {\r\n this.total.couponTotal[coupon.getCode()] = discount; // Store per-coupon discount\r\n totalDiscount += discount; // Accumulate total discount\r\n }\r\n });\r\n // Return the rounded total discount\r\n return PriceModel.getRoundedPrice(totalDiscount, this.country);\r\n }\r\n\r\n\r\n /**\r\n * Gets a plain data object representing the shopping container's current state.\r\n * Includes details from the base model and specific container properties.\r\n * @returns BaseShoppingContainerData object suitable for serialization or API responses.\r\n */\r\n getDetails(): BaseShoppingContainerData {\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n customerId: this.getCustomerId(),\r\n customerEmail: this.getCustomerEmail(),\r\n anonymousId: this.getAnonymousId(),\r\n lineItems: this.getLineItems().map(item => item.getDetails()),\r\n shippingDetails: this.getShippingDetails(),\r\n shippingAddress: this.getShippingAddress()?.getDetails() || null,\r\n billingAddress: this.getBillingAddress()?.getDetails() || null,\r\n coupons: this.getCoupons().map(coupon => coupon.getDetails()),\r\n total: this.getTotal(),\r\n country: this.getCountry(),\r\n currency: this.getCurrency(),\r\n locale: this.getLocale(),\r\n }\r\n };\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/Classes/ShoppingContainer.ts"],"names":["BaseShoppingContainerModel","BaseModel","data","date","item","LineItemModel","AddressModel","coupon","CouponModel","PriceModel","sum","checkExpiry","minCartValueReq","maxCartDiscountCap","couponCategory","discountMethod","potentialDiscount","targetValue","flatAmount","finalDiscount","totalDiscount","discount"],"mappings":"8MAmDA,IAA8BA,CAA9B,CAAA,cAAiEC,GAAU,CAC/D,GACA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AA,CAAO,SAAS,CAAA,CAAIc,CAC3CD,CAAAA,CAAAA,EAAiBC,CAErB,EAAA,CAAC,CAEMZ,CAAAA,GAAAA,CAAW,gBAAgBW,CAAe,CAAA,IAAA,CAAK,OAAO,CAC/D,CAQA,UAAwC,EAAA,CACrC,OAAO,CACL,GAAG,KAAM,CAAA,UAAA,EACT,CAAA,EAAA,CAAI,IAAK,CAAA,KAAA,EACT,CAAA,UAAA,CAAY,KAAK,aAAc,EAAA,CAC/B,aAAe,CAAA,IAAA,CAAK,gBAAiB,EAAA,CACrC,WAAa,CAAA,IAAA,CAAK,gBAClB,CAAA,SAAA,CAAW,IAAK,CAAA,YAAA,EAAe,CAAA,GAAA,CAAIhB,CAAQA,EAAAA,CAAAA,CAAK,YAAY,CAAA,CAC5D,eAAiB,CAAA,IAAA,CAAK,oBACtB,CAAA,eAAA,CAAiB,IAAK,CAAA,kBAAA,IAAsB,UAAW,EAAA,EAAK,IAC5D,CAAA,cAAA,CAAgB,IAAK,CAAA,iBAAA,EAAqB,EAAA,UAAA,IAAgB,IAC1D,CAAA,OAAA,CAAS,IAAK,CAAA,UAAA,EAAa,CAAA,GAAA,CAAIG,CAAUA,EAAAA,CAAAA,CAAO,YAAY,CAAA,CAC5D,KAAO,CAAA,IAAA,CAAK,QAAS,EAAA,CACrB,OAAS,CAAA,IAAA,CAAK,YACd,CAAA,QAAA,CAAU,IAAK,CAAA,WAAA,GACf,MAAQ,CAAA,IAAA,CAAK,SAAU,EACzB,CACF,CACH","file":"chunk-O5C6Z6AY.mjs","sourcesContent":["import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport AddressModel, { AddressData } from \"./Address\";\r\nimport LineItemModel, { LineItemData } from \"./LineItem\";\r\nimport { CountryCode, CurrencyCode, LocaleCode, ShippingDetails } from \"./Common\";\r\nimport PriceModel from \"./Price\";\r\nimport CouponModel, { CouponCategory, CouponData, CouponDiscountMethod } from \"./Coupon\";\r\n\r\nexport type ShoppingContainerTotal = {\r\n shipping?: number;\r\n effectiveShipping?: number;\r\n subtotal?: number;\r\n mrpTotal?: number;\r\n couponTotal?: { [key: string]: number };\r\n grandTotal?: number;\r\n}\r\n\r\nexport type BaseShoppingContainerAttributes = BaseAttributes & {\r\n id: string;\r\n customerId?: string;\r\n customerEmail?: string;\r\n anonymousId?: string;\r\n lineItems: LineItemData[];\r\n shippingDetails: ShippingDetails | null;\r\n shippingAddress?: AddressData | null;\r\n billingAddress?: AddressData | null;\r\n coupons?: CouponData[];\r\n total?: ShoppingContainerTotal;\r\n country: CountryCode;\r\n currency: CurrencyCode;\r\n locale: LocaleCode;\r\n};\r\n\r\nexport type BaseShoppingContainerData = Omit<BaseShoppingContainerAttributes, 'coupons' | 'total'>\r\n& BaseData\r\n& {\r\n coupons: CouponData[],\r\n total: {\r\n shipping: number,\r\n effectiveShipping: number,\r\n subtotal: number,\r\n mrpTotal: number,\r\n couponTotal: { [key: string]: number },\r\n grandTotal: number\r\n };\r\n };\r\n\r\n\r\n/**\r\n * Abstract base class for shopping-related containers like carts and orders.\r\n * Manages common elements such as line items, addresses, coupons, and totals.\r\n */\r\nexport default abstract class BaseShoppingContainerModel extends BaseModel {\r\n protected id: string;\r\n protected customerId?: string;\r\n protected customerEmail?: string;\r\n protected anonymousId?: string;\r\n protected lineItems: LineItemModel[];\r\n protected shippingDetails: ShippingDetails | null;\r\n protected shippingAddress: AddressModel | null;\r\n protected billingAddress: AddressModel | null;\r\n\r\n // CouponsCodes\r\n protected coupons: CouponModel[];\r\n\r\n // Cart Totals\r\n protected total: {\r\n shipping: number;\r\n effectiveShipping: number;\r\n subtotal: number;\r\n mrpTotal: number;\r\n couponTotal: { [key: string]: number; };\r\n grandTotal: number;\r\n };\r\n\r\n protected country: CountryCode;\r\n protected currency: CurrencyCode;\r\n protected locale: LocaleCode;\r\n\r\n /**\r\n * Creates an instance of BaseShoppingContainerModel.\r\n * Initializes common properties and calculates initial base totals.\r\n * @param data - The initial attributes for the shopping container.\r\n * @param date - Optional date object for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: BaseShoppingContainerAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.customerId = data.customerId;\r\n this.customerEmail = data.customerEmail;\r\n this.anonymousId = data.anonymousId;\r\n this.country = data.country;\r\n this.currency = data.currency;\r\n this.locale = data.locale;\r\n this.lineItems = (data.lineItems ?? []).map(item => new LineItemModel(item));\r\n this.billingAddress = data.billingAddress ? new AddressModel(data.billingAddress, date) : null;\r\n this.shippingAddress = data.shippingAddress ? new AddressModel(data.shippingAddress, date) : null;\r\n this.coupons = (data.coupons || []).map(coupon => new CouponModel(coupon));\r\n\r\n this.shippingDetails = data.shippingDetails ? { ...data.shippingDetails } : null;\r\n\r\n this.total = {\r\n shipping: data.total?.shipping || 0,\r\n effectiveShipping: data.total?.effectiveShipping ?? data.total?.shipping ?? 0,\r\n subtotal: data.total?.subtotal || 0,\r\n mrpTotal: data.total?.mrpTotal || 0,\r\n couponTotal: data.total?.couponTotal || {},\r\n grandTotal: data.total?.grandTotal || 0,\r\n };\r\n }\r\n\r\n /**\r\n * Recalculates the subtotal and mrpTotal based on the current line items.\r\n * Uses PriceModel for rounding based on the country.\r\n */\r\n protected recalculateBaseTotals(): void {\r\n this.total.subtotal = PriceModel.getRoundedPrice(this.lineItems.reduce((sum, item) => sum + item.getPriceTotals().subtotal, 0), this.country);\r\n this.total.mrpTotal = PriceModel.getRoundedPrice(this.lineItems.reduce((sum, item) => sum + item.getPriceTotals().mrpTotal, 0), this.country);\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for this shopping container (cart ID or order ID).\r\n * @returns The ID string.\r\n */\r\n public getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the customer ID associated with this container, if available.\r\n * @returns The customer ID string, or undefined.\r\n */\r\n public getCustomerId(): string | undefined {\r\n return this.customerId;\r\n }\r\n\r\n /**\r\n * Gets the customer email associated with this container, if available.\r\n * @returns The customer email string, or undefined.\r\n */\r\n public getCustomerEmail(): string | undefined {\r\n return this.customerEmail;\r\n }\r\n\r\n /**\r\n * Gets the anonymous user ID associated with this container, if available.\r\n * @returns The anonymous ID string, or undefined.\r\n */\r\n public getAnonymousId(): string | undefined {\r\n return this.anonymousId;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the line items in the container.\r\n * Each item is a new LineItemModel instance created from the original's details.\r\n * @returns An array of LineItemModel instances.\r\n */\r\n public getLineItems(): LineItemModel[] {\r\n // Return new instances to prevent modification of internal state\r\n return this.lineItems.map(item => new LineItemModel(item.getDetails()));\r\n }\r\n\r\n /**\r\n * Gets current number of line items in the container\r\n * @returns \r\n */\r\n public getLineItemsCount(): number {\r\n return this.lineItems.length;\r\n }\r\n\r\n /**\r\n * Gets a copy of the shipping details associated with the container.\r\n * @returns A ShippingDetails object, or null if none are set.\r\n */\r\n public getShippingDetails(): ShippingDetails | null {\r\n // Return a shallow copy if details exist\r\n return this.shippingDetails ? { ...this.shippingDetails } : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the shipping address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no shipping address is set.\r\n */\r\n public getShippingAddress(): AddressModel | null {\r\n return this.shippingAddress ? new AddressModel(this.shippingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Checks if a shipping address is associated with this container.\r\n * @returns True if a shipping address is set, false otherwise.\r\n */\r\n public hasShippingAddress(): boolean {\r\n return !!this.shippingAddress;\r\n }\r\n\r\n /**\r\n * Checks if a billing address is associated with this container.\r\n * @returns True if a billing address is set, false otherwise.\r\n */\r\n public hasBillingAddress(): boolean {\r\n return !!this.billingAddress;\r\n }\r\n \r\n /**\r\n * Gets a defensive copy of the billing address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no billing address is set.\r\n */\r\n public getBillingAddress(): AddressModel | null {\r\n return this.billingAddress ? new AddressModel(this.billingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the coupons applied to the container.\r\n * Each item is a new CouponModel instance created from the original's details.\r\n * @returns An array of CouponModel instances.\r\n */\r\n public getCoupons(): CouponModel[] {\r\n return this.coupons.map(coupon => new CouponModel(coupon.getDetails()));\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this container.\r\n * @returns The CountryCode enum value.\r\n */\r\n public getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Gets the currency code associated with this container.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Gets the locale code associated with this container.\r\n * @returns The LocaleCode enum value.\r\n */\r\n public getLocale(): LocaleCode {\r\n return this.locale;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the calculated totals for the container.\r\n * @returns An object containing shipping, subtotal, coupon, and grand totals.\r\n */\r\n public getTotal() {\r\n return { ...this.total, couponTotal: { ...this.total.couponTotal } };\r\n }\r\n\r\n /**\r\n * Calculates the discount value for a given coupon based on the current container state.\r\n * Returns 0 if the coupon is invalid, expired, or not applicable based on cart value or target category.\r\n * @param coupon - The CouponModel instance to evaluate.\r\n * @param checkExpiry - Whether to check the coupon's expiry status.\r\n * @returns The calculated discount amount (rounded according to country rules).\r\n */\r\n public calculateApplicableCouponDiscount(coupon: CouponModel, checkExpiry: boolean = true): number {\r\n // 1. Basic validation (active)\r\n if (checkExpiry && !coupon.isActive()) {\r\n return 0;\r\n }\r\n\r\n // 2. Check regional requirements (min cart value, max discount)\r\n const minCartValueReq = coupon.getMinCartValue(this.country);\r\n const maxCartDiscountCap = coupon.getMaxCartDiscount(this.country);\r\n\r\n // Ensure minCartValueReq exists and subtotal meets the requirement\r\n if (!minCartValueReq || this.total.subtotal < minCartValueReq.price) {\r\n return 0;\r\n }\r\n\r\n // Ensure maxCartDiscountCap exists and is non-negative\r\n if (!maxCartDiscountCap || maxCartDiscountCap.price < 0) {\r\n return 0;\r\n }\r\n\r\n // 3. Calculate potential discount based on method and category\r\n const couponCategory = coupon.getCategory();\r\n const discountMethod = coupon.getDiscountMethod();\r\n let potentialDiscount = 0;\r\n // Determine the value the coupon applies to (shipping cost or subtotal)\r\n const targetValue = couponCategory === CouponCategory.SHIPPING ? this.total.shipping : this.total.subtotal;\r\n\r\n // No discount if the target value is zero or less\r\n if (targetValue <= 0) return 0;\r\n\r\n switch (discountMethod) {\r\n case CouponDiscountMethod.FLAT:\r\n // Flat discount is capped by the target value itself and the max discount cap\r\n const flatAmount = maxCartDiscountCap?.price ?? 0; // Use cap as the flat amount source? Or coupon.value? Needs clarification. Assuming cap IS the flat amount here.\r\n potentialDiscount = Math.min(targetValue, flatAmount);\r\n break;\r\n case CouponDiscountMethod.PERCENTAGE:\r\n // Calculate percentage discount based on the target value\r\n potentialDiscount = targetValue * (coupon.getPercentageValue() / 100);\r\n break;\r\n default:\r\n // Unknown discount method\r\n return 0;\r\n }\r\n\r\n // 4. Apply maximum discount cap to the calculated potential discount\r\n const finalDiscount = Math.min(potentialDiscount, maxCartDiscountCap.price);\r\n\r\n // 5. Round the final discount, ensuring it's not negative\r\n return PriceModel.getRoundedPrice(Math.max(0, finalDiscount), this.country);\r\n }\r\n\r\n /**\r\n * Recalculates the `couponTotal` map based on currently applied coupons.\r\n * Iterates through coupons, calculates their applicable discount, and stores it.\r\n * @param checkExpiry - Whether to check the expiry status of coupons.\r\n * @returns The total discount amount from all valid and applicable coupons (rounded).\r\n */\r\n public recalculateCouponTotals(checkExpiry: boolean = true): number {\r\n this.total.couponTotal = {};\r\n let totalDiscount = 0;\r\n\r\n this.coupons.forEach(coupon => {\r\n const discount = this.calculateApplicableCouponDiscount(coupon, checkExpiry);\r\n if (discount > 0) {\r\n this.total.couponTotal[coupon.getCode()] = discount; // Store per-coupon discount\r\n totalDiscount += discount; // Accumulate total discount\r\n }\r\n });\r\n // Return the rounded total discount\r\n return PriceModel.getRoundedPrice(totalDiscount, this.country);\r\n }\r\n\r\n\r\n /**\r\n * Gets a plain data object representing the shopping container's current state.\r\n * Includes details from the base model and specific container properties.\r\n * @returns BaseShoppingContainerData object suitable for serialization or API responses.\r\n */\r\n getDetails(): BaseShoppingContainerData {\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n customerId: this.getCustomerId(),\r\n customerEmail: this.getCustomerEmail(),\r\n anonymousId: this.getAnonymousId(),\r\n lineItems: this.getLineItems().map(item => item.getDetails()),\r\n shippingDetails: this.getShippingDetails(),\r\n shippingAddress: this.getShippingAddress()?.getDetails() || null,\r\n billingAddress: this.getBillingAddress()?.getDetails() || null,\r\n coupons: this.getCoupons().map(coupon => coupon.getDetails()),\r\n total: this.getTotal(),\r\n country: this.getCountry(),\r\n currency: this.getCurrency(),\r\n locale: this.getLocale(),\r\n }\r\n };\r\n}\r\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-O5C6Z6AY.mjs';import {a as a$2}from'./chunk-V4H3X4PI.mjs';var c=(e=>(e.ACTIVE="ACTIVE",e.FROZEN="FROZEN",e.MERGED="MERGED",e.ORDERED="ORDERED",e))(c||{}),r=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}},h={expiresAtInSeconds:120*24*60*60},a=class extends a$1{state;expireAt;config;constructor(t,o=new Date,i=h){super(t,o),this.state=t.state,this.expireAt=t.expireAt&&typeof t.expireAt=="number"?t.expireAt:Math.floor(o.getTime()/1e3)+i.expiresAtInSeconds,this.config=i,this.updateCartTotals();}getState(){return this.state}getExpireAt(){return this.expireAt}isActive(){let t=Math.ceil(Date.now()/1e3);return this.state==="ACTIVE"&&this.expireAt>t}updateCartTotals(){this.recalculateBaseTotals(),this.recalculateCouponTotals();let t=this.coupons.filter(e=>e.getCategory()==="SHIPPING").reduce((e,s)=>e+(this.total.couponTotal[s.getCode()]??0),0);this.total.effectiveShipping=a$2.getRoundedPrice(Math.max(0,this.total.shipping-t),this.country);let o=this.coupons.filter(e=>e.getCategory()!=="SHIPPING").reduce((e,s)=>e+(this.total.couponTotal[s.getCode()]??0),0),i=this.total.subtotal+this.total.effectiveShipping;this.total.grandTotal=a$2.getRoundedPrice(Math.max(0,i-o),this.country);}clearCartItems(){this.lineItems=[],this.coupons=[],this.updateCartTotals();}addLineItem(t){let o=t.getProductKey(),i=t.getVariantId(),e=this.lineItems.findIndex(s=>s.getProductKey()===o&&s.getVariantId()===i);return e>=0?this.lineItems[e].addSubItems(t.getSubItems(),!0):this.lineItems.push(t),this.updateCartTotals(),e>=0?e:this.lineItems.length-1}updateLineItem(t,o,i){let e=this.lineItems,s=e.findIndex(l=>l.getId()===t);if(s<0)throw new r(t);return e[s].addSubItems([{size:o,quantity:i}],!1),this.updateCartTotals(),s}removeLineItem(t){let i=this.lineItems.findIndex(e=>e.getId()===t);if(i<0)throw new r(t);return this.lineItems.splice(i,1),this.updateCartTotals(),i}getDetails(){return {...super.getDetails(),state:this.getState(),expireAt:this.getExpireAt()}}};export{c as a,r as b,h as c,a as d};//# sourceMappingURL=chunk-WZLKQEOJ.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-WZLKQEOJ.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/Cart.ts"],"names":["CartState","LineItemNotFoundError","lineItemId","DEFAULT_CART_CONFIG","CartModel","BaseShoppingContainerModel","data","date","config","nowSeconds","shippingCouponDiscount","c","sum","PriceModel","nonShippingCouponDiscount","grossTotal","newLineItem","productKey","variantId","index","item","size","quantity","lineItems"],"mappings":"wFAKYA,IAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,EAAA,MAAS,CAAA,QAAA,CACTA,EAAA,MAAS,CAAA,QAAA,CACTA,EAAA,MAAS,CAAA,QAAA,CACTA,EAAA,OAAU,CAAA,SAAA,CAJAA,OAAA,EAOCC,CAAAA,CAA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EG,CAAS,EAAA,CAAA,CAAIA,EAAQ,IAAK,CAAA,SAAA,CAAU,MAAS,CAAA,CACtD,CAUO,cAAA,CAAgBjB,EAAoBmB,CAAcC,CAAAA,CAAAA,CAAkB,CACzE,IAAMC,CAAAA,CAAY,KAAK,SACnBJ,CAAAA,CAAAA,CAAQI,EAAU,SAAWH,CAAAA,CAAAA,EAASA,EAAK,KAAM,EAAA,GAAMlB,CAAU,CAErE,CAAA,GAAGiB,EAAQ,CACT,CAAA,MAAM,IAAIlB,CAAsBC,CAAAA,CAAU,EAG5C,OAAAqB,CAAAA,CAAUJ,CAAK,CAAE,CAAA,WAAA,CAAY,CAAC,CAAE,IAAA,CAAAE,EAAM,QAAAC,CAAAA,CAAS,CAAC,CAAG,CAAA,CAAA,CAAK,EACxD,IAAK,CAAA,gBAAA,GAEEH,CACT,CAQO,eAAgBjB,CAAoB,CAAA,CAEzC,IAAMiB,CADY,CAAA,IAAA,CAAK,UACC,SAAWC,CAAAA,CAAAA,EAASA,EAAK,KAAM,EAAA,GAAMlB,CAAU,CAEvE,CAAA,GAAGiB,EAAQ,CACT,CAAA,MAAM,IAAIlB,CAAsBC,CAAAA,CAAU,EAG5C,OAAK,IAAA,CAAA,SAAA,CAAU,OAAOiB,CAAO,CAAA,CAAC,EAC9B,IAAK,CAAA,gBAAA,GAEEA,CACT,CAEA,YAAuB,CACrB,OAAO,CACL,GAAG,KAAA,CAAM,YACT,CAAA,KAAA,CAAO,KAAK,QAAS,EAAA,CACrB,SAAU,IAAK,CAAA,WAAA,EACjB,CACF,CACF","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../src/Classes/Cart.ts"],"names":["CartState","LineItemNotFoundError","lineItemId","DEFAULT_CART_CONFIG","CartModel","BaseShoppingContainerModel","data","date","config","nowSeconds","shippingCouponDiscount","c","sum","PriceModel","nonShippingCouponDiscount","grossTotal","newLineItem","productKey","variantId","index","item","size","quantity","lineItems"],"mappings":"wFAKYA,IAAAA,CAAAA,CAAAA,CA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./Price\";\r\nimport BaseShoppingContainerModel, { BaseShoppingContainerAttributes, BaseShoppingContainerData } from \"./ShoppingContainer\";\r\n\r\nexport enum CartState {\r\n ACTIVE = \"ACTIVE\",\r\n FROZEN = \"FROZEN\",\r\n MERGED = \"MERGED\",\r\n ORDERED = \"ORDERED\"\r\n}\r\n\r\nexport class LineItemNotFoundError extends Error {\r\n constructor(lineItemId: string) {\r\n super(`Line item with ID '${lineItemId}' not found in the cart.`);\r\n this.name = 'LineItemNotFoundError';\r\n }\r\n}\r\n\r\n/**\r\n * Input attributes for creating or updating a CartModel.\r\n */\r\nexport type CartAttributes = BaseShoppingContainerAttributes & { \r\n state: CartState;\r\n expireAt: number;\r\n};\r\n\r\nexport type CartData = BaseShoppingContainerData & {\r\n state: CartState;\r\n expireAt: number;\r\n};\r\n\r\nexport type CartConfig = {\r\n expiresAtInSeconds: number;\r\n}\r\n\r\nexport const DEFAULT_CART_CONFIG: CartConfig = {\r\n expiresAtInSeconds: 120 * 24 * 60 * 60\r\n}\r\n\r\nexport default class CartModel extends BaseShoppingContainerModel {\r\n protected state: CartState;\r\n protected expireAt: number;\r\n protected config: CartConfig;\r\n\r\n constructor(data: CartAttributes, date: Date = new Date(), config: CartConfig = DEFAULT_CART_CONFIG) {\r\n super(data, date);\r\n this.state = data.state;\r\n this.expireAt = data.expireAt && typeof data.expireAt === 'number' ? data.expireAt : Math.floor(date.getTime()/1000) + config.expiresAtInSeconds;\r\n this.config = config;\r\n \r\n this.updateCartTotals();\r\n }\r\n\r\n public getState(): CartState {\r\n return this.state;\r\n }\r\n\r\n public getExpireAt(): number {\r\n return this.expireAt;\r\n }\r\n\r\n public isActive(): boolean {\r\n const nowSeconds = Math.ceil(Date.now() / 1000);\r\n return this.state === CartState.ACTIVE && (this.expireAt > nowSeconds);\r\n }\r\n\r\n /**\r\n * Recalculates all container totals (subtotal, mrpTotal, coupons, shipping, grandTotal).\r\n * Should be called whenever line items, coupons, or base shipping cost change.\r\n */\r\n public updateCartTotals(): void {\r\n // 1. Calculate line item totals (subtotal, mrpTotal)\r\n this.recalculateBaseTotals();\r\n\r\n // 2. Calculate total coupon discount and update the per-coupon discount map\r\n this.recalculateCouponTotals(); // This updates this.total.couponTotal\r\n\r\n // 3. Calculate effective shipping cost after applying shipping-specific coupons\r\n const shippingCouponDiscount = this.coupons\r\n .filter(c => c.getCategory() === CouponCategory.SHIPPING)\r\n .reduce((sum, c) => sum + (this.total.couponTotal[c.getCode()] ?? 0), 0);\r\n this.total.effectiveShipping = PriceModel.getRoundedPrice(Math.max(0, this.total.shipping - shippingCouponDiscount), this.country);\r\n\r\n // 4. Calculate total discount from non-shipping coupons\r\n const nonShippingCouponDiscount = this.coupons\r\n .filter(c => c.getCategory() !== CouponCategory.SHIPPING)\r\n .reduce((sum, c) => sum + (this.total.couponTotal[c.getCode()] ?? 0), 0);\r\n\r\n // 5. Calculate final grand total: (subtotal + effective shipping) - non-shipping discounts\r\n const grossTotal = this.total.subtotal + this.total.effectiveShipping;\r\n this.total.grandTotal = PriceModel.getRoundedPrice(Math.max(0, grossTotal - nonShippingCouponDiscount), this.country);\r\n }\r\n \r\n public clearCartItems() {\r\n this.lineItems = [];\r\n this.coupons = [];\r\n this.updateCartTotals();\r\n }\r\n\r\n /**\r\n * Adds a new line item or updates the quantity of an existing one.\r\n * @param newLineItem The LineItemModel to add.\r\n * @returns The index of the added/updated line item in the internal array.\r\n */\r\n public addLineItem (newLineItem: LineItemModel) {\r\n const productKey = newLineItem.getProductKey();\r\n const variantId = newLineItem.getVariantId();\r\n let index = this.lineItems.findIndex(\r\n (item) => item.getProductKey() === productKey && item.getVariantId() === variantId\r\n );\r\n\r\n if(index >= 0){\r\n this.lineItems[index].addSubItems(newLineItem.getSubItems(), true);\r\n } else {\r\n this.lineItems.push(newLineItem);\r\n }\r\n\r\n this.updateCartTotals();\r\n return index >= 0 ? index : this.lineItems.length - 1;\r\n }\r\n\r\n /**\r\n * Updates the quantity for a specific size within a line item.\r\n * @param lineItemId The ID of the LineItemModel to update.\r\n * @param size The size identifier within the line item.\r\n * @param quantity The new quantity for the size (0 to remove).\r\n * @returns The index of the updated line item.\r\n * @throws {Error} If the line item is not found.\r\n */\r\n public updateLineItem (lineItemId: string, size: string, quantity: number) {\r\n const lineItems = this.lineItems;\r\n let index = lineItems.findIndex((item) => item.getId() === lineItemId);\r\n \r\n if(index < 0){\r\n throw new LineItemNotFoundError(lineItemId);\r\n }\r\n\r\n lineItems[index].addSubItems([{ size, quantity }], false);\r\n this.updateCartTotals();\r\n\r\n return index;\r\n }\r\n\r\n /**\r\n * Removes a line item completely from the cart.\r\n * @param lineItemId The ID of the LineItemModel to remove.\r\n * @returns The index the item previously occupied.\r\n * @throws {Error} If the line item is not found.\r\n */\r\n public removeLineItem (lineItemId: string) {\r\n const lineItems = this.lineItems;\r\n const index = lineItems.findIndex((item) => item.getId() === lineItemId);\r\n\r\n if(index < 0){\r\n throw new LineItemNotFoundError(lineItemId);\r\n }\r\n\r\n this.lineItems.splice(index, 1);\r\n this.updateCartTotals();\r\n\r\n return index;\r\n }\r\n\r\n getDetails(): CartData {\r\n return {\r\n ...super.getDetails(),\r\n state: this.getState(),\r\n expireAt: this.getExpireAt(),\r\n }\r\n }\r\n}\r\n"]}
|