b23-lib 3.2.2 → 3.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Auth/index.mjs +1 -1
- package/dist/Classes/Cart.js +1 -1
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Charge.d.mts +2 -2
- package/dist/Classes/Charge.d.ts +2 -2
- package/dist/Classes/Charge.js +1 -1
- package/dist/Classes/Charge.js.map +1 -1
- package/dist/Classes/Charge.mjs +1 -1
- package/dist/Classes/Coupon.mjs +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/Invoice.d.mts +32 -5
- package/dist/Classes/Invoice.d.ts +32 -5
- package/dist/Classes/Invoice.js +1 -1
- package/dist/Classes/Invoice.js.map +1 -1
- package/dist/Classes/Invoice.mjs +1 -1
- package/dist/Classes/Invoice.mjs.map +1 -1
- package/dist/Classes/LineItem.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/Product.mjs +1 -1
- package/dist/Classes/ShoppingContainer.js +1 -1
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/{chunk-5IRYC2KY.mjs → chunk-B2VFJRLS.mjs} +2 -2
- package/dist/{chunk-5IRYC2KY.mjs.map → chunk-B2VFJRLS.mjs.map} +1 -1
- package/dist/{chunk-XJPFHEW3.mjs → chunk-G6LH7V5B.mjs} +2 -2
- package/dist/{chunk-XJPFHEW3.mjs.map → chunk-G6LH7V5B.mjs.map} +1 -1
- package/dist/{chunk-QGIQ3MH6.mjs → chunk-MHLRJ4IJ.mjs} +2 -2
- package/dist/{chunk-QGIQ3MH6.mjs.map → chunk-MHLRJ4IJ.mjs.map} +1 -1
- package/dist/{chunk-PWWKQNF7.mjs → chunk-RQ2FFWUW.mjs} +2 -2
- package/dist/{chunk-PWWKQNF7.mjs.map → chunk-RQ2FFWUW.mjs.map} +1 -1
- package/dist/{chunk-MJGCYQ53.mjs → chunk-VTBHWXR4.mjs} +2 -2
- package/dist/{chunk-MJGCYQ53.mjs.map → chunk-VTBHWXR4.mjs.map} +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/Classes/Cart.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'../chunk-
|
|
1
|
+
import {a}from'../chunk-VTBHWXR4.mjs';import'../chunk-B2VFJRLS.mjs';import'../chunk-RQ2FFWUW.mjs';import'../chunk-HX32EJ3F.mjs';import'../chunk-G6LH7V5B.mjs';import'../chunk-SOZHGHMY.mjs';import {b}from'../chunk-MHLRJ4IJ.mjs';import'../chunk-FCRJAAPY.mjs';import'../chunk-2B2XI6FG.mjs';import'../chunk-LI5JQ6UC.mjs';import'../chunk-QK4XJ3GB.mjs';import {a as a$1}from'../chunk-R5DM7WCD.mjs';import'../chunk-UXZBULDS.mjs';var u=(i=>(i.ACTIVE="ACTIVE",i.FROZEN="FROZEN",i.MERGED="MERGED",i.ORDERED="ORDERED",i))(u||{}),p={expiresAtInSeconds:120*24*60*60},c=class extends a{state;expireAt;config;constructor(t,e=new Date,r=p){super(t,e),this.state=t.state,this.expireAt=t.expireAt&&typeof t.expireAt=="number"?t.expireAt:Math.floor(e.getTime()/1e3)+r.expiresAtInSeconds,this.config=r;}getState(){return this.state}getExpireAt(){return this.expireAt}isActive(){let t=Math.ceil(Date.now()/1e3);return this.state==="ACTIVE"&&this.expireAt>t}clearCartItems(){this.lineItems=[],this.charges=[],this.coupons=[],this.shippingDetails=null,this.calculateTotals();}validateLineItems(t){this.lineItems=this.lineItems.map(e=>{try{e.updateProductData(t[e.getProductKey()],this.country,this.currency);}catch(r){console.error(`Error recalculating line item ${e.getId()}:`,r),e.clearLineItem();}return e}).filter(e=>e.getId()),this.calculateTotals();}addLineItem(t){let e=t.getProductKey(),r=t.getSelectionAttributes(),i=b.generateSelectionAttributesKey(r),s=this.lineItems.findIndex(n=>n.getProductKey()===e&&b.generateSelectionAttributesKey(n.getSelectionAttributes())===i);return s>=0?this.lineItems[s].addSubItems(t.getSubItems(),!0):this.lineItems.push(t),this.calculateTotals(),s>=0?s:this.lineItems.length-1}updateLineItem(t,e,r){let i=this.lineItems,s=i.findIndex(n=>n.getId()===t);if(s<0)throw new a$1(t);return i[s].addSubItems([{size:e,quantity:r}],!1),this.calculateTotals(),s}removeLineItem(t){let r=this.lineItems.findIndex(i=>i.getId()===t);if(r<0)throw new a$1(t);return this.lineItems.splice(r,1),this.charges=this.charges.filter(i=>i.getLineItemId()!==t),this.calculateTotals(),r}getDetails(){return {...super.getDetails(),state:this.getState(),expireAt:this.getExpireAt()}}};export{u as CartState,p as DEFAULT_CART_CONFIG,c as default};//# sourceMappingURL=Cart.mjs.map
|
|
2
2
|
//# sourceMappingURL=Cart.mjs.map
|
|
@@ -156,8 +156,8 @@ declare class ChargeModel extends CustomFieldModel {
|
|
|
156
156
|
*/
|
|
157
157
|
private validateTaxRules;
|
|
158
158
|
/**
|
|
159
|
-
|
|
160
|
-
|
|
159
|
+
* Updates the discounts applied to this line item and recalculates totals.
|
|
160
|
+
* @param appliedDiscounts - List of coupons and their allocated discount amounts.
|
|
161
161
|
*/
|
|
162
162
|
updateDiscounts(appliedDiscounts: {
|
|
163
163
|
coupon: CouponModel;
|
package/dist/Classes/Charge.d.ts
CHANGED
|
@@ -156,8 +156,8 @@ declare class ChargeModel extends CustomFieldModel {
|
|
|
156
156
|
*/
|
|
157
157
|
private validateTaxRules;
|
|
158
158
|
/**
|
|
159
|
-
|
|
160
|
-
|
|
159
|
+
* Updates the discounts applied to this line item and recalculates totals.
|
|
160
|
+
* @param appliedDiscounts - List of coupons and their allocated discount amounts.
|
|
161
161
|
*/
|
|
162
162
|
updateDiscounts(appliedDiscounts: {
|
|
163
163
|
coupon: CouponModel;
|
package/dist/Classes/Charge.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var ge=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ge__default=/*#__PURE__*/_interopDefault(ge);var ne=r=>structuredClone(r),M=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:ne(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return ne(this.customFields)}},U=class extends M{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,t,i,n){this.modifiedBy={id:e,authType:t,requestId:i,lambdaName:n};}};var z=new Uint8Array(256),k=z.length;function W(){return k>z.length-16&&(ge__default.default.randomFillSync(z),k=0),z.slice(k,k+=16)}var oe=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function me(r){return typeof r=="string"&&oe.test(r)}var se=me;var p=[];for(let r=0;r<256;++r)p.push((r+256).toString(16).slice(1));function V(r,e=0){return p[r[e+0]]+p[r[e+1]]+p[r[e+2]]+p[r[e+3]]+"-"+p[r[e+4]]+p[r[e+5]]+"-"+p[r[e+6]]+p[r[e+7]]+"-"+p[r[e+8]]+p[r[e+9]]+"-"+p[r[e+10]]+p[r[e+11]]+p[r[e+12]]+p[r[e+13]]+p[r[e+14]]+p[r[e+15]]}function pe(r){if(!se(r))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(r.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(r.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(r.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(r.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var ae=pe;function he(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var ye="6ba7b810-9dad-11d1-80b4-00c04fd430c8",fe="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function _(r,e,t){function i(n,o,a,l){var c;if(typeof n=="string"&&(n=he(n)),typeof o=="string"&&(o=ae(o)),((c=o)===null||c===void 0?void 0:c.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let u=new Uint8Array(16+n.length);if(u.set(o),u.set(n,o.length),u=t(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,a){l=l||0;for(let m=0;m<16;++m)a[l+m]=u[m];return a}return V(u)}try{i.name=r;}catch{}return i.DNS=ye,i.URL=fe,i}var ee={randomUUID:ge__default.default.randomUUID};function be(r,e,t){if(ee.randomUUID&&!e&&!r)return ee.randomUUID();r=r||{};let i=r.random||(r.rng||W)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(let n=0;n<16;++n)e[t+n]=i[n];return e}return V(i)}var te=be;function Ae(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),ge__default.default.createHash("sha1").update(r).digest()}var ce=Ae;var Ce=_("v5",80,ce),re=Ce;var C={"en-IN":"en","kn-IN":"kn"};var ue={INR:"\u20B9"},le={INR:"en-IN"};var Q=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var T=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var j=class extends Error{constructor(e="Tax rule category mismatch."){super(`InvalidTaxRule: ${e}`),this.name="InvalidTaxRuleError";}},G=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},K=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},q=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},Y=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},H=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var B=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},D=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},A=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},f=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},F=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}},$=class extends Error{constructor(e="Invalid charge data."){super(`InvalidCharge: ${e}`),this.name="InvalidChargeError";}},R=class extends Error{constructor(e="Invalid charge tax rule."){super(`InvalidChargeTaxRule: ${e}`),this.name="InvalidChargeTaxRuleError";}};var E=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw new F("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,t){if(t===void 0){if(e==="original")throw new F("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=t;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var s=class r{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new B("Amount cannot be negative.");if(!e.currency)throw new D("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(r.getPrecisionPlaces(this.currency)));}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}getPreciseAmount(e){return parseFloat(e.toFixed(r.getPrecisionPlaces(this.currency)))}compareTo(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new A("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new A("Cannot add prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return new r({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new A("Cannot subtract prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return new r({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new A("Cannot multiply prices in different currencies.");return new r({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new r({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new f("Must be a non-negative number.")}divide(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new A("Cannot divide prices in different currencies.");return new r({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new r({amount:this.getPreciseAmount(this.amount/e),currency:this.currency});throw new f("Must be a positive number.")}min(...e){if(e.length===0)throw new f("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new A("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i},this)}max(...e){if(e.length===0)throw new f("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new A("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return t.compareTo(i)>0?t:i},this)}zero(){return new r({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new r({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return r.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return r.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,t,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=le[t];if(!t||!n)throw new D("Invalid currency code for formatting.");let o=e,a=i.displayAsInteger?0:r.getDecimalPlaces(t),l={style:i.style??"currency",currency:t,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,l).format(o)}catch(c){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,c),`${ue[t]??t} ${r.addThousandSeparators(o.toFixed(a))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static getPrecisionPlaces(e){switch(e){case"INR":default:return 6}}static addThousandSeparators(e){let t=e.split("."),i=t[0],n=t.length>1?"."+t[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,t){if(e<0)throw new B("Amount cannot be negative for rounding.");if(t===void 0)throw new D("Invalid currency code for rounding.");let i=r.getDecimalPlaces(t),n=Math.pow(10,i);return Math.round(e*n)/n}};var Z=class{baseUnitPrice;taxCategory;tiers;constructor(e){let t=new s(e.baseUnitPrice);if(!e.taxCategory)throw new G;let i=(e.tiers??[]).map(c=>({minQuantity:c.minQuantity,unitPrice:new s(c.unitPrice)})).sort((c,u)=>c.minQuantity-u.minQuantity);if(i.some(c=>c.minQuantity<=0))throw new K;let o=i.some(c=>c.unitPrice.getCurrency()!==t.getCurrency()),a=i.some((c,u)=>u>0&&c.unitPrice.compareTo(i[u-1].unitPrice)>0),l=i[0]?.unitPrice.compareTo(t)>0;if(o||a||l)throw new q("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=t,this.taxCategory=e.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}getApplicableTier(e){if(e<=0)throw new Y;for(let t=this.tiers.length-1;t>=0;t--)if(e>=this.tiers[t].minQuantity){let i=this.tiers[t];return {minQuantity:i.minQuantity,unitPrice:i.unitPrice}}throw new H(e)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let e=this.tiers[this.tiers.length-1].unitPrice.getAmount(),t=this.baseUnitPrice.getAmount();return (t-e)/t*100}};var v=class r extends U{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new T("Selection attributes must be an object");return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let t={},i=e.split("|");for(let n of i){let[o,a]=n.split(":");a.startsWith("c+")?t[o]={name:a.slice(2)}:t[o]=a;}return t}catch(t){throw new T(t?.message)}}constructor(e,t=new Date){super(e,t),this.id=e.id,this.key=e.key,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((n,o)=>(e.pricing[o]&&(n[o]=new Z(e.pricing[o])),n),{}),this.targetGender=e.targetGender,this.attributes=g.deepClone(e.attributes),this.specifications=g.deepClone(e.specifications),this.categories=g.deepClone(e.categories);let i=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new T("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let o=r.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(o))throw new Q(o);return i.add(o),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new E(n.images.primary),gallery:(n.images.gallery||[]).map(a=>new E(a))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?g.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[C[e]]??this.name.en:g.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[C[e]]??this.description.en:g.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[C[e]]??this.slug.en:g.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return g.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:g.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let t=r.generateSelectionAttributesKey(e),i=this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===t);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,t){switch(t){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return g.deepClone(this.categories)}getSpecifications(e){return e?g.deepClone(this.specifications[e]??this.specifications[C[e]]??this.specifications.en):g.deepClone(this.specifications)}getSearchTags(e){return e?g.deepClone(this.searchTags[e]??this.searchTags[C[e]]??this.searchTags.en):g.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((t,i)=>(this.pricing[i]&&(t[i]=this.pricing[i]?.getDetails()),t),{}),attributes:this.getAttributes(),variants:this.variants.map(t=>({sku:t.sku,selectionAttributes:g.deepClone(t.selectionAttributes),images:{primary:t.images.primary.getDetails(),gallery:t.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new T("Selection attributes are required");Object.keys(this.attributes).forEach(t=>{if(t.toLowerCase()==="size")return;let i=this.attributes[t],n=e[t];if(n===void 0)throw new T(`Selection attribute '${t}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new T(`Selection attribute '${t}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new T(`Selection attribute '${t}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(o=>o.name===n.name)<0)throw new T(`Selection attribute '${t}' is invalid`)}});}validateSelectionAttribute(e){let t=r.generateSelectionAttributesKey(e);return this.variants.some(i=>r.generateSelectionAttributesKey(i.selectionAttributes)===t)}validateSize(e){return this.attributes.size.includes(e)}};var Ie={isUUID:r=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(r),isEmail:r=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r),isURL:r=>/^(http|https):\/\/[^ "]+$/.test(r),generateUUID:(r,e)=>e&&r?re(r,e):te(),generateSearchId:(r,e)=>`${r}#${v.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:r=>{let[e,t]=r.split("#");return {key:e,selectionAttributes:v.parseSelectionAttributesKey(t)}},deepClone(r){return structuredClone(r)}},g=Ie;var J=class extends M{taxRuleId;taxCategory;taxSystem;taxSubSystem;country;rate;minPrice;maxPrice;excludeMin;excludeMax;effectiveFrom;effectiveTo;constructor(e){super(e),this.taxRuleId=e.taxRuleId,this.taxSystem=e.taxSystem,this.taxSubSystem=e.taxSubSystem,this.taxCategory=e.taxCategory,this.country=e.country,this.rate=e.rate,this.minPrice=new s(e.minPrice),this.maxPrice=e.maxPrice?new s(e.maxPrice):void 0,this.excludeMin=e.excludeMin??!1,this.excludeMax=e.excludeMax??!1,this.effectiveFrom=new Date(e.effectiveFrom).toISOString(),this.effectiveTo=e.effectiveTo?new Date(e.effectiveTo).toISOString():void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getRate(){return this.rate}getMinPrice(){return this.minPrice}getMaxPrice(){return this.maxPrice}getExcludeMin(){return this.excludeMin}getExcludeMax(){return this.excludeMax}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),rate:this.getRate(),minPrice:this.getMinPrice().getDetails(),maxPrice:this.getMaxPrice()?.getDetails(),excludeMin:this.getExcludeMin(),excludeMax:this.getExcludeMax(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0,customFields:this.getAllCustomFields()}}appliesTo(e,t,i,n=new Date){let o=!i||(this.excludeMin?this.minPrice.compareTo(i)<0:this.minPrice.compareTo(i)<=0)&&(this.maxPrice?this.excludeMax?this.maxPrice.compareTo(i)>0:this.maxPrice.compareTo(i)>=0:!0);return this.taxCategory===e&&this.country===t&&o&&Date.parse(this.effectiveFrom)<=n.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=n.getTime():!0)}getApplicableTaxRate(e){return this.appliesTo(this.taxCategory,this.country,e)?this.rate:0}calculateTax(e){return this.appliesTo(this.taxCategory,this.country,e)?e.multiply(this.rate):e.zero()}static getTaxRateDisplayString(e,t,i){let n=t*100,o=n%1===0?n.toString():n.toFixed(2).replace(/\.?0+$/,"");return i?.percentageOnly?`${o}%`:e.getTaxSystem()==="GST"?`${e.getTaxSubSystem()} ${o}%`:`${e.getTaxSystem()} ${o}%`}};var ie=class extends M{id;name;type;category;impact;pricing;lineItemId;total;constructor(e){if(super(e),this.id=e.id,this.name=e.name,this.type=e.type,this.category=e.category,this.impact=e.impact,this.lineItemId=e.lineItemId,this.pricing={baseChargeAmount:new s(e.pricing.baseChargeAmount),taxCategory:e.pricing.taxCategory,applicableTaxRule:e.pricing.applicableTaxRule.map(t=>new J(t))},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new $("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={chargeAmount:new s(e.total.chargeAmount),discountTotal:new s(e.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(e.total.discountBreakdown).map(([t,i])=>[t,new s(i)])),netChargeAmount:new s(e.total.netChargeAmount),taxBreakdown:Object.fromEntries(Object.entries(e.total.taxBreakdown).map(([t,i])=>[t,{rate:i.rate,taxableAmount:new s(i.taxableAmount),taxAmount:new s(i.taxAmount),system:i.system,subSystem:i.subSystem}])),taxTotal:new s(e.total.taxTotal),grandTotal:new s(e.total.grandTotal)};}getId(){return this.id}getName(e){return e?g.deepClone(this.name[e]??this.name[C[e]]??this.name.en):g.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getPricing(){return {baseChargeAmount:this.pricing.baseChargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {chargeAmount:this.total.chargeAmount,discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},netChargeAmount:this.total.netChargeAmount,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,t])=>[e,{rate:t.rate,taxableAmount:t.taxableAmount,taxAmount:t.taxAmount,system:t.system,subSystem:t.subSystem}])),grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(e){if(this.type==="ADJUSTMENT"&&e.length>0)throw new $("Adjustment charges cannot apply tax rules.");e.forEach(t=>{if(!t.appliesTo(this.pricing.taxCategory,t.getCountry()))throw new j}),this.validateTaxRules(e),this.pricing.applicableTaxRule=e,this.calculateTotals();}validateTaxRules(e){if(this.impact==="SUBTRACT"&&e.some(i=>i.getRate()>0))throw new R("Subtractive charges cannot have positive tax rates.");let t=new Set;for(let i=0;i<e.length;i++){let n=e[i].getTaxRuleId();if(t.has(n))throw new R("Duplicate tax rule ID found: "+n);t.add(n);for(let o=i+1;o<e.length;o++){let a=e[i],l=e[o],c=a.getMinPrice(),u=a.getMaxPrice(),m=a.getExcludeMin(),I=a.getExcludeMax(),w=l.getMinPrice(),x=l.getMaxPrice(),P=l.getExcludeMin(),L=l.getExcludeMax(),h=(()=>{if(!u)return !1;let b=u.compareTo(w);return b<0||b===0&&(I||P)})(),y=(()=>{if(!x)return !1;let b=x.compareTo(c);return b<0||b===0&&(L||m)})();if(!(h||y)&&!(c.compareTo(w)===0&&m===P&&I===L&&(!u&&!x||u&&x&&u.compareTo(x)===0)))throw new R(`Overlapping rules found: [${a.getTaxRuleId()}: ${m?"(":"["}${c.getAmount()}-${u?.getAmount()??"Infinity"}${I?")":"]"}] and [${l.getTaxRuleId()}: ${P?"(":"["}${w.getAmount()}-${x?.getAmount()??"Infinity"}${L?")":"]"}]`)}}}updateDiscounts(e){let t={};e.forEach(i=>{t[i.coupon.getCode()]=i.amount;}),this.total.discountBreakdown=t,this.calculateTotals();}calculateTotals(){let e=this.pricing.baseChargeAmount.zero(),t=this.pricing.baseChargeAmount,i=Object.values(this.total.discountBreakdown).reduce((h,y)=>h.add(y),e),n=t.subtract(i),o={},a=this.pricing.applicableTaxRule.reduce((h,y)=>h+y.getApplicableTaxRate(n),0);if(a<=0){this.total={chargeAmount:t,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:n,taxTotal:e,taxBreakdown:{},grandTotal:n};return}let l=t.getCurrency(),c=t.getAmount(),u=1e3,m=s.getRoundedAmount(c/(1+a),l),I=m,w=Number.POSITIVE_INFINITY;for(let h=0;h<u;h++){let y=new s({amount:m,currency:l}),b=this.pricing.applicableTaxRule.sort((S,N)=>N.getApplicableTaxRate(y)-S.getApplicableTaxRate(y)).map(S=>s.getRoundedAmount(m*S.getApplicableTaxRate(y),l)).reduce((S,N)=>S+N,0),O=m+b-c,de=this.pricing.applicableTaxRule.reduce((S,N)=>S+N.getApplicableTaxRate(y),0);if(Math.abs(O)<Math.abs(w)&&(w=O,I=m),O===0||(m=m-O/(1+de),m<0||m>c))break}let x=new s({amount:I,currency:l}),P=e;this.pricing.applicableTaxRule.sort((h,y)=>y.getApplicableTaxRate(x)-h.getApplicableTaxRate(x)).forEach(h=>{let y=h.getApplicableTaxRate(x),X=s.getRoundedAmount(I*y,l),b=new s({amount:X,currency:l});o[h.getTaxRuleId()]={rate:y,taxableAmount:x,taxAmount:b,system:h.getTaxSystem(),subSystem:h.getTaxSubSystem()},P=P.add(b);});let L=n;this.total={chargeAmount:t,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:n,taxBreakdown:o,taxTotal:P,grandTotal:L};}getDetails(){return {id:this.id,name:g.deepClone(this.name),type:this.type,category:this.category,pricing:{baseChargeAmount:this.pricing.baseChargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(t=>t.getDetails())},impact:this.impact,lineItemId:this.lineItemId,total:{chargeAmount:this.total.chargeAmount.getDetails(),discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([t,i])=>[t,i.getDetails()])),netChargeAmount:this.total.netChargeAmount.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,i])=>[t,{rate:i.rate,taxableAmount:i.taxableAmount.getDetails(),taxAmount:i.taxAmount.getDetails(),system:i.system,subSystem:i.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};module.exports=ie;//# sourceMappingURL=Charge.js.map
|
|
1
|
+
'use strict';var ge=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ge__default=/*#__PURE__*/_interopDefault(ge);var ne=r=>structuredClone(r),M=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:ne(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return ne(this.customFields)}},U=class extends M{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,t,i,n){this.modifiedBy={id:e,authType:t,requestId:i,lambdaName:n};}};var z=new Uint8Array(256),k=z.length;function W(){return k>z.length-16&&(ge__default.default.randomFillSync(z),k=0),z.slice(k,k+=16)}var oe=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function me(r){return typeof r=="string"&&oe.test(r)}var se=me;var p=[];for(let r=0;r<256;++r)p.push((r+256).toString(16).slice(1));function V(r,e=0){return p[r[e+0]]+p[r[e+1]]+p[r[e+2]]+p[r[e+3]]+"-"+p[r[e+4]]+p[r[e+5]]+"-"+p[r[e+6]]+p[r[e+7]]+"-"+p[r[e+8]]+p[r[e+9]]+"-"+p[r[e+10]]+p[r[e+11]]+p[r[e+12]]+p[r[e+13]]+p[r[e+14]]+p[r[e+15]]}function pe(r){if(!se(r))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(r.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(r.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(r.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(r.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var ae=pe;function he(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var ye="6ba7b810-9dad-11d1-80b4-00c04fd430c8",fe="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function _(r,e,t){function i(n,o,a,l){var c;if(typeof n=="string"&&(n=he(n)),typeof o=="string"&&(o=ae(o)),((c=o)===null||c===void 0?void 0:c.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let u=new Uint8Array(16+n.length);if(u.set(o),u.set(n,o.length),u=t(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,a){l=l||0;for(let m=0;m<16;++m)a[l+m]=u[m];return a}return V(u)}try{i.name=r;}catch{}return i.DNS=ye,i.URL=fe,i}var ee={randomUUID:ge__default.default.randomUUID};function be(r,e,t){if(ee.randomUUID&&!e&&!r)return ee.randomUUID();r=r||{};let i=r.random||(r.rng||W)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(let n=0;n<16;++n)e[t+n]=i[n];return e}return V(i)}var te=be;function Ae(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),ge__default.default.createHash("sha1").update(r).digest()}var ce=Ae;var Ce=_("v5",80,ce),re=Ce;var C={"en-IN":"en","kn-IN":"kn"};var ue={INR:"\u20B9"},le={INR:"en-IN"};var Q=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var T=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var j=class extends Error{constructor(e="Tax rule category mismatch."){super(`InvalidTaxRule: ${e}`),this.name="InvalidTaxRuleError";}},G=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},K=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},q=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},Y=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},H=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var B=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},D=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},A=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},f=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},F=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}},$=class extends Error{constructor(e="Invalid charge data."){super(`InvalidCharge: ${e}`),this.name="InvalidChargeError";}},R=class extends Error{constructor(e="Invalid charge tax rule."){super(`InvalidChargeTaxRule: ${e}`),this.name="InvalidChargeTaxRuleError";}};var E=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw new F("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,t){if(t===void 0){if(e==="original")throw new F("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=t;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var s=class r{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new B("Amount cannot be negative.");if(!e.currency)throw new D("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(r.getPrecisionPlaces(this.currency)));}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}getPreciseAmount(e){return parseFloat(e.toFixed(r.getPrecisionPlaces(this.currency)))}compareTo(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new A("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new A("Cannot add prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return new r({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new A("Cannot subtract prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return new r({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new A("Cannot multiply prices in different currencies.");return new r({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new r({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new f("Must be a non-negative number.")}divide(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new A("Cannot divide prices in different currencies.");return new r({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new r({amount:this.getPreciseAmount(this.amount/e),currency:this.currency});throw new f("Must be a positive number.")}min(...e){if(e.length===0)throw new f("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new A("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i},this)}max(...e){if(e.length===0)throw new f("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new A("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return t.compareTo(i)>0?t:i},this)}zero(){return new r({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new r({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return r.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return r.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,t,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=le[t];if(!t||!n)throw new D("Invalid currency code for formatting.");let o=e,a=i.displayAsInteger?0:r.getDecimalPlaces(t),l={style:i.style??"currency",currency:t,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,l).format(o)}catch(c){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,c),`${ue[t]??t} ${r.addThousandSeparators(o.toFixed(a))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static getPrecisionPlaces(e){switch(e){case"INR":default:return 6}}static addThousandSeparators(e){let t=e.split("."),i=t[0],n=t.length>1?"."+t[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,t){if(e<0)throw new B("Amount cannot be negative for rounding.");if(t===void 0)throw new D("Invalid currency code for rounding.");let i=r.getDecimalPlaces(t),n=Math.pow(10,i);return Math.round(e*n)/n}};var Z=class{baseUnitPrice;taxCategory;tiers;constructor(e){let t=new s(e.baseUnitPrice);if(!e.taxCategory)throw new G;let i=(e.tiers??[]).map(c=>({minQuantity:c.minQuantity,unitPrice:new s(c.unitPrice)})).sort((c,u)=>c.minQuantity-u.minQuantity);if(i.some(c=>c.minQuantity<=0))throw new K;let o=i.some(c=>c.unitPrice.getCurrency()!==t.getCurrency()),a=i.some((c,u)=>u>0&&c.unitPrice.compareTo(i[u-1].unitPrice)>0),l=i[0]?.unitPrice.compareTo(t)>0;if(o||a||l)throw new q("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=t,this.taxCategory=e.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}getApplicableTier(e){if(e<=0)throw new Y;for(let t=this.tiers.length-1;t>=0;t--)if(e>=this.tiers[t].minQuantity){let i=this.tiers[t];return {minQuantity:i.minQuantity,unitPrice:i.unitPrice}}throw new H(e)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let e=this.tiers[this.tiers.length-1].unitPrice.getAmount(),t=this.baseUnitPrice.getAmount();return (t-e)/t*100}};var v=class r extends U{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new T("Selection attributes must be an object");return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let t={},i=e.split("|");for(let n of i){let[o,a]=n.split(":");a.startsWith("c+")?t[o]={name:a.slice(2)}:t[o]=a;}return t}catch(t){throw new T(t?.message)}}constructor(e,t=new Date){super(e,t),this.id=e.id,this.key=e.key,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((n,o)=>(e.pricing[o]&&(n[o]=new Z(e.pricing[o])),n),{}),this.targetGender=e.targetGender,this.attributes=g.deepClone(e.attributes),this.specifications=g.deepClone(e.specifications),this.categories=g.deepClone(e.categories);let i=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new T("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let o=r.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(o))throw new Q(o);return i.add(o),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new E(n.images.primary),gallery:(n.images.gallery||[]).map(a=>new E(a))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?g.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[C[e]]??this.name.en:g.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[C[e]]??this.description.en:g.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[C[e]]??this.slug.en:g.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return g.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:g.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let t=r.generateSelectionAttributesKey(e),i=this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===t);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,t){switch(t){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return g.deepClone(this.categories)}getSpecifications(e){return e?g.deepClone(this.specifications[e]??this.specifications[C[e]]??this.specifications.en):g.deepClone(this.specifications)}getSearchTags(e){return e?g.deepClone(this.searchTags[e]??this.searchTags[C[e]]??this.searchTags.en):g.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((t,i)=>(this.pricing[i]&&(t[i]=this.pricing[i]?.getDetails()),t),{}),attributes:this.getAttributes(),variants:this.variants.map(t=>({sku:t.sku,selectionAttributes:g.deepClone(t.selectionAttributes),images:{primary:t.images.primary.getDetails(),gallery:t.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new T("Selection attributes are required");Object.keys(this.attributes).forEach(t=>{if(t.toLowerCase()==="size")return;let i=this.attributes[t],n=e[t];if(n===void 0)throw new T(`Selection attribute '${t}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new T(`Selection attribute '${t}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new T(`Selection attribute '${t}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(o=>o.name===n.name)<0)throw new T(`Selection attribute '${t}' is invalid`)}});}validateSelectionAttribute(e){let t=r.generateSelectionAttributesKey(e);return this.variants.some(i=>r.generateSelectionAttributesKey(i.selectionAttributes)===t)}validateSize(e){return this.attributes.size.includes(e)}};var Ie={isUUID:r=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(r),isEmail:r=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r),isURL:r=>/^(http|https):\/\/[^ "]+$/.test(r),generateUUID:(r,e)=>e&&r?re(r,e):te(),generateSearchId:(r,e)=>`${r}#${v.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:r=>{let[e,t]=r.split("#");return {key:e,selectionAttributes:v.parseSelectionAttributesKey(t)}},deepClone(r){return structuredClone(r)}},g=Ie;var J=class extends M{taxRuleId;taxCategory;taxSystem;taxSubSystem;country;rate;minPrice;maxPrice;excludeMin;excludeMax;effectiveFrom;effectiveTo;constructor(e){super(e),this.taxRuleId=e.taxRuleId,this.taxSystem=e.taxSystem,this.taxSubSystem=e.taxSubSystem,this.taxCategory=e.taxCategory,this.country=e.country,this.rate=e.rate,this.minPrice=new s(e.minPrice),this.maxPrice=e.maxPrice?new s(e.maxPrice):void 0,this.excludeMin=e.excludeMin??!1,this.excludeMax=e.excludeMax??!1,this.effectiveFrom=new Date(e.effectiveFrom).toISOString(),this.effectiveTo=e.effectiveTo?new Date(e.effectiveTo).toISOString():void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getRate(){return this.rate}getMinPrice(){return this.minPrice}getMaxPrice(){return this.maxPrice}getExcludeMin(){return this.excludeMin}getExcludeMax(){return this.excludeMax}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),rate:this.getRate(),minPrice:this.getMinPrice().getDetails(),maxPrice:this.getMaxPrice()?.getDetails(),excludeMin:this.getExcludeMin(),excludeMax:this.getExcludeMax(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0,customFields:this.getAllCustomFields()}}appliesTo(e,t,i,n=new Date){let o=!i||(this.excludeMin?this.minPrice.compareTo(i)<0:this.minPrice.compareTo(i)<=0)&&(this.maxPrice?this.excludeMax?this.maxPrice.compareTo(i)>0:this.maxPrice.compareTo(i)>=0:!0);return this.taxCategory===e&&this.country===t&&o&&Date.parse(this.effectiveFrom)<=n.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=n.getTime():!0)}getApplicableTaxRate(e){return this.appliesTo(this.taxCategory,this.country,e)?this.rate:0}calculateTax(e){return this.appliesTo(this.taxCategory,this.country,e)?e.multiply(this.rate):e.zero()}static getTaxRateDisplayString(e,t,i){let n=t*100,o=n%1===0?n.toString():n.toFixed(2).replace(/\.?0+$/,"");return i?.percentageOnly?`${o}%`:e.getTaxSystem()==="GST"?`${e.getTaxSubSystem()} ${o}%`:`${e.getTaxSystem()} ${o}%`}};var ie=class extends M{id;name;type;category;impact;pricing;lineItemId;total;constructor(e){if(super(e),this.id=e.id,this.name=e.name,this.type=e.type,this.category=e.category,this.impact=e.impact,this.lineItemId=e.lineItemId,this.pricing={baseChargeAmount:new s(e.pricing.baseChargeAmount),taxCategory:e.pricing.taxCategory,applicableTaxRule:e.pricing.applicableTaxRule.map(t=>new J(t))},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new $("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={chargeAmount:new s(e.total.chargeAmount),discountTotal:new s(e.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(e.total.discountBreakdown).map(([t,i])=>[t,new s(i)])),netChargeAmount:new s(e.total.netChargeAmount),taxBreakdown:Object.fromEntries(Object.entries(e.total.taxBreakdown).map(([t,i])=>[t,{rate:i.rate,taxableAmount:new s(i.taxableAmount),taxAmount:new s(i.taxAmount),system:i.system,subSystem:i.subSystem}])),taxTotal:new s(e.total.taxTotal),grandTotal:new s(e.total.grandTotal)};}getId(){return this.id}getName(e){return e?g.deepClone(this.name[e]??this.name[C[e]]??this.name.en):g.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getPricing(){return {baseChargeAmount:this.pricing.baseChargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {chargeAmount:this.total.chargeAmount,discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},netChargeAmount:this.total.netChargeAmount,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,t])=>[e,{rate:t.rate,taxableAmount:t.taxableAmount,taxAmount:t.taxAmount,system:t.system,subSystem:t.subSystem}])),grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(e){if(this.type==="ADJUSTMENT"&&e.length>0)throw new $("Adjustment charges cannot apply tax rules.");e.forEach(t=>{if(!t.appliesTo(this.pricing.taxCategory,t.getCountry()))throw new j}),this.validateTaxRules(e),this.pricing.applicableTaxRule=e,this.calculateTotals();}validateTaxRules(e){if(this.impact==="SUBTRACT"&&e.some(i=>i.getRate()>0))throw new R("Subtractive charges cannot have positive tax rates.");let t=new Set;for(let i=0;i<e.length;i++){let n=e[i].getTaxRuleId();if(t.has(n))throw new R("Duplicate tax rule ID found: "+n);t.add(n);for(let o=i+1;o<e.length;o++){let a=e[i],l=e[o],c=a.getMinPrice(),u=a.getMaxPrice(),m=a.getExcludeMin(),I=a.getExcludeMax(),w=l.getMinPrice(),x=l.getMaxPrice(),P=l.getExcludeMin(),L=l.getExcludeMax(),h=(()=>{if(!u)return !1;let b=u.compareTo(w);return b<0||b===0&&(I||P)})(),y=(()=>{if(!x)return !1;let b=x.compareTo(c);return b<0||b===0&&(L||m)})();if(!(h||y)&&!(c.compareTo(w)===0&&m===P&&I===L&&(!u&&!x||u&&x&&u.compareTo(x)===0)))throw new R(`Overlapping rules found: [${a.getTaxRuleId()}: ${m?"(":"["}${c.getAmount()}-${u?.getAmount()??"Infinity"}${I?")":"]"}] and [${l.getTaxRuleId()}: ${P?"(":"["}${w.getAmount()}-${x?.getAmount()??"Infinity"}${L?")":"]"}]`)}}}updateDiscounts(e){let t={};e.forEach(i=>{t[i.coupon.getCode()]=i.amount;}),this.total.discountBreakdown=t,this.calculateTotals();}calculateTotals(){let e=this.pricing.baseChargeAmount.zero(),t=this.pricing.baseChargeAmount,i=Object.values(this.total.discountBreakdown).reduce((h,y)=>h.add(y),e),n=t.subtract(i),o={},a=this.pricing.applicableTaxRule.reduce((h,y)=>h+y.getApplicableTaxRate(n),0);if(a<=0){this.total={chargeAmount:t,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:n,taxTotal:e,taxBreakdown:{},grandTotal:n};return}let l=n.getCurrency(),c=n.getAmount(),u=1e3,m=s.getRoundedAmount(c/(1+a),l),I=m,w=Number.POSITIVE_INFINITY;for(let h=0;h<u;h++){let y=new s({amount:m,currency:l}),b=this.pricing.applicableTaxRule.sort((S,N)=>N.getApplicableTaxRate(y)-S.getApplicableTaxRate(y)).map(S=>s.getRoundedAmount(m*S.getApplicableTaxRate(y),l)).reduce((S,N)=>S+N,0),O=m+b-c,de=this.pricing.applicableTaxRule.reduce((S,N)=>S+N.getApplicableTaxRate(y),0);if(Math.abs(O)<Math.abs(w)&&(w=O,I=m),O===0||(m=m-O/(1+de),m<0||m>c))break}let x=new s({amount:I,currency:l}),P=e;this.pricing.applicableTaxRule.sort((h,y)=>y.getApplicableTaxRate(x)-h.getApplicableTaxRate(x)).forEach(h=>{let y=h.getApplicableTaxRate(x),X=s.getRoundedAmount(I*y,l),b=new s({amount:X,currency:l});o[h.getTaxRuleId()]={rate:y,taxableAmount:x,taxAmount:b,system:h.getTaxSystem(),subSystem:h.getTaxSubSystem()},P=P.add(b);});let L=n;this.total={chargeAmount:t,discountTotal:i,discountBreakdown:this.total.discountBreakdown,netChargeAmount:n,taxBreakdown:o,taxTotal:P,grandTotal:L};}getDetails(){return {id:this.id,name:g.deepClone(this.name),type:this.type,category:this.category,pricing:{baseChargeAmount:this.pricing.baseChargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(t=>t.getDetails())},impact:this.impact,lineItemId:this.lineItemId,total:{chargeAmount:this.total.chargeAmount.getDetails(),discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([t,i])=>[t,i.getDetails()])),netChargeAmount:this.total.netChargeAmount.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,i])=>[t,{rate:i.rate,taxableAmount:i.taxableAmount.getDetails(),taxAmount:i.taxAmount.getDetails(),system:i.system,subSystem:i.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};module.exports=ie;//# sourceMappingURL=Charge.js.map
|
|
2
2
|
//# sourceMappingURL=Charge.js.map
|