b23-lib 3.4.2 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/Auth/index.js +1 -1
  2. package/dist/Auth/index.js.map +1 -1
  3. package/dist/Auth/index.mjs +1 -1
  4. package/dist/Classes/Cart.js +1 -1
  5. package/dist/Classes/Cart.js.map +1 -1
  6. package/dist/Classes/Cart.mjs +1 -1
  7. package/dist/Classes/Charge.js +1 -1
  8. package/dist/Classes/Charge.js.map +1 -1
  9. package/dist/Classes/Charge.mjs +1 -1
  10. package/dist/Classes/Coupon.js +1 -1
  11. package/dist/Classes/Coupon.js.map +1 -1
  12. package/dist/Classes/Coupon.mjs +1 -1
  13. package/dist/Classes/Enum.d.mts +23 -1
  14. package/dist/Classes/Enum.d.ts +23 -1
  15. package/dist/Classes/Enum.js +1 -1
  16. package/dist/Classes/Enum.js.map +1 -1
  17. package/dist/Classes/Enum.mjs +1 -1
  18. package/dist/Classes/Inventory.js +1 -1
  19. package/dist/Classes/Inventory.js.map +1 -1
  20. package/dist/Classes/Inventory.mjs +1 -1
  21. package/dist/Classes/Invoice.d.mts +4 -1
  22. package/dist/Classes/Invoice.d.ts +4 -1
  23. package/dist/Classes/Invoice.js +1 -1
  24. package/dist/Classes/Invoice.js.map +1 -1
  25. package/dist/Classes/Invoice.mjs +1 -1
  26. package/dist/Classes/Invoice.mjs.map +1 -1
  27. package/dist/Classes/LineItem.js +1 -1
  28. package/dist/Classes/LineItem.js.map +1 -1
  29. package/dist/Classes/LineItem.mjs +1 -1
  30. package/dist/Classes/Order.js +1 -1
  31. package/dist/Classes/Order.js.map +1 -1
  32. package/dist/Classes/Order.mjs +1 -1
  33. package/dist/Classes/Price.js +1 -1
  34. package/dist/Classes/Price.js.map +1 -1
  35. package/dist/Classes/Price.mjs +1 -1
  36. package/dist/Classes/Product.js +1 -1
  37. package/dist/Classes/Product.js.map +1 -1
  38. package/dist/Classes/Product.mjs +1 -1
  39. package/dist/Classes/ShoppingContainer.js +1 -1
  40. package/dist/Classes/ShoppingContainer.js.map +1 -1
  41. package/dist/Classes/ShoppingContainer.mjs +1 -1
  42. package/dist/Classes/TaxRule.js +1 -1
  43. package/dist/Classes/TaxRule.js.map +1 -1
  44. package/dist/Classes/TaxRule.mjs +1 -1
  45. package/dist/Classes/TieredPrice.js +1 -1
  46. package/dist/Classes/TieredPrice.js.map +1 -1
  47. package/dist/Classes/TieredPrice.mjs +1 -1
  48. package/dist/{chunk-MHLRJ4IJ.mjs → chunk-4G7JC2EH.mjs} +2 -2
  49. package/dist/{chunk-MHLRJ4IJ.mjs.map → chunk-4G7JC2EH.mjs.map} +1 -1
  50. package/dist/{chunk-LI5JQ6UC.mjs → chunk-6ZKMKSAG.mjs} +2 -2
  51. package/dist/{chunk-LI5JQ6UC.mjs.map → chunk-6ZKMKSAG.mjs.map} +1 -1
  52. package/dist/{chunk-2POPOJGE.mjs → chunk-JYCGENPD.mjs} +2 -2
  53. package/dist/{chunk-2POPOJGE.mjs.map → chunk-JYCGENPD.mjs.map} +1 -1
  54. package/dist/{chunk-FCRJAAPY.mjs → chunk-S6LR7AUZ.mjs} +2 -2
  55. package/dist/{chunk-FCRJAAPY.mjs.map → chunk-S6LR7AUZ.mjs.map} +1 -1
  56. package/dist/chunk-TPIIACE7.mjs +2 -0
  57. package/dist/chunk-TPIIACE7.mjs.map +1 -0
  58. package/dist/{chunk-B2VFJRLS.mjs → chunk-VEOX3TRL.mjs} +2 -2
  59. package/dist/{chunk-B2VFJRLS.mjs.map → chunk-VEOX3TRL.mjs.map} +1 -1
  60. package/dist/{chunk-G6LH7V5B.mjs → chunk-XTF6ND33.mjs} +2 -2
  61. package/dist/{chunk-G6LH7V5B.mjs.map → chunk-XTF6ND33.mjs.map} +1 -1
  62. package/dist/{chunk-SOZHGHMY.mjs → chunk-ZODPRQKQ.mjs} +2 -2
  63. package/dist/{chunk-SOZHGHMY.mjs.map → chunk-ZODPRQKQ.mjs.map} +1 -1
  64. package/dist/{chunk-RQ2FFWUW.mjs → chunk-ZZ4LIKSD.mjs} +2 -2
  65. package/dist/{chunk-RQ2FFWUW.mjs.map → chunk-ZZ4LIKSD.mjs.map} +1 -1
  66. package/dist/index.js +2 -2
  67. package/dist/index.js.map +1 -1
  68. package/dist/index.mjs +1 -1
  69. package/package.json +1 -1
  70. package/dist/chunk-QK4XJ3GB.mjs +0 -2
  71. package/dist/chunk-QK4XJ3GB.mjs.map +0 -1
@@ -1,2 +1,2 @@
1
- export{a as default}from'../chunk-2POPOJGE.mjs';import'../chunk-B2VFJRLS.mjs';import'../chunk-HX32EJ3F.mjs';import'../chunk-G6LH7V5B.mjs';import'../chunk-SOZHGHMY.mjs';import'../chunk-RQ2FFWUW.mjs';import'../chunk-MHLRJ4IJ.mjs';import'../chunk-FCRJAAPY.mjs';import'../chunk-2B2XI6FG.mjs';import'../chunk-LI5JQ6UC.mjs';import'../chunk-QK4XJ3GB.mjs';import'../chunk-R5DM7WCD.mjs';import'../chunk-UXZBULDS.mjs';//# sourceMappingURL=ShoppingContainer.mjs.map
1
+ export{a as default}from'../chunk-JYCGENPD.mjs';import'../chunk-VEOX3TRL.mjs';import'../chunk-HX32EJ3F.mjs';import'../chunk-XTF6ND33.mjs';import'../chunk-ZODPRQKQ.mjs';import'../chunk-ZZ4LIKSD.mjs';import'../chunk-4G7JC2EH.mjs';import'../chunk-S6LR7AUZ.mjs';import'../chunk-2B2XI6FG.mjs';import'../chunk-6ZKMKSAG.mjs';import'../chunk-TPIIACE7.mjs';import'../chunk-R5DM7WCD.mjs';import'../chunk-UXZBULDS.mjs';//# sourceMappingURL=ShoppingContainer.mjs.map
2
2
  //# sourceMappingURL=ShoppingContainer.mjs.map
@@ -1,2 +1,2 @@
1
- 'use strict';var h=r=>structuredClone(r),d=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:h(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return h(this.customFields)}};var g={INR:"\u20B9"},y={INR:"en-IN"};var l=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},u=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},c=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},s=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}};var a=class r{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new l("Amount cannot be negative.");if(!e.currency)throw new u("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 c("Cannot compare prices in different currencies.")}else throw new s("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 c("Cannot add prices in different currencies.")}else throw new s("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 c("Cannot subtract prices in different currencies.")}else throw new s("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 c("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 s("Must be a non-negative number.")}divide(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new c("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 s("Must be a positive number.")}min(...e){if(e.length===0)throw new s("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new c("Cannot compare prices in different currencies.")}else throw new s("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i},this)}max(...e){if(e.length===0)throw new s("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new c("Cannot compare prices in different currencies.")}else throw new s("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=y[t];if(!t||!n)throw new u("Invalid currency code for formatting.");let o=e,p=i.displayAsInteger?0:r.getDecimalPlaces(t),f={style:i.style??"currency",currency:t,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:p,maximumFractionDigits:p};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,f).format(o)}catch(b){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,b),`${g[t]??t} ${r.addThousandSeparators(o.toFixed(p))}`}}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 l("Amount cannot be negative for rounding.");if(t===void 0)throw new u("Invalid currency code for rounding.");let i=r.getDecimalPlaces(t),n=Math.pow(10,i);return Math.round(e*n)/n}};var x=class extends d{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 a(e.minPrice),this.maxPrice=e.maxPrice?new a(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}%`}};exports.TaxRuleModel=x;//# sourceMappingURL=TaxRule.js.map
1
+ 'use strict';var h=r=>structuredClone(r),d=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:h(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return h(this.customFields)}};var g={INR:"\u20B9"},y={INR:"en-IN"};var l=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},u=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},c=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},s=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}};var a=class r{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new l("Amount cannot be negative.");if(!e.currency)throw new u("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 c("Cannot compare prices in different currencies.")}else throw new s("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 c("Cannot add prices in different currencies.")}else throw new s("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 c("Cannot subtract prices in different currencies.")}else throw new s("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 c("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 s("Must be a non-negative number.")}divide(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new c("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 s("Must be a positive number.")}min(...e){if(e.length===0)throw new s("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new c("Cannot compare prices in different currencies.")}else throw new s("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i},this)}max(...e){if(e.length===0)throw new s("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new c("Cannot compare prices in different currencies.")}else throw new s("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=y[t];if(!t||!n)throw new u("Invalid currency code for formatting.");let o=e,p=i.displayAsInteger?0:r.getDecimalPlaces(t),f={style:i.style??"currency",currency:t,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:p,maximumFractionDigits:p};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,f).format(o)}catch(T){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,T),`${g[t]??t} ${r.addThousandSeparators(o.toFixed(p))}`}}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 l("Amount cannot be negative for rounding.");if(t===void 0)throw new u("Invalid currency code for rounding.");let i=r.getDecimalPlaces(t),n=Math.pow(10,i);return Math.round(e*n)/n}};var x=class extends d{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 a(e.minPrice),this.maxPrice=e.maxPrice?new a(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}%`}};exports.TaxRuleModel=x;//# sourceMappingURL=TaxRule.js.map
2
2
  //# sourceMappingURL=TaxRule.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/Classes/Base.ts","../../src/Classes/Enum.ts","../../src/Classes/Error.ts","../../src/Classes/Price.ts","../../src/Classes/TaxRule.ts"],"names":["deepClone","obj","CustomFieldModel","data","date","fieldName","value","CurrencySymbolMap","CurrencyLocaleMap","InvalidPriceAmountError","message","InvalidCurrencyCodeError","CurrencyMismatchError","InvalidArgumentError","PriceModel","_PriceModel","#kind","amount","priceModel","factor","divisor","priceModels","minPrice","currentPrice","maxPrice","currency","options","locale","valueToFormat","fractionDigits","formattingOptions","error","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier","TaxRuleModel","taxCategory","country","price","at","isPriceInRange","taxRule","rate","formateOption","percentage","rateStr"],"mappings":"aAGA,IAAMA,CAAgBC,CAAAA,CAAAA,EAAc,eAAgBA,CAAAA,CAAG,EAU1CC,CAAN,CAAA,KAAuB,CAClB,YAAA,CACV,YAAYC,CAA6BC,CAAAA,CAAAA,CAAa,IAAI,IAAA,CAAQ,CAChE,IAAK,CAAA,YAAA,CAAe,CAAE,GAAGD,EAAK,YAAa,EAC7C,CAOA,cAAA,CAAeE,EAAwB,CACrC,IAAMC,CAAQ,CAAA,IAAA,CAAK,aAAaD,CAAS,CAAA,CACzC,OAA2BC,CAAAA,EAAU,KAAaA,CAC3CN,CAAAA,CAAAA,CAAUM,CAAK,CACxB,CAQA,cAAeD,CAAAA,CAAAA,CAAmBC,CAAkB,CAAA,CAClD,KAAK,YAAaD,CAAAA,CAAS,CAAIC,CAAAA,EACjC,CAMA,kBAAmC,EAAA,CACjC,OAAON,CAAAA,CAAU,KAAK,YAAY,CACpC,CACF,CAAA,CCTO,IAAMO,CAAoB,CAAA,CAC9B,GAAiC,CAAA,QACpC,EAEaC,CAAoB,CAAA,CAC9B,GAAiC,CAAA,OACpC,EC2EO,IAAMC,CAAAA,CAAN,cAAsC,KAAM,CAC/C,WAAYC,CAAAA,CAAAA,CAAkB,4BAA8B,CAAA,CACxD,MAAM,CAAkBA,eAAAA,EAAAA,CAAO,CAAE,CAAA,CAAA,CACjC,KAAK,IAAO,CAAA,0BAChB,CACJ,CAAA,CAEaC,EAAN,cAAuC,KAAM,CAChD,WAAA,CAAYD,EAAkB,4BAA8B,CAAA,C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,CAEzG,CAAA,OAAID,CAAe,EAAA,cAAA,CACV,GAAGE,CAAO,CAAA,CAAA,CAAA,CAGfJ,CAAQ,CAAA,YAAA,KAAmB,KACtB,CAAA,CAAA,EAAGA,CAAQ,CAAA,eAAA,EAAiB,CAAII,CAAAA,EAAAA,CAAO,CAEzC,CAAA,CAAA,CAAA,CAAA,EAAGJ,EAAQ,YAAa,EAAC,CAAII,CAAAA,EAAAA,CAAO,GAC7C,CACF","file":"TaxRule.js","sourcesContent":["import { AuthType } from \"../Auth\";\nimport { ISODateTimeUTC, Prettify } from \"./Common\";\n\nconst deepClone = <T>(obj: T): T => structuredClone(obj);\n\r\nexport interface CustomFields {\r\n [key: string]: any;\r\n}\r\n\r\nexport type CustomFieldAttributes = {\r\n customFields?: CustomFields;\r\n}\r\n\r\nexport class CustomFieldModel {\r\n protected customFields: CustomFields;\r\n constructor(data: CustomFieldAttributes, date: Date = new Date()) {\r\n this.customFields = { ...data.customFields };\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 {\n const value = this.customFields[fieldName];\n if (value === undefined || value === null) return value;\n return deepClone(value);\n }\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 {\n return deepClone(this.customFields);\n }\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 = Prettify<CustomFieldAttributes & {\r\n version?: number;\r\n createdAt?: ISODateTimeUTC;\r\n modifiedAt?: ISODateTimeUTC;\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 extends CustomFieldModel {\r\n protected version: number;\r\n protected createdAt: ISODateTimeUTC;\r\n protected modifiedAt: ISODateTimeUTC;\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 super(data);\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 * 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\nexport const CurrencyLocaleMap = {\r\n [OperationalCountryCurrency.INR]: OperationalLocale[\"en-IN\"],\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 GENERAL = 'General',\r\n}\r\n\r\nexport enum ImageCategory {\r\n PRIMARY = 'PRIMARY',\r\n GALLERY = 'GALLERY'\r\n}\r\n\r\nexport enum ChargeType {\r\n SHIPPING = 'SHIPPING',\r\n ADJUSTMENT = 'ADJUSTMENT'\r\n}\r\n\r\nexport enum ChargeImpact {\r\n ADD = \"ADD\",\r\n SUBTRACT = \"SUBTRACT\",\r\n}\r\n\r\nexport enum TaxSystem {\r\n GST = 'GST',\r\n}\r\n\r\n/**\r\n * LineItemState\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 LineItemState {\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}","export 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\nexport class InvalidLineItemStateError extends Error {\r\n constructor(state: string) {\r\n super(`Invalid line item state: ${state}`);\r\n this.name = 'InvalidLineItemStateError';\r\n }\r\n}\r\n\r\nexport class InvalidLineItemTaxRuleError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidLineItemTaxRule: ${message}`);\r\n this.name = 'InvalidLineItemTaxRuleError';\r\n }\r\n}\r\n\r\nexport class DuplicateSizeError extends Error {\r\n constructor(size: string) {\r\n super(`Duplicate size found: ${size}`);\r\n this.name = 'DuplicateSizeError';\r\n }\r\n}\r\n\r\nexport class DuplicateSelectionAttributeError extends Error {\r\n constructor(attribute: string) {\r\n super(`Duplicate selection attribute found: ${attribute}`);\r\n this.name = 'DuplicateSelectionAttributeError';\r\n }\r\n}\r\n\r\nexport class ProductMismatchError extends Error {\r\n constructor(message: string = \"Product and selection attributes do not match.\") {\r\n super(`ProductMismatch: ${message}`);\r\n this.name = 'ProductMismatchError';\r\n }\r\n}\r\n\r\nexport class ProductInactiveError extends Error {\r\n constructor(message: string = \"Product is not active.\") {\r\n super(`ProductInactive: ${message}`);\r\n this.name = 'ProductInactiveError';\r\n }\r\n}\r\n\r\nexport class SelectionAttributeParseError extends Error {\r\n constructor(message: string = \"Failed to parse selection attributes key.\") {\r\n super(`SelectionAttributeParseError: ${message}`);\r\n this.name = 'SelectionAttributeParseError';\r\n }\r\n}\r\n\r\nexport class SizeMismatchError extends Error {\r\n constructor(message: string = \"Size does not match.\") {\r\n super(`SizeMismatch: ${message}`);\r\n this.name = 'SizeMismatchError';\r\n }\r\n}\r\n\r\nexport class PricingNotFoundError extends Error {\r\n constructor(message: string = \"Pricing details not available for the product\") {\r\n super(`NotFound: ${message}`);\r\n this.name = 'PricingNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxRuleError extends Error {\r\n constructor(message: string = \"Tax rule category mismatch.\") {\r\n super(`InvalidTaxRule: ${message}`);\r\n this.name = 'InvalidTaxRuleError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxCategoryError extends Error {\r\n constructor(message: string = \"Tax category is not valid.\") {\r\n super(`InvalidTaxCategory: ${message}`);\r\n this.name = 'InvalidTaxCategoryError';\r\n }\r\n}\r\n\r\nexport class InvalidMinQuantityError extends Error {\r\n constructor(message: string = \"Minimum quantity must be greater than zero.\") {\r\n super(`InvalidMinQuantity: ${message}`);\r\n this.name = 'InvalidMinQuantityError';\r\n }\r\n}\r\n\r\nexport class InvalidTieredPriceError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidTieredPrice: ${message}`);\r\n this.name = 'InvalidTieredPriceError';\r\n }\r\n}\r\n\r\nexport class InvalidQuantityError extends Error {\r\n constructor(message: string = \"Quantity must be greater than zero.\") {\r\n super(`InvalidQuantity: ${message}`);\r\n this.name = 'InvalidQuantityError';\r\n }\r\n}\r\n\r\nexport class NoApplicableTierError extends Error {\r\n constructor(quantity: number) {\r\n super(`NoApplicableTier: Quantity ${quantity} does not meet the minimum purchase requirement.`);\r\n this.name = 'NoApplicableTierError';\r\n }\r\n}\r\n\r\nexport class TaxSlabNotFoundError extends Error {\r\n constructor(message: string = \"No applicable tax slab or multiple slabs found for the given unit price.\") {\r\n super(`TaxSlabNotFound: ${message}`);\r\n this.name = 'TaxSlabNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidPriceAmountError extends Error {\r\n constructor(message: string = \"Amount cannot be negative.\") {\r\n super(`InvalidAmount: ${message}`);\r\n this.name = 'InvalidPriceAmountError';\r\n }\r\n}\r\n\r\nexport class InvalidCurrencyCodeError extends Error {\r\n constructor(message: string = \"Currency code is required.\") {\r\n super(`InvalidCurrency: ${message}`);\r\n this.name = 'InvalidCurrencyCodeError';\r\n }\r\n}\r\n\r\nexport class CurrencyMismatchError extends Error {\r\n constructor(message: string = \"Cannot perform operation on prices with different currencies.\") {\r\n super(`CurrencyMismatch: ${message}`);\r\n this.name = 'CurrencyMismatchError';\r\n }\r\n}\r\n\r\nexport class InvalidArgumentError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidArgument: ${message}`);\r\n this.name = 'InvalidArgumentError';\r\n }\r\n}\r\n\r\nexport class InvalidImageSourceError extends Error {\r\n constructor(message: string = \"Invalid image source configuration.\") {\r\n super(`InvalidImageSource: ${message}`);\r\n this.name = 'InvalidImageSourceError';\r\n }\r\n}\r\n\r\nexport class InvalidChargeError extends Error {\r\n constructor(message: string = \"Invalid charge data.\") {\r\n super(`InvalidCharge: ${message}`);\r\n this.name = 'InvalidChargeError';\r\n }\r\n}\r\n\r\nexport class InvalidChargeTaxRuleError extends Error {\r\n constructor(message: string = \"Invalid charge tax rule.\") {\r\n super(`InvalidChargeTaxRule: ${message}`);\r\n this.name = 'InvalidChargeTaxRuleError';\r\n }\r\n}\r\n","import { CurrencyCode } from \"./Common\";\r\nimport { CurrencyLocaleMap, CurrencySymbolMap, OperationalCountryCurrency } from \"./Enum\";\r\nimport {\r\n InvalidPriceAmountError,\r\n InvalidCurrencyCodeError,\r\n CurrencyMismatchError,\r\n InvalidArgumentError\r\n} from \"./Error\";\r\n\r\nexport type PriceAttributes = {\r\n amount: number;\r\n currency: CurrencyCode;\r\n}\r\n\r\nexport type PriceData = PriceAttributes;\r\n\r\nexport default class PriceModel {\r\n #kind: string;\r\n protected amount: number;\r\n protected currency: CurrencyCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param amount - The initial price value.\r\n * @param currency - The currency 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(data: PriceAttributes) {\r\n this.#kind = \"PriceModel\";\r\n if (data.amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative.\");\r\n }\r\n\r\n if (!data.currency) {\r\n throw new InvalidCurrencyCodeError(\"Currency code is required.\");\r\n }\r\n\r\n this.currency = data.currency;\r\n this.amount = parseFloat(data.amount.toFixed(PriceModel.getPrecisionPlaces(this.currency)));\r\n }\r\n\r\n get kind() {\r\n return this.#kind;\r\n }\r\n\r\n static isPriceModel(obj: unknown): obj is PriceModel {\r\n return typeof obj === \"object\" &&\r\n obj !== null &&\r\n (obj as any).kind === \"PriceModel\";\r\n }\r\n\r\n /**\r\n * Gets the currency associated with this price instance.\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 * Returns the raw numeric price value.\r\n */\r\n public getAmount(): number {\r\n return this.amount;\r\n }\r\n\r\n /**\r\n *\r\n * @returns PriceData\r\n */\r\n public getDetails(): PriceData {\r\n return {\r\n amount: this.amount,\r\n currency: this.currency\r\n }\r\n }\r\n\r\n public getPreciseAmount(amount: number): number {\r\n return parseFloat(amount.toFixed(PriceModel.getPrecisionPlaces(this.currency)));\r\n }\r\n\r\n /**\r\n * Compares this price with another {@link PriceModel} instance.\r\n *\r\n * The comparison is performed using the numeric price value and is only valid\r\n * when both prices are expressed in the same currency.\r\n *\r\n * ### Comparison result:\r\n * - Returns a **negative number** if this price is **less than** `priceModel`\r\n * - Returns **zero** if both prices are **equal**\r\n * - Returns a **positive number** if this price is **greater than** `priceModel`\r\n *\r\n * @param priceModel - The {@link PriceModel} instance to compare against.\r\n *\r\n * @returns\r\n * A signed number representing the comparison result:\r\n * - `< 0` → this price is lower\r\n * - `0` → prices are equal\r\n * - `> 0` → this price is higher\r\n *\r\n * @throws {Error}\r\n * Throws an error if:\r\n * - `priceModel` is not an instance of {@link PriceModel}\r\n * - The currencies of the two prices do not match\r\n *\r\n * @example\r\n * ```ts\r\n * const a = new PriceModel(\"USD\", 100);\r\n * const b = new PriceModel(\"USD\", 150);\r\n *\r\n * a.compareTo(b); // -50\r\n * b.compareTo(a); // 50\r\n * a.compareTo(a); // 0\r\n * ```\r\n */\r\n public compareTo(priceModel: PriceModel): number {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return this.getPreciseAmount(this.amount - priceModel.getAmount());\r\n }\r\n\r\n public add(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot add prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.getPreciseAmount((this.amount + priceModel.getAmount())),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public subtract(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot subtract prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount - priceModel.getAmount()),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public multiply(factor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(factor)) {\r\n if (this.currency !== factor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot multiply prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount * factor.getAmount()),\r\n currency: this.currency\r\n });\r\n } else if (typeof factor === \"number\" && factor >= 0) {\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount * factor),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a non-negative number.\");\r\n }\r\n\r\n public divide(divisor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(divisor)) {\r\n if (this.currency !== divisor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot divide prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount / divisor.getAmount()),\r\n currency: this.currency\r\n });\r\n } else if (typeof divisor === \"number\" && divisor > 0) {\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount / divisor),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a positive number.\");\r\n }\r\n\r\n public min(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((minPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (minPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return minPrice.compareTo(currentPrice) < 0 ? minPrice : currentPrice;\r\n }, this);\r\n }\r\n\r\n public max(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((maxPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (maxPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return maxPrice.compareTo(currentPrice) > 0 ? maxPrice : currentPrice;\r\n }, this);\r\n }\r\n\r\n /**\r\n * Gets a zero value PriceModel for the same currency.\r\n * @returns A PriceModel instance representing zero in the same currency.\r\n */\r\n public zero(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: 0\r\n });\r\n }\r\n\r\n /**\r\n * Checks if the price is zero.\r\n * @returns True if the price is zero, false otherwise.\r\n */\r\n public isZero(): boolean {\r\n return this.amount === 0;\r\n }\r\n\r\n\r\n public round(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: this.getRoundedAmount()\r\n });\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 getRoundedAmount(): number {\r\n return PriceModel.getRoundedAmount(this.amount, this.currency);\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 * @returns The formatted price string according to locale rules.\r\n */\r\n public getFormattedString() {\r\n return PriceModel.getFormattedString(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n toString() {\r\n return this.getFormattedString();\r\n }\r\n\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the amount.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param amount - The initial amount value.\r\n * @param currency - The currency code for formatting.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the amount rounded to the next 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 * @throws {Error} If currency code is invalid.\r\n */\r\n static getFormattedString(amount: number, currency: CurrencyCode, options: {\r\n displayAsInteger?: boolean,\r\n style?: 'currency' | 'decimal',\r\n currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name'\r\n } = {\r\n displayAsInteger: false,\r\n style: 'currency',\r\n currencyDisplay: 'symbol'\r\n }): string {\r\n\r\n const locale = CurrencyLocaleMap[currency];\r\n if (!currency || !locale) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for formatting.');\r\n }\r\n\r\n let valueToFormat = amount;\r\n const fractionDigits = options.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 (options.displayAsInteger) {\r\n valueToFormat = Math.ceil(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 currency \"${currency}\" and locale \"${locale}\":`, 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 OperationalCountryCurrency.INR:\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n /**\r\n * Helper method to determine standard precision places for a currency.\r\n * @param currency - The currency code.\r\n * @return The number of precision places (0, 2, or 3 based on common rules).\r\n */ \r\n private static getPrecisionPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case OperationalCountryCurrency.INR:\r\n default:\r\n return 6;\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 currency - The currency code to determine the rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the price is negative or currency is invalid.\r\n */\r\n static getRoundedAmount(amount: number, currency: CurrencyCode): number {\r\n if (amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative for rounding.\");\r\n }\r\n\r\n if (currency === undefined) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for rounding.');\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(amount * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n}","import { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\nimport { CountryCode, ISODateTimeUTC, Prettify } from \"./Common\";\r\nimport { TaxSystem } from \"./Enum\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\n\r\nexport type TaxRuleAttributes = Prettify<CustomFieldAttributes & {\r\n taxRuleId: string;\r\n taxCategory: string;\r\n taxSystem: TaxSystem;\r\n taxSubSystem: string;\r\n country: CountryCode;\r\n rate: number;\r\n minPrice: PriceData;\r\n maxPrice?: PriceData;\r\n excludeMin?: boolean;\r\n excludeMax?: boolean;\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n}>;\r\n\r\nexport type TaxRuleData = TaxRuleAttributes;\r\n\r\nexport class TaxRuleModel extends CustomFieldModel {\r\n protected taxRuleId: string;\r\n protected taxCategory: string;\r\n protected taxSystem: TaxSystem;\r\n protected taxSubSystem: string;\r\n protected country: CountryCode;\r\n protected rate: number;\r\n protected minPrice: PriceModel;\r\n protected maxPrice?: PriceModel;\r\n protected excludeMin: boolean;\r\n protected excludeMax: boolean;\r\n protected effectiveFrom: ISODateTimeUTC;\r\n protected effectiveTo?: ISODateTimeUTC;\r\n\r\n constructor(data: TaxRuleAttributes) {\r\n super(data);\r\n this.taxRuleId = data.taxRuleId;\r\n this.taxSystem = data.taxSystem;\r\n this.taxSubSystem = data.taxSubSystem;\r\n this.taxCategory = data.taxCategory;\r\n this.country = data.country;\r\n this.rate = data.rate;\r\n this.minPrice = new PriceModel(data.minPrice);\r\n this.maxPrice = data.maxPrice ? new PriceModel(data.maxPrice) : undefined;\r\n this.excludeMin = data.excludeMin ?? false;\r\n this.excludeMax = data.excludeMax ?? false;\r\n this.effectiveFrom = new Date(data.effectiveFrom).toISOString();\r\n this.effectiveTo = data.effectiveTo ? new Date(data.effectiveTo).toISOString() : undefined;\r\n }\r\n\r\n getTaxRuleId(): string {\r\n return this.taxRuleId;\r\n }\r\n\r\n getTaxSystem(): TaxSystem {\r\n return this.taxSystem;\r\n }\r\n\r\n getTaxSubSystem(): string {\r\n return this.taxSubSystem;\r\n }\r\n\r\n getTaxCategory(): string {\r\n return this.taxCategory;\r\n }\r\n\r\n getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n getRate(): number {\r\n return this.rate;\r\n }\r\n\r\n getMinPrice(): PriceModel {\r\n return this.minPrice;\r\n }\r\n\r\n getMaxPrice(): PriceModel | undefined {\r\n return this.maxPrice;\r\n }\r\n\r\n getExcludeMin(): boolean {\r\n return this.excludeMin;\r\n }\r\n\r\n getExcludeMax(): boolean {\r\n return this.excludeMax;\r\n }\r\n\r\n getEffectiveFrom(): string {\r\n return this.effectiveFrom;\r\n }\r\n\r\n getEffectiveTo(): string | undefined {\r\n return this.effectiveTo;\r\n }\r\n\r\n getDetails(): TaxRuleData {\r\n return {\r\n taxRuleId: this.getTaxRuleId(),\r\n taxSystem: this.getTaxSystem(),\r\n taxSubSystem: this.getTaxSubSystem(),\r\n taxCategory: this.getTaxCategory(),\r\n country: this.getCountry(),\r\n rate: this.getRate(),\r\n minPrice: this.getMinPrice().getDetails(),\r\n maxPrice: this.getMaxPrice()?.getDetails(),\r\n excludeMin: this.getExcludeMin(),\r\n excludeMax: this.getExcludeMax(),\r\n effectiveFrom: this.effectiveFrom,\r\n effectiveTo: this.effectiveTo ? this.effectiveTo : undefined,\r\n customFields: this.getAllCustomFields(),\r\n };\r\n }\r\n\r\n /**\r\n * Checks whether this tax rule is applicable for the given category and country at a specific time.\r\n * @param taxCategory - The tax category to check.\r\n * @param country - The country code to check.\r\n * @param price - The price to check against the rule's price range (optional).\r\n * @param at - The date to check effectiveness against (defaults to now).\r\n * @returns True if the rule is applicable, false otherwise.\r\n */\r\n appliesTo(taxCategory: string, country: CountryCode, price?: PriceModel, at: Date = new Date()): boolean {\r\n const isPriceInRange = !price || (\r\n (this.excludeMin ? this.minPrice.compareTo(price) < 0 : this.minPrice.compareTo(price) <= 0) &&\r\n (this.maxPrice\r\n ? (this.excludeMax ? this.maxPrice.compareTo(price) > 0 : this.maxPrice.compareTo(price) >= 0)\r\n : true\r\n )\r\n );\r\n\r\n return (\r\n this.taxCategory === taxCategory &&\r\n this.country === country &&\r\n isPriceInRange &&\r\n Date.parse(this.effectiveFrom) <= at.getTime() &&\r\n (this.effectiveTo ? Date.parse(this.effectiveTo) >= at.getTime() : true)\r\n );\r\n }\r\n\r\n /**\r\n * Gets the applicable tax rate for a given price. Returns the tax rate if the rule applies, otherwise returns 0.\r\n * @param price - The price to check against the tax rule.\r\n * @returns The applicable tax rate as a decimal (e.g., 0.18 for 18%).\r\n */\r\n getApplicableTaxRate(price: PriceModel): number {\r\n if(this.appliesTo(this.taxCategory, this.country, price)) {\r\n return this.rate;\r\n }\r\n return 0;\r\n }\r\n\r\n /**\r\n * Calculates the tax amount for a given taxable amount.\r\n * @param price - The price used to determine the tax amount.\r\n * @returns The calculated tax amount as a PriceModel. Returns zero if the tax rule does not apply.\r\n */\r\n calculateTax(price: PriceModel): PriceModel {\r\n if(!this.appliesTo(this.taxCategory, this.country, price)) {\r\n return price.zero(); // Return zero tax if the rule does not apply\r\n }\r\n\r\n return price.multiply(this.rate);\r\n }\r\n\r\n\r\n static getTaxRateDisplayString(taxRule: TaxRuleModel, rate: number, formateOption?: {\r\n percentageOnly?: boolean;\r\n }): string {\r\n const percentage = rate * 100;\r\n // Format to remove trailing zeros if it's an integer, otherwise keep up to 2 decimal places\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n\r\n if (formateOption?.percentageOnly) {\r\n return `${rateStr}%`;\r\n }\r\n\r\n if (taxRule.getTaxSystem() === TaxSystem.GST) {\r\n return `${taxRule.getTaxSubSystem()} ${rateStr}%`;\r\n }\r\n return `${taxRule.getTaxSystem()} ${rateStr}%`;\r\n }\r\n}\r\n\r\n"]}
1
+ {"version":3,"sources":["../../src/Classes/Base.ts","../../src/Classes/Enum.ts","../../src/Classes/Error.ts","../../src/Classes/Price.ts","../../src/Classes/TaxRule.ts"],"names":["deepClone","obj","CustomFieldModel","data","date","fieldName","value","CurrencySymbolMap","CurrencyLocaleMap","InvalidPriceAmountError","message","InvalidCurrencyCodeError","CurrencyMismatchError","InvalidArgumentError","PriceModel","_PriceModel","#kind","amount","priceModel","factor","divisor","priceModels","minPrice","currentPrice","maxPrice","currency","options","locale","valueToFormat","fractionDigits","formattingOptions","error","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier","TaxRuleModel","taxCategory","country","price","at","isPriceInRange","taxRule","rate","formateOption","percentage","rateStr"],"mappings":"aAGA,IAAMA,CAAgBC,CAAAA,CAAAA,EAAc,eAAgBA,CAAAA,CAAG,EAU1CC,CAAN,CAAA,KAAuB,CAClB,YAAA,CACV,YAAYC,CAA6BC,CAAAA,CAAAA,CAAa,IAAI,IAAA,CAAQ,CAChE,IAAK,CAAA,YAAA,CAAe,CAAE,GAAGD,EAA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,KAAK,KAAM,CAAA,IAAA,CAAK,WAAW,CAAA,EAAKA,EAAG,OAAQ,EAAA,CAAI,CAEvE,CAAA,CAAA,CAOA,qBAAqBD,CAA2B,CAAA,CAC9C,OAAG,IAAA,CAAK,UAAU,IAAK,CAAA,WAAA,CAAa,IAAK,CAAA,OAAA,CAASA,CAAK,CAC9C,CAAA,IAAA,CAAK,IAEP,CAAA,CACT,CAOA,YAAaA,CAAAA,CAAAA,CAA+B,CAC1C,OAAI,KAAK,SAAU,CAAA,IAAA,CAAK,WAAa,CAAA,IAAA,CAAK,QAASA,CAAK,CAAA,CAIjDA,CAAM,CAAA,QAAA,CAAS,KAAK,IAAI,CAAA,CAHtBA,CAAM,CAAA,IAAA,EAIjB,CAGA,OAAO,uBAAwBG,CAAAA,CAAAA,CAAuBC,EAAcC,CAEzD,CAAA,CACT,IAAMC,CAAAA,CAAaF,EAAO,GAEpBG,CAAAA,CAAAA,CAAUD,CAAa,CAAA,CAAA,GAAM,EAAIA,CAAW,CAAA,QAAA,EAAaA,CAAAA,CAAAA,CAAW,QAAQ,CAAC,CAAA,CAAE,OAAQ,CAAA,QAAA,CAAU,EAAE,CAEzG,CAAA,OAAID,CAAe,EAAA,cAAA,CACV,GAAGE,CAAO,CAAA,CAAA,CAAA,CAGfJ,CAAQ,CAAA,YAAA,KAAmB,KACtB,CAAA,CAAA,EAAGA,CAAQ,CAAA,eAAA,EAAiB,CAAII,CAAAA,EAAAA,CAAO,CAEzC,CAAA,CAAA,CAAA,CAAA,EAAGJ,EAAQ,YAAa,EAAC,CAAII,CAAAA,EAAAA,CAAO,GAC7C,CACF","file":"TaxRule.js","sourcesContent":["import { AuthType } from \"../Auth\";\nimport { ISODateTimeUTC, Prettify } from \"./Common\";\n\nconst deepClone = <T>(obj: T): T => structuredClone(obj);\n\r\nexport interface CustomFields {\r\n [key: string]: any;\r\n}\r\n\r\nexport type CustomFieldAttributes = {\r\n customFields?: CustomFields;\r\n}\r\n\r\nexport class CustomFieldModel {\r\n protected customFields: CustomFields;\r\n constructor(data: CustomFieldAttributes, date: Date = new Date()) {\r\n this.customFields = { ...data.customFields };\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 {\n const value = this.customFields[fieldName];\n if (value === undefined || value === null) return value;\n return deepClone(value);\n }\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 {\n return deepClone(this.customFields);\n }\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 = Prettify<CustomFieldAttributes & {\r\n version?: number;\r\n createdAt?: ISODateTimeUTC;\r\n modifiedAt?: ISODateTimeUTC;\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 extends CustomFieldModel {\r\n protected version: number;\r\n protected createdAt: ISODateTimeUTC;\r\n protected modifiedAt: ISODateTimeUTC;\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 super(data);\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 * 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\nexport const CurrencyLocaleMap = {\r\n [OperationalCountryCurrency.INR]: OperationalLocale[\"en-IN\"],\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 GENERAL = 'General',\r\n}\r\n\r\nexport enum ImageCategory {\r\n PRIMARY = 'PRIMARY',\r\n GALLERY = 'GALLERY'\r\n}\r\n\r\nexport enum ChargeType {\r\n SHIPPING = 'SHIPPING',\r\n ADJUSTMENT = 'ADJUSTMENT'\r\n}\r\n\r\nexport enum ChargeImpact {\r\n ADD = \"ADD\",\r\n SUBTRACT = \"SUBTRACT\",\r\n}\r\n\r\nexport enum TaxSystem {\r\n GST = 'GST',\r\n}\r\n\r\n/**\r\n * LineItemState\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 LineItemState {\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 UNDELIVERED = \"UNDELIVERED\",\r\n REFUND_INITIATED = \"REFUND_INITIATED\",\r\n REFUNDED = \"REFUNDED\",\r\n ON_HOLD = \"ON_HOLD\",\r\n}\r\n/**\r\n * InvoiceState defines the lifecycle of a financial document.\r\n */\r\nexport enum InvoiceState {\r\n /** Preliminary document being drafted; has no legal or financial impact yet. */\r\n DRAFT = \"DRAFT\",\r\n\r\n /** Legally finalized document sent to the customer; tax and revenue are recognized. */\r\n ISSUED = \"ISSUED\",\r\n\r\n /** \r\n * Cancelled before the document became legally effective or reached the customer.\r\n * Used for Failed Deliveries (RTO) where the invoice was not yet reported to GST portals.\r\n */\r\n VOIDED = \"VOIDED\",\r\n\r\n /**\r\n * Officially reversed due to a sales return or refund after the document was legally finalized.\r\n * Marks that the tax liability of this invoice has been nullified elsewhere.\r\n */\r\n CREDITED = \"CREDITED\",\r\n \r\n /** Marked once the invoice has been officially filed with tax authorities (e.g. GSTR-1). */\r\n REPORTED = \"REPORTED\"\r\n}\r\n","export 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\nexport class InvalidLineItemStateError extends Error {\r\n constructor(state: string) {\r\n super(`Invalid line item state: ${state}`);\r\n this.name = 'InvalidLineItemStateError';\r\n }\r\n}\r\n\r\nexport class InvalidLineItemTaxRuleError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidLineItemTaxRule: ${message}`);\r\n this.name = 'InvalidLineItemTaxRuleError';\r\n }\r\n}\r\n\r\nexport class DuplicateSizeError extends Error {\r\n constructor(size: string) {\r\n super(`Duplicate size found: ${size}`);\r\n this.name = 'DuplicateSizeError';\r\n }\r\n}\r\n\r\nexport class DuplicateSelectionAttributeError extends Error {\r\n constructor(attribute: string) {\r\n super(`Duplicate selection attribute found: ${attribute}`);\r\n this.name = 'DuplicateSelectionAttributeError';\r\n }\r\n}\r\n\r\nexport class ProductMismatchError extends Error {\r\n constructor(message: string = \"Product and selection attributes do not match.\") {\r\n super(`ProductMismatch: ${message}`);\r\n this.name = 'ProductMismatchError';\r\n }\r\n}\r\n\r\nexport class ProductInactiveError extends Error {\r\n constructor(message: string = \"Product is not active.\") {\r\n super(`ProductInactive: ${message}`);\r\n this.name = 'ProductInactiveError';\r\n }\r\n}\r\n\r\nexport class SelectionAttributeParseError extends Error {\r\n constructor(message: string = \"Failed to parse selection attributes key.\") {\r\n super(`SelectionAttributeParseError: ${message}`);\r\n this.name = 'SelectionAttributeParseError';\r\n }\r\n}\r\n\r\nexport class SizeMismatchError extends Error {\r\n constructor(message: string = \"Size does not match.\") {\r\n super(`SizeMismatch: ${message}`);\r\n this.name = 'SizeMismatchError';\r\n }\r\n}\r\n\r\nexport class PricingNotFoundError extends Error {\r\n constructor(message: string = \"Pricing details not available for the product\") {\r\n super(`NotFound: ${message}`);\r\n this.name = 'PricingNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxRuleError extends Error {\r\n constructor(message: string = \"Tax rule category mismatch.\") {\r\n super(`InvalidTaxRule: ${message}`);\r\n this.name = 'InvalidTaxRuleError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxCategoryError extends Error {\r\n constructor(message: string = \"Tax category is not valid.\") {\r\n super(`InvalidTaxCategory: ${message}`);\r\n this.name = 'InvalidTaxCategoryError';\r\n }\r\n}\r\n\r\nexport class InvalidMinQuantityError extends Error {\r\n constructor(message: string = \"Minimum quantity must be greater than zero.\") {\r\n super(`InvalidMinQuantity: ${message}`);\r\n this.name = 'InvalidMinQuantityError';\r\n }\r\n}\r\n\r\nexport class InvalidTieredPriceError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidTieredPrice: ${message}`);\r\n this.name = 'InvalidTieredPriceError';\r\n }\r\n}\r\n\r\nexport class InvalidQuantityError extends Error {\r\n constructor(message: string = \"Quantity must be greater than zero.\") {\r\n super(`InvalidQuantity: ${message}`);\r\n this.name = 'InvalidQuantityError';\r\n }\r\n}\r\n\r\nexport class NoApplicableTierError extends Error {\r\n constructor(quantity: number) {\r\n super(`NoApplicableTier: Quantity ${quantity} does not meet the minimum purchase requirement.`);\r\n this.name = 'NoApplicableTierError';\r\n }\r\n}\r\n\r\nexport class TaxSlabNotFoundError extends Error {\r\n constructor(message: string = \"No applicable tax slab or multiple slabs found for the given unit price.\") {\r\n super(`TaxSlabNotFound: ${message}`);\r\n this.name = 'TaxSlabNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidPriceAmountError extends Error {\r\n constructor(message: string = \"Amount cannot be negative.\") {\r\n super(`InvalidAmount: ${message}`);\r\n this.name = 'InvalidPriceAmountError';\r\n }\r\n}\r\n\r\nexport class InvalidCurrencyCodeError extends Error {\r\n constructor(message: string = \"Currency code is required.\") {\r\n super(`InvalidCurrency: ${message}`);\r\n this.name = 'InvalidCurrencyCodeError';\r\n }\r\n}\r\n\r\nexport class CurrencyMismatchError extends Error {\r\n constructor(message: string = \"Cannot perform operation on prices with different currencies.\") {\r\n super(`CurrencyMismatch: ${message}`);\r\n this.name = 'CurrencyMismatchError';\r\n }\r\n}\r\n\r\nexport class InvalidArgumentError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidArgument: ${message}`);\r\n this.name = 'InvalidArgumentError';\r\n }\r\n}\r\n\r\nexport class InvalidImageSourceError extends Error {\r\n constructor(message: string = \"Invalid image source configuration.\") {\r\n super(`InvalidImageSource: ${message}`);\r\n this.name = 'InvalidImageSourceError';\r\n }\r\n}\r\n\r\nexport class InvalidChargeError extends Error {\r\n constructor(message: string = \"Invalid charge data.\") {\r\n super(`InvalidCharge: ${message}`);\r\n this.name = 'InvalidChargeError';\r\n }\r\n}\r\n\r\nexport class InvalidChargeTaxRuleError extends Error {\r\n constructor(message: string = \"Invalid charge tax rule.\") {\r\n super(`InvalidChargeTaxRule: ${message}`);\r\n this.name = 'InvalidChargeTaxRuleError';\r\n }\r\n}\r\n","import { CurrencyCode } from \"./Common\";\r\nimport { CurrencyLocaleMap, CurrencySymbolMap, OperationalCountryCurrency } from \"./Enum\";\r\nimport {\r\n InvalidPriceAmountError,\r\n InvalidCurrencyCodeError,\r\n CurrencyMismatchError,\r\n InvalidArgumentError\r\n} from \"./Error\";\r\n\r\nexport type PriceAttributes = {\r\n amount: number;\r\n currency: CurrencyCode;\r\n}\r\n\r\nexport type PriceData = PriceAttributes;\r\n\r\nexport default class PriceModel {\r\n #kind: string;\r\n protected amount: number;\r\n protected currency: CurrencyCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param amount - The initial price value.\r\n * @param currency - The currency 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(data: PriceAttributes) {\r\n this.#kind = \"PriceModel\";\r\n if (data.amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative.\");\r\n }\r\n\r\n if (!data.currency) {\r\n throw new InvalidCurrencyCodeError(\"Currency code is required.\");\r\n }\r\n\r\n this.currency = data.currency;\r\n this.amount = parseFloat(data.amount.toFixed(PriceModel.getPrecisionPlaces(this.currency)));\r\n }\r\n\r\n get kind() {\r\n return this.#kind;\r\n }\r\n\r\n static isPriceModel(obj: unknown): obj is PriceModel {\r\n return typeof obj === \"object\" &&\r\n obj !== null &&\r\n (obj as any).kind === \"PriceModel\";\r\n }\r\n\r\n /**\r\n * Gets the currency associated with this price instance.\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 * Returns the raw numeric price value.\r\n */\r\n public getAmount(): number {\r\n return this.amount;\r\n }\r\n\r\n /**\r\n *\r\n * @returns PriceData\r\n */\r\n public getDetails(): PriceData {\r\n return {\r\n amount: this.amount,\r\n currency: this.currency\r\n }\r\n }\r\n\r\n public getPreciseAmount(amount: number): number {\r\n return parseFloat(amount.toFixed(PriceModel.getPrecisionPlaces(this.currency)));\r\n }\r\n\r\n /**\r\n * Compares this price with another {@link PriceModel} instance.\r\n *\r\n * The comparison is performed using the numeric price value and is only valid\r\n * when both prices are expressed in the same currency.\r\n *\r\n * ### Comparison result:\r\n * - Returns a **negative number** if this price is **less than** `priceModel`\r\n * - Returns **zero** if both prices are **equal**\r\n * - Returns a **positive number** if this price is **greater than** `priceModel`\r\n *\r\n * @param priceModel - The {@link PriceModel} instance to compare against.\r\n *\r\n * @returns\r\n * A signed number representing the comparison result:\r\n * - `< 0` → this price is lower\r\n * - `0` → prices are equal\r\n * - `> 0` → this price is higher\r\n *\r\n * @throws {Error}\r\n * Throws an error if:\r\n * - `priceModel` is not an instance of {@link PriceModel}\r\n * - The currencies of the two prices do not match\r\n *\r\n * @example\r\n * ```ts\r\n * const a = new PriceModel(\"USD\", 100);\r\n * const b = new PriceModel(\"USD\", 150);\r\n *\r\n * a.compareTo(b); // -50\r\n * b.compareTo(a); // 50\r\n * a.compareTo(a); // 0\r\n * ```\r\n */\r\n public compareTo(priceModel: PriceModel): number {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return this.getPreciseAmount(this.amount - priceModel.getAmount());\r\n }\r\n\r\n public add(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot add prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.getPreciseAmount((this.amount + priceModel.getAmount())),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public subtract(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot subtract prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount - priceModel.getAmount()),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public multiply(factor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(factor)) {\r\n if (this.currency !== factor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot multiply prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount * factor.getAmount()),\r\n currency: this.currency\r\n });\r\n } else if (typeof factor === \"number\" && factor >= 0) {\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount * factor),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a non-negative number.\");\r\n }\r\n\r\n public divide(divisor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(divisor)) {\r\n if (this.currency !== divisor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot divide prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount / divisor.getAmount()),\r\n currency: this.currency\r\n });\r\n } else if (typeof divisor === \"number\" && divisor > 0) {\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount / divisor),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a positive number.\");\r\n }\r\n\r\n public min(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((minPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (minPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return minPrice.compareTo(currentPrice) < 0 ? minPrice : currentPrice;\r\n }, this);\r\n }\r\n\r\n public max(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((maxPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (maxPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return maxPrice.compareTo(currentPrice) > 0 ? maxPrice : currentPrice;\r\n }, this);\r\n }\r\n\r\n /**\r\n * Gets a zero value PriceModel for the same currency.\r\n * @returns A PriceModel instance representing zero in the same currency.\r\n */\r\n public zero(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: 0\r\n });\r\n }\r\n\r\n /**\r\n * Checks if the price is zero.\r\n * @returns True if the price is zero, false otherwise.\r\n */\r\n public isZero(): boolean {\r\n return this.amount === 0;\r\n }\r\n\r\n\r\n public round(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: this.getRoundedAmount()\r\n });\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 getRoundedAmount(): number {\r\n return PriceModel.getRoundedAmount(this.amount, this.currency);\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 * @returns The formatted price string according to locale rules.\r\n */\r\n public getFormattedString() {\r\n return PriceModel.getFormattedString(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n toString() {\r\n return this.getFormattedString();\r\n }\r\n\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the amount.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param amount - The initial amount value.\r\n * @param currency - The currency code for formatting.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the amount rounded to the next 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 * @throws {Error} If currency code is invalid.\r\n */\r\n static getFormattedString(amount: number, currency: CurrencyCode, options: {\r\n displayAsInteger?: boolean,\r\n style?: 'currency' | 'decimal',\r\n currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name'\r\n } = {\r\n displayAsInteger: false,\r\n style: 'currency',\r\n currencyDisplay: 'symbol'\r\n }): string {\r\n\r\n const locale = CurrencyLocaleMap[currency];\r\n if (!currency || !locale) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for formatting.');\r\n }\r\n\r\n let valueToFormat = amount;\r\n const fractionDigits = options.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 (options.displayAsInteger) {\r\n valueToFormat = Math.ceil(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 currency \"${currency}\" and locale \"${locale}\":`, 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 OperationalCountryCurrency.INR:\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n /**\r\n * Helper method to determine standard precision places for a currency.\r\n * @param currency - The currency code.\r\n * @return The number of precision places (0, 2, or 3 based on common rules).\r\n */ \r\n private static getPrecisionPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case OperationalCountryCurrency.INR:\r\n default:\r\n return 6;\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 currency - The currency code to determine the rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the price is negative or currency is invalid.\r\n */\r\n static getRoundedAmount(amount: number, currency: CurrencyCode): number {\r\n if (amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative for rounding.\");\r\n }\r\n\r\n if (currency === undefined) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for rounding.');\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(amount * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n}","import { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\nimport { CountryCode, ISODateTimeUTC, Prettify } from \"./Common\";\r\nimport { TaxSystem } from \"./Enum\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\n\r\nexport type TaxRuleAttributes = Prettify<CustomFieldAttributes & {\r\n taxRuleId: string;\r\n taxCategory: string;\r\n taxSystem: TaxSystem;\r\n taxSubSystem: string;\r\n country: CountryCode;\r\n rate: number;\r\n minPrice: PriceData;\r\n maxPrice?: PriceData;\r\n excludeMin?: boolean;\r\n excludeMax?: boolean;\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n}>;\r\n\r\nexport type TaxRuleData = TaxRuleAttributes;\r\n\r\nexport class TaxRuleModel extends CustomFieldModel {\r\n protected taxRuleId: string;\r\n protected taxCategory: string;\r\n protected taxSystem: TaxSystem;\r\n protected taxSubSystem: string;\r\n protected country: CountryCode;\r\n protected rate: number;\r\n protected minPrice: PriceModel;\r\n protected maxPrice?: PriceModel;\r\n protected excludeMin: boolean;\r\n protected excludeMax: boolean;\r\n protected effectiveFrom: ISODateTimeUTC;\r\n protected effectiveTo?: ISODateTimeUTC;\r\n\r\n constructor(data: TaxRuleAttributes) {\r\n super(data);\r\n this.taxRuleId = data.taxRuleId;\r\n this.taxSystem = data.taxSystem;\r\n this.taxSubSystem = data.taxSubSystem;\r\n this.taxCategory = data.taxCategory;\r\n this.country = data.country;\r\n this.rate = data.rate;\r\n this.minPrice = new PriceModel(data.minPrice);\r\n this.maxPrice = data.maxPrice ? new PriceModel(data.maxPrice) : undefined;\r\n this.excludeMin = data.excludeMin ?? false;\r\n this.excludeMax = data.excludeMax ?? false;\r\n this.effectiveFrom = new Date(data.effectiveFrom).toISOString();\r\n this.effectiveTo = data.effectiveTo ? new Date(data.effectiveTo).toISOString() : undefined;\r\n }\r\n\r\n getTaxRuleId(): string {\r\n return this.taxRuleId;\r\n }\r\n\r\n getTaxSystem(): TaxSystem {\r\n return this.taxSystem;\r\n }\r\n\r\n getTaxSubSystem(): string {\r\n return this.taxSubSystem;\r\n }\r\n\r\n getTaxCategory(): string {\r\n return this.taxCategory;\r\n }\r\n\r\n getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n getRate(): number {\r\n return this.rate;\r\n }\r\n\r\n getMinPrice(): PriceModel {\r\n return this.minPrice;\r\n }\r\n\r\n getMaxPrice(): PriceModel | undefined {\r\n return this.maxPrice;\r\n }\r\n\r\n getExcludeMin(): boolean {\r\n return this.excludeMin;\r\n }\r\n\r\n getExcludeMax(): boolean {\r\n return this.excludeMax;\r\n }\r\n\r\n getEffectiveFrom(): string {\r\n return this.effectiveFrom;\r\n }\r\n\r\n getEffectiveTo(): string | undefined {\r\n return this.effectiveTo;\r\n }\r\n\r\n getDetails(): TaxRuleData {\r\n return {\r\n taxRuleId: this.getTaxRuleId(),\r\n taxSystem: this.getTaxSystem(),\r\n taxSubSystem: this.getTaxSubSystem(),\r\n taxCategory: this.getTaxCategory(),\r\n country: this.getCountry(),\r\n rate: this.getRate(),\r\n minPrice: this.getMinPrice().getDetails(),\r\n maxPrice: this.getMaxPrice()?.getDetails(),\r\n excludeMin: this.getExcludeMin(),\r\n excludeMax: this.getExcludeMax(),\r\n effectiveFrom: this.effectiveFrom,\r\n effectiveTo: this.effectiveTo ? this.effectiveTo : undefined,\r\n customFields: this.getAllCustomFields(),\r\n };\r\n }\r\n\r\n /**\r\n * Checks whether this tax rule is applicable for the given category and country at a specific time.\r\n * @param taxCategory - The tax category to check.\r\n * @param country - The country code to check.\r\n * @param price - The price to check against the rule's price range (optional).\r\n * @param at - The date to check effectiveness against (defaults to now).\r\n * @returns True if the rule is applicable, false otherwise.\r\n */\r\n appliesTo(taxCategory: string, country: CountryCode, price?: PriceModel, at: Date = new Date()): boolean {\r\n const isPriceInRange = !price || (\r\n (this.excludeMin ? this.minPrice.compareTo(price) < 0 : this.minPrice.compareTo(price) <= 0) &&\r\n (this.maxPrice\r\n ? (this.excludeMax ? this.maxPrice.compareTo(price) > 0 : this.maxPrice.compareTo(price) >= 0)\r\n : true\r\n )\r\n );\r\n\r\n return (\r\n this.taxCategory === taxCategory &&\r\n this.country === country &&\r\n isPriceInRange &&\r\n Date.parse(this.effectiveFrom) <= at.getTime() &&\r\n (this.effectiveTo ? Date.parse(this.effectiveTo) >= at.getTime() : true)\r\n );\r\n }\r\n\r\n /**\r\n * Gets the applicable tax rate for a given price. Returns the tax rate if the rule applies, otherwise returns 0.\r\n * @param price - The price to check against the tax rule.\r\n * @returns The applicable tax rate as a decimal (e.g., 0.18 for 18%).\r\n */\r\n getApplicableTaxRate(price: PriceModel): number {\r\n if(this.appliesTo(this.taxCategory, this.country, price)) {\r\n return this.rate;\r\n }\r\n return 0;\r\n }\r\n\r\n /**\r\n * Calculates the tax amount for a given taxable amount.\r\n * @param price - The price used to determine the tax amount.\r\n * @returns The calculated tax amount as a PriceModel. Returns zero if the tax rule does not apply.\r\n */\r\n calculateTax(price: PriceModel): PriceModel {\r\n if(!this.appliesTo(this.taxCategory, this.country, price)) {\r\n return price.zero(); // Return zero tax if the rule does not apply\r\n }\r\n\r\n return price.multiply(this.rate);\r\n }\r\n\r\n\r\n static getTaxRateDisplayString(taxRule: TaxRuleModel, rate: number, formateOption?: {\r\n percentageOnly?: boolean;\r\n }): string {\r\n const percentage = rate * 100;\r\n // Format to remove trailing zeros if it's an integer, otherwise keep up to 2 decimal places\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n\r\n if (formateOption?.percentageOnly) {\r\n return `${rateStr}%`;\r\n }\r\n\r\n if (taxRule.getTaxSystem() === TaxSystem.GST) {\r\n return `${taxRule.getTaxSubSystem()} ${rateStr}%`;\r\n }\r\n return `${taxRule.getTaxSystem()} ${rateStr}%`;\r\n }\r\n}\r\n\r\n"]}
@@ -1,2 +1,2 @@
1
- export{a as TaxRuleModel}from'../chunk-SOZHGHMY.mjs';import'../chunk-LI5JQ6UC.mjs';import'../chunk-QK4XJ3GB.mjs';import'../chunk-R5DM7WCD.mjs';import'../chunk-UXZBULDS.mjs';//# sourceMappingURL=TaxRule.mjs.map
1
+ export{a as TaxRuleModel}from'../chunk-ZODPRQKQ.mjs';import'../chunk-6ZKMKSAG.mjs';import'../chunk-TPIIACE7.mjs';import'../chunk-R5DM7WCD.mjs';import'../chunk-UXZBULDS.mjs';//# sourceMappingURL=TaxRule.mjs.map
2
2
  //# sourceMappingURL=TaxRule.mjs.map
@@ -1,2 +1,2 @@
1
- 'use strict';var f={INR:"\u20B9"},I={INR:"en-IN"};var h=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},y=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},g=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},P=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},x=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var d=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},a=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},s=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},o=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}};var l=class t{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new d("Amount cannot be negative.");if(!e.currency)throw new a("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(t.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(t.getPrecisionPlaces(this.currency)))}compareTo(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot compare prices in different currencies.")}else throw new o("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot add prices in different currencies.")}else throw new o("Must be a PriceModel instance.");return new t({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot subtract prices in different currencies.")}else throw new o("Must be a PriceModel instance.");return new t({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot multiply prices in different currencies.");return new t({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new t({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new o("Must be a non-negative number.")}divide(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot divide prices in different currencies.");return new t({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new t({amount:this.getPreciseAmount(this.amount/e),currency:this.currency});throw new o("Must be a positive number.")}min(...e){if(e.length===0)throw new o("Must provide at least one PriceModel.");return e.reduce((r,n)=>{if(t.isPriceModel(n)){if(r.getCurrency()!==n.getCurrency())throw new s("Cannot compare prices in different currencies.")}else throw new o("Must be a PriceModel instance.");return r.compareTo(n)<0?r:n},this)}max(...e){if(e.length===0)throw new o("Must provide at least one PriceModel.");return e.reduce((r,n)=>{if(t.isPriceModel(n)){if(r.getCurrency()!==n.getCurrency())throw new s("Cannot compare prices in different currencies.")}else throw new o("Must be a PriceModel instance.");return r.compareTo(n)>0?r:n},this)}zero(){return new t({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new t({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return t.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return t.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,r,n={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let c=I[r];if(!r||!c)throw new a("Invalid currency code for formatting.");let u=e,m=n.displayAsInteger?0:t.getDecimalPlaces(r),b={style:n.style??"currency",currency:r,signDisplay:"never",currencyDisplay:n.currencyDisplay,minimumFractionDigits:m,maximumFractionDigits:m};n.displayAsInteger&&(u=Math.ceil(u));try{return new Intl.NumberFormat(c,b).format(u)}catch(i){return console.error(`Error formatting price for currency "${r}" and locale "${c}":`,i),`${f[r]??r} ${t.addThousandSeparators(u.toFixed(m))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static getPrecisionPlaces(e){switch(e){case"INR":default:return 6}}static addThousandSeparators(e){let r=e.split("."),n=r[0],c=r.length>1?"."+r[1]:"";return n.replace(/\B(?=(\d{3})+(?!\d))/g,",")+c}static getRoundedAmount(e,r){if(e<0)throw new d("Amount cannot be negative for rounding.");if(r===void 0)throw new a("Invalid currency code for rounding.");let n=t.getDecimalPlaces(r),c=Math.pow(10,n);return Math.round(e*c)/c}};var w=class{baseUnitPrice;taxCategory;tiers;constructor(e){let r=new l(e.baseUnitPrice);if(!e.taxCategory)throw new h;let n=(e.tiers??[]).map(i=>({minQuantity:i.minQuantity,unitPrice:new l(i.unitPrice)})).sort((i,p)=>i.minQuantity-p.minQuantity);if(n.some(i=>i.minQuantity<=0))throw new y;let u=n.some(i=>i.unitPrice.getCurrency()!==r.getCurrency()),m=n.some((i,p)=>p>0&&i.unitPrice.compareTo(n[p-1].unitPrice)>0),b=n[0]?.unitPrice.compareTo(r)>0;if(u||m||b)throw new g("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=r,this.taxCategory=e.taxCategory,this.tiers=n;}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 P;for(let r=this.tiers.length-1;r>=0;r--)if(e>=this.tiers[r].minQuantity){let n=this.tiers[r];return {minQuantity:n.minQuantity,unitPrice:n.unitPrice}}throw new x(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(),r=this.baseUnitPrice.getAmount();return (r-e)/r*100}};exports.TieredPriceModel=w;//# sourceMappingURL=TieredPrice.js.map
1
+ 'use strict';var f={INR:"\u20B9"},I={INR:"en-IN"};var h=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},y=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},g=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},P=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},E=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var d=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},a=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},o=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},s=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}};var l=class t{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new d("Amount cannot be negative.");if(!e.currency)throw new a("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(t.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(t.getPrecisionPlaces(this.currency)))}compareTo(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new o("Cannot compare prices in different currencies.")}else throw new s("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new o("Cannot add prices in different currencies.")}else throw new s("Must be a PriceModel instance.");return new t({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new o("Cannot subtract prices in different currencies.")}else throw new s("Must be a PriceModel instance.");return new t({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new o("Cannot multiply prices in different currencies.");return new t({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new t({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new s("Must be a non-negative number.")}divide(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new o("Cannot divide prices in different currencies.");return new t({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new t({amount:this.getPreciseAmount(this.amount/e),currency:this.currency});throw new s("Must be a positive number.")}min(...e){if(e.length===0)throw new s("Must provide at least one PriceModel.");return e.reduce((r,n)=>{if(t.isPriceModel(n)){if(r.getCurrency()!==n.getCurrency())throw new o("Cannot compare prices in different currencies.")}else throw new s("Must be a PriceModel instance.");return r.compareTo(n)<0?r:n},this)}max(...e){if(e.length===0)throw new s("Must provide at least one PriceModel.");return e.reduce((r,n)=>{if(t.isPriceModel(n)){if(r.getCurrency()!==n.getCurrency())throw new o("Cannot compare prices in different currencies.")}else throw new s("Must be a PriceModel instance.");return r.compareTo(n)>0?r:n},this)}zero(){return new t({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new t({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return t.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return t.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,r,n={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let c=I[r];if(!r||!c)throw new a("Invalid currency code for formatting.");let u=e,m=n.displayAsInteger?0:t.getDecimalPlaces(r),x={style:n.style??"currency",currency:r,signDisplay:"never",currencyDisplay:n.currencyDisplay,minimumFractionDigits:m,maximumFractionDigits:m};n.displayAsInteger&&(u=Math.ceil(u));try{return new Intl.NumberFormat(c,x).format(u)}catch(i){return console.error(`Error formatting price for currency "${r}" and locale "${c}":`,i),`${f[r]??r} ${t.addThousandSeparators(u.toFixed(m))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static getPrecisionPlaces(e){switch(e){case"INR":default:return 6}}static addThousandSeparators(e){let r=e.split("."),n=r[0],c=r.length>1?"."+r[1]:"";return n.replace(/\B(?=(\d{3})+(?!\d))/g,",")+c}static getRoundedAmount(e,r){if(e<0)throw new d("Amount cannot be negative for rounding.");if(r===void 0)throw new a("Invalid currency code for rounding.");let n=t.getDecimalPlaces(r),c=Math.pow(10,n);return Math.round(e*c)/c}};var D=class{baseUnitPrice;taxCategory;tiers;constructor(e){let r=new l(e.baseUnitPrice);if(!e.taxCategory)throw new h;let n=(e.tiers??[]).map(i=>({minQuantity:i.minQuantity,unitPrice:new l(i.unitPrice)})).sort((i,p)=>i.minQuantity-p.minQuantity);if(n.some(i=>i.minQuantity<=0))throw new y;let u=n.some(i=>i.unitPrice.getCurrency()!==r.getCurrency()),m=n.some((i,p)=>p>0&&i.unitPrice.compareTo(n[p-1].unitPrice)>0),x=n[0]?.unitPrice.compareTo(r)>0;if(u||m||x)throw new g("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=r,this.taxCategory=e.taxCategory,this.tiers=n;}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 P;for(let r=this.tiers.length-1;r>=0;r--)if(e>=this.tiers[r].minQuantity){let n=this.tiers[r];return {minQuantity:n.minQuantity,unitPrice:n.unitPrice}}throw new E(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(),r=this.baseUnitPrice.getAmount();return (r-e)/r*100}};exports.TieredPriceModel=D;//# sourceMappingURL=TieredPrice.js.map
2
2
  //# sourceMappingURL=TieredPrice.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/Classes/Enum.ts","../../src/Classes/Error.ts","../../src/Classes/Price.ts","../../src/Classes/TieredPrice.ts"],"names":["CurrencySymbolMap","CurrencyLocaleMap","InvalidTaxCategoryError","message","InvalidMinQuantityError","InvalidTieredPriceError","InvalidQuantityError","NoApplicableTierError","quantity","InvalidPriceAmountError","InvalidCurrencyCodeError","CurrencyMismatchError","InvalidArgumentError","PriceModel","_PriceModel","#kind","data","obj","amount","priceModel","factor","divisor","priceModels","minPrice","currentPrice","maxPrice","currency","options","locale","valueToFormat","fractionDigits","formattingOptions","error","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier","TieredPriceModel","baseUnitPrice","tiers","tier","a","b","t","hasDifferentCurrency","hasIrregularPricing","index","basePriceExceedsFirstTier","i","lowestTierPrice","basePrice"],"mappings":"aAsCO,IAAMA,CAAoB,CAAA,CAC9B,GAAiC,CAAA,QACpC,EAEaC,CAAoB,CAAA,CAC9B,GAAiC,CAAA,OACpC,CCiCO,CAAA,IAAMC,CAAN,CAAA,cAAsC,KAAM,CAC/C,WAAA,CAAYC,CAAkB,CAAA,4BAAA,CAA8B,CACxD,KAAA,CAAM,CAAuBA,oBAAAA,EAAAA,CAAO,EAAE,CACtC,CAAA,IAAA,CAAK,IAAO,CAAA,0BAChB,CACJ,CAEaC,CAAAA,CAAAA,CAAN,cAAsC,KAAM,CAC/C,WAAYD,CAAAA,CAAAA,CAAkB,6CAA+C,CAAA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WAAe,EAAA,CACvC,CAKA,qBAAA,EAAgC,CAC9B,GAAI,CAAC,IAAK,CAAA,KAAA,CAAM,OAAQ,OAAO,CAAA,CAE/B,IAAM2C,CAAAA,CAAkB,KAAK,KAAM,CAAA,IAAA,CAAK,KAAM,CAAA,MAAA,CAAS,CAAC,CAAA,CAAE,SAAU,CAAA,SAAA,GAC9DC,CAAY,CAAA,IAAA,CAAK,aAAc,CAAA,SAAA,GAErC,OAASA,CAAAA,CAAAA,CAAYD,CAAmBC,EAAAA,CAAAA,CAAa,GACvD,CACF","file":"TieredPrice.js","sourcesContent":["/**\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\nexport const CurrencyLocaleMap = {\r\n [OperationalCountryCurrency.INR]: OperationalLocale[\"en-IN\"],\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 GENERAL = 'General',\r\n}\r\n\r\nexport enum ImageCategory {\r\n PRIMARY = 'PRIMARY',\r\n GALLERY = 'GALLERY'\r\n}\r\n\r\nexport enum ChargeType {\r\n SHIPPING = 'SHIPPING',\r\n ADJUSTMENT = 'ADJUSTMENT'\r\n}\r\n\r\nexport enum ChargeImpact {\r\n ADD = \"ADD\",\r\n SUBTRACT = \"SUBTRACT\",\r\n}\r\n\r\nexport enum TaxSystem {\r\n GST = 'GST',\r\n}\r\n\r\n/**\r\n * LineItemState\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 LineItemState {\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}","export 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\nexport class InvalidLineItemStateError extends Error {\r\n constructor(state: string) {\r\n super(`Invalid line item state: ${state}`);\r\n this.name = 'InvalidLineItemStateError';\r\n }\r\n}\r\n\r\nexport class InvalidLineItemTaxRuleError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidLineItemTaxRule: ${message}`);\r\n this.name = 'InvalidLineItemTaxRuleError';\r\n }\r\n}\r\n\r\nexport class DuplicateSizeError extends Error {\r\n constructor(size: string) {\r\n super(`Duplicate size found: ${size}`);\r\n this.name = 'DuplicateSizeError';\r\n }\r\n}\r\n\r\nexport class DuplicateSelectionAttributeError extends Error {\r\n constructor(attribute: string) {\r\n super(`Duplicate selection attribute found: ${attribute}`);\r\n this.name = 'DuplicateSelectionAttributeError';\r\n }\r\n}\r\n\r\nexport class ProductMismatchError extends Error {\r\n constructor(message: string = \"Product and selection attributes do not match.\") {\r\n super(`ProductMismatch: ${message}`);\r\n this.name = 'ProductMismatchError';\r\n }\r\n}\r\n\r\nexport class ProductInactiveError extends Error {\r\n constructor(message: string = \"Product is not active.\") {\r\n super(`ProductInactive: ${message}`);\r\n this.name = 'ProductInactiveError';\r\n }\r\n}\r\n\r\nexport class SelectionAttributeParseError extends Error {\r\n constructor(message: string = \"Failed to parse selection attributes key.\") {\r\n super(`SelectionAttributeParseError: ${message}`);\r\n this.name = 'SelectionAttributeParseError';\r\n }\r\n}\r\n\r\nexport class SizeMismatchError extends Error {\r\n constructor(message: string = \"Size does not match.\") {\r\n super(`SizeMismatch: ${message}`);\r\n this.name = 'SizeMismatchError';\r\n }\r\n}\r\n\r\nexport class PricingNotFoundError extends Error {\r\n constructor(message: string = \"Pricing details not available for the product\") {\r\n super(`NotFound: ${message}`);\r\n this.name = 'PricingNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxRuleError extends Error {\r\n constructor(message: string = \"Tax rule category mismatch.\") {\r\n super(`InvalidTaxRule: ${message}`);\r\n this.name = 'InvalidTaxRuleError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxCategoryError extends Error {\r\n constructor(message: string = \"Tax category is not valid.\") {\r\n super(`InvalidTaxCategory: ${message}`);\r\n this.name = 'InvalidTaxCategoryError';\r\n }\r\n}\r\n\r\nexport class InvalidMinQuantityError extends Error {\r\n constructor(message: string = \"Minimum quantity must be greater than zero.\") {\r\n super(`InvalidMinQuantity: ${message}`);\r\n this.name = 'InvalidMinQuantityError';\r\n }\r\n}\r\n\r\nexport class InvalidTieredPriceError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidTieredPrice: ${message}`);\r\n this.name = 'InvalidTieredPriceError';\r\n }\r\n}\r\n\r\nexport class InvalidQuantityError extends Error {\r\n constructor(message: string = \"Quantity must be greater than zero.\") {\r\n super(`InvalidQuantity: ${message}`);\r\n this.name = 'InvalidQuantityError';\r\n }\r\n}\r\n\r\nexport class NoApplicableTierError extends Error {\r\n constructor(quantity: number) {\r\n super(`NoApplicableTier: Quantity ${quantity} does not meet the minimum purchase requirement.`);\r\n this.name = 'NoApplicableTierError';\r\n }\r\n}\r\n\r\nexport class TaxSlabNotFoundError extends Error {\r\n constructor(message: string = \"No applicable tax slab or multiple slabs found for the given unit price.\") {\r\n super(`TaxSlabNotFound: ${message}`);\r\n this.name = 'TaxSlabNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidPriceAmountError extends Error {\r\n constructor(message: string = \"Amount cannot be negative.\") {\r\n super(`InvalidAmount: ${message}`);\r\n this.name = 'InvalidPriceAmountError';\r\n }\r\n}\r\n\r\nexport class InvalidCurrencyCodeError extends Error {\r\n constructor(message: string = \"Currency code is required.\") {\r\n super(`InvalidCurrency: ${message}`);\r\n this.name = 'InvalidCurrencyCodeError';\r\n }\r\n}\r\n\r\nexport class CurrencyMismatchError extends Error {\r\n constructor(message: string = \"Cannot perform operation on prices with different currencies.\") {\r\n super(`CurrencyMismatch: ${message}`);\r\n this.name = 'CurrencyMismatchError';\r\n }\r\n}\r\n\r\nexport class InvalidArgumentError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidArgument: ${message}`);\r\n this.name = 'InvalidArgumentError';\r\n }\r\n}\r\n\r\nexport class InvalidImageSourceError extends Error {\r\n constructor(message: string = \"Invalid image source configuration.\") {\r\n super(`InvalidImageSource: ${message}`);\r\n this.name = 'InvalidImageSourceError';\r\n }\r\n}\r\n\r\nexport class InvalidChargeError extends Error {\r\n constructor(message: string = \"Invalid charge data.\") {\r\n super(`InvalidCharge: ${message}`);\r\n this.name = 'InvalidChargeError';\r\n }\r\n}\r\n\r\nexport class InvalidChargeTaxRuleError extends Error {\r\n constructor(message: string = \"Invalid charge tax rule.\") {\r\n super(`InvalidChargeTaxRule: ${message}`);\r\n this.name = 'InvalidChargeTaxRuleError';\r\n }\r\n}\r\n","import { CurrencyCode } from \"./Common\";\r\nimport { CurrencyLocaleMap, CurrencySymbolMap, OperationalCountryCurrency } from \"./Enum\";\r\nimport {\r\n InvalidPriceAmountError,\r\n InvalidCurrencyCodeError,\r\n CurrencyMismatchError,\r\n InvalidArgumentError\r\n} from \"./Error\";\r\n\r\nexport type PriceAttributes = {\r\n amount: number;\r\n currency: CurrencyCode;\r\n}\r\n\r\nexport type PriceData = PriceAttributes;\r\n\r\nexport default class PriceModel {\r\n #kind: string;\r\n protected amount: number;\r\n protected currency: CurrencyCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param amount - The initial price value.\r\n * @param currency - The currency 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(data: PriceAttributes) {\r\n this.#kind = \"PriceModel\";\r\n if (data.amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative.\");\r\n }\r\n\r\n if (!data.currency) {\r\n throw new InvalidCurrencyCodeError(\"Currency code is required.\");\r\n }\r\n\r\n this.currency = data.currency;\r\n this.amount = parseFloat(data.amount.toFixed(PriceModel.getPrecisionPlaces(this.currency)));\r\n }\r\n\r\n get kind() {\r\n return this.#kind;\r\n }\r\n\r\n static isPriceModel(obj: unknown): obj is PriceModel {\r\n return typeof obj === \"object\" &&\r\n obj !== null &&\r\n (obj as any).kind === \"PriceModel\";\r\n }\r\n\r\n /**\r\n * Gets the currency associated with this price instance.\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 * Returns the raw numeric price value.\r\n */\r\n public getAmount(): number {\r\n return this.amount;\r\n }\r\n\r\n /**\r\n *\r\n * @returns PriceData\r\n */\r\n public getDetails(): PriceData {\r\n return {\r\n amount: this.amount,\r\n currency: this.currency\r\n }\r\n }\r\n\r\n public getPreciseAmount(amount: number): number {\r\n return parseFloat(amount.toFixed(PriceModel.getPrecisionPlaces(this.currency)));\r\n }\r\n\r\n /**\r\n * Compares this price with another {@link PriceModel} instance.\r\n *\r\n * The comparison is performed using the numeric price value and is only valid\r\n * when both prices are expressed in the same currency.\r\n *\r\n * ### Comparison result:\r\n * - Returns a **negative number** if this price is **less than** `priceModel`\r\n * - Returns **zero** if both prices are **equal**\r\n * - Returns a **positive number** if this price is **greater than** `priceModel`\r\n *\r\n * @param priceModel - The {@link PriceModel} instance to compare against.\r\n *\r\n * @returns\r\n * A signed number representing the comparison result:\r\n * - `< 0` → this price is lower\r\n * - `0` → prices are equal\r\n * - `> 0` → this price is higher\r\n *\r\n * @throws {Error}\r\n * Throws an error if:\r\n * - `priceModel` is not an instance of {@link PriceModel}\r\n * - The currencies of the two prices do not match\r\n *\r\n * @example\r\n * ```ts\r\n * const a = new PriceModel(\"USD\", 100);\r\n * const b = new PriceModel(\"USD\", 150);\r\n *\r\n * a.compareTo(b); // -50\r\n * b.compareTo(a); // 50\r\n * a.compareTo(a); // 0\r\n * ```\r\n */\r\n public compareTo(priceModel: PriceModel): number {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return this.getPreciseAmount(this.amount - priceModel.getAmount());\r\n }\r\n\r\n public add(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot add prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.getPreciseAmount((this.amount + priceModel.getAmount())),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public subtract(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot subtract prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount - priceModel.getAmount()),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public multiply(factor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(factor)) {\r\n if (this.currency !== factor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot multiply prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount * factor.getAmount()),\r\n currency: this.currency\r\n });\r\n } else if (typeof factor === \"number\" && factor >= 0) {\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount * factor),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a non-negative number.\");\r\n }\r\n\r\n public divide(divisor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(divisor)) {\r\n if (this.currency !== divisor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot divide prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount / divisor.getAmount()),\r\n currency: this.currency\r\n });\r\n } else if (typeof divisor === \"number\" && divisor > 0) {\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount / divisor),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a positive number.\");\r\n }\r\n\r\n public min(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((minPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (minPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return minPrice.compareTo(currentPrice) < 0 ? minPrice : currentPrice;\r\n }, this);\r\n }\r\n\r\n public max(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((maxPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (maxPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return maxPrice.compareTo(currentPrice) > 0 ? maxPrice : currentPrice;\r\n }, this);\r\n }\r\n\r\n /**\r\n * Gets a zero value PriceModel for the same currency.\r\n * @returns A PriceModel instance representing zero in the same currency.\r\n */\r\n public zero(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: 0\r\n });\r\n }\r\n\r\n /**\r\n * Checks if the price is zero.\r\n * @returns True if the price is zero, false otherwise.\r\n */\r\n public isZero(): boolean {\r\n return this.amount === 0;\r\n }\r\n\r\n\r\n public round(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: this.getRoundedAmount()\r\n });\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 getRoundedAmount(): number {\r\n return PriceModel.getRoundedAmount(this.amount, this.currency);\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 * @returns The formatted price string according to locale rules.\r\n */\r\n public getFormattedString() {\r\n return PriceModel.getFormattedString(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n toString() {\r\n return this.getFormattedString();\r\n }\r\n\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the amount.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param amount - The initial amount value.\r\n * @param currency - The currency code for formatting.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the amount rounded to the next 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 * @throws {Error} If currency code is invalid.\r\n */\r\n static getFormattedString(amount: number, currency: CurrencyCode, options: {\r\n displayAsInteger?: boolean,\r\n style?: 'currency' | 'decimal',\r\n currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name'\r\n } = {\r\n displayAsInteger: false,\r\n style: 'currency',\r\n currencyDisplay: 'symbol'\r\n }): string {\r\n\r\n const locale = CurrencyLocaleMap[currency];\r\n if (!currency || !locale) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for formatting.');\r\n }\r\n\r\n let valueToFormat = amount;\r\n const fractionDigits = options.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 (options.displayAsInteger) {\r\n valueToFormat = Math.ceil(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 currency \"${currency}\" and locale \"${locale}\":`, 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 OperationalCountryCurrency.INR:\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n /**\r\n * Helper method to determine standard precision places for a currency.\r\n * @param currency - The currency code.\r\n * @return The number of precision places (0, 2, or 3 based on common rules).\r\n */ \r\n private static getPrecisionPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case OperationalCountryCurrency.INR:\r\n default:\r\n return 6;\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 currency - The currency code to determine the rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the price is negative or currency is invalid.\r\n */\r\n static getRoundedAmount(amount: number, currency: CurrencyCode): number {\r\n if (amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative for rounding.\");\r\n }\r\n\r\n if (currency === undefined) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for rounding.');\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(amount * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n}","import PriceModel, { PriceData } from \"./Price\";\r\nimport {\r\n InvalidTaxCategoryError,\r\n InvalidMinQuantityError,\r\n InvalidTieredPriceError,\r\n InvalidQuantityError,\r\n NoApplicableTierError\r\n} from \"./Error\";\r\n\r\n/**\r\n * Represents a pricing tier based on a minimum purchase quantity.\r\n */\r\nexport type PriceTier = {\r\n minQuantity: number;\r\n unitPrice: PriceModel;\r\n};\r\n\r\n/**\r\n * Represents the attributes required for tiered pricing.\r\n */\r\nexport type TieredPriceAttributes = {\r\n baseUnitPrice: PriceData;\r\n taxCategory: string;\r\n\r\n /** Quantity-based pricing tiers */\r\n tiers: {\r\n minQuantity: number;\r\n unitPrice: PriceData;\r\n }[];\r\n};\r\n\r\nexport type TieredPriceData = TieredPriceAttributes;\r\n\r\nexport class TieredPriceModel {\r\n protected baseUnitPrice: PriceModel;\r\n protected taxCategory: string;\r\n protected tiers: PriceTier[];\r\n\r\n /** Constructor\r\n * Initializes the tiered pricing model with the provided attributes.\r\n * @param data - The tiered pricing attributes.\r\n *\r\n * @throws {Error}\r\n * - If the tax category is not valid\r\n * - If any tier has an invalid minimum quantity or unit price\r\n * - If the base unit price is not valid\r\n */\r\n constructor(data: TieredPriceAttributes) {\r\n const baseUnitPrice = new PriceModel(data.baseUnitPrice);\r\n\r\n if (!data.taxCategory) {\r\n throw new InvalidTaxCategoryError();\r\n }\r\n\r\n const tiers = (data.tiers ?? [])\r\n .map(tier => ({\r\n minQuantity: tier.minQuantity,\r\n unitPrice: new PriceModel(tier.unitPrice),\r\n }))\r\n .sort((a, b) => a.minQuantity - b.minQuantity);\r\n\r\n const hasInvalidMinQuantity = tiers.some(t => t.minQuantity <= 0);\r\n if (hasInvalidMinQuantity) {\r\n throw new InvalidMinQuantityError();\r\n }\r\n\r\n const hasDifferentCurrency = tiers.some(\r\n t => t.unitPrice.getCurrency() !== baseUnitPrice.getCurrency()\r\n );\r\n const hasIrregularPricing = tiers.some(\r\n (tier, index) =>\r\n index > 0 &&\r\n tier.unitPrice.compareTo(tiers[index - 1].unitPrice) > 0\r\n );\r\n const basePriceExceedsFirstTier = tiers[0]?.unitPrice.compareTo(baseUnitPrice) > 0;\r\n\r\n if (hasDifferentCurrency || hasIrregularPricing || basePriceExceedsFirstTier) {\r\n throw new InvalidTieredPriceError(\r\n \"Tiers must share the same currency and must not increase in unit price.\"\r\n );\r\n }\r\n\r\n this.baseUnitPrice = baseUnitPrice;\r\n this.taxCategory = data.taxCategory;\r\n this.tiers = tiers;\r\n }\r\n\r\n /** \r\n * Returns the base unit price \r\n * @returns The base unit price as a PriceModel instance.\r\n */\r\n getBaseUnitPrice(): PriceModel {\r\n return this.baseUnitPrice;\r\n }\r\n\r\n /** \r\n * Returns the tax category \r\n * @returns The tax category as a TaxCategory enum value.\r\n */\r\n getTaxCategory(): string {\r\n return this.taxCategory;\r\n }\r\n\r\n /** \r\n * Returns all pricing tiers sorted by minimum quantity \r\n * @returns An array of PriceTier objects.\r\n */\r\n getTiers(): readonly PriceTier[] {\n return this.tiers.map(tier => ({\n minQuantity: tier.minQuantity,\n unitPrice: tier.unitPrice\n }));\n }\n\r\n getDetails(): TieredPriceData {\r\n return {\r\n baseUnitPrice: this.baseUnitPrice.getDetails(),\r\n taxCategory: this.taxCategory,\r\n tiers: this.tiers.map(tier => ({\r\n minQuantity: tier.minQuantity,\r\n unitPrice: tier.unitPrice.getDetails()\r\n }))\r\n };\r\n }\r\n\r\n /**\r\n * Returns the applicable unit price for a given quantity.\r\n *\r\n * @param quantity - Purchase quantity\r\n * @returns The unit price for the highest applicable tier\r\n *\r\n * @throws {Error}\r\n * - If quantity is less than or equal to zero\r\n * - If quantity does not meet the minimum requirement of any tier\r\n */\r\n getApplicableTier(quantity: number): PriceTier {\n if (quantity <= 0) {\r\n throw new InvalidQuantityError();\r\n }\r\n\r\n for (let i = this.tiers.length - 1; i >= 0; i--) {\r\n if (quantity >= this.tiers[i].minQuantity) {\r\n const tier = this.tiers[i];\n return { minQuantity: tier.minQuantity, unitPrice: tier.unitPrice };\n }\n }\n\r\n throw new NoApplicableTierError(quantity);\r\n }\r\n\r\n /**\r\n * Returns the minimum quantity required to purchase this product.\r\n */\r\n getMinQuantity(): number {\r\n return this.tiers[0]?.minQuantity ?? 1;\r\n }\r\n\r\n /**\r\n * Returns the maximum discount percentage achievable compared to the base unit price.\r\n */\r\n getMaxDiscountPercent(): number {\r\n if (!this.tiers.length) return 0;\r\n\r\n const lowestTierPrice = this.tiers[this.tiers.length - 1].unitPrice.getAmount();\r\n const basePrice = this.baseUnitPrice.getAmount();\r\n\r\n return ((basePrice - lowestTierPrice) / basePrice) * 100;\r\n }\r\n}\r\n"]}
1
+ {"version":3,"sources":["../../src/Classes/Enum.ts","../../src/Classes/Error.ts","../../src/Classes/Price.ts","../../src/Classes/TieredPrice.ts"],"names":["CurrencySymbolMap","CurrencyLocaleMap","InvalidTaxCategoryError","message","InvalidMinQuantityError","InvalidTieredPriceError","InvalidQuantityError","NoApplicableTierError","quantity","InvalidPriceAmountError","InvalidCurrencyCodeError","CurrencyMismatchError","InvalidArgumentError","PriceModel","_PriceModel","#kind","data","obj","amount","priceModel","factor","divisor","priceModels","minPrice","currentPrice","maxPrice","currency","options","locale","valueToFormat","fractionDigits","formattingOptions","error","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier","TieredPriceModel","baseUnitPrice","tiers","tier","a","b","t","has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AA,CAAI,IAAK,CAAA,KAAA,CAAM,OAAS,CAAGA,CAAAA,CAAAA,EAAK,CAAGA,CAAAA,CAAAA,EAAAA,CAC1C,GAAI1C,CAAAA,EAAY,IAAK,CAAA,KAAA,CAAM0C,CAAC,CAAE,CAAA,WAAA,CAAa,CACzC,IAAMR,CAAO,CAAA,IAAA,CAAK,KAAMQ,CAAAA,CAAC,EACzB,OAAO,CAAE,WAAaR,CAAAA,CAAAA,CAAK,WAAa,CAAA,SAAA,CAAWA,CAAK,CAAA,SAAU,CACpE,CAGF,MAAM,IAAInC,CAAAA,CAAsBC,CAAQ,CAC1C,CAKA,cAAyB,EAAA,CACvB,OAAO,IAAK,CAAA,KAAA,CAAM,CAAC,CAAA,EAAG,WAAe,EAAA,CACvC,CAKA,qBAAA,EAAgC,CAC9B,GAAI,CAAC,IAAK,CAAA,KAAA,CAAM,OAAQ,OAAO,CAAA,CAE/B,IAAM2C,CAAAA,CAAkB,KAAK,KAAM,CAAA,IAAA,CAAK,KAAM,CAAA,MAAA,CAAS,CAAC,CAAA,CAAE,SAAU,CAAA,SAAA,GAC9DC,CAAY,CAAA,IAAA,CAAK,aAAc,CAAA,SAAA,GAErC,OAASA,CAAAA,CAAAA,CAAYD,CAAmBC,EAAAA,CAAAA,CAAa,GACvD,CACF","file":"TieredPrice.js","sourcesContent":["/**\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\nexport const CurrencyLocaleMap = {\r\n [OperationalCountryCurrency.INR]: OperationalLocale[\"en-IN\"],\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 GENERAL = 'General',\r\n}\r\n\r\nexport enum ImageCategory {\r\n PRIMARY = 'PRIMARY',\r\n GALLERY = 'GALLERY'\r\n}\r\n\r\nexport enum ChargeType {\r\n SHIPPING = 'SHIPPING',\r\n ADJUSTMENT = 'ADJUSTMENT'\r\n}\r\n\r\nexport enum ChargeImpact {\r\n ADD = \"ADD\",\r\n SUBTRACT = \"SUBTRACT\",\r\n}\r\n\r\nexport enum TaxSystem {\r\n GST = 'GST',\r\n}\r\n\r\n/**\r\n * LineItemState\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 LineItemState {\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 UNDELIVERED = \"UNDELIVERED\",\r\n REFUND_INITIATED = \"REFUND_INITIATED\",\r\n REFUNDED = \"REFUNDED\",\r\n ON_HOLD = \"ON_HOLD\",\r\n}\r\n/**\r\n * InvoiceState defines the lifecycle of a financial document.\r\n */\r\nexport enum InvoiceState {\r\n /** Preliminary document being drafted; has no legal or financial impact yet. */\r\n DRAFT = \"DRAFT\",\r\n\r\n /** Legally finalized document sent to the customer; tax and revenue are recognized. */\r\n ISSUED = \"ISSUED\",\r\n\r\n /** \r\n * Cancelled before the document became legally effective or reached the customer.\r\n * Used for Failed Deliveries (RTO) where the invoice was not yet reported to GST portals.\r\n */\r\n VOIDED = \"VOIDED\",\r\n\r\n /**\r\n * Officially reversed due to a sales return or refund after the document was legally finalized.\r\n * Marks that the tax liability of this invoice has been nullified elsewhere.\r\n */\r\n CREDITED = \"CREDITED\",\r\n \r\n /** Marked once the invoice has been officially filed with tax authorities (e.g. GSTR-1). */\r\n REPORTED = \"REPORTED\"\r\n}\r\n","export 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\nexport class InvalidLineItemStateError extends Error {\r\n constructor(state: string) {\r\n super(`Invalid line item state: ${state}`);\r\n this.name = 'InvalidLineItemStateError';\r\n }\r\n}\r\n\r\nexport class InvalidLineItemTaxRuleError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidLineItemTaxRule: ${message}`);\r\n this.name = 'InvalidLineItemTaxRuleError';\r\n }\r\n}\r\n\r\nexport class DuplicateSizeError extends Error {\r\n constructor(size: string) {\r\n super(`Duplicate size found: ${size}`);\r\n this.name = 'DuplicateSizeError';\r\n }\r\n}\r\n\r\nexport class DuplicateSelectionAttributeError extends Error {\r\n constructor(attribute: string) {\r\n super(`Duplicate selection attribute found: ${attribute}`);\r\n this.name = 'DuplicateSelectionAttributeError';\r\n }\r\n}\r\n\r\nexport class ProductMismatchError extends Error {\r\n constructor(message: string = \"Product and selection attributes do not match.\") {\r\n super(`ProductMismatch: ${message}`);\r\n this.name = 'ProductMismatchError';\r\n }\r\n}\r\n\r\nexport class ProductInactiveError extends Error {\r\n constructor(message: string = \"Product is not active.\") {\r\n super(`ProductInactive: ${message}`);\r\n this.name = 'ProductInactiveError';\r\n }\r\n}\r\n\r\nexport class SelectionAttributeParseError extends Error {\r\n constructor(message: string = \"Failed to parse selection attributes key.\") {\r\n super(`SelectionAttributeParseError: ${message}`);\r\n this.name = 'SelectionAttributeParseError';\r\n }\r\n}\r\n\r\nexport class SizeMismatchError extends Error {\r\n constructor(message: string = \"Size does not match.\") {\r\n super(`SizeMismatch: ${message}`);\r\n this.name = 'SizeMismatchError';\r\n }\r\n}\r\n\r\nexport class PricingNotFoundError extends Error {\r\n constructor(message: string = \"Pricing details not available for the product\") {\r\n super(`NotFound: ${message}`);\r\n this.name = 'PricingNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxRuleError extends Error {\r\n constructor(message: string = \"Tax rule category mismatch.\") {\r\n super(`InvalidTaxRule: ${message}`);\r\n this.name = 'InvalidTaxRuleError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxCategoryError extends Error {\r\n constructor(message: string = \"Tax category is not valid.\") {\r\n super(`InvalidTaxCategory: ${message}`);\r\n this.name = 'InvalidTaxCategoryError';\r\n }\r\n}\r\n\r\nexport class InvalidMinQuantityError extends Error {\r\n constructor(message: string = \"Minimum quantity must be greater than zero.\") {\r\n super(`InvalidMinQuantity: ${message}`);\r\n this.name = 'InvalidMinQuantityError';\r\n }\r\n}\r\n\r\nexport class InvalidTieredPriceError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidTieredPrice: ${message}`);\r\n this.name = 'InvalidTieredPriceError';\r\n }\r\n}\r\n\r\nexport class InvalidQuantityError extends Error {\r\n constructor(message: string = \"Quantity must be greater than zero.\") {\r\n super(`InvalidQuantity: ${message}`);\r\n this.name = 'InvalidQuantityError';\r\n }\r\n}\r\n\r\nexport class NoApplicableTierError extends Error {\r\n constructor(quantity: number) {\r\n super(`NoApplicableTier: Quantity ${quantity} does not meet the minimum purchase requirement.`);\r\n this.name = 'NoApplicableTierError';\r\n }\r\n}\r\n\r\nexport class TaxSlabNotFoundError extends Error {\r\n constructor(message: string = \"No applicable tax slab or multiple slabs found for the given unit price.\") {\r\n super(`TaxSlabNotFound: ${message}`);\r\n this.name = 'TaxSlabNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidPriceAmountError extends Error {\r\n constructor(message: string = \"Amount cannot be negative.\") {\r\n super(`InvalidAmount: ${message}`);\r\n this.name = 'InvalidPriceAmountError';\r\n }\r\n}\r\n\r\nexport class InvalidCurrencyCodeError extends Error {\r\n constructor(message: string = \"Currency code is required.\") {\r\n super(`InvalidCurrency: ${message}`);\r\n this.name = 'InvalidCurrencyCodeError';\r\n }\r\n}\r\n\r\nexport class CurrencyMismatchError extends Error {\r\n constructor(message: string = \"Cannot perform operation on prices with different currencies.\") {\r\n super(`CurrencyMismatch: ${message}`);\r\n this.name = 'CurrencyMismatchError';\r\n }\r\n}\r\n\r\nexport class InvalidArgumentError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidArgument: ${message}`);\r\n this.name = 'InvalidArgumentError';\r\n }\r\n}\r\n\r\nexport class InvalidImageSourceError extends Error {\r\n constructor(message: string = \"Invalid image source configuration.\") {\r\n super(`InvalidImageSource: ${message}`);\r\n this.name = 'InvalidImageSourceError';\r\n }\r\n}\r\n\r\nexport class InvalidChargeError extends Error {\r\n constructor(message: string = \"Invalid charge data.\") {\r\n super(`InvalidCharge: ${message}`);\r\n this.name = 'InvalidChargeError';\r\n }\r\n}\r\n\r\nexport class InvalidChargeTaxRuleError extends Error {\r\n constructor(message: string = \"Invalid charge tax rule.\") {\r\n super(`InvalidChargeTaxRule: ${message}`);\r\n this.name = 'InvalidChargeTaxRuleError';\r\n }\r\n}\r\n","import { CurrencyCode } from \"./Common\";\r\nimport { CurrencyLocaleMap, CurrencySymbolMap, OperationalCountryCurrency } from \"./Enum\";\r\nimport {\r\n InvalidPriceAmountError,\r\n InvalidCurrencyCodeError,\r\n CurrencyMismatchError,\r\n InvalidArgumentError\r\n} from \"./Error\";\r\n\r\nexport type PriceAttributes = {\r\n amount: number;\r\n currency: CurrencyCode;\r\n}\r\n\r\nexport type PriceData = PriceAttributes;\r\n\r\nexport default class PriceModel {\r\n #kind: string;\r\n protected amount: number;\r\n protected currency: CurrencyCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param amount - The initial price value.\r\n * @param currency - The currency 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(data: PriceAttributes) {\r\n this.#kind = \"PriceModel\";\r\n if (data.amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative.\");\r\n }\r\n\r\n if (!data.currency) {\r\n throw new InvalidCurrencyCodeError(\"Currency code is required.\");\r\n }\r\n\r\n this.currency = data.currency;\r\n this.amount = parseFloat(data.amount.toFixed(PriceModel.getPrecisionPlaces(this.currency)));\r\n }\r\n\r\n get kind() {\r\n return this.#kind;\r\n }\r\n\r\n static isPriceModel(obj: unknown): obj is PriceModel {\r\n return typeof obj === \"object\" &&\r\n obj !== null &&\r\n (obj as any).kind === \"PriceModel\";\r\n }\r\n\r\n /**\r\n * Gets the currency associated with this price instance.\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 * Returns the raw numeric price value.\r\n */\r\n public getAmount(): number {\r\n return this.amount;\r\n }\r\n\r\n /**\r\n *\r\n * @returns PriceData\r\n */\r\n public getDetails(): PriceData {\r\n return {\r\n amount: this.amount,\r\n currency: this.currency\r\n }\r\n }\r\n\r\n public getPreciseAmount(amount: number): number {\r\n return parseFloat(amount.toFixed(PriceModel.getPrecisionPlaces(this.currency)));\r\n }\r\n\r\n /**\r\n * Compares this price with another {@link PriceModel} instance.\r\n *\r\n * The comparison is performed using the numeric price value and is only valid\r\n * when both prices are expressed in the same currency.\r\n *\r\n * ### Comparison result:\r\n * - Returns a **negative number** if this price is **less than** `priceModel`\r\n * - Returns **zero** if both prices are **equal**\r\n * - Returns a **positive number** if this price is **greater than** `priceModel`\r\n *\r\n * @param priceModel - The {@link PriceModel} instance to compare against.\r\n *\r\n * @returns\r\n * A signed number representing the comparison result:\r\n * - `< 0` → this price is lower\r\n * - `0` → prices are equal\r\n * - `> 0` → this price is higher\r\n *\r\n * @throws {Error}\r\n * Throws an error if:\r\n * - `priceModel` is not an instance of {@link PriceModel}\r\n * - The currencies of the two prices do not match\r\n *\r\n * @example\r\n * ```ts\r\n * const a = new PriceModel(\"USD\", 100);\r\n * const b = new PriceModel(\"USD\", 150);\r\n *\r\n * a.compareTo(b); // -50\r\n * b.compareTo(a); // 50\r\n * a.compareTo(a); // 0\r\n * ```\r\n */\r\n public compareTo(priceModel: PriceModel): number {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return this.getPreciseAmount(this.amount - priceModel.getAmount());\r\n }\r\n\r\n public add(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot add prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.getPreciseAmount((this.amount + priceModel.getAmount())),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public subtract(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot subtract prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount - priceModel.getAmount()),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public multiply(factor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(factor)) {\r\n if (this.currency !== factor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot multiply prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount * factor.getAmount()),\r\n currency: this.currency\r\n });\r\n } else if (typeof factor === \"number\" && factor >= 0) {\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount * factor),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a non-negative number.\");\r\n }\r\n\r\n public divide(divisor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(divisor)) {\r\n if (this.currency !== divisor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot divide prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount / divisor.getAmount()),\r\n currency: this.currency\r\n });\r\n } else if (typeof divisor === \"number\" && divisor > 0) {\r\n return new PriceModel({\r\n amount: this.getPreciseAmount(this.amount / divisor),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a positive number.\");\r\n }\r\n\r\n public min(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((minPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (minPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return minPrice.compareTo(currentPrice) < 0 ? minPrice : currentPrice;\r\n }, this);\r\n }\r\n\r\n public max(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((maxPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (maxPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return maxPrice.compareTo(currentPrice) > 0 ? maxPrice : currentPrice;\r\n }, this);\r\n }\r\n\r\n /**\r\n * Gets a zero value PriceModel for the same currency.\r\n * @returns A PriceModel instance representing zero in the same currency.\r\n */\r\n public zero(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: 0\r\n });\r\n }\r\n\r\n /**\r\n * Checks if the price is zero.\r\n * @returns True if the price is zero, false otherwise.\r\n */\r\n public isZero(): boolean {\r\n return this.amount === 0;\r\n }\r\n\r\n\r\n public round(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: this.getRoundedAmount()\r\n });\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 getRoundedAmount(): number {\r\n return PriceModel.getRoundedAmount(this.amount, this.currency);\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 * @returns The formatted price string according to locale rules.\r\n */\r\n public getFormattedString() {\r\n return PriceModel.getFormattedString(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n toString() {\r\n return this.getFormattedString();\r\n }\r\n\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the amount.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param amount - The initial amount value.\r\n * @param currency - The currency code for formatting.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the amount rounded to the next 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 * @throws {Error} If currency code is invalid.\r\n */\r\n static getFormattedString(amount: number, currency: CurrencyCode, options: {\r\n displayAsInteger?: boolean,\r\n style?: 'currency' | 'decimal',\r\n currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name'\r\n } = {\r\n displayAsInteger: false,\r\n style: 'currency',\r\n currencyDisplay: 'symbol'\r\n }): string {\r\n\r\n const locale = CurrencyLocaleMap[currency];\r\n if (!currency || !locale) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for formatting.');\r\n }\r\n\r\n let valueToFormat = amount;\r\n const fractionDigits = options.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 (options.displayAsInteger) {\r\n valueToFormat = Math.ceil(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 currency \"${currency}\" and locale \"${locale}\":`, 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 OperationalCountryCurrency.INR:\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n /**\r\n * Helper method to determine standard precision places for a currency.\r\n * @param currency - The currency code.\r\n * @return The number of precision places (0, 2, or 3 based on common rules).\r\n */ \r\n private static getPrecisionPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case OperationalCountryCurrency.INR:\r\n default:\r\n return 6;\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 currency - The currency code to determine the rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the price is negative or currency is invalid.\r\n */\r\n static getRoundedAmount(amount: number, currency: CurrencyCode): number {\r\n if (amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative for rounding.\");\r\n }\r\n\r\n if (currency === undefined) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for rounding.');\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(amount * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n}","import PriceModel, { PriceData } from \"./Price\";\r\nimport {\r\n InvalidTaxCategoryError,\r\n InvalidMinQuantityError,\r\n InvalidTieredPriceError,\r\n InvalidQuantityError,\r\n NoApplicableTierError\r\n} from \"./Error\";\r\n\r\n/**\r\n * Represents a pricing tier based on a minimum purchase quantity.\r\n */\r\nexport type PriceTier = {\r\n minQuantity: number;\r\n unitPrice: PriceModel;\r\n};\r\n\r\n/**\r\n * Represents the attributes required for tiered pricing.\r\n */\r\nexport type TieredPriceAttributes = {\r\n baseUnitPrice: PriceData;\r\n taxCategory: string;\r\n\r\n /** Quantity-based pricing tiers */\r\n tiers: {\r\n minQuantity: number;\r\n unitPrice: PriceData;\r\n }[];\r\n};\r\n\r\nexport type TieredPriceData = TieredPriceAttributes;\r\n\r\nexport class TieredPriceModel {\r\n protected baseUnitPrice: PriceModel;\r\n protected taxCategory: string;\r\n protected tiers: PriceTier[];\r\n\r\n /** Constructor\r\n * Initializes the tiered pricing model with the provided attributes.\r\n * @param data - The tiered pricing attributes.\r\n *\r\n * @throws {Error}\r\n * - If the tax category is not valid\r\n * - If any tier has an invalid minimum quantity or unit price\r\n * - If the base unit price is not valid\r\n */\r\n constructor(data: TieredPriceAttributes) {\r\n const baseUnitPrice = new PriceModel(data.baseUnitPrice);\r\n\r\n if (!data.taxCategory) {\r\n throw new InvalidTaxCategoryError();\r\n }\r\n\r\n const tiers = (data.tiers ?? [])\r\n .map(tier => ({\r\n minQuantity: tier.minQuantity,\r\n unitPrice: new PriceModel(tier.unitPrice),\r\n }))\r\n .sort((a, b) => a.minQuantity - b.minQuantity);\r\n\r\n const hasInvalidMinQuantity = tiers.some(t => t.minQuantity <= 0);\r\n if (hasInvalidMinQuantity) {\r\n throw new InvalidMinQuantityError();\r\n }\r\n\r\n const hasDifferentCurrency = tiers.some(\r\n t => t.unitPrice.getCurrency() !== baseUnitPrice.getCurrency()\r\n );\r\n const hasIrregularPricing = tiers.some(\r\n (tier, index) =>\r\n index > 0 &&\r\n tier.unitPrice.compareTo(tiers[index - 1].unitPrice) > 0\r\n );\r\n const basePriceExceedsFirstTier = tiers[0]?.unitPrice.compareTo(baseUnitPrice) > 0;\r\n\r\n if (hasDifferentCurrency || hasIrregularPricing || basePriceExceedsFirstTier) {\r\n throw new InvalidTieredPriceError(\r\n \"Tiers must share the same currency and must not increase in unit price.\"\r\n );\r\n }\r\n\r\n this.baseUnitPrice = baseUnitPrice;\r\n this.taxCategory = data.taxCategory;\r\n this.tiers = tiers;\r\n }\r\n\r\n /** \r\n * Returns the base unit price \r\n * @returns The base unit price as a PriceModel instance.\r\n */\r\n getBaseUnitPrice(): PriceModel {\r\n return this.baseUnitPrice;\r\n }\r\n\r\n /** \r\n * Returns the tax category \r\n * @returns The tax category as a TaxCategory enum value.\r\n */\r\n getTaxCategory(): string {\r\n return this.taxCategory;\r\n }\r\n\r\n /** \r\n * Returns all pricing tiers sorted by minimum quantity \r\n * @returns An array of PriceTier objects.\r\n */\r\n getTiers(): readonly PriceTier[] {\n return this.tiers.map(tier => ({\n minQuantity: tier.minQuantity,\n unitPrice: tier.unitPrice\n }));\n }\n\r\n getDetails(): TieredPriceData {\r\n return {\r\n baseUnitPrice: this.baseUnitPrice.getDetails(),\r\n taxCategory: this.taxCategory,\r\n tiers: this.tiers.map(tier => ({\r\n minQuantity: tier.minQuantity,\r\n unitPrice: tier.unitPrice.getDetails()\r\n }))\r\n };\r\n }\r\n\r\n /**\r\n * Returns the applicable unit price for a given quantity.\r\n *\r\n * @param quantity - Purchase quantity\r\n * @returns The unit price for the highest applicable tier\r\n *\r\n * @throws {Error}\r\n * - If quantity is less than or equal to zero\r\n * - If quantity does not meet the minimum requirement of any tier\r\n */\r\n getApplicableTier(quantity: number): PriceTier {\n if (quantity <= 0) {\r\n throw new InvalidQuantityError();\r\n }\r\n\r\n for (let i = this.tiers.length - 1; i >= 0; i--) {\r\n if (quantity >= this.tiers[i].minQuantity) {\r\n const tier = this.tiers[i];\n return { minQuantity: tier.minQuantity, unitPrice: tier.unitPrice };\n }\n }\n\r\n throw new NoApplicableTierError(quantity);\r\n }\r\n\r\n /**\r\n * Returns the minimum quantity required to purchase this product.\r\n */\r\n getMinQuantity(): number {\r\n return this.tiers[0]?.minQuantity ?? 1;\r\n }\r\n\r\n /**\r\n * Returns the maximum discount percentage achievable compared to the base unit price.\r\n */\r\n getMaxDiscountPercent(): number {\r\n if (!this.tiers.length) return 0;\r\n\r\n const lowestTierPrice = this.tiers[this.tiers.length - 1].unitPrice.getAmount();\r\n const basePrice = this.baseUnitPrice.getAmount();\r\n\r\n return ((basePrice - lowestTierPrice) / basePrice) * 100;\r\n }\r\n}\r\n"]}
@@ -1,2 +1,2 @@
1
- export{a as TieredPriceModel}from'../chunk-FCRJAAPY.mjs';import'../chunk-LI5JQ6UC.mjs';import'../chunk-QK4XJ3GB.mjs';import'../chunk-R5DM7WCD.mjs';//# sourceMappingURL=TieredPrice.mjs.map
1
+ export{a as TieredPriceModel}from'../chunk-S6LR7AUZ.mjs';import'../chunk-6ZKMKSAG.mjs';import'../chunk-TPIIACE7.mjs';import'../chunk-R5DM7WCD.mjs';//# sourceMappingURL=TieredPrice.mjs.map
2
2
  //# sourceMappingURL=TieredPrice.mjs.map
@@ -1,2 +1,2 @@
1
- import {a as a$1}from'./chunk-FCRJAAPY.mjs';import {b as b$2}from'./chunk-2B2XI6FG.mjs';import {e as e$1}from'./chunk-QK4XJ3GB.mjs';import {h as h$1,e}from'./chunk-R5DM7WCD.mjs';import {b as b$1}from'./chunk-UXZBULDS.mjs';import K from'crypto';var y=new Uint8Array(256),h=y.length;function I(){return h>y.length-16&&(K.randomFillSync(y),h=0),y.slice(h,h+=16)}var z=/^(?:[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 $(t){return typeof t=="string"&&z.test(t)}var U=$;var n=[];for(let t=0;t<256;++t)n.push((t+256).toString(16).slice(1));function b(t,e=0){return n[t[e+0]]+n[t[e+1]]+n[t[e+2]]+n[t[e+3]]+"-"+n[t[e+4]]+n[t[e+5]]+"-"+n[t[e+6]]+n[t[e+7]]+"-"+n[t[e+8]]+n[t[e+9]]+"-"+n[t[e+10]]+n[t[e+11]]+n[t[e+12]]+n[t[e+13]]+n[t[e+14]]+n[t[e+15]]}function k(t){if(!U(t))throw TypeError("Invalid UUID");let e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}var M=k;function V(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var G="6ba7b810-9dad-11d1-80b4-00c04fd430c8",B="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function x(t,e,r){function i(o,s,u,S){var A;if(typeof o=="string"&&(o=V(o)),typeof s=="string"&&(s=M(s)),((A=s)===null||A===void 0?void 0:A.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let g=new Uint8Array(16+o.length);if(g.set(s),g.set(o,s.length),g=r(g),g[6]=g[6]&15|e,g[8]=g[8]&63|128,u){S=S||0;for(let m=0;m<16;++m)u[S+m]=g[m];return u}return b(g)}try{i.name=t;}catch{}return i.DNS=G,i.URL=B,i}var L={randomUUID:K.randomUUID};function j(t,e,r){if(L.randomUUID&&!e&&!t)return L.randomUUID();t=t||{};let i=t.random||(t.rng||I)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){r=r||0;for(let o=0;o<16;++o)e[r+o]=i[o];return e}return b(i)}var D=j;function Z(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),K.createHash("sha1").update(t).digest()}var R=Z;var q=x("v5",80,R),P=q;var O={isUUID:t=>/^[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(t),isEmail:t=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t),isURL:t=>/^(http|https):\/\/[^ "]+$/.test(t),generateUUID:(t,e)=>e&&t?P(t,e):D(),generateSearchId:(t,e)=>`${t}#${f.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:t=>{let[e,r]=t.split("#");return {key:e,selectionAttributes:f.parseSelectionAttributesKey(r)}},deepClone(t){return structuredClone(t)}},a=O;var f=class t extends b$1{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 h$1("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 r={},i=e.split("|");for(let o of i){let[s,u]=o.split(":");u.startsWith("c+")?r[s]={name:u.slice(2)}:r[s]=u;}return r}catch(r){throw new h$1(r?.message)}}constructor(e$1,r=new Date){super(e$1,r),this.id=e$1.id,this.key=e$1.key,this.name={...e$1.name},this.description={...e$1.description},this.slug={...e$1.slug},this.brand=e$1.brand,this.pricing=Object.keys(e$1.pricing).reduce((o,s)=>(e$1.pricing[s]&&(o[s]=new a$1(e$1.pricing[s])),o),{}),this.targetGender=e$1.targetGender,this.attributes=a.deepClone(e$1.attributes),this.specifications=a.deepClone(e$1.specifications),this.categories=a.deepClone(e$1.categories);let i=new Set;this.variants=(e$1.variants||[]).map(o=>{if(!o.selectionAttributes||typeof o.selectionAttributes!="object")throw new h$1("Selection attributes are required");this.checkSelectionAttributes(o.selectionAttributes);let s=t.generateSelectionAttributesKey(o.selectionAttributes);if(i.has(s))throw new e(s);return i.add(s),{sku:o.sku,selectionAttributes:o.selectionAttributes,images:{primary:new b$2(o.images.primary),gallery:(o.images.gallery||[]).map(u=>new b$2(u))}}}),this.isActive=e$1.isActive,this.searchTags=e$1.searchTags?a.deepClone(e$1.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[e$1[e]]??this.name.en:a.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[e$1[e]]??this.description.en:a.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[e$1[e]]??this.slug.en:a.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return a.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:a.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let r=t.generateSelectionAttributesKey(e),i=this.variants.find(o=>t.generateSelectionAttributesKey(o.selectionAttributes)===r);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,r){switch(r){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 a.deepClone(this.categories)}getSpecifications(e){return e?a.deepClone(this.specifications[e]??this.specifications[e$1[e]]??this.specifications.en):a.deepClone(this.specifications)}getSearchTags(e){return e?a.deepClone(this.searchTags[e]??this.searchTags[e$1[e]]??this.searchTags.en):a.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((r,i)=>(this.pricing[i]&&(r[i]=this.pricing[i]?.getDetails()),r),{}),attributes:this.getAttributes(),variants:this.variants.map(r=>({sku:r.sku,selectionAttributes:a.deepClone(r.selectionAttributes),images:{primary:r.images.primary.getDetails(),gallery:r.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 h$1("Selection attributes are required");Object.keys(this.attributes).forEach(r=>{if(r.toLowerCase()==="size")return;let i=this.attributes[r],o=e[r];if(o===void 0)throw new h$1(`Selection attribute '${r}' is missing`);if(typeof i=="string"){if(typeof o!="string"||i!==o)throw new h$1(`Selection attribute '${r}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof o!="string"||!i.includes(o))throw new h$1(`Selection attribute '${r}' is invalid`)}else if(typeof o!="object"||!("name"in o)||i.findIndex(s=>s.name===o.name)<0)throw new h$1(`Selection attribute '${r}' is invalid`)}});}validateSelectionAttribute(e){let r=t.generateSelectionAttributesKey(e);return this.variants.some(i=>t.generateSelectionAttributesKey(i.selectionAttributes)===r)}validateSize(e){return this.attributes.size.includes(e)}};export{a,f as b};//# sourceMappingURL=chunk-MHLRJ4IJ.mjs.map
2
- //# sourceMappingURL=chunk-MHLRJ4IJ.mjs.map
1
+ import {a as a$1}from'./chunk-S6LR7AUZ.mjs';import {b as b$2}from'./chunk-2B2XI6FG.mjs';import {e as e$1}from'./chunk-TPIIACE7.mjs';import {h as h$1,e}from'./chunk-R5DM7WCD.mjs';import {b as b$1}from'./chunk-UXZBULDS.mjs';import K from'crypto';var y=new Uint8Array(256),h=y.length;function I(){return h>y.length-16&&(K.randomFillSync(y),h=0),y.slice(h,h+=16)}var z=/^(?:[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 $(t){return typeof t=="string"&&z.test(t)}var U=$;var n=[];for(let t=0;t<256;++t)n.push((t+256).toString(16).slice(1));function b(t,e=0){return n[t[e+0]]+n[t[e+1]]+n[t[e+2]]+n[t[e+3]]+"-"+n[t[e+4]]+n[t[e+5]]+"-"+n[t[e+6]]+n[t[e+7]]+"-"+n[t[e+8]]+n[t[e+9]]+"-"+n[t[e+10]]+n[t[e+11]]+n[t[e+12]]+n[t[e+13]]+n[t[e+14]]+n[t[e+15]]}function k(t){if(!U(t))throw TypeError("Invalid UUID");let e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}var M=k;function V(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var G="6ba7b810-9dad-11d1-80b4-00c04fd430c8",B="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function x(t,e,r){function i(o,s,u,S){var A;if(typeof o=="string"&&(o=V(o)),typeof s=="string"&&(s=M(s)),((A=s)===null||A===void 0?void 0:A.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let g=new Uint8Array(16+o.length);if(g.set(s),g.set(o,s.length),g=r(g),g[6]=g[6]&15|e,g[8]=g[8]&63|128,u){S=S||0;for(let m=0;m<16;++m)u[S+m]=g[m];return u}return b(g)}try{i.name=t;}catch{}return i.DNS=G,i.URL=B,i}var L={randomUUID:K.randomUUID};function j(t,e,r){if(L.randomUUID&&!e&&!t)return L.randomUUID();t=t||{};let i=t.random||(t.rng||I)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){r=r||0;for(let o=0;o<16;++o)e[r+o]=i[o];return e}return b(i)}var D=j;function Z(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),K.createHash("sha1").update(t).digest()}var R=Z;var q=x("v5",80,R),P=q;var O={isUUID:t=>/^[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(t),isEmail:t=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t),isURL:t=>/^(http|https):\/\/[^ "]+$/.test(t),generateUUID:(t,e)=>e&&t?P(t,e):D(),generateSearchId:(t,e)=>`${t}#${f.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:t=>{let[e,r]=t.split("#");return {key:e,selectionAttributes:f.parseSelectionAttributesKey(r)}},deepClone(t){return structuredClone(t)}},a=O;var f=class t extends b$1{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 h$1("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 r={},i=e.split("|");for(let o of i){let[s,u]=o.split(":");u.startsWith("c+")?r[s]={name:u.slice(2)}:r[s]=u;}return r}catch(r){throw new h$1(r?.message)}}constructor(e$1,r=new Date){super(e$1,r),this.id=e$1.id,this.key=e$1.key,this.name={...e$1.name},this.description={...e$1.description},this.slug={...e$1.slug},this.brand=e$1.brand,this.pricing=Object.keys(e$1.pricing).reduce((o,s)=>(e$1.pricing[s]&&(o[s]=new a$1(e$1.pricing[s])),o),{}),this.targetGender=e$1.targetGender,this.attributes=a.deepClone(e$1.attributes),this.specifications=a.deepClone(e$1.specifications),this.categories=a.deepClone(e$1.categories);let i=new Set;this.variants=(e$1.variants||[]).map(o=>{if(!o.selectionAttributes||typeof o.selectionAttributes!="object")throw new h$1("Selection attributes are required");this.checkSelectionAttributes(o.selectionAttributes);let s=t.generateSelectionAttributesKey(o.selectionAttributes);if(i.has(s))throw new e(s);return i.add(s),{sku:o.sku,selectionAttributes:o.selectionAttributes,images:{primary:new b$2(o.images.primary),gallery:(o.images.gallery||[]).map(u=>new b$2(u))}}}),this.isActive=e$1.isActive,this.searchTags=e$1.searchTags?a.deepClone(e$1.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[e$1[e]]??this.name.en:a.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[e$1[e]]??this.description.en:a.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[e$1[e]]??this.slug.en:a.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return a.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:a.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let r=t.generateSelectionAttributesKey(e),i=this.variants.find(o=>t.generateSelectionAttributesKey(o.selectionAttributes)===r);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,r){switch(r){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 a.deepClone(this.categories)}getSpecifications(e){return e?a.deepClone(this.specifications[e]??this.specifications[e$1[e]]??this.specifications.en):a.deepClone(this.specifications)}getSearchTags(e){return e?a.deepClone(this.searchTags[e]??this.searchTags[e$1[e]]??this.searchTags.en):a.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((r,i)=>(this.pricing[i]&&(r[i]=this.pricing[i]?.getDetails()),r),{}),attributes:this.getAttributes(),variants:this.variants.map(r=>({sku:r.sku,selectionAttributes:a.deepClone(r.selectionAttributes),images:{primary:r.images.primary.getDetails(),gallery:r.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 h$1("Selection attributes are required");Object.keys(this.attributes).forEach(r=>{if(r.toLowerCase()==="size")return;let i=this.attributes[r],o=e[r];if(o===void 0)throw new h$1(`Selection attribute '${r}' is missing`);if(typeof i=="string"){if(typeof o!="string"||i!==o)throw new h$1(`Selection attribute '${r}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof o!="string"||!i.includes(o))throw new h$1(`Selection attribute '${r}' is invalid`)}else if(typeof o!="object"||!("name"in o)||i.findIndex(s=>s.name===o.name)<0)throw new h$1(`Selection attribute '${r}' is invalid`)}});}validateSelectionAttribute(e){let r=t.generateSelectionAttributesKey(e);return this.variants.some(i=>t.generateSelectionAttributesKey(i.selectionAttributes)===r)}validateSize(e){return this.attributes.size.includes(e)}};export{a,f as b};//# sourceMappingURL=chunk-4G7JC2EH.mjs.map
2
+ //# sourceMappingURL=chunk-4G7JC2EH.mjs.map