From 98f237b4bd9ae2b0c213d9804969c8ccb1c6d57b Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Fri, 3 Nov 2023 16:10:46 +0100 Subject: [PATCH 01/75] new middleware for auth:before --- loopback/server/middleware.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/loopback/server/middleware.json b/loopback/server/middleware.json index 31a2f113b..45e8ada23 100644 --- a/loopback/server/middleware.json +++ b/loopback/server/middleware.json @@ -34,12 +34,15 @@ } } }, + "auth:before": { + "./middleware/renew-token": {} + }, "auth:after": { "./middleware/current-user": {}, "./middleware/salix-version": {} }, "parse": { - "body-parser#json":{} + "body-parser#json":{} }, "routes": { "loopback#rest": { From 38d1e2b14fb2babad9453313b7cc54ed55fdf5c9 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Fri, 3 Nov 2023 16:11:35 +0100 Subject: [PATCH 02/75] renew-token middleware definition --- loopback/server/middleware/renew-token.js | 24 +++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 loopback/server/middleware/renew-token.js diff --git a/loopback/server/middleware/renew-token.js b/loopback/server/middleware/renew-token.js new file mode 100644 index 000000000..ab5825942 --- /dev/null +++ b/loopback/server/middleware/renew-token.js @@ -0,0 +1,24 @@ +const {models} = require('vn-loopback/server/server'); + +module.exports = function(options) { + return async function(req, res, next) { + const token = req.headers.authorization; + if (!token) return next(); + + const accessToken = await models.AccessToken.findById(token); + if (!accessToken) return next(); + const maxDate = accessToken.created.setSeconds(accessToken.ttl); + if (new Date().getTime() > new Date(maxDate)) return next(); + + const vnUser = await models.VnUser.findById(accessToken.userId); + if (!vnUser) return next(); + const newToken = await vnUser.createAccessToken(accessToken.ttl); + + // console.log(accessToken, newToken); + // req.accessToken = newToken; + // res.headers.authorization = newToken; + res.setHeader('Authorization', newToken.id); + // const removed = await accessToken.delete({id: token}); + next(); + }; +}; From 82ee4f6e5b344e11111c5684182ca7ab7d5a649f Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Sat, 4 Nov 2023 14:38:21 +0100 Subject: [PATCH 03/75] remove auth:before middleware --- loopback/server/middleware.json | 3 --- 1 file changed, 3 deletions(-) diff --git a/loopback/server/middleware.json b/loopback/server/middleware.json index 45e8ada23..cfc693217 100644 --- a/loopback/server/middleware.json +++ b/loopback/server/middleware.json @@ -34,9 +34,6 @@ } } }, - "auth:before": { - "./middleware/renew-token": {} - }, "auth:after": { "./middleware/current-user": {}, "./middleware/salix-version": {} From 8c6eab23e5ab76d5bf2516c9291a32fe8a1b1dc9 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Sat, 4 Nov 2023 14:39:26 +0100 Subject: [PATCH 04/75] handle expired token and return new token --- back/methods/vn-user/is-token-valid.js | 7 +++++++ back/methods/vn-user/renew-token.js | 26 ++++++++++++++++---------- back/methods/vn-user/validate-token.js | 9 +++++++-- 3 files changed, 30 insertions(+), 12 deletions(-) create mode 100644 back/methods/vn-user/is-token-valid.js diff --git a/back/methods/vn-user/is-token-valid.js b/back/methods/vn-user/is-token-valid.js new file mode 100644 index 000000000..1104b55e2 --- /dev/null +++ b/back/methods/vn-user/is-token-valid.js @@ -0,0 +1,7 @@ + +module.exports = async(token, accessTokenConfig) => { + const now = new Date(); + const differenceMilliseconds = now - token.created; + const differenceSeconds = Math.floor(differenceMilliseconds / 1000); + return differenceSeconds > accessTokenConfig.renewPeriod - accessTokenConfig.courtesyTime; +}; diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index 9850267d6..1206e537f 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -1,5 +1,12 @@ const UserError = require('vn-loopback/util/user-error'); - +const handlePromiseLogout = (Self, {id}, courtesyTime = 60) => { + new Promise(res => { + setTimeout(() => { + res(Self.logout(id)); + } + , courtesyTime * 1000); + }); +}; module.exports = Self => { Self.remoteMethodCtx('renewToken', { description: 'Checks if the token has more than renewPeriod seconds to live and if so, renews it', @@ -19,17 +26,16 @@ module.exports = Self => { const models = Self.app.models; const token = ctx.req.accessToken; - const now = new Date(); - const differenceMilliseconds = now - token.created; - const differenceSeconds = Math.floor(differenceMilliseconds / 1000); + // Check if current token is valid + const isValid = await Self.validateToken(token); + if (!isValid) throw new UserError(`The renew period has not been exceeded`, 'periodNotExceeded'); + const fields = ['courtesyTime']; + const {courtesyTime} = await models.AccessTokenConfig.findOne({fields}); - const fields = ['renewPeriod', 'courtesyTime']; - const accessTokenConfig = await models.AccessTokenConfig.findOne({fields}); + // Schedule to remove current token + handlePromiseLogout(Self, token, courtesyTime); - if (differenceSeconds < accessTokenConfig.renewPeriod - accessTokenConfig.courtesyTime) - throw new UserError(`The renew period has not been exceeded`, 'periodNotExceeded'); - - await Self.logout(token.id); + // Create new accessToken const user = await Self.findById(token.userId); const accessToken = await user.createAccessToken(); diff --git a/back/methods/vn-user/validate-token.js b/back/methods/vn-user/validate-token.js index 7bccfe0b1..5cbbbf0e8 100644 --- a/back/methods/vn-user/validate-token.js +++ b/back/methods/vn-user/validate-token.js @@ -1,3 +1,5 @@ +const isTokenValid = require('./is-token-valid'); + module.exports = Self => { Self.remoteMethod('validateToken', { description: 'Validates the current logged user token', @@ -11,7 +13,10 @@ module.exports = Self => { } }); - Self.validateToken = async function() { - return true; + Self.validateToken = async function(token) { + const fields = ['renewPeriod', 'courtesyTime']; + const accessTokenConfig = await Self.app.models.AccessTokenConfig.findOne({fields}); + const isValid = await isTokenValid(token, accessTokenConfig); + return isValid; }; }; From b02e1f000ef61d4ba0c2156c66fccdb2d5582c31 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Sat, 4 Nov 2023 14:39:59 +0100 Subject: [PATCH 05/75] handle expired token while exists in BD --- loopback/server/middleware/current-user.js | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/loopback/server/middleware/current-user.js b/loopback/server/middleware/current-user.js index a6624351e..8ff4bb618 100644 --- a/loopback/server/middleware/current-user.js +++ b/loopback/server/middleware/current-user.js @@ -1,7 +1,16 @@ +const {models} = require('vn-loopback/server/server'); + module.exports = function(options) { - return function(req, res, next) { - if (!req.accessToken) + return async function(req, res, next) { + if (!req.accessToken) { + const token = req.headers.authorization; + if (!token) return next(); + + const accessToken = await models.AccessToken.findById(token); + if (!accessToken) return next(); + return next(); + } let LoopBackContext = require('loopback-context'); let loopbackContext = LoopBackContext.getCurrentContext(); From 67faf076d267af7a88a7b93ae48bee7f7f9b5c8c Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Sat, 4 Nov 2023 16:51:25 +0100 Subject: [PATCH 06/75] refs '#6264' feat: memoization accessTokenConfig --- back/methods/vn-user/is-token-valid.js | 5 ++++- back/methods/vn-user/renew-token.js | 11 ++++++----- back/methods/vn-user/token-config.js | 9 +++++++++ back/methods/vn-user/validate-token.js | 4 +--- 4 files changed, 20 insertions(+), 9 deletions(-) create mode 100644 back/methods/vn-user/token-config.js diff --git a/back/methods/vn-user/is-token-valid.js b/back/methods/vn-user/is-token-valid.js index 1104b55e2..e40c2765a 100644 --- a/back/methods/vn-user/is-token-valid.js +++ b/back/methods/vn-user/is-token-valid.js @@ -1,5 +1,8 @@ +const tokenConfig = require('./token-config'); + +module.exports = async token => { + const accessTokenConfig = await tokenConfig(); -module.exports = async(token, accessTokenConfig) => { const now = new Date(); const differenceMilliseconds = now - token.created; const differenceSeconds = Math.floor(differenceMilliseconds / 1000); diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index 1206e537f..4226886fc 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -1,5 +1,7 @@ const UserError = require('vn-loopback/util/user-error'); -const handlePromiseLogout = (Self, {id}, courtesyTime = 60) => { +const tokenConfig = require('./token-config'); +const DEFAULT_COURTESY_TIME = 60; +const handlePromiseLogout = (Self, {id}, courtesyTime = DEFAULT_COURTESY_TIME) => { new Promise(res => { setTimeout(() => { res(Self.logout(id)); @@ -23,14 +25,13 @@ module.exports = Self => { }); Self.renewToken = async function(ctx) { - const models = Self.app.models; - const token = ctx.req.accessToken; + const {accessToken: token} = ctx.req; // Check if current token is valid const isValid = await Self.validateToken(token); if (!isValid) throw new UserError(`The renew period has not been exceeded`, 'periodNotExceeded'); - const fields = ['courtesyTime']; - const {courtesyTime} = await models.AccessTokenConfig.findOne({fields}); + + const {courtesyTime} = await tokenConfig(); // Schedule to remove current token handlePromiseLogout(Self, token, courtesyTime); diff --git a/back/methods/vn-user/token-config.js b/back/methods/vn-user/token-config.js new file mode 100644 index 000000000..0936e0b89 --- /dev/null +++ b/back/methods/vn-user/token-config.js @@ -0,0 +1,9 @@ +const DEFAULT_FIELDS = ['renewPeriod', 'courtesyTime']; +const {models} = require('vn-loopback/server/server'); +let currentAccessTokenConfig = null; +module.exports = async(fields = DEFAULT_FIELDS) => { + if (currentAccessTokenConfig) return currentAccessTokenConfig; + const accessTokenConfig = await models.AccessTokenConfig.findOne({fields}); + if (!accessTokenConfig) currentAccessTokenConfig = accessTokenConfig; + return accessTokenConfig; +}; diff --git a/back/methods/vn-user/validate-token.js b/back/methods/vn-user/validate-token.js index 5cbbbf0e8..fadaed43b 100644 --- a/back/methods/vn-user/validate-token.js +++ b/back/methods/vn-user/validate-token.js @@ -14,9 +14,7 @@ module.exports = Self => { }); Self.validateToken = async function(token) { - const fields = ['renewPeriod', 'courtesyTime']; - const accessTokenConfig = await Self.app.models.AccessTokenConfig.findOne({fields}); - const isValid = await isTokenValid(token, accessTokenConfig); + const isValid = await isTokenValid(token); return isValid; }; }; From 21028e3b79be1e5d8afccd9c8df9bd4dca52979a Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Sat, 4 Nov 2023 17:23:44 +0100 Subject: [PATCH 07/75] refs #6264 feat: db changes --- db/changes/234601/00-updateCourtesyTime.sql | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 db/changes/234601/00-updateCourtesyTime.sql diff --git a/db/changes/234601/00-updateCourtesyTime.sql b/db/changes/234601/00-updateCourtesyTime.sql new file mode 100644 index 000000000..4751b2e03 --- /dev/null +++ b/db/changes/234601/00-updateCourtesyTime.sql @@ -0,0 +1,4 @@ +-- Auto-generated SQL script #202311061003 +UPDATE salix.accessTokenConfig + SET courtesyTime=60 + WHERE id=1; From 43366d1ba825dfcd32f13278aceb805b048a0ca5 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Sat, 4 Nov 2023 17:24:04 +0100 Subject: [PATCH 08/75] refs #6264 feat: update fixture.sql --- db/dump/fixtures.sql | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index d70279e7d..9bc3e102a 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2758,7 +2758,7 @@ INSERT INTO `vn`.`sectorCollectionSaleGroup` (`sectorCollectionFk`, `saleGroupFk VALUES (1, 1); -INSERT INTO `vn`.`workerTimeControlConfig` (`id`, `dayBreak`, `dayBreakDriver`, `shortWeekBreak`, `longWeekBreak`, `weekScope`, `mailPass`, `mailHost`, `mailSuccessFolder`, `mailErrorFolder`, `mailUser`, `minHoursToBreak`, `breakHours`, `hoursCompleteWeek`, `startNightlyHours`, `endNightlyHours`, `maxTimePerDay`, `breakTime`, `timeToBreakTime`, `dayMaxTime`, `shortWeekDays`, `longWeekDays`, `teleworkingStart`, `teleworkingStartBreakTime`, `maxTimeToBreak`, `maxWorkShortCycle`, `maxWorkLongCycle`) +INSERT INTO `vn`.`workerTimeControlConfig` (`id`, `dayBreak`, `dayBreakDriver`, `shortWeekBreak`, `longWeekBreak`, `weekScope`, `mailPass`, `mailHost`, `mailSuccessFolder`, `mailErrorFolder`, `mailUser`, `minHoursToBreak`, `breakHours`, `hoursCompleteWeek`, `startNightlyHours`, `endNightlyHours`, `maxTimePerDay`, `breakTime`, `timeToBreakTime`, `dayMaxTime`, `shortWeekDays`, `longWeekDays`, `teleworkingStart`, `teleworkingStartBreakTime`, `maxTimeToBreak`, `maxWorkShortCycle`, `maxWorkLongCycle`) VALUES (1, 43200, 32400, 129600, 259200, 1080000, '', 'imap.verdnatura.es', 'Leidos.exito', 'Leidos.error', 'timeControl', 5.00, 0.33, 40, '22:00:00', '06:00:00', 72000, 1200, 18000, 72000, 6, 13, 28800, 32400, 3600, 561600, 950400); @@ -2945,9 +2945,9 @@ INSERT INTO `vn`.`wagonTypeTray` (`id`, `typeFk`, `height`, `colorFk`) (2, 1, 50, 2), (3, 1, 0, 3); -INSERT INTO `salix`.`accessTokenConfig` (`id`, `renewPeriod`, `renewInterval`) +INSERT INTO `salix`.`accessTokenConfig` (`id`, `renewPeriod`, `courtesyTime`, `renewInterval`) VALUES - (1, 21600, 300); + (1, 21600, 60, 300); INSERT INTO `vn`.`travelConfig` (`id`, `warehouseInFk`, `warehouseOutFk`, `agencyFk`, `companyFk`) VALUES @@ -2986,4 +2986,4 @@ INSERT INTO `vn`.`invoiceCorrectionType` (`id`, `description`) VALUES (1, 'Error in VAT calculation'), (2, 'Error in sales details'), - (3, 'Error in customer data'); \ No newline at end of file + (3, 'Error in customer data'); From 5601ce5dac7ddd8f155961f4ea0d333a391bed04 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Sat, 4 Nov 2023 17:25:30 +0100 Subject: [PATCH 09/75] refs #6264 fix: rename variable --- front/core/services/token.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/front/core/services/token.js b/front/core/services/token.js index 426fe2b73..f1408f7e3 100644 --- a/front/core/services/token.js +++ b/front/core/services/token.js @@ -82,7 +82,7 @@ export default class Token { if (!data) return; this.renewPeriod = data.renewPeriod; this.stopRenewer(); - this.inservalId = setInterval(() => this.checkValidity(), data.renewInterval * 1000); + this.intervalId = setInterval(() => this.checkValidity(), data.renewInterval * 1000); }); } @@ -113,7 +113,7 @@ export default class Token { } stopRenewer() { - clearInterval(this.inservalId); + clearInterval(this.intervalId); } } Token.$inject = ['vnInterceptor', '$http', '$rootScope']; From 0c2b2b25b741d62e54d4cae526199a338a734836 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Sat, 4 Nov 2023 18:07:37 +0100 Subject: [PATCH 10/75] refs #6264 fix: remove unnecessary file --- loopback/server/middleware/renew-token.js | 24 ----------------------- 1 file changed, 24 deletions(-) delete mode 100644 loopback/server/middleware/renew-token.js diff --git a/loopback/server/middleware/renew-token.js b/loopback/server/middleware/renew-token.js deleted file mode 100644 index ab5825942..000000000 --- a/loopback/server/middleware/renew-token.js +++ /dev/null @@ -1,24 +0,0 @@ -const {models} = require('vn-loopback/server/server'); - -module.exports = function(options) { - return async function(req, res, next) { - const token = req.headers.authorization; - if (!token) return next(); - - const accessToken = await models.AccessToken.findById(token); - if (!accessToken) return next(); - const maxDate = accessToken.created.setSeconds(accessToken.ttl); - if (new Date().getTime() > new Date(maxDate)) return next(); - - const vnUser = await models.VnUser.findById(accessToken.userId); - if (!vnUser) return next(); - const newToken = await vnUser.createAccessToken(accessToken.ttl); - - // console.log(accessToken, newToken); - // req.accessToken = newToken; - // res.headers.authorization = newToken; - res.setHeader('Authorization', newToken.id); - // const removed = await accessToken.delete({id: token}); - next(); - }; -}; From 784f5bb7f92f5b7df876b722fcc645972938faac Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 7 Nov 2023 23:23:02 +0100 Subject: [PATCH 11/75] refs #6264 perf: replace now with vnNew --- back/methods/vn-user/is-token-valid.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/methods/vn-user/is-token-valid.js b/back/methods/vn-user/is-token-valid.js index e40c2765a..f4c2a9ea8 100644 --- a/back/methods/vn-user/is-token-valid.js +++ b/back/methods/vn-user/is-token-valid.js @@ -3,7 +3,7 @@ const tokenConfig = require('./token-config'); module.exports = async token => { const accessTokenConfig = await tokenConfig(); - const now = new Date(); + const now = Date.vnNew(); const differenceMilliseconds = now - token.created; const differenceSeconds = Math.floor(differenceMilliseconds / 1000); return differenceSeconds > accessTokenConfig.renewPeriod - accessTokenConfig.courtesyTime; From bcccd1894c555706f115c1fe670ce1c40dfe2b4b Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Fri, 10 Nov 2023 13:13:17 +0100 Subject: [PATCH 12/75] refs #6264 test: init test --- .../methods/vn-user/specs/renew-token.spec.js | 22 +++++++++++++++++++ .../vn-user/specs/validate-token.spec.js | 9 ++++++++ 2 files changed, 31 insertions(+) create mode 100644 back/methods/vn-user/specs/renew-token.spec.js create mode 100644 back/methods/vn-user/specs/validate-token.spec.js diff --git a/back/methods/vn-user/specs/renew-token.spec.js b/back/methods/vn-user/specs/renew-token.spec.js new file mode 100644 index 000000000..cae91f310 --- /dev/null +++ b/back/methods/vn-user/specs/renew-token.spec.js @@ -0,0 +1,22 @@ +describe('Renew Token', () => { + it('Token is valid', async() => { + let login = await VnUser.signIn(unauthCtx, 'salesAssistant', 'nightmare'); + let accessToken = await AccessToken.findById(login.token); + let ctx = {req: {accessToken: accessToken}}; + + expect(login.token).toBeDefined(); + }); + + it('Token is is invalid', async() => { + let error; + try { + await models.VnUser.validateCode('developer', '123456'); + } catch (e) { + error = e; + } + + expect(error).toBeDefined(); + expect(error.statusCode).toBe(400); + expect(error.message).toEqual('Invalid or expired verification code'); + }); +}); diff --git a/back/methods/vn-user/specs/validate-token.spec.js b/back/methods/vn-user/specs/validate-token.spec.js new file mode 100644 index 000000000..0d0af689f --- /dev/null +++ b/back/methods/vn-user/specs/validate-token.spec.js @@ -0,0 +1,9 @@ +describe('Validate Token', () => { + it('Token is not expired', async() => { + + }); + + it('Token is expired', async() => { + + }); +}); From 5c777c705feecca80213dd5a7ef4d70d246e4c26 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 14 Nov 2023 13:00:20 +0100 Subject: [PATCH 13/75] refs #6434 feat: add new error message --- back/methods/vn-user/sign-in.js | 28 +++++++++++++++------------- back/models/vn-user.js | 13 +++++++++++-- loopback/locale/es.json | 4 +++- 3 files changed, 29 insertions(+), 16 deletions(-) diff --git a/back/methods/vn-user/sign-in.js b/back/methods/vn-user/sign-in.js index b9e0d2f70..5c84b654e 100644 --- a/back/methods/vn-user/sign-in.js +++ b/back/methods/vn-user/sign-in.js @@ -26,7 +26,7 @@ module.exports = Self => { } }); - Self.signIn = async function(ctx, user, password, options) { + Self.signIn = async function (ctx, user, password, options) { const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); @@ -40,15 +40,17 @@ module.exports = Self => { const validCredentials = vnUser && await vnUser.hasPassword(password); - if (validCredentials) { - if (!vnUser.active) - throw new UserError('User disabled'); - await Self.sendTwoFactor(ctx, vnUser, myOptions); - await Self.passExpired(vnUser, myOptions); + if (!validCredentials) + throw new UserError('Invalid credentials'); - if (vnUser.twoFactor) - throw new ForbiddenError(null, 'REQUIRES_2FA'); - } + if (!vnUser.active) + throw new UserError('User disabled'); + + await Self.sendTwoFactor(ctx, vnUser, myOptions); + await Self.passExpired(vnUser, myOptions); + + if (vnUser.twoFactor) + throw new ForbiddenError(null, 'REQUIRES_2FA'); return Self.validateLogin(user, password); }; @@ -59,18 +61,18 @@ module.exports = Self => { if (vnUser.passExpired && vnUser.passExpired.getTime() <= today.getTime()) { const err = new UserError('Pass expired', 'passExpired'); - err.details = {userId: vnUser.id, twoFactor: vnUser.twoFactor ? true : false}; + err.details = { userId: vnUser.id, twoFactor: vnUser.twoFactor ? true : false }; throw err; } }; - Self.sendTwoFactor = async(ctx, vnUser, myOptions) => { + Self.sendTwoFactor = async (ctx, vnUser, myOptions) => { if (vnUser.twoFactor === 'email') { const $ = Self.app.models; const code = String(Math.floor(Math.random() * 999999)); const maxTTL = ((60 * 1000) * 5); // 5 min - await $.AuthCode.upsertWithWhere({userFk: vnUser.id}, { + await $.AuthCode.upsertWithWhere({ userFk: vnUser.id }, { userFk: vnUser.id, code: code, expires: Date.vnNow() + maxTTL @@ -87,7 +89,7 @@ module.exports = Self => { ip: ctx.req?.connection?.remoteAddress, device: platform && browser ? platform + ', ' + browser : headers['user-agent'], }, - req: {getLocale: ctx.req.getLocale}, + req: { getLocale: ctx.req.getLocale }, }; await Self.sendTemplate(params, 'auth-code', true); diff --git a/back/models/vn-user.js b/back/models/vn-user.js index de5bf7b63..5c6e4a30f 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -2,6 +2,7 @@ const vnModel = require('vn-loopback/common/models/vn-model'); const {Email} = require('vn-print'); const ForbiddenError = require('vn-loopback/util/forbiddenError'); const LoopBackContext = require('loopback-context'); +const UserError = require('vn-loopback/util/user-error'); module.exports = function(Self) { vnModel(Self); @@ -121,10 +122,18 @@ module.exports = function(Self) { }); Self.validateLogin = async function(user, password) { - let loginInfo = Object.assign({password}, Self.userUses(user)); - token = await Self.login(loginInfo, 'user'); + const loginInfo = Object.assign({password}, Self.userUses(user)); + const token = await Self.login(loginInfo, 'user'); const userToken = await token.user.get(); + + if (userToken.username !== user) { + console.error('ERROR!!! - Signin with other user', userToken, user); + throw new UserError('Try again'); + } + + const userCheck = await Self.app.models.VnUser.findOne({where: {name: user}}); + if (userToken.id != userCheck.id) await Self.validateLogin(user, password); try { await Self.app.models.Account.sync(userToken.name, password); } catch (err) { diff --git a/loopback/locale/es.json b/loopback/locale/es.json index b42720458..7cccc0fd0 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -325,5 +325,7 @@ "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} está en preparación", "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mímina", "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mímina", - "The notification subscription of this worker cant be modified": "La subscripción a la notificación de este trabajador no puede ser modificada" + "The notification subscription of this worker cant be modified": "La subscripción a la notificación de este trabajador no puede ser modificada", + "User disabled": "User disabled", + "Invalid credentials": "Invalid credentials" } From 7f82243ce6000176d9b9eeab03f81d68c781530f Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 14 Nov 2023 15:00:03 +0100 Subject: [PATCH 14/75] refs #6434 feat: create signInLog table --- back/methods/vn-user/sign-in.js | 19 ++++++---- db/changes/234801/00-createSignInLogTable.sql | 19 ++++++++++ modules/account/back/model-config.json | 3 ++ modules/account/back/models/sign_in-log.json | 35 +++++++++++++++++++ 4 files changed, 69 insertions(+), 7 deletions(-) create mode 100644 db/changes/234801/00-createSignInLogTable.sql create mode 100644 modules/account/back/models/sign_in-log.json diff --git a/back/methods/vn-user/sign-in.js b/back/methods/vn-user/sign-in.js index 5c84b654e..78d74b147 100644 --- a/back/methods/vn-user/sign-in.js +++ b/back/methods/vn-user/sign-in.js @@ -26,7 +26,7 @@ module.exports = Self => { } }); - Self.signIn = async function (ctx, user, password, options) { + Self.signIn = async function(ctx, user, password, options) { const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); @@ -51,8 +51,13 @@ module.exports = Self => { if (vnUser.twoFactor) throw new ForbiddenError(null, 'REQUIRES_2FA'); - - return Self.validateLogin(user, password); + const validateLogin = await Self.validateLogin(user, password); + await Self.app.models.SignInLog.create({ + id: validateLogin.token, + userFk: vnUser.id, + ip: ctx.req.ip + }); + return validateLogin; }; Self.passExpired = async vnUser => { @@ -61,18 +66,18 @@ module.exports = Self => { if (vnUser.passExpired && vnUser.passExpired.getTime() <= today.getTime()) { const err = new UserError('Pass expired', 'passExpired'); - err.details = { userId: vnUser.id, twoFactor: vnUser.twoFactor ? true : false }; + err.details = {userId: vnUser.id, twoFactor: vnUser.twoFactor ? true : false}; throw err; } }; - Self.sendTwoFactor = async (ctx, vnUser, myOptions) => { + Self.sendTwoFactor = async(ctx, vnUser, myOptions) => { if (vnUser.twoFactor === 'email') { const $ = Self.app.models; const code = String(Math.floor(Math.random() * 999999)); const maxTTL = ((60 * 1000) * 5); // 5 min - await $.AuthCode.upsertWithWhere({ userFk: vnUser.id }, { + await $.AuthCode.upsertWithWhere({userFk: vnUser.id}, { userFk: vnUser.id, code: code, expires: Date.vnNow() + maxTTL @@ -89,7 +94,7 @@ module.exports = Self => { ip: ctx.req?.connection?.remoteAddress, device: platform && browser ? platform + ', ' + browser : headers['user-agent'], }, - req: { getLocale: ctx.req.getLocale }, + req: {getLocale: ctx.req.getLocale}, }; await Self.sendTemplate(params, 'auth-code', true); diff --git a/db/changes/234801/00-createSignInLogTable.sql b/db/changes/234801/00-createSignInLogTable.sql new file mode 100644 index 000000000..977de4646 --- /dev/null +++ b/db/changes/234801/00-createSignInLogTable.sql @@ -0,0 +1,19 @@ + + +-- +-- Table structure for table `signInLog` +-- + +DROP TABLE IF EXISTS `account`.`signInLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `account`.`signInLog` ( + `id` varchar(10) NOT NULL , + `userFk` int(10) unsigned DEFAULT NULL, + `creationDate` timestamp NULL DEFAULT current_timestamp(), + `ip` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, + PRIMARY KEY (`id`), + KEY `userFk` (`userFk`), + CONSTRAINT `signInLog_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +); + diff --git a/modules/account/back/model-config.json b/modules/account/back/model-config.json index a4eb9fa57..b4bd6dbaf 100644 --- a/modules/account/back/model-config.json +++ b/modules/account/back/model-config.json @@ -35,6 +35,9 @@ "SambaConfig": { "dataSource": "vn" }, + "SignInLog": { + "dataSource": "vn" + }, "Sip": { "dataSource": "vn" }, diff --git a/modules/account/back/models/sign_in-log.json b/modules/account/back/models/sign_in-log.json new file mode 100644 index 000000000..df9ad8153 --- /dev/null +++ b/modules/account/back/models/sign_in-log.json @@ -0,0 +1,35 @@ +{ + "name": "SignInLog", + "base": "VnModel", + "options": { + "mysql": { + "table": "account.signInLog" + } + }, + "properties": { + "id": { + "id": true, + "type": "string", + "forceId": false + }, + "creationDate": { + "type": "date" + }, + "userFk": { + "type": "number" + }, + "ip": { + "type": "string" + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "VnUser", + "foreignKey": "userFk" + } + }, + "scope": { + "order": ["creationDate DESC", "id DESC"] + } +} From add3a81032aae8ecfa41e3fad37179c6b1dacac4 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 15 Nov 2023 09:29:26 +0100 Subject: [PATCH 15/75] refs #6434 feat: remove recursively fn --- back/methods/vn-user/sign-in.js | 2 ++ back/models/vn-user.js | 2 -- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/back/methods/vn-user/sign-in.js b/back/methods/vn-user/sign-in.js index 78d74b147..e51cf8d8e 100644 --- a/back/methods/vn-user/sign-in.js +++ b/back/methods/vn-user/sign-in.js @@ -51,7 +51,9 @@ module.exports = Self => { if (vnUser.twoFactor) throw new ForbiddenError(null, 'REQUIRES_2FA'); + const validateLogin = await Self.validateLogin(user, password); + await Self.app.models.SignInLog.create({ id: validateLogin.token, userFk: vnUser.id, diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 5c6e4a30f..00f5cd0b8 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -132,8 +132,6 @@ module.exports = function(Self) { throw new UserError('Try again'); } - const userCheck = await Self.app.models.VnUser.findOne({where: {name: user}}); - if (userToken.id != userCheck.id) await Self.validateLogin(user, password); try { await Self.app.models.Account.sync(userToken.name, password); } catch (err) { From 72a0932e35539bd53857a0e3cb9c02916c8e5965 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 27 Nov 2023 09:46:27 +0100 Subject: [PATCH 16/75] refs #6264 other: rename camel-case variable --- back/methods/vn-user/specs/sign-in.spec.js | 12 ++++++------ .../methods/account/specs/change-password.spec.js | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/back/methods/vn-user/specs/sign-in.spec.js b/back/methods/vn-user/specs/sign-in.spec.js index f4cad88b9..e02c72ad3 100644 --- a/back/methods/vn-user/specs/sign-in.spec.js +++ b/back/methods/vn-user/specs/sign-in.spec.js @@ -2,7 +2,7 @@ const {models} = require('vn-loopback/server/server'); describe('VnUser Sign-in()', () => { const employeeId = 1; - const unauthCtx = { + const unAuthCtx = { req: { headers: {}, connection: { @@ -15,7 +15,7 @@ describe('VnUser Sign-in()', () => { const {VnUser, AccessToken} = models; describe('when credentials are correct', () => { it('should return the token', async() => { - let login = await VnUser.signIn(unauthCtx, 'salesAssistant', 'nightmare'); + let login = await VnUser.signIn(unAuthCtx, 'salesAssistant', 'nightmare'); let accessToken = await AccessToken.findById(login.token); let ctx = {req: {accessToken: accessToken}}; @@ -25,7 +25,7 @@ describe('VnUser Sign-in()', () => { }); it('should return the token if the user doesnt exist but the client does', async() => { - let login = await VnUser.signIn(unauthCtx, 'PetterParker', 'nightmare'); + let login = await VnUser.signIn(unAuthCtx, 'PetterParker', 'nightmare'); let accessToken = await AccessToken.findById(login.token); let ctx = {req: {accessToken: accessToken}}; @@ -40,7 +40,7 @@ describe('VnUser Sign-in()', () => { let error; try { - await VnUser.signIn(unauthCtx, 'IDontExist', 'TotallyWrongPassword'); + await VnUser.signIn(unAuthCtx, 'IDontExist', 'TotallyWrongPassword'); } catch (e) { error = e; } @@ -61,7 +61,7 @@ describe('VnUser Sign-in()', () => { const options = {transaction: tx}; await employee.updateAttribute('twoFactor', 'email', options); - await VnUser.signIn(unauthCtx, 'employee', 'nightmare', options); + await VnUser.signIn(unAuthCtx, 'employee', 'nightmare', options); await tx.rollback(); } catch (e) { await tx.rollback(); @@ -86,7 +86,7 @@ describe('VnUser Sign-in()', () => { const options = {transaction: tx}; await employee.updateAttribute('passExpired', yesterday, options); - await VnUser.signIn(unauthCtx, 'employee', 'nightmare', options); + await VnUser.signIn(unAuthCtx, 'employee', 'nightmare', options); await tx.rollback(); } catch (e) { await tx.rollback(); diff --git a/modules/account/back/methods/account/specs/change-password.spec.js b/modules/account/back/methods/account/specs/change-password.spec.js index 2fa3010af..c79960212 100644 --- a/modules/account/back/methods/account/specs/change-password.spec.js +++ b/modules/account/back/methods/account/specs/change-password.spec.js @@ -2,7 +2,7 @@ const {models} = require('vn-loopback/server/server'); describe('account changePassword()', () => { const userId = 70; - const unauthCtx = { + const unAuthCtx = { req: { headers: {}, connection: { @@ -79,7 +79,7 @@ describe('account changePassword()', () => { passExpired: yesterday } , options); - await models.VnUser.signIn(unauthCtx, 'trainee', 'nightmare', options); + await models.VnUser.signIn(unAuthCtx, 'trainee', 'nightmare', options); } catch (e) { if (e.message != 'Pass expired') throw e; From 81be3b18f77be9062aed7d29811a8977d7a1b54d Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 27 Nov 2023 09:48:15 +0100 Subject: [PATCH 17/75] refs #6264 test: validate-token and renew-token --- back/methods/vn-user/is-token-valid.js | 5 ++- .../methods/vn-user/specs/renew-token.spec.js | 45 +++++++++++++++---- .../vn-user/specs/validate-token.spec.js | 38 +++++++++++++++- loopback/server/boot/date.js | 3 +- 4 files changed, 76 insertions(+), 15 deletions(-) diff --git a/back/methods/vn-user/is-token-valid.js b/back/methods/vn-user/is-token-valid.js index f4c2a9ea8..c5c05a178 100644 --- a/back/methods/vn-user/is-token-valid.js +++ b/back/methods/vn-user/is-token-valid.js @@ -2,8 +2,9 @@ const tokenConfig = require('./token-config'); module.exports = async token => { const accessTokenConfig = await tokenConfig(); - - const now = Date.vnNew(); + let now = Date.now(); + if (Date?.vnNow !== undefined) + now = Date.vnNow(); const differenceMilliseconds = now - token.created; const differenceSeconds = Math.floor(differenceMilliseconds / 1000); return differenceSeconds > accessTokenConfig.renewPeriod - accessTokenConfig.courtesyTime; diff --git a/back/methods/vn-user/specs/renew-token.spec.js b/back/methods/vn-user/specs/renew-token.spec.js index cae91f310..21d3de1a9 100644 --- a/back/methods/vn-user/specs/renew-token.spec.js +++ b/back/methods/vn-user/specs/renew-token.spec.js @@ -1,22 +1,49 @@ +const {models} = require('vn-loopback/server/server'); describe('Renew Token', () => { - it('Token is valid', async() => { - let login = await VnUser.signIn(unauthCtx, 'salesAssistant', 'nightmare'); - let accessToken = await AccessToken.findById(login.token); - let ctx = {req: {accessToken: accessToken}}; - - expect(login.token).toBeDefined(); + const startingTime = Date.now(); + let ctx = null; + beforeAll(async() => { + const unAuthCtx = { + req: { + headers: {}, + connection: { + remoteAddress: '127.0.0.1' + }, + getLocale: () => 'en' + }, + args: {} + }; + let login = await models.VnUser.signIn(unAuthCtx, 'salesAssistant', 'nightmare'); + let accessToken = await models.AccessToken.findById(login.token); + ctx = {req: {accessToken: accessToken}}; }); - it('Token is is invalid', async() => { + beforeEach(() => { + jasmine.clock().install(); + jasmine.clock().mockDate(new Date(startingTime)); + }); + + afterEach(() => { + jasmine.clock().uninstall(); + }); + + it('should renew process', async() => { + jasmine.clock().mockDate(new Date(startingTime + 21600000)); + const {id} = await models.VnUser.renewToken(ctx); + + expect(id).not.toEqual(ctx.req.accessToken.id); + }); + + it('NOT should renew', async() => { let error; try { - await models.VnUser.validateCode('developer', '123456'); + await models.VnUser.renewToken(ctx); } catch (e) { error = e; } expect(error).toBeDefined(); expect(error.statusCode).toBe(400); - expect(error.message).toEqual('Invalid or expired verification code'); + expect(error.message).toEqual('The renew period has not been exceeded'); }); }); diff --git a/back/methods/vn-user/specs/validate-token.spec.js b/back/methods/vn-user/specs/validate-token.spec.js index 0d0af689f..25207336d 100644 --- a/back/methods/vn-user/specs/validate-token.spec.js +++ b/back/methods/vn-user/specs/validate-token.spec.js @@ -1,9 +1,43 @@ -describe('Validate Token', () => { - it('Token is not expired', async() => { +const {models} = require('vn-loopback/server/server'); +describe('Validate Token', () => { + const startingTime = Date.now(); + let ctx = null; + beforeAll(async() => { + const unAuthCtx = { + req: { + headers: {}, + connection: { + remoteAddress: '127.0.0.1' + }, + getLocale: () => 'en' + }, + args: {} + }; + let login = await models.VnUser.signIn(unAuthCtx, 'salesAssistant', 'nightmare'); + let accessToken = await models.AccessToken.findById(login.token); + ctx = {req: {accessToken: accessToken}}; + }); + + beforeEach(() => { + jasmine.clock().install(); + jasmine.clock().mockDate(new Date(startingTime)); + }); + + afterEach(() => { + jasmine.clock().uninstall(); + }); + + it('Token is not expired', async() => { + jasmine.clock().mockDate(new Date(startingTime + 21600000)); + const isValid = await models.VnUser.validateToken(ctx.req.accessToken); + + expect(isValid).toBeTrue(); }); it('Token is expired', async() => { + const isValid = await models.VnUser.validateToken(ctx.req.accessToken); + expect(isValid).toBeFalse(); }); }); diff --git a/loopback/server/boot/date.js b/loopback/server/boot/date.js index 810745562..d592dc416 100644 --- a/loopback/server/boot/date.js +++ b/loopback/server/boot/date.js @@ -1,6 +1,5 @@ module.exports = () => { - Date.vnUTC = () => { - const env = process.env.NODE_ENV; + Date.vnUTC = (env = process.env.NODE_ENV) => { if (!env || env === 'development') return new Date(Date.UTC(2001, 0, 1, 11)); From 9da5fb9a14e739458f823290b1f1996ad7c1762a Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 27 Nov 2023 10:24:25 +0100 Subject: [PATCH 18/75] refs #6264 other: rename camel-case variable --- back/methods/vn-user/specs/sign-in.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/methods/vn-user/specs/sign-in.spec.js b/back/methods/vn-user/specs/sign-in.spec.js index 99d7b90f9..f800454aa 100644 --- a/back/methods/vn-user/specs/sign-in.spec.js +++ b/back/methods/vn-user/specs/sign-in.spec.js @@ -15,7 +15,7 @@ describe('VnUser Sign-in()', () => { const {VnUser, AccessToken, SignInLog} = models; describe('when credentials are correct', () => { it('should return the token if user uses email', async() => { - let login = await VnUser.signIn(unauthCtx, 'salesAssistant@mydomain.com', 'nightmare'); + let login = await VnUser.signIn(unAuthCtx, 'salesAssistant@mydomain.com', 'nightmare'); let accessToken = await AccessToken.findById(login.token); let ctx = {req: {accessToken: accessToken}}; let signInLog = await SignInLog.find({where: {token: accessToken.id}}); From 62fab4e74412ed9df395079ee92371deb48b8e1e Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 27 Nov 2023 11:52:37 +0100 Subject: [PATCH 19/75] refs #5854 itemShelving traducciones --- modules/item/back/locale/item-shelving/en.yml | 13 +++++++++++++ modules/item/back/locale/item-shelving/es.yml | 13 +++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 modules/item/back/locale/item-shelving/en.yml create mode 100644 modules/item/back/locale/item-shelving/es.yml diff --git a/modules/item/back/locale/item-shelving/en.yml b/modules/item/back/locale/item-shelving/en.yml new file mode 100644 index 000000000..062d4db3f --- /dev/null +++ b/modules/item/back/locale/item-shelving/en.yml @@ -0,0 +1,13 @@ +name: itemShelving +columns: + id: id + itemFk: itemFk + shelvingFk: shelvingFk + visible: visible + created: created + grouping: grouping + packing: packing + packagingFk: packagingFk + userFk: userFk + isChecked: isChecked + buyFk: buyFk diff --git a/modules/item/back/locale/item-shelving/es.yml b/modules/item/back/locale/item-shelving/es.yml new file mode 100644 index 000000000..a64b23bfa --- /dev/null +++ b/modules/item/back/locale/item-shelving/es.yml @@ -0,0 +1,13 @@ +name: artículo del carro +columns: + id: id + itemFk: artículo + shelvingFk: matrícula carro + visible: visible + created: creado + grouping: agrupación + packing: embalaje + packagingFk: paquete + userFk: usuario + isChecked: está revisado + buyFk: compra \ No newline at end of file From d4cd23853ffbd474ee7c55401437c47763a204ef Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 30 Nov 2023 07:32:16 +0100 Subject: [PATCH 20/75] refs #6264 perf: try to remove jasmine.clock() --- back/methods/vn-user/is-token-valid.js | 6 ++---- back/methods/vn-user/renew-token.js | 2 +- back/methods/vn-user/specs/validate-token.spec.js | 2 +- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/back/methods/vn-user/is-token-valid.js b/back/methods/vn-user/is-token-valid.js index c5c05a178..23b68797e 100644 --- a/back/methods/vn-user/is-token-valid.js +++ b/back/methods/vn-user/is-token-valid.js @@ -2,10 +2,8 @@ const tokenConfig = require('./token-config'); module.exports = async token => { const accessTokenConfig = await tokenConfig(); - let now = Date.now(); - if (Date?.vnNow !== undefined) - now = Date.vnNow(); + const now = Date.now(); const differenceMilliseconds = now - token.created; const differenceSeconds = Math.floor(differenceMilliseconds / 1000); - return differenceSeconds > accessTokenConfig.renewPeriod - accessTokenConfig.courtesyTime; + return differenceSeconds < accessTokenConfig.renewPeriod - accessTokenConfig.courtesyTime; }; diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index 4226886fc..cb88e665d 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -29,7 +29,7 @@ module.exports = Self => { // Check if current token is valid const isValid = await Self.validateToken(token); - if (!isValid) throw new UserError(`The renew period has not been exceeded`, 'periodNotExceeded'); + if (isValid) throw new UserError(`The renew period has not been exceeded`, 'periodNotExceeded'); const {courtesyTime} = await tokenConfig(); diff --git a/back/methods/vn-user/specs/validate-token.spec.js b/back/methods/vn-user/specs/validate-token.spec.js index 25207336d..ec254d0e5 100644 --- a/back/methods/vn-user/specs/validate-token.spec.js +++ b/back/methods/vn-user/specs/validate-token.spec.js @@ -29,13 +29,13 @@ describe('Validate Token', () => { }); it('Token is not expired', async() => { - jasmine.clock().mockDate(new Date(startingTime + 21600000)); const isValid = await models.VnUser.validateToken(ctx.req.accessToken); expect(isValid).toBeTrue(); }); it('Token is expired', async() => { + jasmine.clock().mockDate(new Date(startingTime + 21600000)); const isValid = await models.VnUser.validateToken(ctx.req.accessToken); expect(isValid).toBeFalse(); From b9671c0b67b6b4222b61598ac6a5ee2460a684f2 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 4 Dec 2023 14:44:50 +0100 Subject: [PATCH 21/75] refs #6264 perf: remove files related to token --- back/methods/vn-user/is-token-valid.js | 9 --------- back/methods/vn-user/token-config.js | 9 --------- 2 files changed, 18 deletions(-) delete mode 100644 back/methods/vn-user/is-token-valid.js delete mode 100644 back/methods/vn-user/token-config.js diff --git a/back/methods/vn-user/is-token-valid.js b/back/methods/vn-user/is-token-valid.js deleted file mode 100644 index 23b68797e..000000000 --- a/back/methods/vn-user/is-token-valid.js +++ /dev/null @@ -1,9 +0,0 @@ -const tokenConfig = require('./token-config'); - -module.exports = async token => { - const accessTokenConfig = await tokenConfig(); - const now = Date.now(); - const differenceMilliseconds = now - token.created; - const differenceSeconds = Math.floor(differenceMilliseconds / 1000); - return differenceSeconds < accessTokenConfig.renewPeriod - accessTokenConfig.courtesyTime; -}; diff --git a/back/methods/vn-user/token-config.js b/back/methods/vn-user/token-config.js deleted file mode 100644 index 0936e0b89..000000000 --- a/back/methods/vn-user/token-config.js +++ /dev/null @@ -1,9 +0,0 @@ -const DEFAULT_FIELDS = ['renewPeriod', 'courtesyTime']; -const {models} = require('vn-loopback/server/server'); -let currentAccessTokenConfig = null; -module.exports = async(fields = DEFAULT_FIELDS) => { - if (currentAccessTokenConfig) return currentAccessTokenConfig; - const accessTokenConfig = await models.AccessTokenConfig.findOne({fields}); - if (!accessTokenConfig) currentAccessTokenConfig = accessTokenConfig; - return accessTokenConfig; -}; From 5656ed7a2b29860b571125b46796abdd2d7609bd Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 4 Dec 2023 14:46:05 +0100 Subject: [PATCH 22/75] refs #6264 perf: use functions extracted previously --- back/methods/vn-user/renew-token.js | 5 +++-- back/methods/vn-user/validate-token.js | 10 +++++++--- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index cb88e665d..d5d22fd0d 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -1,5 +1,6 @@ const UserError = require('vn-loopback/util/user-error'); -const tokenConfig = require('./token-config'); +const {models} = require('vn-loopback/server/server'); + const DEFAULT_COURTESY_TIME = 60; const handlePromiseLogout = (Self, {id}, courtesyTime = DEFAULT_COURTESY_TIME) => { new Promise(res => { @@ -31,7 +32,7 @@ module.exports = Self => { const isValid = await Self.validateToken(token); if (isValid) throw new UserError(`The renew period has not been exceeded`, 'periodNotExceeded'); - const {courtesyTime} = await tokenConfig(); + const {courtesyTime} = await models.AccessTokenConfig.findOne({fields: ['renewPeriod', 'courtesyTime']}); // Schedule to remove current token handlePromiseLogout(Self, token, courtesyTime); diff --git a/back/methods/vn-user/validate-token.js b/back/methods/vn-user/validate-token.js index fadaed43b..ef3c5b212 100644 --- a/back/methods/vn-user/validate-token.js +++ b/back/methods/vn-user/validate-token.js @@ -1,5 +1,4 @@ -const isTokenValid = require('./is-token-valid'); - +const {models} = require('vn-loopback/server/server'); module.exports = Self => { Self.remoteMethod('validateToken', { description: 'Validates the current logged user token', @@ -14,7 +13,12 @@ module.exports = Self => { }); Self.validateToken = async function(token) { - const isValid = await isTokenValid(token); + const accessTokenConfig = await models.AccessTokenConfig.findOne({fields: ['renewPeriod', 'courtesyTime']}); + const now = Date.now(); + const differenceMilliseconds = now - token.created; + const differenceSeconds = Math.floor(differenceMilliseconds / 1000); + const isValid = differenceSeconds < accessTokenConfig.renewPeriod - accessTokenConfig.courtesyTime; + return isValid; }; }; From a5fb07bf127a81e2e9e80935e89ae8840b28babe Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 5 Dec 2023 13:05:26 +0100 Subject: [PATCH 23/75] refs #6264 perf remove unnecessary code --- loopback/server/middleware/current-user.js | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/loopback/server/middleware/current-user.js b/loopback/server/middleware/current-user.js index 8ff4bb618..b450f6bb1 100644 --- a/loopback/server/middleware/current-user.js +++ b/loopback/server/middleware/current-user.js @@ -1,16 +1,7 @@ -const {models} = require('vn-loopback/server/server'); - module.exports = function(options) { return async function(req, res, next) { - if (!req.accessToken) { - const token = req.headers.authorization; - if (!token) return next(); - - const accessToken = await models.AccessToken.findById(token); - if (!accessToken) return next(); - + if (!req.accessToken) return next(); - } let LoopBackContext = require('loopback-context'); let loopbackContext = LoopBackContext.getCurrentContext(); From c81ca94d2e5c8d7e1a5cb94e2d2da1c0f23dcdce Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 11 Dec 2023 14:44:33 +0100 Subject: [PATCH 24/75] refs #6220 add filter address --- modules/client/back/methods/client/filter.js | 56 +++++++++++++------- 1 file changed, 37 insertions(+), 19 deletions(-) diff --git a/modules/client/back/methods/client/filter.js b/modules/client/back/methods/client/filter.js index 47d5f6d2f..782d355ca 100644 --- a/modules/client/back/methods/client/filter.js +++ b/modules/client/back/methods/client/filter.js @@ -129,25 +129,43 @@ module.exports = Self => { const stmts = []; const stmt = new ParameterizedSQL( `SELECT - DISTINCT c.id, - c.name, - c.fi, - c.socialName, - c.phone, - c.mobile, - c.city, - c.postcode, - c.email, - c.isActive, - c.isFreezed, - p.id AS provinceFk, - p.name AS province, - u.id AS salesPersonFk, - u.name AS salesPerson - FROM client c - LEFT JOIN account.user u ON u.id = c.salesPersonFk - LEFT JOIN province p ON p.id = c.provinceFk - JOIN vn.address a ON a.clientFk = c.id + DISTINCT c.id, + c.name, + c.fi, + c.socialName, + c.phone, + c.mobile, + c.city, + c.postcode, + c.email, + c.isActive, + c.isFreezed, + p.id AS provinceFk, + p.name AS province, + u.id AS salesPersonFk, + u.name AS salesPerson, + a.street, + a.city AS addressCity, + a.provinceFk AS addressProvinceFk, + a.postalCode AS addressPostalCode, + a.phone AS addressPhone, + a.mobile AS addressMobile, + a.nickname, + a.isDefaultAddress, + a.agencyModeFk AS addressAgencyModeFk, + a.isActive AS addressIsActive, + a.longitude AS addressLongitude, + a.latitude AS addressLatitude, + a.isEqualizated, + a.customsAgentFk AS addressCustomsAgentFk, + a.incotermsFk AS addressIncotermsFk, + a.isLogifloraAllowed, + a.editorFk AS addressEditorFk + FROM client c + LEFT JOIN account.user u ON u.id = c.salesPersonFk + LEFT JOIN province p ON p.id = c.provinceFk + JOIN vn.address a ON a.clientFk = c.id; + ` ); From 7e6f311a431502c72abd7116a76518638bcc0160 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 11 Dec 2023 14:51:11 +0100 Subject: [PATCH 25/75] refs #6220 address filter --- modules/client/back/methods/client/filter.js | 32 ++++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/modules/client/back/methods/client/filter.js b/modules/client/back/methods/client/filter.js index 782d355ca..d88f15c3f 100644 --- a/modules/client/back/methods/client/filter.js +++ b/modules/client/back/methods/client/filter.js @@ -140,27 +140,27 @@ module.exports = Self => { c.email, c.isActive, c.isFreezed, - p.id AS provinceFk, - p.name AS province, - u.id AS salesPersonFk, - u.name AS salesPerson, + p.id, + p.name, + u.id, + u.name, a.street, - a.city AS addressCity, - a.provinceFk AS addressProvinceFk, - a.postalCode AS addressPostalCode, - a.phone AS addressPhone, - a.mobile AS addressMobile, + a.city, + a.provinceFk, + a.postalCode, + a.phone, + a.mobile, a.nickname, a.isDefaultAddress, - a.agencyModeFk AS addressAgencyModeFk, - a.isActive AS addressIsActive, - a.longitude AS addressLongitude, - a.latitude AS addressLatitude, + a.agencyModeFk, + a.isActive, + a.longitude, + a.latitude, a.isEqualizated, - a.customsAgentFk AS addressCustomsAgentFk, - a.incotermsFk AS addressIncotermsFk, + a.customsAgentFk, + a.incotermsFk, a.isLogifloraAllowed, - a.editorFk AS addressEditorFk + a.editorFk FROM client c LEFT JOIN account.user u ON u.id = c.salesPersonFk LEFT JOIN province p ON p.id = c.provinceFk From ae767762451137bb58fcaee927f8b401cfe18284 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 12 Dec 2023 12:09:06 +0100 Subject: [PATCH 26/75] refs #2051 feat: removeFile approach --- back/methods/dms/removeFile.js | 15 +++++++---- back/methods/dms/specs/removeFile.spec.js | 2 +- .../back/methods/claim-dms/removeFile.js | 16 ++++++------ .../claim-dms/specs/removeFile.spec.js | 3 ++- .../client-dms/specs/removeFile.spec.js | 3 ++- .../back/methods/ticket-dms/removeFile.js | 14 +++++------ .../ticket-dms/specs/removeFile.spec.js | 2 +- .../back/methods/worker-dms/removeFile.js | 25 ++++++++++++++++--- .../worker-dms/specs/removeFile.spec.js | 3 ++- 9 files changed, 54 insertions(+), 29 deletions(-) diff --git a/back/methods/dms/removeFile.js b/back/methods/dms/removeFile.js index a9ff36883..cb81ff322 100644 --- a/back/methods/dms/removeFile.js +++ b/back/methods/dms/removeFile.js @@ -34,20 +34,25 @@ module.exports = Self => { } try { - const dms = await models.Dms.findById(id, null, myOptions); + let modelDms = null; + if (myOptions.model) { + modelDms = await models[myOptions.model].findById(id, null, myOptions); + id = modelDms.dmsFk; + } + const targetDms = await models.Dms.findById(id, null, myOptions); const trashDmsType = await models.DmsType.findOne({ where: {code: 'trash'} }, myOptions); - const hasWriteRole = await models.DmsType.hasWriteRole(ctx, dms.dmsTypeFk, myOptions); + const hasWriteRole = await models.DmsType.hasWriteRole(ctx, targetDms.dmsTypeFk, myOptions); if (!hasWriteRole) throw new UserError(`You don't have enough privileges`); - await dms.updateAttribute('dmsTypeFk', trashDmsType.id, myOptions); + await targetDms.updateAttribute('dmsTypeFk', trashDmsType.id, myOptions); if (tx) await tx.commit(); - - return dms; + if (modelDms) modelDms.destroy(myOptions); + return targetDms; } catch (e) { if (tx) await tx.rollback(); throw e; diff --git a/back/methods/dms/specs/removeFile.spec.js b/back/methods/dms/specs/removeFile.spec.js index 59a2acecb..e0d1dc1e7 100644 --- a/back/methods/dms/specs/removeFile.spec.js +++ b/back/methods/dms/specs/removeFile.spec.js @@ -1,6 +1,6 @@ const {models} = require('vn-loopback/server/server'); -describe('dms removeFile()', () => { +fdescribe('dms removeFile()', () => { let dmsId = 1; it(`should return an error for a user without enough privileges`, async() => { diff --git a/modules/claim/back/methods/claim-dms/removeFile.js b/modules/claim/back/methods/claim-dms/removeFile.js index edc714235..257b09cf2 100644 --- a/modules/claim/back/methods/claim-dms/removeFile.js +++ b/modules/claim/back/methods/claim-dms/removeFile.js @@ -31,15 +31,15 @@ module.exports = Self => { } try { - const models = Self.app.models; - const targetClaimDms = await models.ClaimDms.findById(id, null, myOptions); - const targetDms = await models.Dms.findById(targetClaimDms.dmsFk, null, myOptions); - const trashDmsType = await models.DmsType.findOne({where: {code: 'trash'}}, myOptions); + // const {models: ClaimDms, Dms} = Self.app.models; + // const targetClaimDms = await ClaimDms.findById(id, null, myOptions); + // await Dms.findById(targetClaimDms.dmsFk, null, myOptions); + // const trashDmsType = await DmsType.findOne({where: {code: 'trash'}}, myOptions); + myOptions.model = 'ClaimDms'; + const targetDms = await Self.app.models.Dms.removeFile(ctx, id, myOptions); + // await targetClaimDms.destroy(myOptions); - await models.Dms.removeFile(ctx, targetClaimDms.dmsFk, myOptions); - await targetClaimDms.destroy(myOptions); - - await targetDms.updateAttribute('dmsTypeFk', trashDmsType.id, myOptions); + // await targetDms.updateAttribute('dmsTypeFk', trashDmsType.id, myOptions); if (tx) await tx.commit(); diff --git a/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js b/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js index 1cd3b16cb..210d805e7 100644 --- a/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js +++ b/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js @@ -1,6 +1,7 @@ const app = require('vn-loopback/server/server'); -describe('TicketDms removeFile()', () => { +// f +fdescribe('TicketDms removeFile()', () => { const ticketDmsId = 1; it(`should return an error for a user without enough privileges`, async() => { let clientId = 1101; diff --git a/modules/client/back/methods/client-dms/specs/removeFile.spec.js b/modules/client/back/methods/client-dms/specs/removeFile.spec.js index 6dac71293..61a00a610 100644 --- a/modules/client/back/methods/client-dms/specs/removeFile.spec.js +++ b/modules/client/back/methods/client-dms/specs/removeFile.spec.js @@ -1,6 +1,7 @@ const models = require('vn-loopback/server/server').models; -describe('ClientDms removeFile()', () => { +// f +fdescribe('ClientDms removeFile()', () => { it(`should return an error for a user without enough privileges`, async() => { const tx = await models.Client.beginTransaction({}); diff --git a/modules/ticket/back/methods/ticket-dms/removeFile.js b/modules/ticket/back/methods/ticket-dms/removeFile.js index f48dc7fef..2e3ccd149 100644 --- a/modules/ticket/back/methods/ticket-dms/removeFile.js +++ b/modules/ticket/back/methods/ticket-dms/removeFile.js @@ -19,7 +19,6 @@ module.exports = Self => { }); Self.removeFile = async(ctx, id, options) => { - const models = Self.app.models; const myOptions = {}; let tx; @@ -32,14 +31,15 @@ module.exports = Self => { } try { - const targetTicketDms = await models.TicketDms.findById(id, null, myOptions); - const targetDms = await models.Dms.findById(targetTicketDms.dmsFk, null, myOptions); - const trashDmsType = await models.DmsType.findOne({where: {code: 'trash'}}, myOptions); + // const targetTicketDms = await models.TicketDms.findById(id, null, myOptions); + myOptions.model = 'TicketDms'; + // await models.Dms.findById(targetTicketDms.dmsFk, null, myOptions); + // const trashDmsType = await models.DmsType.findOne({where: {code: 'trash'}}, myOptions); - await models.Dms.removeFile(ctx, targetTicketDms.dmsFk, myOptions); - await targetTicketDms.destroy(myOptions); + const targetDms = await Self.app.models.Dms.removeFile(ctx, id, myOptions); + // await targetTicketDms.destroy(myOptions); - await targetDms.updateAttribute('dmsTypeFk', trashDmsType.id, myOptions); + // await targetDms.updateAttribute('dmsTypeFk', trashDmsType.id, myOptions); if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/ticket-dms/specs/removeFile.spec.js b/modules/ticket/back/methods/ticket-dms/specs/removeFile.spec.js index 9296984c3..ca4cb5bc3 100644 --- a/modules/ticket/back/methods/ticket-dms/specs/removeFile.spec.js +++ b/modules/ticket/back/methods/ticket-dms/specs/removeFile.spec.js @@ -1,6 +1,6 @@ const models = require('vn-loopback/server/server').models; -describe('TicketDms removeFile()', () => { +fdescribe('TicketDms removeFile()', () => { const ticketDmsId = 1; it(`should return an error for a user without enough privileges`, async() => { const tx = await models.TicketDms.beginTransaction({}); diff --git a/modules/worker/back/methods/worker-dms/removeFile.js b/modules/worker/back/methods/worker-dms/removeFile.js index b441c56ce..397255bb2 100644 --- a/modules/worker/back/methods/worker-dms/removeFile.js +++ b/modules/worker/back/methods/worker-dms/removeFile.js @@ -18,13 +18,30 @@ module.exports = Self => { } }); - Self.removeFile = async(ctx, id) => { + Self.removeFile = async(ctx, id, options) => { const models = Self.app.models; - const workerDms = await Self.findById(id); + let tx; + try { + const myOptions = {}; - await models.Dms.removeFile(ctx, workerDms.dmsFk); + if (typeof options == 'object') + Object.assign(myOptions, options); - return workerDms.destroy(); + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + // const workerDms = await Self.findById(id); + myOptions.model = 'WorkerDms'; + await models.Dms.removeFile(ctx, id, myOptions); + // await workerDms.destroy(); + if (tx) await tx.commit(); + + return workerDms; + } catch (e) { + await tx.rollback(); + throw e; + } }; }; diff --git a/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js b/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js index 3efd09464..e66628656 100644 --- a/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js +++ b/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js @@ -1,6 +1,7 @@ const app = require('vn-loopback/server/server'); -describe('WorkerDms removeFile()', () => { +// f +fdescribe('WorkerDms removeFile()', () => { const workerDmsFk = 1; it(`should return an error for a user without enough privileges`, async() => { let clientId = 1101; From 6cefc982e46261dd680e7e1d5797a2d2ffd1daa9 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 12 Dec 2023 13:14:41 +0100 Subject: [PATCH 27/75] refs #6220 add filter address --- modules/client/back/methods/client/filter.js | 81 ++++++++++---------- 1 file changed, 39 insertions(+), 42 deletions(-) diff --git a/modules/client/back/methods/client/filter.js b/modules/client/back/methods/client/filter.js index d88f15c3f..43310c86b 100644 --- a/modules/client/back/methods/client/filter.js +++ b/modules/client/back/methods/client/filter.js @@ -107,17 +107,29 @@ module.exports = Self => { return {or: [ {'c.phone': {like: `%${value}%`}}, {'c.mobile': {like: `%${value}%`}}, + {'a.phone': {like: `%${value}%`}}, ]}; case 'zoneFk': - param = 'a.postalCode'; - return {[param]: {inq: postalCode}}; + return {'a.postalCode': {inq: postalCode}}; + case 'city': + return {or: [ + {'c.city': {like: `%${value}`}}, + {'a.city': {like: `%${value}`}} + ]}; + case 'postcode': + return {or: [ + {'c.postcode': {like: `%${value}`}}, + {'a.postalCode': {like: `%${value}`}} + ]}; + case 'provinceFk': + return {or: [ + {'p.name': {like: `%${value}`}}, + {'a.provinceFk': {like: `%${value}`}} + ]}; case 'name': case 'salesPersonFk': case 'fi': case 'socialName': - case 'city': - case 'postcode': - case 'provinceFk': case 'email': param = `c.${param}`; return {[param]: {like: `%${value}%`}}; @@ -129,47 +141,32 @@ module.exports = Self => { const stmts = []; const stmt = new ParameterizedSQL( `SELECT - DISTINCT c.id, - c.name, - c.fi, - c.socialName, - c.phone, - c.mobile, - c.city, - c.postcode, - c.email, - c.isActive, - c.isFreezed, - p.id, - p.name, - u.id, - u.name, - a.street, - a.city, - a.provinceFk, - a.postalCode, - a.phone, - a.mobile, - a.nickname, - a.isDefaultAddress, - a.agencyModeFk, - a.isActive, - a.longitude, - a.latitude, - a.isEqualizated, - a.customsAgentFk, - a.incotermsFk, - a.isLogifloraAllowed, - a.editorFk - FROM client c - LEFT JOIN account.user u ON u.id = c.salesPersonFk - LEFT JOIN province p ON p.id = c.provinceFk - JOIN vn.address a ON a.clientFk = c.id; - + DISTINCT c.id, + c.name, + c.fi, + c.socialName, + CONCAT(c.phone, ',',GROUP_CONCAT(DISTINCT a.phone)) phone, + c.mobile, + CONCAT(c.city, ',',GROUP_CONCAT(DISTINCT a.city)) city, + c.postcode, + a.postalCode, + c.email, + c.isActive, + c.isFreezed, + p.id AS provinceFk2, + a.provinceFk, + p.name AS province, + u.id AS salesPersonFk, + u.name AS salesPerson + FROM client c + LEFT JOIN account.user u ON u.id = c.salesPersonFk + LEFT JOIN province p ON p.id = c.provinceFk + JOIN address a ON a.clientFk = c.id ` ); stmt.merge(conn.makeWhere(filter.where)); + stmt.merge('GROUP BY c.id'); stmt.merge(conn.makePagination(filter)); const clientsIndex = stmts.push(stmt) - 1; From 78aa25d74fe7b34c58d9dc0224db3b47312a73d0 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 12 Dec 2023 13:21:08 +0100 Subject: [PATCH 28/75] refs #6220 fix testback --- modules/client/back/methods/client/specs/filter.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/client/back/methods/client/specs/filter.spec.js b/modules/client/back/methods/client/specs/filter.spec.js index 679585050..4a61f8aaf 100644 --- a/modules/client/back/methods/client/specs/filter.spec.js +++ b/modules/client/back/methods/client/specs/filter.spec.js @@ -146,7 +146,7 @@ describe('client filter()', () => { const randomResultClient = result[randomIndex]; expect(result.length).toBeGreaterThanOrEqual(20); - expect(randomResultClient.city.toLowerCase()).toEqual('gotham'); + expect(randomResultClient.city.toLowerCase()).toEqual('gotham,gotham'); await tx.rollback(); } catch (e) { From 6b70f8b3eb0c5d5111adf0df1f2af77dc1083382 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 12 Dec 2023 13:49:14 +0100 Subject: [PATCH 29/75] refs #2051 feat: uploadFile approach --- .../claim/back/methods/claim/uploadFile.js | 116 +++++++----------- .../client/back/methods/client/uploadFile.js | 24 ++-- .../methods/ticket/specs/uploadFile.spec.js | 27 +++- .../ticket/back/methods/ticket/uploadFile.js | 10 +- .../methods/worker/specs/uploadFile.spec.js | 4 +- .../worker/back/methods/worker/uploadFile.js | 32 +++-- 6 files changed, 113 insertions(+), 100 deletions(-) diff --git a/modules/claim/back/methods/claim/uploadFile.js b/modules/claim/back/methods/claim/uploadFile.js index 3d0737cf8..7e4798fef 100644 --- a/modules/claim/back/methods/claim/uploadFile.js +++ b/modules/claim/back/methods/claim/uploadFile.js @@ -1,6 +1,3 @@ -const UserError = require('vn-loopback/util/user-error'); -const fs = require('fs-extra'); -const path = require('path'); module.exports = Self => { Self.remoteMethodCtx('uploadFile', { @@ -57,96 +54,75 @@ module.exports = Self => { }); Self.uploadFile = async(ctx, id, options) => { - const tx = await Self.beginTransaction({}); + const models = Self.app.models; const myOptions = {}; + let tx; if (typeof options == 'object') Object.assign(myOptions, options); - if (!myOptions.transaction) + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); myOptions.transaction = tx; + } - const models = Self.app.models; - const promises = []; - const TempContainer = models.TempContainer; - const ClaimContainer = models.ClaimContainer; - const fileOptions = {}; - const args = ctx.args; + // const promises = []; + // const TempContainer = models.TempContainer; + // const ClaimContainer = models.ClaimContainer; + // const fileOptions = {}; + // const args = ctx.args; - let srcFile; + // let srcFile; try { - const hasWriteRole = await models.DmsType.hasWriteRole(ctx, args.dmsTypeId, myOptions); - if (!hasWriteRole) - throw new UserError(`You don't have enough privileges`); + myOptions.model = 'ClaimDms'; + myOptions.create = {claimFk: id}; + const uploadedFiles = await models.Dms.uploadFile(ctx, myOptions); - // Upload file to temporary path - const tempContainer = await TempContainer.container('dms'); - const uploaded = await TempContainer.upload(tempContainer.name, ctx.req, ctx.result, fileOptions); - const files = Object.values(uploaded.files).map(file => { - return file[0]; - }); + // const hasWriteRole = await models.DmsType.hasWriteRole(ctx, args.dmsTypeId, myOptions); + // if (!hasWriteRole) + // throw new UserError(`You don't have enough privileges`); - const addedDms = []; - for (const uploadedFile of files) { - const newDms = await createDms(ctx, uploadedFile, myOptions); - const pathHash = ClaimContainer.getHash(newDms.id); + // // Upload file to temporary path + // const tempContainer = await TempContainer.container('dms'); + // const uploaded = await TempContainer.upload(tempContainer.name, ctx.req, ctx.result, fileOptions); + // const files = Object.values(uploaded.files).map(file => { + // return file[0]; + // }); - const file = await TempContainer.getFile(tempContainer.name, uploadedFile.name); - srcFile = path.join(file.client.root, file.container, file.name); + // const addedDms = []; + // for (const uploadedFile of files) { + // const newDms = await createDms(ctx, uploadedFile, myOptions); + // const pathHash = ClaimContainer.getHash(newDms.id); - const claimContainer = await ClaimContainer.container(pathHash); - const dstFile = path.join(claimContainer.client.root, pathHash, newDms.file); + // const file = await TempContainer.getFile(tempContainer.name, uploadedFile.name); + // srcFile = path.join(file.client.root, file.container, file.name); - await fs.move(srcFile, dstFile, { - overwrite: true - }); + // const claimContainer = await ClaimContainer.container(pathHash); + // const dstFile = path.join(claimContainer.client.root, pathHash, newDms.file); - addedDms.push(newDms); - } + // await fs.move(srcFile, dstFile, { + // overwrite: true + // }); - addedDms.forEach(dms => { - const newClaimDms = models.ClaimDms.create({ - claimFk: id, - dmsFk: dms.id - }, myOptions); + // addedDms.push(newDms); + // } - promises.push(newClaimDms); - }); - const resolvedPromises = await Promise.all(promises); + // addedDms.forEach(dms => { + // const newClaimDms = models.ClaimDms.create({ + // claimFk: id, + // dmsFk: dms.id + // }, myOptions); + + // promises.push(newClaimDms); + // }); + // const resolvedPromises = await Promise.all(promises); if (tx) await tx.commit(); - return resolvedPromises; + return uploadedFiles; } catch (e) { if (tx) await tx.rollback(); - - if (fs.existsSync(srcFile)) - await fs.unlink(srcFile); - throw e; } }; - - async function createDms(ctx, file, myOptions) { - const models = Self.app.models; - const myUserId = ctx.req.accessToken.userId; - const args = ctx.args; - - const newDms = await models.Dms.create({ - workerFk: myUserId, - dmsTypeFk: args.dmsTypeId, - companyFk: args.companyId, - warehouseFk: args.warehouseId, - reference: args.reference, - description: args.description, - contentType: file.type, - hasFile: args.hasFile - }, myOptions); - - let fileName = file.name; - const extension = models.DmsContainer.getFileExtension(fileName); - fileName = `${newDms.id}.${extension}`; - - return newDms.updateAttribute('file', fileName, myOptions); - } }; diff --git a/modules/client/back/methods/client/uploadFile.js b/modules/client/back/methods/client/uploadFile.js index 99ede27c6..8f471f1b6 100644 --- a/modules/client/back/methods/client/uploadFile.js +++ b/modules/client/back/methods/client/uploadFile.js @@ -56,8 +56,8 @@ module.exports = Self => { Self.uploadFile = async(ctx, id, options) => { const models = Self.app.models; - let tx; const myOptions = {}; + let tx; if (typeof options == 'object') Object.assign(myOptions, options); @@ -67,23 +67,25 @@ module.exports = Self => { myOptions.transaction = tx; } - const promises = []; + // const promises = []; try { + myOptions.model = 'ClientDms'; + myOptions.create = {clientFk: id}; const uploadedFiles = await models.Dms.uploadFile(ctx, myOptions); - uploadedFiles.forEach(dms => { - const newClientDms = models.ClientDms.create({ - clientFk: id, - dmsFk: dms.id - }, myOptions); + // uploadedFiles.forEach(dms => { + // const newClientDms = models.ClientDms.create({ + // clientFk: id, + // dmsFk: dms.id + // }, myOptions); - promises.push(newClientDms); - }); - const resolvedPromises = await Promise.all(promises); + // promises.push(newClientDms); + // }); + // const resolvedPromises = await Promise.all(promises); if (tx) await tx.commit(); - return resolvedPromises; + return uploadedFiles; } catch (e) { if (tx) await tx.rollback(); throw e; diff --git a/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js b/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js index 133c13265..8c01133e6 100644 --- a/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js +++ b/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js @@ -1,6 +1,6 @@ const models = require('vn-loopback/server/server').models; - -describe('Ticket uploadFile()', () => { +// f +fdescribe('Ticket uploadFile()', () => { it(`should return an error for a user without enough privileges`, async() => { const tx = await models.Ticket.beginTransaction({}); @@ -23,4 +23,27 @@ describe('Ticket uploadFile()', () => { expect(error.message).toEqual(`You don't have enough privileges`); }); + + // fit(`should uploadFile`, async() => { + // const tx = await models.Ticket.beginTransaction({}); + + // let error; + // try { + // const options = {transaction: tx}; + + // const ticketId = 15; + // const currentUserId = 9; + // const ticketTypeId = 14; + // const ctx = {req: {accessToken: {userId: currentUserId}}, args: {dmsTypeId: ticketTypeId}, result: new ArrayBuffer(20000)}; + + // await models.Ticket.uploadFile(ctx, ticketId, options); + + // await tx.rollback(); + // } catch (e) { + // await tx.rollback(); + // error = e; + // } + + // expect(error.message).toEqual(`You don't have enough privileges`); + // }); }); diff --git a/modules/ticket/back/methods/ticket/uploadFile.js b/modules/ticket/back/methods/ticket/uploadFile.js index 4de9904e1..63bbe845a 100644 --- a/modules/ticket/back/methods/ticket/uploadFile.js +++ b/modules/ticket/back/methods/ticket/uploadFile.js @@ -59,10 +59,12 @@ module.exports = Self => { myOptions.transaction = tx; } - const promises = []; + // const promises = []; try { + myOptions.model = 'TicketDms'; + myOptions.create = {ticketFk: id}; const uploadedFiles = await models.Dms.uploadFile(ctx, myOptions); - uploadedFiles.forEach(dms => { + /* uploadedFiles.forEach(dms => { const newTicketDms = models.TicketDms.create({ ticketFk: id, dmsFk: dms.id @@ -71,10 +73,10 @@ module.exports = Self => { promises.push(newTicketDms); }); const resolvedPromises = await Promise.all(promises); - +*/ if (tx) await tx.commit(); - return resolvedPromises; + return uploadedFiles; } catch (e) { if (tx) await tx.rollback(); throw e; diff --git a/modules/worker/back/methods/worker/specs/uploadFile.spec.js b/modules/worker/back/methods/worker/specs/uploadFile.spec.js index 7a929cd2b..34426c6a0 100644 --- a/modules/worker/back/methods/worker/specs/uploadFile.spec.js +++ b/modules/worker/back/methods/worker/specs/uploadFile.spec.js @@ -1,6 +1,6 @@ const app = require('vn-loopback/server/server'); - -describe('Worker uploadFile()', () => { +// f +fdescribe('Worker uploadFile()', () => { it(`should return an error for a user without enough privileges`, async() => { let workerId = 1106; let currentUserId = 1102; diff --git a/modules/worker/back/methods/worker/uploadFile.js b/modules/worker/back/methods/worker/uploadFile.js index 588cfe4bd..e624dc904 100644 --- a/modules/worker/back/methods/worker/uploadFile.js +++ b/modules/worker/back/methods/worker/uploadFile.js @@ -48,14 +48,24 @@ module.exports = Self => { Self.uploadFile = async(ctx, id) => { const models = Self.app.models; - const promises = []; - const tx = await Self.beginTransaction({}); + const myOptions = {}; + let tx; + // const promises = []; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } try { - const options = {transaction: tx}; + myOptions.model = 'WorkerDms'; + myOptions.create = {workerFk: id}; - const uploadedFiles = await models.Dms.uploadFile(ctx, options); - uploadedFiles.forEach(dms => { + const uploadedFiles = await models.Dms.uploadFile(ctx, myOptions); + /* uploadedFiles.forEach(dms => { const newWorkerDms = models.WorkerDms.create({ workerFk: id, dmsFk: dms.id @@ -64,13 +74,13 @@ module.exports = Self => { promises.push(newWorkerDms); }); const resolvedPromises = await Promise.all(promises); +*/ + if (tx) await tx.commit(); - await tx.commit(); - - return resolvedPromises; - } catch (err) { - await tx.rollback(); - throw err; + return uploadedFiles; + } catch (e) { + if (tx) await tx.rollback(); + throw e; } }; }; From 6334431d2b01ba0bbfc559ac69c30719e8d48c10 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 12 Dec 2023 14:00:35 +0100 Subject: [PATCH 30/75] refs #2051 feat: uploadFile approach --- back/methods/dms/uploadFile.js | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/back/methods/dms/uploadFile.js b/back/methods/dms/uploadFile.js index a4212b804..abed95a3a 100644 --- a/back/methods/dms/uploadFile.js +++ b/back/methods/dms/uploadFile.js @@ -96,8 +96,21 @@ module.exports = Self => { } if (tx) await tx.commit(); + const promises = []; + const {model, create} = myOptions; + addedDms.forEach(dms => { + const newDms = models[model].create({ + ...create, + dmsFk: dms.id + }, myOptions); - return addedDms; + promises.push(newDms); + }); + const resolvedPromises = await Promise.all(promises); + + // if (tx) await tx.commit(); + + return resolvedPromises; } catch (e) { if (tx) await tx.rollback(); From 412cac7e94114a891fc66111133de27eb29e8e40 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 12 Dec 2023 14:42:36 +0100 Subject: [PATCH 31/75] refs #5925 models table docuware --- back/methods/docuware/upload.js | 5 +++++ back/models/docuwareTablet.json | 20 ++++++++++++++++++++ back/models/user-config.json | 10 +++++++++- db/changes/235201/00-tabletDocuware.sql | 24 ++++++++++++++++++++++++ 4 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 back/models/docuwareTablet.json create mode 100644 db/changes/235201/00-tabletDocuware.sql diff --git a/back/methods/docuware/upload.js b/back/methods/docuware/upload.js index 7055bf8d5..a587079a2 100644 --- a/back/methods/docuware/upload.js +++ b/back/methods/docuware/upload.js @@ -103,6 +103,11 @@ module.exports = Self => { 'FieldName': 'FILTRO_TABLET', 'ItemElementName': 'string', 'Item': 'Tablet1', + }, + { + 'FieldName': 'ID_TABLET', + 'ItemElementName': 'integer', + 'Item': userConfig.tabletFk, } ] }; diff --git a/back/models/docuwareTablet.json b/back/models/docuwareTablet.json new file mode 100644 index 000000000..dde336bca --- /dev/null +++ b/back/models/docuwareTablet.json @@ -0,0 +1,20 @@ +{ + "name": "docuwareTablet", + "base": "VnModel", + "options": { + "mysql": { + "table": "vn.docuwareTablet" + } + }, + "properties": { + "id": { + "type": "number" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string" + } + } +} diff --git a/back/models/user-config.json b/back/models/user-config.json index 52125dc01..35f6aa1e6 100644 --- a/back/models/user-config.json +++ b/back/models/user-config.json @@ -26,6 +26,9 @@ }, "darkMode": { "type": "boolean" + }, + "tabletFk": { + "type": "number" } }, "relations": { @@ -43,6 +46,11 @@ "type": "belongsTo", "model": "VnUser", "foreignKey": "userFk" - } + }, + "Tablet": { + "type": "belongsTo", + "model": "docuwareTablet", + "foreignKey": "tabletFk" + } } } diff --git a/db/changes/235201/00-tabletDocuware.sql b/db/changes/235201/00-tabletDocuware.sql new file mode 100644 index 000000000..c480c1001 --- /dev/null +++ b/db/changes/235201/00-tabletDocuware.sql @@ -0,0 +1,24 @@ +-- vn.docuwareTablet definition + +CREATE TABLE `vn`.`docuwareTablet` ( + `id` int(3) NOT NULL AUTO_INCREMENT, + `name` varchar(100) NOT NULL, + `description` varchar(255) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +-- Auto-generated SQL script. Actual values for binary/complex data types may differ - what you see is the default string representation of values. +INSERT INTO `vn`.`docuwareTablet` (`id`,`name`,`description`) + VALUES (1,'tabletRRHH','tablet de recursos humanos'); +INSERT INTO `vn`.`docuwareTablet` (`id`,`name`,`description`) + VALUES (2,'tabletIT','tablet de IT'); +INSERT INTO `vn`.`docuwareTablet` (`id`,`name`,`description`) + VALUES (3,'tabletCompradores','tablet de compradores'); +INSERT INTO `vn`.`docuwareTablet` (`id`,`name`,`description`) + VALUES (4,'tabletComerciales','tablet de comerciales'); +INSERT INTO `vn`.`docuwareTablet` (`id`,`name`,`description`) + VALUES (5,'tabletAdministracion','tablet de administracion'); + +ALTER TABLE `vn`.`userConfig` +ADD COLUMN tabletFk int(3), +ADD FOREIGN KEY (tabletFk) REFERENCES `vn`.`docuwareTablet`(id); From d206c93305e490024b12751d90fcd335668dafdb Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 12 Dec 2023 15:03:00 +0100 Subject: [PATCH 32/75] refs #2051 feat: getAllowedContentTypes approach --- front/salix/components/index.js | 1 + front/salix/components/section-dms/index.js | 24 +++++++++ front/salix/components/section-dms/style.scss | 0 modules/client/front/dms/create/index.js | 54 ++++++++----------- modules/client/front/dms/edit/index.js | 41 ++++++-------- modules/invoiceIn/front/basic-data/index.js | 15 ++---- .../agency-term/createInvoiceIn/index.js | 45 ++++++---------- modules/ticket/front/dms/create/index.js | 53 ++++++++---------- modules/ticket/front/dms/edit/index.js | 41 ++++++-------- .../travel/front/thermograph/create/index.js | 8 +-- .../travel/front/thermograph/edit/index.js | 13 ++--- modules/worker/front/dms/create/index.js | 11 ++-- modules/worker/front/dms/edit/index.js | 42 ++++++--------- 13 files changed, 142 insertions(+), 206 deletions(-) create mode 100644 front/salix/components/section-dms/index.js create mode 100644 front/salix/components/section-dms/style.scss diff --git a/front/salix/components/index.js b/front/salix/components/index.js index 38b0d0e1f..e843f2f5e 100644 --- a/front/salix/components/index.js +++ b/front/salix/components/index.js @@ -15,6 +15,7 @@ import './module-card'; import './module-main'; import './side-menu/side-menu'; import './section'; +import './section-dms'; import './summary'; import './topbar/topbar'; import './user-popover'; diff --git a/front/salix/components/section-dms/index.js b/front/salix/components/section-dms/index.js new file mode 100644 index 000000000..ae7d496cd --- /dev/null +++ b/front/salix/components/section-dms/index.js @@ -0,0 +1,24 @@ +import ngModule from '../../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +export default class SectionDms extends Component { + getAllowedContentTypes() { + return this.$http.get('DmsContainers/allowedContentTypes').then(res => { + const contentTypes = res.data.join(', '); + this.allowedContentTypes = contentTypes; + return contentTypes; + }); + } + + getDms(dmsId) { + return this.$http.get(`Dms/${dmsId}`).then(res => res); + } + getDmsTypes(params) { + return this.$http.get('DmsTypes/findOne', params).then(res => res); + } +} + +ngModule.vnComponent('vnSectionDms', { + controller: SectionDms +}); diff --git a/front/salix/components/section-dms/style.scss b/front/salix/components/section-dms/style.scss new file mode 100644 index 000000000..e69de29bb diff --git a/modules/client/front/dms/create/index.js b/modules/client/front/dms/create/index.js index 461d0aa36..ec8837981 100644 --- a/modules/client/front/dms/create/index.js +++ b/modules/client/front/dms/create/index.js @@ -1,8 +1,8 @@ import ngModule from '../../module'; -import Section from 'salix/components/section'; +import SectionDms from 'salix/components/section-dms'; import './style.scss'; -class Controller extends Section { +class Controller extends SectionDms { constructor($element, $) { super($element, $); this.dms = { @@ -20,46 +20,36 @@ class Controller extends Section { this._client = value; if (value) { - this.setDefaultParams(); - this.getAllowedContentTypes(); + const params = {filter: { + where: {code: 'paymentsLaw'} + }}; + this.getDmsTypes(params).then(res => this.handleDefaultParams(res)); + this.getAllowedContentTypes().then(data => this.allowedContentTypes = data); } } - getAllowedContentTypes() { - this.$http.get('DmsContainers/allowedContentTypes').then(res => { - const contentTypes = res.data.join(', '); - this.allowedContentTypes = contentTypes; - }); - } - get contentTypesInfo() { return this.$t('ContentTypesInfo', { allowedContentTypes: this.allowedContentTypes }); } - setDefaultParams() { - const params = {filter: { - where: {code: 'paymentsLaw'} - }}; - this.$http.get('DmsTypes/findOne', {params}).then(res => { - const dmsType = res.data && res.data; - const companyId = this.vnConfig.companyFk; - const warehouseId = this.vnConfig.warehouseFk; - const defaultParams = { - reference: this.client.id, - warehouseId: warehouseId, - companyId: companyId, - dmsTypeId: dmsType.id, - description: this.$t('ClientFileDescription', { - dmsTypeName: dmsType.name, - clientId: this.client.id, - clientName: this.client.name - }).toUpperCase() - }; + handleDefaultParams({data: dmsType}) { + const companyId = this.vnConfig.companyFk; + const warehouseId = this.vnConfig.warehouseFk; + const defaultParams = { + reference: this.client.id, + warehouseId: warehouseId, + companyId: companyId, + dmsTypeId: dmsType.id, + description: this.$t('ClientFileDescription', { + dmsTypeName: dmsType.name, + clientId: this.client.id, + clientName: this.client.name + }).toUpperCase() + }; - this.dms = Object.assign(this.dms, defaultParams); - }); + this.dms = Object.assign(this.dms, defaultParams); } onSubmit() { diff --git a/modules/client/front/dms/edit/index.js b/modules/client/front/dms/edit/index.js index 8765eeff2..36c1a9672 100644 --- a/modules/client/front/dms/edit/index.js +++ b/modules/client/front/dms/edit/index.js @@ -1,8 +1,8 @@ import ngModule from '../../module'; -import Section from 'salix/components/section'; +import SectionDms from 'salix/components/section-dms'; import './style.scss'; -class Controller extends Section { +class Controller extends SectionDms { get client() { return this._client; } @@ -11,39 +11,28 @@ class Controller extends Section { this._client = value; if (value) { - this.setDefaultParams(); - this.getAllowedContentTypes(); + this.getDms(this.$params.dmsId).then(handleDefaultParams); + this.getAllowedContentTypes().then(data => this.allowedContentTypes = data); } } - getAllowedContentTypes() { - this.$http.get('DmsContainers/allowedContentTypes').then(res => { - const contentTypes = res.data.join(', '); - this.allowedContentTypes = contentTypes; - }); - } - get contentTypesInfo() { return this.$t('ContentTypesInfo', { allowedContentTypes: this.allowedContentTypes }); } - setDefaultParams() { - const path = `Dms/${this.$params.dmsId}`; - this.$http.get(path).then(res => { - const dms = res.data && res.data; - this.dms = { - reference: dms.reference, - warehouseId: dms.warehouseFk, - companyId: dms.companyFk, - dmsTypeId: dms.dmsTypeFk, - description: dms.description, - hasFile: dms.hasFile, - hasFileAttached: false, - files: [] - }; - }); + handleDefaultParams({data: dms}) { + this.dms = { + reference: dms.reference, + warehouseId: dms.warehouseFk, + companyId: dms.companyFk, + dmsTypeId: dms.dmsTypeFk, + description: dms.description, + hasFile: dms.hasFile, + hasFileAttached: false, + files: [] + }; } onSubmit() { diff --git a/modules/invoiceIn/front/basic-data/index.js b/modules/invoiceIn/front/basic-data/index.js index 246f1b16f..797fda59d 100644 --- a/modules/invoiceIn/front/basic-data/index.js +++ b/modules/invoiceIn/front/basic-data/index.js @@ -1,8 +1,8 @@ import ngModule from '../module'; -import Section from 'salix/components/section'; +import SectionDms from 'salix/components/section-dms'; import UserError from 'core/lib/user-error'; -class Controller extends Section { +class Controller extends SectionDms { constructor($element, $, vnFile) { super($element, $, vnFile); this.dms = { @@ -11,7 +11,7 @@ class Controller extends Section { hasFileAttached: false }; this.vnFile = vnFile; - this.getAllowedContentTypes(); + this.getAllowedContentTypes().then(data => this.allowedContentTypes = data); this._editDownloadDisabled = false; } @@ -53,15 +53,6 @@ class Controller extends Section { }); } - getAllowedContentTypes() { - this.$http.get('DmsContainers/allowedContentTypes').then(res => { - if (res.data.length > 0) { - const contentTypes = res.data.join(', '); - this.allowedContentTypes = contentTypes; - } - }); - } - openEditDialog(dmsId) { this.getFile(dmsId).then(() => this.$.dmsEditDialog.show()); } diff --git a/modules/route/front/agency-term/createInvoiceIn/index.js b/modules/route/front/agency-term/createInvoiceIn/index.js index 0198ab80f..5e54f7929 100644 --- a/modules/route/front/agency-term/createInvoiceIn/index.js +++ b/modules/route/front/agency-term/createInvoiceIn/index.js @@ -1,9 +1,9 @@ import ngModule from '../../module'; -import Section from 'salix/components/section'; +import SectionDms from 'salix/components/section-dms'; import './style.scss'; import UserError from 'core/lib/user-error'; -class Controller extends Section { +class Controller extends SectionDms { constructor($element, $) { super($element, $); this.dms = { @@ -19,9 +19,11 @@ class Controller extends Section { set route(value) { this._route = value; - - this.setDefaultParams(); - this.getAllowedContentTypes(); + const params = {filter: { + where: {code: 'invoiceIn'} + }}; + this.getDmsTypes(params).then(res => this.handleDefaultParams(res)); + this.getAllowedContentTypes().then(data => this.allowedContentTypes = data); } $onChanges() { @@ -29,36 +31,23 @@ class Controller extends Section { this.params = JSON.parse(this.$params.q); } - getAllowedContentTypes() { - this.$http.get('DmsContainers/allowedContentTypes').then(res => { - const contentTypes = res.data.join(', '); - this.allowedContentTypes = contentTypes; - }); - } - get contentTypesInfo() { return this.$t('ContentTypesInfo', { allowedContentTypes: this.allowedContentTypes }); } - setDefaultParams() { - const params = {filter: { - where: {code: 'invoiceIn'} - }}; - this.$http.get('DmsTypes/findOne', {params}).then(res => { - const dmsType = res.data && res.data; - const companyId = this.vnConfig.companyFk; - const warehouseId = this.vnConfig.warehouseFk; - const defaultParams = { - warehouseId: warehouseId, - companyId: companyId, - dmsTypeId: dmsType.id, - description: this.params.supplierName - }; + handleDefaultParams({data: dmsType}) { + const companyId = this.vnConfig.companyFk; + const warehouseId = this.vnConfig.warehouseFk; + const defaultParams = { + warehouseId: warehouseId, + companyId: companyId, + dmsTypeId: dmsType.id, + description: this.params.supplierName + }; - this.dms = Object.assign(this.dms, defaultParams); - }); + this.dms = Object.assign(this.dms, defaultParams); } onSubmit() { diff --git a/modules/ticket/front/dms/create/index.js b/modules/ticket/front/dms/create/index.js index b25abf17c..7b25e4665 100644 --- a/modules/ticket/front/dms/create/index.js +++ b/modules/ticket/front/dms/create/index.js @@ -1,7 +1,7 @@ import ngModule from '../../module'; -import Section from 'salix/components/section'; +import SectionDms from 'salix/components/section-dms'; -class Controller extends Section { +class Controller extends SectionDms { constructor($element, $) { super($element, $); this.dms = { @@ -19,45 +19,36 @@ class Controller extends Section { this._ticket = value; if (value) { - this.setDefaultParams(); - this.getAllowedContentTypes(); + const params = {filter: { + where: {code: 'ticket'} + }}; + this.getDmsTypes(params).then(res => this.handleDefaultParams(res)); + this.getAllowedContentTypes().then(data => this.allowedContentTypes = data); } } - getAllowedContentTypes() { - this.$http.get('DmsContainers/allowedContentTypes').then(res => { - const contentTypes = res.data.join(', '); - this.allowedContentTypes = contentTypes; - }); - } - get contentTypesInfo() { return this.$t('ContentTypesInfo', { allowedContentTypes: this.allowedContentTypes }); } - setDefaultParams() { - const params = {filter: { - where: {code: 'ticket'} - }}; - this.$http.get('DmsTypes/findOne', {params}).then(res => { - const dmsTypeId = res.data && res.data.id; - const warehouseId = this.vnConfig.warehouseFk; - const defaultParams = { - reference: this.ticket.id, - warehouseId: warehouseId, - companyId: this.ticket.companyFk, - dmsTypeId: dmsTypeId, - description: this.$t('FileDescription', { - ticketId: this.ticket.id, - clientId: this.ticket.client.id, - clientName: this.ticket.client.name - }).toUpperCase() - }; + handleDefaultParams(data) { + const dmsTypeId = res?.data?.id; + const warehouseId = this.vnConfig.warehouseFk; + const defaultParams = { + reference: this.ticket.id, + warehouseId: warehouseId, + companyId: this.ticket.companyFk, + dmsTypeId: dmsTypeId, + description: this.$t('FileDescription', { + ticketId: this.ticket.id, + clientId: this.ticket.client.id, + clientName: this.ticket.client.name + }).toUpperCase() + }; - this.dms = Object.assign(this.dms, defaultParams); - }); + this.dms = Object.assign(this.dms, defaultParams); } onSubmit() { diff --git a/modules/ticket/front/dms/edit/index.js b/modules/ticket/front/dms/edit/index.js index 808ca6a6a..9b64f5906 100644 --- a/modules/ticket/front/dms/edit/index.js +++ b/modules/ticket/front/dms/edit/index.js @@ -1,7 +1,7 @@ import ngModule from '../../module'; -import Section from 'salix/components/section'; +import SectionDms from 'salix/components/section-dms'; -class Controller extends Section { +class Controller extends SectionDms { get ticket() { return this._ticket; } @@ -10,39 +10,28 @@ class Controller extends Section { this._ticket = value; if (value) { - this.setDefaultParams(); - this.getAllowedContentTypes(); + this.getDms(this.$params.dmsId).then(handleDefaultParams); + this.getAllowedContentTypes().then(data => this.allowedContentTypes = data); } } - getAllowedContentTypes() { - this.$http.get('DmsContainers/allowedContentTypes').then(res => { - const contentTypes = res.data.join(', '); - this.allowedContentTypes = contentTypes; - }); - } - get contentTypesInfo() { return this.$t('ContentTypesInfo', { allowedContentTypes: this.allowedContentTypes }); } - setDefaultParams() { - const path = `Dms/${this.$params.dmsId}`; - this.$http.get(path).then(res => { - const dms = res.data && res.data; - this.dms = { - reference: dms.reference, - warehouseId: dms.warehouseFk, - companyId: dms.companyFk, - dmsTypeId: dms.dmsTypeFk, - description: dms.description, - hasFile: dms.hasFile, - hasFileAttached: false, - files: [] - }; - }); + handleDefaultParams({data: dms}) { + this.dms = { + reference: dms.reference, + warehouseId: dms.warehouseFk, + companyId: dms.companyFk, + dmsTypeId: dms.dmsTypeFk, + description: dms.description, + hasFile: dms.hasFile, + hasFileAttached: false, + files: [] + }; } onSubmit() { diff --git a/modules/travel/front/thermograph/create/index.js b/modules/travel/front/thermograph/create/index.js index fa2c1261a..e51d23124 100644 --- a/modules/travel/front/thermograph/create/index.js +++ b/modules/travel/front/thermograph/create/index.js @@ -17,16 +17,10 @@ class Controller extends Section { if (value) { this.setDefaultParams(); - this.getAllowedContentTypes(); + this.allowedContentTypes = this.getAllowedContentTypes(); } } - getAllowedContentTypes() { - this.$http.get('DmsContainers/allowedContentTypes').then(res => { - const contentTypes = res.data.join(', '); - this.allowedContentTypes = contentTypes; - }); - } get contentTypesInfo() { return this.$t('ContentTypesInfo', { diff --git a/modules/travel/front/thermograph/edit/index.js b/modules/travel/front/thermograph/edit/index.js index a8df3142d..1678643b2 100644 --- a/modules/travel/front/thermograph/edit/index.js +++ b/modules/travel/front/thermograph/edit/index.js @@ -1,8 +1,8 @@ import ngModule from '../../module'; -import Section from 'salix/components/section'; +import SectionDms from 'salix/components/section-dms'; import './style.scss'; -class Controller extends Section { +class Controller extends SectionDms { get travel() { return this._travel; } @@ -12,17 +12,10 @@ class Controller extends Section { if (value) { this.setDefaultParams(); - this.getAllowedContentTypes(); + this.getAllowedContentTypes().then(data => this.allowedContentTypes = data); } } - getAllowedContentTypes() { - this.$http.get('DmsContainers/allowedContentTypes').then(res => { - const contentTypes = res.data.join(', '); - this.allowedContentTypes = contentTypes; - }); - } - get contentTypesInfo() { return this.$t('ContentTypesInfo', { allowedContentTypes: this.allowedContentTypes diff --git a/modules/worker/front/dms/create/index.js b/modules/worker/front/dms/create/index.js index ff6112211..2f06128b5 100644 --- a/modules/worker/front/dms/create/index.js +++ b/modules/worker/front/dms/create/index.js @@ -21,17 +21,12 @@ class Controller extends Section { if (value) { this.setDefaultParams(); - this.getAllowedContentTypes(); + this.getAllowedContentTypes().then(data => { + this.allowedContentTypes = data; + }); } } - getAllowedContentTypes() { - this.$http.get('DmsContainers/allowedContentTypes').then(res => { - const contentTypes = res.data.join(', '); - this.allowedContentTypes = contentTypes; - }); - } - get contentTypesInfo() { return this.$t('ContentTypesInfo', { allowedContentTypes: this.allowedContentTypes diff --git a/modules/worker/front/dms/edit/index.js b/modules/worker/front/dms/edit/index.js index 31d4c2853..8a1790563 100644 --- a/modules/worker/front/dms/edit/index.js +++ b/modules/worker/front/dms/edit/index.js @@ -1,8 +1,8 @@ import ngModule from '../../module'; -import Section from 'salix/components/section'; +import SectionDms from 'salix/components/section-dms'; import './style.scss'; -class Controller extends Section { +class Controller extends SectionDms { get worker() { return this._worker; } @@ -11,16 +11,10 @@ class Controller extends Section { this._worker = value; if (value) { - this.setDefaultParams(); - this.getAllowedContentTypes(); - } - } + this.getDms(this.$params.dmsId).then(handleDefaultParams); - getAllowedContentTypes() { - this.$http.get('DmsContainers/allowedContentTypes').then(res => { - const contentTypes = res.data.join(', '); - this.allowedContentTypes = contentTypes; - }); + this.getAllowedContentTypes().then(data => this.allowedContentTypes = data); + } } get contentTypesInfo() { @@ -29,21 +23,17 @@ class Controller extends Section { }); } - setDefaultParams() { - const path = `Dms/${this.$params.dmsId}`; - this.$http.get(path).then(res => { - const dms = res.data && res.data; - this.dms = { - reference: dms.reference, - warehouseId: dms.warehouseFk, - companyId: dms.companyFk, - dmsTypeId: dms.dmsTypeFk, - description: dms.description, - hasFile: dms.hasFile, - hasFileAttached: false, - files: [] - }; - }); + handleDefaultParams({data: dms}) { + this.dms = { + reference: dms.reference, + warehouseId: dms.warehouseFk, + companyId: dms.companyFk, + dmsTypeId: dms.dmsTypeFk, + description: dms.description, + hasFile: dms.hasFile, + hasFileAttached: false, + files: [] + }; } onSubmit() { From 5f4adab017696ece18a9a94094567a58dfc1f631 Mon Sep 17 00:00:00 2001 From: robert Date: Tue, 12 Dec 2023 18:03:09 +0100 Subject: [PATCH 33/75] refs #5854 --- modules/item/back/locale/item-shelving/es.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/item/back/locale/item-shelving/es.yml b/modules/item/back/locale/item-shelving/es.yml index a64b23bfa..3aedcd0bf 100644 --- a/modules/item/back/locale/item-shelving/es.yml +++ b/modules/item/back/locale/item-shelving/es.yml @@ -5,8 +5,8 @@ columns: shelvingFk: matrícula carro visible: visible created: creado - grouping: agrupación - packing: embalaje + grouping: grouping + packing: packing packagingFk: paquete userFk: usuario isChecked: está revisado From 0ae75d973fe9ad55cd709f409d698fe1e68446fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20Segarra=20Mart=C3=ADnez?= Date: Tue, 12 Dec 2023 19:42:46 +0100 Subject: [PATCH 34/75] refs #6264 perf: remove async keyword --- loopback/server/middleware/current-user.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/loopback/server/middleware/current-user.js b/loopback/server/middleware/current-user.js index b450f6bb1..a6624351e 100644 --- a/loopback/server/middleware/current-user.js +++ b/loopback/server/middleware/current-user.js @@ -1,5 +1,5 @@ module.exports = function(options) { - return async function(req, res, next) { + return function(req, res, next) { if (!req.accessToken) return next(); From 8441877f36491c956517b3c00b22cac5a6492f20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20Segarra=20Mart=C3=ADnez?= Date: Tue, 12 Dec 2023 19:43:32 +0100 Subject: [PATCH 35/75] refs #6264 perf: remove field's query --- back/methods/vn-user/renew-token.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index d5d22fd0d..4254d075a 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -32,7 +32,7 @@ module.exports = Self => { const isValid = await Self.validateToken(token); if (isValid) throw new UserError(`The renew period has not been exceeded`, 'periodNotExceeded'); - const {courtesyTime} = await models.AccessTokenConfig.findOne({fields: ['renewPeriod', 'courtesyTime']}); + const {courtesyTime} = await models.AccessTokenConfig.findOne({fields: ['courtesyTime']}); // Schedule to remove current token handlePromiseLogout(Self, token, courtesyTime); From 2393625a48ddbaf72f33be6420212fa3b8e3d232 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 13 Dec 2023 08:22:58 +0100 Subject: [PATCH 36/75] refs #5925 Tablet --- back/methods/docuware/upload.js | 17 +++++++++++------ back/models/docuwareTablet.json | 2 +- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/back/methods/docuware/upload.js b/back/methods/docuware/upload.js index a587079a2..0af20b8ac 100644 --- a/back/methods/docuware/upload.js +++ b/back/methods/docuware/upload.js @@ -56,6 +56,16 @@ module.exports = Self => { }] }); + // get tablet + const tablet = await models.userConfig.findById(id, { + include: [{ + relation: 'Tablet', + scope: { + fields: ['id'] + } + }] + }); + // upload file const templateJson = { 'Fields': [ @@ -102,12 +112,7 @@ module.exports = Self => { { 'FieldName': 'FILTRO_TABLET', 'ItemElementName': 'string', - 'Item': 'Tablet1', - }, - { - 'FieldName': 'ID_TABLET', - 'ItemElementName': 'integer', - 'Item': userConfig.tabletFk, + 'Item': tablet.id, } ] }; diff --git a/back/models/docuwareTablet.json b/back/models/docuwareTablet.json index dde336bca..e9e3b6bad 100644 --- a/back/models/docuwareTablet.json +++ b/back/models/docuwareTablet.json @@ -3,7 +3,7 @@ "base": "VnModel", "options": { "mysql": { - "table": "vn.docuwareTablet" + "table": "docuwareTablet" } }, "properties": { From 5b3645a6419e765cf186b4280d22594f83acfb7d Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 13 Dec 2023 11:59:00 +0100 Subject: [PATCH 37/75] refs #6434 fix: bad merge --- back/models/vn-user.js | 27 +++++++++++++++++++ db/changes/234801/00-createSignInLogTable.sql | 19 ------------- 2 files changed, 27 insertions(+), 19 deletions(-) delete mode 100644 db/changes/234801/00-createSignInLogTable.sql diff --git a/back/models/vn-user.js b/back/models/vn-user.js index d840e34e8..7b1471e5c 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -125,6 +125,33 @@ module.exports = function(Self) { return email.send(); }); + /** + * Sign-in validate + * @param {String} user The user + * @param {Object} userToken Options + * @param {Object} token accessToken + * @param {Object} ctx context + */ + Self.signInValidate = async(user, userToken, token, ctx) => { + const [[key, value]] = Object.entries(Self.userUses(user)); + const isOwner = Self.rawSql(`SELECT ? = ? `, [userToken[key], value]); + await Self.app.models.SignInLog.create({ + userName: user, + token: token.id, + userFk: userToken.id, + ip: ctx.req.ip, + owner: isOwner + }); + if (!isOwner) + throw new UserError('Try again'); + }; + + /** + * Validate login params + * @param {String} user The user + * @param {String} password + * @param {Object} ctx context + */ Self.validateLogin = async function(user, password) { let loginInfo = Object.assign({password}, Self.userUses(user)); token = await Self.login(loginInfo, 'user'); diff --git a/db/changes/234801/00-createSignInLogTable.sql b/db/changes/234801/00-createSignInLogTable.sql deleted file mode 100644 index 977de4646..000000000 --- a/db/changes/234801/00-createSignInLogTable.sql +++ /dev/null @@ -1,19 +0,0 @@ - - --- --- Table structure for table `signInLog` --- - -DROP TABLE IF EXISTS `account`.`signInLog`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `account`.`signInLog` ( - `id` varchar(10) NOT NULL , - `userFk` int(10) unsigned DEFAULT NULL, - `creationDate` timestamp NULL DEFAULT current_timestamp(), - `ip` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, - PRIMARY KEY (`id`), - KEY `userFk` (`userFk`), - CONSTRAINT `signInLog_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -); - From 5f93b8c44032a4b982d23383b8c5158f721e9817 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 13 Dec 2023 12:01:18 +0100 Subject: [PATCH 38/75] refs #6434 fix: bad merge --- back/models/vn-user.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 7b1471e5c..e14cd30ea 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -152,9 +152,9 @@ module.exports = function(Self) { * @param {String} password * @param {Object} ctx context */ - Self.validateLogin = async function(user, password) { - let loginInfo = Object.assign({password}, Self.userUses(user)); - token = await Self.login(loginInfo, 'user'); + Self.validateLogin = async function(user, password, ctx) { + const loginInfo = Object.assign({password}, Self.userUses(user)); + const token = await Self.login(loginInfo, 'user'); const userToken = await token.user.get(); From 4e8bec5684935258b23f2d30c568f0ad745c36d8 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 13 Dec 2023 12:03:04 +0100 Subject: [PATCH 39/75] refs #5925 user error --- back/methods/docuware/upload.js | 2 ++ loopback/locale/es.json | 5 +++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/back/methods/docuware/upload.js b/back/methods/docuware/upload.js index 0af20b8ac..5f44e9382 100644 --- a/back/methods/docuware/upload.js +++ b/back/methods/docuware/upload.js @@ -120,6 +120,8 @@ module.exports = Self => { if (process.env.NODE_ENV != 'production') throw new UserError('Action not allowed on the test environment'); + if (!tablet.id) + throw new UserError('This user does not have an assigned tablet.'); // delete old const docuwareFile = await models.Docuware.checkFile(id, fileCabinet, false); if (docuwareFile) { diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 01384efb4..4a2e9a794 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -329,5 +329,6 @@ "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mínima", "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima", "Cannot past travels with entries": "No se pueden pasar envíos con entradas", - "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}" -} \ No newline at end of file + "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", + "This user does not have an assigned tablet.": "Este usuario no tiene tablet asignada" +} From 6af99b7669f0ff0ac8a5b4110993686968d11dd5 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 13 Dec 2023 12:07:41 +0100 Subject: [PATCH 40/75] refs #6434 feat: delete records whe !owner --- db/changes/235201/00-truncate-where-signInLog.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 db/changes/235201/00-truncate-where-signInLog.sql diff --git a/db/changes/235201/00-truncate-where-signInLog.sql b/db/changes/235201/00-truncate-where-signInLog.sql new file mode 100644 index 000000000..93d80d716 --- /dev/null +++ b/db/changes/235201/00-truncate-where-signInLog.sql @@ -0,0 +1 @@ +DELETE FROM `account`.`signInLog` where owner <> FALSE From 5a36fabf058153792cda778c7e0e01c3b52588d1 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 13 Dec 2023 12:07:57 +0100 Subject: [PATCH 41/75] refs #6434 feat: insert record just when fail --- back/models/vn-user.js | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index e14cd30ea..1134df363 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -135,15 +135,16 @@ module.exports = function(Self) { Self.signInValidate = async(user, userToken, token, ctx) => { const [[key, value]] = Object.entries(Self.userUses(user)); const isOwner = Self.rawSql(`SELECT ? = ? `, [userToken[key], value]); - await Self.app.models.SignInLog.create({ - userName: user, - token: token.id, - userFk: userToken.id, - ip: ctx.req.ip, - owner: isOwner - }); - if (!isOwner) - throw new UserError('Try again'); + if (!isOwner) { + await Self.app.models.SignInLog.create({ + userName: user, + token: token.id, + userFk: userToken.id, + ip: ctx.req.ip, + owner: isOwner + }); + } + throw new UserError('Try again'); }; /** From 11b54d66af6f77158441e0627186c128d3c5234c Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 13 Dec 2023 13:31:32 +0100 Subject: [PATCH 42/75] refs #6434 fix: bad merge --- back/methods/vn-user/sign-in.js | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/back/methods/vn-user/sign-in.js b/back/methods/vn-user/sign-in.js index 9626e2e79..782046641 100644 --- a/back/methods/vn-user/sign-in.js +++ b/back/methods/vn-user/sign-in.js @@ -40,14 +40,11 @@ module.exports = Self => { const validCredentials = vnUser && await vnUser.hasPassword(password); - if (!validCredentials) - throw new UserError('Invalid credentials'); - - if (!vnUser.active) - throw new UserError('User disabled'); - - await Self.sendTwoFactor(ctx, vnUser, myOptions); - await Self.passExpired(vnUser, myOptions); + if (validCredentials) { + if (!vnUser.active) + throw new UserError('User disabled'); + await Self.sendTwoFactor(ctx, vnUser, myOptions); + await Self.passExpired(vnUser, myOptions); if (vnUser.twoFactor) throw new ForbiddenError(null, 'REQUIRES_2FA'); From d364a50ec4ecabc20e6e273b155341f169c601a4 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 13 Dec 2023 13:39:43 +0100 Subject: [PATCH 43/75] refs #6264 feat: remove validateToken endpoint --- back/methods/vn-user/renew-token.js | 12 +++++- .../vn-user/specs/validate-token.spec.js | 43 ------------------- back/methods/vn-user/validate-token.js | 24 ----------- back/models/vn-user.js | 1 - back/models/vn-user.json | 7 --- 5 files changed, 11 insertions(+), 76 deletions(-) delete mode 100644 back/methods/vn-user/specs/validate-token.spec.js delete mode 100644 back/methods/vn-user/validate-token.js diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index 4254d075a..e7e826cd1 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -29,7 +29,7 @@ module.exports = Self => { const {accessToken: token} = ctx.req; // Check if current token is valid - const isValid = await Self.validateToken(token); + const isValid = await validateToken(token); if (isValid) throw new UserError(`The renew period has not been exceeded`, 'periodNotExceeded'); const {courtesyTime} = await models.AccessTokenConfig.findOne({fields: ['courtesyTime']}); @@ -43,4 +43,14 @@ module.exports = Self => { return {id: accessToken.id, ttl: accessToken.ttl}; }; + + async function validateToken(token) { + const accessTokenConfig = await models.AccessTokenConfig.findOne({fields: ['renewPeriod', 'courtesyTime']}); + const now = Date.now(); + const differenceMilliseconds = now - token.created; + const differenceSeconds = Math.floor(differenceMilliseconds / 1000); + const isValid = differenceSeconds < accessTokenConfig.renewPeriod - accessTokenConfig.courtesyTime; + + return isValid; + } }; diff --git a/back/methods/vn-user/specs/validate-token.spec.js b/back/methods/vn-user/specs/validate-token.spec.js deleted file mode 100644 index ec254d0e5..000000000 --- a/back/methods/vn-user/specs/validate-token.spec.js +++ /dev/null @@ -1,43 +0,0 @@ -const {models} = require('vn-loopback/server/server'); - -describe('Validate Token', () => { - const startingTime = Date.now(); - let ctx = null; - beforeAll(async() => { - const unAuthCtx = { - req: { - headers: {}, - connection: { - remoteAddress: '127.0.0.1' - }, - getLocale: () => 'en' - }, - args: {} - }; - let login = await models.VnUser.signIn(unAuthCtx, 'salesAssistant', 'nightmare'); - let accessToken = await models.AccessToken.findById(login.token); - ctx = {req: {accessToken: accessToken}}; - }); - - beforeEach(() => { - jasmine.clock().install(); - jasmine.clock().mockDate(new Date(startingTime)); - }); - - afterEach(() => { - jasmine.clock().uninstall(); - }); - - it('Token is not expired', async() => { - const isValid = await models.VnUser.validateToken(ctx.req.accessToken); - - expect(isValid).toBeTrue(); - }); - - it('Token is expired', async() => { - jasmine.clock().mockDate(new Date(startingTime + 21600000)); - const isValid = await models.VnUser.validateToken(ctx.req.accessToken); - - expect(isValid).toBeFalse(); - }); -}); diff --git a/back/methods/vn-user/validate-token.js b/back/methods/vn-user/validate-token.js deleted file mode 100644 index ef3c5b212..000000000 --- a/back/methods/vn-user/validate-token.js +++ /dev/null @@ -1,24 +0,0 @@ -const {models} = require('vn-loopback/server/server'); -module.exports = Self => { - Self.remoteMethod('validateToken', { - description: 'Validates the current logged user token', - returns: { - type: 'Boolean', - root: true - }, - http: { - path: `/validateToken`, - verb: 'GET' - } - }); - - Self.validateToken = async function(token) { - const accessTokenConfig = await models.AccessTokenConfig.findOne({fields: ['renewPeriod', 'courtesyTime']}); - const now = Date.now(); - const differenceMilliseconds = now - token.created; - const differenceSeconds = Math.floor(differenceMilliseconds / 1000); - const isValid = differenceSeconds < accessTokenConfig.renewPeriod - accessTokenConfig.courtesyTime; - - return isValid; - }; -}; diff --git a/back/models/vn-user.js b/back/models/vn-user.js index e14cd30ea..80287de5b 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -10,7 +10,6 @@ module.exports = function(Self) { require('../methods/vn-user/sign-in')(Self); require('../methods/vn-user/acl')(Self); require('../methods/vn-user/recover-password')(Self); - require('../methods/vn-user/validate-token')(Self); require('../methods/vn-user/privileges')(Self); require('../methods/vn-user/validate-auth')(Self); require('../methods/vn-user/renew-token')(Self); diff --git a/back/models/vn-user.json b/back/models/vn-user.json index 0f6daff5a..86ffac2bb 100644 --- a/back/models/vn-user.json +++ b/back/models/vn-user.json @@ -104,13 +104,6 @@ "permission": "ALLOW" }, { - "property": "validateToken", - "accessType": "EXECUTE", - "principalType": "ROLE", - "principalId": "$authenticated", - "permission": "ALLOW" - }, - { "property": "validateAuth", "accessType": "EXECUTE", "principalType": "ROLE", From a5ecec960351372d518a3d8f4fd5e8d7d3c6d2ce Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 13 Dec 2023 13:47:30 +0100 Subject: [PATCH 44/75] refs #2051 feat: remove front methods refactor --- front/salix/components/index.js | 1 - front/salix/components/section-dms/index.js | 24 --------- front/salix/components/section-dms/style.scss | 0 modules/client/front/dms/create/index.js | 54 +++++++++++-------- modules/client/front/dms/edit/index.js | 41 ++++++++------ modules/invoiceIn/front/basic-data/index.js | 15 ++++-- .../agency-term/createInvoiceIn/index.js | 45 ++++++++++------ modules/ticket/front/dms/create/index.js | 53 ++++++++++-------- modules/ticket/front/dms/edit/index.js | 41 ++++++++------ modules/ticket/front/tracking/index/index.js | 10 +--- .../travel/front/thermograph/create/index.js | 8 ++- .../travel/front/thermograph/edit/index.js | 13 +++-- modules/worker/front/dms/create/index.js | 11 ++-- 13 files changed, 182 insertions(+), 134 deletions(-) delete mode 100644 front/salix/components/section-dms/index.js delete mode 100644 front/salix/components/section-dms/style.scss diff --git a/front/salix/components/index.js b/front/salix/components/index.js index e843f2f5e..38b0d0e1f 100644 --- a/front/salix/components/index.js +++ b/front/salix/components/index.js @@ -15,7 +15,6 @@ import './module-card'; import './module-main'; import './side-menu/side-menu'; import './section'; -import './section-dms'; import './summary'; import './topbar/topbar'; import './user-popover'; diff --git a/front/salix/components/section-dms/index.js b/front/salix/components/section-dms/index.js deleted file mode 100644 index ae7d496cd..000000000 --- a/front/salix/components/section-dms/index.js +++ /dev/null @@ -1,24 +0,0 @@ -import ngModule from '../../module'; -import Component from 'core/lib/component'; -import './style.scss'; - -export default class SectionDms extends Component { - getAllowedContentTypes() { - return this.$http.get('DmsContainers/allowedContentTypes').then(res => { - const contentTypes = res.data.join(', '); - this.allowedContentTypes = contentTypes; - return contentTypes; - }); - } - - getDms(dmsId) { - return this.$http.get(`Dms/${dmsId}`).then(res => res); - } - getDmsTypes(params) { - return this.$http.get('DmsTypes/findOne', params).then(res => res); - } -} - -ngModule.vnComponent('vnSectionDms', { - controller: SectionDms -}); diff --git a/front/salix/components/section-dms/style.scss b/front/salix/components/section-dms/style.scss deleted file mode 100644 index e69de29bb..000000000 diff --git a/modules/client/front/dms/create/index.js b/modules/client/front/dms/create/index.js index ec8837981..461d0aa36 100644 --- a/modules/client/front/dms/create/index.js +++ b/modules/client/front/dms/create/index.js @@ -1,8 +1,8 @@ import ngModule from '../../module'; -import SectionDms from 'salix/components/section-dms'; +import Section from 'salix/components/section'; import './style.scss'; -class Controller extends SectionDms { +class Controller extends Section { constructor($element, $) { super($element, $); this.dms = { @@ -20,36 +20,46 @@ class Controller extends SectionDms { this._client = value; if (value) { - const params = {filter: { - where: {code: 'paymentsLaw'} - }}; - this.getDmsTypes(params).then(res => this.handleDefaultParams(res)); - this.getAllowedContentTypes().then(data => this.allowedContentTypes = data); + this.setDefaultParams(); + this.getAllowedContentTypes(); } } + getAllowedContentTypes() { + this.$http.get('DmsContainers/allowedContentTypes').then(res => { + const contentTypes = res.data.join(', '); + this.allowedContentTypes = contentTypes; + }); + } + get contentTypesInfo() { return this.$t('ContentTypesInfo', { allowedContentTypes: this.allowedContentTypes }); } - handleDefaultParams({data: dmsType}) { - const companyId = this.vnConfig.companyFk; - const warehouseId = this.vnConfig.warehouseFk; - const defaultParams = { - reference: this.client.id, - warehouseId: warehouseId, - companyId: companyId, - dmsTypeId: dmsType.id, - description: this.$t('ClientFileDescription', { - dmsTypeName: dmsType.name, - clientId: this.client.id, - clientName: this.client.name - }).toUpperCase() - }; + setDefaultParams() { + const params = {filter: { + where: {code: 'paymentsLaw'} + }}; + this.$http.get('DmsTypes/findOne', {params}).then(res => { + const dmsType = res.data && res.data; + const companyId = this.vnConfig.companyFk; + const warehouseId = this.vnConfig.warehouseFk; + const defaultParams = { + reference: this.client.id, + warehouseId: warehouseId, + companyId: companyId, + dmsTypeId: dmsType.id, + description: this.$t('ClientFileDescription', { + dmsTypeName: dmsType.name, + clientId: this.client.id, + clientName: this.client.name + }).toUpperCase() + }; - this.dms = Object.assign(this.dms, defaultParams); + this.dms = Object.assign(this.dms, defaultParams); + }); } onSubmit() { diff --git a/modules/client/front/dms/edit/index.js b/modules/client/front/dms/edit/index.js index 36c1a9672..8765eeff2 100644 --- a/modules/client/front/dms/edit/index.js +++ b/modules/client/front/dms/edit/index.js @@ -1,8 +1,8 @@ import ngModule from '../../module'; -import SectionDms from 'salix/components/section-dms'; +import Section from 'salix/components/section'; import './style.scss'; -class Controller extends SectionDms { +class Controller extends Section { get client() { return this._client; } @@ -11,28 +11,39 @@ class Controller extends SectionDms { this._client = value; if (value) { - this.getDms(this.$params.dmsId).then(handleDefaultParams); - this.getAllowedContentTypes().then(data => this.allowedContentTypes = data); + this.setDefaultParams(); + this.getAllowedContentTypes(); } } + getAllowedContentTypes() { + this.$http.get('DmsContainers/allowedContentTypes').then(res => { + const contentTypes = res.data.join(', '); + this.allowedContentTypes = contentTypes; + }); + } + get contentTypesInfo() { return this.$t('ContentTypesInfo', { allowedContentTypes: this.allowedContentTypes }); } - handleDefaultParams({data: dms}) { - this.dms = { - reference: dms.reference, - warehouseId: dms.warehouseFk, - companyId: dms.companyFk, - dmsTypeId: dms.dmsTypeFk, - description: dms.description, - hasFile: dms.hasFile, - hasFileAttached: false, - files: [] - }; + setDefaultParams() { + const path = `Dms/${this.$params.dmsId}`; + this.$http.get(path).then(res => { + const dms = res.data && res.data; + this.dms = { + reference: dms.reference, + warehouseId: dms.warehouseFk, + companyId: dms.companyFk, + dmsTypeId: dms.dmsTypeFk, + description: dms.description, + hasFile: dms.hasFile, + hasFileAttached: false, + files: [] + }; + }); } onSubmit() { diff --git a/modules/invoiceIn/front/basic-data/index.js b/modules/invoiceIn/front/basic-data/index.js index 797fda59d..246f1b16f 100644 --- a/modules/invoiceIn/front/basic-data/index.js +++ b/modules/invoiceIn/front/basic-data/index.js @@ -1,8 +1,8 @@ import ngModule from '../module'; -import SectionDms from 'salix/components/section-dms'; +import Section from 'salix/components/section'; import UserError from 'core/lib/user-error'; -class Controller extends SectionDms { +class Controller extends Section { constructor($element, $, vnFile) { super($element, $, vnFile); this.dms = { @@ -11,7 +11,7 @@ class Controller extends SectionDms { hasFileAttached: false }; this.vnFile = vnFile; - this.getAllowedContentTypes().then(data => this.allowedContentTypes = data); + this.getAllowedContentTypes(); this._editDownloadDisabled = false; } @@ -53,6 +53,15 @@ class Controller extends SectionDms { }); } + getAllowedContentTypes() { + this.$http.get('DmsContainers/allowedContentTypes').then(res => { + if (res.data.length > 0) { + const contentTypes = res.data.join(', '); + this.allowedContentTypes = contentTypes; + } + }); + } + openEditDialog(dmsId) { this.getFile(dmsId).then(() => this.$.dmsEditDialog.show()); } diff --git a/modules/route/front/agency-term/createInvoiceIn/index.js b/modules/route/front/agency-term/createInvoiceIn/index.js index 5e54f7929..0198ab80f 100644 --- a/modules/route/front/agency-term/createInvoiceIn/index.js +++ b/modules/route/front/agency-term/createInvoiceIn/index.js @@ -1,9 +1,9 @@ import ngModule from '../../module'; -import SectionDms from 'salix/components/section-dms'; +import Section from 'salix/components/section'; import './style.scss'; import UserError from 'core/lib/user-error'; -class Controller extends SectionDms { +class Controller extends Section { constructor($element, $) { super($element, $); this.dms = { @@ -19,11 +19,9 @@ class Controller extends SectionDms { set route(value) { this._route = value; - const params = {filter: { - where: {code: 'invoiceIn'} - }}; - this.getDmsTypes(params).then(res => this.handleDefaultParams(res)); - this.getAllowedContentTypes().then(data => this.allowedContentTypes = data); + + this.setDefaultParams(); + this.getAllowedContentTypes(); } $onChanges() { @@ -31,23 +29,36 @@ class Controller extends SectionDms { this.params = JSON.parse(this.$params.q); } + getAllowedContentTypes() { + this.$http.get('DmsContainers/allowedContentTypes').then(res => { + const contentTypes = res.data.join(', '); + this.allowedContentTypes = contentTypes; + }); + } + get contentTypesInfo() { return this.$t('ContentTypesInfo', { allowedContentTypes: this.allowedContentTypes }); } - handleDefaultParams({data: dmsType}) { - const companyId = this.vnConfig.companyFk; - const warehouseId = this.vnConfig.warehouseFk; - const defaultParams = { - warehouseId: warehouseId, - companyId: companyId, - dmsTypeId: dmsType.id, - description: this.params.supplierName - }; + setDefaultParams() { + const params = {filter: { + where: {code: 'invoiceIn'} + }}; + this.$http.get('DmsTypes/findOne', {params}).then(res => { + const dmsType = res.data && res.data; + const companyId = this.vnConfig.companyFk; + const warehouseId = this.vnConfig.warehouseFk; + const defaultParams = { + warehouseId: warehouseId, + companyId: companyId, + dmsTypeId: dmsType.id, + description: this.params.supplierName + }; - this.dms = Object.assign(this.dms, defaultParams); + this.dms = Object.assign(this.dms, defaultParams); + }); } onSubmit() { diff --git a/modules/ticket/front/dms/create/index.js b/modules/ticket/front/dms/create/index.js index 7b25e4665..b25abf17c 100644 --- a/modules/ticket/front/dms/create/index.js +++ b/modules/ticket/front/dms/create/index.js @@ -1,7 +1,7 @@ import ngModule from '../../module'; -import SectionDms from 'salix/components/section-dms'; +import Section from 'salix/components/section'; -class Controller extends SectionDms { +class Controller extends Section { constructor($element, $) { super($element, $); this.dms = { @@ -19,36 +19,45 @@ class Controller extends SectionDms { this._ticket = value; if (value) { - const params = {filter: { - where: {code: 'ticket'} - }}; - this.getDmsTypes(params).then(res => this.handleDefaultParams(res)); - this.getAllowedContentTypes().then(data => this.allowedContentTypes = data); + this.setDefaultParams(); + this.getAllowedContentTypes(); } } + getAllowedContentTypes() { + this.$http.get('DmsContainers/allowedContentTypes').then(res => { + const contentTypes = res.data.join(', '); + this.allowedContentTypes = contentTypes; + }); + } + get contentTypesInfo() { return this.$t('ContentTypesInfo', { allowedContentTypes: this.allowedContentTypes }); } - handleDefaultParams(data) { - const dmsTypeId = res?.data?.id; - const warehouseId = this.vnConfig.warehouseFk; - const defaultParams = { - reference: this.ticket.id, - warehouseId: warehouseId, - companyId: this.ticket.companyFk, - dmsTypeId: dmsTypeId, - description: this.$t('FileDescription', { - ticketId: this.ticket.id, - clientId: this.ticket.client.id, - clientName: this.ticket.client.name - }).toUpperCase() - }; + setDefaultParams() { + const params = {filter: { + where: {code: 'ticket'} + }}; + this.$http.get('DmsTypes/findOne', {params}).then(res => { + const dmsTypeId = res.data && res.data.id; + const warehouseId = this.vnConfig.warehouseFk; + const defaultParams = { + reference: this.ticket.id, + warehouseId: warehouseId, + companyId: this.ticket.companyFk, + dmsTypeId: dmsTypeId, + description: this.$t('FileDescription', { + ticketId: this.ticket.id, + clientId: this.ticket.client.id, + clientName: this.ticket.client.name + }).toUpperCase() + }; - this.dms = Object.assign(this.dms, defaultParams); + this.dms = Object.assign(this.dms, defaultParams); + }); } onSubmit() { diff --git a/modules/ticket/front/dms/edit/index.js b/modules/ticket/front/dms/edit/index.js index 9b64f5906..808ca6a6a 100644 --- a/modules/ticket/front/dms/edit/index.js +++ b/modules/ticket/front/dms/edit/index.js @@ -1,7 +1,7 @@ import ngModule from '../../module'; -import SectionDms from 'salix/components/section-dms'; +import Section from 'salix/components/section'; -class Controller extends SectionDms { +class Controller extends Section { get ticket() { return this._ticket; } @@ -10,28 +10,39 @@ class Controller extends SectionDms { this._ticket = value; if (value) { - this.getDms(this.$params.dmsId).then(handleDefaultParams); - this.getAllowedContentTypes().then(data => this.allowedContentTypes = data); + this.setDefaultParams(); + this.getAllowedContentTypes(); } } + getAllowedContentTypes() { + this.$http.get('DmsContainers/allowedContentTypes').then(res => { + const contentTypes = res.data.join(', '); + this.allowedContentTypes = contentTypes; + }); + } + get contentTypesInfo() { return this.$t('ContentTypesInfo', { allowedContentTypes: this.allowedContentTypes }); } - handleDefaultParams({data: dms}) { - this.dms = { - reference: dms.reference, - warehouseId: dms.warehouseFk, - companyId: dms.companyFk, - dmsTypeId: dms.dmsTypeFk, - description: dms.description, - hasFile: dms.hasFile, - hasFileAttached: false, - files: [] - }; + setDefaultParams() { + const path = `Dms/${this.$params.dmsId}`; + this.$http.get(path).then(res => { + const dms = res.data && res.data; + this.dms = { + reference: dms.reference, + warehouseId: dms.warehouseFk, + companyId: dms.companyFk, + dmsTypeId: dms.dmsTypeFk, + description: dms.description, + hasFile: dms.hasFile, + hasFileAttached: false, + files: [] + }; + }); } onSubmit() { diff --git a/modules/ticket/front/tracking/index/index.js b/modules/ticket/front/tracking/index/index.js index 95665b071..ff3dc881b 100644 --- a/modules/ticket/front/tracking/index/index.js +++ b/modules/ticket/front/tracking/index/index.js @@ -7,15 +7,9 @@ class Controller extends Section { this.filter = { include: [ { - relation: 'worker', + relation: 'user', scope: { - fields: ['id'], - include: { - relation: 'user', - scope: { - fields: ['name'] - } - } + fields: ['name'] } }, { relation: 'state', diff --git a/modules/travel/front/thermograph/create/index.js b/modules/travel/front/thermograph/create/index.js index e51d23124..fa2c1261a 100644 --- a/modules/travel/front/thermograph/create/index.js +++ b/modules/travel/front/thermograph/create/index.js @@ -17,10 +17,16 @@ class Controller extends Section { if (value) { this.setDefaultParams(); - this.allowedContentTypes = this.getAllowedContentTypes(); + this.getAllowedContentTypes(); } } + getAllowedContentTypes() { + this.$http.get('DmsContainers/allowedContentTypes').then(res => { + const contentTypes = res.data.join(', '); + this.allowedContentTypes = contentTypes; + }); + } get contentTypesInfo() { return this.$t('ContentTypesInfo', { diff --git a/modules/travel/front/thermograph/edit/index.js b/modules/travel/front/thermograph/edit/index.js index 1678643b2..a8df3142d 100644 --- a/modules/travel/front/thermograph/edit/index.js +++ b/modules/travel/front/thermograph/edit/index.js @@ -1,8 +1,8 @@ import ngModule from '../../module'; -import SectionDms from 'salix/components/section-dms'; +import Section from 'salix/components/section'; import './style.scss'; -class Controller extends SectionDms { +class Controller extends Section { get travel() { return this._travel; } @@ -12,10 +12,17 @@ class Controller extends SectionDms { if (value) { this.setDefaultParams(); - this.getAllowedContentTypes().then(data => this.allowedContentTypes = data); + this.getAllowedContentTypes(); } } + getAllowedContentTypes() { + this.$http.get('DmsContainers/allowedContentTypes').then(res => { + const contentTypes = res.data.join(', '); + this.allowedContentTypes = contentTypes; + }); + } + get contentTypesInfo() { return this.$t('ContentTypesInfo', { allowedContentTypes: this.allowedContentTypes diff --git a/modules/worker/front/dms/create/index.js b/modules/worker/front/dms/create/index.js index 2f06128b5..ff6112211 100644 --- a/modules/worker/front/dms/create/index.js +++ b/modules/worker/front/dms/create/index.js @@ -21,12 +21,17 @@ class Controller extends Section { if (value) { this.setDefaultParams(); - this.getAllowedContentTypes().then(data => { - this.allowedContentTypes = data; - }); + this.getAllowedContentTypes(); } } + getAllowedContentTypes() { + this.$http.get('DmsContainers/allowedContentTypes').then(res => { + const contentTypes = res.data.join(', '); + this.allowedContentTypes = contentTypes; + }); + } + get contentTypesInfo() { return this.$t('ContentTypesInfo', { allowedContentTypes: this.allowedContentTypes From bdf5dd6e3c4e334b44a65a254220cdf239eab0f6 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 13 Dec 2023 13:48:22 +0100 Subject: [PATCH 45/75] refs #2051 feat: restore dms methods --- back/methods/dms/removeFile.js | 15 +++++---------- back/methods/dms/uploadFile.js | 15 +-------------- 2 files changed, 6 insertions(+), 24 deletions(-) diff --git a/back/methods/dms/removeFile.js b/back/methods/dms/removeFile.js index cb81ff322..a9ff36883 100644 --- a/back/methods/dms/removeFile.js +++ b/back/methods/dms/removeFile.js @@ -34,25 +34,20 @@ module.exports = Self => { } try { - let modelDms = null; - if (myOptions.model) { - modelDms = await models[myOptions.model].findById(id, null, myOptions); - id = modelDms.dmsFk; - } - const targetDms = await models.Dms.findById(id, null, myOptions); + const dms = await models.Dms.findById(id, null, myOptions); const trashDmsType = await models.DmsType.findOne({ where: {code: 'trash'} }, myOptions); - const hasWriteRole = await models.DmsType.hasWriteRole(ctx, targetDms.dmsTypeFk, myOptions); + const hasWriteRole = await models.DmsType.hasWriteRole(ctx, dms.dmsTypeFk, myOptions); if (!hasWriteRole) throw new UserError(`You don't have enough privileges`); - await targetDms.updateAttribute('dmsTypeFk', trashDmsType.id, myOptions); + await dms.updateAttribute('dmsTypeFk', trashDmsType.id, myOptions); if (tx) await tx.commit(); - if (modelDms) modelDms.destroy(myOptions); - return targetDms; + + return dms; } catch (e) { if (tx) await tx.rollback(); throw e; diff --git a/back/methods/dms/uploadFile.js b/back/methods/dms/uploadFile.js index abed95a3a..a4212b804 100644 --- a/back/methods/dms/uploadFile.js +++ b/back/methods/dms/uploadFile.js @@ -96,21 +96,8 @@ module.exports = Self => { } if (tx) await tx.commit(); - const promises = []; - const {model, create} = myOptions; - addedDms.forEach(dms => { - const newDms = models[model].create({ - ...create, - dmsFk: dms.id - }, myOptions); - promises.push(newDms); - }); - const resolvedPromises = await Promise.all(promises); - - // if (tx) await tx.commit(); - - return resolvedPromises; + return addedDms; } catch (e) { if (tx) await tx.rollback(); From 7b9e3b0985f55a35e326a54680930ff4da410cba Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 13 Dec 2023 14:24:05 +0100 Subject: [PATCH 46/75] refs #2051 perf: removeFile after review --- back/methods/dms/removeFile.js | 2 +- .../back/methods/claim-dms/removeFile.js | 21 +++++++------- .../back/methods/client-dms/removeFile.js | 12 ++++---- .../back/methods/ticket-dms/removeFile.js | 15 +++++----- .../back/methods/worker-dms/removeFile.js | 29 ++++++++++--------- 5 files changed, 42 insertions(+), 37 deletions(-) diff --git a/back/methods/dms/removeFile.js b/back/methods/dms/removeFile.js index a9ff36883..dc55b4d38 100644 --- a/back/methods/dms/removeFile.js +++ b/back/methods/dms/removeFile.js @@ -22,8 +22,8 @@ module.exports = Self => { Self.removeFile = async(ctx, id, options) => { const models = Self.app.models; - let tx; const myOptions = {}; + let tx; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/claim/back/methods/claim-dms/removeFile.js b/modules/claim/back/methods/claim-dms/removeFile.js index 257b09cf2..0f1da626c 100644 --- a/modules/claim/back/methods/claim-dms/removeFile.js +++ b/modules/claim/back/methods/claim-dms/removeFile.js @@ -1,3 +1,5 @@ +const UserError = require('vn-loopback/util/user-error'); + module.exports = Self => { Self.remoteMethodCtx('removeFile', { description: 'Removes a claim document', @@ -19,8 +21,8 @@ module.exports = Self => { }); Self.removeFile = async(ctx, id, options) => { - let tx; const myOptions = {}; + let tx; if (typeof options == 'object') Object.assign(myOptions, options); @@ -31,19 +33,18 @@ module.exports = Self => { } try { - // const {models: ClaimDms, Dms} = Self.app.models; - // const targetClaimDms = await ClaimDms.findById(id, null, myOptions); - // await Dms.findById(targetClaimDms.dmsFk, null, myOptions); - // const trashDmsType = await DmsType.findOne({where: {code: 'trash'}}, myOptions); - myOptions.model = 'ClaimDms'; - const targetDms = await Self.app.models.Dms.removeFile(ctx, id, myOptions); - // await targetClaimDms.destroy(myOptions); + const claimDms = await Self.findById(id, null, myOptions); - // await targetDms.updateAttribute('dmsTypeFk', trashDmsType.id, myOptions); + const targetDms = await Self.app.models.Dms.removeFile(ctx, claimDms.dmsFk, myOptions); + + if (!targetDms || ! claimDms) + throw new UserError('Try again'); + + const claimDestroyed = await claimDms.destroy(myOptions); if (tx) await tx.commit(); - return targetDms; + return claimDestroyed; } catch (e) { if (tx) await tx.rollback(); throw e; diff --git a/modules/client/back/methods/client-dms/removeFile.js b/modules/client/back/methods/client-dms/removeFile.js index 786a32928..5bd34adcf 100644 --- a/modules/client/back/methods/client-dms/removeFile.js +++ b/modules/client/back/methods/client-dms/removeFile.js @@ -19,9 +19,8 @@ module.exports = Self => { }); Self.removeFile = async(ctx, id, options) => { - const models = Self.app.models; - let tx; const myOptions = {}; + let tx; if (typeof options == 'object') Object.assign(myOptions, options); @@ -34,13 +33,16 @@ module.exports = Self => { try { const clientDms = await Self.findById(id, null, myOptions); - await models.Dms.removeFile(ctx, clientDms.dmsFk, myOptions); + const targetDms = await Self.app.models.Dms.removeFile(ctx, clientDms.dmsFk, myOptions); - const destroyedClient = await clientDms.destroy(myOptions); + if (!targetDms || !clientDms) + throw new UserError('Try again'); + + const clientDestroyed = await clientDms.destroy(myOptions); if (tx) await tx.commit(); - return destroyedClient; + return clientDestroyed; } catch (e) { if (tx) await tx.rollback(); throw e; diff --git a/modules/ticket/back/methods/ticket-dms/removeFile.js b/modules/ticket/back/methods/ticket-dms/removeFile.js index 2e3ccd149..2f6426fbb 100644 --- a/modules/ticket/back/methods/ticket-dms/removeFile.js +++ b/modules/ticket/back/methods/ticket-dms/removeFile.js @@ -31,19 +31,18 @@ module.exports = Self => { } try { - // const targetTicketDms = await models.TicketDms.findById(id, null, myOptions); - myOptions.model = 'TicketDms'; - // await models.Dms.findById(targetTicketDms.dmsFk, null, myOptions); - // const trashDmsType = await models.DmsType.findOne({where: {code: 'trash'}}, myOptions); + const ticketDms = await Self.findById(id, null, myOptions); - const targetDms = await Self.app.models.Dms.removeFile(ctx, id, myOptions); - // await targetTicketDms.destroy(myOptions); + const targetDms = await Self.app.models.Dms.removeFile(ctx, ticketDms.dmsFk, myOptions); - // await targetDms.updateAttribute('dmsTypeFk', trashDmsType.id, myOptions); + if (!targetDms || !ticketDms) + throw new UserError('Try again'); + + const ticketDestroyed = await ticketDms.destroy(myOptions); if (tx) await tx.commit(); - return targetDms; + return ticketDestroyed; } catch (e) { if (tx) await tx.rollback(); throw e; diff --git a/modules/worker/back/methods/worker-dms/removeFile.js b/modules/worker/back/methods/worker-dms/removeFile.js index 397255bb2..6c7b6b850 100644 --- a/modules/worker/back/methods/worker-dms/removeFile.js +++ b/modules/worker/back/methods/worker-dms/removeFile.js @@ -19,25 +19,28 @@ module.exports = Self => { }); Self.removeFile = async(ctx, id, options) => { - const models = Self.app.models; + const myOptions = {}; let tx; + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + try { - const myOptions = {}; + const WorkerDms = await Self.findById(id, null, myOptions); - if (typeof options == 'object') - Object.assign(myOptions, options); + const targetDms = await Self.app.models.Dms.removeFile(ctx, WorkerDms.dmsFk, myOptions); - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } - // const workerDms = await Self.findById(id); - myOptions.model = 'WorkerDms'; - await models.Dms.removeFile(ctx, id, myOptions); - // await workerDms.destroy(); + if (!targetDms || !WorkerDms) + throw new UserError('Try again'); + + const workerDestroyed = await WorkerDms.destroy(myOptions); if (tx) await tx.commit(); - return workerDms; + return workerDestroyed; } catch (e) { await tx.rollback(); throw e; From b9efbc7d4413c363bca6431f6ba7423ff55cc993 Mon Sep 17 00:00:00 2001 From: robert Date: Wed, 13 Dec 2023 14:30:29 +0100 Subject: [PATCH 47/75] refs #5854 --- modules/item/back/locale/item-shelving/en.yml | 10 +++++----- modules/item/back/locale/item-shelving/es.yml | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/modules/item/back/locale/item-shelving/en.yml b/modules/item/back/locale/item-shelving/en.yml index 062d4db3f..997815b2c 100644 --- a/modules/item/back/locale/item-shelving/en.yml +++ b/modules/item/back/locale/item-shelving/en.yml @@ -1,13 +1,13 @@ name: itemShelving columns: id: id - itemFk: itemFk - shelvingFk: shelvingFk + itemFk: item + shelvingFk: shelving visible: visible created: created grouping: grouping packing: packing - packagingFk: packagingFk - userFk: userFk + packagingFk: package + userFk: user isChecked: isChecked - buyFk: buyFk + buyFk: buy diff --git a/modules/item/back/locale/item-shelving/es.yml b/modules/item/back/locale/item-shelving/es.yml index 3aedcd0bf..f00dfd6c5 100644 --- a/modules/item/back/locale/item-shelving/es.yml +++ b/modules/item/back/locale/item-shelving/es.yml @@ -7,7 +7,7 @@ columns: created: creado grouping: grouping packing: packing - packagingFk: paquete + packagingFk: embalaje userFk: usuario isChecked: está revisado buyFk: compra \ No newline at end of file From 40499e44cf8d38dbaadb8501c8829d23ec5f7008 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 13 Dec 2023 15:05:41 +0100 Subject: [PATCH 48/75] refs #6220 remove concat --- modules/client/back/methods/client/filter.js | 10 ++++++---- .../client/back/methods/client/specs/filter.spec.js | 2 +- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/modules/client/back/methods/client/filter.js b/modules/client/back/methods/client/filter.js index 43310c86b..e703ce53d 100644 --- a/modules/client/back/methods/client/filter.js +++ b/modules/client/back/methods/client/filter.js @@ -145,16 +145,18 @@ module.exports = Self => { c.name, c.fi, c.socialName, - CONCAT(c.phone, ',',GROUP_CONCAT(DISTINCT a.phone)) phone, + c.phone, + a.phone, c.mobile, - CONCAT(c.city, ',',GROUP_CONCAT(DISTINCT a.city)) city, + c.city, + a.city, c.postcode, a.postalCode, c.email, c.isActive, c.isFreezed, - p.id AS provinceFk2, - a.provinceFk, + p.id AS provinceClientFk, + a.provinceFk AS provinceAddressFk, p.name AS province, u.id AS salesPersonFk, u.name AS salesPerson diff --git a/modules/client/back/methods/client/specs/filter.spec.js b/modules/client/back/methods/client/specs/filter.spec.js index 4a61f8aaf..679585050 100644 --- a/modules/client/back/methods/client/specs/filter.spec.js +++ b/modules/client/back/methods/client/specs/filter.spec.js @@ -146,7 +146,7 @@ describe('client filter()', () => { const randomResultClient = result[randomIndex]; expect(result.length).toBeGreaterThanOrEqual(20); - expect(randomResultClient.city.toLowerCase()).toEqual('gotham,gotham'); + expect(randomResultClient.city.toLowerCase()).toEqual('gotham'); await tx.rollback(); } catch (e) { From 06bae4482495653d63c30762bc7dcc1a3b84b6cc Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 13 Dec 2023 15:38:46 +0100 Subject: [PATCH 49/75] refs #2051 perf: uploadFile after review --- .../claim/back/methods/claim/uploadFile.js | 56 +++---------------- .../client/back/methods/client/uploadFile.js | 23 +++----- .../ticket/back/methods/ticket/uploadFile.js | 22 +++----- .../back/methods/worker-dms/removeFile.js | 10 +++- .../worker/back/methods/worker/uploadFile.js | 19 ++----- modules/worker/front/dms/edit/index.js | 42 ++++++++------ 6 files changed, 64 insertions(+), 108 deletions(-) diff --git a/modules/claim/back/methods/claim/uploadFile.js b/modules/claim/back/methods/claim/uploadFile.js index 7e4798fef..4fd041456 100644 --- a/modules/claim/back/methods/claim/uploadFile.js +++ b/modules/claim/back/methods/claim/uploadFile.js @@ -54,7 +54,7 @@ module.exports = Self => { }); Self.uploadFile = async(ctx, id, options) => { - const models = Self.app.models; + const {Dms, ClaimDms} = Self.app.models; const myOptions = {}; let tx; @@ -66,56 +66,14 @@ module.exports = Self => { myOptions.transaction = tx; } - // const promises = []; - // const TempContainer = models.TempContainer; - // const ClaimContainer = models.ClaimContainer; - // const fileOptions = {}; - // const args = ctx.args; - - // let srcFile; try { - myOptions.model = 'ClaimDms'; - myOptions.create = {claimFk: id}; - const uploadedFiles = await models.Dms.uploadFile(ctx, myOptions); + const uploadedFiles = await Dms.uploadFile(ctx, myOptions); - // const hasWriteRole = await models.DmsType.hasWriteRole(ctx, args.dmsTypeId, myOptions); - // if (!hasWriteRole) - // throw new UserError(`You don't have enough privileges`); - - // // Upload file to temporary path - // const tempContainer = await TempContainer.container('dms'); - // const uploaded = await TempContainer.upload(tempContainer.name, ctx.req, ctx.result, fileOptions); - // const files = Object.values(uploaded.files).map(file => { - // return file[0]; - // }); - - // const addedDms = []; - // for (const uploadedFile of files) { - // const newDms = await createDms(ctx, uploadedFile, myOptions); - // const pathHash = ClaimContainer.getHash(newDms.id); - - // const file = await TempContainer.getFile(tempContainer.name, uploadedFile.name); - // srcFile = path.join(file.client.root, file.container, file.name); - - // const claimContainer = await ClaimContainer.container(pathHash); - // const dstFile = path.join(claimContainer.client.root, pathHash, newDms.file); - - // await fs.move(srcFile, dstFile, { - // overwrite: true - // }); - - // addedDms.push(newDms); - // } - - // addedDms.forEach(dms => { - // const newClaimDms = models.ClaimDms.create({ - // claimFk: id, - // dmsFk: dms.id - // }, myOptions); - - // promises.push(newClaimDms); - // }); - // const resolvedPromises = await Promise.all(promises); + const promises = uploadedFiles.map(dms => ClaimDms.create({ + claimFk: id, + dmsFk: dms.id + }, myOptions)); + await Promise.all(promises); if (tx) await tx.commit(); diff --git a/modules/client/back/methods/client/uploadFile.js b/modules/client/back/methods/client/uploadFile.js index 8f471f1b6..1a5965955 100644 --- a/modules/client/back/methods/client/uploadFile.js +++ b/modules/client/back/methods/client/uploadFile.js @@ -55,7 +55,7 @@ module.exports = Self => { }); Self.uploadFile = async(ctx, id, options) => { - const models = Self.app.models; + const {Dms, ClientDms} = Self.app.models; const myOptions = {}; let tx; @@ -67,21 +67,16 @@ module.exports = Self => { myOptions.transaction = tx; } - // const promises = []; - try { - myOptions.model = 'ClientDms'; - myOptions.create = {clientFk: id}; - const uploadedFiles = await models.Dms.uploadFile(ctx, myOptions); - // uploadedFiles.forEach(dms => { - // const newClientDms = models.ClientDms.create({ - // clientFk: id, - // dmsFk: dms.id - // }, myOptions); + const uploadedFiles = await Dms.uploadFile(ctx, myOptions); + const promises = uploadedFiles.map(dms => + ClientDms.create({ + clientFk: id, + dmsFk: dms.id + }, myOptions) - // promises.push(newClientDms); - // }); - // const resolvedPromises = await Promise.all(promises); + ); + await Promise.all(promises); if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/ticket/uploadFile.js b/modules/ticket/back/methods/ticket/uploadFile.js index 63bbe845a..eb563783c 100644 --- a/modules/ticket/back/methods/ticket/uploadFile.js +++ b/modules/ticket/back/methods/ticket/uploadFile.js @@ -47,7 +47,7 @@ module.exports = Self => { }); Self.uploadFile = async(ctx, id, options) => { - const models = Self.app.models; + const {Dms, TicketDms} = Self.app.models; const myOptions = {}; let tx; @@ -59,21 +59,15 @@ module.exports = Self => { myOptions.transaction = tx; } - // const promises = []; try { - myOptions.model = 'TicketDms'; - myOptions.create = {ticketFk: id}; - const uploadedFiles = await models.Dms.uploadFile(ctx, myOptions); - /* uploadedFiles.forEach(dms => { - const newTicketDms = models.TicketDms.create({ - ticketFk: id, - dmsFk: dms.id - }, myOptions); + const uploadedFiles = await Dms.uploadFile(ctx, myOptions); + const promises = uploadedFiles.map(dms => TicketDms.create({ + ticketFk: id, + dmsFk: dms.id + }, myOptions)); + + await Promise.all(promises); - promises.push(newTicketDms); - }); - const resolvedPromises = await Promise.all(promises); -*/ if (tx) await tx.commit(); return uploadedFiles; diff --git a/modules/worker/back/methods/worker-dms/removeFile.js b/modules/worker/back/methods/worker-dms/removeFile.js index 6c7b6b850..9fddc8b4b 100644 --- a/modules/worker/back/methods/worker-dms/removeFile.js +++ b/modules/worker/back/methods/worker-dms/removeFile.js @@ -30,9 +30,15 @@ module.exports = Self => { } try { - const WorkerDms = await Self.findById(id, null, myOptions); + // const dms = await Self.app.models.Dms.findById(id, null, myOptions); + const WorkerDms = await Self.findOne({ + where: {document: id} + }, myOptions); - const targetDms = await Self.app.models.Dms.removeFile(ctx, WorkerDms.dmsFk, myOptions); + // const targetDms = await Self.app.models.Dms.removeFile(ctx, id, myOptions); + // const WorkerDms = await Self.findById(+targetDms.reference, null, myOptions); + + const targetDms = await Self.app.models.Dms.removeFile(ctx, id, myOptions); if (!targetDms || !WorkerDms) throw new UserError('Try again'); diff --git a/modules/worker/back/methods/worker/uploadFile.js b/modules/worker/back/methods/worker/uploadFile.js index e624dc904..c3526cbb1 100644 --- a/modules/worker/back/methods/worker/uploadFile.js +++ b/modules/worker/back/methods/worker/uploadFile.js @@ -47,10 +47,9 @@ module.exports = Self => { }); Self.uploadFile = async(ctx, id) => { - const models = Self.app.models; + const {Dms, WorkerDms} = Self.app.models; const myOptions = {}; let tx; - // const promises = []; if (typeof options == 'object') Object.assign(myOptions, options); @@ -61,20 +60,14 @@ module.exports = Self => { } try { - myOptions.model = 'WorkerDms'; - myOptions.create = {workerFk: id}; - - const uploadedFiles = await models.Dms.uploadFile(ctx, myOptions); - /* uploadedFiles.forEach(dms => { - const newWorkerDms = models.WorkerDms.create({ + const uploadedFiles = await Dms.uploadFile(ctx, myOptions); + const promises = uploadedFiles.map(dms => + WorkerDms.create({ workerFk: id, dmsFk: dms.id - }, options); + }, myOptions)); + await Promise.all(promises); - promises.push(newWorkerDms); - }); - const resolvedPromises = await Promise.all(promises); -*/ if (tx) await tx.commit(); return uploadedFiles; diff --git a/modules/worker/front/dms/edit/index.js b/modules/worker/front/dms/edit/index.js index 8a1790563..31d4c2853 100644 --- a/modules/worker/front/dms/edit/index.js +++ b/modules/worker/front/dms/edit/index.js @@ -1,8 +1,8 @@ import ngModule from '../../module'; -import SectionDms from 'salix/components/section-dms'; +import Section from 'salix/components/section'; import './style.scss'; -class Controller extends SectionDms { +class Controller extends Section { get worker() { return this._worker; } @@ -11,29 +11,39 @@ class Controller extends SectionDms { this._worker = value; if (value) { - this.getDms(this.$params.dmsId).then(handleDefaultParams); - - this.getAllowedContentTypes().then(data => this.allowedContentTypes = data); + this.setDefaultParams(); + this.getAllowedContentTypes(); } } + getAllowedContentTypes() { + this.$http.get('DmsContainers/allowedContentTypes').then(res => { + const contentTypes = res.data.join(', '); + this.allowedContentTypes = contentTypes; + }); + } + get contentTypesInfo() { return this.$t('ContentTypesInfo', { allowedContentTypes: this.allowedContentTypes }); } - handleDefaultParams({data: dms}) { - this.dms = { - reference: dms.reference, - warehouseId: dms.warehouseFk, - companyId: dms.companyFk, - dmsTypeId: dms.dmsTypeFk, - description: dms.description, - hasFile: dms.hasFile, - hasFileAttached: false, - files: [] - }; + setDefaultParams() { + const path = `Dms/${this.$params.dmsId}`; + this.$http.get(path).then(res => { + const dms = res.data && res.data; + this.dms = { + reference: dms.reference, + warehouseId: dms.warehouseFk, + companyId: dms.companyFk, + dmsTypeId: dms.dmsTypeFk, + description: dms.description, + hasFile: dms.hasFile, + hasFileAttached: false, + files: [] + }; + }); } onSubmit() { From d7454cdb198fab8e5cb0292935a15e90e7378fa7 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 14 Dec 2023 11:41:59 +0100 Subject: [PATCH 50/75] refs #6576 fix: correct version --- CHANGELOG.md | 11 ++--------- db/changes/235201/.gitkeep | 0 db/dump/fixtures.sql | 4 ---- package.json | 2 +- 4 files changed, 3 insertions(+), 14 deletions(-) delete mode 100644 db/changes/235201/.gitkeep diff --git a/CHANGELOG.md b/CHANGELOG.md index dfdc563fb..45912aff3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,17 +5,10 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [2352.01] - 2023-12-28 - -### Added -### Changed -### Fixed - ## [2350.01] - 2023-12-14 -### Added -### Changed -### Fixed +### Características Añadidas 🆕 +- **Tickets → Expediciones:** Añadido soporte para Viaexpress ## [2348.01] - 2023-11-30 diff --git a/db/changes/235201/.gitkeep b/db/changes/235201/.gitkeep deleted file mode 100644 index e69de29bb..000000000 diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index f422dcb45..3354e95c2 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -5,10 +5,6 @@ SET DEFAULT ROLE 'salix' FOR 'root'@'%'; CREATE SCHEMA IF NOT EXISTS `vn2008`; CREATE SCHEMA IF NOT EXISTS `tmp`; -CREATE ROLE 'salix'; -GRANT 'salix' TO 'root'@'%'; -SET DEFAULT ROLE 'salix' FOR 'root'@'%'; - UPDATE `util`.`config` SET `environment`= 'development'; diff --git a/package.json b/package.json index 66a5cd2fa..586c963dd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "23.52.01", + "version": "23.50.01", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", From 61a323078bd1e30f6ba402570e39700a503aed2f Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 14 Dec 2023 12:04:05 +0100 Subject: [PATCH 51/75] refs #6264 fix: remove DEFAULT_COURTESY_TIME --- back/methods/vn-user/renew-token.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index e7e826cd1..d2f322d40 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -1,8 +1,7 @@ const UserError = require('vn-loopback/util/user-error'); const {models} = require('vn-loopback/server/server'); -const DEFAULT_COURTESY_TIME = 60; -const handlePromiseLogout = (Self, {id}, courtesyTime = DEFAULT_COURTESY_TIME) => { +const handlePromiseLogout = (Self, {id}, courtesyTime) => { new Promise(res => { setTimeout(() => { res(Self.logout(id)); From 8d2985091793832c403e1553e60ddef9f5d222c4 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 14 Dec 2023 12:21:07 +0100 Subject: [PATCH 52/75] refs #6264 perf: remove UserError exception --- back/methods/vn-user/renew-token.js | 3 ++- back/methods/vn-user/specs/renew-token.spec.js | 10 +++++----- front/core/services/token.js | 4 ---- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index d2f322d40..194747949 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -29,7 +29,8 @@ module.exports = Self => { // Check if current token is valid const isValid = await validateToken(token); - if (isValid) throw new UserError(`The renew period has not been exceeded`, 'periodNotExceeded'); + if (isValid) + return token; const {courtesyTime} = await models.AccessTokenConfig.findOne({fields: ['courtesyTime']}); diff --git a/back/methods/vn-user/specs/renew-token.spec.js b/back/methods/vn-user/specs/renew-token.spec.js index 21d3de1a9..b6c15e3c2 100644 --- a/back/methods/vn-user/specs/renew-token.spec.js +++ b/back/methods/vn-user/specs/renew-token.spec.js @@ -37,13 +37,13 @@ describe('Renew Token', () => { it('NOT should renew', async() => { let error; try { - await models.VnUser.renewToken(ctx); + const response = await models.VnUser.renewToken(ctx); + + expect(error).toBeUnDefined(); + expect(error.statusCode).toBe(200); + expect(response.token.id).toEqual(ctx.req.accessToken.id); } catch (e) { error = e; } - - expect(error).toBeDefined(); - expect(error.statusCode).toBe(400); - expect(error.message).toEqual('The renew period has not been exceeded'); }); }); diff --git a/front/core/services/token.js b/front/core/services/token.js index f1408f7e3..c8cb4f6bb 100644 --- a/front/core/services/token.js +++ b/front/core/services/token.js @@ -103,10 +103,6 @@ export default class Token { const token = res.data; this.set(token.id, now, token.ttl, this.remember); }) - .catch(res => { - if (res.data?.error?.code !== 'periodNotExceeded') - throw res; - }) .finally(() => { this.checking = false; }); From d2461d67c954a7d249425733af1771aae5a0b7c2 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 14 Dec 2023 12:25:40 +0100 Subject: [PATCH 53/75] refs #6264 test: perf renew-token.spec.js --- back/methods/vn-user/specs/renew-token.spec.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/back/methods/vn-user/specs/renew-token.spec.js b/back/methods/vn-user/specs/renew-token.spec.js index b6c15e3c2..674ce36f4 100644 --- a/back/methods/vn-user/specs/renew-token.spec.js +++ b/back/methods/vn-user/specs/renew-token.spec.js @@ -36,14 +36,14 @@ describe('Renew Token', () => { it('NOT should renew', async() => { let error; + let response; try { - const response = await models.VnUser.renewToken(ctx); - - expect(error).toBeUnDefined(); - expect(error.statusCode).toBe(200); - expect(response.token.id).toEqual(ctx.req.accessToken.id); + response = await models.VnUser.renewToken(ctx); } catch (e) { error = e; } + + expect(error).toBeUndefined(); + expect(response.id).toEqual(ctx.req.accessToken.id); }); }); From d0af29c0c57d9c19270ddbd502170201219ef1d8 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 14 Dec 2023 12:28:41 +0100 Subject: [PATCH 54/75] refs #6264 test: remove force describe for dms test --- back/methods/dms/specs/removeFile.spec.js | 2 +- modules/claim/back/methods/claim-dms/specs/removeFile.spec.js | 2 +- modules/client/back/methods/client-dms/specs/removeFile.spec.js | 2 +- modules/ticket/back/methods/ticket-dms/specs/removeFile.spec.js | 2 +- modules/ticket/back/methods/ticket/specs/uploadFile.spec.js | 2 +- modules/worker/back/methods/worker-dms/specs/removeFile.spec.js | 2 +- modules/worker/back/methods/worker/specs/uploadFile.spec.js | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/back/methods/dms/specs/removeFile.spec.js b/back/methods/dms/specs/removeFile.spec.js index e0d1dc1e7..59a2acecb 100644 --- a/back/methods/dms/specs/removeFile.spec.js +++ b/back/methods/dms/specs/removeFile.spec.js @@ -1,6 +1,6 @@ const {models} = require('vn-loopback/server/server'); -fdescribe('dms removeFile()', () => { +describe('dms removeFile()', () => { let dmsId = 1; it(`should return an error for a user without enough privileges`, async() => { diff --git a/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js b/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js index 210d805e7..108427b4c 100644 --- a/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js +++ b/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js @@ -1,7 +1,7 @@ const app = require('vn-loopback/server/server'); // f -fdescribe('TicketDms removeFile()', () => { +describe('TicketDms removeFile()', () => { const ticketDmsId = 1; it(`should return an error for a user without enough privileges`, async() => { let clientId = 1101; diff --git a/modules/client/back/methods/client-dms/specs/removeFile.spec.js b/modules/client/back/methods/client-dms/specs/removeFile.spec.js index 61a00a610..95c7d2ac4 100644 --- a/modules/client/back/methods/client-dms/specs/removeFile.spec.js +++ b/modules/client/back/methods/client-dms/specs/removeFile.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; // f -fdescribe('ClientDms removeFile()', () => { +describe('ClientDms removeFile()', () => { it(`should return an error for a user without enough privileges`, async() => { const tx = await models.Client.beginTransaction({}); diff --git a/modules/ticket/back/methods/ticket-dms/specs/removeFile.spec.js b/modules/ticket/back/methods/ticket-dms/specs/removeFile.spec.js index ca4cb5bc3..9296984c3 100644 --- a/modules/ticket/back/methods/ticket-dms/specs/removeFile.spec.js +++ b/modules/ticket/back/methods/ticket-dms/specs/removeFile.spec.js @@ -1,6 +1,6 @@ const models = require('vn-loopback/server/server').models; -fdescribe('TicketDms removeFile()', () => { +describe('TicketDms removeFile()', () => { const ticketDmsId = 1; it(`should return an error for a user without enough privileges`, async() => { const tx = await models.TicketDms.beginTransaction({}); diff --git a/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js b/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js index 8c01133e6..70d532076 100644 --- a/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js +++ b/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js @@ -1,6 +1,6 @@ const models = require('vn-loopback/server/server').models; // f -fdescribe('Ticket uploadFile()', () => { +describe('Ticket uploadFile()', () => { it(`should return an error for a user without enough privileges`, async() => { const tx = await models.Ticket.beginTransaction({}); diff --git a/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js b/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js index e66628656..82c6c3edd 100644 --- a/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js +++ b/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js @@ -1,7 +1,7 @@ const app = require('vn-loopback/server/server'); // f -fdescribe('WorkerDms removeFile()', () => { +describe('WorkerDms removeFile()', () => { const workerDmsFk = 1; it(`should return an error for a user without enough privileges`, async() => { let clientId = 1101; diff --git a/modules/worker/back/methods/worker/specs/uploadFile.spec.js b/modules/worker/back/methods/worker/specs/uploadFile.spec.js index 34426c6a0..71145ef5f 100644 --- a/modules/worker/back/methods/worker/specs/uploadFile.spec.js +++ b/modules/worker/back/methods/worker/specs/uploadFile.spec.js @@ -1,6 +1,6 @@ const app = require('vn-loopback/server/server'); // f -fdescribe('Worker uploadFile()', () => { +describe('Worker uploadFile()', () => { it(`should return an error for a user without enough privileges`, async() => { let workerId = 1106; let currentUserId = 1102; From 1939c65fabcdf68ffb351ba5b51bbb3763d8b7e2 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 14 Dec 2023 12:35:54 +0100 Subject: [PATCH 55/75] refs #6264 test: remove force describe for dms test --- .../claim-dms/specs/removeFile.spec.js | 1 - .../client-dms/specs/removeFile.spec.js | 1 - .../methods/ticket/specs/uploadFile.spec.js | 25 +------------------ .../ticket/back/methods/ticket/uploadFile.js | 1 + .../back/methods/worker-dms/removeFile.js | 4 --- .../worker-dms/specs/removeFile.spec.js | 1 - .../methods/worker/specs/uploadFile.spec.js | 2 +- 7 files changed, 3 insertions(+), 32 deletions(-) diff --git a/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js b/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js index 108427b4c..1cd3b16cb 100644 --- a/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js +++ b/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js @@ -1,6 +1,5 @@ const app = require('vn-loopback/server/server'); -// f describe('TicketDms removeFile()', () => { const ticketDmsId = 1; it(`should return an error for a user without enough privileges`, async() => { diff --git a/modules/client/back/methods/client-dms/specs/removeFile.spec.js b/modules/client/back/methods/client-dms/specs/removeFile.spec.js index 95c7d2ac4..6dac71293 100644 --- a/modules/client/back/methods/client-dms/specs/removeFile.spec.js +++ b/modules/client/back/methods/client-dms/specs/removeFile.spec.js @@ -1,6 +1,5 @@ const models = require('vn-loopback/server/server').models; -// f describe('ClientDms removeFile()', () => { it(`should return an error for a user without enough privileges`, async() => { const tx = await models.Client.beginTransaction({}); diff --git a/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js b/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js index 70d532076..133c13265 100644 --- a/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js +++ b/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js @@ -1,5 +1,5 @@ const models = require('vn-loopback/server/server').models; -// f + describe('Ticket uploadFile()', () => { it(`should return an error for a user without enough privileges`, async() => { const tx = await models.Ticket.beginTransaction({}); @@ -23,27 +23,4 @@ describe('Ticket uploadFile()', () => { expect(error.message).toEqual(`You don't have enough privileges`); }); - - // fit(`should uploadFile`, async() => { - // const tx = await models.Ticket.beginTransaction({}); - - // let error; - // try { - // const options = {transaction: tx}; - - // const ticketId = 15; - // const currentUserId = 9; - // const ticketTypeId = 14; - // const ctx = {req: {accessToken: {userId: currentUserId}}, args: {dmsTypeId: ticketTypeId}, result: new ArrayBuffer(20000)}; - - // await models.Ticket.uploadFile(ctx, ticketId, options); - - // await tx.rollback(); - // } catch (e) { - // await tx.rollback(); - // error = e; - // } - - // expect(error.message).toEqual(`You don't have enough privileges`); - // }); }); diff --git a/modules/ticket/back/methods/ticket/uploadFile.js b/modules/ticket/back/methods/ticket/uploadFile.js index eb563783c..5b79aa973 100644 --- a/modules/ticket/back/methods/ticket/uploadFile.js +++ b/modules/ticket/back/methods/ticket/uploadFile.js @@ -61,6 +61,7 @@ module.exports = Self => { try { const uploadedFiles = await Dms.uploadFile(ctx, myOptions); + const promises = uploadedFiles.map(dms => TicketDms.create({ ticketFk: id, dmsFk: dms.id diff --git a/modules/worker/back/methods/worker-dms/removeFile.js b/modules/worker/back/methods/worker-dms/removeFile.js index 9fddc8b4b..343d6d50b 100644 --- a/modules/worker/back/methods/worker-dms/removeFile.js +++ b/modules/worker/back/methods/worker-dms/removeFile.js @@ -30,14 +30,10 @@ module.exports = Self => { } try { - // const dms = await Self.app.models.Dms.findById(id, null, myOptions); const WorkerDms = await Self.findOne({ where: {document: id} }, myOptions); - // const targetDms = await Self.app.models.Dms.removeFile(ctx, id, myOptions); - // const WorkerDms = await Self.findById(+targetDms.reference, null, myOptions); - const targetDms = await Self.app.models.Dms.removeFile(ctx, id, myOptions); if (!targetDms || !WorkerDms) diff --git a/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js b/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js index 82c6c3edd..3efd09464 100644 --- a/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js +++ b/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js @@ -1,6 +1,5 @@ const app = require('vn-loopback/server/server'); -// f describe('WorkerDms removeFile()', () => { const workerDmsFk = 1; it(`should return an error for a user without enough privileges`, async() => { diff --git a/modules/worker/back/methods/worker/specs/uploadFile.spec.js b/modules/worker/back/methods/worker/specs/uploadFile.spec.js index 71145ef5f..7a929cd2b 100644 --- a/modules/worker/back/methods/worker/specs/uploadFile.spec.js +++ b/modules/worker/back/methods/worker/specs/uploadFile.spec.js @@ -1,5 +1,5 @@ const app = require('vn-loopback/server/server'); -// f + describe('Worker uploadFile()', () => { it(`should return an error for a user without enough privileges`, async() => { let workerId = 1106; From 9316c31180da1f26ae30b0642980a8249936a0cc Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 14 Dec 2023 12:36:36 +0100 Subject: [PATCH 56/75] refs #6264 perf: rename variable when destroy ids --- modules/claim/back/methods/claim-dms/removeFile.js | 4 ++-- modules/client/back/methods/client-dms/removeFile.js | 4 ++-- modules/ticket/back/methods/ticket-dms/removeFile.js | 4 ++-- modules/worker/back/methods/worker-dms/removeFile.js | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/modules/claim/back/methods/claim-dms/removeFile.js b/modules/claim/back/methods/claim-dms/removeFile.js index 0f1da626c..28e78c9d7 100644 --- a/modules/claim/back/methods/claim-dms/removeFile.js +++ b/modules/claim/back/methods/claim-dms/removeFile.js @@ -40,11 +40,11 @@ module.exports = Self => { if (!targetDms || ! claimDms) throw new UserError('Try again'); - const claimDestroyed = await claimDms.destroy(myOptions); + const claimDmsDestroyed = await claimDms.destroy(myOptions); if (tx) await tx.commit(); - return claimDestroyed; + return claimDmsDestroyed; } catch (e) { if (tx) await tx.rollback(); throw e; diff --git a/modules/client/back/methods/client-dms/removeFile.js b/modules/client/back/methods/client-dms/removeFile.js index 5bd34adcf..bc9a0f719 100644 --- a/modules/client/back/methods/client-dms/removeFile.js +++ b/modules/client/back/methods/client-dms/removeFile.js @@ -38,11 +38,11 @@ module.exports = Self => { if (!targetDms || !clientDms) throw new UserError('Try again'); - const clientDestroyed = await clientDms.destroy(myOptions); + const clientDmsDestroyed = await clientDms.destroy(myOptions); if (tx) await tx.commit(); - return clientDestroyed; + return clientDmsDestroyed; } catch (e) { if (tx) await tx.rollback(); throw e; diff --git a/modules/ticket/back/methods/ticket-dms/removeFile.js b/modules/ticket/back/methods/ticket-dms/removeFile.js index 2f6426fbb..6fba4c552 100644 --- a/modules/ticket/back/methods/ticket-dms/removeFile.js +++ b/modules/ticket/back/methods/ticket-dms/removeFile.js @@ -38,11 +38,11 @@ module.exports = Self => { if (!targetDms || !ticketDms) throw new UserError('Try again'); - const ticketDestroyed = await ticketDms.destroy(myOptions); + const ticketDmsDestroyed = await ticketDms.destroy(myOptions); if (tx) await tx.commit(); - return ticketDestroyed; + return ticketDmsDestroyed; } catch (e) { if (tx) await tx.rollback(); throw e; diff --git a/modules/worker/back/methods/worker-dms/removeFile.js b/modules/worker/back/methods/worker-dms/removeFile.js index 343d6d50b..a5a3b6bb8 100644 --- a/modules/worker/back/methods/worker-dms/removeFile.js +++ b/modules/worker/back/methods/worker-dms/removeFile.js @@ -39,10 +39,10 @@ module.exports = Self => { if (!targetDms || !WorkerDms) throw new UserError('Try again'); - const workerDestroyed = await WorkerDms.destroy(myOptions); + const workerDmsDestroyed = await WorkerDms.destroy(myOptions); if (tx) await tx.commit(); - return workerDestroyed; + return workerDmsDestroyed; } catch (e) { await tx.rollback(); throw e; From bbb9f58a9edaa16b442cedbf7bb3226a18651b1d Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 14 Dec 2023 14:37:14 +0100 Subject: [PATCH 57/75] refs #6220 fix(client_filter): fix where --- modules/client/back/methods/client/filter.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/modules/client/back/methods/client/filter.js b/modules/client/back/methods/client/filter.js index e703ce53d..f805c4be9 100644 --- a/modules/client/back/methods/client/filter.js +++ b/modules/client/back/methods/client/filter.js @@ -113,18 +113,18 @@ module.exports = Self => { return {'a.postalCode': {inq: postalCode}}; case 'city': return {or: [ - {'c.city': {like: `%${value}`}}, - {'a.city': {like: `%${value}`}} + {'c.city': {like: `%${value}%`}}, + {'a.city': {like: `%${value}%`}} ]}; case 'postcode': return {or: [ - {'c.postcode': {like: `%${value}`}}, - {'a.postalCode': {like: `%${value}`}} + {'c.postcode': value}, + {'a.postalCode': value} ]}; case 'provinceFk': return {or: [ - {'p.name': {like: `%${value}`}}, - {'a.provinceFk': {like: `%${value}`}} + {'p.id': value}, + {'a.provinceFk': value} ]}; case 'name': case 'salesPersonFk': From c9af8cba816a04088347151447c833616371c306 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Fri, 15 Dec 2023 12:50:05 +0100 Subject: [PATCH 58/75] refs #5878 feat: remove . for this message --- front/salix/locale/es.yml | 2 +- loopback/locale/en.json | 4 ++-- loopback/locale/es.json | 4 ++-- modules/ticket/back/methods/ticket/isEditableOrThrow.js | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/front/salix/locale/es.yml b/front/salix/locale/es.yml index 8ed58a4e4..044d0d043 100644 --- a/front/salix/locale/es.yml +++ b/front/salix/locale/es.yml @@ -18,7 +18,7 @@ Show summary: Mostrar vista previa What is new: Novedades de la versión Settings: Ajustes There is a new version, click here to reload: Hay una nueva versión, pulse aquí para recargar -This ticket is locked.: Este ticket está bloqueado +This ticket is locked: Este ticket está bloqueado # Actions diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 7d5b5ed47..c5e8d4fcf 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -183,7 +183,7 @@ "Social name should be uppercase": "Social name should be uppercase", "Street should be uppercase": "Street should be uppercase", "You don't have enough privileges.": "You don't have enough privileges.", - "This ticket is locked.": "This ticket is locked.", + "This ticket is locked": "This ticket is locked", "This ticket is not editable.": "This ticket is not editable.", "The ticket doesn't exist.": "The ticket doesn't exist.", "The sales do not exists": "The sales do not exists", @@ -201,4 +201,4 @@ "keepPrice": "keepPrice", "Cannot past travels with entries": "Cannot past travels with entries", "It was not able to remove the next expeditions:": "It was not able to remove the next expeditions: {{expeditions}}" -} \ No newline at end of file +} diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 01384efb4..a8134909e 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -312,7 +312,7 @@ "You cannot assign/remove an alias that you are not assigned to": "No puede asignar/eliminar un alias que no tenga asignado", "This invoice has a linked vehicle.": "Esta factura tiene un vehiculo vinculado", "You don't have enough privileges.": "No tienes suficientes permisos.", - "This ticket is locked.": "Este ticket está bloqueado.", + "This ticket is locked": "Este ticket está bloqueado.", "This ticket is not editable.": "Este ticket no es editable.", "The ticket doesn't exist.": "No existe el ticket.", "Social name should be uppercase": "La razón social debe ir en mayúscula", @@ -330,4 +330,4 @@ "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima", "Cannot past travels with entries": "No se pueden pasar envíos con entradas", "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}" -} \ No newline at end of file +} diff --git a/modules/ticket/back/methods/ticket/isEditableOrThrow.js b/modules/ticket/back/methods/ticket/isEditableOrThrow.js index f8285cecd..41438be3a 100644 --- a/modules/ticket/back/methods/ticket/isEditableOrThrow.js +++ b/modules/ticket/back/methods/ticket/isEditableOrThrow.js @@ -41,7 +41,7 @@ module.exports = Self => { throw new ForbiddenError(`This ticket is not editable.`); if (isLocked && !isWeekly) - throw new ForbiddenError(`This ticket is locked.`); + throw new ForbiddenError(`This ticket is locked`); if (isWeekly && !canEditWeeklyTicket) throw new ForbiddenError(`You don't have enough privileges.`); From dc98436b85cc52dfd09bb5b2138c442ae60b411d Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Fri, 15 Dec 2023 13:01:44 +0100 Subject: [PATCH 59/75] refs #2051 perf: rename variable --- modules/worker/back/methods/worker-dms/removeFile.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/worker/back/methods/worker-dms/removeFile.js b/modules/worker/back/methods/worker-dms/removeFile.js index a5a3b6bb8..8eb6c05fd 100644 --- a/modules/worker/back/methods/worker-dms/removeFile.js +++ b/modules/worker/back/methods/worker-dms/removeFile.js @@ -18,7 +18,7 @@ module.exports = Self => { } }); - Self.removeFile = async(ctx, id, options) => { + Self.removeFile = async(ctx, dmsFk, options) => { const myOptions = {}; let tx; if (typeof options == 'object') @@ -31,10 +31,10 @@ module.exports = Self => { try { const WorkerDms = await Self.findOne({ - where: {document: id} + where: {document: dmsFk} }, myOptions); - const targetDms = await Self.app.models.Dms.removeFile(ctx, id, myOptions); + const targetDms = await Self.app.models.Dms.removeFile(ctx, dmsFk, myOptions); if (!targetDms || !WorkerDms) throw new UserError('Try again'); From 8d650cf6c080782f6fd639ed6594725b8913c49b Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 18 Dec 2023 08:09:44 +0100 Subject: [PATCH 60/75] refs #6172 test: remove message code --- modules/ticket/back/methods/ticket/specs/addSale.spec.js | 2 +- .../back/methods/ticket/specs/isEditableOrThrow.spec.js | 4 ++-- .../back/methods/ticket/specs/recalculateComponents.spec.js | 2 +- .../ticket/back/methods/ticket/specs/transferClient.spec.js | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/ticket/back/methods/ticket/specs/addSale.spec.js b/modules/ticket/back/methods/ticket/specs/addSale.spec.js index 8c0e39bec..72c9541d9 100644 --- a/modules/ticket/back/methods/ticket/specs/addSale.spec.js +++ b/modules/ticket/back/methods/ticket/specs/addSale.spec.js @@ -89,6 +89,6 @@ describe('ticket addSale()', () => { error = e; } - expect(error.message).toEqual(`This ticket is locked.`); + expect(error.message).toEqual(`This ticket is locked`); }); }); diff --git a/modules/ticket/back/methods/ticket/specs/isEditableOrThrow.spec.js b/modules/ticket/back/methods/ticket/specs/isEditableOrThrow.spec.js index 6c89bac26..bdf547325 100644 --- a/modules/ticket/back/methods/ticket/specs/isEditableOrThrow.spec.js +++ b/modules/ticket/back/methods/ticket/specs/isEditableOrThrow.spec.js @@ -40,7 +40,7 @@ describe('ticket isEditableOrThrow()', () => { expect(error.message).toEqual(`This ticket is not editable.`); }); - it('should throw an error as this ticket is locked.', async() => { + it('should throw an error as This ticket is locked', async() => { const tx = await models.Ticket.beginTransaction({}); let error; try { @@ -57,7 +57,7 @@ describe('ticket isEditableOrThrow()', () => { await tx.rollback(); } - expect(error.message).toEqual(`This ticket is locked.`); + expect(error.message).toEqual(`This ticket is locked`); }); it('should throw an error as you do not have enough privileges.', async() => { diff --git a/modules/ticket/back/methods/ticket/specs/recalculateComponents.spec.js b/modules/ticket/back/methods/ticket/specs/recalculateComponents.spec.js index 383c2c6d5..d358a79f5 100644 --- a/modules/ticket/back/methods/ticket/specs/recalculateComponents.spec.js +++ b/modules/ticket/back/methods/ticket/specs/recalculateComponents.spec.js @@ -39,6 +39,6 @@ describe('ticket recalculateComponents()', () => { error = e; } - expect(error).toEqual(new ForbiddenError(`This ticket is locked.`)); + expect(error).toEqual(new ForbiddenError(`This ticket is locked`)); }); }); diff --git a/modules/ticket/back/methods/ticket/specs/transferClient.spec.js b/modules/ticket/back/methods/ticket/specs/transferClient.spec.js index c09c20083..5a9edd17e 100644 --- a/modules/ticket/back/methods/ticket/specs/transferClient.spec.js +++ b/modules/ticket/back/methods/ticket/specs/transferClient.spec.js @@ -23,7 +23,7 @@ describe('Ticket transferClient()', () => { error = e; } - expect(error.message).toEqual(`This ticket is locked.`); + expect(error.message).toEqual(`This ticket is locked`); }); it('should be assigned a different clientFk', async() => { From d60f2a7f88f44906f300e9c5c060ed4b5ec82f1e Mon Sep 17 00:00:00 2001 From: davidd Date: Tue, 19 Dec 2023 09:43:09 +0100 Subject: [PATCH 61/75] fix: refs #6398 Changed alias of views --- db/changes/235201/02-views.sql | 4 ++-- modules/ticket/back/methods/ticket/state.js | 4 ++-- modules/ticket/back/models/ticket-state.json | 8 ++++---- modules/ticket/back/models/ticket-tracking.json | 8 ++++---- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/db/changes/235201/02-views.sql b/db/changes/235201/02-views.sql index a0f41594d..af190f596 100644 --- a/db/changes/235201/02-views.sql +++ b/db/changes/235201/02-views.sql @@ -3,7 +3,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` VIEW `vn`.`ticketState` AS SELECT `tt`.`created` AS `updated`, `tt`.`stateFk` AS `stateFk`, - `tt`.`userFk` AS `userFk`, + `tt`.`userFk` AS `workerFk`, `tls`.`ticketFk` AS `ticketFk`, `s`.`id` AS `state`, `s`.`order` AS `productionOrder`, @@ -40,7 +40,7 @@ SELECT `ts`.`state` AS `state`, `ts`.`productionOrder` AS `productionOrder`, `ts`.`alertLevel` AS `alertLevel`, - `ts`.`userFk` AS `userFk`, + `ts`.`userFk` AS `worker`, `ts`.`code` AS `code`, `ts`.`updated` AS `updated`, `ts`.`isPicked` AS `isPicked` diff --git a/modules/ticket/back/methods/ticket/state.js b/modules/ticket/back/methods/ticket/state.js index adac2e42f..01bfbba20 100644 --- a/modules/ticket/back/methods/ticket/state.js +++ b/modules/ticket/back/methods/ticket/state.js @@ -51,12 +51,12 @@ module.exports = Self => { params.stateFk = state.id; } - if (!params.userFk) { + if (!params.workerFk) { const worker = await models.Worker.findOne({ where: {id: userId} }, myOptions); - params.userFk = worker.id; + params.workerFk = worker.id; } const ticketState = await models.TicketState.findById(params.ticketFk, { diff --git a/modules/ticket/back/models/ticket-state.json b/modules/ticket/back/models/ticket-state.json index 3ee50fac0..3dd322939 100644 --- a/modules/ticket/back/models/ticket-state.json +++ b/modules/ticket/back/models/ticket-state.json @@ -34,9 +34,9 @@ "foreignKey": "stateFk" }, "user": { - "type": "belongsTo", - "model": "VnUser", - "foreignKey": "userFk" - } + "type": "belongsTo", + "model": "VnUser", + "foreignKey": "workerFk" + } } } diff --git a/modules/ticket/back/models/ticket-tracking.json b/modules/ticket/back/models/ticket-tracking.json index 8b0617145..4b5a4d473 100644 --- a/modules/ticket/back/models/ticket-tracking.json +++ b/modules/ticket/back/models/ticket-tracking.json @@ -37,9 +37,9 @@ "foreignKey": "stateFk" }, "user": { - "type": "belongsTo", - "model": "VnUser", - "foreignKey": "userFk" - } + "type": "belongsTo", + "model": "VnUser", + "foreignKey": "userFk" + } } } From 17e177b7888adf882683876d75f20d6d79b64799 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 19 Dec 2023 10:12:03 +0100 Subject: [PATCH 62/75] fix: refs #6398 Fix tests back --- modules/ticket/back/methods/ticket/state.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/ticket/back/methods/ticket/state.js b/modules/ticket/back/methods/ticket/state.js index 01bfbba20..adac2e42f 100644 --- a/modules/ticket/back/methods/ticket/state.js +++ b/modules/ticket/back/methods/ticket/state.js @@ -51,12 +51,12 @@ module.exports = Self => { params.stateFk = state.id; } - if (!params.workerFk) { + if (!params.userFk) { const worker = await models.Worker.findOne({ where: {id: userId} }, myOptions); - params.workerFk = worker.id; + params.userFk = worker.id; } const ticketState = await models.TicketState.findById(params.ticketFk, { From 5936a129dad5caa678e5d276b1cec7ac22beccfa Mon Sep 17 00:00:00 2001 From: davidd Date: Tue, 19 Dec 2023 12:58:20 +0100 Subject: [PATCH 63/75] refs #6398 --- db/changes/235201/02-views.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/changes/235201/02-views.sql b/db/changes/235201/02-views.sql index af190f596..1d031c38d 100644 --- a/db/changes/235201/02-views.sql +++ b/db/changes/235201/02-views.sql @@ -40,7 +40,7 @@ SELECT `ts`.`state` AS `state`, `ts`.`productionOrder` AS `productionOrder`, `ts`.`alertLevel` AS `alertLevel`, - `ts`.`userFk` AS `worker`, + `ts`.`worker` AS `worker`, `ts`.`code` AS `code`, `ts`.`updated` AS `updated`, `ts`.`isPicked` AS `isPicked` From 516a3760a183fc42d5ea42fa3a6b7a90f8154a41 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 20 Dec 2023 07:27:13 +0100 Subject: [PATCH 64/75] feat: refs #6582 Added traductions --- modules/route/back/locale/route/en.yml | 15 +++++++++++++++ modules/route/back/locale/route/es.yml | 16 ++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/modules/route/back/locale/route/en.yml b/modules/route/back/locale/route/en.yml index 96aaddb72..12b16c38c 100644 --- a/modules/route/back/locale/route/en.yml +++ b/modules/route/back/locale/route/en.yml @@ -17,3 +17,18 @@ columns: agencyModeFk: agency routeFk: route zoneFk: zone + name: name + beachFk: beach + ticketPacked: tickets packed + ticketFree: tickets free + ticketProduction: tickets production + packages: packages + note: note + dated: dated + dockFk: dock + priority: priority + etd: etd + expeditionTruckFk: truck + m3boxes: m3 boxes + bufferFk: buffer + isPickingAllowed: is picking allowed diff --git a/modules/route/back/locale/route/es.yml b/modules/route/back/locale/route/es.yml index c0a434791..cf6afc211 100644 --- a/modules/route/back/locale/route/es.yml +++ b/modules/route/back/locale/route/es.yml @@ -17,3 +17,19 @@ columns: agencyModeFk: agencia routeFk: ruta zoneFk: zona + name: nombre + beachFk: playa + ticketPacked: tickets encajados + ticketFree: tickets libres + ticketProduction: tickets producción + packages: paquetes + note: nota + dated: fecha + dockFk: muelle + priority: prioridad + etd: etd + expeditionTruckFk: camión + m3boxes: m3 cajas + bufferFk: buffer + isPickingAllowed: está permitido recoger + From 753c6e9ec5e772f893e41d98f9f09175bbd28c36 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 20 Dec 2023 07:28:54 +0100 Subject: [PATCH 65/75] feat: refs #6582 Added traductions --- modules/route/back/locale/route/en.yml | 2 +- modules/route/back/locale/route/es.yml | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/modules/route/back/locale/route/en.yml b/modules/route/back/locale/route/en.yml index 12b16c38c..d86cbe342 100644 --- a/modules/route/back/locale/route/en.yml +++ b/modules/route/back/locale/route/en.yml @@ -31,4 +31,4 @@ columns: expeditionTruckFk: truck m3boxes: m3 boxes bufferFk: buffer - isPickingAllowed: is picking allowed + isPickingAllowed: is picking allowed \ No newline at end of file diff --git a/modules/route/back/locale/route/es.yml b/modules/route/back/locale/route/es.yml index cf6afc211..baefb6433 100644 --- a/modules/route/back/locale/route/es.yml +++ b/modules/route/back/locale/route/es.yml @@ -31,5 +31,4 @@ columns: expeditionTruckFk: camión m3boxes: m3 cajas bufferFk: buffer - isPickingAllowed: está permitido recoger - + isPickingAllowed: está permitido recoger \ No newline at end of file From 57b3d96628ff5a1d7618d3741373ab84d061e4a4 Mon Sep 17 00:00:00 2001 From: JAVIER SEGARRA MARTINEZ Date: Wed, 20 Dec 2023 09:27:25 +0000 Subject: [PATCH 66/75] refs #6434 fix: bad throw error --- back/models/vn-user.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 7b8a308c2..b1d09f0c0 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -142,8 +142,8 @@ module.exports = function(Self) { ip: ctx.req.ip, owner: isOwner }); - } throw new UserError('Try again'); + } }; /** From cb35c3632802ea9b94d41f8bb9fa321ed4b5c10f Mon Sep 17 00:00:00 2001 From: JAVIER SEGARRA MARTINEZ Date: Wed, 20 Dec 2023 10:59:36 +0000 Subject: [PATCH 67/75] refs #6434 test: update tests --- back/methods/vn-user/specs/sign-in.spec.js | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/back/methods/vn-user/specs/sign-in.spec.js b/back/methods/vn-user/specs/sign-in.spec.js index 1c4b4af51..a14dd301e 100644 --- a/back/methods/vn-user/specs/sign-in.spec.js +++ b/back/methods/vn-user/specs/sign-in.spec.js @@ -20,10 +20,7 @@ describe('VnUser Sign-in()', () => { let ctx = {req: {accessToken: accessToken}}; let signInLog = await SignInLog.find({where: {token: accessToken.id}}); - expect(signInLog.length).toEqual(1); - expect(signInLog[0].userFk).toEqual(accessToken.userId); - expect(signInLog[0].owner).toEqual(true); - expect(login.token).toBeDefined(); + expect(signInLog.length).toEqual(0); await VnUser.logout(ctx.req.accessToken.id); }); From 7b0c5fe0a00b5b8ce3410c8e69736e7615afe2d5 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 21 Dec 2023 08:33:50 +0100 Subject: [PATCH 68/75] refs #5739 fix: sql --- CHANGELOG.md | 6 ++++++ .../{235201 => 240001}/00-alterTable.sql | 0 .../00-clientCreditLimitToRoleCreditLimit.sql | 2 +- .../{235201 => 240001}/01-procedures.sql | 0 db/changes/{235201 => 240001}/02-views.sql | 18 +++++++++++------- db/dump/structure.sql | 1 + package-lock.json | 4 ++-- package.json | 2 +- 8 files changed, 22 insertions(+), 11 deletions(-) rename db/changes/{235201 => 240001}/00-alterTable.sql (100%) rename db/changes/{235201 => 240001}/00-clientCreditLimitToRoleCreditLimit.sql (74%) rename db/changes/{235201 => 240001}/01-procedures.sql (100%) rename db/changes/{235201 => 240001}/02-views.sql (79%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 45912aff3..b69b8a29b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [2400.01] - 2024-01-04 + +### Added +### Changed +### Fixed + ## [2350.01] - 2023-12-14 ### Características Añadidas 🆕 diff --git a/db/changes/235201/00-alterTable.sql b/db/changes/240001/00-alterTable.sql similarity index 100% rename from db/changes/235201/00-alterTable.sql rename to db/changes/240001/00-alterTable.sql diff --git a/db/changes/235201/00-clientCreditLimitToRoleCreditLimit.sql b/db/changes/240001/00-clientCreditLimitToRoleCreditLimit.sql similarity index 74% rename from db/changes/235201/00-clientCreditLimitToRoleCreditLimit.sql rename to db/changes/240001/00-clientCreditLimitToRoleCreditLimit.sql index bf4cc6002..2bc0f830d 100644 --- a/db/changes/235201/00-clientCreditLimitToRoleCreditLimit.sql +++ b/db/changes/240001/00-clientCreditLimitToRoleCreditLimit.sql @@ -1,4 +1,4 @@ RENAME TABLE `vn`.`clientCreditLimit` TO `vn`.`roleCreditLimit`; -ALTER TABLE `vn`.`clientCreditLimit` DROP FOREIGN KEY `clientCreditLimit_FK`; +ALTER TABLE `vn`.`roleCreditLimit` DROP FOREIGN KEY `clientCreditLimit_FK`; ALTER TABLE `vn`.`roleCreditLimit` ADD CONSTRAINT `roleCreditLimit_FK` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/db/changes/235201/01-procedures.sql b/db/changes/240001/01-procedures.sql similarity index 100% rename from db/changes/235201/01-procedures.sql rename to db/changes/240001/01-procedures.sql diff --git a/db/changes/235201/02-views.sql b/db/changes/240001/02-views.sql similarity index 79% rename from db/changes/235201/02-views.sql rename to db/changes/240001/02-views.sql index 1d031c38d..86a1049a7 100644 --- a/db/changes/235201/02-views.sql +++ b/db/changes/240001/02-views.sql @@ -1,6 +1,9 @@ +CREATE SCHEMA IF NOT EXISTS `vn2008`; +USE `vn`; + CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER - VIEW `vn`.`ticketState` + VIEW `ticketState` AS SELECT `tt`.`created` AS `updated`, `tt`.`stateFk` AS `stateFk`, `tt`.`userFk` AS `workerFk`, @@ -15,10 +18,10 @@ AS SELECT `tt`.`created` AS `updated`, `s`.`isPicked` AS `isPicked` FROM ( ( - `vn`.`ticketLastState` `tls` - JOIN `vn`.`ticketTracking` `tt` ON(`tt`.`id` = `tls`.`ticketTrackingFk`) + `ticketLastState` `tls` + JOIN `ticketTracking` `tt` ON(`tt`.`id` = `tls`.`ticketTrackingFk`) ) - JOIN `vn`.`state` `s` ON(`s`.`id` = `tt`.`stateFk`) + JOIN `state` `s` ON(`s`.`id` = `tt`.`stateFk`) ); CREATE OR REPLACE DEFINER=`root`@`localhost` @@ -33,9 +36,10 @@ AS SELECT `tt`.`id` AS `inter_id`, `tt`.`supervisorFk` AS `Id_supervisor` FROM `vn`.`ticketTracking` `tt`; -CREATE OR REPLACE -ALGORITHM = UNDEFINED VIEW `ticketStateToday` AS -SELECT +CREATE OR REPLACE DEFINER=`root`@`localhost` + SQL SECURITY DEFINER + VIEW `ticketStateToday` +AS SELECT `ts`.`ticket` AS `ticket`, `ts`.`state` AS `state`, `ts`.`productionOrder` AS `productionOrder`, diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 1db4252f4..694f745ef 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -26391,6 +26391,7 @@ CREATE TABLE `cplusCorrectingType` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `cplusRectificationType` -- diff --git a/package-lock.json b/package-lock.json index 78ef93987..27216b234 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "salix-back", - "version": "23.50.01", + "version": "24.00.01", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "salix-back", - "version": "23.50.01", + "version": "24.00.01", "license": "GPL-3.0", "dependencies": { "axios": "^1.2.2", diff --git a/package.json b/package.json index 586c963dd..e8ceaf5f1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "23.50.01", + "version": "24.00.01", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", From 38279b07868591761fcdcfb4d4b1b69992ffa307 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 21 Dec 2023 08:37:30 +0100 Subject: [PATCH 69/75] refs #6594 deploy: init version 24.02 --- CHANGELOG.md | 6 ++++++ db/changes/240201/.gitkeep | 0 package-lock.json | 4 ++-- package.json | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) create mode 100644 db/changes/240201/.gitkeep diff --git a/CHANGELOG.md b/CHANGELOG.md index b69b8a29b..1907f46bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [2402.01] - 2024-01-11 + +### Added +### Changed +### Fixed + ## [2400.01] - 2024-01-04 ### Added diff --git a/db/changes/240201/.gitkeep b/db/changes/240201/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/package-lock.json b/package-lock.json index 27216b234..012fb50e7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "salix-back", - "version": "24.00.01", + "version": "24.02.01", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "salix-back", - "version": "24.00.01", + "version": "24.02.01", "license": "GPL-3.0", "dependencies": { "axios": "^1.2.2", diff --git a/package.json b/package.json index e8ceaf5f1..ab3d99e19 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "24.00.01", + "version": "24.02.01", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", From dc661f298bfe6c8f4f858bbee0097472435c7379 Mon Sep 17 00:00:00 2001 From: JAVIER SEGARRA MARTINEZ Date: Thu, 21 Dec 2023 09:10:18 +0000 Subject: [PATCH 70/75] refs #6434 test: update tests --- back/methods/vn-user/specs/renew-token.spec.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/back/methods/vn-user/specs/renew-token.spec.js b/back/methods/vn-user/specs/renew-token.spec.js index 674ce36f4..146f6eb0c 100644 --- a/back/methods/vn-user/specs/renew-token.spec.js +++ b/back/methods/vn-user/specs/renew-token.spec.js @@ -27,8 +27,10 @@ describe('Renew Token', () => { jasmine.clock().uninstall(); }); - it('should renew process', async() => { - jasmine.clock().mockDate(new Date(startingTime + 21600000)); + it('should renew token', async() => { + const mockDate = new Date(startingTime + 26600000); + jasmine.clock().mockDate(mockDate); + console.log(startingTime, mockDate) const {id} = await models.VnUser.renewToken(ctx); expect(id).not.toEqual(ctx.req.accessToken.id); From 9951e911ae302e09c08813cbb98ceb038bfbd3c2 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 21 Dec 2023 10:39:46 +0100 Subject: [PATCH 71/75] refs #5925 feat(docuware_upload): use userConfig.tabletFk --- .vscode/settings.json | 2 +- back/methods/docuware/specs/upload.spec.js | 31 +++++++++++++-- back/methods/docuware/upload.js | 46 +++++++++++----------- back/models/docuwareTablet.json | 5 +-- back/models/user-config.json | 2 +- db/changes/235201/00-tabletDocuware.sql | 24 ----------- db/changes/240201/00-tabletDocuware.sql | 10 +++++ db/dump/fixtures.sql | 5 +++ loopback/locale/es.json | 2 +- 9 files changed, 70 insertions(+), 57 deletions(-) delete mode 100644 db/changes/235201/00-tabletDocuware.sql create mode 100644 db/changes/240201/00-tabletDocuware.sql diff --git a/.vscode/settings.json b/.vscode/settings.json index 40ec5c0d3..36b7e21d8 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -3,7 +3,7 @@ // Carácter predeterminado de final de línea. "files.eol": "\n", "editor.codeActionsOnSave": { - "source.fixAll.eslint": true + "source.fixAll.eslint": "explicit" }, "search.useIgnoreFiles": false, "editor.defaultFormatter": "dbaeumer.vscode-eslint", diff --git a/back/methods/docuware/specs/upload.spec.js b/back/methods/docuware/specs/upload.spec.js index 3b8c55a50..2577fa42d 100644 --- a/back/methods/docuware/specs/upload.spec.js +++ b/back/methods/docuware/specs/upload.spec.js @@ -24,15 +24,40 @@ describe('docuware upload()', () => { }); it('should try upload file', async() => { + const tx = await models.Docuware.beginTransaction({}); spyOn(ticketModel, 'deliveryNotePdf').and.returnValue(new Promise(resolve => resolve({}))); let error; try { - await models.Docuware.upload(ctx, ticketIds, fileCabinetName); + const options = {transaction: tx}; + const user = await models.UserConfig.findById(userId, null, options); + await user.updateAttribute('tabletFk', 'Tablet1'); + await models.Docuware.upload(ctx, ticketIds, fileCabinetName, options); + + await tx.rollback(); } catch (e) { - error = e.message; + error = e; + await tx.rollback(); } - expect(error).toEqual('Action not allowed on the test environment'); + expect(error.message).toEqual('Action not allowed on the test environment'); + }); + + it('should throw error when not have tablet assigned', async() => { + const tx = await models.Docuware.beginTransaction({}); + spyOn(ticketModel, 'deliveryNotePdf').and.returnValue(new Promise(resolve => resolve({}))); + + let error; + try { + const options = {transaction: tx}; + await models.Docuware.upload(ctx, ticketIds, fileCabinetName, options); + + await tx.rollback(); + } catch (e) { + error = e; + await tx.rollback(); + } + + expect(error.message).toEqual('This user does not have an assigned tablet'); }); }); diff --git a/back/methods/docuware/upload.js b/back/methods/docuware/upload.js index 5f44e9382..27be72295 100644 --- a/back/methods/docuware/upload.js +++ b/back/methods/docuware/upload.js @@ -29,12 +29,24 @@ module.exports = Self => { } }); - Self.upload = async function(ctx, ticketIds, fileCabinet) { + Self.upload = async function(ctx, ticketIds, fileCabinet, options) { delete ctx.args.ticketIds; const models = Self.app.models; const action = 'store'; - const options = await Self.getOptions(); + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const userConfig = await models.UserConfig.findById(ctx.req.accessToken.userId, { + fields: ['tabletFk'] + }, myOptions); + + if (!userConfig?.tabletFk) + throw new UserError('This user does not have an assigned tablet'); + + const docuwareOptions = await Self.getOptions(); const fileCabinetId = await Self.getFileCabinet(fileCabinet); const dialogId = await Self.getDialog(fileCabinet, action, fileCabinetId); @@ -45,7 +57,7 @@ module.exports = Self => { const deliveryNote = await models.Ticket.deliveryNotePdf(ctx, { id, type: 'deliveryNote' - }); + }, myOptions); // get ticket data const ticket = await models.Ticket.findById(id, { include: [{ @@ -54,17 +66,7 @@ module.exports = Self => { fields: ['id', 'name', 'fi'] } }] - }); - - // get tablet - const tablet = await models.userConfig.findById(id, { - include: [{ - relation: 'Tablet', - scope: { - fields: ['id'] - } - }] - }); + }, myOptions); // upload file const templateJson = { @@ -112,7 +114,7 @@ module.exports = Self => { { 'FieldName': 'FILTRO_TABLET', 'ItemElementName': 'string', - 'Item': tablet.id, + 'Item': userConfig.tabletFk, } ] }; @@ -120,19 +122,17 @@ module.exports = Self => { if (process.env.NODE_ENV != 'production') throw new UserError('Action not allowed on the test environment'); - if (!tablet.id) - throw new UserError('This user does not have an assigned tablet.'); // delete old const docuwareFile = await models.Docuware.checkFile(id, fileCabinet, false); if (docuwareFile) { const deleteJson = { 'Field': [{'FieldName': 'ESTADO', 'Item': 'Pendiente eliminar', 'ItemElementName': 'String'}] }; - const deleteUri = `${options.url}/FileCabinets/${fileCabinetId}/Documents/${docuwareFile.id}/Fields`; - await axios.put(deleteUri, deleteJson, options.headers); + const deleteUri = `${docuwareOptions.url}/FileCabinets/${fileCabinetId}/Documents/${docuwareFile.id}/Fields`; + await axios.put(deleteUri, deleteJson, docuwareOptions.headers); } - const uploadUri = `${options.url}/FileCabinets/${fileCabinetId}/Documents?StoreDialogId=${dialogId}`; + const uploadUri = `${docuwareOptions.url}/FileCabinets/${fileCabinetId}/Documents?StoreDialogId=${dialogId}`; const FormData = require('form-data'); const data = new FormData(); @@ -142,7 +142,7 @@ module.exports = Self => { headers: { 'Content-Type': 'multipart/form-data', 'X-File-ModifiedDate': Date.vnNew(), - 'Cookie': options.headers.headers.Cookie, + 'Cookie': docuwareOptions.headers.headers.Cookie, ...data.getHeaders() }, }; @@ -153,11 +153,11 @@ module.exports = Self => { const $t = ctx.req.__; const message = $t('Failed to upload delivery note', {id}); if (uploaded.length) - await models.TicketTracking.setDelivered(ctx, uploaded); + await models.TicketTracking.setDelivered(ctx, uploaded, myOptions); throw new UserError(message); } uploaded.push(id); } - return models.TicketTracking.setDelivered(ctx, ticketIds); + return models.TicketTracking.setDelivered(ctx, ticketIds, myOptions); }; }; diff --git a/back/models/docuwareTablet.json b/back/models/docuwareTablet.json index e9e3b6bad..dbbf62f56 100644 --- a/back/models/docuwareTablet.json +++ b/back/models/docuwareTablet.json @@ -7,10 +7,7 @@ } }, "properties": { - "id": { - "type": "number" - }, - "name": { + "tablet": { "type": "string" }, "description": { diff --git a/back/models/user-config.json b/back/models/user-config.json index 35f6aa1e6..5c5df1b9e 100644 --- a/back/models/user-config.json +++ b/back/models/user-config.json @@ -28,7 +28,7 @@ "type": "boolean" }, "tabletFk": { - "type": "number" + "type": "string" } }, "relations": { diff --git a/db/changes/235201/00-tabletDocuware.sql b/db/changes/235201/00-tabletDocuware.sql deleted file mode 100644 index c480c1001..000000000 --- a/db/changes/235201/00-tabletDocuware.sql +++ /dev/null @@ -1,24 +0,0 @@ --- vn.docuwareTablet definition - -CREATE TABLE `vn`.`docuwareTablet` ( - `id` int(3) NOT NULL AUTO_INCREMENT, - `name` varchar(100) NOT NULL, - `description` varchar(255) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; - --- Auto-generated SQL script. Actual values for binary/complex data types may differ - what you see is the default string representation of values. -INSERT INTO `vn`.`docuwareTablet` (`id`,`name`,`description`) - VALUES (1,'tabletRRHH','tablet de recursos humanos'); -INSERT INTO `vn`.`docuwareTablet` (`id`,`name`,`description`) - VALUES (2,'tabletIT','tablet de IT'); -INSERT INTO `vn`.`docuwareTablet` (`id`,`name`,`description`) - VALUES (3,'tabletCompradores','tablet de compradores'); -INSERT INTO `vn`.`docuwareTablet` (`id`,`name`,`description`) - VALUES (4,'tabletComerciales','tablet de comerciales'); -INSERT INTO `vn`.`docuwareTablet` (`id`,`name`,`description`) - VALUES (5,'tabletAdministracion','tablet de administracion'); - -ALTER TABLE `vn`.`userConfig` -ADD COLUMN tabletFk int(3), -ADD FOREIGN KEY (tabletFk) REFERENCES `vn`.`docuwareTablet`(id); diff --git a/db/changes/240201/00-tabletDocuware.sql b/db/changes/240201/00-tabletDocuware.sql new file mode 100644 index 000000000..ffa0226b3 --- /dev/null +++ b/db/changes/240201/00-tabletDocuware.sql @@ -0,0 +1,10 @@ +-- vn.docuwareTablet definition + +CREATE TABLE `vn`.`docuwareTablet` ( + `tablet` varchar(100) NOT NULL PRIMARY KEY, + `description` varchar(255) DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +ALTER TABLE `vn`.`userConfig` +ADD COLUMN tabletFk varchar(100) DEFAULT NULL, +ADD FOREIGN KEY (tabletFk) REFERENCES `vn`.`docuwareTablet`(tablet); diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 8997e40b1..479704dd9 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -3009,3 +3009,8 @@ INSERT INTO `vn`.`invoiceCorrectionType` (`id`, `description`) (1, 'Error in VAT calculation'), (2, 'Error in sales details'), (3, 'Error in customer data'); + +INSERT INTO `vn`.`docuwareTablet` (`tablet`,`description`) + VALUES + ('Tablet1','Jarvis tablet'), + ('Tablet2','Avengers tablet'); diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 94bc29a86..a197197ba 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -330,5 +330,5 @@ "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima", "Cannot past travels with entries": "No se pueden pasar envíos con entradas", "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", - "This user does not have an assigned tablet.": "Este usuario no tiene tablet asignada" + "This user does not have an assigned tablet": "Este usuario no tiene tablet asignada" } From 15ec91ec790fbe18191262127a20b402ce824d70 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 29 Dec 2023 14:05:01 +0100 Subject: [PATCH 72/75] fix query: refs #6369 --- modules/invoiceOut/back/methods/invoiceOut/negativeBases.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/invoiceOut/back/methods/invoiceOut/negativeBases.js b/modules/invoiceOut/back/methods/invoiceOut/negativeBases.js index ae9c404af..96c789316 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/negativeBases.js +++ b/modules/invoiceOut/back/methods/invoiceOut/negativeBases.js @@ -90,7 +90,7 @@ module.exports = Self => { AND t.refFk IS NULL AND c.typeFk IN ('normal','trust') GROUP BY t.clientFk, negativeBase.taxableBase - HAVING amount <> 0`, [args.from, args.to])); + HAVING amount < 0`, [args.from, args.to])); stmt = new ParameterizedSQL(` SELECT f.* From 318761185bbf1172657002f2adfde77b895c7118 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 2 Jan 2024 08:07:16 +0100 Subject: [PATCH 73/75] refs #6434 fix: remove console.log --- back/methods/vn-user/specs/renew-token.spec.js | 1 - 1 file changed, 1 deletion(-) diff --git a/back/methods/vn-user/specs/renew-token.spec.js b/back/methods/vn-user/specs/renew-token.spec.js index 146f6eb0c..8d9bbf11c 100644 --- a/back/methods/vn-user/specs/renew-token.spec.js +++ b/back/methods/vn-user/specs/renew-token.spec.js @@ -30,7 +30,6 @@ describe('Renew Token', () => { it('should renew token', async() => { const mockDate = new Date(startingTime + 26600000); jasmine.clock().mockDate(mockDate); - console.log(startingTime, mockDate) const {id} = await models.VnUser.renewToken(ctx); expect(id).not.toEqual(ctx.req.accessToken.id); From 0101dcda3ac950c1add6c3c426c4f745389805c1 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 2 Jan 2024 08:12:45 +0100 Subject: [PATCH 74/75] refs #5925 fix: add options --- back/methods/docuware/specs/upload.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/methods/docuware/specs/upload.spec.js b/back/methods/docuware/specs/upload.spec.js index 2577fa42d..866499b66 100644 --- a/back/methods/docuware/specs/upload.spec.js +++ b/back/methods/docuware/specs/upload.spec.js @@ -31,7 +31,7 @@ describe('docuware upload()', () => { try { const options = {transaction: tx}; const user = await models.UserConfig.findById(userId, null, options); - await user.updateAttribute('tabletFk', 'Tablet1'); + await user.updateAttribute('tabletFk', 'Tablet1', options); await models.Docuware.upload(ctx, ticketIds, fileCabinetName, options); await tx.rollback(); From 6b8a4a512bc58067c2efd00b141e8a45a0d99e8c Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 2 Jan 2024 10:42:50 +0100 Subject: [PATCH 75/75] adding filter: refs #6606 --- .../back/methods/invoiceOut/negativeBasesCsv.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/modules/invoiceOut/back/methods/invoiceOut/negativeBasesCsv.js b/modules/invoiceOut/back/methods/invoiceOut/negativeBasesCsv.js index d70a8fce5..87e9a67ea 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/negativeBasesCsv.js +++ b/modules/invoiceOut/back/methods/invoiceOut/negativeBasesCsv.js @@ -10,13 +10,17 @@ module.exports = Self => { type: 'date', description: 'From date', required: true - }, - { + }, { arg: 'to', type: 'date', description: 'To date', required: true - }], + }, { + arg: 'filter', + type: 'object', + description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string' + }, + ], returns: [ { arg: 'body',