@lyxa.ai/core 1.1.96 → 1.1.98

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.
@@ -6,6 +6,7 @@ const index_1 = require("../index");
6
6
  const auth_1 = require("../../auth");
7
7
  const models_1 = require("../../mongo/models");
8
8
  const enum_1 = require("../../../utilities/enum");
9
+ const error_common_1 = require("../../../utilities/error-common");
9
10
  function createAuthenticatedProcedure(options) {
10
11
  const { entityTypes, allowRefreshToken = true, autoRefresh = true } = options;
11
12
  return index_1.publicProcedure.use(async ({ ctx, next }) => {
@@ -22,26 +23,34 @@ function createAuthenticatedProcedure(options) {
22
23
  ? refreshTokenHeader.replace(/^Bearer\s+/, '')
23
24
  : refreshTokenHeader[0].replace(/^Bearer\s+/, '');
24
25
  }
25
- if (!accessToken) {
26
- throw new server_1.TRPCError({ code: 'UNAUTHORIZED', message: 'Missing access token' });
27
- }
26
+ if (!accessToken)
27
+ (0, error_common_1.unauthorizedError)('Missing access token');
28
28
  let entity = await (0, auth_1.verifyAccessToken)(entityTypes, accessToken);
29
- if (entity?.type == 'USER') {
29
+ if (entity?.type == auth_1.AuthEntityType.USER) {
30
30
  const user = await (0, models_1.getCoreUserModel)().findOne({ _id: entity.parameters.coreUserId });
31
- if (!user) {
31
+ if (!user)
32
32
  throw new server_1.TRPCError({ code: 'UNAUTHORIZED', message: 'User not found' });
33
- }
34
- if (user.status !== enum_1.Status.ACTIVE) {
35
- throw new server_1.TRPCError({ code: 'UNAUTHORIZED', message: 'User is not active' });
36
- }
33
+ if (user.status !== enum_1.Status.ACTIVE)
34
+ (0, error_common_1.unauthorizedError)('User is not active');
37
35
  }
38
- if (entity?.type == 'CRM') {
36
+ if (entity?.type == auth_1.AuthEntityType.CRM) {
39
37
  const admin = await models_1.AdminModel.findOne({ _id: entity.parameters.adminId });
40
- if (!admin) {
38
+ if (!admin)
41
39
  throw new server_1.TRPCError({ code: 'UNAUTHORIZED', message: 'Admin not found' });
40
+ if (admin.status !== enum_1.Status.ACTIVE)
41
+ (0, error_common_1.unauthorizedError)('Admin is not active');
42
+ }
43
+ if (entity?.type == auth_1.AuthEntityType.DELIVERY_BOY) {
44
+ const rider = await models_1.RiderModel.findOne({ _id: entity.id });
45
+ if (!rider)
46
+ throw new server_1.TRPCError({ code: 'UNAUTHORIZED', message: 'Admin not found' });
47
+ if (rider.isLogin) {
48
+ if (rider.lastLoginDeviceId !== entity.parameters.deviceId) {
49
+ (0, error_common_1.unauthorizedError)('You already logged in another device');
50
+ }
42
51
  }
43
- if (admin.status !== enum_1.Status.ACTIVE) {
44
- throw new server_1.TRPCError({ code: 'UNAUTHORIZED', message: 'Admin is not active' });
52
+ else {
53
+ (0, error_common_1.unauthorizedError)('You have been logged out, Please login in again');
45
54
  }
46
55
  }
47
56
  if (entity) {
@@ -51,26 +60,15 @@ function createAuthenticatedProcedure(options) {
51
60
  ctx.tokenRenewed = false;
52
61
  return next({ ctx });
53
62
  }
54
- if (!allowRefreshToken || !refreshToken) {
55
- throw new server_1.TRPCError({
56
- code: 'UNAUTHORIZED',
57
- message: 'Invalid access token',
58
- });
59
- }
63
+ if (!allowRefreshToken || !refreshToken)
64
+ (0, error_common_1.unauthorizedError)('Invalid access token');
60
65
  const renewalResult = await (0, auth_1.handleTokenRenewal)(refreshToken);
61
66
  if (!renewalResult.success) {
62
67
  const errorMessage = renewalResult.tokenStatus === 'revoked' ? 'Refresh token has been revoked' : 'Invalid refresh token';
63
- throw new server_1.TRPCError({
64
- code: 'UNAUTHORIZED',
65
- message: errorMessage,
66
- });
67
- }
68
- if (!entityTypes.includes(renewalResult.entity.type)) {
69
- throw new server_1.TRPCError({
70
- code: 'UNAUTHORIZED',
71
- message: 'Unauthorized entity type',
72
- });
68
+ (0, error_common_1.unauthorizedError)(errorMessage);
73
69
  }
70
+ if (!entityTypes.includes(renewalResult.entity.type))
71
+ (0, error_common_1.unauthorizedError)('Unauthorized entity type');
74
72
  ctx.entity = renewalResult.entity;
75
73
  ctx.tokenType = auth_1.TokenType.REFRESH;
76
74
  ctx.usedRefreshToken = true;
@@ -1 +1 @@
1
- {"version":3,"file":"auth.js","sourceRoot":"/","sources":["libraries/trpc/middlewares/auth.ts"],"names":[],"mappings":";;AAwBA,oEAkGC;AA1HD,yCAAyC;AACzC,oCAA2C;AAC3C,qCAQoB;AACpB,+CAA6E;AAC7E,kDAAiD;AAYjD,SAAgB,4BAA4B,CAAC,OAAoB;IAChE,MAAM,EAAE,WAAW,EAAE,iBAAiB,GAAG,IAAI,EAAE,WAAW,GAAG,IAAI,EAAE,GAAG,OAAO,CAAC;IAE9E,OAAO,uBAAe,CAAC,GAAG,CAAC,KAAK,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE;QAClD,MAAM,UAAU,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;QACpD,MAAM,kBAAkB,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC;QAE9D,IAAI,CAAC,UAAU,EAAE,CAAC;YACjB,MAAM,IAAI,kBAAS,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,yBAAyB,EAAE,CAAC,CAAC;QACnF,CAAC;QAED,MAAM,WAAW,GAAG,UAAU,CAAC,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC;QACzD,IAAI,YAAY,GAAG,EAAE,CAAC;QAEtB,IAAI,kBAAkB,EAAE,CAAC;YACxB,YAAY;gBACX,OAAO,kBAAkB,KAAK,QAAQ;oBACrC,CAAC,CAAC,kBAAkB,CAAC,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC;oBAC9C,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC;QACrD,CAAC;QAED,IAAI,CAAC,WAAW,EAAE,CAAC;YAClB,MAAM,IAAI,kBAAS,CAAC,EAAE,IAAI,EAAE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AC;YAC5C,IAAI,aAAa,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC;gBACzC,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,oBAAoB,EAAE,aAAa,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;YAC9E,CAAC;YAED,IAAI,aAAa,CAAC,SAAS,CAAC,YAAY,EAAE,CAAC;gBAC1C,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,qBAAqB,EAAE,aAAa,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;YAChF,CAAC;QACF,CAAC;QAED,OAAO,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC;IACtB,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { TRPCError } from '@trpc/server';\nimport { publicProcedure } from '../index';\nimport {\n\tAuthEntityType,\n\tverifyAccessToken,\n\tvalidateRefreshToken,\n\tsignAccessToken,\n\tTokenType,\n\trefreshTokens,\n\thandleTokenRenewal,\n} from '../../auth';\nimport { AdminModel, getCoreUserModel, UserModel } from '../../mongo/models';\nimport { Status } from '../../../utilities/enum';\n\ninterface AuthOptions {\n\tentityTypes: AuthEntityType[];\n\tallowRefreshToken?: boolean;\n\tautoRefresh?: boolean;\n}\n\n/**\n * A factory that creates an authenticated procedure, optionally allowing\n * refresh tokens and auto-refreshing expired access tokens.\n */\nexport function createAuthenticatedProcedure(options: AuthOptions) {\n\tconst { entityTypes, allowRefreshToken = true, autoRefresh = true } = options;\n\n\treturn publicProcedure.use(async ({ ctx, next }) => {\n\t\tconst authHeader = ctx.req.headers['authorization'];\n\t\tconst refreshTokenHeader = ctx.req.headers['x-refresh-token'];\n\n\t\tif (!authHeader) {\n\t\t\tthrow new TRPCError({ code: 'UNAUTHORIZED', message: 'No authorization header' });\n\t\t}\n\n\t\tconst accessToken = authHeader.replace(/^Bearer\\s+/, '');\n\t\tlet refreshToken = '';\n\n\t\tif (refreshTokenHeader) {\n\t\t\trefreshToken =\n\t\t\t\ttypeof refreshTokenHeader === 'string'\n\t\t\t\t\t? refreshTokenHeader.replace(/^Bearer\\s+/, '')\n\t\t\t\t\t: refreshTokenHeader[0].replace(/^Bearer\\s+/, '');\n\t\t}\n\n\t\tif (!accessToken) {\n\t\t\tthrow new TRPCError({ code: 'UNAUTHORIZED', message: 'Missing access token' });\n\t\t}\n\n\t\tlet entity = await verifyAccessToken(entityTypes, accessToken);\n\n\t\tif (entity?.type == 'USER') {\n\t\t\tconst user = await getCoreUserModel().findOne({ _id: entity.parameters.coreUserId });\n\t\t\tif (!user) {\n\t\t\t\tthrow new TRPCError({ code: 'UNAUTHORIZED', message: 'User not found' });\n\t\t\t}\n\t\t\tif (user.status !== Status.ACTIVE) {\n\t\t\t\tthrow new TRPCError({ code: 'UNAUTHORIZED', message: 'User is not active' });\n\t\t\t}\n\t\t}\n\t\tif (entity?.type == 'CRM') {\n\t\t\tconst admin = await AdminModel.findOne({ _id: entity.parameters.adminId });\n\t\t\tif (!admin) {\n\t\t\t\tthrow new TRPCError({ code: 'UNAUTHORIZED', message: 'Admin not found' });\n\t\t\t}\n\t\t\tif (admin.status !== Status.ACTIVE) {\n\t\t\t\tthrow new TRPCError({ code: 'UNAUTHORIZED', message: 'Admin is not active' });\n\t\t\t}\n\t\t}\n\t\tif (entity) {\n\t\t\tctx.entity = entity;\n\t\t\tctx.tokenType = TokenType.ACCESS;\n\t\t\tctx.usedRefreshToken = false;\n\t\t\tctx.tokenRenewed = false;\n\n\t\t\treturn next({ ctx });\n\t\t}\n\n\t\tif (!allowRefreshToken || !refreshToken) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'UNAUTHORIZED',\n\t\t\t\tmessage: 'Invalid access token',\n\t\t\t});\n\t\t}\n\n\t\tconst renewalResult = await handleTokenRenewal(refreshToken);\n\n\t\tif (!renewalResult.success) {\n\t\t\tconst errorMessage =\n\t\t\t\trenewalResult.tokenStatus === 'revoked' ? 'Refresh token has been revoked' : 'Invalid refresh token';\n\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'UNAUTHORIZED',\n\t\t\t\tmessage: errorMessage,\n\t\t\t});\n\t\t}\n\n\t\tif (!entityTypes.includes(renewalResult.entity!.type)) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'UNAUTHORIZED',\n\t\t\t\tmessage: 'Unauthorized entity type',\n\t\t\t});\n\t\t}\n\n\t\tctx.entity = renewalResult.entity;\n\t\tctx.tokenType = TokenType.REFRESH;\n\t\tctx.usedRefreshToken = true;\n\n\t\tctx.tokenRenewed = renewalResult.tokenStatus === 'expired';\n\n\t\tif (autoRefresh && renewalResult.newTokens) {\n\t\t\tif (renewalResult.newTokens.accessToken) {\n\t\t\t\tctx.res.setHeader('X-New-Access-Token', renewalResult.newTokens.accessToken);\n\t\t\t}\n\n\t\t\tif (renewalResult.newTokens.refreshToken) {\n\t\t\t\tctx.res.setHeader('X-New-Refresh-Token', renewalResult.newTokens.refreshToken);\n\t\t\t}\n\t\t}\n\n\t\treturn next({ ctx });\n\t});\n}\n"]}
1
+ {"version":3,"file":"auth.js","sourceRoot":"/","sources":["libraries/trpc/middlewares/auth.ts"],"names":[],"mappings":";;AAiBA,oEAgGC;AAjHD,yCAAyC;AACzC,oCAA2C;AAC3C,qCAA+F;AAC/F,+CAA8E;AAC9E,kDAAiD;AACjD,kEAAoE;AAYpE,SAAgB,4BAA4B,CAAC,OAAoB;IAChE,MAAM,EAAE,WAAW,EAAE,iBAAiB,GAAG,IAAI,EAAE,WAAW,GAAG,IAAI,EAAE,GAAG,OAAO,CAAC;IAE9E,OAAO,uBAAe,CAAC,GAAG,CAAC,KAAK,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE;QAClD,MAAM,UAAU,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;QACpD,MAAM,kBAAkB,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC;QAE9D,IAAI,CAAC,UAAU,EAA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AC,CAAC;QAEnF,MAAM,aAAa,GAAG,MAAM,IAAA,yBAAkB,EAAC,YAAY,CAAC,CAAC;QAE7D,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,CAAC;YAC5B,MAAM,YAAY,GACjB,aAAa,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,gCAAgC,CAAC,CAAC,CAAC,uBAAuB,CAAC;YAEtG,IAAA,gCAAiB,EAAC,YAAY,CAAC,CAAC;QACjC,CAAC;QAED,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,aAAa,CAAC,MAAO,CAAC,IAAI,CAAC;YAAE,IAAA,gCAAiB,EAAC,0BAA0B,CAAC,CAAC;QAErG,GAAG,CAAC,MAAM,GAAG,aAAa,CAAC,MAAM,CAAC;QAClC,GAAG,CAAC,SAAS,GAAG,gBAAS,CAAC,OAAO,CAAC;QAClC,GAAG,CAAC,gBAAgB,GAAG,IAAI,CAAC;QAE5B,GAAG,CAAC,YAAY,GAAG,aAAa,CAAC,WAAW,KAAK,SAAS,CAAC;QAE3D,IAAI,WAAW,IAAI,aAAa,CAAC,SAAS,EAAE,CAAC;YAC5C,IAAI,aAAa,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC;gBACzC,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,oBAAoB,EAAE,aAAa,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;YAC9E,CAAC;YAED,IAAI,aAAa,CAAC,SAAS,CAAC,YAAY,EAAE,CAAC;gBAC1C,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,qBAAqB,EAAE,aAAa,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;YAChF,CAAC;QACF,CAAC;QAED,OAAO,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC;IACtB,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { TRPCError } from '@trpc/server';\nimport { publicProcedure } from '../index';\nimport { AuthEntityType, handleTokenRenewal, TokenType, verifyAccessToken, } from '../../auth';\nimport { AdminModel, getCoreUserModel, RiderModel } from '../../mongo/models';\nimport { Status } from '../../../utilities/enum';\nimport { unauthorizedError } from '../../../utilities/error-common';\n\ninterface AuthOptions {\n\tentityTypes: AuthEntityType[];\n\tallowRefreshToken?: boolean;\n\tautoRefresh?: boolean;\n}\n\n/**\n * A factory that creates an authenticated procedure, optionally allowing\n * refresh tokens and auto-refreshing expired access tokens.\n */\nexport function createAuthenticatedProcedure(options: AuthOptions) {\n\tconst { entityTypes, allowRefreshToken = true, autoRefresh = true } = options;\n\n\treturn publicProcedure.use(async ({ ctx, next }) => {\n\t\tconst authHeader = ctx.req.headers['authorization'];\n\t\tconst refreshTokenHeader = ctx.req.headers['x-refresh-token'];\n\n\t\tif (!authHeader) {\n\t\t\tthrow new TRPCError({ code: 'UNAUTHORIZED', message: 'No authorization header' });\n\t\t}\n\n\t\tconst accessToken = authHeader.replace(/^Bearer\\s+/, '');\n\t\tlet refreshToken = '';\n\n\t\tif (refreshTokenHeader) {\n\t\t\trefreshToken =\n\t\t\t\ttypeof refreshTokenHeader === 'string'\n\t\t\t\t\t? refreshTokenHeader.replace(/^Bearer\\s+/, '')\n\t\t\t\t\t: refreshTokenHeader[0].replace(/^Bearer\\s+/, '');\n\t\t}\n\n\t\tif (!accessToken) unauthorizedError('Missing access token');\n\n\t\tlet entity = await verifyAccessToken(entityTypes, accessToken);\n\n\t\tif (entity?.type == AuthEntityType.USER) {\n\t\t\tconst user = await getCoreUserModel().findOne({ _id: entity.parameters.coreUserId });\n\n\t\t\tif (!user) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'User not found' });\n\t\t\tif (user.status !== Status.ACTIVE) unauthorizedError('User is not active');\n\t\t}\n\n\t\tif (entity?.type == AuthEntityType.CRM) {\n\t\t\tconst admin = await AdminModel.findOne({ _id: entity.parameters.adminId });\n\n\t\t\tif (!admin) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Admin not found' });\n\t\t\tif (admin.status !== Status.ACTIVE) unauthorizedError('Admin is not active');\n\t\t}\n\n\t\t// For rider\n\t\tif(entity?.type == AuthEntityType.DELIVERY_BOY) {\n\t\t\tconst rider = await RiderModel.findOne({ _id: entity.id });\n\n\t\t\t// Check the rider exists or not\n\t\t\tif (!rider) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Admin not found' });\n\n\t\t\t// Check the rider isLogin true or false\n\t\t\tif (rider.isLogin) {\n\t\t\t\tif (rider.lastLoginDeviceId !== entity.parameters.deviceId) {\n\t\t\t\t\tunauthorizedError('You already logged in another device');\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tunauthorizedError('You have been logged out, Please login in again');\n\t\t\t}\n\t\t}\n\n\t\tif (entity) {\n\t\t\tctx.entity = entity;\n\t\t\tctx.tokenType = TokenType.ACCESS;\n\t\t\tctx.usedRefreshToken = false;\n\t\t\tctx.tokenRenewed = false;\n\n\t\t\treturn next({ ctx });\n\t\t}\n\n\t\tif (!allowRefreshToken || !refreshToken) unauthorizedError('Invalid access token');\n\n\t\tconst renewalResult = await handleTokenRenewal(refreshToken);\n\n\t\tif (!renewalResult.success) {\n\t\t\tconst errorMessage =\n\t\t\t\trenewalResult.tokenStatus === 'revoked' ? 'Refresh token has been revoked' : 'Invalid refresh token';\n\n\t\t\tunauthorizedError(errorMessage);\n\t\t}\n\n\t\tif (!entityTypes.includes(renewalResult.entity!.type)) unauthorizedError('Unauthorized entity type');\n\n\t\tctx.entity = renewalResult.entity;\n\t\tctx.tokenType = TokenType.REFRESH;\n\t\tctx.usedRefreshToken = true;\n\n\t\tctx.tokenRenewed = renewalResult.tokenStatus === 'expired';\n\n\t\tif (autoRefresh && renewalResult.newTokens) {\n\t\t\tif (renewalResult.newTokens.accessToken) {\n\t\t\t\tctx.res.setHeader('X-New-Access-Token', renewalResult.newTokens.accessToken);\n\t\t\t}\n\n\t\t\tif (renewalResult.newTokens.refreshToken) {\n\t\t\t\tctx.res.setHeader('X-New-Refresh-Token', renewalResult.newTokens.refreshToken);\n\t\t\t}\n\t\t}\n\n\t\treturn next({ ctx });\n\t});\n}\n"]}
@@ -22,7 +22,7 @@ Perfect for sharing types between frontend and backend applications.
22
22
 
23
23
  ## Version
24
24
 
25
- Version: 1.1.96
25
+ Version: 1.1.98
26
26
 
27
27
  ## Dependencies
28
28
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lyxa.ai/types",
3
- "version": "1.1.96",
3
+ "version": "1.1.98",
4
4
  "description": "Lyxa type definitions and validation schemas for both frontend and backend",
5
5
  "author": "elie <42282499+Internalizable@users.noreply.github.com>",
6
6
  "license": "MIT",
@@ -1,4 +1,4 @@
1
- export declare function calculateWalletDeduction(currentMainBalance: number, deductionAmount: number, isDualCurrencyEnabled?: true): {
1
+ export declare function calculateWalletDeduction(currentMainBalance: number, deductionAmount: number, isDualCurrencyEnabled?: boolean): {
2
2
  mainWalletChange: number;
3
3
  reserveWalletChange: number;
4
4
  };
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.calculateWalletDeduction = calculateWalletDeduction;
4
4
  const shared_1 = require("./shared");
5
- function calculateWalletDeduction(currentMainBalance, deductionAmount, isDualCurrencyEnabled) {
5
+ function calculateWalletDeduction(currentMainBalance, deductionAmount, isDualCurrencyEnabled = true) {
6
6
  const round = isDualCurrencyEnabled ? shared_1.roundSecondaryCurrency : shared_1.roundBaseCurrency;
7
7
  const remainingAfterMain = round(currentMainBalance - deductionAmount);
8
8
  if (remainingAfterMain >= 0) {
@@ -1 +1 @@
1
- {"version":3,"file":"wallet.js","sourceRoot":"/","sources":["utilities/wallet.ts"],"names":[],"mappings":";;AAOA,4DAkBC;AAzBD,qCAAqE;AAOrE,SAAgB,wBAAwB,CACvC,kBAA0B,EAC1B,eAAuB,EACvB,qBAA4B;IAK5B,MAAM,KAAK,GAAG,qBAAqB,CAAC,CAAC,CAAC,+BAAsB,CAAC,CAAC,CAAC,0BAAiB,CAAC;IACjF,MAAM,kBAAkB,GAAG,KAAK,CAAC,kBAAkB,GAAG,eAAe,CAAC,CAAC;IAGvE,IAAI,kBAAkB,IAAI,CAAC,EAAE,CAAC;QAC7B,OAAO,EAAE,gBAAgB,EAAE,CAAC,eAAe,EAAE,mBAAmB,EAAE,CAAC,EAAE,CAAC;IACvE,CAAC;IAGD,OAAO,EAAE,gBAAgB,EAAE,CAAC,kBAAkB,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,CAAC;AAC3F,CAAC","sourcesContent":["import { roundBaseCurrency, roundSecondaryCurrency } from './shared';\n\n/**\n * Calculates how much to deduct from a user's wallets.\n * Deducts from the main wallet first, then from the reserve wallet if needed.\n * Returns negative values (for use with $inc updates in MongoDB).\n */\nexport function calculateWalletDeduction(\n\tcurrentMainBalance: number,\n\tdeductionAmount: number,\n\tisDualCurrencyEnabled?: true\n): {\n\tmainWalletChange: number;\n\treserveWalletChange: number;\n} {\n\tconst round = isDualCurrencyEnabled ? roundSecondaryCurrency : roundBaseCurrency;\n\tconst remainingAfterMain = round(currentMainBalance - deductionAmount);\n\n\t// If main has enough, reserve doesn't change\n\tif (remainingAfterMain >= 0) {\n\t\treturn { mainWalletChange: -deductionAmount, reserveWalletChange: 0 };\n\t}\n\n\t// Otherwise, deduct all from main and the remainder (negative) from reserve\n\treturn { mainWalletChange: -currentMainBalance, reserveWalletChange: remainingAfterMain };\n}\n"]}
1
+ {"version":3,"file":"wallet.js","sourceRoot":"/","sources":["utilities/wallet.ts"],"names":[],"mappings":";;AAOA,4DAkBC;AAzBD,qCAAqE;AAOrE,SAAgB,wBAAwB,CACvC,kBAA0B,EAC1B,eAAuB,EACvB,wBAAiC,IAAI;IAKrC,MAAM,KAAK,GAAG,qBAAqB,CAAC,CAAC,CAAC,+BAAsB,CAAC,CAAC,CAAC,0BAAiB,CAAC;IACjF,MAAM,kBAAkB,GAAG,KAAK,CAAC,kBAAkB,GAAG,eAAe,CAAC,CAAC;IAGvE,IAAI,kBAAkB,IAAI,CAAC,EAAE,CAAC;QAC7B,OAAO,EAAE,gBAAgB,EAAE,CAAC,eAAe,EAAE,mBAAmB,EAAE,CAAC,EAAE,CAAC;IACvE,CAAC;IAGD,OAAO,EAAE,gBAAgB,EAAE,CAAC,kBAAkB,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,CAAC;AAC3F,CAAC","sourcesContent":["import { roundBaseCurrency, roundSecondaryCurrency } from './shared';\n\n/**\n * Calculates how much to deduct from a user's wallets.\n * Deducts from the main wallet first, then from the reserve wallet if needed.\n * Returns negative values (for use with $inc updates in MongoDB).\n */\nexport function calculateWalletDeduction(\n\tcurrentMainBalance: number,\n\tdeductionAmount: number,\n\tisDualCurrencyEnabled: boolean = true\n): {\n\tmainWalletChange: number;\n\treserveWalletChange: number;\n} {\n\tconst round = isDualCurrencyEnabled ? roundSecondaryCurrency : roundBaseCurrency;\n\tconst remainingAfterMain = round(currentMainBalance - deductionAmount);\n\n\t// If main has enough, reserve doesn't change\n\tif (remainingAfterMain >= 0) {\n\t\treturn { mainWalletChange: -deductionAmount, reserveWalletChange: 0 };\n\t}\n\n\t// Otherwise, deduct all from main and the remainder (negative) from reserve\n\treturn { mainWalletChange: -currentMainBalance, reserveWalletChange: remainingAfterMain };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lyxa.ai/core",
3
- "version": "1.1.96",
3
+ "version": "1.1.98",
4
4
  "description": "The Core system of the Lyxa services.",
5
5
  "author": "elie <42282499+Internalizable@users.noreply.github.com>",
6
6
  "license": "MIT",