b23-lib 2.0.21 → 2.1.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 (85) 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/Auth/index.mjs.map +1 -1
  5. package/dist/Classes/Address.js +1 -1
  6. package/dist/Classes/Address.js.map +1 -1
  7. package/dist/Classes/Address.mjs +1 -1
  8. package/dist/Classes/Base.d.mts +30 -25
  9. package/dist/Classes/Base.d.ts +30 -25
  10. package/dist/Classes/Base.js +1 -1
  11. package/dist/Classes/Base.js.map +1 -1
  12. package/dist/Classes/Base.mjs +1 -1
  13. package/dist/Classes/Cart.js +2 -1
  14. package/dist/Classes/Cart.js.map +1 -1
  15. package/dist/Classes/Cart.mjs +1 -1
  16. package/dist/Classes/Coupon.js +1 -1
  17. package/dist/Classes/Coupon.js.map +1 -1
  18. package/dist/Classes/Coupon.mjs +1 -1
  19. package/dist/Classes/Customer.js +1 -1
  20. package/dist/Classes/Customer.js.map +1 -1
  21. package/dist/Classes/Customer.mjs +1 -1
  22. package/dist/Classes/Customer.mjs.map +1 -1
  23. package/dist/Classes/CustomerAddress.js +1 -1
  24. package/dist/Classes/CustomerAddress.js.map +1 -1
  25. package/dist/Classes/CustomerAddress.mjs +1 -1
  26. package/dist/Classes/CustomerAddress.mjs.map +1 -1
  27. package/dist/Classes/Inventory.js +1 -1
  28. package/dist/Classes/Inventory.js.map +1 -1
  29. package/dist/Classes/Inventory.mjs +1 -1
  30. package/dist/Classes/Inventory.mjs.map +1 -1
  31. package/dist/Classes/LineItem.d.mts +3 -3
  32. package/dist/Classes/LineItem.d.ts +3 -3
  33. package/dist/Classes/LineItem.js +2 -1
  34. package/dist/Classes/LineItem.js.map +1 -1
  35. package/dist/Classes/LineItem.mjs +1 -1
  36. package/dist/Classes/Order.js +2 -1
  37. package/dist/Classes/Order.js.map +1 -1
  38. package/dist/Classes/Order.mjs +1 -1
  39. package/dist/Classes/Payment.js +1 -1
  40. package/dist/Classes/Payment.js.map +1 -1
  41. package/dist/Classes/Payment.mjs +1 -1
  42. package/dist/Classes/Product.js +1 -1
  43. package/dist/Classes/Product.js.map +1 -1
  44. package/dist/Classes/Product.mjs +1 -1
  45. package/dist/Classes/ShoppingContainer.js +2 -1
  46. package/dist/Classes/ShoppingContainer.js.map +1 -1
  47. package/dist/Classes/ShoppingContainer.mjs +1 -1
  48. package/dist/Classes/TaxRule.d.mts +46 -1
  49. package/dist/Classes/TaxRule.d.ts +46 -1
  50. package/dist/Classes/TaxRule.js +2 -1
  51. package/dist/Classes/TaxRule.js.map +1 -1
  52. package/dist/Classes/TaxRule.mjs +1 -1
  53. package/dist/chunk-6KCJVEZD.mjs +2 -0
  54. package/dist/chunk-6KCJVEZD.mjs.map +1 -0
  55. package/dist/chunk-7NLMXN4H.mjs +2 -0
  56. package/dist/chunk-7NLMXN4H.mjs.map +1 -0
  57. package/dist/chunk-FGXEJC4J.mjs +2 -0
  58. package/dist/{chunk-5WRSQPQ5.mjs.map → chunk-FGXEJC4J.mjs.map} +1 -1
  59. package/dist/chunk-GMGMQ2NX.mjs +2 -0
  60. package/dist/{chunk-I3IWW4V2.mjs.map → chunk-GMGMQ2NX.mjs.map} +1 -1
  61. package/dist/chunk-OIR5JBJY.mjs +2 -0
  62. package/dist/chunk-OIR5JBJY.mjs.map +1 -0
  63. package/dist/chunk-TUT4BB3Z.mjs +3 -0
  64. package/dist/chunk-TUT4BB3Z.mjs.map +1 -0
  65. package/dist/{chunk-5KD2EW7O.mjs → chunk-YSUBOEFT.mjs} +2 -2
  66. package/dist/{chunk-5KD2EW7O.mjs.map → chunk-YSUBOEFT.mjs.map} +1 -1
  67. package/dist/{chunk-K6Q6YDUX.mjs → chunk-ZAHR3SJ2.mjs} +2 -2
  68. package/dist/{chunk-K6Q6YDUX.mjs.map → chunk-ZAHR3SJ2.mjs.map} +1 -1
  69. package/dist/index.d.mts +2 -24
  70. package/dist/index.d.ts +2 -24
  71. package/dist/index.js +2 -2
  72. package/dist/index.js.map +1 -1
  73. package/dist/index.mjs +2 -2
  74. package/dist/index.mjs.map +1 -1
  75. package/package.json +1 -1
  76. package/dist/chunk-55SOBG62.mjs +0 -2
  77. package/dist/chunk-55SOBG62.mjs.map +0 -1
  78. package/dist/chunk-5WRSQPQ5.mjs +0 -2
  79. package/dist/chunk-AMIRIUMH.mjs +0 -2
  80. package/dist/chunk-AMIRIUMH.mjs.map +0 -1
  81. package/dist/chunk-I3IWW4V2.mjs +0 -2
  82. package/dist/chunk-QUC4ZPSY.mjs +0 -2
  83. package/dist/chunk-QUC4ZPSY.mjs.map +0 -1
  84. package/dist/chunk-YOEUA6R6.mjs +0 -2
  85. package/dist/chunk-YOEUA6R6.mjs.map +0 -1
@@ -1,2 +1,2 @@
1
- export{a as default}from'../chunk-5WRSQPQ5.mjs';import'../chunk-QUC4ZPSY.mjs';import'../chunk-YOEUA6R6.mjs';import'../chunk-5KD2EW7O.mjs';import'../chunk-I3IWW4V2.mjs';import'../chunk-K6Q6YDUX.mjs';import'../chunk-ZVLJ5BAG.mjs';import'../chunk-R32ZSPV6.mjs';import'../chunk-72DR3HF2.mjs';import'../chunk-7LEGYAOJ.mjs';import'../chunk-DGFO2MH6.mjs';import'../chunk-55SOBG62.mjs';//# sourceMappingURL=ShoppingContainer.mjs.map
1
+ export{a as default}from'../chunk-FGXEJC4J.mjs';import'../chunk-7NLMXN4H.mjs';import'../chunk-TUT4BB3Z.mjs';import'../chunk-YSUBOEFT.mjs';import'../chunk-GMGMQ2NX.mjs';import'../chunk-ZAHR3SJ2.mjs';import'../chunk-ZVLJ5BAG.mjs';import'../chunk-R32ZSPV6.mjs';import'../chunk-72DR3HF2.mjs';import'../chunk-7LEGYAOJ.mjs';import'../chunk-DGFO2MH6.mjs';import'../chunk-6KCJVEZD.mjs';//# sourceMappingURL=ShoppingContainer.mjs.map
2
2
  //# sourceMappingURL=ShoppingContainer.mjs.map
@@ -14,6 +14,43 @@ type TaxSlabModel = {
14
14
  rate: number;
15
15
  };
16
16
  type TaxSlabs = TaxSlabData[];
17
+ type TaxRateBreakdown = {
18
+ totalRate: number;
19
+ label: string;
20
+ components: {
21
+ rate: number;
22
+ label: string;
23
+ type: 'IGST' | 'CGST' | 'SGST' | 'GST' | string;
24
+ }[];
25
+ };
26
+ type TaxFormattingVariant = 'short' | 'long' | 'detailed' | 'percentageOnly';
27
+ interface TaxFormattingOptions {
28
+ variant?: TaxFormattingVariant;
29
+ includeTaxesSuffix?: boolean;
30
+ merchantState?: string;
31
+ customerState?: string;
32
+ multiline?: boolean;
33
+ separator?: string;
34
+ }
35
+ /**
36
+ * Interface for tax system specific formatting logic.
37
+ */
38
+ interface ITaxSystemFormatter {
39
+ getBreakdown(rate: number, country: CountryCode, options?: TaxFormattingOptions): TaxRateBreakdown;
40
+ getLongName(country: CountryCode): string;
41
+ }
42
+ /**
43
+ * Formatter for GST (Goods and Services Tax).
44
+ * Handles India-specific components (CGST/SGST/IGST).
45
+ */
46
+ declare class GSTFormatter implements ITaxSystemFormatter {
47
+ getBreakdown(rate: number, country: CountryCode, options?: TaxFormattingOptions): TaxRateBreakdown;
48
+ getLongName(): string;
49
+ }
50
+ /**
51
+ * Registry to manage and provide tax formatters.
52
+ */
53
+ declare const TaxFormatterRegistry: Record<string, ITaxSystemFormatter>;
17
54
  type TaxRuleAttributes = {
18
55
  taxRuleId: string;
19
56
  taxSystem: TaxSystem;
@@ -73,6 +110,14 @@ declare class TaxRuleModel extends BaseModel {
73
110
  merchantState?: string;
74
111
  customerState?: string;
75
112
  }): string;
113
+ /**
114
+ * Returns a detailed breakdown of the tax rate into its components (e.g., CGST/SGST).
115
+ */
116
+ getTaxRateBreakdown(unitPrice: PriceModel, options?: TaxFormattingOptions): TaxRateBreakdown;
117
+ /**
118
+ * Formats a tax rate based on versatile options for UI use cases.
119
+ */
120
+ getFormattedTaxRate(unitPrice: PriceModel, options?: TaxFormattingOptions): string;
76
121
  /**
77
122
  * Static method to find the applicable tax rate from a list of slabs.
78
123
  */
@@ -91,4 +136,4 @@ declare class TaxRuleModel extends BaseModel {
91
136
  }): string;
92
137
  }
93
138
 
94
- export { type TaxRuleAttributes, type TaxRuleData, TaxRuleModel, type TaxSlabData, type TaxSlabModel, type TaxSlabs };
139
+ export { GSTFormatter, type ITaxSystemFormatter, TaxFormatterRegistry, type TaxFormattingOptions, type TaxFormattingVariant, type TaxRateBreakdown, type TaxRuleAttributes, type TaxRuleData, TaxRuleModel, type TaxSlabData, type TaxSlabModel, type TaxSlabs };
@@ -14,6 +14,43 @@ type TaxSlabModel = {
14
14
  rate: number;
15
15
  };
16
16
  type TaxSlabs = TaxSlabData[];
17
+ type TaxRateBreakdown = {
18
+ totalRate: number;
19
+ label: string;
20
+ components: {
21
+ rate: number;
22
+ label: string;
23
+ type: 'IGST' | 'CGST' | 'SGST' | 'GST' | string;
24
+ }[];
25
+ };
26
+ type TaxFormattingVariant = 'short' | 'long' | 'detailed' | 'percentageOnly';
27
+ interface TaxFormattingOptions {
28
+ variant?: TaxFormattingVariant;
29
+ includeTaxesSuffix?: boolean;
30
+ merchantState?: string;
31
+ customerState?: string;
32
+ multiline?: boolean;
33
+ separator?: string;
34
+ }
35
+ /**
36
+ * Interface for tax system specific formatting logic.
37
+ */
38
+ interface ITaxSystemFormatter {
39
+ getBreakdown(rate: number, country: CountryCode, options?: TaxFormattingOptions): TaxRateBreakdown;
40
+ getLongName(country: CountryCode): string;
41
+ }
42
+ /**
43
+ * Formatter for GST (Goods and Services Tax).
44
+ * Handles India-specific components (CGST/SGST/IGST).
45
+ */
46
+ declare class GSTFormatter implements ITaxSystemFormatter {
47
+ getBreakdown(rate: number, country: CountryCode, options?: TaxFormattingOptions): TaxRateBreakdown;
48
+ getLongName(): string;
49
+ }
50
+ /**
51
+ * Registry to manage and provide tax formatters.
52
+ */
53
+ declare const TaxFormatterRegistry: Record<string, ITaxSystemFormatter>;
17
54
  type TaxRuleAttributes = {
18
55
  taxRuleId: string;
19
56
  taxSystem: TaxSystem;
@@ -73,6 +110,14 @@ declare class TaxRuleModel extends BaseModel {
73
110
  merchantState?: string;
74
111
  customerState?: string;
75
112
  }): string;
113
+ /**
114
+ * Returns a detailed breakdown of the tax rate into its components (e.g., CGST/SGST).
115
+ */
116
+ getTaxRateBreakdown(unitPrice: PriceModel, options?: TaxFormattingOptions): TaxRateBreakdown;
117
+ /**
118
+ * Formats a tax rate based on versatile options for UI use cases.
119
+ */
120
+ getFormattedTaxRate(unitPrice: PriceModel, options?: TaxFormattingOptions): string;
76
121
  /**
77
122
  * Static method to find the applicable tax rate from a list of slabs.
78
123
  */
@@ -91,4 +136,4 @@ declare class TaxRuleModel extends BaseModel {
91
136
  }): string;
92
137
  }
93
138
 
94
- export { type TaxRuleAttributes, type TaxRuleData, TaxRuleModel, type TaxSlabData, type TaxSlabModel, type TaxSlabs };
139
+ export { GSTFormatter, type ITaxSystemFormatter, TaxFormatterRegistry, type TaxFormattingOptions, type TaxFormattingVariant, type TaxRateBreakdown, type TaxRuleAttributes, type TaxRuleData, TaxRuleModel, type TaxSlabData, type TaxSlabModel, type TaxSlabs };
@@ -1,2 +1,3 @@
1
- 'use strict';var l=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){this.customFields={...e.customFields},this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,t,r,i){this.modifiedBy={id:e,authType:t,requestId:r,lambdaName:i};}getCustomField(e){return this.customFields[e]??null}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return {...this.customFields}}};var g={INR:"\u20B9"},h={INR:"en-IN"};var p=class extends Error{constructor(e="No applicable tax slab or multiple slabs found for the given unit price."){super(`TaxSlabNotFound: ${e}`),this.name="TaxSlabNotFoundError";}},m=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},c=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},s=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},o=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}};var u=class n{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new m("Amount cannot be negative.");if(!e.currency)throw new c("Currency code is required.");this.amount=e.amount,this.currency=e.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}}compareTo(e){if(n.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot compare prices in different currencies.")}else throw new o("Must be a PriceModel instance.");return this.amount-e.getAmount()}add(e){if(n.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot add prices in different currencies.")}else throw new o("Must be a PriceModel instance.");return new n({amount:this.amount+e.getAmount(),currency:this.currency})}subtract(e){if(n.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot subtract prices in different currencies.")}else throw new o("Must be a PriceModel instance.");return new n({amount:this.amount-e.getAmount(),currency:this.currency})}multiply(e){if(n.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot multiply prices in different currencies.");return new n({amount:this.amount*e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new n({amount:this.amount*e,currency:this.currency});throw new o("Must be a non-negative number.")}divide(e){if(n.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new s("Cannot divide prices in different currencies.");return new n({amount:this.amount/e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>0)return new n({amount:this.amount/e,currency:this.currency});throw new o("Must be a positive number.")}min(...e){if(e.length===0)throw new o("Must provide at least one PriceModel.");return e.reduce((t,r)=>{if(n.isPriceModel(r)){if(t.getCurrency()!==r.getCurrency())throw new s("Cannot compare prices in different currencies.")}else throw new o("Must be a PriceModel instance.");return t.compareTo(r)<0?t:r})}max(...e){if(e.length===0)throw new o("Must provide at least one PriceModel.");return e.reduce((t,r)=>{if(n.isPriceModel(r)){if(t.getCurrency()!==r.getCurrency())throw new s("Cannot compare prices in different currencies.")}else throw new o("Must be a PriceModel instance.");return t.compareTo(r)>0?t:r})}zero(){return new n({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new n({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return n.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return n.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,t,r={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let i=h[t];if(!t||!i)throw new c("Invalid currency code for formatting.");let a=e,y=r.displayAsInteger?0:n.getDecimalPlaces(t),x={style:r.style??"currency",currency:t,signDisplay:"never",currencyDisplay:r.currencyDisplay,minimumFractionDigits:y,maximumFractionDigits:y};r.displayAsInteger&&(a=Math.ceil(a));try{return new Intl.NumberFormat(i,x).format(a)}catch(b){return console.error(`Error formatting price for currency "${t}" and locale "${i}":`,b),`${g[t]??t} ${n.addThousandSeparators(a.toFixed(y))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static addThousandSeparators(e){let t=e.split("."),r=t[0],i=t.length>1?"."+t[1]:"";return r.replace(/\B(?=(\d{3})+(?!\d))/g,",")+i}static getRoundedAmount(e,t){if(e<0)throw new m("Amount cannot be negative for rounding.");if(t===void 0)throw new c("Invalid currency code for rounding.");let r=n.getDecimalPlaces(t),i=Math.pow(10,r);return Math.round(e*i)/i}};var f=class n extends l{taxRuleId;taxSystem;taxCategory;country;slabs;effectiveFrom;effectiveTo;constructor(e,t=new Date){super(e,t),this.taxRuleId=e.taxRuleId,this.taxSystem=e.taxSystem,this.taxCategory=e.taxCategory,this.country=e.country,this.slabs=e.slabs.map(r=>({rate:r.rate,minUnitPrice:new u(r.minUnitPrice),maxUnitPrice:r.maxUnitPrice?new u(r.maxUnitPrice):void 0})),this.effectiveFrom=new Date(e.effectiveFrom),this.effectiveTo=e.effectiveTo?new Date(e.effectiveTo):void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getSlabs(){return this.slabs}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),slabs:this.getSlabs().map(e=>({rate:e.rate,minUnitPrice:e.minUnitPrice.getDetails(),maxUnitPrice:e.maxUnitPrice?e.maxUnitPrice.getDetails():void 0})),effectiveFrom:this.effectiveFrom.toISOString(),effectiveTo:this.effectiveTo?this.effectiveTo.toISOString():void 0,...super.getDetails()}}appliesTo(e,t,r=new Date){return this.taxCategory===e&&this.country===t&&this.effectiveFrom<=r&&(this.effectiveTo?this.effectiveTo>=r:!0)}getApplicableTaxRate(e){return n.getApplicableTaxRate(e,this.slabs)}getTaxRateDisplayString(e,t){let r=this.getApplicableTaxRate(e);return n.getTaxRateDisplayString(r,{taxSystem:this.taxSystem,merchantState:t?.merchantState,customerState:t?.customerState})}static getApplicableTaxRate(e,t){let r=t.filter(i=>(i.minUnitPrice===void 0||e.compareTo(i.minUnitPrice)>=0)&&(i.maxUnitPrice===void 0||e.compareTo(i.maxUnitPrice)<0));if(r.length!==1)throw new p;return r[0].rate}static getTaxRateDisplayString(e,t){let r=e*100,i=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,"");if(t.taxSystem==="GST"&&t.merchantState&&t.customerState)if(t.merchantState.toLowerCase().trim()===t.customerState.toLowerCase().trim()){let a=r/2%1===0?(r/2).toString():(r/2).toFixed(2).replace(/\.?0+$/,"");return `${a}% CGST + ${a}% SGST`}else return `${i}% IGST`;return t.taxSystem?`${i}% ${t.taxSystem}`:`${i}%`}};exports.TaxRuleModel=f;//# sourceMappingURL=TaxRule.js.map
1
+ 'use strict';var h=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){return this.customFields[e]??null}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return {...this.customFields}}},d=class extends h{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,t,r,n){this.modifiedBy={id:e,authType:t,requestId:r,lambdaName:n};}};var b={INR:"\u20B9"},S={INR:"en-IN"};var y=class extends Error{constructor(e="No applicable tax slab or multiple slabs found for the given unit price."){super(`TaxSlabNotFound: ${e}`),this.name="TaxSlabNotFoundError";}},p=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},l=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},u=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},a=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}};var m=class i{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new p("Amount cannot be negative.");if(!e.currency)throw new l("Currency code is required.");this.amount=e.amount,this.currency=e.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}}compareTo(e){if(i.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new u("Cannot compare prices in different currencies.")}else throw new a("Must be a PriceModel instance.");return this.amount-e.getAmount()}add(e){if(i.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new u("Cannot add prices in different currencies.")}else throw new a("Must be a PriceModel instance.");return new i({amount:this.amount+e.getAmount(),currency:this.currency})}subtract(e){if(i.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new u("Cannot subtract prices in different currencies.")}else throw new a("Must be a PriceModel instance.");return new i({amount:this.amount-e.getAmount(),currency:this.currency})}multiply(e){if(i.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new u("Cannot multiply prices in different currencies.");return new i({amount:this.amount*e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new i({amount:this.amount*e,currency:this.currency});throw new a("Must be a non-negative number.")}divide(e){if(i.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new u("Cannot divide prices in different currencies.");return new i({amount:this.amount/e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>0)return new i({amount:this.amount/e,currency:this.currency});throw new a("Must be a positive number.")}min(...e){if(e.length===0)throw new a("Must provide at least one PriceModel.");return e.reduce((t,r)=>{if(i.isPriceModel(r)){if(t.getCurrency()!==r.getCurrency())throw new u("Cannot compare prices in different currencies.")}else throw new a("Must be a PriceModel instance.");return t.compareTo(r)<0?t:r})}max(...e){if(e.length===0)throw new a("Must provide at least one PriceModel.");return e.reduce((t,r)=>{if(i.isPriceModel(r)){if(t.getCurrency()!==r.getCurrency())throw new u("Cannot compare prices in different currencies.")}else throw new a("Must be a PriceModel instance.");return t.compareTo(r)>0?t:r})}zero(){return new i({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new i({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return i.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return i.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,t,r={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=S[t];if(!t||!n)throw new l("Invalid currency code for formatting.");let o=e,s=r.displayAsInteger?0:i.getDecimalPlaces(t),c={style:r.style??"currency",currency:t,signDisplay:"never",currencyDisplay:r.currencyDisplay,minimumFractionDigits:s,maximumFractionDigits:s};r.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,c).format(o)}catch(x){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,x),`${b[t]??t} ${i.addThousandSeparators(o.toFixed(s))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static addThousandSeparators(e){let t=e.split("."),r=t[0],n=t.length>1?"."+t[1]:"";return r.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,t){if(e<0)throw new p("Amount cannot be negative for rounding.");if(t===void 0)throw new l("Invalid currency code for rounding.");let r=i.getDecimalPlaces(t),n=Math.pow(10,r);return Math.round(e*n)/n}};var f=class{getBreakdown(e,t,r){let n=e*100,o=n%1===0?n.toString():n.toFixed(2).replace(/\.?0+$/,"");if(t==="IN"&&r?.merchantState&&r?.customerState)if(r.merchantState.toLowerCase().trim()===r.customerState.toLowerCase().trim()){let s=n/2%1===0?(n/2).toString():(n/2).toFixed(2).replace(/\.?0+$/,"");return {totalRate:e,label:`${s}% CGST + ${s}% SGST`,components:[{rate:e/2,label:`${s}% CGST`,type:"CGST"},{rate:e/2,label:`${s}% SGST`,type:"SGST"}]}}else return {totalRate:e,label:`${o}% IGST`,components:[{rate:e,label:`${o}% IGST`,type:"IGST"}]};return {totalRate:e,label:`${o}% GST`,components:[{rate:e,label:`${o}% GST`,type:"GST"}]}}getLongName(){return "Goods and Services Tax"}},C={GST:new f},I=class i extends d{taxRuleId;taxSystem;taxCategory;country;slabs;effectiveFrom;effectiveTo;constructor(e,t=new Date){super(e,t),this.taxRuleId=e.taxRuleId,this.taxSystem=e.taxSystem,this.taxCategory=e.taxCategory,this.country=e.country,this.slabs=e.slabs.map(r=>({rate:r.rate,minUnitPrice:new m(r.minUnitPrice),maxUnitPrice:r.maxUnitPrice?new m(r.maxUnitPrice):void 0})),this.effectiveFrom=new Date(e.effectiveFrom),this.effectiveTo=e.effectiveTo?new Date(e.effectiveTo):void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getSlabs(){return this.slabs}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),slabs:this.getSlabs().map(e=>({rate:e.rate,minUnitPrice:e.minUnitPrice.getDetails(),maxUnitPrice:e.maxUnitPrice?e.maxUnitPrice.getDetails():void 0})),effectiveFrom:this.effectiveFrom.toISOString(),effectiveTo:this.effectiveTo?this.effectiveTo.toISOString():void 0,...super.getDetails()}}appliesTo(e,t,r=new Date){return this.taxCategory===e&&this.country===t&&this.effectiveFrom<=r&&(this.effectiveTo?this.effectiveTo>=r:!0)}getApplicableTaxRate(e){return i.getApplicableTaxRate(e,this.slabs)}getTaxRateDisplayString(e,t){let r=this.getApplicableTaxRate(e);return i.getTaxRateDisplayString(r,{taxSystem:this.taxSystem,merchantState:t?.merchantState,customerState:t?.customerState})}getTaxRateBreakdown(e,t){let r=this.getApplicableTaxRate(e),n=C[this.taxSystem];if(n)return n.getBreakdown(r,this.country,t);let o=r*100,c=`${o%1===0?o.toString():o.toFixed(2).replace(/\.?0+$/,"")}% ${this.taxSystem}`;return {totalRate:r,label:c,components:[{rate:r,label:c,type:this.taxSystem}]}}getFormattedTaxRate(e,t={}){let n=this.getApplicableTaxRate(e)*100,o=n%1===0?n.toString():n.toFixed(2).replace(/\.?0+$/,""),s=t.variant||"short",c="";switch(s){case"percentageOnly":c=`${o}%`;break;case"detailed":let x=this.getTaxRateBreakdown(e,t),w=t.separator||(t.multiline?`
2
+ `:" + ");c=x.components.map(D=>D.label).join(w);break;case"long":let T=C[this.taxSystem],A=T?T.getLongName(this.country):this.taxSystem.toString();c=`${o}% ${A}`;break;case"short":default:c=`${o}% ${this.taxSystem}`;break}return t.includeTaxesSuffix&&(c+=" (Incl. Taxes)"),c}static getApplicableTaxRate(e,t){let r=t.filter(n=>(n.minUnitPrice===void 0||e.compareTo(n.minUnitPrice)>=0)&&(n.maxUnitPrice===void 0||e.compareTo(n.maxUnitPrice)<0));if(r.length!==1)throw new y;return r[0].rate}static getTaxRateDisplayString(e,t){let r=e*100,n=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,"");if(t.taxSystem==="GST"&&t.merchantState&&t.customerState)if(t.merchantState.toLowerCase().trim()===t.customerState.toLowerCase().trim()){let o=r/2%1===0?(r/2).toString():(r/2).toFixed(2).replace(/\.?0+$/,"");return `${o}% CGST + ${o}% SGST`}else return `${n}% IGST`;return t.taxSystem?`${n}% ${t.taxSystem}`:`${n}%`}};exports.GSTFormatter=f;exports.TaxFormatterRegistry=C;exports.TaxRuleModel=I;//# sourceMappingURL=TaxRule.js.map
2
3
  //# sourceMappingURL=TaxRule.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/Classes/Base.ts","../../src/Classes/Enum.ts","../../src/Classes/Error.ts","../../src/Classes/Price.ts","../../src/Classes/TaxRule.ts"],"names":["BaseModel","data","date","id","authType","requestId","lambdaName","fieldName","value","CurrencySymbolMap","CurrencyLocaleMap","TaxSlabNotFoundError","message","InvalidPriceAmountError","InvalidCurrencyCodeError","CurrencyMismatchError","InvalidArgumentError","PriceModel","_PriceModel","#kind","obj","priceModel","factor","divisor","priceModels","minPrice","currentPrice","maxPrice","amount","currency","options","locale","valueToFormat","fractionDigits","formattingOptions","error","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier","TaxRuleModel","_TaxRuleModel","s","taxCategory","country","at","unitPrice","rate","taxSlabs","slabs","percentage","rateStr","splitRate"],"mappings":"aA4BA,IAAqBA,EAArB,KAA+B,CACnB,YACA,CAAA,OAAA,CACA,UACA,UACA,CAAA,UAAA,CAQV,WAAYC,CAAAA,CAAAA,CAAsBC,EAAa,IAAI,IAAA,CAAQ,CACzD,IAAK,CAAA,YAAA,CAAe,CAAE,GAAGD,CAAAA,CAAK,YAAa,CAAA,CAC3C,KAAK,OAAUA,CAAAA,CAAAA,CAAK,OAAW,EAAA,CAAA,CAC/B,KAAK,SAAYA,CAAAA,CAAAA,CAAK,SAAa,EAAA,CAAC,MAAM,IAAK,CAAA,KAAA,CAAMA,EAAK,SAAS,CAAC,EAElE,IAAI,IAAA,CAAKA,CAAK,CAAA,SAAS,EAAE,WAAY,EAAA,CAErCC,CAAK,CAAA,WAAA,GACP,IAAK,CAAA,UAAA,CAAaD,CAAK,CAAA,UAAA,EAAc,CAAC,KAAM,CAAA,IAAA,CAAK,MAAMA,CAAK,CAAA,UAAU,CAAC,CACnE,CAAA,IAAI,IAAKA,CAAAA,CAAAA,CAAK,UAAU,CAAE,CAAA,WAAA,EAC1BC,CAAAA,CAAAA,CAAK,aAET,CAAA,IAAA,CAAK,UAAa,CAAA,CAAE,GAAGD,CAAK,CAAA,UAAW,EACzC,CAMA,UAAA,EAAuB,CACrB,OAAO,CACL,YAAc,CAAA,IAAA,CAAK,oBACnB,CAAA,OAAA,C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AAI,EACzE,CAEA,CAAA,GAAIO,EAAM,MAAW,GAAA,CAAA,CACnB,MAAM,IAAIxC,CAAAA,CAGZ,OAAOwC,CAAAA,CAAM,CAAC,CAAE,CAAA,IAClB,CASA,OAAO,uBAAA,CAAwBF,EAAcnB,CAIlC,CAAA,CACT,IAAMsB,CAAAA,CAAaH,EAAO,GAEpBI,CAAAA,CAAAA,CAAUD,CAAa,CAAA,CAAA,GAAM,EAAIA,CAAW,CAAA,QAAA,EAAaA,CAAAA,CAAAA,CAAW,QAAQ,CAAC,CAAA,CAAE,QAAQ,QAAU,CAAA,EAAE,EAEzG,GAAItB,CAAAA,CAAQ,SAAc,GAAA,KAAA,EAAiBA,EAAQ,aAAiBA,EAAAA,CAAAA,CAAQ,aAC1E,CAAA,GAAIA,EAAQ,aAAc,CAAA,WAAA,EAAc,CAAA,IAAA,KAAWA,CAAQ,CAAA,aAAA,CAAc,aAAc,CAAA,IAAA,GAAQ,CAC7F,IAAMwB,CAAaF,CAAAA,CAAAA,CAAa,EAAK,CAAM,GAAA,CAAA,CAAA,CAAKA,CAAa,CAAA,CAAA,EAAG,UAAcA,CAAAA,CAAAA,CAAAA,CAAa,CAAG,EAAA,OAAA,CAAQ,CAAC,CAAE,CAAA,OAAA,CAAQ,SAAU,EAAE,CAAA,CAC7H,OAAO,CAAGE,EAAAA,CAAS,CAAYA,SAAAA,EAAAA,CAAS,QAC1C,CACE,KAAA,OAAO,GAAGD,CAAO,CAAA,MAAA,CAAA,CAIrB,OAAOvB,CAAQ,CAAA,SAAA,CAAY,CAAGuB,EAAAA,CAAO,KAAKvB,CAAQ,CAAA,SAAS,GAAK,CAAGuB,EAAAA,CAAO,GAC5E,CACF","file":"TaxRule.js","sourcesContent":["import { AuthType } from \"../Auth\";\r\nimport { ISODateTimeUTC } from \"./Common\";\r\n\r\nexport interface CustomFields {\r\n [key: string]: any;\r\n}\r\n\r\nexport type ModifiedBy = {\r\n id?: string;\r\n authType?: string;\r\n requestId?: string;\r\n lambdaName?: string;\r\n}\r\n\r\nexport type BaseAttributes = {\r\n customFields?: CustomFields;\r\n version?: number;\r\n createdAt?: ISODateTimeUTC;\r\n modifiedAt?: ISODateTimeUTC;\r\n modifiedBy?: ModifiedBy;\r\n};\r\n\r\nexport type BaseData = Required<BaseAttributes>;\r\n\r\n/**\r\n * Provides common foundational properties and methods for other data models.\r\n * Handles tracking of custom fields, versioning, and timestamps.\r\n */\r\nexport default class BaseModel {\r\n protected customFields: CustomFields;\r\n protected version: number;\r\n protected createdAt: ISODateTimeUTC;\r\n protected modifiedAt: ISODateTimeUTC;\r\n protected modifiedBy: ModifiedBy;\r\n\r\n /**\r\n * Creates an instance of BaseModel.\r\n * Initializes common properties like timestamps, version, and custom fields.\r\n * @param data - Optional initial attributes for the base model.\r\n * @param date - Optional date object to use for default timestamps (defaults to current time).\r\n */\r\n constructor(data: BaseAttributes, date: Date = new Date()) {\r\n this.customFields = { ...data.customFields };\r\n this.version = data.version ?? 1;\r\n this.createdAt = data.createdAt && !isNaN(Date.parse(data.createdAt))\r\n ?\r\n new Date(data.createdAt).toISOString()\r\n :\r\n date.toISOString();\r\n this.modifiedAt = data.modifiedAt && !isNaN(Date.parse(data.modifiedAt))\r\n ? new Date(data.modifiedAt).toISOString()\r\n : date.toISOString();\r\n\r\n this.modifiedBy = { ...data.modifiedBy };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the base model's current state.\r\n * @returns BaseData object containing common properties.\r\n */\r\n getDetails(): BaseData {\r\n return {\r\n customFields: this.getAllCustomFields(), // Use getter to return a copy\r\n version: this.getVersion(),\r\n createdAt: this.getCreatedAt(),\r\n modifiedAt: this.getModifiedAt(),\r\n modifiedBy: this.getModifiedBy(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the current version number of the model instance.\r\n * @returns The version number.\r\n */\r\n getVersion(): number {\r\n return this.version;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as an ISO 8601 string.\r\n * @returns The creation timestamp string.\r\n */\r\n getCreatedAt(): string {\r\n return this.createdAt;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as a Unix epoch time (milliseconds).\r\n * @returns The creation time in milliseconds since the epoch.\r\n */\r\n getCreatedAtTime(): number {\r\n return new Date(this.createdAt).getTime();\r\n }\r\n\r\n\r\n /**\r\n * Gets the last modification timestamp as an ISO 8601 string.\r\n * @returns The last modification timestamp string.\r\n */\r\n getModifiedAt(): string {\r\n return this.modifiedAt;\r\n }\r\n\r\n /**\r\n * Gets the last modification timestamp as a Unix epoch time (milliseconds).\r\n * @returns The last modification time in milliseconds since the epoch.\r\n */\r\n getModifiedAtTime(): number {\r\n return new Date(this.modifiedAt).getTime();\r\n }\r\n\r\n /**\r\n * Gets the identifier of the user or process that last modified the instance.\r\n * @returns\r\n */\r\n getModifiedBy(): ModifiedBy {\r\n return { ...this.modifiedBy };\r\n }\r\n\r\n /**\r\n * Sets the identifier of the user or process that last modified the instance.\r\n * @param modifiedBy - The identifier string.\r\n */\r\n setModifiedBy(id?: string, authType?: AuthType, requestId?: string, lambdaName?: string): void {\r\n this.modifiedBy = {\r\n id,\r\n authType,\r\n requestId,\r\n lambdaName,\r\n };\r\n }\r\n\r\n /**\r\n * Retrieves the value of a specific custom field.\r\n * @param fieldName - The name (key) of the custom field to retrieve.\r\n * @returns The value of the custom field, or null if the field does not exist.\r\n */\r\n getCustomField(fieldName: string): any {\r\n return this.customFields[fieldName] ?? null;\r\n }\r\n\r\n /**\r\n * Sets the value of a specific custom field.\r\n * Also updates the modification timestamp and increments the version.\r\n * @param fieldName - The name (key) of the custom field to set.\r\n * @param value - The value to assign to the custom field.\r\n */\r\n setCustomField(fieldName: string, value: any): void {\r\n this.customFields[fieldName] = value;\r\n }\r\n\r\n /**\r\n * Retrieves a shallow copy of all custom fields associated with the instance.\r\n * @returns An object containing all custom fields.\r\n */\r\n getAllCustomFields(): CustomFields {\r\n return { ...this.customFields };\r\n }\r\n}\r\n","/**\r\n * Represents the countries where the application operates or products are available.\r\n */\r\nexport enum OperationalCountry {\r\n /** India */ IN = 'IN',\r\n}\r\n \r\nexport enum OperationalCountryCurrency {\r\n /** India */ INR = 'INR',\r\n}\r\n\r\nexport enum OperationalLocale {\r\n /** India */ 'en-IN' = 'en-IN',\r\n /** India ( Kannada) */ 'kn-IN' = 'kn-IN'\r\n}\r\n\r\nexport enum OperationalLanguage {\r\n en = 'en',\r\n kn = 'kn'\r\n}\r\n\r\nexport const LocaleLanguageMap: Record<OperationalLocale, OperationalLanguage> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalLanguage.en,\r\n [OperationalLocale[\"kn-IN\"]]: OperationalLanguage.kn,\r\n}\r\n\r\nexport const LocaleCountryMap: Record<OperationalLocale, OperationalCountry> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalCountry.IN,\r\n [OperationalLocale[\"kn-IN\"]]: OperationalCountry.IN,\r\n}\r\n\r\n/**\r\n * Defines the supported ISO 4217 currency codes as an enumeration.\r\n */\r\nexport const CountryCurrencyMap = {\r\n /** India */ [OperationalCountry.IN]: OperationalCountryCurrency.INR,\r\n};\r\n\r\nexport const CurrencySymbolMap = {\r\n [OperationalCountryCurrency.INR]: '₹',\r\n}\r\n\r\nexport const CurrencyLocaleMap = {\r\n [OperationalCountryCurrency.INR]: OperationalLocale[\"en-IN\"],\r\n}\r\n\r\n/**\r\n * Defines standard gender categories for product targeting.\r\n */\r\nexport enum GenderCategory {\r\n MALE = 'Male',\r\n FEMALE = 'Female',\r\n UNISEX = 'Unisex',\r\n KIDS = 'Kids',\r\n BOY = 'Boy',\r\n GIRL = 'Girl',\r\n GENERAL = 'General',\r\n}\r\n\r\nexport enum ImageCategory {\r\n PRIMARY = 'PRIMARY',\r\n GALLERY = 'GALLERY'\r\n}\r\n\r\nexport enum TaxCategory {\r\n APPAREL = 'apparel',\r\n EXEMPT = 'exempt'\r\n}\r\n\r\nexport enum TaxSystem {\r\n GST = 'GST',\r\n}\r\n\r\n/**\r\n * LineItemState\r\n * \r\n * INITIAL: Item added to order, not yet processed.\r\n * PROCESSING: Item is being prepared for shipment.\r\n * SHIPPED: Item dispatched to customer.\r\n * DELIVERED: Item delivered to customer.\r\n * CANCELLED: Item cancelled before shipment or delivery.\r\n * RETURN_REQUESTED: Customer requests to return item.\r\n * RETURNED: Item received back from customer.\r\n * REFUND_INITIATED: Refund initiated for item.\r\n * REFUNDED: Refund processed for item.\r\n * ON_HOLD: Item is paused due to payment, inventory, or other issues.\r\n */\r\nexport enum LineItemState {\r\n INITIAL = \"INITIAL\",\r\n PROCESSING = \"PROCESSING\",\r\n SHIPPED = \"SHIPPED\",\r\n DELIVERED = \"DELIVERED\",\r\n CANCELLED = \"CANCELLED\",\r\n RETURN_REQUESTED = \"RETURN_REQUESTED\",\r\n RETURNED = \"RETURNED\",\r\n REFUND_INITIATED = \"REFUND_INITIATED\",\r\n REFUNDED = \"REFUNDED\",\r\n ON_HOLD = \"ON_HOLD\",\r\n}","export class LineItemNotFoundError extends Error {\r\n constructor(lineItemId: string) {\r\n super(`Line item with ID '${lineItemId}' not found in the cart.`);\r\n this.name = 'LineItemNotFoundError';\r\n }\r\n}\r\n\r\nexport class DuplicateSizeError extends Error {\r\n constructor(size: string) {\r\n super(`Duplicate size found: ${size}`);\r\n this.name = 'DuplicateSizeError';\r\n }\r\n}\r\n\r\nexport class DuplicateSelectionAttributeError extends Error {\r\n constructor(attribute: string) {\r\n super(`Duplicate selection attribute found: ${attribute}`);\r\n this.name = 'DuplicateSelectionAttributeError';\r\n }\r\n}\r\n\r\nexport class ProductMismatchError extends Error {\r\n constructor(message: string = \"Product and selection attributes do not match.\") {\r\n super(`ProductMismatch: ${message}`);\r\n this.name = 'ProductMismatchError';\r\n }\r\n}\r\n\r\nexport class ProductInactiveError extends Error {\r\n constructor(message: string = \"Product is not active.\") {\r\n super(`ProductInactive: ${message}`);\r\n this.name = 'ProductInactiveError';\r\n }\r\n}\r\n\r\nexport class SelectionAttributeParseError extends Error {\r\n constructor(message: string = \"Failed to parse selection attributes key.\") {\r\n super(`SelectionAttributeParseError: ${message}`);\r\n this.name = 'SelectionAttributeParseError';\r\n }\r\n}\r\n\r\nexport class SizeMismatchError extends Error {\r\n constructor(message: string = \"Size does not match.\") {\r\n super(`SizeMismatch: ${message}`);\r\n this.name = 'SizeMismatchError';\r\n }\r\n}\r\n\r\nexport class PricingNotFoundError extends Error {\r\n constructor(message: string = \"Pricing details not available for the product\") {\r\n super(`NotFound: ${message}`);\r\n this.name = 'PricingNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxRuleError extends Error {\r\n constructor(message: string = \"Tax rule category mismatch.\") {\r\n super(`InvalidTaxRule: ${message}`);\r\n this.name = 'InvalidTaxRuleError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxCategoryError extends Error {\r\n constructor(message: string = \"Tax category is not valid.\") {\r\n super(`InvalidTaxCategory: ${message}`);\r\n this.name = 'InvalidTaxCategoryError';\r\n }\r\n}\r\n\r\nexport class InvalidMinQuantityError extends Error {\r\n constructor(message: string = \"Minimum quantity must be greater than zero.\") {\r\n super(`InvalidMinQuantity: ${message}`);\r\n this.name = 'InvalidMinQuantityError';\r\n }\r\n}\r\n\r\nexport class InvalidTieredPriceError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidTieredPrice: ${message}`);\r\n this.name = 'InvalidTieredPriceError';\r\n }\r\n}\r\n\r\nexport class InvalidQuantityError extends Error {\r\n constructor(message: string = \"Quantity must be greater than zero.\") {\r\n super(`InvalidQuantity: ${message}`);\r\n this.name = 'InvalidQuantityError';\r\n }\r\n}\r\n\r\nexport class NoApplicableTierError extends Error {\r\n constructor(quantity: number) {\r\n super(`NoApplicableTier: Quantity ${quantity} does not meet the minimum purchase requirement.`);\r\n this.name = 'NoApplicableTierError';\r\n }\r\n}\r\n\r\nexport class TaxSlabNotFoundError extends Error {\r\n constructor(message: string = \"No applicable tax slab or multiple slabs found for the given unit price.\") {\r\n super(`TaxSlabNotFound: ${message}`);\r\n this.name = 'TaxSlabNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidPriceAmountError extends Error {\r\n constructor(message: string = \"Amount cannot be negative.\") {\r\n super(`InvalidAmount: ${message}`);\r\n this.name = 'InvalidPriceAmountError';\r\n }\r\n}\r\n\r\nexport class InvalidCurrencyCodeError extends Error {\r\n constructor(message: string = \"Currency code is required.\") {\r\n super(`InvalidCurrency: ${message}`);\r\n this.name = 'InvalidCurrencyCodeError';\r\n }\r\n}\r\n\r\nexport class CurrencyMismatchError extends Error {\r\n constructor(message: string = \"Cannot perform operation on prices with different currencies.\") {\r\n super(`CurrencyMismatch: ${message}`);\r\n this.name = 'CurrencyMismatchError';\r\n }\r\n}\r\n\r\nexport class InvalidArgumentError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidArgument: ${message}`);\r\n this.name = 'InvalidArgumentError';\r\n }\r\n}\r\n\r\nexport class InvalidImageSourceError extends Error {\r\n constructor(message: string = \"Invalid image source configuration.\") {\r\n super(`InvalidImageSource: ${message}`);\r\n this.name = 'InvalidImageSourceError';\r\n }\r\n}","import { CurrencyCode } from \"./Common\";\r\nimport { CurrencyLocaleMap, CurrencySymbolMap, OperationalCountryCurrency } from \"./Enum\";\r\nimport {\r\n InvalidPriceAmountError,\r\n InvalidCurrencyCodeError,\r\n CurrencyMismatchError,\r\n InvalidArgumentError\r\n} from \"./Error\";\r\n\r\nexport type PriceAttributes = {\r\n amount: number;\r\n currency: CurrencyCode;\r\n}\r\n\r\nexport type PriceData = PriceAttributes;\r\n\r\nexport default class PriceModel {\r\n #kind: string;\r\n protected amount: number;\r\n protected currency: CurrencyCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param amount - The initial price value.\r\n * @param currency - The currency code used for rounding and determining the currency symbol.\r\n * @throws {Error} If price is negative or country/currency mapping is missing.\r\n */\r\n constructor(data: PriceAttributes) {\r\n this.#kind = \"PriceModel\";\r\n if (data.amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative.\");\r\n }\r\n\r\n if (!data.currency) {\r\n throw new InvalidCurrencyCodeError(\"Currency code is required.\");\r\n }\r\n\r\n this.amount = data.amount;\r\n this.currency = data.currency;\r\n }\r\n\r\n get kind() {\r\n return this.#kind;\r\n }\r\n\r\n static isPriceModel(obj: unknown): obj is PriceModel {\r\n return typeof obj === \"object\" &&\r\n obj !== null &&\r\n (obj as any).kind === \"PriceModel\";\r\n }\r\n\r\n /**\r\n * Gets the currency associated with this price instance.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Returns the raw numeric price value.\r\n */\r\n public getAmount(): number {\r\n return this.amount;\r\n }\r\n\r\n /**\r\n *\r\n * @returns PriceData\r\n */\r\n public getDetails(): PriceData {\r\n return {\r\n amount: this.amount,\r\n currency: this.currency\r\n }\r\n }\r\n\r\n /**\r\n * Compares this price with another {@link PriceModel} instance.\r\n *\r\n * The comparison is performed using the numeric price value and is only valid\r\n * when both prices are expressed in the same currency.\r\n *\r\n * ### Comparison result:\r\n * - Returns a **negative number** if this price is **less than** `priceModel`\r\n * - Returns **zero** if both prices are **equal**\r\n * - Returns a **positive number** if this price is **greater than** `priceModel`\r\n *\r\n * @param priceModel - The {@link PriceModel} instance to compare against.\r\n *\r\n * @returns\r\n * A signed number representing the comparison result:\r\n * - `< 0` → this price is lower\r\n * - `0` → prices are equal\r\n * - `> 0` → this price is higher\r\n *\r\n * @throws {Error}\r\n * Throws an error if:\r\n * - `priceModel` is not an instance of {@link PriceModel}\r\n * - The currencies of the two prices do not match\r\n *\r\n * @example\r\n * ```ts\r\n * const a = new PriceModel(\"USD\", 100);\r\n * const b = new PriceModel(\"USD\", 150);\r\n *\r\n * a.compareTo(b); // -50\r\n * b.compareTo(a); // 50\r\n * a.compareTo(a); // 0\r\n * ```\r\n */\r\n public compareTo(priceModel: PriceModel): number {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return this.amount - priceModel.getAmount();\r\n }\r\n\r\n public add(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot add prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.amount + priceModel.getAmount(),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public subtract(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot subtract prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.amount - priceModel.getAmount(),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public multiply(factor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(factor)) {\r\n if (this.currency !== factor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot multiply prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.amount * factor.getAmount(),\r\n currency: this.currency\r\n });\r\n } else if (typeof factor === \"number\" && factor >= 0) {\r\n return new PriceModel({\r\n amount: this.amount * factor,\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a non-negative number.\");\r\n }\r\n\r\n public divide(divisor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(divisor)) {\r\n if (this.currency !== divisor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot divide prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.amount / divisor.getAmount(),\r\n currency: this.currency\r\n });\r\n } else if (typeof divisor === \"number\" && divisor > 0) {\r\n return new PriceModel({\r\n amount: this.amount / divisor,\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a positive number.\");\r\n }\r\n\r\n public min(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((minPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (minPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return minPrice.compareTo(currentPrice) < 0 ? minPrice : currentPrice;\r\n });\r\n }\r\n\r\n public max(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((maxPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (maxPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return maxPrice.compareTo(currentPrice) > 0 ? maxPrice : currentPrice;\r\n });\r\n }\r\n\r\n /**\r\n * Gets a zero value PriceModel for the same currency.\r\n * @returns A PriceModel instance representing zero in the same currency.\r\n */\r\n public zero(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: 0\r\n });\r\n }\r\n\r\n /**\r\n * Checks if the price is zero.\r\n * @returns True if the price is zero, false otherwise.\r\n */\r\n public isZero(): boolean {\r\n return this.amount === 0;\r\n }\r\n\r\n\r\n public round(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: this.getRoundedAmount()\r\n });\r\n }\r\n /**\r\n * Gets the rounded price value based on standard currency rules.\r\n * @returns The numeric price, rounded according to its currency's typical decimal places.\r\n */\r\n public getRoundedAmount(): number {\r\n return PriceModel.getRoundedAmount(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price stored in this instance.\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n public getFormattedString() {\r\n return PriceModel.getFormattedString(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n toString() {\r\n return this.getFormattedString();\r\n }\r\n\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the amount.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param amount - The initial amount value.\r\n * @param currency - The currency code for formatting.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the amount rounded to the next nearest integer (no decimals). Defaults to false.\r\n * @param options.style - The style of formatting, either 'currency' or 'decimal'. Defaults to 'currency'.\r\n * @param options.currencyDisplay - The display format for the currency symbol. Options are 'symbol', 'narrowSymbol', 'code', or 'name'. Defaults to 'symbol'.\r\n * @returns The formatted price string according to locale rules.\r\n * @throws {Error} If currency code is invalid.\r\n */\r\n static getFormattedString(amount: number, currency: CurrencyCode, options: {\r\n displayAsInteger?: boolean,\r\n style?: 'currency' | 'decimal',\r\n currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name'\r\n } = {\r\n displayAsInteger: false,\r\n style: 'currency',\r\n currencyDisplay: 'symbol'\r\n }): string {\r\n\r\n const locale = CurrencyLocaleMap[currency];\r\n if (!currency || !locale) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for formatting.');\r\n }\r\n\r\n let valueToFormat = amount;\r\n const fractionDigits = options.displayAsInteger ? 0 : PriceModel.getDecimalPlaces(currency);\r\n\r\n let formattingOptions: Intl.NumberFormatOptions = {\r\n style: options.style ?? 'currency',\r\n currency: currency,\r\n signDisplay: 'never',\r\n currencyDisplay: options.currencyDisplay,\r\n minimumFractionDigits: fractionDigits,\r\n maximumFractionDigits: fractionDigits,\r\n };\r\n\r\n if (options.displayAsInteger) {\r\n valueToFormat = Math.ceil(valueToFormat);\r\n }\r\n\r\n try {\r\n return new Intl.NumberFormat(locale, formattingOptions).format(valueToFormat);\r\n } catch (error) {\r\n console.error(`Error formatting price for currency \"${currency}\" and locale \"${locale}\":`, error);\r\n // Basic fallback without symbol if Intl fails completely\r\n return `${CurrencySymbolMap[currency] ?? currency} ${PriceModel.addThousandSeparators(valueToFormat.toFixed(fractionDigits))}`;\r\n }\r\n }\r\n\r\n /**\r\n * Helper method to determine standard decimal places for a currency.\r\n * @param currency - The currency code.\r\n * @returns The number of decimal places (0, 2, or 3 based on common rules).\r\n */\r\n private static getDecimalPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case OperationalCountryCurrency.INR:\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n /**\r\n * Adds basic thousand separators (commas) to a number string.\r\n * Does not handle different locale separators (e.g., periods, spaces).\r\n * @param numStr - The number string (potentially with decimals).\r\n * @returns The number string with commas added.\r\n */\r\n private static addThousandSeparators(numStr: string): string {\r\n const parts = numStr.split('.');\r\n const integerPart = parts[0];\r\n const decimalPart = parts.length > 1 ? '.' + parts[1] : '';\r\n\r\n const formattedInteger = integerPart.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\r\n return formattedInteger + decimalPart;\r\n }\r\n\r\n /**\r\n * Rounds a price value according to the standard decimal places\r\n * for the currency associated with the given country.\r\n *\r\n * @param price - The price value to round. Must be a non-negative number.\r\n * @param currency - The currency code to determine the rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the price is negative or currency is invalid.\r\n */\r\n static getRoundedAmount(amount: number, currency: CurrencyCode): number {\r\n if (amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative for rounding.\");\r\n }\r\n\r\n if (currency === undefined) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for rounding.');\r\n }\r\n\r\n const decimalPlaces = PriceModel.getDecimalPlaces(currency);\r\n const multiplier = Math.pow(10, decimalPlaces);\r\n const roundedValue = Math.round(amount * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n}","import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, ISODateTimeUTC } from \"./Common\";\r\nimport { TaxCategory, TaxSystem } from \"./Enum\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport { TaxSlabNotFoundError } from \"./Error\";\r\n\r\nexport type TaxSlabData = {\r\n minUnitPrice: PriceData; // inclusive\r\n maxUnitPrice?: PriceData; // exclusive\r\n rate: number; // e.g. 0.05 = 5%\r\n};\r\n\r\nexport type TaxSlabModel = {\r\n minUnitPrice: PriceModel; // inclusive\r\n maxUnitPrice?: PriceModel; // exclusive\r\n rate: number; // e.g. 0.05 = 5%\r\n};\r\n\r\nexport type TaxSlabs = TaxSlabData[];\r\n\r\nexport type TaxRuleAttributes = {\r\n taxRuleId: string;\r\n taxSystem: TaxSystem;\r\n taxCategory: TaxCategory;\r\n country: CountryCode;\r\n slabs: TaxSlabs;\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n} & BaseAttributes;\r\n\r\nexport type TaxRuleData = Required<Omit<TaxRuleAttributes, 'effectiveFrom' | 'effectiveTo'>> & {\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n};\r\n\r\nexport class TaxRuleModel extends BaseModel {\r\n protected taxRuleId: string;\r\n protected taxSystem: TaxSystem;\r\n protected taxCategory: TaxCategory;\r\n protected country: CountryCode;\r\n protected slabs: TaxSlabModel[];\r\n protected effectiveFrom: Date;\r\n protected effectiveTo?: Date;\r\n\r\n /**\r\n * Creates an instance of TaxRuleModel.\r\n * @param data - The initial tax rule attributes.\r\n * @param date - Optional date for creation/modification (defaults to now).\r\n */\r\n constructor(data: TaxRuleAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.taxRuleId = data.taxRuleId;\r\n this.taxSystem = data.taxSystem;\r\n this.taxCategory = data.taxCategory;\r\n this.country = data.country;\r\n this.slabs = data.slabs.map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: new PriceModel(s.minUnitPrice),\r\n maxUnitPrice: s.maxUnitPrice ? new PriceModel(s.maxUnitPrice) : undefined,\r\n }));\r\n this.effectiveFrom = new Date(data.effectiveFrom);\r\n this.effectiveTo = data.effectiveTo ? new Date(data.effectiveTo) : 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 getTaxCategory(): TaxCategory {\r\n return this.taxCategory;\r\n }\r\n\r\n getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n getSlabs(): TaxSlabModel[] {\r\n return this.slabs;\r\n }\r\n\r\n getDetails(): TaxRuleData {\r\n return {\r\n taxRuleId: this.getTaxRuleId(),\r\n taxSystem: this.getTaxSystem(),\r\n taxCategory: this.getTaxCategory(),\r\n country: this.getCountry(),\r\n slabs: this.getSlabs().map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: s.minUnitPrice.getDetails(),\r\n maxUnitPrice: s.maxUnitPrice ? s.maxUnitPrice.getDetails() : undefined,\r\n })),\r\n effectiveFrom: this.effectiveFrom.toISOString(),\r\n effectiveTo: this.effectiveTo ? this.effectiveTo.toISOString() : undefined,\r\n ...super.getDetails()\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 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: TaxCategory, country: CountryCode, at: Date = new Date()): boolean {\r\n return (\r\n this.taxCategory === taxCategory &&\r\n this.country === country &&\r\n this.effectiveFrom <= at &&\r\n (this.effectiveTo ? this.effectiveTo >= at : true)\r\n );\r\n }\r\n\r\n /**\r\n * Calculates the applicable tax rate for a given unit price.\r\n * @param unitPrice - The unit price to find the matching tax slab for.\r\n * @returns The tax rate as a decimal (e.g., 0.05 for 5%).\r\n * @throws {TaxSlabNotFoundError} If no applicable slab or multiple slabs are found.\r\n */\r\n getApplicableTaxRate(unitPrice: PriceModel): number {\r\n return TaxRuleModel.getApplicableTaxRate(unitPrice, this.slabs);\r\n }\r\n\r\n /**\r\n * Returns a user-friendly string representation of the applicable tax rate.\r\n * Handles legal IGST/CGST/SGST formatting for India if states are provided.\r\n * @param unitPrice - The unit price to find the matching tax slab for.\r\n * @param options - Optional states to determine IGST vs CGST/SGST.\r\n * @returns A string like \"18% IGST\", \"9% CGST + 9% SGST\", or \"5% GST\".\r\n */\r\n getTaxRateDisplayString(unitPrice: PriceModel, options?: { merchantState?: string, customerState?: string }): string {\r\n const rate = this.getApplicableTaxRate(unitPrice);\r\n return TaxRuleModel.getTaxRateDisplayString(rate, {\r\n taxSystem: this.taxSystem,\r\n merchantState: options?.merchantState,\r\n customerState: options?.customerState\r\n });\r\n }\r\n\r\n /**\r\n * Static method to find the applicable tax rate from a list of slabs.\r\n */\r\n static getApplicableTaxRate(unitPrice: PriceModel, taxSlabs: TaxSlabModel[]): number {\r\n const slabs = taxSlabs.filter(s =>\r\n (s.minUnitPrice === undefined || unitPrice.compareTo(s.minUnitPrice) >= 0) &&\r\n (s.maxUnitPrice === undefined || unitPrice.compareTo(s.maxUnitPrice) < 0)\r\n );\r\n\r\n if (slabs.length !== 1) {\r\n throw new TaxSlabNotFoundError();\r\n }\r\n\r\n return slabs[0].rate;\r\n }\r\n\r\n /**\r\n * Static method to format a tax rate as a display string.\r\n * Handles legal IGST/CGST/SGST formatting for India if states are provided.\r\n * @param rate - The tax rate as a decimal (e.g., 0.18).\r\n * @param options - Configuration for tax system name and states.\r\n * @returns A formatted string.\r\n */\r\n static getTaxRateDisplayString(rate: number, options: {\r\n taxSystem?: string,\r\n merchantState?: string,\r\n customerState?: string\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 (options.taxSystem === TaxSystem.GST && options.merchantState && options.customerState) {\r\n if (options.merchantState.toLowerCase().trim() === options.customerState.toLowerCase().trim()) {\r\n const splitRate = (percentage / 2) % 1 === 0 ? (percentage / 2).toString() : (percentage / 2).toFixed(2).replace(/\\.?0+$/, '');\r\n return `${splitRate}% CGST + ${splitRate}% SGST`;\r\n } else {\r\n return `${rateStr}% IGST`;\r\n }\r\n }\r\n\r\n return options.taxSystem ? `${rateStr}% ${options.taxSystem}` : `${rateStr}%`;\r\n }\r\n}\r\n"]}
1
+ {"version":3,"sources":["../../src/Classes/Base.ts","../../src/Classes/Enum.ts","../../src/Classes/Error.ts","../../src/Classes/Price.ts","../../src/Classes/TaxRule.ts"],"names":["CustomFieldModel","data","date","fieldName","value","BaseModel","id","authType","requestId","lambdaName","CurrencySymbolMap","CurrencyLocaleMap","TaxSlabNotFoundError","message","InvalidPriceAmountError","InvalidCurrencyCodeError","CurrencyMismatchError","InvalidArgumentError","PriceModel","_PriceModel","#kind","obj","priceModel","factor","divisor","priceModels","minPrice","currentPrice","maxPrice","amount","currency","options","locale","valueToFormat","fractionDigits","formattingOptions","error","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier","GSTFormatter","rate","country","percentage","rateStr","splitRate","TaxFormatterRegistry","TaxRuleModel","_TaxRuleModel","s","taxCategory","at","unitPrice","formatter","label","variant","result","breakdown","separator","c","systemLongName","taxSlabs","slabs"],"mappings":"aAWO,IAAMA,EAAN,KAAuB,CAClB,aACV,WAAYC,CAAAA,CAAAA,CAA6BC,EAAa,IAAI,IAAA,CAAQ,CAChE,IAAK,CAAA,YAAA,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T,IAAMe,EAAaF,CAAO,CAAA,GAAA,CAEpBG,EAAUD,CAAa,CAAA,CAAA,GAAM,EAAIA,CAAW,CAAA,QAAA,GAAaA,CAAW,CAAA,OAAA,CAAQ,CAAC,CAAE,CAAA,OAAA,CAAQ,SAAU,EAAE,CAAA,CAEzG,GAAIf,CAAQ,CAAA,SAAA,GAAc,OAAiBA,CAAQ,CAAA,aAAA,EAAiBA,EAAQ,aAC1E,CAAA,GAAIA,EAAQ,aAAc,CAAA,WAAA,GAAc,IAAK,EAAA,GAAMA,EAAQ,aAAc,CAAA,WAAA,GAAc,IAAK,EAAA,CAAG,CAC7F,IAAMiB,CAAAA,CAAaF,EAAa,CAAK,CAAA,CAAA,GAAM,GAAKA,CAAa,CAAA,CAAA,EAAG,UAAcA,CAAAA,CAAAA,CAAAA,CAAa,GAAG,OAAQ,CAAA,CAAC,EAAE,OAAQ,CAAA,QAAA,CAAU,EAAE,CAC7H,CAAA,OAAO,GAAGE,CAAS,CAAA,SAAA,EAAYA,CAAS,CAC1C,MAAA,CAAA,CAAA,YACS,CAAGD,EAAAA,CAAO,SAIrB,OAAOhB,CAAAA,CAAQ,UAAY,CAAGgB,EAAAA,CAAO,KAAKhB,CAAQ,CAAA,SAAS,GAAK,CAAGgB,EAAAA,CAAO,GAC5E,CACF","file":"TaxRule.js","sourcesContent":["import { AuthType } from \"../Auth\";\r\nimport { ISODateTimeUTC, Prettify } from \"./Common\";\r\n\r\nexport interface CustomFields {\r\n [key: string]: any;\r\n}\r\n\r\nexport type CustomFieldAttributes = {\r\n customFields?: CustomFields;\r\n}\r\n\r\nexport class CustomFieldModel {\r\n protected customFields: CustomFields;\r\n constructor(data: CustomFieldAttributes, date: Date = new Date()) {\r\n this.customFields = { ...data.customFields };\r\n }\r\n\r\n /**\r\n * Retrieves the value of a specific custom field.\r\n * @param fieldName - The name (key) of the custom field to retrieve.\r\n * @returns The value of the custom field, or null if the field does not exist.\r\n */\r\n getCustomField(fieldName: string): any {\r\n return this.customFields[fieldName] ?? null;\r\n }\r\n\r\n /**\r\n * Sets the value of a specific custom field.\r\n * Also updates the modification timestamp and increments the version.\r\n * @param fieldName - The name (key) of the custom field to set.\r\n * @param value - The value to assign to the custom field.\r\n */\r\n setCustomField(fieldName: string, value: any): void {\r\n this.customFields[fieldName] = value;\r\n }\r\n\r\n /**\r\n * Retrieves a shallow copy of all custom fields associated with the instance.\r\n * @returns An object containing all custom fields.\r\n */\r\n getAllCustomFields(): CustomFields {\r\n return { ...this.customFields };\r\n }\r\n}\r\n\r\nexport type ModifiedBy = {\r\n id?: string;\r\n authType?: string;\r\n requestId?: string;\r\n lambdaName?: string;\r\n}\r\n\r\nexport type BaseAttributes = Prettify<CustomFieldAttributes & {\r\n version?: number;\r\n createdAt?: ISODateTimeUTC;\r\n modifiedAt?: ISODateTimeUTC;\r\n modifiedBy?: ModifiedBy;\r\n}>;\r\n\r\nexport type BaseData = Required<BaseAttributes>;\r\n\r\n/**\r\n * Provides common foundational properties and methods for other data models.\r\n * Handles tracking of custom fields, versioning, and timestamps.\r\n */\r\nexport default class BaseModel extends CustomFieldModel {\r\n protected version: number;\r\n protected createdAt: ISODateTimeUTC;\r\n protected modifiedAt: ISODateTimeUTC;\r\n protected modifiedBy: ModifiedBy;\r\n\r\n /**\r\n * Creates an instance of BaseModel.\r\n * Initializes common properties like timestamps, version, and custom fields.\r\n * @param data - Optional initial attributes for the base model.\r\n * @param date - Optional date object to use for default timestamps (defaults to current time).\r\n */\r\n constructor(data: BaseAttributes, date: Date = new Date()) {\r\n super(data);\r\n this.version = data.version ?? 1;\r\n this.createdAt = data.createdAt && !isNaN(Date.parse(data.createdAt))\r\n ?\r\n new Date(data.createdAt).toISOString()\r\n :\r\n date.toISOString();\r\n this.modifiedAt = data.modifiedAt && !isNaN(Date.parse(data.modifiedAt))\r\n ? new Date(data.modifiedAt).toISOString()\r\n : date.toISOString();\r\n\r\n this.modifiedBy = { ...data.modifiedBy };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the base model's current state.\r\n * @returns BaseData object containing common properties.\r\n */\r\n getDetails(): BaseData {\r\n return {\r\n customFields: this.getAllCustomFields(), // Use getter to return a copy\r\n version: this.getVersion(),\r\n createdAt: this.getCreatedAt(),\r\n modifiedAt: this.getModifiedAt(),\r\n modifiedBy: this.getModifiedBy(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the current version number of the model instance.\r\n * @returns The version number.\r\n */\r\n getVersion(): number {\r\n return this.version;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as an ISO 8601 string.\r\n * @returns The creation timestamp string.\r\n */\r\n getCreatedAt(): string {\r\n return this.createdAt;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as a Unix epoch time (milliseconds).\r\n * @returns The creation time in milliseconds since the epoch.\r\n */\r\n getCreatedAtTime(): number {\r\n return new Date(this.createdAt).getTime();\r\n }\r\n\r\n\r\n /**\r\n * Gets the last modification timestamp as an ISO 8601 string.\r\n * @returns The last modification timestamp string.\r\n */\r\n getModifiedAt(): string {\r\n return this.modifiedAt;\r\n }\r\n\r\n /**\r\n * Gets the last modification timestamp as a Unix epoch time (milliseconds).\r\n * @returns The last modification time in milliseconds since the epoch.\r\n */\r\n getModifiedAtTime(): number {\r\n return new Date(this.modifiedAt).getTime();\r\n }\r\n\r\n /**\r\n * Gets the identifier of the user or process that last modified the instance.\r\n * @returns\r\n */\r\n getModifiedBy(): ModifiedBy {\r\n return { ...this.modifiedBy };\r\n }\r\n\r\n /**\r\n * Sets the identifier of the user or process that last modified the instance.\r\n * @param modifiedBy - The identifier string.\r\n */\r\n setModifiedBy(id?: string, authType?: AuthType, requestId?: string, lambdaName?: string): void {\r\n this.modifiedBy = {\r\n id,\r\n authType,\r\n requestId,\r\n lambdaName,\r\n };\r\n }\r\n}\r\n","/**\r\n * Represents the countries where the application operates or products are available.\r\n */\r\nexport enum OperationalCountry {\r\n /** India */ IN = 'IN',\r\n}\r\n \r\nexport enum OperationalCountryCurrency {\r\n /** India */ INR = 'INR',\r\n}\r\n\r\nexport enum OperationalLocale {\r\n /** India */ 'en-IN' = 'en-IN',\r\n /** India ( Kannada) */ 'kn-IN' = 'kn-IN'\r\n}\r\n\r\nexport enum OperationalLanguage {\r\n en = 'en',\r\n kn = 'kn'\r\n}\r\n\r\nexport const LocaleLanguageMap: Record<OperationalLocale, OperationalLanguage> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalLanguage.en,\r\n [OperationalLocale[\"kn-IN\"]]: OperationalLanguage.kn,\r\n}\r\n\r\nexport const LocaleCountryMap: Record<OperationalLocale, OperationalCountry> = {\r\n [OperationalLocale[\"en-IN\"]]: OperationalCountry.IN,\r\n [OperationalLocale[\"kn-IN\"]]: OperationalCountry.IN,\r\n}\r\n\r\n/**\r\n * Defines the supported ISO 4217 currency codes as an enumeration.\r\n */\r\nexport const CountryCurrencyMap = {\r\n /** India */ [OperationalCountry.IN]: OperationalCountryCurrency.INR,\r\n};\r\n\r\nexport const CurrencySymbolMap = {\r\n [OperationalCountryCurrency.INR]: '₹',\r\n}\r\n\r\nexport const CurrencyLocaleMap = {\r\n [OperationalCountryCurrency.INR]: OperationalLocale[\"en-IN\"],\r\n}\r\n\r\n/**\r\n * Defines standard gender categories for product targeting.\r\n */\r\nexport enum GenderCategory {\r\n MALE = 'Male',\r\n FEMALE = 'Female',\r\n UNISEX = 'Unisex',\r\n KIDS = 'Kids',\r\n BOY = 'Boy',\r\n GIRL = 'Girl',\r\n GENERAL = 'General',\r\n}\r\n\r\nexport enum ImageCategory {\r\n PRIMARY = 'PRIMARY',\r\n GALLERY = 'GALLERY'\r\n}\r\n\r\nexport enum TaxCategory {\r\n APPAREL = 'apparel',\r\n EXEMPT = 'exempt'\r\n}\r\n\r\nexport enum TaxSystem {\r\n GST = 'GST',\r\n}\r\n\r\n/**\r\n * LineItemState\r\n * \r\n * INITIAL: Item added to order, not yet processed.\r\n * PROCESSING: Item is being prepared for shipment.\r\n * SHIPPED: Item dispatched to customer.\r\n * DELIVERED: Item delivered to customer.\r\n * CANCELLED: Item cancelled before shipment or delivery.\r\n * RETURN_REQUESTED: Customer requests to return item.\r\n * RETURNED: Item received back from customer.\r\n * REFUND_INITIATED: Refund initiated for item.\r\n * REFUNDED: Refund processed for item.\r\n * ON_HOLD: Item is paused due to payment, inventory, or other issues.\r\n */\r\nexport enum LineItemState {\r\n INITIAL = \"INITIAL\",\r\n PROCESSING = \"PROCESSING\",\r\n SHIPPED = \"SHIPPED\",\r\n DELIVERED = \"DELIVERED\",\r\n CANCELLED = \"CANCELLED\",\r\n RETURN_REQUESTED = \"RETURN_REQUESTED\",\r\n RETURNED = \"RETURNED\",\r\n REFUND_INITIATED = \"REFUND_INITIATED\",\r\n REFUNDED = \"REFUNDED\",\r\n ON_HOLD = \"ON_HOLD\",\r\n}","export class LineItemNotFoundError extends Error {\r\n constructor(lineItemId: string) {\r\n super(`Line item with ID '${lineItemId}' not found in the cart.`);\r\n this.name = 'LineItemNotFoundError';\r\n }\r\n}\r\n\r\nexport class DuplicateSizeError extends Error {\r\n constructor(size: string) {\r\n super(`Duplicate size found: ${size}`);\r\n this.name = 'DuplicateSizeError';\r\n }\r\n}\r\n\r\nexport class DuplicateSelectionAttributeError extends Error {\r\n constructor(attribute: string) {\r\n super(`Duplicate selection attribute found: ${attribute}`);\r\n this.name = 'DuplicateSelectionAttributeError';\r\n }\r\n}\r\n\r\nexport class ProductMismatchError extends Error {\r\n constructor(message: string = \"Product and selection attributes do not match.\") {\r\n super(`ProductMismatch: ${message}`);\r\n this.name = 'ProductMismatchError';\r\n }\r\n}\r\n\r\nexport class ProductInactiveError extends Error {\r\n constructor(message: string = \"Product is not active.\") {\r\n super(`ProductInactive: ${message}`);\r\n this.name = 'ProductInactiveError';\r\n }\r\n}\r\n\r\nexport class SelectionAttributeParseError extends Error {\r\n constructor(message: string = \"Failed to parse selection attributes key.\") {\r\n super(`SelectionAttributeParseError: ${message}`);\r\n this.name = 'SelectionAttributeParseError';\r\n }\r\n}\r\n\r\nexport class SizeMismatchError extends Error {\r\n constructor(message: string = \"Size does not match.\") {\r\n super(`SizeMismatch: ${message}`);\r\n this.name = 'SizeMismatchError';\r\n }\r\n}\r\n\r\nexport class PricingNotFoundError extends Error {\r\n constructor(message: string = \"Pricing details not available for the product\") {\r\n super(`NotFound: ${message}`);\r\n this.name = 'PricingNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxRuleError extends Error {\r\n constructor(message: string = \"Tax rule category mismatch.\") {\r\n super(`InvalidTaxRule: ${message}`);\r\n this.name = 'InvalidTaxRuleError';\r\n }\r\n}\r\n\r\nexport class InvalidTaxCategoryError extends Error {\r\n constructor(message: string = \"Tax category is not valid.\") {\r\n super(`InvalidTaxCategory: ${message}`);\r\n this.name = 'InvalidTaxCategoryError';\r\n }\r\n}\r\n\r\nexport class InvalidMinQuantityError extends Error {\r\n constructor(message: string = \"Minimum quantity must be greater than zero.\") {\r\n super(`InvalidMinQuantity: ${message}`);\r\n this.name = 'InvalidMinQuantityError';\r\n }\r\n}\r\n\r\nexport class InvalidTieredPriceError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidTieredPrice: ${message}`);\r\n this.name = 'InvalidTieredPriceError';\r\n }\r\n}\r\n\r\nexport class InvalidQuantityError extends Error {\r\n constructor(message: string = \"Quantity must be greater than zero.\") {\r\n super(`InvalidQuantity: ${message}`);\r\n this.name = 'InvalidQuantityError';\r\n }\r\n}\r\n\r\nexport class NoApplicableTierError extends Error {\r\n constructor(quantity: number) {\r\n super(`NoApplicableTier: Quantity ${quantity} does not meet the minimum purchase requirement.`);\r\n this.name = 'NoApplicableTierError';\r\n }\r\n}\r\n\r\nexport class TaxSlabNotFoundError extends Error {\r\n constructor(message: string = \"No applicable tax slab or multiple slabs found for the given unit price.\") {\r\n super(`TaxSlabNotFound: ${message}`);\r\n this.name = 'TaxSlabNotFoundError';\r\n }\r\n}\r\n\r\nexport class InvalidPriceAmountError extends Error {\r\n constructor(message: string = \"Amount cannot be negative.\") {\r\n super(`InvalidAmount: ${message}`);\r\n this.name = 'InvalidPriceAmountError';\r\n }\r\n}\r\n\r\nexport class InvalidCurrencyCodeError extends Error {\r\n constructor(message: string = \"Currency code is required.\") {\r\n super(`InvalidCurrency: ${message}`);\r\n this.name = 'InvalidCurrencyCodeError';\r\n }\r\n}\r\n\r\nexport class CurrencyMismatchError extends Error {\r\n constructor(message: string = \"Cannot perform operation on prices with different currencies.\") {\r\n super(`CurrencyMismatch: ${message}`);\r\n this.name = 'CurrencyMismatchError';\r\n }\r\n}\r\n\r\nexport class InvalidArgumentError extends Error {\r\n constructor(message: string) {\r\n super(`InvalidArgument: ${message}`);\r\n this.name = 'InvalidArgumentError';\r\n }\r\n}\r\n\r\nexport class InvalidImageSourceError extends Error {\r\n constructor(message: string = \"Invalid image source configuration.\") {\r\n super(`InvalidImageSource: ${message}`);\r\n this.name = 'InvalidImageSourceError';\r\n }\r\n}","import { CurrencyCode } from \"./Common\";\r\nimport { CurrencyLocaleMap, CurrencySymbolMap, OperationalCountryCurrency } from \"./Enum\";\r\nimport {\r\n InvalidPriceAmountError,\r\n InvalidCurrencyCodeError,\r\n CurrencyMismatchError,\r\n InvalidArgumentError\r\n} from \"./Error\";\r\n\r\nexport type PriceAttributes = {\r\n amount: number;\r\n currency: CurrencyCode;\r\n}\r\n\r\nexport type PriceData = PriceAttributes;\r\n\r\nexport default class PriceModel {\r\n #kind: string;\r\n protected amount: number;\r\n protected currency: CurrencyCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param amount - The initial price value.\r\n * @param currency - The currency code used for rounding and determining the currency symbol.\r\n * @throws {Error} If price is negative or country/currency mapping is missing.\r\n */\r\n constructor(data: PriceAttributes) {\r\n this.#kind = \"PriceModel\";\r\n if (data.amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative.\");\r\n }\r\n\r\n if (!data.currency) {\r\n throw new InvalidCurrencyCodeError(\"Currency code is required.\");\r\n }\r\n\r\n this.amount = data.amount;\r\n this.currency = data.currency;\r\n }\r\n\r\n get kind() {\r\n return this.#kind;\r\n }\r\n\r\n static isPriceModel(obj: unknown): obj is PriceModel {\r\n return typeof obj === \"object\" &&\r\n obj !== null &&\r\n (obj as any).kind === \"PriceModel\";\r\n }\r\n\r\n /**\r\n * Gets the currency associated with this price instance.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Returns the raw numeric price value.\r\n */\r\n public getAmount(): number {\r\n return this.amount;\r\n }\r\n\r\n /**\r\n *\r\n * @returns PriceData\r\n */\r\n public getDetails(): PriceData {\r\n return {\r\n amount: this.amount,\r\n currency: this.currency\r\n }\r\n }\r\n\r\n /**\r\n * Compares this price with another {@link PriceModel} instance.\r\n *\r\n * The comparison is performed using the numeric price value and is only valid\r\n * when both prices are expressed in the same currency.\r\n *\r\n * ### Comparison result:\r\n * - Returns a **negative number** if this price is **less than** `priceModel`\r\n * - Returns **zero** if both prices are **equal**\r\n * - Returns a **positive number** if this price is **greater than** `priceModel`\r\n *\r\n * @param priceModel - The {@link PriceModel} instance to compare against.\r\n *\r\n * @returns\r\n * A signed number representing the comparison result:\r\n * - `< 0` → this price is lower\r\n * - `0` → prices are equal\r\n * - `> 0` → this price is higher\r\n *\r\n * @throws {Error}\r\n * Throws an error if:\r\n * - `priceModel` is not an instance of {@link PriceModel}\r\n * - The currencies of the two prices do not match\r\n *\r\n * @example\r\n * ```ts\r\n * const a = new PriceModel(\"USD\", 100);\r\n * const b = new PriceModel(\"USD\", 150);\r\n *\r\n * a.compareTo(b); // -50\r\n * b.compareTo(a); // 50\r\n * a.compareTo(a); // 0\r\n * ```\r\n */\r\n public compareTo(priceModel: PriceModel): number {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return this.amount - priceModel.getAmount();\r\n }\r\n\r\n public add(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot add prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.amount + priceModel.getAmount(),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public subtract(priceModel: PriceModel): PriceModel {\r\n if (!PriceModel.isPriceModel(priceModel)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (this.currency !== priceModel.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot subtract prices in different currencies.\");\r\n }\r\n\r\n return new PriceModel({\r\n amount: this.amount - priceModel.getAmount(),\r\n currency: this.currency\r\n });\r\n }\r\n\r\n public multiply(factor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(factor)) {\r\n if (this.currency !== factor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot multiply prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.amount * factor.getAmount(),\r\n currency: this.currency\r\n });\r\n } else if (typeof factor === \"number\" && factor >= 0) {\r\n return new PriceModel({\r\n amount: this.amount * factor,\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a non-negative number.\");\r\n }\r\n\r\n public divide(divisor: number | PriceModel): PriceModel {\r\n if (PriceModel.isPriceModel(divisor)) {\r\n if (this.currency !== divisor.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot divide prices in different currencies.\");\r\n }\r\n return new PriceModel({\r\n amount: this.amount / divisor.getAmount(),\r\n currency: this.currency\r\n });\r\n } else if (typeof divisor === \"number\" && divisor > 0) {\r\n return new PriceModel({\r\n amount: this.amount / divisor,\r\n currency: this.currency\r\n });\r\n }\r\n\r\n throw new InvalidArgumentError(\"Must be a positive number.\");\r\n }\r\n\r\n public min(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((minPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (minPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return minPrice.compareTo(currentPrice) < 0 ? minPrice : currentPrice;\r\n });\r\n }\r\n\r\n public max(...priceModels: PriceModel[]): PriceModel {\r\n if (priceModels.length === 0) {\r\n throw new InvalidArgumentError(\"Must provide at least one PriceModel.\");\r\n }\r\n\r\n return priceModels.reduce((maxPrice, currentPrice) => {\r\n if (!PriceModel.isPriceModel(currentPrice)) {\r\n throw new InvalidArgumentError(\"Must be a PriceModel instance.\");\r\n } else if (maxPrice.getCurrency() !== currentPrice.getCurrency()) {\r\n throw new CurrencyMismatchError(\"Cannot compare prices in different currencies.\");\r\n }\r\n\r\n return maxPrice.compareTo(currentPrice) > 0 ? maxPrice : currentPrice;\r\n });\r\n }\r\n\r\n /**\r\n * Gets a zero value PriceModel for the same currency.\r\n * @returns A PriceModel instance representing zero in the same currency.\r\n */\r\n public zero(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: 0\r\n });\r\n }\r\n\r\n /**\r\n * Checks if the price is zero.\r\n * @returns True if the price is zero, false otherwise.\r\n */\r\n public isZero(): boolean {\r\n return this.amount === 0;\r\n }\r\n\r\n\r\n public round(): PriceModel {\r\n return new PriceModel({\r\n currency: this.currency,\r\n amount: this.getRoundedAmount()\r\n });\r\n }\r\n /**\r\n * Gets the rounded price value based on standard currency rules.\r\n * @returns The numeric price, rounded according to its currency's typical decimal places.\r\n */\r\n public getRoundedAmount(): number {\r\n return PriceModel.getRoundedAmount(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price stored in this instance.\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n public getFormattedString() {\r\n return PriceModel.getFormattedString(this.amount, this.currency);\r\n }\r\n\r\n /**\r\n * Uses the static `PriceModel.getFormattedString` method for the actual formatting.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n toString() {\r\n return this.getFormattedString();\r\n }\r\n\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the amount.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param amount - The initial amount value.\r\n * @param currency - The currency code for formatting.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the amount rounded to the next nearest integer (no decimals). Defaults to false.\r\n * @param options.style - The style of formatting, either 'currency' or 'decimal'. Defaults to 'currency'.\r\n * @param options.currencyDisplay - The display format for the currency symbol. Options are 'symbol', 'narrowSymbol', 'code', or 'name'. Defaults to 'symbol'.\r\n * @returns The formatted price string according to locale rules.\r\n * @throws {Error} If currency code is invalid.\r\n */\r\n static getFormattedString(amount: number, currency: CurrencyCode, options: {\r\n displayAsInteger?: boolean,\r\n style?: 'currency' | 'decimal',\r\n currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name'\r\n } = {\r\n displayAsInteger: false,\r\n style: 'currency',\r\n currencyDisplay: 'symbol'\r\n }): string {\r\n\r\n const locale = CurrencyLocaleMap[currency];\r\n if (!currency || !locale) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for formatting.');\r\n }\r\n\r\n let valueToFormat = amount;\r\n const fractionDigits = options.displayAsInteger ? 0 : PriceModel.getDecimalPlaces(currency);\r\n\r\n let formattingOptions: Intl.NumberFormatOptions = {\r\n style: options.style ?? 'currency',\r\n currency: currency,\r\n signDisplay: 'never',\r\n currencyDisplay: options.currencyDisplay,\r\n minimumFractionDigits: fractionDigits,\r\n maximumFractionDigits: fractionDigits,\r\n };\r\n\r\n if (options.displayAsInteger) {\r\n valueToFormat = Math.ceil(valueToFormat);\r\n }\r\n\r\n try {\r\n return new Intl.NumberFormat(locale, formattingOptions).format(valueToFormat);\r\n } catch (error) {\r\n console.error(`Error formatting price for currency \"${currency}\" and locale \"${locale}\":`, error);\r\n // Basic fallback without symbol if Intl fails completely\r\n return `${CurrencySymbolMap[currency] ?? currency} ${PriceModel.addThousandSeparators(valueToFormat.toFixed(fractionDigits))}`;\r\n }\r\n }\r\n\r\n /**\r\n * Helper method to determine standard decimal places for a currency.\r\n * @param currency - The currency code.\r\n * @returns The number of decimal places (0, 2, or 3 based on common rules).\r\n */\r\n private static getDecimalPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case OperationalCountryCurrency.INR:\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n /**\r\n * Adds basic thousand separators (commas) to a number string.\r\n * Does not handle different locale separators (e.g., periods, spaces).\r\n * @param numStr - The number string (potentially with decimals).\r\n * @returns The number string with commas added.\r\n */\r\n private static addThousandSeparators(numStr: string): string {\r\n const parts = numStr.split('.');\r\n const integerPart = parts[0];\r\n const decimalPart = parts.length > 1 ? '.' + parts[1] : '';\r\n\r\n const formattedInteger = integerPart.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\r\n return formattedInteger + decimalPart;\r\n }\r\n\r\n /**\r\n * Rounds a price value according to the standard decimal places\r\n * for the currency associated with the given country.\r\n *\r\n * @param price - The price value to round. Must be a non-negative number.\r\n * @param currency - The currency code to determine the rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the price is negative or currency is invalid.\r\n */\r\n static getRoundedAmount(amount: number, currency: CurrencyCode): number {\r\n if (amount < 0) {\r\n throw new InvalidPriceAmountError(\"Amount cannot be negative for rounding.\");\r\n }\r\n\r\n if (currency === undefined) {\r\n throw new InvalidCurrencyCodeError('Invalid currency code for rounding.');\r\n }\r\n\r\n const decimalPlaces = PriceModel.getDecimalPlaces(currency);\r\n const multiplier = Math.pow(10, decimalPlaces);\r\n const roundedValue = Math.round(amount * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n}","import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, ISODateTimeUTC } from \"./Common\";\r\nimport { TaxCategory, TaxSystem } from \"./Enum\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport { TaxSlabNotFoundError } from \"./Error\";\r\n\r\nexport type TaxSlabData = {\r\n minUnitPrice: PriceData; // inclusive\r\n maxUnitPrice?: PriceData; // exclusive\r\n rate: number; // e.g. 0.05 = 5%\r\n};\r\n\r\nexport type TaxSlabModel = {\r\n minUnitPrice: PriceModel; // inclusive\r\n maxUnitPrice?: PriceModel; // exclusive\r\n rate: number; // e.g. 0.05 = 5%\r\n};\r\n\r\nexport type TaxSlabs = TaxSlabData[];\r\n\r\nexport type TaxRateBreakdown = {\r\n totalRate: number;\r\n label: string;\r\n components: {\r\n rate: number;\r\n label: string;\r\n type: 'IGST' | 'CGST' | 'SGST' | 'GST' | string;\r\n }[];\r\n};\r\n\r\nexport type TaxFormattingVariant = 'short' | 'long' | 'detailed' | 'percentageOnly';\r\n\r\nexport interface TaxFormattingOptions {\r\n variant?: TaxFormattingVariant;\r\n includeTaxesSuffix?: boolean; // e.g. \"(Incl. Taxes)\"\r\n merchantState?: string;\r\n customerState?: string;\r\n multiline?: boolean;\r\n separator?: string; // custom separator, overrides multiline if provided\r\n}\r\n\r\n/**\r\n * Interface for tax system specific formatting logic.\r\n */\r\nexport interface ITaxSystemFormatter {\r\n getBreakdown(rate: number, country: CountryCode, options?: TaxFormattingOptions): TaxRateBreakdown;\r\n getLongName(country: CountryCode): string;\r\n}\r\n\r\n/**\r\n * Formatter for GST (Goods and Services Tax).\r\n * Handles India-specific components (CGST/SGST/IGST).\r\n */\r\nexport class GSTFormatter implements ITaxSystemFormatter {\r\n getBreakdown(rate: number, country: CountryCode, options?: TaxFormattingOptions): TaxRateBreakdown {\r\n const percentage = rate * 100;\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n\r\n if (country === 'IN' && options?.merchantState && options?.customerState) {\r\n if (options.merchantState.toLowerCase().trim() === options.customerState.toLowerCase().trim()) {\r\n const splitRate = (percentage / 2) % 1 === 0 ? (percentage / 2).toString() : (percentage / 2).toFixed(2).replace(/\\.?0+$/, '');\r\n return {\r\n totalRate: rate,\r\n label: `${splitRate}% CGST + ${splitRate}% SGST`,\r\n components: [\r\n { rate: rate / 2, label: `${splitRate}% CGST`, type: 'CGST' },\r\n { rate: rate / 2, label: `${splitRate}% SGST`, type: 'SGST' }\r\n ]\r\n };\r\n } else {\r\n return {\r\n totalRate: rate,\r\n label: `${rateStr}% IGST`,\r\n components: [{ rate: rate, label: `${rateStr}% IGST`, type: 'IGST' }]\r\n };\r\n }\r\n }\r\n\r\n return {\r\n totalRate: rate,\r\n label: `${rateStr}% GST`,\r\n components: [{ rate: rate, label: `${rateStr}% GST`, type: 'GST' }]\r\n };\r\n }\r\n\r\n getLongName(): string {\r\n return 'Goods and Services Tax';\r\n }\r\n}\r\n\r\n/**\r\n * Registry to manage and provide tax formatters.\r\n */\r\nexport const TaxFormatterRegistry: Record<string, ITaxSystemFormatter> = {\r\n [TaxSystem.GST]: new GSTFormatter(),\r\n};\r\n\r\nexport type TaxRuleAttributes = {\r\n taxRuleId: string;\r\n taxSystem: TaxSystem;\r\n taxCategory: TaxCategory;\r\n country: CountryCode;\r\n slabs: TaxSlabs;\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n} & BaseAttributes;\r\n\r\nexport type TaxRuleData = Required<Omit<TaxRuleAttributes, 'effectiveFrom' | 'effectiveTo'>> & {\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n};\r\n\r\nexport class TaxRuleModel extends BaseModel {\r\n protected taxRuleId: string;\r\n protected taxSystem: TaxSystem;\r\n protected taxCategory: TaxCategory;\r\n protected country: CountryCode;\r\n protected slabs: TaxSlabModel[];\r\n protected effectiveFrom: Date;\r\n protected effectiveTo?: Date;\r\n\r\n /**\r\n * Creates an instance of TaxRuleModel.\r\n * @param data - The initial tax rule attributes.\r\n * @param date - Optional date for creation/modification (defaults to now).\r\n */\r\n constructor(data: TaxRuleAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.taxRuleId = data.taxRuleId;\r\n this.taxSystem = data.taxSystem;\r\n this.taxCategory = data.taxCategory;\r\n this.country = data.country;\r\n this.slabs = data.slabs.map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: new PriceModel(s.minUnitPrice),\r\n maxUnitPrice: s.maxUnitPrice ? new PriceModel(s.maxUnitPrice) : undefined,\r\n }));\r\n this.effectiveFrom = new Date(data.effectiveFrom);\r\n this.effectiveTo = data.effectiveTo ? new Date(data.effectiveTo) : 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 getTaxCategory(): TaxCategory {\r\n return this.taxCategory;\r\n }\r\n\r\n getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n getSlabs(): TaxSlabModel[] {\r\n return this.slabs;\r\n }\r\n\r\n getDetails(): TaxRuleData {\r\n return {\r\n taxRuleId: this.getTaxRuleId(),\r\n taxSystem: this.getTaxSystem(),\r\n taxCategory: this.getTaxCategory(),\r\n country: this.getCountry(),\r\n slabs: this.getSlabs().map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: s.minUnitPrice.getDetails(),\r\n maxUnitPrice: s.maxUnitPrice ? s.maxUnitPrice.getDetails() : undefined,\r\n })),\r\n effectiveFrom: this.effectiveFrom.toISOString(),\r\n effectiveTo: this.effectiveTo ? this.effectiveTo.toISOString() : undefined,\r\n ...super.getDetails()\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 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: TaxCategory, country: CountryCode, at: Date = new Date()): boolean {\r\n return (\r\n this.taxCategory === taxCategory &&\r\n this.country === country &&\r\n this.effectiveFrom <= at &&\r\n (this.effectiveTo ? this.effectiveTo >= at : true)\r\n );\r\n }\r\n\r\n /**\r\n * Calculates the applicable tax rate for a given unit price.\r\n * @param unitPrice - The unit price to find the matching tax slab for.\r\n * @returns The tax rate as a decimal (e.g., 0.05 for 5%).\r\n * @throws {TaxSlabNotFoundError} If no applicable slab or multiple slabs are found.\r\n */\r\n getApplicableTaxRate(unitPrice: PriceModel): number {\r\n return TaxRuleModel.getApplicableTaxRate(unitPrice, this.slabs);\r\n }\r\n\r\n /**\r\n * Returns a user-friendly string representation of the applicable tax rate.\r\n * Handles legal IGST/CGST/SGST formatting for India if states are provided.\r\n * @param unitPrice - The unit price to find the matching tax slab for.\r\n * @param options - Optional states to determine IGST vs CGST/SGST.\r\n * @returns A string like \"18% IGST\", \"9% CGST + 9% SGST\", or \"5% GST\".\r\n */\r\n getTaxRateDisplayString(unitPrice: PriceModel, options?: { merchantState?: string, customerState?: string }): string {\r\n const rate = this.getApplicableTaxRate(unitPrice);\r\n return TaxRuleModel.getTaxRateDisplayString(rate, {\r\n taxSystem: this.taxSystem,\r\n merchantState: options?.merchantState,\r\n customerState: options?.customerState\r\n });\r\n }\r\n\r\n /**\r\n * Returns a detailed breakdown of the tax rate into its components (e.g., CGST/SGST).\r\n */\r\n getTaxRateBreakdown(unitPrice: PriceModel, options?: TaxFormattingOptions): TaxRateBreakdown {\r\n const rate = this.getApplicableTaxRate(unitPrice);\r\n const formatter = TaxFormatterRegistry[this.taxSystem];\r\n if (formatter) {\r\n return formatter.getBreakdown(rate, this.country, options);\r\n }\r\n\r\n // Default fallback\r\n const percentage = rate * 100;\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n const label = `${rateStr}% ${this.taxSystem}`;\r\n return {\r\n totalRate: rate,\r\n label: label,\r\n components: [{ rate, label, type: this.taxSystem }]\r\n };\r\n }\r\n\r\n /**\r\n * Formats a tax rate based on versatile options for UI use cases.\r\n */\r\n getFormattedTaxRate(unitPrice: PriceModel, options: TaxFormattingOptions = {}): string {\r\n const rate = this.getApplicableTaxRate(unitPrice);\r\n const percentage = rate * 100;\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n const variant = options.variant || 'short';\r\n let result = '';\r\n\r\n switch (variant) {\r\n case 'percentageOnly':\r\n result = `${rateStr}%`;\r\n break;\r\n case 'detailed':\r\n const breakdown = this.getTaxRateBreakdown(unitPrice, options);\r\n const separator = options.separator || (options.multiline ? '\\n' : ' + ');\r\n result = breakdown.components.map(c => c.label).join(separator);\r\n break;\r\n case 'long':\r\n const formatter = TaxFormatterRegistry[this.taxSystem];\r\n const systemLongName = formatter ? formatter.getLongName(this.country) : this.taxSystem.toString();\r\n result = `${rateStr}% ${systemLongName}`;\r\n break;\r\n case 'short':\r\n default:\r\n result = `${rateStr}% ${this.taxSystem}`;\r\n break;\r\n }\r\n\r\n if (options.includeTaxesSuffix) {\r\n result += ' (Incl. Taxes)';\r\n }\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Static method to find the applicable tax rate from a list of slabs.\r\n */\r\n static getApplicableTaxRate(unitPrice: PriceModel, taxSlabs: TaxSlabModel[]): number {\r\n const slabs = taxSlabs.filter(s =>\r\n (s.minUnitPrice === undefined || unitPrice.compareTo(s.minUnitPrice) >= 0) &&\r\n (s.maxUnitPrice === undefined || unitPrice.compareTo(s.maxUnitPrice) < 0)\r\n );\r\n\r\n if (slabs.length !== 1) {\r\n throw new TaxSlabNotFoundError();\r\n }\r\n\r\n return slabs[0].rate;\r\n }\r\n\r\n /**\r\n * Static method to format a tax rate as a display string.\r\n * Handles legal IGST/CGST/SGST formatting for India if states are provided.\r\n * @param rate - The tax rate as a decimal (e.g., 0.18).\r\n * @param options - Configuration for tax system name and states.\r\n * @returns A formatted string.\r\n */\r\n static getTaxRateDisplayString(rate: number, options: {\r\n taxSystem?: string,\r\n merchantState?: string,\r\n customerState?: string\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 (options.taxSystem === TaxSystem.GST && options.merchantState && options.customerState) {\r\n if (options.merchantState.toLowerCase().trim() === options.customerState.toLowerCase().trim()) {\r\n const splitRate = (percentage / 2) % 1 === 0 ? (percentage / 2).toString() : (percentage / 2).toFixed(2).replace(/\\.?0+$/, '');\r\n return `${splitRate}% CGST + ${splitRate}% SGST`;\r\n } else {\r\n return `${rateStr}% IGST`;\r\n }\r\n }\r\n\r\n return options.taxSystem ? `${rateStr}% ${options.taxSystem}` : `${rateStr}%`;\r\n }\r\n}\r\n"]}
@@ -1,2 +1,2 @@
1
- export{a as TaxRuleModel}from'../chunk-YOEUA6R6.mjs';import'../chunk-R32ZSPV6.mjs';import'../chunk-72DR3HF2.mjs';import'../chunk-DGFO2MH6.mjs';import'../chunk-55SOBG62.mjs';//# sourceMappingURL=TaxRule.mjs.map
1
+ export{a as GSTFormatter,b as TaxFormatterRegistry,c as TaxRuleModel}from'../chunk-TUT4BB3Z.mjs';import'../chunk-R32ZSPV6.mjs';import'../chunk-72DR3HF2.mjs';import'../chunk-DGFO2MH6.mjs';import'../chunk-6KCJVEZD.mjs';//# sourceMappingURL=TaxRule.mjs.map
2
2
  //# sourceMappingURL=TaxRule.mjs.map
@@ -0,0 +1,2 @@
1
+ var i=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){return this.customFields[e]??null}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return {...this.customFields}}},s=class extends i{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,t,d,o){this.modifiedBy={id:e,authType:t,requestId:d,lambdaName:o};}};export{i as a,s as b};//# sourceMappingURL=chunk-6KCJVEZD.mjs.map
2
+ //# sourceMappingURL=chunk-6KCJVEZD.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/Classes/Base.ts"],"names":["CustomFieldModel","data","date","fieldName","value","BaseModel","id","authType","requestId","lambdaName"],"mappings":"AAWaA,IAAAA,CAAAA,CAAN,KAAuB,CAClB,YAAA,CACV,YAAYC,CAA6BC,CAAAA,CAAAA,CAAa,IAAI,IAAA,CAAQ,CAChE,IAAA,CAAK,aAAe,CAAE,GAAGD,CAAK,CAAA,YAAa,EAC7C,CAOA,eAAeE,CAAwB,CAAA,CACrC,OAAO,IAAA,CAAK,YAAaA,CAAAA,CAAS,GAAK,IACzC,CAQA,eAAeA,CAAmBC,CAAAA,CAAAA,CAAkB,CAClD,IAAK,CAAA,YAAA,CAAaD,CAAS,CAAA,CAAIC,EACjC,CAMA,oBAAmC,CACjC,OAAO,CAAE,GAAG,IAAK,CAAA,YAAa,CAChC,CACF,CAAA,CAsBq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AQ,EAC3C,CAMA,aAAA,EAA4B,CAC1B,OAAO,CAAE,GAAG,IAAA,CAAK,UAAW,CAC9B,CAMA,aAAcK,CAAAA,CAAAA,CAAaC,CAAqBC,CAAAA,CAAAA,CAAoBC,CAA2B,CAAA,CAC7F,KAAK,UAAa,CAAA,CAChB,EAAAH,CAAAA,CAAAA,CACA,QAAAC,CAAAA,CAAAA,CACA,UAAAC,CACA,CAAA,UAAA,CAAAC,CACF,EACF,CACF","file":"chunk-6KCJVEZD.mjs","sourcesContent":["import { AuthType } from \"../Auth\";\r\nimport { ISODateTimeUTC, Prettify } from \"./Common\";\r\n\r\nexport interface CustomFields {\r\n [key: string]: any;\r\n}\r\n\r\nexport type CustomFieldAttributes = {\r\n customFields?: CustomFields;\r\n}\r\n\r\nexport class CustomFieldModel {\r\n protected customFields: CustomFields;\r\n constructor(data: CustomFieldAttributes, date: Date = new Date()) {\r\n this.customFields = { ...data.customFields };\r\n }\r\n\r\n /**\r\n * Retrieves the value of a specific custom field.\r\n * @param fieldName - The name (key) of the custom field to retrieve.\r\n * @returns The value of the custom field, or null if the field does not exist.\r\n */\r\n getCustomField(fieldName: string): any {\r\n return this.customFields[fieldName] ?? null;\r\n }\r\n\r\n /**\r\n * Sets the value of a specific custom field.\r\n * Also updates the modification timestamp and increments the version.\r\n * @param fieldName - The name (key) of the custom field to set.\r\n * @param value - The value to assign to the custom field.\r\n */\r\n setCustomField(fieldName: string, value: any): void {\r\n this.customFields[fieldName] = value;\r\n }\r\n\r\n /**\r\n * Retrieves a shallow copy of all custom fields associated with the instance.\r\n * @returns An object containing all custom fields.\r\n */\r\n getAllCustomFields(): CustomFields {\r\n return { ...this.customFields };\r\n }\r\n}\r\n\r\nexport type ModifiedBy = {\r\n id?: string;\r\n authType?: string;\r\n requestId?: string;\r\n lambdaName?: string;\r\n}\r\n\r\nexport type BaseAttributes = Prettify<CustomFieldAttributes & {\r\n version?: number;\r\n createdAt?: ISODateTimeUTC;\r\n modifiedAt?: ISODateTimeUTC;\r\n modifiedBy?: ModifiedBy;\r\n}>;\r\n\r\nexport type BaseData = Required<BaseAttributes>;\r\n\r\n/**\r\n * Provides common foundational properties and methods for other data models.\r\n * Handles tracking of custom fields, versioning, and timestamps.\r\n */\r\nexport default class BaseModel extends CustomFieldModel {\r\n protected version: number;\r\n protected createdAt: ISODateTimeUTC;\r\n protected modifiedAt: ISODateTimeUTC;\r\n protected modifiedBy: ModifiedBy;\r\n\r\n /**\r\n * Creates an instance of BaseModel.\r\n * Initializes common properties like timestamps, version, and custom fields.\r\n * @param data - Optional initial attributes for the base model.\r\n * @param date - Optional date object to use for default timestamps (defaults to current time).\r\n */\r\n constructor(data: BaseAttributes, date: Date = new Date()) {\r\n super(data);\r\n this.version = data.version ?? 1;\r\n this.createdAt = data.createdAt && !isNaN(Date.parse(data.createdAt))\r\n ?\r\n new Date(data.createdAt).toISOString()\r\n :\r\n date.toISOString();\r\n this.modifiedAt = data.modifiedAt && !isNaN(Date.parse(data.modifiedAt))\r\n ? new Date(data.modifiedAt).toISOString()\r\n : date.toISOString();\r\n\r\n this.modifiedBy = { ...data.modifiedBy };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the base model's current state.\r\n * @returns BaseData object containing common properties.\r\n */\r\n getDetails(): BaseData {\r\n return {\r\n customFields: this.getAllCustomFields(), // Use getter to return a copy\r\n version: this.getVersion(),\r\n createdAt: this.getCreatedAt(),\r\n modifiedAt: this.getModifiedAt(),\r\n modifiedBy: this.getModifiedBy(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the current version number of the model instance.\r\n * @returns The version number.\r\n */\r\n getVersion(): number {\r\n return this.version;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as an ISO 8601 string.\r\n * @returns The creation timestamp string.\r\n */\r\n getCreatedAt(): string {\r\n return this.createdAt;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as a Unix epoch time (milliseconds).\r\n * @returns The creation time in milliseconds since the epoch.\r\n */\r\n getCreatedAtTime(): number {\r\n return new Date(this.createdAt).getTime();\r\n }\r\n\r\n\r\n /**\r\n * Gets the last modification timestamp as an ISO 8601 string.\r\n * @returns The last modification timestamp string.\r\n */\r\n getModifiedAt(): string {\r\n return this.modifiedAt;\r\n }\r\n\r\n /**\r\n * Gets the last modification timestamp as a Unix epoch time (milliseconds).\r\n * @returns The last modification time in milliseconds since the epoch.\r\n */\r\n getModifiedAtTime(): number {\r\n return new Date(this.modifiedAt).getTime();\r\n }\r\n\r\n /**\r\n * Gets the identifier of the user or process that last modified the instance.\r\n * @returns\r\n */\r\n getModifiedBy(): ModifiedBy {\r\n return { ...this.modifiedBy };\r\n }\r\n\r\n /**\r\n * Sets the identifier of the user or process that last modified the instance.\r\n * @param modifiedBy - The identifier string.\r\n */\r\n setModifiedBy(id?: string, authType?: AuthType, requestId?: string, lambdaName?: string): void {\r\n this.modifiedBy = {\r\n id,\r\n authType,\r\n requestId,\r\n lambdaName,\r\n };\r\n }\r\n}\r\n"]}
@@ -0,0 +1,2 @@
1
+ import {c}from'./chunk-TUT4BB3Z.mjs';import {a as a$1}from'./chunk-ZAHR3SJ2.mjs';import {a as a$3}from'./chunk-ZVLJ5BAG.mjs';import {a as a$2}from'./chunk-R32ZSPV6.mjs';import {e}from'./chunk-72DR3HF2.mjs';import {b}from'./chunk-7LEGYAOJ.mjs';import {b as b$1,d,e as e$1,g,h,i}from'./chunk-DGFO2MH6.mjs';import {a}from'./chunk-6KCJVEZD.mjs';var p=class extends a{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){super(t),this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=a$1.deepClone(t.selectionAttributes),this.name=a$1.deepClone(t.name),this.specifications=a$1.deepClone(t.specifications),this.primaryImage=new b(t.primaryImage),this.subItems=a$1.deepClone(t.subItems);let i=new Set;this.subItems.forEach(e=>{if(i.has(e.size))throw new b$1(e.size);i.add(e.size);}),this.pricing={unitPrice:new a$2(t.pricing.unitPrice),tierPricing:new a$3(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,tax:{taxRuleId:t.pricing.tax.taxRuleId,taxSystem:t.pricing.tax.taxSystem,country:t.pricing.tax.country,rate:t.pricing.tax.rate,taxSlabs:t.pricing.tax.taxSlabs.map(e=>({rate:e.rate,minUnitPrice:new a$2(e.minUnitPrice),maxUnitPrice:e.maxUnitPrice?new a$2(e.maxUnitPrice):void 0}))}},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,subtotal:new a$2(t.total.subtotal),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([e,a])=>[e,new a$2(a)])),taxableAmount:new a$2(t.total.taxableAmount),taxTotal:new a$2(t.total.taxTotal),grandTotal:new a$2(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return a$1.deepClone(this.selectionAttributes)}getName(t){return t?a$1.deepClone(this.name[t]??this.name[e[t]]??this.name.en):a$1.deepClone(this.name)}getSpecifications(t){return t?a$1.deepClone(this.specifications[t]??this.specifications[e[t]]??this.specifications.en):a$1.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return a$1.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:{taxRuleId:this.pricing.tax.taxRuleId,taxSystem:this.pricing.tax.taxSystem,country:this.pricing.tax.country,rate:this.pricing.tax.rate,taxSlabs:this.pricing.tax.taxSlabs}}}getState(){return this.state}getTotal(){return {quantity:this.total.quantity,subtotal:this.total.subtotal,taxableAmount:this.total.taxableAmount,taxTotal:this.total.taxTotal,discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,i])=>[t,i])),grandTotal:this.total.grandTotal}}getDetails(){return {id:this.getId(),productKey:this.getProductKey(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:this.getPricing().unitPrice.getDetails(),tierPricing:this.getPricing().tierPricing.getDetails(),taxCategory:this.getPricing().taxCategory,tax:{taxRuleId:this.getPricing().tax.taxRuleId,taxSystem:this.getPricing().tax.taxSystem,country:this.getPricing().tax.country,rate:this.getPricing().tax.rate,taxSlabs:this.getPricing().tax.taxSlabs.map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0}))}},state:this.getState(),total:{quantity:this.getTotal().quantity,subtotal:this.getTotal().subtotal.getDetails(),taxableAmount:this.getTotal().taxableAmount.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),discounts:Object.fromEntries(Object.entries(this.getTotal().discounts).map(([t,i])=>[t,i.getDetails()])),grandTotal:this.getTotal().grandTotal.getDetails()},customFields:this.getAllCustomFields()}}addSubItems(t,i){t.forEach(e=>{let a=this.subItems.find(n=>n.size===e.size);a?a.quantity=i?a.quantity+e.quantity:e.quantity:this.subItems.push(e);}),this.subItems=this.subItems.filter(e=>e.quantity>0),this.calculateTotals();}updateProductData(t,i,e){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new d;if(!t.getIsActive())throw new e$1;this.subItems.forEach(c=>{if(!t.validateSize(c.size))throw new g});let a=t.getPriceDetails(i);if(!a||a.getBaseUnitPrice().getCurrency()!==e)throw new h;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let n=this.subItems.reduce((c,l)=>c+l.quantity,0),{unitPrice:s}=a.getApplicableTier(n);this.pricing={unitPrice:s,tierPricing:a,taxCategory:a.getTaxCategory(),tax:this.pricing.tax},this.calculateTotals();}updateDiscounts(t){let i={};t.forEach(e=>{i[e.coupon.getCode()]=e.amount;}),this.total.discounts=i,this.calculateTotals();}updateTax(t){if(!t.appliesTo(this.pricing.taxCategory,this.pricing.tax.country))throw new i;let i$1=this.total.quantity>0?this.total.taxableAmount.divide(this.total.quantity):this.total.taxableAmount.zero();this.pricing.tax={taxRuleId:t.getTaxRuleId(),taxSystem:t.getTaxSystem(),country:t.getCountry(),rate:t.getApplicableTaxRate(i$1),taxSlabs:t.getSlabs()},this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),i=this.subItems.reduce((u,g)=>u+g.quantity,0),{unitPrice:e}=this.pricing.tierPricing.getApplicableTier(i),a=e.multiply(i),n=Object.values(this.total.discounts).reduce((u,g)=>u.add(g),t),s=a.subtract(n),c$1=i>0?s.divide(i):t,l=c.getApplicableTaxRate(c$1,this.pricing.tax.taxSlabs),h=s.multiply(l).round(),A=a.subtract(n).add(h);this.total={quantity:i,subtotal:a,taxableAmount:s,taxTotal:h,discounts:this.total.discounts,grandTotal:A};}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new b({sources:{original:""}}),this.subItems=[],this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:this.pricing.tax},this.total={quantity:0,subtotal:t,taxableAmount:t,taxTotal:t,discounts:{},grandTotal:t};}};export{p as a};//# sourceMappingURL=chunk-7NLMXN4H.mjs.map
2
+ //# sourceMappingURL=chunk-7NLMXN4H.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/Classes/LineItem.ts"],"names":["LineItemModel","CustomFieldModel","data","Utils_default","ImageInfoModel","uniqueSelectionAttributes","item","DuplicateSizeError","PriceModel","TieredPriceModel","s","couponCode","discount","locale","LocaleLanguageMap","subItems","addQuantity","subItem","existingSubItem","sub","product","cartCountry","cartCurrency","ProductMismatchError","ProductInactiveError","SizeMismatchError","productPricing","PricingNotFoundError","quantity","sum","unitPrice","appliedDiscounts","lineItemDiscounts","taxRule","InvalidTaxRuleError","taxableUnitPrice","zero","totalQuantity","subTotal","discounts","taxableAmount","unitTaxbleAmount","taxRate","TaxRuleModel","taxTotal","grandTotal"],"mappings":"qV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,CAAA,WAAA,CAC1B,GAAK,CAAA,IAAA,CAAK,OAAQ,CAAA,GACpB,EACA,IAAK,CAAA,KAAA,CAAQ,CACX,QAAA,CAAU,CACV,CAAA,QAAA,CAAUA,CACV,CAAA,aAAA,CAAeA,CACf,CAAA,QAAA,CAAUA,CACV,CAAA,SAAA,CAAW,EAAC,CACZ,UAAYA,CAAAA,CACd,EACF,CACF","file":"chunk-7NLMXN4H.mjs","sourcesContent":["import Utils from \"../Utils\";\r\nimport { Color, CountryCode, CurrencyCode, LocaleCode, LocalizedString, LocalizedValue } from \"./Common\";\r\nimport CouponModel from \"./Coupon\";\r\nimport { LineItemState, LocaleLanguageMap, TaxCategory, TaxSystem } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport ProductModel, { ProductSelectionAttributes, ProductSpecification, SelectionAttributes } from \"./Product\";\r\nimport { TaxRuleModel, TaxSlabModel, TaxSlabs } from \"./TaxRule\";\r\nimport { TieredPriceData, TieredPriceModel } from \"./TieredPrice\";\r\nimport {\r\n DuplicateSizeError,\r\n ProductMismatchError,\r\n ProductInactiveError,\r\n SizeMismatchError,\r\n PricingNotFoundError,\r\n InvalidTaxRuleError\r\n} from \"./Error\";\r\nimport { CustomFieldAttributes, CustomFieldModel, CustomFields } from \"./Base\";\r\n\r\nexport type SubItem = {\r\n size: string | 'ONESIZE';\r\n quantity: number;\r\n};\r\n\r\nexport type LineItemPricing = {\r\n unitPrice: PriceData;\r\n tierPricing: TieredPriceData;\r\n taxCategory: TaxCategory;\r\n tax: {\r\n taxRuleId: string;\r\n taxSystem: TaxSystem;\r\n country: CountryCode;\r\n rate: number;\r\n taxSlabs: TaxSlabs;\r\n };\r\n};\r\n\r\nexport type LineItemTotals = {\r\n quantity: number;\r\n subtotal: PriceData;\r\n discounts: Record<string, PriceData>; // couponCode -> discount mapping\r\n taxableAmount: PriceData; // subtotal - discount\r\n taxTotal: PriceData;\r\n grandTotal: PriceData;\r\n};\r\n\r\nexport type LineItemAttributes = CustomFieldAttributes & {\r\n id: string;\r\n\r\n productKey: string;\r\n selectionAttributes: SelectionAttributes;\r\n\r\n name: LocalizedString;\r\n specifications: LocalizedValue<ProductSpecification>;\r\n primaryImage: ImageInfoData;\r\n\r\n subItems: SubItem[];\r\n\r\n pricing: LineItemPricing;\r\n\r\n state?: LineItemState;\r\n total: LineItemTotals;\r\n}\r\n\r\nexport type LineItemData = Required<LineItemAttributes>;\r\n\r\n/**\r\n * Represents a line item within a shopping cart.\r\n */\r\nexport default class LineItemModel extends CustomFieldModel {\r\n protected id: string;\r\n protected productKey: string;\r\n protected selectionAttributes: SelectionAttributes;\r\n\r\n protected name: LocalizedString;\r\n protected specifications: LocalizedValue<ProductSpecification>;\r\n protected primaryImage: ImageInfoModel;\r\n protected subItems: SubItem[];\r\n protected pricing: {\r\n unitPrice: PriceModel;\r\n tierPricing: TieredPriceModel;\r\n taxCategory: TaxCategory;\r\n tax: {\r\n taxRuleId: string;\r\n taxSystem: TaxSystem;\r\n country: CountryCode;\r\n taxSlabs: TaxSlabModel[];\r\n rate: number;\r\n };\r\n };\r\n\r\n protected state: LineItemState;\r\n protected total: {\r\n quantity: number;\r\n subtotal: PriceModel;\r\n discounts: Record<string, PriceModel>;\r\n taxableAmount: PriceModel; // subtotal - discount\r\n\r\n taxTotal: PriceModel;\r\n grandTotal: PriceModel;\r\n };\r\n\r\n /**\r\n * Creates an instance of LineItemModel.\r\n * @param data - The initial line item attributes.\r\n */\r\n constructor(data: LineItemAttributes) {\r\n super(data);\r\n this.id = data.id;\r\n this.productKey = data.productKey;\r\n this.selectionAttributes = Utils.deepClone(data.selectionAttributes);\r\n\r\n this.name = Utils.deepClone(data.name);\r\n this.specifications = Utils.deepClone(data.specifications);\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.subItems = Utils.deepClone(data.subItems);\r\n\r\n let uniqueSelectionAttributes = new Set();\r\n this.subItems.forEach(item => {\r\n if (uniqueSelectionAttributes.has(item.size)) {\r\n throw new DuplicateSizeError(item.size);\r\n }\r\n uniqueSelectionAttributes.add(item.size);\r\n });\r\n\r\n this.pricing = {\r\n unitPrice: new PriceModel(data.pricing.unitPrice),\r\n tierPricing: new TieredPriceModel(data.pricing.tierPricing),\r\n taxCategory: data.pricing.taxCategory,\r\n tax: {\r\n taxRuleId: data.pricing.tax.taxRuleId,\r\n taxSystem: data.pricing.tax.taxSystem,\r\n country: data.pricing.tax.country,\r\n rate: data.pricing.tax.rate,\r\n taxSlabs: data.pricing.tax.taxSlabs.map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: new PriceModel(s.minUnitPrice),\r\n maxUnitPrice: s.maxUnitPrice ? new PriceModel(s.maxUnitPrice) : undefined,\r\n })),\r\n },\r\n }\r\n\r\n this.state = data.state ?? LineItemState.INITIAL;\r\n\r\n this.total = {\r\n quantity: data.total.quantity,\r\n subtotal: new PriceModel(data.total.subtotal),\r\n discounts: Object.fromEntries(\r\n Object.entries(data.total.discounts).map(([couponCode, discount]) => [\r\n couponCode,\r\n new PriceModel(discount),\r\n ])\r\n ),\r\n taxableAmount: new PriceModel(data.total.taxableAmount),\r\n taxTotal: new PriceModel(data.total.taxTotal),\r\n grandTotal: new PriceModel(data.total.grandTotal),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the unique identifier of the line item.\r\n * @returns The unique ID string.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the product key associated with this line item.\r\n * @returns The product key string.\r\n */\r\n getProductKey(): string {\r\n return this.productKey;\r\n }\r\n\r\n /**\r\n * Gets the selection attributes (e.g., size, color) for this line item.\r\n * @returns A copy of the selection attributes object.\r\n */\r\n getSelectionAttributes(): SelectionAttributes {\r\n return Utils.deepClone(this.selectionAttributes);\r\n }\r\n\r\n /**\r\n * Gets the full localized product name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the product name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return Utils.deepClone(this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en);\r\n } else {\r\n return Utils.deepClone(this.name);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product specifications object.\r\n * @returns Product Specifications\r\n */\r\n getSpecifications(): LocalizedValue<ProductSpecification>\r\n /**\r\n * Gets the product specifications for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The ProductSpecification object for the specified locale, or undefined if not found.\r\n */\r\n getSpecifications(locale: LocaleCode): ProductSpecification | undefined\r\n getSpecifications(locale?: LocaleCode): LocalizedValue<ProductSpecification> | ProductSpecification | undefined {\r\n if (locale) {\r\n return Utils.deepClone(this.specifications[locale] ?? this.specifications[LocaleLanguageMap[locale]] ?? this.specifications.en);\r\n } else {\r\n return Utils.deepClone(this.specifications);\r\n }\r\n }\r\n\r\n /**\r\n * Gets the image information model for this line item.\r\n * @returns The ImageInfoModel instance.\r\n */\r\n getImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /**\r\n * Gets the sub-items (size/quantity breakdown).\r\n * @returns A copy of the array of SubItems.\r\n */\r\n getSubItems(): SubItem[] {\r\n return Utils.deepClone(this.subItems);\r\n }\r\n\r\n /**\r\n * Gets the total quantity for this line item across all sub-items.\r\n * @returns The total quantity as a number.\r\n */\r\n getTotalQuantity(): number {\r\n return this.total.quantity;\r\n }\r\n\r\n /**\r\n * Gets the pricing information model for this line item.\r\n * @returns An object containing unit price, tiered pricing, tax category, and tax details.\r\n */\r\n getPricing() {\r\n return {\r\n unitPrice: this.pricing.unitPrice,\r\n tierPricing: this.pricing.tierPricing,\r\n taxCategory: this.pricing.taxCategory,\r\n tax: {\r\n taxRuleId: this.pricing.tax.taxRuleId,\r\n taxSystem: this.pricing.tax.taxSystem,\r\n country: this.pricing.tax.country,\r\n rate: this.pricing.tax.rate,\r\n taxSlabs: this.pricing.tax.taxSlabs,\r\n }\r\n };\r\n }\r\n\r\n /**\r\n * Gets the current state of the line item.\r\n * @returns The LineItemState enum value.\r\n */\r\n getState() {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the total price for this line item (including all sub-items).\r\n * @returns An object containing line item totals including subtotal, tax, discounts, and grand total.\r\n */\r\n getTotal() {\r\n return {\r\n quantity: this.total.quantity,\r\n subtotal: this.total.subtotal,\r\n taxableAmount: this.total.taxableAmount,\r\n taxTotal: this.total.taxTotal,\r\n discounts: Object.fromEntries(\r\n Object.entries(this.total.discounts).map(([couponCode, discount]) => [\r\n couponCode,\r\n discount,\r\n ])\r\n ),\r\n grandTotal: this.total.grandTotal,\r\n };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the line item's details.\r\n * @returns LineItemData.\r\n */\r\n getDetails(): LineItemData {\r\n return {\r\n id: this.getId(),\r\n productKey: this.getProductKey(),\r\n selectionAttributes: this.getSelectionAttributes(),\r\n name: this.getName(),\r\n specifications: this.getSpecifications(),\r\n primaryImage: this.getImage().getDetails(),\r\n subItems: this.getSubItems(),\r\n pricing: {\r\n unitPrice: this.getPricing().unitPrice.getDetails(),\r\n tierPricing: this.getPricing().tierPricing.getDetails(),\r\n taxCategory: this.getPricing().taxCategory,\r\n tax: {\r\n taxRuleId: this.getPricing().tax.taxRuleId,\r\n taxSystem: this.getPricing().tax.taxSystem,\r\n country: this.getPricing().tax.country,\r\n rate: this.getPricing().tax.rate,\r\n taxSlabs: this.getPricing().tax.taxSlabs.map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: s.minUnitPrice.getDetails(),\r\n maxUnitPrice: s.maxUnitPrice ? s.maxUnitPrice.getDetails() : undefined,\r\n })),\r\n }\r\n },\r\n state: this.getState(),\r\n total: {\r\n quantity: this.getTotal().quantity,\r\n subtotal: this.getTotal().subtotal.getDetails(),\r\n taxableAmount: this.getTotal().taxableAmount.getDetails(),\r\n taxTotal: this.getTotal().taxTotal.getDetails(),\r\n discounts: Object.fromEntries(\r\n Object.entries(this.getTotal().discounts).map(([couponCode, discount]) => [\r\n couponCode,\r\n discount.getDetails(),\r\n ])\r\n ),\r\n grandTotal: this.getTotal().grandTotal.getDetails(),\r\n },\r\n customFields: this.getAllCustomFields()\r\n };\r\n }\r\n\r\n /**\r\n * Adds or updates sub-items (e.g., sizes with quantities) to the line item.\r\n * If a sub-item with the same size already exists, its quantity is either\r\n * updated by adding the new quantity or replaced entirely, based on the `addQuantity` flag.\r\n * Sub-items with a resulting quantity of 0 are removed.\r\n * @param subItems - An array of `SubItem` objects to add or update.\r\n * @param addQuantity - If true, adds the quantity from `subItem` to the existing quantity.\r\n * If false, replaces the existing quantity with the one from `subItem`.\r\n */\r\n addSubItems(subItems: SubItem[], addQuantity: boolean): void {\r\n subItems.forEach(subItem => {\r\n const existingSubItem = this.subItems.find(item => item.size === subItem.size);\r\n if (existingSubItem) {\r\n existingSubItem.quantity = addQuantity ? existingSubItem.quantity + subItem.quantity : subItem.quantity;\r\n } else {\r\n this.subItems.push(subItem);\r\n }\r\n })\r\n this.subItems = this.subItems.filter(sub => sub.quantity > 0);\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the line item with the latest product data (price, image, name, specifications).\r\n * Validates that the product matches the line item's selection and is active.\r\n * @param product - The product model to update from.\r\n * @param cartCountry - The country code for pricing context.\r\n * @param cartCurrency - The currency code for pricing context.\r\n * @throws {Error} If product mismatch, inactive, size mismatch, or pricing missing.\r\n */\r\n public updateProductData(product: ProductModel, cartCountry: CountryCode, cartCurrency: CurrencyCode): void {\r\n if (this.productKey !== product.getKey() || !product.validateSelectionAttribute(this.selectionAttributes)) {\r\n throw new ProductMismatchError();\r\n } else if (!product.getIsActive()) {\r\n throw new ProductInactiveError();\r\n }\r\n\r\n this.subItems.forEach(subItem => {\r\n if (!product.validateSize(subItem.size)) {\r\n throw new SizeMismatchError();\r\n }\r\n });\r\n\r\n const productPricing = product.getPriceDetails(cartCountry);\r\n if (!productPricing || productPricing.getBaseUnitPrice().getCurrency() !== cartCurrency) {\r\n throw new PricingNotFoundError();\r\n }\r\n this.name = product.getName();\r\n this.specifications = product.getSpecifications();\r\n this.primaryImage = product.getImages(this.selectionAttributes).primary;\r\n\r\n const quantity = this.subItems.reduce((sum, s) => sum + s.quantity, 0);\r\n const { unitPrice } = productPricing.getApplicableTier(quantity);\r\n\r\n this.pricing = {\r\n unitPrice: unitPrice,\r\n tierPricing: productPricing,\r\n taxCategory: productPricing.getTaxCategory(),\r\n tax: this.pricing.tax\r\n }\r\n\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the discounts applied to this line item and recalculates totals.\r\n * @param appliedDiscounts - List of coupons and their allocated discount amounts.\r\n */\r\n public updateDiscounts(appliedDiscounts: { coupon: CouponModel, amount: PriceModel }[]): void {\r\n let lineItemDiscounts = {} as Record<string, PriceModel>;\r\n appliedDiscounts.forEach(discount => {\r\n lineItemDiscounts[discount.coupon.getCode()] = discount.amount;\r\n });\r\n\r\n this.total.discounts = lineItemDiscounts;\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Updates the tax rule for this line item and recalculates totals.\r\n * @param taxRule - The new tax rule to apply.\r\n * @throws {Error} If the tax rule category does not match the item's tax category.\r\n */\r\n public updateTax(taxRule: TaxRuleModel): void {\r\n if (!taxRule.appliesTo(this.pricing.taxCategory, this.pricing.tax.country)) {\r\n throw new InvalidTaxRuleError();\r\n }\r\n\r\n const taxableUnitPrice = this.total.quantity > 0 ? \r\n this.total.taxableAmount.divide(this.total.quantity) \r\n : \r\n this.total.taxableAmount.zero();\r\n\r\n this.pricing.tax = {\r\n taxRuleId: taxRule.getTaxRuleId(),\r\n taxSystem: taxRule.getTaxSystem(),\r\n country: taxRule.getCountry(),\r\n rate: taxRule.getApplicableTaxRate(taxableUnitPrice),\r\n taxSlabs: taxRule.getSlabs(),\r\n };\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Recalculates the line item totals based on current quantity, unit price, discounts, and tax rates.\r\n */\r\n public calculateTotals(): void {\r\n const zero = this.pricing.unitPrice.zero();\r\n const totalQuantity = this.subItems.reduce((sum, s) => sum + s.quantity, 0);\r\n const { unitPrice } = this.pricing.tierPricing.getApplicableTier(totalQuantity);\r\n const subTotal = unitPrice.multiply(totalQuantity);\r\n const discounts = Object.values(this.total.discounts).reduce((sum, s) => sum.add(s), zero);\r\n const taxableAmount = subTotal.subtract(discounts);\r\n const unitTaxbleAmount = totalQuantity > 0 ? taxableAmount.divide(totalQuantity) : zero;\r\n const taxRate = TaxRuleModel.getApplicableTaxRate(unitTaxbleAmount, this.pricing.tax.taxSlabs);\r\n const taxTotal = taxableAmount.multiply(taxRate).round();\r\n const grandTotal = subTotal.subtract(discounts).add(taxTotal);\r\n\r\n this.total = {\r\n quantity: totalQuantity,\r\n subtotal: subTotal,\r\n taxableAmount: taxableAmount,\r\n taxTotal: taxTotal,\r\n discounts: this.total.discounts,\r\n grandTotal: grandTotal\r\n }\r\n }\r\n\r\n /**\r\n * Resets the line item's properties to their default empty or initial state.\r\n * Useful for clearing out line item data without creating a new instance.\r\n * Recalculates total quantity and price total afterwards (which will be zero).\r\n */\r\n clearLineItem(): void {\r\n const zero = this.pricing.unitPrice.zero()\r\n this.id = '';\r\n this.productKey = '';\r\n this.selectionAttributes = { color: { name: '' } };\r\n this.name = { en: '' };\r\n this.primaryImage = new ImageInfoModel({ sources: { original: '' } });\r\n this.subItems = [];\r\n this.pricing = {\r\n unitPrice: zero,\r\n tierPricing: this.pricing.tierPricing,\r\n taxCategory: this.pricing.taxCategory,\r\n tax: this.pricing.tax\r\n }\r\n this.total = {\r\n quantity: 0,\r\n subtotal: zero,\r\n taxableAmount: zero,\r\n taxTotal: zero,\r\n discounts: {},\r\n grandTotal: zero\r\n };\r\n }\r\n}"]}
@@ -0,0 +1,2 @@
1
+ import {a}from'./chunk-7NLMXN4H.mjs';import {b as b$1}from'./chunk-YSUBOEFT.mjs';import {e}from'./chunk-GMGMQ2NX.mjs';import {a as a$1}from'./chunk-ZAHR3SJ2.mjs';import {a as a$2}from'./chunk-R32ZSPV6.mjs';import {b}from'./chunk-6KCJVEZD.mjs';var D=class extends b{id;customerId;customerEmail;anonymousId;lineItems;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,i=new Date){super(t,i),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(o=>new a(o)),this.billingAddress=t.billingAddress?new b$1(t.billingAddress,i):null,this.shippingAddress=t.shippingAddress?new b$1(t.shippingAddress,i):null,this.coupons=(t.coupons??[]).map(o=>new e(o)),this.shippingDetails=t.shippingDetails?a$1.deepClone(t.shippingDetails):null,this.total={subtotal:new a$2(t.total.subtotal),shipping:new a$2(t.total.shipping),effectiveShipping:new a$2(t.total.effectiveShipping),taxTotal:new a$2(t.total.taxTotal),couponTotal:Object.fromEntries(Object.entries(t.total.couponTotal).map(([o,e])=>[o,new a$2(e)])),couponDiscountTotal:new a$2(t.total.couponDiscountTotal),grandTotal:new a$2(t.total.grandTotal)};}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new a(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new b$1(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new b$1(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return this.total}getDetails(){return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(t=>t.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(t=>t.getDetails()),total:{subtotal:this.getTotal().subtotal.getDetails(),shipping:this.getTotal().shipping.getDetails(),effectiveShipping:this.getTotal().effectiveShipping.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),couponTotal:Object.fromEntries(Object.entries(this.getTotal().couponTotal).map(([t,i])=>[t,i.getDetails()])),couponDiscountTotal:this.getTotal().couponDiscountTotal.getDetails(),grandTotal:this.getTotal().grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new a$2({amount:0,currency:this.currency}),i=this.lineItems.filter(r=>r.getState()!=="CANCELLED"),o=i.reduce((r,c)=>r.add(c.getTotal().subtotal),t),e=new a$2({amount:this.shippingDetails?.cost||0,currency:this.currency}).round(),s=t,n={},u={};this.coupons.forEach(r=>{let c=r.calculateApplicableCouponDiscount(o,e,this.country,this.currency);s=s.add(c),n[r.getCode()]=c,r.getCategory()!=="SHIPPING"&&(u[r.getCode()]=c);}),this.applyDiscountsInLineItem(u);let p=i.reduce((r,c)=>r.add(c.getTotal().taxTotal),t),l=this.coupons.find(r=>r.getCategory()==="SHIPPING"),h=l?e.subtract(n[l.getCode()]||t):e,g=o.add(e).add(p).subtract(s);this.total={subtotal:o,shipping:e,effectiveShipping:h,couponTotal:n,couponDiscountTotal:s,taxTotal:p,grandTotal:g};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let i=t.filter(e=>e.getCategory()==="SHIPPING"),o=t.filter(e=>e.getCategory()!=="SHIPPING");this.coupons=[],this.total.couponDiscountTotal=this.total.subtotal.zero(),this.total.couponTotal={},o.length&&this.applyNonShippingCoupons(o),this.applyDiscountsInLineItem(this.total.couponTotal),i.length&&this.applyShippingCoupons(i),this.calculateTotals();}applyDiscountsInLineItem(t){let i=Array.from(Object.entries(t)).filter(e=>!e[1].isZero()),o=new Map;this.lineItems.forEach(e=>o.set(e.getId(),[])),i.forEach(([e,s])=>{let n=this.coupons.find(l=>l.getCode()===e);if(!n||s.isZero())return;let u=this.lineItems.filter(l=>l.getState()!=="CANCELLED"&&!l.getTotal().subtotal.isZero()).sort((l,h)=>l.getTotal().subtotal.compareTo(h.getTotal().subtotal)),p=new a$2({amount:0,currency:this.currency});u.forEach((l,h)=>{let g;h===u.length-1?g=s.subtract(p):g=s.multiply(l.getTotal().subtotal).divide(this.total.subtotal).round(),p=p.add(g),o.get(l.getId())?.push({coupon:n,amount:g});});}),this.lineItems.forEach(e=>{e.getState()==="CANCELLED"||this.total.subtotal.isZero()?e.updateDiscounts([]):e.updateDiscounts(o.get(e.getId())||[]);});}updateTax(t){this.lineItems.forEach(i=>{i.updateTax(t[i.getPricing().taxCategory]);}),this.calculateTotals();}applyNonShippingCoupons(t){let i=t.filter(o=>o.getType()==="coupon");if(i.length===1){let o=i[0].calculateApplicableCouponDiscount(this.total.subtotal,this.total.shipping,this.country,this.currency);o.getAmount()>0&&(this.coupons.push(i[0]),this.total.couponTotal[i[0].getCode()]=o,this.total.couponDiscountTotal=o);}}applyShippingCoupons(t){if(this.total.shipping.getAmount()>0&&t.length>0){let i=this.total.subtotal.subtract(this.total.couponDiscountTotal),o=t.reduce((s,n)=>{if(!s)return n;let u=n.calculateApplicableCouponDiscount(i,this.total.shipping,this.country,this.currency).min(this.total.shipping),p=s.calculateApplicableCouponDiscount(i,this.total.shipping,this.country,this.currency).min(this.total.shipping);return u===p?n.getType()==="coupon"?n:s:u>p?n:s}),e=o.calculateApplicableCouponDiscount(i,this.total.shipping,this.country,this.currency).min(this.total.shipping);e.getAmount()>0&&(this.coupons.push(o),this.total.couponTotal[o.getCode()]=e,this.total.couponDiscountTotal=this.total.couponDiscountTotal.add(e),this.total.effectiveShipping=this.total.shipping.subtract(e));}}};export{D as a};//# sourceMappingURL=chunk-FGXEJC4J.mjs.map
2
+ //# sourceMappingURL=chunk-FGXEJC4J.mjs.map