b23-lib 2.1.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/Auth/index.js +1 -1
  2. package/dist/Auth/index.js.map +1 -1
  3. package/dist/Auth/index.mjs +1 -1
  4. package/dist/Auth/index.mjs.map +1 -1
  5. package/dist/Classes/Address.js +1 -1
  6. package/dist/Classes/Address.js.map +1 -1
  7. package/dist/Classes/Address.mjs +1 -1
  8. package/dist/Classes/Base.d.mts +30 -25
  9. package/dist/Classes/Base.d.ts +30 -25
  10. package/dist/Classes/Base.js +1 -1
  11. package/dist/Classes/Base.js.map +1 -1
  12. package/dist/Classes/Base.mjs +1 -1
  13. package/dist/Classes/Cart.js +2 -2
  14. package/dist/Classes/Cart.js.map +1 -1
  15. package/dist/Classes/Cart.mjs +1 -1
  16. package/dist/Classes/Coupon.js +1 -1
  17. package/dist/Classes/Coupon.js.map +1 -1
  18. package/dist/Classes/Coupon.mjs +1 -1
  19. package/dist/Classes/Customer.js +1 -1
  20. package/dist/Classes/Customer.js.map +1 -1
  21. package/dist/Classes/Customer.mjs +1 -1
  22. package/dist/Classes/Customer.mjs.map +1 -1
  23. package/dist/Classes/CustomerAddress.js +1 -1
  24. package/dist/Classes/CustomerAddress.js.map +1 -1
  25. package/dist/Classes/CustomerAddress.mjs +1 -1
  26. package/dist/Classes/CustomerAddress.mjs.map +1 -1
  27. package/dist/Classes/Inventory.js +1 -1
  28. package/dist/Classes/Inventory.js.map +1 -1
  29. package/dist/Classes/Inventory.mjs +1 -1
  30. package/dist/Classes/Inventory.mjs.map +1 -1
  31. package/dist/Classes/LineItem.d.mts +3 -3
  32. package/dist/Classes/LineItem.d.ts +3 -3
  33. package/dist/Classes/LineItem.js +2 -2
  34. package/dist/Classes/LineItem.js.map +1 -1
  35. package/dist/Classes/LineItem.mjs +1 -1
  36. package/dist/Classes/Order.js +2 -2
  37. package/dist/Classes/Order.js.map +1 -1
  38. package/dist/Classes/Order.mjs +1 -1
  39. package/dist/Classes/Payment.js +1 -1
  40. package/dist/Classes/Payment.js.map +1 -1
  41. package/dist/Classes/Payment.mjs +1 -1
  42. package/dist/Classes/Product.js +1 -1
  43. package/dist/Classes/Product.js.map +1 -1
  44. package/dist/Classes/Product.mjs +1 -1
  45. package/dist/Classes/ShoppingContainer.js +2 -2
  46. package/dist/Classes/ShoppingContainer.js.map +1 -1
  47. package/dist/Classes/ShoppingContainer.mjs +1 -1
  48. package/dist/Classes/TaxRule.js +2 -2
  49. package/dist/Classes/TaxRule.js.map +1 -1
  50. package/dist/Classes/TaxRule.mjs +1 -1
  51. package/dist/chunk-6KCJVEZD.mjs +2 -0
  52. package/dist/chunk-6KCJVEZD.mjs.map +1 -0
  53. package/dist/chunk-7NLMXN4H.mjs +2 -0
  54. package/dist/chunk-7NLMXN4H.mjs.map +1 -0
  55. package/dist/chunk-FGXEJC4J.mjs +2 -0
  56. package/dist/{chunk-G6UFVELO.mjs.map → chunk-FGXEJC4J.mjs.map} +1 -1
  57. package/dist/chunk-GMGMQ2NX.mjs +2 -0
  58. package/dist/{chunk-I3IWW4V2.mjs.map → chunk-GMGMQ2NX.mjs.map} +1 -1
  59. package/dist/chunk-OIR5JBJY.mjs +2 -0
  60. package/dist/chunk-OIR5JBJY.mjs.map +1 -0
  61. package/dist/chunk-TUT4BB3Z.mjs +3 -0
  62. package/dist/{chunk-NFRTZM45.mjs.map → chunk-TUT4BB3Z.mjs.map} +1 -1
  63. package/dist/{chunk-5KD2EW7O.mjs → chunk-YSUBOEFT.mjs} +2 -2
  64. package/dist/{chunk-5KD2EW7O.mjs.map → chunk-YSUBOEFT.mjs.map} +1 -1
  65. package/dist/{chunk-K6Q6YDUX.mjs → chunk-ZAHR3SJ2.mjs} +2 -2
  66. package/dist/{chunk-K6Q6YDUX.mjs.map → chunk-ZAHR3SJ2.mjs.map} +1 -1
  67. package/dist/index.d.mts +2 -24
  68. package/dist/index.d.ts +2 -24
  69. package/dist/index.js +2 -2
  70. package/dist/index.js.map +1 -1
  71. package/dist/index.mjs +2 -2
  72. package/dist/index.mjs.map +1 -1
  73. package/package.json +1 -1
  74. package/dist/chunk-55SOBG62.mjs +0 -2
  75. package/dist/chunk-55SOBG62.mjs.map +0 -1
  76. package/dist/chunk-AMIRIUMH.mjs +0 -2
  77. package/dist/chunk-AMIRIUMH.mjs.map +0 -1
  78. package/dist/chunk-G6UFVELO.mjs +0 -2
  79. package/dist/chunk-I3IWW4V2.mjs +0 -2
  80. package/dist/chunk-MJBRKWRU.mjs +0 -2
  81. package/dist/chunk-MJBRKWRU.mjs.map +0 -1
  82. package/dist/chunk-NFRTZM45.mjs +0 -3
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Classes/ShoppingContainer.ts"],"names":["BaseShoppingContainerModel","BaseModel","data","date","item","LineItemModel","AddressModel","coupon","CouponModel","Utils_default","PriceModel","key","value","zero","filteredLineItems","lineitem","subTotal","total","lineItem","shipping","couponDiscountTotal","couponTotal","nonShippingCouponTotal","couponValue","taxTotal","shippingCoupon","effectiveShipping","grandTotal","shippingDetails","applicableCoupons","shippingCoupons","otherCoupons","couponDiscounts","couponDiscount","itemDiscounts","li","code","totalDiscount","c","validItems","a","b","distributed","index","amount","taxRules","coupons","subTotalWithCouponDiscount","maxValuedCoupon","maxCoupon","currentCoupon","currentCouponValue","maxCouponValue"],"mappings":"mPA6DA,IAA8BA,CAA9B,CAAA,cAAiEC,CAAU,CAC/D,EACA,CAAA,UAAA,CACA,aACA,CAAA,WAAA,CACA,SACA,CAAA,eAAA,CACA,eACA,CAAA,cAAA,CAGA,QAGA,KAUA,CAAA,OAAA,CACA,QACA,CAAA,MAAA,CAQV,WAAYC,CAAAA,CAAAA,CAAuCC,CAAa,CAAA,IAAI,KAAQ,CAC1E,KAAA,CAAMD,CAAMC,CAAAA,CAAI,CAChB,CAAA,IAAA,CAAK,EAAKD,CAAAA,CAAAA,CAAK,GACf,IAAK,CAAA,UAAA,CAA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KAAM,CAAA,mBAAA,CAAsB,IAAK,CAAA,KAAA,CAAM,mBAAoB,CAAA,GAAA,CAAIA,CAAW,CAAA,CAC/E,KAAK,KAAM,CAAA,iBAAA,CAAoB,IAAK,CAAA,KAAA,CAAM,QAAS,CAAA,QAAA,CAASA,CAAW,CAAA,EAE3E,CACF,CACF","file":"chunk-G6UFVELO.mjs","sourcesContent":["import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport AddressModel, { AddressData } from \"./Address\";\r\nimport LineItemModel, { LineItemData } 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 { LineItemState, TaxCategory } from \"./Enum\";\r\nimport { TaxRuleModel } from \"./TaxRule\";\r\n\r\nexport type ShoppingContainerTotal = {\r\n /** Sum of item prices before discounts & tax */\r\n subtotal: PriceData;\r\n\r\n /** Original shipping cost before coupons / promotions */\r\n shipping: PriceData;\r\n\r\n /** Shipping after coupons / promotions (>= 0) */\r\n effectiveShipping: PriceData;\r\n\r\n /** Total tax amount (all tax rules combined) */\r\n taxTotal: PriceData;\r\n\r\n /**\r\n * Coupon discounts applied\r\n * key = couponCode (or couponId)\r\n * value = discount amount (positive number)\r\n */\r\n couponTotal: Record<string, PriceData>;\r\n\r\n /** Total discount from coupons (derived, optional to store) */\r\n couponDiscountTotal: PriceData;\r\n\r\n /** Final payable amount */\r\n grandTotal: PriceData;\r\n};\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 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 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: {\r\n subtotal: PriceModel;\r\n shipping: PriceModel;\r\n effectiveShipping: PriceModel;\r\n taxTotal: PriceModel;\r\n couponTotal: Record<string, PriceModel>;\r\n couponDiscountTotal: PriceModel;\r\n grandTotal: PriceModel;\r\n };\r\n\r\n protected country: CountryCode;\r\n protected currency: CurrencyCode;\r\n protected locale: LocaleCode;\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()) {\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.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 subtotal: new PriceModel(data.total.subtotal),\r\n shipping: new PriceModel(data.total.shipping),\r\n effectiveShipping: new PriceModel(data.total.effectiveShipping),\r\n taxTotal: new PriceModel(data.total.taxTotal),\r\n couponTotal: Object.fromEntries(\r\n Object.entries(data.total.couponTotal).map(([key, value]) => [key, new PriceModel(value)])\r\n ),\r\n couponDiscountTotal: new PriceModel(data.total.couponDiscountTotal),\r\n grandTotal: new PriceModel(data.total.grandTotal),\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 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 a shallow copy if details exist\r\n return this.shippingDetails ? { ...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 this.total;\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 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 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 subtotal: this.getTotal().subtotal.getDetails(),\r\n shipping: this.getTotal().shipping.getDetails(),\r\n effectiveShipping: this.getTotal().effectiveShipping.getDetails(),\r\n taxTotal: this.getTotal().taxTotal.getDetails(),\r\n couponTotal: Object.fromEntries(Object.entries(this.getTotal().couponTotal).map(([key, value]) => [key, value.getDetails()])),\r\n couponDiscountTotal: this.getTotal().couponDiscountTotal.getDetails(),\r\n grandTotal: this.getTotal().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 includes summing line items, calculating shipping, applying coupons, and computing taxes.\r\n */\r\n public calculateTotals(): void {\r\n const zero = new PriceModel({ amount: 0, currency: this.currency });\r\n const filteredLineItems = this.lineItems.filter(lineitem => lineitem.getState() !== LineItemState.CANCELLED);\r\n const subTotal = filteredLineItems.reduce((total, lineItem) => total.add(lineItem.getTotal().subtotal), zero);\r\n\r\n const shipping = new PriceModel({ amount: this.shippingDetails?.cost || 0, currency: this.currency }).round();\r\n\r\n let couponDiscountTotal = zero;\r\n let couponTotal: Record<string, PriceModel> = {};\r\n let nonShippingCouponTotal: Record<string, PriceModel> = {};\r\n this.coupons.forEach(coupon => {\r\n const couponValue = coupon.calculateApplicableCouponDiscount(subTotal, shipping, this.country, this.currency);\r\n couponDiscountTotal = couponDiscountTotal.add(couponValue);\r\n couponTotal[coupon.getCode()] = couponValue;\r\n if (coupon.getCategory() !== CouponCategory.SHIPPING) {\r\n nonShippingCouponTotal[coupon.getCode()] = couponValue;\r\n }\r\n })\r\n this.applyDiscountsInLineItem(nonShippingCouponTotal);\r\n\r\n const taxTotal = filteredLineItems.reduce((total, lineItem) => total.add(lineItem.getTotal().taxTotal), zero);\r\n const shippingCoupon = this.coupons.find(coupon => coupon.getCategory() === CouponCategory.SHIPPING);\r\n const effectiveShipping = shippingCoupon ? shipping.subtract(couponTotal[shippingCoupon.getCode()] || zero) : shipping;\r\n\r\n const grandTotal = subTotal.add(shipping).add(taxTotal).subtract(couponDiscountTotal);\r\n\r\n this.total = {\r\n subtotal: subTotal,\r\n shipping: shipping,\r\n effectiveShipping: effectiveShipping,\r\n couponTotal: couponTotal,\r\n couponDiscountTotal: couponDiscountTotal,\r\n taxTotal: taxTotal,\r\n grandTotal: 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 this.calculateTotals();\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.couponDiscountTotal = this.total.subtotal.zero();\r\n this.total.couponTotal = {};\r\n // Apply non shipping coupons\r\n otherCoupons.length && this.applyNonShippingCoupons(otherCoupons);\r\n this.applyDiscountsInLineItem(this.total.couponTotal);\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, totalDiscount]) => {\r\n const coupon = this.coupons.find(c => c.getCode() === code);\r\n if (!coupon || totalDiscount.isZero()) return;\r\n\r\n const validItems = this.lineItems\r\n .filter(li => li.getState() !== LineItemState.CANCELLED && !li.getTotal().subtotal.isZero())\r\n .sort((a, b) => a.getTotal().subtotal.compareTo(b.getTotal().subtotal));\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 if (index === validItems.length - 1) {\r\n amount = totalDiscount.subtract(distributed);\r\n } else {\r\n amount = totalDiscount.multiply(item.getTotal().subtotal).divide(this.total.subtotal).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 if (lineItem.getState() === LineItemState.CANCELLED || this.total.subtotal.isZero()) {\r\n lineItem.updateDiscounts([]);\r\n } else {\r\n lineItem.updateDiscounts(itemDiscounts.get(lineItem.getId()) || []);\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Updates the tax rules for all line items and recalculates totals.\r\n * @param taxRules - A record of tax rules keyed by tax category.\r\n */\r\n public updateTax(taxRules: Record<TaxCategory, TaxRuleModel>): void {\r\n this.lineItems.forEach(lineItem => {\r\n lineItem.updateTax(taxRules[lineItem.getPricing().taxCategory]);\r\n });\r\n this.calculateTotals();\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 couponValue = coupons[0].calculateApplicableCouponDiscount(this.total.subtotal, this.total.shipping, this.country, this.currency);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(coupons[0]);\r\n this.total.couponTotal[coupons[0].getCode()] = couponValue;\r\n this.total.couponDiscountTotal = 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 if (this.total.shipping.getAmount() > 0 && applicableCoupons.length > 0) {\r\n const subTotalWithCouponDiscount = this.total.subtotal.subtract(this.total.couponDiscountTotal);\r\n\r\n const maxValuedCoupon = applicableCoupons.reduce((maxCoupon, currentCoupon) => {\r\n if (!maxCoupon) return currentCoupon;\r\n\r\n const currentCouponValue = currentCoupon.calculateApplicableCouponDiscount(subTotalWithCouponDiscount, this.total.shipping, this.country, this.currency).min(this.total.shipping);\r\n const maxCouponValue = maxCoupon.calculateApplicableCouponDiscount(subTotalWithCouponDiscount, this.total.shipping, this.country, this.currency).min(this.total.shipping);\r\n\r\n if (currentCouponValue === maxCouponValue) {\r\n return currentCoupon.getType() === 'coupon' ? currentCoupon : maxCoupon;\r\n }\r\n return currentCouponValue > maxCouponValue ? currentCoupon : maxCoupon;\r\n });\r\n\r\n const couponValue = maxValuedCoupon.calculateApplicableCouponDiscount(subTotalWithCouponDiscount, this.total.shipping, this.country, this.currency).min(this.total.shipping);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(maxValuedCoupon);\r\n this.total.couponTotal[maxValuedCoupon.getCode()] = couponValue;\r\n this.total.couponDiscountTotal = this.total.couponDiscountTotal.add(couponValue);\r\n this.total.effectiveShipping = this.total.shipping.subtract(couponValue);\r\n }\r\n }\r\n }\r\n}\r\n\r\n\r\n"]}
1
+ {"version":3,"sources":["../src/Classes/ShoppingContainer.ts"],"names":["BaseShoppingContainerModel","BaseModel","data","date","item","LineItemModel","AddressModel","coupon","CouponModel","Utils_default","PriceModel","key","value","zero","filteredLineItems","lineitem","subTotal","total","lineItem","shipping","couponDiscountTotal","couponTotal","nonShippingCouponTotal","couponValue","taxTotal","shippingCoupon","effectiveShipping","grandTotal","shippingDetails","applicableCoupons","shippingCoupons","otherCoupons","couponDiscounts","couponDiscount","itemDiscounts","li","code","totalDiscount","c","validItems","a","b","distributed","index","amount","taxRules","coupons","subTotalWithCouponDiscount","maxValuedCoupon","maxCoupon","currentCoupon","currentCouponValue","maxCouponValue"],"mappings":"mPA6DA,IAA8BA,CAA9B,CAAA,cAAiEC,CAAU,CAC/D,EACA,CAAA,UAAA,CACA,aACA,CAAA,WAAA,CACA,SACA,CAAA,eAAA,CACA,eACA,CAAA,cAAA,CAGA,QAGA,KAUA,CAAA,OAAA,CACA,QACA,CAAA,MAAA,CAQV,WAAYC,CAAAA,CAAAA,CAAuCC,CAAa,CAAA,IAAI,KAAQ,CAC1E,KAAA,CAAMD,CAAMC,CAAAA,CAAI,CAChB,CAAA,IAAA,CAAK,EAAKD,CAAAA,CAAAA,CAAK,GACf,IAAK,CAAA,UAAA,CAAaA,CAAK,CAAA,UAAA,CACvB,IAAK,CAAA,aAAA,CAAgBA,CAAK,CAAA,aAAA,CAC1B,IAAK,CAAA,WAAA,CAAcA,CAAK,CAAA,WAAA,CACxB,IAAK,CAAA,OAAA,CAAUA,CAAK,CAAA,OAAA,CACpB,KAAK,QAAWA,CAAAA,CAAAA,CAAK,QACrB,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XEJC4J.mjs","sourcesContent":["import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport AddressModel, { AddressData } from \"./Address\";\r\nimport LineItemModel, { LineItemData } 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 { LineItemState, TaxCategory } from \"./Enum\";\r\nimport { TaxRuleModel } from \"./TaxRule\";\r\n\r\nexport type ShoppingContainerTotal = {\r\n /** Sum of item prices before discounts & tax */\r\n subtotal: PriceData;\r\n\r\n /** Original shipping cost before coupons / promotions */\r\n shipping: PriceData;\r\n\r\n /** Shipping after coupons / promotions (>= 0) */\r\n effectiveShipping: PriceData;\r\n\r\n /** Total tax amount (all tax rules combined) */\r\n taxTotal: PriceData;\r\n\r\n /**\r\n * Coupon discounts applied\r\n * key = couponCode (or couponId)\r\n * value = discount amount (positive number)\r\n */\r\n couponTotal: Record<string, PriceData>;\r\n\r\n /** Total discount from coupons (derived, optional to store) */\r\n couponDiscountTotal: PriceData;\r\n\r\n /** Final payable amount */\r\n grandTotal: PriceData;\r\n};\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 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 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: {\r\n subtotal: PriceModel;\r\n shipping: PriceModel;\r\n effectiveShipping: PriceModel;\r\n taxTotal: PriceModel;\r\n couponTotal: Record<string, PriceModel>;\r\n couponDiscountTotal: PriceModel;\r\n grandTotal: PriceModel;\r\n };\r\n\r\n protected country: CountryCode;\r\n protected currency: CurrencyCode;\r\n protected locale: LocaleCode;\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()) {\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.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 subtotal: new PriceModel(data.total.subtotal),\r\n shipping: new PriceModel(data.total.shipping),\r\n effectiveShipping: new PriceModel(data.total.effectiveShipping),\r\n taxTotal: new PriceModel(data.total.taxTotal),\r\n couponTotal: Object.fromEntries(\r\n Object.entries(data.total.couponTotal).map(([key, value]) => [key, new PriceModel(value)])\r\n ),\r\n couponDiscountTotal: new PriceModel(data.total.couponDiscountTotal),\r\n grandTotal: new PriceModel(data.total.grandTotal),\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 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 a shallow copy if details exist\r\n return this.shippingDetails ? { ...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 this.total;\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 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 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 subtotal: this.getTotal().subtotal.getDetails(),\r\n shipping: this.getTotal().shipping.getDetails(),\r\n effectiveShipping: this.getTotal().effectiveShipping.getDetails(),\r\n taxTotal: this.getTotal().taxTotal.getDetails(),\r\n couponTotal: Object.fromEntries(Object.entries(this.getTotal().couponTotal).map(([key, value]) => [key, value.getDetails()])),\r\n couponDiscountTotal: this.getTotal().couponDiscountTotal.getDetails(),\r\n grandTotal: this.getTotal().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 includes summing line items, calculating shipping, applying coupons, and computing taxes.\r\n */\r\n public calculateTotals(): void {\r\n const zero = new PriceModel({ amount: 0, currency: this.currency });\r\n const filteredLineItems = this.lineItems.filter(lineitem => lineitem.getState() !== LineItemState.CANCELLED);\r\n const subTotal = filteredLineItems.reduce((total, lineItem) => total.add(lineItem.getTotal().subtotal), zero);\r\n\r\n const shipping = new PriceModel({ amount: this.shippingDetails?.cost || 0, currency: this.currency }).round();\r\n\r\n let couponDiscountTotal = zero;\r\n let couponTotal: Record<string, PriceModel> = {};\r\n let nonShippingCouponTotal: Record<string, PriceModel> = {};\r\n this.coupons.forEach(coupon => {\r\n const couponValue = coupon.calculateApplicableCouponDiscount(subTotal, shipping, this.country, this.currency);\r\n couponDiscountTotal = couponDiscountTotal.add(couponValue);\r\n couponTotal[coupon.getCode()] = couponValue;\r\n if (coupon.getCategory() !== CouponCategory.SHIPPING) {\r\n nonShippingCouponTotal[coupon.getCode()] = couponValue;\r\n }\r\n })\r\n this.applyDiscountsInLineItem(nonShippingCouponTotal);\r\n\r\n const taxTotal = filteredLineItems.reduce((total, lineItem) => total.add(lineItem.getTotal().taxTotal), zero);\r\n const shippingCoupon = this.coupons.find(coupon => coupon.getCategory() === CouponCategory.SHIPPING);\r\n const effectiveShipping = shippingCoupon ? shipping.subtract(couponTotal[shippingCoupon.getCode()] || zero) : shipping;\r\n\r\n const grandTotal = subTotal.add(shipping).add(taxTotal).subtract(couponDiscountTotal);\r\n\r\n this.total = {\r\n subtotal: subTotal,\r\n shipping: shipping,\r\n effectiveShipping: effectiveShipping,\r\n couponTotal: couponTotal,\r\n couponDiscountTotal: couponDiscountTotal,\r\n taxTotal: taxTotal,\r\n grandTotal: 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 this.calculateTotals();\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.couponDiscountTotal = this.total.subtotal.zero();\r\n this.total.couponTotal = {};\r\n // Apply non shipping coupons\r\n otherCoupons.length && this.applyNonShippingCoupons(otherCoupons);\r\n this.applyDiscountsInLineItem(this.total.couponTotal);\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, totalDiscount]) => {\r\n const coupon = this.coupons.find(c => c.getCode() === code);\r\n if (!coupon || totalDiscount.isZero()) return;\r\n\r\n const validItems = this.lineItems\r\n .filter(li => li.getState() !== LineItemState.CANCELLED && !li.getTotal().subtotal.isZero())\r\n .sort((a, b) => a.getTotal().subtotal.compareTo(b.getTotal().subtotal));\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 if (index === validItems.length - 1) {\r\n amount = totalDiscount.subtract(distributed);\r\n } else {\r\n amount = totalDiscount.multiply(item.getTotal().subtotal).divide(this.total.subtotal).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 if (lineItem.getState() === LineItemState.CANCELLED || this.total.subtotal.isZero()) {\r\n lineItem.updateDiscounts([]);\r\n } else {\r\n lineItem.updateDiscounts(itemDiscounts.get(lineItem.getId()) || []);\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Updates the tax rules for all line items and recalculates totals.\r\n * @param taxRules - A record of tax rules keyed by tax category.\r\n */\r\n public updateTax(taxRules: Record<TaxCategory, TaxRuleModel>): void {\r\n this.lineItems.forEach(lineItem => {\r\n lineItem.updateTax(taxRules[lineItem.getPricing().taxCategory]);\r\n });\r\n this.calculateTotals();\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 couponValue = coupons[0].calculateApplicableCouponDiscount(this.total.subtotal, this.total.shipping, this.country, this.currency);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(coupons[0]);\r\n this.total.couponTotal[coupons[0].getCode()] = couponValue;\r\n this.total.couponDiscountTotal = 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 if (this.total.shipping.getAmount() > 0 && applicableCoupons.length > 0) {\r\n const subTotalWithCouponDiscount = this.total.subtotal.subtract(this.total.couponDiscountTotal);\r\n\r\n const maxValuedCoupon = applicableCoupons.reduce((maxCoupon, currentCoupon) => {\r\n if (!maxCoupon) return currentCoupon;\r\n\r\n const currentCouponValue = currentCoupon.calculateApplicableCouponDiscount(subTotalWithCouponDiscount, this.total.shipping, this.country, this.currency).min(this.total.shipping);\r\n const maxCouponValue = maxCoupon.calculateApplicableCouponDiscount(subTotalWithCouponDiscount, this.total.shipping, this.country, this.currency).min(this.total.shipping);\r\n\r\n if (currentCouponValue === maxCouponValue) {\r\n return currentCoupon.getType() === 'coupon' ? currentCoupon : maxCoupon;\r\n }\r\n return currentCouponValue > maxCouponValue ? currentCoupon : maxCoupon;\r\n });\r\n\r\n const couponValue = maxValuedCoupon.calculateApplicableCouponDiscount(subTotalWithCouponDiscount, this.total.shipping, this.country, this.currency).min(this.total.shipping);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(maxValuedCoupon);\r\n this.total.couponTotal[maxValuedCoupon.getCode()] = couponValue;\r\n this.total.couponDiscountTotal = this.total.couponDiscountTotal.add(couponValue);\r\n this.total.effectiveShipping = this.total.shipping.subtract(couponValue);\r\n }\r\n }\r\n }\r\n}\r\n\r\n\r\n"]}
@@ -0,0 +1,2 @@
1
+ import {a}from'./chunk-ZAHR3SJ2.mjs';import {a as a$1}from'./chunk-R32ZSPV6.mjs';import {e}from'./chunk-72DR3HF2.mjs';import {s}from'./chunk-DGFO2MH6.mjs';import {b as b$1}from'./chunk-6KCJVEZD.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 s("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-GMGMQ2NX.mjs.map
2
+ //# sourceMappingURL=chunk-GMGMQ2NX.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","maxCartDiscountC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ourcesContent":["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 // Ensure minCartValueReq exists and subtotal meets the requirement\r\n if (!minCartValueReq || minCartValueReq.compareTo(cartValue) > 0) {\r\n return zeroDiscount;\r\n }\r\n\r\n // Ensure maxCartDiscountCap exists and is non-negative (price-model throws error when amount < 0)\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}"]}
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,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,IAAO,CAAA,MAAA,CACPA,EAAA,UAAa,CAAA,YAAA,CAFHA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAKAC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CAAC,IAAA,CAAK,QAAS,EAAA,CAChC,OAAOC,CAIT,CAAA,IAAME,CAAkB,CAAA,IAAA,CAAK,gBAAgBd,CAAO,CAAA,CAC9Ce,CAAqB,CAAA,IAAA,CAAK,kBAAmBf,CAAAA,CAAO,CAQ1D,CAAA,GALI,CAACc,CAAmBA,EAAAA,CAAAA,CAAgB,SAAUN,CAAAA,CAAS,EAAI,CAK3D,EAAA,CAACO,CACH,CAAA,OAAOH,EAIT,IAAMI,CAAAA,CAAiB,IAAK,CAAA,WAAA,EACtBC,CAAAA,CAAAA,CAAiB,IAAK,CAAA,iBAAA,GAEtBC,CAAcF,CAAAA,CAAAA,GAAmB,UAA0BP,CAAAA,CAAAA,CAAeD,EAGhF,GAAIU,CAAAA,CAAY,SAAU,EAAA,EAAK,EAAG,OAAON,CAAAA,CAEzC,OAAQK,CAAAA,EACN,IAAK,MAEH,CAAA,IAAME,EAAaJ,CACnBF,CAAAA,CAAAA,CAAoBK,CAAY,CAAA,GAAA,CAAIC,CAAU,CAC9C,CAAA,MACF,IAAK,YAAA,CAEHN,EAAoBK,CAAY,CAAA,QAAA,CAAS,IAAK,CAAA,kBAAA,EAAuB,CAAA,GAAG,CAAE,CAAA,KAAA,GAC1E,MACF,QAEE,OAAON,CACX,CAKA,OAFsBC,CAAAA,CAAkB,GAAIE,CAAAA,CAAkB,CAGhE,CACF","file":"chunk-GMGMQ2NX.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 // Ensure minCartValueReq exists and subtotal meets the requirement\r\n if (!minCartValueReq || minCartValueReq.compareTo(cartValue) > 0) {\r\n return zeroDiscount;\r\n }\r\n\r\n // Ensure maxCartDiscountCap exists and is non-negative (price-model throws error when amount < 0)\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}"]}
@@ -0,0 +1,2 @@
1
+ import _ from'util';var E=Object.freeze({INVALID_UUID:"Invalid UUID",INVALID_EMAIL:"Invalid Email",INVALID_TOKEN:"Invalid Token",TOKEN_EXPIRED:"Token Expired",INVALID_VERIFIER:"Invalid Verifier",INVALID_PERMISSIONS:"Invalid Permissions",INVALID_AUTH_TYPE:"Invalid Authorization Type",USER_PRIVATE_KEY_NOT_FOUND:"User Private Key Not Found",USER_PUBLIC_KEY_NOT_FOUND:"User Public Key Not Found",ANONYMOUS_PRIVATE_KEY_NOT_FOUND:"Anonymous Private Key Not Found",ANONYMOUS_PUBLIC_KEY_NOT_FOUND:"Anonymous Public Key Not Found",SYSTEM_PRIVATE_KEY_NOT_FOUND:"System Private Key Not Found",SYSTEM_PUBLIC_KEY_NOT_FOUND:"System Public Key Not Found",ADMIN_PRIVATE_KEY_NOT_FOUND:"Admin Private Key Not Found",ADMIN_PUBLIC_KEY_NOT_FOUND:"Admin Public Key Not Found",SECRET_TOKEN_NOT_FOUND:"Secret Token Not Found",ANONYMOUS_SESSION_NOT_ALLOWED:"Anonymous Session Not Allowed",USER_SESSION_NOT_ALLOWED:"User Session Not Allowed",SYSTEM_SESSION_NOT_ALLOWED:"System Session Not Allowed",CDN_SESSION_NOT_ALLOWED:"CDN Session Not Allowed",INTERNAL_SERVER_ERROR:"Internal Server Error",SOMETHING_WENT_WRONG:"Something went wrong",AUTH_CONTEXT_NOT_INITIALIZED:"Auth Context not Initialized"});var t={logException:(o,n)=>{console.error(`Exception Occurred in Function: ${o}, Error: ${t.inspect(n)}`);},logError:(o,n)=>{console.error(`Error Occurred in Function: ${o}, Error: ${t.inspect(n)}`);},logWarning:(o,n)=>{console.warn(`Warning in Function: ${o} - ${t.inspect(n)}`);},logMessage:(o,n)=>{console.log(`Message in Function: ${o} - ${t.inspect(n)}`);},logInvalidPayload:(o,n)=>{console.error(`Invalid Payload received for Function: ${o}, Error: ${t.inspect(n)}`);},inspect:o=>typeof o=="string"?o:_.inspect(o)},r=t;var a={handleException:(o,n,e)=>{n.knownError?(n.logError&&r.logError(o,n),e.status(n.status).json({status:n.status,error:n.error})):n.status&&n.error?(r.logException(o,n),e.status(n.status).json({error:n.errorMessage||JSON.stringify(n.error),status:n.status})):(r.logException(o,n),e.status(500).json({status:500,error:E.INTERNAL_SERVER_ERROR}));},generateResponse:(o,n,e)=>({status:o,data:n,error:e}),generateError:(o,n,e=!0,N=!1)=>({status:o,error:n,knownError:e,logError:N})},d=a;export{E as a,r as b,d as c};//# sourceMappingURL=chunk-OIR5JBJY.mjs.map
2
+ //# sourceMappingURL=chunk-OIR5JBJY.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/enums/ErrorTypes.ts","../src/Logger/index.ts","../src/Utils/response.ts"],"names":["ErrorTypes_default","Logger","functionName","error","message","errorMessage","context","util","Logger_default","ResponseUtility","res","status","data","knownError","logError","response_default"],"mappings":"oBAAA,IAAOA,CAAQ,CAAA,MAAA,CAAO,MAAO,CAAA,CACzB,YAAc,CAAA,cAAA,CACd,aAAe,CAAA,eAAA,CACf,aAAe,CAAA,eAAA,CACf,aAAe,CAAA,eAAA,CACf,iBAAkB,kBAClB,CAAA,mBAAA,CAAqB,qBACrB,CAAA,iBAAA,CAAmB,4BACnB,CAAA,0BAAA,CAA4B,4BAC5B,CAAA,yBAAA,CAA2B,2BAC3B,CAAA,+BAAA,CAAiC,iCACjC,CAAA,8BAAA,CAAgC,gCAChC,CAAA,4BAAA,CAA8B,8BAC9B,CAAA,2BAAA,CAA6B,8BAC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,CAAeU,CAAAA,CAAAA,CAAsB,CAAMC,CAAAA,CAAAA,CAAAA,CAAoB,CACtF,CAAA,IAAA,CACL,OAAAH,CACA,CAAA,KAAA,CAAAR,CACA,CAAA,UAAA,CAAAU,CACA,CAAA,QAAA,CAAAC,CACF,CAAA,CAEJ,EAEOC,CAAQN,CAAAA","file":"chunk-OIR5JBJY.mjs","sourcesContent":["export default Object.freeze({\r\n INVALID_UUID: \"Invalid UUID\",\r\n INVALID_EMAIL: \"Invalid Email\",\r\n INVALID_TOKEN: \"Invalid Token\",\r\n TOKEN_EXPIRED: \"Token Expired\",\r\n INVALID_VERIFIER: \"Invalid Verifier\",\r\n INVALID_PERMISSIONS: \"Invalid Permissions\",\r\n INVALID_AUTH_TYPE: \"Invalid Authorization Type\",\r\n USER_PRIVATE_KEY_NOT_FOUND: \"User Private Key Not Found\",\r\n USER_PUBLIC_KEY_NOT_FOUND: \"User Public Key Not Found\",\r\n ANONYMOUS_PRIVATE_KEY_NOT_FOUND: \"Anonymous Private Key Not Found\",\r\n ANONYMOUS_PUBLIC_KEY_NOT_FOUND: \"Anonymous Public Key Not Found\",\r\n SYSTEM_PRIVATE_KEY_NOT_FOUND: \"System Private Key Not Found\",\r\n SYSTEM_PUBLIC_KEY_NOT_FOUND: \"System Public Key Not Found\",\r\n ADMIN_PRIVATE_KEY_NOT_FOUND: \"Admin Private Key Not Found\",\r\n ADMIN_PUBLIC_KEY_NOT_FOUND: \"Admin Public Key Not Found\",\r\n SECRET_TOKEN_NOT_FOUND: \"Secret Token Not Found\",\r\n ANONYMOUS_SESSION_NOT_ALLOWED: \"Anonymous Session Not Allowed\",\r\n USER_SESSION_NOT_ALLOWED: \"User Session Not Allowed\",\r\n SYSTEM_SESSION_NOT_ALLOWED: \"System Session Not Allowed\",\r\n CDN_SESSION_NOT_ALLOWED: \"CDN Session Not Allowed\",\r\n INTERNAL_SERVER_ERROR: \"Internal Server Error\",\r\n SOMETHING_WENT_WRONG: 'Something went wrong',\r\n AUTH_CONTEXT_NOT_INITIALIZED: 'Auth Context not Initialized'\r\n})","import util from 'util';\r\nconst Logger = {\r\n logException: (functionName: string, error: any) => {\r\n console.error(`Exception Occurred in Function: ${functionName}, Error: ${Logger.inspect(error)}`);\r\n },\r\n\r\n logError: (functionName: string, error: any) => {\r\n console.error(`Error Occurred in Function: ${functionName}, Error: ${Logger.inspect(error)}`);\r\n },\r\n\r\n logWarning: (functionName: string, message: any) => {\r\n console.warn(`Warning in Function: ${functionName} - ${Logger.inspect(message)}`);\r\n },\r\n\r\n logMessage: (functionName: string, message: any) => {\r\n console.log(`Message in Function: ${functionName} - ${Logger.inspect(message)}`);\r\n },\r\n\r\n logInvalidPayload: (functionName: string, errorMessage: string) => {\r\n console.error(`Invalid Payload received for Function: ${functionName}, Error: ${Logger.inspect(errorMessage)}`);\r\n },\r\n\r\n inspect: (context: any) => {\r\n return (typeof context === \"string\" ? context : util.inspect(context));\r\n }\r\n}\r\n\r\nexport default Logger;","import ErrorTypes from \"../enums/ErrorTypes\";\r\nimport Logger from \"../Logger\";\r\n\r\nexport const ResponseUtility = {\r\n handleException: (functionName: string, error: any, res: any) => {\r\n if (error.knownError) {\r\n error.logError && Logger.logError(functionName, error);\r\n res.status(error.status).json({\r\n status: error.status,\r\n error: error.error\r\n });\r\n } else if(error.status && error.error) {\r\n Logger.logException(functionName, error);\r\n res.status(error.status).json({\r\n error: error.errorMessage || JSON.stringify(error.error),\r\n status: error.status,\r\n });\r\n } else {\r\n Logger.logException(functionName, error);\r\n res.status(500).json({\r\n status: 500,\r\n error: ErrorTypes.INTERNAL_SERVER_ERROR\r\n })\r\n }\r\n },\r\n\r\n generateResponse: (status: number, data?: any, error?: string) => {\r\n return {\r\n status,\r\n data,\r\n error\r\n }\r\n },\r\n\r\n generateError: (status: number, error: string, knownError: Boolean = true, logError: boolean = false) => {\r\n return {\r\n status,\r\n error,\r\n knownError,\r\n logError\r\n }\r\n }\r\n}\r\n\r\nexport default ResponseUtility;"]}
@@ -0,0 +1,3 @@
1
+ import {a}from'./chunk-R32ZSPV6.mjs';import {o}from'./chunk-DGFO2MH6.mjs';import {b}from'./chunk-6KCJVEZD.mjs';var m=class{getBreakdown(t,a,e){let r=t*100,i=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,"");if(a==="IN"&&e?.merchantState&&e?.customerState)if(e.merchantState.toLowerCase().trim()===e.customerState.toLowerCase().trim()){let o=r/2%1===0?(r/2).toString():(r/2).toFixed(2).replace(/\.?0+$/,"");return {totalRate:t,label:`${o}% CGST + ${o}% SGST`,components:[{rate:t/2,label:`${o}% CGST`,type:"CGST"},{rate:t/2,label:`${o}% SGST`,type:"SGST"}]}}else return {totalRate:t,label:`${i}% IGST`,components:[{rate:t,label:`${i}% IGST`,type:"IGST"}]};return {totalRate:t,label:`${i}% GST`,components:[{rate:t,label:`${i}% GST`,type:"GST"}]}}getLongName(){return "Goods and Services Tax"}},T={GST:new m},g=class s extends b{taxRuleId;taxSystem;taxCategory;country;slabs;effectiveFrom;effectiveTo;constructor(t,a$1=new Date){super(t,a$1),this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxCategory=t.taxCategory,this.country=t.country,this.slabs=t.slabs.map(e=>({rate:e.rate,minUnitPrice:new a(e.minUnitPrice),maxUnitPrice:e.maxUnitPrice?new a(e.maxUnitPrice):void 0})),this.effectiveFrom=new Date(t.effectiveFrom),this.effectiveTo=t.effectiveTo?new Date(t.effectiveTo):void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getSlabs(){return this.slabs}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),slabs:this.getSlabs().map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0})),effectiveFrom:this.effectiveFrom.toISOString(),effectiveTo:this.effectiveTo?this.effectiveTo.toISOString():void 0,...super.getDetails()}}appliesTo(t,a,e=new Date){return this.taxCategory===t&&this.country===a&&this.effectiveFrom<=e&&(this.effectiveTo?this.effectiveTo>=e:!0)}getApplicableTaxRate(t){return s.getApplicableTaxRate(t,this.slabs)}getTaxRateDisplayString(t,a){let e=this.getApplicableTaxRate(t);return s.getTaxRateDisplayString(e,{taxSystem:this.taxSystem,merchantState:a?.merchantState,customerState:a?.customerState})}getTaxRateBreakdown(t,a){let e=this.getApplicableTaxRate(t),r=T[this.taxSystem];if(r)return r.getBreakdown(e,this.country,a);let i=e*100,n=`${i%1===0?i.toString():i.toFixed(2).replace(/\.?0+$/,"")}% ${this.taxSystem}`;return {totalRate:e,label:n,components:[{rate:e,label:n,type:this.taxSystem}]}}getFormattedTaxRate(t,a={}){let r=this.getApplicableTaxRate(t)*100,i=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,""),o=a.variant||"short",n="";switch(o){case"percentageOnly":n=`${i}%`;break;case"detailed":let u=this.getTaxRateBreakdown(t,a),y=a.separator||(a.multiline?`
2
+ `:" + ");n=u.components.map(f=>f.label).join(y);break;case"long":let l=T[this.taxSystem],p=l?l.getLongName(this.country):this.taxSystem.toString();n=`${i}% ${p}`;break;case"short":default:n=`${i}% ${this.taxSystem}`;break}return a.includeTaxesSuffix&&(n+=" (Incl. Taxes)"),n}static getApplicableTaxRate(t,a){let e=a.filter(r=>(r.minUnitPrice===void 0||t.compareTo(r.minUnitPrice)>=0)&&(r.maxUnitPrice===void 0||t.compareTo(r.maxUnitPrice)<0));if(e.length!==1)throw new o;return e[0].rate}static getTaxRateDisplayString(t,a){let e=t*100,r=e%1===0?e.toString():e.toFixed(2).replace(/\.?0+$/,"");if(a.taxSystem==="GST"&&a.merchantState&&a.customerState)if(a.merchantState.toLowerCase().trim()===a.customerState.toLowerCase().trim()){let i=e/2%1===0?(e/2).toString():(e/2).toFixed(2).replace(/\.?0+$/,"");return `${i}% CGST + ${i}% SGST`}else return `${r}% IGST`;return a.taxSystem?`${r}% ${a.taxSystem}`:`${r}%`}};export{m as a,T as b,g as c};//# sourceMappingURL=chunk-TUT4BB3Z.mjs.map
3
+ //# sourceMappingURL=chunk-TUT4BB3Z.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Classes/TaxRule.ts"],"names":["GSTFormatter","rate","country","options","percentage","rateStr","splitRate","TaxFormatterRegistry","TaxRuleModel","_TaxRuleModel","BaseModel","data","date","s","PriceModel","taxCategory","at","unitPrice","formatter","label","variant","result","breakdown","separator","c","systemLongName","taxSlabs","slabs","TaxSlabNotFoundError"],"mappings":"sHAsDO,IAAMA,CAAN,CAAA,KAAkD,CACvD,YAAA,CAAaC,CAAcC,CAAAA,CAAAA,CAAsBC,CAAkD,CAAA,CACjG,IAAMC,CAAAA,CAAaH,CAAO,CAAA,GAAA,CACpBI,CAAUD,CAAAA,CAAAA,CAAa,CAAM,GAAA,CAAA,CAAIA,CAAW,CAAA,QAAA,EAAaA,CAAAA,CAAAA,CAAW,OAAQ,CAAA,CAAC,CAAE,CAAA,OAAA,CAAQ,QAAU,CAAA,EAAE,CAEzG,CAAA,GAAIF,IAAY,IAAQC,EAAAA,CAAAA,EAAS,aAAiBA,EAAAA,CAAAA,EAAS,aACzD,CAAA,GAAIA,CAAQ,CAAA,aAAA,CAAc,WAAY,EAAA,CAAE,IAAK,EAAA,GAAMA,CAAQ,CAAA,aAAA,CAAc,WAAY,EAAA,CAAE,IAAK,EAAA,CAAG,CAC7F,IAAMG,CAAaF,CAAAA,CAAAA,CAAa,CAAK,CAAA,CAAA,GAAM,CAAKA,CAAAA,CAAAA,CAAAA,CAAa,CAAG,EAAA,QAAA,EAAcA,CAAAA,CAAAA,CAAAA,CAAa,CAAG,EAAA,OAAA,CAAQ,CAAC,CAAE,CAAA,OAAA,CAAQ,QAAU,CAAA,EAAE,CAC7H,CAAA,OAAO,CACL,SAAA,CAAWH,CACX,CAAA,KAAA,CAAO,CAAGK,EAAA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,aAAA,EAAiBA,EAAQ,aAC1E,CAAA,GAAIA,EAAQ,aAAc,CAAA,WAAA,GAAc,IAAK,EAAA,GAAMA,EAAQ,aAAc,CAAA,WAAA,GAAc,IAAK,EAAA,CAAG,CAC7F,IAAMG,CAAAA,CAAaF,EAAa,CAAK,CAAA,CAAA,GAAM,GAAKA,CAAa,CAAA,CAAA,EAAG,UAAcA,CAAAA,CAAAA,CAAAA,CAAa,GAAG,OAAQ,CAAA,CAAC,EAAE,OAAQ,CAAA,QAAA,CAAU,EAAE,CAC7H,CAAA,OAAO,GAAGE,CAAS,CAAA,SAAA,EAAYA,CAAS,CAC1C,MAAA,CAAA,CAAA,YACS,CAAGD,EAAAA,CAAO,SAIrB,OAAOF,CAAAA,CAAQ,UAAY,CAAGE,EAAAA,CAAO,KAAKF,CAAQ,CAAA,SAAS,GAAK,CAAGE,EAAAA,CAAO,GAC5E,CACF","file":"chunk-NFRTZM45.mjs","sourcesContent":["import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, ISODateTimeUTC } from \"./Common\";\r\nimport { TaxCategory, TaxSystem } from \"./Enum\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport { TaxSlabNotFoundError } from \"./Error\";\r\n\r\nexport type TaxSlabData = {\r\n minUnitPrice: PriceData; // inclusive\r\n maxUnitPrice?: PriceData; // exclusive\r\n rate: number; // e.g. 0.05 = 5%\r\n};\r\n\r\nexport type TaxSlabModel = {\r\n minUnitPrice: PriceModel; // inclusive\r\n maxUnitPrice?: PriceModel; // exclusive\r\n rate: number; // e.g. 0.05 = 5%\r\n};\r\n\r\nexport type TaxSlabs = TaxSlabData[];\r\n\r\nexport type TaxRateBreakdown = {\r\n totalRate: number;\r\n label: string;\r\n components: {\r\n rate: number;\r\n label: string;\r\n type: 'IGST' | 'CGST' | 'SGST' | 'GST' | string;\r\n }[];\r\n};\r\n\r\nexport type TaxFormattingVariant = 'short' | 'long' | 'detailed' | 'percentageOnly';\r\n\r\nexport interface TaxFormattingOptions {\r\n variant?: TaxFormattingVariant;\r\n includeTaxesSuffix?: boolean; // e.g. \"(Incl. Taxes)\"\r\n merchantState?: string;\r\n customerState?: string;\r\n multiline?: boolean;\r\n separator?: string; // custom separator, overrides multiline if provided\r\n}\r\n\r\n/**\r\n * Interface for tax system specific formatting logic.\r\n */\r\nexport interface ITaxSystemFormatter {\r\n getBreakdown(rate: number, country: CountryCode, options?: TaxFormattingOptions): TaxRateBreakdown;\r\n getLongName(country: CountryCode): string;\r\n}\r\n\r\n/**\r\n * Formatter for GST (Goods and Services Tax).\r\n * Handles India-specific components (CGST/SGST/IGST).\r\n */\r\nexport class GSTFormatter implements ITaxSystemFormatter {\r\n getBreakdown(rate: number, country: CountryCode, options?: TaxFormattingOptions): TaxRateBreakdown {\r\n const percentage = rate * 100;\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n\r\n if (country === 'IN' && options?.merchantState && options?.customerState) {\r\n if (options.merchantState.toLowerCase().trim() === options.customerState.toLowerCase().trim()) {\r\n const splitRate = (percentage / 2) % 1 === 0 ? (percentage / 2).toString() : (percentage / 2).toFixed(2).replace(/\\.?0+$/, '');\r\n return {\r\n totalRate: rate,\r\n label: `${splitRate}% CGST + ${splitRate}% SGST`,\r\n components: [\r\n { rate: rate / 2, label: `${splitRate}% CGST`, type: 'CGST' },\r\n { rate: rate / 2, label: `${splitRate}% SGST`, type: 'SGST' }\r\n ]\r\n };\r\n } else {\r\n return {\r\n totalRate: rate,\r\n label: `${rateStr}% IGST`,\r\n components: [{ rate: rate, label: `${rateStr}% IGST`, type: 'IGST' }]\r\n };\r\n }\r\n }\r\n\r\n return {\r\n totalRate: rate,\r\n label: `${rateStr}% GST`,\r\n components: [{ rate: rate, label: `${rateStr}% GST`, type: 'GST' }]\r\n };\r\n }\r\n\r\n getLongName(): string {\r\n return 'Goods and Services Tax';\r\n }\r\n}\r\n\r\n/**\r\n * Registry to manage and provide tax formatters.\r\n */\r\nexport const TaxFormatterRegistry: Record<string, ITaxSystemFormatter> = {\r\n [TaxSystem.GST]: new GSTFormatter(),\r\n};\r\n\r\nexport type TaxRuleAttributes = {\r\n taxRuleId: string;\r\n taxSystem: TaxSystem;\r\n taxCategory: TaxCategory;\r\n country: CountryCode;\r\n slabs: TaxSlabs;\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n} & BaseAttributes;\r\n\r\nexport type TaxRuleData = Required<Omit<TaxRuleAttributes, 'effectiveFrom' | 'effectiveTo'>> & {\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n};\r\n\r\nexport class TaxRuleModel extends BaseModel {\r\n protected taxRuleId: string;\r\n protected taxSystem: TaxSystem;\r\n protected taxCategory: TaxCategory;\r\n protected country: CountryCode;\r\n protected slabs: TaxSlabModel[];\r\n protected effectiveFrom: Date;\r\n protected effectiveTo?: Date;\r\n\r\n /**\r\n * Creates an instance of TaxRuleModel.\r\n * @param data - The initial tax rule attributes.\r\n * @param date - Optional date for creation/modification (defaults to now).\r\n */\r\n constructor(data: TaxRuleAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.taxRuleId = data.taxRuleId;\r\n this.taxSystem = data.taxSystem;\r\n this.taxCategory = data.taxCategory;\r\n this.country = data.country;\r\n this.slabs = data.slabs.map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: new PriceModel(s.minUnitPrice),\r\n maxUnitPrice: s.maxUnitPrice ? new PriceModel(s.maxUnitPrice) : undefined,\r\n }));\r\n this.effectiveFrom = new Date(data.effectiveFrom);\r\n this.effectiveTo = data.effectiveTo ? new Date(data.effectiveTo) : undefined;\r\n }\r\n\r\n getTaxRuleId(): string {\r\n return this.taxRuleId;\r\n }\r\n\r\n getTaxSystem(): TaxSystem {\r\n return this.taxSystem;\r\n }\r\n\r\n getTaxCategory(): TaxCategory {\r\n return this.taxCategory;\r\n }\r\n\r\n getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n getSlabs(): TaxSlabModel[] {\r\n return this.slabs;\r\n }\r\n\r\n getDetails(): TaxRuleData {\r\n return {\r\n taxRuleId: this.getTaxRuleId(),\r\n taxSystem: this.getTaxSystem(),\r\n taxCategory: this.getTaxCategory(),\r\n country: this.getCountry(),\r\n slabs: this.getSlabs().map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: s.minUnitPrice.getDetails(),\r\n maxUnitPrice: s.maxUnitPrice ? s.maxUnitPrice.getDetails() : undefined,\r\n })),\r\n effectiveFrom: this.effectiveFrom.toISOString(),\r\n effectiveTo: this.effectiveTo ? this.effectiveTo.toISOString() : undefined,\r\n ...super.getDetails()\r\n };\r\n }\r\n\r\n /**\r\n * Checks whether this tax rule is applicable for the given category and country at a specific time.\r\n * @param taxCategory - The tax category to check.\r\n * @param country - The country code to check.\r\n * @param at - The date to check effectiveness against (defaults to now).\r\n * @returns True if the rule is applicable, false otherwise.\r\n */\r\n appliesTo(taxCategory: TaxCategory, country: CountryCode, at: Date = new Date()): boolean {\r\n return (\r\n this.taxCategory === taxCategory &&\r\n this.country === country &&\r\n this.effectiveFrom <= at &&\r\n (this.effectiveTo ? this.effectiveTo >= at : true)\r\n );\r\n }\r\n\r\n /**\r\n * Calculates the applicable tax rate for a given unit price.\r\n * @param unitPrice - The unit price to find the matching tax slab for.\r\n * @returns The tax rate as a decimal (e.g., 0.05 for 5%).\r\n * @throws {TaxSlabNotFoundError} If no applicable slab or multiple slabs are found.\r\n */\r\n getApplicableTaxRate(unitPrice: PriceModel): number {\r\n return TaxRuleModel.getApplicableTaxRate(unitPrice, this.slabs);\r\n }\r\n\r\n /**\r\n * Returns a user-friendly string representation of the applicable tax rate.\r\n * Handles legal IGST/CGST/SGST formatting for India if states are provided.\r\n * @param unitPrice - The unit price to find the matching tax slab for.\r\n * @param options - Optional states to determine IGST vs CGST/SGST.\r\n * @returns A string like \"18% IGST\", \"9% CGST + 9% SGST\", or \"5% GST\".\r\n */\r\n getTaxRateDisplayString(unitPrice: PriceModel, options?: { merchantState?: string, customerState?: string }): string {\r\n const rate = this.getApplicableTaxRate(unitPrice);\r\n return TaxRuleModel.getTaxRateDisplayString(rate, {\r\n taxSystem: this.taxSystem,\r\n merchantState: options?.merchantState,\r\n customerState: options?.customerState\r\n });\r\n }\r\n\r\n /**\r\n * Returns a detailed breakdown of the tax rate into its components (e.g., CGST/SGST).\r\n */\r\n getTaxRateBreakdown(unitPrice: PriceModel, options?: TaxFormattingOptions): TaxRateBreakdown {\r\n const rate = this.getApplicableTaxRate(unitPrice);\r\n const formatter = TaxFormatterRegistry[this.taxSystem];\r\n if (formatter) {\r\n return formatter.getBreakdown(rate, this.country, options);\r\n }\r\n\r\n // Default fallback\r\n const percentage = rate * 100;\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n const label = `${rateStr}% ${this.taxSystem}`;\r\n return {\r\n totalRate: rate,\r\n label: label,\r\n components: [{ rate, label, type: this.taxSystem }]\r\n };\r\n }\r\n\r\n /**\r\n * Formats a tax rate based on versatile options for UI use cases.\r\n */\r\n getFormattedTaxRate(unitPrice: PriceModel, options: TaxFormattingOptions = {}): string {\r\n const rate = this.getApplicableTaxRate(unitPrice);\r\n const percentage = rate * 100;\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n const variant = options.variant || 'short';\r\n let result = '';\r\n\r\n switch (variant) {\r\n case 'percentageOnly':\r\n result = `${rateStr}%`;\r\n break;\r\n case 'detailed':\r\n const breakdown = this.getTaxRateBreakdown(unitPrice, options);\r\n const separator = options.separator || (options.multiline ? '\\n' : ' + ');\r\n result = breakdown.components.map(c => c.label).join(separator);\r\n break;\r\n case 'long':\r\n const formatter = TaxFormatterRegistry[this.taxSystem];\r\n const systemLongName = formatter ? formatter.getLongName(this.country) : this.taxSystem.toString();\r\n result = `${rateStr}% ${systemLongName}`;\r\n break;\r\n case 'short':\r\n default:\r\n result = `${rateStr}% ${this.taxSystem}`;\r\n break;\r\n }\r\n\r\n if (options.includeTaxesSuffix) {\r\n result += ' (Incl. Taxes)';\r\n }\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Static method to find the applicable tax rate from a list of slabs.\r\n */\r\n static getApplicableTaxRate(unitPrice: PriceModel, taxSlabs: TaxSlabModel[]): number {\r\n const slabs = taxSlabs.filter(s =>\r\n (s.minUnitPrice === undefined || unitPrice.compareTo(s.minUnitPrice) >= 0) &&\r\n (s.maxUnitPrice === undefined || unitPrice.compareTo(s.maxUnitPrice) < 0)\r\n );\r\n\r\n if (slabs.length !== 1) {\r\n throw new TaxSlabNotFoundError();\r\n }\r\n\r\n return slabs[0].rate;\r\n }\r\n\r\n /**\r\n * Static method to format a tax rate as a display string.\r\n * Handles legal IGST/CGST/SGST formatting for India if states are provided.\r\n * @param rate - The tax rate as a decimal (e.g., 0.18).\r\n * @param options - Configuration for tax system name and states.\r\n * @returns A formatted string.\r\n */\r\n static getTaxRateDisplayString(rate: number, options: {\r\n taxSystem?: string,\r\n merchantState?: string,\r\n customerState?: string\r\n }): string {\r\n const percentage = rate * 100;\r\n // Format to remove trailing zeros if it's an integer, otherwise keep up to 2 decimal places\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n\r\n if (options.taxSystem === TaxSystem.GST && options.merchantState && options.customerState) {\r\n if (options.merchantState.toLowerCase().trim() === options.customerState.toLowerCase().trim()) {\r\n const splitRate = (percentage / 2) % 1 === 0 ? (percentage / 2).toString() : (percentage / 2).toFixed(2).replace(/\\.?0+$/, '');\r\n return `${splitRate}% CGST + ${splitRate}% SGST`;\r\n } else {\r\n return `${rateStr}% IGST`;\r\n }\r\n }\r\n\r\n return options.taxSystem ? `${rateStr}% ${options.taxSystem}` : `${rateStr}%`;\r\n }\r\n}\r\n"]}
1
+ {"version":3,"sources":["../src/Classes/TaxRule.ts"],"names":["GSTFormatter","rate","country","options","percentage","rateStr","splitRate","TaxFormatterRegistry","TaxRuleModel","_TaxRuleModel","BaseModel","data","date","s","PriceModel","taxCategory","at","unitPrice","formatter","label","variant","result","breakdown","separator","c","systemLongName","taxSlabs","slabs","TaxSlabNotFoundError"],"mappings":"+GAsDO,IAAMA,CAAN,CAAA,KAAkD,CACvD,YAAA,CAAaC,CAAcC,CAAAA,CAAAA,CAAsBC,CAAkD,CAAA,CACjG,IAAMC,CAAAA,CAAaH,CAAO,CAAA,GAAA,CACpBI,CAAUD,CAAAA,CAAAA,CAAa,CAAM,GAAA,CAAA,CAAIA,CAAW,CAAA,QAAA,EAAaA,CAAAA,CAAAA,CAAW,OAAQ,CAAA,CAAC,CAAE,CAAA,OAAA,CAAQ,QAAU,CAAA,EAAE,CAEzG,CAAA,GAAIF,IAAY,IAAQC,EAAAA,CAAAA,EAAS,aAAiBA,EAAAA,CAAAA,EAAS,aACzD,CAAA,GAAIA,CAAQ,CAAA,aAAA,CAAc,WAAY,EAAA,CAAE,IAAK,EAAA,GAAMA,CAAQ,CAAA,aAAA,CAAc,WAAY,EAAA,CAAE,IAAK,EAAA,CAAG,CAC7F,IAAMG,CAAaF,CAAAA,CAAAA,CAAa,CAAK,CAAA,CAAA,GAAM,CAAKA,CAAAA,CAAAA,CAAAA,CAAa,CAAG,EAAA,QAAA,EAAcA,CAAAA,CAAAA,CAAAA,CAAa,CAAG,EAAA,OAAA,CAAQ,CAAC,CAAE,CAAA,OAAA,CAAQ,QAAU,CAAA,EAAE,CAC7H,CAAA,OAAO,CACL,SAAA,CAAWH,CACX,CAAA,KAAA,CAAO,CAAGK,EAAAA,CAAS,CAAYA,SAAAA,EAAAA,CAAS,CACxC,MAAA,CAAA,CAAA,UAAA,CAAY,CACV,CAAE,IAAML,CAAAA,CAAAA,CAAO,CAAG,CAAA,KAAA,CAAO,CAAGK,EAAAA,CAAS,CAAU,MAAA,CAAA,CAAA,IAAA,CAAM,MAA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A,GAAM,GAAKA,CAAa,CAAA,CAAA,EAAG,UAAcA,CAAAA,CAAAA,CAAAA,CAAa,GAAG,OAAQ,CAAA,CAAC,EAAE,OAAQ,CAAA,QAAA,CAAU,EAAE,CAC7H,CAAA,OAAO,GAAGE,CAAS,CAAA,SAAA,EAAYA,CAAS,CAC1C,MAAA,CAAA,CAAA,YACS,CAAGD,EAAAA,CAAO,SAIrB,OAAOF,CAAAA,CAAQ,UAAY,CAAGE,EAAAA,CAAO,KAAKF,CAAQ,CAAA,SAAS,GAAK,CAAGE,EAAAA,CAAO,GAC5E,CACF","file":"chunk-TUT4BB3Z.mjs","sourcesContent":["import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, ISODateTimeUTC } from \"./Common\";\r\nimport { TaxCategory, TaxSystem } from \"./Enum\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport { TaxSlabNotFoundError } from \"./Error\";\r\n\r\nexport type TaxSlabData = {\r\n minUnitPrice: PriceData; // inclusive\r\n maxUnitPrice?: PriceData; // exclusive\r\n rate: number; // e.g. 0.05 = 5%\r\n};\r\n\r\nexport type TaxSlabModel = {\r\n minUnitPrice: PriceModel; // inclusive\r\n maxUnitPrice?: PriceModel; // exclusive\r\n rate: number; // e.g. 0.05 = 5%\r\n};\r\n\r\nexport type TaxSlabs = TaxSlabData[];\r\n\r\nexport type TaxRateBreakdown = {\r\n totalRate: number;\r\n label: string;\r\n components: {\r\n rate: number;\r\n label: string;\r\n type: 'IGST' | 'CGST' | 'SGST' | 'GST' | string;\r\n }[];\r\n};\r\n\r\nexport type TaxFormattingVariant = 'short' | 'long' | 'detailed' | 'percentageOnly';\r\n\r\nexport interface TaxFormattingOptions {\r\n variant?: TaxFormattingVariant;\r\n includeTaxesSuffix?: boolean; // e.g. \"(Incl. Taxes)\"\r\n merchantState?: string;\r\n customerState?: string;\r\n multiline?: boolean;\r\n separator?: string; // custom separator, overrides multiline if provided\r\n}\r\n\r\n/**\r\n * Interface for tax system specific formatting logic.\r\n */\r\nexport interface ITaxSystemFormatter {\r\n getBreakdown(rate: number, country: CountryCode, options?: TaxFormattingOptions): TaxRateBreakdown;\r\n getLongName(country: CountryCode): string;\r\n}\r\n\r\n/**\r\n * Formatter for GST (Goods and Services Tax).\r\n * Handles India-specific components (CGST/SGST/IGST).\r\n */\r\nexport class GSTFormatter implements ITaxSystemFormatter {\r\n getBreakdown(rate: number, country: CountryCode, options?: TaxFormattingOptions): TaxRateBreakdown {\r\n const percentage = rate * 100;\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n\r\n if (country === 'IN' && options?.merchantState && options?.customerState) {\r\n if (options.merchantState.toLowerCase().trim() === options.customerState.toLowerCase().trim()) {\r\n const splitRate = (percentage / 2) % 1 === 0 ? (percentage / 2).toString() : (percentage / 2).toFixed(2).replace(/\\.?0+$/, '');\r\n return {\r\n totalRate: rate,\r\n label: `${splitRate}% CGST + ${splitRate}% SGST`,\r\n components: [\r\n { rate: rate / 2, label: `${splitRate}% CGST`, type: 'CGST' },\r\n { rate: rate / 2, label: `${splitRate}% SGST`, type: 'SGST' }\r\n ]\r\n };\r\n } else {\r\n return {\r\n totalRate: rate,\r\n label: `${rateStr}% IGST`,\r\n components: [{ rate: rate, label: `${rateStr}% IGST`, type: 'IGST' }]\r\n };\r\n }\r\n }\r\n\r\n return {\r\n totalRate: rate,\r\n label: `${rateStr}% GST`,\r\n components: [{ rate: rate, label: `${rateStr}% GST`, type: 'GST' }]\r\n };\r\n }\r\n\r\n getLongName(): string {\r\n return 'Goods and Services Tax';\r\n }\r\n}\r\n\r\n/**\r\n * Registry to manage and provide tax formatters.\r\n */\r\nexport const TaxFormatterRegistry: Record<string, ITaxSystemFormatter> = {\r\n [TaxSystem.GST]: new GSTFormatter(),\r\n};\r\n\r\nexport type TaxRuleAttributes = {\r\n taxRuleId: string;\r\n taxSystem: TaxSystem;\r\n taxCategory: TaxCategory;\r\n country: CountryCode;\r\n slabs: TaxSlabs;\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n} & BaseAttributes;\r\n\r\nexport type TaxRuleData = Required<Omit<TaxRuleAttributes, 'effectiveFrom' | 'effectiveTo'>> & {\r\n effectiveFrom: ISODateTimeUTC;\r\n effectiveTo?: ISODateTimeUTC;\r\n};\r\n\r\nexport class TaxRuleModel extends BaseModel {\r\n protected taxRuleId: string;\r\n protected taxSystem: TaxSystem;\r\n protected taxCategory: TaxCategory;\r\n protected country: CountryCode;\r\n protected slabs: TaxSlabModel[];\r\n protected effectiveFrom: Date;\r\n protected effectiveTo?: Date;\r\n\r\n /**\r\n * Creates an instance of TaxRuleModel.\r\n * @param data - The initial tax rule attributes.\r\n * @param date - Optional date for creation/modification (defaults to now).\r\n */\r\n constructor(data: TaxRuleAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.taxRuleId = data.taxRuleId;\r\n this.taxSystem = data.taxSystem;\r\n this.taxCategory = data.taxCategory;\r\n this.country = data.country;\r\n this.slabs = data.slabs.map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: new PriceModel(s.minUnitPrice),\r\n maxUnitPrice: s.maxUnitPrice ? new PriceModel(s.maxUnitPrice) : undefined,\r\n }));\r\n this.effectiveFrom = new Date(data.effectiveFrom);\r\n this.effectiveTo = data.effectiveTo ? new Date(data.effectiveTo) : undefined;\r\n }\r\n\r\n getTaxRuleId(): string {\r\n return this.taxRuleId;\r\n }\r\n\r\n getTaxSystem(): TaxSystem {\r\n return this.taxSystem;\r\n }\r\n\r\n getTaxCategory(): TaxCategory {\r\n return this.taxCategory;\r\n }\r\n\r\n getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n getSlabs(): TaxSlabModel[] {\r\n return this.slabs;\r\n }\r\n\r\n getDetails(): TaxRuleData {\r\n return {\r\n taxRuleId: this.getTaxRuleId(),\r\n taxSystem: this.getTaxSystem(),\r\n taxCategory: this.getTaxCategory(),\r\n country: this.getCountry(),\r\n slabs: this.getSlabs().map(s => ({\r\n rate: s.rate,\r\n minUnitPrice: s.minUnitPrice.getDetails(),\r\n maxUnitPrice: s.maxUnitPrice ? s.maxUnitPrice.getDetails() : undefined,\r\n })),\r\n effectiveFrom: this.effectiveFrom.toISOString(),\r\n effectiveTo: this.effectiveTo ? this.effectiveTo.toISOString() : undefined,\r\n ...super.getDetails()\r\n };\r\n }\r\n\r\n /**\r\n * Checks whether this tax rule is applicable for the given category and country at a specific time.\r\n * @param taxCategory - The tax category to check.\r\n * @param country - The country code to check.\r\n * @param at - The date to check effectiveness against (defaults to now).\r\n * @returns True if the rule is applicable, false otherwise.\r\n */\r\n appliesTo(taxCategory: TaxCategory, country: CountryCode, at: Date = new Date()): boolean {\r\n return (\r\n this.taxCategory === taxCategory &&\r\n this.country === country &&\r\n this.effectiveFrom <= at &&\r\n (this.effectiveTo ? this.effectiveTo >= at : true)\r\n );\r\n }\r\n\r\n /**\r\n * Calculates the applicable tax rate for a given unit price.\r\n * @param unitPrice - The unit price to find the matching tax slab for.\r\n * @returns The tax rate as a decimal (e.g., 0.05 for 5%).\r\n * @throws {TaxSlabNotFoundError} If no applicable slab or multiple slabs are found.\r\n */\r\n getApplicableTaxRate(unitPrice: PriceModel): number {\r\n return TaxRuleModel.getApplicableTaxRate(unitPrice, this.slabs);\r\n }\r\n\r\n /**\r\n * Returns a user-friendly string representation of the applicable tax rate.\r\n * Handles legal IGST/CGST/SGST formatting for India if states are provided.\r\n * @param unitPrice - The unit price to find the matching tax slab for.\r\n * @param options - Optional states to determine IGST vs CGST/SGST.\r\n * @returns A string like \"18% IGST\", \"9% CGST + 9% SGST\", or \"5% GST\".\r\n */\r\n getTaxRateDisplayString(unitPrice: PriceModel, options?: { merchantState?: string, customerState?: string }): string {\r\n const rate = this.getApplicableTaxRate(unitPrice);\r\n return TaxRuleModel.getTaxRateDisplayString(rate, {\r\n taxSystem: this.taxSystem,\r\n merchantState: options?.merchantState,\r\n customerState: options?.customerState\r\n });\r\n }\r\n\r\n /**\r\n * Returns a detailed breakdown of the tax rate into its components (e.g., CGST/SGST).\r\n */\r\n getTaxRateBreakdown(unitPrice: PriceModel, options?: TaxFormattingOptions): TaxRateBreakdown {\r\n const rate = this.getApplicableTaxRate(unitPrice);\r\n const formatter = TaxFormatterRegistry[this.taxSystem];\r\n if (formatter) {\r\n return formatter.getBreakdown(rate, this.country, options);\r\n }\r\n\r\n // Default fallback\r\n const percentage = rate * 100;\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n const label = `${rateStr}% ${this.taxSystem}`;\r\n return {\r\n totalRate: rate,\r\n label: label,\r\n components: [{ rate, label, type: this.taxSystem }]\r\n };\r\n }\r\n\r\n /**\r\n * Formats a tax rate based on versatile options for UI use cases.\r\n */\r\n getFormattedTaxRate(unitPrice: PriceModel, options: TaxFormattingOptions = {}): string {\r\n const rate = this.getApplicableTaxRate(unitPrice);\r\n const percentage = rate * 100;\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n const variant = options.variant || 'short';\r\n let result = '';\r\n\r\n switch (variant) {\r\n case 'percentageOnly':\r\n result = `${rateStr}%`;\r\n break;\r\n case 'detailed':\r\n const breakdown = this.getTaxRateBreakdown(unitPrice, options);\r\n const separator = options.separator || (options.multiline ? '\\n' : ' + ');\r\n result = breakdown.components.map(c => c.label).join(separator);\r\n break;\r\n case 'long':\r\n const formatter = TaxFormatterRegistry[this.taxSystem];\r\n const systemLongName = formatter ? formatter.getLongName(this.country) : this.taxSystem.toString();\r\n result = `${rateStr}% ${systemLongName}`;\r\n break;\r\n case 'short':\r\n default:\r\n result = `${rateStr}% ${this.taxSystem}`;\r\n break;\r\n }\r\n\r\n if (options.includeTaxesSuffix) {\r\n result += ' (Incl. Taxes)';\r\n }\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Static method to find the applicable tax rate from a list of slabs.\r\n */\r\n static getApplicableTaxRate(unitPrice: PriceModel, taxSlabs: TaxSlabModel[]): number {\r\n const slabs = taxSlabs.filter(s =>\r\n (s.minUnitPrice === undefined || unitPrice.compareTo(s.minUnitPrice) >= 0) &&\r\n (s.maxUnitPrice === undefined || unitPrice.compareTo(s.maxUnitPrice) < 0)\r\n );\r\n\r\n if (slabs.length !== 1) {\r\n throw new TaxSlabNotFoundError();\r\n }\r\n\r\n return slabs[0].rate;\r\n }\r\n\r\n /**\r\n * Static method to format a tax rate as a display string.\r\n * Handles legal IGST/CGST/SGST formatting for India if states are provided.\r\n * @param rate - The tax rate as a decimal (e.g., 0.18).\r\n * @param options - Configuration for tax system name and states.\r\n * @returns A formatted string.\r\n */\r\n static getTaxRateDisplayString(rate: number, options: {\r\n taxSystem?: string,\r\n merchantState?: string,\r\n customerState?: string\r\n }): string {\r\n const percentage = rate * 100;\r\n // Format to remove trailing zeros if it's an integer, otherwise keep up to 2 decimal places\r\n const rateStr = percentage % 1 === 0 ? percentage.toString() : percentage.toFixed(2).replace(/\\.?0+$/, '');\r\n\r\n if (options.taxSystem === TaxSystem.GST && options.merchantState && options.customerState) {\r\n if (options.merchantState.toLowerCase().trim() === options.customerState.toLowerCase().trim()) {\r\n const splitRate = (percentage / 2) % 1 === 0 ? (percentage / 2).toString() : (percentage / 2).toFixed(2).replace(/\\.?0+$/, '');\r\n return `${splitRate}% CGST + ${splitRate}% SGST`;\r\n } else {\r\n return `${rateStr}% IGST`;\r\n }\r\n }\r\n\r\n return options.taxSystem ? `${rateStr}% ${options.taxSystem}` : `${rateStr}%`;\r\n }\r\n}\r\n"]}
@@ -1,2 +1,2 @@
1
- import {a}from'./chunk-55SOBG62.mjs';var n=(e=>(e.BILLING="billing",e.SHIPPING="shipping",e.BILLING_AND_SHIPPING="billing&shipping",e.NONE="none",e))(n||{}),t=class extends a{id;firstName;lastName;company;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(s,r=new Date){super(s,r),this.id=s.id,this.firstName=s.firstName,this.lastName=s.lastName||"",this.company=s.company||"",this.phone=s.phone,this.email=s.email,this.addressLine1=s.addressLine1,this.addressLine2=s.addressLine2||"",this.city=s.city,this.postalCode=s.postalCode,this.state=s.state,this.country=s.country,this.isBillingAddress=s.isBillingAddress,this.isShippingAddress=s.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),company:this.getCompany(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getCompany(){return this.company}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(s){return s==="shipping"||s==="billing&shipping"}static checkIfBillingAddress(s){return s==="billing"||s==="billing&shipping"}};export{n as a,t as b};//# sourceMappingURL=chunk-5KD2EW7O.mjs.map
2
- //# sourceMappingURL=chunk-5KD2EW7O.mjs.map
1
+ import {b}from'./chunk-6KCJVEZD.mjs';var n=(e=>(e.BILLING="billing",e.SHIPPING="shipping",e.BILLING_AND_SHIPPING="billing&shipping",e.NONE="none",e))(n||{}),t=class extends b{id;firstName;lastName;company;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(s,r=new Date){super(s,r),this.id=s.id,this.firstName=s.firstName,this.lastName=s.lastName||"",this.company=s.company||"",this.phone=s.phone,this.email=s.email,this.addressLine1=s.addressLine1,this.addressLine2=s.addressLine2||"",this.city=s.city,this.postalCode=s.postalCode,this.state=s.state,this.country=s.country,this.isBillingAddress=s.isBillingAddress,this.isShippingAddress=s.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),company:this.getCompany(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getCompany(){return this.company}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(s){return s==="shipping"||s==="billing&shipping"}static checkIfBillingAddress(s){return s==="billing"||s==="billing&shipping"}};export{n as a,t as b};//# sourceMappingURL=chunk-YSUBOEFT.mjs.map
2
+ //# sourceMappingURL=chunk-YSUBOEFT.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Classes/Address.ts"],"names":["AddressType","AddressModel","BaseModel","data","date","addressType"],"mappings":"qCAEO,IAAKA,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,OAAU,CAAA,SAAA,CACVA,EAAA,QAAW,CAAA,UAAA,CACXA,CAAA,CAAA,oBAAA,CAAuB,kBACvBA,CAAAA,CAAAA,CAAA,IAAO,CAAA,MAAA,CAJGA,OAAA,EA8BSC,CAAAA,CAAAA,CAAAA,CAArB,cAA0CC,CAAU,CAC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UAAwBA,EAAAA,CAAAA,GAAgB,kBACjE,CAOA,OAAO,qBAAsBA,CAAAA,CAAAA,CAAmC,CAC9D,OAAOA,CAAAA,GAAgB,SAAuBA,EAAAA,CAAAA,GAAgB,kBAChE,CACF","file":"chunk-5KD2EW7O.mjs","sourcesContent":["import BaseModel, { BaseAttributes } from \"./Base\";\r\n\r\nexport enum AddressType {\r\n BILLING = \"billing\",\r\n SHIPPING = \"shipping\",\r\n BILLING_AND_SHIPPING = \"billing&shipping\",\r\n NONE = \"none\",\r\n}\r\n\r\nexport type AddressAttributes = BaseAttributes & {\r\n id: string;\r\n firstName: string;\r\n lastName?: string;\r\n company?: string;\r\n phone: string;\r\n email: string;\r\n addressLine1: string;\r\n addressLine2?: string;\r\n city: string;\r\n postalCode: string\r\n state: string;\r\n country: string;\r\n isBillingAddress: boolean;\r\n isShippingAddress: boolean;\r\n};\r\n\r\nexport type AddressData = Required<AddressAttributes>;\r\n\r\n/**\r\n * Represents a physical address associated with a customer or order.\r\n * Handles both billing and shipping address types.\r\n */\r\nexport default class AddressModel extends BaseModel {\r\n protected id: string;\r\n protected firstName: string;\r\n protected lastName: string;\r\n protected company: string;\r\n protected phone: string;\r\n protected email: string;\r\n protected addressLine1: string;\r\n protected addressLine2: string;\r\n protected city: string;\r\n protected postalCode: string\r\n protected state: string;\r\n protected country: string;\r\n protected isBillingAddress: boolean;\r\n protected isShippingAddress: boolean;\r\n\r\n /**\r\n * Creates an instance of AddressModel.\r\n * @param data - The initial address attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: AddressAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.firstName = data.firstName;\r\n this.lastName = data.lastName || '';\r\n this.company = data.company || '';\r\n this.phone = data.phone;\r\n this.email = data.email;\r\n this.addressLine1 = data.addressLine1;\r\n this.addressLine2 = data.addressLine2 || '';\r\n this.city = data.city;\r\n this.postalCode = data.postalCode;\r\n this.state = data.state;\r\n this.country = data.country;\r\n this.isBillingAddress = data.isBillingAddress;\r\n this.isShippingAddress = data.isShippingAddress;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the address's current state.\r\n * Includes all address fields and base model fields.\r\n * @returns AddressData object suitable for serialization or API responses.\r\n */\r\n getDetails(): AddressData {\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n firstName: this.getFirstName(),\r\n lastName: this.getLastName(),\r\n company: this.getCompany(),\r\n phone: this.getPhone(),\r\n email: this.getEmail(),\r\n addressLine1: this.getAddressLine1(),\r\n addressLine2: this.getAddressLine2(),\r\n city: this.getCity(),\r\n postalCode: this.getPostalCode(),\r\n state: this.getState(),\r\n country: this.getCountry(),\r\n isBillingAddress: this.getIsBillingAddress(),\r\n isShippingAddress: this.getIsShippingAddress(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for the address.\r\n * @returns The address ID.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the first name associated with the address.\r\n * @returns The first name.\r\n */\r\n getFirstName(): string {\r\n return this.firstName;\r\n }\r\n\r\n /**\r\n * Gets the last name associated with the address.\r\n * @returns The last name.\r\n */\r\n getLastName(): string {\r\n return this.lastName;\r\n }\r\n\r\n /**\r\n * Gets the company name associated with the address.\r\n * @returns The company name.\r\n */\r\n getCompany(): string {\r\n return this.company;\r\n }\r\n\r\n /**\r\n * Gets the phone number associated with the address.\r\n * @returns The phone number.\r\n */\r\n getPhone(): string {\r\n return this.phone;\r\n }\r\n\r\n /**\r\n * Gets the email address associated with the address.\r\n * @returns The email address.\r\n */\r\n getEmail(): string {\r\n return this.email;\r\n }\r\n\r\n /**\r\n * Gets the primary address line (e.g., street address).\r\n * @returns The first address line.\r\n */\r\n getAddressLine1(): string {\r\n return this.addressLine1;\r\n }\r\n\r\n /**\r\n * Gets the secondary address line (e.g., apartment, suite).\r\n * Returns an empty string if not provided.\r\n * @returns The second address line or an empty string.\r\n */\r\n getAddressLine2(): string {\r\n return this.addressLine2;\r\n }\r\n\r\n /**\r\n * Gets the city name.\r\n * @returns The city.\r\n */\r\n getCity(): string {\r\n return this.city;\r\n }\r\n\r\n /**\r\n * Gets the postal code (e.g., ZIP code).\r\n * @returns The postal code.\r\n */\r\n getPostalCode(): string {\r\n return this.postalCode;\r\n }\r\n\r\n /**\r\n * Gets the state, province, or region.\r\n * @returns The state.\r\n */\r\n getState(): string {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the country name or code.\r\n * @returns The country.\r\n */\r\n getCountry(): string {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Checks if this address is designated as a billing address.\r\n * @returns True if it's a billing address, false otherwise.\r\n */\r\n getIsBillingAddress(): boolean {\r\n return this.isBillingAddress;\r\n }\r\n\r\n /**\r\n * Checks if this address is designated as a shipping address.\r\n * @returns True if it's a shipping address, false otherwise.\r\n */\r\n getIsShippingAddress(): boolean {\r\n return this.isShippingAddress;\r\n }\r\n\r\n /**\r\n * Determines the type of the address based on its billing and shipping flags.\r\n * @returns The AddressType enum value representing the address's role.\r\n */\r\n getAddressType(): AddressType {\r\n if (this.isBillingAddress && this.isShippingAddress) {\r\n return AddressType.BILLING_AND_SHIPPING;\r\n } else if (this.isBillingAddress) {\r\n return AddressType.BILLING;\r\n } else if (this.isShippingAddress) {\r\n return AddressType.SHIPPING;\r\n } else {\r\n return AddressType.NONE;\r\n }\r\n }\r\n\r\n /**\r\n * Static method to check if a given AddressType includes shipping.\r\n * @param addressType - The address type to check.\r\n * @returns True if the type is SHIPPING or BILLING_AND_SHIPPING.\r\n */\r\n static checkIfShippingAddress(addressType: AddressType): boolean {\r\n return addressType === AddressType.SHIPPING || addressType === AddressType.BILLING_AND_SHIPPING;\r\n }\r\n\r\n /**\r\n * Static method to check if a given AddressType includes billing.\r\n * @param addressType - The address type to check.\r\n * @returns True if the type is BILLING or BILLING_AND_SHIPPING.\r\n */\r\n static checkIfBillingAddress(addressType: AddressType): boolean {\r\n return addressType === AddressType.BILLING || addressType === AddressType.BILLING_AND_SHIPPING;\r\n }\r\n}"]}
1
+ {"version":3,"sources":["../src/Classes/Address.ts"],"names":["AddressType","AddressModel","BaseModel","data","date","addressType"],"mappings":"qCAEO,IAAKA,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,OAAU,CAAA,SAAA,CACVA,EAAA,QAAW,CAAA,UAAA,CACXA,CAAA,CAAA,oBAAA,CAAuB,kBACvBA,CAAAA,CAAAA,CAAA,IAAO,CAAA,MAAA,CAJGA,OAAA,EA8BSC,CAAAA,CAAAA,CAAAA,CAArB,cAA0CC,CAAU,CACxC,EAAA,CACA,SACA,CAAA,QAAA,CACA,QACA,KACA,CAAA,KAAA,CACA,YACA,CAAA,YAAA,CACA,IACA,CAAA,UAAA,CACA,KACA,CAAA,OAAA,CACA,iBACA,iBAOV,CAAA,WAAA,CAAYC,CAAyBC,CAAAA,CAAAA,CAAa,IAAI,IAAA,CAAQ,CAC5D,KAAA,CAAMD,EAAMC,CAAI,CAAA,CAChB,IAAK,CAAA,EAAA,CAAKD,CAAK,CAAA,EAAA,CACf,IAAK,CAAA,SAAA,CAAYA,EAAK,SACtB,CAAA,IAAA,CAAK,QAAWA,CAAAA,CAAAA,CAAK,QAAY,EAAA,EAAA,CACjC,IAAK,CAAA,OAAA,CAAUA,EAAK,OAAW,EAAA,EAAA,CAC/B,IAAK,CAAA,KAAA,CAAQA,EAAK,KAClB,CAAA,IAAA,CAAK,KAAQA,CAAAA,CAAAA,CAAK,MAClB,IAAK,CAAA,YAAA,CAAeA,CAAK,CAAA,YAAA,CACzB,IAAK,CAAA,YAAA,CAAeA,CAAK,CAAA,YAAA,EAAgB,GACzC,IAAK,CAAA,IAAA,CAAOA,CAAK,CAAA,IAAA,CACjB,IAAK,CAAA,UAAA,CAAaA,CAAK,CAAA,UAAA,CACvB,KAAK,KAAQA,CAAAA,CAAAA,CAAK,KAClB,CAAA,IAAA,CAAK,OAAUA,CAAAA,CAAAA,CAAK,OACpB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,KACd,CAMA,UAAqB,EAAA,CACnB,OAAO,IAAA,CAAK,OACd,CAMA,qBAA+B,CAC7B,OAAO,IAAK,CAAA,gBACd,CAMA,oBAAA,EAAgC,CAC9B,OAAO,KAAK,iBACd,CAMA,cAA8B,EAAA,CAC5B,OAAI,IAAA,CAAK,gBAAoB,EAAA,IAAA,CAAK,kBACzB,kBACE,CAAA,IAAA,CAAK,gBACP,CAAA,SAAA,CACE,IAAK,CAAA,iBAAA,CACP,UAEA,CAAA,MAEX,CAOA,OAAO,sBAAA,CAAuBE,CAAmC,CAAA,CAC/D,OAAOA,CAAAA,GAAgB,UAAwBA,EAAAA,CAAAA,GAAgB,kBACjE,CAOA,OAAO,qBAAsBA,CAAAA,CAAAA,CAAmC,CAC9D,OAAOA,CAAAA,GAAgB,SAAuBA,EAAAA,CAAAA,GAAgB,kBAChE,CACF","file":"chunk-YSUBOEFT.mjs","sourcesContent":["import BaseModel, { BaseAttributes } from \"./Base\";\r\n\r\nexport enum AddressType {\r\n BILLING = \"billing\",\r\n SHIPPING = \"shipping\",\r\n BILLING_AND_SHIPPING = \"billing&shipping\",\r\n NONE = \"none\",\r\n}\r\n\r\nexport type AddressAttributes = BaseAttributes & {\r\n id: string;\r\n firstName: string;\r\n lastName?: string;\r\n company?: string;\r\n phone: string;\r\n email: string;\r\n addressLine1: string;\r\n addressLine2?: string;\r\n city: string;\r\n postalCode: string\r\n state: string;\r\n country: string;\r\n isBillingAddress: boolean;\r\n isShippingAddress: boolean;\r\n};\r\n\r\nexport type AddressData = Required<AddressAttributes>;\r\n\r\n/**\r\n * Represents a physical address associated with a customer or order.\r\n * Handles both billing and shipping address types.\r\n */\r\nexport default class AddressModel extends BaseModel {\r\n protected id: string;\r\n protected firstName: string;\r\n protected lastName: string;\r\n protected company: string;\r\n protected phone: string;\r\n protected email: string;\r\n protected addressLine1: string;\r\n protected addressLine2: string;\r\n protected city: string;\r\n protected postalCode: string\r\n protected state: string;\r\n protected country: string;\r\n protected isBillingAddress: boolean;\r\n protected isShippingAddress: boolean;\r\n\r\n /**\r\n * Creates an instance of AddressModel.\r\n * @param data - The initial address attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: AddressAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.firstName = data.firstName;\r\n this.lastName = data.lastName || '';\r\n this.company = data.company || '';\r\n this.phone = data.phone;\r\n this.email = data.email;\r\n this.addressLine1 = data.addressLine1;\r\n this.addressLine2 = data.addressLine2 || '';\r\n this.city = data.city;\r\n this.postalCode = data.postalCode;\r\n this.state = data.state;\r\n this.country = data.country;\r\n this.isBillingAddress = data.isBillingAddress;\r\n this.isShippingAddress = data.isShippingAddress;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the address's current state.\r\n * Includes all address fields and base model fields.\r\n * @returns AddressData object suitable for serialization or API responses.\r\n */\r\n getDetails(): AddressData {\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n firstName: this.getFirstName(),\r\n lastName: this.getLastName(),\r\n company: this.getCompany(),\r\n phone: this.getPhone(),\r\n email: this.getEmail(),\r\n addressLine1: this.getAddressLine1(),\r\n addressLine2: this.getAddressLine2(),\r\n city: this.getCity(),\r\n postalCode: this.getPostalCode(),\r\n state: this.getState(),\r\n country: this.getCountry(),\r\n isBillingAddress: this.getIsBillingAddress(),\r\n isShippingAddress: this.getIsShippingAddress(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for the address.\r\n * @returns The address ID.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the first name associated with the address.\r\n * @returns The first name.\r\n */\r\n getFirstName(): string {\r\n return this.firstName;\r\n }\r\n\r\n /**\r\n * Gets the last name associated with the address.\r\n * @returns The last name.\r\n */\r\n getLastName(): string {\r\n return this.lastName;\r\n }\r\n\r\n /**\r\n * Gets the company name associated with the address.\r\n * @returns The company name.\r\n */\r\n getCompany(): string {\r\n return this.company;\r\n }\r\n\r\n /**\r\n * Gets the phone number associated with the address.\r\n * @returns The phone number.\r\n */\r\n getPhone(): string {\r\n return this.phone;\r\n }\r\n\r\n /**\r\n * Gets the email address associated with the address.\r\n * @returns The email address.\r\n */\r\n getEmail(): string {\r\n return this.email;\r\n }\r\n\r\n /**\r\n * Gets the primary address line (e.g., street address).\r\n * @returns The first address line.\r\n */\r\n getAddressLine1(): string {\r\n return this.addressLine1;\r\n }\r\n\r\n /**\r\n * Gets the secondary address line (e.g., apartment, suite).\r\n * Returns an empty string if not provided.\r\n * @returns The second address line or an empty string.\r\n */\r\n getAddressLine2(): string {\r\n return this.addressLine2;\r\n }\r\n\r\n /**\r\n * Gets the city name.\r\n * @returns The city.\r\n */\r\n getCity(): string {\r\n return this.city;\r\n }\r\n\r\n /**\r\n * Gets the postal code (e.g., ZIP code).\r\n * @returns The postal code.\r\n */\r\n getPostalCode(): string {\r\n return this.postalCode;\r\n }\r\n\r\n /**\r\n * Gets the state, province, or region.\r\n * @returns The state.\r\n */\r\n getState(): string {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the country name or code.\r\n * @returns The country.\r\n */\r\n getCountry(): string {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Checks if this address is designated as a billing address.\r\n * @returns True if it's a billing address, false otherwise.\r\n */\r\n getIsBillingAddress(): boolean {\r\n return this.isBillingAddress;\r\n }\r\n\r\n /**\r\n * Checks if this address is designated as a shipping address.\r\n * @returns True if it's a shipping address, false otherwise.\r\n */\r\n getIsShippingAddress(): boolean {\r\n return this.isShippingAddress;\r\n }\r\n\r\n /**\r\n * Determines the type of the address based on its billing and shipping flags.\r\n * @returns The AddressType enum value representing the address's role.\r\n */\r\n getAddressType(): AddressType {\r\n if (this.isBillingAddress && this.isShippingAddress) {\r\n return AddressType.BILLING_AND_SHIPPING;\r\n } else if (this.isBillingAddress) {\r\n return AddressType.BILLING;\r\n } else if (this.isShippingAddress) {\r\n return AddressType.SHIPPING;\r\n } else {\r\n return AddressType.NONE;\r\n }\r\n }\r\n\r\n /**\r\n * Static method to check if a given AddressType includes shipping.\r\n * @param addressType - The address type to check.\r\n * @returns True if the type is SHIPPING or BILLING_AND_SHIPPING.\r\n */\r\n static checkIfShippingAddress(addressType: AddressType): boolean {\r\n return addressType === AddressType.SHIPPING || addressType === AddressType.BILLING_AND_SHIPPING;\r\n }\r\n\r\n /**\r\n * Static method to check if a given AddressType includes billing.\r\n * @param addressType - The address type to check.\r\n * @returns True if the type is BILLING or BILLING_AND_SHIPPING.\r\n */\r\n static checkIfBillingAddress(addressType: AddressType): boolean {\r\n return addressType === AddressType.BILLING || addressType === AddressType.BILLING_AND_SHIPPING;\r\n }\r\n}"]}
@@ -1,2 +1,2 @@
1
- import {a as a$2}from'./chunk-ZVLJ5BAG.mjs';import {e}from'./chunk-72DR3HF2.mjs';import {b as b$1}from'./chunk-7LEGYAOJ.mjs';import {f as f$1,c}from'./chunk-DGFO2MH6.mjs';import {a as a$1}from'./chunk-55SOBG62.mjs';import K from'crypto';var y=new Uint8Array(256),h=y.length;function I(){return h>y.length-16&&(K.randomFillSync(y),h=0),y.slice(h,h+=16)}var z=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function $(t){return typeof t=="string"&&z.test(t)}var U=$;var n=[];for(let t=0;t<256;++t)n.push((t+256).toString(16).slice(1));function b(t,e=0){return n[t[e+0]]+n[t[e+1]]+n[t[e+2]]+n[t[e+3]]+"-"+n[t[e+4]]+n[t[e+5]]+"-"+n[t[e+6]]+n[t[e+7]]+"-"+n[t[e+8]]+n[t[e+9]]+"-"+n[t[e+10]]+n[t[e+11]]+n[t[e+12]]+n[t[e+13]]+n[t[e+14]]+n[t[e+15]]}function k(t){if(!U(t))throw TypeError("Invalid UUID");let e,i=new Uint8Array(16);return i[0]=(e=parseInt(t.slice(0,8),16))>>>24,i[1]=e>>>16&255,i[2]=e>>>8&255,i[3]=e&255,i[4]=(e=parseInt(t.slice(9,13),16))>>>8,i[5]=e&255,i[6]=(e=parseInt(t.slice(14,18),16))>>>8,i[7]=e&255,i[8]=(e=parseInt(t.slice(19,23),16))>>>8,i[9]=e&255,i[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,i[11]=e/4294967296&255,i[12]=e>>>24&255,i[13]=e>>>16&255,i[14]=e>>>8&255,i[15]=e&255,i}var M=k;function V(t){t=unescape(encodeURIComponent(t));let e=[];for(let i=0;i<t.length;++i)e.push(t.charCodeAt(i));return e}var G="6ba7b810-9dad-11d1-80b4-00c04fd430c8",B="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function x(t,e,i){function r(o,s,u,S){var A;if(typeof o=="string"&&(o=V(o)),typeof s=="string"&&(s=M(s)),((A=s)===null||A===void 0?void 0:A.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let g=new Uint8Array(16+o.length);if(g.set(s),g.set(o,s.length),g=i(g),g[6]=g[6]&15|e,g[8]=g[8]&63|128,u){S=S||0;for(let m=0;m<16;++m)u[S+m]=g[m];return u}return b(g)}try{r.name=t;}catch{}return r.DNS=G,r.URL=B,r}var L={randomUUID:K.randomUUID};function j(t,e,i){if(L.randomUUID&&!e&&!t)return L.randomUUID();t=t||{};let r=t.random||(t.rng||I)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){i=i||0;for(let o=0;o<16;++o)e[i+o]=r[o];return e}return b(r)}var D=j;function Z(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),K.createHash("sha1").update(t).digest()}var R=Z;var q=x("v5",80,R),P=q;var O={isUUID:t=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t),isEmail:t=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t),isURL:t=>/^(http|https):\/\/[^ "]+$/.test(t),generateUUID:(t,e)=>e&&t?P(t,e):D(),generateSearchId:(t,e)=>`${t}#${f.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:t=>{let[e,i]=t.split("#");return {key:e,selectionAttributes:f.parseSelectionAttributesKey(i)}},deepClone(t){return structuredClone(t)}},a=O;var f=class t extends a$1{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new f$1("Selection attributes must be an object");return Object.keys(e).filter(r=>e[r]!==void 0&&r.toLowerCase()!=="size").sort().map(r=>e[r].name?`${r}:c+${e[r].name}`:`${r}:${e[r]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let i={},r=e.split("|");for(let o of r){let[s,u]=o.split(":");u.startsWith("c+")?i[s]={name:u.slice(2)}:i[s]=u;}return i}catch(i){throw new f$1(i?.message)}}constructor(e,i=new Date){super(e,i),this.id=e.id,this.key=e.key,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((o,s)=>(e.pricing[s]&&(o[s]=new a$2(e.pricing[s])),o),{}),this.targetGender=e.targetGender,this.attributes=a.deepClone(e.attributes),this.specifications=a.deepClone(e.specifications),this.categories=a.deepClone(e.categories);let r=new Set;this.variants=(e.variants||[]).map(o=>{if(!o.selectionAttributes||typeof o.selectionAttributes!="object")throw new f$1("Selection attributes are required");this.checkSelectionAttributes(o.selectionAttributes);let s=t.generateSelectionAttributesKey(o.selectionAttributes);if(r.has(s))throw new c(s);return r.add(s),{sku:o.sku,selectionAttributes:o.selectionAttributes,images:{primary:new b$1(o.images.primary),gallery:(o.images.gallery||[]).map(u=>new b$1(u))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?a.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e$1){return e$1?this.name[e$1]??this.name[e[e$1]]??this.name.en:a.deepClone(this.name)}getDescription(e$1){return e$1?this.description[e$1]??this.description[e[e$1]]??this.description.en:a.deepClone(this.description)}getSlug(e$1){return e$1?this.slug[e$1]??this.slug[e[e$1]]??this.slug.en:a.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:this.pricing}getAttributes(){return a.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:e.selectionAttributes,images:{primary:e.images.primary,gallery:e.images.gallery}}))}getImagesBySelectionAttributes(e){let i=t.generateSelectionAttributesKey(e),r=this.variants.find(o=>t.generateSelectionAttributesKey(o.selectionAttributes)===i);return r?r.images:null}getImages(e,i){switch(i){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return a.deepClone(this.categories)}getSpecifications(e$1){return e$1?a.deepClone(this.specifications[e$1]??this.specifications[e[e$1]]??this.specifications.en):a.deepClone(this.specifications)}getSearchTags(e$1){return e$1?a.deepClone(this.searchTags[e$1]??this.searchTags[e[e$1]]??this.searchTags.en):a.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((i,r)=>(this.pricing[r]&&(i[r]=this.pricing[r]?.getDetails()),i),{}),attributes:this.getAttributes(),variants:this.variants.map(i=>({sku:i.sku,selectionAttributes:a.deepClone(i.selectionAttributes),images:{primary:i.images.primary.getDetails(),gallery:i.images.gallery.map(r=>r.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new f$1("Selection attributes are required");Object.keys(this.attributes).forEach(i=>{if(i.toLowerCase()==="size")return;let r=this.attributes[i],o=e[i];if(o===void 0)throw new f$1(`Selection attribute '${i}' is missing`);if(typeof r=="string"){if(typeof o!="string"||r!==o)throw new f$1(`Selection attribute '${i}' is invalid`)}else if(Array.isArray(r)){if(r.length>0&&typeof r[0]=="string"){if(typeof o!="string"||!r.includes(o))throw new f$1(`Selection attribute '${i}' is invalid`)}else if(typeof o!="object"||!("name"in o)||r.findIndex(s=>s.name===o.name)<0)throw new f$1(`Selection attribute '${i}' is invalid`)}});}validateSelectionAttribute(e){let i=t.generateSelectionAttributesKey(e);return this.variants.some(r=>t.generateSelectionAttributesKey(r.selectionAttributes)===i)}validateSize(e){return this.attributes.size.includes(e)}};export{a,f as b};//# sourceMappingURL=chunk-K6Q6YDUX.mjs.map
2
- //# sourceMappingURL=chunk-K6Q6YDUX.mjs.map
1
+ import {a as a$1}from'./chunk-ZVLJ5BAG.mjs';import {e}from'./chunk-72DR3HF2.mjs';import {b as b$2}from'./chunk-7LEGYAOJ.mjs';import {f as f$1,c}from'./chunk-DGFO2MH6.mjs';import {b as b$1}from'./chunk-6KCJVEZD.mjs';import K from'crypto';var y=new Uint8Array(256),h=y.length;function I(){return h>y.length-16&&(K.randomFillSync(y),h=0),y.slice(h,h+=16)}var z=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function $(t){return typeof t=="string"&&z.test(t)}var U=$;var n=[];for(let t=0;t<256;++t)n.push((t+256).toString(16).slice(1));function b(t,e=0){return n[t[e+0]]+n[t[e+1]]+n[t[e+2]]+n[t[e+3]]+"-"+n[t[e+4]]+n[t[e+5]]+"-"+n[t[e+6]]+n[t[e+7]]+"-"+n[t[e+8]]+n[t[e+9]]+"-"+n[t[e+10]]+n[t[e+11]]+n[t[e+12]]+n[t[e+13]]+n[t[e+14]]+n[t[e+15]]}function k(t){if(!U(t))throw TypeError("Invalid UUID");let e,i=new Uint8Array(16);return i[0]=(e=parseInt(t.slice(0,8),16))>>>24,i[1]=e>>>16&255,i[2]=e>>>8&255,i[3]=e&255,i[4]=(e=parseInt(t.slice(9,13),16))>>>8,i[5]=e&255,i[6]=(e=parseInt(t.slice(14,18),16))>>>8,i[7]=e&255,i[8]=(e=parseInt(t.slice(19,23),16))>>>8,i[9]=e&255,i[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,i[11]=e/4294967296&255,i[12]=e>>>24&255,i[13]=e>>>16&255,i[14]=e>>>8&255,i[15]=e&255,i}var M=k;function V(t){t=unescape(encodeURIComponent(t));let e=[];for(let i=0;i<t.length;++i)e.push(t.charCodeAt(i));return e}var G="6ba7b810-9dad-11d1-80b4-00c04fd430c8",B="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function x(t,e,i){function r(o,s,u,S){var A;if(typeof o=="string"&&(o=V(o)),typeof s=="string"&&(s=M(s)),((A=s)===null||A===void 0?void 0:A.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let g=new Uint8Array(16+o.length);if(g.set(s),g.set(o,s.length),g=i(g),g[6]=g[6]&15|e,g[8]=g[8]&63|128,u){S=S||0;for(let m=0;m<16;++m)u[S+m]=g[m];return u}return b(g)}try{r.name=t;}catch{}return r.DNS=G,r.URL=B,r}var L={randomUUID:K.randomUUID};function j(t,e,i){if(L.randomUUID&&!e&&!t)return L.randomUUID();t=t||{};let r=t.random||(t.rng||I)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){i=i||0;for(let o=0;o<16;++o)e[i+o]=r[o];return e}return b(r)}var D=j;function Z(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),K.createHash("sha1").update(t).digest()}var R=Z;var q=x("v5",80,R),P=q;var O={isUUID:t=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t),isEmail:t=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t),isURL:t=>/^(http|https):\/\/[^ "]+$/.test(t),generateUUID:(t,e)=>e&&t?P(t,e):D(),generateSearchId:(t,e)=>`${t}#${f.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:t=>{let[e,i]=t.split("#");return {key:e,selectionAttributes:f.parseSelectionAttributesKey(i)}},deepClone(t){return structuredClone(t)}},a=O;var f=class t extends b$1{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new f$1("Selection attributes must be an object");return Object.keys(e).filter(r=>e[r]!==void 0&&r.toLowerCase()!=="size").sort().map(r=>e[r].name?`${r}:c+${e[r].name}`:`${r}:${e[r]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let i={},r=e.split("|");for(let o of r){let[s,u]=o.split(":");u.startsWith("c+")?i[s]={name:u.slice(2)}:i[s]=u;}return i}catch(i){throw new f$1(i?.message)}}constructor(e,i=new Date){super(e,i),this.id=e.id,this.key=e.key,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((o,s)=>(e.pricing[s]&&(o[s]=new a$1(e.pricing[s])),o),{}),this.targetGender=e.targetGender,this.attributes=a.deepClone(e.attributes),this.specifications=a.deepClone(e.specifications),this.categories=a.deepClone(e.categories);let r=new Set;this.variants=(e.variants||[]).map(o=>{if(!o.selectionAttributes||typeof o.selectionAttributes!="object")throw new f$1("Selection attributes are required");this.checkSelectionAttributes(o.selectionAttributes);let s=t.generateSelectionAttributesKey(o.selectionAttributes);if(r.has(s))throw new c(s);return r.add(s),{sku:o.sku,selectionAttributes:o.selectionAttributes,images:{primary:new b$2(o.images.primary),gallery:(o.images.gallery||[]).map(u=>new b$2(u))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?a.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e$1){return e$1?this.name[e$1]??this.name[e[e$1]]??this.name.en:a.deepClone(this.name)}getDescription(e$1){return e$1?this.description[e$1]??this.description[e[e$1]]??this.description.en:a.deepClone(this.description)}getSlug(e$1){return e$1?this.slug[e$1]??this.slug[e[e$1]]??this.slug.en:a.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:this.pricing}getAttributes(){return a.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:e.selectionAttributes,images:{primary:e.images.primary,gallery:e.images.gallery}}))}getImagesBySelectionAttributes(e){let i=t.generateSelectionAttributesKey(e),r=this.variants.find(o=>t.generateSelectionAttributesKey(o.selectionAttributes)===i);return r?r.images:null}getImages(e,i){switch(i){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return a.deepClone(this.categories)}getSpecifications(e$1){return e$1?a.deepClone(this.specifications[e$1]??this.specifications[e[e$1]]??this.specifications.en):a.deepClone(this.specifications)}getSearchTags(e$1){return e$1?a.deepClone(this.searchTags[e$1]??this.searchTags[e[e$1]]??this.searchTags.en):a.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((i,r)=>(this.pricing[r]&&(i[r]=this.pricing[r]?.getDetails()),i),{}),attributes:this.getAttributes(),variants:this.variants.map(i=>({sku:i.sku,selectionAttributes:a.deepClone(i.selectionAttributes),images:{primary:i.images.primary.getDetails(),gallery:i.images.gallery.map(r=>r.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new f$1("Selection attributes are required");Object.keys(this.attributes).forEach(i=>{if(i.toLowerCase()==="size")return;let r=this.attributes[i],o=e[i];if(o===void 0)throw new f$1(`Selection attribute '${i}' is missing`);if(typeof r=="string"){if(typeof o!="string"||r!==o)throw new f$1(`Selection attribute '${i}' is invalid`)}else if(Array.isArray(r)){if(r.length>0&&typeof r[0]=="string"){if(typeof o!="string"||!r.includes(o))throw new f$1(`Selection attribute '${i}' is invalid`)}else if(typeof o!="object"||!("name"in o)||r.findIndex(s=>s.name===o.name)<0)throw new f$1(`Selection attribute '${i}' is invalid`)}});}validateSelectionAttribute(e){let i=t.generateSelectionAttributesKey(e);return this.variants.some(r=>t.generateSelectionAttributesKey(r.selectionAttributes)===i)}validateSize(e){return this.attributes.size.includes(e)}};export{a,f as b};//# sourceMappingURL=chunk-ZAHR3SJ2.mjs.map
2
+ //# sourceMappingURL=chunk-ZAHR3SJ2.mjs.map