b23-lib 3.10.1 → 4.0.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.
- package/dist/Auth/index.js +1 -1
- package/dist/Auth/index.js.map +1 -1
- package/dist/Auth/index.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/Charge.d.mts +23 -7
- package/dist/Classes/Charge.d.ts +23 -7
- 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/Inventory.js +1 -1
- package/dist/Classes/Inventory.js.map +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/Invoice.d.mts +44 -10
- package/dist/Classes/Invoice.d.ts +44 -10
- package/dist/Classes/Invoice.js +1 -1
- package/dist/Classes/Invoice.js.map +1 -1
- package/dist/Classes/Invoice.mjs +1 -1
- package/dist/Classes/Invoice.mjs.map +1 -1
- package/dist/Classes/LineItem.d.mts +28 -8
- package/dist/Classes/LineItem.d.ts +28 -8
- 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/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 +55 -26
- package/dist/Classes/ShoppingContainer.d.ts +55 -26
- 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 +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-MBR2GRKU.mjs → chunk-3SUQYXIJ.mjs} +2 -2
- package/dist/{chunk-MBR2GRKU.mjs.map → chunk-3SUQYXIJ.mjs.map} +1 -1
- package/dist/chunk-MAUKFI5A.mjs +2 -0
- package/dist/chunk-MAUKFI5A.mjs.map +1 -0
- package/dist/chunk-MWDQACOC.mjs +2 -0
- package/dist/chunk-MWDQACOC.mjs.map +1 -0
- package/dist/chunk-QW2TQXMP.mjs +2 -0
- package/dist/chunk-QW2TQXMP.mjs.map +1 -0
- package/dist/chunk-XMNNRBPH.mjs +2 -0
- package/dist/chunk-XMNNRBPH.mjs.map +1 -0
- package/dist/{chunk-4PTWJI6J.mjs → chunk-XXKEHCV5.mjs} +2 -2
- package/dist/chunk-XXKEHCV5.mjs.map +1 -0
- package/dist/{chunk-EZ35IKUA.mjs → chunk-YT3U73BS.mjs} +2 -2
- package/dist/chunk-YT3U73BS.mjs.map +1 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-4PTWJI6J.mjs.map +0 -1
- package/dist/chunk-5N2HRXWJ.mjs +0 -2
- package/dist/chunk-5N2HRXWJ.mjs.map +0 -1
- package/dist/chunk-6QSZECNF.mjs +0 -2
- package/dist/chunk-6QSZECNF.mjs.map +0 -1
- package/dist/chunk-EZ35IKUA.mjs.map +0 -1
- package/dist/chunk-MPKIC2MS.mjs +0 -2
- package/dist/chunk-MPKIC2MS.mjs.map +0 -1
- package/dist/chunk-NXDEYUDI.mjs +0 -2
- package/dist/chunk-NXDEYUDI.mjs.map +0 -1
package/dist/Classes/Cart.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'../chunk-
|
|
1
|
+
import {a}from'../chunk-MAUKFI5A.mjs';import'../chunk-XMNNRBPH.mjs';import'../chunk-3SUQYXIJ.mjs';import'../chunk-HX32EJ3F.mjs';import'../chunk-QW2TQXMP.mjs';import'../chunk-MWDQACOC.mjs';import'../chunk-YT3U73BS.mjs';import {f}from'../chunk-XXKEHCV5.mjs';import'../chunk-7RAIVZKB.mjs';import'../chunk-UIQH5QIR.mjs';import'../chunk-PL5HGCWN.mjs';import {a as a$1}from'../chunk-O6BLQQO7.mjs';import'../chunk-UXZBULDS.mjs';var p=(i=>(i.ACTIVE="ACTIVE",i.FROZEN="FROZEN",i.MERGED="MERGED",i.ORDERED="ORDERED",i))(p||{}),h={expiresAtInSeconds:120*24*60*60},c=class extends a{state;expireAt;config;constructor(t,e=new Date,r=h){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.charges=[],this.coupons=[],this.shippingDetails=null,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,e){let r=t.getProductKey(),i=t.getSelectionAttributes(),n=f.generateSelectionAttributesKey(i),s=this.lineItems.findIndex(l=>l.getProductKey()===r&&f.generateSelectionAttributesKey(l.getSelectionAttributes())===n);return s>=0?(t.addSubItems(this.lineItems[s].getSubItems(),e),this.lineItems[s]=t):this.lineItems.push(t),this.calculateTotals(),s>=0?s:this.lineItems.length-1}updateLineItem(t,e,r){let i=this.lineItems,n=i.findIndex(s=>s.getId()===t);if(n<0)throw new a$1(t);return i[n].addSubItems([{size:e,quantity:r}],!1),this.calculateTotals(),n}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{p as CartState,h as DEFAULT_CART_CONFIG,c as default};//# sourceMappingURL=Cart.mjs.map
|
|
2
2
|
//# sourceMappingURL=Cart.mjs.map
|
|
@@ -12,6 +12,7 @@ type ChargePricing = {
|
|
|
12
12
|
taxCategory: string;
|
|
13
13
|
/** Tax rules applicable to the charge. */
|
|
14
14
|
applicableTaxRule: TaxRuleData[];
|
|
15
|
+
isTaxInclusive?: boolean;
|
|
15
16
|
};
|
|
16
17
|
type ChargePricingModel = {
|
|
17
18
|
/** Tax-inclusive original charge amount before any discounts. Always non-negative. */
|
|
@@ -20,6 +21,7 @@ type ChargePricingModel = {
|
|
|
20
21
|
taxCategory: string;
|
|
21
22
|
/** Tax rules applicable to the charge. */
|
|
22
23
|
applicableTaxRule: TaxRuleModel[];
|
|
24
|
+
isTaxInclusive: boolean;
|
|
23
25
|
};
|
|
24
26
|
type ChargeTaxBreakdown = {
|
|
25
27
|
/** Tax rate: e.g., 0.09 for 9% */
|
|
@@ -39,28 +41,37 @@ type ChargeTaxBreakdownModel = {
|
|
|
39
41
|
subSystem: string;
|
|
40
42
|
};
|
|
41
43
|
type ChargeTotals = {
|
|
42
|
-
/** Tax-inclusive original charge amount before discounts (copied from pricing) */
|
|
43
|
-
chargeAmount: PriceData;
|
|
44
44
|
/** Coupon code -> discount amount mapping */
|
|
45
45
|
discountBreakdown: Record<string, PriceData>;
|
|
46
46
|
/** Sum of all discounts */
|
|
47
47
|
discountTotal: PriceData;
|
|
48
|
-
/** chargeAmount - totalDiscount → final tax-inclusive payable amount after discounts */
|
|
49
|
-
netChargeAmount: PriceData;
|
|
50
48
|
/** Sum of all taxAmount values */
|
|
51
49
|
taxTotal: PriceData;
|
|
52
50
|
/** Tax breakdown per rule/category (reverse-calculated from netChargeAmount) */
|
|
53
51
|
taxBreakdown: Record<string, ChargeTaxBreakdown>;
|
|
54
|
-
|
|
52
|
+
taxExclusive: {
|
|
53
|
+
chargeAmount: PriceData;
|
|
54
|
+
netChargeAmount: PriceData;
|
|
55
|
+
};
|
|
56
|
+
taxInclusive: {
|
|
57
|
+
chargeAmount: PriceData;
|
|
58
|
+
netChargeAmount: PriceData;
|
|
59
|
+
};
|
|
55
60
|
grandTotal: PriceData;
|
|
56
61
|
};
|
|
57
62
|
type ChargeTotalsModel = {
|
|
58
|
-
chargeAmount: PriceModel;
|
|
59
63
|
discountTotal: PriceModel;
|
|
60
64
|
discountBreakdown: Record<string, PriceModel>;
|
|
61
|
-
netChargeAmount: PriceModel;
|
|
62
65
|
taxTotal: PriceModel;
|
|
63
66
|
taxBreakdown: Record<string, ChargeTaxBreakdownModel>;
|
|
67
|
+
taxExclusive: {
|
|
68
|
+
chargeAmount: PriceModel;
|
|
69
|
+
netChargeAmount: PriceModel;
|
|
70
|
+
};
|
|
71
|
+
taxInclusive: {
|
|
72
|
+
chargeAmount: PriceModel;
|
|
73
|
+
netChargeAmount: PriceModel;
|
|
74
|
+
};
|
|
64
75
|
grandTotal: PriceModel;
|
|
65
76
|
};
|
|
66
77
|
type ChargeAttributes = CustomFieldAttributes & {
|
|
@@ -126,6 +137,10 @@ declare class ChargeModel extends CustomFieldModel {
|
|
|
126
137
|
* @returns The line item id or undefined.
|
|
127
138
|
*/
|
|
128
139
|
getLineItemId(): string | undefined;
|
|
140
|
+
/**
|
|
141
|
+
* Gets whether the charge is tax inclusive.
|
|
142
|
+
*/
|
|
143
|
+
getIsTaxInclusive(): boolean;
|
|
129
144
|
/**
|
|
130
145
|
* Gets the pricing details (models) for this charge.
|
|
131
146
|
* @returns Pricing details including price, tax category, and tax rules.
|
|
@@ -165,6 +180,7 @@ declare class ChargeModel extends CustomFieldModel {
|
|
|
165
180
|
}[]): void;
|
|
166
181
|
/**
|
|
167
182
|
* Recalculates totals for this charge based on pricing and discounts.
|
|
183
|
+
* Delegates tax computation to shared calculateDualViewTotals utility.
|
|
168
184
|
*/
|
|
169
185
|
calculateTotals(): void;
|
|
170
186
|
/**
|
package/dist/Classes/Charge.d.ts
CHANGED
|
@@ -12,6 +12,7 @@ type ChargePricing = {
|
|
|
12
12
|
taxCategory: string;
|
|
13
13
|
/** Tax rules applicable to the charge. */
|
|
14
14
|
applicableTaxRule: TaxRuleData[];
|
|
15
|
+
isTaxInclusive?: boolean;
|
|
15
16
|
};
|
|
16
17
|
type ChargePricingModel = {
|
|
17
18
|
/** Tax-inclusive original charge amount before any discounts. Always non-negative. */
|
|
@@ -20,6 +21,7 @@ type ChargePricingModel = {
|
|
|
20
21
|
taxCategory: string;
|
|
21
22
|
/** Tax rules applicable to the charge. */
|
|
22
23
|
applicableTaxRule: TaxRuleModel[];
|
|
24
|
+
isTaxInclusive: boolean;
|
|
23
25
|
};
|
|
24
26
|
type ChargeTaxBreakdown = {
|
|
25
27
|
/** Tax rate: e.g., 0.09 for 9% */
|
|
@@ -39,28 +41,37 @@ type ChargeTaxBreakdownModel = {
|
|
|
39
41
|
subSystem: string;
|
|
40
42
|
};
|
|
41
43
|
type ChargeTotals = {
|
|
42
|
-
/** Tax-inclusive original charge amount before discounts (copied from pricing) */
|
|
43
|
-
chargeAmount: PriceData;
|
|
44
44
|
/** Coupon code -> discount amount mapping */
|
|
45
45
|
discountBreakdown: Record<string, PriceData>;
|
|
46
46
|
/** Sum of all discounts */
|
|
47
47
|
discountTotal: PriceData;
|
|
48
|
-
/** chargeAmount - totalDiscount → final tax-inclusive payable amount after discounts */
|
|
49
|
-
netChargeAmount: PriceData;
|
|
50
48
|
/** Sum of all taxAmount values */
|
|
51
49
|
taxTotal: PriceData;
|
|
52
50
|
/** Tax breakdown per rule/category (reverse-calculated from netChargeAmount) */
|
|
53
51
|
taxBreakdown: Record<string, ChargeTaxBreakdown>;
|
|
54
|
-
|
|
52
|
+
taxExclusive: {
|
|
53
|
+
chargeAmount: PriceData;
|
|
54
|
+
netChargeAmount: PriceData;
|
|
55
|
+
};
|
|
56
|
+
taxInclusive: {
|
|
57
|
+
chargeAmount: PriceData;
|
|
58
|
+
netChargeAmount: PriceData;
|
|
59
|
+
};
|
|
55
60
|
grandTotal: PriceData;
|
|
56
61
|
};
|
|
57
62
|
type ChargeTotalsModel = {
|
|
58
|
-
chargeAmount: PriceModel;
|
|
59
63
|
discountTotal: PriceModel;
|
|
60
64
|
discountBreakdown: Record<string, PriceModel>;
|
|
61
|
-
netChargeAmount: PriceModel;
|
|
62
65
|
taxTotal: PriceModel;
|
|
63
66
|
taxBreakdown: Record<string, ChargeTaxBreakdownModel>;
|
|
67
|
+
taxExclusive: {
|
|
68
|
+
chargeAmount: PriceModel;
|
|
69
|
+
netChargeAmount: PriceModel;
|
|
70
|
+
};
|
|
71
|
+
taxInclusive: {
|
|
72
|
+
chargeAmount: PriceModel;
|
|
73
|
+
netChargeAmount: PriceModel;
|
|
74
|
+
};
|
|
64
75
|
grandTotal: PriceModel;
|
|
65
76
|
};
|
|
66
77
|
type ChargeAttributes = CustomFieldAttributes & {
|
|
@@ -126,6 +137,10 @@ declare class ChargeModel extends CustomFieldModel {
|
|
|
126
137
|
* @returns The line item id or undefined.
|
|
127
138
|
*/
|
|
128
139
|
getLineItemId(): string | undefined;
|
|
140
|
+
/**
|
|
141
|
+
* Gets whether the charge is tax inclusive.
|
|
142
|
+
*/
|
|
143
|
+
getIsTaxInclusive(): boolean;
|
|
129
144
|
/**
|
|
130
145
|
* Gets the pricing details (models) for this charge.
|
|
131
146
|
* @returns Pricing details including price, tax category, and tax rules.
|
|
@@ -165,6 +180,7 @@ declare class ChargeModel extends CustomFieldModel {
|
|
|
165
180
|
}[]): void;
|
|
166
181
|
/**
|
|
167
182
|
* Recalculates totals for this charge based on pricing and discounts.
|
|
183
|
+
* Delegates tax computation to shared calculateDualViewTotals utility.
|
|
168
184
|
*/
|
|
169
185
|
calculateTotals(): void;
|
|
170
186
|
/**
|
package/dist/Classes/Charge.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var ge=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ge__default=/*#__PURE__*/_interopDefault(ge);var re=i=>structuredClone(i),D=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:re(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return re(this.customFields)}},O=class extends D{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,t,r,n){this.modifiedBy={id:e,authType:t,requestId:r,lambdaName:n};}};var V=new Uint8Array(256),Q=V.length;function H(){return Q>V.length-16&&(ge__default.default.randomFillSync(V),Q=0),V.slice(Q,Q+=16)}var ie=/^(?:[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 me(i){return typeof i=="string"&&ie.test(i)}var ne=me;var p=[];for(let i=0;i<256;++i)p.push((i+256).toString(16).slice(1));function G(i,e=0){return p[i[e+0]]+p[i[e+1]]+p[i[e+2]]+p[i[e+3]]+"-"+p[i[e+4]]+p[i[e+5]]+"-"+p[i[e+6]]+p[i[e+7]]+"-"+p[i[e+8]]+p[i[e+9]]+"-"+p[i[e+10]]+p[i[e+11]]+p[i[e+12]]+p[i[e+13]]+p[i[e+14]]+p[i[e+15]]}function pe(i){if(!ne(i))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(i.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(i.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(i.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(i.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(i.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 oe=pe;function he(i){i=unescape(encodeURIComponent(i));let e=[];for(let t=0;t<i.length;++t)e.push(i.charCodeAt(t));return e}var ye="6ba7b810-9dad-11d1-80b4-00c04fd430c8",be="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Z(i,e,t){function r(n,o,c,s){var u;if(typeof n=="string"&&(n=he(n)),typeof o=="string"&&(o=oe(o)),((u=o)===null||u===void 0?void 0:u.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+n.length);if(a.set(o),a.set(n,o.length),a=t(a),a[6]=a[6]&15|e,a[8]=a[8]&63|128,c){s=s||0;for(let d=0;d<16;++d)c[s+d]=a[d];return c}return G(a)}try{r.name=i;}catch{}return r.DNS=ye,r.URL=be,r}var J={randomUUID:ge__default.default.randomUUID};function xe(i,e,t){if(J.randomUUID&&!e&&!i)return J.randomUUID();i=i||{};let r=i.random||(i.rng||H)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){t=t||0;for(let n=0;n<16;++n)e[t+n]=r[n];return e}return G(r)}var X=xe;function Pe(i){return Array.isArray(i)?i=Buffer.from(i):typeof i=="string"&&(i=Buffer.from(i,"utf8")),ge__default.default.createHash("sha1").update(i).digest()}var se=Pe;var Ae=Z("v5",80,se),W=Ae;var S={"en-IN":"en","kn-IN":"kn"};var ae={INR:"\u20B9"},ce={INR:"en-IN"};var K=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var T=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var j=class extends Error{constructor(e="Tax rule category mismatch."){super(`InvalidTaxRule: ${e}`),this.name="InvalidTaxRuleError";}},q=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";}},I=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";}},F=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var k=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},E=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},P=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},f=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},$=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}},z=class extends Error{constructor(e="Invalid charge data."){super(`InvalidCharge: ${e}`),this.name="InvalidChargeError";}},R=class extends Error{constructor(e="Invalid charge tax rule."){super(`InvalidChargeTaxRule: ${e}`),this.name="InvalidChargeTaxRuleError";}},A=class extends Error{constructor(e="Invalid pricing type."){super(`InvalidPricingType: ${e}`),this.name="InvalidPricingTypeError";}};var v=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 $("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 $("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 l=class i{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new k("Amount cannot be negative.");if(!e.currency)throw new E("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(i.getPrecisionPlaces(this.currency)));}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}getPreciseAmount(e){return parseFloat(e.toFixed(i.getPrecisionPlaces(this.currency)))}compareTo(e){if(i.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new P("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(i.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new P("Cannot add prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return new i({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(i.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new P("Cannot subtract prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return new i({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(i.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new P("Cannot multiply prices in different currencies.");return new i({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new i({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new f("Must be a non-negative number.")}divide(e){if(i.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new P("Cannot divide prices in different currencies.");return new i({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new i({amount:this.getPreciseAmount(this.amount/e),currency:this.currency});throw new f("Must be a positive number.")}min(...e){if(e.length===0)throw new f("Must provide at least one PriceModel.");return e.reduce((t,r)=>{if(i.isPriceModel(r)){if(t.getCurrency()!==r.getCurrency())throw new P("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return t.compareTo(r)<0?t:r},this)}max(...e){if(e.length===0)throw new f("Must provide at least one PriceModel.");return e.reduce((t,r)=>{if(i.isPriceModel(r)){if(t.getCurrency()!==r.getCurrency())throw new P("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return t.compareTo(r)>0?t:r},this)}zero(){return new i({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new i({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return i.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return i.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,t,r={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=ce[t];if(!t||!n)throw new E("Invalid currency code for formatting.");let o=e,c=r.displayAsInteger?0:i.getDecimalPlaces(t),s={style:r.style??"currency",currency:t,signDisplay:"never",currencyDisplay:r.currencyDisplay,minimumFractionDigits:c,maximumFractionDigits:c};r.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,s).format(o)}catch(u){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,u),`${ae[t]??t} ${i.addThousandSeparators(o.toFixed(c))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static getPrecisionPlaces(e){switch(e){case"INR":default:return 6}}static addThousandSeparators(e){let t=e.split("."),r=t[0],n=t.length>1?"."+t[1]:"";return r.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,t){if(e<0)throw new k("Amount cannot be negative for rounding.");if(t===void 0)throw new E("Invalid currency code for rounding.");let r=i.getDecimalPlaces(t),n=Math.pow(10,r);return Math.round(e*n)/n}static getSmallestUnit(e){let t=i.getDecimalPlaces(e);return 1/Math.pow(10,t)}};var U=class{type;taxCategory;isTaxInclusive;static create(e){return e.type==="selection"?new ee(e):new _(e)}constructor(e){if(!e.taxCategory)throw new q;this.taxCategory=e.taxCategory,this.isTaxInclusive=e.isTaxInclusive??!1,this.type=e.type??"volume";}getType(){return this.type}getTaxCategory(){return this.taxCategory}getIsTaxInclusive(){return this.isTaxInclusive}},_=class extends U{baseUnitPrice;tiers;currency;constructor(e){if(super(e),this.type="volume",!e.baseUnitPrice)throw new I("Base unit price is required for volume pricing.");this.baseUnitPrice=new l(e.baseUnitPrice),this.currency=e.currency??this.baseUnitPrice.getCurrency();let t=(e.tiers??[]).map(s=>({enabled:s.enabled??!0,minQuantity:s.minQuantity,unitPrice:new l(s.unitPrice)})).sort((s,u)=>s.minQuantity-u.minQuantity);if(t.some(s=>s.minQuantity<=0))throw new N;let n=this.baseUnitPrice.getCurrency()!==this.currency||t.some(s=>s.unitPrice.getCurrency()!==this.currency),o=t.some((s,u)=>u>0&&s.unitPrice.compareTo(t[u-1].unitPrice)>0),c=t[0]?.unitPrice.compareTo(this.baseUnitPrice)>0;if(n||o||c)throw new I("Tiers must share the same currency and must not increase in unit price.");this.tiers=t;}isPriceAvailable(){return this.tiers.filter(e=>e.enabled).length>0}getBaseUnitPrice(){return this.baseUnitPrice}getCurrency(){return this.baseUnitPrice.getCurrency()}getApplicableUnitPrice(e){if(e<=0)throw new B;let t=this.tiers.filter(r=>r.enabled);for(let r=t.length-1;r>=0;r--){let n=t[r];if(e>=n.minQuantity)return n.unitPrice}throw new F(e)}getMinQuantity(){return this.tiers.filter(t=>t.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(){let e=this.tiers.filter(o=>o.enabled);if(!e.length)return 0;let t=Math.min(...e.map(o=>o.unitPrice.getAmount())),r=this.baseUnitPrice.getAmount(),n=(r-t)/r*100;return n>0?n:0}getMinPrice(){let e=this.tiers.filter(t=>t.enabled);return e.length?e[e.length-1].unitPrice:null}getMaxPrice(){let e=this.tiers.filter(t=>t.enabled);return e.length?e[0].unitPrice:null}getTiers(){return this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,baseUnitPrice:this.baseUnitPrice.getDetails(),tiers:this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}},ee=class extends U{currency;selections;constructor(e){super(e),this.type="selection",this.currency=e.currency,this.selections=(e.selections??[]).map(t=>{if(!t.baseUnitPrice)throw new I("Base unit price is required for each selection.");let r=new l(t.baseUnitPrice),n=(t.tiers??[]).map(a=>({enabled:a.enabled??!0,minQuantity:a.minQuantity??1,unitPrice:new l(a.unitPrice)})).sort((a,d)=>a.minQuantity-d.minQuantity);if(n.some(a=>a.minQuantity<=0))throw new N;let c=r.getCurrency()!==this.currency||n.some(a=>a.unitPrice.getCurrency()!==this.currency),s=n.some((a,d)=>d>0&&a.unitPrice.compareTo(n[d-1].unitPrice)>0),u=n[0]?.unitPrice.compareTo(r)>0;if(c||s||u)throw new I("Tiers must share the same currency and must not increase in unit price within the same selection.");return {selectionAttributes:{...t.selectionAttributes},baseUnitPrice:r,tiers:n}});}findMatch(e,t=!1){let r=C.generateSelectionAttributesKey(e),n=this.selections.find(o=>C.generateSelectionAttributesKey(o.selectionAttributes)===r);if(!n&&t)throw new I("No pricing configuration found for selection variant.");return n??null}isPriceAvailable(e){if(!e)return console.warn("Selection attributes are required to check price availability for selection pricing."),!1;let t=this.findMatch(e);return t?t.tiers.filter(r=>r.enabled).length>0:!1}getBaseUnitPrice(e){if(!e)throw new A("Selection attributes are required to get base unit price for selection pricing.");return this.findMatch(e,!0).baseUnitPrice}getCurrency(){return this.currency}getApplicableUnitPrice(e,t){if(e<=0)throw new B;if(!t)throw new A("Selection attributes are required to get applicable unit price for selection pricing.");let n=this.findMatch(t,!0).tiers.filter(o=>o.enabled);for(let o=n.length-1;o>=0;o--){let c=n[o];if(e>=c.minQuantity)return c.unitPrice}throw new F(e)}getMinQuantity(e){if(!e)throw new A("Selection attributes are required to get min quantity for selection pricing.");return this.findMatch(e,!0).tiers.filter(n=>n.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(e){if(!e)throw new A("Selection attributes are required to get max discount for selection pricing.");let t=this.findMatch(e,!0),r=t.tiers.filter(s=>s.enabled);if(!r.length)return 0;let n=Math.min(...r.map(s=>s.unitPrice.getAmount())),o=t.baseUnitPrice.getAmount(),c=(o-n)/o*100;return c>0?c:0}getTiers(e){if(!e)throw new A("Selection attributes are required to get tiers for selection pricing.");return this.findMatch(e,!0).tiers.map(r=>({enabled:r.enabled,minQuantity:r.minQuantity,unitPrice:r.unitPrice}))}getMinPrice(e){if(!e)throw new A("Selection attributes are required to get min price for selection pricing.");let t=this.findMatch(e);if(!t)return null;let r=t.tiers.filter(n=>n.enabled);return r.length?r[r.length-1].unitPrice:null}getMaxPrice(e){if(!e)throw new A("Selection attributes are required to get max price for selection pricing.");let t=this.findMatch(e);if(!t)return null;let r=t.tiers.filter(n=>n.enabled);return r.length?r[0].unitPrice:null}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,selections:this.selections.map(e=>({selectionAttributes:e.selectionAttributes,baseUnitPrice:e.baseUnitPrice.getDetails(),...e.tiers.length>0?{tiers:e.tiers.map(t=>({enabled:t.enabled,minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}:{}}))}}};var C=class i extends O{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;productType;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new T("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 t={},r=e.split("|");for(let n of r){let[o,c]=n.split(":");c.startsWith("c+")?t[o]={name:c.slice(2)}:t[o]=c;}return t}catch(t){throw new T(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]=U.create(e.pricing[o])),n),{}),this.targetGender=e.targetGender,this.attributes=m.deepClone(e.attributes),this.specifications=m.deepClone(e.specifications),this.categories=m.deepClone(e.categories),this.productType=e.productType??"GOODS";let r=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new T("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let o=i.generateSelectionAttributesKey(n.selectionAttributes);if(r.has(o))throw new K(o);return r.add(o),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new v(n.images.primary),gallery:(n.images.gallery||[]).map(c=>new v(c))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?m.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[S[e]]??this.name.en:m.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[S[e]]??this.description.en:m.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[S[e]]??this.slug.en:m.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return m.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:m.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let t=i.generateSelectionAttributesKey(e),r=this.variants.find(n=>i.generateSelectionAttributesKey(n.selectionAttributes)===t);return r?{primary:r.images.primary,gallery:[...r.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 m.deepClone(this.categories)}getProductType(){return this.productType}getSpecifications(e){return e?m.deepClone(this.specifications[e]??this.specifications[S[e]]??this.specifications.en):m.deepClone(this.specifications)}getSearchTags(e){return e?m.deepClone(this.searchTags[e]??this.searchTags[S[e]]??this.searchTags.en):m.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,r)=>(this.pricing[r]&&(t[r]=this.pricing[r]?.getDetails()),t),{}),attributes:this.getAttributes(),variants:this.variants.map(t=>({sku:t.sku,selectionAttributes:m.deepClone(t.selectionAttributes),images:{primary:t.images.primary.getDetails(),gallery:t.images.gallery.map(r=>r.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),productType:this.getProductType(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new T("Selection attributes are required");Object.keys(this.attributes).forEach(t=>{if(t.toLowerCase()==="size")return;let r=this.attributes[t],n=e[t];if(n===void 0)throw new T(`Selection attribute '${t}' is missing`);if(typeof r=="string"){if(typeof n!="string"||r!==n)throw new T(`Selection attribute '${t}' is invalid`)}else if(Array.isArray(r)){if(r.length>0&&typeof r[0]=="string"){if(typeof n!="string"||!r.includes(n))throw new T(`Selection attribute '${t}' is invalid`)}else if(typeof n!="object"||!("name"in n)||r.findIndex(o=>o.name===n.name)<0)throw new T(`Selection attribute '${t}' is invalid`)}});}getSku(e){let t=i.generateSelectionAttributesKey(e);return this.variants.find(n=>i.generateSelectionAttributesKey(n.selectionAttributes)===t)?.sku}validateSelectionAttribute(e){let t=i.generateSelectionAttributesKey(e);return this.variants.some(r=>i.generateSelectionAttributesKey(r.selectionAttributes)===t)}validateSize(e){return this.attributes.size.includes(e)}};var Ce={isUUID:i=>/^[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(i),isEmail:i=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(i),isURL:i=>/^(http|https):\/\/[^ "]+$/.test(i),generateUUID:(i,e)=>e&&i?W(i,e):X(),generateSearchId:(i,e)=>`${i}#${C.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:i=>{let[e,t]=i.split("#");return {key:e,selectionAttributes:C.parseSelectionAttributesKey(t)}},deepClone(i){return structuredClone(i)}},m=Ce;var ue=(i,e)=>{let t=e.reduce((a,d)=>a+d.getApplicableTaxRate(i),0);if(t<=0)return i;let r=i.divide(1+t).round().getAmount(),n=i.getCurrency(),o=i.getAmount(),c=r,s=Number.POSITIVE_INFINITY,u=1e4;for(let a=0;a<u;a++){let d=new l({amount:r,currency:n}),b=e.sort((x,M)=>M.getApplicableTaxRate(d)-x.getApplicableTaxRate(d)).map(x=>d.multiply(x.getApplicableTaxRate(d)).round().getAmount()).reduce((x,M)=>x+M,0),y=r+b-o,L=e.reduce((x,M)=>x+M.getApplicableTaxRate(d),0);if(Math.abs(y)<Math.abs(s)&&(s=y,c=r),y===0)break;r=r-y/(1+L);}if(Math.abs(s)>l.getSmallestUnit(n))throw new Error("Failed to converge on a valid tax exclusive base.");return new l({amount:c,currency:n})},le=(i,e,t)=>{let r=i.zero(),n=[...t].sort((o,c)=>c.getApplicableTaxRate(i)-o.getApplicableTaxRate(i));return n.map((o,c)=>{let s=o.getApplicableTaxRate(i),u;return c===n.length-1?u=e.subtract(i).subtract(r):u=i.multiply(s).round(),r=r.add(u),{ruleId:o.getTaxRuleId(),taxAmount:u,rate:s}})};var Y=class extends D{taxRuleId;taxCategory;taxSystem;taxSubSystem;country;rate;minPrice;maxPrice;excludeMin;excludeMax;effectiveFrom;effectiveTo;constructor(e){super(e),this.taxRuleId=e.taxRuleId,this.taxSystem=e.taxSystem,this.taxSubSystem=e.taxSubSystem,this.taxCategory=e.taxCategory,this.country=e.country,this.rate=e.rate,this.minPrice=new l(e.minPrice),this.maxPrice=e.maxPrice?new l(e.maxPrice):void 0,this.excludeMin=e.excludeMin??!1,this.excludeMax=e.excludeMax??!1,this.effectiveFrom=new Date(e.effectiveFrom).toISOString(),this.effectiveTo=e.effectiveTo?new Date(e.effectiveTo).toISOString():void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getRate(){return this.rate}getMinPrice(){return this.minPrice}getMaxPrice(){return this.maxPrice}getExcludeMin(){return this.excludeMin}getExcludeMax(){return this.excludeMax}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),rate:this.getRate(),minPrice:this.getMinPrice().getDetails(),maxPrice:this.getMaxPrice()?.getDetails(),excludeMin:this.getExcludeMin(),excludeMax:this.getExcludeMax(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0,customFields:this.getAllCustomFields()}}appliesTo(e,t,r,n=new Date){let o=!r||(this.excludeMin?this.minPrice.compareTo(r)<0:this.minPrice.compareTo(r)<=0)&&(this.maxPrice?this.excludeMax?this.maxPrice.compareTo(r)>0:this.maxPrice.compareTo(r)>=0:!0);return this.taxCategory===e&&this.country===t&&o&&Date.parse(this.effectiveFrom)<=n.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=n.getTime():!0)}getApplicableTaxRate(e){return this.appliesTo(this.taxCategory,this.country,e)?this.rate:0}calculateTax(e){return this.appliesTo(this.taxCategory,this.country,e)?e.multiply(this.rate):e.zero()}static getTaxRateDisplayString(e,t,r){let n=t*100,o=n%1===0?n.toString():n.toFixed(2).replace(/\.?0+$/,"");return r?.percentageOnly?`${o}%`:e.getTaxSystem()==="GST"?`${e.getTaxSubSystem()} ${o}%`:`${e.getTaxSystem()} ${o}%`}};var te=class extends D{id;name;type;category;impact;pricing;lineItemId;total;constructor(e){if(super(e),this.id=e.id,this.name=e.name,this.type=e.type,this.category=e.category,this.impact=e.impact,this.lineItemId=e.lineItemId,this.pricing={baseChargeAmount:new l(e.pricing.baseChargeAmount),taxCategory:e.pricing.taxCategory,applicableTaxRule:e.pricing.applicableTaxRule.map(t=>new Y(t))},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new z("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={chargeAmount:new l(e.total.chargeAmount),discountTotal:new l(e.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(e.total.discountBreakdown).map(([t,r])=>[t,new l(r)])),netChargeAmount:new l(e.total.netChargeAmount),taxBreakdown:Object.fromEntries(Object.entries(e.total.taxBreakdown).map(([t,r])=>[t,{rate:r.rate,taxableAmount:new l(r.taxableAmount),taxAmount:new l(r.taxAmount),system:r.system,subSystem:r.subSystem}])),taxTotal:new l(e.total.taxTotal),grandTotal:new l(e.total.grandTotal)};}getId(){return this.id}getName(e){return e?m.deepClone(this.name[e]??this.name[S[e]]??this.name.en):m.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getPricing(){return {baseChargeAmount:this.pricing.baseChargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule]}}getTotal(){return {chargeAmount:this.total.chargeAmount,discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},netChargeAmount:this.total.netChargeAmount,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,t])=>[e,{rate:t.rate,taxableAmount:t.taxableAmount,taxAmount:t.taxAmount,system:t.system,subSystem:t.subSystem}])),grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(e){if(this.type==="ADJUSTMENT"&&e.length>0)throw new z("Adjustment charges cannot apply tax rules.");e.forEach(t=>{if(!t.appliesTo(this.pricing.taxCategory,t.getCountry()))throw new j}),this.validateTaxRules(e),this.pricing.applicableTaxRule=e,this.calculateTotals();}validateTaxRules(e){if(this.impact==="SUBTRACT"&&e.some(r=>r.getRate()>0))throw new R("Subtractive charges cannot have positive tax rates.");let t=new Set;for(let r=0;r<e.length;r++){let n=e[r].getTaxRuleId();if(t.has(n))throw new R("Duplicate tax rule ID found: "+n);t.add(n);for(let o=r+1;o<e.length;o++){let c=e[r],s=e[o],u=c.getMinPrice(),a=c.getMaxPrice(),d=c.getExcludeMin(),h=c.getExcludeMax(),b=s.getMinPrice(),y=s.getMaxPrice(),L=s.getExcludeMin(),x=s.getExcludeMax(),M=(()=>{if(!a)return !1;let w=a.compareTo(b);return w<0||w===0&&(h||L)})(),de=(()=>{if(!y)return !1;let w=y.compareTo(u);return w<0||w===0&&(x||d)})();if(!(M||de)&&!(u.compareTo(b)===0&&d===L&&h===x&&(!a&&!y||a&&y&&a.compareTo(y)===0)))throw new R(`Overlapping rules found: [${c.getTaxRuleId()}: ${d?"(":"["}${u.getAmount()}-${a?.getAmount()??"Infinity"}${h?")":"]"}] and [${s.getTaxRuleId()}: ${L?"(":"["}${b.getAmount()}-${y?.getAmount()??"Infinity"}${x?")":"]"}]`)}}}updateDiscounts(e){let t={};e.forEach(r=>{t[r.coupon.getCode()]=r.amount;}),this.total.discountBreakdown=t,this.calculateTotals();}calculateTotals(){let e=this.pricing.baseChargeAmount.zero(),t=this.pricing.baseChargeAmount,r=Object.values(this.total.discountBreakdown).reduce((h,b)=>h.add(b),e),n=t.subtract(r),o={};if(this.pricing.applicableTaxRule.reduce((h,b)=>h+b.getApplicableTaxRate(n),0)<=0){this.total={chargeAmount:t,discountTotal:r,discountBreakdown:this.total.discountBreakdown,netChargeAmount:n,taxTotal:e,taxBreakdown:{},grandTotal:n};return}let s=ue(n,this.pricing.applicableTaxRule),u=le(s,n,this.pricing.applicableTaxRule),a=e;u.forEach(h=>{let b=this.pricing.applicableTaxRule.find(y=>y.getTaxRuleId()===h.ruleId);o[h.ruleId]={rate:h.rate,taxableAmount:s,taxAmount:h.taxAmount,system:b.getTaxSystem(),subSystem:b.getTaxSubSystem()},a=a.add(h.taxAmount);});let d=n;this.total={chargeAmount:t,discountTotal:r,discountBreakdown:this.total.discountBreakdown,netChargeAmount:n,taxBreakdown:o,taxTotal:a,grandTotal:d};}getDetails(){return {id:this.id,name:m.deepClone(this.name),type:this.type,category:this.category,pricing:{baseChargeAmount:this.pricing.baseChargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(t=>t.getDetails())},impact:this.impact,lineItemId:this.lineItemId,total:{chargeAmount:this.total.chargeAmount.getDetails(),discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([t,r])=>[t,r.getDetails()])),netChargeAmount:this.total.netChargeAmount.getDetails(),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,r])=>[t,{rate:r.rate,taxableAmount:r.taxableAmount.getDetails(),taxAmount:r.taxAmount.getDetails(),system:r.system,subSystem:r.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};module.exports=te;//# sourceMappingURL=Charge.js.map
|
|
1
|
+
'use strict';var ge=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ge__default=/*#__PURE__*/_interopDefault(ge);var re=i=>structuredClone(i),M=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:re(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return re(this.customFields)}},B=class extends M{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,t,r,n){this.modifiedBy={id:e,authType:t,requestId:r,lambdaName:n};}};var Q=new Uint8Array(256),V=Q.length;function Z(){return V>Q.length-16&&(ge__default.default.randomFillSync(Q),V=0),Q.slice(V,V+=16)}var ie=/^(?:[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 me(i){return typeof i=="string"&&ie.test(i)}var ne=me;var p=[];for(let i=0;i<256;++i)p.push((i+256).toString(16).slice(1));function G(i,e=0){return p[i[e+0]]+p[i[e+1]]+p[i[e+2]]+p[i[e+3]]+"-"+p[i[e+4]]+p[i[e+5]]+"-"+p[i[e+6]]+p[i[e+7]]+"-"+p[i[e+8]]+p[i[e+9]]+"-"+p[i[e+10]]+p[i[e+11]]+p[i[e+12]]+p[i[e+13]]+p[i[e+14]]+p[i[e+15]]}function pe(i){if(!ne(i))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(i.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(i.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(i.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(i.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(i.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 oe=pe;function he(i){i=unescape(encodeURIComponent(i));let e=[];for(let t=0;t<i.length;++t)e.push(i.charCodeAt(t));return e}var ye="6ba7b810-9dad-11d1-80b4-00c04fd430c8",xe="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function H(i,e,t){function r(n,o,s,a){var u;if(typeof n=="string"&&(n=he(n)),typeof o=="string"&&(o=oe(o)),((u=o)===null||u===void 0?void 0:u.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+n.length);if(c.set(o),c.set(n,o.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,s){a=a||0;for(let l=0;l<16;++l)s[a+l]=c[l];return s}return G(c)}try{r.name=i;}catch{}return r.DNS=ye,r.URL=xe,r}var J={randomUUID:ge__default.default.randomUUID};function fe(i,e,t){if(J.randomUUID&&!e&&!i)return J.randomUUID();i=i||{};let r=i.random||(i.rng||Z)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){t=t||0;for(let n=0;n<16;++n)e[t+n]=r[n];return e}return G(r)}var X=fe;function Pe(i){return Array.isArray(i)?i=Buffer.from(i):typeof i=="string"&&(i=Buffer.from(i,"utf8")),ge__default.default.createHash("sha1").update(i).digest()}var se=Pe;var Ae=H("v5",80,se),W=Ae;var I={"en-IN":"en","kn-IN":"kn"};var ae={INR:"\u20B9"},ce={INR:"en-IN"};var K=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var b=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var j=class extends Error{constructor(e="Tax rule category mismatch."){super(`InvalidTaxRule: ${e}`),this.name="InvalidTaxRuleError";}},q=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},O=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";}},N=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},k=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var F=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},D=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},T=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";}},$=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}},z=class extends Error{constructor(e="Invalid charge data."){super(`InvalidCharge: ${e}`),this.name="InvalidChargeError";}},E=class extends Error{constructor(e="Invalid charge tax rule."){super(`InvalidChargeTaxRule: ${e}`),this.name="InvalidChargeTaxRuleError";}},P=class extends Error{constructor(e="Invalid pricing type."){super(`InvalidPricingType: ${e}`),this.name="InvalidPricingTypeError";}};var v=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 $("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 $("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 d=class i{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new F("Amount cannot be negative.");if(!e.currency)throw new D("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(i.getPrecisionPlaces(this.currency)));}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}getPreciseAmount(e){return parseFloat(e.toFixed(i.getPrecisionPlaces(this.currency)))}compareTo(e){if(i.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new T("Cannot compare prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(i.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new T("Cannot add prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return new i({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(i.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new T("Cannot subtract prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return new i({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(i.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new T("Cannot multiply prices in different currencies.");return new i({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new i({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new h("Must be a non-negative number.")}divide(e){if(i.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new T("Cannot divide prices in different currencies.");return new i({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new i({amount:this.getPreciseAmount(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,r)=>{if(i.isPriceModel(r)){if(t.getCurrency()!==r.getCurrency())throw new T("Cannot compare prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return t.compareTo(r)<0?t:r},this)}max(...e){if(e.length===0)throw new h("Must provide at least one PriceModel.");return e.reduce((t,r)=>{if(i.isPriceModel(r)){if(t.getCurrency()!==r.getCurrency())throw new T("Cannot compare prices in different currencies.")}else throw new h("Must be a PriceModel instance.");return t.compareTo(r)>0?t:r},this)}zero(){return new i({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new i({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return i.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return i.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,t,r={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=ce[t];if(!t||!n)throw new D("Invalid currency code for formatting.");let o=e,s=r.displayAsInteger?0:i.getDecimalPlaces(t),a={style:r.style??"currency",currency:t,signDisplay:"never",currencyDisplay:r.currencyDisplay,minimumFractionDigits:s,maximumFractionDigits:s};r.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,a).format(o)}catch(u){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,u),`${ae[t]??t} ${i.addThousandSeparators(o.toFixed(s))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static getPrecisionPlaces(e){switch(e){case"INR":default:return 6}}static addThousandSeparators(e){let t=e.split("."),r=t[0],n=t.length>1?"."+t[1]:"";return r.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,t){if(e<0)throw new F("Amount cannot be negative for rounding.");if(t===void 0)throw new D("Invalid currency code for rounding.");let r=i.getDecimalPlaces(t),n=Math.pow(10,r);return Math.round(e*n)/n}static getSmallestUnit(e){let t=i.getDecimalPlaces(e);return 1/Math.pow(10,t)}};var R=class{type;taxCategory;isTaxInclusive;static create(e){return e.type==="selection"?new ee(e):new _(e)}constructor(e){if(!e.taxCategory)throw new q;this.taxCategory=e.taxCategory,this.isTaxInclusive=e.isTaxInclusive??!1,this.type=e.type??"volume";}getType(){return this.type}getTaxCategory(){return this.taxCategory}getIsTaxInclusive(){return this.isTaxInclusive}},_=class extends R{baseUnitPrice;tiers;currency;constructor(e){if(super(e),this.type="volume",!e.baseUnitPrice)throw new f("Base unit price is required for volume pricing.");this.baseUnitPrice=new d(e.baseUnitPrice),this.currency=e.currency??this.baseUnitPrice.getCurrency();let t=(e.tiers??[]).map(a=>({enabled:a.enabled??!0,minQuantity:a.minQuantity,unitPrice:new d(a.unitPrice)})).sort((a,u)=>a.minQuantity-u.minQuantity);if(t.some(a=>a.minQuantity<=0))throw new O;if(this.baseUnitPrice.isZero()||t[0]?.unitPrice.isZero())throw new f("Base unit price and tier unit price must not be zero.");let n=this.baseUnitPrice.getCurrency()!==this.currency||t.some(a=>a.unitPrice.getCurrency()!==this.currency),o=t.some((a,u)=>u>0&&a.unitPrice.compareTo(t[u-1].unitPrice)>0),s=t[0]?.unitPrice.compareTo(this.baseUnitPrice)>0;if(n||o||s)throw new f("Tiers must share the same currency and must not increase in unit price.");this.tiers=t;}isPriceAvailable(){return this.tiers.filter(e=>e.enabled).length>0}getBaseUnitPrice(){return this.baseUnitPrice}getCurrency(){return this.baseUnitPrice.getCurrency()}getApplicableUnitPrice(e){if(e<=0)throw new N;let t=this.tiers.filter(r=>r.enabled);for(let r=t.length-1;r>=0;r--){let n=t[r];if(e>=n.minQuantity)return n.unitPrice}throw new k(e)}getMinQuantity(){return this.tiers.filter(t=>t.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(){let e=this.tiers.filter(o=>o.enabled);if(!e.length)return 0;let t=Math.min(...e.map(o=>o.unitPrice.getAmount())),r=this.baseUnitPrice.getAmount(),n=(r-t)/r*100;return n>0?n:0}getMinPrice(){let e=this.tiers.filter(t=>t.enabled);return e.length?e[e.length-1].unitPrice:null}getMaxPrice(){let e=this.tiers.filter(t=>t.enabled);return e.length?e[0].unitPrice:null}getTiers(){return this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,baseUnitPrice:this.baseUnitPrice.getDetails(),tiers:this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}},ee=class extends R{currency;selections;constructor(e){super(e),this.type="selection",this.currency=e.currency,this.selections=(e.selections??[]).map(t=>{if(!t.baseUnitPrice)throw new f("Base unit price is required for each selection.");let r=new d(t.baseUnitPrice),n=(t.tiers??[]).map(c=>({enabled:c.enabled??!0,minQuantity:c.minQuantity??1,unitPrice:new d(c.unitPrice)})).sort((c,l)=>c.minQuantity-l.minQuantity);if(n.some(c=>c.minQuantity<=0))throw new O;if(r.isZero()||n[0]?.unitPrice.isZero())throw new f("Base unit price and tier unit price must not be zero.");let s=r.getCurrency()!==this.currency||n.some(c=>c.unitPrice.getCurrency()!==this.currency),a=n.some((c,l)=>l>0&&c.unitPrice.compareTo(n[l-1].unitPrice)>0),u=n[0]?.unitPrice.compareTo(r)>0;if(s||a||u)throw new f("Tiers must share the same currency and must not increase in unit price within the same selection.");return {selectionAttributes:{...t.selectionAttributes},baseUnitPrice:r,tiers:n}});}findMatch(e,t=!1){let r=A.generateSelectionAttributesKey(e),n=this.selections.find(o=>A.generateSelectionAttributesKey(o.selectionAttributes)===r);if(!n&&t)throw new f("No pricing configuration found for selection variant.");return n??null}isPriceAvailable(e){if(!e)return console.warn("Selection attributes are required to check price availability for selection pricing."),!1;let t=this.findMatch(e);return t?t.tiers.filter(r=>r.enabled).length>0:!1}getBaseUnitPrice(e){if(!e)throw new P("Selection attributes are required to get base unit price for selection pricing.");return this.findMatch(e,!0).baseUnitPrice}getCurrency(){return this.currency}getApplicableUnitPrice(e,t){if(e<=0)throw new N;if(!t)throw new P("Selection attributes are required to get applicable unit price for selection pricing.");let n=this.findMatch(t,!0).tiers.filter(o=>o.enabled);for(let o=n.length-1;o>=0;o--){let s=n[o];if(e>=s.minQuantity)return s.unitPrice}throw new k(e)}getMinQuantity(e){if(!e)throw new P("Selection attributes are required to get min quantity for selection pricing.");return this.findMatch(e,!0).tiers.filter(n=>n.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(e){if(!e)throw new P("Selection attributes are required to get max discount for selection pricing.");let t=this.findMatch(e,!0),r=t.tiers.filter(a=>a.enabled);if(!r.length)return 0;let n=Math.min(...r.map(a=>a.unitPrice.getAmount())),o=t.baseUnitPrice.getAmount(),s=(o-n)/o*100;return s>0?s:0}getTiers(e){if(!e)throw new P("Selection attributes are required to get tiers for selection pricing.");return this.findMatch(e,!0).tiers.map(r=>({enabled:r.enabled,minQuantity:r.minQuantity,unitPrice:r.unitPrice}))}getMinPrice(e){if(!e)throw new P("Selection attributes are required to get min price for selection pricing.");let t=this.findMatch(e);if(!t)return null;let r=t.tiers.filter(n=>n.enabled);return r.length?r[r.length-1].unitPrice:null}getMaxPrice(e){if(!e)throw new P("Selection attributes are required to get max price for selection pricing.");let t=this.findMatch(e);if(!t)return null;let r=t.tiers.filter(n=>n.enabled);return r.length?r[0].unitPrice:null}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,selections:this.selections.map(e=>({selectionAttributes:e.selectionAttributes,baseUnitPrice:e.baseUnitPrice.getDetails(),...e.tiers.length>0?{tiers:e.tiers.map(t=>({enabled:t.enabled,minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}:{}}))}}};var A=class i extends B{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;productType;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new b("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 t={},r=e.split("|");for(let n of r){let[o,s]=n.split(":");s.startsWith("c+")?t[o]={name:s.slice(2)}:t[o]=s;}return t}catch(t){throw new b(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]=R.create(e.pricing[o])),n),{}),this.targetGender=e.targetGender,this.attributes=m.deepClone(e.attributes),this.specifications=m.deepClone(e.specifications),this.categories=m.deepClone(e.categories),this.productType=e.productType??"GOODS";let r=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new b("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let o=i.generateSelectionAttributesKey(n.selectionAttributes);if(r.has(o))throw new K(o);return r.add(o),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new v(n.images.primary),gallery:(n.images.gallery||[]).map(s=>new v(s))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?m.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[I[e]]??this.name.en:m.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[I[e]]??this.description.en:m.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[I[e]]??this.slug.en:m.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return m.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:m.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let t=i.generateSelectionAttributesKey(e),r=this.variants.find(n=>i.generateSelectionAttributesKey(n.selectionAttributes)===t);return r?{primary:r.images.primary,gallery:[...r.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 m.deepClone(this.categories)}getProductType(){return this.productType}getSpecifications(e){return e?m.deepClone(this.specifications[e]??this.specifications[I[e]]??this.specifications.en):m.deepClone(this.specifications)}getSearchTags(e){return e?m.deepClone(this.searchTags[e]??this.searchTags[I[e]]??this.searchTags.en):m.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,r)=>(this.pricing[r]&&(t[r]=this.pricing[r]?.getDetails()),t),{}),attributes:this.getAttributes(),variants:this.variants.map(t=>({sku:t.sku,selectionAttributes:m.deepClone(t.selectionAttributes),images:{primary:t.images.primary.getDetails(),gallery:t.images.gallery.map(r=>r.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),productType:this.getProductType(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new b("Selection attributes are required");Object.keys(this.attributes).forEach(t=>{if(t.toLowerCase()==="size")return;let r=this.attributes[t],n=e[t];if(n===void 0)throw new b(`Selection attribute '${t}' is missing`);if(typeof r=="string"){if(typeof n!="string"||r!==n)throw new b(`Selection attribute '${t}' is invalid`)}else if(Array.isArray(r)){if(r.length>0&&typeof r[0]=="string"){if(typeof n!="string"||!r.includes(n))throw new b(`Selection attribute '${t}' is invalid`)}else if(typeof n!="object"||!("name"in n)||r.findIndex(o=>o.name===n.name)<0)throw new b(`Selection attribute '${t}' is invalid`)}});}getSku(e){let t=i.generateSelectionAttributesKey(e);return this.variants.find(n=>i.generateSelectionAttributesKey(n.selectionAttributes)===t)?.sku}validateSelectionAttribute(e){let t=i.generateSelectionAttributesKey(e);return this.variants.some(r=>i.generateSelectionAttributesKey(r.selectionAttributes)===t)}validateSize(e){return this.attributes.size.includes(e)}};var Ce={isUUID:i=>/^[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(i),isEmail:i=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(i),isURL:i=>/^(http|https):\/\/[^ "]+$/.test(i),generateUUID:(i,e)=>e&&i?W(i,e):X(),generateSearchId:(i,e)=>`${i}#${A.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:i=>{let[e,t]=i.split("#");return {key:e,selectionAttributes:A.parseSelectionAttributesKey(t)}},deepClone(i){return structuredClone(i)}},m=Ce;var ue=(i,e)=>{let t=e.reduce((c,l)=>c+l.getApplicableTaxRate(i),0);if(t<=0)return i;let r=i.divide(1+t).round().getAmount(),n=i.getCurrency(),o=i.getAmount(),s=r,a=Number.POSITIVE_INFINITY,u=1e4;for(let c=0;c<u;c++){let l=new d({amount:r,currency:n}),U=e.sort((x,S)=>S.getApplicableTaxRate(l)-x.getApplicableTaxRate(l)).map(x=>l.multiply(x.getApplicableTaxRate(l)).round().getAmount()).reduce((x,S)=>x+S,0),y=r+U-o,L=e.reduce((x,S)=>x+S.getApplicableTaxRate(l),0);if(Math.abs(y)<Math.abs(a)&&(a=y,s=r),y===0)break;r=r-y/(1+L);}if(Math.abs(a)>d.getSmallestUnit(n))throw new Error("Failed to converge on a valid tax exclusive base.");return new d({amount:s,currency:n})},Ie=(i,e,t)=>{let r=i.zero(),n=[...t].sort((o,s)=>s.getApplicableTaxRate(i)-o.getApplicableTaxRate(i));return n.map((o,s)=>{let a=o.getApplicableTaxRate(i),u;return s===n.length-1?u=e.subtract(i).subtract(r):u=i.multiply(a).round(),r=r.add(u),{ruleId:o.getTaxRuleId(),taxAmount:u,rate:a}})},Se=(i,e,t)=>{let r=i.zero(),n=r,o=[];if(e){if(t.reduce((c,l)=>c+l.getApplicableTaxRate(i),0)<=0)return {entries:[],taxTotal:r,taxableBase:i};let a=ue(i,t);return Ie(a,i,t).forEach(c=>{let l=t.find(C=>C.getTaxRuleId()===c.ruleId);o.push({ruleId:c.ruleId,rate:c.rate,taxableAmount:a,taxAmount:c.taxAmount,system:l.getTaxSystem(),subSystem:l.getTaxSubSystem()}),n=n.add(c.taxAmount);}),{entries:o,taxTotal:n,taxableBase:a}}else return t.forEach(s=>{let a=s.getApplicableTaxRate(i);if(a<=0)return;let u=s.calculateTax(i);o.push({ruleId:s.getTaxRuleId(),rate:a,taxableAmount:i,taxAmount:u,system:s.getTaxSystem(),subSystem:s.getTaxSubSystem()}),n=n.add(u);}),{entries:o,taxTotal:n,taxableBase:i}},le=(i,e,t,r)=>{let n=i.subtract(e),{entries:o,taxTotal:s,taxableBase:a}=Se(n,t,r);if(t)return {taxExclusive:{baseAmount:ue(i,r),netAmount:a,grandTotal:a},taxInclusive:{baseAmount:i,netAmount:n,grandTotal:n},taxTotal:s,taxBreakdown:o,discountTotal:e};{let u=i.zero();r.forEach(C=>{u=u.add(C.calculateTax(i));});let c=i.add(u),l=n.add(s);return {taxExclusive:{baseAmount:i,netAmount:n,grandTotal:n},taxInclusive:{baseAmount:c,netAmount:l,grandTotal:l},taxTotal:s,taxBreakdown:o,discountTotal:e}}};var Y=class extends M{taxRuleId;taxCategory;taxSystem;taxSubSystem;country;rate;minPrice;maxPrice;excludeMin;excludeMax;effectiveFrom;effectiveTo;constructor(e){super(e),this.taxRuleId=e.taxRuleId,this.taxSystem=e.taxSystem,this.taxSubSystem=e.taxSubSystem,this.taxCategory=e.taxCategory,this.country=e.country,this.rate=e.rate,this.minPrice=new d(e.minPrice),this.maxPrice=e.maxPrice?new d(e.maxPrice):void 0,this.excludeMin=e.excludeMin??!1,this.excludeMax=e.excludeMax??!1,this.effectiveFrom=new Date(e.effectiveFrom).toISOString(),this.effectiveTo=e.effectiveTo?new Date(e.effectiveTo).toISOString():void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxSubSystem(){return this.taxSubSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getRate(){return this.rate}getMinPrice(){return this.minPrice}getMaxPrice(){return this.maxPrice}getExcludeMin(){return this.excludeMin}getExcludeMax(){return this.excludeMax}getEffectiveFrom(){return this.effectiveFrom}getEffectiveTo(){return this.effectiveTo}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxSubSystem:this.getTaxSubSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),rate:this.getRate(),minPrice:this.getMinPrice().getDetails(),maxPrice:this.getMaxPrice()?.getDetails(),excludeMin:this.getExcludeMin(),excludeMax:this.getExcludeMax(),effectiveFrom:this.effectiveFrom,effectiveTo:this.effectiveTo?this.effectiveTo:void 0,customFields:this.getAllCustomFields()}}appliesTo(e,t,r,n=new Date){let o=!r||(this.excludeMin?this.minPrice.compareTo(r)<0:this.minPrice.compareTo(r)<=0)&&(this.maxPrice?this.excludeMax?this.maxPrice.compareTo(r)>0:this.maxPrice.compareTo(r)>=0:!0);return this.taxCategory===e&&this.country===t&&o&&Date.parse(this.effectiveFrom)<=n.getTime()&&(this.effectiveTo?Date.parse(this.effectiveTo)>=n.getTime():!0)}getApplicableTaxRate(e){return this.appliesTo(this.taxCategory,this.country,e)?this.rate:0}calculateTax(e){return this.appliesTo(this.taxCategory,this.country,e)?e.multiply(this.rate).round():e.zero()}static getTaxRateDisplayString(e,t,r){let n=t*100,o=n%1===0?n.toString():n.toFixed(2).replace(/\.?0+$/,"");return r?.percentageOnly?`${o}%`:e.getTaxSystem()==="GST"?`${e.getTaxSubSystem()} ${o}%`:`${e.getTaxSystem()} ${o}%`}};var te=class extends M{id;name;type;category;impact;pricing;lineItemId;total;constructor(e){if(super(e),this.id=e.id,this.name=e.name,this.type=e.type,this.category=e.category,this.impact=e.impact,this.lineItemId=e.lineItemId,this.pricing={baseChargeAmount:new d(e.pricing.baseChargeAmount),taxCategory:e.pricing.taxCategory,applicableTaxRule:e.pricing.applicableTaxRule.map(t=>new Y(t)),isTaxInclusive:e.pricing.isTaxInclusive??!1},this.validateTaxRules(this.pricing.applicableTaxRule),this.impact==="SUBTRACT"&&this.type!=="ADJUSTMENT")throw new z("SUBTRACT impact is only allowed for ADJUSTMENT charge");this.total={discountTotal:new d(e.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(e.total.discountBreakdown).map(([t,r])=>[t,new d(r)])),taxBreakdown:Object.fromEntries(Object.entries(e.total.taxBreakdown).map(([t,r])=>[t,{rate:r.rate,taxableAmount:new d(r.taxableAmount),taxAmount:new d(r.taxAmount),system:r.system,subSystem:r.subSystem}])),taxTotal:new d(e.total.taxTotal),taxExclusive:{chargeAmount:new d(e.total.taxExclusive.chargeAmount),netChargeAmount:new d(e.total.taxExclusive.netChargeAmount)},taxInclusive:{chargeAmount:new d(e.total.taxInclusive.chargeAmount),netChargeAmount:new d(e.total.taxInclusive.netChargeAmount)},grandTotal:new d(e.total.grandTotal)};}getId(){return this.id}getName(e){return e?m.deepClone(this.name[e]??this.name[I[e]]??this.name.en):m.deepClone(this.name)}getCategory(){return this.category}getType(){return this.type}getImpact(){return this.impact}getLineItemId(){return this.lineItemId}getIsTaxInclusive(){return this.pricing.isTaxInclusive}getPricing(){return {baseChargeAmount:this.pricing.baseChargeAmount,taxCategory:this.pricing.taxCategory,applicableTaxRule:[...this.pricing.applicableTaxRule],isTaxInclusive:this.pricing.isTaxInclusive}}getTotal(){return {discountTotal:this.total.discountTotal,discountBreakdown:{...this.total.discountBreakdown},taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([e,t])=>[e,{rate:t.rate,taxableAmount:t.taxableAmount,taxAmount:t.taxAmount,system:t.system,subSystem:t.subSystem}])),taxExclusive:{chargeAmount:this.total.taxExclusive.chargeAmount,netChargeAmount:this.total.taxExclusive.netChargeAmount},taxInclusive:{chargeAmount:this.total.taxInclusive.chargeAmount,netChargeAmount:this.total.taxInclusive.netChargeAmount},grandTotal:this.total.grandTotal}}getApplicableTaxRules(){return [...this.pricing.applicableTaxRule]}updateTax(e){if(this.type==="ADJUSTMENT"&&e.length>0)throw new z("Adjustment charges cannot apply tax rules.");e.forEach(t=>{if(!t.appliesTo(this.pricing.taxCategory,t.getCountry()))throw new j}),this.validateTaxRules(e),this.pricing.applicableTaxRule=e,this.calculateTotals();}validateTaxRules(e){if(this.impact==="SUBTRACT"&&e.some(r=>r.getRate()>0))throw new E("Subtractive charges cannot have positive tax rates.");let t=new Set;for(let r=0;r<e.length;r++){let n=e[r].getTaxRuleId();if(t.has(n))throw new E("Duplicate tax rule ID found: "+n);t.add(n);for(let o=r+1;o<e.length;o++){let s=e[r],a=e[o],u=s.getMinPrice(),c=s.getMaxPrice(),l=s.getExcludeMin(),C=s.getExcludeMax(),U=a.getMinPrice(),y=a.getMaxPrice(),L=a.getExcludeMin(),x=a.getExcludeMax(),S=(()=>{if(!c)return !1;let w=c.compareTo(U);return w<0||w===0&&(C||L)})(),de=(()=>{if(!y)return !1;let w=y.compareTo(u);return w<0||w===0&&(x||l)})();if(!(S||de)&&!(u.compareTo(U)===0&&l===L&&C===x&&(!c&&!y||c&&y&&c.compareTo(y)===0)))throw new E(`Overlapping rules found: [${s.getTaxRuleId()}: ${l?"(":"["}${u.getAmount()}-${c?.getAmount()??"Infinity"}${C?")":"]"}] and [${a.getTaxRuleId()}: ${L?"(":"["}${U.getAmount()}-${y?.getAmount()??"Infinity"}${x?")":"]"}]`)}}}updateDiscounts(e){let t={};e.forEach(r=>{t[r.coupon.getCode()]=r.amount;}),this.total.discountBreakdown=t,this.calculateTotals();}calculateTotals(){let e=this.pricing.baseChargeAmount.zero(),t=Object.values(this.total.discountBreakdown).reduce((o,s)=>o.add(s),e),r=le(this.pricing.baseChargeAmount,t,this.pricing.isTaxInclusive,this.pricing.applicableTaxRule),n={};r.taxBreakdown.forEach(o=>{n[o.ruleId]={rate:o.rate,taxableAmount:o.taxableAmount,taxAmount:o.taxAmount,system:o.system,subSystem:o.subSystem};}),this.total={discountTotal:r.discountTotal,discountBreakdown:this.total.discountBreakdown,taxTotal:r.taxTotal,taxBreakdown:n,taxExclusive:{chargeAmount:r.taxExclusive.baseAmount,netChargeAmount:r.taxExclusive.netAmount},taxInclusive:{chargeAmount:r.taxInclusive.baseAmount,netChargeAmount:r.taxInclusive.netAmount},grandTotal:r.taxInclusive.grandTotal};}getDetails(){return {id:this.id,name:m.deepClone(this.name),type:this.type,category:this.category,pricing:{baseChargeAmount:this.pricing.baseChargeAmount.getDetails(),taxCategory:this.pricing.taxCategory,applicableTaxRule:this.pricing.applicableTaxRule.map(t=>t.getDetails()),isTaxInclusive:this.pricing.isTaxInclusive},impact:this.impact,lineItemId:this.lineItemId,total:{discountTotal:this.total.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(this.total.discountBreakdown).map(([t,r])=>[t,r.getDetails()])),taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,r])=>[t,{rate:r.rate,taxableAmount:r.taxableAmount.getDetails(),taxAmount:r.taxAmount.getDetails(),system:r.system,subSystem:r.subSystem}])),taxTotal:this.total.taxTotal.getDetails(),taxExclusive:{chargeAmount:this.total.taxExclusive.chargeAmount.getDetails(),netChargeAmount:this.total.taxExclusive.netChargeAmount.getDetails()},taxInclusive:{chargeAmount:this.total.taxInclusive.chargeAmount.getDetails(),netChargeAmount:this.total.taxInclusive.netChargeAmount.getDetails()},grandTotal:this.total.grandTotal.getDetails()},customFields:this.getAllCustomFields()}}};module.exports=te;//# sourceMappingURL=Charge.js.map
|
|
2
2
|
//# sourceMappingURL=Charge.js.map
|