b23-lib 3.10.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/Auth/index.js +1 -1
  2. package/dist/Auth/index.js.map +1 -1
  3. package/dist/Auth/index.mjs +1 -1
  4. package/dist/Classes/Cart.js +1 -1
  5. package/dist/Classes/Cart.js.map +1 -1
  6. package/dist/Classes/Cart.mjs +1 -1
  7. package/dist/Classes/Charge.d.mts +23 -7
  8. package/dist/Classes/Charge.d.ts +23 -7
  9. package/dist/Classes/Charge.js +1 -1
  10. package/dist/Classes/Charge.js.map +1 -1
  11. package/dist/Classes/Charge.mjs +1 -1
  12. package/dist/Classes/Coupon.js +1 -1
  13. package/dist/Classes/Coupon.js.map +1 -1
  14. package/dist/Classes/Coupon.mjs +1 -1
  15. package/dist/Classes/Inventory.js +1 -1
  16. package/dist/Classes/Inventory.js.map +1 -1
  17. package/dist/Classes/Inventory.mjs +1 -1
  18. package/dist/Classes/Invoice.d.mts +44 -10
  19. package/dist/Classes/Invoice.d.ts +44 -10
  20. package/dist/Classes/Invoice.js +1 -1
  21. package/dist/Classes/Invoice.js.map +1 -1
  22. package/dist/Classes/Invoice.mjs +1 -1
  23. package/dist/Classes/Invoice.mjs.map +1 -1
  24. package/dist/Classes/LineItem.d.mts +28 -8
  25. package/dist/Classes/LineItem.d.ts +28 -8
  26. package/dist/Classes/LineItem.js +1 -1
  27. package/dist/Classes/LineItem.js.map +1 -1
  28. package/dist/Classes/LineItem.mjs +1 -1
  29. package/dist/Classes/Order.js +1 -1
  30. package/dist/Classes/Order.js.map +1 -1
  31. package/dist/Classes/Order.mjs +1 -1
  32. package/dist/Classes/Product.js +1 -1
  33. package/dist/Classes/Product.js.map +1 -1
  34. package/dist/Classes/Product.mjs +1 -1
  35. package/dist/Classes/ShoppingContainer.d.mts +55 -26
  36. package/dist/Classes/ShoppingContainer.d.ts +55 -26
  37. package/dist/Classes/ShoppingContainer.js +1 -1
  38. package/dist/Classes/ShoppingContainer.js.map +1 -1
  39. package/dist/Classes/ShoppingContainer.mjs +1 -1
  40. package/dist/Classes/TieredPrice.js +1 -1
  41. package/dist/Classes/TieredPrice.js.map +1 -1
  42. package/dist/Classes/TieredPrice.mjs +1 -1
  43. package/dist/{chunk-MBR2GRKU.mjs → chunk-3SUQYXIJ.mjs} +2 -2
  44. package/dist/{chunk-MBR2GRKU.mjs.map → chunk-3SUQYXIJ.mjs.map} +1 -1
  45. package/dist/chunk-A2PC4S2X.mjs +2 -0
  46. package/dist/chunk-A2PC4S2X.mjs.map +1 -0
  47. package/dist/chunk-LE4HS2A6.mjs +2 -0
  48. package/dist/chunk-LE4HS2A6.mjs.map +1 -0
  49. package/dist/chunk-MWDQACOC.mjs +2 -0
  50. package/dist/chunk-MWDQACOC.mjs.map +1 -0
  51. package/dist/{chunk-4PTWJI6J.mjs → chunk-XXKEHCV5.mjs} +2 -2
  52. package/dist/chunk-XXKEHCV5.mjs.map +1 -0
  53. package/dist/chunk-YDSXBMNW.mjs +2 -0
  54. package/dist/chunk-YDSXBMNW.mjs.map +1 -0
  55. package/dist/index.js +1 -1
  56. package/dist/index.js.map +1 -1
  57. package/dist/index.mjs +1 -1
  58. package/package.json +1 -1
  59. package/dist/chunk-4PTWJI6J.mjs.map +0 -1
  60. package/dist/chunk-5N2HRXWJ.mjs +0 -2
  61. package/dist/chunk-5N2HRXWJ.mjs.map +0 -1
  62. package/dist/chunk-6QSZECNF.mjs +0 -2
  63. package/dist/chunk-6QSZECNF.mjs.map +0 -1
  64. package/dist/chunk-MPKIC2MS.mjs +0 -2
  65. package/dist/chunk-MPKIC2MS.mjs.map +0 -1
  66. package/dist/chunk-NXDEYUDI.mjs +0 -2
  67. package/dist/chunk-NXDEYUDI.mjs.map +0 -1
@@ -1,2 +1,2 @@
1
- import {a}from'./chunk-4PTWJI6J.mjs';import {a as a$1}from'./chunk-UIQH5QIR.mjs';import {e}from'./chunk-PL5HGCWN.mjs';import {u}from'./chunk-O6BLQQO7.mjs';import {b as b$1}from'./chunk-UXZBULDS.mjs';var y=(t=>(t.COUPON="coupon",t.AUTOMATIC="automatic",t))(y||{}),M=(t=>(t.FLAT="flat",t.PERCENTAGE="percentage",t))(M||{}),b=(t=>(t.SHIPPING="SHIPPING",t.CUSTOMER="CUSTOMER",t))(b||{}),P=(t=>(t.ALL="all",t.FTB="ftb",t))(P||{}),p=class extends b$1{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(e,t=new Date){if(super(e,t),this.couponCode=e.couponCode,this.name=a.deepClone(e.name),this.description=a.deepClone(e.description),this.type=e.type,this.customerId=e.customerId,this.validFrom=e.validFrom&&Date.parse(e.validFrom)?new Date(e.validFrom).toISOString():t.toISOString(),this.validTo=e.validTo&&Date.parse(e.validTo)?new Date(e.validTo).toISOString():t.toISOString(),this.minCartValue=Object.keys(e.minCartValue).reduce((o,i)=>{let r=e.minCartValue[i];return r&&(o[i]=new a$1(r)),o},{}),this.maxCartDiscount=Object.keys(e.maxCartDiscount).reduce((o,i)=>{let r=e.maxCartDiscount[i];return r&&(o[i]=new a$1(r)),o},{}),this.discountMethod=e.discountMethod,this.percentageValue=e.percentageValue??0,this.percentageValue>100)throw new u("Percentage value cannot be greater than 100");this.applicableTo=e.applicableTo,this.category=e.category;}getCode(){return this.couponCode}getName(e$1){return e$1?this.name[e$1]??this.name[e[e$1]]??this.name.en:{...this.name}}getDescription(e$1){return e$1?this.description[e$1]??this.description[e[e$1]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(e){return e?this.minCartValue[e]:{...this.minCartValue}}getMaxCartDiscount(e){return e?this.maxCartDiscount[e]:{...this.maxCartDiscount}}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:Object.keys(this.getMinCartValue()).reduce((e,t)=>{let o=this.getMinCartValue(t);return o&&(e[t]=o.getDetails()),e},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((e,t)=>{let o=this.getMaxCartDiscount(t);return o&&(e[t]=o.getDetails()),e},{}),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(e){return this.applicableTo==="all"||this.applicableTo==="ftb"&&e}calculateApplicableCouponDiscount(e,t,o,i,r=!0){let n=new a$1({amount:0,currency:i}),s;if(r&&!this.isActive())return n;let C=this.getMinCartValue(o),c=this.getMaxCartDiscount(o);if(!C||C.compareTo(e)>0||!c)return n;let h=this.getCategory(),D=this.getDiscountMethod(),u=h==="SHIPPING"?t:e;if(u.getAmount()<=0)return n;switch(D){case"flat":let T=c;s=u.min(T);break;case"percentage":s=u.multiply(this.getPercentageValue()/100).round();break;default:return n}return s.min(c)}};export{y as a,M as b,b as c,P as d,p as e};//# sourceMappingURL=chunk-MBR2GRKU.mjs.map
2
- //# sourceMappingURL=chunk-MBR2GRKU.mjs.map
1
+ import {a}from'./chunk-XXKEHCV5.mjs';import {a as a$1}from'./chunk-UIQH5QIR.mjs';import {e}from'./chunk-PL5HGCWN.mjs';import {u}from'./chunk-O6BLQQO7.mjs';import {b as b$1}from'./chunk-UXZBULDS.mjs';var y=(t=>(t.COUPON="coupon",t.AUTOMATIC="automatic",t))(y||{}),M=(t=>(t.FLAT="flat",t.PERCENTAGE="percentage",t))(M||{}),b=(t=>(t.SHIPPING="SHIPPING",t.CUSTOMER="CUSTOMER",t))(b||{}),P=(t=>(t.ALL="all",t.FTB="ftb",t))(P||{}),p=class extends b$1{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(e,t=new Date){if(super(e,t),this.couponCode=e.couponCode,this.name=a.deepClone(e.name),this.description=a.deepClone(e.description),this.type=e.type,this.customerId=e.customerId,this.validFrom=e.validFrom&&Date.parse(e.validFrom)?new Date(e.validFrom).toISOString():t.toISOString(),this.validTo=e.validTo&&Date.parse(e.validTo)?new Date(e.validTo).toISOString():t.toISOString(),this.minCartValue=Object.keys(e.minCartValue).reduce((o,i)=>{let r=e.minCartValue[i];return r&&(o[i]=new a$1(r)),o},{}),this.maxCartDiscount=Object.keys(e.maxCartDiscount).reduce((o,i)=>{let r=e.maxCartDiscount[i];return r&&(o[i]=new a$1(r)),o},{}),this.discountMethod=e.discountMethod,this.percentageValue=e.percentageValue??0,this.percentageValue>100)throw new u("Percentage value cannot be greater than 100");this.applicableTo=e.applicableTo,this.category=e.category;}getCode(){return this.couponCode}getName(e$1){return e$1?this.name[e$1]??this.name[e[e$1]]??this.name.en:{...this.name}}getDescription(e$1){return e$1?this.description[e$1]??this.description[e[e$1]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(e){return e?this.minCartValue[e]:{...this.minCartValue}}getMaxCartDiscount(e){return e?this.maxCartDiscount[e]:{...this.maxCartDiscount}}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:Object.keys(this.getMinCartValue()).reduce((e,t)=>{let o=this.getMinCartValue(t);return o&&(e[t]=o.getDetails()),e},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((e,t)=>{let o=this.getMaxCartDiscount(t);return o&&(e[t]=o.getDetails()),e},{}),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(e){return this.applicableTo==="all"||this.applicableTo==="ftb"&&e}calculateApplicableCouponDiscount(e,t,o,i,r=!0){let n=new a$1({amount:0,currency:i}),s;if(r&&!this.isActive())return n;let C=this.getMinCartValue(o),c=this.getMaxCartDiscount(o);if(!C||C.compareTo(e)>0||!c)return n;let h=this.getCategory(),D=this.getDiscountMethod(),u=h==="SHIPPING"?t:e;if(u.getAmount()<=0)return n;switch(D){case"flat":let T=c;s=u.min(T);break;case"percentage":s=u.multiply(this.getPercentageValue()/100).round();break;default:return n}return s.min(c)}};export{y as a,M as b,b as c,P as d,p as e};//# sourceMappingURL=chunk-3SUQYXIJ.mjs.map
2
+ //# sourceMappingURL=chunk-3SUQYXIJ.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Classes/Coupon.ts"],"names":["CouponType","CouponDiscountMethod","CouponCategory","ApplicableTo","CouponModel","BaseModel","data","date","Utils_default","acc","country","priceData","PriceModel","InvalidArgumentError","locale","LocaleLanguageMap","priceModel","ftbCustomer","cartValue","shippingCost","currency","checkExpiry","zeroDiscount","potentialDiscount","minCartValueReq","maxCartDiscountCap","couponCategory","discountMethod","targetValue","flatAmount"],"mappings":"uMAOO,IAAKA,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,MAAS,CAAA,QAAA,CACTA,EAAA,SAAY,CAAA,WAAA,CAFFA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAKAC,OACVA,CAAA,CAAA,IAAA,CAAO,MACPA,CAAAA,CAAAA,CAAA,WAAa,YAFHA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAKAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,CAAA,CAAA,QAAA,CA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J,GAAIF,CAAe,EAAA,CAAC,IAAK,CAAA,QAAA,GACvB,OAAOC,CAAAA,CAIT,IAAME,CAAAA,CAAkB,KAAK,eAAgBd,CAAAA,CAAO,CAC9Ce,CAAAA,CAAAA,CAAqB,IAAK,CAAA,kBAAA,CAAmBf,CAAO,CAAA,CAQ1D,GALI,CAACc,CAAAA,EAAmBA,CAAgB,CAAA,SAAA,CAAUN,CAAS,CAAI,CAAA,CAAA,EAK3D,CAACO,CAAAA,CACH,OAAOH,CAIT,CAAA,IAAMI,CAAiB,CAAA,IAAA,CAAK,WAAY,EAAA,CAClCC,CAAiB,CAAA,IAAA,CAAK,mBAEtBC,CAAAA,CAAAA,CAAcF,CAAmB,GAAA,UAAA,CAA0BP,EAAeD,CAGhF,CAAA,GAAIU,CAAY,CAAA,SAAA,IAAe,CAAG,CAAA,OAAON,CAEzC,CAAA,OAAQK,CAAgB,EACtB,IAAK,MAAA,CAEH,IAAME,CAAaJ,CAAAA,CAAAA,CACnBF,CAAoBK,CAAAA,CAAAA,CAAY,IAAIC,CAAU,CAAA,CAC9C,MACF,IAAK,aAEHN,CAAoBK,CAAAA,CAAAA,CAAY,QAAS,CAAA,IAAA,CAAK,oBAAuB,CAAA,GAAG,CAAE,CAAA,KAAA,GAC1E,MACF,QAEE,OAAON,CACX,CAKA,OAFsBC,CAAAA,CAAkB,GAAIE,CAAAA,CAAkB,CAGhE,CACF","file":"chunk-MBR2GRKU.mjs","sourcesContent":["import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, CurrencyCode, ISODateTimeUTC, LocaleCode, LocalizedString, RegionalPrice } from \"./Common\";\r\nimport { LocaleLanguageMap } from \"./Enum\";\r\nimport { InvalidArgumentError } from \"./Error\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\n\r\nexport enum CouponType {\r\n COUPON = \"coupon\",\r\n AUTOMATIC = \"automatic\",\r\n}\r\n\r\nexport enum CouponDiscountMethod {\r\n FLAT = \"flat\",\r\n PERCENTAGE = \"percentage\",\r\n}\r\n\r\nexport enum CouponCategory {\r\n SHIPPING = \"SHIPPING\",\r\n CUSTOMER = \"CUSTOMER\",\r\n}\r\n\r\nexport enum ApplicableTo {\r\n ALL = \"all\",\r\n FTB = \"ftb\",\r\n}\r\n\r\nexport type CouponAttribute = BaseAttributes & {\r\n couponCode: string;\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n type: CouponType;\r\n customerId?: string;\r\n validFrom: ISODateTimeUTC;\r\n validTo: ISODateTimeUTC;\r\n minCartValue: RegionalPrice;\r\n maxCartDiscount: RegionalPrice;\r\n discountMethod: CouponDiscountMethod;\r\n percentageValue?: number;\r\n applicableTo: ApplicableTo;\r\n category: CouponCategory;\r\n};\r\n\r\nexport type CouponData = Required<CouponAttribute>\r\n\r\n/**\r\n * Represents a discount coupon, extending BaseModel.\r\n */\r\nexport default class CouponModel extends BaseModel {\r\n protected couponCode: string;\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected type: CouponType;\r\n protected customerId?: string;\r\n protected validFrom: ISODateTimeUTC;\r\n protected validTo: ISODateTimeUTC;\r\n protected minCartValue: {\r\n [country in CountryCode]?: PriceModel;\r\n };\r\n protected maxCartDiscount: {\r\n [country in CountryCode]?: PriceModel;\r\n };\r\n protected discountMethod: CouponDiscountMethod;\r\n protected percentageValue: number;\r\n protected applicableTo: ApplicableTo;\r\n protected category: CouponCategory;\r\n\r\n /**\r\n * Creates an instance of CouponModel.\r\n * @param data - The initial coupon attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: CouponAttribute, date: Date = new Date()) {\r\n super(data, date);\r\n\r\n this.couponCode = data.couponCode;\r\n this.name = Utils.deepClone(data.name);\r\n this.description = Utils.deepClone(data.description);\r\n this.type = data.type;\r\n this.customerId = data.customerId;\r\n this.validFrom = data.validFrom && Date.parse(data.validFrom) ? new Date(data.validFrom).toISOString() : date.toISOString();\r\n this.validTo = data.validTo && Date.parse(data.validTo) ? new Date(data.validTo).toISOString() : date.toISOString();\r\n this.minCartValue = (Object.keys(data.minCartValue) as CountryCode[]).reduce((acc, country) => {\r\n const priceData = data.minCartValue[country] as PriceData;\r\n if (priceData) {\r\n acc[country] = new PriceModel(priceData);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: PriceModel });\r\n this.maxCartDiscount = (Object.keys(data.maxCartDiscount) as CountryCode[]).reduce((acc, country) => {\r\n const priceData = data.maxCartDiscount[country] as PriceData;\r\n if (priceData) {\r\n acc[country] = new PriceModel(priceData);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: PriceModel });\r\n this.discountMethod = data.discountMethod;\r\n this.percentageValue = data.percentageValue ?? 0;\r\n if (this.percentageValue > 100) {\r\n throw new InvalidArgumentError('Percentage value cannot be greater than 100');\r\n }\r\n\r\n this.applicableTo = data.applicableTo;\r\n this.category = data.category;\r\n }\r\n\r\n /** Gets the unique coupon code. */\r\n getCode(): string {\r\n return this.couponCode;\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the coupon name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon description object.\r\n * @returns A copy of the LocalizedString object for the description, or undefined.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the coupon description for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The description string for the specified locale.\r\n */\r\n getDescription(locale: LocaleCode): string\r\n getDescription(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.description[locale] ?? this.description[LocaleLanguageMap[locale]] ?? this.description.en;\r\n } else {\r\n return { ...this.description };\r\n }\r\n }\r\n\r\n /** Gets the type of coupon (COUPON or AUTOMATIC). */\r\n getType(): CouponType {\r\n return this.type;\r\n }\r\n\r\n /** Gets the specific customer ID this coupon is limited to, if any. */\r\n getCustomerId(): string {\r\n return this.customerId ?? '';\r\n }\r\n\r\n /** Gets the ISO date string from when the coupon is valid. */\r\n getValidFrom(): ISODateTimeUTC {\r\n return this.validFrom;\r\n }\r\n\r\n /** Gets the ISO date string until when the coupon is valid. */\r\n getValidTo(): ISODateTimeUTC {\r\n return this.validTo;\r\n }\r\n\r\n /**\r\n * Gets the list of minimum cart values required for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional minimum cart values.\r\n */\r\n getMinCartValue(): { [country in CountryCode]?: PriceModel }\r\n\r\n /**\r\n * Gets the minimum cart value required for the coupon for a specific country.\r\n * @param country - The country code to filter the minimum value for.\r\n * @returns The regional minimum cart value for the specified country, or undefined if not set for that country.\r\n */\r\n getMinCartValue(country: CountryCode): PriceModel | undefined\r\n getMinCartValue(country?: CountryCode) {\r\n if (country) {\r\n return this.minCartValue[country];\r\n }\r\n return { ...this.minCartValue };\r\n }\r\n\r\n /**\r\n * Gets the list of maximum discount amounts allowed for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional maximum discount caps.\r\n */\r\n getMaxCartDiscount(): { [country in CountryCode]?: PriceModel }\r\n /**\r\n * Gets the maximum discount amount allowed for the coupon for a specific country.\r\n * @param country - The country code to filter the maximum discount for.\r\n * @returns The regional maximum discount cap for the specified country, or undefined if not set for that country.\r\n */\r\n getMaxCartDiscount(country: CountryCode): PriceModel | undefined\r\n getMaxCartDiscount(country?: CountryCode) {\r\n if (country) {\r\n return this.maxCartDiscount[country];\r\n }\r\n return { ...this.maxCartDiscount };\r\n }\r\n\r\n /** Gets the discount method (FLAT or PERCENTAGE). */\r\n getDiscountMethod(): CouponDiscountMethod {\r\n return this.discountMethod;\r\n }\r\n\r\n /** Gets the percentage discount value (0-100). */\r\n getPercentageValue(): number {\r\n return this.percentageValue;\r\n }\r\n\r\n /** Gets the customer applicability rule (ALL or FTB). */\r\n getApplicableTo(): ApplicableTo {\r\n return this.applicableTo;\r\n }\r\n\r\n /** Gets the category of the coupon (SHIPPING or CUSTOMER). */\r\n getCategory(): CouponCategory {\r\n return this.category;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the coupon's details.\r\n * @returns A CouponData object.\r\n */\r\n getDetails(): CouponData {\r\n return {\r\n ...super.getDetails(),\r\n couponCode: this.getCode(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n type: this.getType(),\r\n customerId: this.getCustomerId(),\r\n validFrom: this.getValidFrom(),\r\n validTo: this.getValidTo(),\r\n minCartValue: (Object.keys(this.getMinCartValue()) as CountryCode[]).reduce((acc, country) => {\r\n const priceModel = this.getMinCartValue(country);\r\n if (priceModel) {\r\n acc[country] = priceModel.getDetails();\r\n }\r\n return acc;\r\n }, {} as RegionalPrice),\r\n maxCartDiscount: (Object.keys(this.getMaxCartDiscount()) as CountryCode[]).reduce((acc, country) => {\r\n const priceModel = this.getMaxCartDiscount(country);\r\n if (priceModel) {\r\n acc[country] = priceModel.getDetails();\r\n }\r\n return acc;\r\n }, {} as RegionalPrice),\r\n discountMethod: this.getDiscountMethod(),\r\n percentageValue: this.getPercentageValue(),\r\n applicableTo: this.getApplicableTo(),\r\n category: this.getCategory(),\r\n };\r\n }\r\n\r\n /**\r\n * Checks if the coupon is currently active based on its validity dates.\r\n * @returns True if the coupon is currently within its validity period, false otherwise.\r\n */\r\n isActive(): boolean {\r\n return new Date(this.validFrom) <= new Date() && new Date(this.validTo) >= new Date();\r\n }\r\n\r\n\r\n /**\r\n * Checks if the coupon is applicable to a customer based on their status (e.g., first-time buyer).\r\n * @param ftbCustomer - A boolean indicating whether the customer is a first-time buyer.\r\n * @returns True if the coupon's applicability rule matches the customer's status, false otherwise.\r\n */\r\n isApplicableTo(ftbCustomer: boolean): boolean {\r\n return this.applicableTo === ApplicableTo.ALL || (this.applicableTo === ApplicableTo.FTB && ftbCustomer);\r\n }\r\n\r\n /**\r\n * Calculates the discount value for a given coupon based on the current container state.\r\n * Returns 0 if the coupon is invalid, expired, or not applicable based on cart value or target category.\r\n * @param cartValue - The cart subtotal as a PriceModel.\r\n * @param shippingCost - The cart shipping cost.\r\n * @param country - The country code.\r\n * @param currency - The currency code.\r\n * @returns The calculated discount amount (rounded according to country rules).\r\n */\r\n public calculateApplicableCouponDiscount(cartValue: PriceModel, shippingCost: PriceModel, country: CountryCode, currency: CurrencyCode, checkExpiry: boolean = true): PriceModel {\r\n let zeroDiscount: PriceModel = new PriceModel({ amount: 0, currency });\r\n let potentialDiscount: PriceModel;\r\n\r\n // 1. Basic validation (active)\r\n if (checkExpiry && !this.isActive()) {\r\n return zeroDiscount;\r\n }\r\n\r\n // 2. Check regional requirements (min cart value, max discount)\r\n const minCartValueReq = this.getMinCartValue(country);\r\n const maxCartDiscountCap = this.getMaxCartDiscount(country);\r\n\r\n // If minCartValueReq is not set or the cart value is less than the minimum required, return zero discount\r\n if (!minCartValueReq || minCartValueReq.compareTo(cartValue) > 0) {\r\n return zeroDiscount;\r\n }\r\n\r\n // If maxCartDiscountCap is not set, return zero discount\r\n if (!maxCartDiscountCap) {\r\n return zeroDiscount;\r\n }\r\n\r\n // 3. Calculate potential discount based on method and category\r\n const couponCategory = this.getCategory();\r\n const discountMethod = this.getDiscountMethod();\r\n // Determine the value the coupon applies to (shipping cost or subtotal)\r\n const targetValue = couponCategory === CouponCategory.SHIPPING ? shippingCost : cartValue;\r\n\r\n // No discount if the target value is zero or less\r\n if (targetValue.getAmount() <= 0) return zeroDiscount;\r\n\r\n switch (discountMethod) {\r\n case CouponDiscountMethod.FLAT:\r\n // Flat discount is capped by the target value itself and the max discount cap\r\n const flatAmount = maxCartDiscountCap; // Use cap as the flat amount source? Or coupon.value? Needs clarification. Assuming cap IS the flat amount here.\r\n potentialDiscount = targetValue.min(flatAmount);\r\n break;\r\n case CouponDiscountMethod.PERCENTAGE:\r\n // Calculate percentage discount based on the target value\r\n potentialDiscount = targetValue.multiply(this.getPercentageValue() / 100).round();\r\n break;\r\n default:\r\n // Unknown discount method\r\n return zeroDiscount;\r\n }\r\n\r\n // 4. Apply maximum discount cap to the calculated potential discount\r\n const finalDiscount = potentialDiscount.min(maxCartDiscountCap);\r\n\r\n return finalDiscount;\r\n }\r\n}\r\n"]}
1
+ {"version":3,"sources":["../src/Classes/Coupon.ts"],"names":["CouponType","CouponDiscountMethod","CouponCategory","ApplicableTo","CouponModel","BaseModel","data","date","Utils_default","acc","country","priceData","PriceModel","InvalidArgumentError","locale","LocaleLanguageMap","priceModel","ftbCustomer","cartValue","shippingCost","currency","checkExpiry","zeroDiscount","potentialDiscount","minCartValueReq","maxCartDiscountCap","couponCategory","discountMethod","targetValue","flatAmount"],"mappings":"uMAOO,IAAKA,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,MAAS,CAAA,QAAA,CACTA,EAAA,SAAY,CAAA,WAAA,CAFFA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAKAC,OACVA,CAAA,CAAA,IAAA,CAAO,MACPA,CAAAA,CAAAA,CAAA,WAAa,YAFHA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAKAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,CAAA,CAAA,QAAA,CAAW,UACXA,CAAAA,CAAAA,CAAA,SAAW,UAFDA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAKAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,EAAA,GAAM,CAAA,KAAA,CACNA,CAAA,CAAA,GAAA,CAAM,MAFIA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CA0BSC,CAArB,CAAA,cAAyCC,GAAU,CACvC,UACA,CAAA,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,CACH,OAAOH,CAIT,CAAA,IAAMI,CAAiB,CAAA,IAAA,CAAK,WAAY,EAAA,CAClCC,CAAiB,CAAA,IAAA,CAAK,mBAEtBC,CAAAA,CAAAA,CAAcF,CAAmB,GAAA,UAAA,CAA0BP,EAAeD,CAGhF,CAAA,GAAIU,CAAY,CAAA,SAAA,IAAe,CAAG,CAAA,OAAON,CAEzC,CAAA,OAAQK,CAAgB,EACtB,IAAK,MAAA,CAEH,IAAME,CAAaJ,CAAAA,CAAAA,CACnBF,CAAoBK,CAAAA,CAAAA,CAAY,IAAIC,CAAU,CAAA,CAC9C,MACF,IAAK,aAEHN,CAAoBK,CAAAA,CAAAA,CAAY,QAAS,CAAA,IAAA,CAAK,oBAAuB,CAAA,GAAG,CAAE,CAAA,KAAA,GAC1E,MACF,QAEE,OAAON,CACX,CAKA,OAFsBC,CAAAA,CAAkB,GAAIE,CAAAA,CAAkB,CAGhE,CACF","file":"chunk-3SUQYXIJ.mjs","sourcesContent":["import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, CurrencyCode, ISODateTimeUTC, LocaleCode, LocalizedString, RegionalPrice } from \"./Common\";\r\nimport { LocaleLanguageMap } from \"./Enum\";\r\nimport { InvalidArgumentError } from \"./Error\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\n\r\nexport enum CouponType {\r\n COUPON = \"coupon\",\r\n AUTOMATIC = \"automatic\",\r\n}\r\n\r\nexport enum CouponDiscountMethod {\r\n FLAT = \"flat\",\r\n PERCENTAGE = \"percentage\",\r\n}\r\n\r\nexport enum CouponCategory {\r\n SHIPPING = \"SHIPPING\",\r\n CUSTOMER = \"CUSTOMER\",\r\n}\r\n\r\nexport enum ApplicableTo {\r\n ALL = \"all\",\r\n FTB = \"ftb\",\r\n}\r\n\r\nexport type CouponAttribute = BaseAttributes & {\r\n couponCode: string;\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n type: CouponType;\r\n customerId?: string;\r\n validFrom: ISODateTimeUTC;\r\n validTo: ISODateTimeUTC;\r\n minCartValue: RegionalPrice;\r\n maxCartDiscount: RegionalPrice;\r\n discountMethod: CouponDiscountMethod;\r\n percentageValue?: number;\r\n applicableTo: ApplicableTo;\r\n category: CouponCategory;\r\n};\r\n\r\nexport type CouponData = Required<CouponAttribute>\r\n\r\n/**\r\n * Represents a discount coupon, extending BaseModel.\r\n */\r\nexport default class CouponModel extends BaseModel {\r\n protected couponCode: string;\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected type: CouponType;\r\n protected customerId?: string;\r\n protected validFrom: ISODateTimeUTC;\r\n protected validTo: ISODateTimeUTC;\r\n protected minCartValue: {\r\n [country in CountryCode]?: PriceModel;\r\n };\r\n protected maxCartDiscount: {\r\n [country in CountryCode]?: PriceModel;\r\n };\r\n protected discountMethod: CouponDiscountMethod;\r\n protected percentageValue: number;\r\n protected applicableTo: ApplicableTo;\r\n protected category: CouponCategory;\r\n\r\n /**\r\n * Creates an instance of CouponModel.\r\n * @param data - The initial coupon attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: CouponAttribute, date: Date = new Date()) {\r\n super(data, date);\r\n\r\n this.couponCode = data.couponCode;\r\n this.name = Utils.deepClone(data.name);\r\n this.description = Utils.deepClone(data.description);\r\n this.type = data.type;\r\n this.customerId = data.customerId;\r\n this.validFrom = data.validFrom && Date.parse(data.validFrom) ? new Date(data.validFrom).toISOString() : date.toISOString();\r\n this.validTo = data.validTo && Date.parse(data.validTo) ? new Date(data.validTo).toISOString() : date.toISOString();\r\n this.minCartValue = (Object.keys(data.minCartValue) as CountryCode[]).reduce((acc, country) => {\r\n const priceData = data.minCartValue[country] as PriceData;\r\n if (priceData) {\r\n acc[country] = new PriceModel(priceData);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: PriceModel });\r\n this.maxCartDiscount = (Object.keys(data.maxCartDiscount) as CountryCode[]).reduce((acc, country) => {\r\n const priceData = data.maxCartDiscount[country] as PriceData;\r\n if (priceData) {\r\n acc[country] = new PriceModel(priceData);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: PriceModel });\r\n this.discountMethod = data.discountMethod;\r\n this.percentageValue = data.percentageValue ?? 0;\r\n if (this.percentageValue > 100) {\r\n throw new InvalidArgumentError('Percentage value cannot be greater than 100');\r\n }\r\n\r\n this.applicableTo = data.applicableTo;\r\n this.category = data.category;\r\n }\r\n\r\n /** Gets the unique coupon code. */\r\n getCode(): string {\r\n return this.couponCode;\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the coupon name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon description object.\r\n * @returns A copy of the LocalizedString object for the description, or undefined.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the coupon description for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The description string for the specified locale.\r\n */\r\n getDescription(locale: LocaleCode): string\r\n getDescription(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.description[locale] ?? this.description[LocaleLanguageMap[locale]] ?? this.description.en;\r\n } else {\r\n return { ...this.description };\r\n }\r\n }\r\n\r\n /** Gets the type of coupon (COUPON or AUTOMATIC). */\r\n getType(): CouponType {\r\n return this.type;\r\n }\r\n\r\n /** Gets the specific customer ID this coupon is limited to, if any. */\r\n getCustomerId(): string {\r\n return this.customerId ?? '';\r\n }\r\n\r\n /** Gets the ISO date string from when the coupon is valid. */\r\n getValidFrom(): ISODateTimeUTC {\r\n return this.validFrom;\r\n }\r\n\r\n /** Gets the ISO date string until when the coupon is valid. */\r\n getValidTo(): ISODateTimeUTC {\r\n return this.validTo;\r\n }\r\n\r\n /**\r\n * Gets the list of minimum cart values required for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional minimum cart values.\r\n */\r\n getMinCartValue(): { [country in CountryCode]?: PriceModel }\r\n\r\n /**\r\n * Gets the minimum cart value required for the coupon for a specific country.\r\n * @param country - The country code to filter the minimum value for.\r\n * @returns The regional minimum cart value for the specified country, or undefined if not set for that country.\r\n */\r\n getMinCartValue(country: CountryCode): PriceModel | undefined\r\n getMinCartValue(country?: CountryCode) {\r\n if (country) {\r\n return this.minCartValue[country];\r\n }\r\n return { ...this.minCartValue };\r\n }\r\n\r\n /**\r\n * Gets the list of maximum discount amounts allowed for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional maximum discount caps.\r\n */\r\n getMaxCartDiscount(): { [country in CountryCode]?: PriceModel }\r\n /**\r\n * Gets the maximum discount amount allowed for the coupon for a specific country.\r\n * @param country - The country code to filter the maximum discount for.\r\n * @returns The regional maximum discount cap for the specified country, or undefined if not set for that country.\r\n */\r\n getMaxCartDiscount(country: CountryCode): PriceModel | undefined\r\n getMaxCartDiscount(country?: CountryCode) {\r\n if (country) {\r\n return this.maxCartDiscount[country];\r\n }\r\n return { ...this.maxCartDiscount };\r\n }\r\n\r\n /** Gets the discount method (FLAT or PERCENTAGE). */\r\n getDiscountMethod(): CouponDiscountMethod {\r\n return this.discountMethod;\r\n }\r\n\r\n /** Gets the percentage discount value (0-100). */\r\n getPercentageValue(): number {\r\n return this.percentageValue;\r\n }\r\n\r\n /** Gets the customer applicability rule (ALL or FTB). */\r\n getApplicableTo(): ApplicableTo {\r\n return this.applicableTo;\r\n }\r\n\r\n /** Gets the category of the coupon (SHIPPING or CUSTOMER). */\r\n getCategory(): CouponCategory {\r\n return this.category;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the coupon's details.\r\n * @returns A CouponData object.\r\n */\r\n getDetails(): CouponData {\r\n return {\r\n ...super.getDetails(),\r\n couponCode: this.getCode(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n type: this.getType(),\r\n customerId: this.getCustomerId(),\r\n validFrom: this.getValidFrom(),\r\n validTo: this.getValidTo(),\r\n minCartValue: (Object.keys(this.getMinCartValue()) as CountryCode[]).reduce((acc, country) => {\r\n const priceModel = this.getMinCartValue(country);\r\n if (priceModel) {\r\n acc[country] = priceModel.getDetails();\r\n }\r\n return acc;\r\n }, {} as RegionalPrice),\r\n maxCartDiscount: (Object.keys(this.getMaxCartDiscount()) as CountryCode[]).reduce((acc, country) => {\r\n const priceModel = this.getMaxCartDiscount(country);\r\n if (priceModel) {\r\n acc[country] = priceModel.getDetails();\r\n }\r\n return acc;\r\n }, {} as RegionalPrice),\r\n discountMethod: this.getDiscountMethod(),\r\n percentageValue: this.getPercentageValue(),\r\n applicableTo: this.getApplicableTo(),\r\n category: this.getCategory(),\r\n };\r\n }\r\n\r\n /**\r\n * Checks if the coupon is currently active based on its validity dates.\r\n * @returns True if the coupon is currently within its validity period, false otherwise.\r\n */\r\n isActive(): boolean {\r\n return new Date(this.validFrom) <= new Date() && new Date(this.validTo) >= new Date();\r\n }\r\n\r\n\r\n /**\r\n * Checks if the coupon is applicable to a customer based on their status (e.g., first-time buyer).\r\n * @param ftbCustomer - A boolean indicating whether the customer is a first-time buyer.\r\n * @returns True if the coupon's applicability rule matches the customer's status, false otherwise.\r\n */\r\n isApplicableTo(ftbCustomer: boolean): boolean {\r\n return this.applicableTo === ApplicableTo.ALL || (this.applicableTo === ApplicableTo.FTB && ftbCustomer);\r\n }\r\n\r\n /**\r\n * Calculates the discount value for a given coupon based on the current container state.\r\n * Returns 0 if the coupon is invalid, expired, or not applicable based on cart value or target category.\r\n * @param cartValue - The cart subtotal as a PriceModel.\r\n * @param shippingCost - The cart shipping cost.\r\n * @param country - The country code.\r\n * @param currency - The currency code.\r\n * @returns The calculated discount amount (rounded according to country rules).\r\n */\r\n public calculateApplicableCouponDiscount(cartValue: PriceModel, shippingCost: PriceModel, country: CountryCode, currency: CurrencyCode, checkExpiry: boolean = true): PriceModel {\r\n let zeroDiscount: PriceModel = new PriceModel({ amount: 0, currency });\r\n let potentialDiscount: PriceModel;\r\n\r\n // 1. Basic validation (active)\r\n if (checkExpiry && !this.isActive()) {\r\n return zeroDiscount;\r\n }\r\n\r\n // 2. Check regional requirements (min cart value, max discount)\r\n const minCartValueReq = this.getMinCartValue(country);\r\n const maxCartDiscountCap = this.getMaxCartDiscount(country);\r\n\r\n // If minCartValueReq is not set or the cart value is less than the minimum required, return zero discount\r\n if (!minCartValueReq || minCartValueReq.compareTo(cartValue) > 0) {\r\n return zeroDiscount;\r\n }\r\n\r\n // If maxCartDiscountCap is not set, return zero discount\r\n if (!maxCartDiscountCap) {\r\n return zeroDiscount;\r\n }\r\n\r\n // 3. Calculate potential discount based on method and category\r\n const couponCategory = this.getCategory();\r\n const discountMethod = this.getDiscountMethod();\r\n // Determine the value the coupon applies to (shipping cost or subtotal)\r\n const targetValue = couponCategory === CouponCategory.SHIPPING ? shippingCost : cartValue;\r\n\r\n // No discount if the target value is zero or less\r\n if (targetValue.getAmount() <= 0) return zeroDiscount;\r\n\r\n switch (discountMethod) {\r\n case CouponDiscountMethod.FLAT:\r\n // Flat discount is capped by the target value itself and the max discount cap\r\n const flatAmount = maxCartDiscountCap; // Use cap as the flat amount source? Or coupon.value? Needs clarification. Assuming cap IS the flat amount here.\r\n potentialDiscount = targetValue.min(flatAmount);\r\n break;\r\n case CouponDiscountMethod.PERCENTAGE:\r\n // Calculate percentage discount based on the target value\r\n potentialDiscount = targetValue.multiply(this.getPercentageValue() / 100).round();\r\n break;\r\n default:\r\n // Unknown discount method\r\n return zeroDiscount;\r\n }\r\n\r\n // 4. Apply maximum discount cap to the calculated potential discount\r\n const finalDiscount = potentialDiscount.min(maxCartDiscountCap);\r\n\r\n return finalDiscount;\r\n }\r\n}\r\n"]}
@@ -0,0 +1,2 @@
1
+ import {a as a$4}from'./chunk-MWDQACOC.mjs';import {a as a$2}from'./chunk-EZ35IKUA.mjs';import {a as a$3}from'./chunk-XXKEHCV5.mjs';import {a as a$1}from'./chunk-UIQH5QIR.mjs';import {e}from'./chunk-PL5HGCWN.mjs';import {w,k,x}from'./chunk-O6BLQQO7.mjs';import {a}from'./chunk-UXZBULDS.mjs';var b=class extends a{id;name;type;category;impact;pricing;lineItemId;total;constructor(t){if(super(t),this.id=t.id,this.name=t.name,this.type=t.type,this.category=t.category,this.impact=t.impact,this.lineItemId=t.lineItemId,this.pricing={baseChargeAmount:new a$1(t.pricing.baseChargeAmount),taxCategory:t.pricing.taxCategory,applicableTaxRule:t.pricing.applicableTaxRule.map(a=>new a$2(a)),isTaxInclusive:t.pricing.isTaxInclusive??!1},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new w("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={discountTotal:new a$1(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([a,e])=>[a,new a$1(e)])),taxBreakdown:Object.fromEntries(Object.entries(t.total.taxBreakdown).map(([a,e])=>[a,{rate:e.rate,taxableAmount:new a$1(e.taxableAmount),taxAmount:new a$1(e.taxAmount),system:e.system,subSystem:e.subSystem}])),taxTotal:new a$1(t.total.taxTotal),taxExclusive:{chargeAmount:new a$1(t.total.taxExclusive.chargeAmount),netChargeAmount:new a$1(t.total.taxExclusive.netChargeAmount)},taxInclusive:{chargeAmount:new a$1(t.total.taxInclusive.chargeAmount),netChargeAmount:new a$1(t.total.taxInclusive.netChargeAmount)},grandTotal:new a$1(t.total.grandTotal)};}getId(){return this.id}getName(t){return t?a$3.deepClone(this.name[t]??this.name[e[t]]??this.name.en):a$3.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getIsTaxInclusive(){return this.pricing.isTaxInclusive}getPricing(){return {baseChargeAmount:this.pricing.baseChargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule],isTaxInclusive:this.pricing.isTaxInclusive}}getTotal(){return {discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,a])=>[t,{rate:a.rate,taxableAmount:a.taxableAmount,taxAmount:a.taxAmount,system:a.system,subSystem:a.subSystem}])),taxExclusive:{chargeAmount:this.total.taxExclusive.chargeAmount,netChargeAmount:this.total.taxExclusive.netChargeAmount},taxInclusive:{chargeAmount:this.total.taxInclusive.chargeAmount,netChargeAmount:this.total.taxInclusive.netChargeAmount},grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(t){if(this.type==="ADJUSTMENT"&&t.length>0)throw new w("Adjustment charges cannot apply tax rules.");t.forEach(a=>{if(!a.appliesTo(this.pricing.taxCategory,a.getCountry()))throw new k}),this.validateTaxRules(t),this.pricing.applicableTaxRule=t,this.calculateTotals();}validateTaxRules(t){if(this.impact==="SUBTRACT"&&t.some(e=>e.getRate()>0))throw new x("Subtractive charges cannot have positive tax rates.");let a=new Set;for(let e=0;e<t.length;e++){let n=t[e].getTaxRuleId();if(a.has(n))throw new x("Duplicate tax rule ID found: "+n);a.add(n);for(let i=e+1;i<t.length;i++){let r=t[e],u=t[i],h=r.getMinPrice(),s=r.getMaxPrice(),p=r.getExcludeMin(),d=r.getExcludeMax(),x$1=u.getMinPrice(),l=u.getMaxPrice(),T=u.getExcludeMin(),A=u.getExcludeMax(),f=(()=>{if(!s)return !1;let c=s.compareTo(x$1);return c<0||c===0&&(d||T)})(),D=(()=>{if(!l)return !1;let c=l.compareTo(h);return c<0||c===0&&(A||p)})();if(!(f||D)&&!(h.compareTo(x$1)===0&&p===T&&d===A&&(!s&&!l||s&&l&&s.compareTo(l)===0)))throw new x(`Overlapping rules found: [${r.getTaxRuleId()}: ${p?"(":"["}${h.getAmount()}-${s?.getAmount()??"Infinity"}${d?")":"]"}] and [${u.getTaxRuleId()}: ${T?"(":"["}${x$1.getAmount()}-${l?.getAmount()??"Infinity"}${A?")":"]"}]`)}}}updateDiscounts(t){let a={};t.forEach(e=>{a[e.coupon.getCode()]=e.amount;}),this.total.discountBreakdown=a,this.calculateTotals();}calculateTotals(){let t=this.pricing.baseChargeAmount.zero(),a=Object.values(this.total.discountBreakdown).reduce((i,r)=>i.add(r),t),e=a$4(this.pricing.baseChargeAmount,a,this.pricing.isTaxInclusive,this.pricing.applicableTaxRule),n={};e.taxBreakdown.forEach(i=>{n[i.ruleId]={rate:i.rate,taxableAmount:i.taxableAmount,taxAmount:i.taxAmount,system:i.system,subSystem:i.subSystem};}),this.total={discountTotal:e.discountTotal,discountBreakdown:this.total.discountBreakdown,taxTotal:e.taxTotal,taxBreakdown:n,taxExclusive:{chargeAmount:e.taxExclusive.baseAmount,netChargeAmount:e.taxExclusive.netAmount},taxInclusive:{chargeAmount:e.taxInclusive.baseAmount,netChargeAmount:e.taxInclusive.netAmount},grandTotal:e.taxInclusive.grandTotal};}getDetails(){return {id:this.id,name:a$3.deepClone(this.name),type:this.type,category:this.category,pricing:{baseChargeAmount:this.pricing.baseChargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(a=>a.getDetails()),isTaxInclusive:this.pricing.isTaxInclusive},impact:this.impact,lineItemId:this.lineItemId,total:{discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([a,e])=>[a,e.getDetails()])),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([a,e])=>[a,{rate:e.rate,taxableAmount:e.taxableAmount.getDetails(),taxAmount:e.taxAmount.getDetails(),system:e.system,subSystem:e.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),taxExclusive:{chargeAmount:this.total.taxExclusive.chargeAmount.getDetails(),netChargeAmount:this.total.taxExclusive.netChargeAmount.getDetails()},taxInclusive:{chargeAmount:this.total.taxInclusive.chargeAmount.getDetails(),netChargeAmount:this.total.taxInclusive.netChargeAmount.getDetails()},grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};export{b as a};//# sourceMappingURL=chunk-A2PC4S2X.mjs.map
2
+ //# sourceMappingURL=chunk-A2PC4S2X.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/Classes/Charge.ts"],"names":["ChargeModel","CustomFieldModel","data","PriceModel","r","TaxRuleModel","InvalidChargeError","discountId","discount","taxRuleId","taxBreakdown","locale","Utils_default","LocaleLanguageMap","key","value","taxRules","taxRule","InvalidTaxRuleError","InvalidChargeTaxRuleError","uniqueTaxRule","i","currentTaxRuleId","j","r1","r2","r1Min","r1Max","r1ExcludeMin","r1ExcludeMax","r2Min","r2Max","r2ExcludeMin","r2ExcludeMax","r1EndsBeforeR2Starts","compare","r2EndsBeforeR1Starts","appliedDiscounts","chargeDiscounts","zero","totalDiscount","sum","s","result","calculateDualViewTotals","entry","k","v"],"mappings":"mSAwGqBA,IAAAA,CAAAA,CAArB,cAAyCC,CAAiB,CAC/C,EAAA,CACA,IACA,CAAA,IAAA,CACA,QACA,CAAA,MAAA,CACA,OACA,CAAA,UAAA,CACA,KAEV,CAAA,WAAA,CAAYC,CAAwB,CAAA,CAgBnC,GAfA,KAAA,CAAMA,CAAI,CAAA,CACV,IAAK,CAAA,EAAA,CAAKA,CAAK,CAAA,EAAA,CACf,IAAK,CAAA,IAAA,CAAOA,CAAK,CAAA,IAAA,CACjB,IAAK,CAAA,IAAA,CAAOA,EAAK,IACjB,CAAA,IAAA,CAAK,QAAWA,CAAAA,CAAAA,CAAK,QACrB,CAAA,IAAA,CAAK,MAASA,CAAAA,CAAAA,CAAK,MACnB,CAAA,IAAA,CAAK,UAAaA,CAAAA,CAAAA,CAAK,UACv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CAAK,KAAM,CAAA,YAAA,CAAa,YAAa,CAAA,UAAA,EACnD,CAAA,eAAA,CAAiB,IAAK,CAAA,KAAA,CAAM,YAAa,CAAA,eAAA,CAAgB,UAAW,EACrE,CACA,CAAA,YAAA,CAAc,CACb,YAAA,CAAc,IAAK,CAAA,KAAA,CAAM,YAAa,CAAA,YAAA,CAAa,UAAW,EAAA,CAC9D,eAAiB,CAAA,IAAA,CAAK,KAAM,CAAA,YAAA,CAAa,eAAgB,CAAA,UAAA,EAC1D,CAAA,CACA,UAAY,CAAA,IAAA,CAAK,KAAM,CAAA,UAAA,CAAW,UAAW,EAC9C,CACA,CAAA,YAAA,CAAc,IAAK,CAAA,kBAAA,EACpB,CAED,CACD","file":"chunk-A2PC4S2X.mjs","sourcesContent":["import { CustomFieldAttributes, CustomFieldModel } from \"./Base\";\r\nimport Utils from \"../Utils\";\r\nimport { LocaleCode, LocalizedString } from \"./Common\";\r\nimport { ChargeImpact, ChargeType, LocaleLanguageMap, TaxSystem } from \"./Enum\";\r\nimport { InvalidChargeTaxRuleError, InvalidChargeError, InvalidTaxRuleError } from \"./Error\";\r\nimport { calculateDualViewTotals } from \"../Utils/TaxMath\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport { TaxRuleData, TaxRuleModel } from \"./TaxRule\";\r\nimport CouponModel from \"./Coupon\";\r\n\r\nexport type ChargePricing = {\r\n /** Tax-inclusive original charge amount before any discounts. Always non-negative. */\r\n baseChargeAmount: PriceData;\r\n /** Tax category of the charge. */\r\n taxCategory: string;\r\n /** Tax rules applicable to the charge. */\r\n applicableTaxRule: TaxRuleData[];\r\n isTaxInclusive?: boolean;\r\n};\r\n\r\nexport type ChargePricingModel = {\r\n /** Tax-inclusive original charge amount before any discounts. Always non-negative. */\r\n baseChargeAmount: PriceModel;\r\n /** Tax category of the charge. */\r\n taxCategory: string;\r\n /** Tax rules applicable to the charge. */\r\n applicableTaxRule: TaxRuleModel[];\r\n isTaxInclusive: boolean;\r\n};\r\n\r\nexport type ChargeTaxBreakdown = {\r\n /** Tax rate: e.g., 0.09 for 9% */\r\n rate: number;\r\n /** Reverse-calculated pre-tax base from the netChargeAmount (post-discount) */\r\n taxableAmount: PriceData;\r\n /** Tax portion for this rule (netChargeAmount - taxableAmount) */\r\n taxAmount: PriceData;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type ChargeTaxBreakdownModel = {\r\n rate: number;\r\n taxableAmount: PriceModel;\r\n taxAmount: PriceModel;\r\n system: TaxSystem;\r\n subSystem: string;\r\n};\r\n\r\nexport type ChargeTotals = {\r\n /** Coupon code -> discount amount mapping */\r\n discountBreakdown: Record<string, PriceData>;\r\n /** Sum of all discounts */\r\n discountTotal: PriceData;\r\n /** Sum of all taxAmount values */\r\n taxTotal: PriceData;\r\n /** Tax breakdown per rule/category (reverse-calculated from netChargeAmount) */\r\n taxBreakdown: Record<string, ChargeTaxBreakdown>;\r\n taxExclusive: {\r\n chargeAmount: PriceData;\r\n netChargeAmount: PriceData;\r\n };\r\n taxInclusive: {\r\n chargeAmount: PriceData;\r\n netChargeAmount: PriceData;\r\n };\r\n grandTotal: PriceData;\r\n};\r\n\r\nexport type ChargeTotalsModel = {\r\n discountTotal: PriceModel;\r\n discountBreakdown: Record<string, PriceModel>;\r\n taxTotal: PriceModel;\r\n taxBreakdown: Record<string, ChargeTaxBreakdownModel>;\r\n taxExclusive: {\r\n chargeAmount: PriceModel;\r\n netChargeAmount: PriceModel;\r\n };\r\n taxInclusive: {\r\n chargeAmount: PriceModel;\r\n netChargeAmount: PriceModel;\r\n };\r\n grandTotal: PriceModel;\r\n};\r\n\r\nexport type ChargeAttributes = CustomFieldAttributes & {\r\n id: string;\r\n name: LocalizedString;\r\n type: ChargeType;\r\n category: string;\r\n impact: ChargeImpact; // ADD or SUBTRACT\r\n pricing: ChargePricing;\r\n lineItemId?: string;\r\n total: ChargeTotals;\r\n};\r\n\r\nexport type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId'> & {\r\n\tlineItemId?: string;\r\n};\r\n\r\n/**\r\n * Represents an additional charge (or discount if amount is negative) in a shopping container.\r\n * Supports its own tax rules.\r\n */\r\nexport default class ChargeModel extends CustomFieldModel {\r\n\tprotected id: string;\r\n\tprotected name: LocalizedString;\r\n\tprotected type: ChargeType;\r\n\tprotected category: string;\r\n\tprotected impact: ChargeImpact;\r\n\tprotected pricing: ChargePricingModel;\r\n\tprotected lineItemId?: string;\r\n\tprotected total: ChargeTotalsModel;\r\n\r\n\tconstructor(data: ChargeAttributes) {\r\n\t\tsuper(data);\r\n\t\tthis.id = data.id;\r\n\t\tthis.name = data.name;\r\n\t\tthis.type = data.type;\r\n\t\tthis.category = data.category;\r\n\t\tthis.impact = data.impact;\r\n\t\tthis.lineItemId = data.lineItemId;\r\n\t\tthis.pricing = {\r\n\t\t\tbaseChargeAmount: new PriceModel(data.pricing.baseChargeAmount),\r\n\t\t\ttaxCategory: data.pricing.taxCategory,\r\n\t\t\tapplicableTaxRule: data.pricing.applicableTaxRule.map(r => new TaxRuleModel(r)),\r\n\t\t\tisTaxInclusive: data.pricing.isTaxInclusive ?? false\r\n\t\t};\r\n\r\n\t\tthis.validateTaxRules(this.pricing.applicableTaxRule);\r\n\t\tif(this.impact === ChargeImpact.SUBTRACT && this.type !== ChargeType.ADJUSTMENT) {\r\n\t\t\tthrow new InvalidChargeError('SUBTRACT impact is only allowed for ADJUSTMENT charge');\r\n\t\t}\r\n\r\n\t\tthis.total = {\r\n\t\t\tdiscountTotal: new PriceModel(data.total.discountTotal),\r\n\t\t\tdiscountBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(data.total.discountBreakdown).map(([discountId, discount]) => [\r\n\t\t\t\t\tdiscountId,\r\n\t\t\t\t\tnew PriceModel(discount)\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\ttaxBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(data.total.taxBreakdown).map(([taxRuleId, taxBreakdown]) => [\r\n\t\t\t\t\ttaxRuleId,\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\trate: taxBreakdown.rate,\r\n\t\t\t\t\t\ttaxableAmount: new PriceModel(taxBreakdown.taxableAmount),\r\n\t\t\t\t\t\ttaxAmount: new PriceModel(taxBreakdown.taxAmount),\r\n\t\t\t\t\t\tsystem: taxBreakdown.system,\r\n\t\t\t\t\t\tsubSystem: taxBreakdown.subSystem\r\n\t\t\t\t\t}\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\ttaxTotal: new PriceModel(data.total.taxTotal),\r\n\t\t\ttaxExclusive: {\r\n\t\t\t\tchargeAmount: new PriceModel(data.total.taxExclusive.chargeAmount),\r\n\t\t\t\tnetChargeAmount: new PriceModel(data.total.taxExclusive.netChargeAmount),\r\n\t\t\t},\r\n\t\t\ttaxInclusive: {\r\n\t\t\t\tchargeAmount: new PriceModel(data.total.taxInclusive.chargeAmount),\r\n\t\t\t\tnetChargeAmount: new PriceModel(data.total.taxInclusive.netChargeAmount),\r\n\t\t\t},\r\n\t\t\tgrandTotal: new PriceModel(data.total.grandTotal),\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the unique identifier of the charge.\r\n\t * @returns \r\n\t */\r\n\tpublic getId(): string { return this.id; }\r\n\r\n\r\n\t/**\r\n\t * Gets the full localized product name object.\r\n\t * @returns A copy of the LocalizedString object for the name.\r\n\t */\r\n\tgetName(): LocalizedString\r\n\t/**\r\n\t * Gets the product name for a specific locale, falling back to English ('en').\r\n\t * @param locale - The desired locale code.\r\n\t * @returns The name string for the specified locale.\r\n\t */\r\n\tgetName(locale: LocaleCode): string\r\n\tgetName(locale?: LocaleCode): LocalizedString | string {\r\n\t\tif (locale) {\r\n\t\t\treturn Utils.deepClone(this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en);\r\n\t\t} else {\r\n\t\t\treturn Utils.deepClone(this.name);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the charge category.\r\n\t * @returns The category string.\r\n\t */\r\n\tpublic getCategory(): string { return this.category; }\r\n\r\n\t/**\r\n\t * Gets the charge type.\r\n\t * @returns The charge type enum value.\r\n\t */\r\n\tpublic getType(): ChargeType { return this.type; }\r\n\t/**\r\n\t * Gets the charge impact (add or subtract).\r\n\t * @returns The charge impact.\r\n\t */\r\n\tpublic getImpact(): ChargeImpact { return this.impact; }\r\n\r\n\t/**\r\n\t * Gets the related line item id, if any.\r\n\t * @returns The line item id or undefined.\r\n\t */\r\n\tpublic getLineItemId(): string | undefined { return this.lineItemId; }\r\n\r\n\t/**\r\n\t * Gets whether the charge is tax inclusive.\r\n\t */\r\n\tpublic getIsTaxInclusive(): boolean {\r\n\t\treturn this.pricing.isTaxInclusive;\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the pricing details (models) for this charge.\r\n\t * @returns Pricing details including price, tax category, and tax rules.\r\n\t */\r\n\tpublic getPricing(): ChargePricingModel {\r\n\t\treturn {\r\n\t\t\tbaseChargeAmount: this.pricing.baseChargeAmount,\r\n\t\t\ttaxCategory: this.pricing.taxCategory,\r\n\t\t\tapplicableTaxRule: [...this.pricing.applicableTaxRule],\r\n\t\t\tisTaxInclusive: this.pricing.isTaxInclusive\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the computed totals for this charge.\r\n\t * @returns Totals including discounts, taxes, and grand total.\r\n\t */\r\n\tpublic getTotal(): ChargeTotalsModel {\r\n\t\treturn {\r\n\t\t\tdiscountTotal: this.total.discountTotal,\r\n\t\t\tdiscountBreakdown: { ...this.total.discountBreakdown },\r\n\t\t\ttaxTotal: this.total.taxTotal,\r\n\t\t\ttaxBreakdown: Object.fromEntries(\r\n\t\t\t\tObject.entries(this.total.taxBreakdown).map(([key, value]) => [\r\n\t\t\t\t\tkey,\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\trate: value.rate,\r\n\t\t\t\t\t\ttaxableAmount: value.taxableAmount,\r\n\t\t\t\t\t\ttaxAmount: value.taxAmount,\r\n\t\t\t\t\t\tsystem: value.system,\r\n\t\t\t\t\t\tsubSystem: value.subSystem\r\n\t\t\t\t\t}\r\n\t\t\t\t])\r\n\t\t\t),\r\n\t\t\ttaxExclusive: {\r\n\t\t\t\tchargeAmount: this.total.taxExclusive.chargeAmount,\r\n\t\t\t\tnetChargeAmount: this.total.taxExclusive.netChargeAmount,\r\n\t\t\t},\r\n\t\t\ttaxInclusive: {\r\n\t\t\t\tchargeAmount: this.total.taxInclusive.chargeAmount,\r\n\t\t\t\tnetChargeAmount: this.total.taxInclusive.netChargeAmount,\r\n\t\t\t},\r\n\t\t\tgrandTotal: this.total.grandTotal,\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the applicable tax rules for this charge.\r\n\t * @returns A list of tax rules.\r\n\t */\r\n\tpublic getApplicableTaxRules(): TaxRuleModel[] {\r\n\t\treturn [...this.pricing.applicableTaxRule];\r\n\t}\r\n\r\n\t/**\r\n\t * Updates the tax rule for this line item and recalculates totals.\r\n\t * @param taxRule - The new tax rule to apply.\r\n\t * @throws {Error} If the tax rule category does not match the item's tax category.\r\n\t */\r\n\tpublic updateTax(taxRules: TaxRuleModel[]): void {\r\n\t\tif (this.type === ChargeType.ADJUSTMENT && taxRules.length > 0) {\r\n\t\t\tthrow new InvalidChargeError(\"Adjustment charges cannot apply tax rules.\");\r\n\t\t}\r\n\t\ttaxRules.forEach(taxRule => {\r\n\t\t\tif (!taxRule.appliesTo(this.pricing.taxCategory, taxRule.getCountry())) {\r\n\t\t\t\tthrow new InvalidTaxRuleError();\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\t// Remove the old taxableUnitPrice calculation - no longer needed\r\n\t\tthis.validateTaxRules(taxRules);\r\n\t\tthis.pricing.applicableTaxRule = taxRules;\r\n\t\tthis.calculateTotals();\r\n\t}\r\n\r\n\t/**\r\n\t * Validates that there are no overlapping price brackets for any tax rules within the charge.\r\n\t * @param taxRules - The list of tax rules to validate.\r\n\t * @throws {InvalidChargeTaxRuleError} If any rules have positive tax rates with SUBTRACT impact or if duplicate rule IDs are found.\r\n\t * @throws {InvalidChargeTaxRuleError} Duplicate tax rule IDs will results in error.\r\n\t * @throws {CoincidingTaxBracketError} If any overlapping rules are found.\r\n\t */\r\n\tprivate validateTaxRules(taxRules: TaxRuleModel[]): void {\r\n\t\tif(this.impact === ChargeImpact.SUBTRACT) {\r\n\t\t\tif(taxRules.some(taxRule => taxRule.getRate() > 0)) {\r\n\t\t\t\tthrow new InvalidChargeTaxRuleError(\"Subtractive charges cannot have positive tax rates.\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst uniqueTaxRule = new Set();\r\n\t\tfor (let i = 0; i < taxRules.length; i++) {\r\n\t\t\tconst currentTaxRuleId = taxRules[i].getTaxRuleId();\r\n\t\t\tif(uniqueTaxRule.has(currentTaxRuleId)){\r\n\t\t\t\tthrow new InvalidChargeTaxRuleError(\"Duplicate tax rule ID found: \" + currentTaxRuleId);\r\n\t\t\t} else {\r\n\t\t\t\tuniqueTaxRule.add(currentTaxRuleId);\r\n\t\t\t}\r\n\r\n\t\t\tfor (let j = i + 1; j < taxRules.length; j++) {\r\n\t\t\t\tconst r1 = taxRules[i];\r\n\t\t\t\tconst r2 = taxRules[j];\r\n\r\n\t\t\t\tconst r1Min = r1.getMinPrice();\r\n\t\t\t\tconst r1Max = r1.getMaxPrice();\r\n\t\t\t\tconst r1ExcludeMin = r1.getExcludeMin();\r\n\t\t\t\tconst r1ExcludeMax = r1.getExcludeMax();\r\n\t\t\t\tconst r2Min = r2.getMinPrice();\r\n\t\t\t\tconst r2Max = r2.getMaxPrice();\r\n\t\t\t\tconst r2ExcludeMin = r2.getExcludeMin();\r\n\t\t\t\tconst r2ExcludeMax = r2.getExcludeMax();\r\n\r\n\t\t\t\t// Two ranges are disjoint if one ends strictly before the other starts.\r\n\t\t\t\t// If they only touch at one point, disjoint only when either side excludes that point.\r\n\t\t\t\tconst r1EndsBeforeR2Starts = (() => {\r\n\t\t\t\t\tif (!r1Max) return false;\r\n\t\t\t\t\tconst compare = r1Max.compareTo(r2Min);\r\n\t\t\t\t\treturn compare < 0 || (compare === 0 && (r1ExcludeMax || r2ExcludeMin));\r\n\t\t\t\t})();\r\n\t\t\t\tconst r2EndsBeforeR1Starts = (() => {\r\n\t\t\t\t\tif (!r2Max) return false;\r\n\t\t\t\t\tconst compare = r2Max.compareTo(r1Min);\r\n\t\t\t\t\treturn compare < 0 || (compare === 0 && (r2ExcludeMax || r1ExcludeMin));\r\n\t\t\t\t})();\r\n\t\t\t\tconst overlap = !(r1EndsBeforeR2Starts || r2EndsBeforeR1Starts);\r\n\r\n\t\t\t\tif (overlap) {\r\n\t\t\t\t\t// Exception: Allow overlapping rules if they have the exact same price bracket (slab)\r\n\t\t\t\t\tconst sameSlab = r1Min.compareTo(r2Min) === 0 &&\r\n\t\t\t\t\t\tr1ExcludeMin === r2ExcludeMin &&\r\n\t\t\t\t\t\tr1ExcludeMax === r2ExcludeMax &&\r\n\t\t\t\t\t\t((!r1Max && !r2Max) || (r1Max && r2Max && r1Max.compareTo(r2Max) === 0));\r\n\r\n\t\t\t\t\tif (!sameSlab) {\r\n\t\t\t\t\t\tthrow new InvalidChargeTaxRuleError(\r\n\t\t\t\t\t\t\t`Overlapping rules found: [${r1.getTaxRuleId()}: ${r1ExcludeMin ? \"(\" : \"[\"}${r1Min.getAmount()}-${r1Max?.getAmount() ?? \"Infinity\"}${r1ExcludeMax ? \")\" : \"]\"}] and [${r2.getTaxRuleId()}: ${r2ExcludeMin ? \"(\" : \"[\"}${r2Min.getAmount()}-${r2Max?.getAmount() ?? \"Infinity\"}${r2ExcludeMax ? \")\" : \"]\"}]`\r\n\t\t\t\t\t\t);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Updates the discounts applied to this line item and recalculates totals.\r\n\t * @param appliedDiscounts - List of coupons and their allocated discount amounts.\r\n\t*/\r\n\tpublic updateDiscounts(appliedDiscounts: { coupon: CouponModel, amount: PriceModel }[]): void {\r\n\t\tlet chargeDiscounts = {} as Record<string, PriceModel>;\r\n\t\tappliedDiscounts.forEach(discount => {\r\n\t\t\tchargeDiscounts[discount.coupon.getCode()] = discount.amount;\r\n\t\t});\r\n\r\n\t\tthis.total.discountBreakdown = chargeDiscounts;\r\n\t\tthis.calculateTotals();\r\n\t}\r\n\r\n\t/**\r\n\t * Recalculates totals for this charge based on pricing and discounts.\r\n\t * Delegates tax computation to shared calculateDualViewTotals utility.\r\n\t */\r\n\tpublic calculateTotals(): void {\r\n\t\tconst zero = this.pricing.baseChargeAmount.zero();\r\n\t\tconst totalDiscount = Object.values(this.total.discountBreakdown).reduce((sum, s) => sum.add(s), zero);\r\n\r\n\t\tconst result = calculateDualViewTotals(\r\n\t\t\tthis.pricing.baseChargeAmount,\r\n\t\t\ttotalDiscount,\r\n\t\t\tthis.pricing.isTaxInclusive,\r\n\t\t\tthis.pricing.applicableTaxRule\r\n\t\t);\r\n\r\n\t\t// Map TaxBreakdownEntry[] to Record<string, ChargeTaxBreakdownModel>\r\n\t\tconst taxBreakdown: Record<string, ChargeTaxBreakdownModel> = {};\r\n\t\tresult.taxBreakdown.forEach(entry => {\r\n\t\t\ttaxBreakdown[entry.ruleId] = {\r\n\t\t\t\trate: entry.rate,\r\n\t\t\t\ttaxableAmount: entry.taxableAmount,\r\n\t\t\t\ttaxAmount: entry.taxAmount,\r\n\t\t\t\tsystem: entry.system,\r\n\t\t\t\tsubSystem: entry.subSystem\r\n\t\t\t};\r\n\t\t});\r\n\r\n\t\tthis.total = {\r\n\t\t\tdiscountTotal: result.discountTotal,\r\n\t\t\tdiscountBreakdown: this.total.discountBreakdown,\r\n\t\t\ttaxTotal: result.taxTotal,\r\n\t\t\ttaxBreakdown: taxBreakdown,\r\n\t\t\ttaxExclusive: {\r\n\t\t\t\tchargeAmount: result.taxExclusive.baseAmount,\r\n\t\t\t\tnetChargeAmount: result.taxExclusive.netAmount,\r\n\t\t\t},\r\n\t\t\ttaxInclusive: {\r\n\t\t\t\tchargeAmount: result.taxInclusive.baseAmount,\r\n\t\t\t\tnetChargeAmount: result.taxInclusive.netAmount,\r\n\t\t\t},\r\n\t\t\tgrandTotal: result.taxInclusive.grandTotal,\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Gets a plain data object representing this charge.\r\n\t * @returns ChargeData for serialization.\r\n\t */\r\n\tpublic getDetails(): ChargeData {\r\n\t\tconst details: ChargeData = {\r\n\t\t\tid: this.id,\r\n\t\t\tname: Utils.deepClone(this.name),\r\n\t\t\ttype: this.type,\r\n\t\t\tcategory: this.category,\r\n\t\t\tpricing: {\r\n\t\t\t\tbaseChargeAmount: this.pricing.baseChargeAmount.getDetails(),\r\n\t\t\t\ttaxCategory: this.pricing.taxCategory,\r\n\t\t\t\tapplicableTaxRule: this.pricing.applicableTaxRule.map(r => r.getDetails()),\r\n\t\t\t\tisTaxInclusive: this.pricing.isTaxInclusive\r\n\t\t\t},\r\n\t\t\timpact: this.impact,\r\n\t\t\tlineItemId: this.lineItemId,\r\n\t\t\ttotal: {\r\n\t\t\t\tdiscountTotal: this.total.discountTotal.getDetails(),\r\n\t\t\t\tdiscountBreakdown: Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([k, v]) => [k, v.getDetails()])),\r\n\t\t\t\ttaxBreakdown: Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([k, v]) => [k, {\r\n\t\t\t\t\trate: v.rate,\r\n\t\t\t\t\ttaxableAmount: v.taxableAmount.getDetails(),\r\n\t\t\t\t\ttaxAmount: v.taxAmount.getDetails(),\r\n\t\t\t\t\tsystem: v.system,\r\n\t\t\t\t\tsubSystem: v.subSystem\r\n\t\t\t\t}])),\r\n\t\t\t\ttaxTotal: this.total.taxTotal.getDetails(),\r\n\t\t\t\ttaxExclusive: {\r\n\t\t\t\t\tchargeAmount: this.total.taxExclusive.chargeAmount.getDetails(),\r\n\t\t\t\t\tnetChargeAmount: this.total.taxExclusive.netChargeAmount.getDetails(),\r\n\t\t\t\t},\r\n\t\t\t\ttaxInclusive: {\r\n\t\t\t\t\tchargeAmount: this.total.taxInclusive.chargeAmount.getDetails(),\r\n\t\t\t\t\tnetChargeAmount: this.total.taxInclusive.netChargeAmount.getDetails(),\r\n\t\t\t\t},\r\n\t\t\t\tgrandTotal: this.total.grandTotal.getDetails(),\r\n\t\t\t},\r\n\t\t\tcustomFields: this.getAllCustomFields()\r\n\t\t};\r\n\t\treturn details;\r\n\t}\r\n}\r\n"]}
@@ -0,0 +1,2 @@
1
+ import {a}from'./chunk-YDSXBMNW.mjs';import {e}from'./chunk-3SUQYXIJ.mjs';import {b as b$1}from'./chunk-HX32EJ3F.mjs';import {a as a$1}from'./chunk-A2PC4S2X.mjs';import {a as a$2}from'./chunk-XXKEHCV5.mjs';import {a as a$3}from'./chunk-UIQH5QIR.mjs';import {b}from'./chunk-UXZBULDS.mjs';var R=class extends b{id;customerId;customerEmail;anonymousId;lineItems;charges;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;#t;constructor(t,e$1=new Date,a$4={checkCouponExpiry:!0}){super(t,e$1),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(i=>new a(i)),this.charges=(t.charges??[]).map(i=>new a$1(i)),this.billingAddress=t.billingAddress?new b$1(t.billingAddress,e$1):null,this.shippingAddress=t.shippingAddress?new b$1(t.shippingAddress,e$1):null,this.coupons=(t.coupons??[]).map(i=>new e(i)),this.shippingDetails=t.shippingDetails?a$2.deepClone(t.shippingDetails):null,this.total={lineItemTaxTotal:new a$3(t.total.lineItemTaxTotal),lineItemTaxBreakdown:this.mapTaxBreakdown(t.total.lineItemTaxBreakdown),additiveChargesTaxTotal:new a$3(t.total.additiveChargesTaxTotal),additiveChargesTaxBreakdown:this.mapTaxBreakdown(t.total.additiveChargesTaxBreakdown),adjustmentCharges:new a$3(t.total.adjustmentCharges),discountTotal:new a$3(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([i,o])=>[i,new a$3(o)])),taxTotal:new a$3(t.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(t.total.taxBreakdown),taxExclusive:{lineItemSubtotal:new a$3(t.total.taxExclusive.lineItemSubtotal),netLineItemSubtotal:new a$3(t.total.taxExclusive.netLineItemSubtotal),additiveCharges:new a$3(t.total.taxExclusive.additiveCharges),netAdditiveCharges:new a$3(t.total.taxExclusive.netAdditiveCharges),shippingCharges:new a$3(t.total.taxExclusive.shippingCharges),netShippingCharges:new a$3(t.total.taxExclusive.netShippingCharges)},taxInclusive:{lineItemSubtotal:new a$3(t.total.taxInclusive.lineItemSubtotal),netLineItemSubtotal:new a$3(t.total.taxInclusive.netLineItemSubtotal),additiveCharges:new a$3(t.total.taxInclusive.additiveCharges),netAdditiveCharges:new a$3(t.total.taxInclusive.netAdditiveCharges),shippingCharges:new a$3(t.total.taxInclusive.shippingCharges),netShippingCharges:new a$3(t.total.taxInclusive.netShippingCharges)},grandTotal:new a$3(t.total.grandTotal)},this.#t={checkCouponExpiry:a$4.checkCouponExpiry};}mapTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,a])=>[e,{system:a.system,totalAmount:new a$3(a.totalAmount),subSystems:Object.fromEntries(Object.entries(a.subSystems).map(([i,o])=>[i,new a$3(o)]))}]))}serializeTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,a])=>[e,{system:a.system,totalAmount:a.totalAmount.getDetails(),subSystems:Object.fromEntries(Object.entries(a.subSystems).map(([i,o])=>[i,o.getDetails()]))}]))}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}getCharges(){return this.charges.map(t=>new a$1(t.getDetails()))}addCharge(t){this.charges.push(t),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?a$2.deepClone(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 {lineItemTaxTotal:this.total.lineItemTaxTotal,lineItemTaxBreakdown:Object.fromEntries(Object.entries(this.total.lineItemTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),additiveChargesTaxTotal:this.total.additiveChargesTaxTotal,additiveChargesTaxBreakdown:Object.fromEntries(Object.entries(this.total.additiveChargesTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),adjustmentCharges:this.total.adjustmentCharges,discountBreakdown:{...this.total.discountBreakdown},discountTotal:this.total.discountTotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),taxExclusive:{lineItemSubtotal:this.total.taxExclusive.lineItemSubtotal,netLineItemSubtotal:this.total.taxExclusive.netLineItemSubtotal,additiveCharges:this.total.taxExclusive.additiveCharges,netAdditiveCharges:this.total.taxExclusive.netAdditiveCharges,shippingCharges:this.total.taxExclusive.shippingCharges,netShippingCharges:this.total.taxExclusive.netShippingCharges},taxInclusive:{lineItemSubtotal:this.total.taxInclusive.lineItemSubtotal,netLineItemSubtotal:this.total.taxInclusive.netLineItemSubtotal,additiveCharges:this.total.taxInclusive.additiveCharges,netAdditiveCharges:this.total.taxInclusive.netAdditiveCharges,shippingCharges:this.total.taxInclusive.shippingCharges,netShippingCharges:this.total.taxInclusive.netShippingCharges},grandTotal:this.total.grandTotal}}getDetails(){let t=this.getTotal();return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(e=>e.getDetails()),charges:this.getCharges().map(e=>e.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(e=>e.getDetails()),total:{lineItemTaxTotal:t.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(t.lineItemTaxBreakdown),additiveChargesTaxTotal:t.additiveChargesTaxTotal.getDetails(),additiveChargesTaxBreakdown:this.serializeTaxBreakdown(t.additiveChargesTaxBreakdown),adjustmentCharges:t.adjustmentCharges.getDetails(),discountTotal:t.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(t.discountBreakdown).map(([e,a])=>[e,a.getDetails()])),taxTotal:t.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(t.taxBreakdown),taxExclusive:{lineItemSubtotal:t.taxExclusive.lineItemSubtotal.getDetails(),netLineItemSubtotal:t.taxExclusive.netLineItemSubtotal.getDetails(),additiveCharges:t.taxExclusive.additiveCharges.getDetails(),netAdditiveCharges:t.taxExclusive.netAdditiveCharges.getDetails(),shippingCharges:t.taxExclusive.shippingCharges.getDetails(),netShippingCharges:t.taxExclusive.netShippingCharges.getDetails()},taxInclusive:{lineItemSubtotal:t.taxInclusive.lineItemSubtotal.getDetails(),netLineItemSubtotal:t.taxInclusive.netLineItemSubtotal.getDetails(),additiveCharges:t.taxInclusive.additiveCharges.getDetails(),netAdditiveCharges:t.taxInclusive.netAdditiveCharges.getDetails(),shippingCharges:t.taxInclusive.shippingCharges.getDetails(),netShippingCharges:t.taxInclusive.netShippingCharges.getDetails()},grandTotal:t.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new a$3({amount:0,currency:this.currency});this.lineItems.forEach(c=>{c.getState()!=="CANCELLED"&&c.updateDiscounts([]);}),this.charges.forEach(c=>c.updateDiscounts([]));let e=this.getCouponEvaluationBases(),a=t,i={},o={};this.coupons.filter(c=>c.getCategory()!=="SHIPPING").forEach(c=>{let s=c.calculateApplicableCouponDiscount(e.targetSubtotal,e.targetShipping,this.country,this.currency,this.#t.checkCouponExpiry);a=a.add(s),i[c.getCode()]=s,o[c.getCode()]=s;}),this.applyDiscountsInLineItem(o);let g=this.getCouponEvaluationBases(),m={};this.coupons.filter(c=>c.getCategory()==="SHIPPING").forEach(c=>{let s=c.calculateApplicableCouponDiscount(g.targetNetSubtotal,g.targetShipping,this.country,this.currency,this.#t.checkCouponExpiry).min(g.targetShipping);a=a.add(s),i[c.getCode()]=s,m[c.getCode()]=s;}),this.applyDiscountsInShippingCharges(m);let n=t,r=t,d=t,h=t,C=t,T=t,w={},N={},z={},v=(c,s)=>{Object.entries(c).forEach(([F,V])=>{let{system:x,subSystem:y,taxAmount:P}=V;s[x]||(s[x]={system:x,totalAmount:t,subSystems:{}}),s[x].subSystems[y]?s[x].subSystems[y]=s[x].subSystems[y].add(P):s[x].subSystems[y]=P,s[x].totalAmount=s[x].totalAmount.add(P);});};this.lineItems.filter(c=>c.getState()!=="CANCELLED").forEach(c=>{let s=c.getTotal();d=d.add(s.taxExclusive.subtotal),h=h.add(s.taxExclusive.netSubtotal),C=C.add(s.taxInclusive.subtotal),T=T.add(s.taxInclusive.netSubtotal),s.taxBreakdown&&(v(s.taxBreakdown,N),v(s.taxBreakdown,w),n=n.add(s.taxTotal));});let D=t,A=t,E=t,S=t,B=t,k=t,M=t,f=t,b=t;this.charges.forEach(c=>{let s=c.getTotal();c.getImpact()==="ADD"?(D=D.add(s.taxExclusive.chargeAmount),A=A.add(s.taxExclusive.netChargeAmount),E=E.add(s.taxInclusive.chargeAmount),S=S.add(s.grandTotal),c.getType()==="SHIPPING"&&(B=B.add(s.taxExclusive.chargeAmount),k=k.add(s.taxExclusive.netChargeAmount),M=M.add(s.taxInclusive.chargeAmount),f=f.add(s.grandTotal)),s.taxBreakdown&&(v(s.taxBreakdown,z),v(s.taxBreakdown,w),r=r.add(s.taxTotal))):c.getImpact()==="SUBTRACT"&&(b=b.add(s.grandTotal));});let Z=n.add(r),U=T.add(S).subtract(b);this.total={lineItemTaxTotal:n,lineItemTaxBreakdown:N,additiveChargesTaxTotal:r,additiveChargesTaxBreakdown:z,adjustmentCharges:b,discountTotal:a,discountBreakdown:i,taxTotal:Z,taxBreakdown:w,taxExclusive:{lineItemSubtotal:d,netLineItemSubtotal:h,additiveCharges:D,netAdditiveCharges:A,shippingCharges:B,netShippingCharges:k},taxInclusive:{lineItemSubtotal:C,netLineItemSubtotal:T,additiveCharges:E,netAdditiveCharges:S,shippingCharges:M,netShippingCharges:f},grandTotal:U};}updateShippingDetails(t){this.shippingDetails=t;}applyCoupons(t){let e=t.filter(i=>i.getCategory()==="SHIPPING"),a=t.filter(i=>i.getCategory()!=="SHIPPING");this.coupons=[],this.total.discountTotal=this.total.discountTotal.zero(),this.total.discountBreakdown={},a.length&&this.applyNonShippingCoupons(a),this.applyDiscountsInLineItem(this.total.discountBreakdown),e.length&&this.applyShippingCoupons(e),this.calculateTotals();}applyDiscountsInLineItem(t){let e=Array.from(Object.entries(t)).filter(i=>!i[1].isZero()),a=new Map;this.lineItems.forEach(i=>a.set(i.getId(),[])),e.forEach(([i,o])=>{let p=this.coupons.find(n=>n.getCode()===i);if(!p||o.isZero())return;let g=this.lineItems.reduce((n,r)=>n.add(r.getIsTaxInclusive()?r.getTotal().taxInclusive.subtotal:r.getTotal().taxExclusive.subtotal),new a$3({amount:0,currency:this.currency})),m=this.lineItems.filter(n=>n.getState()!=="CANCELLED"&&!n.getTotal().taxExclusive.subtotal.isZero()).sort((n,r)=>{let d=n.getIsTaxInclusive()?n.getTotal().taxInclusive.subtotal:n.getTotal().taxExclusive.subtotal,h=r.getIsTaxInclusive()?r.getTotal().taxInclusive.subtotal:r.getTotal().taxExclusive.subtotal;return d.compareTo(h)}),u=new a$3({amount:0,currency:this.currency});m.forEach((n,r)=>{let d,h=n.getIsTaxInclusive()?n.getTotal().taxInclusive.subtotal:n.getTotal().taxExclusive.subtotal;r===m.length-1?d=o.subtract(u):d=o.multiply(h).divide(g).round(),u=u.add(d),a.get(n.getId())?.push({coupon:p,amount:d});});}),this.lineItems.forEach(i=>{i.updateDiscounts(a.get(i.getId()));});}applyDiscountsInShippingCharges(t){let e=Array.from(Object.entries(t)).filter(o=>!o[1].isZero()),a=this.charges.filter(o=>o.getType()==="SHIPPING"),i=new Map;a.forEach(o=>i.set(o.getId(),[])),e.forEach(([o,p])=>{let g=this.coupons.find(r=>r.getCode()===o);if(!g||p.isZero())return;let m=a.reduce((r,d)=>r.add(d.getIsTaxInclusive()?d.getTotal().taxInclusive.chargeAmount:d.getTotal().taxExclusive.chargeAmount),new a$3({amount:0,currency:this.currency})),u=a.filter(r=>!r.getTotal().taxExclusive.chargeAmount.isZero()).sort((r,d)=>{let h=r.getIsTaxInclusive()?r.getTotal().taxInclusive.chargeAmount:r.getTotal().taxExclusive.chargeAmount,C=d.getIsTaxInclusive()?d.getTotal().taxInclusive.chargeAmount:d.getTotal().taxExclusive.chargeAmount;return h.compareTo(C)}),n=new a$3({amount:0,currency:this.currency});u.forEach((r,d)=>{let h,C=r.getIsTaxInclusive()?r.getTotal().taxInclusive.chargeAmount:r.getTotal().taxExclusive.chargeAmount;d===u.length-1?h=p.subtract(n):h=p.multiply(C).divide(m).round(),n=n.add(h),i.get(r.getId())?.push({coupon:g,amount:h});});}),a.forEach(o=>{o.updateDiscounts(i.get(o.getId()));});}getCouponEvaluationBases(){let t=new a$3({amount:0,currency:this.currency}),e=this.lineItems.filter(u=>u.getState()!=="CANCELLED"),a=this.charges.filter(u=>u.getType()==="SHIPPING"),i=e.some(u=>u.getIsTaxInclusive()),o=e.reduce((u,n)=>u.add(i?n.getTotal().taxInclusive.subtotal:n.getTotal().taxExclusive.subtotal),t),p=e.reduce((u,n)=>u.add(i?n.getTotal().taxInclusive.netSubtotal:n.getTotal().taxExclusive.netSubtotal),t),g=a.some(u=>u.getIsTaxInclusive()),m=a.reduce((u,n)=>u.add(g?n.getTotal().taxInclusive.chargeAmount:n.getTotal().taxExclusive.chargeAmount),t);return {targetSubtotal:o,targetShipping:m,targetNetSubtotal:p}}applyNonShippingCoupons(t){let e=t.filter(a=>a.getType()==="coupon");if(e.length===1){let a=this.getCouponEvaluationBases(),i=e[0].calculateApplicableCouponDiscount(a.targetSubtotal,a.targetShipping,this.country,this.currency,this.#t.checkCouponExpiry);i.getAmount()>0&&(this.coupons.push(e[0]),this.total.discountTotal=i,this.total.discountBreakdown[e[0].getCode()]=i);}}applyShippingCoupons(t){let e=this.getCouponEvaluationBases();if(e.targetShipping.getAmount()>0&&t.length>0){let a=e.targetNetSubtotal,i=t.reduce((p,g)=>{if(!p)return g;let m=g.calculateApplicableCouponDiscount(a,e.targetShipping,this.country,this.currency,this.#t.checkCouponExpiry).min(e.targetShipping),u=p.calculateApplicableCouponDiscount(a,e.targetShipping,this.country,this.currency,this.#t.checkCouponExpiry).min(e.targetShipping);return m.compareTo(u)===0?g.getType()==="coupon"?g:p:m.compareTo(u)>0?g:p}),o=i.calculateApplicableCouponDiscount(a,e.targetShipping,this.country,this.currency,this.#t.checkCouponExpiry).min(e.targetShipping);o.getAmount()>0&&(this.coupons.push(i),this.total.discountTotal=this.total.discountTotal.add(o),this.total.discountBreakdown[i.getCode()]=o);}}};export{R as a};//# sourceMappingURL=chunk-LE4HS2A6.mjs.map
2
+ //# sourceMappingURL=chunk-LE4HS2A6.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/Classes/ShoppingContainer.ts"],"names":["BaseShoppingContainerModel","BaseModel","#metaData","data","date","metaData","item","LineItemModel","charge","ChargeModel","AddressModel","coupon","CouponModel","Utils_default","PriceModel","key","value","breakdown","systemKey","systemValue","subKey","subValue","totals","zero","li","bases","discountTotal","discountBreakdown","nonShippingCouponTotal","couponValue","updatedBases","shippingCouponTotal","lineItemTaxTotal","additiveChargesTaxTotal","lineItemSubtotalExcl","netLineItemSubtotalExcl","lineItemSubtotalIncl","netLineItemSubtotalIncl","taxBreakdown","lineItemTaxBreakdown","additiveChargesTaxBreakdown","mergeTax","source","target","_","system","subSystem","taxAmount","t","additiveChargesExcl","netAdditiveChargesExcl","additiveChargesIncl","netAdditiveChargesIncl","shippingChargesExcl","netShippingChargesExcl","shippingChargesIncl","netShippingChargesIncl","adjustmentChargesIncl","taxTotal","grandTotal","shippingDetails","applicableCoupons","shippingCoupons","otherCoupons","couponTotal","couponDiscounts","couponDiscount","itemDiscounts","code","c","targetSubtotal","total","lineItem","validItems","a","b","aVal","bVal","distributed","index","amount","itemVal","shippingCharges","chargeDiscounts","targetShipping","validCharges","chargeVal","activeItems","isAnyItemInclusive","targetNetSubtotal","isAnyShippingInclusive","coupons","netLineItemSubtotal","maxValuedCoupon","maxCoupon","currentCoupon","currentCouponValue","maxCouponValue"],"mappings":"+RAmJA,IAA8BA,CAA9B,CAAA,cAAiEC,CAAU,CAC/D,GACA,UACA,CAAA,aAAA,CACA,WACA,CAAA,SAAA,CACA,QACA,eACA,CAAA,eAAA,CACA,cAGA,CAAA,OAAA,CAGA,MAEA,OACA,CAAA,QAAA,CACA,MACVC,CAAAA,EAAAA,CAQA,WAAYC,CAAAA,CAAAA,CAAuCC,GAAa,CAAA,IAAI,KAAQC,GAAsC,CAAA,CAAE,iBAAmB,CAAA,CAAA,CAAK,EAAG,CAC7I,KAAA,CAAMF,CAAMC,CAAAA,GAAI,EAChB,IAAK,CAAA,EAAA,CAAKD,CAAK,CAAA,EAAA,CACf,IAAK,CAAA,UAAA,CAAaA,CAAK,CAAA,UAAA,CACvB,KAAK,aAAgBA,CAAAA,CAAAA,CAAK,aAC1B,CAAA,IAAA,CAAK,YAAcA,CAAK,CAAA,WAAA,CACxB,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IuB,CAAM,CAAA,cAAc,CACpMI,CAAAA,CAAAA,CAAY,WAAc,CAAA,CAAA,GAC5B,IAAK,CAAA,OAAA,CAAQ,KAAKgE,CAAe,CAAA,CACjC,IAAK,CAAA,KAAA,CAAM,cAAgB,IAAK,CAAA,KAAA,CAAM,aAAc,CAAA,GAAA,CAAIhE,CAAW,CACnE,CAAA,IAAA,CAAK,KAAM,CAAA,iBAAA,CAAkBgE,EAAgB,OAAQ,EAAC,CAAIhE,CAAAA,CAAAA,EAE9D,CACF,CAEF","file":"chunk-LE4HS2A6.mjs","sourcesContent":["import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport AddressModel, { AddressData } from \"./Address\";\r\nimport LineItemModel, { LineItemData, LineItemTaxBreakdown, LineItemTaxBreakdownModel } from \"./LineItem\";\r\nimport { CountryCode, CurrencyCode, LocaleCode, ShippingDetails } from \"./Common\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport CouponModel, { CouponCategory, CouponData, CouponType } from \"./Coupon\";\r\nimport Utils from \"../Utils\";\r\nimport { ChargeImpact, ChargeType, LineItemState, TaxSystem } from \"./Enum\";\r\nimport ChargeModel, { ChargeData, ChargeTaxBreakdownModel } from \"./Charge\";\r\n\r\n/**\r\n * Breakdown of a specific tax system (e.g., GST, VAT) for the entire container.\r\n * Groups taxes by system and then by specific rule/subsystem.\r\n */\r\nexport type TaxSystemBreakdown = {\r\n /** Name of the tax system (e.g., GST) */\r\n system: TaxSystem;\r\n /** Total tax amount collected for this system across all line items and charges */\r\n totalAmount: PriceData;\r\n /** Detailed breakdown by rule/subsystem to total tax amount (e.g., CGST, SGST) */\r\n subSystems: Record<string, PriceData>;\r\n};\r\n\r\n/**\r\n * Internal model for tax system breakdown using PriceModel instances.\r\n */\r\nexport type TaxSystemBreakdownModel = {\r\n system: TaxSystem;\r\n totalAmount: PriceModel;\r\n subSystems: Record<string, PriceModel>;\r\n};\r\n\r\nexport type ShoppingContainerTaxBreakdownModel = Record<string, TaxSystemBreakdownModel>;\r\n\r\n/**\r\n * Comprehensive totals for a shopping container, logically grouped by source.\r\n */\r\nexport type ShoppingContainerTotal = {\r\n // --- Item Totals ---\r\n /** Total tax collected specifically from line items */\r\n lineItemTaxTotal: PriceData;\r\n /** Granular tax breakdown for all line items */\r\n lineItemTaxBreakdown: Record<string, TaxSystemBreakdown>;\r\n\r\n // --- Charge Totals ---\r\n /** Tax reverse-calculated from additive charges only */\r\n additiveChargesTaxTotal: PriceData;\r\n /** Granular tax breakdown from additive charges */\r\n additiveChargesTaxBreakdown: Record<string, TaxSystemBreakdown>;\r\n\r\n /** Sum of post-discount netChargeAmount for subtractive charges – absolute amount to subtract */\r\n adjustmentCharges: PriceData;\r\n\r\n // --- Aggregate Totals ---\r\n /** Combined total tax (lineItemTaxTotal + chargeTaxTotal) */\r\n taxTotal: PriceData;\r\n /** Combined granular tax breakdown for the entire container */\r\n taxBreakdown: Record<string, TaxSystemBreakdown>;\r\n /** Sum of all coupon discounts applied to the container */\r\n discountTotal: PriceData;\r\n /** Map of applied coupon codes to their calculated discount amounts */\r\n discountBreakdown: Record<string, PriceData>;\r\n\r\n taxExclusive: {\r\n lineItemSubtotal: PriceData;\r\n netLineItemSubtotal: PriceData;\r\n additiveCharges: PriceData;\r\n netAdditiveCharges: PriceData;\r\n shippingCharges: PriceData;\r\n netShippingCharges: PriceData;\r\n };\r\n taxInclusive: {\r\n lineItemSubtotal: PriceData;\r\n netLineItemSubtotal: PriceData;\r\n additiveCharges: PriceData;\r\n netAdditiveCharges: PriceData;\r\n shippingCharges: PriceData;\r\n netShippingCharges: PriceData;\r\n };\r\n grandTotal: PriceData;\r\n};\r\n\r\n\r\n/**\r\n * Internal model version of ShoppingContainerTotal using PriceModel instances.\r\n */\r\nexport type ShoppingContainerTotalModel = {\r\n lineItemTaxTotal: PriceModel;\r\n lineItemTaxBreakdown: Record<string, TaxSystemBreakdownModel>;\r\n\r\n additiveChargesTaxTotal: PriceModel;\r\n additiveChargesTaxBreakdown: Record<string, TaxSystemBreakdownModel>;\r\n\r\n adjustmentCharges: PriceModel;\r\n\r\n taxTotal: PriceModel;\r\n taxBreakdown: Record<string, TaxSystemBreakdownModel>;\r\n discountTotal: PriceModel;\r\n discountBreakdown: Record<string, PriceModel>;\r\n\r\n taxExclusive: {\r\n lineItemSubtotal: PriceModel;\r\n netLineItemSubtotal: PriceModel;\r\n additiveCharges: PriceModel;\r\n netAdditiveCharges: PriceModel;\r\n shippingCharges: PriceModel;\r\n netShippingCharges: PriceModel;\r\n };\r\n taxInclusive: {\r\n lineItemSubtotal: PriceModel;\r\n netLineItemSubtotal: PriceModel;\r\n additiveCharges: PriceModel;\r\n netAdditiveCharges: PriceModel;\r\n shippingCharges: PriceModel;\r\n netShippingCharges: PriceModel;\r\n };\r\n grandTotal: PriceModel;\r\n};\r\n\r\nexport type ShoppingContainerMetaData = {\r\n checkCouponExpiry: boolean\r\n}\r\n\r\nexport type BaseShoppingContainerAttributes = BaseAttributes & {\r\n id: string;\r\n customerId?: string;\r\n customerEmail?: string;\r\n anonymousId?: string;\r\n lineItems: LineItemData[];\r\n charges: ChargeData[];\r\n shippingDetails: ShippingDetails | null;\r\n shippingAddress?: AddressData | null;\r\n billingAddress?: AddressData | null;\r\n coupons: CouponData[];\r\n total: ShoppingContainerTotal;\r\n country: CountryCode;\r\n currency: CurrencyCode;\r\n locale: LocaleCode;\r\n};\r\n\r\nexport type BaseShoppingContainerData = BaseShoppingContainerAttributes & BaseData\r\n\r\n\r\n/**\r\n * Abstract base class for shopping-related containers like carts and orders.\r\n * Manages common elements such as line items, addresses, coupons, and totals.\r\n */\r\nexport default abstract class BaseShoppingContainerModel extends BaseModel {\r\n protected id: string;\r\n protected customerId?: string;\r\n protected customerEmail?: string;\r\n protected anonymousId?: string;\r\n protected lineItems: LineItemModel[];\r\n protected charges: ChargeModel[];\r\n protected shippingDetails: ShippingDetails | null;\r\n protected shippingAddress: AddressModel | null;\r\n protected billingAddress: AddressModel | null;\r\n\r\n // CouponsCodes\r\n protected coupons: CouponModel[];\r\n\r\n // Cart Totals\r\n protected total: ShoppingContainerTotalModel;\r\n\r\n protected country: CountryCode;\r\n protected currency: CurrencyCode;\r\n protected locale: LocaleCode;\r\n #metaData: ShoppingContainerMetaData;\r\n\r\n /**\r\n * Creates an instance of BaseShoppingContainerModel.\r\n * Initializes common properties and calculates initial base totals.\r\n * @param data - The initial attributes for the shopping container.\r\n * @param date - Optional date object for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: BaseShoppingContainerAttributes, date: Date = new Date(), metaData: ShoppingContainerMetaData = { checkCouponExpiry: true }) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.customerId = data.customerId;\r\n this.customerEmail = data.customerEmail;\r\n this.anonymousId = data.anonymousId;\r\n this.country = data.country;\r\n this.currency = data.currency;\r\n this.locale = data.locale;\r\n this.lineItems = (data.lineItems ?? []).map(item => new LineItemModel(item));\r\n this.charges = (data.charges ?? []).map(charge => new ChargeModel(charge));\r\n this.billingAddress = data.billingAddress ? new AddressModel(data.billingAddress, date) : null;\r\n this.shippingAddress = data.shippingAddress ? new AddressModel(data.shippingAddress, date) : null;\r\n this.coupons = (data.coupons ?? []).map(coupon => new CouponModel(coupon));\r\n\r\n this.shippingDetails = data.shippingDetails ? Utils.deepClone(data.shippingDetails) : null;\r\n\r\n this.total = {\r\n lineItemTaxTotal: new PriceModel(data.total.lineItemTaxTotal),\r\n lineItemTaxBreakdown: this.mapTaxBreakdown(data.total.lineItemTaxBreakdown),\r\n\r\n additiveChargesTaxTotal: new PriceModel(data.total.additiveChargesTaxTotal),\r\n additiveChargesTaxBreakdown: this.mapTaxBreakdown(data.total.additiveChargesTaxBreakdown),\r\n adjustmentCharges: new PriceModel(data.total.adjustmentCharges),\r\n\r\n discountTotal: new PriceModel(data.total.discountTotal),\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(data.total.discountBreakdown).map(([key, value]) => [key, new PriceModel(value)])\r\n ),\r\n\r\n taxTotal: new PriceModel(data.total.taxTotal),\r\n taxBreakdown: this.mapTaxBreakdown(data.total.taxBreakdown),\r\n\r\n taxExclusive: {\r\n lineItemSubtotal: new PriceModel(data.total.taxExclusive.lineItemSubtotal),\r\n netLineItemSubtotal: new PriceModel(data.total.taxExclusive.netLineItemSubtotal),\r\n additiveCharges: new PriceModel(data.total.taxExclusive.additiveCharges),\r\n netAdditiveCharges: new PriceModel(data.total.taxExclusive.netAdditiveCharges),\r\n shippingCharges: new PriceModel(data.total.taxExclusive.shippingCharges),\r\n netShippingCharges: new PriceModel(data.total.taxExclusive.netShippingCharges),\r\n },\r\n taxInclusive: {\r\n lineItemSubtotal: new PriceModel(data.total.taxInclusive.lineItemSubtotal),\r\n netLineItemSubtotal: new PriceModel(data.total.taxInclusive.netLineItemSubtotal),\r\n additiveCharges: new PriceModel(data.total.taxInclusive.additiveCharges),\r\n netAdditiveCharges: new PriceModel(data.total.taxInclusive.netAdditiveCharges),\r\n shippingCharges: new PriceModel(data.total.taxInclusive.shippingCharges),\r\n netShippingCharges: new PriceModel(data.total.taxInclusive.netShippingCharges),\r\n },\r\n grandTotal: new PriceModel(data.total.grandTotal),\r\n };\r\n\r\n this.#metaData = {\r\n checkCouponExpiry: metaData.checkCouponExpiry\r\n }\r\n }\r\n\r\n private mapTaxBreakdown(breakdown: Record<string, TaxSystemBreakdown>): Record<string, TaxSystemBreakdownModel> {\r\n return Object.fromEntries(\r\n Object.entries(breakdown || {}).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: new PriceModel(systemValue.totalAmount),\r\n subSystems: Object.fromEntries(\r\n Object.entries(systemValue.subSystems).map(([subKey, subValue]) => [\r\n subKey,\r\n new PriceModel(subValue)\r\n ])\r\n )\r\n }\r\n ])\r\n );\r\n }\r\n\r\n private serializeTaxBreakdown(breakdown: Record<string, TaxSystemBreakdownModel>): Record<string, TaxSystemBreakdown> {\r\n return Object.fromEntries(\r\n Object.entries(breakdown || {}).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount.getDetails(),\r\n subSystems: Object.fromEntries(\r\n Object.entries(systemValue.subSystems).map(([subKey, subValue]) => [\r\n subKey,\r\n subValue.getDetails()\r\n ])\r\n )\r\n }\r\n ])\r\n );\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for this shopping container (cart ID or order ID).\r\n * @returns The ID string.\r\n */\r\n public getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the customer ID associated with this container, if available.\r\n * @returns The customer ID string, or undefined.\r\n */\r\n public getCustomerId(): string | undefined {\r\n return this.customerId;\r\n }\r\n\r\n /**\r\n * Gets the customer email associated with this container, if available.\r\n * @returns The customer email string, or undefined.\r\n */\r\n public getCustomerEmail(): string | undefined {\r\n return this.customerEmail;\r\n }\r\n\r\n /**\r\n * Gets the anonymous user ID associated with this container, if available.\r\n * @returns The anonymous ID string, or undefined.\r\n */\r\n public getAnonymousId(): string | undefined {\r\n return this.anonymousId;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the line items in the container.\r\n * Each item is a new LineItemModel instance created from the original's details.\r\n * @returns An array of LineItemModel instances.\r\n */\r\n public getLineItems(): LineItemModel[] {\r\n // Return new instances to prevent modification of internal state\r\n return this.lineItems.map(item => new LineItemModel(item.getDetails()));\r\n }\r\n\r\n /**\r\n * Gets current number of line items in the container.\r\n * @returns The count of line items.\r\n */\r\n public getLineItemsCount(): number {\r\n return this.lineItems.length;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the charges in the container.\r\n * @returns An array of ChargeModel instances.\r\n */\r\n public getCharges(): ChargeModel[] {\r\n return this.charges.map(charge => new ChargeModel(charge.getDetails()));\r\n }\r\n\r\n /**\r\n * Adds a new charge to the container and recalculates totals.\r\n * @param charge - The charge to add.\r\n */\r\n public addCharge(charge: ChargeModel): void {\r\n this.charges.push(charge);\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Clears all charges from the container and recalculates totals.\r\n */\r\n public clearCharges(): void {\r\n this.charges = [];\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Gets a copy of the shipping details associated with the container.\r\n * @returns A ShippingDetails object, or null if none are set.\r\n */\r\n public getShippingDetails(): ShippingDetails | null {\r\n return this.shippingDetails ? Utils.deepClone(this.shippingDetails) : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the shipping address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no shipping address is set.\r\n */\r\n public getShippingAddress(): AddressModel | null {\r\n return this.shippingAddress ? new AddressModel(this.shippingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Checks if a shipping address is associated with this container.\r\n * @returns True if a shipping address is set, false otherwise.\r\n */\r\n public hasShippingAddress(): boolean {\r\n return !!this.shippingAddress;\r\n }\r\n\r\n /**\r\n * Checks if a billing address is associated with this container.\r\n * @returns True if a billing address is set, false otherwise.\r\n */\r\n public hasBillingAddress(): boolean {\r\n return !!this.billingAddress;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the billing address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no billing address is set.\r\n */\r\n public getBillingAddress(): AddressModel | null {\r\n return this.billingAddress ? new AddressModel(this.billingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the coupons applied to the container.\r\n * Each item is a new CouponModel instance created from the original's details.\r\n * @returns An array of CouponModel instances.\r\n */\r\n public getCoupons(): CouponModel[] {\r\n return [...this.coupons];\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this container.\r\n * @returns The CountryCode enum value.\r\n */\r\n public getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Gets the currency code associated with this container.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Gets the locale code associated with this container.\r\n * @returns The LocaleCode enum value.\r\n */\r\n public getLocale(): LocaleCode {\r\n return this.locale;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the calculated totals for the container.\r\n * @returns An object containing shipping, subtotal, coupon, and grand totals.\r\n */\r\n public getTotal() {\r\n return {\r\n lineItemTaxTotal: this.total.lineItemTaxTotal,\r\n lineItemTaxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.lineItemTaxBreakdown).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount,\r\n subSystems: { ...systemValue.subSystems }\r\n }\r\n ])\r\n ),\r\n additiveChargesTaxTotal: this.total.additiveChargesTaxTotal,\r\n additiveChargesTaxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.additiveChargesTaxBreakdown).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount,\r\n subSystems: { ...systemValue.subSystems }\r\n }\r\n ])\r\n ),\r\n adjustmentCharges: this.total.adjustmentCharges,\r\n discountBreakdown: { ...this.total.discountBreakdown },\r\n discountTotal: this.total.discountTotal,\r\n taxTotal: this.total.taxTotal,\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.taxBreakdown).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount,\r\n subSystems: { ...systemValue.subSystems }\r\n }\r\n ])\r\n ),\r\n taxExclusive: {\r\n lineItemSubtotal: this.total.taxExclusive.lineItemSubtotal,\r\n netLineItemSubtotal: this.total.taxExclusive.netLineItemSubtotal,\r\n additiveCharges: this.total.taxExclusive.additiveCharges,\r\n netAdditiveCharges: this.total.taxExclusive.netAdditiveCharges,\r\n shippingCharges: this.total.taxExclusive.shippingCharges,\r\n netShippingCharges: this.total.taxExclusive.netShippingCharges,\r\n },\r\n taxInclusive: {\r\n lineItemSubtotal: this.total.taxInclusive.lineItemSubtotal,\r\n netLineItemSubtotal: this.total.taxInclusive.netLineItemSubtotal,\r\n additiveCharges: this.total.taxInclusive.additiveCharges,\r\n netAdditiveCharges: this.total.taxInclusive.netAdditiveCharges,\r\n shippingCharges: this.total.taxInclusive.shippingCharges,\r\n netShippingCharges: this.total.taxInclusive.netShippingCharges,\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 shopping container's current state.\r\n * Includes details from the base model and specific container properties.\r\n * @returns BaseShoppingContainerData object suitable for serialization or API responses.\r\n */\r\n getDetails(): BaseShoppingContainerData {\r\n const totals = this.getTotal();\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n customerId: this.getCustomerId(),\r\n customerEmail: this.getCustomerEmail(),\r\n anonymousId: this.getAnonymousId(),\r\n lineItems: this.getLineItems().map(item => item.getDetails()),\r\n charges: this.getCharges().map(charge => charge.getDetails()),\r\n shippingDetails: this.getShippingDetails(),\r\n shippingAddress: this.getShippingAddress()?.getDetails() || null,\r\n billingAddress: this.getBillingAddress()?.getDetails() || null,\r\n coupons: this.getCoupons().map(coupon => coupon.getDetails()),\r\n total: {\r\n // Item Totals\r\n lineItemTaxTotal: totals.lineItemTaxTotal.getDetails(),\r\n lineItemTaxBreakdown: this.serializeTaxBreakdown(totals.lineItemTaxBreakdown),\r\n\r\n // Charge Totals\r\n additiveChargesTaxTotal: totals.additiveChargesTaxTotal.getDetails(),\r\n additiveChargesTaxBreakdown: this.serializeTaxBreakdown(totals.additiveChargesTaxBreakdown),\r\n\r\n adjustmentCharges: totals.adjustmentCharges.getDetails(),\r\n\r\n // Aggregate Totals\r\n discountTotal: totals.discountTotal.getDetails(),\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(totals.discountBreakdown).map(([key, value]) => [key, value.getDetails()])\r\n ),\r\n taxTotal: totals.taxTotal.getDetails(),\r\n taxBreakdown: this.serializeTaxBreakdown(totals.taxBreakdown),\r\n\r\n taxExclusive: {\r\n lineItemSubtotal: totals.taxExclusive.lineItemSubtotal.getDetails(),\r\n netLineItemSubtotal: totals.taxExclusive.netLineItemSubtotal.getDetails(),\r\n additiveCharges: totals.taxExclusive.additiveCharges.getDetails(),\r\n netAdditiveCharges: totals.taxExclusive.netAdditiveCharges.getDetails(),\r\n shippingCharges: totals.taxExclusive.shippingCharges.getDetails(),\r\n netShippingCharges: totals.taxExclusive.netShippingCharges.getDetails(),\r\n },\r\n taxInclusive: {\r\n lineItemSubtotal: totals.taxInclusive.lineItemSubtotal.getDetails(),\r\n netLineItemSubtotal: totals.taxInclusive.netLineItemSubtotal.getDetails(),\r\n additiveCharges: totals.taxInclusive.additiveCharges.getDetails(),\r\n netAdditiveCharges: totals.taxInclusive.netAdditiveCharges.getDetails(),\r\n shippingCharges: totals.taxInclusive.shippingCharges.getDetails(),\r\n netShippingCharges: totals.taxInclusive.netShippingCharges.getDetails(),\r\n },\r\n grandTotal: totals.grandTotal.getDetails(),\r\n },\r\n country: this.getCountry(),\r\n currency: this.getCurrency(),\r\n locale: this.getLocale(),\r\n };\r\n }\r\n\r\n /**\r\n * Recalculates the total costs for the shopping container.\r\n * This orchestrates computing base totals, applying active coupons, and aggregating the final net results.\r\n */\r\n public calculateTotals(): void {\r\n const zero = new PriceModel({ amount: 0, currency: this.currency });\r\n\r\n // Step 1: Initialize baseline totals for all active items and charges.\r\n // We clear any existing discounts so we can evaluate base subtotals accurately.\r\n this.lineItems.forEach(li => {\r\n if (li.getState() !== LineItemState.CANCELLED) li.updateDiscounts([]);\r\n });\r\n this.charges.forEach(charge => charge.updateDiscounts([]));\r\n\r\n // Step 2: Evaluate Non-Shipping Coupons on gross subtotals\r\n const bases = this.getCouponEvaluationBases();\r\n let discountTotal = zero;\r\n let discountBreakdown: Record<string, PriceModel> = {};\r\n let nonShippingCouponTotal: Record<string, PriceModel> = {};\r\n\r\n const nonShippingCoupons = this.coupons.filter(c => c.getCategory() !== CouponCategory.SHIPPING);\r\n nonShippingCoupons.forEach(coupon => {\r\n const couponValue = coupon.calculateApplicableCouponDiscount(bases.targetSubtotal, bases.targetShipping, this.country, this.currency, this.#metaData.checkCouponExpiry);\r\n discountTotal = discountTotal.add(couponValue);\r\n discountBreakdown[coupon.getCode()] = couponValue;\r\n nonShippingCouponTotal[coupon.getCode()] = couponValue;\r\n });\r\n\r\n // Step 3: Distribute Non-Shipping Coupons\r\n // This internally recalculates the net subtotals and taxes for line items.\r\n this.applyDiscountsInLineItem(nonShippingCouponTotal);\r\n\r\n // Step 4: Evaluate Shipping Coupons using dynamically updated Net Subtotals\r\n const updatedBases = this.getCouponEvaluationBases();\r\n let shippingCouponTotal: Record<string, PriceModel> = {};\r\n \r\n const shippingCoupons = this.coupons.filter(c => c.getCategory() === CouponCategory.SHIPPING);\r\n shippingCoupons.forEach(coupon => {\r\n const couponValue = coupon.calculateApplicableCouponDiscount(updatedBases.targetNetSubtotal, updatedBases.targetShipping, this.country, this.currency, this.#metaData.checkCouponExpiry).min(updatedBases.targetShipping);\r\n discountTotal = discountTotal.add(couponValue);\r\n discountBreakdown[coupon.getCode()] = couponValue;\r\n shippingCouponTotal[coupon.getCode()] = couponValue;\r\n });\r\n\r\n // Step 5: Distribute Shipping Coupons\r\n this.applyDiscountsInShippingCharges(shippingCouponTotal);\r\n\r\n // Step 6: Aggregate everything into `this.total`\r\n let lineItemTaxTotal = zero;\r\n let additiveChargesTaxTotal = zero;\r\n\r\n let lineItemSubtotalExcl = zero;\r\n let netLineItemSubtotalExcl = zero;\r\n let lineItemSubtotalIncl = zero;\r\n let netLineItemSubtotalIncl = zero;\r\n\r\n const taxBreakdown: ShoppingContainerTaxBreakdownModel = {};\r\n const lineItemTaxBreakdown: ShoppingContainerTaxBreakdownModel = {};\r\n const additiveChargesTaxBreakdown: ShoppingContainerTaxBreakdownModel = {};\r\n\r\n const mergeTax = (source: Record<string, LineItemTaxBreakdownModel | ChargeTaxBreakdownModel>, target: ShoppingContainerTaxBreakdownModel) => {\r\n Object.entries(source).forEach(([_, breakdown]) => {\r\n const { system, subSystem, taxAmount } = breakdown;\r\n if (!target[system]) target[system] = { system, totalAmount: zero, subSystems: {} };\r\n if (!target[system].subSystems[subSystem]) target[system].subSystems[subSystem] = taxAmount;\r\n else target[system].subSystems[subSystem] = target[system].subSystems[subSystem].add(taxAmount);\r\n target[system].totalAmount = target[system].totalAmount.add(taxAmount);\r\n });\r\n };\r\n\r\n const filteredLineItems = this.lineItems.filter(li => li.getState() !== LineItemState.CANCELLED);\r\n filteredLineItems.forEach(li => {\r\n const t = li.getTotal();\r\n lineItemSubtotalExcl = lineItemSubtotalExcl.add(t.taxExclusive.subtotal);\r\n netLineItemSubtotalExcl = netLineItemSubtotalExcl.add(t.taxExclusive.netSubtotal);\r\n lineItemSubtotalIncl = lineItemSubtotalIncl.add(t.taxInclusive.subtotal);\r\n netLineItemSubtotalIncl = netLineItemSubtotalIncl.add(t.taxInclusive.netSubtotal);\r\n\r\n if (t.taxBreakdown) {\r\n mergeTax(t.taxBreakdown, lineItemTaxBreakdown);\r\n mergeTax(t.taxBreakdown, taxBreakdown);\r\n lineItemTaxTotal = lineItemTaxTotal.add(t.taxTotal);\r\n }\r\n });\r\n\r\n let additiveChargesExcl = zero;\r\n let netAdditiveChargesExcl = zero;\r\n let additiveChargesIncl = zero;\r\n let netAdditiveChargesIncl = zero;\r\n\r\n let shippingChargesExcl = zero;\r\n let netShippingChargesExcl = zero;\r\n let shippingChargesIncl = zero;\r\n let netShippingChargesIncl = zero;\r\n\r\n let adjustmentChargesIncl = zero;\r\n\r\n this.charges.forEach(charge => {\r\n const t = charge.getTotal();\r\n if (charge.getImpact() === ChargeImpact.ADD) {\r\n additiveChargesExcl = additiveChargesExcl.add(t.taxExclusive.chargeAmount);\r\n netAdditiveChargesExcl = netAdditiveChargesExcl.add(t.taxExclusive.netChargeAmount);\r\n additiveChargesIncl = additiveChargesIncl.add(t.taxInclusive.chargeAmount);\r\n netAdditiveChargesIncl = netAdditiveChargesIncl.add(t.grandTotal);\r\n\r\n if (charge.getType() === ChargeType.SHIPPING) {\r\n shippingChargesExcl = shippingChargesExcl.add(t.taxExclusive.chargeAmount);\r\n netShippingChargesExcl = netShippingChargesExcl.add(t.taxExclusive.netChargeAmount);\r\n shippingChargesIncl = shippingChargesIncl.add(t.taxInclusive.chargeAmount);\r\n netShippingChargesIncl = netShippingChargesIncl.add(t.grandTotal);\r\n }\r\n\r\n if (t.taxBreakdown) {\r\n mergeTax(t.taxBreakdown, additiveChargesTaxBreakdown);\r\n mergeTax(t.taxBreakdown, taxBreakdown);\r\n additiveChargesTaxTotal = additiveChargesTaxTotal.add(t.taxTotal);\r\n }\r\n } else if (charge.getImpact() === ChargeImpact.SUBTRACT) {\r\n adjustmentChargesIncl = adjustmentChargesIncl.add(t.grandTotal);\r\n }\r\n });\r\n\r\n const taxTotal = lineItemTaxTotal.add(additiveChargesTaxTotal);\r\n const grandTotal = netLineItemSubtotalIncl.add(netAdditiveChargesIncl).subtract(adjustmentChargesIncl);\r\n\r\n this.total = {\r\n lineItemTaxTotal,\r\n lineItemTaxBreakdown,\r\n additiveChargesTaxTotal,\r\n additiveChargesTaxBreakdown,\r\n adjustmentCharges: adjustmentChargesIncl,\r\n discountTotal,\r\n discountBreakdown,\r\n taxTotal,\r\n taxBreakdown,\r\n taxExclusive: {\r\n lineItemSubtotal: lineItemSubtotalExcl,\r\n netLineItemSubtotal: netLineItemSubtotalExcl,\r\n additiveCharges: additiveChargesExcl,\r\n netAdditiveCharges: netAdditiveChargesExcl,\r\n shippingCharges: shippingChargesExcl,\r\n netShippingCharges: netShippingChargesExcl,\r\n },\r\n taxInclusive: {\r\n lineItemSubtotal: lineItemSubtotalIncl,\r\n netLineItemSubtotal: netLineItemSubtotalIncl,\r\n additiveCharges: additiveChargesIncl,\r\n netAdditiveCharges: netAdditiveChargesIncl,\r\n shippingCharges: shippingChargesIncl,\r\n netShippingCharges: netShippingChargesIncl,\r\n },\r\n grandTotal,\r\n };\r\n }\r\n\r\n /**\r\n * Updates the shipping details and recalculates the totals.\r\n * @param shippingDetails - The new shipping details to apply.\r\n */\r\n public updateShippingDetails(shippingDetails: ShippingDetails): void {\r\n this.shippingDetails = shippingDetails;\r\n }\r\n\r\n /**\r\n * Applies a list of coupons to the shopping container.\r\n * Filters out invalid coupons, separates shipping and non-shipping coupons,\r\n * and distributes discounts to line items.\r\n * @param applicableCoupons - The list of coupons to attempt to apply.\r\n */\r\n public applyCoupons(applicableCoupons: CouponModel[]): void {\r\n //Apply coupons\r\n const shippingCoupons = applicableCoupons.filter(coupon => coupon.getCategory() === CouponCategory.SHIPPING);\r\n const otherCoupons = applicableCoupons.filter(coupon => coupon.getCategory() !== CouponCategory.SHIPPING);\r\n\r\n this.coupons = [];\r\n this.total.discountTotal = this.total.discountTotal.zero();\r\n this.total.discountBreakdown = {};\r\n // Apply non shipping coupons\r\n otherCoupons.length && this.applyNonShippingCoupons(otherCoupons);\r\n this.applyDiscountsInLineItem(this.total.discountBreakdown);\r\n\r\n // Apply shipping coupons\r\n shippingCoupons.length && this.applyShippingCoupons(shippingCoupons);\r\n\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Distributes the total discount amount among the line items.\r\n * @param couponTotal - A record of coupon codes and their calculated discount amounts.\r\n */\r\n private applyDiscountsInLineItem(couponTotal: Record<string, PriceModel>) {\r\n const couponDiscounts: [string, PriceModel][] = Array.from(Object.entries(couponTotal))\r\n .filter(couponDiscount => !couponDiscount[1].isZero());\r\n\r\n const itemDiscounts = new Map<string, { coupon: CouponModel, amount: PriceModel }[]>();\r\n this.lineItems.forEach(li => itemDiscounts.set(li.getId(), []));\r\n\r\n couponDiscounts.forEach(([code, discountTotal]) => {\r\n const coupon = this.coupons.find(c => c.getCode() === code);\r\n if (!coupon || discountTotal.isZero()) return;\r\n\r\n const targetSubtotal = this.lineItems.reduce(\r\n (total, lineItem) => total.add(lineItem.getIsTaxInclusive() ? lineItem.getTotal().taxInclusive.subtotal : lineItem.getTotal().taxExclusive.subtotal),\r\n new PriceModel({ amount: 0, currency: this.currency })\r\n );\r\n\r\n const validItems = this.lineItems\r\n .filter(li => li.getState() !== LineItemState.CANCELLED && !li.getTotal().taxExclusive.subtotal.isZero())\r\n .sort((a, b) => {\r\n const aVal = a.getIsTaxInclusive() ? a.getTotal().taxInclusive.subtotal : a.getTotal().taxExclusive.subtotal;\r\n const bVal = b.getIsTaxInclusive() ? b.getTotal().taxInclusive.subtotal : b.getTotal().taxExclusive.subtotal;\r\n return aVal.compareTo(bVal);\r\n });\r\n\r\n let distributed = new PriceModel({ amount: 0, currency: this.currency });\r\n\r\n validItems.forEach((item, index) => {\r\n let amount: PriceModel;\r\n const itemVal = item.getIsTaxInclusive() ? item.getTotal().taxInclusive.subtotal : item.getTotal().taxExclusive.subtotal;\r\n if (index === validItems.length - 1) {\r\n amount = discountTotal.subtract(distributed);\r\n } else {\r\n amount = discountTotal.multiply(itemVal).divide(targetSubtotal).round();\r\n }\r\n distributed = distributed.add(amount);\r\n itemDiscounts.get(item.getId())?.push({ coupon, amount });\r\n });\r\n });\r\n\r\n this.lineItems.forEach(lineItem => {\r\n lineItem.updateDiscounts(itemDiscounts.get(lineItem.getId())!);\r\n });\r\n }\r\n\r\n private applyDiscountsInShippingCharges(couponTotal: Record<string, PriceModel>) {\r\n const couponDiscounts: [string, PriceModel][] = Array.from(Object.entries(couponTotal))\r\n .filter(couponDiscount => !couponDiscount[1].isZero());\r\n const shippingCharges = this.charges.filter(charge => charge.getType() === ChargeType.SHIPPING);\r\n\r\n const chargeDiscounts = new Map<string, { coupon: CouponModel, amount: PriceModel }[]>();\r\n shippingCharges.forEach(li => chargeDiscounts.set(li.getId(), []));\r\n\r\n couponDiscounts.forEach(([code, discountTotal]) => {\r\n const coupon = this.coupons.find(c => c.getCode() === code);\r\n if (!coupon || discountTotal.isZero()) return;\r\n\r\n const targetShipping = shippingCharges.reduce(\r\n (total, charge) => total.add(charge.getIsTaxInclusive() ? charge.getTotal().taxInclusive.chargeAmount : charge.getTotal().taxExclusive.chargeAmount),\r\n new PriceModel({ amount: 0, currency: this.currency })\r\n );\r\n\r\n const validCharges = shippingCharges\r\n .filter(charge => !charge.getTotal().taxExclusive.chargeAmount.isZero())\r\n .sort((a, b) => {\r\n const aVal = a.getIsTaxInclusive() ? a.getTotal().taxInclusive.chargeAmount : a.getTotal().taxExclusive.chargeAmount;\r\n const bVal = b.getIsTaxInclusive() ? b.getTotal().taxInclusive.chargeAmount : b.getTotal().taxExclusive.chargeAmount;\r\n return aVal.compareTo(bVal);\r\n });\r\n\r\n let distributed = new PriceModel({ amount: 0, currency: this.currency });\r\n\r\n validCharges.forEach((charge, index) => {\r\n let amount: PriceModel;\r\n const chargeVal = charge.getIsTaxInclusive() ? charge.getTotal().taxInclusive.chargeAmount : charge.getTotal().taxExclusive.chargeAmount;\r\n if (index === validCharges.length - 1) {\r\n amount = discountTotal.subtract(distributed);\r\n } else {\r\n amount = discountTotal.multiply(chargeVal).divide(targetShipping).round();\r\n }\r\n distributed = distributed.add(amount);\r\n chargeDiscounts.get(charge.getId())?.push({ coupon, amount });\r\n });\r\n });\r\n\r\n shippingCharges.forEach(charge => {\r\n charge.updateDiscounts(chargeDiscounts.get(charge.getId())!);\r\n });\r\n }\r\n\r\n /**\r\n * Helper to resolve the correct evaluation basis for line items and shipping charges.\r\n * If any item in a group is tax-inclusive, the inclusive total is used for the entire group.\r\n * Otherwise, the exclusive total is used.\r\n */\r\n private getCouponEvaluationBases() {\r\n const zero = new PriceModel({ amount: 0, currency: this.currency });\r\n const activeItems = this.lineItems.filter(li => li.getState() !== LineItemState.CANCELLED);\r\n const shippingCharges = this.charges.filter(charge => charge.getType() === ChargeType.SHIPPING);\r\n\r\n const isAnyItemInclusive = activeItems.some(li => li.getIsTaxInclusive());\r\n const targetSubtotal = activeItems.reduce(\r\n (total, li) => total.add(isAnyItemInclusive ? li.getTotal().taxInclusive.subtotal : li.getTotal().taxExclusive.subtotal),\r\n zero\r\n );\r\n\r\n const targetNetSubtotal = activeItems.reduce(\r\n (total, li) => total.add(isAnyItemInclusive ? li.getTotal().taxInclusive.netSubtotal : li.getTotal().taxExclusive.netSubtotal),\r\n zero\r\n );\r\n\r\n const isAnyShippingInclusive = shippingCharges.some(c => c.getIsTaxInclusive());\r\n const targetShipping = shippingCharges.reduce(\r\n (total, c) => total.add(isAnyShippingInclusive ? c.getTotal().taxInclusive.chargeAmount : c.getTotal().taxExclusive.chargeAmount),\r\n zero\r\n );\r\n\r\n return { targetSubtotal, targetShipping, targetNetSubtotal };\r\n }\r\n\r\n /**\r\n * Selects and applies the best applicable non-shipping coupon.\r\n * Currently supports applying only a single coupon of type COUPON.\r\n * @param applicableCoupons - List of available non-shipping coupons.\r\n */\r\n private applyNonShippingCoupons(applicableCoupons: CouponModel[]) {\r\n const coupons = applicableCoupons.filter(coupon => coupon.getType() === CouponType.COUPON);\r\n if (coupons.length === 1) {\r\n const bases = this.getCouponEvaluationBases();\r\n const couponValue = coupons[0].calculateApplicableCouponDiscount(bases.targetSubtotal, bases.targetShipping, this.country, this.currency, this.#metaData.checkCouponExpiry);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(coupons[0]);\r\n this.total.discountTotal = couponValue;\r\n this.total.discountBreakdown[coupons[0].getCode()] = couponValue;\r\n }\r\n }\r\n // Todo: Add support to other type in future like promotion\r\n }\r\n\r\n /**\r\n * Selects and applies the best applicable shipping coupon.\r\n * @param applicableCoupons - List of available shipping coupons.\r\n */\r\n private applyShippingCoupons(applicableCoupons: CouponModel[]) {\r\n const bases = this.getCouponEvaluationBases();\r\n if (bases.targetShipping.getAmount() > 0 && applicableCoupons.length > 0) {\r\n const netLineItemSubtotal = bases.targetNetSubtotal;\r\n\r\n const maxValuedCoupon = applicableCoupons.reduce((maxCoupon, currentCoupon) => {\r\n if (!maxCoupon) return currentCoupon;\r\n\r\n const currentCouponValue = currentCoupon.calculateApplicableCouponDiscount(netLineItemSubtotal, bases.targetShipping, this.country, this.currency, this.#metaData.checkCouponExpiry).min(bases.targetShipping);\r\n const maxCouponValue = maxCoupon.calculateApplicableCouponDiscount(netLineItemSubtotal, bases.targetShipping, this.country, this.currency, this.#metaData.checkCouponExpiry).min(bases.targetShipping);\r\n\r\n if (currentCouponValue.compareTo(maxCouponValue) === 0) {\r\n return currentCoupon.getType() === CouponType.COUPON ? currentCoupon : maxCoupon;\r\n }\r\n return currentCouponValue.compareTo(maxCouponValue) > 0 ? currentCoupon : maxCoupon;\r\n });\r\n\r\n const couponValue = maxValuedCoupon.calculateApplicableCouponDiscount(netLineItemSubtotal, bases.targetShipping, this.country, this.currency, this.#metaData.checkCouponExpiry).min(bases.targetShipping);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(maxValuedCoupon);\r\n this.total.discountTotal = this.total.discountTotal.add(couponValue);\r\n this.total.discountBreakdown[maxValuedCoupon.getCode()] = couponValue;\r\n }\r\n }\r\n }\r\n\r\n}\r\n\r\n\r\n"]}
@@ -0,0 +1,2 @@
1
+ import {a}from'./chunk-UIQH5QIR.mjs';var p=(e,u)=>{let i=u.reduce((s,n)=>s+n.getApplicableTaxRate(e),0);if(i<=0)return e;let a$1=e.divide(1+i).round().getAmount(),t=e.getCurrency(),c=e.getAmount(),r=a$1,o=Number.POSITIVE_INFINITY,l=1e4;for(let s=0;s<l;s++){let n=new a({amount:a$1,currency:t}),g=u.sort((d,x)=>x.getApplicableTaxRate(n)-d.getApplicableTaxRate(n)).map(d=>n.multiply(d.getApplicableTaxRate(n)).round().getAmount()).reduce((d,x)=>d+x,0),m=a$1+g-c,A=u.reduce((d,x)=>d+x.getApplicableTaxRate(n),0);if(Math.abs(m)<Math.abs(o)&&(o=m,r=a$1),m===0)break;a$1=a$1-m/(1+A);}if(Math.abs(o)>a.getSmallestUnit(t))throw new Error("Failed to converge on a valid tax exclusive base.");return new a({amount:r,currency:t})},M=(e,u,i)=>{let a=e.zero(),t=[...i].sort((c,r)=>r.getApplicableTaxRate(e)-c.getApplicableTaxRate(e));return t.map((c,r)=>{let o=c.getApplicableTaxRate(e),l;return r===t.length-1?l=u.subtract(e).subtract(a):l=e.multiply(o).round(),a=a.add(l),{ruleId:c.getTaxRuleId(),taxAmount:l,rate:o}})},y=(e,u,i)=>{let a=e.zero(),t=a,c=[];if(u){if(i.reduce((s,n)=>s+n.getApplicableTaxRate(e),0)<=0)return {entries:[],taxTotal:a,taxableBase:e};let o=p(e,i);return M(o,e,i).forEach(s=>{let n=i.find(T=>T.getTaxRuleId()===s.ruleId);c.push({ruleId:s.ruleId,rate:s.rate,taxableAmount:o,taxAmount:s.taxAmount,system:n.getTaxSystem(),subSystem:n.getTaxSubSystem()}),t=t.add(s.taxAmount);}),{entries:c,taxTotal:t,taxableBase:o}}else return i.forEach(r=>{let o=r.getApplicableTaxRate(e);if(o<=0)return;let l=r.calculateTax(e);c.push({ruleId:r.getTaxRuleId(),rate:o,taxableAmount:e,taxAmount:l,system:r.getTaxSystem(),subSystem:r.getTaxSubSystem()}),t=t.add(l);}),{entries:c,taxTotal:t,taxableBase:e}},I=(e,u,i,a)=>{let t=e.subtract(u),{entries:c,taxTotal:r,taxableBase:o}=y(t,i,a);if(i)return {taxExclusive:{baseAmount:p(e,a),netAmount:o,grandTotal:o},taxInclusive:{baseAmount:e,netAmount:t,grandTotal:t},taxTotal:r,taxBreakdown:c,discountTotal:u};{let l=e.zero();a.forEach(T=>{l=l.add(T.calculateTax(e));});let s=e.add(l),n=t.add(r);return {taxExclusive:{baseAmount:e,netAmount:t,grandTotal:t},taxInclusive:{baseAmount:s,netAmount:n,grandTotal:n},taxTotal:r,taxBreakdown:c,discountTotal:u}}};export{I as a};//# sourceMappingURL=chunk-MWDQACOC.mjs.map
2
+ //# sourceMappingURL=chunk-MWDQACOC.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/Utils/TaxMath.ts"],"names":["extractExclusiveBase","grossValue","applicableTaxRules","totalRate","sum","r","baseValue","currency","grossAmount","bestBaseValue","bestDiff","maxIterations","i","currentTaxableBase","PriceModel","taxSum","a","b","rule","v","diff","currentTotalRate","calculateDistributedTaxes","baseModel","grossModel","distributedTax","sortedRules","index","ruleRate","taxAmount","calculateTaxBreakdown","netAmount","isTaxInclusive","taxRules","zero","taxTotal","entries","taxableBase","dt","taxRule","rate","calculateDualViewTotals","discount","originalTax","grossAmountInclTax","netAmountInclTax"],"mappings":"qCAIO,IAAMA,CAAuB,CAAA,CAChCC,CACAC,CAAAA,CAAAA,GACa,CACb,IAAMC,CAAYD,CAAAA,CAAAA,CAAmB,MAAO,CAAA,CAACE,CAAKC,CAAAA,CAAAA,GAAMD,CAAMC,CAAAA,CAAAA,CAAE,oBAAqBJ,CAAAA,CAAU,CAAG,CAAA,CAAC,CAEnG,CAAA,GAAIE,CAAa,EAAA,CAAA,CACb,OAAOF,CAAAA,CAGX,IAAIK,GAAAA,CAAYL,CAAW,CAAA,MAAA,CAAO,EAAIE,CAAS,CAAA,CAAE,KAAM,EAAA,CAAE,SAAU,EAAA,CAC7DI,CAAWN,CAAAA,CAAAA,CAAW,WAAY,EAAA,CAClCO,CAAcP,CAAAA,CAAAA,CAAW,SAAU,EAAA,CAErCQ,CAAgBH,CAAAA,GAAAA,CAChBI,EAAW,MAAO,CAAA,iBAAA,CAChBC,CAAgB,CAAA,GAAA,CAEtB,IAASC,IAAAA,CAAAA,CAAI,CAAGA,CAAAA,CAAAA,CAAID,CAAeC,CAAAA,CAAAA,EAAAA,CAAK,CACpC,IAAMC,CAAqB,CAAA,IAAIC,CAAW,CAAA,CAAE,OAAQR,GAAW,CAAA,QAAA,CAAAC,CAAS,CAAC,CAKnEQ,CAAAA,CAAAA,CAJQb,CACT,CAAA,IAAA,CAAK,CAACc,CAAAA,CAAGC,CAAMA,GAAAA,CAAAA,CAAE,oBAAqBJ,CAAAA,CAAkB,CAAIG,CAAAA,CAAAA,CAAE,qBAAqBH,CAAkB,CAAC,CACtG,CAAA,GAAA,CAAIK,CAAQL,EAAAA,CAAAA,CAAmB,QAASK,CAAAA,CAAAA,CAAK,oBAAqBL,CAAAA,C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PriceModel from \"../Classes/Price\";\nimport { TaxSystem } from \"../Classes/Enum\";\nimport { TaxRuleModel } from \"../Classes/TaxRule\";\n\nexport const extractExclusiveBase = (\n grossValue: PriceModel,\n applicableTaxRules: TaxRuleModel[]\n): PriceModel => {\n const totalRate = applicableTaxRules.reduce((sum, r) => sum + r.getApplicableTaxRate(grossValue), 0);\n \n if (totalRate <= 0) {\n return grossValue;\n }\n \n let baseValue = grossValue.divide(1 + totalRate).round().getAmount();\n const currency = grossValue.getCurrency();\n const grossAmount = grossValue.getAmount();\n\n let bestBaseValue = baseValue;\n let bestDiff = Number.POSITIVE_INFINITY;\n const maxIterations = 10000;\n\n for (let i = 0; i < maxIterations; i++) {\n const currentTaxableBase = new PriceModel({ amount: baseValue, currency });\n const taxes = applicableTaxRules\n .sort((a, b) => b.getApplicableTaxRate(currentTaxableBase) - a.getApplicableTaxRate(currentTaxableBase))\n .map(rule => currentTaxableBase.multiply(rule.getApplicableTaxRate(currentTaxableBase)).round().getAmount());\n\n const taxSum = taxes.reduce((sum, v) => sum + v, 0);\n const diff = (baseValue + taxSum) - grossAmount;\n\n const currentTotalRate = applicableTaxRules.reduce((sum, r) => sum + r.getApplicableTaxRate(currentTaxableBase), 0);\n\n if (Math.abs(diff) < Math.abs(bestDiff)) {\n bestDiff = diff;\n bestBaseValue = baseValue;\n }\n\n if (diff === 0) break;\n baseValue = baseValue - diff / (1 + currentTotalRate);\n }\n\n if (Math.abs(bestDiff) > PriceModel.getSmallestUnit(currency)) {\n throw new Error(\"Failed to converge on a valid tax exclusive base.\");\n }\n\n return new PriceModel({ amount: bestBaseValue, currency });\n}\n\nexport const calculateDistributedTaxes = (\n baseModel: PriceModel,\n grossModel: PriceModel,\n applicableTaxRules: TaxRuleModel[]\n): { ruleId: string, taxAmount: PriceModel, rate: number }[] => {\n let distributedTax = baseModel.zero();\n \n const sortedRules = [...applicableTaxRules].sort(\n (a, b) => b.getApplicableTaxRate(baseModel) - a.getApplicableTaxRate(baseModel)\n );\n\n return sortedRules.map((rule, index) => {\n const ruleRate = rule.getApplicableTaxRate(baseModel);\n let taxAmount: PriceModel;\n \n if (index === sortedRules.length - 1) {\n taxAmount = grossModel.subtract(baseModel).subtract(distributedTax);\n } else {\n taxAmount = baseModel.multiply(ruleRate).round();\n }\n \n distributedTax = distributedTax.add(taxAmount);\n \n return {\n ruleId: rule.getTaxRuleId(),\n taxAmount,\n rate: ruleRate\n };\n });\n};\n\n// ─── Shared Tax Calculation Functions ─────────────────────────────\n\n/**\n * Represents a single tax rule's contribution to the total tax.\n */\nexport type TaxBreakdownEntry = {\n ruleId: string;\n rate: number;\n taxableAmount: PriceModel;\n taxAmount: PriceModel;\n system: TaxSystem;\n subSystem: string;\n};\n\n/**\n * Result of a tax breakdown calculation containing per-rule entries,\n * the aggregate tax total, and the exclusive taxable base.\n */\nexport type TaxBreakdownResult = {\n entries: TaxBreakdownEntry[];\n taxTotal: PriceModel;\n taxableBase: PriceModel;\n};\n\n/**\n * Calculates a tax breakdown from a net amount and tax rules.\n * Handles both tax-inclusive (reverse calculation) and tax-exclusive (forward calculation) paths.\n *\n * @param netAmount - The net amount (after discounts) in its native basis (inclusive or exclusive).\n * @param isTaxInclusive - Whether netAmount already contains tax.\n * @param taxRules - The applicable tax rules.\n * @returns Per-rule tax entries, total tax, and the exclusive taxable base.\n */\nexport const calculateTaxBreakdown = (\n netAmount: PriceModel,\n isTaxInclusive: boolean,\n taxRules: TaxRuleModel[]\n): TaxBreakdownResult => {\n const zero = netAmount.zero();\n let taxTotal = zero;\n const entries: TaxBreakdownEntry[] = [];\n\n if (isTaxInclusive) {\n const totalRate = taxRules.reduce((sum, r) => sum + r.getApplicableTaxRate(netAmount), 0);\n if (totalRate <= 0) {\n return { entries: [], taxTotal: zero, taxableBase: netAmount };\n }\n\n const taxableBase = extractExclusiveBase(netAmount, taxRules);\n const distributedTaxes = calculateDistributedTaxes(taxableBase, netAmount, taxRules);\n\n distributedTaxes.forEach(dt => {\n const taxRule = taxRules.find(r => r.getTaxRuleId() === dt.ruleId)!;\n entries.push({\n ruleId: dt.ruleId,\n rate: dt.rate,\n taxableAmount: taxableBase,\n taxAmount: dt.taxAmount,\n system: taxRule.getTaxSystem(),\n subSystem: taxRule.getTaxSubSystem()\n });\n taxTotal = taxTotal.add(dt.taxAmount);\n });\n\n return { entries, taxTotal, taxableBase };\n } else {\n taxRules.forEach(taxRule => {\n const rate = taxRule.getApplicableTaxRate(netAmount);\n if (rate <= 0) return; // Skip non-applicable rules\n const taxAmount = taxRule.calculateTax(netAmount);\n entries.push({\n ruleId: taxRule.getTaxRuleId(),\n rate,\n taxableAmount: netAmount,\n taxAmount,\n system: taxRule.getTaxSystem(),\n subSystem: taxRule.getTaxSubSystem()\n });\n taxTotal = taxTotal.add(taxAmount);\n });\n\n return { entries, taxTotal, taxableBase: netAmount };\n }\n};\n\n/**\n * Result containing both tax-exclusive and tax-inclusive views of totals.\n */\nexport type DualViewTotals = {\n taxExclusive: { baseAmount: PriceModel; netAmount: PriceModel; grandTotal: PriceModel };\n taxInclusive: { baseAmount: PriceModel; netAmount: PriceModel; grandTotal: PriceModel };\n taxTotal: PriceModel;\n taxBreakdown: TaxBreakdownEntry[];\n discountTotal: PriceModel;\n};\n\n/**\n * Computes both tax-exclusive and tax-inclusive views of totals for a given gross amount,\n * discount, and tax rules. Suitable for flat-amount entities like charges.\n *\n * @param grossAmount - The original amount (before discounts), in its native basis.\n * @param discount - The total discount to apply (in the same basis as grossAmount).\n * @param isTaxInclusive - Whether grossAmount already contains tax.\n * @param taxRules - The applicable tax rules.\n * @returns Both exclusive and inclusive views, tax breakdown, and totals.\n */\nexport const calculateDualViewTotals = (\n grossAmount: PriceModel,\n discount: PriceModel,\n isTaxInclusive: boolean,\n taxRules: TaxRuleModel[]\n): DualViewTotals => {\n const netAmount = grossAmount.subtract(discount);\n const { entries, taxTotal, taxableBase } = calculateTaxBreakdown(netAmount, isTaxInclusive, taxRules);\n\n if (isTaxInclusive) {\n const grossExclBase = extractExclusiveBase(grossAmount, taxRules);\n\n return {\n taxExclusive: {\n baseAmount: grossExclBase,\n netAmount: taxableBase,\n grandTotal: taxableBase,\n },\n taxInclusive: {\n baseAmount: grossAmount,\n netAmount: netAmount,\n grandTotal: netAmount,\n },\n taxTotal,\n taxBreakdown: entries,\n discountTotal: discount,\n };\n } else {\n let originalTax = grossAmount.zero();\n taxRules.forEach(taxRule => {\n originalTax = originalTax.add(taxRule.calculateTax(grossAmount));\n });\n const grossAmountInclTax = grossAmount.add(originalTax);\n const netAmountInclTax = netAmount.add(taxTotal);\n\n return {\n taxExclusive: {\n baseAmount: grossAmount,\n netAmount: netAmount,\n grandTotal: netAmount,\n },\n taxInclusive: {\n baseAmount: grossAmountInclTax,\n netAmount: netAmountInclTax,\n grandTotal: netAmountInclTax,\n },\n taxTotal,\n taxBreakdown: entries,\n discountTotal: discount,\n };\n }\n};\n"]}
@@ -1,2 +1,2 @@
1
- import {b as b$1}from'./chunk-7RAIVZKB.mjs';import {a}from'./chunk-UIQH5QIR.mjs';import {e as e$1}from'./chunk-PL5HGCWN.mjs';import {h,e,l as l$1,n,m as m$1,o,p,y}from'./chunk-O6BLQQO7.mjs';import {b}from'./chunk-UXZBULDS.mjs';import G from'crypto';var C=new Uint8Array(256),T=C.length;function v(){return T>C.length-16&&(G.randomFillSync(C),T=0),C.slice(T,T+=16)}var R=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function q(r){return typeof r=="string"&&R.test(r)}var $=q;var u=[];for(let r=0;r<256;++r)u.push((r+256).toString(16).slice(1));function x(r,e=0){return u[r[e+0]]+u[r[e+1]]+u[r[e+2]]+u[r[e+3]]+"-"+u[r[e+4]]+u[r[e+5]]+"-"+u[r[e+6]]+u[r[e+7]]+"-"+u[r[e+8]]+u[r[e+9]]+"-"+u[r[e+10]]+u[r[e+11]]+u[r[e+12]]+u[r[e+13]]+u[r[e+14]]+u[r[e+15]]}function j(r){if(!$(r))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(r.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(r.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(r.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(r.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var B=j;function Z(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var Y="6ba7b810-9dad-11d1-80b4-00c04fd430c8",F="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function U(r,e,t){function i(n,s,a,c){var p;if(typeof n=="string"&&(n=Z(n)),typeof s=="string"&&(s=B(s)),((p=s)===null||p===void 0?void 0:p.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let o=new Uint8Array(16+n.length);if(o.set(s),o.set(n,s.length),o=t(o),o[6]=o[6]&15|e,o[8]=o[8]&63|128,a){c=c||0;for(let y=0;y<16;++y)a[c+y]=o[y];return a}return x(o)}try{i.name=r;}catch{}return i.DNS=Y,i.URL=F,i}var L={randomUUID:G.randomUUID};function W(r,e,t){if(L.randomUUID&&!e&&!r)return L.randomUUID();r=r||{};let i=r.random||(r.rng||v)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(let n=0;n<16;++n)e[t+n]=i[n];return e}return x(i)}var E=W;function J(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),G.createHash("sha1").update(r).digest()}var N=J;var _=U("v5",80,N),Q=_;var ee={isUUID:r=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(r),isEmail:r=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r),isURL:r=>/^(http|https):\/\/[^ "]+$/.test(r),generateUUID:(r,e)=>e&&r?Q(r,e):E(),generateSearchId:(r,e)=>`${r}#${m.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:r=>{let[e,t]=r.split("#");return {key:e,selectionAttributes:m.parseSelectionAttributesKey(t)}},deepClone(r){return structuredClone(r)}},l=ee;var m=class r extends b{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;productType;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new h("Selection attributes must be an object");return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let t={},i=e.split("|");for(let n of i){let[s,a]=n.split(":");a.startsWith("c+")?t[s]={name:a.slice(2)}:t[s]=a;}return t}catch(t){throw new h(t?.message)}}constructor(e$1,t=new Date){super(e$1,t),this.id=e$1.id,this.key=e$1.key,this.name={...e$1.name},this.description={...e$1.description},this.slug={...e$1.slug},this.brand=e$1.brand,this.pricing=Object.keys(e$1.pricing).reduce((n,s)=>(e$1.pricing[s]&&(n[s]=S.create(e$1.pricing[s])),n),{}),this.targetGender=e$1.targetGender,this.attributes=l.deepClone(e$1.attributes),this.specifications=l.deepClone(e$1.specifications),this.categories=l.deepClone(e$1.categories),this.productType=e$1.productType??"GOODS";let i=new Set;this.variants=(e$1.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new h("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let s=r.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(s))throw new e(s);return i.add(s),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new b$1(n.images.primary),gallery:(n.images.gallery||[]).map(a=>new b$1(a))}}}),this.isActive=e$1.isActive,this.searchTags=e$1.searchTags?l.deepClone(e$1.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[e$1[e]]??this.name.en:l.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[e$1[e]]??this.description.en:l.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[e$1[e]]??this.slug.en:l.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return l.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:l.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let t=r.generateSelectionAttributesKey(e),i=this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===t);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,t){switch(t){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return l.deepClone(this.categories)}getProductType(){return this.productType}getSpecifications(e){return e?l.deepClone(this.specifications[e]??this.specifications[e$1[e]]??this.specifications.en):l.deepClone(this.specifications)}getSearchTags(e){return e?l.deepClone(this.searchTags[e]??this.searchTags[e$1[e]]??this.searchTags.en):l.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((t,i)=>(this.pricing[i]&&(t[i]=this.pricing[i]?.getDetails()),t),{}),attributes:this.getAttributes(),variants:this.variants.map(t=>({sku:t.sku,selectionAttributes:l.deepClone(t.selectionAttributes),images:{primary:t.images.primary.getDetails(),gallery:t.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),productType:this.getProductType(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new h("Selection attributes are required");Object.keys(this.attributes).forEach(t=>{if(t.toLowerCase()==="size")return;let i=this.attributes[t],n=e[t];if(n===void 0)throw new h(`Selection attribute '${t}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new h(`Selection attribute '${t}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new h(`Selection attribute '${t}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(s=>s.name===n.name)<0)throw new h(`Selection attribute '${t}' is invalid`)}});}getSku(e){let t=r.generateSelectionAttributesKey(e);return this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===t)?.sku}validateSelectionAttribute(e){let t=r.generateSelectionAttributesKey(e);return this.variants.some(i=>r.generateSelectionAttributesKey(i.selectionAttributes)===t)}validateSize(e){return this.attributes.size.includes(e)}};var te=(t=>(t.VOLUME="volume",t.SELECTION="selection",t))(te||{}),S=class{type;taxCategory;isTaxInclusive;static create(e){return e.type==="selection"?new V(e):new z(e)}constructor(e){if(!e.taxCategory)throw new l$1;this.taxCategory=e.taxCategory,this.isTaxInclusive=e.isTaxInclusive??!1,this.type=e.type??"volume";}getType(){return this.type}getTaxCategory(){return this.taxCategory}getIsTaxInclusive(){return this.isTaxInclusive}},z=class extends S{baseUnitPrice;tiers;currency;constructor(e){if(super(e),this.type="volume",!e.baseUnitPrice)throw new n("Base unit price is required for volume pricing.");this.baseUnitPrice=new a(e.baseUnitPrice),this.currency=e.currency??this.baseUnitPrice.getCurrency();let t=(e.tiers??[]).map(c=>({enabled:c.enabled??!0,minQuantity:c.minQuantity,unitPrice:new a(c.unitPrice)})).sort((c,p)=>c.minQuantity-p.minQuantity);if(t.some(c=>c.minQuantity<=0))throw new m$1;let n$1=this.baseUnitPrice.getCurrency()!==this.currency||t.some(c=>c.unitPrice.getCurrency()!==this.currency),s=t.some((c,p)=>p>0&&c.unitPrice.compareTo(t[p-1].unitPrice)>0),a$1=t[0]?.unitPrice.compareTo(this.baseUnitPrice)>0;if(n$1||s||a$1)throw new n("Tiers must share the same currency and must not increase in unit price.");this.tiers=t;}isPriceAvailable(){return this.tiers.filter(e=>e.enabled).length>0}getBaseUnitPrice(){return this.baseUnitPrice}getCurrency(){return this.baseUnitPrice.getCurrency()}getApplicableUnitPrice(e){if(e<=0)throw new o;let t=this.tiers.filter(i=>i.enabled);for(let i=t.length-1;i>=0;i--){let n=t[i];if(e>=n.minQuantity)return n.unitPrice}throw new p(e)}getMinQuantity(){return this.tiers.filter(t=>t.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(){let e=this.tiers.filter(s=>s.enabled);if(!e.length)return 0;let t=Math.min(...e.map(s=>s.unitPrice.getAmount())),i=this.baseUnitPrice.getAmount(),n=(i-t)/i*100;return n>0?n:0}getMinPrice(){let e=this.tiers.filter(t=>t.enabled);return e.length?e[e.length-1].unitPrice:null}getMaxPrice(){let e=this.tiers.filter(t=>t.enabled);return e.length?e[0].unitPrice:null}getTiers(){return this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,baseUnitPrice:this.baseUnitPrice.getDetails(),tiers:this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}},V=class extends S{currency;selections;constructor(e){super(e),this.type="selection",this.currency=e.currency,this.selections=(e.selections??[]).map(t=>{if(!t.baseUnitPrice)throw new n("Base unit price is required for each selection.");let i=new a(t.baseUnitPrice),n$1=(t.tiers??[]).map(o=>({enabled:o.enabled??!0,minQuantity:o.minQuantity??1,unitPrice:new a(o.unitPrice)})).sort((o,y)=>o.minQuantity-y.minQuantity);if(n$1.some(o=>o.minQuantity<=0))throw new m$1;let a$1=i.getCurrency()!==this.currency||n$1.some(o=>o.unitPrice.getCurrency()!==this.currency),c=n$1.some((o,y)=>y>0&&o.unitPrice.compareTo(n$1[y-1].unitPrice)>0),p=n$1[0]?.unitPrice.compareTo(i)>0;if(a$1||c||p)throw new n("Tiers must share the same currency and must not increase in unit price within the same selection.");return {selectionAttributes:{...t.selectionAttributes},baseUnitPrice:i,tiers:n$1}});}findMatch(e,t=!1){let i=m.generateSelectionAttributesKey(e),n$1=this.selections.find(s=>m.generateSelectionAttributesKey(s.selectionAttributes)===i);if(!n$1&&t)throw new n("No pricing configuration found for selection variant.");return n$1??null}isPriceAvailable(e){if(!e)return console.warn("Selection attributes are required to check price availability for selection pricing."),!1;let t=this.findMatch(e);return t?t.tiers.filter(i=>i.enabled).length>0:!1}getBaseUnitPrice(e){if(!e)throw new y("Selection attributes are required to get base unit price for selection pricing.");return this.findMatch(e,!0).baseUnitPrice}getCurrency(){return this.currency}getApplicableUnitPrice(e,t){if(e<=0)throw new o;if(!t)throw new y("Selection attributes are required to get applicable unit price for selection pricing.");let n=this.findMatch(t,!0).tiers.filter(s=>s.enabled);for(let s=n.length-1;s>=0;s--){let a=n[s];if(e>=a.minQuantity)return a.unitPrice}throw new p(e)}getMinQuantity(e){if(!e)throw new y("Selection attributes are required to get min quantity for selection pricing.");return this.findMatch(e,!0).tiers.filter(n=>n.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(e){if(!e)throw new y("Selection attributes are required to get max discount for selection pricing.");let t=this.findMatch(e,!0),i=t.tiers.filter(c=>c.enabled);if(!i.length)return 0;let n=Math.min(...i.map(c=>c.unitPrice.getAmount())),s=t.baseUnitPrice.getAmount(),a=(s-n)/s*100;return a>0?a:0}getTiers(e){if(!e)throw new y("Selection attributes are required to get tiers for selection pricing.");return this.findMatch(e,!0).tiers.map(i=>({enabled:i.enabled,minQuantity:i.minQuantity,unitPrice:i.unitPrice}))}getMinPrice(e){if(!e)throw new y("Selection attributes are required to get min price for selection pricing.");let t=this.findMatch(e);if(!t)return null;let i=t.tiers.filter(n=>n.enabled);return i.length?i[i.length-1].unitPrice:null}getMaxPrice(e){if(!e)throw new y("Selection attributes are required to get max price for selection pricing.");let t=this.findMatch(e);if(!t)return null;let i=t.tiers.filter(n=>n.enabled);return i.length?i[0].unitPrice:null}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,selections:this.selections.map(e=>({selectionAttributes:e.selectionAttributes,baseUnitPrice:e.baseUnitPrice.getDetails(),...e.tiers.length>0?{tiers:e.tiers.map(t=>({enabled:t.enabled,minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}:{}}))}}};export{l as a,te as b,S as c,z as d,V as e,m as f};//# sourceMappingURL=chunk-4PTWJI6J.mjs.map
2
- //# sourceMappingURL=chunk-4PTWJI6J.mjs.map
1
+ import {b as b$1}from'./chunk-7RAIVZKB.mjs';import {a}from'./chunk-UIQH5QIR.mjs';import {e as e$1}from'./chunk-PL5HGCWN.mjs';import {h,e,l as l$1,n,m as m$1,o,p,y}from'./chunk-O6BLQQO7.mjs';import {b}from'./chunk-UXZBULDS.mjs';import G from'crypto';var C=new Uint8Array(256),T=C.length;function v(){return T>C.length-16&&(G.randomFillSync(C),T=0),C.slice(T,T+=16)}var R=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function q(r){return typeof r=="string"&&R.test(r)}var B=q;var u=[];for(let r=0;r<256;++r)u.push((r+256).toString(16).slice(1));function x(r,e=0){return u[r[e+0]]+u[r[e+1]]+u[r[e+2]]+u[r[e+3]]+"-"+u[r[e+4]]+u[r[e+5]]+"-"+u[r[e+6]]+u[r[e+7]]+"-"+u[r[e+8]]+u[r[e+9]]+"-"+u[r[e+10]]+u[r[e+11]]+u[r[e+12]]+u[r[e+13]]+u[r[e+14]]+u[r[e+15]]}function j(r){if(!B(r))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(r.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(r.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(r.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(r.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var $=j;function Z(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var Y="6ba7b810-9dad-11d1-80b4-00c04fd430c8",F="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function U(r,e,t){function i(n,s,a,c){var p;if(typeof n=="string"&&(n=Z(n)),typeof s=="string"&&(s=$(s)),((p=s)===null||p===void 0?void 0:p.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let o=new Uint8Array(16+n.length);if(o.set(s),o.set(n,s.length),o=t(o),o[6]=o[6]&15|e,o[8]=o[8]&63|128,a){c=c||0;for(let y=0;y<16;++y)a[c+y]=o[y];return a}return x(o)}try{i.name=r;}catch{}return i.DNS=Y,i.URL=F,i}var L={randomUUID:G.randomUUID};function W(r,e,t){if(L.randomUUID&&!e&&!r)return L.randomUUID();r=r||{};let i=r.random||(r.rng||v)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(let n=0;n<16;++n)e[t+n]=i[n];return e}return x(i)}var E=W;function J(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),G.createHash("sha1").update(r).digest()}var N=J;var _=U("v5",80,N),z=_;var ee={isUUID:r=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(r),isEmail:r=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r),isURL:r=>/^(http|https):\/\/[^ "]+$/.test(r),generateUUID:(r,e)=>e&&r?z(r,e):E(),generateSearchId:(r,e)=>`${r}#${m.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:r=>{let[e,t]=r.split("#");return {key:e,selectionAttributes:m.parseSelectionAttributesKey(t)}},deepClone(r){return structuredClone(r)}},l=ee;var m=class r extends b{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;productType;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new h("Selection attributes must be an object");return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let t={},i=e.split("|");for(let n of i){let[s,a]=n.split(":");a.startsWith("c+")?t[s]={name:a.slice(2)}:t[s]=a;}return t}catch(t){throw new h(t?.message)}}constructor(e$1,t=new Date){super(e$1,t),this.id=e$1.id,this.key=e$1.key,this.name={...e$1.name},this.description={...e$1.description},this.slug={...e$1.slug},this.brand=e$1.brand,this.pricing=Object.keys(e$1.pricing).reduce((n,s)=>(e$1.pricing[s]&&(n[s]=S.create(e$1.pricing[s])),n),{}),this.targetGender=e$1.targetGender,this.attributes=l.deepClone(e$1.attributes),this.specifications=l.deepClone(e$1.specifications),this.categories=l.deepClone(e$1.categories),this.productType=e$1.productType??"GOODS";let i=new Set;this.variants=(e$1.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new h("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let s=r.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(s))throw new e(s);return i.add(s),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new b$1(n.images.primary),gallery:(n.images.gallery||[]).map(a=>new b$1(a))}}}),this.isActive=e$1.isActive,this.searchTags=e$1.searchTags?l.deepClone(e$1.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[e$1[e]]??this.name.en:l.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[e$1[e]]??this.description.en:l.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[e$1[e]]??this.slug.en:l.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return l.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:l.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let t=r.generateSelectionAttributesKey(e),i=this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===t);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,t){switch(t){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return l.deepClone(this.categories)}getProductType(){return this.productType}getSpecifications(e){return e?l.deepClone(this.specifications[e]??this.specifications[e$1[e]]??this.specifications.en):l.deepClone(this.specifications)}getSearchTags(e){return e?l.deepClone(this.searchTags[e]??this.searchTags[e$1[e]]??this.searchTags.en):l.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((t,i)=>(this.pricing[i]&&(t[i]=this.pricing[i]?.getDetails()),t),{}),attributes:this.getAttributes(),variants:this.variants.map(t=>({sku:t.sku,selectionAttributes:l.deepClone(t.selectionAttributes),images:{primary:t.images.primary.getDetails(),gallery:t.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),productType:this.getProductType(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new h("Selection attributes are required");Object.keys(this.attributes).forEach(t=>{if(t.toLowerCase()==="size")return;let i=this.attributes[t],n=e[t];if(n===void 0)throw new h(`Selection attribute '${t}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new h(`Selection attribute '${t}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new h(`Selection attribute '${t}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(s=>s.name===n.name)<0)throw new h(`Selection attribute '${t}' is invalid`)}});}getSku(e){let t=r.generateSelectionAttributesKey(e);return this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===t)?.sku}validateSelectionAttribute(e){let t=r.generateSelectionAttributesKey(e);return this.variants.some(i=>r.generateSelectionAttributesKey(i.selectionAttributes)===t)}validateSize(e){return this.attributes.size.includes(e)}};var te=(t=>(t.VOLUME="volume",t.SELECTION="selection",t))(te||{}),S=class{type;taxCategory;isTaxInclusive;static create(e){return e.type==="selection"?new V(e):new Q(e)}constructor(e){if(!e.taxCategory)throw new l$1;this.taxCategory=e.taxCategory,this.isTaxInclusive=e.isTaxInclusive??!1,this.type=e.type??"volume";}getType(){return this.type}getTaxCategory(){return this.taxCategory}getIsTaxInclusive(){return this.isTaxInclusive}},Q=class extends S{baseUnitPrice;tiers;currency;constructor(e){if(super(e),this.type="volume",!e.baseUnitPrice)throw new n("Base unit price is required for volume pricing.");this.baseUnitPrice=new a(e.baseUnitPrice),this.currency=e.currency??this.baseUnitPrice.getCurrency();let t=(e.tiers??[]).map(c=>({enabled:c.enabled??!0,minQuantity:c.minQuantity,unitPrice:new a(c.unitPrice)})).sort((c,p)=>c.minQuantity-p.minQuantity);if(t.some(c=>c.minQuantity<=0))throw new m$1;if(this.baseUnitPrice.isZero()||t[0]?.unitPrice.isZero())throw new n("Base unit price and tier unit price must not be zero.");let n$1=this.baseUnitPrice.getCurrency()!==this.currency||t.some(c=>c.unitPrice.getCurrency()!==this.currency),s=t.some((c,p)=>p>0&&c.unitPrice.compareTo(t[p-1].unitPrice)>0),a$1=t[0]?.unitPrice.compareTo(this.baseUnitPrice)>0;if(n$1||s||a$1)throw new n("Tiers must share the same currency and must not increase in unit price.");this.tiers=t;}isPriceAvailable(){return this.tiers.filter(e=>e.enabled).length>0}getBaseUnitPrice(){return this.baseUnitPrice}getCurrency(){return this.baseUnitPrice.getCurrency()}getApplicableUnitPrice(e){if(e<=0)throw new o;let t=this.tiers.filter(i=>i.enabled);for(let i=t.length-1;i>=0;i--){let n=t[i];if(e>=n.minQuantity)return n.unitPrice}throw new p(e)}getMinQuantity(){return this.tiers.filter(t=>t.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(){let e=this.tiers.filter(s=>s.enabled);if(!e.length)return 0;let t=Math.min(...e.map(s=>s.unitPrice.getAmount())),i=this.baseUnitPrice.getAmount(),n=(i-t)/i*100;return n>0?n:0}getMinPrice(){let e=this.tiers.filter(t=>t.enabled);return e.length?e[e.length-1].unitPrice:null}getMaxPrice(){let e=this.tiers.filter(t=>t.enabled);return e.length?e[0].unitPrice:null}getTiers(){return this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,baseUnitPrice:this.baseUnitPrice.getDetails(),tiers:this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}},V=class extends S{currency;selections;constructor(e){super(e),this.type="selection",this.currency=e.currency,this.selections=(e.selections??[]).map(t=>{if(!t.baseUnitPrice)throw new n("Base unit price is required for each selection.");let i=new a(t.baseUnitPrice),n$1=(t.tiers??[]).map(o=>({enabled:o.enabled??!0,minQuantity:o.minQuantity??1,unitPrice:new a(o.unitPrice)})).sort((o,y)=>o.minQuantity-y.minQuantity);if(n$1.some(o=>o.minQuantity<=0))throw new m$1;if(i.isZero()||n$1[0]?.unitPrice.isZero())throw new n("Base unit price and tier unit price must not be zero.");let a$1=i.getCurrency()!==this.currency||n$1.some(o=>o.unitPrice.getCurrency()!==this.currency),c=n$1.some((o,y)=>y>0&&o.unitPrice.compareTo(n$1[y-1].unitPrice)>0),p=n$1[0]?.unitPrice.compareTo(i)>0;if(a$1||c||p)throw new n("Tiers must share the same currency and must not increase in unit price within the same selection.");return {selectionAttributes:{...t.selectionAttributes},baseUnitPrice:i,tiers:n$1}});}findMatch(e,t=!1){let i=m.generateSelectionAttributesKey(e),n$1=this.selections.find(s=>m.generateSelectionAttributesKey(s.selectionAttributes)===i);if(!n$1&&t)throw new n("No pricing configuration found for selection variant.");return n$1??null}isPriceAvailable(e){if(!e)return console.warn("Selection attributes are required to check price availability for selection pricing."),!1;let t=this.findMatch(e);return t?t.tiers.filter(i=>i.enabled).length>0:!1}getBaseUnitPrice(e){if(!e)throw new y("Selection attributes are required to get base unit price for selection pricing.");return this.findMatch(e,!0).baseUnitPrice}getCurrency(){return this.currency}getApplicableUnitPrice(e,t){if(e<=0)throw new o;if(!t)throw new y("Selection attributes are required to get applicable unit price for selection pricing.");let n=this.findMatch(t,!0).tiers.filter(s=>s.enabled);for(let s=n.length-1;s>=0;s--){let a=n[s];if(e>=a.minQuantity)return a.unitPrice}throw new p(e)}getMinQuantity(e){if(!e)throw new y("Selection attributes are required to get min quantity for selection pricing.");return this.findMatch(e,!0).tiers.filter(n=>n.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(e){if(!e)throw new y("Selection attributes are required to get max discount for selection pricing.");let t=this.findMatch(e,!0),i=t.tiers.filter(c=>c.enabled);if(!i.length)return 0;let n=Math.min(...i.map(c=>c.unitPrice.getAmount())),s=t.baseUnitPrice.getAmount(),a=(s-n)/s*100;return a>0?a:0}getTiers(e){if(!e)throw new y("Selection attributes are required to get tiers for selection pricing.");return this.findMatch(e,!0).tiers.map(i=>({enabled:i.enabled,minQuantity:i.minQuantity,unitPrice:i.unitPrice}))}getMinPrice(e){if(!e)throw new y("Selection attributes are required to get min price for selection pricing.");let t=this.findMatch(e);if(!t)return null;let i=t.tiers.filter(n=>n.enabled);return i.length?i[i.length-1].unitPrice:null}getMaxPrice(e){if(!e)throw new y("Selection attributes are required to get max price for selection pricing.");let t=this.findMatch(e);if(!t)return null;let i=t.tiers.filter(n=>n.enabled);return i.length?i[0].unitPrice:null}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,selections:this.selections.map(e=>({selectionAttributes:e.selectionAttributes,baseUnitPrice:e.baseUnitPrice.getDetails(),...e.tiers.length>0?{tiers:e.tiers.map(t=>({enabled:t.enabled,minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}:{}}))}}};export{l as a,te as b,S as c,Q as d,V as e,m as f};//# sourceMappingURL=chunk-XXKEHCV5.mjs.map
2
+ //# sourceMappingURL=chunk-XXKEHCV5.mjs.map