b23-lib 3.9.9 → 3.10.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/Auth/index.mjs.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/{chunk-SZLAIOMF.mjs → chunk-6QSZECNF.mjs} +2 -2
- package/dist/{chunk-SZLAIOMF.mjs.map → chunk-6QSZECNF.mjs.map} +1 -1
- package/dist/chunk-XZFALA7N.mjs +2 -0
- package/dist/chunk-XZFALA7N.mjs.map +1 -0
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-AMIRIUMH.mjs +0 -2
- package/dist/chunk-AMIRIUMH.mjs.map +0 -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-
|
|
1
|
+
import {a as a$1,b,d,c as c$1}from'../chunk-XZFALA7N.mjs';import {a as a$2}from'../chunk-4PTWJI6J.mjs';import'../chunk-7RAIVZKB.mjs';import'../chunk-UIQH5QIR.mjs';import'../chunk-PL5HGCWN.mjs';import'../chunk-O6BLQQO7.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:d,anonymousPublicKeys:h,systemTokenAge:m,systemPrivateKeys:T,systemPublicKeys:A,adminTokenAge:u,adminPrivateKeys:g,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(d,"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(g,"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.data.isTokenValid===!0,a$1.INVALID_TOKEN),n.data.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:d}={...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 g;switch(A){case"Anon":if(!i)throw c$1.generateError(403,a$1.ANONYMOUS_SESSION_NOT_ALLOWED);g=await this.verifyAnonymousToken(u);break;case"User":if(!n)throw c$1.generateError(403,a$1.USER_SESSION_NOT_ALLOWED);g=await this.verifyUserToken(u);break;case"System":if(!r)throw c$1.generateError(403,a$1.SYSTEM_SESSION_NOT_ALLOWED);g=await this.verifySystemToken(u);break;case"Admin":g=await this.verifyAdminToken(u,t,!0);break;case"CDN":if(!d)throw c$1.generateError(403,a$1.CDN_SESSION_NOT_ALLOWED);g=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(" ")||[],d=r==="CDN"?{id:n,type:"CDN"}:r?this.decodeJWTPayloadWithJose(n):{},h=c.init(d?.id||n,d?.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/Auth/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/Auth/AuthContext.ts","../../src/Auth/index.ts"],"names":["AuthContext","_AuthContext","id","type","token","requestId","assert","ErrorTypes_default","fallbackLambdaName","baseId","DefaultAuthUtilityConfig","AuthType","DefaultAuthMiddlewareConfig","AuthUtility","config","userTokenAge","userPrivateKeys","userPublicKeys","anonymousTokenAge","anonymousPrivateKeys","anonymousPublicKeys","systemTokenAge","systemPrivateKeys","systemPublicKeys","adminTokenAge","adminPrivateKeys","adminPublicKeys","cdnKeys","jsonString","keyType","parsed","item","Logger_default","error","warn","keys","limit","payload","privateKeyString","expiration","privateKey","importPKCS8","SignJWT","publicKeyString","i","publicKey","importSPKI","jwtVerify","additionalData","Utils_default","email","verifier","permissions","authenticate","response","fetch_default","response_default","allowAnonymous","allowSystem","allowUser","allowCDN","req","res","next","authType","decodeJwt","authContext","Auth_default"],"mappings":"yVAIqBA,IAAAA,CAAAA,CAArB,MAAqBC,CAAY,CAC/B,OAAe,QAAA,CAA+B,KACtC,EACA,CAAA,IAAA,CACA,KACA,CAAA,aAAA,CACA,WACA,SAEA,CAAA,WAAA,CAAYC,CAAYC,CAAAA,CAAAA,CAAgBC,EAAeC,CAAmB,CAAA,CAChF,IAAK,CAAA,EAAA,CAAKH,EACV,IAAK,CAAA,IAAA,CAAOC,CACZ,CAAA,IAAA,CAAK,MAAQC,CACb,CAAA,IAAA,CAAK,UAAa,CAAA,OAAA,CAAQ,IAAI,wBAC9B,CAAA,IAAA,CAAK,aAAgB,CAAA,IAAI,KAC3B,CAEA,OAAc,WAA2B,EAAA,CACvC,OAAAE,CAAOL,CAAAA,CAAAA,CAAY,QAAUM,CAAAA,GAAAA,CAAW,4BAA4B,CAC7DN,CAAAA,CAAAA,CAAY,QACrB,CAEA,OAAc,IAAKC,CAAAA,CAAAA,CAAYC,CAAgBC,CAAAA,CAAAA,CAAeC,EAAgC,CAC5F,OAAAJ,CAAY,CAAA,QAAA,CAAW,IAAIA,CAAAA,CAAYC,CAAIC,CAAAA,CAAAA,CAAMC,EAAOC,CAAS,CAAA,CAC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AAA,CAAM,GAAG,CAAA,EAAK,EAC9DxB,CAAAA,CAAAA,CAAU2B,CAAa,GAAA,KAAA,CAAe,CAAE,EAAI5D,CAAAA,CAAAA,CAAO,IAAM,CAAA,KAAa,EAAK4D,CAAW,CAAA,IAAA,CAAK,wBAAyB5D,CAAAA,CAAK,EAAI,EAAC,CAE5H8D,CAAclE,CAAAA,CAAAA,CAAY,KAAKqC,CAAS,EAAA,EAAA,EAAMjC,CAAOiC,CAAAA,CAAAA,EAAS,MAAQ2B,CAAU5D,CAAAA,CAAAA,CAAOyD,CAAI,CAAA,GAAA,CAAI,cAAc,CAAC,CAAA,CACpH7B,CAAO,CAAA,UAAA,CAAW,wBAAyB,CAA4BkC,yBAAAA,EAAAA,CAAAA,CAAY,OAAQ,EAAA,EAAK,SAAS,CAAMA,GAAAA,EAAAA,CAAAA,CAAY,KAAM,EAAA,EAAK,OAAO,CAAE,CAAA,CAAA,CAE/IJ,CAAI,CAAA,EAAA,CAAG,SAAU,IAAM,CACrB9B,CAAO,CAAA,UAAA,CAAW,wBAAyB,4BAA4B,CAAA,CACvEhC,CAAY,CAAA,MAAA,GACd,CAAC,CAAA,CAED+D,CAAK,GACP,OAAS9B,CAAY,CAAA,CACnBD,CAAO,CAAA,QAAA,CAAS,wBAAyBC,CAAK,CAAA,CAC9CuB,GAAgB,CAAA,eAAA,CACd,wBACAA,GAAgB,CAAA,aAAA,CAAc,GAAKvB,CAAAA,CAAAA,CAAM,OAAS1B,GAAW,CAAA,qBAAA,CAAuB,CAAI,CAAA,CAAA,CACxFuD,CACF,EACF,CACF,CACF,CACF,EAEOK,CAAQtD,CAAAA","file":"index.mjs","sourcesContent":["import assert from \"assert\";\r\nimport ErrorTypes from \"../enums/ErrorTypes\";\r\nimport { AuthType } from \"./index\";\r\n\r\nexport default class AuthContext {\r\n private static instance: AuthContext | null = null;\r\n private id: string;\r\n private type: AuthType;\r\n private token?: string;\r\n private initializedAt: Date;\r\n private lambdaName?: string;\r\n private requestId?: string;\r\n\r\n private constructor(id: string, type: AuthType, token: string, requestId: string) {\r\n this.id = id;\r\n this.type = type;\r\n this.token = token;\r\n this.lambdaName = process.env.AWS_LAMBDA_FUNCTION_NAME;\r\n this.initializedAt = new Date();\r\n }\r\n\r\n public static getInstance(): AuthContext {\r\n assert(AuthContext.instance, ErrorTypes.AUTH_CONTEXT_NOT_INITIALIZED);\r\n return AuthContext.instance;\r\n }\r\n\r\n public static init(id: string, type: AuthType, token: string, requestId: string): AuthContext {\r\n AuthContext.instance = new AuthContext(id, type, token, requestId);\r\n return AuthContext.instance;\r\n }\r\n\r\n public static uninit() {\r\n AuthContext.instance = null;\r\n }\r\n\r\n public getId(): string {\r\n return this.id;\r\n }\r\n\r\n public getType(): AuthType {\r\n return this.type;\r\n }\r\n\r\n public getToken(): string | undefined {\r\n return this.token;\r\n }\r\n \r\n public getLambdaName(): string | undefined{\r\n return this.lambdaName;\r\n }\r\n\r\n public getRequestId(): string | undefined {\r\n return this.requestId;\r\n }\r\n\r\n public getInitializedAt(): Date {\r\n return this.initializedAt;\r\n }\r\n\r\n public getSystemID(fallbackLambdaName: string): string {\r\n let baseId = this.lambdaName || fallbackLambdaName;\r\n if (this.requestId) {\r\n return `${baseId} - ${this.requestId}`;\r\n }\r\n return baseId;\r\n }\r\n}","import { decodeJwt, importPKCS8, importSPKI, jwtVerify, SignJWT} from 'jose';\r\nimport ErrorTypes from '../enums/ErrorTypes';\r\nimport Logger from '../Logger';\r\nimport Utils from '../Utils';\r\nimport ResponseUtility from '../Utils/response';\r\nimport assert from 'assert';\r\nimport Fetch from '../Utils/fetch';\r\nimport AuthContext from './AuthContext';\r\n\r\ntype StringifiedJSONArray = string;\r\n\r\nexport type AuthPayloadData = {\r\n id: string;\r\n type: AuthType;\r\n verifier?: string;\r\n [key: string]: any;\r\n}\r\n\r\nexport interface AuthUtilityConfig {\r\n userTokenAge: string;\r\n userPrivateKeys: StringifiedJSONArray;\r\n userPublicKeys: StringifiedJSONArray;\r\n anonymousTokenAge: string;\r\n anonymousPrivateKeys: StringifiedJSONArray;\r\n anonymousPublicKeys: StringifiedJSONArray;\r\n systemTokenAge: string;\r\n systemPrivateKeys: StringifiedJSONArray;\r\n systemPublicKeys: StringifiedJSONArray;\r\n adminTokenAge: string;\r\n adminPrivateKeys: StringifiedJSONArray;\r\n adminPublicKeys: StringifiedJSONArray;\r\n cdnKeys: StringifiedJSONArray;\r\n}\r\n\r\nexport const DefaultAuthUtilityConfig: Readonly<AuthUtilityConfig> = {\r\n userTokenAge: '30 days',\r\n userPrivateKeys: '[]',\r\n userPublicKeys: '[]',\r\n anonymousTokenAge: '30 days',\r\n anonymousPrivateKeys: '[]',\r\n anonymousPublicKeys: '[]',\r\n systemTokenAge: '5 min',\r\n systemPrivateKeys: '[]',\r\n systemPublicKeys: '[]',\r\n adminTokenAge: '30 days',\r\n adminPrivateKeys: '[]',\r\n adminPublicKeys: '[]',\r\n cdnKeys: '[]',\r\n};\r\n\r\nexport enum AuthType {\r\n ANON = 'Anon',\r\n USER = 'User',\r\n SYSTEM = 'System',\r\n ADMIN = 'Admin',\r\n CDN = 'CDN'\r\n}\r\n\r\nexport interface AuthMiddlewareConfig {\r\n allowAnonymous: boolean;\r\n allowSystem: boolean;\r\n allowUser: boolean;\r\n allowCDN: boolean;\r\n}\r\n\r\nexport const DefaultAuthMiddlewareConfig: Readonly<AuthMiddlewareConfig> = {\r\n allowAnonymous: false,\r\n allowSystem: true,\r\n allowUser: true,\r\n allowCDN: false\r\n};\r\n\r\n/**\r\n * A utility class for JWT authentication and authorization.\r\n */\r\nclass AuthUtility {\r\n private userTokenAge: string;\r\n private userPrivateKeys: string[];\r\n private userPublicKeys: string[];\r\n\r\n private anonymousTokenAge: string;\r\n private anonymousPrivateKeys: string[];\r\n private anonymousPublicKeys: string[];\r\n\r\n private systemTokenAge: string;\r\n private systemPrivateKeys: string[];\r\n private systemPublicKeys: string[];\r\n\r\n private adminTokenAge: string;\r\n private adminPrivateKeys: string[];\r\n private adminPublicKeys: string[];\r\n\r\n private cdnKeys: string[];\r\n\r\n /**\r\n * Initializes the AuthUtility class with a configuration.\r\n * @param config The configuration for the utility (optional).\r\n */\r\n constructor(config: Partial<AuthUtilityConfig> = DefaultAuthUtilityConfig) {\r\n const {\r\n userTokenAge,\r\n userPrivateKeys,\r\n userPublicKeys,\r\n anonymousTokenAge,\r\n anonymousPrivateKeys,\r\n anonymousPublicKeys,\r\n systemTokenAge,\r\n systemPrivateKeys,\r\n systemPublicKeys,\r\n adminTokenAge,\r\n adminPrivateKeys,\r\n adminPublicKeys,\r\n cdnKeys\r\n } = { ...DefaultAuthUtilityConfig, ...config };\r\n\r\n this.userTokenAge = userTokenAge;\r\n this.userPrivateKeys = this.parseKeyArray(userPrivateKeys, 'user private');\r\n this.userPublicKeys = this.parseKeyArray(userPublicKeys, 'user public');\r\n\r\n this.anonymousTokenAge = anonymousTokenAge;\r\n this.anonymousPrivateKeys = this.parseKeyArray(anonymousPrivateKeys, 'anonymous private');\r\n this.anonymousPublicKeys = this.parseKeyArray(anonymousPublicKeys, 'anonymous public');\r\n\r\n this.systemTokenAge = systemTokenAge;\r\n this.systemPrivateKeys = this.parseKeyArray(systemPrivateKeys, 'system private');\r\n this.systemPublicKeys = this.parseKeyArray(systemPublicKeys, 'system public');\r\n\r\n this.adminTokenAge = adminTokenAge;\r\n this.adminPrivateKeys = this.parseKeyArray(adminPrivateKeys, 'admin private');\r\n this.adminPublicKeys = this.parseKeyArray(adminPublicKeys, 'admin public');\r\n\r\n this.cdnKeys = this.parseKeyArray(cdnKeys, 'cdn');\r\n\r\n this.logWarnings();\r\n }\r\n\r\n private parseKeyArray(jsonString: string, keyType: string): string[] {\r\n try {\r\n const parsed = JSON.parse(jsonString);\r\n if (!Array.isArray(parsed) || !parsed.every(item => typeof item === 'string')) {\r\n Logger.logError('AuthUtility', `Invalid format for ${keyType} keys in config: Expected stringified array of strings.`);\r\n return [];\r\n }\r\n return parsed;\r\n } catch (error) {\r\n Logger.logError('AuthUtility', `Failed to parse ${keyType} keys from config: ${error}`);\r\n return [];\r\n }\r\n }\r\n\r\n /**\r\n * Logs warnings if the number of keys exceeds recommended limits.\r\n */\r\n private logWarnings() {\r\n const warn = (type: string, keys: string[], limit: number) =>\r\n keys.length > limit &&\r\n Logger.logWarning(\r\n 'AuthUtility',\r\n `More than ${limit} ${type} keys provided. This is not recommended.`\r\n );\r\n\r\n warn('user private', this.userPrivateKeys, 3);\r\n warn('user public', this.userPublicKeys, 3);\r\n warn('anonymous private', this.anonymousPrivateKeys, 1);\r\n warn('anonymous public', this.anonymousPublicKeys, 3);\r\n warn('system private', this.systemPrivateKeys, 1);\r\n warn('system public', this.systemPublicKeys, 3);\r\n warn('admin private', this.adminPrivateKeys, 1);\r\n warn('admin public', this.adminPublicKeys, 3);\r\n }\r\n\r\n private async createSignedJWT(payload: AuthPayloadData, privateKeyString: string, expiration: string){\r\n const privateKey = await importPKCS8(privateKeyString, 'RS256');\r\n const token = await new SignJWT(payload)\r\n .setProtectedHeader({ alg: 'RS256' })\r\n .setExpirationTime(expiration)\r\n .setIssuedAt()\r\n .sign(privateKey);\r\n\r\n return token;\r\n }\r\n\r\n private async verifySignedJWT(token: string, publicKeyString: string[], expiration: string): Promise<AuthPayloadData> {\r\n for(let i = publicKeyString.length - 1; i >= 0 ; i--){\r\n try { \r\n const publicKey = await importSPKI(publicKeyString[i], 'RS256')\r\n const jwt = await jwtVerify(token, publicKey, { clockTolerance: 30, maxTokenAge: expiration });\r\n return jwt.payload as AuthPayloadData;\r\n } catch (error) {\r\n if (i === 0) {\r\n throw error;\r\n }\r\n // Try with the next oldest key\r\n continue;\r\n }\r\n }\r\n throw new Error(ErrorTypes.INVALID_TOKEN);\r\n }\r\n\r\n \r\n /**\r\n * Creates an anonymous token with the given ID and additional data.\r\n *\r\n * @param id - The unique identifier for the token. Must be a valid UUID.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT as a string.\r\n * @throws Will throw an error if no anonymous private keys are found or if the ID is not a valid UUID.\r\n */\r\n async createAnonymousToken(id: string, additionalData?: object): Promise<string> {\r\n assert(this.anonymousPrivateKeys.length, ErrorTypes.ANONYMOUS_PRIVATE_KEY_NOT_FOUND);\r\n\r\n assert(Utils.isUUID(id), ErrorTypes.INVALID_UUID);\r\n const payload = {\r\n id,\r\n type: AuthType.ANON,\r\n ...additionalData\r\n };\r\n\r\n return await this.createSignedJWT(payload, this.anonymousPrivateKeys[this.anonymousPrivateKeys.length - 1], this.anonymousTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies an anonymous token by checking its signature and payload type.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @returns The payload of the verified token.\r\n * @throws Will throw an error if no anonymous public keys are found or if the token type is invalid.\r\n */\r\n async verifyAnonymousToken(token: string){\r\n assert(this.anonymousPublicKeys.length, ErrorTypes.ANONYMOUS_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.anonymousPublicKeys, this.anonymousTokenAge);\r\n assert(payload.type === AuthType.ANON, ErrorTypes.INVALID_AUTH_TYPE);\r\n return payload;\r\n }\r\n\r\n /**\r\n * Creates a signed JWT token for a user.\r\n *\r\n * @param id - The UUID of the user.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT token as a string.\r\n * @throws Will throw an error if no user private keys are found or if the provided id is not a valid UUID.\r\n */\r\n async createUserToken(id: string, additionalData?: object): Promise<string> {\r\n assert(this.userPrivateKeys.length, ErrorTypes.USER_PRIVATE_KEY_NOT_FOUND);\r\n assert(Utils.isUUID(id), ErrorTypes.INVALID_UUID);\r\n\r\n const payload = {\r\n id,\r\n type: AuthType.USER,\r\n ...additionalData\r\n };\r\n return await this.createSignedJWT(payload, this.userPrivateKeys[this.userPrivateKeys.length - 1], this.userTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies the provided user token by checking its signature and payload.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @returns The payload of the verified token if valid.\r\n * @throws Will throw an error if no user public keys are found or if the token type is invalid.\r\n */\r\n async verifyUserToken(token: string){\r\n assert(this.userPublicKeys.length, ErrorTypes.USER_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.userPublicKeys, this.userTokenAge);\r\n assert(payload.type === AuthType.USER, ErrorTypes.INVALID_AUTH_TYPE);\r\n return payload;\r\n }\r\n\r\n /**\r\n * Creates a signed JWT (JSON Web Token) for a system with the given ID and optional additional data.\r\n *\r\n * @param id - The unique identifier for the system.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT as a string.\r\n * @throws Will throw an error if no system private keys are found.\r\n */\r\n async createSystemToken(id: string, additionalData?: object): Promise<string> {\r\n assert(this.systemPrivateKeys.length, ErrorTypes.SYSTEM_PRIVATE_KEY_NOT_FOUND);\r\n\r\n const payload = {\r\n id,\r\n type: AuthType.SYSTEM,\r\n ...additionalData\r\n };\r\n return await this.createSignedJWT(payload, this.systemPrivateKeys[this.systemPrivateKeys.length - 1], this.systemTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies a system token by checking its signature and payload type.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @returns The payload of the verified token.\r\n * @throws Will throw an error if no system public keys are found or if the token type is not 'System'.\r\n */\r\n async verifySystemToken(token: string){\r\n assert(this.systemPublicKeys.length, ErrorTypes.USER_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.systemPublicKeys, this.systemTokenAge);\r\n assert(payload.type === AuthType.SYSTEM, ErrorTypes.INVALID_AUTH_TYPE);\r\n return payload;\r\n }\r\n\r\n /**\r\n * Creates a signed JWT token for an admin user.\r\n *\r\n * @param email - The email of the admin user.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT token string.\r\n * @throws Will throw an error if no admin private keys are found or if the provided id is not a valid UUID.\r\n */\r\n async createAdminToken(email: string, verifier: string, additionalData?: object): Promise<string> {\r\n assert(this.adminPrivateKeys.length, ErrorTypes.ADMIN_PRIVATE_KEY_NOT_FOUND);\r\n\r\n assert(Utils.isEmail(email), ErrorTypes.INVALID_EMAIL);\r\n assert(Utils.isURL(verifier), ErrorTypes.INVALID_VERIFIER);\r\n const payload = {\r\n id: email,\r\n type: AuthType.ADMIN,\r\n verifier: verifier,\r\n ...additionalData\r\n };\r\n return await this.createSignedJWT(payload, this.adminPrivateKeys[this.adminPrivateKeys.length - 1], this.adminTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies the provided admin token by checking its signature and payload.\r\n * Ensures that the token is signed with one of the known admin public keys\r\n * and that the payload type is 'Admin'.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @param permissions - The permissions required for the admin user.\r\n * @param authenticate - Whether to authenticate the token with the verifier.\r\n * @returns The payload of the verified token.\r\n * @throws Will throw an error if no admin public keys are found or if the token is invalid or if the admin doesn't have proper permissions.\r\n */\r\n async verifyAdminToken(token: string, permissions: string[], authenticate: boolean){\r\n assert(this.adminPublicKeys.length, ErrorTypes.ADMIN_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.adminPublicKeys, this.adminTokenAge);\r\n assert(payload.type === AuthType.ADMIN, ErrorTypes.INVALID_AUTH_TYPE);\r\n\r\n if(authenticate) {\r\n const response = await Fetch(payload.verifier as string, '', 'POST', {}, { token, permissions });\r\n assert(response.data.isTokenValid === true, ErrorTypes.INVALID_TOKEN);\r\n \r\n if(response.data.hasPermissions !== true){\r\n throw ResponseUtility.generateError(403, ErrorTypes.INVALID_PERMISSIONS)\r\n }\r\n }\r\n\r\n return payload;\r\n }\r\n\r\n async verifyCDNToken(token: string) {\r\n assert(this.cdnKeys.includes(token), ErrorTypes.INVALID_TOKEN);\r\n\r\n const payload: AuthPayloadData = {\r\n id: token,\r\n type: AuthType.CDN,\r\n };\r\n\r\n return payload;\r\n }\r\n\r\n /**\r\n * Middleware function to handle authentication based on different token types.\r\n * It verifies the token and sets the authentication details in the response locals.\r\n *\r\n * @param {Partial<AuthMiddlewareConfig>} [config=DefaultAuthMiddlewareConfig] - Configuration object to customize the middleware behavior.\r\n * @returns Middleware function to handle authentication.\r\n */\r\n AuthMiddleware(config: Partial<AuthMiddlewareConfig> = DefaultAuthMiddlewareConfig, permissions: string[] = []) {\r\n const { allowAnonymous, allowSystem, allowUser, allowCDN } = { ...DefaultAuthMiddlewareConfig, ...config };\r\n return async (req: any, res: any, next: any) => {\r\n try {\r\n const [authType, token] = req.get('Authorization')?.split(' ') || [];\r\n if (!token) throw new Error(ErrorTypes.INVALID_TOKEN);\r\n\r\n let payload;\r\n switch (authType as AuthType) {\r\n case AuthType.ANON:\r\n if (!allowAnonymous) throw ResponseUtility.generateError(403, ErrorTypes.ANONYMOUS_SESSION_NOT_ALLOWED);\r\n payload = await this.verifyAnonymousToken(token);\r\n break;\r\n case AuthType.USER:\r\n if (!allowUser) throw ResponseUtility.generateError(403, ErrorTypes.USER_SESSION_NOT_ALLOWED);\r\n payload = await this.verifyUserToken(token);\r\n break;\r\n case AuthType.SYSTEM:\r\n if (!allowSystem) throw ResponseUtility.generateError(403, ErrorTypes.SYSTEM_SESSION_NOT_ALLOWED);\r\n payload = await this.verifySystemToken(token);\r\n break;\r\n case AuthType.ADMIN:\r\n payload = await this.verifyAdminToken(token, permissions, true);\r\n break;\r\n case AuthType.CDN:\r\n if (!allowCDN) throw ResponseUtility.generateError(403, ErrorTypes.CDN_SESSION_NOT_ALLOWED);\r\n payload = await this.verifyCDNToken(token);\r\n\r\n break;\r\n default:\r\n throw ResponseUtility.generateError(403, ErrorTypes.INVALID_AUTH_TYPE);\r\n }\r\n\r\n next();\r\n } catch (error: any) {\r\n Logger.logError('AuthMiddleware', error);\r\n ResponseUtility.handleException(\r\n 'AuthMiddleware',\r\n ResponseUtility.generateError(401, error.error || ErrorTypes.TOKEN_EXPIRED, true),\r\n res\r\n );\r\n }\r\n };\r\n }\r\n\r\n /**\r\n * Decodes the payload of a JWT using jose.decodeJwt without verifying\r\n * the signature or expiration.\r\n * WARNING: This is insecure as it doesn't validate the token's integrity.\r\n * Use only when you understand the risks and have a specific need.\r\n *\r\n * @param token - The JWT string.\r\n * @returns The decoded payload object, or null if the token format is invalid or decoding fails.\r\n */\r\n decodeJWTPayloadWithJose(token: string): Record<string, any> | null {\r\n if (!token || typeof token !== 'string') {\r\n Logger.logError(\"AuthContextMiddleware\", \"Invalid token provided for decoding.\");\r\n return null;\r\n }\r\n\r\n try {\r\n const payload = decodeJwt(token);\r\n return payload;\r\n } catch (error) {\r\n Logger.logError(\"AuthContextMiddleware\", `Failed to decode JWT payload: ${error}`);\r\n return null;\r\n }\r\n }\r\n\r\n AuthContextMiddleware() {\r\n return async (req: any, res: any, next: any) => {\r\n try {\r\n const [authType, token] = req.get('Authorization')?.split(' ') || [];\r\n let payload = authType === AuthType.CDN ? { id: token, type: AuthType.CDN } : (authType ? this.decodeJWTPayloadWithJose(token) : {});\r\n\r\n const authContext = AuthContext.init(payload?.id || token, payload?.type || authType, token, req.get('x-request-id'));\r\n Logger.logMessage('AuthContextMiddleware', `AuthContext initialized: ${authContext.getType() || 'No-Type'} - ${authContext.getId() || 'No-Id'}`);\r\n\r\n res.on('finish', () => {\r\n Logger.logMessage('AuthContextMiddleware', 'Uninitializing AuthContext');\r\n AuthContext.uninit();\r\n });\r\n\r\n next();\r\n } catch (error: any) {\r\n Logger.logError('AuthContextMiddleware', error);\r\n ResponseUtility.handleException(\r\n 'AuthContextMiddleware',\r\n ResponseUtility.generateError(500, error.error || ErrorTypes.INTERNAL_SERVER_ERROR, true),\r\n res\r\n );\r\n }\r\n };\r\n }\r\n}\r\n\r\nexport default AuthUtility;\r\nexport { AuthContext };\r\n\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/Auth/AuthContext.ts","../../src/Auth/index.ts"],"names":["AuthContext","_AuthContext","id","type","token","requestId","assert","ErrorTypes_default","fallbackLambdaName","baseId","DefaultAuthUtilityConfig","AuthType","DefaultAuthMiddlewareConfig","AuthUtility","config","userTokenAge","userPrivateKeys","userPublicKeys","anonymousTokenAge","anonymousPrivateKeys","anonymousPublicKeys","systemTokenAge","systemPrivateKeys","systemPublicKeys","adminTokenAge","adminPrivateKeys","adminPublicKeys","cdnKeys","jsonString","keyType","parsed","item","Logger_default","error","warn","keys","limit","payload","privateKeyString","expiration","privateKey","importPKCS8","SignJWT","publicKeyString","i","publicKey","importSPKI","jwtVerify","additionalData","Utils_default","email","verifier","permissions","authenticate","response","fetch_default","response_default","allowAnonymous","allowSystem","allowUser","allowCDN","req","res","next","authType","decodeJwt","authContext","Auth_default"],"mappings":"yVAIqBA,IAAAA,CAAAA,CAArB,MAAqBC,CAAY,CAC/B,OAAe,QAAA,CAA+B,KACtC,EACA,CAAA,IAAA,CACA,KACA,CAAA,aAAA,CACA,WACA,SAEA,CAAA,WAAA,CAAYC,CAAYC,CAAAA,CAAAA,CAAgBC,EAAeC,CAAmB,CAAA,CAChF,IAAK,CAAA,EAAA,CAAKH,EACV,IAAK,CAAA,IAAA,CAAOC,CACZ,CAAA,IAAA,CAAK,MAAQC,CACb,CAAA,IAAA,CAAK,UAAa,CAAA,OAAA,CAAQ,IAAI,wBAC9B,CAAA,IAAA,CAAK,aAAgB,CAAA,IAAI,KAC3B,CAEA,OAAc,WAA2B,EAAA,CACvC,OAAAE,CAAOL,CAAAA,CAAAA,CAAY,QAAUM,CAAAA,GAAAA,CAAW,4BAA4B,CAC7DN,CAAAA,CAAAA,CAAY,QACrB,CAEA,OAAc,IAAKC,CAAAA,CAAAA,CAAYC,CAAgBC,CAAAA,CAAAA,CAAeC,EAAgC,CAC5F,OAAAJ,CAAY,CAAA,QAAA,CAAW,IAAIA,CAAYC,CAAAA,CAAAA,CAAIC,CAAMC,CAAAA,CAAAA,CAAOC,CAAS,CAC1DJ,CAAAA,CAAAA,CAAY,QACrB,CAEA,OAAc,MAAS,EAAA,CACrBA,CAAY,CAAA,QAAA,CAAW,KACzB,CAEO,KAAA,EAAgB,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AAe,CAAE,EAAI5D,CAAAA,CAAAA,CAAO,IAAM,CAAA,KAAa,EAAK4D,CAAW,CAAA,IAAA,CAAK,wBAAyB5D,CAAAA,CAAK,EAAI,EAAC,CAE5H8D,CAAclE,CAAAA,CAAAA,CAAY,KAAKqC,CAAS,EAAA,EAAA,EAAMjC,CAAOiC,CAAAA,CAAAA,EAAS,MAAQ2B,CAAU5D,CAAAA,CAAAA,CAAOyD,CAAI,CAAA,GAAA,CAAI,cAAc,CAAC,CAAA,CACpH7B,CAAO,CAAA,UAAA,CAAW,wBAAyB,CAA4BkC,yBAAAA,EAAAA,CAAAA,CAAY,OAAQ,EAAA,EAAK,SAAS,CAAMA,GAAAA,EAAAA,CAAAA,CAAY,KAAM,EAAA,EAAK,OAAO,CAAE,CAAA,CAAA,CAE/IJ,CAAI,CAAA,EAAA,CAAG,SAAU,IAAM,CACrB9B,CAAO,CAAA,UAAA,CAAW,wBAAyB,4BAA4B,CAAA,CACvEhC,CAAY,CAAA,MAAA,GACd,CAAC,CAAA,CAED+D,CAAK,GACP,OAAS9B,CAAY,CAAA,CACnBD,CAAO,CAAA,QAAA,CAAS,wBAAyBC,CAAK,CAAA,CAC9CuB,GAAgB,CAAA,eAAA,CACd,wBACAA,GAAgB,CAAA,aAAA,CAAc,GAAKvB,CAAAA,CAAAA,CAAM,OAAS1B,GAAW,CAAA,qBAAA,CAAuB,CAAI,CAAA,CAAA,CACxFuD,CACF,EACF,CACF,CACF,CACF,EAEOK,CAAQtD,CAAAA","file":"index.mjs","sourcesContent":["import assert from \"assert\";\r\nimport ErrorTypes from \"../enums/ErrorTypes\";\r\nimport { AuthType } from \"./index\";\r\n\r\nexport default class AuthContext {\r\n private static instance: AuthContext | null = null;\r\n private id: string;\r\n private type: AuthType;\r\n private token?: string;\r\n private initializedAt: Date;\r\n private lambdaName?: string;\r\n private requestId?: string;\r\n\r\n private constructor(id: string, type: AuthType, token: string, requestId: string) {\r\n this.id = id;\r\n this.type = type;\r\n this.token = token;\r\n this.lambdaName = process.env.AWS_LAMBDA_FUNCTION_NAME;\r\n this.initializedAt = new Date();\r\n }\r\n\r\n public static getInstance(): AuthContext {\r\n assert(AuthContext.instance, ErrorTypes.AUTH_CONTEXT_NOT_INITIALIZED);\r\n return AuthContext.instance;\r\n }\r\n\r\n public static init(id: string, type: AuthType, token: string, requestId: string): AuthContext {\r\n AuthContext.instance = new AuthContext(id, type, token, requestId);\r\n return AuthContext.instance;\r\n }\r\n\r\n public static uninit() {\r\n AuthContext.instance = null;\r\n }\r\n\r\n public getId(): string {\r\n return this.id;\r\n }\r\n\r\n public getType(): AuthType {\r\n return this.type;\r\n }\r\n\r\n public getToken(): string | undefined {\r\n return this.token;\r\n }\r\n \r\n public getLambdaName(): string | undefined{\r\n return this.lambdaName;\r\n }\r\n\r\n public getRequestId(): string | undefined {\r\n return this.requestId;\r\n }\r\n\r\n public getInitializedAt(): Date {\r\n return this.initializedAt;\r\n }\r\n\r\n public getSystemID(fallbackLambdaName: string): string {\r\n let baseId = this.lambdaName || fallbackLambdaName;\r\n if (this.requestId) {\r\n return `${baseId} - ${this.requestId}`;\r\n }\r\n return baseId;\r\n }\r\n}","import { decodeJwt, importPKCS8, importSPKI, jwtVerify, SignJWT} from 'jose';\r\nimport ErrorTypes from '../enums/ErrorTypes';\r\nimport Logger from '../Logger';\r\nimport Utils from '../Utils';\r\nimport ResponseUtility from '../Utils/response';\r\nimport assert from 'assert';\r\nimport Fetch from '../Utils/fetch';\r\nimport AuthContext from './AuthContext';\r\n\r\ntype StringifiedJSONArray = string;\r\n\r\nexport type AuthPayloadData = {\r\n id: string;\r\n type: AuthType;\r\n verifier?: string;\r\n [key: string]: any;\r\n}\r\n\r\nexport interface AuthUtilityConfig {\r\n userTokenAge: string;\r\n userPrivateKeys: StringifiedJSONArray;\r\n userPublicKeys: StringifiedJSONArray;\r\n anonymousTokenAge: string;\r\n anonymousPrivateKeys: StringifiedJSONArray;\r\n anonymousPublicKeys: StringifiedJSONArray;\r\n systemTokenAge: string;\r\n systemPrivateKeys: StringifiedJSONArray;\r\n systemPublicKeys: StringifiedJSONArray;\r\n adminTokenAge: string;\r\n adminPrivateKeys: StringifiedJSONArray;\r\n adminPublicKeys: StringifiedJSONArray;\r\n cdnKeys: StringifiedJSONArray;\r\n}\r\n\r\nexport const DefaultAuthUtilityConfig: Readonly<AuthUtilityConfig> = {\r\n userTokenAge: '30 days',\r\n userPrivateKeys: '[]',\r\n userPublicKeys: '[]',\r\n anonymousTokenAge: '30 days',\r\n anonymousPrivateKeys: '[]',\r\n anonymousPublicKeys: '[]',\r\n systemTokenAge: '5 min',\r\n systemPrivateKeys: '[]',\r\n systemPublicKeys: '[]',\r\n adminTokenAge: '30 days',\r\n adminPrivateKeys: '[]',\r\n adminPublicKeys: '[]',\r\n cdnKeys: '[]',\r\n};\r\n\r\nexport enum AuthType {\r\n ANON = 'Anon',\r\n USER = 'User',\r\n SYSTEM = 'System',\r\n ADMIN = 'Admin',\r\n CDN = 'CDN'\r\n}\r\n\r\nexport interface AuthMiddlewareConfig {\r\n allowAnonymous: boolean;\r\n allowSystem: boolean;\r\n allowUser: boolean;\r\n allowCDN: boolean;\r\n}\r\n\r\nexport const DefaultAuthMiddlewareConfig: Readonly<AuthMiddlewareConfig> = {\r\n allowAnonymous: false,\r\n allowSystem: true,\r\n allowUser: true,\r\n allowCDN: false\r\n};\r\n\r\n/**\r\n * A utility class for JWT authentication and authorization.\r\n */\r\nclass AuthUtility {\r\n private userTokenAge: string;\r\n private userPrivateKeys: string[];\r\n private userPublicKeys: string[];\r\n\r\n private anonymousTokenAge: string;\r\n private anonymousPrivateKeys: string[];\r\n private anonymousPublicKeys: string[];\r\n\r\n private systemTokenAge: string;\r\n private systemPrivateKeys: string[];\r\n private systemPublicKeys: string[];\r\n\r\n private adminTokenAge: string;\r\n private adminPrivateKeys: string[];\r\n private adminPublicKeys: string[];\r\n\r\n private cdnKeys: string[];\r\n\r\n /**\r\n * Initializes the AuthUtility class with a configuration.\r\n * @param config The configuration for the utility (optional).\r\n */\r\n constructor(config: Partial<AuthUtilityConfig> = DefaultAuthUtilityConfig) {\r\n const {\r\n userTokenAge,\r\n userPrivateKeys,\r\n userPublicKeys,\r\n anonymousTokenAge,\r\n anonymousPrivateKeys,\r\n anonymousPublicKeys,\r\n systemTokenAge,\r\n systemPrivateKeys,\r\n systemPublicKeys,\r\n adminTokenAge,\r\n adminPrivateKeys,\r\n adminPublicKeys,\r\n cdnKeys\r\n } = { ...DefaultAuthUtilityConfig, ...config };\r\n\r\n this.userTokenAge = userTokenAge;\r\n this.userPrivateKeys = this.parseKeyArray(userPrivateKeys, 'user private');\r\n this.userPublicKeys = this.parseKeyArray(userPublicKeys, 'user public');\r\n\r\n this.anonymousTokenAge = anonymousTokenAge;\r\n this.anonymousPrivateKeys = this.parseKeyArray(anonymousPrivateKeys, 'anonymous private');\r\n this.anonymousPublicKeys = this.parseKeyArray(anonymousPublicKeys, 'anonymous public');\r\n\r\n this.systemTokenAge = systemTokenAge;\r\n this.systemPrivateKeys = this.parseKeyArray(systemPrivateKeys, 'system private');\r\n this.systemPublicKeys = this.parseKeyArray(systemPublicKeys, 'system public');\r\n\r\n this.adminTokenAge = adminTokenAge;\r\n this.adminPrivateKeys = this.parseKeyArray(adminPrivateKeys, 'admin private');\r\n this.adminPublicKeys = this.parseKeyArray(adminPublicKeys, 'admin public');\r\n\r\n this.cdnKeys = this.parseKeyArray(cdnKeys, 'cdn');\r\n\r\n this.logWarnings();\r\n }\r\n\r\n private parseKeyArray(jsonString: string, keyType: string): string[] {\r\n try {\r\n const parsed = JSON.parse(jsonString);\r\n if (!Array.isArray(parsed) || !parsed.every(item => typeof item === 'string')) {\r\n Logger.logError('AuthUtility', `Invalid format for ${keyType} keys in config: Expected stringified array of strings.`);\r\n return [];\r\n }\r\n return parsed;\r\n } catch (error) {\r\n Logger.logError('AuthUtility', `Failed to parse ${keyType} keys from config: ${error}`);\r\n return [];\r\n }\r\n }\r\n\r\n /**\r\n * Logs warnings if the number of keys exceeds recommended limits.\r\n */\r\n private logWarnings() {\r\n const warn = (type: string, keys: string[], limit: number) =>\r\n keys.length > limit &&\r\n Logger.logWarning(\r\n 'AuthUtility',\r\n `More than ${limit} ${type} keys provided. This is not recommended.`\r\n );\r\n\r\n warn('user private', this.userPrivateKeys, 3);\r\n warn('user public', this.userPublicKeys, 3);\r\n warn('anonymous private', this.anonymousPrivateKeys, 1);\r\n warn('anonymous public', this.anonymousPublicKeys, 3);\r\n warn('system private', this.systemPrivateKeys, 1);\r\n warn('system public', this.systemPublicKeys, 3);\r\n warn('admin private', this.adminPrivateKeys, 1);\r\n warn('admin public', this.adminPublicKeys, 3);\r\n }\r\n\r\n private async createSignedJWT(payload: AuthPayloadData, privateKeyString: string, expiration: string){\r\n const privateKey = await importPKCS8(privateKeyString, 'RS256');\r\n const token = await new SignJWT(payload)\r\n .setProtectedHeader({ alg: 'RS256' })\r\n .setExpirationTime(expiration)\r\n .setIssuedAt()\r\n .sign(privateKey);\r\n\r\n return token;\r\n }\r\n\r\n private async verifySignedJWT(token: string, publicKeyString: string[], expiration: string): Promise<AuthPayloadData> {\r\n for(let i = publicKeyString.length - 1; i >= 0 ; i--){\r\n try { \r\n const publicKey = await importSPKI(publicKeyString[i], 'RS256')\r\n const jwt = await jwtVerify(token, publicKey, { clockTolerance: 30, maxTokenAge: expiration });\r\n return jwt.payload as AuthPayloadData;\r\n } catch (error) {\r\n if (i === 0) {\r\n throw error;\r\n }\r\n // Try with the next oldest key\r\n continue;\r\n }\r\n }\r\n throw new Error(ErrorTypes.INVALID_TOKEN);\r\n }\r\n\r\n \r\n /**\r\n * Creates an anonymous token with the given ID and additional data.\r\n *\r\n * @param id - The unique identifier for the token. Must be a valid UUID.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT as a string.\r\n * @throws Will throw an error if no anonymous private keys are found or if the ID is not a valid UUID.\r\n */\r\n async createAnonymousToken(id: string, additionalData?: object): Promise<string> {\r\n assert(this.anonymousPrivateKeys.length, ErrorTypes.ANONYMOUS_PRIVATE_KEY_NOT_FOUND);\r\n\r\n assert(Utils.isUUID(id), ErrorTypes.INVALID_UUID);\r\n const payload = {\r\n id,\r\n type: AuthType.ANON,\r\n ...additionalData\r\n };\r\n\r\n return await this.createSignedJWT(payload, this.anonymousPrivateKeys[this.anonymousPrivateKeys.length - 1], this.anonymousTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies an anonymous token by checking its signature and payload type.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @returns The payload of the verified token.\r\n * @throws Will throw an error if no anonymous public keys are found or if the token type is invalid.\r\n */\r\n async verifyAnonymousToken(token: string){\r\n assert(this.anonymousPublicKeys.length, ErrorTypes.ANONYMOUS_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.anonymousPublicKeys, this.anonymousTokenAge);\r\n assert(payload.type === AuthType.ANON, ErrorTypes.INVALID_AUTH_TYPE);\r\n return payload;\r\n }\r\n\r\n /**\r\n * Creates a signed JWT token for a user.\r\n *\r\n * @param id - The UUID of the user.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT token as a string.\r\n * @throws Will throw an error if no user private keys are found or if the provided id is not a valid UUID.\r\n */\r\n async createUserToken(id: string, additionalData?: object): Promise<string> {\r\n assert(this.userPrivateKeys.length, ErrorTypes.USER_PRIVATE_KEY_NOT_FOUND);\r\n assert(Utils.isUUID(id), ErrorTypes.INVALID_UUID);\r\n\r\n const payload = {\r\n id,\r\n type: AuthType.USER,\r\n ...additionalData\r\n };\r\n return await this.createSignedJWT(payload, this.userPrivateKeys[this.userPrivateKeys.length - 1], this.userTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies the provided user token by checking its signature and payload.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @returns The payload of the verified token if valid.\r\n * @throws Will throw an error if no user public keys are found or if the token type is invalid.\r\n */\r\n async verifyUserToken(token: string){\r\n assert(this.userPublicKeys.length, ErrorTypes.USER_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.userPublicKeys, this.userTokenAge);\r\n assert(payload.type === AuthType.USER, ErrorTypes.INVALID_AUTH_TYPE);\r\n return payload;\r\n }\r\n\r\n /**\r\n * Creates a signed JWT (JSON Web Token) for a system with the given ID and optional additional data.\r\n *\r\n * @param id - The unique identifier for the system.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT as a string.\r\n * @throws Will throw an error if no system private keys are found.\r\n */\r\n async createSystemToken(id: string, additionalData?: object): Promise<string> {\r\n assert(this.systemPrivateKeys.length, ErrorTypes.SYSTEM_PRIVATE_KEY_NOT_FOUND);\r\n\r\n const payload = {\r\n id,\r\n type: AuthType.SYSTEM,\r\n ...additionalData\r\n };\r\n return await this.createSignedJWT(payload, this.systemPrivateKeys[this.systemPrivateKeys.length - 1], this.systemTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies a system token by checking its signature and payload type.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @returns The payload of the verified token.\r\n * @throws Will throw an error if no system public keys are found or if the token type is not 'System'.\r\n */\r\n async verifySystemToken(token: string){\r\n assert(this.systemPublicKeys.length, ErrorTypes.USER_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.systemPublicKeys, this.systemTokenAge);\r\n assert(payload.type === AuthType.SYSTEM, ErrorTypes.INVALID_AUTH_TYPE);\r\n return payload;\r\n }\r\n\r\n /**\r\n * Creates a signed JWT token for an admin user.\r\n *\r\n * @param email - The email of the admin user.\r\n * @param additionalData - Optional additional data to include in the token payload.\r\n * @returns A promise that resolves to the signed JWT token string.\r\n * @throws Will throw an error if no admin private keys are found or if the provided id is not a valid UUID.\r\n */\r\n async createAdminToken(email: string, verifier: string, additionalData?: object): Promise<string> {\r\n assert(this.adminPrivateKeys.length, ErrorTypes.ADMIN_PRIVATE_KEY_NOT_FOUND);\r\n\r\n assert(Utils.isEmail(email), ErrorTypes.INVALID_EMAIL);\r\n assert(Utils.isURL(verifier), ErrorTypes.INVALID_VERIFIER);\r\n const payload = {\r\n id: email,\r\n type: AuthType.ADMIN,\r\n verifier: verifier,\r\n ...additionalData\r\n };\r\n return await this.createSignedJWT(payload, this.adminPrivateKeys[this.adminPrivateKeys.length - 1], this.adminTokenAge);\r\n }\r\n\r\n /**\r\n * Verifies the provided admin token by checking its signature and payload.\r\n * Ensures that the token is signed with one of the known admin public keys\r\n * and that the payload type is 'Admin'.\r\n *\r\n * @param token - The JWT token to be verified.\r\n * @param permissions - The permissions required for the admin user.\r\n * @param authenticate - Whether to authenticate the token with the verifier.\r\n * @returns The payload of the verified token.\r\n * @throws Will throw an error if no admin public keys are found or if the token is invalid or if the admin doesn't have proper permissions.\r\n */\r\n async verifyAdminToken(token: string, permissions: string[], authenticate: boolean){\r\n assert(this.adminPublicKeys.length, ErrorTypes.ADMIN_PUBLIC_KEY_NOT_FOUND);\r\n const payload = await this.verifySignedJWT(token, this.adminPublicKeys, this.adminTokenAge);\r\n assert(payload.type === AuthType.ADMIN, ErrorTypes.INVALID_AUTH_TYPE);\r\n\r\n if(authenticate) {\r\n const response = await Fetch(payload.verifier as string, '', 'POST', {}, { token, permissions });\r\n assert(response.data.data.isTokenValid === true, ErrorTypes.INVALID_TOKEN);\r\n \r\n if(response.data.data.hasPermissions !== true){\r\n throw ResponseUtility.generateError(403, ErrorTypes.INVALID_PERMISSIONS)\r\n }\r\n }\r\n\r\n return payload;\r\n }\r\n\r\n async verifyCDNToken(token: string) {\r\n assert(this.cdnKeys.includes(token), ErrorTypes.INVALID_TOKEN);\r\n\r\n const payload: AuthPayloadData = {\r\n id: token,\r\n type: AuthType.CDN,\r\n };\r\n\r\n return payload;\r\n }\r\n\r\n /**\r\n * Middleware function to handle authentication based on different token types.\r\n * It verifies the token and sets the authentication details in the response locals.\r\n *\r\n * @param {Partial<AuthMiddlewareConfig>} [config=DefaultAuthMiddlewareConfig] - Configuration object to customize the middleware behavior.\r\n * @returns Middleware function to handle authentication.\r\n */\r\n AuthMiddleware(config: Partial<AuthMiddlewareConfig> = DefaultAuthMiddlewareConfig, permissions: string[] = []) {\r\n const { allowAnonymous, allowSystem, allowUser, allowCDN } = { ...DefaultAuthMiddlewareConfig, ...config };\r\n return async (req: any, res: any, next: any) => {\r\n try {\r\n const [authType, token] = req.get('Authorization')?.split(' ') || [];\r\n if (!token) throw new Error(ErrorTypes.INVALID_TOKEN);\r\n\r\n let payload;\r\n switch (authType as AuthType) {\r\n case AuthType.ANON:\r\n if (!allowAnonymous) throw ResponseUtility.generateError(403, ErrorTypes.ANONYMOUS_SESSION_NOT_ALLOWED);\r\n payload = await this.verifyAnonymousToken(token);\r\n break;\r\n case AuthType.USER:\r\n if (!allowUser) throw ResponseUtility.generateError(403, ErrorTypes.USER_SESSION_NOT_ALLOWED);\r\n payload = await this.verifyUserToken(token);\r\n break;\r\n case AuthType.SYSTEM:\r\n if (!allowSystem) throw ResponseUtility.generateError(403, ErrorTypes.SYSTEM_SESSION_NOT_ALLOWED);\r\n payload = await this.verifySystemToken(token);\r\n break;\r\n case AuthType.ADMIN:\r\n payload = await this.verifyAdminToken(token, permissions, true);\r\n break;\r\n case AuthType.CDN:\r\n if (!allowCDN) throw ResponseUtility.generateError(403, ErrorTypes.CDN_SESSION_NOT_ALLOWED);\r\n payload = await this.verifyCDNToken(token);\r\n\r\n break;\r\n default:\r\n throw ResponseUtility.generateError(403, ErrorTypes.INVALID_AUTH_TYPE);\r\n }\r\n\r\n next();\r\n } catch (error: any) {\r\n Logger.logError('AuthMiddleware', error);\r\n ResponseUtility.handleException(\r\n 'AuthMiddleware',\r\n ResponseUtility.generateError(401, error.error || ErrorTypes.TOKEN_EXPIRED, true),\r\n res\r\n );\r\n }\r\n };\r\n }\r\n\r\n /**\r\n * Decodes the payload of a JWT using jose.decodeJwt without verifying\r\n * the signature or expiration.\r\n * WARNING: This is insecure as it doesn't validate the token's integrity.\r\n * Use only when you understand the risks and have a specific need.\r\n *\r\n * @param token - The JWT string.\r\n * @returns The decoded payload object, or null if the token format is invalid or decoding fails.\r\n */\r\n decodeJWTPayloadWithJose(token: string): Record<string, any> | null {\r\n if (!token || typeof token !== 'string') {\r\n Logger.logError(\"AuthContextMiddleware\", \"Invalid token provided for decoding.\");\r\n return null;\r\n }\r\n\r\n try {\r\n const payload = decodeJwt(token);\r\n return payload;\r\n } catch (error) {\r\n Logger.logError(\"AuthContextMiddleware\", `Failed to decode JWT payload: ${error}`);\r\n return null;\r\n }\r\n }\r\n\r\n AuthContextMiddleware() {\r\n return async (req: any, res: any, next: any) => {\r\n try {\r\n const [authType, token] = req.get('Authorization')?.split(' ') || [];\r\n let payload = authType === AuthType.CDN ? { id: token, type: AuthType.CDN } : (authType ? this.decodeJWTPayloadWithJose(token) : {});\r\n\r\n const authContext = AuthContext.init(payload?.id || token, payload?.type || authType, token, req.get('x-request-id'));\r\n Logger.logMessage('AuthContextMiddleware', `AuthContext initialized: ${authContext.getType() || 'No-Type'} - ${authContext.getId() || 'No-Id'}`);\r\n\r\n res.on('finish', () => {\r\n Logger.logMessage('AuthContextMiddleware', 'Uninitializing AuthContext');\r\n AuthContext.uninit();\r\n });\r\n\r\n next();\r\n } catch (error: any) {\r\n Logger.logError('AuthContextMiddleware', error);\r\n ResponseUtility.handleException(\r\n 'AuthContextMiddleware',\r\n ResponseUtility.generateError(500, error.error || ErrorTypes.INTERNAL_SERVER_ERROR, true),\r\n res\r\n );\r\n }\r\n };\r\n }\r\n}\r\n\r\nexport default AuthUtility;\r\nexport { AuthContext };\r\n\r\n"]}
|
package/dist/Classes/Cart.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'../chunk-
|
|
1
|
+
import {a}from'../chunk-6QSZECNF.mjs';import'../chunk-NXDEYUDI.mjs';import'../chunk-HX32EJ3F.mjs';import'../chunk-5N2HRXWJ.mjs';import'../chunk-MPKIC2MS.mjs';import'../chunk-EZ35IKUA.mjs';import'../chunk-MBR2GRKU.mjs';import {f}from'../chunk-4PTWJI6J.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
|
package/dist/Classes/Order.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1}from'../chunk-
|
|
1
|
+
import {a as a$1}from'../chunk-6QSZECNF.mjs';import'../chunk-NXDEYUDI.mjs';import {b}from'../chunk-HX32EJ3F.mjs';import'../chunk-5N2HRXWJ.mjs';import'../chunk-MPKIC2MS.mjs';import'../chunk-EZ35IKUA.mjs';import'../chunk-MBR2GRKU.mjs';import'../chunk-4PTWJI6J.mjs';import'../chunk-7RAIVZKB.mjs';import'../chunk-UIQH5QIR.mjs';import'../chunk-PL5HGCWN.mjs';import {a as a$2}from'../chunk-O6BLQQO7.mjs';import'../chunk-UXZBULDS.mjs';var a=(s=>(s.PLACED="PLACED",s.PENDING_PAYMENT="PENDING_PAYMENT",s.PROCESSING="PROCESSING",s.CANCELLED="CANCELLED",s.COMPLETED="COMPLETED",s))(a||{}),i=class extends a$1{orderNumber;cartId;paymentStatus;holdReason;state;shippingAddress;billingAddress;constructor(t,e=new Date){super(t,e,{checkCouponExpiry:!1}),this.orderNumber=t.orderNumber,this.cartId=t.cartId,this.paymentStatus=t.paymentStatus,this.holdReason=t.holdReason||"",this.state=t.state,this.shippingAddress=new b(t.shippingAddress,e),this.billingAddress=new b(t.billingAddress,e);}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getShippingAddress(){return this.shippingAddress}getBillingAddress(){return this.billingAddress}getOrderNumber(){return this.orderNumber}getCartId(){return this.cartId}getPaymentStatus(){return this.paymentStatus}getHoldReason(){return this.holdReason}getState(){return this.state}getLineItemState(t){let e=this.getLineItems().find(d=>d.getId()===t);if(!e)throw new a$2(t);return e.getState()}getDetails(){return {...super.getDetails(),orderNumber:this.getOrderNumber(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),shippingAddress:this.getShippingAddress().getDetails(),billingAddress:this.getBillingAddress().getDetails(),cartId:this.getCartId(),paymentStatus:this.getPaymentStatus(),holdReason:this.getHoldReason(),state:this.getState()}}};export{a as OrderState,i as default};//# sourceMappingURL=Order.mjs.map
|
|
2
2
|
//# sourceMappingURL=Order.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as default}from'../chunk-
|
|
1
|
+
export{a as default}from'../chunk-6QSZECNF.mjs';import'../chunk-NXDEYUDI.mjs';import'../chunk-HX32EJ3F.mjs';import'../chunk-5N2HRXWJ.mjs';import'../chunk-MPKIC2MS.mjs';import'../chunk-EZ35IKUA.mjs';import'../chunk-MBR2GRKU.mjs';import'../chunk-4PTWJI6J.mjs';import'../chunk-7RAIVZKB.mjs';import'../chunk-UIQH5QIR.mjs';import'../chunk-PL5HGCWN.mjs';import'../chunk-O6BLQQO7.mjs';import'../chunk-UXZBULDS.mjs';//# sourceMappingURL=ShoppingContainer.mjs.map
|
|
2
2
|
//# sourceMappingURL=ShoppingContainer.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-NXDEYUDI.mjs';import {e}from'./chunk-MBR2GRKU.mjs';import {b as b$1}from'./chunk-HX32EJ3F.mjs';import {a as a$1}from'./chunk-5N2HRXWJ.mjs';import {a as a$2}from'./chunk-4PTWJI6J.mjs';import {a as a$3}from'./chunk-UIQH5QIR.mjs';import {b}from'./chunk-UXZBULDS.mjs';var B=class extends b{id;customerId;customerEmail;anonymousId;lineItems;charges;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;#t;constructor(t,e$1=new Date,a$4={checkCouponExpiry:!0}){super(t,e$1),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(o=>new a(o)),this.charges=(t.charges??[]).map(o=>new a$1(o)),this.billingAddress=t.billingAddress?new b$1(t.billingAddress,e$1):null,this.shippingAddress=t.shippingAddress?new b$1(t.shippingAddress,e$1):null,this.coupons=(t.coupons??[]).map(o=>new e(o)),this.shippingDetails=t.shippingDetails?a$2.deepClone(t.shippingDetails):null,this.total={lineItemSubtotal:new a$3(t.total.lineItemSubtotal),netLineItemSubtotal:new a$3(t.total.netLineItemSubtotal),lineItemTaxTotal:new a$3(t.total.lineItemTaxTotal),lineItemTaxBreakdown:this.mapTaxBreakdown(t.total.lineItemTaxBreakdown),additiveCharges:new a$3(t.total.additiveCharges),netAdditiveCharges:new a$3(t.total.netAdditiveCharges),additiveChargesTaxTotal:new a$3(t.total.additiveChargesTaxTotal),additiveChargesTaxBreakdown:this.mapTaxBreakdown(t.total.additiveChargesTaxBreakdown),adjustmentCharges:new a$3(t.total.adjustmentCharges),shippingCharges:new a$3(t.total.shippingCharges),netShippingCharges:new a$3(t.total.netShippingCharges),discountTotal:new a$3(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([o,n])=>[o,new a$3(n)])),taxTotal:new a$3(t.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(t.total.taxBreakdown),grandTotal:new a$3(t.total.grandTotal)},this.#t={checkCouponExpiry:a$4.checkCouponExpiry};}mapTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,a])=>[e,{system:a.system,totalAmount:new a$3(a.totalAmount),subSystems:Object.fromEntries(Object.entries(a.subSystems).map(([o,n])=>[o,new a$3(n)]))}]))}serializeTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,a])=>[e,{system:a.system,totalAmount:a.totalAmount.getDetails(),subSystems:Object.fromEntries(Object.entries(a.subSystems).map(([o,n])=>[o,n.getDetails()]))}]))}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new a(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(t=>new a$1(t.getDetails()))}addCharge(t){this.charges.push(t),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?a$2.deepClone(this.shippingDetails):null}getShippingAddress(){return this.shippingAddress?new b$1(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new b$1(this.billingAddress.getDetails()):null}getCoupons(){return [...this.coupons]}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {lineItemSubtotal:this.total.lineItemSubtotal,netLineItemSubtotal:this.total.netLineItemSubtotal,lineItemTaxTotal:this.total.lineItemTaxTotal,lineItemTaxBreakdown:Object.fromEntries(Object.entries(this.total.lineItemTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),additiveCharges:this.total.additiveCharges,netAdditiveCharges:this.total.netAdditiveCharges,additiveChargesTaxTotal:this.total.additiveChargesTaxTotal,additiveChargesTaxBreakdown:Object.fromEntries(Object.entries(this.total.additiveChargesTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),adjustmentCharges:this.total.adjustmentCharges,shippingCharges:this.total.shippingCharges,netShippingCharges:this.total.netShippingCharges,discountBreakdown:{...this.total.discountBreakdown},discountTotal:this.total.discountTotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),grandTotal:this.total.grandTotal}}getDetails(){let t=this.getTotal();return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(e=>e.getDetails()),charges:this.getCharges().map(e=>e.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(e=>e.getDetails()),total:{lineItemSubtotal:t.lineItemSubtotal.getDetails(),netLineItemSubtotal:t.netLineItemSubtotal.getDetails(),lineItemTaxTotal:t.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(t.lineItemTaxBreakdown),additiveCharges:t.additiveCharges.getDetails(),netAdditiveCharges:t.netAdditiveCharges.getDetails(),additiveChargesTaxTotal:t.additiveChargesTaxTotal.getDetails(),additiveChargesTaxBreakdown:this.serializeTaxBreakdown(t.additiveChargesTaxBreakdown),adjustmentCharges:t.adjustmentCharges.getDetails(),shippingCharges:t.shippingCharges.getDetails(),netShippingCharges:t.netShippingCharges.getDetails(),discountTotal:t.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(t.discountBreakdown).map(([e,a])=>[e,a.getDetails()])),taxTotal:t.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(t.taxBreakdown),grandTotal:t.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new a$3({amount:0,currency:this.currency}),e=this.lineItems.filter(i=>i.getState()!=="CANCELLED"),a=e.reduce((i,s)=>i.add(s.getTotal().subtotal),t),o=this.charges.filter(i=>i.getType()==="SHIPPING").reduce((i,s)=>i.add(s.getTotal().chargeAmount),t);this.total.lineItemSubtotal=a,this.total.shippingCharges=o;let n=t,l={},p={};this.coupons.forEach(i=>{let s=i.calculateApplicableCouponDiscount(a,o,this.country,this.currency,this.#t.checkCouponExpiry);n=n.add(s),l[i.getCode()]=s,i.getCategory()!=="SHIPPING"&&(p[i.getCode()]=s);}),this.total.discountTotal=n,this.total.discountBreakdown=l,this.applyDiscountsInLineItem(p);let h=this.coupons.find(i=>i.getCategory()==="SHIPPING");h?this.applyDiscountsInShippingCharges({[h.getCode()]:l[h.getCode()]||t}):this.applyDiscountsInShippingCharges({});let d=this.lineItems.reduce((i,s)=>i.add(s.getTotal().netSubtotal),t),c=this.charges.filter(i=>i.getType()==="SHIPPING").reduce((i,s)=>i.add(s.getTotal().grandTotal),t);this.total.netLineItemSubtotal=d,this.total.netShippingCharges=c;let g=this.charges.filter(i=>i.getImpact()==="ADD").reduce((i,s)=>i.add(s.getTotal().chargeAmount),t),m=this.charges.filter(i=>i.getImpact()==="ADD").reduce((i,s)=>i.add(s.getTotal().grandTotal),t),k=this.charges.filter(i=>i.getImpact()==="SUBTRACT").reduce((i,s)=>i.add(s.getTotal().grandTotal),t),f=t,C=t,I=t,b={},M={},P={},x=(i,s)=>{Object.entries(i).forEach(([O,T])=>{let u=T.system,S=T.subSystem;s[u]||(s[u]={system:u,totalAmount:t,subSystems:{}}),s[u].subSystems[S]?s[u].subSystems[S]=s[u].subSystems[S].add(T.taxAmount):s[u].subSystems[S]=T.taxAmount,s[u].totalAmount=s[u].totalAmount.add(T.taxAmount);});};e.forEach(i=>{let s=i.getTotal().taxBreakdown;s&&(x(s,M),x(s,b),C=C.add(i.getTotal().taxTotal));}),this.charges.forEach(i=>{let s=i.getTotal().taxBreakdown;s&&(x(s,P),x(s,b),I=I.add(i.getTotal().taxTotal));}),f=C.add(I);let L=d.add(C).add(m).subtract(k);this.total={lineItemSubtotal:a,netLineItemSubtotal:d,lineItemTaxTotal:C,lineItemTaxBreakdown:M,additiveCharges:g,netAdditiveCharges:m,additiveChargesTaxTotal:I,additiveChargesTaxBreakdown:P,adjustmentCharges:k,shippingCharges:o,netShippingCharges:c,discountTotal:n,discountBreakdown:l,taxTotal:f,taxBreakdown:b,grandTotal:L};}updateShippingDetails(t){this.shippingDetails=t;}applyCoupons(t){let e=t.filter(o=>o.getCategory()==="SHIPPING"),a=t.filter(o=>o.getCategory()!=="SHIPPING");this.coupons=[],this.total.discountTotal=this.total.lineItemSubtotal.zero(),this.total.discountBreakdown={},a.length&&this.applyNonShippingCoupons(a),this.applyDiscountsInLineItem(this.total.discountBreakdown),e.length&&this.applyShippingCoupons(e),this.calculateTotals();}applyDiscountsInLineItem(t){let e=Array.from(Object.entries(t)).filter(o=>!o[1].isZero()),a=new Map;this.lineItems.forEach(o=>a.set(o.getId(),[])),e.forEach(([o,n])=>{let l=this.coupons.find(d=>d.getCode()===o);if(!l||n.isZero())return;let p=this.lineItems.filter(d=>d.getState()!=="CANCELLED"&&!d.getTotal().subtotal.isZero()).sort((d,c)=>d.getTotal().subtotal.compareTo(c.getTotal().subtotal)),h=new a$3({amount:0,currency:this.currency});p.forEach((d,c)=>{let g;c===p.length-1?g=n.subtract(h):g=n.multiply(d.getTotal().subtotal).divide(this.total.lineItemSubtotal).round(),h=h.add(g),a.get(d.getId())?.push({coupon:l,amount:g});});}),this.lineItems.forEach(o=>{o.getState()==="CANCELLED"||this.total.lineItemSubtotal.isZero()?o.updateDiscounts([]):o.updateDiscounts(a.get(o.getId())||[]);});}applyDiscountsInShippingCharges(t){let e=Array.from(Object.entries(t)).filter(n=>!n[1].isZero()),a=this.charges.filter(n=>n.getType()==="SHIPPING"),o=new Map;a.forEach(n=>o.set(n.getId(),[])),e.forEach(([n,l])=>{let p=this.coupons.find(c=>c.getCode()===n);if(!p||l.isZero())return;let h=a.sort((c,g)=>c.getTotal().grandTotal.compareTo(g.getTotal().grandTotal)),d=new a$3({amount:0,currency:this.currency});h.forEach((c,g)=>{let m;g===h.length-1?m=l.subtract(d):m=l.multiply(c.getTotal().chargeAmount).divide(this.total.shippingCharges).round(),d=d.add(m),o.get(c.getId())?.push({coupon:p,amount:m});});}),a.forEach(n=>{n.updateDiscounts(o.get(n.getId())||[]);});}applyNonShippingCoupons(t){let e=t.filter(a=>a.getType()==="coupon");if(e.length===1){let a=e[0].calculateApplicableCouponDiscount(this.total.lineItemSubtotal,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry);a.getAmount()>0&&(this.coupons.push(e[0]),this.total.discountTotal=a,this.total.discountBreakdown[e[0].getCode()]=a);}}applyShippingCoupons(t){if(this.total.shippingCharges.getAmount()>0&&t.length>0){let e=this.total.lineItemSubtotal.subtract(this.total.discountTotal),a=t.reduce((n,l)=>{if(!n)return l;let p=l.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry).min(this.total.shippingCharges),h=n.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry).min(this.total.shippingCharges);return p.compareTo(h)===0?l.getType()==="coupon"?l:n:p.compareTo(h)>0?l:n}),o=a.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry).min(this.total.shippingCharges);o.getAmount()>0&&(this.coupons.push(a),this.total.discountTotal=this.total.discountTotal.add(o),this.total.discountBreakdown[a.getCode()]=o);}}};export{B as a};//# sourceMappingURL=chunk-SZLAIOMF.mjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a}from'./chunk-NXDEYUDI.mjs';import {b as b$1}from'./chunk-HX32EJ3F.mjs';import {a as a$1}from'./chunk-5N2HRXWJ.mjs';import {e}from'./chunk-MBR2GRKU.mjs';import {a as a$2}from'./chunk-4PTWJI6J.mjs';import {a as a$3}from'./chunk-UIQH5QIR.mjs';import {b}from'./chunk-UXZBULDS.mjs';var B=class extends b{id;customerId;customerEmail;anonymousId;lineItems;charges;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;#t;constructor(t,e$1=new Date,a$4={checkCouponExpiry:!0}){super(t,e$1),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(o=>new a(o)),this.charges=(t.charges??[]).map(o=>new a$1(o)),this.billingAddress=t.billingAddress?new b$1(t.billingAddress,e$1):null,this.shippingAddress=t.shippingAddress?new b$1(t.shippingAddress,e$1):null,this.coupons=(t.coupons??[]).map(o=>new e(o)),this.shippingDetails=t.shippingDetails?a$2.deepClone(t.shippingDetails):null,this.total={lineItemSubtotal:new a$3(t.total.lineItemSubtotal),netLineItemSubtotal:new a$3(t.total.netLineItemSubtotal),lineItemTaxTotal:new a$3(t.total.lineItemTaxTotal),lineItemTaxBreakdown:this.mapTaxBreakdown(t.total.lineItemTaxBreakdown),additiveCharges:new a$3(t.total.additiveCharges),netAdditiveCharges:new a$3(t.total.netAdditiveCharges),additiveChargesTaxTotal:new a$3(t.total.additiveChargesTaxTotal),additiveChargesTaxBreakdown:this.mapTaxBreakdown(t.total.additiveChargesTaxBreakdown),adjustmentCharges:new a$3(t.total.adjustmentCharges),shippingCharges:new a$3(t.total.shippingCharges),netShippingCharges:new a$3(t.total.netShippingCharges),discountTotal:new a$3(t.total.discountTotal),discountBreakdown:Object.fromEntries(Object.entries(t.total.discountBreakdown).map(([o,n])=>[o,new a$3(n)])),taxTotal:new a$3(t.total.taxTotal),taxBreakdown:this.mapTaxBreakdown(t.total.taxBreakdown),grandTotal:new a$3(t.total.grandTotal)},this.#t={checkCouponExpiry:a$4.checkCouponExpiry};}mapTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,a])=>[e,{system:a.system,totalAmount:new a$3(a.totalAmount),subSystems:Object.fromEntries(Object.entries(a.subSystems).map(([o,n])=>[o,new a$3(n)]))}]))}serializeTaxBreakdown(t){return Object.fromEntries(Object.entries(t||{}).map(([e,a])=>[e,{system:a.system,totalAmount:a.totalAmount.getDetails(),subSystems:Object.fromEntries(Object.entries(a.subSystems).map(([o,n])=>[o,n.getDetails()]))}]))}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new a(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getCharges(){return this.charges.map(t=>new a$1(t.getDetails()))}addCharge(t){this.charges.push(t),this.calculateTotals();}clearCharges(){this.charges=[],this.calculateTotals();}getShippingDetails(){return this.shippingDetails?a$2.deepClone(this.shippingDetails):null}getShippingAddress(){return this.shippingAddress?new b$1(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new b$1(this.billingAddress.getDetails()):null}getCoupons(){return [...this.coupons]}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {lineItemSubtotal:this.total.lineItemSubtotal,netLineItemSubtotal:this.total.netLineItemSubtotal,lineItemTaxTotal:this.total.lineItemTaxTotal,lineItemTaxBreakdown:Object.fromEntries(Object.entries(this.total.lineItemTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),additiveCharges:this.total.additiveCharges,netAdditiveCharges:this.total.netAdditiveCharges,additiveChargesTaxTotal:this.total.additiveChargesTaxTotal,additiveChargesTaxBreakdown:Object.fromEntries(Object.entries(this.total.additiveChargesTaxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),adjustmentCharges:this.total.adjustmentCharges,shippingCharges:this.total.shippingCharges,netShippingCharges:this.total.netShippingCharges,discountBreakdown:{...this.total.discountBreakdown},discountTotal:this.total.discountTotal,taxTotal:this.total.taxTotal,taxBreakdown:Object.fromEntries(Object.entries(this.total.taxBreakdown).map(([t,e])=>[t,{system:e.system,totalAmount:e.totalAmount,subSystems:{...e.subSystems}}])),grandTotal:this.total.grandTotal}}getDetails(){let t=this.getTotal();return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(e=>e.getDetails()),charges:this.getCharges().map(e=>e.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(e=>e.getDetails()),total:{lineItemSubtotal:t.lineItemSubtotal.getDetails(),netLineItemSubtotal:t.netLineItemSubtotal.getDetails(),lineItemTaxTotal:t.lineItemTaxTotal.getDetails(),lineItemTaxBreakdown:this.serializeTaxBreakdown(t.lineItemTaxBreakdown),additiveCharges:t.additiveCharges.getDetails(),netAdditiveCharges:t.netAdditiveCharges.getDetails(),additiveChargesTaxTotal:t.additiveChargesTaxTotal.getDetails(),additiveChargesTaxBreakdown:this.serializeTaxBreakdown(t.additiveChargesTaxBreakdown),adjustmentCharges:t.adjustmentCharges.getDetails(),shippingCharges:t.shippingCharges.getDetails(),netShippingCharges:t.netShippingCharges.getDetails(),discountTotal:t.discountTotal.getDetails(),discountBreakdown:Object.fromEntries(Object.entries(t.discountBreakdown).map(([e,a])=>[e,a.getDetails()])),taxTotal:t.taxTotal.getDetails(),taxBreakdown:this.serializeTaxBreakdown(t.taxBreakdown),grandTotal:t.grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new a$3({amount:0,currency:this.currency}),e=this.lineItems.filter(i=>i.getState()!=="CANCELLED"),a=e.reduce((i,s)=>i.add(s.getTotal().subtotal),t),o=this.charges.filter(i=>i.getType()==="SHIPPING").reduce((i,s)=>i.add(s.getTotal().chargeAmount),t);this.total.lineItemSubtotal=a,this.total.shippingCharges=o;let n=t,l={},p={};this.coupons.forEach(i=>{let s=i.calculateApplicableCouponDiscount(a,o,this.country,this.currency,this.#t.checkCouponExpiry);n=n.add(s),l[i.getCode()]=s,i.getCategory()!=="SHIPPING"&&(p[i.getCode()]=s);}),this.total.discountTotal=n,this.total.discountBreakdown=l,this.applyDiscountsInLineItem(p);let h=this.coupons.find(i=>i.getCategory()==="SHIPPING");h?this.applyDiscountsInShippingCharges({[h.getCode()]:l[h.getCode()]||t}):this.applyDiscountsInShippingCharges({});let d=this.lineItems.reduce((i,s)=>i.add(s.getTotal().netSubtotal),t),c=this.charges.filter(i=>i.getType()==="SHIPPING").reduce((i,s)=>i.add(s.getTotal().grandTotal),t);this.total.netLineItemSubtotal=d,this.total.netShippingCharges=c;let g=this.charges.filter(i=>i.getImpact()==="ADD").reduce((i,s)=>i.add(s.getTotal().chargeAmount),t),m=this.charges.filter(i=>i.getImpact()==="ADD").reduce((i,s)=>i.add(s.getTotal().grandTotal),t),k=this.charges.filter(i=>i.getImpact()==="SUBTRACT").reduce((i,s)=>i.add(s.getTotal().grandTotal),t),f=t,C=t,I=t,b={},M={},P={},x=(i,s)=>{Object.entries(i).forEach(([O,T])=>{let u=T.system,S=T.subSystem;s[u]||(s[u]={system:u,totalAmount:t,subSystems:{}}),s[u].subSystems[S]?s[u].subSystems[S]=s[u].subSystems[S].add(T.taxAmount):s[u].subSystems[S]=T.taxAmount,s[u].totalAmount=s[u].totalAmount.add(T.taxAmount);});};e.forEach(i=>{let s=i.getTotal().taxBreakdown;s&&(x(s,M),x(s,b),C=C.add(i.getTotal().taxTotal));}),this.charges.forEach(i=>{let s=i.getTotal().taxBreakdown;s&&(x(s,P),x(s,b),I=I.add(i.getTotal().taxTotal));}),f=C.add(I);let L=d.add(C).add(m).subtract(k);this.total={lineItemSubtotal:a,netLineItemSubtotal:d,lineItemTaxTotal:C,lineItemTaxBreakdown:M,additiveCharges:g,netAdditiveCharges:m,additiveChargesTaxTotal:I,additiveChargesTaxBreakdown:P,adjustmentCharges:k,shippingCharges:o,netShippingCharges:c,discountTotal:n,discountBreakdown:l,taxTotal:f,taxBreakdown:b,grandTotal:L};}updateShippingDetails(t){this.shippingDetails=t;}applyCoupons(t){let e=t.filter(o=>o.getCategory()==="SHIPPING"),a=t.filter(o=>o.getCategory()!=="SHIPPING");this.coupons=[],this.total.discountTotal=this.total.lineItemSubtotal.zero(),this.total.discountBreakdown={},a.length&&this.applyNonShippingCoupons(a),this.applyDiscountsInLineItem(this.total.discountBreakdown),e.length&&this.applyShippingCoupons(e),this.calculateTotals();}applyDiscountsInLineItem(t){let e=Array.from(Object.entries(t)).filter(o=>!o[1].isZero()),a=new Map;this.lineItems.forEach(o=>a.set(o.getId(),[])),e.forEach(([o,n])=>{let l=this.coupons.find(d=>d.getCode()===o);if(!l||n.isZero())return;let p=this.lineItems.filter(d=>d.getState()!=="CANCELLED"&&!d.getTotal().subtotal.isZero()).sort((d,c)=>d.getTotal().subtotal.compareTo(c.getTotal().subtotal)),h=new a$3({amount:0,currency:this.currency});p.forEach((d,c)=>{let g;c===p.length-1?g=n.subtract(h):g=n.multiply(d.getTotal().subtotal).divide(this.total.lineItemSubtotal).round(),h=h.add(g),a.get(d.getId())?.push({coupon:l,amount:g});});}),this.lineItems.forEach(o=>{o.getState()==="CANCELLED"||this.total.lineItemSubtotal.isZero()?o.updateDiscounts([]):o.updateDiscounts(a.get(o.getId())||[]);});}applyDiscountsInShippingCharges(t){let e=Array.from(Object.entries(t)).filter(n=>!n[1].isZero()),a=this.charges.filter(n=>n.getType()==="SHIPPING"),o=new Map;a.forEach(n=>o.set(n.getId(),[])),e.forEach(([n,l])=>{let p=this.coupons.find(c=>c.getCode()===n);if(!p||l.isZero())return;let h=a.sort((c,g)=>c.getTotal().grandTotal.compareTo(g.getTotal().grandTotal)),d=new a$3({amount:0,currency:this.currency});h.forEach((c,g)=>{let m;g===h.length-1?m=l.subtract(d):m=l.multiply(c.getTotal().chargeAmount).divide(this.total.shippingCharges).round(),d=d.add(m),o.get(c.getId())?.push({coupon:p,amount:m});});}),a.forEach(n=>{n.updateDiscounts(o.get(n.getId())||[]);});}applyNonShippingCoupons(t){let e=t.filter(a=>a.getType()==="coupon");if(e.length===1){let a=e[0].calculateApplicableCouponDiscount(this.total.lineItemSubtotal,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry);a.getAmount()>0&&(this.coupons.push(e[0]),this.total.discountTotal=a,this.total.discountBreakdown[e[0].getCode()]=a);}}applyShippingCoupons(t){if(this.total.shippingCharges.getAmount()>0&&t.length>0){let e=this.total.lineItemSubtotal.subtract(this.total.discountTotal),a=t.reduce((n,l)=>{if(!n)return l;let p=l.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry).min(this.total.shippingCharges),h=n.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry).min(this.total.shippingCharges);return p.compareTo(h)===0?l.getType()==="coupon"?l:n:p.compareTo(h)>0?l:n}),o=a.calculateApplicableCouponDiscount(e,this.total.shippingCharges,this.country,this.currency,this.#t.checkCouponExpiry).min(this.total.shippingCharges);o.getAmount()>0&&(this.coupons.push(a),this.total.discountTotal=this.total.discountTotal.add(o),this.total.discountBreakdown[a.getCode()]=o);}}};export{B as a};//# sourceMappingURL=chunk-6QSZECNF.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-6QSZECNF.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Classes/ShoppingContainer.ts"],"names":["BaseShoppingContainerModel","BaseModel","#metaData","data","date","metaData","item","LineItemModel","charge","ChargeModel","AddressModel","coupon","CouponModel","Utils_default","PriceModel","key","value","breakdown","systemKey","systemValue","subKey","subValue","totals","zero","filteredLineItems","lineitem","lineItemSubtotal","total","lineItem","shippingCharges","discountTotal","discountBreakdown","nonShippingCouponTotal","couponValue","shippingCoupon","netLineItemSubtotal","netShippingCharges","additiveCharges","netAdditiveCharges","adjustmentCharges","taxTotal","lineItemTaxTotal","additiveChargesTaxTotal","taxBreakdown","lineItemTaxBreakdown","additiveChargesTaxBreakdown","mergeTax","sourceBreakdown","targetBreakdown","ruleId","system","subsystem","lineItemTaxes","chargeTaxes","grandTotal","shippingDetails","applicableCoupons","shippingCoupons","otherCoupons","couponTotal","couponDiscounts","couponDiscount","itemDiscounts","li","code","c","validItems","a","b","distributed","index","amount","chargeDiscounts","validCharges","coupons","maxValuedCoupon","maxCoupon","currentCoupon","currentCouponValue","maxCouponValue"],"mappings":"+RAsIA,IAA8BA,CAA9B,CAAA,cAAiEC,CAAU,CAC/D,EACA,CAAA,UAAA,CACA,aACA,CAAA,WAAA,CACA,SACA,CAAA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AA,IAAA,CAAK,KAAM,CAAA,aAAA,CAAgB,IAAK,CAAA,KAAA,CAAM,aAAc,CAAA,GAAA,CAAI1C,CAAW,CAAA,CACnE,IAAK,CAAA,KAAA,CAAM,iBAAkB0C,CAAAA,CAAAA,CAAgB,OAAQ,EAAC,CAAI1C,CAAAA,CAAAA,EAE9D,CACF,CACF","file":"chunk-SZLAIOMF.mjs","sourcesContent":["import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport AddressModel, { AddressData } from \"./Address\";\r\nimport LineItemModel, { LineItemData, LineItemTaxBreakdown, LineItemTaxBreakdownModel } from \"./LineItem\";\r\nimport { CountryCode, CurrencyCode, LocaleCode, ShippingDetails } from \"./Common\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport CouponModel, { CouponCategory, CouponData, CouponType } from \"./Coupon\";\r\nimport Utils from \"../Utils\";\r\nimport { ChargeImpact, ChargeType, LineItemState, TaxSystem } from \"./Enum\";\r\nimport ChargeModel, { ChargeData, ChargeTaxBreakdownModel } from \"./Charge\";\r\n\r\n/**\r\n * Breakdown of a specific tax system (e.g., GST, VAT) for the entire container.\r\n * Groups taxes by system and then by specific rule/subsystem.\r\n */\r\nexport type TaxSystemBreakdown = {\r\n /** Name of the tax system (e.g., GST) */\r\n system: TaxSystem;\r\n /** Total tax amount collected for this system across all line items and charges */\r\n totalAmount: PriceData;\r\n /** Detailed breakdown by rule/subsystem to total tax amount (e.g., CGST, SGST) */\r\n subSystems: Record<string, PriceData>;\r\n};\r\n\r\n/**\r\n * Internal model for tax system breakdown using PriceModel instances.\r\n */\r\nexport type TaxSystemBreakdownModel = {\r\n system: TaxSystem;\r\n totalAmount: PriceModel;\r\n subSystems: Record<string, PriceModel>;\r\n};\r\n\r\nexport type ShoppingContainerTaxBreakdownModel = Record<string, TaxSystemBreakdownModel>;\r\n\r\n/**\r\n * Comprehensive totals for a shopping container, logically grouped by source.\r\n */\r\nexport type ShoppingContainerTotal = {\r\n // --- Item Totals ---\r\n /** Sum of all line item prices before any discounts or taxes */\r\n lineItemSubtotal: PriceData;\r\n /** Total item subtotal after item-level discounts have been applied (taxable base for items) */\r\n netLineItemSubtotal: PriceData;\r\n /** Total tax collected specifically from line items */\r\n lineItemTaxTotal: PriceData;\r\n /** Granular tax breakdown for all line items */\r\n lineItemTaxBreakdown: Record<string, TaxSystemBreakdown>;\r\n\r\n // --- Charge Totals ---\r\n /** Sum of pre-discount chargeAmount for additive charges (tax-inclusive) */\r\n additiveCharges: PriceData;\r\n /** Sum of post-discount netChargeAmount for additive charges – final payable (tax-inclusive) */\r\n netAdditiveCharges: PriceData;\r\n /** Tax reverse-calculated from additive charges only */\r\n additiveChargesTaxTotal: PriceData;\r\n /** Granular tax breakdown from additive charges */\r\n additiveChargesTaxBreakdown: Record<string, TaxSystemBreakdown>;\r\n\r\n /** Sum of post-discount netChargeAmount for subtractive charges – absolute amount to subtract */\r\n adjustmentCharges: PriceData;\r\n\r\n /** Pre-discount shipping gross (tax-inclusive, part of additive charges) */\r\n shippingCharges: PriceData;\r\n /** Shipping cost after any shipping-specific discounts */\r\n netShippingCharges: PriceData;\r\n\r\n // --- Aggregate Totals ---\r\n /** Combined total tax (lineItemTaxTotal + chargeTaxTotal) */\r\n taxTotal: PriceData;\r\n /** Combined granular tax breakdown for the entire container */\r\n taxBreakdown: Record<string, TaxSystemBreakdown>;\r\n /** Sum of all coupon discounts applied to the container */\r\n discountTotal: PriceData;\r\n /** Map of applied coupon codes to their calculated discount amounts */\r\n discountBreakdown: Record<string, PriceData>;\r\n /** Final total amount to be paid (NetSubtotal + ChargesTotal + TaxTotal - (any remaining discounts)) */\r\n grandTotal: PriceData;\r\n};\r\n\r\n\r\n/**\r\n * Internal model version of ShoppingContainerTotal using PriceModel instances.\r\n */\r\nexport type ShoppingContainerTotalModel = {\r\n lineItemSubtotal: PriceModel;\r\n netLineItemSubtotal: PriceModel;\r\n lineItemTaxTotal: PriceModel;\r\n lineItemTaxBreakdown: Record<string, TaxSystemBreakdownModel>;\r\n\r\n additiveCharges: PriceModel;\r\n netAdditiveCharges: PriceModel;\r\n additiveChargesTaxTotal: PriceModel;\r\n additiveChargesTaxBreakdown: Record<string, TaxSystemBreakdownModel>;\r\n\r\n adjustmentCharges: PriceModel;\r\n\r\n shippingCharges: PriceModel;\r\n netShippingCharges: PriceModel;\r\n\r\n taxTotal: PriceModel;\r\n taxBreakdown: Record<string, TaxSystemBreakdownModel>;\r\n discountTotal: PriceModel;\r\n discountBreakdown: Record<string, PriceModel>;\r\n grandTotal: PriceModel;\r\n};\r\n\r\nexport type ShoppingContainerMetaData = {\r\n checkCouponExpiry: boolean\r\n}\r\n\r\nexport type BaseShoppingContainerAttributes = BaseAttributes & {\r\n id: string;\r\n customerId?: string;\r\n customerEmail?: string;\r\n anonymousId?: string;\r\n lineItems: LineItemData[];\r\n charges: ChargeData[];\r\n shippingDetails: ShippingDetails | null;\r\n shippingAddress?: AddressData | null;\r\n billingAddress?: AddressData | null;\r\n coupons: CouponData[];\r\n total: ShoppingContainerTotal;\r\n country: CountryCode;\r\n currency: CurrencyCode;\r\n locale: LocaleCode;\r\n};\r\n\r\nexport type BaseShoppingContainerData = BaseShoppingContainerAttributes & BaseData\r\n\r\n\r\n/**\r\n * Abstract base class for shopping-related containers like carts and orders.\r\n * Manages common elements such as line items, addresses, coupons, and totals.\r\n */\r\nexport default abstract class BaseShoppingContainerModel extends BaseModel {\r\n protected id: string;\r\n protected customerId?: string;\r\n protected customerEmail?: string;\r\n protected anonymousId?: string;\r\n protected lineItems: LineItemModel[];\r\n protected charges: ChargeModel[];\r\n protected shippingDetails: ShippingDetails | null;\r\n protected shippingAddress: AddressModel | null;\r\n protected billingAddress: AddressModel | null;\r\n\r\n // CouponsCodes\r\n protected coupons: CouponModel[];\r\n\r\n // Cart Totals\r\n protected total: ShoppingContainerTotalModel;\r\n\r\n protected country: CountryCode;\r\n protected currency: CurrencyCode;\r\n protected locale: LocaleCode;\r\n #metaData: ShoppingContainerMetaData;\r\n\r\n /**\r\n * Creates an instance of BaseShoppingContainerModel.\r\n * Initializes common properties and calculates initial base totals.\r\n * @param data - The initial attributes for the shopping container.\r\n * @param date - Optional date object for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: BaseShoppingContainerAttributes, date: Date = new Date(), metaData: ShoppingContainerMetaData = { checkCouponExpiry: true }) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.customerId = data.customerId;\r\n this.customerEmail = data.customerEmail;\r\n this.anonymousId = data.anonymousId;\r\n this.country = data.country;\r\n this.currency = data.currency;\r\n this.locale = data.locale;\r\n this.lineItems = (data.lineItems ?? []).map(item => new LineItemModel(item));\r\n this.charges = (data.charges ?? []).map(charge => new ChargeModel(charge));\r\n this.billingAddress = data.billingAddress ? new AddressModel(data.billingAddress, date) : null;\r\n this.shippingAddress = data.shippingAddress ? new AddressModel(data.shippingAddress, date) : null;\r\n this.coupons = (data.coupons ?? []).map(coupon => new CouponModel(coupon));\r\n\r\n this.shippingDetails = data.shippingDetails ? Utils.deepClone(data.shippingDetails) : null;\r\n\r\n this.total = {\r\n lineItemSubtotal: new PriceModel(data.total.lineItemSubtotal),\r\n netLineItemSubtotal: new PriceModel(data.total.netLineItemSubtotal),\r\n lineItemTaxTotal: new PriceModel(data.total.lineItemTaxTotal),\r\n lineItemTaxBreakdown: this.mapTaxBreakdown(data.total.lineItemTaxBreakdown),\r\n\r\n additiveCharges: new PriceModel(data.total.additiveCharges),\r\n netAdditiveCharges: new PriceModel(data.total.netAdditiveCharges),\r\n additiveChargesTaxTotal: new PriceModel(data.total.additiveChargesTaxTotal),\r\n\r\n additiveChargesTaxBreakdown: this.mapTaxBreakdown(data.total.additiveChargesTaxBreakdown),\r\n adjustmentCharges: new PriceModel(data.total.adjustmentCharges),\r\n shippingCharges: new PriceModel(data.total.shippingCharges),\r\n netShippingCharges: new PriceModel(data.total.netShippingCharges),\r\n\r\n discountTotal: new PriceModel(data.total.discountTotal),\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(data.total.discountBreakdown).map(([key, value]) => [key, new PriceModel(value)])\r\n ),\r\n\r\n taxTotal: new PriceModel(data.total.taxTotal),\r\n taxBreakdown: this.mapTaxBreakdown(data.total.taxBreakdown),\r\n grandTotal: new PriceModel(data.total.grandTotal),\r\n };\r\n\r\n this.#metaData = {\r\n checkCouponExpiry: metaData.checkCouponExpiry\r\n }\r\n }\r\n\r\n private mapTaxBreakdown(breakdown: Record<string, TaxSystemBreakdown>): Record<string, TaxSystemBreakdownModel> {\r\n return Object.fromEntries(\r\n Object.entries(breakdown || {}).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: new PriceModel(systemValue.totalAmount),\r\n subSystems: Object.fromEntries(\r\n Object.entries(systemValue.subSystems).map(([subKey, subValue]) => [\r\n subKey,\r\n new PriceModel(subValue)\r\n ])\r\n )\r\n }\r\n ])\r\n );\r\n }\r\n\r\n private serializeTaxBreakdown(breakdown: Record<string, TaxSystemBreakdownModel>): Record<string, TaxSystemBreakdown> {\r\n return Object.fromEntries(\r\n Object.entries(breakdown || {}).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount.getDetails(),\r\n subSystems: Object.fromEntries(\r\n Object.entries(systemValue.subSystems).map(([subKey, subValue]) => [\r\n subKey,\r\n subValue.getDetails()\r\n ])\r\n )\r\n }\r\n ])\r\n );\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for this shopping container (cart ID or order ID).\r\n * @returns The ID string.\r\n */\r\n public getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the customer ID associated with this container, if available.\r\n * @returns The customer ID string, or undefined.\r\n */\r\n public getCustomerId(): string | undefined {\r\n return this.customerId;\r\n }\r\n\r\n /**\r\n * Gets the customer email associated with this container, if available.\r\n * @returns The customer email string, or undefined.\r\n */\r\n public getCustomerEmail(): string | undefined {\r\n return this.customerEmail;\r\n }\r\n\r\n /**\r\n * Gets the anonymous user ID associated with this container, if available.\r\n * @returns The anonymous ID string, or undefined.\r\n */\r\n public getAnonymousId(): string | undefined {\r\n return this.anonymousId;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the line items in the container.\r\n * Each item is a new LineItemModel instance created from the original's details.\r\n * @returns An array of LineItemModel instances.\r\n */\r\n public getLineItems(): LineItemModel[] {\r\n // Return new instances to prevent modification of internal state\r\n return this.lineItems.map(item => new LineItemModel(item.getDetails()));\r\n }\r\n\r\n /**\r\n * Gets current number of line items in the container.\r\n * @returns The count of line items.\r\n */\r\n public getLineItemsCount(): number {\r\n return this.lineItems.length;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the charges in the container.\r\n * @returns An array of ChargeModel instances.\r\n */\r\n public getCharges(): ChargeModel[] {\r\n return this.charges.map(charge => new ChargeModel(charge.getDetails()));\r\n }\r\n\r\n /**\r\n * Adds a new charge to the container and recalculates totals.\r\n * @param charge - The charge to add.\r\n */\r\n public addCharge(charge: ChargeModel): void {\r\n this.charges.push(charge);\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Clears all charges from the container and recalculates totals.\r\n */\r\n public clearCharges(): void {\r\n this.charges = [];\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Gets a copy of the shipping details associated with the container.\r\n * @returns A ShippingDetails object, or null if none are set.\r\n */\r\n public getShippingDetails(): ShippingDetails | null {\r\n return this.shippingDetails ? Utils.deepClone(this.shippingDetails) : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the shipping address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no shipping address is set.\r\n */\r\n public getShippingAddress(): AddressModel | null {\r\n return this.shippingAddress ? new AddressModel(this.shippingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Checks if a shipping address is associated with this container.\r\n * @returns True if a shipping address is set, false otherwise.\r\n */\r\n public hasShippingAddress(): boolean {\r\n return !!this.shippingAddress;\r\n }\r\n\r\n /**\r\n * Checks if a billing address is associated with this container.\r\n * @returns True if a billing address is set, false otherwise.\r\n */\r\n public hasBillingAddress(): boolean {\r\n return !!this.billingAddress;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the billing address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no billing address is set.\r\n */\r\n public getBillingAddress(): AddressModel | null {\r\n return this.billingAddress ? new AddressModel(this.billingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the coupons applied to the container.\r\n * Each item is a new CouponModel instance created from the original's details.\r\n * @returns An array of CouponModel instances.\r\n */\r\n public getCoupons(): CouponModel[] {\r\n return [...this.coupons];\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this container.\r\n * @returns The CountryCode enum value.\r\n */\r\n public getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Gets the currency code associated with this container.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Gets the locale code associated with this container.\r\n * @returns The LocaleCode enum value.\r\n */\r\n public getLocale(): LocaleCode {\r\n return this.locale;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the calculated totals for the container.\r\n * @returns An object containing shipping, subtotal, coupon, and grand totals.\r\n */\r\n public getTotal() {\r\n return {\r\n lineItemSubtotal: this.total.lineItemSubtotal,\r\n netLineItemSubtotal: this.total.netLineItemSubtotal,\r\n lineItemTaxTotal: this.total.lineItemTaxTotal,\r\n lineItemTaxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.lineItemTaxBreakdown).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount,\r\n subSystems: { ...systemValue.subSystems }\r\n }\r\n ])\r\n ),\r\n additiveCharges: this.total.additiveCharges,\r\n netAdditiveCharges : this.total.netAdditiveCharges,\r\n additiveChargesTaxTotal: this.total.additiveChargesTaxTotal,\r\n additiveChargesTaxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.additiveChargesTaxBreakdown).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount,\r\n subSystems: { ...systemValue.subSystems }\r\n }\r\n ])\r\n ),\r\n adjustmentCharges: this.total.adjustmentCharges,\r\n shippingCharges: this.total.shippingCharges,\r\n netShippingCharges: this.total.netShippingCharges,\r\n discountBreakdown: { ...this.total.discountBreakdown },\r\n discountTotal: this.total.discountTotal,\r\n taxTotal: this.total.taxTotal,\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.taxBreakdown).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount,\r\n subSystems: { ...systemValue.subSystems }\r\n }\r\n ])\r\n ),\r\n grandTotal: this.total.grandTotal,\r\n };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the shopping container's current state.\r\n * Includes details from the base model and specific container properties.\r\n * @returns BaseShoppingContainerData object suitable for serialization or API responses.\r\n */\r\n getDetails(): BaseShoppingContainerData {\r\n const totals = this.getTotal();\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n customerId: this.getCustomerId(),\r\n customerEmail: this.getCustomerEmail(),\r\n anonymousId: this.getAnonymousId(),\r\n lineItems: this.getLineItems().map(item => item.getDetails()),\r\n charges: this.getCharges().map(charge => charge.getDetails()),\r\n shippingDetails: this.getShippingDetails(),\r\n shippingAddress: this.getShippingAddress()?.getDetails() || null,\r\n billingAddress: this.getBillingAddress()?.getDetails() || null,\r\n coupons: this.getCoupons().map(coupon => coupon.getDetails()),\r\n total: {\r\n // Item Totals\r\n lineItemSubtotal: totals.lineItemSubtotal.getDetails(),\r\n netLineItemSubtotal: totals.netLineItemSubtotal.getDetails(),\r\n lineItemTaxTotal: totals.lineItemTaxTotal.getDetails(),\r\n lineItemTaxBreakdown: this.serializeTaxBreakdown(totals.lineItemTaxBreakdown),\r\n\r\n // Charge Totals\r\n additiveCharges: totals.additiveCharges.getDetails(),\r\n netAdditiveCharges: totals.netAdditiveCharges.getDetails(),\r\n additiveChargesTaxTotal: totals.additiveChargesTaxTotal.getDetails(),\r\n additiveChargesTaxBreakdown: this.serializeTaxBreakdown(totals.additiveChargesTaxBreakdown),\r\n\r\n adjustmentCharges: totals.adjustmentCharges.getDetails(),\r\n\r\n shippingCharges: totals.shippingCharges.getDetails(),\r\n netShippingCharges: totals.netShippingCharges.getDetails(),\r\n\r\n // Aggregate Totals\r\n discountTotal: totals.discountTotal.getDetails(),\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(totals.discountBreakdown).map(([key, value]) => [key, value.getDetails()])\r\n ),\r\n taxTotal: totals.taxTotal.getDetails(),\r\n taxBreakdown: this.serializeTaxBreakdown(totals.taxBreakdown),\r\n grandTotal: totals.grandTotal.getDetails(),\r\n },\r\n country: this.getCountry(),\r\n currency: this.getCurrency(),\r\n locale: this.getLocale(),\r\n };\r\n }\r\n\r\n /**\r\n * Recalculates the total costs for the shopping container.\r\n * This includes summing line items, calculating shipping, applying coupons, and computing taxes.\r\n */\r\n public calculateTotals(): void {\r\n const zero = new PriceModel({ amount: 0, currency: this.currency });\r\n \r\n // 1. Calculate LineItem subtotals and Shipping Cost\r\n const filteredLineItems = this.lineItems.filter(lineitem => lineitem.getState() !== LineItemState.CANCELLED);\r\n const lineItemSubtotal = filteredLineItems.reduce((total, lineItem) => total.add(lineItem.getTotal().subtotal), zero);\r\n const shippingCharges = this.charges\r\n .filter(charge => charge.getType() === ChargeType.SHIPPING)\r\n .reduce((total, charge) => total.add(charge.getTotal().chargeAmount), zero);\r\n\r\n // 1.1 Assign lineitemSubTotal and shipping charges to total, which will be used for coupon calculations\r\n this.total.lineItemSubtotal = lineItemSubtotal;\r\n this.total.shippingCharges = shippingCharges;\r\n\r\n // 2. Calculate coupon values based on gross subtotal & shipping\r\n let discountTotal = zero;\r\n let discountBreakdown: Record<string, PriceModel> = {};\r\n let nonShippingCouponTotal: Record<string, PriceModel> = {};\r\n this.coupons.forEach(coupon => {\r\n const couponValue = coupon.calculateApplicableCouponDiscount(lineItemSubtotal, shippingCharges, this.country, this.currency, this.#metaData.checkCouponExpiry);\r\n discountTotal = discountTotal.add(couponValue);\r\n discountBreakdown[coupon.getCode()] = couponValue;\r\n if (coupon.getCategory() !== CouponCategory.SHIPPING) {\r\n nonShippingCouponTotal[coupon.getCode()] = couponValue;\r\n }\r\n })\r\n\r\n // 2.1. Assign discount total and breakdown to total\r\n this.total.discountTotal = discountTotal;\r\n this.total.discountBreakdown = discountBreakdown;\r\n\r\n // 3. Apply discounts at lineitem and shipping charges\r\n this.applyDiscountsInLineItem(nonShippingCouponTotal);\r\n\r\n const shippingCoupon = this.coupons.find(coupon => coupon.getCategory() === CouponCategory.SHIPPING);\r\n if(shippingCoupon) {\r\n this.applyDiscountsInShippingCharges({[shippingCoupon.getCode()] : discountBreakdown[shippingCoupon.getCode()] || zero});\r\n } else {\r\n // If no shipping coupon, ensure any previous discounts on shipping charges are cleared\r\n this.applyDiscountsInShippingCharges({});\r\n }\r\n\r\n // 3.1 Calculate net lineitemSubtotal and net shipping after discount\r\n const netLineItemSubtotal = this.lineItems.reduce((total, lineItem) => total.add(lineItem.getTotal().netSubtotal), zero);\r\n const netShippingCharges = this.charges\r\n .filter(charge => charge.getType() === ChargeType.SHIPPING)\r\n .reduce((total, charge) => total.add(charge.getTotal().grandTotal), zero);\r\n\r\n // 3.2 Assign net lineitemSubtotal and net shipping to total\r\n this.total.netLineItemSubtotal = netLineItemSubtotal;\r\n this.total.netShippingCharges = netShippingCharges;\r\n\r\n // 4. Calculate charges and net charges after discount\r\n const additiveCharges = this.charges\r\n .filter(charge => charge.getImpact() === ChargeImpact.ADD)\r\n .reduce((total, charge) => total.add(charge.getTotal().chargeAmount), zero);\r\n const netAdditiveCharges = this.charges\r\n .filter(charge => charge.getImpact() === ChargeImpact.ADD)\r\n .reduce((total, charge) => total.add(charge.getTotal().grandTotal), zero);\r\n const adjustmentCharges = this.charges\r\n .filter(charge => charge.getImpact() === ChargeImpact.SUBTRACT)\r\n .reduce((total, charge) => total.add(charge.getTotal().grandTotal), zero);\r\n\r\n // 5. Aggregate Taxes & Grand Total from all items and charges\r\n let taxTotal = zero;\r\n let lineItemTaxTotal = zero;\r\n let additiveChargesTaxTotal = zero;\r\n\r\n const taxBreakdown: ShoppingContainerTaxBreakdownModel = {};\r\n const lineItemTaxBreakdown: ShoppingContainerTaxBreakdownModel = {};\r\n const additiveChargesTaxBreakdown: ShoppingContainerTaxBreakdownModel = {};\r\n\r\n // Helper to merge tax breakdowns into hierarchical structure\r\n const mergeTax = (\r\n sourceBreakdown: Record<string, LineItemTaxBreakdownModel | ChargeTaxBreakdownModel>,\r\n targetBreakdown: ShoppingContainerTaxBreakdownModel\r\n ) => {\r\n Object.entries(sourceBreakdown).forEach(([ruleId, breakdown]) => {\r\n const system = breakdown.system;\r\n const subsystem = breakdown.subSystem;\r\n\r\n // Populate Target Breakdown\r\n if (!targetBreakdown[system]) {\r\n targetBreakdown[system] = { system, totalAmount: zero, subSystems: {} };\r\n }\r\n if (!targetBreakdown[system].subSystems[subsystem]) {\r\n targetBreakdown[system].subSystems[subsystem] = breakdown.taxAmount;\r\n } else {\r\n targetBreakdown[system].subSystems[subsystem] = targetBreakdown[system].subSystems[subsystem].add(breakdown.taxAmount);\r\n }\r\n targetBreakdown[system].totalAmount = targetBreakdown[system].totalAmount.add(breakdown.taxAmount);\r\n });\r\n };\r\n\r\n // 5.1 Merge line item taxes\r\n filteredLineItems.forEach(lineItem => {\r\n const lineItemTaxes = lineItem.getTotal().taxBreakdown;\r\n if (lineItemTaxes) {\r\n mergeTax(lineItemTaxes, lineItemTaxBreakdown);\r\n mergeTax(lineItemTaxes, taxBreakdown);\r\n lineItemTaxTotal = lineItemTaxTotal.add(lineItem.getTotal().taxTotal);\r\n }\r\n });\r\n\r\n // 5.2 Merge charge taxes\r\n this.charges.forEach(charge => {\r\n const chargeTaxes = charge.getTotal().taxBreakdown;\r\n if (chargeTaxes) {\r\n mergeTax(chargeTaxes, additiveChargesTaxBreakdown);\r\n mergeTax(chargeTaxes, taxBreakdown);\r\n additiveChargesTaxTotal = additiveChargesTaxTotal.add(charge.getTotal().taxTotal);\r\n }\r\n });\r\n\r\n // 5.3 Calculate total tax\r\n taxTotal = lineItemTaxTotal.add(additiveChargesTaxTotal);\r\n\r\n // 6. Final Grand Total: netLineItemSubtotal + lineItemTaxTotal + netAdditiveCharges (includes netShippingCharges) - adjustmentCharges\r\n const grandTotal = netLineItemSubtotal.add(lineItemTaxTotal).add(netAdditiveCharges).subtract(adjustmentCharges);\r\n\r\n\r\n // 7. Reconstruct total object\r\n this.total = {\r\n lineItemSubtotal: lineItemSubtotal,\r\n netLineItemSubtotal: netLineItemSubtotal,\r\n lineItemTaxTotal: lineItemTaxTotal,\r\n lineItemTaxBreakdown: lineItemTaxBreakdown,\r\n\r\n additiveCharges: additiveCharges,\r\n netAdditiveCharges: netAdditiveCharges,\r\n additiveChargesTaxTotal: additiveChargesTaxTotal,\r\n additiveChargesTaxBreakdown: additiveChargesTaxBreakdown,\r\n\r\n adjustmentCharges: adjustmentCharges,\r\n shippingCharges: shippingCharges,\r\n netShippingCharges: netShippingCharges,\r\n\r\n discountTotal: discountTotal,\r\n discountBreakdown: discountBreakdown,\r\n taxTotal: taxTotal,\r\n taxBreakdown: taxBreakdown,\r\n grandTotal: grandTotal,\r\n };\r\n }\r\n\r\n /**\r\n * Updates the shipping details and recalculates the totals.\r\n * @param shippingDetails - The new shipping details to apply.\r\n */\r\n public updateShippingDetails(shippingDetails: ShippingDetails): void {\r\n this.shippingDetails = shippingDetails;\r\n }\r\n\r\n /**\r\n * Applies a list of coupons to the shopping container.\r\n * Filters out invalid coupons, separates shipping and non-shipping coupons,\r\n * and distributes discounts to line items.\r\n * @param applicableCoupons - The list of coupons to attempt to apply.\r\n */\r\n public applyCoupons(applicableCoupons: CouponModel[]): void {\r\n //Apply coupons\r\n const shippingCoupons = applicableCoupons.filter(coupon => coupon.getCategory() === CouponCategory.SHIPPING);\r\n const otherCoupons = applicableCoupons.filter(coupon => coupon.getCategory() !== CouponCategory.SHIPPING);\r\n\r\n this.coupons = [];\r\n this.total.discountTotal = this.total.lineItemSubtotal.zero();\r\n this.total.discountBreakdown = {};\r\n // Apply non shipping coupons\r\n otherCoupons.length && this.applyNonShippingCoupons(otherCoupons);\r\n this.applyDiscountsInLineItem(this.total.discountBreakdown);\r\n\r\n // Apply shipping coupons\r\n shippingCoupons.length && this.applyShippingCoupons(shippingCoupons);\r\n\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Distributes the total discount amount among the line items.\r\n * @param couponTotal - A record of coupon codes and their calculated discount amounts.\r\n */\r\n private applyDiscountsInLineItem(couponTotal: Record<string, PriceModel>) {\r\n const couponDiscounts: [string, PriceModel][] = Array.from(Object.entries(couponTotal))\r\n .filter(couponDiscount => !couponDiscount[1].isZero());\r\n\r\n const itemDiscounts = new Map<string, { coupon: CouponModel, amount: PriceModel }[]>();\r\n this.lineItems.forEach(li => itemDiscounts.set(li.getId(), []));\r\n\r\n couponDiscounts.forEach(([code, discountTotal]) => {\r\n const coupon = this.coupons.find(c => c.getCode() === code);\r\n if (!coupon || discountTotal.isZero()) return;\r\n\r\n const validItems = this.lineItems\r\n .filter(li => li.getState() !== LineItemState.CANCELLED && !li.getTotal().subtotal.isZero())\r\n .sort((a, b) => a.getTotal().subtotal.compareTo(b.getTotal().subtotal));\r\n\r\n let distributed = new PriceModel({ amount: 0, currency: this.currency });\r\n\r\n validItems.forEach((item, index) => {\r\n let amount: PriceModel;\r\n if (index === validItems.length - 1) {\r\n amount = discountTotal.subtract(distributed);\r\n } else {\r\n amount = discountTotal.multiply(item.getTotal().subtotal).divide(this.total.lineItemSubtotal).round();\r\n }\r\n distributed = distributed.add(amount);\r\n itemDiscounts.get(item.getId())?.push({ coupon, amount });\r\n });\r\n });\r\n\r\n this.lineItems.forEach(lineItem => {\r\n if (lineItem.getState() === LineItemState.CANCELLED || this.total.lineItemSubtotal.isZero()) {\r\n lineItem.updateDiscounts([]);\r\n } else {\r\n lineItem.updateDiscounts(itemDiscounts.get(lineItem.getId()) || []);\r\n }\r\n });\r\n }\r\n\r\n private applyDiscountsInShippingCharges(couponTotal: Record<string, PriceModel>) {\r\n const couponDiscounts: [string, PriceModel][] = Array.from(Object.entries(couponTotal))\r\n .filter(couponDiscount => !couponDiscount[1].isZero());\r\n const shippingCharges = this.charges.filter(charge => charge.getType() === ChargeType.SHIPPING);\r\n\r\n const chargeDiscounts = new Map<string, { coupon: CouponModel, amount: PriceModel }[]>();\r\n shippingCharges.forEach(li => chargeDiscounts.set(li.getId(), []));\r\n\r\n couponDiscounts.forEach(([code, discountTotal]) => {\r\n const coupon = this.coupons.find(c => c.getCode() === code);\r\n if (!coupon || discountTotal.isZero()) return;\r\n\r\n const validCharges = shippingCharges\r\n .sort((a, b) => a.getTotal().grandTotal.compareTo(b.getTotal().grandTotal));\r\n\r\n let distributed = new PriceModel({ amount: 0, currency: this.currency });\r\n\r\n validCharges.forEach((charge, index) => {\r\n let amount: PriceModel;\r\n if (index === validCharges.length - 1) {\r\n amount = discountTotal.subtract(distributed);\r\n } else {\r\n amount = discountTotal.multiply(charge.getTotal().chargeAmount).divide(this.total.shippingCharges).round();\r\n }\r\n distributed = distributed.add(amount);\r\n chargeDiscounts.get(charge.getId())?.push({ coupon, amount });\r\n });\r\n });\r\n\r\n shippingCharges.forEach(charge => {\r\n charge.updateDiscounts(chargeDiscounts.get(charge.getId()) || []);\r\n });\r\n }\r\n\r\n /**\r\n * Selects and applies the best applicable non-shipping coupon.\r\n * Currently supports applying only a single coupon of type COUPON.\r\n * @param applicableCoupons - List of available non-shipping coupons.\r\n */\r\n private applyNonShippingCoupons(applicableCoupons: CouponModel[]) {\r\n const coupons = applicableCoupons.filter(coupon => coupon.getType() === CouponType.COUPON);\r\n if (coupons.length === 1) {\r\n const couponValue = coupons[0].calculateApplicableCouponDiscount(this.total.lineItemSubtotal, this.total.shippingCharges, this.country, this.currency, this.#metaData.checkCouponExpiry);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(coupons[0]);\r\n this.total.discountTotal = couponValue;\r\n this.total.discountBreakdown[coupons[0].getCode()] = couponValue;\r\n }\r\n }\r\n // Todo: Add support to other type in future like promotion\r\n }\r\n\r\n /**\r\n * Selects and applies the best applicable shipping coupon.\r\n * @param applicableCoupons - List of available shipping coupons.\r\n */\r\n private applyShippingCoupons(applicableCoupons: CouponModel[]) {\r\n if (this.total.shippingCharges.getAmount() > 0 && applicableCoupons.length > 0) {\r\n const netLineItemSubtotal = this.total.lineItemSubtotal.subtract(this.total.discountTotal);\r\n\r\n const maxValuedCoupon = applicableCoupons.reduce((maxCoupon, currentCoupon) => {\r\n if (!maxCoupon) return currentCoupon;\r\n\r\n const currentCouponValue = currentCoupon.calculateApplicableCouponDiscount(netLineItemSubtotal, this.total.shippingCharges, this.country, this.currency, this.#metaData.checkCouponExpiry).min(this.total.shippingCharges);\r\n const maxCouponValue = maxCoupon.calculateApplicableCouponDiscount(netLineItemSubtotal, this.total.shippingCharges, this.country, this.currency, this.#metaData.checkCouponExpiry).min(this.total.shippingCharges);\r\n\r\n if (currentCouponValue.compareTo(maxCouponValue) === 0) {\r\n return currentCoupon.getType() === CouponType.COUPON ? currentCoupon : maxCoupon;\r\n }\r\n return currentCouponValue.compareTo(maxCouponValue) > 0 ? currentCoupon : maxCoupon;\r\n });\r\n\r\n const couponValue = maxValuedCoupon.calculateApplicableCouponDiscount(netLineItemSubtotal, this.total.shippingCharges, this.country, this.currency, this.#metaData.checkCouponExpiry).min(this.total.shippingCharges);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(maxValuedCoupon);\r\n this.total.discountTotal = this.total.discountTotal.add(couponValue);\r\n this.total.discountBreakdown[maxValuedCoupon.getCode()] = couponValue;\r\n }\r\n }\r\n }\r\n}\r\n\r\n\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/Classes/ShoppingContainer.ts"],"names":["BaseShoppingContainerModel","BaseModel","#metaData","data","date","metaData","item","LineItemModel","charge","ChargeModel","AddressModel","coupon","CouponModel","Utils_default","PriceModel","key","value","breakdown","systemKey","systemValue","subKey","subValue","totals","zero","filteredLineItems","lineitem","lineItemSubtotal","total","lineItem","shippingCharges","discountTotal","discountBreakdown","nonShippingCouponTotal","couponValue","shippingCoupon","netLineItemSubtotal","netShippingCharges","additiveCharges","netAdditiveCharges","adjustmentCharges","taxTotal","lineItemTaxTotal","additiveChargesTaxTotal","taxBreakdown","lineItemTaxBreakdown","additiveChargesTaxBreakdown","mergeTax","sourceBreakdown","targetBreakdown","ruleId","system","subsystem","lineItemTaxes","chargeTaxes","grandTotal","shippingDetails","applicableCoupons","shippingCoupons","otherCoupons","couponTotal","couponDiscounts","couponDiscount","itemDiscounts","li","code","c","validItems","a","b","distributed","index","amount","chargeDiscounts","validCharges","coupons","maxValuedCoupon","maxCoupon","currentCoupon","currentCouponValue","maxCouponValue"],"mappings":"+RAsIA,IAA8BA,CAA9B,CAAA,cAAiEC,CAAU,CAC/D,EACA,CAAA,UAAA,CACA,aACA,CAAA,WAAA,CACA,SACA,CAAA,OAAA,CACA,eACA,CAAA,eAAA,CACA,cAGA,CAAA,OAAA,CAGA,KAEA,CAAA,OAAA,CACA,QACA,CAAA,MAAA,CACVC,EAQA,CAAA,WAAA,CAAYC,CAAuCC,CAAAA,GAAAA,CAAa,IAAI,IAAA,CAAQC,GAAsC,CAAA,CAAE,iBAAmB,CAAA,CAAA,CAAK,CAAG,CAAA,CAC7I,KAAMF,CAAAA,CAAAA,CAAMC,GAAI,CAAA,CAChB,IAAK,CAAA,EAAA,CAAKD,CAAK,CAAA,EAAA,CACf,IAAK,CAAA,UAAA,CAAaA,CAAK,CAAA,UAAA,CACvB,IAAK,CAAA,aAAA,CAAgBA,CAAK,CAAA,aAAA,CAC1B,IAAK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AAA,CAAK,KAAM,CAAA,eAAA,CAAiB,IAAK,CAAA,OAAA,CAAS,IAAK,CAAA,QAAA,CAAU,IAAKjC,CAAAA,EAAAA,CAAU,iBAAiB,CAAA,CAAE,GAAI,CAAA,IAAA,CAAK,KAAM,CAAA,eAAe,CAEjN,CAAA,OAAI4E,CAAmB,CAAA,SAAA,CAAUC,CAAc,CAAA,GAAM,CAC5CF,CAAAA,CAAAA,CAAc,OAAQ,EAAA,GAAM,QAAoBA,CAAAA,CAAAA,CAAgBD,CAElEE,CAAAA,CAAAA,CAAmB,SAAUC,CAAAA,CAAc,CAAI,CAAA,CAAA,CAAIF,CAAgBD,CAAAA,CAC5E,CAAC,CAAA,CAEK3C,CAAc0C,CAAAA,CAAAA,CAAgB,iCAAkCxC,CAAAA,CAAAA,CAAqB,IAAK,CAAA,KAAA,CAAM,eAAiB,CAAA,IAAA,CAAK,OAAS,CAAA,IAAA,CAAK,QAAU,CAAA,IAAA,CAAKjC,EAAU,CAAA,iBAAiB,CAAE,CAAA,GAAA,CAAI,IAAK,CAAA,KAAA,CAAM,eAAe,CAAA,CAChN+B,CAAY,CAAA,SAAA,EAAc,CAAA,CAAA,GAC5B,IAAK,CAAA,OAAA,CAAQ,IAAK0C,CAAAA,CAAe,CACjC,CAAA,IAAA,CAAK,KAAM,CAAA,aAAA,CAAgB,IAAK,CAAA,KAAA,CAAM,aAAc,CAAA,GAAA,CAAI1C,CAAW,CAAA,CACnE,IAAK,CAAA,KAAA,CAAM,iBAAkB0C,CAAAA,CAAAA,CAAgB,OAAQ,EAAC,CAAI1C,CAAAA,CAAAA,EAE9D,CACF,CACF","file":"chunk-6QSZECNF.mjs","sourcesContent":["import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport AddressModel, { AddressData } from \"./Address\";\r\nimport LineItemModel, { LineItemData, LineItemTaxBreakdown, LineItemTaxBreakdownModel } from \"./LineItem\";\r\nimport { CountryCode, CurrencyCode, LocaleCode, ShippingDetails } from \"./Common\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\nimport CouponModel, { CouponCategory, CouponData, CouponType } from \"./Coupon\";\r\nimport Utils from \"../Utils\";\r\nimport { ChargeImpact, ChargeType, LineItemState, TaxSystem } from \"./Enum\";\r\nimport ChargeModel, { ChargeData, ChargeTaxBreakdownModel } from \"./Charge\";\r\n\r\n/**\r\n * Breakdown of a specific tax system (e.g., GST, VAT) for the entire container.\r\n * Groups taxes by system and then by specific rule/subsystem.\r\n */\r\nexport type TaxSystemBreakdown = {\r\n /** Name of the tax system (e.g., GST) */\r\n system: TaxSystem;\r\n /** Total tax amount collected for this system across all line items and charges */\r\n totalAmount: PriceData;\r\n /** Detailed breakdown by rule/subsystem to total tax amount (e.g., CGST, SGST) */\r\n subSystems: Record<string, PriceData>;\r\n};\r\n\r\n/**\r\n * Internal model for tax system breakdown using PriceModel instances.\r\n */\r\nexport type TaxSystemBreakdownModel = {\r\n system: TaxSystem;\r\n totalAmount: PriceModel;\r\n subSystems: Record<string, PriceModel>;\r\n};\r\n\r\nexport type ShoppingContainerTaxBreakdownModel = Record<string, TaxSystemBreakdownModel>;\r\n\r\n/**\r\n * Comprehensive totals for a shopping container, logically grouped by source.\r\n */\r\nexport type ShoppingContainerTotal = {\r\n // --- Item Totals ---\r\n /** Sum of all line item prices before any discounts or taxes */\r\n lineItemSubtotal: PriceData;\r\n /** Total item subtotal after item-level discounts have been applied (taxable base for items) */\r\n netLineItemSubtotal: PriceData;\r\n /** Total tax collected specifically from line items */\r\n lineItemTaxTotal: PriceData;\r\n /** Granular tax breakdown for all line items */\r\n lineItemTaxBreakdown: Record<string, TaxSystemBreakdown>;\r\n\r\n // --- Charge Totals ---\r\n /** Sum of pre-discount chargeAmount for additive charges (tax-inclusive) */\r\n additiveCharges: PriceData;\r\n /** Sum of post-discount netChargeAmount for additive charges – final payable (tax-inclusive) */\r\n netAdditiveCharges: PriceData;\r\n /** Tax reverse-calculated from additive charges only */\r\n additiveChargesTaxTotal: PriceData;\r\n /** Granular tax breakdown from additive charges */\r\n additiveChargesTaxBreakdown: Record<string, TaxSystemBreakdown>;\r\n\r\n /** Sum of post-discount netChargeAmount for subtractive charges – absolute amount to subtract */\r\n adjustmentCharges: PriceData;\r\n\r\n /** Pre-discount shipping gross (tax-inclusive, part of additive charges) */\r\n shippingCharges: PriceData;\r\n /** Shipping cost after any shipping-specific discounts */\r\n netShippingCharges: PriceData;\r\n\r\n // --- Aggregate Totals ---\r\n /** Combined total tax (lineItemTaxTotal + chargeTaxTotal) */\r\n taxTotal: PriceData;\r\n /** Combined granular tax breakdown for the entire container */\r\n taxBreakdown: Record<string, TaxSystemBreakdown>;\r\n /** Sum of all coupon discounts applied to the container */\r\n discountTotal: PriceData;\r\n /** Map of applied coupon codes to their calculated discount amounts */\r\n discountBreakdown: Record<string, PriceData>;\r\n /** Final total amount to be paid (NetSubtotal + ChargesTotal + TaxTotal - (any remaining discounts)) */\r\n grandTotal: PriceData;\r\n};\r\n\r\n\r\n/**\r\n * Internal model version of ShoppingContainerTotal using PriceModel instances.\r\n */\r\nexport type ShoppingContainerTotalModel = {\r\n lineItemSubtotal: PriceModel;\r\n netLineItemSubtotal: PriceModel;\r\n lineItemTaxTotal: PriceModel;\r\n lineItemTaxBreakdown: Record<string, TaxSystemBreakdownModel>;\r\n\r\n additiveCharges: PriceModel;\r\n netAdditiveCharges: PriceModel;\r\n additiveChargesTaxTotal: PriceModel;\r\n additiveChargesTaxBreakdown: Record<string, TaxSystemBreakdownModel>;\r\n\r\n adjustmentCharges: PriceModel;\r\n\r\n shippingCharges: PriceModel;\r\n netShippingCharges: PriceModel;\r\n\r\n taxTotal: PriceModel;\r\n taxBreakdown: Record<string, TaxSystemBreakdownModel>;\r\n discountTotal: PriceModel;\r\n discountBreakdown: Record<string, PriceModel>;\r\n grandTotal: PriceModel;\r\n};\r\n\r\nexport type ShoppingContainerMetaData = {\r\n checkCouponExpiry: boolean\r\n}\r\n\r\nexport type BaseShoppingContainerAttributes = BaseAttributes & {\r\n id: string;\r\n customerId?: string;\r\n customerEmail?: string;\r\n anonymousId?: string;\r\n lineItems: LineItemData[];\r\n charges: ChargeData[];\r\n shippingDetails: ShippingDetails | null;\r\n shippingAddress?: AddressData | null;\r\n billingAddress?: AddressData | null;\r\n coupons: CouponData[];\r\n total: ShoppingContainerTotal;\r\n country: CountryCode;\r\n currency: CurrencyCode;\r\n locale: LocaleCode;\r\n};\r\n\r\nexport type BaseShoppingContainerData = BaseShoppingContainerAttributes & BaseData\r\n\r\n\r\n/**\r\n * Abstract base class for shopping-related containers like carts and orders.\r\n * Manages common elements such as line items, addresses, coupons, and totals.\r\n */\r\nexport default abstract class BaseShoppingContainerModel extends BaseModel {\r\n protected id: string;\r\n protected customerId?: string;\r\n protected customerEmail?: string;\r\n protected anonymousId?: string;\r\n protected lineItems: LineItemModel[];\r\n protected charges: ChargeModel[];\r\n protected shippingDetails: ShippingDetails | null;\r\n protected shippingAddress: AddressModel | null;\r\n protected billingAddress: AddressModel | null;\r\n\r\n // CouponsCodes\r\n protected coupons: CouponModel[];\r\n\r\n // Cart Totals\r\n protected total: ShoppingContainerTotalModel;\r\n\r\n protected country: CountryCode;\r\n protected currency: CurrencyCode;\r\n protected locale: LocaleCode;\r\n #metaData: ShoppingContainerMetaData;\r\n\r\n /**\r\n * Creates an instance of BaseShoppingContainerModel.\r\n * Initializes common properties and calculates initial base totals.\r\n * @param data - The initial attributes for the shopping container.\r\n * @param date - Optional date object for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: BaseShoppingContainerAttributes, date: Date = new Date(), metaData: ShoppingContainerMetaData = { checkCouponExpiry: true }) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.customerId = data.customerId;\r\n this.customerEmail = data.customerEmail;\r\n this.anonymousId = data.anonymousId;\r\n this.country = data.country;\r\n this.currency = data.currency;\r\n this.locale = data.locale;\r\n this.lineItems = (data.lineItems ?? []).map(item => new LineItemModel(item));\r\n this.charges = (data.charges ?? []).map(charge => new ChargeModel(charge));\r\n this.billingAddress = data.billingAddress ? new AddressModel(data.billingAddress, date) : null;\r\n this.shippingAddress = data.shippingAddress ? new AddressModel(data.shippingAddress, date) : null;\r\n this.coupons = (data.coupons ?? []).map(coupon => new CouponModel(coupon));\r\n\r\n this.shippingDetails = data.shippingDetails ? Utils.deepClone(data.shippingDetails) : null;\r\n\r\n this.total = {\r\n lineItemSubtotal: new PriceModel(data.total.lineItemSubtotal),\r\n netLineItemSubtotal: new PriceModel(data.total.netLineItemSubtotal),\r\n lineItemTaxTotal: new PriceModel(data.total.lineItemTaxTotal),\r\n lineItemTaxBreakdown: this.mapTaxBreakdown(data.total.lineItemTaxBreakdown),\r\n\r\n additiveCharges: new PriceModel(data.total.additiveCharges),\r\n netAdditiveCharges: new PriceModel(data.total.netAdditiveCharges),\r\n additiveChargesTaxTotal: new PriceModel(data.total.additiveChargesTaxTotal),\r\n\r\n additiveChargesTaxBreakdown: this.mapTaxBreakdown(data.total.additiveChargesTaxBreakdown),\r\n adjustmentCharges: new PriceModel(data.total.adjustmentCharges),\r\n shippingCharges: new PriceModel(data.total.shippingCharges),\r\n netShippingCharges: new PriceModel(data.total.netShippingCharges),\r\n\r\n discountTotal: new PriceModel(data.total.discountTotal),\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(data.total.discountBreakdown).map(([key, value]) => [key, new PriceModel(value)])\r\n ),\r\n\r\n taxTotal: new PriceModel(data.total.taxTotal),\r\n taxBreakdown: this.mapTaxBreakdown(data.total.taxBreakdown),\r\n grandTotal: new PriceModel(data.total.grandTotal),\r\n };\r\n\r\n this.#metaData = {\r\n checkCouponExpiry: metaData.checkCouponExpiry\r\n }\r\n }\r\n\r\n private mapTaxBreakdown(breakdown: Record<string, TaxSystemBreakdown>): Record<string, TaxSystemBreakdownModel> {\r\n return Object.fromEntries(\r\n Object.entries(breakdown || {}).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: new PriceModel(systemValue.totalAmount),\r\n subSystems: Object.fromEntries(\r\n Object.entries(systemValue.subSystems).map(([subKey, subValue]) => [\r\n subKey,\r\n new PriceModel(subValue)\r\n ])\r\n )\r\n }\r\n ])\r\n );\r\n }\r\n\r\n private serializeTaxBreakdown(breakdown: Record<string, TaxSystemBreakdownModel>): Record<string, TaxSystemBreakdown> {\r\n return Object.fromEntries(\r\n Object.entries(breakdown || {}).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount.getDetails(),\r\n subSystems: Object.fromEntries(\r\n Object.entries(systemValue.subSystems).map(([subKey, subValue]) => [\r\n subKey,\r\n subValue.getDetails()\r\n ])\r\n )\r\n }\r\n ])\r\n );\r\n }\r\n\r\n /**\r\n * Gets the unique identifier for this shopping container (cart ID or order ID).\r\n * @returns The ID string.\r\n */\r\n public getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the customer ID associated with this container, if available.\r\n * @returns The customer ID string, or undefined.\r\n */\r\n public getCustomerId(): string | undefined {\r\n return this.customerId;\r\n }\r\n\r\n /**\r\n * Gets the customer email associated with this container, if available.\r\n * @returns The customer email string, or undefined.\r\n */\r\n public getCustomerEmail(): string | undefined {\r\n return this.customerEmail;\r\n }\r\n\r\n /**\r\n * Gets the anonymous user ID associated with this container, if available.\r\n * @returns The anonymous ID string, or undefined.\r\n */\r\n public getAnonymousId(): string | undefined {\r\n return this.anonymousId;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the line items in the container.\r\n * Each item is a new LineItemModel instance created from the original's details.\r\n * @returns An array of LineItemModel instances.\r\n */\r\n public getLineItems(): LineItemModel[] {\r\n // Return new instances to prevent modification of internal state\r\n return this.lineItems.map(item => new LineItemModel(item.getDetails()));\r\n }\r\n\r\n /**\r\n * Gets current number of line items in the container.\r\n * @returns The count of line items.\r\n */\r\n public getLineItemsCount(): number {\r\n return this.lineItems.length;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the charges in the container.\r\n * @returns An array of ChargeModel instances.\r\n */\r\n public getCharges(): ChargeModel[] {\r\n return this.charges.map(charge => new ChargeModel(charge.getDetails()));\r\n }\r\n\r\n /**\r\n * Adds a new charge to the container and recalculates totals.\r\n * @param charge - The charge to add.\r\n */\r\n public addCharge(charge: ChargeModel): void {\r\n this.charges.push(charge);\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Clears all charges from the container and recalculates totals.\r\n */\r\n public clearCharges(): void {\r\n this.charges = [];\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Gets a copy of the shipping details associated with the container.\r\n * @returns A ShippingDetails object, or null if none are set.\r\n */\r\n public getShippingDetails(): ShippingDetails | null {\r\n return this.shippingDetails ? Utils.deepClone(this.shippingDetails) : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the shipping address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no shipping address is set.\r\n */\r\n public getShippingAddress(): AddressModel | null {\r\n return this.shippingAddress ? new AddressModel(this.shippingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Checks if a shipping address is associated with this container.\r\n * @returns True if a shipping address is set, false otherwise.\r\n */\r\n public hasShippingAddress(): boolean {\r\n return !!this.shippingAddress;\r\n }\r\n\r\n /**\r\n * Checks if a billing address is associated with this container.\r\n * @returns True if a billing address is set, false otherwise.\r\n */\r\n public hasBillingAddress(): boolean {\r\n return !!this.billingAddress;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the billing address associated with the container.\r\n * Returns a new AddressModel instance created from the original's details.\r\n * @returns An AddressModel instance, or null if no billing address is set.\r\n */\r\n public getBillingAddress(): AddressModel | null {\r\n return this.billingAddress ? new AddressModel(this.billingAddress.getDetails()) : null;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the coupons applied to the container.\r\n * Each item is a new CouponModel instance created from the original's details.\r\n * @returns An array of CouponModel instances.\r\n */\r\n public getCoupons(): CouponModel[] {\r\n return [...this.coupons];\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this container.\r\n * @returns The CountryCode enum value.\r\n */\r\n public getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Gets the currency code associated with this container.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode {\r\n return this.currency;\r\n }\r\n\r\n /**\r\n * Gets the locale code associated with this container.\r\n * @returns The LocaleCode enum value.\r\n */\r\n public getLocale(): LocaleCode {\r\n return this.locale;\r\n }\r\n\r\n /**\r\n * Gets a defensive copy of the calculated totals for the container.\r\n * @returns An object containing shipping, subtotal, coupon, and grand totals.\r\n */\r\n public getTotal() {\r\n return {\r\n lineItemSubtotal: this.total.lineItemSubtotal,\r\n netLineItemSubtotal: this.total.netLineItemSubtotal,\r\n lineItemTaxTotal: this.total.lineItemTaxTotal,\r\n lineItemTaxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.lineItemTaxBreakdown).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount,\r\n subSystems: { ...systemValue.subSystems }\r\n }\r\n ])\r\n ),\r\n additiveCharges: this.total.additiveCharges,\r\n netAdditiveCharges : this.total.netAdditiveCharges,\r\n additiveChargesTaxTotal: this.total.additiveChargesTaxTotal,\r\n additiveChargesTaxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.additiveChargesTaxBreakdown).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount,\r\n subSystems: { ...systemValue.subSystems }\r\n }\r\n ])\r\n ),\r\n adjustmentCharges: this.total.adjustmentCharges,\r\n shippingCharges: this.total.shippingCharges,\r\n netShippingCharges: this.total.netShippingCharges,\r\n discountBreakdown: { ...this.total.discountBreakdown },\r\n discountTotal: this.total.discountTotal,\r\n taxTotal: this.total.taxTotal,\r\n taxBreakdown: Object.fromEntries(\r\n Object.entries(this.total.taxBreakdown).map(([systemKey, systemValue]) => [\r\n systemKey,\r\n {\r\n system: systemValue.system,\r\n totalAmount: systemValue.totalAmount,\r\n subSystems: { ...systemValue.subSystems }\r\n }\r\n ])\r\n ),\r\n grandTotal: this.total.grandTotal,\r\n };\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the shopping container's current state.\r\n * Includes details from the base model and specific container properties.\r\n * @returns BaseShoppingContainerData object suitable for serialization or API responses.\r\n */\r\n getDetails(): BaseShoppingContainerData {\r\n const totals = this.getTotal();\r\n return {\r\n ...super.getDetails(),\r\n id: this.getId(),\r\n customerId: this.getCustomerId(),\r\n customerEmail: this.getCustomerEmail(),\r\n anonymousId: this.getAnonymousId(),\r\n lineItems: this.getLineItems().map(item => item.getDetails()),\r\n charges: this.getCharges().map(charge => charge.getDetails()),\r\n shippingDetails: this.getShippingDetails(),\r\n shippingAddress: this.getShippingAddress()?.getDetails() || null,\r\n billingAddress: this.getBillingAddress()?.getDetails() || null,\r\n coupons: this.getCoupons().map(coupon => coupon.getDetails()),\r\n total: {\r\n // Item Totals\r\n lineItemSubtotal: totals.lineItemSubtotal.getDetails(),\r\n netLineItemSubtotal: totals.netLineItemSubtotal.getDetails(),\r\n lineItemTaxTotal: totals.lineItemTaxTotal.getDetails(),\r\n lineItemTaxBreakdown: this.serializeTaxBreakdown(totals.lineItemTaxBreakdown),\r\n\r\n // Charge Totals\r\n additiveCharges: totals.additiveCharges.getDetails(),\r\n netAdditiveCharges: totals.netAdditiveCharges.getDetails(),\r\n additiveChargesTaxTotal: totals.additiveChargesTaxTotal.getDetails(),\r\n additiveChargesTaxBreakdown: this.serializeTaxBreakdown(totals.additiveChargesTaxBreakdown),\r\n\r\n adjustmentCharges: totals.adjustmentCharges.getDetails(),\r\n\r\n shippingCharges: totals.shippingCharges.getDetails(),\r\n netShippingCharges: totals.netShippingCharges.getDetails(),\r\n\r\n // Aggregate Totals\r\n discountTotal: totals.discountTotal.getDetails(),\r\n discountBreakdown: Object.fromEntries(\r\n Object.entries(totals.discountBreakdown).map(([key, value]) => [key, value.getDetails()])\r\n ),\r\n taxTotal: totals.taxTotal.getDetails(),\r\n taxBreakdown: this.serializeTaxBreakdown(totals.taxBreakdown),\r\n grandTotal: totals.grandTotal.getDetails(),\r\n },\r\n country: this.getCountry(),\r\n currency: this.getCurrency(),\r\n locale: this.getLocale(),\r\n };\r\n }\r\n\r\n /**\r\n * Recalculates the total costs for the shopping container.\r\n * This includes summing line items, calculating shipping, applying coupons, and computing taxes.\r\n */\r\n public calculateTotals(): void {\r\n const zero = new PriceModel({ amount: 0, currency: this.currency });\r\n \r\n // 1. Calculate LineItem subtotals and Shipping Cost\r\n const filteredLineItems = this.lineItems.filter(lineitem => lineitem.getState() !== LineItemState.CANCELLED);\r\n const lineItemSubtotal = filteredLineItems.reduce((total, lineItem) => total.add(lineItem.getTotal().subtotal), zero);\r\n const shippingCharges = this.charges\r\n .filter(charge => charge.getType() === ChargeType.SHIPPING)\r\n .reduce((total, charge) => total.add(charge.getTotal().chargeAmount), zero);\r\n\r\n // 1.1 Assign lineitemSubTotal and shipping charges to total, which will be used for coupon calculations\r\n this.total.lineItemSubtotal = lineItemSubtotal;\r\n this.total.shippingCharges = shippingCharges;\r\n\r\n // 2. Calculate coupon values based on gross subtotal & shipping\r\n let discountTotal = zero;\r\n let discountBreakdown: Record<string, PriceModel> = {};\r\n let nonShippingCouponTotal: Record<string, PriceModel> = {};\r\n this.coupons.forEach(coupon => {\r\n const couponValue = coupon.calculateApplicableCouponDiscount(lineItemSubtotal, shippingCharges, this.country, this.currency, this.#metaData.checkCouponExpiry);\r\n discountTotal = discountTotal.add(couponValue);\r\n discountBreakdown[coupon.getCode()] = couponValue;\r\n if (coupon.getCategory() !== CouponCategory.SHIPPING) {\r\n nonShippingCouponTotal[coupon.getCode()] = couponValue;\r\n }\r\n })\r\n\r\n // 2.1. Assign discount total and breakdown to total\r\n this.total.discountTotal = discountTotal;\r\n this.total.discountBreakdown = discountBreakdown;\r\n\r\n // 3. Apply discounts at lineitem and shipping charges\r\n this.applyDiscountsInLineItem(nonShippingCouponTotal);\r\n\r\n const shippingCoupon = this.coupons.find(coupon => coupon.getCategory() === CouponCategory.SHIPPING);\r\n if(shippingCoupon) {\r\n this.applyDiscountsInShippingCharges({[shippingCoupon.getCode()] : discountBreakdown[shippingCoupon.getCode()] || zero});\r\n } else {\r\n // If no shipping coupon, ensure any previous discounts on shipping charges are cleared\r\n this.applyDiscountsInShippingCharges({});\r\n }\r\n\r\n // 3.1 Calculate net lineitemSubtotal and net shipping after discount\r\n const netLineItemSubtotal = this.lineItems.reduce((total, lineItem) => total.add(lineItem.getTotal().netSubtotal), zero);\r\n const netShippingCharges = this.charges\r\n .filter(charge => charge.getType() === ChargeType.SHIPPING)\r\n .reduce((total, charge) => total.add(charge.getTotal().grandTotal), zero);\r\n\r\n // 3.2 Assign net lineitemSubtotal and net shipping to total\r\n this.total.netLineItemSubtotal = netLineItemSubtotal;\r\n this.total.netShippingCharges = netShippingCharges;\r\n\r\n // 4. Calculate charges and net charges after discount\r\n const additiveCharges = this.charges\r\n .filter(charge => charge.getImpact() === ChargeImpact.ADD)\r\n .reduce((total, charge) => total.add(charge.getTotal().chargeAmount), zero);\r\n const netAdditiveCharges = this.charges\r\n .filter(charge => charge.getImpact() === ChargeImpact.ADD)\r\n .reduce((total, charge) => total.add(charge.getTotal().grandTotal), zero);\r\n const adjustmentCharges = this.charges\r\n .filter(charge => charge.getImpact() === ChargeImpact.SUBTRACT)\r\n .reduce((total, charge) => total.add(charge.getTotal().grandTotal), zero);\r\n\r\n // 5. Aggregate Taxes & Grand Total from all items and charges\r\n let taxTotal = zero;\r\n let lineItemTaxTotal = zero;\r\n let additiveChargesTaxTotal = zero;\r\n\r\n const taxBreakdown: ShoppingContainerTaxBreakdownModel = {};\r\n const lineItemTaxBreakdown: ShoppingContainerTaxBreakdownModel = {};\r\n const additiveChargesTaxBreakdown: ShoppingContainerTaxBreakdownModel = {};\r\n\r\n // Helper to merge tax breakdowns into hierarchical structure\r\n const mergeTax = (\r\n sourceBreakdown: Record<string, LineItemTaxBreakdownModel | ChargeTaxBreakdownModel>,\r\n targetBreakdown: ShoppingContainerTaxBreakdownModel\r\n ) => {\r\n Object.entries(sourceBreakdown).forEach(([ruleId, breakdown]) => {\r\n const system = breakdown.system;\r\n const subsystem = breakdown.subSystem;\r\n\r\n // Populate Target Breakdown\r\n if (!targetBreakdown[system]) {\r\n targetBreakdown[system] = { system, totalAmount: zero, subSystems: {} };\r\n }\r\n if (!targetBreakdown[system].subSystems[subsystem]) {\r\n targetBreakdown[system].subSystems[subsystem] = breakdown.taxAmount;\r\n } else {\r\n targetBreakdown[system].subSystems[subsystem] = targetBreakdown[system].subSystems[subsystem].add(breakdown.taxAmount);\r\n }\r\n targetBreakdown[system].totalAmount = targetBreakdown[system].totalAmount.add(breakdown.taxAmount);\r\n });\r\n };\r\n\r\n // 5.1 Merge line item taxes\r\n filteredLineItems.forEach(lineItem => {\r\n const lineItemTaxes = lineItem.getTotal().taxBreakdown;\r\n if (lineItemTaxes) {\r\n mergeTax(lineItemTaxes, lineItemTaxBreakdown);\r\n mergeTax(lineItemTaxes, taxBreakdown);\r\n lineItemTaxTotal = lineItemTaxTotal.add(lineItem.getTotal().taxTotal);\r\n }\r\n });\r\n\r\n // 5.2 Merge charge taxes\r\n this.charges.forEach(charge => {\r\n const chargeTaxes = charge.getTotal().taxBreakdown;\r\n if (chargeTaxes) {\r\n mergeTax(chargeTaxes, additiveChargesTaxBreakdown);\r\n mergeTax(chargeTaxes, taxBreakdown);\r\n additiveChargesTaxTotal = additiveChargesTaxTotal.add(charge.getTotal().taxTotal);\r\n }\r\n });\r\n\r\n // 5.3 Calculate total tax\r\n taxTotal = lineItemTaxTotal.add(additiveChargesTaxTotal);\r\n\r\n // 6. Final Grand Total: netLineItemSubtotal + lineItemTaxTotal + netAdditiveCharges (includes netShippingCharges) - adjustmentCharges\r\n const grandTotal = netLineItemSubtotal.add(lineItemTaxTotal).add(netAdditiveCharges).subtract(adjustmentCharges);\r\n\r\n\r\n // 7. Reconstruct total object\r\n this.total = {\r\n lineItemSubtotal: lineItemSubtotal,\r\n netLineItemSubtotal: netLineItemSubtotal,\r\n lineItemTaxTotal: lineItemTaxTotal,\r\n lineItemTaxBreakdown: lineItemTaxBreakdown,\r\n\r\n additiveCharges: additiveCharges,\r\n netAdditiveCharges: netAdditiveCharges,\r\n additiveChargesTaxTotal: additiveChargesTaxTotal,\r\n additiveChargesTaxBreakdown: additiveChargesTaxBreakdown,\r\n\r\n adjustmentCharges: adjustmentCharges,\r\n shippingCharges: shippingCharges,\r\n netShippingCharges: netShippingCharges,\r\n\r\n discountTotal: discountTotal,\r\n discountBreakdown: discountBreakdown,\r\n taxTotal: taxTotal,\r\n taxBreakdown: taxBreakdown,\r\n grandTotal: grandTotal,\r\n };\r\n }\r\n\r\n /**\r\n * Updates the shipping details and recalculates the totals.\r\n * @param shippingDetails - The new shipping details to apply.\r\n */\r\n public updateShippingDetails(shippingDetails: ShippingDetails): void {\r\n this.shippingDetails = shippingDetails;\r\n }\r\n\r\n /**\r\n * Applies a list of coupons to the shopping container.\r\n * Filters out invalid coupons, separates shipping and non-shipping coupons,\r\n * and distributes discounts to line items.\r\n * @param applicableCoupons - The list of coupons to attempt to apply.\r\n */\r\n public applyCoupons(applicableCoupons: CouponModel[]): void {\r\n //Apply coupons\r\n const shippingCoupons = applicableCoupons.filter(coupon => coupon.getCategory() === CouponCategory.SHIPPING);\r\n const otherCoupons = applicableCoupons.filter(coupon => coupon.getCategory() !== CouponCategory.SHIPPING);\r\n\r\n this.coupons = [];\r\n this.total.discountTotal = this.total.lineItemSubtotal.zero();\r\n this.total.discountBreakdown = {};\r\n // Apply non shipping coupons\r\n otherCoupons.length && this.applyNonShippingCoupons(otherCoupons);\r\n this.applyDiscountsInLineItem(this.total.discountBreakdown);\r\n\r\n // Apply shipping coupons\r\n shippingCoupons.length && this.applyShippingCoupons(shippingCoupons);\r\n\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Distributes the total discount amount among the line items.\r\n * @param couponTotal - A record of coupon codes and their calculated discount amounts.\r\n */\r\n private applyDiscountsInLineItem(couponTotal: Record<string, PriceModel>) {\r\n const couponDiscounts: [string, PriceModel][] = Array.from(Object.entries(couponTotal))\r\n .filter(couponDiscount => !couponDiscount[1].isZero());\r\n\r\n const itemDiscounts = new Map<string, { coupon: CouponModel, amount: PriceModel }[]>();\r\n this.lineItems.forEach(li => itemDiscounts.set(li.getId(), []));\r\n\r\n couponDiscounts.forEach(([code, discountTotal]) => {\r\n const coupon = this.coupons.find(c => c.getCode() === code);\r\n if (!coupon || discountTotal.isZero()) return;\r\n\r\n const validItems = this.lineItems\r\n .filter(li => li.getState() !== LineItemState.CANCELLED && !li.getTotal().subtotal.isZero())\r\n .sort((a, b) => a.getTotal().subtotal.compareTo(b.getTotal().subtotal));\r\n\r\n let distributed = new PriceModel({ amount: 0, currency: this.currency });\r\n\r\n validItems.forEach((item, index) => {\r\n let amount: PriceModel;\r\n if (index === validItems.length - 1) {\r\n amount = discountTotal.subtract(distributed);\r\n } else {\r\n amount = discountTotal.multiply(item.getTotal().subtotal).divide(this.total.lineItemSubtotal).round();\r\n }\r\n distributed = distributed.add(amount);\r\n itemDiscounts.get(item.getId())?.push({ coupon, amount });\r\n });\r\n });\r\n\r\n this.lineItems.forEach(lineItem => {\r\n if (lineItem.getState() === LineItemState.CANCELLED || this.total.lineItemSubtotal.isZero()) {\r\n lineItem.updateDiscounts([]);\r\n } else {\r\n lineItem.updateDiscounts(itemDiscounts.get(lineItem.getId()) || []);\r\n }\r\n });\r\n }\r\n\r\n private applyDiscountsInShippingCharges(couponTotal: Record<string, PriceModel>) {\r\n const couponDiscounts: [string, PriceModel][] = Array.from(Object.entries(couponTotal))\r\n .filter(couponDiscount => !couponDiscount[1].isZero());\r\n const shippingCharges = this.charges.filter(charge => charge.getType() === ChargeType.SHIPPING);\r\n\r\n const chargeDiscounts = new Map<string, { coupon: CouponModel, amount: PriceModel }[]>();\r\n shippingCharges.forEach(li => chargeDiscounts.set(li.getId(), []));\r\n\r\n couponDiscounts.forEach(([code, discountTotal]) => {\r\n const coupon = this.coupons.find(c => c.getCode() === code);\r\n if (!coupon || discountTotal.isZero()) return;\r\n\r\n const validCharges = shippingCharges\r\n .sort((a, b) => a.getTotal().grandTotal.compareTo(b.getTotal().grandTotal));\r\n\r\n let distributed = new PriceModel({ amount: 0, currency: this.currency });\r\n\r\n validCharges.forEach((charge, index) => {\r\n let amount: PriceModel;\r\n if (index === validCharges.length - 1) {\r\n amount = discountTotal.subtract(distributed);\r\n } else {\r\n amount = discountTotal.multiply(charge.getTotal().chargeAmount).divide(this.total.shippingCharges).round();\r\n }\r\n distributed = distributed.add(amount);\r\n chargeDiscounts.get(charge.getId())?.push({ coupon, amount });\r\n });\r\n });\r\n\r\n shippingCharges.forEach(charge => {\r\n charge.updateDiscounts(chargeDiscounts.get(charge.getId()) || []);\r\n });\r\n }\r\n\r\n /**\r\n * Selects and applies the best applicable non-shipping coupon.\r\n * Currently supports applying only a single coupon of type COUPON.\r\n * @param applicableCoupons - List of available non-shipping coupons.\r\n */\r\n private applyNonShippingCoupons(applicableCoupons: CouponModel[]) {\r\n const coupons = applicableCoupons.filter(coupon => coupon.getType() === CouponType.COUPON);\r\n if (coupons.length === 1) {\r\n const couponValue = coupons[0].calculateApplicableCouponDiscount(this.total.lineItemSubtotal, this.total.shippingCharges, this.country, this.currency, this.#metaData.checkCouponExpiry);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(coupons[0]);\r\n this.total.discountTotal = couponValue;\r\n this.total.discountBreakdown[coupons[0].getCode()] = couponValue;\r\n }\r\n }\r\n // Todo: Add support to other type in future like promotion\r\n }\r\n\r\n /**\r\n * Selects and applies the best applicable shipping coupon.\r\n * @param applicableCoupons - List of available shipping coupons.\r\n */\r\n private applyShippingCoupons(applicableCoupons: CouponModel[]) {\r\n if (this.total.shippingCharges.getAmount() > 0 && applicableCoupons.length > 0) {\r\n const netLineItemSubtotal = this.total.lineItemSubtotal.subtract(this.total.discountTotal);\r\n\r\n const maxValuedCoupon = applicableCoupons.reduce((maxCoupon, currentCoupon) => {\r\n if (!maxCoupon) return currentCoupon;\r\n\r\n const currentCouponValue = currentCoupon.calculateApplicableCouponDiscount(netLineItemSubtotal, this.total.shippingCharges, this.country, this.currency, this.#metaData.checkCouponExpiry).min(this.total.shippingCharges);\r\n const maxCouponValue = maxCoupon.calculateApplicableCouponDiscount(netLineItemSubtotal, this.total.shippingCharges, this.country, this.currency, this.#metaData.checkCouponExpiry).min(this.total.shippingCharges);\r\n\r\n if (currentCouponValue.compareTo(maxCouponValue) === 0) {\r\n return currentCoupon.getType() === CouponType.COUPON ? currentCoupon : maxCoupon;\r\n }\r\n return currentCouponValue.compareTo(maxCouponValue) > 0 ? currentCoupon : maxCoupon;\r\n });\r\n\r\n const couponValue = maxValuedCoupon.calculateApplicableCouponDiscount(netLineItemSubtotal, this.total.shippingCharges, this.country, this.currency, this.#metaData.checkCouponExpiry).min(this.total.shippingCharges);\r\n if (couponValue.getAmount() > 0) {\r\n this.coupons.push(maxValuedCoupon);\r\n this.total.discountTotal = this.total.discountTotal.add(couponValue);\r\n this.total.discountBreakdown[maxValuedCoupon.getCode()] = couponValue;\r\n }\r\n }\r\n }\r\n}\r\n\r\n\r\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import I from'util';var a=Object.freeze({INVALID_UUID:"Invalid UUID",INVALID_EMAIL:"Invalid Email",INVALID_TOKEN:"Invalid Token",TOKEN_EXPIRED:"Token Expired",INVALID_VERIFIER:"Invalid Verifier",INVALID_PERMISSIONS:"Invalid Permissions",INVALID_AUTH_TYPE:"Invalid Authorization Type",USER_PRIVATE_KEY_NOT_FOUND:"User Private Key Not Found",USER_PUBLIC_KEY_NOT_FOUND:"User Public Key Not Found",ANONYMOUS_PRIVATE_KEY_NOT_FOUND:"Anonymous Private Key Not Found",ANONYMOUS_PUBLIC_KEY_NOT_FOUND:"Anonymous Public Key Not Found",SYSTEM_PRIVATE_KEY_NOT_FOUND:"System Private Key Not Found",SYSTEM_PUBLIC_KEY_NOT_FOUND:"System Public Key Not Found",ADMIN_PRIVATE_KEY_NOT_FOUND:"Admin Private Key Not Found",ADMIN_PUBLIC_KEY_NOT_FOUND:"Admin Public Key Not Found",SECRET_TOKEN_NOT_FOUND:"Secret Token Not Found",ANONYMOUS_SESSION_NOT_ALLOWED:"Anonymous Session Not Allowed",USER_SESSION_NOT_ALLOWED:"User Session Not Allowed",SYSTEM_SESSION_NOT_ALLOWED:"System Session Not Allowed",CDN_SESSION_NOT_ALLOWED:"CDN Session Not Allowed",INTERNAL_SERVER_ERROR:"Internal Server Error",SOMETHING_WENT_WRONG:"Something went wrong",AUTH_CONTEXT_NOT_INITIALIZED:"Auth Context not Initialized"});var n={logException:(s,t)=>{console.error(`Exception Occurred in Function: ${s}, Error: ${n.inspect(t)}`);},logError:(s,t)=>{console.error(`Error Occurred in Function: ${s}, Error: ${n.inspect(t)}`);},logWarning:(s,t)=>{console.warn(`Warning in Function: ${s} - ${n.inspect(t)}`);},logMessage:(s,t)=>{console.log(`Message in Function: ${s} - ${n.inspect(t)}`);},logInvalidPayload:(s,t)=>{console.error(`Invalid Payload received for Function: ${s}, Error: ${n.inspect(t)}`);},inspect:s=>typeof s=="string"?s:I.inspect(s)},o=n;var S={handleException:(s,t,r)=>{t.knownError?(t.logError&&o.logError(s,t),r.status(t.status).json({status:t.status,error:t.error})):t.status&&t.error?(o.logException(s,t),r.status(t.status).json({error:t.errorMessage||JSON.stringify(t.error),status:t.status})):(o.logException(s,t),r.status(500).json({status:500,error:a.INTERNAL_SERVER_ERROR}));},generateResponse:(s,t,r)=>({status:s,data:t,error:r}),generateError:(s,t,r=!0,E=!1)=>({status:s,error:t,knownError:r,logError:E})},D=S;var y=async(s,t,r="GET",E={},l)=>{let c={method:r,headers:{"Content-Type":"application/json",...E}};r!=="GET"&&l&&(c.body=JSON.stringify(l));let i=`${s}${t?"/"+t:""}`;try{let e=await fetch(i,c);if(!e.ok){let u,N=await e.text();try{u=JSON.parse(N);}catch{u={status:e.status,error:N||e.statusText},o.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${i}. Raw text: ${N}`);}throw {status:e.status,statusText:e.statusText,error:u}}let O=await e.json();return o.logMessage("Fetch",`API call successful: URL-${i}, Status- ${e.status}`),{status:e.status,statusText:e.statusText,data:O}}catch(e){throw o.logError("Fetch",`API call failed: URL-${i}, Status- ${e.status||500}, Error- ${o.inspect(e.error||e)}`),{status:e.status||500,statusText:e.statusText||a.INTERNAL_SERVER_ERROR,error:e.error||{status:e.status||500,error:e.statusText||a.SOMETHING_WENT_WRONG}}}},K=y;export{a,o as b,D as c,K as d};//# sourceMappingURL=chunk-XZFALA7N.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-XZFALA7N.mjs.map
|