b23-lib 3.2.0 → 3.2.2
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.mjs +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Charge.mjs +1 -1
- package/dist/Classes/Coupon.mjs +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/Invoice.d.mts +29 -9
- package/dist/Classes/Invoice.d.ts +29 -9
- 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.mjs +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/Product.mjs +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/{chunk-B2VFJRLS.mjs → chunk-5IRYC2KY.mjs} +2 -2
- package/dist/{chunk-B2VFJRLS.mjs.map → chunk-5IRYC2KY.mjs.map} +1 -1
- package/dist/{chunk-FR22CXZF.mjs → chunk-MJGCYQ53.mjs} +2 -2
- package/dist/{chunk-FR22CXZF.mjs.map → chunk-MJGCYQ53.mjs.map} +1 -1
- package/dist/{chunk-RQ2FFWUW.mjs → chunk-PWWKQNF7.mjs} +2 -2
- package/dist/{chunk-RQ2FFWUW.mjs.map → chunk-PWWKQNF7.mjs.map} +1 -1
- package/dist/{chunk-MHLRJ4IJ.mjs → chunk-QGIQ3MH6.mjs} +2 -2
- package/dist/{chunk-MHLRJ4IJ.mjs.map → chunk-QGIQ3MH6.mjs.map} +1 -1
- package/dist/{chunk-BSDPFVRK.mjs → chunk-XJPFHEW3.mjs} +2 -2
- package/dist/{chunk-BSDPFVRK.mjs.map → chunk-XJPFHEW3.mjs.map} +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/Auth/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1,b,d,c as c$1}from'../chunk-AMIRIUMH.mjs';import {a as a$2}from'../chunk-
|
|
1
|
+
import {a as a$1,b,d,c as c$1}from'../chunk-AMIRIUMH.mjs';import {a as a$2}from'../chunk-QGIQ3MH6.mjs';import'../chunk-FCRJAAPY.mjs';import'../chunk-LI5JQ6UC.mjs';import'../chunk-QK4XJ3GB.mjs';import'../chunk-2B2XI6FG.mjs';import'../chunk-R5DM7WCD.mjs';import'../chunk-UXZBULDS.mjs';import {importPKCS8,SignJWT,importSPKI,jwtVerify,decodeJwt}from'jose';import a from'assert';var c=class l{static instance=null;id;type;token;initializedAt;lambdaName;requestId;constructor(e,t,i,r){this.id=e,this.type=t,this.token=i,this.lambdaName=process.env.AWS_LAMBDA_FUNCTION_NAME,this.initializedAt=new Date;}static getInstance(){return a(l.instance,a$1.AUTH_CONTEXT_NOT_INITIALIZED),l.instance}static init(e,t,i,r){return l.instance=new l(e,t,i,r),l.instance}static uninit(){l.instance=null;}getId(){return this.id}getType(){return this.type}getToken(){return this.token}getLambdaName(){return this.lambdaName}getRequestId(){return this.requestId}getInitializedAt(){return this.initializedAt}getSystemID(e){let t=this.lambdaName||e;return this.requestId?`${t} - ${this.requestId}`:t}};var K={userTokenAge:"30 days",userPrivateKeys:"[]",userPublicKeys:"[]",anonymousTokenAge:"30 days",anonymousPrivateKeys:"[]",anonymousPublicKeys:"[]",systemTokenAge:"5 min",systemPrivateKeys:"[]",systemPublicKeys:"[]",adminTokenAge:"30 days",adminPrivateKeys:"[]",adminPublicKeys:"[]",cdnKeys:"[]"},U=(n=>(n.ANON="Anon",n.USER="User",n.SYSTEM="System",n.ADMIN="Admin",n.CDN="CDN",n))(U||{}),v={allowAnonymous:!1,allowSystem:!0,allowUser:!0,allowCDN:!1},N=class{userTokenAge;userPrivateKeys;userPublicKeys;anonymousTokenAge;anonymousPrivateKeys;anonymousPublicKeys;systemTokenAge;systemPrivateKeys;systemPublicKeys;adminTokenAge;adminPrivateKeys;adminPublicKeys;cdnKeys;constructor(e=K){let{userTokenAge:t,userPrivateKeys:i,userPublicKeys:r,anonymousTokenAge:n,anonymousPrivateKeys:g,anonymousPublicKeys:h,systemTokenAge:m,systemPrivateKeys:T,systemPublicKeys:A,adminTokenAge:u,adminPrivateKeys:d,adminPublicKeys:S,cdnKeys:f}={...K,...e};this.userTokenAge=t,this.userPrivateKeys=this.parseKeyArray(i,"user private"),this.userPublicKeys=this.parseKeyArray(r,"user public"),this.anonymousTokenAge=n,this.anonymousPrivateKeys=this.parseKeyArray(g,"anonymous private"),this.anonymousPublicKeys=this.parseKeyArray(h,"anonymous public"),this.systemTokenAge=m,this.systemPrivateKeys=this.parseKeyArray(T,"system private"),this.systemPublicKeys=this.parseKeyArray(A,"system public"),this.adminTokenAge=u,this.adminPrivateKeys=this.parseKeyArray(d,"admin private"),this.adminPublicKeys=this.parseKeyArray(S,"admin public"),this.cdnKeys=this.parseKeyArray(f,"cdn"),this.logWarnings();}parseKeyArray(e,t){try{let i=JSON.parse(e);return !Array.isArray(i)||!i.every(r=>typeof r=="string")?(b.logError("AuthUtility",`Invalid format for ${t} keys in config: Expected stringified array of strings.`),[]):i}catch(i){return b.logError("AuthUtility",`Failed to parse ${t} keys from config: ${i}`),[]}}logWarnings(){let e=(t,i,r)=>i.length>r&&b.logWarning("AuthUtility",`More than ${r} ${t} keys provided. This is not recommended.`);e("user private",this.userPrivateKeys,3),e("user public",this.userPublicKeys,3),e("anonymous private",this.anonymousPrivateKeys,1),e("anonymous public",this.anonymousPublicKeys,3),e("system private",this.systemPrivateKeys,1),e("system public",this.systemPublicKeys,3),e("admin private",this.adminPrivateKeys,1),e("admin public",this.adminPublicKeys,3);}async createSignedJWT(e,t,i){let r=await importPKCS8(t,"RS256");return await new SignJWT(e).setProtectedHeader({alg:"RS256"}).setExpirationTime(i).setIssuedAt().sign(r)}async verifySignedJWT(e,t,i){for(let r=t.length-1;r>=0;r--)try{let n=await importSPKI(t[r],"RS256");return (await jwtVerify(e,n,{clockTolerance:30,maxTokenAge:i})).payload}catch(n){if(r===0)throw n;continue}throw new Error(a$1.INVALID_TOKEN)}async createAnonymousToken(e,t){a(this.anonymousPrivateKeys.length,a$1.ANONYMOUS_PRIVATE_KEY_NOT_FOUND),a(a$2.isUUID(e),a$1.INVALID_UUID);let i={id:e,type:"Anon",...t};return await this.createSignedJWT(i,this.anonymousPrivateKeys[this.anonymousPrivateKeys.length-1],this.anonymousTokenAge)}async verifyAnonymousToken(e){a(this.anonymousPublicKeys.length,a$1.ANONYMOUS_PUBLIC_KEY_NOT_FOUND);let t=await this.verifySignedJWT(e,this.anonymousPublicKeys,this.anonymousTokenAge);return a(t.type==="Anon",a$1.INVALID_AUTH_TYPE),t}async createUserToken(e,t){a(this.userPrivateKeys.length,a$1.USER_PRIVATE_KEY_NOT_FOUND),a(a$2.isUUID(e),a$1.INVALID_UUID);let i={id:e,type:"User",...t};return await this.createSignedJWT(i,this.userPrivateKeys[this.userPrivateKeys.length-1],this.userTokenAge)}async verifyUserToken(e){a(this.userPublicKeys.length,a$1.USER_PUBLIC_KEY_NOT_FOUND);let t=await this.verifySignedJWT(e,this.userPublicKeys,this.userTokenAge);return a(t.type==="User",a$1.INVALID_AUTH_TYPE),t}async createSystemToken(e,t){a(this.systemPrivateKeys.length,a$1.SYSTEM_PRIVATE_KEY_NOT_FOUND);let i={id:e,type:"System",...t};return await this.createSignedJWT(i,this.systemPrivateKeys[this.systemPrivateKeys.length-1],this.systemTokenAge)}async verifySystemToken(e){a(this.systemPublicKeys.length,a$1.USER_PUBLIC_KEY_NOT_FOUND);let t=await this.verifySignedJWT(e,this.systemPublicKeys,this.systemTokenAge);return a(t.type==="System",a$1.INVALID_AUTH_TYPE),t}async createAdminToken(e,t,i){a(this.adminPrivateKeys.length,a$1.ADMIN_PRIVATE_KEY_NOT_FOUND),a(a$2.isEmail(e),a$1.INVALID_EMAIL),a(a$2.isURL(t),a$1.INVALID_VERIFIER);let r={id:e,type:"Admin",verifier:t,...i};return await this.createSignedJWT(r,this.adminPrivateKeys[this.adminPrivateKeys.length-1],this.adminTokenAge)}async verifyAdminToken(e,t,i){a(this.adminPublicKeys.length,a$1.ADMIN_PUBLIC_KEY_NOT_FOUND);let r=await this.verifySignedJWT(e,this.adminPublicKeys,this.adminTokenAge);if(a(r.type==="Admin",a$1.INVALID_AUTH_TYPE),i){let n=await d(r.verifier,"","POST",{},{token:e,permissions:t});if(a(n.data.isTokenValid===!0,a$1.INVALID_TOKEN),n.data.hasPermissions!==!0)throw c$1.generateError(403,a$1.INVALID_PERMISSIONS)}return r}async verifyCDNToken(e){return a(this.cdnKeys.includes(e),a$1.INVALID_TOKEN),{id:e,type:"CDN"}}AuthMiddleware(e=v,t=[]){let{allowAnonymous:i,allowSystem:r,allowUser:n,allowCDN:g}={...v,...e};return async(h,m,T)=>{try{let[A,u]=h.get("Authorization")?.split(" ")||[];if(!u)throw new Error(a$1.INVALID_TOKEN);let d;switch(A){case"Anon":if(!i)throw c$1.generateError(403,a$1.ANONYMOUS_SESSION_NOT_ALLOWED);d=await this.verifyAnonymousToken(u);break;case"User":if(!n)throw c$1.generateError(403,a$1.USER_SESSION_NOT_ALLOWED);d=await this.verifyUserToken(u);break;case"System":if(!r)throw c$1.generateError(403,a$1.SYSTEM_SESSION_NOT_ALLOWED);d=await this.verifySystemToken(u);break;case"Admin":d=await this.verifyAdminToken(u,t,!0);break;case"CDN":if(!g)throw c$1.generateError(403,a$1.CDN_SESSION_NOT_ALLOWED);d=await this.verifyCDNToken(u);break;default:throw c$1.generateError(403,a$1.INVALID_AUTH_TYPE)}T();}catch(A){b.logError("AuthMiddleware",A),c$1.handleException("AuthMiddleware",c$1.generateError(401,A.error||a$1.TOKEN_EXPIRED,!0),m);}}}decodeJWTPayloadWithJose(e){if(!e||typeof e!="string")return b.logError("AuthContextMiddleware","Invalid token provided for decoding."),null;try{return decodeJwt(e)}catch(t){return b.logError("AuthContextMiddleware",`Failed to decode JWT payload: ${t}`),null}}AuthContextMiddleware(){return async(e,t,i)=>{try{let[r,n]=e.get("Authorization")?.split(" ")||[],g=r==="CDN"?{id:n,type:"CDN"}:r?this.decodeJWTPayloadWithJose(n):{},h=c.init(g?.id||n,g?.type||r,n,e.get("x-request-id"));b.logMessage("AuthContextMiddleware",`AuthContext initialized: ${h.getType()||"No-Type"} - ${h.getId()||"No-Id"}`),t.on("finish",()=>{b.logMessage("AuthContextMiddleware","Uninitializing AuthContext"),c.uninit();}),i();}catch(r){b.logError("AuthContextMiddleware",r),c$1.handleException("AuthContextMiddleware",c$1.generateError(500,r.error||a$1.INTERNAL_SERVER_ERROR,!0),t);}}}},j=N;export{c as AuthContext,U as AuthType,v as DefaultAuthMiddlewareConfig,K as DefaultAuthUtilityConfig,j as default};//# sourceMappingURL=index.mjs.map
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/Classes/Cart.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'../chunk-
|
|
1
|
+
import {a}from'../chunk-MJGCYQ53.mjs';import'../chunk-5IRYC2KY.mjs';import'../chunk-HX32EJ3F.mjs';import'../chunk-XJPFHEW3.mjs';import'../chunk-SOZHGHMY.mjs';import'../chunk-PWWKQNF7.mjs';import {b}from'../chunk-QGIQ3MH6.mjs';import'../chunk-FCRJAAPY.mjs';import'../chunk-LI5JQ6UC.mjs';import'../chunk-QK4XJ3GB.mjs';import'../chunk-2B2XI6FG.mjs';import {a as a$1}from'../chunk-R5DM7WCD.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.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){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
|
package/dist/Classes/Charge.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as default}from'../chunk-
|
|
1
|
+
export{a as default}from'../chunk-XJPFHEW3.mjs';import'../chunk-SOZHGHMY.mjs';import'../chunk-QGIQ3MH6.mjs';import'../chunk-FCRJAAPY.mjs';import'../chunk-LI5JQ6UC.mjs';import'../chunk-QK4XJ3GB.mjs';import'../chunk-2B2XI6FG.mjs';import'../chunk-R5DM7WCD.mjs';import'../chunk-UXZBULDS.mjs';//# sourceMappingURL=Charge.mjs.map
|
|
2
2
|
//# sourceMappingURL=Charge.mjs.map
|
package/dist/Classes/Coupon.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{d as ApplicableTo,c as CouponCategory,b as CouponDiscountMethod,a as CouponType,e as default}from'../chunk-
|
|
1
|
+
export{d as ApplicableTo,c as CouponCategory,b as CouponDiscountMethod,a as CouponType,e as default}from'../chunk-PWWKQNF7.mjs';import'../chunk-QGIQ3MH6.mjs';import'../chunk-FCRJAAPY.mjs';import'../chunk-LI5JQ6UC.mjs';import'../chunk-QK4XJ3GB.mjs';import'../chunk-2B2XI6FG.mjs';import'../chunk-R5DM7WCD.mjs';import'../chunk-UXZBULDS.mjs';//# sourceMappingURL=Coupon.mjs.map
|
|
2
2
|
//# sourceMappingURL=Coupon.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a,b as b$1}from'../chunk-
|
|
1
|
+
import {a,b as b$1}from'../chunk-QGIQ3MH6.mjs';import'../chunk-FCRJAAPY.mjs';import'../chunk-LI5JQ6UC.mjs';import'../chunk-QK4XJ3GB.mjs';import'../chunk-2B2XI6FG.mjs';import'../chunk-R5DM7WCD.mjs';import {b}from'../chunk-UXZBULDS.mjs';var u=class extends b{productKey;stocks;constructor(r,o=new Date){super(r,o),this.productKey=r.productKey,this.stocks=r.stocks.map(e=>({selectionAttributes:a.deepClone(e.selectionAttributes),size:e.size,available:e.available,country:e.country}));}getProductKey(){return this.productKey}getStockData(r,o,e){let n=r?b$1.generateSelectionAttributesKey(r):void 0;return this.stocks.filter(t=>!(n&&b$1.generateSelectionAttributesKey(t.selectionAttributes)!==n||o&&t.size!==o||e&&t.country!==e)).map(t=>({selectionAttributes:a.deepClone(t.selectionAttributes),size:t.size,available:t.available,country:t.country}))}getDetails(){return {...super.getDetails(),productKey:this.getProductKey(),stocks:this.getStockData()}}};export{u as InventoryModel};//# sourceMappingURL=Inventory.mjs.map
|
|
2
2
|
//# sourceMappingURL=Inventory.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TaxSystem } from './Enum.mjs';
|
|
1
|
+
import { TaxSystem, ChargeType, ChargeImpact } from './Enum.mjs';
|
|
2
2
|
import { P as PriceData, a as PriceModel, b as Prettify, C as CountryCode, c as CurrencyCode, L as LocaleCode } from '../Common-DY253_Gs.mjs';
|
|
3
3
|
import AddressModel, { AddressData } from './Address.mjs';
|
|
4
4
|
import { ShoppingContainerTotal, ShoppingContainerTotalModel } from './ShoppingContainer.mjs';
|
|
@@ -32,20 +32,23 @@ type InvoiceLineItemData = {
|
|
|
32
32
|
name: string;
|
|
33
33
|
variantLabel: string;
|
|
34
34
|
quantity: number;
|
|
35
|
-
netUnitPrice:
|
|
36
|
-
netSubtotal:
|
|
37
|
-
taxTotal:
|
|
38
|
-
grandTotal:
|
|
35
|
+
netUnitPrice: PriceData;
|
|
36
|
+
netSubtotal: PriceData;
|
|
37
|
+
taxTotal: PriceData;
|
|
38
|
+
grandTotal: PriceData;
|
|
39
39
|
taxBreakdown: Record<string, InvoiceTaxBreakdown>;
|
|
40
40
|
taxCode: string;
|
|
41
41
|
taxCodeType: string;
|
|
42
42
|
};
|
|
43
43
|
type InvoiceChargeData = {
|
|
44
44
|
id: string;
|
|
45
|
+
type: ChargeType;
|
|
46
|
+
category: string;
|
|
47
|
+
impact: ChargeImpact;
|
|
45
48
|
name: string;
|
|
46
|
-
taxableValue:
|
|
47
|
-
taxTotal:
|
|
48
|
-
grandTotal:
|
|
49
|
+
taxableValue: PriceData;
|
|
50
|
+
taxTotal: PriceData;
|
|
51
|
+
grandTotal: PriceData;
|
|
49
52
|
taxBreakdown: Record<string, InvoiceTaxBreakdown>;
|
|
50
53
|
taxCode: string;
|
|
51
54
|
taxCodeType: string;
|
|
@@ -56,6 +59,20 @@ type InvoiceTaxContextData = {
|
|
|
56
59
|
supplyRegion: string;
|
|
57
60
|
supplyRegionCode: string;
|
|
58
61
|
};
|
|
62
|
+
type MerchantData = {
|
|
63
|
+
merchantName: string;
|
|
64
|
+
taxIdentifier: string;
|
|
65
|
+
email: string;
|
|
66
|
+
phone: string;
|
|
67
|
+
address: AddressData;
|
|
68
|
+
};
|
|
69
|
+
type MerchantModel = {
|
|
70
|
+
merchantName: string;
|
|
71
|
+
taxIdentifier: string;
|
|
72
|
+
email: string;
|
|
73
|
+
phone: string;
|
|
74
|
+
address: AddressModel;
|
|
75
|
+
};
|
|
59
76
|
type InvoiceTotal = ShoppingContainerTotal;
|
|
60
77
|
type InvoiceTotalModel = ShoppingContainerTotalModel;
|
|
61
78
|
type InvoiceAttributes = Prettify<BaseAttributes & {
|
|
@@ -70,6 +87,7 @@ type InvoiceAttributes = Prettify<BaseAttributes & {
|
|
|
70
87
|
billingAddress: AddressData;
|
|
71
88
|
shippingAddress: AddressData;
|
|
72
89
|
taxContext: InvoiceTaxContextData;
|
|
90
|
+
merchant: MerchantData;
|
|
73
91
|
lineItems: InvoiceLineItemData[];
|
|
74
92
|
charges: InvoiceChargeData[];
|
|
75
93
|
total: InvoiceTotal;
|
|
@@ -87,6 +105,7 @@ declare class InvoiceModel extends BaseModel {
|
|
|
87
105
|
protected billingAddress: AddressModel;
|
|
88
106
|
protected shippingAddress: AddressModel;
|
|
89
107
|
protected taxContext: InvoiceTaxContextData;
|
|
108
|
+
protected merchant: MerchantModel;
|
|
90
109
|
protected lineItems: InvoiceLineItemData[];
|
|
91
110
|
protected charges: InvoiceChargeData[];
|
|
92
111
|
protected total: InvoiceTotalModel;
|
|
@@ -111,10 +130,11 @@ declare class InvoiceModel extends BaseModel {
|
|
|
111
130
|
getPlaceOfSupplyCode(): string;
|
|
112
131
|
getSupplyRegion(): string;
|
|
113
132
|
getSupplyRegionCode(): string;
|
|
133
|
+
getMerchant(): MerchantModel;
|
|
114
134
|
getLineItems(): InvoiceLineItemData[];
|
|
115
135
|
getCharges(): InvoiceChargeData[];
|
|
116
136
|
getTotal(): InvoiceTotalModel;
|
|
117
137
|
getDetails(): InvoiceData;
|
|
118
138
|
}
|
|
119
139
|
|
|
120
|
-
export { type InvoiceAttributes, type InvoiceChargeData, type InvoiceData, type InvoiceLineItemData, type InvoiceTaxBreakdown, type InvoiceTaxBreakdownModel, type InvoiceTaxContextData, type InvoiceTotal, type InvoiceTotalModel, InvoiceModel as default };
|
|
140
|
+
export { type InvoiceAttributes, type InvoiceChargeData, type InvoiceData, type InvoiceLineItemData, type InvoiceTaxBreakdown, type InvoiceTaxBreakdownModel, type InvoiceTaxContextData, type InvoiceTotal, type InvoiceTotalModel, type MerchantData, type MerchantModel, InvoiceModel as default };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TaxSystem } from './Enum.js';
|
|
1
|
+
import { TaxSystem, ChargeType, ChargeImpact } from './Enum.js';
|
|
2
2
|
import { P as PriceData, a as PriceModel, b as Prettify, C as CountryCode, c as CurrencyCode, L as LocaleCode } from '../Common-BPgGKaZC.js';
|
|
3
3
|
import AddressModel, { AddressData } from './Address.js';
|
|
4
4
|
import { ShoppingContainerTotal, ShoppingContainerTotalModel } from './ShoppingContainer.js';
|
|
@@ -32,20 +32,23 @@ type InvoiceLineItemData = {
|
|
|
32
32
|
name: string;
|
|
33
33
|
variantLabel: string;
|
|
34
34
|
quantity: number;
|
|
35
|
-
netUnitPrice:
|
|
36
|
-
netSubtotal:
|
|
37
|
-
taxTotal:
|
|
38
|
-
grandTotal:
|
|
35
|
+
netUnitPrice: PriceData;
|
|
36
|
+
netSubtotal: PriceData;
|
|
37
|
+
taxTotal: PriceData;
|
|
38
|
+
grandTotal: PriceData;
|
|
39
39
|
taxBreakdown: Record<string, InvoiceTaxBreakdown>;
|
|
40
40
|
taxCode: string;
|
|
41
41
|
taxCodeType: string;
|
|
42
42
|
};
|
|
43
43
|
type InvoiceChargeData = {
|
|
44
44
|
id: string;
|
|
45
|
+
type: ChargeType;
|
|
46
|
+
category: string;
|
|
47
|
+
impact: ChargeImpact;
|
|
45
48
|
name: string;
|
|
46
|
-
taxableValue:
|
|
47
|
-
taxTotal:
|
|
48
|
-
grandTotal:
|
|
49
|
+
taxableValue: PriceData;
|
|
50
|
+
taxTotal: PriceData;
|
|
51
|
+
grandTotal: PriceData;
|
|
49
52
|
taxBreakdown: Record<string, InvoiceTaxBreakdown>;
|
|
50
53
|
taxCode: string;
|
|
51
54
|
taxCodeType: string;
|
|
@@ -56,6 +59,20 @@ type InvoiceTaxContextData = {
|
|
|
56
59
|
supplyRegion: string;
|
|
57
60
|
supplyRegionCode: string;
|
|
58
61
|
};
|
|
62
|
+
type MerchantData = {
|
|
63
|
+
merchantName: string;
|
|
64
|
+
taxIdentifier: string;
|
|
65
|
+
email: string;
|
|
66
|
+
phone: string;
|
|
67
|
+
address: AddressData;
|
|
68
|
+
};
|
|
69
|
+
type MerchantModel = {
|
|
70
|
+
merchantName: string;
|
|
71
|
+
taxIdentifier: string;
|
|
72
|
+
email: string;
|
|
73
|
+
phone: string;
|
|
74
|
+
address: AddressModel;
|
|
75
|
+
};
|
|
59
76
|
type InvoiceTotal = ShoppingContainerTotal;
|
|
60
77
|
type InvoiceTotalModel = ShoppingContainerTotalModel;
|
|
61
78
|
type InvoiceAttributes = Prettify<BaseAttributes & {
|
|
@@ -70,6 +87,7 @@ type InvoiceAttributes = Prettify<BaseAttributes & {
|
|
|
70
87
|
billingAddress: AddressData;
|
|
71
88
|
shippingAddress: AddressData;
|
|
72
89
|
taxContext: InvoiceTaxContextData;
|
|
90
|
+
merchant: MerchantData;
|
|
73
91
|
lineItems: InvoiceLineItemData[];
|
|
74
92
|
charges: InvoiceChargeData[];
|
|
75
93
|
total: InvoiceTotal;
|
|
@@ -87,6 +105,7 @@ declare class InvoiceModel extends BaseModel {
|
|
|
87
105
|
protected billingAddress: AddressModel;
|
|
88
106
|
protected shippingAddress: AddressModel;
|
|
89
107
|
protected taxContext: InvoiceTaxContextData;
|
|
108
|
+
protected merchant: MerchantModel;
|
|
90
109
|
protected lineItems: InvoiceLineItemData[];
|
|
91
110
|
protected charges: InvoiceChargeData[];
|
|
92
111
|
protected total: InvoiceTotalModel;
|
|
@@ -111,10 +130,11 @@ declare class InvoiceModel extends BaseModel {
|
|
|
111
130
|
getPlaceOfSupplyCode(): string;
|
|
112
131
|
getSupplyRegion(): string;
|
|
113
132
|
getSupplyRegionCode(): string;
|
|
133
|
+
getMerchant(): MerchantModel;
|
|
114
134
|
getLineItems(): InvoiceLineItemData[];
|
|
115
135
|
getCharges(): InvoiceChargeData[];
|
|
116
136
|
getTotal(): InvoiceTotalModel;
|
|
117
137
|
getDetails(): InvoiceData;
|
|
118
138
|
}
|
|
119
139
|
|
|
120
|
-
export { type InvoiceAttributes, type InvoiceChargeData, type InvoiceData, type InvoiceLineItemData, type InvoiceTaxBreakdown, type InvoiceTaxBreakdownModel, type InvoiceTaxContextData, type InvoiceTotal, type InvoiceTotalModel, InvoiceModel as default };
|
|
140
|
+
export { type InvoiceAttributes, type InvoiceChargeData, type InvoiceData, type InvoiceLineItemData, type InvoiceTaxBreakdown, type InvoiceTaxBreakdownModel, type InvoiceTaxContextData, type InvoiceTotal, type InvoiceTotalModel, type MerchantData, type MerchantModel, InvoiceModel as default };
|
package/dist/Classes/Invoice.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var x={INR:"\u20B9"},I={INR:"en-IN"};var m=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";}},c=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},o=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}};var n=class r{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new m("Amount cannot be negative.");if(!e.currency)throw new d("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(r.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(r.getPrecisionPlaces(this.currency)))}compareTo(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new c("Cannot compare prices in different currencies.")}else throw new o("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new c("Cannot add prices in different currencies.")}else throw new o("Must be a PriceModel instance.");return new r({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new c("Cannot subtract prices in different currencies.")}else throw new o("Must be a PriceModel instance.");return new r({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new c("Cannot multiply prices in different currencies.");return new r({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new r({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new o("Must be a non-negative number.")}divide(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new c("Cannot divide prices in different currencies.");return new r({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new r({amount:this.getPreciseAmount(this.amount/e),currency:this.currency});throw new o("Must be a positive number.")}min(...e){if(e.length===0)throw new o("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new c("Cannot compare prices in different currencies.")}else throw new o("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i},this)}max(...e){if(e.length===0)throw new o("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new c("Cannot compare prices in different currencies.")}else throw new o("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 s=I[t];if(!t||!s)throw new d("Invalid currency code for formatting.");let a=e,p=i.displayAsInteger?0:r.getDecimalPlaces(t),A={style:i.style??"currency",currency:t,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:p,maximumFractionDigits:p};i.displayAsInteger&&(a=Math.ceil(a));try{return new Intl.NumberFormat(s,A).format(a)}catch(b){return console.error(`Error formatting price for currency "${t}" and locale "${s}":`,b),`${x[t]??t} ${r.addThousandSeparators(a.toFixed(p))}`}}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("."),i=t[0],s=t.length>1?"."+t[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+s}static getRoundedAmount(e,t){if(e<0)throw new m("Amount cannot be negative for rounding.");if(t===void 0)throw new d("Invalid currency code for rounding.");let i=r.getDecimalPlaces(t),s=Math.pow(10,i);return Math.round(e*s)/s}};var C=r=>structuredClone(r),h=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:C(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return C(this.customFields)}},u=class extends h{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(e,t,i,s){this.modifiedBy={id:e,authType:t,requestId:i,lambdaName:s};}};var l=class extends u{id;firstName;lastName;company;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(e,t=new Date){super(e,t),this.id=e.id,this.firstName=e.firstName,this.lastName=e.lastName||"",this.company=e.company||"",this.phone=e.phone,this.email=e.email,this.addressLine1=e.addressLine1,this.addressLine2=e.addressLine2||"",this.city=e.city,this.postalCode=e.postalCode,this.state=e.state,this.country=e.country,this.isBillingAddress=e.isBillingAddress,this.isShippingAddress=e.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),company:this.getCompany(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getCompany(){return this.company}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(e){return e==="shipping"||e==="billing&shipping"}static checkIfBillingAddress(e){return e==="billing"||e==="billing&shipping"}};var y=class extends u{invoiceNumber;orderNumber;issueDate;country;currency;locale;customerId;customerEmail;billingAddress;shippingAddress;taxContext;lineItems;charges;total;constructor(e,t=new Date){super(e,t),this.invoiceNumber=e.invoiceNumber,this.orderNumber=e.orderNumber,this.issueDate=e.issueDate,this.country=e.country,this.currency=e.currency,this.locale=e.locale,this.customerId=e.customerId,this.customerEmail=e.customerEmail,this.billingAddress=new l(e.billingAddress),this.shippingAddress=new l(e.shippingAddress),this.taxContext=e.taxContext,this.lineItems=e.lineItems,this.charges=e.charges,this.total={lineItemSubtotal:new n(e.total.lineItemSubtotal),netLineItemSubtotal:new n(e.total.netLineItemSubtotal),lineItemTaxTotal:new n(e.total.lineItemTaxTotal),lineItemTaxBreakdown:this.mapTaxBreakdown(e.total.lineItemTaxBreakdown),additiveCharges:new n(e.total.additiveCharges),netAdditiveCharges:new n(e.total.netAdditiveCharges),additiveChargesTaxTotal:new n(e.total.additiveChargesTaxTotal),additiveChargesTaxBreakdown:this.mapTaxBreakdown(e.total.additiveChargesTaxBreakdown),adjustmentCharges:new n(e.total.adjustmentCharges),shippingCharges:new n(e.total.shippingCharges),netShippingCharges:new n(e.total.netShippingCharges),discountTotal:new n(e.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(e.total.discountBreakdown).map(([i,s])=>[i,new n(s)])),taxTotal:new n(e.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(e.total.taxBreakdown),grandTotal:new n(e.total.grandTotal)};}mapTaxBreakdown(e){return Object.fromEntries(Object.entries(e||{}).map(([t,i])=>[t,{system:i.system,totalAmount:new n(i.totalAmount),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([s,a])=>[s,new n(a)]))}]))}serializeTaxBreakdown(e){return Object.fromEntries(Object.entries(e||{}).map(([t,i])=>[t,{system:i.system,totalAmount:i.totalAmount.getDetails(),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([s,a])=>[s,a.getDetails()]))}]))}getInvoiceNumber(){return this.invoiceNumber}getOrderNumber(){return this.orderNumber}getIssueDate(){return this.issueDate}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getTaxContext(){return {...this.taxContext}}getTaxRegistrationNumber(){return this.taxContext.recipientTaxIdentifier}getRecipientTaxIdentifier(){return this.taxContext.recipientTaxIdentifier}getRecipientTaxIdentifierType(){return this.taxContext.recipientTaxIdentifierType}getBillingAddress(){return this.billingAddress}getShippingAddress(){return this.shippingAddress}getPlaceOfSupplyState(){return this.taxContext.supplyRegion}getPlaceOfSupplyCode(){return this.taxContext.supplyRegionCode}getSupplyRegion(){return this.taxContext.supplyRegion}getSupplyRegionCode(){return this.taxContext.supplyRegionCode}getLineItems(){return this.lineItems}getCharges(){return this.charges}getTotal(){return this.total}getDetails(){let e=this.getTotal();return {...super.getDetails(),invoiceNumber:this.invoiceNumber,orderNumber:this.orderNumber,issueDate:this.issueDate,country:this.country,currency:this.currency,locale:this.locale,customerId:this.customerId,customerEmail:this.customerEmail,billingAddress:this.billingAddress.getDetails(),shippingAddress:this.shippingAddress.getDetails(),taxContext:this.taxContext,lineItems:this.lineItems,charges:this.charges,total:{lineItemSubtotal:e.lineItemSubtotal.getDetails(),netLineItemSubtotal:e.netLineItemSubtotal.getDetails(),lineItemTaxTotal:e.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(e.lineItemTaxBreakdown),additiveCharges:e.additiveCharges.getDetails(),netAdditiveCharges:e.netAdditiveCharges.getDetails(),additiveChargesTaxTotal:e.additiveChargesTaxTotal.getDetails(),additiveChargesTaxBreakdown:this.serializeTaxBreakdown(e.additiveChargesTaxBreakdown),adjustmentCharges:e.adjustmentCharges.getDetails(),shippingCharges:e.shippingCharges.getDetails(),netShippingCharges:e.netShippingCharges.getDetails(),discountTotal:e.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(e.discountBreakdown).map(([t,i])=>[t,i.getDetails()])),taxTotal:e.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(e.taxBreakdown),grandTotal:e.grandTotal.getDetails()}}}};module.exports=y;//# sourceMappingURL=Invoice.js.map
|
|
1
|
+
'use strict';var J=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var J__default=/*#__PURE__*/_interopDefault(J);var x={"en-IN":"en","kn-IN":"kn"};var Q={INR:"\u20B9"},K={INR:"en-IN"};var D=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var p=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var w=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},v=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},M=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";}},L=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var T=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},I=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},h=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},m=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},S=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};var o=class r{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new T("Amount cannot be negative.");if(!e.currency)throw new I("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(r.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(r.getPrecisionPlaces(this.currency)))}compareTo(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new h("Cannot compare prices in different currencies.")}else throw new m("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new h("Cannot add prices in different currencies.")}else throw new m("Must be a PriceModel instance.");return new r({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new h("Cannot subtract prices in different currencies.")}else throw new m("Must be a PriceModel instance.");return new r({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new h("Cannot multiply prices in different currencies.");return new r({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new r({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new m("Must be a non-negative number.")}divide(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new h("Cannot divide prices in different currencies.");return new r({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new r({amount:this.getPreciseAmount(this.amount/e),currency:this.currency});throw new m("Must be a positive number.")}min(...e){if(e.length===0)throw new m("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new h("Cannot compare prices in different currencies.")}else throw new m("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i},this)}max(...e){if(e.length===0)throw new m("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new h("Cannot compare prices in different currencies.")}else throw new m("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=K[t];if(!t||!n)throw new I("Invalid currency code for formatting.");let s=e,d=i.displayAsInteger?0:r.getDecimalPlaces(t),f={style:i.style??"currency",currency:t,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:d,maximumFractionDigits:d};i.displayAsInteger&&(s=Math.ceil(s));try{return new Intl.NumberFormat(n,f).format(s)}catch(l){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,l),`${Q[t]??t} ${r.addThousandSeparators(s.toFixed(d))}`}}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("."),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 T("Amount cannot be negative for rounding.");if(t===void 0)throw new I("Invalid currency code for rounding.");let i=r.getDecimalPlaces(t),n=Math.pow(10,i);return Math.round(e*n)/n}};var V=r=>structuredClone(r),U=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:V(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return V(this.customFields)}},y=class extends U{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 b=class extends y{id;firstName;lastName;company;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(e,t=new Date){super(e,t),this.id=e.id,this.firstName=e.firstName,this.lastName=e.lastName||"",this.company=e.company||"",this.phone=e.phone,this.email=e.email,this.addressLine1=e.addressLine1,this.addressLine2=e.addressLine2||"",this.city=e.city,this.postalCode=e.postalCode,this.state=e.state,this.country=e.country,this.isBillingAddress=e.isBillingAddress,this.isShippingAddress=e.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),company:this.getCompany(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getCompany(){return this.company}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(e){return e==="shipping"||e==="billing&shipping"}static checkIfBillingAddress(e){return e==="billing"||e==="billing&shipping"}};var B=new Uint8Array(256),E=B.length;function O(){return E>B.length-16&&(J__default.default.randomFillSync(B),E=0),B.slice(E,E+=16)}var H=/^(?:[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 X(r){return typeof r=="string"&&H.test(r)}var q=X;var u=[];for(let r=0;r<256;++r)u.push((r+256).toString(16).slice(1));function R(r,e=0){return u[r[e+0]]+u[r[e+1]]+u[r[e+2]]+u[r[e+3]]+"-"+u[r[e+4]]+u[r[e+5]]+"-"+u[r[e+6]]+u[r[e+7]]+"-"+u[r[e+8]]+u[r[e+9]]+"-"+u[r[e+10]]+u[r[e+11]]+u[r[e+12]]+u[r[e+13]]+u[r[e+14]]+u[r[e+15]]}function W(r){if(!q(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 Y=W;function _(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var ee="6ba7b810-9dad-11d1-80b4-00c04fd430c8",te="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function $(r,e,t){function i(n,s,d,f){var l;if(typeof n=="string"&&(n=_(n)),typeof s=="string"&&(s=Y(s)),((l=s)===null||l===void 0?void 0:l.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let g=new Uint8Array(16+n.length);if(g.set(s),g.set(n,s.length),g=t(g),g[6]=g[6]&15|e,g[8]=g[8]&63|128,d){f=f||0;for(let P=0;P<16;++P)d[f+P]=g[P];return d}return R(g)}try{i.name=r;}catch{}return i.DNS=ee,i.URL=te,i}var F={randomUUID:J__default.default.randomUUID};function ie(r,e,t){if(F.randomUUID&&!e&&!r)return F.randomUUID();r=r||{};let i=r.random||(r.rng||O)();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 R(i)}var z=ie;function se(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),J__default.default.createHash("sha1").update(r).digest()}var Z=se;var oe=$("v5",80,Z),G=oe;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 S("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 S("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 k=class{baseUnitPrice;taxCategory;tiers;constructor(e){let t=new o(e.baseUnitPrice);if(!e.taxCategory)throw new w;let i=(e.tiers??[]).map(l=>({minQuantity:l.minQuantity,unitPrice:new o(l.unitPrice)})).sort((l,g)=>l.minQuantity-g.minQuantity);if(i.some(l=>l.minQuantity<=0))throw new v;let s=i.some(l=>l.unitPrice.getCurrency()!==t.getCurrency()),d=i.some((l,g)=>g>0&&l.unitPrice.compareTo(i[g-1].unitPrice)>0),f=i[0]?.unitPrice.compareTo(t)>0;if(s||d||f)throw new M("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 N;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 L(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 C=class r extends y{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 p("Selection attributes must be an object");return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let t={},i=e.split("|");for(let n of i){let[s,d]=n.split(":");d.startsWith("c+")?t[s]={name:d.slice(2)}:t[s]=d;}return t}catch(t){throw new p(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,s)=>(e.pricing[s]&&(n[s]=new k(e.pricing[s])),n),{}),this.targetGender=e.targetGender,this.attributes=c.deepClone(e.attributes),this.specifications=c.deepClone(e.specifications),this.categories=c.deepClone(e.categories);let i=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new p("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let s=r.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(s))throw new D(s);return i.add(s),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new A(n.images.primary),gallery:(n.images.gallery||[]).map(d=>new A(d))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?c.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[x[e]]??this.name.en:c.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[x[e]]??this.description.en:c.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[x[e]]??this.slug.en:c.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return c.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:c.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 c.deepClone(this.categories)}getSpecifications(e){return e?c.deepClone(this.specifications[e]??this.specifications[x[e]]??this.specifications.en):c.deepClone(this.specifications)}getSearchTags(e){return e?c.deepClone(this.searchTags[e]??this.searchTags[x[e]]??this.searchTags.en):c.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:c.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 p("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 p(`Selection attribute '${t}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new p(`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 p(`Selection attribute '${t}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(s=>s.name===n.name)<0)throw new p(`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 ae={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?G(r,e):z(),generateSearchId:(r,e)=>`${r}#${C.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:r=>{let[e,t]=r.split("#");return {key:e,selectionAttributes:C.parseSelectionAttributesKey(t)}},deepClone(r){return structuredClone(r)}},c=ae;var j=class extends y{invoiceNumber;orderNumber;issueDate;country;currency;locale;customerId;customerEmail;billingAddress;shippingAddress;taxContext;merchant;lineItems;charges;total;constructor(e,t=new Date){super(e,t),this.invoiceNumber=e.invoiceNumber,this.orderNumber=e.orderNumber,this.issueDate=e.issueDate,this.country=e.country,this.currency=e.currency,this.locale=e.locale,this.customerId=e.customerId,this.customerEmail=e.customerEmail,this.billingAddress=new b(e.billingAddress),this.shippingAddress=new b(e.shippingAddress),this.taxContext=e.taxContext,this.merchant={merchantName:e.merchant.merchantName,taxIdentifier:e.merchant.taxIdentifier,email:e.merchant.email,phone:e.merchant.phone,address:new b(e.merchant.address)},this.lineItems=c.deepClone(e.lineItems),this.charges=c.deepClone(e.charges),this.total={lineItemSubtotal:new o(e.total.lineItemSubtotal),netLineItemSubtotal:new o(e.total.netLineItemSubtotal),lineItemTaxTotal:new o(e.total.lineItemTaxTotal),lineItemTaxBreakdown:this.mapTaxBreakdown(e.total.lineItemTaxBreakdown),additiveCharges:new o(e.total.additiveCharges),netAdditiveCharges:new o(e.total.netAdditiveCharges),additiveChargesTaxTotal:new o(e.total.additiveChargesTaxTotal),additiveChargesTaxBreakdown:this.mapTaxBreakdown(e.total.additiveChargesTaxBreakdown),adjustmentCharges:new o(e.total.adjustmentCharges),shippingCharges:new o(e.total.shippingCharges),netShippingCharges:new o(e.total.netShippingCharges),discountTotal:new o(e.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(e.total.discountBreakdown).map(([i,n])=>[i,new o(n)])),taxTotal:new o(e.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(e.total.taxBreakdown),grandTotal:new o(e.total.grandTotal)};}mapTaxBreakdown(e){return Object.fromEntries(Object.entries(e||{}).map(([t,i])=>[t,{system:i.system,totalAmount:new o(i.totalAmount),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([n,s])=>[n,new o(s)]))}]))}serializeTaxBreakdown(e){return Object.fromEntries(Object.entries(e||{}).map(([t,i])=>[t,{system:i.system,totalAmount:i.totalAmount.getDetails(),subSystems:Object.fromEntries(Object.entries(i.subSystems).map(([n,s])=>[n,s.getDetails()]))}]))}getInvoiceNumber(){return this.invoiceNumber}getOrderNumber(){return this.orderNumber}getIssueDate(){return this.issueDate}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getTaxContext(){return {...this.taxContext}}getTaxRegistrationNumber(){return this.taxContext.recipientTaxIdentifier}getRecipientTaxIdentifier(){return this.taxContext.recipientTaxIdentifier}getRecipientTaxIdentifierType(){return this.taxContext.recipientTaxIdentifierType}getBillingAddress(){return this.billingAddress}getShippingAddress(){return this.shippingAddress}getPlaceOfSupplyState(){return this.taxContext.supplyRegion}getPlaceOfSupplyCode(){return this.taxContext.supplyRegionCode}getSupplyRegion(){return this.taxContext.supplyRegion}getSupplyRegionCode(){return this.taxContext.supplyRegionCode}getMerchant(){return {merchantName:this.merchant.merchantName,taxIdentifier:this.merchant.taxIdentifier,email:this.merchant.email,phone:this.merchant.phone,address:this.merchant.address}}getLineItems(){return this.lineItems}getCharges(){return this.charges}getTotal(){return this.total}getDetails(){let e=this.getTotal();return {...super.getDetails(),invoiceNumber:this.invoiceNumber,orderNumber:this.orderNumber,issueDate:this.issueDate,country:this.country,currency:this.currency,locale:this.locale,customerId:this.customerId,customerEmail:this.customerEmail,billingAddress:this.billingAddress.getDetails(),shippingAddress:this.shippingAddress.getDetails(),taxContext:this.taxContext,merchant:{merchantName:this.merchant.merchantName,taxIdentifier:this.merchant.taxIdentifier,email:this.merchant.email,phone:this.merchant.phone,address:this.merchant.address.getDetails()},lineItems:this.lineItems,charges:this.charges,total:{lineItemSubtotal:e.lineItemSubtotal.getDetails(),netLineItemSubtotal:e.netLineItemSubtotal.getDetails(),lineItemTaxTotal:e.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(e.lineItemTaxBreakdown),additiveCharges:e.additiveCharges.getDetails(),netAdditiveCharges:e.netAdditiveCharges.getDetails(),additiveChargesTaxTotal:e.additiveChargesTaxTotal.getDetails(),additiveChargesTaxBreakdown:this.serializeTaxBreakdown(e.additiveChargesTaxBreakdown),adjustmentCharges:e.adjustmentCharges.getDetails(),shippingCharges:e.shippingCharges.getDetails(),netShippingCharges:e.netShippingCharges.getDetails(),discountTotal:e.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(e.discountBreakdown).map(([t,i])=>[t,i.getDetails()])),taxTotal:e.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(e.taxBreakdown),grandTotal:e.grandTotal.getDetails()}}}};module.exports=j;//# sourceMappingURL=Invoice.js.map
|
|
2
2
|
//# sourceMappingURL=Invoice.js.map
|