b23-lib 3.0.7 → 3.0.9
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.
- package/dist/Auth/index.js +1 -1
- package/dist/Auth/index.js.map +1 -1
- package/dist/Auth/index.mjs +1 -1
- package/dist/Auth/index.mjs.map +1 -1
- package/dist/Classes/Address.js +1 -1
- package/dist/Classes/Address.js.map +1 -1
- package/dist/Classes/Address.mjs +1 -1
- package/dist/Classes/Base.js +1 -1
- package/dist/Classes/Base.js.map +1 -1
- package/dist/Classes/Base.mjs +1 -1
- package/dist/Classes/Cart.js +1 -1
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Cart.mjs.map +1 -1
- package/dist/Classes/Charge.d.mts +53 -2
- package/dist/Classes/Charge.d.ts +53 -2
- package/dist/Classes/Charge.js +1 -1
- package/dist/Classes/Charge.js.map +1 -1
- package/dist/Classes/Charge.mjs +1 -1
- package/dist/Classes/Coupon.js +1 -1
- package/dist/Classes/Coupon.js.map +1 -1
- package/dist/Classes/Coupon.mjs +1 -1
- package/dist/Classes/Customer.js +1 -1
- package/dist/Classes/Customer.js.map +1 -1
- package/dist/Classes/Customer.mjs +1 -1
- package/dist/Classes/Customer.mjs.map +1 -1
- package/dist/Classes/CustomerAddress.js +1 -1
- package/dist/Classes/CustomerAddress.js.map +1 -1
- package/dist/Classes/CustomerAddress.mjs +1 -1
- package/dist/Classes/CustomerAddress.mjs.map +1 -1
- package/dist/Classes/Enum.d.mts +9 -1
- package/dist/Classes/Enum.d.ts +9 -1
- package/dist/Classes/Enum.js +1 -1
- package/dist/Classes/Enum.js.map +1 -1
- package/dist/Classes/Enum.mjs +1 -1
- package/dist/Classes/Inventory.js +1 -1
- package/dist/Classes/Inventory.js.map +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/Inventory.mjs.map +1 -1
- package/dist/Classes/LineItem.js +1 -1
- package/dist/Classes/LineItem.js.map +1 -1
- package/dist/Classes/LineItem.mjs +1 -1
- package/dist/Classes/Order.js +1 -1
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/Order.mjs.map +1 -1
- package/dist/Classes/Payment.js +1 -1
- package/dist/Classes/Payment.js.map +1 -1
- package/dist/Classes/Payment.mjs +1 -1
- package/dist/Classes/Payment.mjs.map +1 -1
- package/dist/Classes/Price.js +1 -1
- package/dist/Classes/Price.js.map +1 -1
- package/dist/Classes/Price.mjs +1 -1
- package/dist/Classes/Product.js +1 -1
- package/dist/Classes/Product.js.map +1 -1
- package/dist/Classes/Product.mjs +1 -1
- package/dist/Classes/ShoppingContainer.d.mts +4 -0
- package/dist/Classes/ShoppingContainer.d.ts +4 -0
- package/dist/Classes/ShoppingContainer.js +1 -1
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/Classes/TaxRule.js.map +1 -1
- package/dist/Classes/TaxRule.mjs +1 -1
- package/dist/Classes/TieredPrice.js +1 -1
- package/dist/Classes/TieredPrice.js.map +1 -1
- package/dist/Classes/TieredPrice.mjs +1 -1
- package/dist/chunk-2QHUEAZR.mjs +2 -0
- package/dist/chunk-2QHUEAZR.mjs.map +1 -0
- package/dist/{chunk-XHGUVYQO.mjs → chunk-3HKY6ZOF.mjs} +2 -2
- package/dist/{chunk-XHGUVYQO.mjs.map → chunk-3HKY6ZOF.mjs.map} +1 -1
- package/dist/chunk-4ZFZXWD7.mjs +2 -0
- package/dist/chunk-4ZFZXWD7.mjs.map +1 -0
- package/dist/chunk-GFMGTV5E.mjs +2 -0
- package/dist/chunk-GFMGTV5E.mjs.map +1 -0
- package/dist/{chunk-R3ZADSUJ.mjs → chunk-HX32EJ3F.mjs} +2 -2
- package/dist/{chunk-R3ZADSUJ.mjs.map → chunk-HX32EJ3F.mjs.map} +1 -1
- package/dist/{chunk-L3CNGDFJ.mjs → chunk-JCUHTCOC.mjs} +2 -2
- package/dist/{chunk-L3CNGDFJ.mjs.map → chunk-JCUHTCOC.mjs.map} +1 -1
- package/dist/chunk-OAE2FJFJ.mjs +2 -0
- package/dist/chunk-OAE2FJFJ.mjs.map +1 -0
- package/dist/{chunk-XBFSNBKL.mjs → chunk-QLYPJDDV.mjs} +2 -2
- package/dist/{chunk-XBFSNBKL.mjs.map → chunk-QLYPJDDV.mjs.map} +1 -1
- package/dist/chunk-UXZBULDS.mjs +2 -0
- package/dist/chunk-UXZBULDS.mjs.map +1 -0
- package/dist/chunk-Z3CF4K5C.mjs +2 -0
- package/dist/{chunk-IQNK7EEI.mjs.map → chunk-Z3CF4K5C.mjs.map} +1 -1
- package/dist/chunk-ZZ3B7OGM.mjs +2 -0
- package/dist/{chunk-RHSKHT5F.mjs.map → chunk-ZZ3B7OGM.mjs.map} +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-FC4P26U3.mjs +0 -2
- package/dist/chunk-FC4P26U3.mjs.map +0 -1
- package/dist/chunk-GJ2DSRIP.mjs +0 -2
- package/dist/chunk-GJ2DSRIP.mjs.map +0 -1
- package/dist/chunk-HKXV6QWV.mjs +0 -2
- package/dist/chunk-HKXV6QWV.mjs.map +0 -1
- package/dist/chunk-IQNK7EEI.mjs +0 -2
- package/dist/chunk-RHSKHT5F.mjs +0 -2
- package/dist/chunk-URFRPQCT.mjs +0 -2
- package/dist/chunk-URFRPQCT.mjs.map +0 -1
package/dist/Classes/Cart.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'../chunk-
|
|
1
|
+
import {a}from'../chunk-2QHUEAZR.mjs';import'../chunk-ZZ3B7OGM.mjs';import'../chunk-HX32EJ3F.mjs';import'../chunk-4ZFZXWD7.mjs';import'../chunk-JCUHTCOC.mjs';import'../chunk-Z3CF4K5C.mjs';import {b}from'../chunk-OAE2FJFJ.mjs';import'../chunk-QLYPJDDV.mjs';import'../chunk-3HKY6ZOF.mjs';import'../chunk-GFMGTV5E.mjs';import'../chunk-RSTZJZSQ.mjs';import {a as a$1}from'../chunk-XPKK6DFA.mjs';import'../chunk-UXZBULDS.mjs';var u=(i=>(i.ACTIVE="ACTIVE",i.FROZEN="FROZEN",i.MERGED="MERGED",i.ORDERED="ORDERED",i))(u||{}),p={expiresAtInSeconds:120*24*60*60},c=class extends a{state;expireAt;config;constructor(t,e=new Date,r=p){super(t,e),this.state=t.state,this.expireAt=t.expireAt&&typeof t.expireAt=="number"?t.expireAt:Math.floor(e.getTime()/1e3)+r.expiresAtInSeconds,this.config=r;}getState(){return this.state}getExpireAt(){return this.expireAt}isActive(){let t=Math.ceil(Date.now()/1e3);return this.state==="ACTIVE"&&this.expireAt>t}clearCartItems(){this.lineItems=[],this.coupons=[],this.shippingDetails=null,this.total.discounts={},this.calculateTotals();}validateLineItems(t){this.lineItems=this.lineItems.map(e=>{try{e.updateProductData(t[e.getProductKey()],this.country,this.currency);}catch(r){console.error(`Error recalculating line item ${e.getId()}:`,r),e.clearLineItem();}return e}).filter(e=>e.getId()),this.calculateTotals();}addLineItem(t){let e=t.getProductKey(),r=t.getSelectionAttributes(),i=b.generateSelectionAttributesKey(r),s=this.lineItems.findIndex(n=>n.getProductKey()===e&&b.generateSelectionAttributesKey(n.getSelectionAttributes())===i);return s>=0?this.lineItems[s].addSubItems(t.getSubItems(),!0):this.lineItems.push(t),this.calculateTotals(),s>=0?s:this.lineItems.length-1}updateLineItem(t,e,r){let i=this.lineItems,s=i.findIndex(n=>n.getId()===t);if(s<0)throw new a$1(t);return i[s].addSubItems([{size:e,quantity:r}],!1),this.calculateTotals(),s}removeLineItem(t){let r=this.lineItems.findIndex(i=>i.getId()===t);if(r<0)throw new a$1(t);return this.lineItems.splice(r,1),this.charges=this.charges.filter(i=>i.getLineItemId()!==t),this.calculateTotals(),r}getDetails(){return {...super.getDetails(),state:this.getState(),expireAt:this.getExpireAt()}}};export{u as CartState,p as DEFAULT_CART_CONFIG,c as default};//# sourceMappingURL=Cart.mjs.map
|
|
2
2
|
//# sourceMappingURL=Cart.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/Classes/Cart.ts"],"names":["CartState","DEFAULT_CART_CONFIG","CartModel","BaseShoppingContainerModel","data","date","config","nowSeconds","products","lineItem","error","newLineItem","productKey","selectionAttributes","selectionAttributeKey","ProductModel","index","item","lineItemId","size","quantity","lineItems","LineItemNotFoundError","charge"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../../src/Classes/Cart.ts"],"names":["CartState","DEFAULT_CART_CONFIG","CartModel","BaseShoppingContainerModel","data","date","config","nowSeconds","products","lineItem","error","newLineItem","productKey","selectionAttributes","selectionAttributeKey","ProductModel","index","item","lineItemId","size","quantity","lineItems","LineItemNotFoundError","charge"],"mappings":"qaAKO,IAAKA,OACVA,CAAA,CAAA,MAAA,CAAS,QACTA,CAAAA,CAAAA,CAAA,OAAS,QACTA,CAAAA,CAAAA,CAAA,MAAS,CAAA,QAAA,CACTA,EAAA,OAAU,CAAA,SAAA,CAJAA,OAAA,EAwBCC,CAAAA,CAAAA,CAAAA,CAAkC,CAC7C,kBAAoB,CAAA,GAAA,CAAM,EAAK,CAAA,EAAA,CAAK,EACtC,CAEqBC,CAAAA,CAAAA,CAArB,cAAuCC,CAA2B,CACtD,MACA,QACA,CAAA,MAAA,CAEV,WAAYC,CAAAA,CAAAA,CAAsBC,EAAa,IAAI,IAAA,CAAQC,EAAqBL,CAAqB,CAAA,CACnG,MAAMG,CAAMC,CAAAA,CAAI,CAChB,CAAA,IAAA,CAAK,MAAQD,CAAK,CAAA,KAAA,CAClB,KAAK,QAAWA,CAAAA,CAAAA,CAAK,UAAY,OAAOA,CAAAA,CAAK,QAAa,EAAA,QAAA,CAAWA,EAAK,QAAW,CAAA,IAAA,CAAK,MAAMC,CAAK,CAAA,OAAA,GAAY,GAAI,CAAA,CAAIC,CAAO,CAAA,kBAAA,CAChI,KAAK,MAASA,CAAAA,EAChB,CAMO,QAAsB,EAAA,CAC3B,OAAO,IAAK,CAAA,KACd,CAMO,WAAA,EAAsB,CAC3B,OAAO,IAAA,CAAK,QACd,CAMO,QAAA,EAAoB,CACzB,IAAMC,CAAAA,CAAa,IAAK,CAAA,IAAA,CAAK,KAAK,GAAI,EAAA,CAAI,GAAI,CAC9C,CAAA,OAAO,KAAK,KAAU,GAAA,QAAA,EAAqB,IAAK,CAAA,QAAA,CAAWA,CAC7D,CAKO,cAAA,EAAiB,CACtB,IAAK,CAAA,SAAA,CAAY,EACjB,CAAA,IAAA,CAAK,OAAU,CAAA,GACf,IAAK,CAAA,eAAA,CAAkB,KACvB,IAAK,CAAA,KAAA,CAAM,UAAY,EAAC,CACxB,IAAK,CAAA,eAAA,GACP,CAOO,iBAAA,CAAkBC,EAA8C,CACrE,IAAA,CAAK,UAAY,IAAK,CAAA,SAAA,CAAU,GAAIC,CAAAA,CAAAA,EAAY,CAC9C,GAAI,CACFA,EAAS,iBAAkBD,CAAAA,CAAAA,CAASC,EAAS,aAAc,EAAC,CAAG,CAAA,IAAA,CAAK,QAAS,IAAK,CAAA,QAAQ,EAC5F,CAASC,MAAAA,CAAAA,CAAO,CACd,OAAQ,CAAA,KAAA,CAAM,CAAiCD,8BAAAA,EAAAA,CAAAA,CAAS,OAAO,CAAA,CAAA,CAAA,CAAKC,CAAK,CACzED,CAAAA,CAAAA,CAAS,gBACX,CACA,OAAOA,CACT,CAAC,CAAE,CAAA,MAAA,CAAOA,GAAYA,CAAS,CAAA,KAAA,EAAO,CAEtC,CAAA,IAAA,CAAK,eAAgB,GACvB,CAOO,WAAYE,CAAAA,CAAAA,CAA4B,CAC7C,IAAMC,EAAaD,CAAY,CAAA,aAAA,EACzBE,CAAAA,CAAAA,CAAsBF,EAAY,sBAAuB,EAAA,CACzDG,EAAwBC,CAAa,CAAA,8BAAA,CAA+BF,CAAmB,CACzFG,CAAAA,CAAAA,CAAQ,IAAK,CAAA,SAAA,CAAU,UACxBC,CAASA,EAAAA,CAAAA,CAAK,eAAoBL,GAAAA,CAAAA,EAAcG,EAAa,8BAA+BE,CAAAA,CAAAA,CAAK,sBAAuB,EAAC,IAAMH,CAClI,CAAA,CAEA,OAAIE,CAAS,EAAA,CAAA,CACX,KAAK,SAAUA,CAAAA,CAAK,CAAE,CAAA,WAAA,CAAYL,EAAY,WAAY,EAAA,CAAG,EAAI,CAEjE,CAAA,IAAA,CAAK,UAAU,IAAKA,CAAAA,CAAW,CAGjC,CAAA,IAAA,CAAK,iBACEK,CAAAA,CAAAA,EAAS,EAAIA,CAAQ,CAAA,IAAA,CAAK,UAAU,MAAS,CAAA,CACtD,CAUO,cAAA,CAAeE,EAAoBC,CAAcC,CAAAA,CAAAA,CAAkB,CACxE,IAAMC,CAAAA,CAAY,KAAK,SACnBL,CAAAA,CAAAA,CAAQK,CAAU,CAAA,SAAA,CAAWJ,GAASA,CAAK,CAAA,KAAA,KAAYC,CAAU,CAAA,CAErE,GAAIF,CAAQ,CAAA,CAAA,CACV,MAAM,IAAIM,IAAsBJ,CAAU,CAAA,CAG5C,OAAAG,CAAUL,CAAAA,CAAK,EAAE,WAAY,CAAA,CAAC,CAAE,IAAA,CAAAG,EAAM,QAAAC,CAAAA,CAAS,CAAC,CAAG,CAAA,CAAA,CAAK,EACxD,IAAK,CAAA,eAAA,EAEEJ,CAAAA,CACT,CAQO,cAAeE,CAAAA,CAAAA,CAAoB,CAExC,IAAMF,CAAAA,CADY,KAAK,SACC,CAAA,SAAA,CAAWC,CAASA,EAAAA,CAAAA,CAAK,OAAYC,GAAAA,CAAU,EAEvE,GAAIF,CAAAA,CAAQ,EACV,MAAM,IAAIM,GAAsBJ,CAAAA,CAAU,EAG5C,OAAK,IAAA,CAAA,SAAA,CAAU,OAAOF,CAAO,CAAA,CAAC,EAC9B,IAAK,CAAA,OAAA,CAAU,IAAK,CAAA,OAAA,CAAQ,OAAOO,CAAUA,EAAAA,CAAAA,CAAO,eAAoBL,GAAAA,CAAU,EAClF,IAAK,CAAA,eAAA,EAEEF,CAAAA,CACT,CAEA,UAAuB,EAAA,CACrB,OAAO,CACL,GAAG,MAAM,UAAW,EAAA,CACpB,KAAO,CAAA,IAAA,CAAK,UACZ,CAAA,QAAA,CAAU,KAAK,WAAY,EAC7B,CACF,CACF","file":"Cart.mjs","sourcesContent":["import { LineItemNotFoundError } from \"./Error\";\r\nimport LineItemModel from \"./LineItem\";\r\nimport ProductModel from \"./Product\";\r\nimport BaseShoppingContainerModel, { BaseShoppingContainerAttributes, BaseShoppingContainerData } from \"./ShoppingContainer\";\r\n\r\nexport enum CartState {\r\n ACTIVE = \"ACTIVE\",\r\n FROZEN = \"FROZEN\",\r\n MERGED = \"MERGED\",\r\n ORDERED = \"ORDERED\"\r\n}\r\n\r\n/**\r\n * Input attributes for creating or updating a CartModel.\r\n */\r\nexport type CartAttributes = BaseShoppingContainerAttributes & {\r\n state: CartState;\r\n expireAt: number;\r\n};\r\n\r\nexport type CartData = BaseShoppingContainerData & {\r\n state: CartState;\r\n expireAt: number;\r\n};\r\n\r\nexport type CartConfig = {\r\n expiresAtInSeconds: number;\r\n}\r\n\r\nexport const DEFAULT_CART_CONFIG: CartConfig = {\r\n expiresAtInSeconds: 120 * 24 * 60 * 60\r\n}\r\n\r\nexport default class CartModel extends BaseShoppingContainerModel {\r\n protected state: CartState;\r\n protected expireAt: number;\r\n protected config: CartConfig;\r\n\r\n constructor(data: CartAttributes, date: Date = new Date(), config: CartConfig = DEFAULT_CART_CONFIG) {\r\n super(data, date);\r\n this.state = data.state;\r\n this.expireAt = data.expireAt && typeof data.expireAt === 'number' ? data.expireAt : Math.floor(date.getTime() / 1000) + config.expiresAtInSeconds;\r\n this.config = config;\r\n }\r\n\r\n /**\r\n * Gets the current state of the cart (e.g., ACTIVE, ORDERED).\r\n * @returns The CartState enum value.\r\n */\r\n public getState(): CartState {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the timestamp when the cart expires.\r\n * @returns The expiration timestamp in seconds (Unix epoch).\r\n */\r\n public getExpireAt(): number {\r\n return this.expireAt;\r\n }\r\n\r\n /**\r\n * Checks if the cart is currently active and not expired.\r\n * @returns True if active and not expired, false otherwise.\r\n */\r\n public isActive(): boolean {\r\n const nowSeconds = Math.ceil(Date.now() / 1000);\r\n return this.state === CartState.ACTIVE && (this.expireAt > nowSeconds);\r\n }\r\n\r\n /**\r\n * Clears all line items, coupons, and shipping details from the cart and resets totals.\r\n */\r\n public clearCartItems() {\r\n this.lineItems = [];\r\n this.coupons = [];\r\n this.shippingDetails = null;\r\n this.total.discounts = {};\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Validates line items against the current product catalog.\r\n * Updates product data for each item and removes invalid items.\r\n * @param products - A record map of ProductModels keyed by product ID/key.\r\n */\r\n public validateLineItems(products: Record<string, ProductModel>): void {\r\n this.lineItems = this.lineItems.map(lineItem => {\r\n try {\r\n lineItem.updateProductData(products[lineItem.getProductKey()], this.country, this.currency);\r\n } catch (error) {\r\n console.error(`Error recalculating line item ${lineItem.getId()}:`, error);\r\n lineItem.clearLineItem();\r\n }\r\n return lineItem;\r\n }).filter(lineItem => lineItem.getId());\r\n\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Adds a new line item or updates the quantity of an existing one.\r\n * @param newLineItem The LineItemModel to add.\r\n * @returns The index of the added/updated line item in the internal array.\r\n */\r\n public addLineItem(newLineItem: LineItemModel) {\r\n const productKey = newLineItem.getProductKey();\r\n const selectionAttributes = newLineItem.getSelectionAttributes();\r\n const selectionAttributeKey = ProductModel.generateSelectionAttributesKey(selectionAttributes);\r\n let index = this.lineItems.findIndex(\r\n (item) => item.getProductKey() === productKey && ProductModel.generateSelectionAttributesKey(item.getSelectionAttributes()) === selectionAttributeKey\r\n );\r\n\r\n if (index >= 0) {\r\n this.lineItems[index].addSubItems(newLineItem.getSubItems(), true);\r\n } else {\r\n this.lineItems.push(newLineItem);\r\n }\r\n\r\n this.calculateTotals();\r\n return index >= 0 ? index : this.lineItems.length - 1;\r\n }\r\n\r\n /**\r\n * Updates the quantity for a specific size within a line item.\r\n * @param lineItemId The ID of the LineItemModel to update.\r\n * @param size The size identifier within the line item.\r\n * @param quantity The new quantity for the size (0 to remove).\r\n * @returns The index of the updated line item.\r\n * @throws {Error} If the line item is not found.\r\n */\r\n public updateLineItem(lineItemId: string, size: string, quantity: number) {\r\n const lineItems = this.lineItems;\r\n let index = lineItems.findIndex((item) => item.getId() === lineItemId);\r\n\r\n if (index < 0) {\r\n throw new LineItemNotFoundError(lineItemId);\r\n }\r\n\r\n lineItems[index].addSubItems([{ size, quantity }], false);\r\n this.calculateTotals();\r\n\r\n return index;\r\n }\r\n\r\n /**\r\n * Removes a line item completely from the cart.\r\n * @param lineItemId The ID of the LineItemModel to remove.\r\n * @returns The index the item previously occupied.\r\n * @throws {Error} If the line item is not found.\r\n */\r\n public removeLineItem(lineItemId: string) {\r\n const lineItems = this.lineItems;\r\n const index = lineItems.findIndex((item) => item.getId() === lineItemId);\r\n\r\n if (index < 0) {\r\n throw new LineItemNotFoundError(lineItemId);\r\n }\r\n\r\n this.lineItems.splice(index, 1);\r\n this.charges = this.charges.filter(charge => charge.getLineItemId() !== lineItemId);\r\n this.calculateTotals();\r\n\r\n return index;\r\n }\r\n\r\n getDetails(): CartData {\r\n return {\r\n ...super.getDetails(),\r\n state: this.getState(),\r\n expireAt: this.getExpireAt(),\r\n }\r\n }\r\n}\r\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CustomFieldAttributes, CustomFieldModel } from './Base.mjs';
|
|
2
2
|
import { b as PriceData, c as PriceModel, d as LocalizedString, L as LocaleCode } from '../Common-XM4zQpWC.mjs';
|
|
3
|
-
import { TaxSystem, ChargeType } from './Enum.mjs';
|
|
3
|
+
import { TaxSystem, ChargeType, ChargeImpact, ChargeTaxTreatment } from './Enum.mjs';
|
|
4
4
|
import { FixedTaxRuleData, FixedTaxRuleModel } from './TaxRule.mjs';
|
|
5
5
|
import CouponModel from './Coupon.mjs';
|
|
6
6
|
import '../Auth/index.mjs';
|
|
@@ -48,11 +48,15 @@ type ChargeAttributes = CustomFieldAttributes & {
|
|
|
48
48
|
category: string;
|
|
49
49
|
lineItemId?: string;
|
|
50
50
|
chargeType: ChargeType;
|
|
51
|
+
impact?: ChargeImpact;
|
|
52
|
+
taxTreatment?: ChargeTaxTreatment;
|
|
51
53
|
pricing: ChargePricing;
|
|
52
54
|
total: ChargeTotals;
|
|
53
55
|
};
|
|
54
|
-
type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId'> & {
|
|
56
|
+
type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId' | 'impact' | 'taxTreatment'> & {
|
|
55
57
|
lineItemId?: string;
|
|
58
|
+
impact?: ChargeImpact;
|
|
59
|
+
taxTreatment?: ChargeTaxTreatment;
|
|
56
60
|
};
|
|
57
61
|
/**
|
|
58
62
|
* Represents an additional charge (or discount if amount is negative) in a shopping container.
|
|
@@ -64,6 +68,8 @@ declare class ChargeModel extends CustomFieldModel {
|
|
|
64
68
|
protected category: string;
|
|
65
69
|
protected lineItemId?: string;
|
|
66
70
|
protected chargeType: ChargeType;
|
|
71
|
+
protected impact: ChargeImpact;
|
|
72
|
+
protected taxTreatment: ChargeTaxTreatment;
|
|
67
73
|
protected pricing: {
|
|
68
74
|
price: PriceModel;
|
|
69
75
|
taxCategory: string;
|
|
@@ -71,6 +77,10 @@ declare class ChargeModel extends CustomFieldModel {
|
|
|
71
77
|
};
|
|
72
78
|
protected total: ChargeTotalsModel;
|
|
73
79
|
constructor(data: ChargeAttributes);
|
|
80
|
+
/**
|
|
81
|
+
* Gets the unique identifier of the charge.
|
|
82
|
+
* @returns
|
|
83
|
+
*/
|
|
74
84
|
getId(): string;
|
|
75
85
|
/**
|
|
76
86
|
* Gets the full localized product name object.
|
|
@@ -83,15 +93,49 @@ declare class ChargeModel extends CustomFieldModel {
|
|
|
83
93
|
* @returns The name string for the specified locale.
|
|
84
94
|
*/
|
|
85
95
|
getName(locale: LocaleCode): string;
|
|
96
|
+
/**
|
|
97
|
+
* Gets the charge category.
|
|
98
|
+
* @returns The category string.
|
|
99
|
+
*/
|
|
86
100
|
getCategory(): string;
|
|
101
|
+
/**
|
|
102
|
+
* Gets the charge type.
|
|
103
|
+
* @returns The charge type enum value.
|
|
104
|
+
*/
|
|
87
105
|
getChargeType(): ChargeType;
|
|
106
|
+
/**
|
|
107
|
+
* Gets the charge impact (add or subtract).
|
|
108
|
+
* @returns The charge impact.
|
|
109
|
+
*/
|
|
110
|
+
getImpact(): ChargeImpact;
|
|
111
|
+
/**
|
|
112
|
+
* Gets how tax is treated for this charge.
|
|
113
|
+
* @returns The tax treatment for this charge.
|
|
114
|
+
*/
|
|
115
|
+
getTaxTreatment(): ChargeTaxTreatment;
|
|
116
|
+
/**
|
|
117
|
+
* Gets the related line item id, if any.
|
|
118
|
+
* @returns The line item id or undefined.
|
|
119
|
+
*/
|
|
88
120
|
getLineItemId(): string | undefined;
|
|
121
|
+
/**
|
|
122
|
+
* Gets the pricing details (models) for this charge.
|
|
123
|
+
* @returns Pricing details including price, tax category, and tax rules.
|
|
124
|
+
*/
|
|
89
125
|
getPricing(): {
|
|
90
126
|
price: PriceModel;
|
|
91
127
|
taxCategory: string;
|
|
92
128
|
applicableTaxRule: FixedTaxRuleModel[];
|
|
93
129
|
};
|
|
130
|
+
/**
|
|
131
|
+
* Gets the computed totals for this charge.
|
|
132
|
+
* @returns Totals including discounts, taxes, and grand total.
|
|
133
|
+
*/
|
|
94
134
|
getTotal(): ChargeTotalsModel;
|
|
135
|
+
/**
|
|
136
|
+
* Gets the applicable tax rules for this charge.
|
|
137
|
+
* @returns A list of tax rules.
|
|
138
|
+
*/
|
|
95
139
|
getApplicableTaxRules(): FixedTaxRuleModel[];
|
|
96
140
|
/**
|
|
97
141
|
* Updates the tax rule for this line item and recalculates totals.
|
|
@@ -107,7 +151,14 @@ declare class ChargeModel extends CustomFieldModel {
|
|
|
107
151
|
coupon: CouponModel;
|
|
108
152
|
amount: PriceModel;
|
|
109
153
|
}[]): void;
|
|
154
|
+
/**
|
|
155
|
+
* Recalculates totals for this charge based on pricing and discounts.
|
|
156
|
+
*/
|
|
110
157
|
calculateTotals(): void;
|
|
158
|
+
/**
|
|
159
|
+
* Gets a plain data object representing this charge.
|
|
160
|
+
* @returns ChargeData for serialization.
|
|
161
|
+
*/
|
|
111
162
|
getDetails(): ChargeData;
|
|
112
163
|
}
|
|
113
164
|
|
package/dist/Classes/Charge.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CustomFieldAttributes, CustomFieldModel } from './Base.js';
|
|
2
2
|
import { b as PriceData, c as PriceModel, d as LocalizedString, L as LocaleCode } from '../Common-uAn7Sunn.js';
|
|
3
|
-
import { TaxSystem, ChargeType } from './Enum.js';
|
|
3
|
+
import { TaxSystem, ChargeType, ChargeImpact, ChargeTaxTreatment } from './Enum.js';
|
|
4
4
|
import { FixedTaxRuleData, FixedTaxRuleModel } from './TaxRule.js';
|
|
5
5
|
import CouponModel from './Coupon.js';
|
|
6
6
|
import '../Auth/index.js';
|
|
@@ -48,11 +48,15 @@ type ChargeAttributes = CustomFieldAttributes & {
|
|
|
48
48
|
category: string;
|
|
49
49
|
lineItemId?: string;
|
|
50
50
|
chargeType: ChargeType;
|
|
51
|
+
impact?: ChargeImpact;
|
|
52
|
+
taxTreatment?: ChargeTaxTreatment;
|
|
51
53
|
pricing: ChargePricing;
|
|
52
54
|
total: ChargeTotals;
|
|
53
55
|
};
|
|
54
|
-
type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId'> & {
|
|
56
|
+
type ChargeData = Omit<Required<ChargeAttributes>, 'lineItemId' | 'impact' | 'taxTreatment'> & {
|
|
55
57
|
lineItemId?: string;
|
|
58
|
+
impact?: ChargeImpact;
|
|
59
|
+
taxTreatment?: ChargeTaxTreatment;
|
|
56
60
|
};
|
|
57
61
|
/**
|
|
58
62
|
* Represents an additional charge (or discount if amount is negative) in a shopping container.
|
|
@@ -64,6 +68,8 @@ declare class ChargeModel extends CustomFieldModel {
|
|
|
64
68
|
protected category: string;
|
|
65
69
|
protected lineItemId?: string;
|
|
66
70
|
protected chargeType: ChargeType;
|
|
71
|
+
protected impact: ChargeImpact;
|
|
72
|
+
protected taxTreatment: ChargeTaxTreatment;
|
|
67
73
|
protected pricing: {
|
|
68
74
|
price: PriceModel;
|
|
69
75
|
taxCategory: string;
|
|
@@ -71,6 +77,10 @@ declare class ChargeModel extends CustomFieldModel {
|
|
|
71
77
|
};
|
|
72
78
|
protected total: ChargeTotalsModel;
|
|
73
79
|
constructor(data: ChargeAttributes);
|
|
80
|
+
/**
|
|
81
|
+
* Gets the unique identifier of the charge.
|
|
82
|
+
* @returns
|
|
83
|
+
*/
|
|
74
84
|
getId(): string;
|
|
75
85
|
/**
|
|
76
86
|
* Gets the full localized product name object.
|
|
@@ -83,15 +93,49 @@ declare class ChargeModel extends CustomFieldModel {
|
|
|
83
93
|
* @returns The name string for the specified locale.
|
|
84
94
|
*/
|
|
85
95
|
getName(locale: LocaleCode): string;
|
|
96
|
+
/**
|
|
97
|
+
* Gets the charge category.
|
|
98
|
+
* @returns The category string.
|
|
99
|
+
*/
|
|
86
100
|
getCategory(): string;
|
|
101
|
+
/**
|
|
102
|
+
* Gets the charge type.
|
|
103
|
+
* @returns The charge type enum value.
|
|
104
|
+
*/
|
|
87
105
|
getChargeType(): ChargeType;
|
|
106
|
+
/**
|
|
107
|
+
* Gets the charge impact (add or subtract).
|
|
108
|
+
* @returns The charge impact.
|
|
109
|
+
*/
|
|
110
|
+
getImpact(): ChargeImpact;
|
|
111
|
+
/**
|
|
112
|
+
* Gets how tax is treated for this charge.
|
|
113
|
+
* @returns The tax treatment for this charge.
|
|
114
|
+
*/
|
|
115
|
+
getTaxTreatment(): ChargeTaxTreatment;
|
|
116
|
+
/**
|
|
117
|
+
* Gets the related line item id, if any.
|
|
118
|
+
* @returns The line item id or undefined.
|
|
119
|
+
*/
|
|
88
120
|
getLineItemId(): string | undefined;
|
|
121
|
+
/**
|
|
122
|
+
* Gets the pricing details (models) for this charge.
|
|
123
|
+
* @returns Pricing details including price, tax category, and tax rules.
|
|
124
|
+
*/
|
|
89
125
|
getPricing(): {
|
|
90
126
|
price: PriceModel;
|
|
91
127
|
taxCategory: string;
|
|
92
128
|
applicableTaxRule: FixedTaxRuleModel[];
|
|
93
129
|
};
|
|
130
|
+
/**
|
|
131
|
+
* Gets the computed totals for this charge.
|
|
132
|
+
* @returns Totals including discounts, taxes, and grand total.
|
|
133
|
+
*/
|
|
94
134
|
getTotal(): ChargeTotalsModel;
|
|
135
|
+
/**
|
|
136
|
+
* Gets the applicable tax rules for this charge.
|
|
137
|
+
* @returns A list of tax rules.
|
|
138
|
+
*/
|
|
95
139
|
getApplicableTaxRules(): FixedTaxRuleModel[];
|
|
96
140
|
/**
|
|
97
141
|
* Updates the tax rule for this line item and recalculates totals.
|
|
@@ -107,7 +151,14 @@ declare class ChargeModel extends CustomFieldModel {
|
|
|
107
151
|
coupon: CouponModel;
|
|
108
152
|
amount: PriceModel;
|
|
109
153
|
}[]): void;
|
|
154
|
+
/**
|
|
155
|
+
* Recalculates totals for this charge based on pricing and discounts.
|
|
156
|
+
*/
|
|
110
157
|
calculateTotals(): void;
|
|
158
|
+
/**
|
|
159
|
+
* Gets a plain data object representing this charge.
|
|
160
|
+
* @returns ChargeData for serialization.
|
|
161
|
+
*/
|
|
111
162
|
getDetails(): ChargeData;
|
|
112
163
|
}
|
|
113
164
|
|
package/dist/Classes/Charge.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var ne=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ne__default=/*#__PURE__*/_interopDefault(ne);var R=new Uint8Array(256),M=R.length;function k(){return M>R.length-16&&(ne__default.default.randomFillSync(R),M=0),R.slice(M,M+=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 oe(r){return typeof r=="string"&&Z.test(r)}var J=oe;var d=[];for(let r=0;r<256;++r)d.push((r+256).toString(16).slice(1));function v(r,e=0){return d[r[e+0]]+d[r[e+1]]+d[r[e+2]]+d[r[e+3]]+"-"+d[r[e+4]]+d[r[e+5]]+"-"+d[r[e+6]]+d[r[e+7]]+"-"+d[r[e+8]]+d[r[e+9]]+"-"+d[r[e+10]]+d[r[e+11]]+d[r[e+12]]+d[r[e+13]]+d[r[e+14]]+d[r[e+15]]}function se(r){if(!J(r))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(r.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(r.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(r.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(r.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var X=se;function ae(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var ce="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ue="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Q(r,e,t){function i(n,o,a,p){var c;if(typeof n=="string"&&(n=ae(n)),typeof o=="string"&&(o=X(o)),((c=o)===null||c===void 0?void 0:c.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+n.length);if(l.set(o),l.set(n,o.length),l=t(l),l[6]=l[6]&15|e,l[8]=l[8]&63|128,a){p=p||0;for(let x=0;x<16;++x)a[p+x]=l[x];return a}return v(l)}try{i.name=r;}catch{}return i.DNS=ce,i.URL=ue,i}var G={randomUUID:ne__default.default.randomUUID};function de(r,e,t){if(G.randomUUID&&!e&&!r)return G.randomUUID();r=r||{};let i=r.random||(r.rng||k)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(let n=0;n<16;++n)e[t+n]=i[n];return e}return v(i)}var V=de;function pe(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),ne__default.default.createHash("sha1").update(r).digest()}var W=pe;var me=Q("v5",80,W),j=me;var T={"en-IN":"en","kn-IN":"kn"};var _={INR:"\u20B9"},ee={INR:"en-IN"};var E=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var y=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var U=class extends Error{constructor(e="Tax rule category mismatch."){super(`InvalidTaxRule: ${e}`),this.name="InvalidTaxRuleError";}},L=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},N=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},F=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},B=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},O=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var S=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},C=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},f=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},h=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},I=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};var P=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw new I("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,t){if(t===void 0){if(e==="original")throw new I("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=t;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var g=class r{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new S("Amount cannot be negative.");if(!e.currency)throw new C("Currency code is required.");this.amount=e.amount,this.currency=e.currency;}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot compare prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return this.amount-e.getAmount()}add(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot add prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return new r({amount:this.amount+e.getAmount(),currency:this.currency})}subtract(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot subtract prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return new r({amount:this.amount-e.getAmount(),currency:this.currency})}multiply(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot multiply prices in different currencies.");return new r({amount:this.amount*e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new r({amount:this.amount*e,currency:this.currency});throw new h("Must be a non-negative number.")}divide(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot divide prices in different currencies.");return new r({amount:this.amount/e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>0)return new r({amount:this.amount/e,currency:this.currency});throw new h("Must be a positive number.")}min(...e){if(e.length===0)throw new h("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new f("Cannot compare prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i},this)}max(...e){if(e.length===0)throw new h("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new f("Cannot compare prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return t.compareTo(i)>0?t:i},this)}zero(){return new r({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new r({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return r.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return r.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,t,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=ee[t];if(!t||!n)throw new C("Invalid currency code for formatting.");let o=e,a=i.displayAsInteger?0:r.getDecimalPlaces(t),p={style:i.style??"currency",currency:t,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,p).format(o)}catch(c){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,c),`${_[t]??t} ${r.addThousandSeparators(o.toFixed(a))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static addThousandSeparators(e){let t=e.split("."),i=t[0],n=t.length>1?"."+t[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,t){if(e<0)throw new S("Amount cannot be negative for rounding.");if(t===void 0)throw new C("Invalid currency code for rounding.");let i=r.getDecimalPlaces(t),n=Math.pow(10,i);return Math.round(e*n)/n}};var $=class{baseUnitPrice;taxCategory;tiers;constructor(e){let t=new g(e.baseUnitPrice);if(!e.taxCategory)throw new L;let i=(e.tiers??[]).map(c=>({minQuantity:c.minQuantity,unitPrice:new g(c.unitPrice)})).sort((c,l)=>c.minQuantity-l.minQuantity);if(i.some(c=>c.minQuantity<=0))throw new N;let o=i.some(c=>c.unitPrice.getCurrency()!==t.getCurrency()),a=i.some((c,l)=>l>0&&c.unitPrice.compareTo(i[l-1].unitPrice)>0),p=i[0]?.unitPrice.compareTo(t)>0;if(o||a||p)throw new F("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=t,this.taxCategory=e.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}getApplicableTier(e){if(e<=0)throw new B;for(let t=this.tiers.length-1;t>=0;t--)if(e>=this.tiers[t].minQuantity){let i=this.tiers[t];return {minQuantity:i.minQuantity,unitPrice:i.unitPrice}}throw new O(e)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let e=this.tiers[this.tiers.length-1].unitPrice.getAmount(),t=this.baseUnitPrice.getAmount();return (t-e)/t*100}};var A=class r extends D{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 y("Selection attributes must be an object");return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let t={},i=e.split("|");for(let n of i){let[o,a]=n.split(":");a.startsWith("c+")?t[o]={name:a.slice(2)}:t[o]=a;}return t}catch(t){throw new y(t?.message)}}constructor(e,t=new Date){super(e,t),this.id=e.id,this.key=e.key,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((n,o)=>(e.pricing[o]&&(n[o]=new $(e.pricing[o])),n),{}),this.targetGender=e.targetGender,this.attributes=s.deepClone(e.attributes),this.specifications=s.deepClone(e.specifications),this.categories=s.deepClone(e.categories);let i=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new y("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let o=r.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(o))throw new E(o);return i.add(o),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new P(n.images.primary),gallery:(n.images.gallery||[]).map(a=>new P(a))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?s.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[T[e]]??this.name.en:s.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[T[e]]??this.description.en:s.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[T[e]]??this.slug.en:s.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return s.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:s.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let t=r.generateSelectionAttributesKey(e),i=this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===t);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,t){switch(t){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return s.deepClone(this.categories)}getSpecifications(e){return e?s.deepClone(this.specifications[e]??this.specifications[T[e]]??this.specifications.en):s.deepClone(this.specifications)}getSearchTags(e){return e?s.deepClone(this.searchTags[e]??this.searchTags[T[e]]??this.searchTags.en):s.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((t,i)=>(this.pricing[i]&&(t[i]=this.pricing[i]?.getDetails()),t),{}),attributes:this.getAttributes(),variants:this.variants.map(t=>({sku:t.sku,selectionAttributes:s.deepClone(t.selectionAttributes),images:{primary:t.images.primary.getDetails(),gallery:t.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new y("Selection attributes are required");Object.keys(this.attributes).forEach(t=>{if(t.toLowerCase()==="size")return;let i=this.attributes[t],n=e[t];if(n===void 0)throw new y(`Selection attribute '${t}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new y(`Selection attribute '${t}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new y(`Selection attribute '${t}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(o=>o.name===n.name)<0)throw new y(`Selection attribute '${t}' is invalid`)}});}validateSelectionAttribute(e){let t=r.generateSelectionAttributesKey(e);return this.variants.some(i=>r.generateSelectionAttributesKey(i.selectionAttributes)===t)}validateSize(e){return this.attributes.size.includes(e)}};var he={isUUID:r=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(r),isEmail:r=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r),isURL:r=>/^(http|https):\/\/[^ "]+$/.test(r),generateUUID:(r,e)=>e&&r?j(r,e):V(),generateSearchId:(r,e)=>`${r}#${A.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:r=>{let[e,t]=r.split("#");return {key:e,selectionAttributes:A.parseSelectionAttributesKey(t)}},deepClone(r){return structuredClone(r)}},s=he;var w=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:s.deepClone(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return s.deepClone(this.customFields)}},D=class extends w{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,t,i,n){this.modifiedBy={id:e,authType:t,requestId:i,lambdaName:n};}};var K=class{taxRuleId;taxCategory;taxSystem;taxSubSystem;taxCountry;effectiveFrom;effectiveTo;constructor(e){this.taxRuleId=e.taxRuleId,this.taxSystem=e.taxSystem,this.taxSubSystem=e.taxSubSystem,this.taxCategory=e.taxCategory,this.taxCountry=e.taxCountry,this.effectiveFrom=new Date(e.effectiveFrom).toISOString(),this.effectiveTo=e.effectiveTo?new Date(e.effectiveTo).toISOString():void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getTaxCountry(){return this.taxCountry}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),taxCountry:this.getTaxCountry(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0}}appliesTo(e,t,i=new Date){return this.taxCategory===e&&this.taxCountry===t&&Date.parse(this.effectiveFrom)<=i.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=i.getTime():!0)}static getTaxRateDisplayString(e,t,i){let n=t*100,o=n%1===0?n.toString():n.toFixed(2).replace(/\.?0+$/,"");return i?.percentageOnly?`${o}%`:e.getTaxSystem()==="GST"?`${e.getTaxSubSystem()} ${o}%`:`${e.getTaxSystem()} ${o}%`}};var z=class extends K{rate;constructor(e){super(e),this.rate=e.rate;}getApplicableTaxRate(){return this.rate}calculateTax(e){let t=this.getApplicableTaxRate();return e.multiply(t)}getDetails(){return {...super.getDetails(),rate:this.getApplicableTaxRate()}}};var q=class extends w{id;name;category;lineItemId;chargeType;pricing;total;constructor(e){super(e),this.id=e.id,this.name=e.name,this.category=e.category,this.lineItemId=e.lineItemId,this.chargeType=e.chargeType,this.pricing={price:new g(e.pricing.price),taxCategory:e.pricing.taxCategory,applicableTaxRule:e.pricing.applicableTaxRule.map(t=>new z(t))},this.total={price:new g(e.total.price),discounts:Object.fromEntries(Object.entries(e.total.discounts).map(([t,i])=>[t,new g(i)])),totalDiscount:new g(e.total.totalDiscount),netPrice:new g(e.total.netPrice),taxBreakdown:Object.fromEntries(Object.entries(e.total.taxBreakdown).map(([t,i])=>[t,{rate:i.rate,taxablePrice:new g(i.taxablePrice),amount:new g(i.amount),system:i.system,subSystem:i.subSystem}])),taxTotal:new g(e.total.taxTotal),grandTotal:new g(e.total.grandTotal)};}getId(){return this.id}getName(e){return e?s.deepClone(this.name[e]??this.name[T[e]]??this.name.en):s.deepClone(this.name)}getCategory(){return this.category}getChargeType(){return this.chargeType}getLineItemId(){return this.lineItemId}getPricing(){return {price:this.pricing.price,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {price:this.total.price,discounts:{...this.total.discounts},netPrice:this.total.netPrice,totalDiscount:this.total.totalDiscount,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,t])=>[e,{rate:t.rate,taxablePrice:t.taxablePrice,amount:t.amount,system:t.system,subSystem:t.subSystem}])),taxTotal:this.total.taxTotal,grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(e){e.forEach(t=>{if(!t.appliesTo(this.pricing.taxCategory,t.getTaxCountry()))throw new U}),this.pricing.applicableTaxRule=e,this.calculateTotals();}updateDiscounts(e){let t={};e.forEach(i=>{t[i.coupon.getCode()]=i.amount;}),this.total.discounts=t,this.calculateTotals();}calculateTotals(){let e=this.pricing.price.zero(),t=this.pricing.price,i=Object.values(this.total.discounts).reduce((m,b)=>m.add(b),e),n=t.subtract(i),o={},a=this.pricing.applicableTaxRule.reduce((m,b)=>m+b.getApplicableTaxRate(),0),p=n.divide(1+a).round(),c=a>0?n.subtract(p):e,l=e,x=this.pricing.applicableTaxRule.reduce((m,b)=>b.getApplicableTaxRate()>m.getApplicableTaxRate()?b:m),H=x.getTaxRuleId();this.pricing.applicableTaxRule.forEach(m=>{if(m.getTaxRuleId()===H)return;let b=m.getApplicableTaxRate(),Y=a>0?c.multiply(b).divide(a).round():e;o[m.getTaxRuleId()]={rate:b,taxablePrice:p,amount:Y,system:m.getTaxSystem(),subSystem:m.getTaxSubSystem()},l=l.add(Y);});let te=c.subtract(l);o[H]={rate:x.getApplicableTaxRate(),taxablePrice:p,amount:te,system:x.getTaxSystem(),subSystem:x.getTaxSubSystem()};let re=p,ie=n;this.total={price:t,discounts:this.total.discounts,netPrice:re,totalDiscount:i,taxBreakdown:o,taxTotal:c,grandTotal:ie};}getDetails(){return {id:this.id,name:s.deepClone(this.name),category:this.category,lineItemId:this.lineItemId,chargeType:this.chargeType,pricing:{price:this.pricing.price.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(t=>t.getDetails())},total:{price:this.total.price.getDetails(),discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,i])=>[t,i.getDetails()])),totalDiscount:this.total.totalDiscount.getDetails(),netPrice:this.total.netPrice.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,i])=>[t,{rate:i.rate,taxablePrice:i.taxablePrice.getDetails(),amount:i.amount.getDetails(),system:i.system,subSystem:i.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};module.exports=q;//# sourceMappingURL=Charge.js.map
|
|
1
|
+
'use strict';var se=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var se__default=/*#__PURE__*/_interopDefault(se);var Z=r=>structuredClone(r),I=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:Z(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return Z(this.customFields)}},D=class extends I{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,t,i,n){this.modifiedBy={id:e,authType:t,requestId:i,lambdaName:n};}};var E=new Uint8Array(256),R=E.length;function j(){return R>E.length-16&&(se__default.default.randomFillSync(E),R=0),E.slice(R,R+=16)}var J=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function oe(r){return typeof r=="string"&&J.test(r)}var W=oe;var d=[];for(let r=0;r<256;++r)d.push((r+256).toString(16).slice(1));function v(r,e=0){return d[r[e+0]]+d[r[e+1]]+d[r[e+2]]+d[r[e+3]]+"-"+d[r[e+4]]+d[r[e+5]]+"-"+d[r[e+6]]+d[r[e+7]]+"-"+d[r[e+8]]+d[r[e+9]]+"-"+d[r[e+10]]+d[r[e+11]]+d[r[e+12]]+d[r[e+13]]+d[r[e+14]]+d[r[e+15]]}function ce(r){if(!W(r))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(r.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(r.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(r.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(r.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var _=ce;function ue(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var le="6ba7b810-9dad-11d1-80b4-00c04fd430c8",de="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Q(r,e,t){function i(n,a,s,p){var o;if(typeof n=="string"&&(n=ue(n)),typeof a=="string"&&(a=_(a)),((o=a)===null||o===void 0?void 0:o.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+n.length);if(l.set(a),l.set(n,a.length),l=t(l),l[6]=l[6]&15|e,l[8]=l[8]&63|128,s){p=p||0;for(let f=0;f<16;++f)s[p+f]=l[f];return s}return v(l)}try{i.name=r;}catch{}return i.DNS=le,i.URL=de,i}var G={randomUUID:se__default.default.randomUUID};function pe(r,e,t){if(G.randomUUID&&!e&&!r)return G.randomUUID();r=r||{};let i=r.random||(r.rng||j)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(let n=0;n<16;++n)e[t+n]=i[n];return e}return v(i)}var V=pe;function he(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),se__default.default.createHash("sha1").update(r).digest()}var ee=he;var ye=Q("v5",80,ee),K=ye;var T={"en-IN":"en","kn-IN":"kn"};var te={INR:"\u20B9"},re={INR:"en-IN"};var U=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var y=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var L=class extends Error{constructor(e="Tax rule category mismatch."){super(`InvalidTaxRule: ${e}`),this.name="InvalidTaxRuleError";}},N=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},F=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},B=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},O=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},$=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var w=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},P=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},x=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},h=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},M=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}},C=class extends Error{constructor(e="Invalid charge data."){super(`InvalidCharge: ${e}`),this.name="InvalidChargeError";}};var A=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw new M("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,t){if(t===void 0){if(e==="original")throw new M("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=t;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var g=class r{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new w("Amount cannot be negative.");if(!e.currency)throw new P("Currency code is required.");this.amount=e.amount,this.currency=e.currency;}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new x("Cannot compare prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return this.amount-e.getAmount()}add(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new x("Cannot add prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return new r({amount:this.amount+e.getAmount(),currency:this.currency})}subtract(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new x("Cannot subtract prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return new r({amount:this.amount-e.getAmount(),currency:this.currency})}multiply(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new x("Cannot multiply prices in different currencies.");return new r({amount:this.amount*e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new r({amount:this.amount*e,currency:this.currency});throw new h("Must be a non-negative number.")}divide(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new x("Cannot divide prices in different currencies.");return new r({amount:this.amount/e.getAmount(),currency:this.currency})}else if(typeof e=="number"&&e>0)return new r({amount:this.amount/e,currency:this.currency});throw new h("Must be a positive number.")}min(...e){if(e.length===0)throw new h("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new x("Cannot compare prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i},this)}max(...e){if(e.length===0)throw new h("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new x("Cannot compare prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return t.compareTo(i)>0?t:i},this)}zero(){return new r({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new r({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return r.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return r.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,t,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=re[t];if(!t||!n)throw new P("Invalid currency code for formatting.");let a=e,s=i.displayAsInteger?0:r.getDecimalPlaces(t),p={style:i.style??"currency",currency:t,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:s,maximumFractionDigits:s};i.displayAsInteger&&(a=Math.ceil(a));try{return new Intl.NumberFormat(n,p).format(a)}catch(o){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,o),`${te[t]??t} ${r.addThousandSeparators(a.toFixed(s))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static addThousandSeparators(e){let t=e.split("."),i=t[0],n=t.length>1?"."+t[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,t){if(e<0)throw new w("Amount cannot be negative for rounding.");if(t===void 0)throw new P("Invalid currency code for rounding.");let i=r.getDecimalPlaces(t),n=Math.pow(10,i);return Math.round(e*n)/n}};var k=class{baseUnitPrice;taxCategory;tiers;constructor(e){let t=new g(e.baseUnitPrice);if(!e.taxCategory)throw new N;let i=(e.tiers??[]).map(o=>({minQuantity:o.minQuantity,unitPrice:new g(o.unitPrice)})).sort((o,l)=>o.minQuantity-l.minQuantity);if(i.some(o=>o.minQuantity<=0))throw new F;let a=i.some(o=>o.unitPrice.getCurrency()!==t.getCurrency()),s=i.some((o,l)=>l>0&&o.unitPrice.compareTo(i[l-1].unitPrice)>0),p=i[0]?.unitPrice.compareTo(t)>0;if(a||s||p)throw new B("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=t,this.taxCategory=e.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}getApplicableTier(e){if(e<=0)throw new O;for(let t=this.tiers.length-1;t>=0;t--)if(e>=this.tiers[t].minQuantity){let i=this.tiers[t];return {minQuantity:i.minQuantity,unitPrice:i.unitPrice}}throw new $(e)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let e=this.tiers[this.tiers.length-1].unitPrice.getAmount(),t=this.baseUnitPrice.getAmount();return (t-e)/t*100}};var S=class r extends D{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 y("Selection attributes must be an object");return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let t={},i=e.split("|");for(let n of i){let[a,s]=n.split(":");s.startsWith("c+")?t[a]={name:s.slice(2)}:t[a]=s;}return t}catch(t){throw new y(t?.message)}}constructor(e,t=new Date){super(e,t),this.id=e.id,this.key=e.key,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((n,a)=>(e.pricing[a]&&(n[a]=new k(e.pricing[a])),n),{}),this.targetGender=e.targetGender,this.attributes=u.deepClone(e.attributes),this.specifications=u.deepClone(e.specifications),this.categories=u.deepClone(e.categories);let i=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new y("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let a=r.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(a))throw new U(a);return i.add(a),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new A(n.images.primary),gallery:(n.images.gallery||[]).map(s=>new A(s))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?u.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[T[e]]??this.name.en:u.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[T[e]]??this.description.en:u.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[T[e]]??this.slug.en:u.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return u.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:u.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let t=r.generateSelectionAttributesKey(e),i=this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===t);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,t){switch(t){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return u.deepClone(this.categories)}getSpecifications(e){return e?u.deepClone(this.specifications[e]??this.specifications[T[e]]??this.specifications.en):u.deepClone(this.specifications)}getSearchTags(e){return e?u.deepClone(this.searchTags[e]??this.searchTags[T[e]]??this.searchTags.en):u.deepClone(this.searchTags)}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((t,i)=>(this.pricing[i]&&(t[i]=this.pricing[i]?.getDetails()),t),{}),attributes:this.getAttributes(),variants:this.variants.map(t=>({sku:t.sku,selectionAttributes:u.deepClone(t.selectionAttributes),images:{primary:t.images.primary.getDetails(),gallery:t.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new y("Selection attributes are required");Object.keys(this.attributes).forEach(t=>{if(t.toLowerCase()==="size")return;let i=this.attributes[t],n=e[t];if(n===void 0)throw new y(`Selection attribute '${t}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new y(`Selection attribute '${t}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new y(`Selection attribute '${t}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(a=>a.name===n.name)<0)throw new y(`Selection attribute '${t}' is invalid`)}});}validateSelectionAttribute(e){let t=r.generateSelectionAttributesKey(e);return this.variants.some(i=>r.generateSelectionAttributesKey(i.selectionAttributes)===t)}validateSize(e){return this.attributes.size.includes(e)}};var xe={isUUID:r=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(r),isEmail:r=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r),isURL:r=>/^(http|https):\/\/[^ "]+$/.test(r),generateUUID:(r,e)=>e&&r?K(r,e):V(),generateSearchId:(r,e)=>`${r}#${S.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:r=>{let[e,t]=r.split("#");return {key:e,selectionAttributes:S.parseSelectionAttributesKey(t)}},deepClone(r){return structuredClone(r)}},u=xe;var Y=class{taxRuleId;taxCategory;taxSystem;taxSubSystem;taxCountry;effectiveFrom;effectiveTo;constructor(e){this.taxRuleId=e.taxRuleId,this.taxSystem=e.taxSystem,this.taxSubSystem=e.taxSubSystem,this.taxCategory=e.taxCategory,this.taxCountry=e.taxCountry,this.effectiveFrom=new Date(e.effectiveFrom).toISOString(),this.effectiveTo=e.effectiveTo?new Date(e.effectiveTo).toISOString():void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getTaxCountry(){return this.taxCountry}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),taxCountry:this.getTaxCountry(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0}}appliesTo(e,t,i=new Date){return this.taxCategory===e&&this.taxCountry===t&&Date.parse(this.effectiveFrom)<=i.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=i.getTime():!0)}static getTaxRateDisplayString(e,t,i){let n=t*100,a=n%1===0?n.toString():n.toFixed(2).replace(/\.?0+$/,"");return i?.percentageOnly?`${a}%`:e.getTaxSystem()==="GST"?`${e.getTaxSubSystem()} ${a}%`:`${e.getTaxSystem()} ${a}%`}};var z=class extends Y{rate;constructor(e){super(e),this.rate=e.rate;}getApplicableTaxRate(){return this.rate}calculateTax(e){let t=this.getApplicableTaxRate();return e.multiply(t)}getDetails(){return {...super.getDetails(),rate:this.getApplicableTaxRate()}}};var q=class extends I{id;name;category;lineItemId;chargeType;impact;taxTreatment;pricing;total;constructor(e){if(super(e),this.id=e.id,this.name=e.name,this.category=e.category,this.lineItemId=e.lineItemId,this.chargeType=e.chargeType,this.impact=e.impact??"ADD",this.taxTreatment=e.taxTreatment??"APPLY",this.pricing={price:new g(e.pricing.price),taxCategory:e.pricing.taxCategory,applicableTaxRule:e.pricing.applicableTaxRule.map(t=>new z(t))},this.chargeType!=="ADJUSTMENT"){if(this.impact!=="ADD")throw new C("Only adjustment charges can be subtractive.");if(this.taxTreatment!=="APPLY")throw new C("Non-adjustment charges must apply tax.")}else {if(this.taxTreatment!=="EXEMPT")throw new C("Adjustment charges must be tax exempt.");if(this.pricing.applicableTaxRule.length>0)throw new C("Adjustment charges cannot have tax rules.")}this.total={price:new g(e.total.price),discounts:Object.fromEntries(Object.entries(e.total.discounts).map(([t,i])=>[t,new g(i)])),totalDiscount:new g(e.total.totalDiscount),netPrice:new g(e.total.netPrice),taxBreakdown:Object.fromEntries(Object.entries(e.total.taxBreakdown).map(([t,i])=>[t,{rate:i.rate,taxablePrice:new g(i.taxablePrice),amount:new g(i.amount),system:i.system,subSystem:i.subSystem}])),taxTotal:new g(e.total.taxTotal),grandTotal:new g(e.total.grandTotal)};}getId(){return this.id}getName(e){return e?u.deepClone(this.name[e]??this.name[T[e]]??this.name.en):u.deepClone(this.name)}getCategory(){return this.category}getChargeType(){return this.chargeType}getImpact(){return this.impact}getTaxTreatment(){return this.taxTreatment}getLineItemId(){return this.lineItemId}getPricing(){return {price:this.pricing.price,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {price:this.total.price,discounts:{...this.total.discounts},netPrice:this.total.netPrice,totalDiscount:this.total.totalDiscount,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,t])=>[e,{rate:t.rate,taxablePrice:t.taxablePrice,amount:t.amount,system:t.system,subSystem:t.subSystem}])),taxTotal:this.total.taxTotal,grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(e){if(this.chargeType==="ADJUSTMENT")throw new C("Adjustment charges cannot apply tax rules.");e.forEach(t=>{if(!t.appliesTo(this.pricing.taxCategory,t.getTaxCountry()))throw new L}),this.pricing.applicableTaxRule=e,this.calculateTotals();}updateDiscounts(e){let t={};e.forEach(i=>{t[i.coupon.getCode()]=i.amount;}),this.total.discounts=t,this.calculateTotals();}calculateTotals(){let e=this.pricing.price.zero(),t=this.pricing.price,i=Object.values(this.total.discounts).reduce((m,b)=>m.add(b),e),n=t.subtract(i);if(this.taxTreatment==="EXEMPT"){this.total={price:t,discounts:this.total.discounts,netPrice:n,totalDiscount:i,taxBreakdown:{},taxTotal:e,grandTotal:n};return}let a={},s=this.pricing.applicableTaxRule.reduce((m,b)=>m+b.getApplicableTaxRate(),0),p=n.divide(1+s).round(),o=s>0?n.subtract(p):e,l=e,f=this.pricing.applicableTaxRule.reduce((m,b)=>b.getApplicableTaxRate()>m.getApplicableTaxRate()?b:m),H=f.getTaxRuleId();this.pricing.applicableTaxRule.forEach(m=>{if(m.getTaxRuleId()===H)return;let b=m.getApplicableTaxRate(),X=s>0?o.multiply(b).divide(s).round():e;a[m.getTaxRuleId()]={rate:b,taxablePrice:p,amount:X,system:m.getTaxSystem(),subSystem:m.getTaxSubSystem()},l=l.add(X);});let ie=o.subtract(l);a[H]={rate:f.getApplicableTaxRate(),taxablePrice:p,amount:ie,system:f.getTaxSystem(),subSystem:f.getTaxSubSystem()};let ne=p,ae=n;this.total={price:t,discounts:this.total.discounts,netPrice:ne,totalDiscount:i,taxBreakdown:a,taxTotal:o,grandTotal:ae};}getDetails(){return {id:this.id,name:u.deepClone(this.name),category:this.category,lineItemId:this.lineItemId,chargeType:this.chargeType,impact:this.impact,taxTreatment:this.taxTreatment,pricing:{price:this.pricing.price.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(t=>t.getDetails())},total:{price:this.total.price.getDetails(),discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,i])=>[t,i.getDetails()])),totalDiscount:this.total.totalDiscount.getDetails(),netPrice:this.total.netPrice.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,i])=>[t,{rate:i.rate,taxablePrice:i.taxablePrice.getDetails(),amount:i.amount.getDetails(),system:i.system,subSystem:i.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};module.exports=q;//# sourceMappingURL=Charge.js.map
|
|
2
2
|
//# sourceMappingURL=Charge.js.map
|