b23-lib 3.4.2 → 3.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) 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/Address.d.mts +1 -1
  5. package/dist/Classes/Address.d.ts +1 -1
  6. package/dist/Classes/Base.d.mts +1 -1
  7. package/dist/Classes/Base.d.ts +1 -1
  8. package/dist/Classes/Cart.d.mts +1 -1
  9. package/dist/Classes/Cart.d.ts +1 -1
  10. package/dist/Classes/Cart.js +1 -1
  11. package/dist/Classes/Cart.js.map +1 -1
  12. package/dist/Classes/Cart.mjs +1 -1
  13. package/dist/Classes/Charge.d.mts +1 -1
  14. package/dist/Classes/Charge.d.ts +1 -1
  15. package/dist/Classes/Charge.js +1 -1
  16. package/dist/Classes/Charge.js.map +1 -1
  17. package/dist/Classes/Charge.mjs +1 -1
  18. package/dist/Classes/Common.d.mts +1 -1
  19. package/dist/Classes/Common.d.ts +1 -1
  20. package/dist/Classes/Coupon.d.mts +1 -1
  21. package/dist/Classes/Coupon.d.ts +1 -1
  22. package/dist/Classes/Coupon.js +1 -1
  23. package/dist/Classes/Coupon.js.map +1 -1
  24. package/dist/Classes/Coupon.mjs +1 -1
  25. package/dist/Classes/Customer.d.mts +4 -4
  26. package/dist/Classes/Customer.d.ts +4 -4
  27. package/dist/Classes/Customer.js +1 -1
  28. package/dist/Classes/Customer.js.map +1 -1
  29. package/dist/Classes/Customer.mjs.map +1 -1
  30. package/dist/Classes/CustomerAddress.d.mts +1 -1
  31. package/dist/Classes/CustomerAddress.d.ts +1 -1
  32. package/dist/Classes/Enum.d.mts +23 -1
  33. package/dist/Classes/Enum.d.ts +23 -1
  34. package/dist/Classes/Enum.js +1 -1
  35. package/dist/Classes/Enum.js.map +1 -1
  36. package/dist/Classes/Enum.mjs +1 -1
  37. package/dist/Classes/Inventory.d.mts +1 -1
  38. package/dist/Classes/Inventory.d.ts +1 -1
  39. package/dist/Classes/Inventory.js +1 -1
  40. package/dist/Classes/Inventory.js.map +1 -1
  41. package/dist/Classes/Inventory.mjs +1 -1
  42. package/dist/Classes/Invoice.d.mts +5 -2
  43. package/dist/Classes/Invoice.d.ts +5 -2
  44. package/dist/Classes/Invoice.js +1 -1
  45. package/dist/Classes/Invoice.js.map +1 -1
  46. package/dist/Classes/Invoice.mjs +1 -1
  47. package/dist/Classes/Invoice.mjs.map +1 -1
  48. package/dist/Classes/LineItem.d.mts +1 -1
  49. package/dist/Classes/LineItem.d.ts +1 -1
  50. package/dist/Classes/LineItem.js +1 -1
  51. package/dist/Classes/LineItem.js.map +1 -1
  52. package/dist/Classes/LineItem.mjs +1 -1
  53. package/dist/Classes/Order.d.mts +1 -1
  54. package/dist/Classes/Order.d.ts +1 -1
  55. package/dist/Classes/Order.js +1 -1
  56. package/dist/Classes/Order.js.map +1 -1
  57. package/dist/Classes/Order.mjs +1 -1
  58. package/dist/Classes/Payment.d.mts +1 -1
  59. package/dist/Classes/Payment.d.ts +1 -1
  60. package/dist/Classes/Price.d.mts +1 -1
  61. package/dist/Classes/Price.d.ts +1 -1
  62. package/dist/Classes/Price.js +1 -1
  63. package/dist/Classes/Price.js.map +1 -1
  64. package/dist/Classes/Price.mjs +1 -1
  65. package/dist/Classes/Product.d.mts +1 -1
  66. package/dist/Classes/Product.d.ts +1 -1
  67. package/dist/Classes/Product.js +1 -1
  68. package/dist/Classes/Product.js.map +1 -1
  69. package/dist/Classes/Product.mjs +1 -1
  70. package/dist/Classes/ShoppingContainer.d.mts +1 -1
  71. package/dist/Classes/ShoppingContainer.d.ts +1 -1
  72. package/dist/Classes/ShoppingContainer.js +1 -1
  73. package/dist/Classes/ShoppingContainer.js.map +1 -1
  74. package/dist/Classes/ShoppingContainer.mjs +1 -1
  75. package/dist/Classes/TaxRule.d.mts +1 -1
  76. package/dist/Classes/TaxRule.d.ts +1 -1
  77. package/dist/Classes/TaxRule.js +1 -1
  78. package/dist/Classes/TaxRule.js.map +1 -1
  79. package/dist/Classes/TaxRule.mjs +1 -1
  80. package/dist/Classes/TieredPrice.d.mts +1 -1
  81. package/dist/Classes/TieredPrice.d.ts +1 -1
  82. package/dist/Classes/TieredPrice.js +1 -1
  83. package/dist/Classes/TieredPrice.js.map +1 -1
  84. package/dist/Classes/TieredPrice.mjs +1 -1
  85. package/dist/{Common-Du2s_43h.d.mts → Common-CJ_dZU3n.d.mts} +6 -1
  86. package/dist/{Common-BsfeCt6G.d.ts → Common-D01ijYt3.d.ts} +6 -1
  87. package/dist/{chunk-MHLRJ4IJ.mjs → chunk-4G7JC2EH.mjs} +2 -2
  88. package/dist/{chunk-MHLRJ4IJ.mjs.map → chunk-4G7JC2EH.mjs.map} +1 -1
  89. package/dist/{chunk-LI5JQ6UC.mjs → chunk-6ZKMKSAG.mjs} +2 -2
  90. package/dist/{chunk-LI5JQ6UC.mjs.map → chunk-6ZKMKSAG.mjs.map} +1 -1
  91. package/dist/{chunk-RQ2FFWUW.mjs → chunk-G4AM63RT.mjs} +2 -2
  92. package/dist/{chunk-RQ2FFWUW.mjs.map → chunk-G4AM63RT.mjs.map} +1 -1
  93. package/dist/{chunk-2POPOJGE.mjs → chunk-O6EVIZAP.mjs} +2 -2
  94. package/dist/{chunk-2POPOJGE.mjs.map → chunk-O6EVIZAP.mjs.map} +1 -1
  95. package/dist/{chunk-FCRJAAPY.mjs → chunk-S6LR7AUZ.mjs} +2 -2
  96. package/dist/{chunk-FCRJAAPY.mjs.map → chunk-S6LR7AUZ.mjs.map} +1 -1
  97. package/dist/chunk-TPIIACE7.mjs +2 -0
  98. package/dist/chunk-TPIIACE7.mjs.map +1 -0
  99. package/dist/{chunk-B2VFJRLS.mjs → chunk-VEOX3TRL.mjs} +2 -2
  100. package/dist/{chunk-B2VFJRLS.mjs.map → chunk-VEOX3TRL.mjs.map} +1 -1
  101. package/dist/{chunk-G6LH7V5B.mjs → chunk-XTF6ND33.mjs} +2 -2
  102. package/dist/{chunk-G6LH7V5B.mjs.map → chunk-XTF6ND33.mjs.map} +1 -1
  103. package/dist/{chunk-SOZHGHMY.mjs → chunk-ZODPRQKQ.mjs} +2 -2
  104. package/dist/{chunk-SOZHGHMY.mjs.map → chunk-ZODPRQKQ.mjs.map} +1 -1
  105. package/dist/index.d.mts +5 -1
  106. package/dist/index.d.ts +5 -1
  107. package/dist/index.js +2 -2
  108. package/dist/index.js.map +1 -1
  109. package/dist/index.mjs +1 -1
  110. package/dist/index.mjs.map +1 -1
  111. package/package.json +1 -1
  112. package/dist/chunk-QK4XJ3GB.mjs +0 -2
  113. package/dist/chunk-QK4XJ3GB.mjs.map +0 -1
@@ -1,2 +1,2 @@
1
- import {a as a$2}from'./chunk-SOZHGHMY.mjs';import {a as a$3}from'./chunk-MHLRJ4IJ.mjs';import {a as a$1}from'./chunk-LI5JQ6UC.mjs';import {e}from'./chunk-QK4XJ3GB.mjs';import {w,k,x}from'./chunk-R5DM7WCD.mjs';import {a}from'./chunk-UXZBULDS.mjs';var I=class extends a{id;name;type;category;impact;pricing;lineItemId;total;constructor(t){if(super(t),this.id=t.id,this.name=t.name,this.type=t.type,this.category=t.category,this.impact=t.impact,this.lineItemId=t.lineItemId,this.pricing={baseChargeAmount:new a$1(t.pricing.baseChargeAmount),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(e=>new a$2(e))},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new w("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={chargeAmount:new a$1(t.total.chargeAmount),discountTotal:new a$1(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([e,a])=>[e,new a$1(a)])),netChargeAmount:new a$1(t.total.netChargeAmount),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([e,a])=>[e,{rate:a.rate,taxableAmount:new a$1(a.taxableAmount),taxAmount:new a$1(a.taxAmount),system:a.system,subSystem:a.subSystem}])),taxTotal:new a$1(t.total.taxTotal),grandTotal:new a$1(t.total.grandTotal)};}getId(){return this.id}getName(t){return t?a$3.deepClone(this.name[t]??this.name[e[t]]??this.name.en):a$3.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getPricing(){return {baseChargeAmount:this.pricing.baseChargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {chargeAmount:this.total.chargeAmount,discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},netChargeAmount:this.total.netChargeAmount,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableAmount:e.taxableAmount,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(t){if(this.type==="ADJUSTMENT"&&t.length>0)throw new w("Adjustment charges cannot apply tax rules.");t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new k}),this.validateTaxRules(t),this.pricing.applicableTaxRule=t,this.calculateTotals();}validateTaxRules(t){if(this.impact==="SUBTRACT"&&t.some(a=>a.getRate()>0))throw new x("Subtractive charges cannot have positive tax rates.");let e=new Set;for(let a=0;a<t.length;a++){let l=t[a].getTaxRuleId();if(e.has(l))throw new x("Duplicate tax rule ID found: "+l);e.add(l);for(let T=a+1;T<t.length;T++){let u=t[a],s=t[T],d=u.getMinPrice(),p=u.getMaxPrice(),n=u.getExcludeMin(),m=u.getExcludeMax(),b=s.getMinPrice(),c=s.getMaxPrice(),h=s.getExcludeMin(),A=s.getExcludeMax(),r=(()=>{if(!p)return !1;let g=p.compareTo(b);return g<0||g===0&&(m||h)})(),i=(()=>{if(!c)return !1;let g=c.compareTo(d);return g<0||g===0&&(A||n)})();if(!(r||i)&&!(d.compareTo(b)===0&&n===h&&m===A&&(!p&&!c||p&&c&&p.compareTo(c)===0)))throw new x(`Overlapping rules found: [${u.getTaxRuleId()}: ${n?"(":"["}${d.getAmount()}-${p?.getAmount()??"Infinity"}${m?")":"]"}] and [${s.getTaxRuleId()}: ${h?"(":"["}${b.getAmount()}-${c?.getAmount()??"Infinity"}${A?")":"]"}]`)}}}updateDiscounts(t){let e={};t.forEach(a=>{e[a.coupon.getCode()]=a.amount;}),this.total.discountBreakdown=e,this.calculateTotals();}calculateTotals(){let t=this.pricing.baseChargeAmount.zero(),e=this.pricing.baseChargeAmount,a=Object.values(this.total.discountBreakdown).reduce((r,i)=>r.add(i),t),l=e.subtract(a),T={},u=this.pricing.applicableTaxRule.reduce((r,i)=>r+i.getApplicableTaxRate(l),0);if(u<=0){this.total={chargeAmount:e,discountTotal:a,discountBreakdown:this.total.discountBreakdown,netChargeAmount:l,taxTotal:t,taxBreakdown:{},grandTotal:l};return}let s=l.getCurrency(),d=l.getAmount(),p=1e3,n=a$1.getRoundedAmount(d/(1+u),s),m=n,b=Number.POSITIVE_INFINITY;for(let r=0;r<p;r++){let i=new a$1({amount:n,currency:s}),g=this.pricing.applicableTaxRule.sort((x,C)=>C.getApplicableTaxRate(i)-x.getApplicableTaxRate(i)).map(x=>a$1.getRoundedAmount(n*x.getApplicableTaxRate(i),s)).reduce((x,C)=>x+C,0),y=n+g-d,k=this.pricing.applicableTaxRule.reduce((x,C)=>x+C.getApplicableTaxRate(i),0);if(Math.abs(y)<Math.abs(b)&&(b=y,m=n),y===0||(n=n-y/(1+k),n<0||n>d))break}let c=new a$1({amount:m,currency:s}),h=t;this.pricing.applicableTaxRule.sort((r,i)=>i.getApplicableTaxRate(c)-r.getApplicableTaxRate(c)).forEach(r=>{let i=r.getApplicableTaxRate(c),f=a$1.getRoundedAmount(m*i,s),g=new a$1({amount:f,currency:s});T[r.getTaxRuleId()]={rate:i,taxableAmount:c,taxAmount:g,system:r.getTaxSystem(),subSystem:r.getTaxSubSystem()},h=h.add(g);});let A=l;this.total={chargeAmount:e,discountTotal:a,discountBreakdown:this.total.discountBreakdown,netChargeAmount:l,taxBreakdown:T,taxTotal:h,grandTotal:A};}getDetails(){return {id:this.id,name:a$3.deepClone(this.name),type:this.type,category:this.category,pricing:{baseChargeAmount:this.pricing.baseChargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(e=>e.getDetails())},impact:this.impact,lineItemId:this.lineItemId,total:{chargeAmount:this.total.chargeAmount.getDetails(),discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([e,a])=>[e,a.getDetails()])),netChargeAmount:this.total.netChargeAmount.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,a])=>[e,{rate:a.rate,taxableAmount:a.taxableAmount.getDetails(),taxAmount:a.taxAmount.getDetails(),system:a.system,subSystem:a.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};export{I as a};//# sourceMappingURL=chunk-G6LH7V5B.mjs.map
2
- //# sourceMappingURL=chunk-G6LH7V5B.mjs.map
1
+ import {a as a$2}from'./chunk-ZODPRQKQ.mjs';import {a as a$3}from'./chunk-4G7JC2EH.mjs';import {a as a$1}from'./chunk-6ZKMKSAG.mjs';import {e}from'./chunk-TPIIACE7.mjs';import {w,k,x}from'./chunk-R5DM7WCD.mjs';import {a}from'./chunk-UXZBULDS.mjs';var I=class extends a{id;name;type;category;impact;pricing;lineItemId;total;constructor(t){if(super(t),this.id=t.id,this.name=t.name,this.type=t.type,this.category=t.category,this.impact=t.impact,this.lineItemId=t.lineItemId,this.pricing={baseChargeAmount:new a$1(t.pricing.baseChargeAmount),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(e=>new a$2(e))},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new w("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={chargeAmount:new a$1(t.total.chargeAmount),discountTotal:new a$1(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([e,a])=>[e,new a$1(a)])),netChargeAmount:new a$1(t.total.netChargeAmount),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([e,a])=>[e,{rate:a.rate,taxableAmount:new a$1(a.taxableAmount),taxAmount:new a$1(a.taxAmount),system:a.system,subSystem:a.subSystem}])),taxTotal:new a$1(t.total.taxTotal),grandTotal:new a$1(t.total.grandTotal)};}getId(){return this.id}getName(t){return t?a$3.deepClone(this.name[t]??this.name[e[t]]??this.name.en):a$3.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getPricing(){return {baseChargeAmount:this.pricing.baseChargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {chargeAmount:this.total.chargeAmount,discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},netChargeAmount:this.total.netChargeAmount,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{rate:e.rate,taxableAmount:e.taxableAmount,taxAmount:e.taxAmount,system:e.system,subSystem:e.subSystem}])),grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(t){if(this.type==="ADJUSTMENT"&&t.length>0)throw new w("Adjustment charges cannot apply tax rules.");t.forEach(e=>{if(!e.appliesTo(this.pricing.taxCategory,e.getCountry()))throw new k}),this.validateTaxRules(t),this.pricing.applicableTaxRule=t,this.calculateTotals();}validateTaxRules(t){if(this.impact==="SUBTRACT"&&t.some(a=>a.getRate()>0))throw new x("Subtractive charges cannot have positive tax rates.");let e=new Set;for(let a=0;a<t.length;a++){let l=t[a].getTaxRuleId();if(e.has(l))throw new x("Duplicate tax rule ID found: "+l);e.add(l);for(let T=a+1;T<t.length;T++){let u=t[a],s=t[T],d=u.getMinPrice(),p=u.getMaxPrice(),n=u.getExcludeMin(),m=u.getExcludeMax(),b=s.getMinPrice(),c=s.getMaxPrice(),h=s.getExcludeMin(),A=s.getExcludeMax(),r=(()=>{if(!p)return !1;let g=p.compareTo(b);return g<0||g===0&&(m||h)})(),i=(()=>{if(!c)return !1;let g=c.compareTo(d);return g<0||g===0&&(A||n)})();if(!(r||i)&&!(d.compareTo(b)===0&&n===h&&m===A&&(!p&&!c||p&&c&&p.compareTo(c)===0)))throw new x(`Overlapping rules found: [${u.getTaxRuleId()}: ${n?"(":"["}${d.getAmount()}-${p?.getAmount()??"Infinity"}${m?")":"]"}] and [${s.getTaxRuleId()}: ${h?"(":"["}${b.getAmount()}-${c?.getAmount()??"Infinity"}${A?")":"]"}]`)}}}updateDiscounts(t){let e={};t.forEach(a=>{e[a.coupon.getCode()]=a.amount;}),this.total.discountBreakdown=e,this.calculateTotals();}calculateTotals(){let t=this.pricing.baseChargeAmount.zero(),e=this.pricing.baseChargeAmount,a=Object.values(this.total.discountBreakdown).reduce((r,i)=>r.add(i),t),l=e.subtract(a),T={},u=this.pricing.applicableTaxRule.reduce((r,i)=>r+i.getApplicableTaxRate(l),0);if(u<=0){this.total={chargeAmount:e,discountTotal:a,discountBreakdown:this.total.discountBreakdown,netChargeAmount:l,taxTotal:t,taxBreakdown:{},grandTotal:l};return}let s=l.getCurrency(),d=l.getAmount(),p=1e3,n=a$1.getRoundedAmount(d/(1+u),s),m=n,b=Number.POSITIVE_INFINITY;for(let r=0;r<p;r++){let i=new a$1({amount:n,currency:s}),g=this.pricing.applicableTaxRule.sort((x,C)=>C.getApplicableTaxRate(i)-x.getApplicableTaxRate(i)).map(x=>a$1.getRoundedAmount(n*x.getApplicableTaxRate(i),s)).reduce((x,C)=>x+C,0),y=n+g-d,k=this.pricing.applicableTaxRule.reduce((x,C)=>x+C.getApplicableTaxRate(i),0);if(Math.abs(y)<Math.abs(b)&&(b=y,m=n),y===0||(n=n-y/(1+k),n<0||n>d))break}let c=new a$1({amount:m,currency:s}),h=t;this.pricing.applicableTaxRule.sort((r,i)=>i.getApplicableTaxRate(c)-r.getApplicableTaxRate(c)).forEach(r=>{let i=r.getApplicableTaxRate(c),f=a$1.getRoundedAmount(m*i,s),g=new a$1({amount:f,currency:s});T[r.getTaxRuleId()]={rate:i,taxableAmount:c,taxAmount:g,system:r.getTaxSystem(),subSystem:r.getTaxSubSystem()},h=h.add(g);});let A=l;this.total={chargeAmount:e,discountTotal:a,discountBreakdown:this.total.discountBreakdown,netChargeAmount:l,taxBreakdown:T,taxTotal:h,grandTotal:A};}getDetails(){return {id:this.id,name:a$3.deepClone(this.name),type:this.type,category:this.category,pricing:{baseChargeAmount:this.pricing.baseChargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(e=>e.getDetails())},impact:this.impact,lineItemId:this.lineItemId,total:{chargeAmount:this.total.chargeAmount.getDetails(),discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([e,a])=>[e,a.getDetails()])),netChargeAmount:this.total.netChargeAmount.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,a])=>[e,{rate:a.rate,taxableAmount:a.taxableAmount.getDetails(),taxAmount:a.taxAmount.getDetails(),system:a.system,subSystem:a.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};export{I as a};//# sourceMappingURL=chunk-XTF6ND33.mjs.map
2
+ //# sourceMappingURL=chunk-XTF6ND33.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Classes/Charge.ts"],"names":["ChargeModel","CustomFieldModel","data","PriceModel","r","TaxRuleModel","InvalidChargeError","discountId","discount","taxRuleId","taxBreakdown","locale","Utils_default","LocaleLanguageMap","key","value","taxRules","taxRule","InvalidTaxRuleError","InvalidChargeTaxRuleError","uniqueTaxRule","i","currentTaxRuleId","j","r1","r2","r1Min","r1Max","r1ExcludeMin","r1ExcludeMax","r2Min","r2Max","r2ExcludeMin","r2ExcludeMax","r1EndsBeforeR2Starts","compare","r2EndsBeforeR1Starts","appliedDiscounts","chargeDiscounts","zero","baseChargeAmount","totalDiscount","sum","s","netChargeAmount","totalRate","currency","grossValue","maxIterations","baseValue","bestBaseValue","bestDiff","currentTaxableBase","taxSum","a","b","rule","v","diff","currentTotalRate","taxableBase","distributedTax","rate","taxAmountValue","taxAmount","grandTotal","k"],"mappings":"uPA4FA,IAAqBA,CAArB,CAAA,cAAyCC,CAAiB,CAC/C,EACA,CAAA,IAAA,CACA,IACA,CAAA,QAAA,CACA,MACA,CAAA,OAAA,CACA,UACA,CAAA,KAAA,CAEV,YAAYC,CAAwB,CAAA,CAenC,GAdA,KAAA,CAAMA,CAAI,CAAA,CACV,IAAK,CAAA,EAAA,CAAKA,CAAK,CAAA,EAAA,CACf,IAAK,CAAA,IAAA,CAAOA,CAAK,CAAA,IAAA,CACjB,IAAK,CAAA,IAAA,CAAOA,EAAK,IACjB,CAAA,IAAA,CAAK,QAAWA,CAAAA,CAAAA,CAAK,QACrB,CAAA,IAAA,CAAK,MAASA,CAAAA,CAAAA,CAAK,MACnB,CAAA,IAAA,CAAK,UAAaA,CAAAA,CAAAA,CAAK,UACvB,CAAA,IAAA,CAAK,OAAU,CAAA,CACd,iBAAkB,IAAIC,GAAAA,CAAWD,CAAK,CAAA,OAAA,CAAQ,gBAAgB,CAAA,CAC9D,WAAaA,CAAAA,CAAAA,CAAK,QAAQ,WAC1B,CAAA,iBAAA,CAAmBA,CAAK,CAAA,OAAA,CAAQ,iBAAkB,CAAA,GAAA,CAAIE,CAAK,EAAA,IAAIC,IAAaD,CAAC,CAAC,CAC/E,C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KAAM,CAAA,QAAA,CAAS,UAAW,EAAA,CACzC,UAAY,CAAA,IAAA,CAAK,MAAM,UAAW,CAAA,UAAA,EACnC,CAAA,CACA,YAAc,CAAA,IAAA,CAAK,kBAAmB,EACvC,CAED,CACD","file":"chunk-G6LH7V5B.mjs","sourcesContent":["import { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\nimport Utils from \"../Utils\";\r\nimport { LocaleCode, LocalizedString } from \"./Common\";\r\nimport { ChargeImpact, ChargeType, LocaleLanguageMap, TaxSystem } from \"./Enum\";\r\nimport { InvalidChargeTaxRuleError, InvalidChargeError, InvalidTaxRuleError } from \"./Error\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport { TaxRuleData, TaxRuleModel } from \"./TaxRule\";\r\nimport CouponModel from \"./Coupon\";\r\n\r\nexport type ChargePricing = {\r\n /** Tax-inclusive original charge amount before any discounts. Always non-negative. */\r\n baseChargeAmount: PriceData;\r\n /** Tax category of the charge. */\r\n taxCategory: string;\r\n /** Tax rules applicable to the charge. */\r\n applicableTaxRule: TaxRuleData[];\r\n};\r\n\r\nexport type ChargePricingModel = {\r\n /** Tax-inclusive original charge amount before any discounts. Always non-negative. */\r\n baseChargeAmount: PriceModel;\r\n /** Tax category of the charge. */\r\n taxCategory: string;\r\n /** Tax rules applicable to the charge. */\r\n applicableTaxRule: TaxRuleModel[];\r\n};\r\n\r\nexport type ChargeTaxBreakdown = {\r\n /** Tax rate: e.g., 0.09 for 9% */\r\n rate: number;\r\n /** Reverse-calculated pre-tax base from the netChargeAmount (post-discount) */\r\n taxableAmount: PriceData;\r\n /** Tax portion for this rule (netChargeAmount - taxableAmount) */\r\n taxAmount: PriceData;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type ChargeTaxBreakdownModel = {\r\n rate: number;\r\n taxableAmount: PriceModel;\r\n taxAmount: PriceModel;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type ChargeTotals = {\r\n /** Tax-inclusive original charge amount before discounts (copied from pricing) */\r\n chargeAmount: PriceData;\r\n /** Coupon code -> discount amount mapping */\r\n discountBreakdown: Record<string, PriceData>;\r\n /** Sum of all discounts */\r\n discountTotal: PriceData;\r\n /** chargeAmount - totalDiscount → final tax-inclusive payable amount after discounts */\r\n netChargeAmount: PriceData;\r\n /** Sum of all taxAmount values */\r\n taxTotal: PriceData;\r\n /** Tax breakdown per rule/category (reverse-calculated from netChargeAmount) */\r\n taxBreakdown: Record<string, ChargeTaxBreakdown>;\r\n /** Final payable/contribution amount. Equals netChargeAmount (tax-inclusive after discounts). */\r\n grandTotal: PriceData;\r\n};\r\n\r\nexport type ChargeTotalsModel = {\r\n chargeAmount: PriceModel;\r\n discountTotal: PriceModel;\r\n discountBreakdown: Record<string, PriceModel>;\r\n netChargeAmount: PriceModel;\r\n taxTotal: PriceModel;\r\n taxBreakdown: Record<string, ChargeTaxBreakdownModel>;\r\n grandTotal: PriceModel; // Equals netChargeAmount\r\n};\r\n\r\nexport type ChargeAttributes = CustomFieldAttributes & {\r\n id: string;\r\n name: LocalizedString;\r\n type: ChargeType;\r\n category: string;\r\n impact: ChargeImpact; // ADD or SUBTRACT\r\n pricing: ChargePricing;\r\n lineItemId?: string;\r\n total: ChargeTotals;\r\n};\r\n\r\nexport type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId'> & {\r\n\tlineItemId?: string;\r\n};\r\n\r\n/**\r\n * Represents an additional charge (or discount if amount is negative) in a shopping container.\r\n * Supports its own tax rules.\r\n */\r\nexport default class ChargeModel extends CustomFieldModel {\r\n\tprotected id: string;\r\n\tprotected name: LocalizedString;\r\n\tprotected type: ChargeType;\r\n\tprotected category: string;\r\n\tprotected impact: ChargeImpact;\r\n\tprotected pricing: ChargePricingModel;\r\n\tprotected lineItemId?: string;\r\n\tprotected total: ChargeTotalsModel;\r\n\r\n\tconstructor(data: ChargeAttributes) {\r\n\t\tsuper(data);\r\n\t\tthis.id = data.id;\r\n\t\tthis.name = data.name;\r\n\t\tthis.type = data.type;\r\n\t\tthis.category = data.category;\r\n\t\tthis.impact = data.impact;\r\n\t\tthis.lineItemId = data.lineItemId;\r\n\t\tthis.pricing = {\r\n\t\t\tbaseChargeAmount: new PriceModel(data.pricing.baseChargeAmount),\r\n\t\t\ttaxCategory: data.pricing.taxCategory,\r\n\t\t\tapplicableTaxRule: data.pricing.applicableTaxRule.map(r => new TaxRuleModel(r))\r\n\t\t};\r\n\r\n\t\tthis.validateTaxRules(this.pricing.applicableTaxRule);\r\n\t\tif(this.impact === ChargeImpact.SUBTRACT && this.type !== ChargeType.ADJUSTMENT) {\r\n\t\t\tthrow new InvalidChargeError('SUBTRACT impact is only allowed for ADJUSTMENT charge');\r\n\t\t}\r\n\r\n\t\tthis.total = {\r\n\t\t\tchargeAmount: new PriceModel(data.total.chargeAmount),\r\n\t\t\tdiscountTotal: new PriceModel(data.total.discountTotal),\r\n\t\t\tdiscountBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(data.total.discountBreakdown).map(([discountId, discount]) => [\r\n\t\t\t\t\tdiscountId,\r\n\t\t\t\t\tnew PriceModel(discount)\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\tnetChargeAmount: new PriceModel(data.total.netChargeAmount),\r\n\t\t\ttaxBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(data.total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n\t\t\t\t\ttaxRuleId,\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\trate: taxBreakdown.rate,\r\n\t\t\t\t\t\ttaxableAmount: new PriceModel(taxBreakdown.taxableAmount),\r\n\t\t\t\t\t\ttaxAmount: new PriceModel(taxBreakdown.taxAmount),\r\n\t\t\t\t\t\tsystem: taxBreakdown.system,\r\n\t\t\t\t\t\tsubSystem: taxBreakdown.subSystem\r\n\t\t\t\t\t}\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\ttaxTotal: new PriceModel(data.total.taxTotal),\r\n\t\t\tgrandTotal: new PriceModel(data.total.grandTotal),\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the unique identifier of the charge.\r\n\t * @returns \r\n\t */\r\n\tpublic getId(): string { return this.id; }\r\n\r\n\r\n\t/**\r\n\t * Gets the full localized product name object.\r\n\t * @returns A copy of the LocalizedString object for the name.\r\n\t */\r\n\tgetName(): LocalizedString\r\n\t/**\r\n\t * Gets the product name for a specific locale, falling back to English ('en').\r\n\t * @param locale - The desired locale code.\r\n\t * @returns The name string for the specified locale.\r\n\t */\r\n\tgetName(locale: LocaleCode): string\r\n\tgetName(locale?: LocaleCode): LocalizedString | string {\r\n\t\tif (locale) {\r\n\t\t\treturn Utils.deepClone(this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en);\r\n\t\t} else {\r\n\t\t\treturn Utils.deepClone(this.name);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the charge category.\r\n\t * @returns The category string.\r\n\t */\r\n\tpublic getCategory(): string { return this.category; }\r\n\r\n\t/**\r\n\t * Gets the charge type.\r\n\t * @returns The charge type enum value.\r\n\t */\r\n\tpublic getType(): ChargeType { return this.type; }\r\n\t/**\r\n\t * Gets the charge impact (add or subtract).\r\n\t * @returns The charge impact.\r\n\t */\r\n\tpublic getImpact(): ChargeImpact { return this.impact; }\r\n\r\n\t/**\r\n\t * Gets the related line item id, if any.\r\n\t * @returns The line item id or undefined.\r\n\t */\r\n\tpublic getLineItemId(): string | undefined { return this.lineItemId; }\r\n\r\n\t/**\r\n\t * Gets the pricing details (models) for this charge.\r\n\t * @returns Pricing details including price, tax category, and tax rules.\r\n\t */\r\n\tpublic getPricing(): ChargePricingModel {\r\n\t\treturn {\r\n\t\t\tbaseChargeAmount: this.pricing.baseChargeAmount,\r\n\t\t\ttaxCategory: this.pricing.taxCategory,\r\n\t\t\tapplicableTaxRule: [...this.pricing.applicableTaxRule]\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the computed totals for this charge.\r\n\t * @returns Totals including discounts, taxes, and grand total.\r\n\t */\r\n\tpublic getTotal(): ChargeTotalsModel {\r\n\t\treturn {\r\n\t\t\tchargeAmount: this.total.chargeAmount,\r\n\t\t\tdiscountTotal: this.total.discountTotal,\r\n\t\t\tdiscountBreakdown: { ...this.total.discountBreakdown },\r\n\t\t\tnetChargeAmount: this.total.netChargeAmount,\r\n\t\t\ttaxTotal: this.total.taxTotal,\r\n\t\t\ttaxBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(this.total.taxBreakdown).map(([key, value]) => [\r\n\t\t\t\t\tkey,\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\trate: value.rate,\r\n\t\t\t\t\t\ttaxableAmount: value.taxableAmount,\r\n\t\t\t\t\t\ttaxAmount: value.taxAmount,\r\n\t\t\t\t\t\tsystem: value.system,\r\n\t\t\t\t\t\tsubSystem: value.subSystem\r\n\t\t\t\t\t}\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\tgrandTotal: this.total.grandTotal,\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the applicable tax rules for this charge.\r\n\t * @returns A list of tax rules.\r\n\t */\r\n\tpublic getApplicableTaxRules(): TaxRuleModel[] {\r\n\t\treturn [...this.pricing.applicableTaxRule];\r\n\t}\r\n\r\n\t/**\r\n\t * Updates the tax rule for this line item and recalculates totals.\r\n\t * @param taxRule - The new tax rule to apply.\r\n\t * @throws {Error} If the tax rule category does not match the item's tax category.\r\n\t */\r\n\tpublic updateTax(taxRules: TaxRuleModel[]): void {\r\n\t\tif (this.type === ChargeType.ADJUSTMENT && taxRules.length > 0) {\r\n\t\t\tthrow new InvalidChargeError(\"Adjustment charges cannot apply tax rules.\");\r\n\t\t}\r\n\t\ttaxRules.forEach(taxRule => {\r\n\t\t\tif (!taxRule.appliesTo(this.pricing.taxCategory, taxRule.getCountry())) {\r\n\t\t\t\tthrow new InvalidTaxRuleError();\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\t// Remove the old taxableUnitPrice calculation - no longer needed\r\n\t\tthis.validateTaxRules(taxRules);\r\n\t\tthis.pricing.applicableTaxRule = taxRules;\r\n\t\tthis.calculateTotals();\r\n\t}\r\n\r\n\t/**\r\n\t * Validates that there are no overlapping price brackets for any tax rules within the charge.\r\n\t * @param taxRules - The list of tax rules to validate.\r\n\t * @throws {InvalidChargeTaxRuleError} If any rules have positive tax rates with SUBTRACT impact or if duplicate rule IDs are found.\r\n\t * @throws {InvalidChargeTaxRuleError} Duplicate tax rule IDs will results in error.\r\n\t * @throws {CoincidingTaxBracketError} If any overlapping rules are found.\r\n\t */\r\n\tprivate validateTaxRules(taxRules: TaxRuleModel[]): void {\r\n\t\tif(this.impact === ChargeImpact.SUBTRACT) {\r\n\t\t\tif(taxRules.some(taxRule => taxRule.getRate() > 0)) {\r\n\t\t\t\tthrow new InvalidChargeTaxRuleError(\"Subtractive charges cannot have positive tax rates.\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst uniqueTaxRule = new Set();\r\n\t\tfor (let i = 0; i < taxRules.length; i++) {\r\n\t\t\tconst currentTaxRuleId = taxRules[i].getTaxRuleId();\r\n\t\t\tif(uniqueTaxRule.has(currentTaxRuleId)){\r\n\t\t\t\tthrow new InvalidChargeTaxRuleError(\"Duplicate tax rule ID found: \" + currentTaxRuleId);\r\n\t\t\t} else {\r\n\t\t\t\tuniqueTaxRule.add(currentTaxRuleId);\r\n\t\t\t}\r\n\r\n\t\t\tfor (let j = i + 1; j < taxRules.length; j++) {\r\n\t\t\t\tconst r1 = taxRules[i];\r\n\t\t\t\tconst r2 = taxRules[j];\r\n\r\n\t\t\t\tconst r1Min = r1.getMinPrice();\r\n\t\t\t\tconst r1Max = r1.getMaxPrice();\r\n\t\t\t\tconst r1ExcludeMin = r1.getExcludeMin();\r\n\t\t\t\tconst r1ExcludeMax = r1.getExcludeMax();\r\n\t\t\t\tconst r2Min = r2.getMinPrice();\r\n\t\t\t\tconst r2Max = r2.getMaxPrice();\r\n\t\t\t\tconst r2ExcludeMin = r2.getExcludeMin();\r\n\t\t\t\tconst r2ExcludeMax = r2.getExcludeMax();\r\n\r\n\t\t\t\t// Two ranges are disjoint if one ends strictly before the other starts.\r\n\t\t\t\t// If they only touch at one point, disjoint only when either side excludes that point.\r\n\t\t\t\tconst r1EndsBeforeR2Starts = (() => {\r\n\t\t\t\t\tif (!r1Max) return false;\r\n\t\t\t\t\tconst compare = r1Max.compareTo(r2Min);\r\n\t\t\t\t\treturn compare < 0 || (compare === 0 && (r1ExcludeMax || r2ExcludeMin));\r\n\t\t\t\t})();\r\n\t\t\t\tconst r2EndsBeforeR1Starts = (() => {\r\n\t\t\t\t\tif (!r2Max) return false;\r\n\t\t\t\t\tconst compare = r2Max.compareTo(r1Min);\r\n\t\t\t\t\treturn compare < 0 || (compare === 0 && (r2ExcludeMax || r1ExcludeMin));\r\n\t\t\t\t})();\r\n\t\t\t\tconst overlap = !(r1EndsBeforeR2Starts || r2EndsBeforeR1Starts);\r\n\r\n\t\t\t\tif (overlap) {\r\n\t\t\t\t\t// Exception: Allow overlapping rules if they have the exact same price bracket (slab)\r\n\t\t\t\t\tconst sameSlab = r1Min.compareTo(r2Min) === 0 &&\r\n\t\t\t\t\t\tr1ExcludeMin === r2ExcludeMin &&\r\n\t\t\t\t\t\tr1ExcludeMax === r2ExcludeMax &&\r\n\t\t\t\t\t\t((!r1Max && !r2Max) || (r1Max && r2Max && r1Max.compareTo(r2Max) === 0));\r\n\r\n\t\t\t\t\tif (!sameSlab) {\r\n\t\t\t\t\t\tthrow new InvalidChargeTaxRuleError(\r\n\t\t\t\t\t\t\t`Overlapping rules found: [${r1.getTaxRuleId()}: ${r1ExcludeMin ? \"(\" : \"[\"}${r1Min.getAmount()}-${r1Max?.getAmount() ?? \"Infinity\"}${r1ExcludeMax ? \")\" : \"]\"}] and [${r2.getTaxRuleId()}: ${r2ExcludeMin ? \"(\" : \"[\"}${r2Min.getAmount()}-${r2Max?.getAmount() ?? \"Infinity\"}${r2ExcludeMax ? \")\" : \"]\"}]`\r\n\t\t\t\t\t\t);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Updates the discounts applied to this line item and recalculates totals.\r\n\t * @param appliedDiscounts - List of coupons and their allocated discount amounts.\r\n\t*/\r\n\tpublic updateDiscounts(appliedDiscounts: { coupon: CouponModel, amount: PriceModel }[]): void {\r\n\t\tlet chargeDiscounts = {} as Record<string, PriceModel>;\r\n\t\tappliedDiscounts.forEach(discount => {\r\n\t\t\tchargeDiscounts[discount.coupon.getCode()] = discount.amount;\r\n\t\t});\r\n\r\n\t\tthis.total.discountBreakdown = chargeDiscounts;\r\n\t\tthis.calculateTotals();\r\n\t}\r\n\r\n\t/**\r\n\t * Recalculates totals for this charge based on pricing and discounts.\r\n\t */\r\n\tpublic calculateTotals(): void {\r\n\t\tconst zero = this.pricing.baseChargeAmount.zero();\r\n\t\tconst baseChargeAmount = this.pricing.baseChargeAmount;\r\n\r\n\t\tconst totalDiscount = Object.values(this.total.discountBreakdown).reduce((sum, s) => sum.add(s), zero);\r\n\t\tconst netChargeAmount = baseChargeAmount.subtract(totalDiscount);\r\n\r\n\t\tconst taxBreakdown: Record<string, ChargeTaxBreakdownModel> = {};\r\n\r\n\t\t// 1. Calculate total rate for inclusive back-calculation\r\n\t\tconst totalRate = this.pricing.applicableTaxRule.reduce((sum, r) => sum + r.getApplicableTaxRate(netChargeAmount), 0);\r\n\r\n\t\tif (totalRate <= 0) {\r\n\t\t\tthis.total = {\r\n\t\t\t\tchargeAmount: baseChargeAmount,\r\n\t\t\t\tdiscountTotal: totalDiscount,\r\n\t\t\t\tdiscountBreakdown: this.total.discountBreakdown,\r\n\t\t\t\tnetChargeAmount: netChargeAmount,\r\n\t\t\t\ttaxTotal: zero,\r\n\t\t\t\ttaxBreakdown: {},\r\n\t\t\t\tgrandTotal: netChargeAmount\r\n\t\t\t};\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// 2. Iteratively find a taxable base so that base + sum(rounded taxes) == gross\r\n\t\tconst currency = netChargeAmount.getCurrency();\r\n\t\tconst grossValue = netChargeAmount.getAmount();\r\n\t\tconst maxIterations = 1000;\r\n\r\n\t\tlet baseValue = PriceModel.getRoundedAmount(grossValue / (1 + totalRate), currency);\r\n\t\tlet bestBaseValue = baseValue;\r\n\t\tlet bestDiff = Number.POSITIVE_INFINITY;\r\n\r\n\t\tfor (let i = 0; i < maxIterations; i++) {\r\n\t\t\tconst currentTaxableBase = new PriceModel({ amount: baseValue, currency });\r\n\t\t\tconst taxes = this.pricing.applicableTaxRule\r\n\t\t\t\t.sort((a, b) => b.getApplicableTaxRate(currentTaxableBase) - a.getApplicableTaxRate(currentTaxableBase))\r\n\t\t\t\t.map(rule =>\r\n\t\t\t\t\tPriceModel.getRoundedAmount(baseValue * rule.getApplicableTaxRate(currentTaxableBase), currency)\r\n\t\t\t\t);\r\n\r\n\t\t\tconst taxSum = taxes.reduce((sum, v) => sum + v, 0);\r\n\t\t\tconst diff = (baseValue + taxSum) - grossValue;\r\n\r\n\t\t\tconst currentTotalRate = this.pricing.applicableTaxRule.reduce((sum, r) => sum + r.getApplicableTaxRate(currentTaxableBase), 0);\r\n\r\n\t\t\tif (Math.abs(diff) < Math.abs(bestDiff)) {\r\n\t\t\t\tbestDiff = diff;\r\n\t\t\t\tbestBaseValue = baseValue;\r\n\t\t\t}\r\n\r\n\t\t\tif (diff === 0) break;\r\n\t\t\tbaseValue = baseValue - diff / (1 + currentTotalRate); // Adjust base value based on the difference\r\n\t\t\tif (baseValue < 0 || baseValue > grossValue) break;\r\n\t\t}\r\n\r\n\t\tconst taxableBase = new PriceModel({ amount: bestBaseValue, currency });\r\n\r\n\t\t// 3. Compute tax amounts per rule based on final taxable base\r\n\t\tlet distributedTax = zero;\r\n\t\tthis.pricing.applicableTaxRule\r\n\t\t\t.sort((a, b) => b.getApplicableTaxRate(taxableBase) - a.getApplicableTaxRate(taxableBase))\r\n\t\t\t.forEach((taxRule) => {\r\n\t\t\t\tconst rate = taxRule.getApplicableTaxRate(taxableBase);\r\n\t\t\t\tconst taxAmountValue = PriceModel.getRoundedAmount(bestBaseValue * rate, currency);\r\n\t\t\t\tconst taxAmount = new PriceModel({ amount: taxAmountValue, currency });\r\n\r\n\t\t\t\ttaxBreakdown[taxRule.getTaxRuleId()] = {\r\n\t\t\t\t\trate: rate,\r\n\t\t\t\t\ttaxableAmount: taxableBase,\r\n\t\t\t\t\ttaxAmount: taxAmount,\r\n\t\t\t\t\tsystem: taxRule.getTaxSystem(),\r\n\t\t\t\t\tsubSystem: taxRule.getTaxSubSystem()\r\n\t\t\t\t};\r\n\t\t\t\tdistributedTax = distributedTax.add(taxAmount);\r\n\t\t\t});\r\n\r\n\t\tconst grandTotal = netChargeAmount;\r\n\t\tthis.total = {\r\n\t\t\tchargeAmount: baseChargeAmount,\r\n\t\t\tdiscountTotal: totalDiscount,\r\n\t\t\tdiscountBreakdown: this.total.discountBreakdown,\r\n\t\t\tnetChargeAmount: netChargeAmount,\r\n\t\t\ttaxBreakdown: taxBreakdown,\r\n\t\t\ttaxTotal: distributedTax,\r\n\t\t\tgrandTotal: grandTotal\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets a plain data object representing this charge.\r\n\t * @returns ChargeData for serialization.\r\n\t */\r\n\tpublic getDetails(): ChargeData {\r\n\t\tconst details: ChargeData = {\r\n\t\t\tid: this.id,\r\n\t\t\tname: Utils.deepClone(this.name),\r\n\t\t\ttype: this.type,\r\n\t\t\tcategory: this.category,\r\n\t\t\tpricing: {\r\n\t\t\t\tbaseChargeAmount: this.pricing.baseChargeAmount.getDetails(),\r\n\t\t\t\ttaxCategory: this.pricing.taxCategory,\r\n\t\t\t\tapplicableTaxRule: this.pricing.applicableTaxRule.map(r => r.getDetails())\r\n\t\t\t},\r\n\t\t\timpact: this.impact,\r\n\t\t\tlineItemId: this.lineItemId,\r\n\t\t\ttotal: {\r\n\t\t\t\tchargeAmount: this.total.chargeAmount.getDetails(),\r\n\t\t\t\tdiscountTotal: this.total.discountTotal.getDetails(),\r\n\t\t\t\tdiscountBreakdown: Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([k, v]) => [k, v.getDetails()])),\r\n\t\t\t\tnetChargeAmount: this.total.netChargeAmount.getDetails(),\r\n\t\t\t\ttaxBreakdown: Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([k, v]) => [k, {\r\n\t\t\t\t\trate: v.rate,\r\n\t\t\t\t\ttaxableAmount: v.taxableAmount.getDetails(),\r\n\t\t\t\t\ttaxAmount: v.taxAmount.getDetails(),\r\n\t\t\t\t\tsystem: v.system,\r\n\t\t\t\t\tsubSystem: v.subSystem\r\n\t\t\t\t}])),\r\n\t\t\t\ttaxTotal: this.total.taxTotal.getDetails(),\r\n\t\t\t\tgrandTotal: this.total.grandTotal.getDetails()\r\n\t\t\t},\r\n\t\t\tcustomFields: this.getAllCustomFields()\r\n\t\t};\r\n\t\treturn details;\r\n\t}\r\n}\r\n"]}
1
+ {"version":3,"sources":["../src/Classes/Charge.ts"],"names":["ChargeModel","CustomFieldModel","data","PriceModel","r","TaxRuleModel","InvalidChargeError","discountId","discount","taxRuleId","taxBreakdown","locale","Utils_default","LocaleLanguageMap","key","value","taxRules","taxRule","InvalidTaxRuleError","InvalidChargeTaxRuleError","uniqueTaxRule","i","currentTaxRuleId","j","r1","r2","r1Min","r1Max","r1ExcludeMin","r1ExcludeMax","r2Min","r2Max","r2ExcludeMin","r2ExcludeMax","r1EndsBeforeR2Starts","compare","r2EndsBeforeR1Starts","appliedDiscounts","chargeDiscounts","zero","baseChargeAmount","totalDiscount","sum","s","netChargeAmount","totalRate","currency","grossValue","maxIterations","baseValue","bestBaseValue","bestDiff","currentTaxableBase","taxSum","a","b","rule","v","diff","currentTotalRate","taxableBase","distributedTax","rate","taxAmountValue","taxAmount","grandTotal","k"],"mappings":"uPA4FA,IAAqBA,CAArB,CA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AAA,GACxC,iBAAmB,CAAA,MAAA,CAAO,WAAY,CAAA,MAAA,CAAO,OAAQ,CAAA,IAAA,CAAK,KAAM,CAAA,iBAAiB,EAAE,GAAI,CAAA,CAAC,CAAC8D,CAAAA,CAAGT,CAAC,CAAA,GAAM,CAACS,CAAAA,CAAGT,EAAE,UAAW,EAAC,CAAC,CAAC,CACvH,CAAA,eAAA,CAAiB,IAAK,CAAA,KAAA,CAAM,eAAgB,CAAA,UAAA,EAC5C,CAAA,YAAA,CAAc,MAAO,CAAA,WAAA,CAAY,MAAO,CAAA,OAAA,CAAQ,KAAK,KAAM,CAAA,YAAY,CAAE,CAAA,GAAA,CAAI,CAAC,CAACS,CAAGT,CAAAA,CAAC,IAAM,CAACS,CAAAA,CAAG,CAC5F,IAAA,CAAMT,CAAE,CAAA,IAAA,CACR,aAAeA,CAAAA,CAAAA,CAAE,cAAc,UAAW,EAAA,CAC1C,SAAWA,CAAAA,CAAAA,CAAE,SAAU,CAAA,UAAA,EACvB,CAAA,MAAA,CAAQA,CAAE,CAAA,MAAA,CACV,SAAWA,CAAAA,CAAAA,CAAE,SACd,CAAC,CAAC,CAAC,EACH,QAAU,CAAA,IAAA,CAAK,KAAM,CAAA,QAAA,CAAS,UAAW,EAAA,CACzC,UAAY,CAAA,IAAA,CAAK,MAAM,UAAW,CAAA,UAAA,EACnC,CAAA,CACA,YAAc,CAAA,IAAA,CAAK,kBAAmB,EACvC,CAED,CACD","file":"chunk-XTF6ND33.mjs","sourcesContent":["import { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\nimport Utils from \"../Utils\";\r\nimport { LocaleCode, LocalizedString } from \"./Common\";\r\nimport { ChargeImpact, ChargeType, LocaleLanguageMap, TaxSystem } from \"./Enum\";\r\nimport { InvalidChargeTaxRuleError, InvalidChargeError, InvalidTaxRuleError } from \"./Error\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport { TaxRuleData, TaxRuleModel } from \"./TaxRule\";\r\nimport CouponModel from \"./Coupon\";\r\n\r\nexport type ChargePricing = {\r\n /** Tax-inclusive original charge amount before any discounts. Always non-negative. */\r\n baseChargeAmount: PriceData;\r\n /** Tax category of the charge. */\r\n taxCategory: string;\r\n /** Tax rules applicable to the charge. */\r\n applicableTaxRule: TaxRuleData[];\r\n};\r\n\r\nexport type ChargePricingModel = {\r\n /** Tax-inclusive original charge amount before any discounts. Always non-negative. */\r\n baseChargeAmount: PriceModel;\r\n /** Tax category of the charge. */\r\n taxCategory: string;\r\n /** Tax rules applicable to the charge. */\r\n applicableTaxRule: TaxRuleModel[];\r\n};\r\n\r\nexport type ChargeTaxBreakdown = {\r\n /** Tax rate: e.g., 0.09 for 9% */\r\n rate: number;\r\n /** Reverse-calculated pre-tax base from the netChargeAmount (post-discount) */\r\n taxableAmount: PriceData;\r\n /** Tax portion for this rule (netChargeAmount - taxableAmount) */\r\n taxAmount: PriceData;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type ChargeTaxBreakdownModel = {\r\n rate: number;\r\n taxableAmount: PriceModel;\r\n taxAmount: PriceModel;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type ChargeTotals = {\r\n /** Tax-inclusive original charge amount before discounts (copied from pricing) */\r\n chargeAmount: PriceData;\r\n /** Coupon code -> discount amount mapping */\r\n discountBreakdown: Record<string, PriceData>;\r\n /** Sum of all discounts */\r\n discountTotal: PriceData;\r\n /** chargeAmount - totalDiscount → final tax-inclusive payable amount after discounts */\r\n netChargeAmount: PriceData;\r\n /** Sum of all taxAmount values */\r\n taxTotal: PriceData;\r\n /** Tax breakdown per rule/category (reverse-calculated from netChargeAmount) */\r\n taxBreakdown: Record<string, ChargeTaxBreakdown>;\r\n /** Final payable/contribution amount. Equals netChargeAmount (tax-inclusive after discounts). */\r\n grandTotal: PriceData;\r\n};\r\n\r\nexport type ChargeTotalsModel = {\r\n chargeAmount: PriceModel;\r\n discountTotal: PriceModel;\r\n discountBreakdown: Record<string, PriceModel>;\r\n netChargeAmount: PriceModel;\r\n taxTotal: PriceModel;\r\n taxBreakdown: Record<string, ChargeTaxBreakdownModel>;\r\n grandTotal: PriceModel; // Equals netChargeAmount\r\n};\r\n\r\nexport type ChargeAttributes = CustomFieldAttributes & {\r\n id: string;\r\n name: LocalizedString;\r\n type: ChargeType;\r\n category: string;\r\n impact: ChargeImpact; // ADD or SUBTRACT\r\n pricing: ChargePricing;\r\n lineItemId?: string;\r\n total: ChargeTotals;\r\n};\r\n\r\nexport type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId'> & {\r\n\tlineItemId?: string;\r\n};\r\n\r\n/**\r\n * Represents an additional charge (or discount if amount is negative) in a shopping container.\r\n * Supports its own tax rules.\r\n */\r\nexport default class ChargeModel extends CustomFieldModel {\r\n\tprotected id: string;\r\n\tprotected name: LocalizedString;\r\n\tprotected type: ChargeType;\r\n\tprotected category: string;\r\n\tprotected impact: ChargeImpact;\r\n\tprotected pricing: ChargePricingModel;\r\n\tprotected lineItemId?: string;\r\n\tprotected total: ChargeTotalsModel;\r\n\r\n\tconstructor(data: ChargeAttributes) {\r\n\t\tsuper(data);\r\n\t\tthis.id = data.id;\r\n\t\tthis.name = data.name;\r\n\t\tthis.type = data.type;\r\n\t\tthis.category = data.category;\r\n\t\tthis.impact = data.impact;\r\n\t\tthis.lineItemId = data.lineItemId;\r\n\t\tthis.pricing = {\r\n\t\t\tbaseChargeAmount: new PriceModel(data.pricing.baseChargeAmount),\r\n\t\t\ttaxCategory: data.pricing.taxCategory,\r\n\t\t\tapplicableTaxRule: data.pricing.applicableTaxRule.map(r => new TaxRuleModel(r))\r\n\t\t};\r\n\r\n\t\tthis.validateTaxRules(this.pricing.applicableTaxRule);\r\n\t\tif(this.impact === ChargeImpact.SUBTRACT && this.type !== ChargeType.ADJUSTMENT) {\r\n\t\t\tthrow new InvalidChargeError('SUBTRACT impact is only allowed for ADJUSTMENT charge');\r\n\t\t}\r\n\r\n\t\tthis.total = {\r\n\t\t\tchargeAmount: new PriceModel(data.total.chargeAmount),\r\n\t\t\tdiscountTotal: new PriceModel(data.total.discountTotal),\r\n\t\t\tdiscountBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(data.total.discountBreakdown).map(([discountId, discount]) => [\r\n\t\t\t\t\tdiscountId,\r\n\t\t\t\t\tnew PriceModel(discount)\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\tnetChargeAmount: new PriceModel(data.total.netChargeAmount),\r\n\t\t\ttaxBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(data.total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n\t\t\t\t\ttaxRuleId,\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\trate: taxBreakdown.rate,\r\n\t\t\t\t\t\ttaxableAmount: new PriceModel(taxBreakdown.taxableAmount),\r\n\t\t\t\t\t\ttaxAmount: new PriceModel(taxBreakdown.taxAmount),\r\n\t\t\t\t\t\tsystem: taxBreakdown.system,\r\n\t\t\t\t\t\tsubSystem: taxBreakdown.subSystem\r\n\t\t\t\t\t}\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\ttaxTotal: new PriceModel(data.total.taxTotal),\r\n\t\t\tgrandTotal: new PriceModel(data.total.grandTotal),\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the unique identifier of the charge.\r\n\t * @returns \r\n\t */\r\n\tpublic getId(): string { return this.id; }\r\n\r\n\r\n\t/**\r\n\t * Gets the full localized product name object.\r\n\t * @returns A copy of the LocalizedString object for the name.\r\n\t */\r\n\tgetName(): LocalizedString\r\n\t/**\r\n\t * Gets the product name for a specific locale, falling back to English ('en').\r\n\t * @param locale - The desired locale code.\r\n\t * @returns The name string for the specified locale.\r\n\t */\r\n\tgetName(locale: LocaleCode): string\r\n\tgetName(locale?: LocaleCode): LocalizedString | string {\r\n\t\tif (locale) {\r\n\t\t\treturn Utils.deepClone(this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en);\r\n\t\t} else {\r\n\t\t\treturn Utils.deepClone(this.name);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the charge category.\r\n\t * @returns The category string.\r\n\t */\r\n\tpublic getCategory(): string { return this.category; }\r\n\r\n\t/**\r\n\t * Gets the charge type.\r\n\t * @returns The charge type enum value.\r\n\t */\r\n\tpublic getType(): ChargeType { return this.type; }\r\n\t/**\r\n\t * Gets the charge impact (add or subtract).\r\n\t * @returns The charge impact.\r\n\t */\r\n\tpublic getImpact(): ChargeImpact { return this.impact; }\r\n\r\n\t/**\r\n\t * Gets the related line item id, if any.\r\n\t * @returns The line item id or undefined.\r\n\t */\r\n\tpublic getLineItemId(): string | undefined { return this.lineItemId; }\r\n\r\n\t/**\r\n\t * Gets the pricing details (models) for this charge.\r\n\t * @returns Pricing details including price, tax category, and tax rules.\r\n\t */\r\n\tpublic getPricing(): ChargePricingModel {\r\n\t\treturn {\r\n\t\t\tbaseChargeAmount: this.pricing.baseChargeAmount,\r\n\t\t\ttaxCategory: this.pricing.taxCategory,\r\n\t\t\tapplicableTaxRule: [...this.pricing.applicableTaxRule]\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the computed totals for this charge.\r\n\t * @returns Totals including discounts, taxes, and grand total.\r\n\t */\r\n\tpublic getTotal(): ChargeTotalsModel {\r\n\t\treturn {\r\n\t\t\tchargeAmount: this.total.chargeAmount,\r\n\t\t\tdiscountTotal: this.total.discountTotal,\r\n\t\t\tdiscountBreakdown: { ...this.total.discountBreakdown },\r\n\t\t\tnetChargeAmount: this.total.netChargeAmount,\r\n\t\t\ttaxTotal: this.total.taxTotal,\r\n\t\t\ttaxBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(this.total.taxBreakdown).map(([key, value]) => [\r\n\t\t\t\t\tkey,\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\trate: value.rate,\r\n\t\t\t\t\t\ttaxableAmount: value.taxableAmount,\r\n\t\t\t\t\t\ttaxAmount: value.taxAmount,\r\n\t\t\t\t\t\tsystem: value.system,\r\n\t\t\t\t\t\tsubSystem: value.subSystem\r\n\t\t\t\t\t}\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\tgrandTotal: this.total.grandTotal,\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the applicable tax rules for this charge.\r\n\t * @returns A list of tax rules.\r\n\t */\r\n\tpublic getApplicableTaxRules(): TaxRuleModel[] {\r\n\t\treturn [...this.pricing.applicableTaxRule];\r\n\t}\r\n\r\n\t/**\r\n\t * Updates the tax rule for this line item and recalculates totals.\r\n\t * @param taxRule - The new tax rule to apply.\r\n\t * @throws {Error} If the tax rule category does not match the item's tax category.\r\n\t */\r\n\tpublic updateTax(taxRules: TaxRuleModel[]): void {\r\n\t\tif (this.type === ChargeType.ADJUSTMENT && taxRules.length > 0) {\r\n\t\t\tthrow new InvalidChargeError(\"Adjustment charges cannot apply tax rules.\");\r\n\t\t}\r\n\t\ttaxRules.forEach(taxRule => {\r\n\t\t\tif (!taxRule.appliesTo(this.pricing.taxCategory, taxRule.getCountry())) {\r\n\t\t\t\tthrow new InvalidTaxRuleError();\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\t// Remove the old taxableUnitPrice calculation - no longer needed\r\n\t\tthis.validateTaxRules(taxRules);\r\n\t\tthis.pricing.applicableTaxRule = taxRules;\r\n\t\tthis.calculateTotals();\r\n\t}\r\n\r\n\t/**\r\n\t * Validates that there are no overlapping price brackets for any tax rules within the charge.\r\n\t * @param taxRules - The list of tax rules to validate.\r\n\t * @throws {InvalidChargeTaxRuleError} If any rules have positive tax rates with SUBTRACT impact or if duplicate rule IDs are found.\r\n\t * @throws {InvalidChargeTaxRuleError} Duplicate tax rule IDs will results in error.\r\n\t * @throws {CoincidingTaxBracketError} If any overlapping rules are found.\r\n\t */\r\n\tprivate validateTaxRules(taxRules: TaxRuleModel[]): void {\r\n\t\tif(this.impact === ChargeImpact.SUBTRACT) {\r\n\t\t\tif(taxRules.some(taxRule => taxRule.getRate() > 0)) {\r\n\t\t\t\tthrow new InvalidChargeTaxRuleError(\"Subtractive charges cannot have positive tax rates.\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst uniqueTaxRule = new Set();\r\n\t\tfor (let i = 0; i < taxRules.length; i++) {\r\n\t\t\tconst currentTaxRuleId = taxRules[i].getTaxRuleId();\r\n\t\t\tif(uniqueTaxRule.has(currentTaxRuleId)){\r\n\t\t\t\tthrow new InvalidChargeTaxRuleError(\"Duplicate tax rule ID found: \" + currentTaxRuleId);\r\n\t\t\t} else {\r\n\t\t\t\tuniqueTaxRule.add(currentTaxRuleId);\r\n\t\t\t}\r\n\r\n\t\t\tfor (let j = i + 1; j < taxRules.length; j++) {\r\n\t\t\t\tconst r1 = taxRules[i];\r\n\t\t\t\tconst r2 = taxRules[j];\r\n\r\n\t\t\t\tconst r1Min = r1.getMinPrice();\r\n\t\t\t\tconst r1Max = r1.getMaxPrice();\r\n\t\t\t\tconst r1ExcludeMin = r1.getExcludeMin();\r\n\t\t\t\tconst r1ExcludeMax = r1.getExcludeMax();\r\n\t\t\t\tconst r2Min = r2.getMinPrice();\r\n\t\t\t\tconst r2Max = r2.getMaxPrice();\r\n\t\t\t\tconst r2ExcludeMin = r2.getExcludeMin();\r\n\t\t\t\tconst r2ExcludeMax = r2.getExcludeMax();\r\n\r\n\t\t\t\t// Two ranges are disjoint if one ends strictly before the other starts.\r\n\t\t\t\t// If they only touch at one point, disjoint only when either side excludes that point.\r\n\t\t\t\tconst r1EndsBeforeR2Starts = (() => {\r\n\t\t\t\t\tif (!r1Max) return false;\r\n\t\t\t\t\tconst compare = r1Max.compareTo(r2Min);\r\n\t\t\t\t\treturn compare < 0 || (compare === 0 && (r1ExcludeMax || r2ExcludeMin));\r\n\t\t\t\t})();\r\n\t\t\t\tconst r2EndsBeforeR1Starts = (() => {\r\n\t\t\t\t\tif (!r2Max) return false;\r\n\t\t\t\t\tconst compare = r2Max.compareTo(r1Min);\r\n\t\t\t\t\treturn compare < 0 || (compare === 0 && (r2ExcludeMax || r1ExcludeMin));\r\n\t\t\t\t})();\r\n\t\t\t\tconst overlap = !(r1EndsBeforeR2Starts || r2EndsBeforeR1Starts);\r\n\r\n\t\t\t\tif (overlap) {\r\n\t\t\t\t\t// Exception: Allow overlapping rules if they have the exact same price bracket (slab)\r\n\t\t\t\t\tconst sameSlab = r1Min.compareTo(r2Min) === 0 &&\r\n\t\t\t\t\t\tr1ExcludeMin === r2ExcludeMin &&\r\n\t\t\t\t\t\tr1ExcludeMax === r2ExcludeMax &&\r\n\t\t\t\t\t\t((!r1Max && !r2Max) || (r1Max && r2Max && r1Max.compareTo(r2Max) === 0));\r\n\r\n\t\t\t\t\tif (!sameSlab) {\r\n\t\t\t\t\t\tthrow new InvalidChargeTaxRuleError(\r\n\t\t\t\t\t\t\t`Overlapping rules found: [${r1.getTaxRuleId()}: ${r1ExcludeMin ? \"(\" : \"[\"}${r1Min.getAmount()}-${r1Max?.getAmount() ?? \"Infinity\"}${r1ExcludeMax ? \")\" : \"]\"}] and [${r2.getTaxRuleId()}: ${r2ExcludeMin ? \"(\" : \"[\"}${r2Min.getAmount()}-${r2Max?.getAmount() ?? \"Infinity\"}${r2ExcludeMax ? \")\" : \"]\"}]`\r\n\t\t\t\t\t\t);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Updates the discounts applied to this line item and recalculates totals.\r\n\t * @param appliedDiscounts - List of coupons and their allocated discount amounts.\r\n\t*/\r\n\tpublic updateDiscounts(appliedDiscounts: { coupon: CouponModel, amount: PriceModel }[]): void {\r\n\t\tlet chargeDiscounts = {} as Record<string, PriceModel>;\r\n\t\tappliedDiscounts.forEach(discount => {\r\n\t\t\tchargeDiscounts[discount.coupon.getCode()] = discount.amount;\r\n\t\t});\r\n\r\n\t\tthis.total.discountBreakdown = chargeDiscounts;\r\n\t\tthis.calculateTotals();\r\n\t}\r\n\r\n\t/**\r\n\t * Recalculates totals for this charge based on pricing and discounts.\r\n\t */\r\n\tpublic calculateTotals(): void {\r\n\t\tconst zero = this.pricing.baseChargeAmount.zero();\r\n\t\tconst baseChargeAmount = this.pricing.baseChargeAmount;\r\n\r\n\t\tconst totalDiscount = Object.values(this.total.discountBreakdown).reduce((sum, s) => sum.add(s), zero);\r\n\t\tconst netChargeAmount = baseChargeAmount.subtract(totalDiscount);\r\n\r\n\t\tconst taxBreakdown: Record<string, ChargeTaxBreakdownModel> = {};\r\n\r\n\t\t// 1. Calculate total rate for inclusive back-calculation\r\n\t\tconst totalRate = this.pricing.applicableTaxRule.reduce((sum, r) => sum + r.getApplicableTaxRate(netChargeAmount), 0);\r\n\r\n\t\tif (totalRate <= 0) {\r\n\t\t\tthis.total = {\r\n\t\t\t\tchargeAmount: baseChargeAmount,\r\n\t\t\t\tdiscountTotal: totalDiscount,\r\n\t\t\t\tdiscountBreakdown: this.total.discountBreakdown,\r\n\t\t\t\tnetChargeAmount: netChargeAmount,\r\n\t\t\t\ttaxTotal: zero,\r\n\t\t\t\ttaxBreakdown: {},\r\n\t\t\t\tgrandTotal: netChargeAmount\r\n\t\t\t};\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// 2. Iteratively find a taxable base so that base + sum(rounded taxes) == gross\r\n\t\tconst currency = netChargeAmount.getCurrency();\r\n\t\tconst grossValue = netChargeAmount.getAmount();\r\n\t\tconst maxIterations = 1000;\r\n\r\n\t\tlet baseValue = PriceModel.getRoundedAmount(grossValue / (1 + totalRate), currency);\r\n\t\tlet bestBaseValue = baseValue;\r\n\t\tlet bestDiff = Number.POSITIVE_INFINITY;\r\n\r\n\t\tfor (let i = 0; i < maxIterations; i++) {\r\n\t\t\tconst currentTaxableBase = new PriceModel({ amount: baseValue, currency });\r\n\t\t\tconst taxes = this.pricing.applicableTaxRule\r\n\t\t\t\t.sort((a, b) => b.getApplicableTaxRate(currentTaxableBase) - a.getApplicableTaxRate(currentTaxableBase))\r\n\t\t\t\t.map(rule =>\r\n\t\t\t\t\tPriceModel.getRoundedAmount(baseValue * rule.getApplicableTaxRate(currentTaxableBase), currency)\r\n\t\t\t\t);\r\n\r\n\t\t\tconst taxSum = taxes.reduce((sum, v) => sum + v, 0);\r\n\t\t\tconst diff = (baseValue + taxSum) - grossValue;\r\n\r\n\t\t\tconst currentTotalRate = this.pricing.applicableTaxRule.reduce((sum, r) => sum + r.getApplicableTaxRate(currentTaxableBase), 0);\r\n\r\n\t\t\tif (Math.abs(diff) < Math.abs(bestDiff)) {\r\n\t\t\t\tbestDiff = diff;\r\n\t\t\t\tbestBaseValue = baseValue;\r\n\t\t\t}\r\n\r\n\t\t\tif (diff === 0) break;\r\n\t\t\tbaseValue = baseValue - diff / (1 + currentTotalRate); // Adjust base value based on the difference\r\n\t\t\tif (baseValue < 0 || baseValue > grossValue) break;\r\n\t\t}\r\n\r\n\t\tconst taxableBase = new PriceModel({ amount: bestBaseValue, currency });\r\n\r\n\t\t// 3. Compute tax amounts per rule based on final taxable base\r\n\t\tlet distributedTax = zero;\r\n\t\tthis.pricing.applicableTaxRule\r\n\t\t\t.sort((a, b) => b.getApplicableTaxRate(taxableBase) - a.getApplicableTaxRate(taxableBase))\r\n\t\t\t.forEach((taxRule) => {\r\n\t\t\t\tconst rate = taxRule.getApplicableTaxRate(taxableBase);\r\n\t\t\t\tconst taxAmountValue = PriceModel.getRoundedAmount(bestBaseValue * rate, currency);\r\n\t\t\t\tconst taxAmount = new PriceModel({ amount: taxAmountValue, currency });\r\n\r\n\t\t\t\ttaxBreakdown[taxRule.getTaxRuleId()] = {\r\n\t\t\t\t\trate: rate,\r\n\t\t\t\t\ttaxableAmount: taxableBase,\r\n\t\t\t\t\ttaxAmount: taxAmount,\r\n\t\t\t\t\tsystem: taxRule.getTaxSystem(),\r\n\t\t\t\t\tsubSystem: taxRule.getTaxSubSystem()\r\n\t\t\t\t};\r\n\t\t\t\tdistributedTax = distributedTax.add(taxAmount);\r\n\t\t\t});\r\n\r\n\t\tconst grandTotal = netChargeAmount;\r\n\t\tthis.total = {\r\n\t\t\tchargeAmount: baseChargeAmount,\r\n\t\t\tdiscountTotal: totalDiscount,\r\n\t\t\tdiscountBreakdown: this.total.discountBreakdown,\r\n\t\t\tnetChargeAmount: netChargeAmount,\r\n\t\t\ttaxBreakdown: taxBreakdown,\r\n\t\t\ttaxTotal: distributedTax,\r\n\t\t\tgrandTotal: grandTotal\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets a plain data object representing this charge.\r\n\t * @returns ChargeData for serialization.\r\n\t */\r\n\tpublic getDetails(): ChargeData {\r\n\t\tconst details: ChargeData = {\r\n\t\t\tid: this.id,\r\n\t\t\tname: Utils.deepClone(this.name),\r\n\t\t\ttype: this.type,\r\n\t\t\tcategory: this.category,\r\n\t\t\tpricing: {\r\n\t\t\t\tbaseChargeAmount: this.pricing.baseChargeAmount.getDetails(),\r\n\t\t\t\ttaxCategory: this.pricing.taxCategory,\r\n\t\t\t\tapplicableTaxRule: this.pricing.applicableTaxRule.map(r => r.getDetails())\r\n\t\t\t},\r\n\t\t\timpact: this.impact,\r\n\t\t\tlineItemId: this.lineItemId,\r\n\t\t\ttotal: {\r\n\t\t\t\tchargeAmount: this.total.chargeAmount.getDetails(),\r\n\t\t\t\tdiscountTotal: this.total.discountTotal.getDetails(),\r\n\t\t\t\tdiscountBreakdown: Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([k, v]) => [k, v.getDetails()])),\r\n\t\t\t\tnetChargeAmount: this.total.netChargeAmount.getDetails(),\r\n\t\t\t\ttaxBreakdown: Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([k, v]) => [k, {\r\n\t\t\t\t\trate: v.rate,\r\n\t\t\t\t\ttaxableAmount: v.taxableAmount.getDetails(),\r\n\t\t\t\t\ttaxAmount: v.taxAmount.getDetails(),\r\n\t\t\t\t\tsystem: v.system,\r\n\t\t\t\t\tsubSystem: v.subSystem\r\n\t\t\t\t}])),\r\n\t\t\t\ttaxTotal: this.total.taxTotal.getDetails(),\r\n\t\t\t\tgrandTotal: this.total.grandTotal.getDetails()\r\n\t\t\t},\r\n\t\t\tcustomFields: this.getAllCustomFields()\r\n\t\t};\r\n\t\treturn details;\r\n\t}\r\n}\r\n"]}
@@ -1,2 +1,2 @@
1
- import {a as a$1}from'./chunk-LI5JQ6UC.mjs';import {a}from'./chunk-UXZBULDS.mjs';var n=class extends a{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$1(e.minPrice),this.maxPrice=e.maxPrice?new a$1(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,o,t,i=new Date){let r=!t||(this.excludeMin?this.minPrice.compareTo(t)<0:this.minPrice.compareTo(t)<=0)&&(this.maxPrice?this.excludeMax?this.maxPrice.compareTo(t)>0:this.maxPrice.compareTo(t)>=0:!0);return this.taxCategory===e&&this.country===o&&r&&Date.parse(this.effectiveFrom)<=i.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=i.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,o,t){let i=o*100,r=i%1===0?i.toString():i.toFixed(2).replace(/\.?0+$/,"");return t?.percentageOnly?`${r}%`:e.getTaxSystem()==="GST"?`${e.getTaxSubSystem()} ${r}%`:`${e.getTaxSystem()} ${r}%`}};export{n as a};//# sourceMappingURL=chunk-SOZHGHMY.mjs.map
2
- //# sourceMappingURL=chunk-SOZHGHMY.mjs.map
1
+ import {a as a$1}from'./chunk-6ZKMKSAG.mjs';import {a}from'./chunk-UXZBULDS.mjs';var n=class extends a{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$1(e.minPrice),this.maxPrice=e.maxPrice?new a$1(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,o,t,i=new Date){let r=!t||(this.excludeMin?this.minPrice.compareTo(t)<0:this.minPrice.compareTo(t)<=0)&&(this.maxPrice?this.excludeMax?this.maxPrice.compareTo(t)>0:this.maxPrice.compareTo(t)>=0:!0);return this.taxCategory===e&&this.country===o&&r&&Date.parse(this.effectiveFrom)<=i.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=i.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,o,t){let i=o*100,r=i%1===0?i.toString():i.toFixed(2).replace(/\.?0+$/,"");return t?.percentageOnly?`${r}%`:e.getTaxSystem()==="GST"?`${e.getTaxSubSystem()} ${r}%`:`${e.getTaxSystem()} ${r}%`}};export{n as a};//# sourceMappingURL=chunk-ZODPRQKQ.mjs.map
2
+ //# sourceMappingURL=chunk-ZODPRQKQ.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Classes/TaxRule.ts"],"names":["TaxRuleModel","CustomFieldModel","data","PriceModel","taxCategory","country","price","at","isPriceInRange","taxRule","rate","formateOption","percentage","rateStr"],"mappings":"iFAsBaA,IAAAA,CAAAA,CAAN,cAA2BC,CAAiB,CACvC,UACA,WACA,CAAA,SAAA,CACA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CAAG,OAAQ,EAAA,GAC5C,IAAK,CAAA,WAAA,CAAc,KAAK,KAAM,CAAA,IAAA,CAAK,WAAW,CAAKA,EAAAA,CAAAA,CAAG,SAAY,CAAA,CAAA,CAAA,CAEvE,CAOA,oBAAqBD,CAAAA,CAAAA,CAA2B,CAC9C,OAAG,IAAA,CAAK,UAAU,IAAK,CAAA,WAAA,CAAa,KAAK,OAASA,CAAAA,CAAK,EAC9C,IAAK,CAAA,IAAA,CAEP,CACT,CAOA,YAAA,CAAaA,EAA+B,CAC1C,OAAI,KAAK,SAAU,CAAA,IAAA,CAAK,YAAa,IAAK,CAAA,OAAA,CAASA,CAAK,CAIjDA,CAAAA,CAAAA,CAAM,SAAS,IAAK,CAAA,IAAI,EAHtBA,CAAM,CAAA,IAAA,EAIjB,CAGA,OAAO,uBAAA,CAAwBG,EAAuBC,CAAcC,CAAAA,CAAAA,CAEzD,CACT,IAAMC,CAAAA,CAAaF,EAAO,GAEpBG,CAAAA,CAAAA,CAAUD,EAAa,CAAM,GAAA,CAAA,CAAIA,EAAW,QAAS,EAAA,CAAIA,EAAW,OAAQ,CAAA,CAAC,EAAE,OAAQ,CAAA,QAAA,CAAU,EAAE,CAEzG,CAAA,OAAID,GAAe,cACV,CAAA,CAAA,EAAGE,CAAO,CAGfJ,CAAAA,CAAAA,CAAAA,CAAAA,CAAQ,cAAmB,GAAA,KAAA,CACtB,GAAGA,CAAQ,CAAA,eAAA,EAAiB,CAAII,CAAAA,EAAAA,CAAO,IAEzC,CAAGJ,EAAAA,CAAAA,CAAQ,cAAc,CAAA,CAAA,EAAII,CAAO,CAAA,CAAA,CAC7C,CACF","file":"chunk-SOZHGHMY.mjs","sourcesContent":["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/TaxRule.ts"],"names":["TaxRuleModel","CustomFieldModel","data","PriceModel","taxCategory","country","price","at","isPriceInRange","taxRule","rate","formateOption","percentage","rateStr"],"mappings":"iFAsBaA,IAAAA,CAAAA,CAAN,cAA2BC,CAAiB,CACvC,UACA,WACA,CAAA,SAAA,CACA,aACA,OACA,CAAA,IAAA,CACA,SACA,QACA,CAAA,UAAA,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,KAAK,KAAM,CAAA,IAAA,CAAK,WAAW,CAAKA,EAAAA,CAAAA,CAAG,SAAY,CAAA,CAAA,CAAA,CAEvE,CAOA,oBAAqBD,CAAAA,CAAAA,CAA2B,CAC9C,OAAG,IAAA,CAAK,UAAU,IAAK,CAAA,WAAA,CAAa,KAAK,OAASA,CAAAA,CAAK,EAC9C,IAAK,CAAA,IAAA,CAEP,CACT,CAOA,YAAA,CAAaA,EAA+B,CAC1C,OAAI,KAAK,SAAU,CAAA,IAAA,CAAK,YAAa,IAAK,CAAA,OAAA,CAASA,CAAK,CAIjDA,CAAAA,CAAAA,CAAM,SAAS,IAAK,CAAA,IAAI,EAHtBA,CAAM,CAAA,IAAA,EAIjB,CAGA,OAAO,uBAAA,CAAwBG,EAAuBC,CAAcC,CAAAA,CAAAA,CAEzD,CACT,IAAMC,CAAAA,CAAaF,EAAO,GAEpBG,CAAAA,CAAAA,CAAUD,EAAa,CAAM,GAAA,CAAA,CAAIA,EAAW,QAAS,EAAA,CAAIA,EAAW,OAAQ,CAAA,CAAC,EAAE,OAAQ,CAAA,QAAA,CAAU,EAAE,CAEzG,CAAA,OAAID,GAAe,cACV,CAAA,CAAA,EAAGE,CAAO,CAGfJ,CAAAA,CAAAA,CAAAA,CAAAA,CAAQ,cAAmB,GAAA,KAAA,CACtB,GAAGA,CAAQ,CAAA,eAAA,EAAiB,CAAII,CAAAA,EAAAA,CAAO,IAEzC,CAAGJ,EAAAA,CAAAA,CAAQ,cAAc,CAAA,CAAA,EAAII,CAAO,CAAA,CAAA,CAC7C,CACF","file":"chunk-ZODPRQKQ.mjs","sourcesContent":["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"]}
package/dist/index.d.mts CHANGED
@@ -2,7 +2,7 @@ import { GenderCategory, OperationalCountry, OperationalCountryCurrency, Operati
2
2
  import { SelectionAttributes } from './Classes/Product.mjs';
3
3
  import './Classes/Base.mjs';
4
4
  import './Auth/index.mjs';
5
- import './Common-Du2s_43h.mjs';
5
+ import './Common-CJ_dZU3n.mjs';
6
6
  import './Classes/ImageInfo.mjs';
7
7
  import './Classes/TieredPrice.mjs';
8
8
 
@@ -165,6 +165,10 @@ declare const Schema: {
165
165
  type: string;
166
166
  pattern: string;
167
167
  };
168
+ e164Phone: {
169
+ type: string;
170
+ pattern: string;
171
+ };
168
172
  email: {
169
173
  type: string;
170
174
  pattern: string;
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import { GenderCategory, OperationalCountry, OperationalCountryCurrency, Operati
2
2
  import { SelectionAttributes } from './Classes/Product.js';
3
3
  import './Classes/Base.js';
4
4
  import './Auth/index.js';
5
- import './Common-BsfeCt6G.js';
5
+ import './Common-D01ijYt3.js';
6
6
  import './Classes/ImageInfo.js';
7
7
  import './Classes/TieredPrice.js';
8
8
 
@@ -165,6 +165,10 @@ declare const Schema: {
165
165
  type: string;
166
166
  pattern: string;
167
167
  };
168
+ e164Phone: {
169
+ type: string;
170
+ pattern: string;
171
+ };
168
172
  email: {
169
173
  type: string;
170
174
  pattern: string;
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict';var se=require('crypto'),Ae=require('util');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var se__default=/*#__PURE__*/_interopDefault(se);var Ae__default=/*#__PURE__*/_interopDefault(Ae);var V=(e=>(e.IN="IN",e))(V||{}),D=(e=>(e.INR="INR",e))(D||{}),w=(t=>(t["en-IN"]="en-IN",t["kn-IN"]="kn-IN",t))(w||{}),$=(r=>(r.en="en",r.kn="kn",r))($||{}),A={"en-IN":"en","kn-IN":"kn"};var J={INR:"\u20B9"},Z={INR:"en-IN"},k=(l=>(l.MALE="Male",l.FEMALE="Female",l.UNISEX="Unisex",l.KIDS="Kids",l.BOY="Boy",l.GIRL="Girl",l.GENERAL="General",l))(k||{});var M=new Uint8Array(256),v=M.length;function G(){return v>M.length-16&&(se__default.default.randomFillSync(M),v=0),M.slice(v,v+=16)}var X=/^(?:[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 oe(t){return typeof t=="string"&&X.test(t)}var ee=oe;var d=[];for(let t=0;t<256;++t)d.push((t+256).toString(16).slice(1));function L(t,e=0){return d[t[e+0]]+d[t[e+1]]+d[t[e+2]]+d[t[e+3]]+"-"+d[t[e+4]]+d[t[e+5]]+"-"+d[t[e+6]]+d[t[e+7]]+"-"+d[t[e+8]]+d[t[e+9]]+"-"+d[t[e+10]]+d[t[e+11]]+d[t[e+12]]+d[t[e+13]]+d[t[e+14]]+d[t[e+15]]}function ae(t){if(!ee(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 te=ae;function ce(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var ue="6ba7b810-9dad-11d1-80b4-00c04fd430c8",le="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function j(t,e,r){function i(n,o,c,l){var s;if(typeof n=="string"&&(n=ce(n)),typeof o=="string"&&(o=te(o)),((s=o)===null||s===void 0?void 0:s.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let u=new Uint8Array(16+n.length);if(u.set(o),u.set(n,o.length),u=r(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,c){l=l||0;for(let b=0;b<16;++b)c[l+b]=u[b];return c}return L(u)}try{i.name=t;}catch{}return i.DNS=ue,i.URL=le,i}var Q={randomUUID:se__default.default.randomUUID};function ge(t,e,r){if(Q.randomUUID&&!e&&!t)return Q.randomUUID();t=t||{};let i=t.random||(t.rng||G)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){r=r||0;for(let n=0;n<16;++n)e[r+n]=i[n];return e}return L(i)}var q=ge;function me(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),se__default.default.createHash("sha1").update(t).digest()}var re=me;var fe=j("v5",80,re),Y=fe;var ye={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?Y(t,e):q(),generateSearchId:(t,e)=>`${t}#${h.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:t=>{let[e,r]=t.split("#");return {key:e,selectionAttributes:h.parseSelectionAttributesKey(r)}},deepClone(t){return structuredClone(t)}},g=ye;var ie=t=>structuredClone(t),H=class{customFields;constructor(e,r=new Date){this.customFields={...e.customFields};}getCustomField(e){let r=this.customFields[e];return r==null?r:ie(r)}setCustomField(e,r){this.customFields[e]=r;}getAllCustomFields(){return ie(this.customFields)}},P=class extends H{version;createdAt;modifiedAt;modifiedBy;constructor(e,r=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():r.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():r.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,r,i,n){this.modifiedBy={id:e,authType:r,requestId:i,lambdaName:n};}};var R=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var f=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var O=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},U=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},F=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},z=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},_=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var C=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},x=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},y=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},p=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},E=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};var I=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw new E("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,r){if(r===void 0){if(e==="original")throw new E("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=r;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var T=class t{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new C("Amount cannot be negative.");if(!e.currency)throw new x("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 y("Cannot compare prices in different currencies.")}else throw new p("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 y("Cannot add prices in different currencies.")}else throw new p("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 y("Cannot subtract prices in different currencies.")}else throw new p("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 y("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 p("Must be a non-negative number.")}divide(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new y("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 p("Must be a positive number.")}min(...e){if(e.length===0)throw new p("Must provide at least one PriceModel.");return e.reduce((r,i)=>{if(t.isPriceModel(i)){if(r.getCurrency()!==i.getCurrency())throw new y("Cannot compare prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return r.compareTo(i)<0?r:i},this)}max(...e){if(e.length===0)throw new p("Must provide at least one PriceModel.");return e.reduce((r,i)=>{if(t.isPriceModel(i)){if(r.getCurrency()!==i.getCurrency())throw new y("Cannot compare prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return r.compareTo(i)>0?r:i},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,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=Z[r];if(!r||!n)throw new x("Invalid currency code for formatting.");let o=e,c=i.displayAsInteger?0:t.getDecimalPlaces(r),l={style:i.style??"currency",currency:r,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:c,maximumFractionDigits:c};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,l).format(o)}catch(s){return console.error(`Error formatting price for currency "${r}" and locale "${n}":`,s),`${J[r]??r} ${t.addThousandSeparators(o.toFixed(c))}`}}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("."),i=r[0],n=r.length>1?"."+r[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,r){if(e<0)throw new C("Amount cannot be negative for rounding.");if(r===void 0)throw new x("Invalid currency code for rounding.");let i=t.getDecimalPlaces(r),n=Math.pow(10,i);return Math.round(e*n)/n}};var B=class{baseUnitPrice;taxCategory;tiers;constructor(e){let r=new T(e.baseUnitPrice);if(!e.taxCategory)throw new O;let i=(e.tiers??[]).map(s=>({minQuantity:s.minQuantity,unitPrice:new T(s.unitPrice)})).sort((s,u)=>s.minQuantity-u.minQuantity);if(i.some(s=>s.minQuantity<=0))throw new U;let o=i.some(s=>s.unitPrice.getCurrency()!==r.getCurrency()),c=i.some((s,u)=>u>0&&s.unitPrice.compareTo(i[u-1].unitPrice)>0),l=i[0]?.unitPrice.compareTo(r)>0;if(o||c||l)throw new F("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=r,this.taxCategory=e.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}getApplicableTier(e){if(e<=0)throw new z;for(let r=this.tiers.length-1;r>=0;r--)if(e>=this.tiers[r].minQuantity){let i=this.tiers[r];return {minQuantity:i.minQuantity,unitPrice:i.unitPrice}}throw new _(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}};var h=class t extends P{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 f("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 n of i){let[o,c]=n.split(":");c.startsWith("c+")?r[o]={name:c.slice(2)}:r[o]=c;}return r}catch(r){throw new f(r?.message)}}constructor(e,r=new Date){super(e,r),this.id=e.id,this.key=e.key,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((n,o)=>(e.pricing[o]&&(n[o]=new B(e.pricing[o])),n),{}),this.targetGender=e.targetGender,this.attributes=g.deepClone(e.attributes),this.specifications=g.deepClone(e.specifications),this.categories=g.deepClone(e.categories);let i=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new f("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let o=t.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(o))throw new R(o);return i.add(o),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new I(n.images.primary),gallery:(n.images.gallery||[]).map(c=>new I(c))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?g.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[A[e]]??this.name.en:g.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[A[e]]??this.description.en:g.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[A[e]]??this.slug.en:g.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return g.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:g.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let r=t.generateSelectionAttributesKey(e),i=this.variants.find(n=>t.generateSelectionAttributesKey(n.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 g.deepClone(this.categories)}getSpecifications(e){return e?g.deepClone(this.specifications[e]??this.specifications[A[e]]??this.specifications.en):g.deepClone(this.specifications)}getSearchTags(e){return e?g.deepClone(this.searchTags[e]??this.searchTags[A[e]]??this.searchTags.en):g.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((r,i)=>(this.pricing[i]&&(r[i]=this.pricing[i]?.getDetails()),r),{}),attributes:this.getAttributes(),variants:this.variants.map(r=>({sku:r.sku,selectionAttributes:g.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 f("Selection attributes are required");Object.keys(this.attributes).forEach(r=>{if(r.toLowerCase()==="size")return;let i=this.attributes[r],n=e[r];if(n===void 0)throw new f(`Selection attribute '${r}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new f(`Selection attribute '${r}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new f(`Selection attribute '${r}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(o=>o.name===n.name)<0)throw new f(`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)}};var ne={$id:"standards",definitions:{lowercaseText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]*$"},lowercaseText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,10}$"},lowercaseText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,16}$"},lowercaseText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,30}$"},lowercaseText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,50}$"},lowercaseText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,256}$"},text:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).*$"},text10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,10}$"},text16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,16}$"},text30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,30}$"},text50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,50}$"},text256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,256}$"},requiredText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).+$"},requiredText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,10}$"},requiredText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,16}$"},requiredText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,30}$"},requiredText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,50}$"},requiredText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,256}$"},url:{type:"string",pattern:"^https://[^\\s/$.?#].[^\\s]*$",maxLength:2048},uuid:{type:"string",minLength:1,pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"},productKey:{type:"string",pattern:h.productKeyRegex.source},productSku:{type:"string",pattern:h.productSKURegex.source},genderCategory:{type:"string",enum:Object.values(k)},price:{type:"object",properties:{amount:{type:"number",minimum:0},currency:{$ref:"#/definitions/currency"}},additionalProperties:!1,required:["amount","currency"]},color:{type:"object",properties:{name:{type:"string"},hex:{type:"string"}},additionalProperties:!1,required:["name"]},attributeValue:{oneOf:[{type:"string"},{$ref:"#/definitions/color"}]},selectionAttributes:{type:"object",properties:{color:{$ref:"#/definitions/color"}},required:["color"],additionalProperties:{$ref:"#/definitions/attributeValue"}},firstName:{$ref:"#/definitions/requiredText30"},lastName:{$ref:"#/definitions/text30"},company:{$ref:"#/definitions/text50"},phone:{type:"string",pattern:"^[0-9]{10}$"},email:{type:"string",pattern:"^[^\\s]+@[^\\s]+\\.[^\\s]+$"},addressLine1:{$ref:"#/definitions/requiredText50"},addressLine2:{$ref:"#/definitions/text50"},city:{$ref:"#/definitions/requiredText30"},postalCode:{$ref:"#/definitions/requiredText16"},state:{type:"string",enum:["AP","AR","AS","BR","CT","GA","GJ","HR","HP","JH","KA","KL","MP","MH","MN","ML","MZ","NL","OR","PB","RJ","SK","TN","TG","TR","UP","UT","WB","AN","CH","DH","LD","DL","PY","LA","JK"]},country:{type:"string",enum:Object.values(V)},currency:{type:"string",enum:Object.values(D)},locale:{type:"string",enum:Object.values(w)},language:{type:"string",enum:Object.values($)},localeOrLanguage:{type:"string",enum:[...Object.values(w),...Object.values($)]},addressType:{type:"string",enum:["shipping","billing","billing&shipping"]},address:{type:"object",properties:{firstName:{$ref:"standards#/definitions/firstName"},lastName:{$ref:"standards#/definitions/lastName"},company:{$ref:"standards#/definitions/company"},phone:{$ref:"standards#/definitions/phone"},email:{$ref:"standards#/definitions/email"},addressLine1:{$ref:"standards#/definitions/addressLine1"},addressLine2:{$ref:"standards#/definitions/addressLine2"},city:{$ref:"standards#/definitions/city"},postalCode:{$ref:"standards#/definitions/postalCode"},state:{$ref:"standards#/definitions/state"},country:{$ref:"standards#/definitions/country"}},required:["firstName","lastName","phone","email","addressLine1","postalCode","state","country"]}}};var he={getStandardSchemaDefinition(){return ne}},be=he;var N=Object.freeze({INVALID_UUID:"Invalid UUID",INVALID_EMAIL:"Invalid Email",INVALID_TOKEN:"Invalid Token",TOKEN_EXPIRED:"Token Expired",INVALID_VERIFIER:"Invalid Verifier",INVALID_PERMISSIONS:"Invalid Permissions",INVALID_AUTH_TYPE:"Invalid Authorization Type",USER_PRIVATE_KEY_NOT_FOUND:"User Private Key Not Found",USER_PUBLIC_KEY_NOT_FOUND:"User Public Key Not Found",ANONYMOUS_PRIVATE_KEY_NOT_FOUND:"Anonymous Private Key Not Found",ANONYMOUS_PUBLIC_KEY_NOT_FOUND:"Anonymous Public Key Not Found",SYSTEM_PRIVATE_KEY_NOT_FOUND:"System Private Key Not Found",SYSTEM_PUBLIC_KEY_NOT_FOUND:"System Public Key Not Found",ADMIN_PRIVATE_KEY_NOT_FOUND:"Admin Private Key Not Found",ADMIN_PUBLIC_KEY_NOT_FOUND:"Admin Public Key Not Found",SECRET_TOKEN_NOT_FOUND:"Secret Token Not Found",ANONYMOUS_SESSION_NOT_ALLOWED:"Anonymous Session Not Allowed",USER_SESSION_NOT_ALLOWED:"User Session Not Allowed",SYSTEM_SESSION_NOT_ALLOWED:"System Session Not Allowed",CDN_SESSION_NOT_ALLOWED:"CDN Session Not Allowed",INTERNAL_SERVER_ERROR:"Internal Server Error",SOMETHING_WENT_WRONG:"Something went wrong",AUTH_CONTEXT_NOT_INITIALIZED:"Auth Context not Initialized"});var S={logException:(t,e)=>{console.error(`Exception Occurred in Function: ${t}, Error: ${S.inspect(e)}`);},logError:(t,e)=>{console.error(`Error Occurred in Function: ${t}, Error: ${S.inspect(e)}`);},logWarning:(t,e)=>{console.warn(`Warning in Function: ${t} - ${S.inspect(e)}`);},logMessage:(t,e)=>{console.log(`Message in Function: ${t} - ${S.inspect(e)}`);},logInvalidPayload:(t,e)=>{console.error(`Invalid Payload received for Function: ${t}, Error: ${S.inspect(e)}`);},inspect:t=>typeof t=="string"?t:Ae__default.default.inspect(t)},m=S;var xe={handleException:(t,e,r)=>{e.knownError?(e.logError&&m.logError(t,e),r.status(e.status).json({status:e.status,error:e.error})):e.status&&e.error?(m.logException(t,e),r.status(e.status).json({error:e.errorMessage||JSON.stringify(e.error),status:e.status})):(m.logException(t,e),r.status(500).json({status:500,error:N.INTERNAL_SERVER_ERROR}));},generateResponse:(t,e,r)=>({status:t,data:e,error:r}),generateError:(t,e,r=!0,i=!1)=>({status:t,error:e,knownError:r,logError:i})},Ie=xe;var Te=async(t,e,r="GET",i={},n)=>{let o={method:r,headers:{"Content-Type":"application/json",...i}};r!=="GET"&&n&&(o.body=JSON.stringify(n));let c=`${t}${e?"/"+e:""}`,l=c.includes("api.xetile.com")||c.includes("localhost");try{let s=await fetch(c,o);if(!s.ok){let b,K=await s.text();try{b=JSON.parse(K);}catch{b={status:s.status,error:K||s.statusText},m.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${c}. Raw text: ${K}`);}throw {status:s.status,statusText:s.statusText,error:b}}let u=await s.json();return m.logMessage("Fetch",`API call successful: URL-${c}, Status- ${s.status}`),{status:s.status,statusText:s.statusText,data:l?u.data:u}}catch(s){throw m.logError("Fetch",`API call failed: URL-${c}, Status- ${s.status||500}, Error- ${m.inspect(s.error||s)}`),{status:s.status||500,statusText:s.statusText||N.INTERNAL_SERVER_ERROR,error:s.error||{status:s.status||500,error:s.statusText||N.SOMETHING_WENT_WRONG}}}},Se=Te;var W=class{cache=new Map;maxSize;ttl;cleanupInterval;constructor(e=1e3,r=5*60*1e3){if(!Number.isFinite(e)||e<1)throw new RangeError("maxSize must be a finite number greater than or equal to 1.");if(!Number.isFinite(r)||r<1)throw new RangeError("ttl must be a finite number greater than or equal to 1.");this.maxSize=e,this.ttl=r,this.cleanupInterval=setInterval(()=>this.cleanup(),60*1e3),this.cleanupInterval.unref&&this.cleanupInterval.unref();}cleanup(){let e=Date.now();for(let[r,i]of this.cache.entries())e>=i.expiry&&this.cache.delete(r);}set(e,r){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i);}this.cache.set(e,{value:r,expiry:Date.now()+this.ttl});}get(e){let r=this.cache.get(e);if(r){if(Date.now()>=r.expiry){this.cache.delete(e);return}return this.cache.delete(e),m.logMessage("MemoryCache.get",`Successfully read cache data for key: ${e}`),this.cache.set(e,r),r.value}}dispose(){clearInterval(this.cleanupInterval);}},Pe=W;
2
- exports.Fetch=Se;exports.Logger=m;exports.MemoryCache=Pe;exports.ResponseUtility=Ie;exports.Schema=be;exports.Utils=g;//# sourceMappingURL=index.js.map
1
+ 'use strict';var se=require('crypto'),Ae=require('util');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var se__default=/*#__PURE__*/_interopDefault(se);var Ae__default=/*#__PURE__*/_interopDefault(Ae);var V=(e=>(e.IN="IN",e))(V||{}),N=(e=>(e.INR="INR",e))(N||{}),w=(t=>(t["en-IN"]="en-IN",t["kn-IN"]="kn-IN",t))(w||{}),$=(r=>(r.en="en",r.kn="kn",r))($||{}),A={"en-IN":"en","kn-IN":"kn"};var J={INR:"\u20B9"},Z={INR:"en-IN"},k=(l=>(l.MALE="Male",l.FEMALE="Female",l.UNISEX="Unisex",l.KIDS="Kids",l.BOY="Boy",l.GIRL="Girl",l.GENERAL="General",l))(k||{});var M=new Uint8Array(256),R=M.length;function G(){return R>M.length-16&&(se__default.default.randomFillSync(M),R=0),M.slice(R,R+=16)}var X=/^(?:[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 oe(t){return typeof t=="string"&&X.test(t)}var ee=oe;var d=[];for(let t=0;t<256;++t)d.push((t+256).toString(16).slice(1));function L(t,e=0){return d[t[e+0]]+d[t[e+1]]+d[t[e+2]]+d[t[e+3]]+"-"+d[t[e+4]]+d[t[e+5]]+"-"+d[t[e+6]]+d[t[e+7]]+"-"+d[t[e+8]]+d[t[e+9]]+"-"+d[t[e+10]]+d[t[e+11]]+d[t[e+12]]+d[t[e+13]]+d[t[e+14]]+d[t[e+15]]}function ae(t){if(!ee(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 te=ae;function ce(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var ue="6ba7b810-9dad-11d1-80b4-00c04fd430c8",le="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function j(t,e,r){function i(n,o,c,l){var s;if(typeof n=="string"&&(n=ce(n)),typeof o=="string"&&(o=te(o)),((s=o)===null||s===void 0?void 0:s.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let u=new Uint8Array(16+n.length);if(u.set(o),u.set(n,o.length),u=r(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,c){l=l||0;for(let b=0;b<16;++b)c[l+b]=u[b];return c}return L(u)}try{i.name=t;}catch{}return i.DNS=ue,i.URL=le,i}var Q={randomUUID:se__default.default.randomUUID};function ge(t,e,r){if(Q.randomUUID&&!e&&!t)return Q.randomUUID();t=t||{};let i=t.random||(t.rng||G)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){r=r||0;for(let n=0;n<16;++n)e[r+n]=i[n];return e}return L(i)}var q=ge;function me(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),se__default.default.createHash("sha1").update(t).digest()}var re=me;var fe=j("v5",80,re),Y=fe;var ye={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?Y(t,e):q(),generateSearchId:(t,e)=>`${t}#${h.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:t=>{let[e,r]=t.split("#");return {key:e,selectionAttributes:h.parseSelectionAttributesKey(r)}},deepClone(t){return structuredClone(t)}},g=ye;var ie=t=>structuredClone(t),H=class{customFields;constructor(e,r=new Date){this.customFields={...e.customFields};}getCustomField(e){let r=this.customFields[e];return r==null?r:ie(r)}setCustomField(e,r){this.customFields[e]=r;}getAllCustomFields(){return ie(this.customFields)}},S=class extends H{version;createdAt;modifiedAt;modifiedBy;constructor(e,r=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():r.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():r.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,r,i,n){this.modifiedBy={id:e,authType:r,requestId:i,lambdaName:n};}};var v=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var f=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var O=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},U=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},F=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},z=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},_=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var P=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},x=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},y=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},p=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},C=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};var I=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw new C("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,r){if(r===void 0){if(e==="original")throw new C("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=r;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var T=class t{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new P("Amount cannot be negative.");if(!e.currency)throw new x("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 y("Cannot compare prices in different currencies.")}else throw new p("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 y("Cannot add prices in different currencies.")}else throw new p("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 y("Cannot subtract prices in different currencies.")}else throw new p("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 y("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 p("Must be a non-negative number.")}divide(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new y("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 p("Must be a positive number.")}min(...e){if(e.length===0)throw new p("Must provide at least one PriceModel.");return e.reduce((r,i)=>{if(t.isPriceModel(i)){if(r.getCurrency()!==i.getCurrency())throw new y("Cannot compare prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return r.compareTo(i)<0?r:i},this)}max(...e){if(e.length===0)throw new p("Must provide at least one PriceModel.");return e.reduce((r,i)=>{if(t.isPriceModel(i)){if(r.getCurrency()!==i.getCurrency())throw new y("Cannot compare prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return r.compareTo(i)>0?r:i},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,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=Z[r];if(!r||!n)throw new x("Invalid currency code for formatting.");let o=e,c=i.displayAsInteger?0:t.getDecimalPlaces(r),l={style:i.style??"currency",currency:r,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:c,maximumFractionDigits:c};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,l).format(o)}catch(s){return console.error(`Error formatting price for currency "${r}" and locale "${n}":`,s),`${J[r]??r} ${t.addThousandSeparators(o.toFixed(c))}`}}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("."),i=r[0],n=r.length>1?"."+r[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,r){if(e<0)throw new P("Amount cannot be negative for rounding.");if(r===void 0)throw new x("Invalid currency code for rounding.");let i=t.getDecimalPlaces(r),n=Math.pow(10,i);return Math.round(e*n)/n}};var B=class{baseUnitPrice;taxCategory;tiers;constructor(e){let r=new T(e.baseUnitPrice);if(!e.taxCategory)throw new O;let i=(e.tiers??[]).map(s=>({minQuantity:s.minQuantity,unitPrice:new T(s.unitPrice)})).sort((s,u)=>s.minQuantity-u.minQuantity);if(i.some(s=>s.minQuantity<=0))throw new U;let o=i.some(s=>s.unitPrice.getCurrency()!==r.getCurrency()),c=i.some((s,u)=>u>0&&s.unitPrice.compareTo(i[u-1].unitPrice)>0),l=i[0]?.unitPrice.compareTo(r)>0;if(o||c||l)throw new F("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=r,this.taxCategory=e.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}getApplicableTier(e){if(e<=0)throw new z;for(let r=this.tiers.length-1;r>=0;r--)if(e>=this.tiers[r].minQuantity){let i=this.tiers[r];return {minQuantity:i.minQuantity,unitPrice:i.unitPrice}}throw new _(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}};var h=class t extends S{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 f("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 n of i){let[o,c]=n.split(":");c.startsWith("c+")?r[o]={name:c.slice(2)}:r[o]=c;}return r}catch(r){throw new f(r?.message)}}constructor(e,r=new Date){super(e,r),this.id=e.id,this.key=e.key,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((n,o)=>(e.pricing[o]&&(n[o]=new B(e.pricing[o])),n),{}),this.targetGender=e.targetGender,this.attributes=g.deepClone(e.attributes),this.specifications=g.deepClone(e.specifications),this.categories=g.deepClone(e.categories);let i=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new f("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let o=t.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(o))throw new v(o);return i.add(o),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new I(n.images.primary),gallery:(n.images.gallery||[]).map(c=>new I(c))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?g.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[A[e]]??this.name.en:g.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[A[e]]??this.description.en:g.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[A[e]]??this.slug.en:g.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return g.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:g.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let r=t.generateSelectionAttributesKey(e),i=this.variants.find(n=>t.generateSelectionAttributesKey(n.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 g.deepClone(this.categories)}getSpecifications(e){return e?g.deepClone(this.specifications[e]??this.specifications[A[e]]??this.specifications.en):g.deepClone(this.specifications)}getSearchTags(e){return e?g.deepClone(this.searchTags[e]??this.searchTags[A[e]]??this.searchTags.en):g.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((r,i)=>(this.pricing[i]&&(r[i]=this.pricing[i]?.getDetails()),r),{}),attributes:this.getAttributes(),variants:this.variants.map(r=>({sku:r.sku,selectionAttributes:g.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 f("Selection attributes are required");Object.keys(this.attributes).forEach(r=>{if(r.toLowerCase()==="size")return;let i=this.attributes[r],n=e[r];if(n===void 0)throw new f(`Selection attribute '${r}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new f(`Selection attribute '${r}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new f(`Selection attribute '${r}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(o=>o.name===n.name)<0)throw new f(`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)}};var ne={$id:"standards",definitions:{lowercaseText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]*$"},lowercaseText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,10}$"},lowercaseText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,16}$"},lowercaseText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,30}$"},lowercaseText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,50}$"},lowercaseText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,256}$"},text:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).*$"},text10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,10}$"},text16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,16}$"},text30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,30}$"},text50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,50}$"},text256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,256}$"},requiredText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).+$"},requiredText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,10}$"},requiredText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,16}$"},requiredText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,30}$"},requiredText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,50}$"},requiredText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,256}$"},url:{type:"string",pattern:"^https://[^\\s/$.?#].[^\\s]*$",maxLength:2048},uuid:{type:"string",minLength:1,pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"},productKey:{type:"string",pattern:h.productKeyRegex.source},productSku:{type:"string",pattern:h.productSKURegex.source},genderCategory:{type:"string",enum:Object.values(k)},price:{type:"object",properties:{amount:{type:"number",minimum:0},currency:{$ref:"#/definitions/currency"}},additionalProperties:!1,required:["amount","currency"]},color:{type:"object",properties:{name:{type:"string"},hex:{type:"string"}},additionalProperties:!1,required:["name"]},attributeValue:{oneOf:[{type:"string"},{$ref:"#/definitions/color"}]},selectionAttributes:{type:"object",properties:{color:{$ref:"#/definitions/color"}},required:["color"],additionalProperties:{$ref:"#/definitions/attributeValue"}},firstName:{$ref:"#/definitions/requiredText30"},lastName:{$ref:"#/definitions/text30"},company:{$ref:"#/definitions/text50"},phone:{type:"string",pattern:"^[0-9]{10}$"},e164Phone:{type:"string",pattern:"^\\+[1-9]\\d{1,14}$"},email:{type:"string",pattern:"^[^\\s]+@[^\\s]+\\.[^\\s]+$"},addressLine1:{$ref:"#/definitions/requiredText50"},addressLine2:{$ref:"#/definitions/text50"},city:{$ref:"#/definitions/requiredText30"},postalCode:{$ref:"#/definitions/requiredText16"},state:{type:"string",enum:["AP","AR","AS","BR","CT","GA","GJ","HR","HP","JH","KA","KL","MP","MH","MN","ML","MZ","NL","OR","PB","RJ","SK","TN","TG","TR","UP","UT","WB","AN","CH","DH","LD","DL","PY","LA","JK"]},country:{type:"string",enum:Object.values(V)},currency:{type:"string",enum:Object.values(N)},locale:{type:"string",enum:Object.values(w)},language:{type:"string",enum:Object.values($)},localeOrLanguage:{type:"string",enum:[...Object.values(w),...Object.values($)]},addressType:{type:"string",enum:["shipping","billing","billing&shipping"]},address:{type:"object",properties:{firstName:{$ref:"standards#/definitions/firstName"},lastName:{$ref:"standards#/definitions/lastName"},company:{$ref:"standards#/definitions/company"},phone:{$ref:"standards#/definitions/phone"},email:{$ref:"standards#/definitions/email"},addressLine1:{$ref:"standards#/definitions/addressLine1"},addressLine2:{$ref:"standards#/definitions/addressLine2"},city:{$ref:"standards#/definitions/city"},postalCode:{$ref:"standards#/definitions/postalCode"},state:{$ref:"standards#/definitions/state"},country:{$ref:"standards#/definitions/country"}},required:["firstName","lastName","phone","email","addressLine1","postalCode","state","country"]}}};var he={getStandardSchemaDefinition(){return ne}},be=he;var D=Object.freeze({INVALID_UUID:"Invalid UUID",INVALID_EMAIL:"Invalid Email",INVALID_TOKEN:"Invalid Token",TOKEN_EXPIRED:"Token Expired",INVALID_VERIFIER:"Invalid Verifier",INVALID_PERMISSIONS:"Invalid Permissions",INVALID_AUTH_TYPE:"Invalid Authorization Type",USER_PRIVATE_KEY_NOT_FOUND:"User Private Key Not Found",USER_PUBLIC_KEY_NOT_FOUND:"User Public Key Not Found",ANONYMOUS_PRIVATE_KEY_NOT_FOUND:"Anonymous Private Key Not Found",ANONYMOUS_PUBLIC_KEY_NOT_FOUND:"Anonymous Public Key Not Found",SYSTEM_PRIVATE_KEY_NOT_FOUND:"System Private Key Not Found",SYSTEM_PUBLIC_KEY_NOT_FOUND:"System Public Key Not Found",ADMIN_PRIVATE_KEY_NOT_FOUND:"Admin Private Key Not Found",ADMIN_PUBLIC_KEY_NOT_FOUND:"Admin Public Key Not Found",SECRET_TOKEN_NOT_FOUND:"Secret Token Not Found",ANONYMOUS_SESSION_NOT_ALLOWED:"Anonymous Session Not Allowed",USER_SESSION_NOT_ALLOWED:"User Session Not Allowed",SYSTEM_SESSION_NOT_ALLOWED:"System Session Not Allowed",CDN_SESSION_NOT_ALLOWED:"CDN Session Not Allowed",INTERNAL_SERVER_ERROR:"Internal Server Error",SOMETHING_WENT_WRONG:"Something went wrong",AUTH_CONTEXT_NOT_INITIALIZED:"Auth Context not Initialized"});var E={logException:(t,e)=>{console.error(`Exception Occurred in Function: ${t}, Error: ${E.inspect(e)}`);},logError:(t,e)=>{console.error(`Error Occurred in Function: ${t}, Error: ${E.inspect(e)}`);},logWarning:(t,e)=>{console.warn(`Warning in Function: ${t} - ${E.inspect(e)}`);},logMessage:(t,e)=>{console.log(`Message in Function: ${t} - ${E.inspect(e)}`);},logInvalidPayload:(t,e)=>{console.error(`Invalid Payload received for Function: ${t}, Error: ${E.inspect(e)}`);},inspect:t=>typeof t=="string"?t:Ae__default.default.inspect(t)},m=E;var xe={handleException:(t,e,r)=>{e.knownError?(e.logError&&m.logError(t,e),r.status(e.status).json({status:e.status,error:e.error})):e.status&&e.error?(m.logException(t,e),r.status(e.status).json({error:e.errorMessage||JSON.stringify(e.error),status:e.status})):(m.logException(t,e),r.status(500).json({status:500,error:D.INTERNAL_SERVER_ERROR}));},generateResponse:(t,e,r)=>({status:t,data:e,error:r}),generateError:(t,e,r=!0,i=!1)=>({status:t,error:e,knownError:r,logError:i})},Ie=xe;var Te=async(t,e,r="GET",i={},n)=>{let o={method:r,headers:{"Content-Type":"application/json",...i}};r!=="GET"&&n&&(o.body=JSON.stringify(n));let c=`${t}${e?"/"+e:""}`,l=c.includes("api.xetile.com")||c.includes("localhost");try{let s=await fetch(c,o);if(!s.ok){let b,K=await s.text();try{b=JSON.parse(K);}catch{b={status:s.status,error:K||s.statusText},m.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${c}. Raw text: ${K}`);}throw {status:s.status,statusText:s.statusText,error:b}}let u=await s.json();return m.logMessage("Fetch",`API call successful: URL-${c}, Status- ${s.status}`),{status:s.status,statusText:s.statusText,data:l?u.data:u}}catch(s){throw m.logError("Fetch",`API call failed: URL-${c}, Status- ${s.status||500}, Error- ${m.inspect(s.error||s)}`),{status:s.status||500,statusText:s.statusText||D.INTERNAL_SERVER_ERROR,error:s.error||{status:s.status||500,error:s.statusText||D.SOMETHING_WENT_WRONG}}}},Ee=Te;var W=class{cache=new Map;maxSize;ttl;cleanupInterval;constructor(e=1e3,r=5*60*1e3){if(!Number.isFinite(e)||e<1)throw new RangeError("maxSize must be a finite number greater than or equal to 1.");if(!Number.isFinite(r)||r<1)throw new RangeError("ttl must be a finite number greater than or equal to 1.");this.maxSize=e,this.ttl=r,this.cleanupInterval=setInterval(()=>this.cleanup(),60*1e3),this.cleanupInterval.unref&&this.cleanupInterval.unref();}cleanup(){let e=Date.now();for(let[r,i]of this.cache.entries())e>=i.expiry&&this.cache.delete(r);}set(e,r){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i);}this.cache.set(e,{value:r,expiry:Date.now()+this.ttl});}get(e){let r=this.cache.get(e);if(r){if(Date.now()>=r.expiry){this.cache.delete(e);return}return this.cache.delete(e),m.logMessage("MemoryCache.get",`Successfully read cache data for key: ${e}`),this.cache.set(e,r),r.value}}dispose(){clearInterval(this.cleanupInterval);}},Se=W;
2
+ exports.Fetch=Ee;exports.Logger=m;exports.MemoryCache=Se;exports.ResponseUtility=Ie;exports.Schema=be;exports.Utils=g;//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map