From f3e43686a3db0f7a1e43434fd8e3396f5436b657 Mon Sep 17 00:00:00 2001 From: vicent Date: Thu, 24 Aug 2023 14:59:28 +0200 Subject: [PATCH 001/207] refs #5811 feat: al borrar expedicion borrar tmb de viaexpress --- .../viaexpress-config/deleteShipment.ejs | 11 +++++ .../viaexpress-config/deleteShipment.js | 45 +++++++++++++++++++ .../deleteShipmentRenderer.js | 44 ++++++++++++++++++ modules/ticket/back/models/expedition.json | 3 ++ 4 files changed, 103 insertions(+) create mode 100644 back/methods/viaexpress-config/deleteShipment.ejs create mode 100644 back/methods/viaexpress-config/deleteShipment.js create mode 100644 back/methods/viaexpress-config/deleteShipmentRenderer.js diff --git a/back/methods/viaexpress-config/deleteShipment.ejs b/back/methods/viaexpress-config/deleteShipment.ejs new file mode 100644 index 000000000..3be459a8d --- /dev/null +++ b/back/methods/viaexpress-config/deleteShipment.ejs @@ -0,0 +1,11 @@ + + + + + <%= viaexpressConfig.client %> + <%= viaexpressConfig.user %> + <%= viaexpressConfig.password %> + <%= externalId %> + + + diff --git a/back/methods/viaexpress-config/deleteShipment.js b/back/methods/viaexpress-config/deleteShipment.js new file mode 100644 index 000000000..40509899b --- /dev/null +++ b/back/methods/viaexpress-config/deleteShipment.js @@ -0,0 +1,45 @@ +const axios = require('axios'); +const {DOMParser} = require('xmldom'); + +module.exports = Self => { + Self.remoteMethod('deleteShipment', { + description: 'Create an expedition and return a label', + accessType: 'WRITE', + accepts: [{ + arg: 'expeditionFk', + type: 'number', + required: true + }], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/deleteShipment`, + verb: 'POST' + } + }); + + Self.deleteShipment = async expeditionFk => { + const models = Self.app.models; + + const viaexpressConfig = await models.ViaexpressConfig.findOne({ + fields: ['url'] + }); + + const renderedXml = await models.ViaexpressConfig.deleteShipmentRenderer(expeditionFk); + const response = await axios.post(`${viaexpressConfig.url}ServicioVxClientes.asmx`, renderedXml, { + headers: { + 'Content-Type': 'application/soap+xml; charset=utf-8' + } + }); + + const xmlString = response.data; + const parser = new DOMParser(); + const xmlDoc = parser.parseFromString(xmlString, 'text/xml'); + const resultElement = xmlDoc.getElementsByTagName('DeleteEnvioResult')[0]; + const result = resultElement.textContent; + + return result; + }; +}; diff --git a/back/methods/viaexpress-config/deleteShipmentRenderer.js b/back/methods/viaexpress-config/deleteShipmentRenderer.js new file mode 100644 index 000000000..d9106a9ec --- /dev/null +++ b/back/methods/viaexpress-config/deleteShipmentRenderer.js @@ -0,0 +1,44 @@ +const fs = require('fs'); +const ejs = require('ejs'); + +module.exports = Self => { + Self.remoteMethod('deleteShipmentRenderer', { + description: 'Renders the data from an XML', + accessType: 'READ', + accepts: [{ + arg: 'expeditionFk', + type: 'number', + required: true + }], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/deleteShipmentRenderer`, + verb: 'GET' + } + }); + + Self.deleteShipmentRenderer = async expeditionFk => { + const models = Self.app.models; + + const viaexpressConfig = await models.ViaexpressConfig.findOne({ + fields: ['client', 'user', 'password'] + }); + + const expedition = await models.Expedition.findOne({ + fields: ['id', 'externalId'], + where: {id: expeditionFk} + }); + + const data = { + viaexpressConfig, + externalId: expedition.externalId + }; + + const template = fs.readFileSync(__dirname + '/deleteShipment.ejs', 'utf-8'); + const renderedXml = ejs.render(template, data); + return renderedXml; + }; +}; diff --git a/modules/ticket/back/models/expedition.json b/modules/ticket/back/models/expedition.json index e32a3b23d..1ad083ce3 100644 --- a/modules/ticket/back/models/expedition.json +++ b/modules/ticket/back/models/expedition.json @@ -20,6 +20,9 @@ }, "counter": { "type": "number" + }, + "externalId": { + "type": "string" } }, "relations": { From d1df8009a620138e1a53de2c19ab952d725590d8 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 29 Aug 2023 10:52:05 +0200 Subject: [PATCH 002/207] refs #6023 Fix change rol bug --- back/methods/vn-user/privileges.js | 66 ++++++++++++-------- modules/account/back/methods/account/sync.js | 5 ++ 2 files changed, 44 insertions(+), 27 deletions(-) diff --git a/back/methods/vn-user/privileges.js b/back/methods/vn-user/privileges.js index 08cfaaae8..05ad4481c 100644 --- a/back/methods/vn-user/privileges.js +++ b/back/methods/vn-user/privileges.js @@ -40,44 +40,56 @@ module.exports = Self => { const userId = ctx.req.accessToken.userId; const myOptions = {}; + let tx; if (typeof options == 'object') Object.assign(myOptions, options); - const user = await Self.findById(userId, {fields: ['hasGrant']}, myOptions); + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + }; - const userToUpdate = await Self.findById(id, { - fields: ['id', 'name', 'hasGrant', 'roleFk', 'password', 'email'], - include: { - relation: 'role', - scope: { - fields: ['name'] + try { + const user = await Self.findById(userId, {fields: ['hasGrant']}, myOptions); + + const userToUpdate = await Self.findById(id, { + fields: ['id', 'name', 'hasGrant', 'roleFk', 'password', 'email'], + include: { + relation: 'role', + scope: { + fields: ['name'] + } } - } - }, myOptions); + }, myOptions); - if (!user.hasGrant) - throw new UserError(`You don't have grant privilege`); + if (!user.hasGrant) + throw new UserError(`You don't have grant privilege`); - const hasRoleFromUser = await Self.hasRole(userId, userToUpdate.role().name, myOptions); + const hasRoleFromUser = await Self.hasRole(userId, userToUpdate.role().name, myOptions); - if (!hasRoleFromUser) - throw new UserError(`You don't own the role and you can't assign it to another user`); - - if (hasGrant != null) - userToUpdate.hasGrant = hasGrant; - - if (roleFk) { - const role = await models.Role.findById(roleFk, {fields: ['name']}, myOptions); - const hasRole = await Self.hasRole(userId, role.name, myOptions); - - if (!hasRole) + if (!hasRoleFromUser) throw new UserError(`You don't own the role and you can't assign it to another user`); - userToUpdate.roleFk = roleFk; - } + if (hasGrant != null) + userToUpdate.hasGrant = hasGrant; - await userToUpdate.save(userToUpdate); - await models.Account.sync(userToUpdate.name); + if (roleFk) { + const role = await models.Role.findById(roleFk, {fields: ['name']}, myOptions); + const hasRole = await Self.hasRole(userId, role.name, myOptions); + + if (!hasRole) + throw new UserError(`You don't own the role and you can't assign it to another user`); + + userToUpdate.roleFk = roleFk; + } + + await userToUpdate.save(myOptions); + await models.Account.sync(userToUpdate.name, null, null, myOptions); + await tx.commit(); + } catch (err) { + await tx.rollback(); + throw err; + }; }; }; diff --git a/modules/account/back/methods/account/sync.js b/modules/account/back/methods/account/sync.js index a5befc22c..3ab19eed5 100644 --- a/modules/account/back/methods/account/sync.js +++ b/modules/account/back/methods/account/sync.js @@ -30,6 +30,11 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + }; + const models = Self.app.models; const user = await models.VnUser.findOne({ fields: ['id'], From 9f6d034f9cf044f9ab688bb860bf4277d1df7bec Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 29 Aug 2023 13:45:20 +0200 Subject: [PATCH 003/207] refs #6023 Minor changes --- back/methods/vn-user/privileges.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/back/methods/vn-user/privileges.js b/back/methods/vn-user/privileges.js index 05ad4481c..0520fd5c2 100644 --- a/back/methods/vn-user/privileges.js +++ b/back/methods/vn-user/privileges.js @@ -86,9 +86,9 @@ module.exports = Self => { await userToUpdate.save(myOptions); await models.Account.sync(userToUpdate.name, null, null, myOptions); - await tx.commit(); + if (tx) await tx.commit(); } catch (err) { - await tx.rollback(); + if (tx) await tx.rollback(); throw err; }; }; From 0dbb77fc646f625df5432ba655c7a9da0357034e Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 31 Aug 2023 09:20:33 +0200 Subject: [PATCH 004/207] refs #6023 Transactioned sync --- modules/account/back/methods/account/sync.js | 31 +++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/modules/account/back/methods/account/sync.js b/modules/account/back/methods/account/sync.js index 3ab19eed5..c4f9cb181 100644 --- a/modules/account/back/methods/account/sync.js +++ b/modules/account/back/methods/account/sync.js @@ -25,8 +25,10 @@ module.exports = Self => { }); Self.sync = async function(userName, password, force, options) { + const models = Self.app.models; const myOptions = {}; - + let tx; + if (typeof options == 'object') Object.assign(myOptions, options); @@ -35,16 +37,23 @@ module.exports = Self => { myOptions.transaction = tx; }; - const models = Self.app.models; - const user = await models.VnUser.findOne({ - fields: ['id'], - where: {name: userName} - }, myOptions); - const isSync = !await models.UserSync.exists(userName, myOptions); + try { + const user = await models.VnUser.findOne({ + fields: ['id'], + where: {name: userName} + }, myOptions); + const isSync = !await models.UserSync.exists(userName, myOptions); - if (!force && isSync && user) return; - await models.AccountConfig.syncUser(userName, password); - await models.UserSync.destroyById(userName, myOptions); + if (!force && isSync && user) { + if (tx) await tx.rollback(); + return; + } + await models.AccountConfig.syncUser(userName, password); + await models.UserSync.destroyById(userName, myOptions); + if (tx) await tx.commit(); + } catch (err) { + if (tx) await tx.rollback(); + throw err; + } }; }; - From 04008110f155653bf7ba1e04d31b7fbd9178d5ca Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 4 Sep 2023 08:32:02 +0200 Subject: [PATCH 005/207] refs #6172 Change --- front/salix/module.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/front/salix/module.js b/front/salix/module.js index f8fa0faf0..5025eec22 100644 --- a/front/salix/module.js +++ b/front/salix/module.js @@ -120,7 +120,7 @@ function $exceptionHandler(vnApp, $window, $state, $injector) { messageT = 'Invalid login'; break; case 403: - messageT = 'Access denied'; + messageT = (exception.data.error.message) ? exception.data.error.message : 'Access denied'; break; case 502: messageT = 'It seems that the server has fall down'; From fa08ebf416846166cdd665607ce7c7912a54232d Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 17 Oct 2023 08:57:45 +0200 Subject: [PATCH 006/207] refs #5867 fix: tickets sql --- print/templates/reports/driver-route/sql/tickets.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/print/templates/reports/driver-route/sql/tickets.sql b/print/templates/reports/driver-route/sql/tickets.sql index 09e73819b..9d548c2b3 100644 --- a/print/templates/reports/driver-route/sql/tickets.sql +++ b/print/templates/reports/driver-route/sql/tickets.sql @@ -20,7 +20,7 @@ SELECT u.nickName salesPersonName, ipkg.itemPackingTypes FROM route r - LEFT JOIN ticket t ON t.routeFk = r.id + JOIN ticket t ON t.routeFk = r.id LEFT JOIN address a ON a.id = t.addressFk LEFT JOIN client c ON c.id = t.clientFk LEFT JOIN worker w ON w.id = client_getSalesPerson(t.clientFk, CURDATE()) From 98f237b4bd9ae2b0c213d9804969c8ccb1c6d57b Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Fri, 3 Nov 2023 16:10:46 +0100 Subject: [PATCH 007/207] 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 008/207] 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 009/207] 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 010/207] 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 011/207] 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 012/207] 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 013/207] 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 014/207] 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 015/207] 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 016/207] 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 017/207] 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 9f92bc4b4c5e72bc63385605a115f6d464416dac Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 10 Nov 2023 11:43:42 +0100 Subject: [PATCH 018/207] fix: refs #6023 Rollback privileges.js --- back/methods/vn-user/privileges.js | 66 ++++++++++++------------------ 1 file changed, 27 insertions(+), 39 deletions(-) diff --git a/back/methods/vn-user/privileges.js b/back/methods/vn-user/privileges.js index 0520fd5c2..08cfaaae8 100644 --- a/back/methods/vn-user/privileges.js +++ b/back/methods/vn-user/privileges.js @@ -40,56 +40,44 @@ module.exports = Self => { const userId = ctx.req.accessToken.userId; const myOptions = {}; - let tx; if (typeof options == 'object') Object.assign(myOptions, options); - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - }; + const user = await Self.findById(userId, {fields: ['hasGrant']}, myOptions); - try { - const user = await Self.findById(userId, {fields: ['hasGrant']}, myOptions); - - const userToUpdate = await Self.findById(id, { - fields: ['id', 'name', 'hasGrant', 'roleFk', 'password', 'email'], - include: { - relation: 'role', - scope: { - fields: ['name'] - } + const userToUpdate = await Self.findById(id, { + fields: ['id', 'name', 'hasGrant', 'roleFk', 'password', 'email'], + include: { + relation: 'role', + scope: { + fields: ['name'] } - }, myOptions); + } + }, myOptions); - if (!user.hasGrant) - throw new UserError(`You don't have grant privilege`); + if (!user.hasGrant) + throw new UserError(`You don't have grant privilege`); - const hasRoleFromUser = await Self.hasRole(userId, userToUpdate.role().name, myOptions); + const hasRoleFromUser = await Self.hasRole(userId, userToUpdate.role().name, myOptions); - if (!hasRoleFromUser) + if (!hasRoleFromUser) + throw new UserError(`You don't own the role and you can't assign it to another user`); + + if (hasGrant != null) + userToUpdate.hasGrant = hasGrant; + + if (roleFk) { + const role = await models.Role.findById(roleFk, {fields: ['name']}, myOptions); + const hasRole = await Self.hasRole(userId, role.name, myOptions); + + if (!hasRole) throw new UserError(`You don't own the role and you can't assign it to another user`); - if (hasGrant != null) - userToUpdate.hasGrant = hasGrant; + userToUpdate.roleFk = roleFk; + } - if (roleFk) { - const role = await models.Role.findById(roleFk, {fields: ['name']}, myOptions); - const hasRole = await Self.hasRole(userId, role.name, myOptions); - - if (!hasRole) - throw new UserError(`You don't own the role and you can't assign it to another user`); - - userToUpdate.roleFk = roleFk; - } - - await userToUpdate.save(myOptions); - await models.Account.sync(userToUpdate.name, null, null, myOptions); - if (tx) await tx.commit(); - } catch (err) { - if (tx) await tx.rollback(); - throw err; - }; + await userToUpdate.save(userToUpdate); + await models.Account.sync(userToUpdate.name); }; }; From b7da144967c5c34cdcd937ae39169fcae8001df1 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 10 Nov 2023 11:55:37 +0100 Subject: [PATCH 019/207] feat: refs #6023 Added SELECT FOR UPDATE --- modules/account/back/methods/account/sync.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/modules/account/back/methods/account/sync.js b/modules/account/back/methods/account/sync.js index c4f9cb181..8548e71f3 100644 --- a/modules/account/back/methods/account/sync.js +++ b/modules/account/back/methods/account/sync.js @@ -48,6 +48,13 @@ module.exports = Self => { if (tx) await tx.rollback(); return; } + + await Self.rawSql(` + SELECT id + FROM account.user + WHERE id = ? + FOR UPDATE`, [user.id], myOptions); + await models.AccountConfig.syncUser(userName, password); await models.UserSync.destroyById(userName, myOptions); if (tx) await tx.commit(); From bcccd1894c555706f115c1fe670ce1c40dfe2b4b Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Fri, 10 Nov 2023 13:13:17 +0100 Subject: [PATCH 020/207] 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 5dbfe31a60d129f2d076c548096f5e653050b218 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Fri, 10 Nov 2023 15:12:03 +0100 Subject: [PATCH 021/207] refs #5666 feat: define VnRole --- .vscode/settings.json | 6 ++++++ back/model-config.json | 3 +++ back/models/vn-role.json | 13 +++++++++++++ 3 files changed, 22 insertions(+) create mode 100644 back/models/vn-role.json diff --git a/.vscode/settings.json b/.vscode/settings.json index 05d23f3bb..4c2761987 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -10,5 +10,11 @@ "eslint.format.enable": true, "[javascript]": { "editor.defaultFormatter": "dbaeumer.vscode-eslint" + }, + "cSpell.words": [ + "Loggable" + ], + "[json]": { + "editor.defaultFormatter": "vscode.json-language-features" } } diff --git a/back/model-config.json b/back/model-config.json index ebc0e321b..84dd9eebd 100644 --- a/back/model-config.json +++ b/back/model-config.json @@ -142,6 +142,9 @@ "VnUser": { "dataSource": "vn" }, + "VnRole": { + "dataSource": "vn" + }, "OsTicket": { "dataSource": "osticket" }, diff --git a/back/models/vn-role.json b/back/models/vn-role.json new file mode 100644 index 000000000..e841f8a88 --- /dev/null +++ b/back/models/vn-role.json @@ -0,0 +1,13 @@ +{ + "name": "VnRole", + "base": "Role", + "validateUpsert": true, + "options": { + "mysql": { + "table": "account.role" + } + }, + "mixins": { + "RegisterLog": true + } +} From cf3cc37d97f61372dd9072492b60ffce5ad35cfd Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Fri, 10 Nov 2023 15:12:24 +0100 Subject: [PATCH 022/207] refs #5666 feat: create mixin --- back/mixins/register-log.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 back/mixins/register-log.js diff --git a/back/mixins/register-log.js b/back/mixins/register-log.js new file mode 100644 index 000000000..555191e57 --- /dev/null +++ b/back/mixins/register-log.js @@ -0,0 +1,20 @@ + +const loggable = require('vn-loopback/util/log'); + +module.exports = function(Self, options) { + Self.once('attached', function(ctx) { + }); + + Self.observe('before save', async function(ctx, next) { + await loggable.translateValues(Self, ctx.currentInstance); + }); + + let Mixin = { + + }; + + for (let method in Mixin) { + if (!Self.prototype[method]) + Self.prototype[method] = Mixin[method]; + } +}; From 3c5af184bbc6458ca3963b7a561b187577a1509f Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Fri, 10 Nov 2023 15:12:49 +0100 Subject: [PATCH 023/207] refs #5666 feat: use mixin for this models --- back/models/vn-user.json | 3 +++ modules/account/back/models/account.json | 3 +++ 2 files changed, 6 insertions(+) diff --git a/back/models/vn-user.json b/back/models/vn-user.json index 0f6daff5a..28fca8fe8 100644 --- a/back/models/vn-user.json +++ b/back/models/vn-user.json @@ -7,6 +7,9 @@ "table": "account.user" } }, + "mixins": { + "RegisterLog": true + }, "resetPasswordTokenTTL": "604800", "properties": { "id": { diff --git a/modules/account/back/models/account.json b/modules/account/back/models/account.json index 3c22521cb..3c76c85c3 100644 --- a/modules/account/back/models/account.json +++ b/modules/account/back/models/account.json @@ -6,6 +6,9 @@ "table": "account.account" } }, + "mixins": { + "RegisterLog": true + }, "properties": { "id": { "id": true From a102c3f3a952da468734039c1e133e4470270842 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 13 Nov 2023 09:53:35 +0100 Subject: [PATCH 024/207] refs #5666 perf: loggable to mixin --- loopback/common/mixins/loggable.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 loopback/common/mixins/loggable.js diff --git a/loopback/common/mixins/loggable.js b/loopback/common/mixins/loggable.js new file mode 100644 index 000000000..760fdf60a --- /dev/null +++ b/loopback/common/mixins/loggable.js @@ -0,0 +1,12 @@ +const LoopBackContext = require('loopback-context'); +async function handleObserve(ctx) { + ctx.options.httpCtx = LoopBackContext.getCurrentContext(); +} +module.exports = function(Self) { + let Mixin = { + 'before save': handleObserve, + 'before delete': handleObserve, + }; + for (const [listener, handler] of Object.entries(Mixin)) + Self.observe(listener, handler); +}; From aab88dc7dede9b31d733b5ff647224fc3b93d3f4 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 13 Nov 2023 09:54:12 +0100 Subject: [PATCH 025/207] refs #5666 perf: use use loggable as mixin --- back/models/vn-role.json | 2 +- back/models/vn-user.json | 2 +- loopback/common/models/loggable.json | 13 ++++++++----- modules/account/back/models/account.json | 5 +---- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/back/models/vn-role.json b/back/models/vn-role.json index e841f8a88..c7d7e172b 100644 --- a/back/models/vn-role.json +++ b/back/models/vn-role.json @@ -8,6 +8,6 @@ } }, "mixins": { - "RegisterLog": true + "Loggable": true } } diff --git a/back/models/vn-user.json b/back/models/vn-user.json index 28fca8fe8..bda0a6ec3 100644 --- a/back/models/vn-user.json +++ b/back/models/vn-user.json @@ -8,7 +8,7 @@ } }, "mixins": { - "RegisterLog": true + "Loggable": true }, "resetPasswordTokenTTL": "604800", "properties": { diff --git a/loopback/common/models/loggable.json b/loopback/common/models/loggable.json index 9101532a3..62822d0af 100644 --- a/loopback/common/models/loggable.json +++ b/loopback/common/models/loggable.json @@ -1,5 +1,8 @@ -{ - "name": "Loggable", - "base": "VnModel", - "validateUpsert": true -} +{ + "name": "Loggable", + "base": "VnModel", + "validateUpsert": true, + "mixins": { + "Loggable": true + } +} diff --git a/modules/account/back/models/account.json b/modules/account/back/models/account.json index 3c76c85c3..3e4371604 100644 --- a/modules/account/back/models/account.json +++ b/modules/account/back/models/account.json @@ -6,10 +6,7 @@ "table": "account.account" } }, - "mixins": { - "RegisterLog": true - }, - "properties": { + "properties": { "id": { "id": true } From 384b5eb7c7705cc1603bebaa67d09d58afbe4c91 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 13 Nov 2023 09:56:16 +0100 Subject: [PATCH 026/207] refs #5666 remove old file --- back/mixins/register-log.js | 20 ------ modules/account/back/models/account.json | 86 ++++++++++++------------ 2 files changed, 43 insertions(+), 63 deletions(-) delete mode 100644 back/mixins/register-log.js diff --git a/back/mixins/register-log.js b/back/mixins/register-log.js deleted file mode 100644 index 555191e57..000000000 --- a/back/mixins/register-log.js +++ /dev/null @@ -1,20 +0,0 @@ - -const loggable = require('vn-loopback/util/log'); - -module.exports = function(Self, options) { - Self.once('attached', function(ctx) { - }); - - Self.observe('before save', async function(ctx, next) { - await loggable.translateValues(Self, ctx.currentInstance); - }); - - let Mixin = { - - }; - - for (let method in Mixin) { - if (!Self.prototype[method]) - Self.prototype[method] = Mixin[method]; - } -}; diff --git a/modules/account/back/models/account.json b/modules/account/back/models/account.json index 3e4371604..6c2784696 100644 --- a/modules/account/back/models/account.json +++ b/modules/account/back/models/account.json @@ -1,49 +1,49 @@ { - "name": "Account", - "base": "VnModel", - "options": { - "mysql": { - "table": "account.account" - } - }, + "name": "Account", + "base": "VnModel", + "options": { + "mysql": { + "table": "account.account" + } + }, "properties": { - "id": { - "id": true - } - }, - "relations": { - "user": { - "type": "belongsTo", - "model": "VnUser", - "foreignKey": "id" - }, - "aliases": { - "type": "hasMany", - "model": "MailAliasAccount", - "foreignKey": "account" - } - }, - "acls": [ - { - "property": "login", - "accessType": "EXECUTE", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" + "id": { + "id": true + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "VnUser", + "foreignKey": "id" }, - { + "aliases": { + "type": "hasMany", + "model": "MailAliasAccount", + "foreignKey": "account" + } + }, + "acls": [ + { + "property": "login", + "accessType": "EXECUTE", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }, + { "property": "logout", - "accessType": "EXECUTE", - "principalType": "ROLE", - "principalId": "$authenticated", - "permission": "ALLOW" - }, - { + "accessType": "EXECUTE", + "principalType": "ROLE", + "principalId": "$authenticated", + "permission": "ALLOW" + }, + { "property": "changePassword", - "accessType": "EXECUTE", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" - } - ] + "accessType": "EXECUTE", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] } From 6527cae72a2e725166049af6001d5382253f9330 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 14 Nov 2023 07:58:33 +0100 Subject: [PATCH 027/207] refactor: refs #6172 Added real message error --- front/salix/locale/es.yml | 1 + front/salix/module.js | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/front/salix/locale/es.yml b/front/salix/locale/es.yml index bed41c63b..8ed58a4e4 100644 --- a/front/salix/locale/es.yml +++ b/front/salix/locale/es.yml @@ -18,6 +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 # Actions diff --git a/front/salix/module.js b/front/salix/module.js index 5025eec22..bb7e189a9 100644 --- a/front/salix/module.js +++ b/front/salix/module.js @@ -120,7 +120,7 @@ function $exceptionHandler(vnApp, $window, $state, $injector) { messageT = 'Invalid login'; break; case 403: - messageT = (exception.data.error.message) ? exception.data.error.message : 'Access denied'; + messageT = exception.data.error.message || 'Access denied'; break; case 502: messageT = 'It seems that the server has fall down'; From 5c777c705feecca80213dd5a7ef4d70d246e4c26 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 14 Nov 2023 13:00:20 +0100 Subject: [PATCH 028/207] 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 029/207] 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 030/207] 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 3f7663da976c32d4b171311e4ce7800652be038d Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 15 Nov 2023 10:09:04 +0100 Subject: [PATCH 031/207] feat: refs #6275 crea back etExpeditionSummary --- .vscode/settings.json | 3 + .../methods/route/getExpeditionSummary.js | 64 +++++++++++++++++++ modules/route/back/models/route.js | 3 +- .../ticket/back/models/expedition-state.json | 7 ++ modules/ticket/back/models/expedition.json | 2 +- 5 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 modules/route/back/methods/route/getExpeditionSummary.js diff --git a/.vscode/settings.json b/.vscode/settings.json index 05d23f3bb..020c3ae7c 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -10,5 +10,8 @@ "eslint.format.enable": true, "[javascript]": { "editor.defaultFormatter": "dbaeumer.vscode-eslint" + }, + "[json]": { + "editor.defaultFormatter": "vscode.json-language-features" } } diff --git a/modules/route/back/methods/route/getExpeditionSummary.js b/modules/route/back/methods/route/getExpeditionSummary.js new file mode 100644 index 000000000..d35ab8611 --- /dev/null +++ b/modules/route/back/methods/route/getExpeditionSummary.js @@ -0,0 +1,64 @@ +module.exports = Self => { + Self.remoteMethod('getExpeditionSummary', { + description: 'Get summary of expeditions for a given route', + accepts: [ + { + arg: 'routeFk', + type: 'number', + required: true, + description: 'Foreign key for Route' + } + ], + returns: { + type: 'object', + root: true + }, + http: { + path: '/getExpeditionSummary', + verb: 'get' + } + }); + + Self.getExpeditionSummary = async(routeFk, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = ` + SELECT routeFk, + addressFk, + SUM(total) total, + SUM(delivery) delivery, + SUM(lost) lost, + SUM(delivered) delivered, + GROUP_CONCAT(totalPacking ORDER BY total DESC SEPARATOR ' ') itemPackingType + FROM ( + SELECT r.id AS routeFk, + t.addressFk, + CONCAT (IFNULL(e.itemPackingTypeFk,'-'), '', COUNT(*)) totalPacking, + COUNT(*) total, + SUM(est.code = 'ON DELIVERY') delivery, + SUM(est.code = 'LOST') lost, + SUM(est.code = 'DELIVERED') delivered, + t.priority + FROM vn.ticket t + JOIN vn.route r ON r.id = t.routeFk + JOIN vn.expedition e ON e.ticketFk = t.id + LEFT JOIN vn.expeditionStateType est ON est.id = e.stateTypeFk + JOIN vn.agencyMode am ON am.id = r.agencyModeFk + JOIN vn.agency ag ON ag.id = am.agencyFk + LEFT JOIN vn.userConfig uc ON uc.userFk = account.myUser_getId() + WHERE (r.created = util.VN_CURDATE() OR r.created = TIMESTAMPADD(day,-1, util.VN_CURDATE())) + AND t.routeFk = ? + GROUP BY t.addressFk, e.itemPackingTypeFk + ) sub + GROUP BY addressFk + ORDER BY priority DESC + `; + + const results = await Self.rawSql(query, [routeFk], options); + return results; + }; +}; + diff --git a/modules/route/back/models/route.js b/modules/route/back/models/route.js index 65fa43ab5..53440fc23 100644 --- a/modules/route/back/models/route.js +++ b/modules/route/back/models/route.js @@ -17,6 +17,7 @@ module.exports = Self => { require('../methods/route/cmr')(Self); require('../methods/route/getExternalCmrs')(Self); require('../methods/route/downloadCmrsZip')(Self); + require('../methods/route/getExpeditionSummary')(Self); Self.validate('kmStart', validateDistance, { message: 'Distance must be lesser than 1000' @@ -31,5 +32,5 @@ module.exports = Self => { const routeMaxKm = 1000; if (routeTotalKm > routeMaxKm || this.kmStart > this.kmEnd) err(); - }; + } }; diff --git a/modules/ticket/back/models/expedition-state.json b/modules/ticket/back/models/expedition-state.json index 262eb2e38..eda0f79fd 100644 --- a/modules/ticket/back/models/expedition-state.json +++ b/modules/ticket/back/models/expedition-state.json @@ -24,5 +24,12 @@ "userFk": { "type": "number" } + }, + "relations": { + "expeditionStateType": { + "type": "belongsTo", + "model": "ExpeditionStateType", + "foreignKey": "typeFk" + } } } diff --git a/modules/ticket/back/models/expedition.json b/modules/ticket/back/models/expedition.json index e32a3b23d..08950d0d1 100644 --- a/modules/ticket/back/models/expedition.json +++ b/modules/ticket/back/models/expedition.json @@ -30,7 +30,7 @@ }, "agencyMode": { "type": "belongsTo", - "model": "agency-mode", + "model": "AgencyMode", "foreignKey": "agencyModeFk" }, "worker": { From 0ddfb28327a2723fe394eec50482f3669a6bf274 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 20 Nov 2023 07:56:15 +0100 Subject: [PATCH 032/207] refs #5914 fix: transferInvoice --- db/dump/dumpedFixtures.sql | 13 +- db/dump/structure.sql | 6 +- loopback/locale/es.json | 15 ++- .../invoiceOut/specs/transferinvoice.spec.js | 4 +- .../methods/invoiceOut/transferInvoice.js | 34 +++-- .../back/models/invoice-correction.json | 9 +- ...ype-477.json => sii-type-invoice-out.json} | 3 + .../front/descriptor-menu/index.html | 120 +++++++++--------- .../invoiceOut/front/descriptor-menu/index.js | 10 +- .../front/descriptor-menu/locale/es.yml | 2 +- modules/ticket/back/methods/sale/refund.js | 4 +- .../back/methods/ticket/invoiceTickets.js | 19 ++- .../ticket/back/methods/ticket/makeInvoice.js | 18 ++- modules/ticket/back/methods/ticket/refund.js | 2 +- 14 files changed, 155 insertions(+), 104 deletions(-) rename modules/invoiceOut/back/models/{cplus-invoice-type-477.json => sii-type-invoice-out.json} (86%) diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index 43eba7f24..5e3438dbf 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -280,7 +280,18 @@ UNLOCK TABLES; LOCK TABLES `siiTypeInvoiceOut` WRITE; /*!40000 ALTER TABLE `siiTypeInvoiceOut` DISABLE KEYS */; -INSERT INTO `siiTypeInvoiceOut` VALUES (1,'F1 - Factura'),(2,'F2 - Factura simplificada (ticket)'),(3,'F3 - Factura emitida en sustitución de facturas simplificadas facturadas y declaradas'),(4,'F4 - Asiento resumen de facturas'),(5,'R1 - Factura rectificativa (Art. 80.1, 80.2 y error fundado en derecho)'),(6,'R2 - Factura rectificativa (Art. 80.3)'),(7,'R3 - Factura rectificativa (Art. 80.4)'),(8,'R4 - Factura rectificativa (Resto)'),(9,'R5 - Factura rectificativa en facturas simplificadas'); + +INSERT INTO `siiTypeInvoiceOut` (id, code, description) VALUES + (1, 'F1', 'Factura'), + (2, 'F2', 'Factura simplificada (ticket)'), + (3, 'F3', 'Factura emitida en sustitución de facturas simplificadas facturadas y declaradas'), + (4, 'F4', 'Asiento resumen de facturas'), + (5, 'R1', 'Factura rectificativa (Art. 80.1, 80.2 y error fundado en derecho)'), + (6, 'R2', 'Factura rectificativa (Art. 80.3)'), + (7, 'R3', 'Factura rectificativa (Art. 80.4)'), + (8, 'R4', 'Factura rectificativa (Resto)'), + (9, 'R5', 'Factura rectificativa en facturas simplificadas'); + /*!40000 ALTER TABLE `siiTypeInvoiceOut` ENABLE KEYS */; UNLOCK TABLES; diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 3dab0c5a4..2eecf6c30 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -26001,9 +26001,11 @@ DROP TABLE IF EXISTS `siiTypeInvoiceOut`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `siiTypeInvoiceOut` ( `id` int(10) unsigned NOT NULL, + `code` varchar(2) NOT NULL, `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='(*18) TIPO FACTURA (Asientos)REPERCUTIDO - DEVENGADO (477)'; + PRIMARY KEY (`id`), + UNIQUE KEY `code_UNIQUE` (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tipo de Factura Emitidas en el suministro de inmediato'; /*!40101 SET character_set_client = @saved_cs_client */; -- diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 239faff34..0dcbe0dc2 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -326,5 +326,16 @@ "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": "Usuario desactivado", "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" -} + "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima", + "Base negativa para los tickets: 65": "Base negativa para los tickets: 65", + "Base negativa para los tickets: 67": "Base negativa para los tickets: 67", + "Base negativa para los tickets: 70": "Base negativa para los tickets: 70", + "Base negativa para los tickets: 72": "Base negativa para los tickets: 72", + "Base negativa para los tickets: 74": "Base negativa para los tickets: 74", + "Base negativa para los tickets: 33": "Base negativa para los tickets: 33", + "Base negativa para los tickets: 35": "Base negativa para los tickets: 35", + "Base negativa para los tickets: 37": "Base negativa para los tickets: 37", + "Base negativa para los tickets: 39": "Base negativa para los tickets: 39", + "Base negativa para los tickets: 41": "Base negativa para los tickets: 41", + "Base negativa para los tickets: 43": "Base negativa para los tickets: 43" +} \ No newline at end of file diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js index 800a4ea83..dea4b6d00 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js @@ -24,7 +24,7 @@ describe('InvoiceOut tranferInvoice()', () => { const options = {transaction: tx}; const args = { id: '1', - ref: 'T4444444', + refFk: 'T4444444', newClientFk: 1, cplusRectificationId: 1, siiTypeInvoiceOutId: 1, @@ -49,7 +49,7 @@ describe('InvoiceOut tranferInvoice()', () => { const options = {transaction: tx}; const args = { id: '1', - ref: 'T1111111', + refFk: 'T1111111', newClientFk: 1101, cplusRectificationId: 1, siiTypeInvoiceOutId: 1, diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js index dde535c99..dcdd9b9b1 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js @@ -12,7 +12,7 @@ module.exports = Self => { description: 'Issued invoice id' }, { - arg: 'ref', + arg: 'refFk', type: 'string', required: true }, @@ -22,17 +22,17 @@ module.exports = Self => { required: true }, { - arg: 'cplusRectificationId', + arg: 'cplusRectificationFk', type: 'number', required: true }, { - arg: 'siiTypeInvoiceOutId', + arg: 'siiTypeInvoiceOutFk', type: 'number', required: true }, { - arg: 'invoiceCorrectionTypeId', + arg: 'invoiceCorrectionTypeFk', type: 'number', required: true }, @@ -50,14 +50,14 @@ module.exports = Self => { Self.transferInvoice = async(ctx, options) => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; - const args = ctx.args; + const {id, refFk, newClientFk, cplusRectificationFk, siiTypeInvoiceOutFk, invoiceCorrectionTypeFk} = ctx.args; let tx; if (typeof options == 'object') Object.assign(myOptions, options); - const {clientFk} = await models.InvoiceOut.findById(args.id); + const {clientFk} = await models.InvoiceOut.findById(id); - if (clientFk == args.newClientFk) + if (clientFk == newClientFk) throw new UserError(`Select a different client`); if (!myOptions.transaction) { @@ -65,10 +65,10 @@ module.exports = Self => { myOptions.transaction = tx; } try { - const filterRef = {where: {refFk: args.ref}}; + const filterRef = {where: {refFk: refFk}}; const tickets = await models.Ticket.find(filterRef, myOptions); const ticketsIds = tickets.map(ticket => ticket.id); - await models.Ticket.refund(ctx, ticketsIds, null, myOptions); + const refundTickets = await models.Ticket.refund(ctx, ticketsIds, null, myOptions); const filterTicket = {where: {ticketFk: {inq: ticketsIds}}}; @@ -82,20 +82,16 @@ module.exports = Self => { const clonedTicketIds = []; for (const clonedTicket of clonedTickets) { - await clonedTicket.updateAttribute('clientFk', args.newClientFk, myOptions); + await clonedTicket.updateAttribute('clientFk', newClientFk, myOptions); clonedTicketIds.push(clonedTicket.id); } - const invoiceIds = await models.Ticket.invoiceTickets(ctx, clonedTicketIds, myOptions); - const [invoiceId] = invoiceIds; + const invoiceCorrection = + {correctedFk: id, cplusRectificationFk, siiTypeInvoiceOutFk, invoiceCorrectionTypeFk}; + const refundTicketIds = refundTickets.map(ticket => ticket.id); - await models.InvoiceCorrection.create({ - correctingFk: invoiceId, - correctedFk: args.id, - cplusRectificationTypeFk: args.cplusRectificationId, - siiTypeInvoiceOutFk: args.siiTypeInvoiceOutId, - invoiceCorrectionTypeFk: args.invoiceCorrectionTypeId - }, myOptions); + await models.Ticket.invoiceTickets(ctx, refundTicketIds, invoiceCorrection, myOptions); + const [[invoiceId]] = await models.Ticket.invoiceTickets(ctx, clonedTicketIds, myOptions); if (tx) { await tx.commit(); diff --git a/modules/invoiceOut/back/models/invoice-correction.json b/modules/invoiceOut/back/models/invoice-correction.json index 43e4f07ef..5924c9232 100644 --- a/modules/invoiceOut/back/models/invoice-correction.json +++ b/modules/invoiceOut/back/models/invoice-correction.json @@ -16,13 +16,16 @@ "type": "number" }, "cplusRectificationTypeFk": { - "type": "number" + "type": "number", + "required": true }, "siiTypeInvoiceOutFk": { - "type": "number" + "type": "number", + "required": true }, "invoiceCorrectionTypeFk": { - "type": "number" + "type": "number", + "required": true } } } diff --git a/modules/invoiceOut/back/models/cplus-invoice-type-477.json b/modules/invoiceOut/back/models/sii-type-invoice-out.json similarity index 86% rename from modules/invoiceOut/back/models/cplus-invoice-type-477.json rename to modules/invoiceOut/back/models/sii-type-invoice-out.json index 17b312617..58d50a12c 100644 --- a/modules/invoiceOut/back/models/cplus-invoice-type-477.json +++ b/modules/invoiceOut/back/models/sii-type-invoice-out.json @@ -12,6 +12,9 @@ "type": "number", "description": "Identifier" }, + "code": { + "type": "string" + }, "description": { "type": "string" } diff --git a/modules/invoiceOut/front/descriptor-menu/index.html b/modules/invoiceOut/front/descriptor-menu/index.html index 0052f0c03..267aa0b15 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.html +++ b/modules/invoiceOut/front/descriptor-menu/index.html @@ -7,7 +7,8 @@ + data="siiTypeInvoiceOuts" + where="{code: {like: 'R%'}}"> + + transferInvoice +
- - - - #{{id}} - {{::name}} - - - - - {{::description}} - - - - - - - - - -
+ + + + #{{id}} - {{::name}} + + + + + {{::description}} + + + + + + + {{::code}} - {{::description}} + + + + + +
diff --git a/modules/invoiceOut/front/descriptor-menu/index.js b/modules/invoiceOut/front/descriptor-menu/index.js index d3862a753..f9d436092 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.js +++ b/modules/invoiceOut/front/descriptor-menu/index.js @@ -129,11 +129,11 @@ class Controller extends Section { transferInvoice() { const params = { id: this.invoiceOut.id, - ref: this.invoiceOut.ref, - newClientFk: this.invoiceOut.client.id, - cplusRectificationId: this.cplusRectificationType, - siiTypeInvoiceOutId: this.siiTypeInvoiceOut, - invoiceCorrectionTypeId: this.invoiceCorrectionType + refFk: this.invoiceOut.ref, + newClientFk: this.clientId, + cplusRectificationFk: this.cplusRectificationType, + siiTypeInvoiceOutFk: this.siiTypeInvoiceOut, + invoiceCorrectionTypeFk: this.invoiceCorrectionType }; this.$http.post(`InvoiceOuts/transferInvoice`, params).then(res => { const invoiceId = res.data; diff --git a/modules/invoiceOut/front/descriptor-menu/locale/es.yml b/modules/invoiceOut/front/descriptor-menu/locale/es.yml index 0f74b5fec..9456646af 100644 --- a/modules/invoiceOut/front/descriptor-menu/locale/es.yml +++ b/modules/invoiceOut/front/descriptor-menu/locale/es.yml @@ -22,4 +22,4 @@ The email can't be empty: El correo no puede estar vacío The following refund tickets have been created: "Se han creado los siguientes tickets de abono: {{ticketIds}}" Refund...: Abono... Transfer invoice to...: Transferir factura a... -Cplus Type: Cplus Tipo +Rectificative type: Tipo rectificativa diff --git a/modules/ticket/back/methods/sale/refund.js b/modules/ticket/back/methods/sale/refund.js index 17b70f12b..a7831e7e3 100644 --- a/modules/ticket/back/methods/sale/refund.js +++ b/modules/ticket/back/methods/sale/refund.js @@ -19,7 +19,7 @@ module.exports = Self => { } ], returns: { - type: ['number'], + type: ['object'], root: true }, http: { @@ -54,7 +54,7 @@ module.exports = Self => { if (tx) await tx.commit(); - return refundsTicket[0]; + return refundsTicket; } catch (e) { if (tx) await tx.rollback(); throw e; diff --git a/modules/ticket/back/methods/ticket/invoiceTickets.js b/modules/ticket/back/methods/ticket/invoiceTickets.js index fa3ee93af..29fb1769b 100644 --- a/modules/ticket/back/methods/ticket/invoiceTickets.js +++ b/modules/ticket/back/methods/ticket/invoiceTickets.js @@ -10,7 +10,13 @@ module.exports = function(Self) { description: 'The tickets id', type: ['number'], required: true + }, + { + arg: 'invoiceCorrection', + description: 'The invoice correction', + type: 'object', } + ], returns: { type: ['object'], @@ -22,7 +28,7 @@ module.exports = function(Self) { } }); - Self.invoiceTickets = async(ctx, ticketsIds, options) => { + Self.invoiceTickets = async(ctx, ticketsIds, invoiceCorrection, options) => { const models = Self.app.models; const date = Date.vnNew(); date.setHours(0, 0, 0, 0); @@ -68,9 +74,9 @@ module.exports = function(Self) { const addressIds = result.map(address => address.addressFk); for (const address of addressIds) - await createInvoice(ctx, companyId, ticketsIds, address, invoicesIds, myOptions); + await createInvoice(ctx, companyId, ticketsIds, address, invoicesIds, invoiceCorrection, myOptions); } else - await createInvoice(ctx, companyId, ticketsIds, null, invoicesIds, myOptions); + await createInvoice(ctx, companyId, ticketsIds, null, invoicesIds, invoiceCorrection, myOptions); if (tx) await tx.commit(); } catch (e) { @@ -85,9 +91,9 @@ module.exports = function(Self) { return invoicesIds; }; - async function createInvoice(ctx, companyId, ticketsIds, address, invoicesIds, myOptions) { + async function createInvoice(ctx, companyId, ticketsIds, address, invoicesIds, invoiceCorrection, myOptions) { const models = Self.app.models; - + console.log(ticketsIds, address); await models.Ticket.rawSql(` CREATE OR REPLACE TEMPORARY TABLE tmp.ticketToInvoice (PRIMARY KEY (id)) @@ -98,7 +104,8 @@ module.exports = function(Self) { ${address ? `AND addressFk = ${address}` : ''} `, [ticketsIds], myOptions); - const invoiceId = await models.Ticket.makeInvoice(ctx, 'R', companyId, Date.vnNew(), myOptions); + const invoiceId = + await models.Ticket.makeInvoice(ctx, 'R', companyId, Date.vnNew(), invoiceCorrection, myOptions); invoicesIds.push(invoiceId); } }; diff --git a/modules/ticket/back/methods/ticket/makeInvoice.js b/modules/ticket/back/methods/ticket/makeInvoice.js index e18e58e0b..9618e49e0 100644 --- a/modules/ticket/back/methods/ticket/makeInvoice.js +++ b/modules/ticket/back/methods/ticket/makeInvoice.js @@ -22,6 +22,11 @@ module.exports = function(Self) { description: 'The invoice date', type: 'date', required: true + }, + { + arg: 'invoiceCorrection', + description: 'The invoice correction', + type: 'object', } ], returns: { @@ -34,7 +39,7 @@ module.exports = function(Self) { } }); - Self.makeInvoice = async(ctx, invoiceType, companyFk, invoiceDate, options) => { + Self.makeInvoice = async(ctx, invoiceType, companyFk, invoiceDate, invoiceCorrection, options) => { const models = Self.app.models; invoiceDate.setHours(0, 0, 0, 0); @@ -67,8 +72,8 @@ module.exports = function(Self) { const [firstTicket] = tickets; const clientId = firstTicket.clientFk; - const clientCanBeInvoiced = await models.Client.canBeInvoiced(clientId, companyFk, myOptions); - if (!clientCanBeInvoiced) + const clientCanBeInvoiced = await models.Client.canBeInvoiced(clientId, companyFk, invoiceCorrection, myOptions); + if (!clientCanBeInvoiced && !invoiceCorrection) throw new UserError(`This client can't be invoiced`); const query = `SELECT vn.invoiceSerial(?, ?, ?) AS serial`; @@ -85,6 +90,13 @@ module.exports = function(Self) { if (!resultInvoice) throw new UserError('No tickets to invoice', 'notInvoiced'); + if (invoiceCorrection) { + await models.InvoiceCorrection.create( + Object.assign(invoiceCorrection, {correctingFk: resultInvoice.id}), + myOptions + ); + } + if (serial != 'R' && resultInvoice.id) await Self.rawSql('CALL invoiceOutBooking(?)', [resultInvoice.id], myOptions); diff --git a/modules/ticket/back/methods/ticket/refund.js b/modules/ticket/back/methods/ticket/refund.js index 758384ae2..4fed02260 100644 --- a/modules/ticket/back/methods/ticket/refund.js +++ b/modules/ticket/back/methods/ticket/refund.js @@ -15,7 +15,7 @@ module.exports = Self => { } ], returns: { - type: ['number'], + type: ['object'], root: true }, http: { From 0a2fd9cf5de1915d897d4a5871f74f74ff988019 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Mon, 20 Nov 2023 18:39:37 +0100 Subject: [PATCH 033/207] fix: refs #6432, #5848 account sync fixes --- .../test.js | 4 +- ...ount-synchronizer.js => account-linker.js} | 12 +- modules/account/back/models/account-config.js | 158 ++++++++---------- modules/account/back/models/ldap-config.js | 3 +- modules/account/back/models/ldap-config.json | 2 +- modules/account/back/models/role-config.js | 4 +- modules/account/back/models/role-config.json | 2 +- modules/account/back/models/samba-config.js | 3 +- modules/account/back/models/samba-config.json | 2 +- modules/account/back/models/sip-config.js | 2 +- modules/account/back/models/sip-config.json | 3 +- modules/account/front/descriptor/index.html | 3 +- 12 files changed, 96 insertions(+), 102 deletions(-) rename modules/account/back/methods/{account-synchronizer => account-linker}/test.js (59%) rename modules/account/back/mixins/{account-synchronizer.js => account-linker.js} (85%) diff --git a/modules/account/back/methods/account-synchronizer/test.js b/modules/account/back/methods/account-linker/test.js similarity index 59% rename from modules/account/back/methods/account-synchronizer/test.js rename to modules/account/back/methods/account-linker/test.js index a77940168..990af2df8 100644 --- a/modules/account/back/methods/account-synchronizer/test.js +++ b/modules/account/back/methods/account-linker/test.js @@ -1,3 +1,4 @@ +const NotFoundError = require('vn-loopback/util/not-found-error'); module.exports = Self => { Self.remoteMethod('test', { @@ -9,7 +10,8 @@ module.exports = Self => { }); Self.test = async function() { - let connector = await Self.getSynchronizer(); + const connector = await Self.getLinker(); + if (!connector) throw new NotFoundError('Linker not configured'); await connector.test(); }; }; diff --git a/modules/account/back/mixins/account-synchronizer.js b/modules/account/back/mixins/account-linker.js similarity index 85% rename from modules/account/back/mixins/account-synchronizer.js rename to modules/account/back/mixins/account-linker.js index 8ba8bfe9d..c882d0893 100644 --- a/modules/account/back/mixins/account-synchronizer.js +++ b/modules/account/back/mixins/account-linker.js @@ -3,14 +3,14 @@ const app = require('vn-loopback/server/server'); const UserError = require('vn-loopback/util/user-error'); module.exports = function(Self, options) { - require('../methods/account-synchronizer/test')(Self); + require('../methods/account-linker/test')(Self); Self.once('attached', function() { - app.models.AccountConfig.addSynchronizer(Self); + app.models.AccountConfig.addLinker(Self); }); /** - * Mixin for user synchronizers. + * Mixin for account linkers. * * @property {Array} $ * @property {Object} accountConfig @@ -18,12 +18,12 @@ module.exports = function(Self, options) { */ let Mixin = { /** - * Initalizes the synchronizer. + * Initalizes the linker. */ async init() {}, /** - * Deinitalizes the synchronizer. + * Deinitalizes the linker. */ async deinit() {}, @@ -57,7 +57,7 @@ module.exports = function(Self, options) { async syncRoles() {}, /** - * Tests synchronizer configuration. + * Tests linker configuration. */ async test() { try { diff --git a/modules/account/back/models/account-config.js b/modules/account/back/models/account-config.js index 0db699b99..2cc6b240d 100644 --- a/modules/account/back/models/account-config.js +++ b/modules/account/back/models/account-config.js @@ -3,94 +3,85 @@ const models = require('vn-loopback/server/server').models; module.exports = Self => { Object.assign(Self, { - synchronizers: [], + linkers: [], - addSynchronizer(synchronizer) { - this.synchronizers.push(synchronizer); + addLinker(linker) { + this.linkers.push(linker); }, - async getInstance() { - let instance = await Self.findOne({ + async initEngine() { + const accountConfig = await Self.findOne({ fields: ['homedir', 'shell', 'idBase'] }); - await instance.synchronizerInit(); - return instance; + const mailConfig = await models.MailConfig.findOne({ + fields: ['domain'] + }); + + const linkers = []; + + for (const Linker of Self.linkers) { + const linker = await Linker.getLinker(); + if (!linker) continue; + Object.assign(linker, {accountConfig}); + await linker.init(); + linkers.push(linker); + } + + Object.assign(accountConfig, { + linkers, + domain: mailConfig.domain + }); + + return { + accountConfig, + linkers + }; + }, + + async deinitEngine(engine) { + for (const linker of engine.linkers) + await linker.deinit(); + }, + + async syncUser(userName, password) { + const engine = await Self.initEngine(); + try { + await Self.syncUserBase(engine, userName, password, true); + } finally { + await Self.deinitEngine(engine); + } }, async syncUsers() { - let instance = await Self.getInstance(); + const engine = await Self.initEngine(); + + let usersToSync = new Set(); + for (const linker of engine.linkers) + await linker.getUsers(usersToSync); - let usersToSync = await instance.synchronizerGetUsers(); usersToSync = Array.from(usersToSync.values()) .sort((a, b) => a.localeCompare(b)); for (let userName of usersToSync) { try { + // eslint-disable-next-line no-console console.log(`Synchronizing user '${userName}'`); - await instance.synchronizerSyncUser(userName); + + await Self.syncUserBase(engine, userName); + + // eslint-disable-next-line no-console console.log(` -> User '${userName}' sinchronized`); } catch (err) { + // eslint-disable-next-line no-console console.error(` -> User '${userName}' synchronization error:`, err.message); } } - await instance.synchronizerDeinit(); + await Self.deinitEngine(engine); await Self.syncRoles(); }, - async syncUser(userName, password) { - let instance = await Self.getInstance(); - try { - await instance.synchronizerSyncUser(userName, password, true); - } finally { - await instance.synchronizerDeinit(); - } - }, - - async syncRoles() { - let instance = await Self.getInstance(); - try { - await instance.synchronizerSyncRoles(); - } finally { - await instance.synchronizerDeinit(); - } - }, - - async getSynchronizer() { - return await Self.findOne(); - } - }); - - Object.assign(Self.prototype, { - async synchronizerInit() { - let mailConfig = await models.MailConfig.findOne({ - fields: ['domain'] - }); - - let synchronizers = []; - - for (let Synchronizer of Self.synchronizers) { - let synchronizer = await Synchronizer.getSynchronizer(); - if (!synchronizer) continue; - Object.assign(synchronizer, { - accountConfig: this - }); - await synchronizer.init(); - synchronizers.push(synchronizer); - } - - Object.assign(this, { - synchronizers, - domain: mailConfig.domain - }); - }, - - async synchronizerDeinit() { - for (let synchronizer of this.synchronizers) - await synchronizer.deinit(); - }, - - async synchronizerSyncUser(userName, password, syncGroups) { + async syncUserBase(engine, userName, password, syncGroups) { if (!userName) return; userName = userName.toLowerCase(); @@ -98,7 +89,7 @@ module.exports = Self => { if (['administrator', 'root'].indexOf(userName) >= 0) return; - let user = await models.VnUser.findOne({ + const user = await models.VnUser.findOne({ where: {name: userName}, fields: [ 'id', @@ -130,27 +121,28 @@ module.exports = Self => { ] }); - let info = { + const info = { user, hasAccount: false }; if (user) { - let exists = await models.Account.exists(user.id); + const exists = await models.Account.exists(user.id); + const {accountConfig} = engine; Object.assign(info, { hasAccount: user.active && exists, - corporateMail: `${userName}@${this.domain}`, - uidNumber: this.idBase + user.id + corporateMail: `${userName}@${accountConfig.domain}`, + uidNumber: accountConfig.idBase + user.id }); } - let errs = []; + const errs = []; - for (let synchronizer of this.synchronizers) { + for (const linker of engine.linkers) { try { - await synchronizer.syncUser(userName, info, password); + await linker.syncUser(userName, info, password); if (syncGroups) - await synchronizer.syncUserGroups(userName, info); + await linker.syncUserGroups(userName, info); } catch (err) { errs.push(err); } @@ -159,18 +151,16 @@ module.exports = Self => { if (errs.length) throw errs[0]; }, - async synchronizerGetUsers() { - let usersToSync = new Set(); + async syncRoles() { + const engine = await Self.initEngine(); + try { + await Self.rawSql(`CALL account.role_sync`); - for (let synchronizer of this.synchronizers) - await synchronizer.getUsers(usersToSync); - - return usersToSync; - }, - - async synchronizerSyncRoles() { - for (let synchronizer of this.synchronizers) - await synchronizer.syncRoles(); + for (const linker of engine.linkers) + await linker.syncRoles(); + } finally { + await Self.deinitEngine(engine); + } } }); }; diff --git a/modules/account/back/models/ldap-config.js b/modules/account/back/models/ldap-config.js index 9dcc4136d..b557d243c 100644 --- a/modules/account/back/models/ldap-config.js +++ b/modules/account/back/models/ldap-config.js @@ -7,7 +7,7 @@ const nthash = require('smbhash').nthash; module.exports = Self => { const shouldSync = process.env.NODE_ENV !== 'test'; - Self.getSynchronizer = async function() { + Self.getLinker = async function() { return await Self.findOne({ fields: [ 'server', @@ -24,6 +24,7 @@ module.exports = Self => { this.client = ldap.createClient({ url: this.server }); + this.client.on('error', () => {}); await this.client.bind(this.rdn, this.password); }, diff --git a/modules/account/back/models/ldap-config.json b/modules/account/back/models/ldap-config.json index 2fd5aa901..d4d3a094d 100644 --- a/modules/account/back/models/ldap-config.json +++ b/modules/account/back/models/ldap-config.json @@ -7,7 +7,7 @@ } }, "mixins": { - "AccountSynchronizer": {} + "AccountLinker": {} }, "properties": { "id": { diff --git a/modules/account/back/models/role-config.js b/modules/account/back/models/role-config.js index b90ef75fb..d6c57b70b 100644 --- a/modules/account/back/models/role-config.js +++ b/modules/account/back/models/role-config.js @@ -1,6 +1,6 @@ module.exports = Self => { - Self.getSynchronizer = async function() { + Self.getLinker = async function() { let NODE_ENV = process.env.NODE_ENV; if (!NODE_ENV || NODE_ENV == 'development') return null; @@ -45,6 +45,7 @@ module.exports = Self => { } if (!isUpdatable) { + // eslint-disable-next-line no-console console.warn(`RoleConfig.syncUser(): User '${userName}' cannot be updated, not managed by me`); return; } @@ -82,6 +83,7 @@ module.exports = Self => { [mysqlUser, this.userHost]); } catch (err) { if (err.code == 'ER_REVOKE_GRANTS') + // eslint-disable-next-line no-console console.warn(`${err.code}: ${err.sqlMessage}: ${err.sql}`); else throw err; diff --git a/modules/account/back/models/role-config.json b/modules/account/back/models/role-config.json index f4138bea8..3b843eaea 100644 --- a/modules/account/back/models/role-config.json +++ b/modules/account/back/models/role-config.json @@ -7,7 +7,7 @@ } }, "mixins": { - "AccountSynchronizer": {} + "AccountLinker": {} }, "properties": { "id": { diff --git a/modules/account/back/models/samba-config.js b/modules/account/back/models/samba-config.js index 7714fb01c..f5672ca21 100644 --- a/modules/account/back/models/samba-config.js +++ b/modules/account/back/models/samba-config.js @@ -13,7 +13,7 @@ const UserAccountControlFlags = { module.exports = Self => { const shouldSync = process.env.NODE_ENV !== 'test'; - Self.getSynchronizer = async function() { + Self.getLinker = async function() { return await Self.findOne({ fields: [ 'host', @@ -39,6 +39,7 @@ module.exports = Self => { url: `ldaps://${this.adController}:636`, tlsOptions: {rejectUnauthorized: this.verifyCert} }); + adClient.on('error', () => {}); await adClient.bind(bindDn, this.adPassword); Object.assign(this, { adClient, diff --git a/modules/account/back/models/samba-config.json b/modules/account/back/models/samba-config.json index 28cbb2689..4c9e0a794 100644 --- a/modules/account/back/models/samba-config.json +++ b/modules/account/back/models/samba-config.json @@ -7,7 +7,7 @@ } }, "mixins": { - "AccountSynchronizer": {} + "AccountLinker": {} }, "properties": { "id": { diff --git a/modules/account/back/models/sip-config.js b/modules/account/back/models/sip-config.js index 3b5cb2dbb..703783337 100644 --- a/modules/account/back/models/sip-config.js +++ b/modules/account/back/models/sip-config.js @@ -2,7 +2,7 @@ const app = require('vn-loopback/server/server'); module.exports = Self => { - Self.getSynchronizer = async function() { + Self.getLinker = async function() { return await Self.findOne({fields: ['id']}); }; diff --git a/modules/account/back/models/sip-config.json b/modules/account/back/models/sip-config.json index 6c5ba3db3..a25d09c67 100644 --- a/modules/account/back/models/sip-config.json +++ b/modules/account/back/models/sip-config.json @@ -7,7 +7,7 @@ } }, "mixins": { - "AccountSynchronizer": {} + "AccountLinker": {} }, "properties": { "id": { @@ -16,4 +16,3 @@ } } } - \ No newline at end of file diff --git a/modules/account/front/descriptor/index.html b/modules/account/front/descriptor/index.html index b0a70edd1..86e78dfce 100644 --- a/modules/account/front/descriptor/index.html +++ b/modules/account/front/descriptor/index.html @@ -68,7 +68,6 @@ Deactivate user - + Do you want to synchronize user? From bf7c67dbdeb595594beff1977a6374f0d8a5009d Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 21 Nov 2023 09:26:02 +0100 Subject: [PATCH 034/207] fix: refs #6197 add definer to events --- modules/account/back/models/role-inherit.js | 2 +- modules/zone/back/models/zone-closure.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/account/back/models/role-inherit.js b/modules/account/back/models/role-inherit.js index 7d31e62b1..e994f844e 100644 --- a/modules/account/back/models/role-inherit.js +++ b/modules/account/back/models/role-inherit.js @@ -9,7 +9,7 @@ module.exports = Self => { Self.observe(hook, async() => { try { await Self.rawSql(` - CREATE EVENT account.role_sync + CREATE DEFINER = CURRENT_ROLE EVENT account.role_sync ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 5 SECOND DO CALL role_sync; `); diff --git a/modules/zone/back/models/zone-closure.js b/modules/zone/back/models/zone-closure.js index d25d6f707..61350ef56 100644 --- a/modules/zone/back/models/zone-closure.js +++ b/modules/zone/back/models/zone-closure.js @@ -14,7 +14,7 @@ module.exports = Self => { async function doCalc(ctx) { try { await Self.rawSql(` - CREATE EVENT zoneClosure_doRecalc + CREATE DEFINER = CURRENT_ROLE EVENT zoneClosure_doRecalc ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 15 SECOND DO CALL zoneClosure_recalc; `); From a0a9e299d93e7adb778b2c021a8ef91477278510 Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 22 Nov 2023 12:39:21 +0100 Subject: [PATCH 035/207] feat: refs #6275 getTickets with phone --- .../methods/route/getExpeditionSummary.js | 40 +++++++++---------- .../route/back/methods/route/getTickets.js | 11 +++-- 2 files changed, 28 insertions(+), 23 deletions(-) diff --git a/modules/route/back/methods/route/getExpeditionSummary.js b/modules/route/back/methods/route/getExpeditionSummary.js index d35ab8611..ee89401a8 100644 --- a/modules/route/back/methods/route/getExpeditionSummary.js +++ b/modules/route/back/methods/route/getExpeditionSummary.js @@ -34,30 +34,30 @@ module.exports = Self => { SUM(delivered) delivered, GROUP_CONCAT(totalPacking ORDER BY total DESC SEPARATOR ' ') itemPackingType FROM ( - SELECT r.id AS routeFk, - t.addressFk, - CONCAT (IFNULL(e.itemPackingTypeFk,'-'), '', COUNT(*)) totalPacking, - COUNT(*) total, - SUM(est.code = 'ON DELIVERY') delivery, - SUM(est.code = 'LOST') lost, - SUM(est.code = 'DELIVERED') delivered, - t.priority - FROM vn.ticket t - JOIN vn.route r ON r.id = t.routeFk - JOIN vn.expedition e ON e.ticketFk = t.id - LEFT JOIN vn.expeditionStateType est ON est.id = e.stateTypeFk - JOIN vn.agencyMode am ON am.id = r.agencyModeFk - JOIN vn.agency ag ON ag.id = am.agencyFk - LEFT JOIN vn.userConfig uc ON uc.userFk = account.myUser_getId() - WHERE (r.created = util.VN_CURDATE() OR r.created = TIMESTAMPADD(day,-1, util.VN_CURDATE())) - AND t.routeFk = ? - GROUP BY t.addressFk, e.itemPackingTypeFk - ) sub + SELECT r.id AS routeFk, + t.addressFk, + CONCAT (IFNULL(e.itemPackingTypeFk,'-'), '', COUNT(*)) totalPacking, + COUNT(*) total, + SUM(est.code = 'ON DELIVERY') delivery, + SUM(est.code = 'LOST') lost, + SUM(est.code = 'DELIVERED') delivered, + t.priority + FROM vn.ticket t + JOIN vn.route r ON r.id = t.routeFk + JOIN vn.expedition e ON e.ticketFk = t.id + LEFT JOIN vn.expeditionStateType est ON est.id = e.stateTypeFk + JOIN vn.agencyMode am ON am.id = r.agencyModeFk + JOIN vn.agency ag ON ag.id = am.agencyFk + LEFT JOIN vn.userConfig uc ON uc.userFk = account.myUser_getId() + WHERE (r.created = util.VN_CURDATE() OR r.created = util.yesterday()) + AND t.routeFk = ? + GROUP BY t.addressFk, e.itemPackingTypeFk + ) sub GROUP BY addressFk ORDER BY priority DESC `; - const results = await Self.rawSql(query, [routeFk], options); + const results = await Self.rawSql(query, [routeFk], myOptions); return results; }; }; diff --git a/modules/route/back/methods/route/getTickets.js b/modules/route/back/methods/route/getTickets.js index 1eb9e27f5..8e1356a42 100644 --- a/modules/route/back/methods/route/getTickets.js +++ b/modules/route/back/methods/route/getTickets.js @@ -51,11 +51,16 @@ module.exports = Self => { u.nickname AS userNickname, vn.ticketTotalVolume(t.id) AS volume, tob.description, - GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt + GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt, + c.phone ClientPhone, + c.mobile ClientMobile, + a.phone AddressPhone, + a.mobile AddressMobile FROM vn.route r JOIN ticket t ON t.routeFk = r.id - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk + JOIN client c ON t.clientFk = c.id + LEFT JOIN vn.sale s ON s.ticketFk = t.id + LEFT JOIN vn.item i ON i.id = s.itemFk LEFT JOIN ticketState ts ON ts.ticketFk = t.id LEFT JOIN state st ON st.id = ts.stateFk LEFT JOIN warehouse wh ON wh.id = t.warehouseFk From 6b07ee4eb1913294468af4e4202c9d768c1ff716 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 22 Nov 2023 18:35:14 +0100 Subject: [PATCH 036/207] hotfix workerhours --- modules/worker/front/time-control/index.js | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index a60c71589..f8a94be52 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -111,10 +111,8 @@ class Controller extends Section { dayIndex.setDate(dayIndex.getDate() + 1); } - if (this.worker) { - this.fetchHours(); - this.getWeekData(); - } + this.fetchHours(); + this.getWeekData(); } set weekTotalHours(totalHours) { @@ -404,7 +402,7 @@ class Controller extends Section { }); } - changeState(state, reason) { + state(state, reason) { this.state = state; this.reason = reason; this.repaint(); From 900dffbbba344b62662e7fa8ce388d0d9006a20e Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 23 Nov 2023 10:26:28 +0100 Subject: [PATCH 037/207] refs #5811 delete viaexpress expeditions included --- back/models/viaexpress-config.js | 2 + loopback/locale/en.json | 3 +- loopback/locale/es.json | 5 +- .../methods/expedition/deleteExpeditions.js | 66 +++++++++++-------- modules/ticket/back/models/expedition.json | 2 +- 5 files changed, 45 insertions(+), 33 deletions(-) diff --git a/back/models/viaexpress-config.js b/back/models/viaexpress-config.js index d0335b28b..429c0a0d8 100644 --- a/back/models/viaexpress-config.js +++ b/back/models/viaexpress-config.js @@ -1,4 +1,6 @@ module.exports = Self => { require('../methods/viaexpress-config/internationalExpedition')(Self); require('../methods/viaexpress-config/renderer')(Self); + require('../methods/viaexpress-config/deleteShipment')(Self); + require('../methods/viaexpress-config/deleteShipmentRenderer')(Self); }; diff --git a/loopback/locale/en.json b/loopback/locale/en.json index ed6aa474f..7d5b5ed47 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -199,5 +199,6 @@ "You can only add negative amounts in refund tickets": "You can only add negative amounts in refund tickets", "Try again": "Try again", "keepPrice": "keepPrice", - "Cannot past travels with entries": "Cannot past travels with entries" + "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 41acc36c3..01384efb4 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -328,5 +328,6 @@ "User disabled": "Usuario desactivado", "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" -} + "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/expedition/deleteExpeditions.js b/modules/ticket/back/methods/expedition/deleteExpeditions.js index 2419d3a5e..72c48fd3a 100644 --- a/modules/ticket/back/methods/expedition/deleteExpeditions.js +++ b/modules/ticket/back/methods/expedition/deleteExpeditions.js @@ -1,6 +1,7 @@ +const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.remoteMethod('deleteExpeditions', { + Self.remoteMethodCtx('deleteExpeditions', { description: 'Delete the selected expeditions', accessType: 'WRITE', accepts: [{ @@ -9,44 +10,51 @@ module.exports = Self => { required: true, description: 'The expeditions ids to delete' }], - returns: { - type: ['object'], - root: true - }, http: { path: `/deleteExpeditions`, verb: 'POST' } }); - Self.deleteExpeditions = async(expeditionIds, options) => { + Self.deleteExpeditions = async(ctx, expeditionIds) => { const models = Self.app.models; - const myOptions = {}; - let tx; + const $t = ctx.req.__; + const notDeletedExpeditions = []; - if (typeof options == 'object') - Object.assign(myOptions, options); + for (let expeditionId of expeditionIds) { + const filter = { + fields: [], + where: { + id: expeditionId + }, + include: [ + { + relation: 'agencyMode', + scope: { + fields: ['code'], + } + } + ] + }; - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; + const expedition = await models.Expedition.findOne(filter); + const {code} = expedition.agencyMode(); + + if (code && code.toLowerCase().substring(0, 10) == 'viaexpress') { + const isDeleted = await models.ViaexpressConfig.deleteShipment(expeditionId); + + if (isDeleted === 'true') + await models.Expedition.destroyById(expeditionId); + + else if (!isDeleted) + notDeletedExpeditions.push(expeditionId); + } else + await models.Expedition.destroyById(expeditionId); } - - try { - const promises = []; - for (let expeditionId of expeditionIds) { - const deletedExpedition = models.Expedition.destroyById(expeditionId, myOptions); - promises.push(deletedExpedition); - } - - const deletedExpeditions = await Promise.all(promises); - - if (tx) await tx.commit(); - - return deletedExpeditions; - } catch (e) { - if (tx) await tx.rollback(); - throw e; + if (notDeletedExpeditions.length) { + throw new UserError( + $t(`It was not able to remove the next expeditions:`, {expeditions: notDeletedExpeditions.join()}) + ); } }; }; diff --git a/modules/ticket/back/models/expedition.json b/modules/ticket/back/models/expedition.json index 1ad083ce3..069c6e281 100644 --- a/modules/ticket/back/models/expedition.json +++ b/modules/ticket/back/models/expedition.json @@ -33,7 +33,7 @@ }, "agencyMode": { "type": "belongsTo", - "model": "agency-mode", + "model": "AgencyMode", "foreignKey": "agencyModeFk" }, "worker": { From 2e67ef4f5d40e86cfc6bfa251b2da278509e2a5f Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 23 Nov 2023 10:32:07 +0100 Subject: [PATCH 038/207] refs #5811 refactor deleteExpeditions --- modules/ticket/back/methods/expedition/deleteExpeditions.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/modules/ticket/back/methods/expedition/deleteExpeditions.js b/modules/ticket/back/methods/expedition/deleteExpeditions.js index 72c48fd3a..a53c5d82c 100644 --- a/modules/ticket/back/methods/expedition/deleteExpeditions.js +++ b/modules/ticket/back/methods/expedition/deleteExpeditions.js @@ -43,11 +43,9 @@ module.exports = Self => { if (code && code.toLowerCase().substring(0, 10) == 'viaexpress') { const isDeleted = await models.ViaexpressConfig.deleteShipment(expeditionId); - if (isDeleted === 'true') - await models.Expedition.destroyById(expeditionId); + if (isDeleted === 'true') await models.Expedition.destroyById(expeditionId); - else if (!isDeleted) - notDeletedExpeditions.push(expeditionId); + else notDeletedExpeditions.push(expeditionId); } else await models.Expedition.destroyById(expeditionId); } From db15285858f366732b256725756b57306e7437a5 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 23 Nov 2023 11:21:56 +0100 Subject: [PATCH 039/207] refs #5811 test updated --- .../methods/expedition/deleteExpeditions.js | 20 ++++++++++++++----- .../specs/deleteExpeditions.spec.js | 13 ++++++------ 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/modules/ticket/back/methods/expedition/deleteExpeditions.js b/modules/ticket/back/methods/expedition/deleteExpeditions.js index a53c5d82c..3c98c8017 100644 --- a/modules/ticket/back/methods/expedition/deleteExpeditions.js +++ b/modules/ticket/back/methods/expedition/deleteExpeditions.js @@ -13,6 +13,10 @@ module.exports = Self => { http: { path: `/deleteExpeditions`, verb: 'POST' + }, + returns: { + type: ['object'], + root: true } }); @@ -20,6 +24,7 @@ module.exports = Self => { const models = Self.app.models; const $t = ctx.req.__; const notDeletedExpeditions = []; + const deletedExpeditions = []; for (let expeditionId of expeditionIds) { const filter = { @@ -43,16 +48,21 @@ module.exports = Self => { if (code && code.toLowerCase().substring(0, 10) == 'viaexpress') { const isDeleted = await models.ViaexpressConfig.deleteShipment(expeditionId); - if (isDeleted === 'true') await models.Expedition.destroyById(expeditionId); - - else notDeletedExpeditions.push(expeditionId); - } else - await models.Expedition.destroyById(expeditionId); + if (isDeleted === 'true') { + const deletedExpedition = await models.Expedition.destroyById(expeditionId); + deletedExpeditions.push(deletedExpedition); + } else notDeletedExpeditions.push(expeditionId); + } else { + const deletedExpedition = await models.Expedition.destroyById(expeditionId); + deletedExpeditions.push(deletedExpedition); + } } + if (notDeletedExpeditions.length) { throw new UserError( $t(`It was not able to remove the next expeditions:`, {expeditions: notDeletedExpeditions.join()}) ); } + return deletedExpeditions; }; }; diff --git a/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js b/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js index 61937989e..bf8bafe34 100644 --- a/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js +++ b/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js @@ -2,17 +2,16 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('ticket deleteExpeditions()', () => { + let ctx; beforeAll(async() => { - const activeCtx = { + ctx = { accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } + req: { + headers: {origin: 'http://localhost'} } }; spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx + active: ctx }); }); @@ -23,7 +22,7 @@ describe('ticket deleteExpeditions()', () => { const options = {transaction: tx}; const expeditionIds = [12, 13]; - const result = await models.Expedition.deleteExpeditions(expeditionIds, options); + const result = await models.Expedition.deleteExpeditions(ctx, expeditionIds, options); expect(result.length).toEqual(2); From e314a67fe72f6112337330f7aefa1e46b7d7e84f Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 23 Nov 2023 13:25:31 +0100 Subject: [PATCH 040/207] refs #6274 time control methods migrated --- .../methods/worker-time-control/clockIn.js | 34 ++++++++++++++++ .../methods/worker-time-control/getClockIn.js | 30 ++++++++++++++ .../back/methods/worker-time-control/login.js | 39 +++++++++++++++++++ .../worker/back/models/worker-time-control.js | 3 ++ 4 files changed, 106 insertions(+) create mode 100644 modules/worker/back/methods/worker-time-control/clockIn.js create mode 100644 modules/worker/back/methods/worker-time-control/getClockIn.js create mode 100644 modules/worker/back/methods/worker-time-control/login.js diff --git a/modules/worker/back/methods/worker-time-control/clockIn.js b/modules/worker/back/methods/worker-time-control/clockIn.js new file mode 100644 index 000000000..45de85f1d --- /dev/null +++ b/modules/worker/back/methods/worker-time-control/clockIn.js @@ -0,0 +1,34 @@ +module.exports = Self => { + Self.remoteMethodCtx('clockIn', { + description: 'Check if the employee can clock in', + accessType: 'READ', + accepts: [ + { + arg: 'workerFk', + type: 'integer', + required: true, + }, + { + arg: 'direction', + type: 'integer' + }, + { + arg: 'key', + type: 'string', + } + ], + http: { + path: `/clockIn`, + verb: 'POST' + } + }); + + Self.clockIn = async(ctx, pin, direction, key, options) => { + const myOptions = {}; + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = 'CALL vn.workerTimeControl_clockIn(?, NULL, ?)'; + return await Self.rawSql(query, [workerFk, direction], options); + }; +}; diff --git a/modules/worker/back/methods/worker-time-control/getClockIn.js b/modules/worker/back/methods/worker-time-control/getClockIn.js new file mode 100644 index 000000000..603914655 --- /dev/null +++ b/modules/worker/back/methods/worker-time-control/getClockIn.js @@ -0,0 +1,30 @@ +module.exports = Self => { + Self.remoteMethodCtx('getClockIn', { + description: 'Shows the clockings for each day, in columns per day', + accessType: 'READ', + accepts: [ + { + arg: 'workerFk', + type: 'int', + required: true, + }, + { + arg: 'key', + type: 'string', + } + ], + http: { + path: `/getClockIn`, + verb: 'POST' + } + }); + + Self.getClockIn = async(ctx, workerFk, key, options) => { + const myOptions = {}; + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = `CALL vn.workerTimeControl_getClockIn(?, CURDATE())`; + return await Self.rawSql(query, [workerFk], myOptions); + }; +}; diff --git a/modules/worker/back/methods/worker-time-control/login.js b/modules/worker/back/methods/worker-time-control/login.js new file mode 100644 index 000000000..75813411a --- /dev/null +++ b/modules/worker/back/methods/worker-time-control/login.js @@ -0,0 +1,39 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('login', { + description: 'Consult the user\'s information and the buttons that must be activated after logging in', + accessType: 'READ', + accepts: [ + { + arg: 'pin', + type: 'string', + required: true, + }, + { + arg: 'key', + type: 'string', + } + ], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/login`, + verb: 'POST' + } + }); + + Self.login = async(ctx, pin, key, options) => { + const myOptions = {}; + if (typeof options == 'object') + Object.assign(myOptions, options); + + const query = `CALL vn.workerTimeControl_login(?)`; + const user = await Self.rawSql(query, [pin], myOptions); + + if (!user) throw new UserError('Indique el pin.'); + return user; + }; +}; diff --git a/modules/worker/back/models/worker-time-control.js b/modules/worker/back/models/worker-time-control.js index d5da680cf..1457c7a46 100644 --- a/modules/worker/back/models/worker-time-control.js +++ b/modules/worker/back/models/worker-time-control.js @@ -10,6 +10,9 @@ module.exports = Self => { require('../methods/worker-time-control/weeklyHourRecordEmail')(Self); require('../methods/worker-time-control/getMailStates')(Self); require('../methods/worker-time-control/resendWeeklyHourEmail')(Self); + require('../methods/worker-time-control/login')(Self); + require('../methods/worker-time-control/getClockIn')(Self); + require('../methods/worker-time-control/clockIn')(Self); Self.rewriteDbError(function(err) { if (err.code === 'ER_DUP_ENTRY') From eeef279483a5adc30d3ad3e31197d1f0e0141c5f Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 23 Nov 2023 13:34:29 +0100 Subject: [PATCH 041/207] refs #5811 replace decription --- back/methods/viaexpress-config/deleteShipment.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/methods/viaexpress-config/deleteShipment.js b/back/methods/viaexpress-config/deleteShipment.js index 40509899b..babd3eeee 100644 --- a/back/methods/viaexpress-config/deleteShipment.js +++ b/back/methods/viaexpress-config/deleteShipment.js @@ -3,7 +3,7 @@ const {DOMParser} = require('xmldom'); module.exports = Self => { Self.remoteMethod('deleteShipment', { - description: 'Create an expedition and return a label', + description: 'Delete a shipment by providing the expedition ID, interacting with Viaexpress API', accessType: 'WRITE', accepts: [{ arg: 'expeditionFk', From ebe467f721c659ab7cfaa12230fc6771e3d2b73c Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 24 Nov 2023 07:04:55 +0100 Subject: [PATCH 042/207] refs #6506 hotfix --- modules/worker/front/calendar/index.html | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/worker/front/calendar/index.html b/modules/worker/front/calendar/index.html index d64c22408..75e892575 100644 --- a/modules/worker/front/calendar/index.html +++ b/modules/worker/front/calendar/index.html @@ -70,6 +70,7 @@ fields="['started', 'ended']" ng-model="$ctrl.businessId" search-function="{businessFk: $search}" + show-field="businessFk" value-field="businessFk" order="businessFk DESC" limit="5"> From 8a568f180a3d9de0f745aa33ff894616fb3eec8a Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 24 Nov 2023 07:47:57 +0100 Subject: [PATCH 043/207] refs #6506 fix e2e, refactor business --- modules/worker/front/calendar/index.html | 2 +- modules/worker/front/time-control/index.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/worker/front/calendar/index.html b/modules/worker/front/calendar/index.html index 75e892575..0e5433dc5 100644 --- a/modules/worker/front/calendar/index.html +++ b/modules/worker/front/calendar/index.html @@ -71,7 +71,7 @@ ng-model="$ctrl.businessId" search-function="{businessFk: $search}" show-field="businessFk" - value-field="businessFk" + value-field="businessId" order="businessFk DESC" limit="5"> diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index f8a94be52..4d5f55d27 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -402,7 +402,7 @@ class Controller extends Section { }); } - state(state, reason) { + changeState(state, reason) { this.state = state; this.reason = reason; this.repaint(); From 4071c06b5f7a2817b717d673d94e80bf4553df6e Mon Sep 17 00:00:00 2001 From: jgallego Date: Fri, 24 Nov 2023 08:15:39 +0100 Subject: [PATCH 044/207] feat: refs #6275 getTickets con los campos de silex --- modules/route/back/methods/route/getTickets.js | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/modules/route/back/methods/route/getTickets.js b/modules/route/back/methods/route/getTickets.js index 8e1356a42..89c68131a 100644 --- a/modules/route/back/methods/route/getTickets.js +++ b/modules/route/back/methods/route/getTickets.js @@ -3,7 +3,7 @@ const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; module.exports = Self => { Self.remoteMethod('getTickets', { - description: 'Return the tickets information displayed on the route module', + description: 'Find all instances of the model matched by filter from the data source.', accessType: 'READ', accepts: [ { @@ -55,7 +55,12 @@ module.exports = Self => { c.phone ClientPhone, c.mobile ClientMobile, a.phone AddressPhone, - a.mobile AddressMobile + a.mobile AddressMobile, + a.longitude, + a.latitude, + wm.mediaValue SalePersonPhone, + t.cmrFk, + t.isSigned Signed FROM vn.route r JOIN ticket t ON t.routeFk = r.id JOIN client c ON t.clientFk = c.id @@ -70,7 +75,8 @@ module.exports = Self => { LEFT JOIN address a ON a.id = t.addressFk LEFT JOIN agencyMode am ON am.id = t.agencyModeFk LEFT JOIN account.user u ON u.id = r.workerFk - LEFT JOIN vehicle v ON v.id = r.vehicleFk` + LEFT JOIN vehicle v ON v.id = r.vehicleFk + LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk` ); if (!filter.where) filter.where = {}; From 5d18c211a0c9159a39e4f4d02c18d899f4d1b689 Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 24 Nov 2023 08:40:06 +0100 Subject: [PATCH 045/207] refs #6507 state --- modules/worker/front/time-control/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index 4d5f55d27..f8a94be52 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -402,7 +402,7 @@ class Controller extends Section { }); } - changeState(state, reason) { + state(state, reason) { this.state = state; this.reason = reason; this.repaint(); From 8ac3887d8025840b3b90c4cbaae3af4e3d2171c4 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 24 Nov 2023 10:53:38 +0100 Subject: [PATCH 046/207] refs #5811 rename methods --- .../{deleteShipment.ejs => deleteExpedition.ejs} | 0 .../{deleteShipment.js => deleteExpedition.js} | 8 ++++---- ...eteShipmentRenderer.js => deleteExpeditionRenderer.js} | 8 ++++---- back/models/viaexpress-config.js | 4 ++-- .../ticket/back/methods/expedition/deleteExpeditions.js | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) rename back/methods/viaexpress-config/{deleteShipment.ejs => deleteExpedition.ejs} (100%) rename back/methods/viaexpress-config/{deleteShipment.js => deleteExpedition.js} (88%) rename back/methods/viaexpress-config/{deleteShipmentRenderer.js => deleteExpeditionRenderer.js} (79%) diff --git a/back/methods/viaexpress-config/deleteShipment.ejs b/back/methods/viaexpress-config/deleteExpedition.ejs similarity index 100% rename from back/methods/viaexpress-config/deleteShipment.ejs rename to back/methods/viaexpress-config/deleteExpedition.ejs diff --git a/back/methods/viaexpress-config/deleteShipment.js b/back/methods/viaexpress-config/deleteExpedition.js similarity index 88% rename from back/methods/viaexpress-config/deleteShipment.js rename to back/methods/viaexpress-config/deleteExpedition.js index babd3eeee..189745554 100644 --- a/back/methods/viaexpress-config/deleteShipment.js +++ b/back/methods/viaexpress-config/deleteExpedition.js @@ -2,7 +2,7 @@ const axios = require('axios'); const {DOMParser} = require('xmldom'); module.exports = Self => { - Self.remoteMethod('deleteShipment', { + Self.remoteMethod('deleteExpedition', { description: 'Delete a shipment by providing the expedition ID, interacting with Viaexpress API', accessType: 'WRITE', accepts: [{ @@ -15,19 +15,19 @@ module.exports = Self => { root: true }, http: { - path: `/deleteShipment`, + path: `/deleteExpedition`, verb: 'POST' } }); - Self.deleteShipment = async expeditionFk => { + Self.deleteExpedition = async expeditionFk => { const models = Self.app.models; const viaexpressConfig = await models.ViaexpressConfig.findOne({ fields: ['url'] }); - const renderedXml = await models.ViaexpressConfig.deleteShipmentRenderer(expeditionFk); + const renderedXml = await models.ViaexpressConfig.deleteExpeditionRenderer(expeditionFk); const response = await axios.post(`${viaexpressConfig.url}ServicioVxClientes.asmx`, renderedXml, { headers: { 'Content-Type': 'application/soap+xml; charset=utf-8' diff --git a/back/methods/viaexpress-config/deleteShipmentRenderer.js b/back/methods/viaexpress-config/deleteExpeditionRenderer.js similarity index 79% rename from back/methods/viaexpress-config/deleteShipmentRenderer.js rename to back/methods/viaexpress-config/deleteExpeditionRenderer.js index d9106a9ec..645eaddd1 100644 --- a/back/methods/viaexpress-config/deleteShipmentRenderer.js +++ b/back/methods/viaexpress-config/deleteExpeditionRenderer.js @@ -2,7 +2,7 @@ const fs = require('fs'); const ejs = require('ejs'); module.exports = Self => { - Self.remoteMethod('deleteShipmentRenderer', { + Self.remoteMethod('deleteExpeditionRenderer', { description: 'Renders the data from an XML', accessType: 'READ', accepts: [{ @@ -15,12 +15,12 @@ module.exports = Self => { root: true }, http: { - path: `/deleteShipmentRenderer`, + path: `/deleteExpeditionRenderer`, verb: 'GET' } }); - Self.deleteShipmentRenderer = async expeditionFk => { + Self.deleteExpeditionRenderer = async expeditionFk => { const models = Self.app.models; const viaexpressConfig = await models.ViaexpressConfig.findOne({ @@ -37,7 +37,7 @@ module.exports = Self => { externalId: expedition.externalId }; - const template = fs.readFileSync(__dirname + '/deleteShipment.ejs', 'utf-8'); + const template = fs.readFileSync(__dirname + '/deleteExpedition.ejs', 'utf-8'); const renderedXml = ejs.render(template, data); return renderedXml; }; diff --git a/back/models/viaexpress-config.js b/back/models/viaexpress-config.js index 429c0a0d8..d00c99e82 100644 --- a/back/models/viaexpress-config.js +++ b/back/models/viaexpress-config.js @@ -1,6 +1,6 @@ module.exports = Self => { require('../methods/viaexpress-config/internationalExpedition')(Self); require('../methods/viaexpress-config/renderer')(Self); - require('../methods/viaexpress-config/deleteShipment')(Self); - require('../methods/viaexpress-config/deleteShipmentRenderer')(Self); + require('../methods/viaexpress-config/deleteExpedition')(Self); + require('../methods/viaexpress-config/deleteExpeditionRenderer')(Self); }; diff --git a/modules/ticket/back/methods/expedition/deleteExpeditions.js b/modules/ticket/back/methods/expedition/deleteExpeditions.js index 3c98c8017..55ca474d7 100644 --- a/modules/ticket/back/methods/expedition/deleteExpeditions.js +++ b/modules/ticket/back/methods/expedition/deleteExpeditions.js @@ -46,7 +46,7 @@ module.exports = Self => { const {code} = expedition.agencyMode(); if (code && code.toLowerCase().substring(0, 10) == 'viaexpress') { - const isDeleted = await models.ViaexpressConfig.deleteShipment(expeditionId); + const isDeleted = await models.ViaexpressConfig.deleteExpedition(expeditionId); if (isDeleted === 'true') { const deletedExpedition = await models.Expedition.destroyById(expeditionId); From 2be1639e9fb841da26c819379dcee66828d55e99 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 24 Nov 2023 12:42:25 +0100 Subject: [PATCH 047/207] refactor: refs #3222 Expence to expense --- db/.archive/225201/00-invoiceOut_new.sql | 14 +- db/.archive/231001/02-invoiceOut_new.sql | 14 +- db/.archive/232001/00-invoiceOut_new.sql | 14 +- db/dump/fixtures.sql | 10 +- db/dump/structure.sql | 158 +++++++++--------- .../invoiceIn/back/locale/invoiceIn/en.yml | 2 +- .../invoiceIn/back/locale/invoiceIn/es.yml | 2 +- .../invoiceIn/back/locale/invoiceInTax/en.yml | 2 +- .../invoiceIn/back/locale/invoiceInTax/es.yml | 2 +- .../back/methods/invoice-in/filter.js | 2 +- .../invoiceIn/back/models/invoice-in-tax.json | 2 +- modules/invoiceIn/back/models/invoice-in.json | 2 +- modules/item/back/models/expense.json | 2 +- modules/item/back/models/item.json | 2 +- modules/item/front/basic-data/index.html | 2 +- .../methods/agency-term/createInvoiceIn.js | 4 +- .../route/back/models/agency-term-config.json | 2 +- .../back/models/ticket-service-type.json | 2 +- 18 files changed, 119 insertions(+), 119 deletions(-) diff --git a/db/.archive/225201/00-invoiceOut_new.sql b/db/.archive/225201/00-invoiceOut_new.sql index 8e23fb43b..c0f6bc697 100644 --- a/db/.archive/225201/00-invoiceOut_new.sql +++ b/db/.archive/225201/00-invoiceOut_new.sql @@ -118,13 +118,13 @@ BEGIN SELECT 'UPDATE', account.myUser_getId(), ti.id, CONCAT('Crea factura ', vNewRef) FROM tmp.ticketToInvoice ti; - CALL invoiceExpenceMake(vNewInvoiceId); + CALL invoiceExpenseMake(vNewInvoiceId); CALL invoiceTaxMake(vNewInvoiceId,vTaxArea); UPDATE invoiceOut io JOIN ( SELECT SUM(amount) AS total - FROM invoiceOutExpence + FROM invoiceOutExpense WHERE invoiceOutFk = vNewInvoiceId ) base JOIN ( @@ -166,18 +166,18 @@ BEGIN SET @vTaxableBaseServices := 0.00; SET @vTaxCodeGeneral := NULL; - INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) - SELECT vNewInvoiceInId, @vTaxableBaseServices, sub.expenceFk, sub.taxTypeSageFk , sub.transactionTypeSageFk + INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk) + SELECT vNewInvoiceInId, @vTaxableBaseServices, sub.expenseFk, sub.taxTypeSageFk , sub.transactionTypeSageFk FROM ( - SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase, i.expenceFk, i.taxTypeSageFk , i.transactionTypeSageFk, @vTaxCodeGeneral := i.taxClassCodeFk + SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase, i.expenseFk, i.taxTypeSageFk , i.transactionTypeSageFk, @vTaxCodeGeneral := i.taxClassCodeFk FROM tmp.ticketServiceTax tst JOIN vn.invoiceOutTaxConfig i ON i.taxClassCodeFk = tst.code WHERE i.isService HAVING taxableBase ) sub; - INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) - SELECT vNewInvoiceInId, SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral, @vTaxableBaseServices, 0) taxableBase, i.expenceFk, i.taxTypeSageFk , i.transactionTypeSageFk + INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk) + SELECT vNewInvoiceInId, SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral, @vTaxableBaseServices, 0) taxableBase, i.expenseFk, i.taxTypeSageFk , i.transactionTypeSageFk FROM tmp.ticketTax tt JOIN vn.invoiceOutTaxConfig i ON i.taxClassCodeFk = tt.code WHERE !i.isService diff --git a/db/.archive/231001/02-invoiceOut_new.sql b/db/.archive/231001/02-invoiceOut_new.sql index d570dfb72..e87c44cd0 100644 --- a/db/.archive/231001/02-invoiceOut_new.sql +++ b/db/.archive/231001/02-invoiceOut_new.sql @@ -139,13 +139,13 @@ BEGIN SELECT 'UPDATE', account.myUser_getId(), ti.id, CONCAT('Crea factura ', vNewRef) FROM tmp.ticketToInvoice ti; - CALL invoiceExpenceMake(vNewInvoiceId); + CALL invoiceExpenseMake(vNewInvoiceId); CALL invoiceTaxMake(vNewInvoiceId,vTaxArea); UPDATE invoiceOut io JOIN ( SELECT SUM(amount) total - FROM invoiceOutExpence + FROM invoiceOutExpense WHERE invoiceOutFk = vNewInvoiceId ) base JOIN ( @@ -182,15 +182,15 @@ BEGIN SET @vTaxableBaseServices := 0.00; SET @vTaxCodeGeneral := NULL; - INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) + INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk) SELECT vNewInvoiceInFk, @vTaxableBaseServices, - sub.expenceFk, + sub.expenseFk, sub.taxTypeSageFk, sub.transactionTypeSageFk FROM ( SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase, - i.expenceFk, + i.expenseFk, i.taxTypeSageFk, i.transactionTypeSageFk, @vTaxCodeGeneral := i.taxClassCodeFk @@ -200,11 +200,11 @@ BEGIN HAVING taxableBase ) sub; - INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) + INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk) SELECT vNewInvoiceInFk, SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral, @vTaxableBaseServices, 0) taxableBase, - i.expenceFk, + i.expenseFk, i.taxTypeSageFk , i.transactionTypeSageFk FROM tmp.ticketTax tt diff --git a/db/.archive/232001/00-invoiceOut_new.sql b/db/.archive/232001/00-invoiceOut_new.sql index b497dffda..175c31b74 100644 --- a/db/.archive/232001/00-invoiceOut_new.sql +++ b/db/.archive/232001/00-invoiceOut_new.sql @@ -135,13 +135,13 @@ BEGIN INSERT INTO ticketTracking(stateFk,ticketFk,workerFk) SELECT * FROM tmp.updateInter; - CALL invoiceExpenceMake(vNewInvoiceId); + CALL invoiceExpenseMake(vNewInvoiceId); CALL invoiceTaxMake(vNewInvoiceId,vTaxArea); UPDATE invoiceOut io JOIN ( SELECT SUM(amount) total - FROM invoiceOutExpence + FROM invoiceOutExpense WHERE invoiceOutFk = vNewInvoiceId ) base JOIN ( @@ -178,15 +178,15 @@ BEGIN SET @vTaxableBaseServices := 0.00; SET @vTaxCodeGeneral := NULL; - INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) + INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk) SELECT vNewInvoiceInFk, @vTaxableBaseServices, - sub.expenceFk, + sub.expenseFk, sub.taxTypeSageFk, sub.transactionTypeSageFk FROM ( SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase, - i.expenceFk, + i.expenseFk, i.taxTypeSageFk, i.transactionTypeSageFk, @vTaxCodeGeneral := i.taxClassCodeFk @@ -196,11 +196,11 @@ BEGIN HAVING taxableBase ) sub; - INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) + INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk) SELECT vNewInvoiceInFk, SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral, @vTaxableBaseServices, 0) taxableBase, - i.expenceFk, + i.expenseFk, i.taxTypeSageFk , i.transactionTypeSageFk FROM tmp.ticketTax tt diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 788487ed0..93b7b796f 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -630,7 +630,7 @@ INSERT INTO `vn`.`invoiceOutTax` (`invoiceOutFk`, `taxableBase`, `vat`, `pgcFk`) (4, 8.07, 0.81, 4770000010), (5, 8.07, 0.81, 4770000010); -INSERT INTO `vn`.`expence`(`id`, `name`, `isWithheld`) +INSERT INTO `vn`.`expense`(`id`, `name`, `isWithheld`) VALUES (2000000000, 'Inmovilizado pendiente', 0), (2000000001, 'Compra de bienes de inmovilizado', 0), @@ -642,7 +642,7 @@ INSERT INTO `vn`.`expence`(`id`, `name`, `isWithheld`) (7050000000, 'Prestacion de servicios', 1); -INSERT INTO `vn`.`invoiceOutExpence`(`id`, `invoiceOutFk`, `amount`, `expenceFk`, `created`) +INSERT INTO `vn`.`invoiceOutExpense`(`id`, `invoiceOutFk`, `amount`, `expenseFk`, `created`) VALUES (1, 1, 813.06, 2000000000, util.VN_CURDATE()), (2, 1, 33.80, 4751000000, util.VN_CURDATE()), @@ -922,7 +922,7 @@ INSERT INTO `vn`.`itemFamily`(`code`, `description`) ('SER', 'Services'), ('VT', 'Sales'); -INSERT INTO `vn`.`item`(`id`, `typeFk`, `stems`, `originFk`, `description`, `producerFk`, `intrastatFk`, `expenceFk`, +INSERT INTO `vn`.`item`(`id`, `typeFk`, `stems`, `originFk`, `description`, `producerFk`, `intrastatFk`, `expenseFk`, `comment`, `relevancy`, `image`, `subName`, `minPrice`, `stars`, `family`, `isFloramondo`, `genericFk`, `itemPackingTypeFk`, `hasMinPrice`, `packingShelve`, `weightByPiece`) VALUES (1, 2, 1, 1, NULL, 1, 06021010, 2000000000, NULL, 0, '1', NULL, 0, 1, 'EMB', 0, NULL, 'V', 0, 15,3), @@ -1939,7 +1939,7 @@ INSERT INTO `vn`.`ticketRequest`(`id`, `description`, `requesterFk`, `attenderFk (4, 'Melee weapon combat first 15cm', 18, 35, 15, NULL, 1.30, NULL, NULL, 11, util.VN_CURDATE()), (5, 'Melee weapon combat first 15cm', 18, 35, 15, 4, 1.30, 0, NULL, 18, util.VN_CURDATE()); -INSERT INTO `vn`.`ticketServiceType`(`id`, `name`, `expenceFk`) +INSERT INTO `vn`.`ticketServiceType`(`id`, `name`, `expenseFk`) VALUES (1, 'Porte Agencia', 7001000000), (2, 'Portes Retorno', 7001000000), @@ -2561,7 +2561,7 @@ INSERT INTO `vn`.`duaInvoiceIn`(`id`, `duaFk`, `invoiceInFk`) (9, 9, 9), (10, 10, 10); -INSERT INTO `vn`.`invoiceInTax` (`invoiceInFk`, `taxableBase`, `expenceFk`, `foreignValue`, `taxTypeSageFk`, `transactionTypeSageFk`) +INSERT INTO `vn`.`invoiceInTax` (`invoiceInFk`, `taxableBase`, `expenseFk`, `foreignValue`, `taxTypeSageFk`, `transactionTypeSageFk`) VALUES (1, 99.99, '2000000000', NULL, NULL, NULL), (2, 999.99, '2000000000', NULL, NULL, NULL), diff --git a/db/dump/structure.sql b/db/dump/structure.sql index d8a717aa3..1db4252f4 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -9692,7 +9692,7 @@ proc: BEGIN `name`, longName, subName, - expenceFk, + expenseFk, typeFk, intrastatFk, originFk, @@ -10080,7 +10080,7 @@ BEGIN `name`, longName, subName, - expenceFk, + expenseFk, typeFk, intrastatFk, originFk, @@ -17338,7 +17338,7 @@ BEGIN JOIN vn.XDiario x ON x.id = mci.id JOIN vn.supplier s ON s.id = supplierFk JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id - JOIN vn.expence e ON e.id = iit.expenceFk + JOIN vn.expense e ON e.id = iit.expenseFk JOIN TiposRetencion t ON t.CodigoRetencion = ii.withholdingSageFk LEFT JOIN tmp.invoiceDua id ON id.id = mci.id JOIN (SELECT SUM(x2.BASEEURO) taxableBase, SUM(x2.EURODEBE) taxBase @@ -17441,7 +17441,7 @@ BEGIN i.serial COLLATE utf8mb3_unicode_ci serial, i.supplierFk, i.issued, - IF(expenceFkDeductible, FALSE, i.isVatDeductible) isVatDeductible, + IF(expenseFkDeductible, FALSE, i.isVatDeductible) isVatDeductible, IF(c.code = 'EUR', '',c.`code`) currencyFk FROM vn.invoiceIn i JOIN vn.currency c ON c.id = i.currencyFk @@ -17949,7 +17949,7 @@ BEGIN e.id accountFk, UCASE(e.name), '' - FROM vn.expence e + FROM vn.expense e UNION SELECT company_getCode(vCompanyFk), b.account, @@ -22010,7 +22010,7 @@ DROP TABLE IF EXISTS `agencyTermConfig`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `agencyTermConfig` ( - `expenceFk` varchar(10) DEFAULT NULL, + `expenseFk` varchar(10) DEFAULT NULL, `vatAccountSupported` varchar(15) DEFAULT NULL, `vatPercentage` decimal(28,10) DEFAULT NULL, `transaction` varchar(50) DEFAULT NULL @@ -29097,19 +29097,19 @@ SET character_set_client = utf8; SET character_set_client = @saved_cs_client; -- --- Table structure for table `expence` +-- Table structure for table `expense` -- -DROP TABLE IF EXISTS `expence`; +DROP TABLE IF EXISTS `expense`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `expence` ( +CREATE TABLE `expense` ( `id` varchar(10) NOT NULL, `name` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL, `isWithheld` tinyint(4) NOT NULL DEFAULT 0, `code` varchar(25) DEFAULT NULL, PRIMARY KEY (`id`), - UNIQUE KEY `expence_UN` (`code`) + UNIQUE KEY `expense_UN` (`code`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -29862,7 +29862,7 @@ CREATE TABLE `invoiceIn` ( `bookEntried` date DEFAULT NULL COMMENT 'Fecha Asiento', `isVatDeductible` tinyint(1) NOT NULL DEFAULT 1, `withholdingSageFk` smallint(6) DEFAULT NULL COMMENT 'Tipos de retención SAGE', - `expenceFkDeductible` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, + `expenseFkDeductible` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, `editorFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `proveedor_id` (`supplierFk`), @@ -29877,12 +29877,12 @@ CREATE TABLE `invoiceIn` ( KEY `recibida_ibfk_6` (`cplusRectificationTypeFk`), KEY `recibida_ibfk_7` (`siiTrascendencyInvoiceInFk`), KEY `invoiceIn_withholdingFk_idx` (`withholdingSageFk`), - KEY `invoiceIn_expenceFkDeductible_idx` (`expenceFkDeductible`), + KEY `invoiceIn_expenseFkDeductible_idx` (`expenseFkDeductible`), KEY `invoiceIn_fk_editor` (`editorFk`), KEY `invoiceIn_FK` (`currencyFk`), CONSTRAINT `invoiceInCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceIn_FK` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON UPDATE CASCADE, - CONSTRAINT `invoiceIn_expenceFkDeductible` FOREIGN KEY (`expenceFkDeductible`) REFERENCES `expence` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceIn_expenseFkDeductible` FOREIGN KEY (`expenseFkDeductible`) REFERENCES `expense` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceIn_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `invoiceIn_ibfk_3` FOREIGN KEY (`cplusSubjectOpFk`) REFERENCES `cplusSubjectOp` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceIn_ibfk_4` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `cplusTaxBreak` (`id`) ON UPDATE CASCADE, @@ -30283,7 +30283,7 @@ CREATE TABLE `invoiceInSage` ( `taxTypeSageFk` smallint(6) NOT NULL, `transactionTypeSageFk` tinyint(4) NOT NULL, `isService` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Para diferenciar producto de servicio', - `expenceFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, + `expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, `withholdingSageFk` smallint(6) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `invoiceInSafe_unique` (`taxClassFk`,`invoiceInSerialFk`,`isService`,`withholdingSageFk`), @@ -30292,8 +30292,8 @@ CREATE TABLE `invoiceInSage` ( KEY `invoiceInSage_invoiceInSerialFk` (`invoiceInSerialFk`), KEY `invoiceInSage_taxTypeSageFk` (`taxTypeSageFk`), KEY `invoiceInSage_transactionTypeSageFk` (`transactionTypeSageFk`), - KEY `invoiceInSage_idx` (`expenceFk`), - CONSTRAINT `invoiceInSage_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE, + KEY `invoiceInSage_idx` (`expenseFk`), + CONSTRAINT `invoiceInSage_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceInSage_invoiceInSerialFk` FOREIGN KEY (`invoiceInSerialFk`) REFERENCES `invoiceInSerial` (`code`) ON UPDATE CASCADE, CONSTRAINT `invoiceInSage_taxClassFk` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`code`) ON UPDATE CASCADE, CONSTRAINT `invoiceInSage_taxTypeSageFk` FOREIGN KEY (`taxTypeSageFk`) REFERENCES `sage`.`TiposIva` (`CodigoIva`) ON UPDATE CASCADE, @@ -30334,7 +30334,7 @@ CREATE TABLE `invoiceInTax` ( `invoiceInFk` mediumint(8) unsigned NOT NULL, `taxCodeFk` int(10) DEFAULT NULL, `taxableBase` decimal(10,2) NOT NULL, - `expenceFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, + `expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, `foreignValue` decimal(10,2) DEFAULT NULL, `taxTypeSageFk` smallint(6) DEFAULT NULL COMMENT 'Tipo de IVA SAGE', `transactionTypeSageFk` tinyint(4) DEFAULT NULL COMMENT 'Tipo de transacción SAGE', @@ -30345,9 +30345,9 @@ CREATE TABLE `invoiceInTax` ( KEY `recibida_iva_ibfk_2` (`taxCodeFk`), KEY `recibida_iva_taxTypeSageFk` (`taxTypeSageFk`), KEY `invoiceInTax_transactionTypeSageFk_idx` (`transactionTypeSageFk`), - KEY `invoiceInTax_idx` (`expenceFk`), + KEY `invoiceInTax_idx` (`expenseFk`), KEY `invoiceInTax_fk_editor` (`editorFk`), - CONSTRAINT `invoiceInTax_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceInTax_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceInTax_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `invoiceInTax_ibfk_5` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `invoiceInTax_transactionTypeSageFk` FOREIGN KEY (`transactionTypeSageFk`) REFERENCES `sage`.`TiposTransacciones` (`CodigoTransaccion`) ON UPDATE CASCADE, @@ -30615,23 +30615,23 @@ CREATE TABLE `invoiceOutConfig` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `invoiceOutExpence` +-- Table structure for table `invoiceOutExpense` -- -DROP TABLE IF EXISTS `invoiceOutExpence`; +DROP TABLE IF EXISTS `invoiceOutExpense`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `invoiceOutExpence` ( +CREATE TABLE `invoiceOutExpense` ( `id` int(11) NOT NULL AUTO_INCREMENT, `invoiceOutFk` int(10) unsigned NOT NULL, `amount` decimal(10,2) NOT NULL DEFAULT 0.00, - `expenceFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, + `expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, `created` timestamp NULL DEFAULT current_timestamp(), PRIMARY KEY (`id`), - KEY `invoiceOutExpence_FK_1_idx` (`invoiceOutFk`), - KEY `invoiceOutExpence_expenceFk_idx` (`expenceFk`), - CONSTRAINT `invoiceOutExpence_FK_1` FOREIGN KEY (`invoiceOutFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `invoiceOutExpence_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE + KEY `invoiceOutExpense_FK_1_idx` (`invoiceOutFk`), + KEY `invoiceOutExpense_expenseFk_idx` (`expenseFk`), + CONSTRAINT `invoiceOutExpense_FK_1` FOREIGN KEY (`invoiceOutFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `invoiceOutExpense_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Desglosa la base imponible de una factura en funcion del tipo de gasto/venta'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -30694,7 +30694,7 @@ CREATE TABLE `invoiceOutTaxConfig` ( `taxTypeSageFk` smallint(6) DEFAULT NULL, `transactionTypeSageFk` tinyint(4) DEFAULT NULL, `isService` tinyint(1) DEFAULT 0, - `expenceFk` varchar(10) DEFAULT NULL, + `expenseFk` varchar(10) DEFAULT NULL, PRIMARY KEY (`id`), KEY `invoiceOutTaxConfig_FK` (`taxClassCodeFk`), KEY `invoiceOutTaxConfig_FK_1` (`taxTypeSageFk`), @@ -30737,7 +30737,7 @@ CREATE TABLE `item` ( `description` varchar(1000) DEFAULT NULL, `density` int(11) NOT NULL DEFAULT 167 COMMENT 'Almacena la densidad en kg/m3 para el calculo de los portes, si no se especifica se pone por defecto la del tipo en un trigger', `relevancy` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'La web ordena de forma descendiente por este campo para mostrar los artículos', - `expenceFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '7001000000', + `expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '7001000000', `isActive` tinyint(1) NOT NULL DEFAULT 1, `longName` varchar(50) DEFAULT NULL, `subName` varchar(50) DEFAULT NULL, @@ -30792,11 +30792,11 @@ CREATE TABLE `item` ( KEY `item_size_IDX` (`size`) USING BTREE, KEY `item_size_IDX2` (`longName`) USING BTREE, KEY `item_lastUsed_IDX` (`lastUsed`) USING BTREE, - KEY `item_expenceFk_idx` (`expenceFk`), + KEY `item_expenseFk_idx` (`expenseFk`), KEY `item_fk_editor` (`editorFk`), CONSTRAINT `item_FK` FOREIGN KEY (`genericFk`) REFERENCES `item` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `item_FK_1` FOREIGN KEY (`typeFk`) REFERENCES `itemType` (`id`), - CONSTRAINT `item_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE, + CONSTRAINT `item_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE, CONSTRAINT `item_family` FOREIGN KEY (`family`) REFERENCES `itemFamily` (`code`) ON UPDATE CASCADE, CONSTRAINT `item_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `item_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `origin` (`id`) ON UPDATE CASCADE, @@ -40606,10 +40606,10 @@ DROP TABLE IF EXISTS `ticketServiceType`; CREATE TABLE `ticketServiceType` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, - `expenceFk` varchar(10) NOT NULL DEFAULT '7050000000', + `expenseFk` varchar(10) NOT NULL DEFAULT '7050000000', PRIMARY KEY (`id`), - KEY `ticketServiceType_expenceFk_idx` (`expenceFk`), - CONSTRAINT `ticketServiceType_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE + KEY `ticketServiceType_expenseFk_idx` (`expenseFk`), + CONSTRAINT `ticketServiceType_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Lista de los posibles servicios a elegir'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -46533,7 +46533,7 @@ BEGIN WHERE io.ref = vInvoiceRef UNION ALL SELECT ioe.amount - FROM invoiceOutExpence ioe + FROM invoiceOutExpense ioe JOIN invoiceOut io ON io.id = ioe.invoiceOutFk WHERE io.ref = vInvoiceRef ) t1; @@ -57741,7 +57741,7 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceExpenceMake` */; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceExpenseMake` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -57749,28 +57749,28 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceExpenceMake`(IN vInvoice INT) +CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceExpenseMake`(IN vInvoice INT) BEGIN /* Inserta las partidas de gasto correspondientes a la factura * REQUIERE tabla tmp.ticketToInvoice * @param vInvoice Numero de factura */ - DELETE FROM invoiceOutExpence + DELETE FROM invoiceOutExpense WHERE invoiceOutFk = vInvoice; - INSERT INTO invoiceOutExpence(invoiceOutFk, expenceFk, amount) + INSERT INTO invoiceOutExpense(invoiceOutFk, expenseFk, amount) SELECT vInvoice, - expenceFk, + expenseFk, SUM(ROUND(quantity * price * (100 - discount)/100,2)) amount FROM tmp.ticketToInvoice t JOIN sale s ON s.ticketFk = t.id JOIN item i ON i.id = s.itemFk - GROUP BY i.expenceFk + GROUP BY i.expenseFk HAVING amount != 0; - INSERT INTO invoiceOutExpence(invoiceOutFk, expenceFk, amount) + INSERT INTO invoiceOutExpense(invoiceOutFk, expenseFk, amount) SELECT vInvoice, - tst.expenceFk, + tst.expenseFk, SUM(ROUND(ts.quantity * ts.price ,2)) amount FROM tmp.ticketToInvoice t JOIN ticketService ts ON ts.ticketFk = t.id @@ -58125,7 +58125,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInTax_getFromEntries`(IN vId BEGIN DECLARE vRate DOUBLE DEFAULT 1; DECLARE vDated DATE; - DECLARE vExpenceFk VARCHAR(10); + DECLARE vExpenseFk VARCHAR(10); SELECT MAX(rr.dated) INTO vDated FROM referenceRate rr @@ -58139,8 +58139,8 @@ BEGIN WHERE dated = vDated; END IF; - SELECT id INTO vExpenceFk - FROM vn.expence + SELECT id INTO vExpenseFk + FROM vn.expense WHERE `name` = 'Adquisición mercancia Extracomunitaria' GROUP BY id LIMIT 1; @@ -58148,10 +58148,10 @@ BEGIN DELETE FROM invoiceInTax WHERE invoiceInFk = vId; - INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, foreignValue, taxTypeSageFk, transactionTypeSageFk) + INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, foreignValue, taxTypeSageFk, transactionTypeSageFk) SELECT ii.id, SUM(b.buyingValue * b.quantity) / IFNULL(vRate,1) taxableBase, - vExpenceFk, + vExpenseFk, IF(ii.currencyFk = 1,NULL,SUM(b.buyingValue * b.quantity )) divisa, taxTypeSageFk, transactionTypeSageFk @@ -58188,7 +58188,7 @@ BEGIN SELECT ii.bookEntried, iit.foreignValue, ii.companyFk, - ii.expenceFkDeductible, + ii.expenseFkDeductible, iit.taxableBase, iit.transactionTypeSageFk, ii.serial, @@ -58218,8 +58218,8 @@ BEGIN cit.id invoicesCount, e.code, e.isWithheld, - e.id expenceFk, - e.name expenceName + e.id expenseFk, + e.name expenseName FROM invoiceIn ii JOIN supplier s ON s.id = ii.supplierFk LEFT JOIN province p ON p.id = s.provinceFk @@ -58231,7 +58231,7 @@ BEGIN JOIN siiTypeInvoiceIn cit ON cit.id = ii.siiTypeInvoiceInFk LEFT JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id LEFT JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = iit.transactionTypeSageFk - LEFT JOIN expence e ON e.id = iit.expenceFk + LEFT JOIN expense e ON e.id = iit.expenseFk LEFT JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk LEFT JOIN sage.taxType tt ON tt.id = ti.CodigoIva WHERE ii.id = vSelf; @@ -58286,7 +58286,7 @@ BEGIN empresa_id) SELECT vBookNumber ASIEN, tii.bookEntried FECHA, - IF(tii.isWithheld, LPAD(RIGHT(tii.supplierAccount, 5), 10, tii.expenceFk),tii.expenceFk) SUBCTA, + IF(tii.isWithheld, LPAD(RIGHT(tii.supplierAccount, 5), 10, tii.expenseFk),tii.expenseFk) SUBCTA, tii.supplierAccount CONTRA, IF(tii.isWithheld AND tii.taxableBase < 0, NULL, ROUND(SUM(tii.taxableBase),2)) EURODEBE, IF(tii.isWithheld AND tii.taxableBase < 0, ROUND(SUM(-tii.taxableBase), 2), NULL) EUROHABER, @@ -58301,7 +58301,7 @@ BEGIN tii.companyFk empresa_id FROM tInvoiceIn tii WHERE tii.code IS NULL OR tii.code <> 'suplido' - GROUP BY tii.expenceFk; + GROUP BY tii.expenseFk; -- Líneas de IVA INSERT INTO XDiario( @@ -58335,11 +58335,11 @@ BEGIN empresa_id) SELECT vBookNumber ASIEN, tii.bookEntried FECHA, - IF(tii.expenceFkDeductible>0, tii.expenceFkDeductible, tii.CuentaIvaSoportado) SUBCTA, + IF(tii.expenseFkDeductible>0, tii.expenseFkDeductible, tii.CuentaIvaSoportado) SUBCTA, tii.supplierAccount CONTRA, SUM(ROUND(tii.PorcentajeIva * tii.taxableBase / 100, 2)) EURODEBE, SUM(tii.taxableBase) BASEEURO, - GROUP_CONCAT(DISTINCT tii.expenceName SEPARATOR ', ') CONCEPTO, + GROUP_CONCAT(DISTINCT tii.expenseName SEPARATOR ', ') CONCEPTO, vSelf FACTURA, tii.PorcentajeIva IVA, IF(tii.isUeeMember AND eWithheld.id IS NULL, '', '*') AUXILIAR, @@ -58365,13 +58365,13 @@ BEGIN LEFT JOIN ( SELECT e.id FROM tInvoiceIn tii - JOIN expence e ON e.id = tii.expenceFk + JOIN expense e ON e.id = tii.expenseFk WHERE e.isWithheld LIMIT 1 ) eWithheld ON TRUE WHERE tii.taxTypeSageFk IS NOT NULL AND (tii.taxCode IS NULL OR tii.taxCode NOT IN ('import10', 'import21')) - GROUP BY tii.PorcentajeIva, tii.expenceFk; + GROUP BY tii.PorcentajeIva, tii.expenseFk; -- Línea iva inversor sujeto pasivo INSERT INTO XDiario( @@ -58408,7 +58408,7 @@ BEGIN tii.supplierAccount CONTRA, SUM(ROUND(tii.PorcentajeIva * tii.taxableBase / 100,2)) EUROHABER, ROUND(SUM(tii.taxableBase),2) BASEEURO, - GROUP_CONCAT(DISTINCT tii.expenceName SEPARATOR ', ') CONCEPTO, + GROUP_CONCAT(DISTINCT tii.expenseName SEPARATOR ', ') CONCEPTO, vSelf FACTURA, tii.PorcentajeIva IVA, '*' AUXILIAR, @@ -58436,7 +58436,7 @@ BEGIN AND NOT(tii.isVies AND c.nontaxableTransactionTypeFk = tii.transactionTypeSageFk AND tii.taxCode = 'nonTaxable') - GROUP BY tii.PorcentajeIva, tii.expenceFk; + GROUP BY tii.PorcentajeIva, tii.expenseFk; -- Actualización del registro original UPDATE invoiceIn ii @@ -58509,14 +58509,14 @@ BEGIN FROM ticket WHERE refFk = vInvoiceRef; - CALL invoiceExpenceMake(vInvoiceFk); + CALL invoiceExpenseMake(vInvoiceFk); CALL invoiceTaxMake(vInvoiceFk,vTaxArea); UPDATE invoiceOut io JOIN ( SELECT SUM(amount) AS total - FROM invoiceOutExpence + FROM invoiceOutExpense WHERE invoiceOutFk = vInvoiceFk ) base JOIN ( @@ -58552,7 +58552,7 @@ BEGIN * param vInvoice factura_id */ DECLARE vBookNumber INT; - DECLARE vExpenceConcept VARCHAR(50); + DECLARE vExpenseConcept VARCHAR(50); DECLARE vSpainCountryFk INT; DECLARE vOldBookNumber INT; @@ -58644,7 +58644,7 @@ BEGIN SELECT vBookNumber AS ASIEN, rs.FECHA, - ioe.expenceFk AS SUBCTA, + ioe.expenseFk AS SUBCTA, rs.clientBookingAccount AS CONTRA, ioe.amount AS EUROHABER, rs.Concept AS CONCEPTO, @@ -58652,13 +58652,13 @@ BEGIN rs.FECHA_OP, rs.companyFk AS empresa_id FROM rs - JOIN invoiceOutExpence ioe + JOIN invoiceOutExpense ioe WHERE ioe.invoiceOutFk = vInvoice; SELECT GROUP_CONCAT(`name` SEPARATOR ',') - INTO vExpenceConcept - FROM expence e - JOIN invoiceOutExpence ioe ON ioe.expenceFk = e.id + INTO vExpenseConcept + FROM expense e + JOIN invoiceOutExpense ioe ON ioe.expenseFk = e.id WHERE ioe.invoiceOutFk = vInvoice; -- Lineas de IVA @@ -58701,7 +58701,7 @@ BEGIN rs.clientBookingAccount AS CONTRA, iot.vat AS EUROHABER, iot.taxableBase AS BASEEURO, - CONCAT(vExpenceConcept,' : ',rs.Concept) AS CONCEPTO, + CONCAT(vExpenseConcept,' : ',rs.Concept) AS CONCEPTO, rs.invoiceNum AS FACTURA, IF(pe2.equFk,0,pgc.rate) AS IVA, IF(pe2.equFk,0,pgce.rate) AS RECEQUIV, @@ -58844,7 +58844,7 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutTaxAndExpence` */; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutTaxAndExpense` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -58852,7 +58852,7 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOutTaxAndExpence`() +CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOutTaxAndExpense`() BEGIN /* Para tickets ya facturados, vuelve a repetir el proceso de facturación. @@ -58906,7 +58906,7 @@ BEGIN FROM ticket WHERE refFk = vInvoiceRef; - CALL invoiceExpenceMake(vInvoice); + CALL invoiceExpenseMake(vInvoice); CALL invoiceTaxMake(vInvoice,vCountry,vTaxArea); FETCH rs INTO vInvoice ,vInvoiceRef; @@ -59140,13 +59140,13 @@ BEGIN INSERT INTO ticketTracking(stateFk,ticketFk,workerFk) SELECT * FROM tmp.updateInter; - CALL invoiceExpenceMake(vNewInvoiceId); + CALL invoiceExpenseMake(vNewInvoiceId); CALL invoiceTaxMake(vNewInvoiceId,vTaxArea); UPDATE invoiceOut io JOIN ( SELECT SUM(amount) total - FROM invoiceOutExpence + FROM invoiceOutExpense WHERE invoiceOutFk = vNewInvoiceId ) base JOIN ( @@ -59183,15 +59183,15 @@ BEGIN SET @vTaxableBaseServices := 0.00; SET @vTaxCodeGeneral := NULL; - INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) + INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk) SELECT vNewInvoiceInFk, @vTaxableBaseServices, - sub.expenceFk, + sub.expenseFk, sub.taxTypeSageFk, sub.transactionTypeSageFk FROM ( SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase, - i.expenceFk, + i.expenseFk, i.taxTypeSageFk, i.transactionTypeSageFk, @vTaxCodeGeneral := i.taxClassCodeFk @@ -59201,11 +59201,11 @@ BEGIN HAVING taxableBase ) sub; - INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) + INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk) SELECT vNewInvoiceInFk, SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral, @vTaxableBaseServices, 0) taxableBase, - i.expenceFk, + i.expenseFk, i.taxTypeSageFk , i.transactionTypeSageFk FROM tmp.ticketTax tt diff --git a/modules/invoiceIn/back/locale/invoiceIn/en.yml b/modules/invoiceIn/back/locale/invoiceIn/en.yml index ec9a824b6..9e94eba0d 100644 --- a/modules/invoiceIn/back/locale/invoiceIn/en.yml +++ b/modules/invoiceIn/back/locale/invoiceIn/en.yml @@ -16,5 +16,5 @@ columns: bookEntried: book entried isVatDeductible: is VAT deductible withholdingSageFk: withholding - expenceFkDeductible: expence deductible + expenseFkDeductible: expense deductible editorFk: editor \ No newline at end of file diff --git a/modules/invoiceIn/back/locale/invoiceIn/es.yml b/modules/invoiceIn/back/locale/invoiceIn/es.yml index 64e96b379..bd64c4327 100644 --- a/modules/invoiceIn/back/locale/invoiceIn/es.yml +++ b/modules/invoiceIn/back/locale/invoiceIn/es.yml @@ -16,5 +16,5 @@ columns: bookEntried: fecha asiento isVatDeductible: impuesto deducible withholdingSageFk: código de retención - expenceFkDeductible: gasto deducible + expenseFkDeductible: gasto deducible editorFk: editor \ No newline at end of file diff --git a/modules/invoiceIn/back/locale/invoiceInTax/en.yml b/modules/invoiceIn/back/locale/invoiceInTax/en.yml index c0d12c37d..6af547d3f 100644 --- a/modules/invoiceIn/back/locale/invoiceInTax/en.yml +++ b/modules/invoiceIn/back/locale/invoiceInTax/en.yml @@ -4,7 +4,7 @@ columns: invoiceInFk: invoice in taxCodeFk: tax taxableBase: taxable base - expenceFk: expence + expenseFk: expense foreignValue: foreign amount taxTypeSageFk: tax type transactionTypeSageFk: transaction type diff --git a/modules/invoiceIn/back/locale/invoiceInTax/es.yml b/modules/invoiceIn/back/locale/invoiceInTax/es.yml index 7cb847ed8..92f3855e4 100644 --- a/modules/invoiceIn/back/locale/invoiceInTax/es.yml +++ b/modules/invoiceIn/back/locale/invoiceInTax/es.yml @@ -4,7 +4,7 @@ columns: invoiceInFk: factura recibida taxCodeFk: código IVA taxableBase: base imponible - expenceFk: código gasto + expenseFk: código gasto foreignValue: importe divisa taxTypeSageFk: código impuesto transactionTypeSageFk: código transacción diff --git a/modules/invoiceIn/back/methods/invoice-in/filter.js b/modules/invoiceIn/back/methods/invoice-in/filter.js index f5eab9099..dd193af85 100644 --- a/modules/invoiceIn/back/methods/invoice-in/filter.js +++ b/modules/invoiceIn/back/methods/invoice-in/filter.js @@ -146,7 +146,7 @@ module.exports = Self => { ii.docFk AS dmsFk, dm.file, ii.supplierFk, - ii.expenceFkDeductible deductibleExpenseFk, + ii.expenseFkDeductible deductibleExpenseFk, s.name AS supplierName, s.account, SUM(iid.amount) AS amount, diff --git a/modules/invoiceIn/back/models/invoice-in-tax.json b/modules/invoiceIn/back/models/invoice-in-tax.json index 1f68476c3..bc57a4376 100644 --- a/modules/invoiceIn/back/models/invoice-in-tax.json +++ b/modules/invoiceIn/back/models/invoice-in-tax.json @@ -21,7 +21,7 @@ "expenseFk": { "type": "number", "mysql": { - "columnName": "expenceFk" + "columnName": "expenseFk" } }, "created": { diff --git a/modules/invoiceIn/back/models/invoice-in.json b/modules/invoiceIn/back/models/invoice-in.json index 754899866..5be55c851 100644 --- a/modules/invoiceIn/back/models/invoice-in.json +++ b/modules/invoiceIn/back/models/invoice-in.json @@ -51,7 +51,7 @@ "deductibleExpenseFk": { "type": "number", "mysql": { - "columnName": "expenceFkDeductible" + "columnName": "expenseFkDeductible" } } }, diff --git a/modules/item/back/models/expense.json b/modules/item/back/models/expense.json index 03147c08b..468063602 100644 --- a/modules/item/back/models/expense.json +++ b/modules/item/back/models/expense.json @@ -3,7 +3,7 @@ "base": "VnModel", "options": { "mysql": { - "table": "expence" + "table": "expense" } }, "properties": { diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json index 6db1f5efc..3f3547fd1 100644 --- a/modules/item/back/models/item.json +++ b/modules/item/back/models/item.json @@ -119,7 +119,7 @@ "expenseFk": { "type": "number", "mysql": { - "columnName": "expenceFk" + "columnName": "expenseFk" } }, "minPrice": { diff --git a/modules/item/front/basic-data/index.html b/modules/item/front/basic-data/index.html index 426c17800..3e47faa5f 100644 --- a/modules/item/front/basic-data/index.html +++ b/modules/item/front/basic-data/index.html @@ -105,7 +105,7 @@ url="Expenses" label="Expense" ng-model="$ctrl.item.expenseFk" - vn-name="expence" + vn-name="expense" initial-data="$ctrl.item.expense"> diff --git a/modules/route/back/methods/agency-term/createInvoiceIn.js b/modules/route/back/methods/agency-term/createInvoiceIn.js index 5a8430e49..f00ab95c6 100644 --- a/modules/route/back/methods/agency-term/createInvoiceIn.js +++ b/modules/route/back/methods/agency-term/createInvoiceIn.js @@ -54,7 +54,7 @@ module.exports = Self => { dmsFk: firstDms.id, }, myOptions); - const expence = await models.AgencyTermConfig.findOne(null, myOptions); + const expense = await models.AgencyTermConfig.findOne(null, myOptions); const [taxTypeSage] = await Self.rawSql(` SELECT IFNULL(s.taxTypeSageFk, CodigoIva) value @@ -78,7 +78,7 @@ module.exports = Self => { await models.InvoiceInTax.create({ invoiceInFk: newInvoiceIn.id, taxableBase: firstRow.totalPrice, - expenseFk: expence.expenceFk, + expenseFk: expense.expenseFk, taxTypeSageFk: taxTypeSage.value, transactionTypeSageFk: transactionTypeSage.value }, myOptions); diff --git a/modules/route/back/models/agency-term-config.json b/modules/route/back/models/agency-term-config.json index c94fc266b..81a608acf 100644 --- a/modules/route/back/models/agency-term-config.json +++ b/modules/route/back/models/agency-term-config.json @@ -7,7 +7,7 @@ } }, "properties": { - "expenceFk": { + "expenseFk": { "type": "string", "id": true }, diff --git a/modules/ticket/back/models/ticket-service-type.json b/modules/ticket/back/models/ticket-service-type.json index ec2c9232a..9340d6023 100644 --- a/modules/ticket/back/models/ticket-service-type.json +++ b/modules/ticket/back/models/ticket-service-type.json @@ -18,7 +18,7 @@ "expenseFk": { "type": "number", "mysql": { - "columnName": "expenceFk" + "columnName": "expenseFk" } } }, From f9d5cad4123a1c032c05e56e36da9927d7f52b10 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 27 Nov 2023 07:57:18 +0100 Subject: [PATCH 048/207] refs #6506 contract --- modules/worker/front/calendar/index.html | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/modules/worker/front/calendar/index.html b/modules/worker/front/calendar/index.html index d64c22408..0b6732024 100644 --- a/modules/worker/front/calendar/index.html +++ b/modules/worker/front/calendar/index.html @@ -70,17 +70,18 @@ fields="['started', 'ended']" ng-model="$ctrl.businessId" search-function="{businessFk: $search}" + show-field="businessFk" value-field="businessFk" order="businessFk DESC" limit="5"> - -
#{{businessFk}}
-
- {{started | date: 'dd/MM/yyyy'}} - {{ended ? (ended | date: 'dd/MM/yyyy') : 'Indef.'}} -
-
- - + +
#{{businessFk}}
+
+ {{started | date: 'dd/MM/yyyy'}} - {{ended ? (ended | date: 'dd/MM/yyyy') : 'Indef.'}} +
+
+ +
From 72a0932e35539bd53857a0e3cb9c02916c8e5965 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 27 Nov 2023 09:46:27 +0100 Subject: [PATCH 049/207] 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 050/207] 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 aefff68c2903d94f1470b11d76781635fcad1b8c Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 27 Nov 2023 09:51:56 +0100 Subject: [PATCH 051/207] refactor: refs #3222 Requested changes --- modules/invoiceIn/back/models/invoice-in-tax.json | 5 +---- modules/item/back/models/item.json | 8 +------- 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/modules/invoiceIn/back/models/invoice-in-tax.json b/modules/invoiceIn/back/models/invoice-in-tax.json index bc57a4376..5bfbbe2a8 100644 --- a/modules/invoiceIn/back/models/invoice-in-tax.json +++ b/modules/invoiceIn/back/models/invoice-in-tax.json @@ -19,10 +19,7 @@ "type": "number" }, "expenseFk": { - "type": "number", - "mysql": { - "columnName": "expenseFk" - } + "type": "number" }, "created": { "type": "date" diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json index 3f3547fd1..097fe7708 100644 --- a/modules/item/back/models/item.json +++ b/modules/item/back/models/item.json @@ -117,10 +117,7 @@ "description": "The item family" }, "expenseFk": { - "type": "number", - "mysql": { - "columnName": "expenseFk" - } + "type": "number" }, "minPrice": { "type": "number" @@ -131,9 +128,6 @@ "nonRecycledPlastic": { "type": "number" }, - "minQuantity": { - "type": "number" - }, "packingOut": { "type": "number" }, From 9da5fb9a14e739458f823290b1f1996ad7c1762a Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 27 Nov 2023 10:24:25 +0100 Subject: [PATCH 052/207] 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 053/207] 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 37555cbb63290c523e2d237d5d058890d59cb751 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 27 Nov 2023 15:10:00 +0100 Subject: [PATCH 054/207] refs #6335 warmFix(ticketAdvance): correct properties --- modules/ticket/front/advance/index.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/modules/ticket/front/advance/index.js b/modules/ticket/front/advance/index.js index fb539311f..1f47d8242 100644 --- a/modules/ticket/front/advance/index.js +++ b/modules/ticket/front/advance/index.js @@ -202,9 +202,9 @@ export default class Controller extends Section { if (!ticket.landed) { const newLanded = await this.getLanded({ shipped: this.$.model.userParams.dateToAdvance, - addressFk: ticket.addressFk, - agencyModeFk: ticket.agencyModeFk, - warehouseFk: ticket.warehouseFk + addressFk: ticket.futureAddressFk, + agencyModeFk: ticket.agencyModeFk ?? ticket.futureAgencyModeFk, + warehouseFk: ticket.futureWarehouseFk }); if (!newLanded) throw new Error(this.$t(`No delivery zone available for this landing date`)); @@ -213,13 +213,13 @@ export default class Controller extends Section { ticket.zoneFk = newLanded.zoneFk; } const params = { - clientFk: ticket.clientFk, + clientFk: ticket.futureClientFk, nickname: ticket.nickname, agencyModeFk: ticket.agencyModeFk ?? ticket.futureAgencyModeFk, - addressFk: ticket.addressFk, + addressFk: ticket.futureAddressFk, zoneFk: ticket.zoneFk ?? ticket.futureZoneFk, - warehouseFk: ticket.warehouseFk, - companyFk: ticket.companyFk, + warehouseFk: ticket.futureWarehouseFk, + companyFk: ticket.futureCompanyFk, shipped: this.$.model.userParams.dateToAdvance, landed: ticket.landed, isDeleted: false, From 50a97693b99d91df8d5c6b776de7d784a6195c4f Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 28 Nov 2023 07:48:42 +0100 Subject: [PATCH 055/207] refs 5666 feat: remove loggable.js file --- loopback/common/models/loggable.js | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 loopback/common/models/loggable.js diff --git a/loopback/common/models/loggable.js b/loopback/common/models/loggable.js deleted file mode 100644 index 360c84566..000000000 --- a/loopback/common/models/loggable.js +++ /dev/null @@ -1,15 +0,0 @@ -const LoopBackContext = require('loopback-context'); - -module.exports = function(Self) { - Self.setup = function() { - Self.super_.setup.call(this); - }; - - Self.observe('before save', async function(ctx) { - ctx.options.httpCtx = LoopBackContext.getCurrentContext(); - }); - - Self.observe('before delete', async function(ctx) { - ctx.options.httpCtx = LoopBackContext.getCurrentContext(); - }); -}; From f5f2896cbf3be60d1c70d4eb1f850143d1eb0153 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 28 Nov 2023 08:12:16 +0100 Subject: [PATCH 056/207] refs 5666 feat: replace Role model by VnRole model --- back/models/dms-type.json | 4 ++-- back/models/image-collection.json | 5 ++--- back/models/notificationAcl.json | 4 ++-- back/models/vn-user.json | 2 +- modules/account/back/models/role-inherit.json | 4 ++-- modules/account/back/models/role-role.json | 4 ++-- modules/claim/back/models/claim-state.json | 2 +- modules/client/back/models/client-credit-limit.json | 4 ++-- 8 files changed, 14 insertions(+), 15 deletions(-) diff --git a/back/models/dms-type.json b/back/models/dms-type.json index de3d564b4..8d7195132 100644 --- a/back/models/dms-type.json +++ b/back/models/dms-type.json @@ -29,12 +29,12 @@ "relations": { "readRole": { "type": "belongsTo", - "model": "Role", + "model": "VnRole", "foreignKey": "readRoleFk" }, "writeRole": { "type": "belongsTo", - "model": "Role", + "model": "VnRole", "foreignKey": "writeRoleFk" } }, diff --git a/back/models/image-collection.json b/back/models/image-collection.json index 186ab0208..ae0e0adcd 100644 --- a/back/models/image-collection.json +++ b/back/models/image-collection.json @@ -46,12 +46,12 @@ }, "readRole": { "type": "belongsTo", - "model": "Role", + "model": "VnRole", "foreignKey": "readRoleFk" }, "writeRole": { "type": "belongsTo", - "model": "Role", + "model": "VnRole", "foreignKey": "writeRoleFk" } }, @@ -64,4 +64,3 @@ } ] } - \ No newline at end of file diff --git a/back/models/notificationAcl.json b/back/models/notificationAcl.json index a20187961..9ab85530f 100644 --- a/back/models/notificationAcl.json +++ b/back/models/notificationAcl.json @@ -24,8 +24,8 @@ }, "role": { "type": "belongsTo", - "model": "Role", + "model": "VnRole", "foreignKey": "roleFk" } } -} \ No newline at end of file +} diff --git a/back/models/vn-user.json b/back/models/vn-user.json index bda0a6ec3..cf5796123 100644 --- a/back/models/vn-user.json +++ b/back/models/vn-user.json @@ -66,7 +66,7 @@ "relations": { "role": { "type": "belongsTo", - "model": "Role", + "model": "VnRole", "foreignKey": "roleFk" }, "roles": { diff --git a/modules/account/back/models/role-inherit.json b/modules/account/back/models/role-inherit.json index 4b69ffdc2..a89f47b77 100644 --- a/modules/account/back/models/role-inherit.json +++ b/modules/account/back/models/role-inherit.json @@ -15,12 +15,12 @@ "relations": { "owner": { "type": "belongsTo", - "model": "Role", + "model": "VnRole", "foreignKey": "role" }, "inherits": { "type": "belongsTo", - "model": "Role", + "model": "VnRole", "foreignKey": "inheritsFrom" } } diff --git a/modules/account/back/models/role-role.json b/modules/account/back/models/role-role.json index 77df7a920..e59351c59 100644 --- a/modules/account/back/models/role-role.json +++ b/modules/account/back/models/role-role.json @@ -14,12 +14,12 @@ "relations": { "owner": { "type": "belongsTo", - "model": "Role", + "model": "VnRole", "foreignKey": "role" }, "inherits": { "type": "belongsTo", - "model": "Role", + "model": "VnRole", "foreignKey": "inheritsFrom" } } diff --git a/modules/claim/back/models/claim-state.json b/modules/claim/back/models/claim-state.json index f5bde4168..3ee932f16 100644 --- a/modules/claim/back/models/claim-state.json +++ b/modules/claim/back/models/claim-state.json @@ -32,7 +32,7 @@ "relations": { "writeRole": { "type": "belongsTo", - "model": "Role", + "model": "VnRole", "foreignKey": "roleFk" } }, diff --git a/modules/client/back/models/client-credit-limit.json b/modules/client/back/models/client-credit-limit.json index 740f0cf53..922d4d14b 100644 --- a/modules/client/back/models/client-credit-limit.json +++ b/modules/client/back/models/client-credit-limit.json @@ -19,8 +19,8 @@ "relations": { "role": { "type": "belongsTo", - "model": "Role", + "model": "VnRole", "foreignKey": "roleFk" } } -} \ No newline at end of file +} From 2fa56cce4b0a554b63e12bea0112e047700acbc8 Mon Sep 17 00:00:00 2001 From: jgallego Date: Tue, 28 Nov 2023 09:22:00 +0100 Subject: [PATCH 057/207] fix: refs #5652 arreglo fixtures --- db/dump/fixtures.sql | 6 +++--- .../back/methods/sales-monitor/specs/salesFilter.spec.js | 2 +- modules/ticket/back/methods/ticket/specs/filter.spec.js | 2 +- .../back/methods/ticket/specs/getSalespersonMana.spec.js | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 93b7b796f..2d5a4093c 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -362,7 +362,7 @@ INSERT INTO `vn`.`contactChannel`(`id`, `name`) INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`phone`,`mobile`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`gestdocFk`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`,`clientTypeFk`, `hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`eypbc`, `businessTypeFk`,`typeFk`) VALUES - (1101, 'Bruce Wayne', '84612325V', 'BATMAN', 'Alfred', '1007 MOUNTAIN DRIVE, GOTHAM', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','loses'), + (1101, 'Bruce Wayne', '84612325V', 'BATMAN', 'Alfred', '1007 MOUNTAIN DRIVE, GOTHAM', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','normal'), (1102, 'Petter Parker', '87945234L', 'SPIDER MAN', 'Aunt May', '20 INGRAM STREET, QUEENS, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'PetterParker@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','normal'), (1103, 'Clark Kent', '06815934E', 'SUPER MAN', 'lois lane', '344 CLINTON STREET, APARTAMENT 3-D', 'Gotham', 46460, 1111111111, 222222222, 1, 'ClarkKent@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 0, 19, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','normal'), (1104, 'Tony Stark', '06089160W', 'IRON MAN', 'Pepper Potts', '10880 MALIBU POINT, 90265', 'Gotham', 46460, 1111111111, 222222222, 1, 'TonyStark@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','normal'), @@ -372,8 +372,8 @@ INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city (1108, 'Charles Xavier', '22641921P', 'PROFESSOR X', 'Beast', '3800 VICTORY PKWY, CINCINNATI, OH 45207, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 5, 1, 300, 13, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 1, NULL, 0, 0, 19, 0, 1, 'florist','normal'), (1109, 'Bruce Banner', '16104829E', 'HULK', 'Black widow', 'SOMEWHERE IN NEW YORK', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, 0, NULL, 0, 0, 9, 0, 1, 'florist','normal'), (1110, 'Jessica Jones', '58282869H', 'JESSICA JONES', 'Luke Cage', 'NYCC 2015 POSTER', 'Gotham', 46460, 1111111111, 222222222, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, 0, NULL, 0, 0, NULL, 0, 1, 'florist','normal'), - (1111, 'Missing', NULL, 'MISSING MAN', 'Anton', 'THE SPACE, UNIVERSE FAR AWAY', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, 'others','normal'), - (1112, 'Trash', NULL, 'GARBAGE MAN', 'Unknown name', 'NEW YORK CITY, UNDERGROUND', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, 'others','normal'); + (1111, 'Missing', NULL, 'MISSING MAN', 'Anton', 'THE SPACE, UNIVERSE FAR AWAY', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, 'others','loses'), + (1112, 'Trash', NULL, 'GARBAGE MAN', 'Unknown name', 'NEW YORK CITY, UNDERGROUND', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, 'others','loses'); INSERT INTO `vn`.`client`(`id`, `name`, `fi`, `socialName`, `contact`, `street`, `city`, `postcode`, `isRelevant`, `email`, `iban`,`dueDay`,`accountingAccount`, `isEqualizated`, `provinceFk`, `hasToInvoice`, `credit`, `countryFk`, `isActive`, `gestdocFk`, `quality`, `payMethodFk`,`created`, `isTaxDataChecked`) SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), CONCAT(name, 'Social'), CONCAT(name, 'Contact'), CONCAT(name, 'Street'), 'GOTHAM', 46460, 1, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5, util.VN_CURDATE(), 1 diff --git a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js index c3da7f08b..bdafd14e2 100644 --- a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js +++ b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js @@ -151,7 +151,7 @@ describe('SalesMonitor salesFilter()', () => { const result = await models.SalesMonitor.salesFilter(ctx, filter, options); const firstRow = result[0]; - expect(result.length).toEqual(15); + expect(result.length).toEqual(12); expect(firstRow.alertLevel).not.toEqual(0); await tx.rollback(); diff --git a/modules/ticket/back/methods/ticket/specs/filter.spec.js b/modules/ticket/back/methods/ticket/specs/filter.spec.js index 2e5730980..43f3c3680 100644 --- a/modules/ticket/back/methods/ticket/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket/specs/filter.spec.js @@ -68,7 +68,7 @@ describe('ticket filter()', () => { const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); - expect(result.length).toEqual(9); + expect(result.length).toEqual(6); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js b/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js index 12c115ff9..6029ca4a7 100644 --- a/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js +++ b/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js @@ -9,7 +9,7 @@ describe('ticket getSalesPersonMana()', () => { const mana = await models.Ticket.getSalesPersonMana(1, options); - expect(mana).toEqual(73); + expect(mana).toEqual(124); await tx.rollback(); } catch (e) { From f2673c38183ef06dd7c8ed7e04bddd842b53ab52 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 28 Nov 2023 12:12:42 +0100 Subject: [PATCH 058/207] refs #5835 rate added --- modules/invoiceIn/back/methods/invoice-in/summary.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/invoiceIn/back/methods/invoice-in/summary.js b/modules/invoiceIn/back/methods/invoice-in/summary.js index 0e55eeaac..fe198b2b4 100644 --- a/modules/invoiceIn/back/methods/invoice-in/summary.js +++ b/modules/invoiceIn/back/methods/invoice-in/summary.js @@ -112,7 +112,7 @@ module.exports = Self => { { relation: 'taxTypeSage', scope: { - fields: ['vat'] + fields: ['vat', 'rate'] } }] } From 63533459b0991abf3c3d67492c1739780f7bbd98 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 28 Nov 2023 13:22:17 +0100 Subject: [PATCH 059/207] refs #6434 feat: improve signIn method --- back/methods/vn-user/sign-in.js | 8 +--- back/methods/vn-user/specs/sign-in.spec.js | 15 +++--- back/models/vn-user.js | 47 ++++++++++++++----- db/changes/234901/00-createSignInLogTable.sql | 15 ++++++ modules/account/back/models/sign_in-log.json | 7 ++- 5 files changed, 66 insertions(+), 26 deletions(-) create mode 100644 db/changes/234901/00-createSignInLogTable.sql diff --git a/back/methods/vn-user/sign-in.js b/back/methods/vn-user/sign-in.js index 9c2d568f4..782046641 100644 --- a/back/methods/vn-user/sign-in.js +++ b/back/methods/vn-user/sign-in.js @@ -49,13 +49,7 @@ 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({ - token: validateLogin.token, - userFk: vnUser.id, - ip: ctx.req.ip - }); - return validateLogin; + return Self.validateLogin(user, password, ctx); }; Self.passExpired = async vnUser => { diff --git a/back/methods/vn-user/specs/sign-in.spec.js b/back/methods/vn-user/specs/sign-in.spec.js index ac2dfe2b2..1c4b4af51 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,20 +15,21 @@ 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}}); expect(signInLog.length).toEqual(1); expect(signInLog[0].userFk).toEqual(accessToken.userId); + expect(signInLog[0].owner).toEqual(true); expect(login.token).toBeDefined(); await VnUser.logout(ctx.req.accessToken.id); }); 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}}; @@ -38,7 +39,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}}; @@ -53,7 +54,7 @@ describe('VnUser Sign-in()', () => { let error; try { - await VnUser.signIn(unauthCtx, 'IDontExist', 'TotallyWrongPassword'); + await VnUser.signIn(unAuthCtx, 'IDontExist', 'TotallyWrongPassword'); } catch (e) { error = e; } @@ -74,7 +75,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(); @@ -99,7 +100,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/back/models/vn-user.js b/back/models/vn-user.js index 719e96cbf..6b9b9bab5 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -124,20 +124,43 @@ module.exports = function(Self) { return email.send(); }); - Self.signInValidate = (user, userToken) => { + + /** + * Sign-in validate. * + * @param {Integer} 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)); - if (userToken[key].toLowerCase().trim() !== value.toLowerCase().trim()) { - console.error('ERROR!!! - Signin with other user', userToken, user); + const isOwner = Self.rawSql(`SELECT ? = ? `, [userToken[key], value]); + await Self.app.models.SignInLog.create({ + token: token.id, + userFk: userToken.id, + ip: ctx.req.ip, + owner: isOwner + }); + if (!isOwner) { + console.error('ERROR!!! - SignIn with other user', userToken, user); throw new UserError('Try again'); } }; - Self.validateLogin = async function(user, password) { + /** + * Validate login params* + * @param {String} user The user + * @param {String} password + * @param {Object} ctx context + */ + 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(); - Self.signInValidate(user, userToken); + + if (ctx) + await Self.signInValidate(user, userToken, token, ctx); try { await Self.app.models.Account.sync(userToken.name, password); @@ -187,8 +210,8 @@ module.exports = function(Self) { }; Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls = - Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls - .filter(acl => acl.property != 'changePassword'); + Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls + .filter(acl => acl.property != 'changePassword'); Self.userSecurity = async(ctx, userId, options) => { const models = Self.app.models; @@ -226,10 +249,12 @@ module.exports = function(Self) { const env = process.env.NODE_ENV; const liliumUrl = await Self.app.models.Url.findOne({ - where: {and: [ - {appName: 'lilium'}, - {environment: env} - ]} + where: { + and: [ + {appName: 'lilium'}, + {environment: env} + ] + } }); class Mailer { diff --git a/db/changes/234901/00-createSignInLogTable.sql b/db/changes/234901/00-createSignInLogTable.sql new file mode 100644 index 000000000..f77268375 --- /dev/null +++ b/db/changes/234901/00-createSignInLogTable.sql @@ -0,0 +1,15 @@ + +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 INT NOT NULL AUTO_INCREMENT PRIMARY KEY, + `token` varchar(255) 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, + `owner` tinyint(1) DEFAULT 1, + 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/models/sign_in-log.json b/modules/account/back/models/sign_in-log.json index c5c014e60..0da3dc3dd 100644 --- a/modules/account/back/models/sign_in-log.json +++ b/modules/account/back/models/sign_in-log.json @@ -25,7 +25,12 @@ "type": "number" }, "ip": { - "type": "string" + "type": "string" + }, + "owner": { + "type": "boolean", + "required": true, + "default": true } }, "relations": { From 29fb36010cd303390b1f56b686d57d644f67ce88 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 28 Nov 2023 14:48:03 +0100 Subject: [PATCH 060/207] refs #6274 back methods created --- db/changes/235001/00-timecontrol.sql | 13 ++++++++++++ .../methods/worker-time-control/clockIn.js | 19 +++++++++--------- .../methods/worker-time-control/getClockIn.js | 20 ++++++++++--------- .../back/methods/worker-time-control/login.js | 10 +++------- 4 files changed, 37 insertions(+), 25 deletions(-) create mode 100644 db/changes/235001/00-timecontrol.sql diff --git a/db/changes/235001/00-timecontrol.sql b/db/changes/235001/00-timecontrol.sql new file mode 100644 index 000000000..ac7dc85d6 --- /dev/null +++ b/db/changes/235001/00-timecontrol.sql @@ -0,0 +1,13 @@ +INSERT INTO `account`.`role` (name, description) + VALUES ('timeControl','Tablet para fichar'); + +INSERT INTO `account`.`roleInherit` (role, inheritsFrom) + VALUES (127, 11); + +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + ('workerTimeControl', 'login', 'READ', 'ALLOW', 'ROLE', '*'), + ('workerTimeControl', 'getClockIn', 'READ', 'ALLOW', 'ROLE', '*'), + ('workerTimeControl', 'clockIn', 'WRITE', 'ALLOW', 'ROLE', '*'); + +CALL `account`.`role_sync`(); diff --git a/modules/worker/back/methods/worker-time-control/clockIn.js b/modules/worker/back/methods/worker-time-control/clockIn.js index 45de85f1d..3cc57d341 100644 --- a/modules/worker/back/methods/worker-time-control/clockIn.js +++ b/modules/worker/back/methods/worker-time-control/clockIn.js @@ -1,7 +1,7 @@ module.exports = Self => { - Self.remoteMethodCtx('clockIn', { + Self.remoteMethod('clockIn', { description: 'Check if the employee can clock in', - accessType: 'READ', + accessType: 'WRITE', accepts: [ { arg: 'workerFk', @@ -10,25 +10,26 @@ module.exports = Self => { }, { arg: 'direction', - type: 'integer' + type: 'string' }, - { - arg: 'key', - type: 'string', - } + ], http: { path: `/clockIn`, verb: 'POST' + }, + returns: { + type: 'Object', + root: true } }); - Self.clockIn = async(ctx, pin, direction, key, options) => { + Self.clockIn = async(workerFk, direction, options) => { const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); const query = 'CALL vn.workerTimeControl_clockIn(?, NULL, ?)'; - return await Self.rawSql(query, [workerFk, direction], options); + return await Self.rawSql(query, [workerFk, direction], myOptions); }; }; diff --git a/modules/worker/back/methods/worker-time-control/getClockIn.js b/modules/worker/back/methods/worker-time-control/getClockIn.js index 603914655..bc0675db8 100644 --- a/modules/worker/back/methods/worker-time-control/getClockIn.js +++ b/modules/worker/back/methods/worker-time-control/getClockIn.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethodCtx('getClockIn', { + Self.remoteMethod('getClockIn', { description: 'Shows the clockings for each day, in columns per day', accessType: 'READ', accepts: [ @@ -8,23 +8,25 @@ module.exports = Self => { type: 'int', required: true, }, - { - arg: 'key', - type: 'string', - } + ], http: { path: `/getClockIn`, - verb: 'POST' - } + verb: 'GET' + }, + returns: { + type: ['Object'], + root: true + }, }); - Self.getClockIn = async(ctx, workerFk, key, options) => { + Self.getClockIn = async(workerFk, options) => { const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); const query = `CALL vn.workerTimeControl_getClockIn(?, CURDATE())`; - return await Self.rawSql(query, [workerFk], myOptions); + const [result] = await Self.rawSql(query, [workerFk], myOptions); + return result; }; }; diff --git a/modules/worker/back/methods/worker-time-control/login.js b/modules/worker/back/methods/worker-time-control/login.js index 75813411a..894b5ba17 100644 --- a/modules/worker/back/methods/worker-time-control/login.js +++ b/modules/worker/back/methods/worker-time-control/login.js @@ -1,7 +1,7 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.remoteMethodCtx('login', { + Self.remoteMethod('login', { description: 'Consult the user\'s information and the buttons that must be activated after logging in', accessType: 'READ', accepts: [ @@ -10,10 +10,6 @@ module.exports = Self => { type: 'string', required: true, }, - { - arg: 'key', - type: 'string', - } ], returns: { type: 'Object', @@ -25,7 +21,7 @@ module.exports = Self => { } }); - Self.login = async(ctx, pin, key, options) => { + Self.login = async(pin, options) => { const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); @@ -34,6 +30,6 @@ module.exports = Self => { const user = await Self.rawSql(query, [pin], myOptions); if (!user) throw new UserError('Indique el pin.'); - return user; + return user[0][0]; }; }; From 0186c2c80678f518de105192d1e306f2361f056a Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 29 Nov 2023 07:33:49 +0100 Subject: [PATCH 061/207] refs #6085 aclMail back --- db/changes/235001/00-aclsMails.sql | 7 ++++ .../account/front/alias/acl/create/index.js | 33 +++++++++++++++++++ modules/account/front/alias/acl/index.js | 4 +++ .../account/front/alias/acl/index/index.js | 15 +++++++++ modules/account/front/alias/acl/main/index.js | 18 ++++++++++ 5 files changed, 77 insertions(+) create mode 100644 db/changes/235001/00-aclsMails.sql create mode 100644 modules/account/front/alias/acl/create/index.js create mode 100644 modules/account/front/alias/acl/index.js create mode 100644 modules/account/front/alias/acl/index/index.js create mode 100644 modules/account/front/alias/acl/main/index.js diff --git a/db/changes/235001/00-aclsMails.sql b/db/changes/235001/00-aclsMails.sql new file mode 100644 index 000000000..92603aec4 --- /dev/null +++ b/db/changes/235001/00-aclsMails.sql @@ -0,0 +1,7 @@ +-- Definición de la tabla mailAliasACL +CREATE TABLE `account`.`mailAliasACL` ( + `mailAliasFk` int(10) unsigned NOT NULL, + `roleFk` int(10) unsigned NOT NULL, + FOREIGN KEY (`mailAliasFk`) REFERENCES `account`.`mailAlias` (`id`), + FOREIGN KEY (`roleFk`) REFERENCES `account`.`role` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; diff --git a/modules/account/front/alias/acl/create/index.js b/modules/account/front/alias/acl/create/index.js new file mode 100644 index 000000000..1f9d73272 --- /dev/null +++ b/modules/account/front/alias/acl/create/index.js @@ -0,0 +1,33 @@ +import ngModule from '../../module'; +import Section from 'salix/components/section'; + +export default class Controller extends Section { + constructor(...args) { + super(...args); + this.accessTypes = [ + {name: '*'}, + {name: 'READ'}, + {name: 'WRITE'} + ]; + this.permissions = [ + {name: 'ALLOW'}, + {name: 'DENY'} + ]; + + this.models = []; + for (let model in window.validations) + this.models.push({name: model}); + + this.acl = { + property: '*', + principalType: 'ROLE', + accessType: 'READ', + permission: 'ALLOW' + }; + } +} + +ngModule.component('vnAclMailCreate', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/account/front/alias/acl/index.js b/modules/account/front/alias/acl/index.js new file mode 100644 index 000000000..8393859a5 --- /dev/null +++ b/modules/account/front/alias/acl/index.js @@ -0,0 +1,4 @@ +import './main'; +import './index/'; +import './create'; +import './search-panel'; diff --git a/modules/account/front/alias/acl/index/index.js b/modules/account/front/alias/acl/index/index.js new file mode 100644 index 000000000..b78dfa7f5 --- /dev/null +++ b/modules/account/front/alias/acl/index/index.js @@ -0,0 +1,15 @@ +import ngModule from '../../module'; +import Section from 'salix/components/section'; + +export default class Controller extends Section { + onDelete(row) { + return this.$http.delete(`ACLs/${row.id}`) + .then(() => this.$.model.refresh()) + .then(() => this.vnApp.showSuccess(this.$t('ACL removed'))); + } +} + +ngModule.component('vnAclMailIndex', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/account/front/alias/acl/main/index.js b/modules/account/front/alias/acl/main/index.js new file mode 100644 index 000000000..431ef48c5 --- /dev/null +++ b/modules/account/front/alias/acl/main/index.js @@ -0,0 +1,18 @@ +import ngModule from '../../module'; +import ModuleMain from 'salix/components/module-main'; + +export default class ACL extends ModuleMain { + exprBuilder(param, value) { + switch (param) { + case 'search': + return {model: {like: `%${value}%`}}; + default: + return {[param]: value}; + } + } +} + +ngModule.vnComponent('vnAclMailComponent', { + controller: ACL, + template: require('./index.html') +}); From e548ef4dae1d056cfc2f34396a3e3e164ee2b9a8 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 29 Nov 2023 07:51:58 +0100 Subject: [PATCH 062/207] refs #6085 searchpanel and change path --- .../account/front/alias/acl/create/index.js | 4 +-- .../account/front/alias/acl/index/index.js | 4 +-- modules/account/front/alias/acl/main/index.js | 6 ++--- .../front/alias/acl/search-panel/index.js | 26 +++++++++++++++++++ modules/account/front/alias/index.js | 1 + 5 files changed, 34 insertions(+), 7 deletions(-) create mode 100644 modules/account/front/alias/acl/search-panel/index.js diff --git a/modules/account/front/alias/acl/create/index.js b/modules/account/front/alias/acl/create/index.js index 1f9d73272..58e70e4aa 100644 --- a/modules/account/front/alias/acl/create/index.js +++ b/modules/account/front/alias/acl/create/index.js @@ -1,4 +1,4 @@ -import ngModule from '../../module'; +import ngModule from '../../../module'; import Section from 'salix/components/section'; export default class Controller extends Section { @@ -28,6 +28,6 @@ export default class Controller extends Section { } ngModule.component('vnAclMailCreate', { - template: require('./index.html'), + // template: require('./index.html'), controller: Controller }); diff --git a/modules/account/front/alias/acl/index/index.js b/modules/account/front/alias/acl/index/index.js index b78dfa7f5..5d8d49574 100644 --- a/modules/account/front/alias/acl/index/index.js +++ b/modules/account/front/alias/acl/index/index.js @@ -1,4 +1,4 @@ -import ngModule from '../../module'; +import ngModule from '../../../module'; import Section from 'salix/components/section'; export default class Controller extends Section { @@ -10,6 +10,6 @@ export default class Controller extends Section { } ngModule.component('vnAclMailIndex', { - template: require('./index.html'), + // template: require('./index.html'), controller: Controller }); diff --git a/modules/account/front/alias/acl/main/index.js b/modules/account/front/alias/acl/main/index.js index 431ef48c5..97f04ee50 100644 --- a/modules/account/front/alias/acl/main/index.js +++ b/modules/account/front/alias/acl/main/index.js @@ -1,4 +1,4 @@ -import ngModule from '../../module'; +import ngModule from '../../../module'; import ModuleMain from 'salix/components/module-main'; export default class ACL extends ModuleMain { @@ -13,6 +13,6 @@ export default class ACL extends ModuleMain { } ngModule.vnComponent('vnAclMailComponent', { - controller: ACL, - template: require('./index.html') + controller: ACL + // template: require('./index.html') }); diff --git a/modules/account/front/alias/acl/search-panel/index.js b/modules/account/front/alias/acl/search-panel/index.js new file mode 100644 index 000000000..67db33383 --- /dev/null +++ b/modules/account/front/alias/acl/search-panel/index.js @@ -0,0 +1,26 @@ +import ngModule from '../../../module'; +import SearchPanel from 'core/components/searchbar/search-panel'; + +export default class Controller extends SearchPanel { + constructor(...args) { + super(...args); + this.accessTypes = [ + {name: '*'}, + {name: 'READ'}, + {name: 'WRITE'} + ]; + this.permissions = [ + {name: 'ALLOW'}, + {name: 'DENY'} + ]; + + this.models = []; + for (let model in window.validations) + this.models.push({name: model}); + } +} + +ngModule.component('vnAclSearchPanel', { + // template: require('./index.html'), + controller: Controller +}); diff --git a/modules/account/front/alias/index.js b/modules/account/front/alias/index.js index 8eed3a3d3..598421749 100644 --- a/modules/account/front/alias/index.js +++ b/modules/account/front/alias/index.js @@ -7,3 +7,4 @@ import './descriptor'; import './create'; import './basic-data'; import './users'; +import './acl'; From 48dd068190e20819d9906b8212c5f1c74b58e00d Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 29 Nov 2023 08:37:56 +0100 Subject: [PATCH 063/207] refs #6274 upperCase Model --- db/changes/235001/00-timecontrol.sql | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/db/changes/235001/00-timecontrol.sql b/db/changes/235001/00-timecontrol.sql index ac7dc85d6..4e350b002 100644 --- a/db/changes/235001/00-timecontrol.sql +++ b/db/changes/235001/00-timecontrol.sql @@ -6,8 +6,8 @@ INSERT INTO `account`.`roleInherit` (role, inheritsFrom) INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) VALUES - ('workerTimeControl', 'login', 'READ', 'ALLOW', 'ROLE', '*'), - ('workerTimeControl', 'getClockIn', 'READ', 'ALLOW', 'ROLE', '*'), - ('workerTimeControl', 'clockIn', 'WRITE', 'ALLOW', 'ROLE', '*'); + ('WorkerTimeControl', 'login', 'READ', 'ALLOW', 'ROLE', 'timeControl'), + ('WorkerTimeControl', 'getClockIn', 'READ', 'ALLOW', 'ROLE', 'timeControl'), + ('WorkerTimeControl', 'clockIn', 'WRITE', 'ALLOW', 'ROLE', 'timeControl'); CALL `account`.`role_sync`(); From 2e22984e77de749f76d93f36821350160c3ad138 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 29 Nov 2023 09:13:54 +0100 Subject: [PATCH 064/207] refs #6197 fix: add salix role in fixtures --- db/dump/fixtures.sql | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 93b7b796f..441026f43 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -1,3 +1,7 @@ +CREATE ROLE 'salix'; +GRANT 'salix' TO 'root'@'%'; +SET DEFAULT ROLE 'salix' FOR 'root'@'%'; + CREATE SCHEMA IF NOT EXISTS `vn2008`; CREATE SCHEMA IF NOT EXISTS `tmp`; From 9a3efdd6fe9e29cf0dd6ca97c8c384e26bd99a53 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 29 Nov 2023 13:55:44 +0100 Subject: [PATCH 065/207] refs #6085 model y back --- modules/account/back/models/mail-alias-acl.js | 70 +++++++++++++++++++ .../account/back/models/mail-alias-acl.json | 29 ++++++++ 2 files changed, 99 insertions(+) create mode 100644 modules/account/back/models/mail-alias-acl.js create mode 100644 modules/account/back/models/mail-alias-acl.json diff --git a/modules/account/back/models/mail-alias-acl.js b/modules/account/back/models/mail-alias-acl.js new file mode 100644 index 000000000..4a74472fe --- /dev/null +++ b/modules/account/back/models/mail-alias-acl.js @@ -0,0 +1,70 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + require('../methods/notification/getList')(Self); + + Self.observe('before save', async function(ctx) { + await checkModifyPermission(ctx); + }); + + Self.observe('before delete', async function(ctx) { + await checkModifyPermission(ctx); + }); + + async function checkModifyPermission(ctx) { + const models = Self.app.models; + const instance = ctx.instance; + const userId = ctx.options.accessToken.userId; + + let mailAliasFk; + let roleFk; + + if (instance) { + mailAliasFk = instance.mailAliasFk; + roleFk = instance.roleFk; + } else { + const mailAliasAcl = await models.MailAlias.findById(ctx.where.id); + mailAliasFk = mailAliasAcl.id; + roleFk = mailAliasAcl.roleFk; + } + + const role = await models.VnUser.findById(roleFk, {fields: ['id', 'role']}); + const available = await Self.getAvailable(roleFk); + const hasAcl = available.has(mailAliasFk); + + if (!hasAcl || (userId.role != role)) + throw new UserError('The alias cant be modified'); + } + + Self.getAvailable = async function(userId, options) { + const availableMailAliasMap = new Map(); + const models = Self.app.models; + + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const roles = await models.RoleMapping.find({ + fields: ['roleId'], + where: {principalId: userId} + }, myOptions); + + const availableMailAlias = await models.MailAliasAcl.find({ + fields: ['mailAliasFk', 'roleFk'], + include: {relation: 'roleFk'}, + where: { + roleFk: { + inq: roles.map(role => role.roleId), + }, + } + }, myOptions); + + for (available of availableMailAlias) { + availableMailAliasMap.set(available.mailAliasFk, { + mailAliasFk: available.mailAliasFk, + }); + } + return availableMailAliasMap; + }; +}; diff --git a/modules/account/back/models/mail-alias-acl.json b/modules/account/back/models/mail-alias-acl.json new file mode 100644 index 000000000..2e44f38eb --- /dev/null +++ b/modules/account/back/models/mail-alias-acl.json @@ -0,0 +1,29 @@ +{ + "name": "mailAliasACL", + "base": "VnModel", + "options": { + "mysql": { + "table": "account.mailAliasACL" + } + }, + "properties": { + "mailAliasFk": { + "type": "number" + }, + "roleFk": { + "type": "number" + } + }, + "relations": { + "mailAlias": { + "type": "belongsTo", + "model": "VnUser", + "foreignKey": "mailAliasFk" + }, + "role": { + "type": "belongsTo", + "model": "VnUser", + "foreignKey": "roleFk" + } + } +} From 48b82b02cad3501d599c4ef688942de5f0ecf807 Mon Sep 17 00:00:00 2001 From: JAVIER SEGARRA MARTINEZ Date: Wed, 29 Nov 2023 19:32:10 +0000 Subject: [PATCH 066/207] refs #6434 change param type for signInValidate --- 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 6b9b9bab5..e32d83a36 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -127,7 +127,7 @@ module.exports = function(Self) { /** * Sign-in validate. * - * @param {Integer} user The user + * @param {String} user The user * @param {Object} userToken Options * @param {Object} token accessToken * @param {Object} ctx context From ed6c0924d794e1a99a1f08e9c69ba55303120c24 Mon Sep 17 00:00:00 2001 From: JAVIER SEGARRA MARTINEZ Date: Wed, 29 Nov 2023 19:33:04 +0000 Subject: [PATCH 067/207] refs #6434 perf: remove console.error --- back/models/vn-user.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index e32d83a36..288bd4d1f 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -141,10 +141,8 @@ module.exports = function(Self) { ip: ctx.req.ip, owner: isOwner }); - if (!isOwner) { - console.error('ERROR!!! - SignIn with other user', userToken, user); + if (!isOwner) throw new UserError('Try again'); - } }; /** From 9176cdb4cbed343727f470d01bc0cfff9a65ad8b Mon Sep 17 00:00:00 2001 From: JAVIER SEGARRA MARTINEZ Date: Wed, 29 Nov 2023 19:34:00 +0000 Subject: [PATCH 068/207] refs #6434 perf: new field in SignInLog table --- back/models/vn-user.js | 1 + 1 file changed, 1 insertion(+) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 288bd4d1f..ad0f88d8c 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -136,6 +136,7 @@ module.exports = function(Self) { 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, From 46774b2e73b42fefa147803770e54adfd992a06c Mon Sep 17 00:00:00 2001 From: JAVIER SEGARRA MARTINEZ Date: Wed, 29 Nov 2023 19:35:37 +0000 Subject: [PATCH 069/207] refs #6434 perf: new field in SignInLog table --- db/changes/234901/00-createSignInLogTable.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/db/changes/234901/00-createSignInLogTable.sql b/db/changes/234901/00-createSignInLogTable.sql index f77268375..49187c9cb 100644 --- a/db/changes/234901/00-createSignInLogTable.sql +++ b/db/changes/234901/00-createSignInLogTable.sql @@ -7,6 +7,7 @@ CREATE TABLE `account`.`signInLog` ( `token` varchar(255) NOT NULL , `userFk` int(10) unsigned DEFAULT NULL, `creationDate` timestamp NULL DEFAULT current_timestamp(), + `userName` varchar(30) NOT NULL, `ip` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, `owner` tinyint(1) DEFAULT 1, KEY `userFk` (`userFk`), From 1576ab992d2cc6a4b5f1e89efa5c2c6136c52634 Mon Sep 17 00:00:00 2001 From: JAVIER SEGARRA MARTINEZ Date: Wed, 29 Nov 2023 19:36:30 +0000 Subject: [PATCH 070/207] refs #6434 perf: new field in SignInLog table --- modules/account/back/models/sign_in-log.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/modules/account/back/models/sign_in-log.json b/modules/account/back/models/sign_in-log.json index 0da3dc3dd..8656e92dc 100644 --- a/modules/account/back/models/sign_in-log.json +++ b/modules/account/back/models/sign_in-log.json @@ -27,6 +27,9 @@ "ip": { "type": "string" }, + "userName": { + "type": "string" + }, "owner": { "type": "boolean", "required": true, From d4cd23853ffbd474ee7c55401437c47763a204ef Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 30 Nov 2023 07:32:16 +0100 Subject: [PATCH 071/207] 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 138d11b7b0cb72c3b0d91fa553eaf32cfba5b8de Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 30 Nov 2023 08:10:32 +0100 Subject: [PATCH 072/207] refs #6434 perf new version folder for sql file --- db/changes/{234604 => 264802}/00-createSignInLogTable.sql | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename db/changes/{234604 => 264802}/00-createSignInLogTable.sql (100%) diff --git a/db/changes/234604/00-createSignInLogTable.sql b/db/changes/264802/00-createSignInLogTable.sql similarity index 100% rename from db/changes/234604/00-createSignInLogTable.sql rename to db/changes/264802/00-createSignInLogTable.sql From 6b354a20adc64aed73826740de80839051aca1c0 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 30 Nov 2023 08:13:28 +0100 Subject: [PATCH 073/207] refs #6434 perf: add sql table description --- db/changes/234901/00-createSignInLogTable.sql | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/db/changes/234901/00-createSignInLogTable.sql b/db/changes/234901/00-createSignInLogTable.sql index 49187c9cb..942f651c9 100644 --- a/db/changes/234901/00-createSignInLogTable.sql +++ b/db/changes/234901/00-createSignInLogTable.sql @@ -1,4 +1,9 @@ +-- +-- Table structure for table `signInLog` +-- Description: log to debug cross-login error +-- + DROP TABLE IF EXISTS `account`.`signInLog`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; From 58855a7cddb75720369e9eb596f96f0e16f8f692 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 30 Nov 2023 08:14:56 +0100 Subject: [PATCH 074/207] refs #6434 perf: remove bad characters method description --- back/models/vn-user.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index ad0f88d8c..e14cd30ea 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -126,7 +126,7 @@ module.exports = function(Self) { }); /** - * Sign-in validate. * + * Sign-in validate * @param {String} user The user * @param {Object} userToken Options * @param {Object} token accessToken @@ -147,7 +147,7 @@ module.exports = function(Self) { }; /** - * Validate login params* + * Validate login params * @param {String} user The user * @param {String} password * @param {Object} ctx context From 80f8037f58f72f0e3ecdf34755d81422951eebe8 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 30 Nov 2023 08:23:14 +0100 Subject: [PATCH 075/207] refs #6434 perf remove version folder for sql file --- db/changes/264802/00-createSignInLogTable.sql | 20 ------------------- 1 file changed, 20 deletions(-) delete mode 100644 db/changes/264802/00-createSignInLogTable.sql diff --git a/db/changes/264802/00-createSignInLogTable.sql b/db/changes/264802/00-createSignInLogTable.sql deleted file mode 100644 index 525348135..000000000 --- a/db/changes/264802/00-createSignInLogTable.sql +++ /dev/null @@ -1,20 +0,0 @@ - - --- --- Table structure for table `signInLog` --- Description: log to debug cross-login error --- - -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 INT NOT NULL AUTO_INCREMENT PRIMARY KEY, - `token` varchar(255) 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, - KEY `userFk` (`userFk`), - CONSTRAINT `signInLog_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -); - From 7611acb8f2d156358b8d4699594cfbc2ac3157f6 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 30 Nov 2023 08:34:10 +0100 Subject: [PATCH 076/207] refs #6434 perf rename version folder for sql file --- db/changes/{234901 => 234802}/00-createSignInLogTable.sql | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename db/changes/{234901 => 234802}/00-createSignInLogTable.sql (100%) diff --git a/db/changes/234901/00-createSignInLogTable.sql b/db/changes/234802/00-createSignInLogTable.sql similarity index 100% rename from db/changes/234901/00-createSignInLogTable.sql rename to db/changes/234802/00-createSignInLogTable.sql From 9cdb7c3ccab620912c1a4bb9c7c7ac955895c00e Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 30 Nov 2023 09:18:00 +0100 Subject: [PATCH 077/207] refs #6065 remove workcenter --- modules/worker/front/time-control/index.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index f8a94be52..f6a6ed535 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -111,8 +111,10 @@ class Controller extends Section { dayIndex.setDate(dayIndex.getDate() + 1); } - this.fetchHours(); - this.getWeekData(); + if (this.worker) { + this.fetchHours(); + this.getWeekData(); + } } set weekTotalHours(totalHours) { @@ -171,8 +173,6 @@ class Controller extends Section { ]} }; this.$.model.applyFilter(filter, params).then(() => { - if (!this.card.hasWorkCenter) return; - this.getWorkedHours(this.started, this.ended); this.getAbsences(); }); From 3f22f48df728e16624d86985df9e180ad448e510 Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 30 Nov 2023 12:13:12 +0100 Subject: [PATCH 078/207] fix(getFiltered): refs #3271 fix to event filter --- db/dump/fixtures.sql | 6 +- .../back/methods/route/getExternalCmrs.js | 190 +++++++++--------- .../back/methods/zone/getEventsFiltered.js | 57 +++--- .../zone/specs/getEventsFiltered.spec.js | 10 +- 4 files changed, 133 insertions(+), 130 deletions(-) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 788487ed0..a0b97b34e 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2343,9 +2343,11 @@ INSERT INTO `vn`.`zoneEvent`(`zoneFk`, `type`, `weekDays`) (8, 'indefinitely', 'mon,tue,wed,thu,fri,sat,sun'), (10, 'indefinitely', 'mon,tue,wed,thu,fri,sat,sun'); -INSERT INTO `vn`.`zoneEvent`(`zoneFk`, `type`, `started`, `ended`) +INSERT INTO `vn`.`zoneEvent`(`zoneFk`, `type`, `started`, `ended`, `weekDays`) VALUES - (9, 'range', DATE_ADD(util.VN_CURDATE(), INTERVAL -1 YEAR), DATE_ADD(util.VN_CURDATE(), INTERVAL +1 YEAR)); + (9, 'range', DATE_ADD(util.VN_CURDATE(), INTERVAL -1 YEAR), DATE_ADD(util.VN_CURDATE(), INTERVAL +1 YEAR), 'mon'), + (9, 'range', util.VN_CURDATE(), NULL, 'tue'), + (9, 'range', NULL, util.VN_CURDATE(), 'wed'); INSERT INTO `vn`.`workerTimeControl`(`userFk`, `timed`, `manual`, `direction`, `isSendMail`) VALUES diff --git a/modules/route/back/methods/route/getExternalCmrs.js b/modules/route/back/methods/route/getExternalCmrs.js index 4750e53a1..3fc9798b0 100644 --- a/modules/route/back/methods/route/getExternalCmrs.js +++ b/modules/route/back/methods/route/getExternalCmrs.js @@ -3,99 +3,101 @@ const buildFilter = require('vn-loopback/util/filter').buildFilter; const mergeFilters = require('vn-loopback/util/filter').mergeFilters; module.exports = Self => { - Self.remoteMethod('getExternalCmrs', { - description: 'Returns an array of external cmrs', - accessType: 'READ', - accepts: [ - { - arg: 'filter', - type: 'object', - description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', - }, - { - arg: 'cmrFk', - type: 'integer', - description: 'Searchs the route by id', - }, - { - arg: 'ticketFk', - type: 'integer', - description: 'The worker id', - }, - { - arg: 'routeFk', - type: 'integer', - description: 'The route id', - }, - { - arg: 'country', - type: 'string', - description: 'The agencyMode id', - }, - { - arg: 'clientFk', - type: 'integer', - description: 'The vehicle id', - }, - { - arg: 'hasCmrDms', - type: 'boolean', - description: 'The vehicle id', - }, - { - arg: 'shipped', - type: 'date', - description: 'The to date filter', - }, - ], - returns: { - type: ['object'], - root: true - }, - http: { - path: `/getExternalCmrs`, - verb: 'GET' - } - }); + Self.remoteMethod('getExternalCmrs', { + description: 'Returns an array of external cmrs', + accessType: 'READ', + accepts: [ + { + arg: 'filter', + type: 'object', + description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', + }, + { + arg: 'cmrFk', + type: 'integer', + description: 'Searchs the route by id', + }, + { + arg: 'ticketFk', + type: 'integer', + description: 'The worker id', + }, + { + arg: 'routeFk', + type: 'integer', + description: 'The route id', + }, + { + arg: 'country', + type: 'string', + description: 'The agencyMode id', + }, + { + arg: 'clientFk', + type: 'integer', + description: 'The vehicle id', + }, + { + arg: 'hasCmrDms', + type: 'boolean', + description: 'The vehicle id', + }, + { + arg: 'shipped', + type: 'date', + description: 'The to date filter', + }, + ], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/getExternalCmrs`, + verb: 'GET' + } + }); - Self.getExternalCmrs = async( - filter, - cmrFk, - ticketFk, - routeFk, - country, - clientFk, - hasCmrDms, - shipped, - options - ) => { - const params = { - cmrFk, - ticketFk, - routeFk, - country, - clientFk, - hasCmrDms, - shipped, - }; - const conn = Self.dataSource.connector; + Self.getExternalCmrs = async( + filter, + cmrFk, + ticketFk, + routeFk, + country, + clientFk, + hasCmrDms, + shipped, + options + ) => { + const params = { + cmrFk, + ticketFk, + routeFk, + country, + clientFk, + hasCmrDms, + shipped, + }; + const conn = Self.dataSource.connector; - let where = buildFilter(params, (param, value) => {return {[param]: value}}); - filter = mergeFilters(filter, {where}); + let where = buildFilter(params, (param, value) => { + return {[param]: value}; + }); + filter = mergeFilters(filter, {where}); - if (!filter.where) { - const yesterday = new Date(); - yesterday.setDate(yesterday.getDate() - 1); - filter.where = {'shipped': yesterday.toISOString().split('T')[0]} - } + if (!filter.where) { + const yesterday = new Date(); + yesterday.setDate(yesterday.getDate() - 1); + filter.where = {'shipped': yesterday.toISOString().split('T')[0]}; + } - const myOptions = {}; + const myOptions = {}; - if (typeof options == 'object') - Object.assign(myOptions, options); + if (typeof options == 'object') + Object.assign(myOptions, options); - let stmts = []; - const stmt = new ParameterizedSQL(` + let stmts = []; + const stmt = new ParameterizedSQL(` SELECT * FROM ( SELECT t.cmrFk, @@ -129,13 +131,13 @@ module.exports = Self => { AND dm.code = 'DELIVERY' AND t.cmrFk ) sub - `); + `); - stmt.merge(conn.makeSuffix(filter)); - const itemsIndex = stmts.push(stmt) - 1; + stmt.merge(conn.makeSuffix(filter)); + const itemsIndex = stmts.push(stmt) - 1; - const sql = ParameterizedSQL.join(stmts, ';'); - const result = await conn.executeStmt(sql); - return itemsIndex === 0 ? result : result[itemsIndex]; - }; + const sql = ParameterizedSQL.join(stmts, ';'); + const result = await conn.executeStmt(sql); + return itemsIndex === 0 ? result : result[itemsIndex]; + }; }; diff --git a/modules/zone/back/methods/zone/getEventsFiltered.js b/modules/zone/back/methods/zone/getEventsFiltered.js index b7875785d..85db76a58 100644 --- a/modules/zone/back/methods/zone/getEventsFiltered.js +++ b/modules/zone/back/methods/zone/getEventsFiltered.js @@ -35,44 +35,39 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - query = ` - SELECT * - FROM vn.zoneEvent - WHERE zoneFk = ? - AND ((type = 'indefinitely') - OR (type = 'day' AND dated BETWEEN ? AND ?) - OR (type = 'range' - AND ( - (started BETWEEN ? AND ?) - OR - (ended BETWEEN ? AND ?) - OR - (started <= ? AND ended >= ?) - ) - ) - ) - ORDER BY type='indefinitely' DESC, type='range' DESC, type='day' DESC;`; - const events = await Self.rawSql(query, - [zoneFk, started, ended, started, ended, started, ended, started, ended], myOptions); + ended = simpleDate(ended); + started = simpleDate(started); query = ` - SELECT e.* - FROM vn.zoneExclusion e - LEFT JOIN vn.zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id - WHERE e.zoneFk = ? - AND e.dated BETWEEN ? AND ? - AND eg.zoneExclusionFk IS NULL;`; + SELECT * + FROM vn.zoneEvent + WHERE zoneFk = ? + AND (IFNULL(started, ?) <= ? AND IFNULL(ended,?) >= ?) + ORDER BY type='indefinitely' DESC, type='range' DESC, type='day' DESC;`; + const events = await Self.rawSql(query, + [zoneFk, started, ended, ended, started], myOptions); + + query = ` + SELECT e.* + FROM vn.zoneExclusion e + LEFT JOIN vn.zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id + WHERE e.zoneFk = ? + AND e.dated BETWEEN ? AND ? + AND eg.zoneExclusionFk IS NULL;`; const exclusions = await Self.rawSql(query, [zoneFk, started, ended], myOptions); query = ` - SELECT eg.*, e.zoneFk, e.dated, e.created, e.userFk - FROM vn.zoneExclusion e - LEFT JOIN vn.zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id - WHERE e.zoneFk = ? - AND e.dated BETWEEN ? AND ? - AND eg.zoneExclusionFk IS NOT NULL;`; + SELECT eg.*, e.zoneFk, e.dated, e.created, e.userFk + FROM vn.zoneExclusion e + LEFT JOIN vn.zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id + WHERE e.zoneFk = ? + AND e.dated BETWEEN ? AND ? + AND eg.zoneExclusionFk IS NOT NULL;`; const geoExclusions = await Self.rawSql(query, [zoneFk, started, ended], myOptions); return {events, exclusions, geoExclusions}; }; + function simpleDate(date) { + return date.toISOString().split('T')[0]; + } }; diff --git a/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js b/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js index 6fd6bb994..d1c7f1fc4 100644 --- a/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js +++ b/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js @@ -30,7 +30,7 @@ describe('zone getEventsFiltered()', () => { const result = await models.Zone.getEventsFiltered(9, today, today, options); - expect(result.events.length).toEqual(1); + expect(result.events.length).toEqual(3); expect(result.exclusions.length).toEqual(0); await tx.rollback(); @@ -47,11 +47,15 @@ describe('zone getEventsFiltered()', () => { const options = {transaction: tx}; const date = Date.vnNew(); date.setFullYear(date.getFullYear() - 2); - const dateTomorrow = new Date(date.setDate(date.getDate() + 1)); + const dateTomorrow = new Date(date); + dateTomorrow.setDate(dateTomorrow.getDate() + 1); const result = await models.Zone.getEventsFiltered(9, date, dateTomorrow, options); + console.log('dateTomorrow: ', dateTomorrow); + console.log('date: ', date); + console.log('result: ', result); - expect(result.events.length).toEqual(0); + expect(result.events.length).toEqual(1); expect(result.exclusions.length).toEqual(0); await tx.rollback(); From 16001099b61adc0d297f88c204e0748e5c3ee57f Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 30 Nov 2023 12:15:48 +0100 Subject: [PATCH 079/207] refs #5666 feat: update ACLs for role and vnRole --- db/changes/235001/00-updateACL_Role_VnRole.sql | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 db/changes/235001/00-updateACL_Role_VnRole.sql diff --git a/db/changes/235001/00-updateACL_Role_VnRole.sql b/db/changes/235001/00-updateACL_Role_VnRole.sql new file mode 100644 index 000000000..0b1083991 --- /dev/null +++ b/db/changes/235001/00-updateACL_Role_VnRole.sql @@ -0,0 +1,8 @@ +-- Auto-generated SQL script #202311301038 +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) + VALUES ('VnRole','*','*','ALLOW','ROLE','$everyone'); +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) + VALUES ('VnRole','*','*','ALLOW','ROLE','employee'); + +-- Auto-generated SQL script #202311301203 +UPDATE `salix`.`ACL` SET permission='DENY' WHERE model='Role'; From 01e713522415ac0710145f802eb0e8b9384cadbb Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 30 Nov 2023 12:20:05 +0100 Subject: [PATCH 080/207] refs #5666 feat: replace Role by VnRole in front --- modules/account/front/acl/create/index.html | 4 ++-- modules/account/front/acl/search-panel/index.html | 6 +++--- modules/account/front/create/index.html | 2 +- modules/account/front/privileges/index.html | 2 +- modules/account/front/role/basic-data/index.html | 8 ++++---- modules/account/front/role/card/index.js | 2 +- modules/account/front/role/create/index.html | 6 +++--- modules/account/front/role/descriptor/index.js | 2 +- modules/account/front/role/main/index.html | 4 ++-- modules/account/front/role/subroles/index.html | 6 +++--- modules/account/front/role/summary/index.js | 2 +- modules/account/front/search-panel/index.html | 4 ++-- 12 files changed, 24 insertions(+), 24 deletions(-) diff --git a/modules/account/front/acl/create/index.html b/modules/account/front/acl/create/index.html index 7f4fa9e46..14332f737 100644 --- a/modules/account/front/acl/create/index.html +++ b/modules/account/front/acl/create/index.html @@ -15,7 +15,7 @@ @@ -32,7 +32,7 @@ diff --git a/modules/account/front/acl/search-panel/index.html b/modules/account/front/acl/search-panel/index.html index b83b9c255..a3efab440 100644 --- a/modules/account/front/acl/search-panel/index.html +++ b/modules/account/front/acl/search-panel/index.html @@ -4,7 +4,7 @@ -
\ No newline at end of file + diff --git a/modules/account/front/create/index.html b/modules/account/front/create/index.html index acc07d346..70a518885 100644 --- a/modules/account/front/create/index.html +++ b/modules/account/front/create/index.html @@ -30,7 +30,7 @@ + url="VnRoles"> diff --git a/modules/account/front/role/basic-data/index.html b/modules/account/front/role/basic-data/index.html index 749927186..a6d39f3e3 100644 --- a/modules/account/front/role/basic-data/index.html +++ b/modules/account/front/role/basic-data/index.html @@ -1,6 +1,6 @@ @@ -11,13 +11,13 @@ @@ -35,4 +35,4 @@ ng-click="watcher.loadOriginalData()"> - \ No newline at end of file + diff --git a/modules/account/front/role/card/index.js b/modules/account/front/role/card/index.js index 6f888211d..3c7c758ef 100644 --- a/modules/account/front/role/card/index.js +++ b/modules/account/front/role/card/index.js @@ -3,7 +3,7 @@ import ModuleCard from 'salix/components/module-card'; class Controller extends ModuleCard { reload() { - this.$http.get(`Roles/${this.$params.id}`) + this.$http.get(`VnRoles/${this.$params.id}`) .then(res => this.role = res.data); } } diff --git a/modules/account/front/role/create/index.html b/modules/account/front/role/create/index.html index 02900d580..b747f7d00 100644 --- a/modules/account/front/role/create/index.html +++ b/modules/account/front/role/create/index.html @@ -1,6 +1,6 @@ @@ -12,13 +12,13 @@ diff --git a/modules/account/front/role/descriptor/index.js b/modules/account/front/role/descriptor/index.js index a1b578133..17b585cb7 100644 --- a/modules/account/front/role/descriptor/index.js +++ b/modules/account/front/role/descriptor/index.js @@ -11,7 +11,7 @@ class Controller extends Descriptor { } onDelete() { - return this.$http.delete(`Roles/${this.id}`) + return this.$http.delete(`VnRoles/${this.id}`) .then(() => this.$state.go('account.role')) .then(() => this.vnApp.showSuccess(this.$t('Role removed'))); } diff --git a/modules/account/front/role/main/index.html b/modules/account/front/role/main/index.html index 9d7e6e053..cfef28e57 100644 --- a/modules/account/front/role/main/index.html +++ b/modules/account/front/role/main/index.html @@ -1,6 +1,6 @@ @@ -15,4 +15,4 @@ - \ No newline at end of file + diff --git a/modules/account/front/role/subroles/index.html b/modules/account/front/role/subroles/index.html index bc554b9f9..eba1002b0 100644 --- a/modules/account/front/role/subroles/index.html +++ b/modules/account/front/role/subroles/index.html @@ -33,14 +33,14 @@ ng-click="$ctrl.onAddClick()" fixed-bottom-right> - @@ -49,7 +49,7 @@
- this.$.summary = res.data); } diff --git a/modules/account/front/search-panel/index.html b/modules/account/front/search-panel/index.html index f80b537aa..a539d9657 100644 --- a/modules/account/front/search-panel/index.html +++ b/modules/account/front/search-panel/index.html @@ -19,7 +19,7 @@ vn-one label="Role" ng-model="filter.roleFk" - url="Roles" + url="VnRoles" value-field="id" show-field="name"> @@ -28,4 +28,4 @@ - \ No newline at end of file + From ab69dcd4fe5c182f71713de516ff12c40a29a792 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 30 Nov 2023 12:32:41 +0100 Subject: [PATCH 081/207] refs #6524 fix: fixtures and feat: new changelog format --- CHANGELOG.md | 13 ++++++------- db/dump/fixtures.sql | 4 ++++ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f16511b6..70174ede3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,14 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [2348.01] - 2023-11-30 -### Added -- (Ticket -> Adelantar) Permite mover lineas sin generar negativos -- (Ticket -> Adelantar) Permite modificar la fecha de los tickets -- (Trabajadores -> Notificaciones) Nueva sección (lilium) +### Características Añadidas 🆕 +- **Tickets → Adelantar:** Permite mover lineas sin generar negativos +- **Tickets → Adelantar:** Permite modificar la fecha de los tickets +- **Trabajadores → Notificaciones:** Nueva sección (lilium) -### Changed -### Fixed -- (Ticket -> RocketChat) Arreglada detección de cambios +### Correcciones 🛠️ +- **Tickets → RocketChat:** Arreglada detección de cambios ## [2346.01] - 2023-11-16 diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 788487ed0..d9eed401e 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -1,6 +1,10 @@ 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'; From 8ab981907d2f1db8b702883e5790a8c01cf247c5 Mon Sep 17 00:00:00 2001 From: davidd Date: Thu, 30 Nov 2023 14:25:00 +0100 Subject: [PATCH 082/207] refactor(ticketTracking.userFk): refs #6398 workerFk to userFk --- db/changes/235001/00-alterTable.sql | 1 + db/changes/235001/01-procedures.sql | 1129 +++++++++++++++++ db/changes/235001/02-views.sql | 34 + db/dump/fixtures.sql | 3 +- .../importToNewRefundTicket.js | 2 +- .../back/methods/ticket/specs/state.spec.js | 20 +- modules/ticket/back/methods/ticket/state.js | 4 +- modules/ticket/back/models/ticket-state.json | 10 +- modules/ticket/back/models/ticket-tracking.js | 2 +- .../ticket/back/models/ticket-tracking.json | 26 +- modules/ticket/front/tracking/index/index.js | 10 +- modules/zone/back/methods/zone/deleteZone.js | 2 +- 12 files changed, 1201 insertions(+), 42 deletions(-) create mode 100644 db/changes/235001/00-alterTable.sql create mode 100644 db/changes/235001/01-procedures.sql create mode 100644 db/changes/235001/02-views.sql diff --git a/db/changes/235001/00-alterTable.sql b/db/changes/235001/00-alterTable.sql new file mode 100644 index 000000000..b6974b715 --- /dev/null +++ b/db/changes/235001/00-alterTable.sql @@ -0,0 +1 @@ +ALTER TABLE `vn`.`ticketTracking` CHANGE `workerFk` `userFk` int(10) unsigned DEFAULT NULL NULL; \ No newline at end of file diff --git a/db/changes/235001/01-procedures.sql b/db/changes/235001/01-procedures.sql new file mode 100644 index 000000000..121348fbf --- /dev/null +++ b/db/changes/235001/01-procedures.sql @@ -0,0 +1,1129 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`order_confirmWithUser`(vSelf INT, vUserId INT) +BEGIN +/** + * Confirms an order, creating each of its tickets on the corresponding + * date, store and user. + * + * @param vSelf The order identifier + * @param vUser The user identifier + */ + DECLARE vOk BOOL; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vWarehouse INT; + DECLARE vShipment DATE; + DECLARE vTicket INT; + DECLARE vNotes VARCHAR(255); + DECLARE vItem INT; + DECLARE vConcept VARCHAR(30); + DECLARE vAmount INT; + DECLARE vPrice DECIMAL(10,2); + DECLARE vSale INT; + DECLARE vRate INT; + DECLARE vRowId INT; + DECLARE vPriceFixed DECIMAL(10,2); + DECLARE vDelivery DATE; + DECLARE vAddress INT; + DECLARE vIsConfirmed BOOL; + DECLARE vClientId INT; + DECLARE vCompanyId INT; + DECLARE vAgencyModeId INT; + DECLARE TICKET_FREE INT DEFAULT 2; + DECLARE vCalc INT; + DECLARE vIsLogifloraItem BOOL; + DECLARE vOldQuantity INT; + DECLARE vNewQuantity INT; + DECLARE vIsTaxDataChecked BOOL; + + DECLARE cDates CURSOR FOR + SELECT zgs.shipped, r.warehouse_id + FROM `order` o + JOIN order_row r ON r.order_id = o.id + LEFT JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = r.warehouse_id + WHERE o.id = vSelf AND r.amount != 0 + GROUP BY r.warehouse_id; + + DECLARE cRows CURSOR FOR + SELECT r.id, r.item_id, i.name, r.amount, r.price, r.rate, i.isFloramondo + FROM order_row r + JOIN vn.item i ON i.id = r.item_id + WHERE r.amount != 0 + AND r.warehouse_id = vWarehouse + AND r.order_id = vSelf + ORDER BY r.rate DESC; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + -- Carga los datos del pedido + SELECT o.date_send, o.address_id, o.note, a.clientFk, + o.company_id, o.agency_id, c.isTaxDataChecked + INTO vDelivery, vAddress, vNotes, vClientId, + vCompanyId, vAgencyModeId, vIsTaxDataChecked + FROM hedera.`order` o + JOIN vn.address a ON a.id = o.address_id + JOIN vn.client c ON c.id = a.clientFk + WHERE o.id = vSelf; + + -- Verifica si el cliente tiene los datos comprobados + IF NOT vIsTaxDataChecked THEN + CALL util.throw ('clientNotVerified'); + END IF; + + -- Carga las fechas de salida de cada almacen + CALL vn.zone_getShipped (vDelivery, vAddress, vAgencyModeId, FALSE); + + -- Trabajador que realiza la accion + IF vUserId IS NULL THEN + SELECT employeeFk INTO vUserId FROM orderConfig; + END IF; + + START TRANSACTION; + + CALL order_checkEditable(vSelf); + + -- Check order is not empty + + SELECT COUNT(*) > 0 INTO vOk + FROM order_row WHERE order_id = vSelf AND amount > 0; + + IF NOT vOk THEN + CALL util.throw ('ORDER_EMPTY'); + END IF; + + -- Crea los tickets del pedido + + OPEN cDates; + + lDates: + LOOP + SET vTicket = NULL; + SET vDone = FALSE; + FETCH cDates INTO vShipment, vWarehouse; + + IF vDone THEN + LEAVE lDates; + END IF; + + -- Busca un ticket existente que coincida con los parametros + WITH tPrevia AS + (SELECT DISTINCT s.ticketFk + FROM vn.sale s + JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id + JOIN vn.ticket t ON t.id = s.ticketFk + WHERE t.shipped BETWEEN vShipment AND util.dayend(vShipment) + ) + SELECT t.id INTO vTicket + FROM vn.ticket t + LEFT JOIN tPrevia tp ON tp.ticketFk = t.id + LEFT JOIN vn.ticketState tls on tls.ticket = t.id + JOIN hedera.`order` o + ON o.address_id = t.addressFk + AND vWarehouse = t.warehouseFk + AND o.date_send = t.landed + AND DATE(t.shipped) = vShipment + WHERE o.id = vSelf + AND t.refFk IS NULL + AND tp.ticketFk IS NULL + AND IFNULL(tls.alertLevel,0) = 0 + LIMIT 1; + + -- Crea el ticket en el caso de no existir uno adecuado + IF vTicket IS NULL + THEN + + SET vShipment = IFNULL(vShipment, util.VN_CURDATE()); + + CALL vn.ticket_add( + vClientId, + vShipment, + vWarehouse, + vCompanyId, + vAddress, + vAgencyModeId, + NULL, + vDelivery, + vUserId, + TRUE, + vTicket + ); + ELSE + INSERT INTO vn.ticketTracking + SET ticketFk = vTicket, + userFk = vUserId, + stateFk = TICKET_FREE; + END IF; + + INSERT IGNORE INTO vn.orderTicket + SET orderFk = vSelf, + ticketFk = vTicket; + + -- Añade las notas + + IF vNotes IS NOT NULL AND vNotes != '' + THEN + INSERT INTO vn.ticketObservation SET + ticketFk = vTicket, + observationTypeFk = 4 /* salesperson */, + `description` = vNotes + ON DUPLICATE KEY UPDATE + `description` = CONCAT(VALUES(`description`),'. ', `description`); + END IF; + + -- Añade los movimientos y sus componentes + + OPEN cRows; + + lRows: LOOP + SET vDone = FALSE; + FETCH cRows INTO vRowId, vItem, vConcept, vAmount, vPrice, vRate, vIsLogifloraItem; + + IF vDone THEN + LEAVE lRows; + END IF; + + SET vSale = NULL; + + SELECT s.id, s.quantity INTO vSale, vOldQuantity + FROM vn.sale s + WHERE ticketFk = vTicket + AND price = vPrice + AND itemFk = vItem + AND discount = 0 + LIMIT 1; + + IF vSale THEN + UPDATE vn.sale + SET quantity = quantity + vAmount, + originalQuantity = quantity + WHERE id = vSale; + + SELECT s.quantity INTO vNewQuantity + FROM vn.sale s + WHERE id = vSale; + ELSE + -- Obtiene el coste + SELECT SUM(rc.`price`) valueSum INTO vPriceFixed + FROM orderRowComponent rc + JOIN vn.component c ON c.id = rc.componentFk + JOIN vn.componentType ct ON ct.id = c.typeFk AND ct.isBase + WHERE rc.rowFk = vRowId; + + INSERT INTO vn.sale + SET itemFk = vItem, + ticketFk = vTicket, + concept = vConcept, + quantity = vAmount, + price = vPrice, + priceFixed = vPriceFixed, + isPriceFixed = TRUE; + + SET vSale = LAST_INSERT_ID(); + + INSERT INTO vn.saleComponent + (saleFk, componentFk, `value`) + SELECT vSale, rc.componentFk, rc.price + FROM orderRowComponent rc + JOIN vn.component c ON c.id = rc.componentFk + WHERE rc.rowFk = vRowId + GROUP BY vSale, rc.componentFk; + END IF; + + UPDATE order_row SET Id_Movimiento = vSale + WHERE id = vRowId; + + -- Inserta en putOrder si la compra es de Floramondo + IF vIsLogifloraItem THEN + CALL cache.availableNoRaids_refresh(vCalc,FALSE,vWarehouse,vShipment); + + SET @available := 0; + + SELECT GREATEST(0,available) INTO @available + FROM cache.availableNoRaids + WHERE calc_id = vCalc + AND item_id = vItem; + + UPDATE cache.availableNoRaids + SET available = GREATEST(0,available - vAmount) + WHERE item_id = vItem + AND calc_id = vCalc; + + INSERT INTO edi.putOrder ( + deliveryInformationID, + supplyResponseId, + quantity , + EndUserPartyId, + EndUserPartyGLN, + FHAdminNumber, + saleFk + ) + SELECT di.ID, + i.supplyResponseFk, + CEIL((vAmount - @available)/ sr.NumberOfItemsPerCask), + o.address_id , + vClientId, + IFNULL(ca.fhAdminNumber, fhc.defaultAdminNumber), + vSale + FROM edi.deliveryInformation di + JOIN vn.item i ON i.supplyResponseFk = di.supplyResponseID + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + LEFT JOIN edi.clientFHAdminNumber ca ON ca.clientFk = vClientId + JOIN edi.floraHollandConfig fhc + JOIN hedera.`order` o ON o.id = vSelf + WHERE i.id = vItem + AND di.LatestOrderDateTime > util.VN_NOW() + AND vAmount > @available + LIMIT 1; + END IF; + END LOOP; + + CLOSE cRows; + END LOOP; + + CLOSE cDates; + + UPDATE `order` SET confirmed = TRUE, confirm_date = util.VN_NOW() + WHERE id = vSelf; + + COMMIT; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceOut_new`( + vSerial VARCHAR(255), + vInvoiceDate DATE, + vTaxArea VARCHAR(25), + OUT vNewInvoiceId INT) +BEGIN +/** + * Creación de facturas emitidas. + * requiere previamente tabla tmp.ticketToInvoice(id). + * + * @param vSerial serie a la cual se hace la factura + * @param vInvoiceDate fecha de la factura + * @param vTaxArea tipo de iva en relacion a la empresa y al cliente + * @param vNewInvoiceId id de la factura que se acaba de generar + * @return vNewInvoiceId + */ + DECLARE vIsAnySaleToInvoice BOOL; + DECLARE vIsAnyServiceToInvoice BOOL; + DECLARE vNewRef VARCHAR(255); + DECLARE vWorker INT DEFAULT account.myUser_getId(); + DECLARE vCompanyFk INT; + DECLARE vInterCompanyFk INT; + DECLARE vClientFk INT; + DECLARE vCplusStandardInvoiceTypeFk INT DEFAULT 1; + DECLARE vCplusCorrectingInvoiceTypeFk INT DEFAULT 6; + DECLARE vCplusSimplifiedInvoiceTypeFk INT DEFAULT 2; + DECLARE vCorrectingSerial VARCHAR(1) DEFAULT 'R'; + DECLARE vSimplifiedSerial VARCHAR(1) DEFAULT 'S'; + DECLARE vNewInvoiceInFk INT; + DECLARE vIsInterCompany BOOL DEFAULT FALSE; + DECLARE vIsCEESerial BOOL DEFAULT FALSE; + DECLARE vIsCorrectInvoiceDate BOOL; + DECLARE vMaxShipped DATE; + DECLARE vDone BOOL; + DECLARE vTicketFk INT; + DECLARE vCursor CURSOR FOR + SELECT id + FROM tmp.ticketToInvoice; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + SET vInvoiceDate = IFNULL(vInvoiceDate, util.VN_CURDATE()); + + SELECT t.clientFk, + t.companyFk, + MAX(DATE(t.shipped)), + DATE(vInvoiceDate) >= invoiceOut_getMaxIssued( + vSerial, + t.companyFk, + YEAR(vInvoiceDate)) + INTO vClientFk, + vCompanyFk, + vMaxShipped, + vIsCorrectInvoiceDate + FROM tmp.ticketToInvoice tt + JOIN ticket t ON t.id = tt.id; + + IF(vMaxShipped > vInvoiceDate) THEN + CALL util.throw("Invoice date can't be less than max date"); + END IF; + + IF NOT vIsCorrectInvoiceDate THEN + CALL util.throw('Exists an invoice with a previous date'); + END IF; + + -- Eliminem de tmp.ticketToInvoice els tickets que no han de ser facturats + DELETE ti.* + FROM tmp.ticketToInvoice ti + JOIN ticket t ON t.id = ti.id + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + JOIN supplier su ON su.id = t.companyFk + JOIN client c ON c.id = t.clientFk + LEFT JOIN itemTaxCountry itc ON itc.itemFk = i.id AND itc.countryFk = su.countryFk + WHERE (YEAR(t.shipped) < 2001 AND t.isDeleted) + OR c.isTaxDataChecked = FALSE + OR t.isDeleted + OR c.hasToInvoice = FALSE + OR itc.id IS NULL; + + SELECT SUM(s.quantity * s.price * (100 - s.discount)/100) <> 0 + INTO vIsAnySaleToInvoice + FROM tmp.ticketToInvoice t + JOIN sale s ON s.ticketFk = t.id; + + SELECT COUNT(*) > 0 INTO vIsAnyServiceToInvoice + FROM tmp.ticketToInvoice t + JOIN ticketService ts ON ts.ticketFk = t.id; + + IF (vIsAnySaleToInvoice OR vIsAnyServiceToInvoice) + AND (vCorrectingSerial = vSerial OR NOT hasAnyNegativeBase()) + THEN + + -- el trigger añade el siguiente Id_Factura correspondiente a la vSerial + INSERT INTO invoiceOut( + ref, + serial, + issued, + clientFk, + dued, + companyFk, + siiTypeInvoiceOutFk + ) + SELECT + 1, + vSerial, + vInvoiceDate, + vClientFk, + getDueDate(vInvoiceDate, dueDay), + vCompanyFk, + IF(vSerial = vCorrectingSerial, + vCplusCorrectingInvoiceTypeFk, + IF(vSerial = vSimplifiedSerial, + vCplusSimplifiedInvoiceTypeFk, + vCplusStandardInvoiceTypeFk)) + FROM client + WHERE id = vClientFk; + + SET vNewInvoiceId = LAST_INSERT_ID(); + + SELECT `ref` + INTO vNewRef + FROM invoiceOut + WHERE id = vNewInvoiceId; + + OPEN vCursor; + l: LOOP + SET vDone = FALSE; + FETCH vCursor INTO vTicketFk; + + IF vDone THEN + LEAVE l; + END IF; + + CALL ticket_recalc(vTicketFk, vTaxArea); + + END LOOP; + CLOSE vCursor; + + UPDATE ticket t + JOIN tmp.ticketToInvoice ti ON ti.id = t.id + SET t.refFk = vNewRef; + + DROP TEMPORARY TABLE IF EXISTS tmp.updateInter; + CREATE TEMPORARY TABLE tmp.updateInter ENGINE = MEMORY + SELECT s.id, ti.id ticket_id, vWorker Id_Trabajador + FROM tmp.ticketToInvoice ti + LEFT JOIN ticketState ts ON ti.id = ts.ticket + JOIN state s + WHERE IFNULL(ts.alertLevel, 0) < 3 and s.`code` = getAlert3State(ti.id); + + INSERT INTO ticketTracking(stateFk, ticketFk, userFk) + SELECT * FROM tmp.updateInter; + + CALL invoiceExpenceMake(vNewInvoiceId); + CALL invoiceTaxMake(vNewInvoiceId, vTaxArea); + + UPDATE invoiceOut io + JOIN ( + SELECT SUM(amount) total + FROM invoiceOutExpence + WHERE invoiceOutFk = vNewInvoiceId + ) base + JOIN ( + SELECT SUM(vat) total + FROM invoiceOutTax + WHERE invoiceOutFk = vNewInvoiceId + ) vat + SET io.amount = base.total + vat.total + WHERE io.id = vNewInvoiceId; + + DROP TEMPORARY TABLE tmp.updateInter; + + SELECT COUNT(*), id + INTO vIsInterCompany, vInterCompanyFk + FROM company + WHERE clientFk = vClientFk; + + IF (vIsInterCompany) THEN + + INSERT INTO invoiceIn(supplierFk, supplierRef, issued, companyFk) + SELECT vCompanyFk, vNewRef, vInvoiceDate, vInterCompanyFk; + + SET vNewInvoiceInFk = LAST_INSERT_ID(); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + (KEY (ticketFk)) + ENGINE = MEMORY + SELECT id ticketFk + FROM tmp.ticketToInvoice; + + CALL `ticket_getTax`('NATIONAL'); + + SET @vTaxableBaseServices := 0.00; + SET @vTaxCodeGeneral := NULL; + + INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) + SELECT vNewInvoiceInFk, + @vTaxableBaseServices, + sub.expenceFk, + sub.taxTypeSageFk, + sub.transactionTypeSageFk + FROM ( + SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase, + i.expenceFk, + i.taxTypeSageFk, + i.transactionTypeSageFk, + @vTaxCodeGeneral := i.taxClassCodeFk + FROM tmp.ticketServiceTax tst + JOIN invoiceOutTaxConfig i ON i.taxClassCodeFk = tst.code + WHERE i.isService + HAVING taxableBase + ) sub; + + INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) + SELECT vNewInvoiceInFk, + SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral, + @vTaxableBaseServices, 0) taxableBase, + i.expenceFk, + i.taxTypeSageFk , + i.transactionTypeSageFk + FROM tmp.ticketTax tt + JOIN invoiceOutTaxConfig i ON i.taxClassCodeFk = tt.code + WHERE !i.isService + GROUP BY tt.pgcFk + HAVING taxableBase + ORDER BY tt.priority; + + CALL invoiceInDueDay_calculate(vNewInvoiceInFk); + + SELECT COUNT(*) INTO vIsCEESerial + FROM invoiceOutSerial + WHERE code = vSerial; + + IF vIsCEESerial THEN + + INSERT INTO invoiceInIntrastat ( + invoiceInFk, + intrastatFk, + amount, + stems, + countryFk, + net) + SELECT + vNewInvoiceInFk, + i.intrastatFk, + SUM(CAST((s.quantity * s.price * (100 - s.discount) / 100 ) AS DECIMAL(10, 2))), + SUM(CAST(IFNULL(i.stems, 1) * s.quantity AS DECIMAL(10, 2))), + su.countryFk, + CAST(SUM(IFNULL(i.stems, 1) + * s.quantity + * IF(ic.grams, ic.grams, IFNULL(i.weightByPiece, 0)) / 1000) AS DECIMAL(10, 2)) + FROM sale s + JOIN ticket t ON s.ticketFk = t.id + JOIN supplier su ON su.id = t.companyFk + JOIN item i ON i.id = s.itemFk + LEFT JOIN itemCost ic ON ic.itemFk = i.id AND ic.warehouseFk = t.warehouseFk + WHERE t.refFk = vNewRef + GROUP BY i.intrastatFk; + + END IF; + DROP TEMPORARY TABLE tmp.ticket; + DROP TEMPORARY TABLE tmp.ticketAmount; + DROP TEMPORARY TABLE tmp.ticketTax; + DROP TEMPORARY TABLE tmp.ticketServiceTax; + END IF; + END IF; + DROP TEMPORARY TABLE `tmp`.`ticketToInvoice`; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`productionError_add`() +BEGIN + DECLARE vDatedFrom DATETIME; + DECLARE vDatedTo DATETIME; +/** + * Rellena la tabla vn.productionError con estadisticas de encajadores, revisores y sacadores. Se ejecuta en el nightTask + */ + SELECT util.VN_CURDATE() - INTERVAL 1 DAY, util.dayend(util.VN_CURDATE() - INTERVAL 1 DAY) INTO vDatedFrom, vDatedTo; + CALL timeControl_calculateAll(vDatedFrom, vDatedTo); + + -- Rellena la tabla tmp.errorsByClaim con encajadores, revisores y sacadores + CREATE OR REPLACE TEMPORARY TABLE tmp.errorsByClaim + ENGINE = MEMORY + SELECT COUNT(c.ticketFk) errors, + cd.workerFk + FROM claimDevelopment cd + JOIN claim c ON cd.claimFk = c.id + JOIN ticket t ON c.ticketFk = t.id + JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id + WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo + AND cr.code IN ('pic', 'chk', 'pck') + GROUP BY cd.workerFk; + + -- Genera la tabla tmp.volume con encajadores, sacadores y revisores + CREATE OR REPLACE TEMPORARY TABLE tmp.volume + ENGINE = MEMORY + SELECT SUM(w.volume) volume, + w.workerFk + FROM bs.workerProductivity w + WHERE w.dated BETWEEN vDatedFrom AND vDatedTo + GROUP BY w.workerFk; + + -- Rellena la tabla tmp.errorsByChecker con fallos de revisores + CREATE OR REPLACE TEMPORARY TABLE tmp.errorsByChecker + ENGINE = MEMORY + SELECT st.workerFk, + COUNT(t.id) errors + FROM saleMistake sm + JOIN saleTracking st ON sm.saleFk = st.saleFk + JOIN `state` s2 ON s2.id = st.stateFk + JOIN sale s ON s.id = sm.saleFk + JOIN ticket t on t.id = s.ticketFk + WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo) + AND s2.code IN ('OK','PREVIOUS_PREPARATION','PREPARED','CHECKED') + GROUP BY st.workerFk; + + -- Rellena la tabla tmp.expeditionErrors con fallos de expediciones + CREATE OR REPLACE TEMPORARY TABLE tmp.expeditionErrors + ENGINE = MEMORY + SELECT COUNT(t.id) errors, + e.workerFk + FROM vn.expeditionMistake pm + JOIN vn.expedition e ON e.id = pm.expeditionFk + JOIN vn.ticket t ON t.id = e.ticketFk + WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo + GROUP BY e.workerFk; + + -- Genera la tabla tmp.total para sacadores y revisores + CREATE OR REPLACE TEMPORARY TABLE tmp.total + ENGINE = MEMORY + SELECT st.workerFk, + COUNT(DISTINCT t.id) ticketCount, + COUNT(s.id) lineCount + FROM saleTracking st + JOIN `state` s2 ON s2.id = st.stateFk + JOIN sale s ON s.id = st.saleFk + JOIN ticket t ON s.ticketFk = t.id + WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo) + AND s2.code IN ('OK','PREVIOUS_PREPARATION','PREPARED','CHECKED') + GROUP BY st.workerFk; + + -- Rellena la tabla vn.productionError con sacadores + INSERT INTO productionError(userFk, + firstname, + lastname, + rol, + ticketNumber, + lineNumber, + error, + volume, + hourStart, + hourEnd, + hourWorked, + dated) + SELECT w.id, + w.firstName, + w.lastName, + "Sacadores", + t.ticketCount totalTickets, + t.lineCount, + IFNULL(ec.errors,0) + IFNULL(ec2.errors,0) errors, + v.volume volume, + SUBSTRING(tc.tableTimed, 1, 5) hourStart, + SUBSTRING(tc.tableTimed, LENGTH(tc.tableTimed)-4, 5) hourEnd, + IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) hourWorked, + vDatedFrom dated + FROM tmp.total t + LEFT JOIN worker w ON w.id = t.workerFk + LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = t.workerFk + LEFT JOIN tmp.errorsByClaim ec ON ec.workerFk = t.workerFk + LEFT JOIN tmp.volume v ON v.workerFk = t.workerFk + LEFT JOIN tmp.errorsByChecker ec2 ON ec2.workerFk = t.workerFk + JOIN (SELECT DISTINCT w.id -- Verificamos que son sacadores + FROM vn.collection c + JOIN vn.state s ON s.id = c.stateFk + JOIN vn.train tn ON tn.id = c.trainFk + JOIN vn.worker w ON w.id = c.workerFk + WHERE c.created BETWEEN vDatedFrom AND vDatedTo) sub ON sub.id = w.id + GROUP BY w.id; + + CREATE OR REPLACE TEMPORARY TABLE itemPickerErrors -- Errores de los sacadores, derivadores de los revisadores + ENGINE = MEMORY + SELECT COUNT(c.ticketFk) errors, + tt.userFk + FROM claimDevelopment cd + JOIN claim c ON cd.claimFk = c.id + JOIN ticket t ON c.ticketFk = t.id + JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id + JOIN ticketTracking tt ON tt.ticketFk = t.id + JOIN `state` s ON s.id = tt.stateFk + WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo + AND cr.code = 'chk' + AND s.code = 'ON_PREPARATION' + GROUP BY tt.userFk; + + UPDATE productionError ep + JOIN itemPickerErrors ipe ON ipe.workerFk = ep.userFk + SET ep.error = ep.error + ipe.errors + WHERE vDatedFrom = ep.dated AND ep.rol = 'Sacadores'; + + DROP TEMPORARY TABLE itemPickerErrors; + + -- Rellena la tabla vn.productionError con revisores + CALL productionError_addCheckerPackager(vDatedFrom, vDatedTo, "Revisadores"); + + -- Genera la tabla tmp.total para encajadores + CREATE OR REPLACE TEMPORARY TABLE tmp.total + ENGINE = MEMORY + SELECT e.workerFk, + COUNT(DISTINCT t.id) ticketCount, + COUNT(s.id) lineCount + FROM expedition e + JOIN ticket t ON e.ticketFk = t.id + JOIN sale s ON s.ticketFk = t.id + WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo + GROUP BY e.workerFk; + + -- Rellena la tabla vn.productionError con encajadores + CALL productionError_addCheckerPackager(vDatedFrom, vDatedTo, "Encajadores"); + + DROP TEMPORARY TABLE tmp.errorsByClaim, + tmp.volume, + tmp.errorsByChecker, + tmp.expeditionErrors, + tmp.total; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sectorProductivity_add`() +BEGIN + DECLARE vDatedFrom DATETIME; + DECLARE vDatedTo DATETIME; + + SELECT DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY), CONCAT(DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY),' 23:59:59') INTO vDatedFrom, vDatedTo; + + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate; + DROP TEMPORARY TABLE IF EXISTS tmp.errorsByChecker; + DROP TEMPORARY TABLE IF EXISTS tmp.previousErrors; + + CALL timeControl_calculateAll(vDatedFrom, vDatedTo); + + CREATE TEMPORARY TABLE tmp.errorsByChecker + ENGINE = MEMORY + SELECT sc.userFk workerFk, COUNT(DISTINCT s.ticketFk) errorsByChecker + FROM saleMistake sm + JOIN vn.saleGroupDetail sgd on sgd.saleFk = sm.saleFk + JOIN vn.sectorCollectionSaleGroup scsg on scsg.saleGroupFk = sgd.saleGroupFk + JOIN vn.sectorCollection sc on sc.id = scsg.sectorCollectionFk + JOIN sale s ON s.id = sm.saleFk + JOIN ticket t on t.id = s.ticketFk + WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo) + GROUP BY sc.userFk ; + + CREATE TEMPORARY TABLE tmp.previousErrors -- Errores de previa, derivadores de los revisadores (por reclamación) + ENGINE = MEMORY + SELECT tt.userFk, COUNT(c.ticketFk) errorsByClaim + FROM claimDevelopment cd + JOIN claim c ON cd.claimFk = c.id + JOIN ticket t ON c.ticketFk = t.id + JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id + JOIN ticketTracking tt ON tt.ticketFk = t.id + JOIN `state` s ON s.id = tt.stateFk + WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND cr.description = 'Revisadores' AND s.code = 'OK PREVIOUS' + GROUP BY cd.workerFk; + + DELETE FROM sectorProductivity + WHERE dated = vDatedFrom + AND sector IN ('Algemesi Artificial','Algemesi Complementos'); + + INSERT INTO sectorProductivity(workerFk, firstName, lastName, sector, ticketCount, saleCount, error, volume, hourWorked, dated) + SELECT w.id workerFk, + w.firstName, + w.lastName, + se.description sector, + COUNT(DISTINCT s.ticketFk) ticketCount, + COUNT(sgd.id) saleCount, + IFNULL(ec2.errorsByChecker,0) + IFNULL(pe.errorsByClaim, 0) errors, + wp.volume, + IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) AS hourWorked, + DATE(vDatedFrom) dated + FROM vn.saleGroupDetail sgd + JOIN vn.saleGroup sg on sg.id = sgd.saleGroupFk + JOIN vn.sectorCollectionSaleGroup scsg on scsg.saleGroupFk = sgd.saleGroupFk + JOIN vn.sectorCollection sc on sc.id = scsg.sectorCollectionFk + join vn.sector se on se.id = sc.sectorFk + JOIN vn.worker w ON w.id = sc.userFk + LEFT JOIN vn.sale s ON s.id = sgd.saleFk + LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = w.id + LEFT JOIN bs.workerProductivity wp ON wp.workerFk = w.id + LEFT JOIN `state` s2 ON s2.id = wp.stateFk AND s2.code = 'OK PREVIOUS' + LEFT JOIN tmp.errorsByChecker ec2 ON ec2.workerFk = w.id + LEFT JOIN tmp.previousErrors pe ON pe.workerFk = w.id + WHERE DATE(sc.created) = vDatedFrom + AND wp.dated = vDatedFrom + GROUP BY w.id; + + DROP TEMPORARY TABLE tmp.timeControlCalculate; + DROP TEMPORARY TABLE tmp.errorsByChecker; + DROP TEMPORARY TABLE tmp.previousErrors; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketStateUpdate`(vTicketFk INT, vStateCode VARCHAR(45)) +BEGIN + + /* + * @deprecated:utilizar ticket_setState + */ + + DECLARE vAlertLevel INT; + + SELECT s.alertLevel INTO vAlertLevel + FROM vn.state s + JOIN vn.ticketState ts ON ts.stateFk = s.id + WHERE ts.ticketFk = vTicketFk; + + IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN + + INSERT INTO ticketTracking(stateFk, ticketFk, userFk) + SELECT id, vTicketFk, account.myUser_getId() + FROM vn.state + WHERE `code` = vStateCode collate utf8_unicode_ci; + + END IF; + +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_Clone`(vOriginalTicket INT, OUT vNewTicket INT) +BEGIN +/** + * Clona el contenido de un ticket en otro + * + * @param vOriginalTicket ticket Original + * @param vNewTicket ticket creado + */ + DECLARE vStateFk INT; + + INSERT INTO ticket ( + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + warehouseFk, + companyFk, + landed, + zoneFk, + zonePrice, + zoneBonus, + routeFk, + priority, + hasPriority, + clonedFrom + ) + SELECT + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + warehouseFk, + companyFk, + landed, + zoneFk, + zonePrice, + zoneBonus, + routeFk, + priority, + hasPriority, + vOriginalTicket + FROM ticket + WHERE id = vOriginalTicket; + + SET vNewTicket = LAST_INSERT_ID(); + + INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) + SELECT vNewTicket, observationTypeFk, description + FROM ticketObservation + WHERE ticketFk = vOriginalTicket; + + INSERT INTO ticketTracking(ticketFk, stateFk, userFk, created) + SELECT vNewTicket, stateFk, userFk, created + FROM ticketTracking + WHERE ticketFk = vOriginalTicket + ORDER BY created; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_add`( + vClientId INT + ,vShipped DATE + ,vWarehouseFk INT + ,vCompanyFk INT + ,vAddressFk INT + ,vAgencyModeFk INT + ,vRouteFk INT + ,vlanded DATE + ,vUserId INT + ,vIsRequiredZone INT + ,OUT vNewTicket INT) +BEGIN +/** +* Crea un ticket, +* ¡¡NO se debe llamar directamente, llamar a salix que hace comprobaciones previas!! +* +* @param vClientId id del cliente +* @param vShipped dia preparacion +* @param vWarehouseFk id del warehouse +* @param vCompanyFk id la empresa +* @param vAddressFk id del consignatario +* @param vAgencyModeFk id de la agencia +* @param vRouteFk id de la ruta | NULL +* @param vlanded dia llegada +* @param vUserId que crea el ticket +* @param vIsRequiredZone Indica si tiene que tener zona valida para ser creado +* @return vNewTicket id del ticket creado +*/ + DECLARE vZoneFk INT; + DECLARE vPrice DECIMAL(10,2); + DECLARE vBonus DECIMAL(10,2); + DECLARE vIsActive BOOL; + + IF vClientId IS NULL THEN + CALL util.throw ('CLIENT_NOT_ESPECIFIED'); + END IF; + + SELECT isActive INTO vIsActive + FROM vn.client + WHERE id = vClientId; + + IF NOT vIsActive THEN + CALL util.throw ('CLIENT_NOT_ACTIVE'); + END IF; + + IF NOT vAddressFk OR vAddressFk IS NULL THEN + SELECT id INTO vAddressFk + FROM address + WHERE clientFk = vClientId + AND isDefaultAddress; + END IF; + + IF vAgencyModeFk IS NOT NULL THEN + CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE); + + SELECT zoneFk, price, bonus + INTO vZoneFk, vPrice, vBonus + FROM tmp.zoneGetShipped + WHERE shipped = vShipped + AND warehouseFk = vWarehouseFk + LIMIT 1; + + IF (vZoneFk IS NULL OR vZoneFk = 0) AND vIsRequiredZone THEN + CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS'); + END IF; + END IF; + + INSERT INTO ticket ( + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + warehouseFk, + routeFk, + companyFk, + landed, + zoneFk, + zonePrice, + zoneBonus + ) + SELECT vClientId, + vShipped, + a.id, + vAgencyModeFk, + a.nickname, + vWarehouseFk, + IF(vRouteFk,vRouteFk,NULL), + vCompanyFk, + vlanded, + vZoneFk, + vPrice, + vBonus + FROM address a + JOIN agencyMode am ON am.id = a.agencyModeFk + WHERE a.id = vAddressFk; + + SET vNewTicket = LAST_INSERT_ID(); + + INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) + SELECT vNewTicket, ao.observationTypeFk, ao.description + FROM addressObservation ao + JOIN address a ON a.id = ao.addressFk + WHERE a.id = vAddressFk; + + IF (SELECT COUNT(*) + FROM bs.clientNewBorn cnb + WHERE cnb.clientFk = vClientId + AND NOT cnb.isRookie) = 0 THEN + + CALL vn.ticketObservation_addNewBorn(vNewTicket); + END IF; + + IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN + INSERT INTO ticketTracking(stateFk, ticketFk, userFk) + SELECT id, vNewTicket, account.myUser_getId() + FROM state + WHERE `code` = 'DELIVERED'; + END IF; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setNextState`(vSelf INT) +BEGIN +/** + * Cambia el estado del ticket al siguiente estado según la tabla state + * + * @param vSelf id dle ticket + */ + DECLARE vStateFk INT; + DECLARE vNewStateFk INT; + + SELECT stateFk INTO vStateFk + FROM ticketState + WHERE ticketFk = vSelf; + + SELECT nextStateFk INTO vNewStateFk + FROM state + WHERE id = vStateFk; + + INSERT INTO ticketTracking(stateFk, ticketFk, userFk) + VALUES (vNewStateFk, vSelf, account.myUser_getId()); +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setPreviousState`(vTicketFk INT) +BEGIN + DECLARE vControlFk INT; + + SELECT MAX(id) INTO vControlFk + FROM ticketTracking + WHERE ticketFk = vTicketFk; + + IF (SELECT s.code + FROM vn.state s + JOIN ticketTracking tt ON tt.stateFk = s.id + WHERE tt.id = vControlFk) + = 'PREVIOUS_PREPARATION' THEN + SELECT id + INTO vControlFk + FROM ticketTracking tt + JOIN vn.state s ON tt.stateFk = s.id + WHERE ticketFk = vTicketFk + AND id < vControlFk + AND s.code != 'PREVIOUS_PREPARATION' + ORDER BY id DESC + LIMIT 1; + + INSERT INTO ticketTracking(stateFk, ticketFk, userFk) + SELECT s.nextStateFk, tt.ticketFk, account.myUser_getId() + FROM ticketTracking tt + JOIN vn.state s ON tt.stateFk = s.id + WHERE id = vControlFk; + END IF; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setState`( + vSelf INT, + vStateCode VARCHAR(255) COLLATE utf8_general_ci +) +BEGIN +/** + * Modifica el estado de un ticket si se cumplen las condiciones necesarias. + * + * @param vSelf el id del ticket + * @param vStateCode estado a modificar del ticket + */ + DECLARE vticketAlertLevel INT; + DECLARE vTicketStateCode VARCHAR(255); + DECLARE vCanChangeState BOOL; + DECLARE vPackedAlertLevel INT; + DECLARE vZoneFk INT; + + SELECT s.alertLevel, s.`code`, t.zoneFk + INTO vticketAlertLevel, vTicketStateCode, vZoneFk + FROM state s + JOIN ticketTracking tt ON tt.stateFk = s.id + JOIN ticket t ON t.id = tt.ticketFk + WHERE tt.ticketFk = vSelf + ORDER BY tt.created DESC + LIMIT 1; + + SELECT id INTO vPackedAlertLevel FROM alertLevel WHERE code = 'PACKED'; + + IF vStateCode = 'OK' AND vZoneFk IS NULL THEN + CALL util.throw('ASSIGN_ZONE_FIRST'); + END IF; + + SET vCanChangeState = ( + vStateCode <> 'ON_CHECKING' OR + vticketAlertLevel < vPackedAlertLevel + )AND NOT ( + vTicketStateCode IN ('CHECKED', 'CHECKING') + AND vStateCode IN ('PREPARED', 'ON_PREPARATION') + ); + + IF vCanChangeState THEN + INSERT INTO ticketTracking (stateFk, ticketFk, userFk) + SELECT id, vSelf, account.myUser_getId() + FROM state + WHERE `code` = vStateCode COLLATE utf8_unicode_ci; + + IF vStateCode = 'PACKED' THEN + CALL ticket_doCmr(vSelf); + END IF; + ELSE + CALL util.throw('INCORRECT_TICKET_STATE'); + END IF; +END$$ +DELIMITER ; diff --git a/db/changes/235001/02-views.sql b/db/changes/235001/02-views.sql new file mode 100644 index 000000000..d399bb3b4 --- /dev/null +++ b/db/changes/235001/02-views.sql @@ -0,0 +1,34 @@ +CREATE OR REPLACE DEFINER=`root`@`localhost` + SQL SECURITY DEFINER + VIEW `vn`.`ticketState` +AS SELECT `tt`.`created` AS `updated`, + `tt`.`stateFk` AS `stateFk`, + `tt`.`userFk` AS `userFk`, + `tls`.`ticketFk` AS `ticketFk`, + `s`.`id` AS `state`, + `s`.`order` AS `productionOrder`, + `s`.`alertLevel` AS `alertLevel`, + `s`.`code` AS `code`, + `tls`.`ticketFk` AS `ticket`, + `tt`.`userFk` AS `worker`, + `s`.`isPreviousPreparable` AS `isPreviousPreparable`, + `s`.`isPicked` AS `isPicked` +FROM ( + ( + `vn`.`ticketLastState` `tls` + JOIN `vn`.`ticketTracking` `tt` ON(`tt`.`id` = `tls`.`ticketTrackingFk`) + ) + JOIN `vn`.`state` `s` ON(`s`.`id` = `tt`.`stateFk`) + ); + +CREATE OR REPLACE DEFINER=`root`@`localhost` + SQL SECURITY DEFINER + VIEW `vn2008`.`v_inter` +AS SELECT `tt`.`id` AS `inter_id`, + `tt`.`stateFk` AS `state_id`, + `tt`.`notes` AS `nota`, + `tt`.`created` AS `odbc_date`, + `tt`.`ticketFk` AS `Id_Ticket`, + `tt`.`userFk` AS `Id_Trabajador`, + `tt`.`supervisorFk` AS `Id_supervisor` +FROM `vn`.`ticketTracking` `tt`; diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 788487ed0..dc37b76f9 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -767,7 +767,7 @@ INSERT INTO `vn`.`ticketObservation`(`id`, `ticketFk`, `observationTypeFk`, `des -- FIX for state hours on local, inter_afterInsert -- UPDATE vncontrol.inter SET odbc_date = DATE_ADD(util.VN_CURDATE(), INTERVAL -10 SECOND); -INSERT INTO `vn`.`ticketTracking`(`ticketFk`, `stateFk`, `workerFk`, `created`) +INSERT INTO `vn`.`ticketTracking`(`ticketFk`, `stateFk`, `userFk`, `created`) VALUES (1, 16, 5 , DATE_ADD(util.VN_NOW(), INTERVAL -1 MONTH)), (2, 16, 5 , DATE_ADD(util.VN_NOW(), INTERVAL -1 MONTH)), @@ -811,6 +811,7 @@ INSERT INTO `vn`.`config`(`id`, `mdbServer`, `fakeEmail`, `defaultersMaxAmount`, VALUES (1, 'beta-server', 'nightmare@mydomain.com', '200', DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH)); + INSERT INTO `vn`.`greugeType`(`id`, `name`, `code`) VALUES (1, 'Diff', 'diff'), diff --git a/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js b/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js index be3baccd7..a01590f58 100644 --- a/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js +++ b/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js @@ -123,7 +123,7 @@ module.exports = Self => { await models.TicketTracking.create({ ticketFk: newRefundTicket.id, stateFk: state.id, - workerFk: worker.id + userFk: worker.id }, myOptions); const salesToRefund = await models.ClaimBeginning.find(salesFilter, myOptions); diff --git a/modules/ticket/back/methods/ticket/specs/state.spec.js b/modules/ticket/back/methods/ticket/specs/state.spec.js index 9b5e80165..f369932de 100644 --- a/modules/ticket/back/methods/ticket/specs/state.spec.js +++ b/modules/ticket/back/methods/ticket/specs/state.spec.js @@ -94,10 +94,10 @@ describe('ticket state()', () => { const ticketTracking = await models.Ticket.state(ctx, params, options); - expect(ticketTracking.__data.ticketFk).toBe(params.ticketFk); - expect(ticketTracking.__data.stateFk).toBe(params.stateFk); - expect(ticketTracking.__data.workerFk).toBe(49); - expect(ticketTracking.__data.id).toBeDefined(); + expect(ticketTracking.ticketFk).toBe(params.ticketFk); + expect(ticketTracking.stateFk).toBe(params.stateFk); + expect(ticketTracking.userFk).toBe(49); + expect(ticketTracking.id).toBeDefined(); await tx.rollback(); } catch (e) { @@ -116,14 +116,14 @@ describe('ticket state()', () => { const ticket = await models.Ticket.create(sampleTicket, options); const ctx = {req: {accessToken: {userId: 18}}}; const assignedState = await models.State.findOne({where: {code: 'PICKER_DESIGNED'}}, options); - const params = {ticketFk: ticket.id, stateFk: assignedState.id, workerFk: 1}; + const params = {ticketFk: ticket.id, stateFk: assignedState.id, userFk: 1}; const res = await models.Ticket.state(ctx, params, options); - expect(res.__data.ticketFk).toBe(params.ticketFk); - expect(res.__data.stateFk).toBe(params.stateFk); - expect(res.__data.workerFk).toBe(params.workerFk); - expect(res.__data.workerFk).toBe(1); - expect(res.__data.id).toBeDefined(); + expect(res.ticketFk).toBe(params.ticketFk); + expect(res.stateFk).toBe(params.stateFk); + expect(res.userFk).toBe(params.userFk); + expect(res.userFk).toBe(1); + expect(res.id).toBeDefined(); await tx.rollback(); } catch (e) { 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, { diff --git a/modules/ticket/back/models/ticket-state.json b/modules/ticket/back/models/ticket-state.json index a10938ef0..3ee50fac0 100644 --- a/modules/ticket/back/models/ticket-state.json +++ b/modules/ticket/back/models/ticket-state.json @@ -33,10 +33,10 @@ "model": "State", "foreignKey": "stateFk" }, - "worker": { - "type": "belongsTo", - "model": "Worker", - "foreignKey": "workerFk" - } + "user": { + "type": "belongsTo", + "model": "VnUser", + "foreignKey": "userFk" + } } } diff --git a/modules/ticket/back/models/ticket-tracking.js b/modules/ticket/back/models/ticket-tracking.js index 92e046d3e..72e1880b9 100644 --- a/modules/ticket/back/models/ticket-tracking.js +++ b/modules/ticket/back/models/ticket-tracking.js @@ -2,5 +2,5 @@ module.exports = function(Self) { require('../methods/ticket-tracking/setDelivered')(Self); Self.validatesPresenceOf('stateFk', {message: 'State cannot be blank'}); - Self.validatesPresenceOf('workerFk', {message: 'Worker cannot be blank'}); + Self.validatesPresenceOf('userFk', {message: 'Worker cannot be blank'}); }; diff --git a/modules/ticket/back/models/ticket-tracking.json b/modules/ticket/back/models/ticket-tracking.json index 8b5ce0b64..8b0617145 100644 --- a/modules/ticket/back/models/ticket-tracking.json +++ b/modules/ticket/back/models/ticket-tracking.json @@ -8,21 +8,21 @@ }, "properties": { "id": { - "id": true, - "type": "number", - "forceId": false + "id": true, + "type": "number", + "forceId": false }, "created": { - "type": "date" + "type": "date" }, "ticketFk": { - "type": "number" + "type": "number" }, "stateFk": { - "type": "number" + "type": "number" }, - "workerFk": { - "type": "number" + "userFk": { + "type": "number" } }, "relations": { @@ -36,10 +36,10 @@ "model": "State", "foreignKey": "stateFk" }, - "worker": { - "type": "belongsTo", - "model": "Worker", - "foreignKey": "workerFk" - } + "user": { + "type": "belongsTo", + "model": "VnUser", + "foreignKey": "userFk" + } } } 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/zone/back/methods/zone/deleteZone.js b/modules/zone/back/methods/zone/deleteZone.js index 13d45428c..38e724cd3 100644 --- a/modules/zone/back/methods/zone/deleteZone.js +++ b/modules/zone/back/methods/zone/deleteZone.js @@ -64,7 +64,7 @@ module.exports = Self => { promises.push(models.TicketTracking.create({ ticketFk: ticket.id, stateFk: fixingState.id, - workerFk: worker.id + userFk: worker.id }, myOptions)); } } From 72283005b80ee3fab6dbb25daa1e1258846a28a5 Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 30 Nov 2023 14:43:14 +0100 Subject: [PATCH 083/207] remove(console.log): refs #3271 remove console.log --- modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js | 3 --- 1 file changed, 3 deletions(-) diff --git a/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js b/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js index d1c7f1fc4..7167b83de 100644 --- a/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js +++ b/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js @@ -51,9 +51,6 @@ describe('zone getEventsFiltered()', () => { dateTomorrow.setDate(dateTomorrow.getDate() + 1); const result = await models.Zone.getEventsFiltered(9, date, dateTomorrow, options); - console.log('dateTomorrow: ', dateTomorrow); - console.log('date: ', date); - console.log('result: ', result); expect(result.events.length).toEqual(1); expect(result.exclusions.length).toEqual(0); From e634a5e2139d8f948d9478f668e12b7c97a5b884 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 30 Nov 2023 15:15:40 +0100 Subject: [PATCH 084/207] refs #5914 feat: create getTaxBases and use in negatives and positives procedures --- db/changes/235001/00-getTaxBases.sql | 33 +++++++++++++++++++ .../235001/01-newHasAnyPositiveBase.sql | 28 ++++++++++++++++ .../235001/01-refactorHasAnyNegativeBase.sql | 28 ++++++++++++++++ db/dump/fixtures.sql | 13 ++++---- 4 files changed, 96 insertions(+), 6 deletions(-) create mode 100644 db/changes/235001/00-getTaxBases.sql create mode 100644 db/changes/235001/01-newHasAnyPositiveBase.sql create mode 100644 db/changes/235001/01-refactorHasAnyNegativeBase.sql diff --git a/db/changes/235001/00-getTaxBases.sql b/db/changes/235001/00-getTaxBases.sql new file mode 100644 index 000000000..fa43c32f7 --- /dev/null +++ b/db/changes/235001/00-getTaxBases.sql @@ -0,0 +1,33 @@ +DELIMITER $$ +$$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`getTaxBases`() +BEGIN + +/* Calcula y devuelve en número de bases imponibles postivas y negativas +* Requiere la tabla temporal tmp.ticketToInvoice(id) +* +* returns tmp.taxBases +*/ + + CREATE OR REPLACE TEMPORARY TABLE tmp.ticket + (KEY (ticketFk)) + ENGINE = MEMORY + SELECT id ticketFk + FROM tmp.ticketToInvoice; + + CALL ticket_getTax(NULL); + + DROP TEMPORARY TABLE IF EXISTS tmp.taxBases; + CREATE TEMPORARY TABLE tmp.taxBases + ENGINE = MEMORY + SELECT + SUM(CASE WHEN taxableBase > 0 THEN 1 ELSE 0 END) as positive, + SUM(CASE WHEN taxableBase < 0 THEN 1 ELSE 0 END) as negative + FROM( + SELECT SUM(taxableBase) as taxableBase + FROM tmp.ticketTax + GROUP BY pgcFk + ) t; + +END$$ +DELIMITER ; diff --git a/db/changes/235001/01-newHasAnyPositiveBase.sql b/db/changes/235001/01-newHasAnyPositiveBase.sql new file mode 100644 index 000000000..c9e7e8e05 --- /dev/null +++ b/db/changes/235001/01-newHasAnyPositiveBase.sql @@ -0,0 +1,28 @@ +DELIMITER $$ +$$ +CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`hasAnyPositiveBase`() RETURNS tinyint(1) + DETERMINISTIC +BEGIN + +/* Calcula si existe alguna base imponible positiva +* Requiere la tabla temporal tmp.ticketToInvoice(id) para getTaxBases() +* +* returns BOOLEAN +*/ + + DECLARE hasAnyPositiveBase BOOLEAN; + + CALL getTaxBases(); + + SELECT positive > 0 INTO hasAnyPositiveBase + FROM tmp.taxBases; + + DROP TEMPORARY TABLE + tmp.ticketTax, + tmp.ticket, + tmp.taxBases; + + RETURN hasAnyPositiveBase; + +END$$ +DELIMITER ; diff --git a/db/changes/235001/01-refactorHasAnyNegativeBase.sql b/db/changes/235001/01-refactorHasAnyNegativeBase.sql new file mode 100644 index 000000000..b6780e280 --- /dev/null +++ b/db/changes/235001/01-refactorHasAnyNegativeBase.sql @@ -0,0 +1,28 @@ +DELIMITER $$ +$$ +CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`hasAnyNegativeBase`() RETURNS tinyint(1) + DETERMINISTIC +BEGIN + +/* Calcula si existe alguna base imponible negativa +* Requiere la tabla temporal tmp.ticketToInvoice(id) para getTaxBases() +* +* returns BOOLEAN +*/ + + DECLARE hasAnyNegativeBase BOOLEAN; + + CALL getTaxBases(); + + SELECT negative > 0 INTO hasAnyNegativeBase + FROM tmp.taxBases; + + DROP TEMPORARY TABLE + tmp.ticketTax, + tmp.ticket, + tmp.taxBases; + + RETURN hasAnyNegativeBase; + +END$$ +DELIMITER ; diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 788487ed0..ed0a30d14 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -598,18 +598,19 @@ INSERT INTO `vn`.`taxArea` (`code`, `claveOperacionFactura`, `CodigoTransaccion` INSERT INTO `vn`.`invoiceOutSerial` (`code`, `description`, `isTaxed`, `taxAreaFk`, `isCEE`, `type`) VALUES - ('A', 'Global nacional', 1, 'NATIONAL', 0, 'global'), - ('T', 'Española rapida', 1, 'NATIONAL', 0, 'quick'), - ('V', 'Intracomunitaria global', 0, 'CEE', 1, 'global'), - ('M', 'Múltiple nacional', 1, 'NATIONAL', 0, 'quick'), - ('E', 'Exportación rápida', 0, 'WORLD', 0, 'quick'); + ('A', 'Global nacional', 1, 'NATIONAL', 0, 'global'), + ('T', 'Española rapida', 1, 'NATIONAL', 0, 'quick'), + ('V', 'Intracomunitaria global', 0, 'CEE', 1, 'global'), + ('M', 'Múltiple nacional', 1, 'NATIONAL', 0, 'quick'), + ('R', 'Rectificativa', 1, 'NATIONAL', 0, NULL), + ('E', 'Exportación rápida', 0, 'WORLD', 0, 'quick'); INSERT INTO `vn`.`invoiceOut`(`id`, `serial`, `amount`, `issued`,`clientFk`, `created`, `companyFk`, `dued`, `booked`, `bankFk`, `hasPdf`) VALUES (1, 'T', 1026.24, util.VN_CURDATE(), 1101, util.VN_CURDATE(), 442, util.VN_CURDATE(), util.VN_CURDATE(), 1, 0), (2, 'T', 121.36, util.VN_CURDATE(), 1102, util.VN_CURDATE(), 442, util.VN_CURDATE(), util.VN_CURDATE(), 1, 0), (3, 'T', 8.88, util.VN_CURDATE(), 1103, util.VN_CURDATE(), 442, util.VN_CURDATE(), util.VN_CURDATE(), 1, 0), - (4, 'T', 8.88, util.VN_CURDATE(), 1103, util.VN_CURDATE(), 442, util.VN_CURDATE(), util.VN_CURDATE(), 1, 0), + (4, 'T', 8.88, util.VN_CURDATE(), 1104, util.VN_CURDATE(), 442, util.VN_CURDATE(), util.VN_CURDATE(), 1, 0), (5, 'A', 8.88, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1103, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 442, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 0); UPDATE `vn`.`invoiceOut` SET ref = 'T1111111' WHERE id = 1; From b2e7ea3089b24acfbc1dfbde612cbe7ee36940b5 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 30 Nov 2023 15:16:41 +0100 Subject: [PATCH 085/207] refs #5914 feat: make invoice support rectificative --- loopback/locale/es.json | 3 ++- .../back/methods/client/canBeInvoiced.js | 2 +- .../back/methods/invoiceOut/invoiceClient.js | 1 + .../invoiceOut/specs/transferinvoice.spec.js | 23 +++++++++++----- .../methods/invoiceOut/transferInvoice.js | 8 +++--- .../invoiceOut/front/descriptor-menu/index.js | 2 +- .../back/methods/sale/specs/refund.spec.js | 8 +++--- .../back/methods/ticket/canBeInvoiced.js | 16 ++++++++---- .../back/methods/ticket/invoiceTickets.js | 1 - .../ticket/back/methods/ticket/makeInvoice.js | 26 +++++++++++-------- .../ticket/specs/canBeInvoiced.spec.js | 8 +++--- .../ticket/specs/invoiceTickets.spec.js | 10 +++---- .../methods/ticket/specs/makeInvoice.spec.js | 4 +-- modules/ticket/front/descriptor-menu/index.js | 2 +- .../front/descriptor-menu/index.spec.js | 5 ++-- modules/ticket/front/sale/index.js | 2 +- modules/ticket/front/sale/index.spec.js | 2 +- 17 files changed, 72 insertions(+), 51 deletions(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 41acc36c3..71e0dc6af 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -328,5 +328,6 @@ "User disabled": "Usuario desactivado", "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" + "Cannot past travels with entries": "No se pueden pasar envíos con entradas", + "No tickets to invoice": "No hay tickets para facturar" } diff --git a/modules/client/back/methods/client/canBeInvoiced.js b/modules/client/back/methods/client/canBeInvoiced.js index 843e9549f..cdb865500 100644 --- a/modules/client/back/methods/client/canBeInvoiced.js +++ b/modules/client/back/methods/client/canBeInvoiced.js @@ -1,7 +1,7 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = function(Self) { - Self.remoteMethodCtx('canBeInvoiced', { + Self.remoteMethod('canBeInvoiced', { description: 'Change property isEqualizated in all client addresses', accessType: 'READ', accepts: [ diff --git a/modules/invoiceOut/back/methods/invoiceOut/invoiceClient.js b/modules/invoiceOut/back/methods/invoiceOut/invoiceClient.js index fa22dab1e..530b02353 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/invoiceClient.js +++ b/modules/invoiceOut/back/methods/invoiceOut/invoiceClient.js @@ -80,6 +80,7 @@ module.exports = Self => { invoiceType, args.companyFk, args.invoiceDate, + null, options ); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js index dea4b6d00..b3bd17826 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js @@ -23,20 +23,29 @@ describe('InvoiceOut tranferInvoice()', () => { const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; const args = { - id: '1', + id: '4', refFk: 'T4444444', newClientFk: 1, - cplusRectificationId: 1, - siiTypeInvoiceOutId: 1, - invoiceCorrectionTypeId: 1 + cplusRectificationTypeFk: 1, + siiTypeInvoiceOutFk: 1, + invoiceCorrectionTypeFk: 1 }; ctx.args = args; try { + const {clientFk: oldClient} = await models.InvoiceOut.findById(args.id, {fields: ['clientFk']}); + const invoicesBefore = await models.InvoiceOut.find({}, options); const result = await models.InvoiceOut.transferInvoice( ctx, options); + const invoicesAfter = await models.InvoiceOut.find({}, options); + const rectificativeInvoice = invoicesAfter[invoicesAfter.length - 2]; + const newInvoice = invoicesAfter[invoicesAfter.length - 1]; expect(result).toBeDefined(); + expect(invoicesAfter.length - invoicesBefore.length).toEqual(2); + expect(rectificativeInvoice.clientFk).toEqual(oldClient); + expect(newInvoice.clientFk).toEqual(args.newClientFk); + await tx.rollback(); } catch (e) { await tx.rollback(); @@ -51,9 +60,9 @@ describe('InvoiceOut tranferInvoice()', () => { id: '1', refFk: 'T1111111', newClientFk: 1101, - cplusRectificationId: 1, - siiTypeInvoiceOutId: 1, - invoiceCorrectionTypeId: 1 + cplusRectificationTypeFk: 1, + siiTypeInvoiceOutFk: 1, + invoiceCorrectionTypeFk: 1 }; ctx.args = args; try { diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js index dcdd9b9b1..5f2428539 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js @@ -22,7 +22,7 @@ module.exports = Self => { required: true }, { - arg: 'cplusRectificationFk', + arg: 'cplusRectificationTypeFk', type: 'number', required: true }, @@ -50,7 +50,7 @@ module.exports = Self => { Self.transferInvoice = async(ctx, options) => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; - const {id, refFk, newClientFk, cplusRectificationFk, siiTypeInvoiceOutFk, invoiceCorrectionTypeFk} = ctx.args; + const {id, refFk, newClientFk, cplusRectificationTypeFk, siiTypeInvoiceOutFk, invoiceCorrectionTypeFk} = ctx.args; let tx; if (typeof options == 'object') Object.assign(myOptions, options); @@ -87,11 +87,11 @@ module.exports = Self => { } const invoiceCorrection = - {correctedFk: id, cplusRectificationFk, siiTypeInvoiceOutFk, invoiceCorrectionTypeFk}; + {correctedFk: id, cplusRectificationTypeFk, siiTypeInvoiceOutFk, invoiceCorrectionTypeFk}; const refundTicketIds = refundTickets.map(ticket => ticket.id); await models.Ticket.invoiceTickets(ctx, refundTicketIds, invoiceCorrection, myOptions); - const [[invoiceId]] = await models.Ticket.invoiceTickets(ctx, clonedTicketIds, myOptions); + const [invoiceId] = await models.Ticket.invoiceTickets(ctx, clonedTicketIds, null, myOptions); if (tx) { await tx.commit(); diff --git a/modules/invoiceOut/front/descriptor-menu/index.js b/modules/invoiceOut/front/descriptor-menu/index.js index f9d436092..aee323e39 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.js +++ b/modules/invoiceOut/front/descriptor-menu/index.js @@ -131,7 +131,7 @@ class Controller extends Section { id: this.invoiceOut.id, refFk: this.invoiceOut.ref, newClientFk: this.clientId, - cplusRectificationFk: this.cplusRectificationType, + cplusRectificationTypeFk: this.cplusRectificationType, siiTypeInvoiceOutFk: this.siiTypeInvoiceOut, invoiceCorrectionTypeFk: this.invoiceCorrectionType }; diff --git a/modules/ticket/back/methods/sale/specs/refund.spec.js b/modules/ticket/back/methods/sale/specs/refund.spec.js index 08eb1fabd..60f77e90c 100644 --- a/modules/ticket/back/methods/sale/specs/refund.spec.js +++ b/modules/ticket/back/methods/sale/specs/refund.spec.js @@ -23,9 +23,9 @@ describe('Sale refund()', () => { try { const options = {transaction: tx}; - const refundedTicket = await models.Sale.refund(ctx, salesIds, servicesIds, withWarehouse, options); + const refundedTickets = await models.Sale.refund(ctx, salesIds, servicesIds, withWarehouse, options); - expect(refundedTicket).toBeDefined(); + expect(refundedTickets).toBeDefined(); await tx.rollback(); } catch (e) { @@ -42,11 +42,11 @@ describe('Sale refund()', () => { const options = {transaction: tx}; const ticketsBefore = await models.Ticket.find({}, options); - const ticket = await models.Sale.refund(ctx, salesIds, servicesIds, withWarehouse, options); + const tickets = await models.Sale.refund(ctx, salesIds, servicesIds, withWarehouse, options); const refundedTicket = await models.Ticket.findOne({ where: { - id: ticket.id + id: tickets[0].id }, include: [ { diff --git a/modules/ticket/back/methods/ticket/canBeInvoiced.js b/modules/ticket/back/methods/ticket/canBeInvoiced.js index 348f02348..fe7223c17 100644 --- a/modules/ticket/back/methods/ticket/canBeInvoiced.js +++ b/modules/ticket/back/methods/ticket/canBeInvoiced.js @@ -10,6 +10,11 @@ module.exports = function(Self) { description: 'The tickets id', type: ['number'], required: true + }, + { + arg: 'isRectificative', + description: 'If it is rectificative', + type: 'boolean' } ], returns: { @@ -23,7 +28,7 @@ module.exports = function(Self) { } }); - Self.canBeInvoiced = async(ctx, ticketsIds, options) => { + Self.canBeInvoiced = async(ctx, ticketsIds, isRectificative, options) => { const myOptions = {}; const $t = ctx.req.__; // $translate @@ -48,10 +53,11 @@ module.exports = function(Self) { const [supplierCompany] = await Self.rawSql(query, [companyFk], options); const isSpanishCompany = supplierCompany?.isSpanishCompany; - - const [result] = await Self.rawSql('SELECT hasAnyNegativeBase() AS base', null, options); - const hasAnyNegativeBase = result?.base && isSpanishCompany; - if (hasAnyNegativeBase) + const taxBaseFunction = isRectificative ? 'hasAnyPositiveBase' : 'hasAnyNegativeBase'; + const [result] = + await Self.rawSql(`SELECT ?() AS hasBasesProblem`, [taxBaseFunction], options); + const hasAnyIncorrectBase = result?.hasBasesProblem && isSpanishCompany; + if (hasAnyIncorrectBase) throw new UserError($t('Negative basis of tickets', {ticketsIds: ticketsIds})); const today = Date.vnNew(); diff --git a/modules/ticket/back/methods/ticket/invoiceTickets.js b/modules/ticket/back/methods/ticket/invoiceTickets.js index 29fb1769b..212f6556a 100644 --- a/modules/ticket/back/methods/ticket/invoiceTickets.js +++ b/modules/ticket/back/methods/ticket/invoiceTickets.js @@ -93,7 +93,6 @@ module.exports = function(Self) { async function createInvoice(ctx, companyId, ticketsIds, address, invoicesIds, invoiceCorrection, myOptions) { const models = Self.app.models; - console.log(ticketsIds, address); await models.Ticket.rawSql(` CREATE OR REPLACE TEMPORARY TABLE tmp.ticketToInvoice (PRIMARY KEY (id)) diff --git a/modules/ticket/back/methods/ticket/makeInvoice.js b/modules/ticket/back/methods/ticket/makeInvoice.js index 6f1586c2b..fe7e527c8 100644 --- a/modules/ticket/back/methods/ticket/makeInvoice.js +++ b/modules/ticket/back/methods/ticket/makeInvoice.js @@ -67,20 +67,24 @@ module.exports = function(Self) { fields: ['id', 'clientFk', 'addressFk'] }, myOptions); - await models.Ticket.canBeInvoiced(ctx, ticketsIds, myOptions); + await models.Ticket.canBeInvoiced(ctx, ticketsIds, !!invoiceCorrection, myOptions); const [firstTicket] = tickets; const clientId = firstTicket.clientFk; - const clientCanBeInvoiced = await models.Client.canBeInvoiced(clientId, companyFk, invoiceCorrection, myOptions); - if (!clientCanBeInvoiced && !invoiceCorrection) + const clientCanBeInvoiced = + await models.Client.canBeInvoiced(clientId, companyFk, myOptions); + + if (!clientCanBeInvoiced) throw new UserError(`This client can't be invoiced`); - const query = `SELECT vn.invoiceSerial(?, ?, ?) AS serial`; - const [{serial}] = await Self.rawSql(query, [ - clientId, - companyFk, - invoiceType, - ], myOptions); + const [{serial}] = invoiceCorrection ? [{serial: 'R'}] : await Self.rawSql( + `SELECT vn.invoiceSerial(?, ?, ?) AS serial`, + [ + clientId, + companyFk, + invoiceType + ], + myOptions); const invoiceOutSerial = await models.InvoiceOutSerial.findById(serial); if (invoiceOutSerial?.taxAreaFk == 'WORLD') { @@ -92,7 +96,7 @@ module.exports = function(Self) { await Self.rawSql('CALL invoiceOut_new(?, ?, null, @invoiceId)', [serial, invoiceDate], myOptions); const [resultInvoice] = await Self.rawSql('SELECT @invoiceId id', [], myOptions); - if (!resultInvoice) + if (!resultInvoice?.id) throw new UserError('No tickets to invoice', 'notInvoiced'); if (invoiceCorrection) { @@ -102,7 +106,7 @@ module.exports = function(Self) { ); } - if (serial != 'R' && resultInvoice.id) + if (resultInvoice.id) // serial != 'R' && await Self.rawSql('CALL invoiceOutBooking(?)', [resultInvoice.id], myOptions); if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/ticket/specs/canBeInvoiced.spec.js b/modules/ticket/back/methods/ticket/specs/canBeInvoiced.spec.js index 538dbc49f..e443ed6d3 100644 --- a/modules/ticket/back/methods/ticket/specs/canBeInvoiced.spec.js +++ b/modules/ticket/back/methods/ticket/specs/canBeInvoiced.spec.js @@ -27,7 +27,7 @@ describe('ticket canBeInvoiced()', () => { WHERE id IN (?) `, [ticketId], options); - const canBeInvoiced = await models.Ticket.canBeInvoiced(ctx, [ticketId], options); + const canBeInvoiced = await models.Ticket.canBeInvoiced(ctx, [ticketId], false, options); expect(canBeInvoiced).toEqual(false); @@ -59,7 +59,7 @@ describe('ticket canBeInvoiced()', () => { WHERE id IN (?) `, [ticketId], options); - const canBeInvoiced = await models.Ticket.canBeInvoiced(ctx, [ticketId], options); + const canBeInvoiced = await models.Ticket.canBeInvoiced(ctx, [ticketId], false, options); expect(canBeInvoiced).toEqual(false); @@ -95,7 +95,7 @@ describe('ticket canBeInvoiced()', () => { WHERE id IN (?) `, [ticketId], options); - const canBeInvoiced = await models.Ticket.canBeInvoiced(ctx, [ticketId], options); + const canBeInvoiced = await models.Ticket.canBeInvoiced(ctx, [ticketId], false, options); expect(canBeInvoiced).toEqual(false); @@ -123,7 +123,7 @@ describe('ticket canBeInvoiced()', () => { WHERE id IN (?) `, [ticketId], options); - const canBeInvoiced = await models.Ticket.canBeInvoiced(ctx, [ticketId], options); + const canBeInvoiced = await models.Ticket.canBeInvoiced(ctx, [ticketId], false, options); expect(canBeInvoiced).toEqual(true); diff --git a/modules/ticket/back/methods/ticket/specs/invoiceTickets.spec.js b/modules/ticket/back/methods/ticket/specs/invoiceTickets.spec.js index 8971fb24a..162dc066a 100644 --- a/modules/ticket/back/methods/ticket/specs/invoiceTickets.spec.js +++ b/modules/ticket/back/methods/ticket/specs/invoiceTickets.spec.js @@ -31,7 +31,7 @@ describe('ticket invoiceTickets()', () => { const options = {transaction: tx}; const ticketsIds = [11, 16]; - await models.Ticket.invoiceTickets(ctx, ticketsIds, options); + await models.Ticket.invoiceTickets(ctx, ticketsIds, null, options); await tx.rollback(); } catch (e) { @@ -57,7 +57,7 @@ describe('ticket invoiceTickets()', () => { await client.updateAttribute('isTaxDataChecked', false, options); const ticketsIds = [11]; - await models.Ticket.invoiceTickets(ctx, ticketsIds, options); + await models.Ticket.invoiceTickets(ctx, ticketsIds, null, options); await tx.rollback(); } catch (e) { @@ -80,8 +80,8 @@ describe('ticket invoiceTickets()', () => { const options = {transaction: tx}; const ticketsIds = [11]; - await models.Ticket.invoiceTickets(ctx, ticketsIds, options); - await models.Ticket.invoiceTickets(ctx, ticketsIds, options); + await models.Ticket.invoiceTickets(ctx, ticketsIds, null, options); + await models.Ticket.invoiceTickets(ctx, ticketsIds, null, options); await tx.rollback(); } catch (e) { @@ -102,7 +102,7 @@ describe('ticket invoiceTickets()', () => { const options = {transaction: tx}; const ticketsIds = [11]; - const invoicesIds = await models.Ticket.invoiceTickets(ctx, ticketsIds, options); + const invoicesIds = await models.Ticket.invoiceTickets(ctx, ticketsIds, null, options); expect(invoicesIds.length).toBeGreaterThan(0); diff --git a/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js b/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js index 9b1fd8f6f..456303602 100644 --- a/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js +++ b/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js @@ -42,7 +42,7 @@ describe('ticket makeInvoice()', () => { WHERE id IN (?) `, [ticketsIds], options); - const invoiceId = await models.Ticket.makeInvoice(ctx, invoiceType, companyFk, invoiceDate, options); + const invoiceId = await models.Ticket.makeInvoice(ctx, invoiceType, companyFk, invoiceDate, null, options); expect(invoiceId).toBeDefined(); @@ -70,7 +70,7 @@ describe('ticket makeInvoice()', () => { WHERE id IN (?) `, [ticketsId], options); - await models.Ticket.makeInvoice(ctx, invoiceType, companyFk, invoiceDate, options); + await models.Ticket.makeInvoice(ctx, invoiceType, companyFk, invoiceDate, null, options); await tx.rollback(); } catch (e) { error = e; diff --git a/modules/ticket/front/descriptor-menu/index.js b/modules/ticket/front/descriptor-menu/index.js index 18db8c147..cd819e623 100644 --- a/modules/ticket/front/descriptor-menu/index.js +++ b/modules/ticket/front/descriptor-menu/index.js @@ -292,7 +292,7 @@ class Controller extends Section { const query = 'Tickets/refund'; return this.$http.post(query, params) .then(res => { - const refundTicket = res.data; + const [refundTicket] = res.data; this.vnApp.showSuccess(this.$t('The following refund ticket have been created', { ticketId: refundTicket.id })); diff --git a/modules/ticket/front/descriptor-menu/index.spec.js b/modules/ticket/front/descriptor-menu/index.spec.js index 1bb270165..c755b14c3 100644 --- a/modules/ticket/front/descriptor-menu/index.spec.js +++ b/modules/ticket/front/descriptor-menu/index.spec.js @@ -262,11 +262,12 @@ describe('Ticket Component vnTicketDescriptorMenu', () => { const params = { ticketsIds: [16] }; - $httpBackend.expectPOST('Tickets/refund', params).respond({id: 99}); + const response = {id: 99}; + $httpBackend.expectPOST('Tickets/refund', params).respond([response]); controller.refund(); $httpBackend.flush(); - expect(controller.$state.go).toHaveBeenCalledWith('ticket.card.sale', {id: 99}); + expect(controller.$state.go).toHaveBeenCalledWith('ticket.card.sale', response); }); }); diff --git a/modules/ticket/front/sale/index.js b/modules/ticket/front/sale/index.js index 4f6a9e757..ed6d9b10a 100644 --- a/modules/ticket/front/sale/index.js +++ b/modules/ticket/front/sale/index.js @@ -526,7 +526,7 @@ class Controller extends Section { const params = {salesIds: salesIds, withWarehouse: withWarehouse}; const query = 'Sales/refund'; this.$http.post(query, params).then(res => { - const refundTicket = res.data; + const [refundTicket] = res.data; this.vnApp.showSuccess(this.$t('The following refund ticket have been created', { ticketId: refundTicket.id })); diff --git a/modules/ticket/front/sale/index.spec.js b/modules/ticket/front/sale/index.spec.js index 70781eb58..36be32f52 100644 --- a/modules/ticket/front/sale/index.spec.js +++ b/modules/ticket/front/sale/index.spec.js @@ -729,7 +729,7 @@ describe('Ticket', () => { salesIds: [1, 4], }; const refundTicket = {id: 99}; - $httpBackend.expect('POST', 'Sales/refund', params).respond(200, refundTicket); + $httpBackend.expect('POST', 'Sales/refund', params).respond(200, [refundTicket]); controller.createRefund(); $httpBackend.flush(); From 303b6f524051e05439eb8bd0342e9a97771727cd Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 1 Dec 2023 13:48:56 +0100 Subject: [PATCH 086/207] fix(expencefk): refs #6398 expenceFk to expenseFk --- db/changes/235001/01-procedures.sql | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/db/changes/235001/01-procedures.sql b/db/changes/235001/01-procedures.sql index 121348fbf..3777708d5 100644 --- a/db/changes/235001/01-procedures.sql +++ b/db/changes/235001/01-procedures.sql @@ -450,13 +450,13 @@ BEGIN INSERT INTO ticketTracking(stateFk, ticketFk, userFk) SELECT * FROM tmp.updateInter; - CALL invoiceExpenceMake(vNewInvoiceId); + CALL invoiceExpenseMake(vNewInvoiceId); CALL invoiceTaxMake(vNewInvoiceId, vTaxArea); UPDATE invoiceOut io JOIN ( SELECT SUM(amount) total - FROM invoiceOutExpence + FROM invoiceOutExpense WHERE invoiceOutFk = vNewInvoiceId ) base JOIN ( @@ -493,15 +493,15 @@ BEGIN SET @vTaxableBaseServices := 0.00; SET @vTaxCodeGeneral := NULL; - INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) + INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk) SELECT vNewInvoiceInFk, @vTaxableBaseServices, - sub.expenceFk, + sub.expenseFk, sub.taxTypeSageFk, sub.transactionTypeSageFk FROM ( SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase, - i.expenceFk, + i.expenseFk, i.taxTypeSageFk, i.transactionTypeSageFk, @vTaxCodeGeneral := i.taxClassCodeFk @@ -511,11 +511,11 @@ BEGIN HAVING taxableBase ) sub; - INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) + INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk) SELECT vNewInvoiceInFk, SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral, @vTaxableBaseServices, 0) taxableBase, - i.expenceFk, + i.expenseFk, i.taxTypeSageFk , i.transactionTypeSageFk FROM tmp.ticketTax tt From 6d486fbec99ae2b471882a2b24530b5b34453f06 Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 1 Dec 2023 13:58:45 +0100 Subject: [PATCH 087/207] refs #6085 trad, remove front, back test --- back/models/specs/mailAliasAccount.spec.js | 73 +++++++++++++++++++ db/changes/235001/00-aclsMails.sql | 3 +- db/dump/fixtures.sql | 7 ++ front/core/locale/es.yml | 1 + loopback/locale/es.json | 4 +- modules/account/back/model-config.json | 3 + .../account/back/models/mail-alias-account.js | 68 ++++++++--------- modules/account/back/models/mail-alias-acl.js | 59 ++++++--------- .../account/back/models/mail-alias-acl.json | 10 ++- .../account/front/alias/acl/create/index.js | 33 --------- modules/account/front/alias/acl/index.js | 4 - .../account/front/alias/acl/index/index.js | 15 ---- modules/account/front/alias/acl/main/index.js | 18 ----- .../front/alias/acl/search-panel/index.js | 26 ------- modules/account/front/alias/index.js | 1 - 15 files changed, 151 insertions(+), 174 deletions(-) create mode 100644 back/models/specs/mailAliasAccount.spec.js delete mode 100644 modules/account/front/alias/acl/create/index.js delete mode 100644 modules/account/front/alias/acl/index.js delete mode 100644 modules/account/front/alias/acl/index/index.js delete mode 100644 modules/account/front/alias/acl/main/index.js delete mode 100644 modules/account/front/alias/acl/search-panel/index.js diff --git a/back/models/specs/mailAliasAccount.spec.js b/back/models/specs/mailAliasAccount.spec.js new file mode 100644 index 000000000..46d447f90 --- /dev/null +++ b/back/models/specs/mailAliasAccount.spec.js @@ -0,0 +1,73 @@ +const models = require('vn-loopback/server/server').models; + +fdescribe('loopback model MailAliasAccount', () => { + it('should fail to add a mail Alias if the worker doesnt have ACLs', async() => { + const tx = await models.MailAliasAccount.beginTransaction({}); + let error; + + try { + const options = {transaction: tx, accessToken: {userId: 1}}; + await models.MailAliasAccount.create({mailAliasFk: 2, roleFk: 5}, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toEqual('The alias cant be modified'); + }); + + it('should add a mail Alias', async() => { + const tx = await models.MailAliasAccount.beginTransaction({}); + let error; + + try { + const options = {transaction: tx, accessToken: {userId: 9}}; + await models.MailAliasAccount.create({mailAliasFk: 2, roleFk: 5}, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).toBeUndefined(); + }); + + it('should add a mail Alias of an inherit role', async() => { + const tx = await models.MailAliasAccount.beginTransaction({}); + let error; + + try { + const options = {transaction: tx, accessToken: {userId: 9}}; + await models.MailAliasAccount.create({mailAliasFk: 3, roleFk: 5}, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).toBeUndefined(); + }); + + it('should delete a mail Alias', async() => { + const tx = await models.MailAliasAccount.beginTransaction({}); + let error; + + try { + const options = {transaction: tx, accessToken: {userId: 1}}; + const mailAclId = 2; + await models.MailAliasAccount.destroyAll({id: mailAclId}, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).toBeUndefined(); + }); +}); + diff --git a/db/changes/235001/00-aclsMails.sql b/db/changes/235001/00-aclsMails.sql index 92603aec4..5cfea4030 100644 --- a/db/changes/235001/00-aclsMails.sql +++ b/db/changes/235001/00-aclsMails.sql @@ -1,5 +1,6 @@ -- Definición de la tabla mailAliasACL -CREATE TABLE `account`.`mailAliasACL` ( + +CREATE OR REPLACE TABLE `account`.`mailAliasAcl` ( `mailAliasFk` int(10) unsigned NOT NULL, `roleFk` int(10) unsigned NOT NULL, FOREIGN KEY (`mailAliasFk`) REFERENCES `account`.`mailAlias` (`id`), diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 93b7b796f..62f96b459 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -3002,3 +3002,10 @@ INSERT INTO `vn`.`invoiceCorrectionType` (`id`, `description`) (1, 'Error in VAT calculation'), (2, 'Error in sales details'), (3, 'Error in customer data'); + +INSERT INTO `account`.`mailAliasAcl` (`mailAliasFk`, `roleFk`) + VALUES + (1, 1), + (2, 9), + (3, 15); + diff --git a/front/core/locale/es.yml b/front/core/locale/es.yml index 96c34d98c..1b9bbb40b 100644 --- a/front/core/locale/es.yml +++ b/front/core/locale/es.yml @@ -68,3 +68,4 @@ Load more results: Cargar más resultados Send cau: Enviar cau By sending this ticket, all the data related to the error, the section, the user, etc., are already sent.: Al enviar este cau ya se envían todos los datos relacionados con el error, la sección, el usuario, etc ExplainReason: Explique el motivo por el que no deberia aparecer este fallo +You already have the mailAlias: Ya tienes este mail diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 01384efb4..2e516bf12 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -329,5 +329,7 @@ "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}}" + "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", + "You already have the mailAlias": "You already have the mailAlias", + "The alias cant be modified": "The alias cant be modified" } \ No newline at end of file diff --git a/modules/account/back/model-config.json b/modules/account/back/model-config.json index b4bd6dbaf..0cd43d0ce 100644 --- a/modules/account/back/model-config.json +++ b/modules/account/back/model-config.json @@ -14,6 +14,9 @@ "MailAliasAccount": { "dataSource": "vn" }, + "MailAliasAcl": { + "dataSource": "vn" + }, "MailConfig": { "dataSource": "vn" }, diff --git a/modules/account/back/models/mail-alias-account.js b/modules/account/back/models/mail-alias-account.js index 6f5213f24..a95189689 100644 --- a/modules/account/back/models/mail-alias-account.js +++ b/modules/account/back/models/mail-alias-account.js @@ -2,54 +2,54 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { + Self.rewriteDbError(function(err) { + if (err.code === 'ER_DUP_ENTRY') + return new UserError(`You already have the mailAlias`); + return err; + }); + Self.observe('before save', async ctx => { const changes = ctx.currentInstance || ctx.instance; - await Self.hasGrant(ctx, changes.mailAlias); + await checkModifyPermission(ctx, changes.mailAlias); }); Self.observe('before delete', async ctx => { const mailAliasAccount = await Self.findById(ctx.where.id); - await Self.hasGrant(ctx, mailAliasAccount.mailAlias); + await checkModifyPermission(ctx, mailAliasAccount.mailAlias); }); - /** - * Checks if current user has - * grant to add/remove alias - * - * @param {Object} ctx - Request context - * @param {Interger} mailAlias - mailAlias id - * @return {Boolean} True for user with grant - */ - Self.hasGrant = async function(ctx, mailAlias) { + async function checkModifyPermission(ctx, mailAliasFk) { + const userId = ctx.options.accessToken.userId; + const available = await Self.getAvailable(userId); + if (!available.has(mailAliasFk)) + throw new UserError('The alias cant be modified'); + } + + Self.getAvailable = async function(userId, options) { const models = Self.app.models; - const accessToken = {req: {accessToken: ctx.options.accessToken}}; - const userId = accessToken.req.accessToken.userId; - const canEditAlias = await models.ACL.checkAccessAcl(accessToken, 'MailAliasAccount', 'canEditAlias', 'WRITE'); - if (canEditAlias) return true; + const myOptions = {}; - const user = await models.VnUser.findById(userId, {fields: ['hasGrant']}); - if (!user.hasGrant) - throw new UserError(`You don't have grant privilege`); + if (typeof options == 'object') + Object.assign(myOptions, options); - const account = await models.Account.findById(userId, { - fields: ['id'], - include: { - relation: 'aliases', - scope: { - fields: ['mailAlias'] - } + const roles = await models.RoleMapping.find({ + fields: ['roleId'], + where: {principalId: userId} + }, myOptions); + + const availableMailAlias = await models.MailAliasAcl.find({ + fields: ['mailAliasFk'], + include: {relation: 'mailAlias'}, + where: { + roleFk: { + inq: roles.map(role => role.roleId), + }, } - }); - - const aliases = account.aliases().map(alias => alias.mailAlias); - - const hasAlias = aliases.includes(mailAlias); - if (!hasAlias) - throw new UserError(`You cannot assign/remove an alias that you are not assigned to`); - - return true; + }, myOptions); + const mailAliasArray = Array.from(availableMailAlias, alias => alias.mailAliasFk); + return new Set(mailAliasArray); }; }; diff --git a/modules/account/back/models/mail-alias-acl.js b/modules/account/back/models/mail-alias-acl.js index 4a74472fe..a95189689 100644 --- a/modules/account/back/models/mail-alias-acl.js +++ b/modules/account/back/models/mail-alias-acl.js @@ -1,43 +1,33 @@ + const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - require('../methods/notification/getList')(Self); - - Self.observe('before save', async function(ctx) { - await checkModifyPermission(ctx); + Self.rewriteDbError(function(err) { + if (err.code === 'ER_DUP_ENTRY') + return new UserError(`You already have the mailAlias`); + return err; }); - Self.observe('before delete', async function(ctx) { - await checkModifyPermission(ctx); + Self.observe('before save', async ctx => { + const changes = ctx.currentInstance || ctx.instance; + + await checkModifyPermission(ctx, changes.mailAlias); }); - async function checkModifyPermission(ctx) { - const models = Self.app.models; - const instance = ctx.instance; + Self.observe('before delete', async ctx => { + const mailAliasAccount = await Self.findById(ctx.where.id); + + await checkModifyPermission(ctx, mailAliasAccount.mailAlias); + }); + + async function checkModifyPermission(ctx, mailAliasFk) { const userId = ctx.options.accessToken.userId; - - let mailAliasFk; - let roleFk; - - if (instance) { - mailAliasFk = instance.mailAliasFk; - roleFk = instance.roleFk; - } else { - const mailAliasAcl = await models.MailAlias.findById(ctx.where.id); - mailAliasFk = mailAliasAcl.id; - roleFk = mailAliasAcl.roleFk; - } - - const role = await models.VnUser.findById(roleFk, {fields: ['id', 'role']}); - const available = await Self.getAvailable(roleFk); - const hasAcl = available.has(mailAliasFk); - - if (!hasAcl || (userId.role != role)) + const available = await Self.getAvailable(userId); + if (!available.has(mailAliasFk)) throw new UserError('The alias cant be modified'); } Self.getAvailable = async function(userId, options) { - const availableMailAliasMap = new Map(); const models = Self.app.models; const myOptions = {}; @@ -51,20 +41,15 @@ module.exports = Self => { }, myOptions); const availableMailAlias = await models.MailAliasAcl.find({ - fields: ['mailAliasFk', 'roleFk'], - include: {relation: 'roleFk'}, + fields: ['mailAliasFk'], + include: {relation: 'mailAlias'}, where: { roleFk: { inq: roles.map(role => role.roleId), }, } }, myOptions); - - for (available of availableMailAlias) { - availableMailAliasMap.set(available.mailAliasFk, { - mailAliasFk: available.mailAliasFk, - }); - } - return availableMailAliasMap; + const mailAliasArray = Array.from(availableMailAlias, alias => alias.mailAliasFk); + return new Set(mailAliasArray); }; }; diff --git a/modules/account/back/models/mail-alias-acl.json b/modules/account/back/models/mail-alias-acl.json index 2e44f38eb..014b95d14 100644 --- a/modules/account/back/models/mail-alias-acl.json +++ b/modules/account/back/models/mail-alias-acl.json @@ -1,28 +1,30 @@ { - "name": "mailAliasACL", + "name": "MailAliasAcl", "base": "VnModel", "options": { "mysql": { - "table": "account.mailAliasACL" + "table": "account.mailAliasAcl" } }, "properties": { "mailAliasFk": { + "id": true, "type": "number" }, "roleFk": { + "id": true, "type": "number" } }, "relations": { "mailAlias": { "type": "belongsTo", - "model": "VnUser", + "model": "MailAlias", "foreignKey": "mailAliasFk" }, "role": { "type": "belongsTo", - "model": "VnUser", + "model": "Role", "foreignKey": "roleFk" } } diff --git a/modules/account/front/alias/acl/create/index.js b/modules/account/front/alias/acl/create/index.js deleted file mode 100644 index 58e70e4aa..000000000 --- a/modules/account/front/alias/acl/create/index.js +++ /dev/null @@ -1,33 +0,0 @@ -import ngModule from '../../../module'; -import Section from 'salix/components/section'; - -export default class Controller extends Section { - constructor(...args) { - super(...args); - this.accessTypes = [ - {name: '*'}, - {name: 'READ'}, - {name: 'WRITE'} - ]; - this.permissions = [ - {name: 'ALLOW'}, - {name: 'DENY'} - ]; - - this.models = []; - for (let model in window.validations) - this.models.push({name: model}); - - this.acl = { - property: '*', - principalType: 'ROLE', - accessType: 'READ', - permission: 'ALLOW' - }; - } -} - -ngModule.component('vnAclMailCreate', { - // template: require('./index.html'), - controller: Controller -}); diff --git a/modules/account/front/alias/acl/index.js b/modules/account/front/alias/acl/index.js deleted file mode 100644 index 8393859a5..000000000 --- a/modules/account/front/alias/acl/index.js +++ /dev/null @@ -1,4 +0,0 @@ -import './main'; -import './index/'; -import './create'; -import './search-panel'; diff --git a/modules/account/front/alias/acl/index/index.js b/modules/account/front/alias/acl/index/index.js deleted file mode 100644 index 5d8d49574..000000000 --- a/modules/account/front/alias/acl/index/index.js +++ /dev/null @@ -1,15 +0,0 @@ -import ngModule from '../../../module'; -import Section from 'salix/components/section'; - -export default class Controller extends Section { - onDelete(row) { - return this.$http.delete(`ACLs/${row.id}`) - .then(() => this.$.model.refresh()) - .then(() => this.vnApp.showSuccess(this.$t('ACL removed'))); - } -} - -ngModule.component('vnAclMailIndex', { - // template: require('./index.html'), - controller: Controller -}); diff --git a/modules/account/front/alias/acl/main/index.js b/modules/account/front/alias/acl/main/index.js deleted file mode 100644 index 97f04ee50..000000000 --- a/modules/account/front/alias/acl/main/index.js +++ /dev/null @@ -1,18 +0,0 @@ -import ngModule from '../../../module'; -import ModuleMain from 'salix/components/module-main'; - -export default class ACL extends ModuleMain { - exprBuilder(param, value) { - switch (param) { - case 'search': - return {model: {like: `%${value}%`}}; - default: - return {[param]: value}; - } - } -} - -ngModule.vnComponent('vnAclMailComponent', { - controller: ACL - // template: require('./index.html') -}); diff --git a/modules/account/front/alias/acl/search-panel/index.js b/modules/account/front/alias/acl/search-panel/index.js deleted file mode 100644 index 67db33383..000000000 --- a/modules/account/front/alias/acl/search-panel/index.js +++ /dev/null @@ -1,26 +0,0 @@ -import ngModule from '../../../module'; -import SearchPanel from 'core/components/searchbar/search-panel'; - -export default class Controller extends SearchPanel { - constructor(...args) { - super(...args); - this.accessTypes = [ - {name: '*'}, - {name: 'READ'}, - {name: 'WRITE'} - ]; - this.permissions = [ - {name: 'ALLOW'}, - {name: 'DENY'} - ]; - - this.models = []; - for (let model in window.validations) - this.models.push({name: model}); - } -} - -ngModule.component('vnAclSearchPanel', { - // template: require('./index.html'), - controller: Controller -}); diff --git a/modules/account/front/alias/index.js b/modules/account/front/alias/index.js index 598421749..8eed3a3d3 100644 --- a/modules/account/front/alias/index.js +++ b/modules/account/front/alias/index.js @@ -7,4 +7,3 @@ import './descriptor'; import './create'; import './basic-data'; import './users'; -import './acl'; From c0ce7e542febf97895ad6ff14e9869f182407e05 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 4 Dec 2023 09:40:57 +0100 Subject: [PATCH 088/207] refs #6085 solve testback --- back/models/specs/mailAliasAccount.spec.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/back/models/specs/mailAliasAccount.spec.js b/back/models/specs/mailAliasAccount.spec.js index 46d447f90..c07e16d60 100644 --- a/back/models/specs/mailAliasAccount.spec.js +++ b/back/models/specs/mailAliasAccount.spec.js @@ -24,7 +24,7 @@ fdescribe('loopback model MailAliasAccount', () => { try { const options = {transaction: tx, accessToken: {userId: 9}}; - await models.MailAliasAccount.create({mailAliasFk: 2, roleFk: 5}, options); + await models.MailAliasAccount.create({mailAlias: 2, account: 5}, options); await tx.rollback(); } catch (e) { @@ -41,7 +41,7 @@ fdescribe('loopback model MailAliasAccount', () => { try { const options = {transaction: tx, accessToken: {userId: 9}}; - await models.MailAliasAccount.create({mailAliasFk: 3, roleFk: 5}, options); + await models.MailAliasAccount.create({mailAlias: 3, account: 5}, options); await tx.rollback(); } catch (e) { From 051c93a42cdee0ab6403924c95cc1dd4771e6859 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 4 Dec 2023 09:41:24 +0100 Subject: [PATCH 089/207] remove fdescribe --- back/models/specs/mailAliasAccount.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/models/specs/mailAliasAccount.spec.js b/back/models/specs/mailAliasAccount.spec.js index c07e16d60..d26ed2313 100644 --- a/back/models/specs/mailAliasAccount.spec.js +++ b/back/models/specs/mailAliasAccount.spec.js @@ -1,6 +1,6 @@ const models = require('vn-loopback/server/server').models; -fdescribe('loopback model MailAliasAccount', () => { +describe('loopback model MailAliasAccount', () => { it('should fail to add a mail Alias if the worker doesnt have ACLs', async() => { const tx = await models.MailAliasAccount.beginTransaction({}); let error; From b9671c0b67b6b4222b61598ac6a5ee2460a684f2 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 4 Dec 2023 14:44:50 +0100 Subject: [PATCH 090/207] 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 091/207] 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 2fe631f078bf2ca596e083ede0c015e3c1aec2d5 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 5 Dec 2023 07:15:22 +0100 Subject: [PATCH 092/207] refs #5666 feat: change models permissions --- back/model-config.json | 12 ++++++------ db/changes/235001/00-updateACL_Role_VnRole.sql | 14 +++++++++----- loopback/server/model-config.json | 8 -------- 3 files changed, 15 insertions(+), 19 deletions(-) diff --git a/back/model-config.json b/back/model-config.json index 84dd9eebd..27a94498c 100644 --- a/back/model-config.json +++ b/back/model-config.json @@ -139,12 +139,6 @@ "Warehouse": { "dataSource": "vn" }, - "VnUser": { - "dataSource": "vn" - }, - "VnRole": { - "dataSource": "vn" - }, "OsTicket": { "dataSource": "osticket" }, @@ -159,6 +153,12 @@ }, "ViaexpressConfig": { "dataSource": "vn" + }, + "VnUser": { + "dataSource": "vn" + }, + "VnRole": { + "dataSource": "vn" } } diff --git a/db/changes/235001/00-updateACL_Role_VnRole.sql b/db/changes/235001/00-updateACL_Role_VnRole.sql index 0b1083991..6fbec02a6 100644 --- a/db/changes/235001/00-updateACL_Role_VnRole.sql +++ b/db/changes/235001/00-updateACL_Role_VnRole.sql @@ -1,8 +1,12 @@ -- Auto-generated SQL script #202311301038 -INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) - VALUES ('VnRole','*','*','ALLOW','ROLE','$everyone'); -INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) - VALUES ('VnRole','*','*','ALLOW','ROLE','employee'); +-- INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) +-- VALUES ('VnRole','*','*','ALLOW','ROLE','$everyone'); +-- INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) +-- VALUES ('VnRole','*','*','ALLOW','ROLE','employee'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) VALUES + ('VnRole','*','READ','ALLOW','ROLE','employee'), + ('VnRole','*','WRITE','ALLOW','ROLE','it'); -- Auto-generated SQL script #202311301203 -UPDATE `salix`.`ACL` SET permission='DENY' WHERE model='Role'; +DELETE FROM`salix`.`ACL` WHERE model='Role'; + diff --git a/loopback/server/model-config.json b/loopback/server/model-config.json index 33ef3797d..51874988d 100644 --- a/loopback/server/model-config.json +++ b/loopback/server/model-config.json @@ -25,14 +25,6 @@ "FieldAcl": { "dataSource": "vn" }, - "Role": { - "dataSource": "vn", - "options": { - "mysql": { - "table": "salix.Role" - } - } - }, "RoleMapping": { "dataSource": "vn", "options": { From 57add7abf016602c15786d719efd3f46142a549a Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 5 Dec 2023 07:16:12 +0100 Subject: [PATCH 093/207] refs #5666 perf: replace Role by VnRole --- back/methods/vn-user/privileges.js | 2 +- back/methods/vn-user/specs/privileges.spec.js | 2 +- modules/account/back/models/ldap-config.js | 2 +- modules/ticket/back/methods/sale/specs/canEdit.spec.js | 4 ++-- .../back/methods/worker/specs/activeWithInheritedRole.spec.js | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/back/methods/vn-user/privileges.js b/back/methods/vn-user/privileges.js index 08cfaaae8..9f936c29b 100644 --- a/back/methods/vn-user/privileges.js +++ b/back/methods/vn-user/privileges.js @@ -68,7 +68,7 @@ module.exports = Self => { userToUpdate.hasGrant = hasGrant; if (roleFk) { - const role = await models.Role.findById(roleFk, {fields: ['name']}, myOptions); + const role = await models.VnRole.findById(roleFk, {fields: ['name']}, myOptions); const hasRole = await Self.hasRole(userId, role.name, myOptions); if (!hasRole) diff --git a/back/methods/vn-user/specs/privileges.spec.js b/back/methods/vn-user/specs/privileges.spec.js index 3d25eecf9..04d9c09ff 100644 --- a/back/methods/vn-user/specs/privileges.spec.js +++ b/back/methods/vn-user/specs/privileges.spec.js @@ -70,7 +70,7 @@ describe('VnUser privileges()', () => { const tx = await models.VnUser.beginTransaction({}); const options = {transaction: tx}; - const agency = await models.Role.findOne({ + const agency = await models.VnRole.findOne({ where: { name: 'agency' } diff --git a/modules/account/back/models/ldap-config.js b/modules/account/back/models/ldap-config.js index b557d243c..89f0add48 100644 --- a/modules/account/back/models/ldap-config.js +++ b/modules/account/back/models/ldap-config.js @@ -239,7 +239,7 @@ module.exports = Self => { // Prepare data - let roles = await $.Role.find({ + let roles = await $.VnRole.find({ fields: ['id', 'name', 'description'] }); let roleRoles = await $.RoleRole.find({ diff --git a/modules/ticket/back/methods/sale/specs/canEdit.spec.js b/modules/ticket/back/methods/sale/specs/canEdit.spec.js index eef9136a8..200ea24cc 100644 --- a/modules/ticket/back/methods/sale/specs/canEdit.spec.js +++ b/modules/ticket/back/methods/sale/specs/canEdit.spec.js @@ -102,7 +102,7 @@ describe('sale canEdit()', () => { try { const options = {transaction: tx}; - const role = await models.Role.findOne({ + const role = await models.VnRole.findOne({ where: { name: roleEnabled.principalId } @@ -159,7 +159,7 @@ describe('sale canEdit()', () => { try { const options = {transaction: tx}; - const role = await models.Role.findOne({ + const role = await models.VnRole.findOne({ where: { name: roleEnabled.principalId } diff --git a/modules/worker/back/methods/worker/specs/activeWithInheritedRole.spec.js b/modules/worker/back/methods/worker/specs/activeWithInheritedRole.spec.js index da54f6adb..580e07351 100644 --- a/modules/worker/back/methods/worker/specs/activeWithInheritedRole.spec.js +++ b/modules/worker/back/methods/worker/specs/activeWithInheritedRole.spec.js @@ -3,7 +3,7 @@ const app = require('vn-loopback/server/server'); describe('Worker activeWithInheritedRole', () => { let allRolesCount; beforeAll(async() => { - allRolesCount = await app.models.Role.count(); + allRolesCount = await app.models.VnRole.count(); }); it('should return the workers with an inherited role of salesPerson', async() => { From b4f4714c0a9f6fae89c38b165e813582b37fc99f Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 5 Dec 2023 07:47:38 +0100 Subject: [PATCH 094/207] refs #5666 feat: remove loggable.json --- loopback/common/models/loggable.json | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 loopback/common/models/loggable.json diff --git a/loopback/common/models/loggable.json b/loopback/common/models/loggable.json deleted file mode 100644 index 62822d0af..000000000 --- a/loopback/common/models/loggable.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "Loggable", - "base": "VnModel", - "validateUpsert": true, - "mixins": { - "Loggable": true - } -} From 1d92bbf4a21f24e30e4e51328e636b19ecc6a560 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 5 Dec 2023 07:48:56 +0100 Subject: [PATCH 095/207] refs #5666 feat: replace base value and add mixins --- modules/claim/back/models/claim-beginning.json | 5 ++++- modules/claim/back/models/claim-development.json | 5 ++++- modules/claim/back/models/claim-dms.json | 5 ++++- modules/claim/back/models/claim-end.json | 5 ++++- modules/claim/back/models/claim-observation.json | 5 ++++- modules/claim/back/models/claim-state.json | 5 ++++- modules/claim/back/models/claim.json | 5 ++++- modules/client/back/models/address.json | 5 ++++- modules/client/back/models/client-contact.json | 5 ++++- modules/client/back/models/client-dms.json | 5 ++++- modules/client/back/models/client-informa.json | 5 ++++- modules/client/back/models/client-observation.json | 5 ++++- modules/client/back/models/client-sample.json | 5 ++++- modules/client/back/models/client.json | 5 ++++- modules/client/back/models/greuge.json | 5 ++++- modules/client/back/models/recovery.json | 5 ++++- modules/entry/back/models/buy.json | 5 ++++- modules/entry/back/models/entry-observation.json | 5 ++++- modules/entry/back/models/entry.json | 5 ++++- modules/invoiceIn/back/models/invoice-in-tax.json | 5 ++++- modules/invoiceIn/back/models/invoice-in.json | 5 ++++- modules/item/back/models/item-barcode.json | 5 ++++- modules/item/back/models/item-botanical.json | 5 ++++- modules/item/back/models/item-shelving.json | 5 ++++- modules/item/back/models/item-tag.json | 5 ++++- modules/item/back/models/item-tax-country.json | 5 ++++- modules/item/back/models/item.json | 5 ++++- modules/route/back/models/route.json | 5 ++++- modules/shelving/back/models/shelving.json | 5 ++++- modules/supplier/back/models/supplier-account.json | 5 ++++- modules/supplier/back/models/supplier-address.json | 5 ++++- modules/supplier/back/models/supplier-contact.json | 5 ++++- modules/supplier/back/models/supplier.json | 5 ++++- modules/ticket/back/models/expedition.json | 5 ++++- modules/ticket/back/models/sale.json | 5 ++++- modules/ticket/back/models/ticket-dms.json | 5 ++++- modules/ticket/back/models/ticket-observation.json | 5 ++++- modules/ticket/back/models/ticket-packaging.json | 5 ++++- modules/ticket/back/models/ticket-refund.json | 5 ++++- modules/ticket/back/models/ticket-request.json | 5 ++++- modules/ticket/back/models/ticket-service.json | 5 ++++- modules/ticket/back/models/ticket-tracking.json | 5 ++++- modules/ticket/back/models/ticket-weekly.json | 5 ++++- modules/ticket/back/models/ticket.json | 5 ++++- modules/travel/back/models/travel-thermograph.json | 5 ++++- modules/travel/back/models/travel.json | 5 ++++- modules/worker/back/models/device-production-user.json | 5 ++++- modules/worker/back/models/device-production.json | 5 ++++- modules/worker/back/models/worker-dms.json | 5 ++++- modules/worker/back/models/worker.json | 5 ++++- modules/zone/back/models/zone-event.json | 5 ++++- modules/zone/back/models/zone-exclusion.json | 5 ++++- modules/zone/back/models/zone-included.json | 5 ++++- modules/zone/back/models/zone-warehouse.json | 5 ++++- modules/zone/back/models/zone.json | 5 ++++- 55 files changed, 220 insertions(+), 55 deletions(-) diff --git a/modules/claim/back/models/claim-beginning.json b/modules/claim/back/models/claim-beginning.json index d355881e8..d224586da 100644 --- a/modules/claim/back/models/claim-beginning.json +++ b/modules/claim/back/models/claim-beginning.json @@ -1,6 +1,9 @@ { "name": "ClaimBeginning", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "claimBeginning" diff --git a/modules/claim/back/models/claim-development.json b/modules/claim/back/models/claim-development.json index b0f352f50..732955660 100644 --- a/modules/claim/back/models/claim-development.json +++ b/modules/claim/back/models/claim-development.json @@ -1,6 +1,9 @@ { "name": "ClaimDevelopment", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "claimDevelopment" diff --git a/modules/claim/back/models/claim-dms.json b/modules/claim/back/models/claim-dms.json index 26c90fd69..ed12c925b 100644 --- a/modules/claim/back/models/claim-dms.json +++ b/modules/claim/back/models/claim-dms.json @@ -1,6 +1,9 @@ { "name": "ClaimDms", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "claimDms" diff --git a/modules/claim/back/models/claim-end.json b/modules/claim/back/models/claim-end.json index 9f12ff93a..ef5477f50 100644 --- a/modules/claim/back/models/claim-end.json +++ b/modules/claim/back/models/claim-end.json @@ -1,6 +1,9 @@ { "name": "ClaimEnd", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "claimEnd" diff --git a/modules/claim/back/models/claim-observation.json b/modules/claim/back/models/claim-observation.json index 2d418b76e..1e4cb6a0f 100644 --- a/modules/claim/back/models/claim-observation.json +++ b/modules/claim/back/models/claim-observation.json @@ -1,6 +1,9 @@ { "name": "ClaimObservation", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "claimObservation" diff --git a/modules/claim/back/models/claim-state.json b/modules/claim/back/models/claim-state.json index 3ee932f16..c50fdebdf 100644 --- a/modules/claim/back/models/claim-state.json +++ b/modules/claim/back/models/claim-state.json @@ -1,6 +1,9 @@ { "name": "ClaimState", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "claimState" diff --git a/modules/claim/back/models/claim.json b/modules/claim/back/models/claim.json index a7db1f3e1..b85b9e073 100644 --- a/modules/claim/back/models/claim.json +++ b/modules/claim/back/models/claim.json @@ -1,6 +1,9 @@ { "name": "Claim", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "claim" diff --git a/modules/client/back/models/address.json b/modules/client/back/models/address.json index 5f962677d..e8bf8d8a0 100644 --- a/modules/client/back/models/address.json +++ b/modules/client/back/models/address.json @@ -1,7 +1,10 @@ { "name": "Address", "description": "Client addresses", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "address" diff --git a/modules/client/back/models/client-contact.json b/modules/client/back/models/client-contact.json index 3f71ab79e..55cc9d436 100644 --- a/modules/client/back/models/client-contact.json +++ b/modules/client/back/models/client-contact.json @@ -1,7 +1,10 @@ { "name": "ClientContact", "description": "Client phone contacts", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "clientContact" diff --git a/modules/client/back/models/client-dms.json b/modules/client/back/models/client-dms.json index 14b19498e..6dbcd0140 100644 --- a/modules/client/back/models/client-dms.json +++ b/modules/client/back/models/client-dms.json @@ -1,6 +1,9 @@ { "name": "ClientDms", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "clientDms" diff --git a/modules/client/back/models/client-informa.json b/modules/client/back/models/client-informa.json index 0c652484e..5e536faff 100644 --- a/modules/client/back/models/client-informa.json +++ b/modules/client/back/models/client-informa.json @@ -1,6 +1,9 @@ { "name": "ClientInforma", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "log": { "model":"ClientLog", "relation": "client", diff --git a/modules/client/back/models/client-observation.json b/modules/client/back/models/client-observation.json index 95d00d374..b204ebeb4 100644 --- a/modules/client/back/models/client-observation.json +++ b/modules/client/back/models/client-observation.json @@ -1,7 +1,10 @@ { "name": "ClientObservation", "description": "Client notes", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "clientObservation" diff --git a/modules/client/back/models/client-sample.json b/modules/client/back/models/client-sample.json index a32f308ab..4cd55d9df 100644 --- a/modules/client/back/models/client-sample.json +++ b/modules/client/back/models/client-sample.json @@ -1,6 +1,9 @@ { "name": "ClientSample", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "clientSample" diff --git a/modules/client/back/models/client.json b/modules/client/back/models/client.json index f32915bb5..bfde05162 100644 --- a/modules/client/back/models/client.json +++ b/modules/client/back/models/client.json @@ -1,6 +1,9 @@ { "name": "Client", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "client" diff --git a/modules/client/back/models/greuge.json b/modules/client/back/models/greuge.json index 884cbd34e..f57744f8a 100644 --- a/modules/client/back/models/greuge.json +++ b/modules/client/back/models/greuge.json @@ -1,6 +1,9 @@ { "name": "Greuge", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "greuge" diff --git a/modules/client/back/models/recovery.json b/modules/client/back/models/recovery.json index 5ea89197d..89ec54494 100644 --- a/modules/client/back/models/recovery.json +++ b/modules/client/back/models/recovery.json @@ -1,6 +1,9 @@ { "name": "Recovery", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "recovery" diff --git a/modules/entry/back/models/buy.json b/modules/entry/back/models/buy.json index 30379eaf6..fa804f4d8 100644 --- a/modules/entry/back/models/buy.json +++ b/modules/entry/back/models/buy.json @@ -1,6 +1,9 @@ { "name": "Buy", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "buy" diff --git a/modules/entry/back/models/entry-observation.json b/modules/entry/back/models/entry-observation.json index cdf0c5e6e..6a1592037 100644 --- a/modules/entry/back/models/entry-observation.json +++ b/modules/entry/back/models/entry-observation.json @@ -1,6 +1,9 @@ { "name": "EntryObservation", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "entryObservation" diff --git a/modules/entry/back/models/entry.json b/modules/entry/back/models/entry.json index a7508b4e8..0f3e389b6 100644 --- a/modules/entry/back/models/entry.json +++ b/modules/entry/back/models/entry.json @@ -1,6 +1,9 @@ { "name": "Entry", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "entry" diff --git a/modules/invoiceIn/back/models/invoice-in-tax.json b/modules/invoiceIn/back/models/invoice-in-tax.json index 5bfbbe2a8..53b5548b6 100644 --- a/modules/invoiceIn/back/models/invoice-in-tax.json +++ b/modules/invoiceIn/back/models/invoice-in-tax.json @@ -1,6 +1,9 @@ { "name": "InvoiceInTax", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "invoiceInTax" diff --git a/modules/invoiceIn/back/models/invoice-in.json b/modules/invoiceIn/back/models/invoice-in.json index 5be55c851..59c179e76 100644 --- a/modules/invoiceIn/back/models/invoice-in.json +++ b/modules/invoiceIn/back/models/invoice-in.json @@ -1,6 +1,9 @@ { "name": "InvoiceIn", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "invoiceIn" diff --git a/modules/item/back/models/item-barcode.json b/modules/item/back/models/item-barcode.json index 12068a65f..6726900ea 100644 --- a/modules/item/back/models/item-barcode.json +++ b/modules/item/back/models/item-barcode.json @@ -1,6 +1,9 @@ { "name": "ItemBarcode", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "itemBarcode" diff --git a/modules/item/back/models/item-botanical.json b/modules/item/back/models/item-botanical.json index 8a8bba870..ff1410615 100644 --- a/modules/item/back/models/item-botanical.json +++ b/modules/item/back/models/item-botanical.json @@ -1,6 +1,9 @@ { "name": "ItemBotanical", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "itemBotanical" diff --git a/modules/item/back/models/item-shelving.json b/modules/item/back/models/item-shelving.json index bb1a141c4..f3be98fc4 100644 --- a/modules/item/back/models/item-shelving.json +++ b/modules/item/back/models/item-shelving.json @@ -1,6 +1,9 @@ { "name": "ItemShelving", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "itemShelving" diff --git a/modules/item/back/models/item-tag.json b/modules/item/back/models/item-tag.json index 0742f8d3f..5702cf6cf 100644 --- a/modules/item/back/models/item-tag.json +++ b/modules/item/back/models/item-tag.json @@ -1,6 +1,9 @@ { "name": "ItemTag", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "itemTag" diff --git a/modules/item/back/models/item-tax-country.json b/modules/item/back/models/item-tax-country.json index 002be97d8..795a1b950 100644 --- a/modules/item/back/models/item-tax-country.json +++ b/modules/item/back/models/item-tax-country.json @@ -1,6 +1,9 @@ { "name": "ItemTaxCountry", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "itemTaxCountry" diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json index 097fe7708..595fb537d 100644 --- a/modules/item/back/models/item.json +++ b/modules/item/back/models/item.json @@ -1,6 +1,9 @@ { "name": "Item", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "item" diff --git a/modules/route/back/models/route.json b/modules/route/back/models/route.json index cdb64dd71..f8be9023c 100644 --- a/modules/route/back/models/route.json +++ b/modules/route/back/models/route.json @@ -1,6 +1,9 @@ { "name": "Route", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "route" diff --git a/modules/shelving/back/models/shelving.json b/modules/shelving/back/models/shelving.json index 3103b5a4a..46fce31e8 100644 --- a/modules/shelving/back/models/shelving.json +++ b/modules/shelving/back/models/shelving.json @@ -1,6 +1,9 @@ { "name": "Shelving", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "shelving" diff --git a/modules/supplier/back/models/supplier-account.json b/modules/supplier/back/models/supplier-account.json index bc9cf0e24..460c435e2 100644 --- a/modules/supplier/back/models/supplier-account.json +++ b/modules/supplier/back/models/supplier-account.json @@ -1,6 +1,9 @@ { "name": "SupplierAccount", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "supplierAccount" diff --git a/modules/supplier/back/models/supplier-address.json b/modules/supplier/back/models/supplier-address.json index 001b3a31f..fcd599287 100644 --- a/modules/supplier/back/models/supplier-address.json +++ b/modules/supplier/back/models/supplier-address.json @@ -1,7 +1,10 @@ { "name": "SupplierAddress", "description": "Supplier addresses", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "supplierAddress" diff --git a/modules/supplier/back/models/supplier-contact.json b/modules/supplier/back/models/supplier-contact.json index f928cd204..4ea1b8c2a 100644 --- a/modules/supplier/back/models/supplier-contact.json +++ b/modules/supplier/back/models/supplier-contact.json @@ -1,6 +1,9 @@ { "name": "SupplierContact", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "supplierContact" diff --git a/modules/supplier/back/models/supplier.json b/modules/supplier/back/models/supplier.json index b6245ef32..59d23f106 100644 --- a/modules/supplier/back/models/supplier.json +++ b/modules/supplier/back/models/supplier.json @@ -1,6 +1,9 @@ { "name": "Supplier", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "supplier" diff --git a/modules/ticket/back/models/expedition.json b/modules/ticket/back/models/expedition.json index 069c6e281..2dcca1e87 100644 --- a/modules/ticket/back/models/expedition.json +++ b/modules/ticket/back/models/expedition.json @@ -1,6 +1,9 @@ { "name": "Expedition", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "expedition" diff --git a/modules/ticket/back/models/sale.json b/modules/ticket/back/models/sale.json index 72ca1f5e0..96a36bbc9 100644 --- a/modules/ticket/back/models/sale.json +++ b/modules/ticket/back/models/sale.json @@ -1,6 +1,9 @@ { "name": "Sale", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "sale" diff --git a/modules/ticket/back/models/ticket-dms.json b/modules/ticket/back/models/ticket-dms.json index 071999be7..a3e697506 100644 --- a/modules/ticket/back/models/ticket-dms.json +++ b/modules/ticket/back/models/ticket-dms.json @@ -1,6 +1,9 @@ { "name": "TicketDms", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "ticketDms" diff --git a/modules/ticket/back/models/ticket-observation.json b/modules/ticket/back/models/ticket-observation.json index 64e49b217..26d6f7586 100644 --- a/modules/ticket/back/models/ticket-observation.json +++ b/modules/ticket/back/models/ticket-observation.json @@ -1,6 +1,9 @@ { "name": "TicketObservation", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "ticketObservation" diff --git a/modules/ticket/back/models/ticket-packaging.json b/modules/ticket/back/models/ticket-packaging.json index 6c94c810e..0cf494809 100644 --- a/modules/ticket/back/models/ticket-packaging.json +++ b/modules/ticket/back/models/ticket-packaging.json @@ -1,6 +1,9 @@ { "name": "TicketPackaging", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "ticketPackaging" diff --git a/modules/ticket/back/models/ticket-refund.json b/modules/ticket/back/models/ticket-refund.json index d344a3f1c..249270c8b 100644 --- a/modules/ticket/back/models/ticket-refund.json +++ b/modules/ticket/back/models/ticket-refund.json @@ -1,6 +1,9 @@ { "name": "TicketRefund", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "ticketRefund" diff --git a/modules/ticket/back/models/ticket-request.json b/modules/ticket/back/models/ticket-request.json index f8407792e..2cfcd30a1 100644 --- a/modules/ticket/back/models/ticket-request.json +++ b/modules/ticket/back/models/ticket-request.json @@ -1,6 +1,9 @@ { "name": "TicketRequest", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "ticketRequest" diff --git a/modules/ticket/back/models/ticket-service.json b/modules/ticket/back/models/ticket-service.json index f1dbede13..4dfbd2fbd 100644 --- a/modules/ticket/back/models/ticket-service.json +++ b/modules/ticket/back/models/ticket-service.json @@ -1,6 +1,9 @@ { "name": "TicketService", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "ticketService" diff --git a/modules/ticket/back/models/ticket-tracking.json b/modules/ticket/back/models/ticket-tracking.json index 8b5ce0b64..472bdb966 100644 --- a/modules/ticket/back/models/ticket-tracking.json +++ b/modules/ticket/back/models/ticket-tracking.json @@ -1,6 +1,9 @@ { "name": "TicketTracking", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "ticketTracking" diff --git a/modules/ticket/back/models/ticket-weekly.json b/modules/ticket/back/models/ticket-weekly.json index c5e485aa2..7494cac79 100644 --- a/modules/ticket/back/models/ticket-weekly.json +++ b/modules/ticket/back/models/ticket-weekly.json @@ -1,6 +1,9 @@ { "name": "TicketWeekly", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "ticketWeekly" diff --git a/modules/ticket/back/models/ticket.json b/modules/ticket/back/models/ticket.json index ec4193bed..c55cd82bb 100644 --- a/modules/ticket/back/models/ticket.json +++ b/modules/ticket/back/models/ticket.json @@ -1,6 +1,9 @@ { "name": "Ticket", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "ticket" diff --git a/modules/travel/back/models/travel-thermograph.json b/modules/travel/back/models/travel-thermograph.json index 08eec2847..cc8e60aaf 100644 --- a/modules/travel/back/models/travel-thermograph.json +++ b/modules/travel/back/models/travel-thermograph.json @@ -1,6 +1,9 @@ { "name": "TravelThermograph", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "travelThermograph" diff --git a/modules/travel/back/models/travel.json b/modules/travel/back/models/travel.json index 95d458121..701894a76 100644 --- a/modules/travel/back/models/travel.json +++ b/modules/travel/back/models/travel.json @@ -1,6 +1,9 @@ { "name": "Travel", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "travel" diff --git a/modules/worker/back/models/device-production-user.json b/modules/worker/back/models/device-production-user.json index 3eeaae137..35a90fb50 100644 --- a/modules/worker/back/models/device-production-user.json +++ b/modules/worker/back/models/device-production-user.json @@ -1,6 +1,9 @@ { "name": "DeviceProductionUser", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "log": { "model": "DeviceProductionLog", "relation": "deviceProduction" diff --git a/modules/worker/back/models/device-production.json b/modules/worker/back/models/device-production.json index 35787cccc..f6e5105ad 100644 --- a/modules/worker/back/models/device-production.json +++ b/modules/worker/back/models/device-production.json @@ -1,6 +1,9 @@ { "name": "DeviceProduction", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "log": { "model": "DeviceProductionLog" }, diff --git a/modules/worker/back/models/worker-dms.json b/modules/worker/back/models/worker-dms.json index e9a9f1773..a5c0f30b2 100644 --- a/modules/worker/back/models/worker-dms.json +++ b/modules/worker/back/models/worker-dms.json @@ -1,6 +1,9 @@ { "name": "WorkerDms", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "workerDocument" diff --git a/modules/worker/back/models/worker.json b/modules/worker/back/models/worker.json index 1a777fffe..ed430f133 100644 --- a/modules/worker/back/models/worker.json +++ b/modules/worker/back/models/worker.json @@ -1,7 +1,10 @@ { "name": "Worker", "description": "Company employees", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "worker" diff --git a/modules/zone/back/models/zone-event.json b/modules/zone/back/models/zone-event.json index e477dad6a..366bdec9d 100644 --- a/modules/zone/back/models/zone-event.json +++ b/modules/zone/back/models/zone-event.json @@ -1,6 +1,9 @@ { "name": "ZoneEvent", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "zoneEvent" diff --git a/modules/zone/back/models/zone-exclusion.json b/modules/zone/back/models/zone-exclusion.json index 00c9145cd..6e91a0a01 100644 --- a/modules/zone/back/models/zone-exclusion.json +++ b/modules/zone/back/models/zone-exclusion.json @@ -1,6 +1,9 @@ { "name": "ZoneExclusion", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "zoneExclusion" diff --git a/modules/zone/back/models/zone-included.json b/modules/zone/back/models/zone-included.json index deba73f34..a34e51091 100644 --- a/modules/zone/back/models/zone-included.json +++ b/modules/zone/back/models/zone-included.json @@ -1,6 +1,9 @@ { "name": "ZoneIncluded", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "zoneIncluded" diff --git a/modules/zone/back/models/zone-warehouse.json b/modules/zone/back/models/zone-warehouse.json index b222e95e7..c2cc989f0 100644 --- a/modules/zone/back/models/zone-warehouse.json +++ b/modules/zone/back/models/zone-warehouse.json @@ -1,6 +1,9 @@ { "name": "ZoneWarehouse", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "zoneWarehouse" diff --git a/modules/zone/back/models/zone.json b/modules/zone/back/models/zone.json index c86da3d3e..cf7371053 100644 --- a/modules/zone/back/models/zone.json +++ b/modules/zone/back/models/zone.json @@ -1,6 +1,9 @@ { "name": "Zone", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "zone" From 6f32a588bbc9faacdb5182cf01477f779af19219 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 5 Dec 2023 07:49:10 +0100 Subject: [PATCH 096/207] refs #5666 feat: add role relation to RoleMapping --- loopback/server/model-config.json | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/loopback/server/model-config.json b/loopback/server/model-config.json index 51874988d..56b5360e8 100644 --- a/loopback/server/model-config.json +++ b/loopback/server/model-config.json @@ -31,6 +31,13 @@ "mysql": { "table": "salix.RoleMapping" } + }, + "relations": { + "role": { + "type": "belongsTo", + "model": "VnRole", + "foreignKey": "roleId" + } } }, "Schema": { From 7a63e527a5298b05028c7721eddbefcfe597f695 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 5 Dec 2023 07:50:52 +0100 Subject: [PATCH 097/207] refs #5666 perf: remove comments --- db/changes/235001/00-updateACL_Role_VnRole.sql | 6 ------ 1 file changed, 6 deletions(-) diff --git a/db/changes/235001/00-updateACL_Role_VnRole.sql b/db/changes/235001/00-updateACL_Role_VnRole.sql index 6fbec02a6..b08a44138 100644 --- a/db/changes/235001/00-updateACL_Role_VnRole.sql +++ b/db/changes/235001/00-updateACL_Role_VnRole.sql @@ -1,12 +1,6 @@ --- Auto-generated SQL script #202311301038 --- INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) --- VALUES ('VnRole','*','*','ALLOW','ROLE','$everyone'); --- INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) --- VALUES ('VnRole','*','*','ALLOW','ROLE','employee'); INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) VALUES ('VnRole','*','READ','ALLOW','ROLE','employee'), ('VnRole','*','WRITE','ALLOW','ROLE','it'); --- Auto-generated SQL script #202311301203 DELETE FROM`salix`.`ACL` WHERE model='Role'; From 318f7e3c0d3d05d498863a7238bddfd380f9cdc7 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 5 Dec 2023 08:20:55 +0100 Subject: [PATCH 098/207] REFS #6275 feat:Silex_to_Salix --- db/changes/235001/00-silexToSalix.sql | 46 +++++++++++++++++++ .../route/back/methods/route/getTickets.js | 26 +++++------ 2 files changed, 59 insertions(+), 13 deletions(-) create mode 100644 db/changes/235001/00-silexToSalix.sql diff --git a/db/changes/235001/00-silexToSalix.sql b/db/changes/235001/00-silexToSalix.sql new file mode 100644 index 000000000..362b967cc --- /dev/null +++ b/db/changes/235001/00-silexToSalix.sql @@ -0,0 +1,46 @@ + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`delivery_beforeInsert` + BEFORE INSERT ON `delivery` + FOR EACH ROW +BEGIN + + IF (NEW.ticketFk IS NOT NULL) + THEN + UPDATE address + SET longitude = NEW.longitude, + latitude = NEW.latitude + WHERE id IN ( + SELECT addressFK + FROM ticket + WHERE id = NEW.ticketFk + ); + END IF; + +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`delivery_beforeUpdate` + BEFORE UPDATE ON `delivery` + FOR EACH ROW +BEGIN + +IF (NEW.longitude <> OLD.longitude OR NEW.latitude <> OLD.latitude OR NEW.ticketFk <> OLD.ticketFk) + THEN + UPDATE address + SET longitude = NEW.longitude, + latitude = NEW.latitude + WHERE id IN ( + SELECT addressFK + FROM ticket + WHERE id = NEW.ticketFk + ); + END IF; + +END$$ +DELIMITER ; + + +ALTER TABLE `vn`.`address` MODIFY COLUMN longitude decimal(11,7) DEFAULT NULL NULL COMMENT 'Indica la última longitud proporcionada por tabla delivery'; +ALTER TABLE `vn`.`address` MODIFY COLUMN latitude decimal(11,7) DEFAULT NULL NULL COMMENT 'Indica la última latitud proporcionada por tabla delivery'; diff --git a/modules/route/back/methods/route/getTickets.js b/modules/route/back/methods/route/getTickets.js index 89c68131a..d1ebf9ee7 100644 --- a/modules/route/back/methods/route/getTickets.js +++ b/modules/route/back/methods/route/getTickets.js @@ -40,27 +40,27 @@ module.exports = Self => { t.clientFk, t.priority, t.addressFk, - st.code AS ticketStateCode, - st.name AS ticketStateName, - wh.name AS warehouseName, - tob.description AS ticketObservation, + st.code ticketStateCode, + st.name ticketStateName, + wh.name warehouseName, + tob.description ticketObservation, a.street, a.postalCode, a.city, - am.name AS agencyModeName, - u.nickname AS userNickname, - vn.ticketTotalVolume(t.id) AS volume, + am.name agencyModeName, + u.nickname userNickname, + vn.ticketTotalVolume(t.id) volume, tob.description, GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt, - c.phone ClientPhone, - c.mobile ClientMobile, - a.phone AddressPhone, - a.mobile AddressMobile, + c.phone clientPhone, + c.mobile clientMobile, + a.phone addressPhone, + a.mobile addressMobile, a.longitude, a.latitude, - wm.mediaValue SalePersonPhone, + wm.mediaValue salePersonPhone, t.cmrFk, - t.isSigned Signed + t.isSigned signed FROM vn.route r JOIN ticket t ON t.routeFk = r.id JOIN client c ON t.clientFk = c.id From af07a531ed5c92f313b5b3f4313b3f03bb9dacb9 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 5 Dec 2023 08:49:55 +0100 Subject: [PATCH 099/207] refs #6318 quantity --- modules/ticket/back/methods/ticket-request/confirm.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ticket/back/methods/ticket-request/confirm.js b/modules/ticket/back/methods/ticket-request/confirm.js index 00310f33c..e782bd66e 100644 --- a/modules/ticket/back/methods/ticket-request/confirm.js +++ b/modules/ticket/back/methods/ticket-request/confirm.js @@ -63,7 +63,7 @@ module.exports = Self => { const isAvailable = itemStock.available > 0; - if (!isAvailable) + if (!isAvailable || !ctx.args.quantity) throw new UserError(`This item is not available`); if (request.saleFk) From 419ab418160579a6fa8f420a4fe098199d1f0a8e Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 5 Dec 2023 09:55:22 +0100 Subject: [PATCH 100/207] refs #6276 Acl addTimeEntry --- db/changes/235001/00-timecontrol.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/changes/235001/00-timecontrol.sql b/db/changes/235001/00-timecontrol.sql index 4e350b002..8b59c1cac 100644 --- a/db/changes/235001/00-timecontrol.sql +++ b/db/changes/235001/00-timecontrol.sql @@ -8,6 +8,6 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp VALUES ('WorkerTimeControl', 'login', 'READ', 'ALLOW', 'ROLE', 'timeControl'), ('WorkerTimeControl', 'getClockIn', 'READ', 'ALLOW', 'ROLE', 'timeControl'), - ('WorkerTimeControl', 'clockIn', 'WRITE', 'ALLOW', 'ROLE', 'timeControl'); + ('WorkerTimeControl', 'addTimeEntry', 'WRITE', 'ALLOW', 'ROLE', 'timeControl'); CALL `account`.`role_sync`(); From f55e85a189ddb7244d45eeb205e9dea3f4183894 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 5 Dec 2023 10:35:48 +0100 Subject: [PATCH 101/207] refs #6010 remove pending --- modules/ticket/back/methods/ticket/specs/filter.spec.js | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/ticket/back/methods/ticket/specs/filter.spec.js b/modules/ticket/back/methods/ticket/specs/filter.spec.js index 43f3c3680..c1d3f1a9c 100644 --- a/modules/ticket/back/methods/ticket/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket/specs/filter.spec.js @@ -141,7 +141,6 @@ describe('ticket filter()', () => { }); it('should return the tickets that are not pending', async() => { - pending('#6010 test intermitente'); const tx = await models.Ticket.beginTransaction({}); try { From 25006a938be9214bcd62690d5c3c1709053a0e26 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 5 Dec 2023 11:53:27 +0100 Subject: [PATCH 102/207] refs #6274 refactor clockIn --- db/changes/235001/00-timecontrol.sql | 2 +- .../methods/worker-time-control/addTimeEntry.js | 5 +---- .../back/methods/worker-time-control/clockIn.js | 16 +++++++++++++--- 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/db/changes/235001/00-timecontrol.sql b/db/changes/235001/00-timecontrol.sql index 8b59c1cac..4e350b002 100644 --- a/db/changes/235001/00-timecontrol.sql +++ b/db/changes/235001/00-timecontrol.sql @@ -8,6 +8,6 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp VALUES ('WorkerTimeControl', 'login', 'READ', 'ALLOW', 'ROLE', 'timeControl'), ('WorkerTimeControl', 'getClockIn', 'READ', 'ALLOW', 'ROLE', 'timeControl'), - ('WorkerTimeControl', 'addTimeEntry', 'WRITE', 'ALLOW', 'ROLE', 'timeControl'); + ('WorkerTimeControl', 'clockIn', 'WRITE', 'ALLOW', 'ROLE', 'timeControl'); CALL `account`.`role_sync`(); diff --git a/modules/worker/back/methods/worker-time-control/addTimeEntry.js b/modules/worker/back/methods/worker-time-control/addTimeEntry.js index cc652fb90..f3b0127c4 100644 --- a/modules/worker/back/methods/worker-time-control/addTimeEntry.js +++ b/modules/worker/back/methods/worker-time-control/addTimeEntry.js @@ -46,10 +46,7 @@ module.exports = Self => { if (!isSubordinate || (isSubordinate && isHimself && !isTeamBoss)) throw new UserError(`You don't have enough privileges`); - query = `CALL vn.workerTimeControl_clockIn(?,?,?)`; - const [response] = await Self.rawSql(query, [workerId, args.timed, args.direction], myOptions); - if (response[0] && response[0].error) - throw new UserError(response[0].error); + const response = await Self.clockIn(workerId, args.timed, args.direction, myOptions); await models.WorkerTimeControl.resendWeeklyHourEmail(ctx, workerId, args.timed, myOptions); diff --git a/modules/worker/back/methods/worker-time-control/clockIn.js b/modules/worker/back/methods/worker-time-control/clockIn.js index 3cc57d341..6ed742778 100644 --- a/modules/worker/back/methods/worker-time-control/clockIn.js +++ b/modules/worker/back/methods/worker-time-control/clockIn.js @@ -1,3 +1,5 @@ +const UserError = require('vn-loopback/util/user-error'); + module.exports = Self => { Self.remoteMethod('clockIn', { description: 'Check if the employee can clock in', @@ -8,6 +10,10 @@ module.exports = Self => { type: 'integer', required: true, }, + { + arg: 'timed', + type: 'date' + }, { arg: 'direction', type: 'string' @@ -24,12 +30,16 @@ module.exports = Self => { } }); - Self.clockIn = async(workerFk, direction, options) => { + Self.clockIn = async(workerFk, timed, direction, options) => { const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); - const query = 'CALL vn.workerTimeControl_clockIn(?, NULL, ?)'; - return await Self.rawSql(query, [workerFk, direction], myOptions); + const query = 'CALL vn.workerTimeControl_clockIn(?, ?, ?)'; + const [response] = await Self.rawSql(query, [workerFk, timed, direction], myOptions); + if (response[0] && response[0].error) + throw new UserError(response[0].error); + + return response; }; }; From 035b31d878cb989e64f3dc06cd75ff539aad6f74 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 5 Dec 2023 12:00:31 +0100 Subject: [PATCH 103/207] refs #5666 test: fix e2e tests --- front/core/directives/rule.js | 6 +++++- modules/account/front/role/basic-data/index.html | 10 +++++++--- modules/account/front/role/create/index.html | 4 ++-- modules/account/front/role/descriptor/index.html | 2 +- 4 files changed, 15 insertions(+), 7 deletions(-) diff --git a/front/core/directives/rule.js b/front/core/directives/rule.js index f65efe176..d944e13ed 100644 --- a/front/core/directives/rule.js +++ b/front/core/directives/rule.js @@ -23,7 +23,7 @@ export function directive($translate, $window) { let rule = $attrs.rule.split('.'); let modelName = rule.shift(); let fieldName = rule.shift(); - + let modelAlias = $attrs.ruleAlias; let split = $attrs.ngModel.split('.'); if (!fieldName) fieldName = split.pop() || null; if (!modelName) modelName = firstUpper(split.pop() || ''); @@ -31,8 +31,12 @@ export function directive($translate, $window) { if (!modelName || !fieldName) throw new Error(`rule: Cannot retrieve model or field attribute`); + let modelValidations = vnValidations[modelName]; + if (!modelValidations) + modelValidations = vnValidations[modelAlias]; + if (!modelValidations) throw new Error(`rule: Model '${modelName}' doesn't exist`); diff --git a/modules/account/front/role/basic-data/index.html b/modules/account/front/role/basic-data/index.html index a6d39f3e3..46cb080b7 100644 --- a/modules/account/front/role/basic-data/index.html +++ b/modules/account/front/role/basic-data/index.html @@ -7,6 +7,7 @@
@@ -14,12 +15,15 @@ label="Name" ng-model="$ctrl.role.name" rule + rule-alias="VnRole" vn-focus> + label="Description" + ng-model="$ctrl.role.description" + rule + rule-alias="VnRole" + > diff --git a/modules/account/front/role/create/index.html b/modules/account/front/role/create/index.html index b747f7d00..ee43484d7 100644 --- a/modules/account/front/role/create/index.html +++ b/modules/account/front/role/create/index.html @@ -13,13 +13,13 @@ diff --git a/modules/account/front/role/descriptor/index.html b/modules/account/front/role/descriptor/index.html index 4cd4ac822..d8bf4857a 100644 --- a/modules/account/front/role/descriptor/index.html +++ b/modules/account/front/role/descriptor/index.html @@ -24,4 +24,4 @@ on-accept="$ctrl.onDelete()" question="Are you sure you want to continue?" message="Role will be removed"> - \ No newline at end of file + From a5fb07bf127a81e2e9e80935e89ae8840b28babe Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 5 Dec 2023 13:05:26 +0100 Subject: [PATCH 104/207] 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 b50a6add0d5e7cc2678a35ff9707f20457dec769 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 5 Dec 2023 15:57:42 +0100 Subject: [PATCH 105/207] refs #6274 merge renewToken --- db/changes/235001/00-timecontrol.sql | 3 ++- db/changes/{234601 => 235001}/00-updateCourtesyTime.sql | 0 2 files changed, 2 insertions(+), 1 deletion(-) rename db/changes/{234601 => 235001}/00-updateCourtesyTime.sql (100%) diff --git a/db/changes/235001/00-timecontrol.sql b/db/changes/235001/00-timecontrol.sql index 4e350b002..0d3bd59b2 100644 --- a/db/changes/235001/00-timecontrol.sql +++ b/db/changes/235001/00-timecontrol.sql @@ -8,6 +8,7 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp VALUES ('WorkerTimeControl', 'login', 'READ', 'ALLOW', 'ROLE', 'timeControl'), ('WorkerTimeControl', 'getClockIn', 'READ', 'ALLOW', 'ROLE', 'timeControl'), - ('WorkerTimeControl', 'clockIn', 'WRITE', 'ALLOW', 'ROLE', 'timeControl'); + ('WorkerTimeControl', 'clockIn', 'WRITE', 'ALLOW', 'ROLE', 'timeControl'), + ('VnUser', 'renewToken', 'WRITE', 'ALLOW', 'ROLE', 'timeControl'); CALL `account`.`role_sync`(); diff --git a/db/changes/234601/00-updateCourtesyTime.sql b/db/changes/235001/00-updateCourtesyTime.sql similarity index 100% rename from db/changes/234601/00-updateCourtesyTime.sql rename to db/changes/235001/00-updateCourtesyTime.sql From c9bcd672c90af292ed5ef81b5619fe9493daec80 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 7 Dec 2023 07:59:21 +0100 Subject: [PATCH 106/207] refs #6028 add:email in ByWorker --- modules/route/back/methods/route/filter.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/modules/route/back/methods/route/filter.js b/modules/route/back/methods/route/filter.js index afefa77d1..ea2f0533e 100644 --- a/modules/route/back/methods/route/filter.js +++ b/modules/route/back/methods/route/filter.js @@ -130,13 +130,15 @@ module.exports = Self => { am.name agencyName, u.name AS workerUserName, v.numberPlate AS vehiclePlateNumber, - Date_format(r.time, '%H:%i') hour + Date_format(r.time, '%H:%i') hour, + eu.email FROM route r LEFT JOIN agencyMode am ON am.id = r.agencyModeFk LEFT JOIN agency a ON a.id = am.agencyFk LEFT JOIN vehicle v ON v.id = r.vehicleFk LEFT JOIN worker w ON w.id = r.workerFk - LEFT JOIN account.user u ON u.id = w.id` + LEFT JOIN account.user u ON u.id = w.id + LEFT JOIN account.emailUser eu ON eu.userFk = r.workerFk` ); stmt.merge(conn.makeSuffix(filter)); From 0263d880caec8672234a3e90b4a3fb71981b6f7c Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 7 Dec 2023 08:00:17 +0100 Subject: [PATCH 107/207] refs #6028 add:email in ByWorker --- modules/route/back/methods/route/filter.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/route/back/methods/route/filter.js b/modules/route/back/methods/route/filter.js index ea2f0533e..7c2225dc9 100644 --- a/modules/route/back/methods/route/filter.js +++ b/modules/route/back/methods/route/filter.js @@ -138,7 +138,7 @@ module.exports = Self => { LEFT JOIN vehicle v ON v.id = r.vehicleFk LEFT JOIN worker w ON w.id = r.workerFk LEFT JOIN account.user u ON u.id = w.id - LEFT JOIN account.emailUser eu ON eu.userFk = r.workerFk` + LEFT JOIN account.emailUser eu ON eu.userFk = r.workerFk` ); stmt.merge(conn.makeSuffix(filter)); From 58ba1c10d0029c0b62c72e14748ccd88685f8195 Mon Sep 17 00:00:00 2001 From: jgallego Date: Thu, 7 Dec 2023 08:01:16 +0100 Subject: [PATCH 108/207] ci: dev-test --- CHANGELOG.md | 6 ++++++ db/changes/235201/.gitkeep | 0 package.json | 2 +- 3 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 db/changes/235201/.gitkeep diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bc8ae021..dfdc563fb 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). +## [2352.01] - 2023-12-28 + +### Added +### Changed +### Fixed + ## [2350.01] - 2023-12-14 ### Added diff --git a/db/changes/235201/.gitkeep b/db/changes/235201/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/package.json b/package.json index 586c963dd..66a5cd2fa 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "23.50.01", + "version": "23.52.01", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", From 61ed53bd1d75f3bbc0e0478231a2c60b8033aba6 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 7 Dec 2023 10:37:06 +0100 Subject: [PATCH 109/207] REFS #6275 feat:Silex_to_Salix --- db/changes/235001/00-silexToSalix.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/changes/235001/00-silexToSalix.sql b/db/changes/235001/00-silexToSalix.sql index 362b967cc..bad430ac2 100644 --- a/db/changes/235001/00-silexToSalix.sql +++ b/db/changes/235001/00-silexToSalix.sql @@ -5,7 +5,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`delivery_beforeInsert FOR EACH ROW BEGIN - IF (NEW.ticketFk IS NOT NULL) + IF (NEW.longitude IS NOT NULL AND NEW.latitude IS NOT NULL AND NEW.ticketFK IS NOT NULL) THEN UPDATE address SET longitude = NEW.longitude, @@ -26,7 +26,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`delivery_beforeUpdate FOR EACH ROW BEGIN -IF (NEW.longitude <> OLD.longitude OR NEW.latitude <> OLD.latitude OR NEW.ticketFk <> OLD.ticketFk) +IF (NEW.longitude IS NOT NULL AND NEW.latitude IS NOT NULL AND NEW.ticketFK IS NOT NULL) THEN UPDATE address SET longitude = NEW.longitude, From fa65cc84a9e98b9d3c7e059b67ae0b797c261e86 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 7 Dec 2023 11:39:22 +0100 Subject: [PATCH 110/207] REFS #6275 feat:Silex_to_Salix --- .../methods/route/specs/getExpeditionSummary.spec.js | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 modules/route/back/methods/route/specs/getExpeditionSummary.spec.js diff --git a/modules/route/back/methods/route/specs/getExpeditionSummary.spec.js b/modules/route/back/methods/route/specs/getExpeditionSummary.spec.js new file mode 100644 index 000000000..b2147aa0b --- /dev/null +++ b/modules/route/back/methods/route/specs/getExpeditionSummary.spec.js @@ -0,0 +1,10 @@ +const app = require('vn-loopback/server/server'); + +describe('route getExpeditionSummary()', () => { + const routeId = 1; + fit('should return a summary of expeditions for a route', async() => { + const result = await app.models.Route.getExpeditionSummary(routeId); + + expect(result.length).toEqual(3); + }); +}); From 9937fbed5e77c1986ee4a5076c1df53aa05b3d56 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 7 Dec 2023 11:59:01 +0100 Subject: [PATCH 111/207] REFS #6275 feat:Silex_to_Salix --- .../route/back/methods/route/specs/getExpeditionSummary.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/route/back/methods/route/specs/getExpeditionSummary.spec.js b/modules/route/back/methods/route/specs/getExpeditionSummary.spec.js index b2147aa0b..bdc124227 100644 --- a/modules/route/back/methods/route/specs/getExpeditionSummary.spec.js +++ b/modules/route/back/methods/route/specs/getExpeditionSummary.spec.js @@ -2,7 +2,7 @@ const app = require('vn-loopback/server/server'); describe('route getExpeditionSummary()', () => { const routeId = 1; - fit('should return a summary of expeditions for a route', async() => { + it('should return a summary of expeditions for a route', async() => { const result = await app.models.Route.getExpeditionSummary(routeId); expect(result.length).toEqual(3); From 7e9134ecc385967ab71eb1b81a9a3ccdb9e13d59 Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 7 Dec 2023 13:47:07 +0100 Subject: [PATCH 112/207] refs #5971 change sql address --- print/templates/reports/invoice/invoice.html | 4 ++++ print/templates/reports/invoice/sql/tickets.sql | 5 ++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/print/templates/reports/invoice/invoice.html b/print/templates/reports/invoice/invoice.html index 45b6c3934..af1aaa423 100644 --- a/print/templates/reports/invoice/invoice.html +++ b/print/templates/reports/invoice/invoice.html @@ -16,6 +16,7 @@ {{$t('clientId')}} {{client.id}} + {{$t('invoice')}} @@ -80,6 +81,9 @@ {{formatDate(ticket.shipped, '%d-%m-%Y')}} + +

{{ticket.street}}

+

{{ticket.nickname}}

diff --git a/print/templates/reports/invoice/sql/tickets.sql b/print/templates/reports/invoice/sql/tickets.sql index a8385599c..35828c5de 100644 --- a/print/templates/reports/invoice/sql/tickets.sql +++ b/print/templates/reports/invoice/sql/tickets.sql @@ -2,9 +2,12 @@ SELECT t.id, t.shipped, t.nickname, - tto.description + tto.description, + t.addressFk, + a.street FROM invoiceOut io JOIN ticket t ON t.refFk = io.REF + JOIN `address` a ON a.id = t.addressFk LEFT JOIN observationType ot ON ot.code = 'invoiceOut' LEFT JOIN ticketObservation tto ON tto.ticketFk = t.id AND tto.observationTypeFk = ot.id From 968dc6523132aab070131880afe6bdad55c0931f Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 7 Dec 2023 14:47:22 +0100 Subject: [PATCH 113/207] refs #6274 tests created --- .../worker-time-control/addTimeEntry.js | 8 ++---- .../methods/worker-time-control/clockIn.js | 2 +- .../methods/worker-time-control/getClockIn.js | 4 +-- .../resendWeeklyHourEmail.js | 2 +- .../worker-time-control/specs/clockIn.spec.js | 28 +++++++++++++++++++ .../specs/getClockIn.spec.js | 16 +++++++++++ .../worker-time-control/specs/login.spec.js | 20 +++++++++++++ 7 files changed, 70 insertions(+), 10 deletions(-) create mode 100644 modules/worker/back/methods/worker-time-control/specs/clockIn.spec.js create mode 100644 modules/worker/back/methods/worker-time-control/specs/getClockIn.spec.js create mode 100644 modules/worker/back/methods/worker-time-control/specs/login.spec.js diff --git a/modules/worker/back/methods/worker-time-control/addTimeEntry.js b/modules/worker/back/methods/worker-time-control/addTimeEntry.js index f3b0127c4..96e3a47d9 100644 --- a/modules/worker/back/methods/worker-time-control/addTimeEntry.js +++ b/modules/worker/back/methods/worker-time-control/addTimeEntry.js @@ -43,13 +43,9 @@ module.exports = Self => { const isTeamBoss = await models.ACL.checkAccessAcl(ctx, 'Worker', 'isTeamBoss', 'WRITE'); const isHimself = userId == workerId; - if (!isSubordinate || (isSubordinate && isHimself && !isTeamBoss)) + if (!isSubordinate || (isHimself && !isTeamBoss)) throw new UserError(`You don't have enough privileges`); - const response = await Self.clockIn(workerId, args.timed, args.direction, myOptions); - - await models.WorkerTimeControl.resendWeeklyHourEmail(ctx, workerId, args.timed, myOptions); - - return response; + return await Self.clockIn(workerId, args.timed, args.direction, myOptions); }; }; diff --git a/modules/worker/back/methods/worker-time-control/clockIn.js b/modules/worker/back/methods/worker-time-control/clockIn.js index 6ed742778..2e2441cc2 100644 --- a/modules/worker/back/methods/worker-time-control/clockIn.js +++ b/modules/worker/back/methods/worker-time-control/clockIn.js @@ -7,7 +7,7 @@ module.exports = Self => { accepts: [ { arg: 'workerFk', - type: 'integer', + type: 'number', required: true, }, { diff --git a/modules/worker/back/methods/worker-time-control/getClockIn.js b/modules/worker/back/methods/worker-time-control/getClockIn.js index bc0675db8..470700643 100644 --- a/modules/worker/back/methods/worker-time-control/getClockIn.js +++ b/modules/worker/back/methods/worker-time-control/getClockIn.js @@ -25,8 +25,8 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const query = `CALL vn.workerTimeControl_getClockIn(?, CURDATE())`; - const [result] = await Self.rawSql(query, [workerFk], myOptions); + const query = `CALL vn.workerTimeControl_getClockIn(?, ?)`; + const [result] = await Self.rawSql(query, [workerFk, Date.vnNew()], myOptions); return result; }; }; diff --git a/modules/worker/back/methods/worker-time-control/resendWeeklyHourEmail.js b/modules/worker/back/methods/worker-time-control/resendWeeklyHourEmail.js index 2452a29f9..896458455 100644 --- a/modules/worker/back/methods/worker-time-control/resendWeeklyHourEmail.js +++ b/modules/worker/back/methods/worker-time-control/resendWeeklyHourEmail.js @@ -1,6 +1,6 @@ module.exports = Self => { Self.remoteMethodCtx('resendWeeklyHourEmail', { - description: 'Adds a new hour registry', + description: 'Send the records for the week of the date provided', accessType: 'WRITE', accepts: [{ arg: 'id', diff --git a/modules/worker/back/methods/worker-time-control/specs/clockIn.spec.js b/modules/worker/back/methods/worker-time-control/specs/clockIn.spec.js new file mode 100644 index 000000000..970fd2fe2 --- /dev/null +++ b/modules/worker/back/methods/worker-time-control/specs/clockIn.spec.js @@ -0,0 +1,28 @@ +const models = require('vn-loopback/server/server').models; + +describe('workerTimeControl clockIn()', () => { + const workerId = 9; + const inTime = '2001-01-01T00:00:00.000Z'; + + it('should correctly clock in', async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + + try { + const options = {transaction: tx}; + await models.WorkerTimeControl.clockIn(workerId, inTime, 'in', options); + const isClockIn = await models.WorkerTimeControl.findOne({ + where: { + userFk: workerId + } + }, options); + + expect(isClockIn).toBeDefined(); + expect(isClockIn.direction).toBe('in'); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); + diff --git a/modules/worker/back/methods/worker-time-control/specs/getClockIn.spec.js b/modules/worker/back/methods/worker-time-control/specs/getClockIn.spec.js new file mode 100644 index 000000000..d75ffac70 --- /dev/null +++ b/modules/worker/back/methods/worker-time-control/specs/getClockIn.spec.js @@ -0,0 +1,16 @@ +const models = require('vn-loopback/server/server').models; + +describe('workerTimeControl getClockIn()', () => { + it('should correctly get the timetable of a worker', async() => { + const response = await models.WorkerTimeControl.getClockIn(1106, {}); + + expect(response.length).toEqual(4); + const [inHrs, middleOutHrs, middleInHrs, outHrs] = response; + + expect(inHrs['0daysAgo']).toEqual('07:00'); + expect(middleOutHrs['0daysAgo']).toEqual('10:00'); + expect(middleInHrs['0daysAgo']).toEqual('10:20'); + expect(outHrs['0daysAgo']).toEqual('14:50'); + }); +}); + diff --git a/modules/worker/back/methods/worker-time-control/specs/login.spec.js b/modules/worker/back/methods/worker-time-control/specs/login.spec.js new file mode 100644 index 000000000..88596f297 --- /dev/null +++ b/modules/worker/back/methods/worker-time-control/specs/login.spec.js @@ -0,0 +1,20 @@ +const UserError = require('vn-loopback/util/user-error'); +const models = require('vn-loopback/server/server').models; + +describe('workerTimeControl login()', () => { + it('should correctly login', async() => { + const response = await models.WorkerTimeControl.login(9, {}); + + expect(response.name).toBe('developer'); + }); + + it('should throw UserError if pin is not provided', async() => { + try { + await models.WorkerTimeControl.login(); + } catch (error) { + expect(error).toBeInstanceOf(UserError); + expect(error.message).toBe('Indique el pin.'); + } + }); +}); + From b86c73777fe4970326e249843913f6226d824087 Mon Sep 17 00:00:00 2001 From: JAVIER SEGARRA MARTINEZ Date: Thu, 7 Dec 2023 19:05:54 +0000 Subject: [PATCH 114/207] Update back/tests.js --- back/tests.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/back/tests.js b/back/tests.js index 97e548d33..efade4d7d 100644 --- a/back/tests.js +++ b/back/tests.js @@ -7,6 +7,10 @@ process.on('warning', warning => { console.log(warning.stack); }); +process.on('SIGUSR2', async() => { + if (container) await container.rm(); +}); + process.on('exit', async function() { if (container) await container.rm(); }); From 5a99408ba7295439a3a8061380b009dcf153731e Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 11 Dec 2023 07:31:57 +0100 Subject: [PATCH 115/207] feat: refs #6548 add buyer department to salesPerson list in client BasicData --- modules/client/front/basic-data/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/client/front/basic-data/index.html b/modules/client/front/basic-data/index.html index e48b39fdc..acab99d91 100644 --- a/modules/client/front/basic-data/index.html +++ b/modules/client/front/basic-data/index.html @@ -62,7 +62,7 @@ From ec66386b442a292329819041dca82b2c2677b2b6 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 11 Dec 2023 07:49:44 +0100 Subject: [PATCH 116/207] refs #5914 fix: correct sql folder --- db/changes/{235001 => 235201}/00-getTaxBases.sql | 0 db/changes/{235001 => 235201}/01-newHasAnyPositiveBase.sql | 0 db/changes/{235001 => 235201}/01-refactorHasAnyNegativeBase.sql | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename db/changes/{235001 => 235201}/00-getTaxBases.sql (100%) rename db/changes/{235001 => 235201}/01-newHasAnyPositiveBase.sql (100%) rename db/changes/{235001 => 235201}/01-refactorHasAnyNegativeBase.sql (100%) diff --git a/db/changes/235001/00-getTaxBases.sql b/db/changes/235201/00-getTaxBases.sql similarity index 100% rename from db/changes/235001/00-getTaxBases.sql rename to db/changes/235201/00-getTaxBases.sql diff --git a/db/changes/235001/01-newHasAnyPositiveBase.sql b/db/changes/235201/01-newHasAnyPositiveBase.sql similarity index 100% rename from db/changes/235001/01-newHasAnyPositiveBase.sql rename to db/changes/235201/01-newHasAnyPositiveBase.sql diff --git a/db/changes/235001/01-refactorHasAnyNegativeBase.sql b/db/changes/235201/01-refactorHasAnyNegativeBase.sql similarity index 100% rename from db/changes/235001/01-refactorHasAnyNegativeBase.sql rename to db/changes/235201/01-refactorHasAnyNegativeBase.sql From 584f3264edc86712c840998d5794c9b34c7fd632 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 11 Dec 2023 08:54:58 +0100 Subject: [PATCH 117/207] refs #6085 refactor sql trad --- .../{235001 => 235201}/00-aclsMails.sql | 0 front/core/locale/es.yml | 2 +- loopback/locale/es.json | 6 +- .../account/back/models/mail-alias-account.js | 14 ++--- modules/account/back/models/mail-alias-acl.js | 55 ------------------- 5 files changed, 9 insertions(+), 68 deletions(-) rename db/changes/{235001 => 235201}/00-aclsMails.sql (100%) delete mode 100644 modules/account/back/models/mail-alias-acl.js diff --git a/db/changes/235001/00-aclsMails.sql b/db/changes/235201/00-aclsMails.sql similarity index 100% rename from db/changes/235001/00-aclsMails.sql rename to db/changes/235201/00-aclsMails.sql diff --git a/front/core/locale/es.yml b/front/core/locale/es.yml index 1b9bbb40b..17e955ff5 100644 --- a/front/core/locale/es.yml +++ b/front/core/locale/es.yml @@ -68,4 +68,4 @@ Load more results: Cargar más resultados Send cau: Enviar cau By sending this ticket, all the data related to the error, the section, the user, etc., are already sent.: Al enviar este cau ya se envían todos los datos relacionados con el error, la sección, el usuario, etc ExplainReason: Explique el motivo por el que no deberia aparecer este fallo -You already have the mailAlias: Ya tienes este mail +You already have the mailAlias: Ya tienes este alias de correo diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 2e516bf12..c26bf3ebc 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -330,6 +330,6 @@ "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}}", - "You already have the mailAlias": "You already have the mailAlias", - "The alias cant be modified": "The alias cant be modified" -} \ No newline at end of file + "You already have the mailAlias": "Ya tienes este alias de correo", + "The alias cant be modified": "Este alias de correo no puede ser modificado" +} diff --git a/modules/account/back/models/mail-alias-account.js b/modules/account/back/models/mail-alias-account.js index a95189689..91fc43008 100644 --- a/modules/account/back/models/mail-alias-account.js +++ b/modules/account/back/models/mail-alias-account.js @@ -22,12 +22,6 @@ module.exports = Self => { async function checkModifyPermission(ctx, mailAliasFk) { const userId = ctx.options.accessToken.userId; - const available = await Self.getAvailable(userId); - if (!available.has(mailAliasFk)) - throw new UserError('The alias cant be modified'); - } - - Self.getAvailable = async function(userId, options) { const models = Self.app.models; const myOptions = {}; @@ -47,9 +41,11 @@ module.exports = Self => { roleFk: { inq: roles.map(role => role.roleId), }, + mailAliasFk } }, myOptions); - const mailAliasArray = Array.from(availableMailAlias, alias => alias.mailAliasFk); - return new Set(mailAliasArray); - }; + + console.log(availableMailAlias); + if (!availableMailAlias.length) throw new UserError('The alias cant be modified'); + } }; diff --git a/modules/account/back/models/mail-alias-acl.js b/modules/account/back/models/mail-alias-acl.js deleted file mode 100644 index a95189689..000000000 --- a/modules/account/back/models/mail-alias-acl.js +++ /dev/null @@ -1,55 +0,0 @@ - -const UserError = require('vn-loopback/util/user-error'); - -module.exports = Self => { - Self.rewriteDbError(function(err) { - if (err.code === 'ER_DUP_ENTRY') - return new UserError(`You already have the mailAlias`); - return err; - }); - - Self.observe('before save', async ctx => { - const changes = ctx.currentInstance || ctx.instance; - - await checkModifyPermission(ctx, changes.mailAlias); - }); - - Self.observe('before delete', async ctx => { - const mailAliasAccount = await Self.findById(ctx.where.id); - - await checkModifyPermission(ctx, mailAliasAccount.mailAlias); - }); - - async function checkModifyPermission(ctx, mailAliasFk) { - const userId = ctx.options.accessToken.userId; - const available = await Self.getAvailable(userId); - if (!available.has(mailAliasFk)) - throw new UserError('The alias cant be modified'); - } - - Self.getAvailable = async function(userId, options) { - const models = Self.app.models; - - const myOptions = {}; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - const roles = await models.RoleMapping.find({ - fields: ['roleId'], - where: {principalId: userId} - }, myOptions); - - const availableMailAlias = await models.MailAliasAcl.find({ - fields: ['mailAliasFk'], - include: {relation: 'mailAlias'}, - where: { - roleFk: { - inq: roles.map(role => role.roleId), - }, - } - }, myOptions); - const mailAliasArray = Array.from(availableMailAlias, alias => alias.mailAliasFk); - return new Set(mailAliasArray); - }; -}; From 57ed36cdfc3a0015da94a0eacc74bb0bbcef1505 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 11 Dec 2023 09:43:38 +0100 Subject: [PATCH 118/207] ref #6085 remove console options --- modules/account/back/models/mail-alias-account.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/modules/account/back/models/mail-alias-account.js b/modules/account/back/models/mail-alias-account.js index 91fc43008..cf9c73f3b 100644 --- a/modules/account/back/models/mail-alias-account.js +++ b/modules/account/back/models/mail-alias-account.js @@ -26,8 +26,7 @@ module.exports = Self => { const myOptions = {}; - if (typeof options == 'object') - Object.assign(myOptions, options); + Object.assign(myOptions); const roles = await models.RoleMapping.find({ fields: ['roleId'], @@ -45,7 +44,6 @@ module.exports = Self => { } }, myOptions); - console.log(availableMailAlias); if (!availableMailAlias.length) throw new UserError('The alias cant be modified'); } }; From 6ac5d28c4003cd7a192955d5538e5074e45d8b11 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 11 Dec 2023 09:59:09 +0100 Subject: [PATCH 119/207] refs #6085 fix back --- back/models/specs/mailAliasAccount.spec.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/back/models/specs/mailAliasAccount.spec.js b/back/models/specs/mailAliasAccount.spec.js index d26ed2313..c13cc7ae8 100644 --- a/back/models/specs/mailAliasAccount.spec.js +++ b/back/models/specs/mailAliasAccount.spec.js @@ -6,8 +6,8 @@ describe('loopback model MailAliasAccount', () => { let error; try { - const options = {transaction: tx, accessToken: {userId: 1}}; - await models.MailAliasAccount.create({mailAliasFk: 2, roleFk: 5}, options); + const options = {transaction: tx, accessToken: {userId: 57}}; + await models.MailAliasAccount.create({mailAlias: 2, account: 5}, options); await tx.rollback(); } catch (e) { From 53ff8784ffd8c388b3f3607a1d09977980fa4cf3 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 11 Dec 2023 10:16:46 +0100 Subject: [PATCH 120/207] refs #6085 remove myOptions --- modules/account/back/models/mail-alias-account.js | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/modules/account/back/models/mail-alias-account.js b/modules/account/back/models/mail-alias-account.js index cf9c73f3b..8f8e45ae8 100644 --- a/modules/account/back/models/mail-alias-account.js +++ b/modules/account/back/models/mail-alias-account.js @@ -24,14 +24,10 @@ module.exports = Self => { const userId = ctx.options.accessToken.userId; const models = Self.app.models; - const myOptions = {}; - - Object.assign(myOptions); - const roles = await models.RoleMapping.find({ fields: ['roleId'], where: {principalId: userId} - }, myOptions); + }); const availableMailAlias = await models.MailAliasAcl.find({ fields: ['mailAliasFk'], @@ -42,7 +38,7 @@ module.exports = Self => { }, mailAliasFk } - }, myOptions); + }); if (!availableMailAlias.length) throw new UserError('The alias cant be modified'); } From 09ad31a92def0a95fc8066c12dd717dbeb8021f4 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 11 Dec 2023 10:58:48 +0100 Subject: [PATCH 121/207] feat: refs #6172 Requested changes --- front/salix/module.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/front/salix/module.js b/front/salix/module.js index bb7e189a9..62d6cac98 100644 --- a/front/salix/module.js +++ b/front/salix/module.js @@ -120,7 +120,7 @@ function $exceptionHandler(vnApp, $window, $state, $injector) { messageT = 'Invalid login'; break; case 403: - messageT = exception.data.error.message || 'Access denied'; + messageT = exception.data?.error?.message || 'Access denied'; break; case 502: messageT = 'It seems that the server has fall down'; From d1f0557923efb2fa1e774ad1b6a3a590fb94f27d Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 11 Dec 2023 12:40:16 +0100 Subject: [PATCH 122/207] refs #5666 perf: remove ruleAlias property --- front/core/directives/rule.js | 5 ----- modules/account/front/role/basic-data/index.html | 6 ++---- modules/account/front/role/card/index.spec.js | 4 ++-- modules/account/front/role/descriptor/index.spec.js | 4 ++-- 4 files changed, 6 insertions(+), 13 deletions(-) diff --git a/front/core/directives/rule.js b/front/core/directives/rule.js index d944e13ed..34781c2aa 100644 --- a/front/core/directives/rule.js +++ b/front/core/directives/rule.js @@ -23,7 +23,6 @@ export function directive($translate, $window) { let rule = $attrs.rule.split('.'); let modelName = rule.shift(); let fieldName = rule.shift(); - let modelAlias = $attrs.ruleAlias; let split = $attrs.ngModel.split('.'); if (!fieldName) fieldName = split.pop() || null; if (!modelName) modelName = firstUpper(split.pop() || ''); @@ -31,12 +30,8 @@ export function directive($translate, $window) { if (!modelName || !fieldName) throw new Error(`rule: Cannot retrieve model or field attribute`); - let modelValidations = vnValidations[modelName]; - if (!modelValidations) - modelValidations = vnValidations[modelAlias]; - if (!modelValidations) throw new Error(`rule: Model '${modelName}' doesn't exist`); diff --git a/modules/account/front/role/basic-data/index.html b/modules/account/front/role/basic-data/index.html index 46cb080b7..846f8b455 100644 --- a/modules/account/front/role/basic-data/index.html +++ b/modules/account/front/role/basic-data/index.html @@ -14,15 +14,13 @@ diff --git a/modules/account/front/role/card/index.spec.js b/modules/account/front/role/card/index.spec.js index f39840e5f..f02c08f28 100644 --- a/modules/account/front/role/card/index.spec.js +++ b/modules/account/front/role/card/index.spec.js @@ -1,6 +1,6 @@ import './index'; -describe('component vnRoleCard', () => { +fdescribe('component vnRoleCard', () => { let controller; let $httpBackend; @@ -15,7 +15,7 @@ describe('component vnRoleCard', () => { it('should reload the controller data', () => { controller.$params.id = 1; - $httpBackend.expectGET('Roles/1').respond('foo'); + $httpBackend.expectGET('VnRoles/1').respond('foo'); controller.reload(); $httpBackend.flush(); diff --git a/modules/account/front/role/descriptor/index.spec.js b/modules/account/front/role/descriptor/index.spec.js index e2761c639..eafb96727 100644 --- a/modules/account/front/role/descriptor/index.spec.js +++ b/modules/account/front/role/descriptor/index.spec.js @@ -1,6 +1,6 @@ import './index'; -describe('component vnRoleDescriptor', () => { +fdescribe('component vnRoleDescriptor', () => { let controller; let $httpBackend; @@ -18,7 +18,7 @@ describe('component vnRoleDescriptor', () => { controller.$state.go = jest.fn(); jest.spyOn(controller.vnApp, 'showSuccess'); - $httpBackend.expectDELETE('Roles/1').respond(); + $httpBackend.expectDELETE('VnRoles/1').respond(); controller.onDelete(); $httpBackend.flush(); From 2beb1f65f09847b78ec5e486af4f359a36887cb0 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 11 Dec 2023 12:45:55 +0100 Subject: [PATCH 123/207] refs #6085 findOne --- modules/account/back/models/mail-alias-account.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/account/back/models/mail-alias-account.js b/modules/account/back/models/mail-alias-account.js index 8f8e45ae8..5eb561408 100644 --- a/modules/account/back/models/mail-alias-account.js +++ b/modules/account/back/models/mail-alias-account.js @@ -29,7 +29,7 @@ module.exports = Self => { where: {principalId: userId} }); - const availableMailAlias = await models.MailAliasAcl.find({ + const availableMailAlias = await models.MailAliasAcl.findOne({ fields: ['mailAliasFk'], include: {relation: 'mailAlias'}, where: { @@ -40,6 +40,6 @@ module.exports = Self => { } }); - if (!availableMailAlias.length) throw new UserError('The alias cant be modified'); + if (!availableMailAlias) throw new UserError('The alias cant be modified'); } }; From f817551a57f1e9b04682d642dfb4d5b7a926d84e Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 11 Dec 2023 12:59:02 +0100 Subject: [PATCH 124/207] refs #5666 perf: remove ruleAlias property --- modules/account/front/role/create/index.html | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/account/front/role/create/index.html b/modules/account/front/role/create/index.html index ee43484d7..77d6fc2c1 100644 --- a/modules/account/front/role/create/index.html +++ b/modules/account/front/role/create/index.html @@ -13,14 +13,14 @@ + ng-model="$ctrl.role.description" + rule="VnRole.description"> From 84270587cb8beeeab9db0aa56a5af1c1e26250d2 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 11 Dec 2023 13:42:19 +0100 Subject: [PATCH 125/207] refs #6274 refactor --- modules/worker/back/methods/worker-time-control/addTimeEntry.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/worker/back/methods/worker-time-control/addTimeEntry.js b/modules/worker/back/methods/worker-time-control/addTimeEntry.js index 96e3a47d9..5dbac51ca 100644 --- a/modules/worker/back/methods/worker-time-control/addTimeEntry.js +++ b/modules/worker/back/methods/worker-time-control/addTimeEntry.js @@ -46,6 +46,6 @@ module.exports = Self => { if (!isSubordinate || (isHimself && !isTeamBoss)) throw new UserError(`You don't have enough privileges`); - return await Self.clockIn(workerId, args.timed, args.direction, myOptions); + return Self.clockIn(workerId, args.timed, args.direction, myOptions); }; }; From c81ca94d2e5c8d7e1a5cb94e2d2da1c0f23dcdce Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 11 Dec 2023 14:44:33 +0100 Subject: [PATCH 126/207] 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 127/207] 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 128/207] 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 ea39f8b3be10e0f92c143d398a21bdfb82463739 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 12 Dec 2023 12:25:51 +0100 Subject: [PATCH 129/207] remove duplicate --- db/dump/fixtures.sql | 4 ---- 1 file changed, 4 deletions(-) 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'; From 6cefc982e46261dd680e7e1d5797a2d2ffd1daa9 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 12 Dec 2023 13:14:41 +0100 Subject: [PATCH 130/207] 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 131/207] 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 132/207] 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 133/207] 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 134/207] 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 135/207] 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 136/207] 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 137/207] 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 138/207] 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 435819cf3cb32ff3e28007baf6491537db97fe6c Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 13 Dec 2023 07:24:13 +0100 Subject: [PATCH 139/207] refs #6275 feat:Silex_to_Salix test getExpeditionSummary --- .../route/back/methods/route/specs/getExpeditionSummary.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/route/back/methods/route/specs/getExpeditionSummary.spec.js b/modules/route/back/methods/route/specs/getExpeditionSummary.spec.js index bdc124227..9d70c339a 100644 --- a/modules/route/back/methods/route/specs/getExpeditionSummary.spec.js +++ b/modules/route/back/methods/route/specs/getExpeditionSummary.spec.js @@ -5,6 +5,6 @@ describe('route getExpeditionSummary()', () => { it('should return a summary of expeditions for a route', async() => { const result = await app.models.Route.getExpeditionSummary(routeId); - expect(result.length).toEqual(3); + expect(result.every(route => route.id = routeId)).toBeTruthy(); }); }); From 2393625a48ddbaf72f33be6420212fa3b8e3d232 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 13 Dec 2023 08:22:58 +0100 Subject: [PATCH 140/207] 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 69dd34665fa79a717477b638339437f72958044c Mon Sep 17 00:00:00 2001 From: pablone Date: Wed, 13 Dec 2023 08:50:17 +0100 Subject: [PATCH 141/207] refactor(renameTable): refs #6125 clientCreditLimit to roleCreditLimit --- db/changes/235201/00-clientCreditLimitToRoleCreditLimit.sql | 4 ++++ db/dump/fixtures.sql | 2 +- modules/client/back/model-config.json | 2 +- modules/client/back/models/client.js | 2 +- .../{client-credit-limit.json => role-credit-limit.json} | 4 ++-- 5 files changed, 9 insertions(+), 5 deletions(-) create mode 100644 db/changes/235201/00-clientCreditLimitToRoleCreditLimit.sql rename modules/client/back/models/{client-credit-limit.json => role-credit-limit.json} (85%) diff --git a/db/changes/235201/00-clientCreditLimitToRoleCreditLimit.sql b/db/changes/235201/00-clientCreditLimitToRoleCreditLimit.sql new file mode 100644 index 000000000..bf4cc6002 --- /dev/null +++ b/db/changes/235201/00-clientCreditLimitToRoleCreditLimit.sql @@ -0,0 +1,4 @@ +RENAME TABLE `vn`.`clientCreditLimit` TO `vn`.`roleCreditLimit`; +ALTER TABLE `vn`.`clientCreditLimit` 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/dump/fixtures.sql b/db/dump/fixtures.sql index 3354e95c2..78793a31a 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -493,7 +493,7 @@ INSERT INTO `vn`.`clientCredit`(`clientFk`, `workerFk`, `amount`, `created`) (1104, 9, 90 , util.VN_CURDATE()), (1105, 9, 90 , util.VN_CURDATE()); -INSERT INTO `vn`.`clientCreditLimit`(`id`, `maxAmount`, `roleFk`) +INSERT INTO `vn`.`roleCreditLimit`(`id`, `maxAmount`, `roleFk`) VALUES (1, 9999999, 20), (2, 10000, 21), diff --git a/modules/client/back/model-config.json b/modules/client/back/model-config.json index 0cc5df9a2..a21407732 100644 --- a/modules/client/back/model-config.json +++ b/modules/client/back/model-config.json @@ -29,7 +29,7 @@ "ClientCredit": { "dataSource": "vn" }, - "ClientCreditLimit": { + "RoleCreditLimit": { "dataSource": "vn" }, "ClientConsumptionQueue": { diff --git a/modules/client/back/models/client.js b/modules/client/back/models/client.js index 72b702779..a9e14effa 100644 --- a/modules/client/back/models/client.js +++ b/modules/client/back/models/client.js @@ -463,7 +463,7 @@ module.exports = Self => { throw new UserError(`You can't change the credit set to zero from a financialBoss`); } - const creditLimits = await models.ClientCreditLimit.find({ + const creditLimits = await models.RoleCreditLimit.find({ fields: ['roleFk'], where: { maxAmount: {gte: changes.credit} diff --git a/modules/client/back/models/client-credit-limit.json b/modules/client/back/models/role-credit-limit.json similarity index 85% rename from modules/client/back/models/client-credit-limit.json rename to modules/client/back/models/role-credit-limit.json index 740f0cf53..4ea28b1a4 100644 --- a/modules/client/back/models/client-credit-limit.json +++ b/modules/client/back/models/role-credit-limit.json @@ -1,9 +1,9 @@ { - "name": "ClientCreditLimit", + "name": "RoleCreditLimit", "base": "VnModel", "options": { "mysql": { - "table": "clientCreditLimit" + "table": "roleCreditLimit" } }, "properties": { From 2f61b648f732c8125c67ffff095504d985a136c8 Mon Sep 17 00:00:00 2001 From: davidd Date: Wed, 13 Dec 2023 09:49:03 +0100 Subject: [PATCH 142/207] refs #6398 --- db/changes/{235001 => 235201}/00-alterTable.sql | 0 db/changes/{235001 => 235201}/01-procedures.sql | 0 db/changes/{235001 => 235201}/02-views.sql | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename db/changes/{235001 => 235201}/00-alterTable.sql (100%) rename db/changes/{235001 => 235201}/01-procedures.sql (100%) rename db/changes/{235001 => 235201}/02-views.sql (100%) diff --git a/db/changes/235001/00-alterTable.sql b/db/changes/235201/00-alterTable.sql similarity index 100% rename from db/changes/235001/00-alterTable.sql rename to db/changes/235201/00-alterTable.sql diff --git a/db/changes/235001/01-procedures.sql b/db/changes/235201/01-procedures.sql similarity index 100% rename from db/changes/235001/01-procedures.sql rename to db/changes/235201/01-procedures.sql diff --git a/db/changes/235001/02-views.sql b/db/changes/235201/02-views.sql similarity index 100% rename from db/changes/235001/02-views.sql rename to db/changes/235201/02-views.sql From 5b3645a6419e765cf186b4280d22594f83acfb7d Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 13 Dec 2023 11:59:00 +0100 Subject: [PATCH 143/207] 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 144/207] 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 145/207] 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 d4fa1e9acaed06ef4dd30b1f44853c2c0420a822 Mon Sep 17 00:00:00 2001 From: davidd Date: Wed, 13 Dec 2023 12:04:07 +0100 Subject: [PATCH 146/207] refs #6398 --- db/changes/235201/02-views.sql | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/db/changes/235201/02-views.sql b/db/changes/235201/02-views.sql index d399bb3b4..a0f41594d 100644 --- a/db/changes/235201/02-views.sql +++ b/db/changes/235201/02-views.sql @@ -32,3 +32,21 @@ AS SELECT `tt`.`id` AS `inter_id`, `tt`.`userFk` AS `Id_Trabajador`, `tt`.`supervisorFk` AS `Id_supervisor` FROM `vn`.`ticketTracking` `tt`; + +CREATE OR REPLACE +ALGORITHM = UNDEFINED VIEW `ticketStateToday` AS +SELECT + `ts`.`ticket` AS `ticket`, + `ts`.`state` AS `state`, + `ts`.`productionOrder` AS `productionOrder`, + `ts`.`alertLevel` AS `alertLevel`, + `ts`.`userFk` AS `userFk`, + `ts`.`code` AS `code`, + `ts`.`updated` AS `updated`, + `ts`.`isPicked` AS `isPicked` +FROM + (`ticketState` `ts` +JOIN `ticket` `t` ON + (`t`.`id` = `ts`.`ticket`)) +WHERE + `t`.`shipped` BETWEEN `util`.`VN_CURDATE`() AND `MIDNIGHT`(`util`.`VN_CURDATE`()); From 6af99b7669f0ff0ac8a5b4110993686968d11dd5 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 13 Dec 2023 12:07:41 +0100 Subject: [PATCH 147/207] 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 148/207] 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 149/207] 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 150/207] 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 151/207] 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 152/207] 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 153/207] 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 154/207] 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 155/207] 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 156/207] 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 157/207] 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 158/207] 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 159/207] 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 160/207] 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 161/207] 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 162/207] 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 163/207] 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 164/207] 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 e89ec55839e065aaabb34d4df3a4472cb20c452d Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 14 Dec 2023 15:09:07 +0100 Subject: [PATCH 165/207] fix: refs #6172 --- e2e/paths/08-route/03_create_and_clone.spec.js | 2 +- front/core/services/locale/en.yml | 2 +- front/core/services/locale/es.yml | 2 +- front/salix/module.js | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/e2e/paths/08-route/03_create_and_clone.spec.js b/e2e/paths/08-route/03_create_and_clone.spec.js index 0b8da98b4..31c0cfc18 100644 --- a/e2e/paths/08-route/03_create_and_clone.spec.js +++ b/e2e/paths/08-route/03_create_and_clone.spec.js @@ -26,7 +26,7 @@ describe('Route create path', () => { await page.waitToClick(selectors.createRouteView.submitButton); const message = await page.waitForSnackbar(); - expect(message.text).toContain('Access denied'); + expect(message.text).toContain('Access Denied'); }); }); diff --git a/front/core/services/locale/en.yml b/front/core/services/locale/en.yml index 2be73e696..8eb8a6f0d 100644 --- a/front/core/services/locale/en.yml +++ b/front/core/services/locale/en.yml @@ -3,4 +3,4 @@ Could not contact the server: Could not contact the server, make sure you have a Please enter your username: Please enter your username It seems that the server has fall down: It seems that the server has fall down, wait a few minutes and try again Session has expired: Your session has expired, please login again -Access denied: Access denied \ No newline at end of file +Access Denied: Access Denied \ No newline at end of file diff --git a/front/core/services/locale/es.yml b/front/core/services/locale/es.yml index e9811e38f..2c43ca3b2 100644 --- a/front/core/services/locale/es.yml +++ b/front/core/services/locale/es.yml @@ -3,5 +3,5 @@ Could not contact the server: No se ha podido contactar con el servidor, asegura Please enter your username: Por favor introduce tu nombre de usuario It seems that the server has fall down: Parece que el servidor se ha caído, espera unos minutos e inténtalo de nuevo Session has expired: Tu sesión ha expirado, por favor vuelve a iniciar sesión -Access denied: Acción no permitida +Access Denied: Acción no permitida Direction not found: Dirección no encontrada diff --git a/front/salix/module.js b/front/salix/module.js index 62d6cac98..0ce855308 100644 --- a/front/salix/module.js +++ b/front/salix/module.js @@ -120,7 +120,7 @@ function $exceptionHandler(vnApp, $window, $state, $injector) { messageT = 'Invalid login'; break; case 403: - messageT = exception.data?.error?.message || 'Access denied'; + messageT = exception.data?.error?.message || 'Access Denied'; break; case 502: messageT = 'It seems that the server has fall down'; From 21a1dbeae7fe4a9d9fe75ef910efbdb0fd023dde Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 14 Dec 2023 15:56:49 +0100 Subject: [PATCH 166/207] refs #5914 fix: ticket canBeInvoiced and optimized invoiceTickets --- .../235201/01-refactorHasAnyNegativeBase.sql | 1 + db/dump/fixtures.sql | 2 +- e2e/paths/05-ticket/18_index_payout.spec.js | 2 +- e2e/paths/09-invoice-out/01_summary.spec.js | 4 +-- loopback/locale/en.json | 6 ++-- loopback/locale/es.json | 9 +++-- .../methods/client/specs/consumption.spec.js | 4 +-- .../invoiceOut/specs/transferinvoice.spec.js | 26 ++++++++++++++- .../front/descriptor-menu/index.html | 2 +- .../invoiceOut/front/index/manual/index.html | 1 + .../back/methods/ticket/canBeInvoiced.js | 23 +++---------- .../back/methods/ticket/invoiceTickets.js | 33 ++++++++----------- .../ticket/back/methods/ticket/makeInvoice.js | 2 +- 13 files changed, 64 insertions(+), 51 deletions(-) diff --git a/db/changes/235201/01-refactorHasAnyNegativeBase.sql b/db/changes/235201/01-refactorHasAnyNegativeBase.sql index b6780e280..65822fc95 100644 --- a/db/changes/235201/01-refactorHasAnyNegativeBase.sql +++ b/db/changes/235201/01-refactorHasAnyNegativeBase.sql @@ -26,3 +26,4 @@ BEGIN END$$ DELIMITER ; + diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 874e42787..127bf5ef0 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -720,7 +720,7 @@ INSERT INTO `vn`.`route`(`id`, `time`, `workerFk`, `created`, `vehicleFk`, `agen INSERT INTO `vn`.`ticket`(`id`, `priority`, `agencyModeFk`,`warehouseFk`,`routeFk`, `shipped`, `landed`, `clientFk`,`nickname`, `addressFk`, `refFk`, `isDeleted`, `zoneFk`, `zonePrice`, `zoneBonus`, `created`, `weight`) VALUES (1 , 3, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 121, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1), - (2 , 1, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2), + (2 , 1, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 1, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2), (3 , 1, 7, 1, 6, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -2 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 3, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), NULL), (4 , 3, 2, 1, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -3 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 9, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), NULL), (5 , 3, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -4 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), NULL), diff --git a/e2e/paths/05-ticket/18_index_payout.spec.js b/e2e/paths/05-ticket/18_index_payout.spec.js index 7e5201d11..9c5518424 100644 --- a/e2e/paths/05-ticket/18_index_payout.spec.js +++ b/e2e/paths/05-ticket/18_index_payout.spec.js @@ -35,7 +35,7 @@ describe('Ticket index payout path', () => { await page.waitToClick(selectors.ticketsIndex.openAdvancedSearchButton); await page.write(selectors.ticketsIndex.advancedSearchClient, '1101'); await page.keyboard.press('Enter'); - await page.waitForNumberOfElements(selectors.ticketsIndex.anySearchResult, 9); + await page.waitForNumberOfElements(selectors.ticketsIndex.anySearchResult, 10); await page.waitToClick(selectors.ticketsIndex.firstTicketCheckbox); await page.waitToClick(selectors.ticketsIndex.secondTicketCheckbox); diff --git a/e2e/paths/09-invoice-out/01_summary.spec.js b/e2e/paths/09-invoice-out/01_summary.spec.js index 728f0130a..09ac66ffc 100644 --- a/e2e/paths/09-invoice-out/01_summary.spec.js +++ b/e2e/paths/09-invoice-out/01_summary.spec.js @@ -28,7 +28,6 @@ describe('InvoiceOut summary path', () => { it('should contain the tax breakdown', async() => { const firstTax = await page.waitToGetProperty(selectors.invoiceOutSummary.taxOne, 'innerText'); - const secondTax = await page.waitToGetProperty(selectors.invoiceOutSummary.taxTwo, 'innerText'); expect(firstTax).toContain('10%'); @@ -37,10 +36,9 @@ describe('InvoiceOut summary path', () => { it('should contain the tickets info', async() => { const firstTicket = await page.waitToGetProperty(selectors.invoiceOutSummary.ticketOne, 'innerText'); - const secondTicket = await page.waitToGetProperty(selectors.invoiceOutSummary.ticketTwo, 'innerText'); expect(firstTicket).toContain('Bat cave'); - expect(secondTicket).toContain('Stark tower'); + expect(secondTicket).toContain('Bat cave'); }); }); diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 7d5b5ed47..962e1ea13 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -45,6 +45,7 @@ "Extension format is invalid": "Extension format is invalid", "NO_ZONE_FOR_THIS_PARAMETERS": "NO_ZONE_FOR_THIS_PARAMETERS", "This client can't be invoiced": "This client can't be invoiced", + "You must provide the correction information to generate a corrective invoice": "You must provide the correction information to generate a corrective invoice", "The introduced hour already exists": "The introduced hour already exists", "Invalid parameters to create a new ticket": "Invalid parameters to create a new ticket", "Concept cannot be blank": "Concept cannot be blank", @@ -178,7 +179,8 @@ "The renew period has not been exceeded": "The renew period has not been exceeded", "You can not use the same password": "You can not use the same password", "Valid priorities": "Valid priorities: %d", - "Negative basis of tickets": "Negative basis of tickets: {{ticketsIds}}", + "hasAnyNegativeBase": "Negative basis of tickets: {{ticketsIds}}", + "hasAnyPositiveBase": "Positive basis of tickets: {{ticketsIds}}", "This ticket cannot be left empty.": "This ticket cannot be left empty. %s", "Social name should be uppercase": "Social name should be uppercase", "Street should be uppercase": "Street should be uppercase", @@ -201,4 +203,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 e544be0e6..0c2ad3238 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -72,6 +72,7 @@ "The secret can't be blank": "La contraseña no puede estar en blanco", "We weren't able to send this SMS": "No hemos podido enviar el SMS", "This client can't be invoiced": "Este cliente no puede ser facturado", + "You must provide the correction information to generate a corrective invoice": "Debes informar la información de corrección para generar una factura rectificativa", "This ticket can't be invoiced": "Este ticket no puede ser facturado", "You cannot add or modify services to an invoiced ticket": "No puedes añadir o modificar servicios a un ticket facturado", "This ticket can not be modified": "Este ticket no puede ser modificado", @@ -305,7 +306,8 @@ "Mail not sent": "Se ha producido un fallo al enviar la factura al cliente [{{clientId}}]({{{clientUrl}}}), por favor revisa la dirección de correo electrónico", "The renew period has not been exceeded": "El periodo de renovación no ha sido superado", "Valid priorities": "Prioridades válidas: %d", - "Negative basis of tickets": "Base negativa para los tickets: {{ticketsIds}}", + "hasAnyNegativeBase": "Base negativa para los tickets: {{ticketsIds}}", + "hasAnyPositiveBase": "Base positivas para los tickets: {{ticketsIds}}", "You cannot assign an alias that you are not assigned to": "No puede asignar un alias que no tenga asignado", "This ticket cannot be left empty.": "Este ticket no se puede dejar vacío. %s", "The company has not informed the supplier account for bank transfers": "La empresa no tiene informado la cuenta de proveedor para transferencias bancarias", @@ -330,5 +332,8 @@ "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", "No tickets to invoice": "No hay tickets para facturar", - "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}" + "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", + "Base negativa para los tickets: 39": "Base negativa para los tickets: 39", + "Base negativa para los tickets: 41": "Base negativa para los tickets: 41", + "keepPrice": "keepPrice" } diff --git a/modules/client/back/methods/client/specs/consumption.spec.js b/modules/client/back/methods/client/specs/consumption.spec.js index 47a495d79..85dbb7422 100644 --- a/modules/client/back/methods/client/specs/consumption.spec.js +++ b/modules/client/back/methods/client/specs/consumption.spec.js @@ -16,7 +16,7 @@ describe('client consumption() filter', () => { }; const result = await models.Client.consumption(ctx, filter, options); - expect(result.length).toEqual(10); + expect(result.length).toEqual(11); await tx.rollback(); } catch (e) { @@ -49,7 +49,7 @@ describe('client consumption() filter', () => { const thirdRow = result[2]; expect(result.length).toEqual(3); - expect(firstRow.quantity).toEqual(10); + expect(firstRow.quantity).toEqual(11); expect(secondRow.quantity).toEqual(15); expect(thirdRow.quantity).toEqual(20); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js index b3bd17826..11575999a 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js @@ -2,7 +2,7 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); -describe('InvoiceOut tranferInvoice()', () => { +describe('InvoiceOut transferInvoice()', () => { const activeCtx = { accessToken: {userId: 5}, http: { @@ -69,9 +69,33 @@ describe('InvoiceOut tranferInvoice()', () => { await models.InvoiceOut.transferInvoice( ctx, options); + await tx.rollback(); } catch (e) { expect(e.message).toBe(`Select a different client`); await tx.rollback(); } }); + + it('should throw an UserError when it is refund', async() => { + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; + const args = { + id: '1', + refFk: 'T1111111', + newClientFk: 1102, + cplusRectificationTypeFk: 1, + siiTypeInvoiceOutFk: 1, + invoiceCorrectionTypeFk: 1 + }; + ctx.args = args; + try { + await models.InvoiceOut.transferInvoice( + ctx, + options); + await tx.rollback(); + } catch (e) { + expect(e.message).toContain(`This ticket is already a refund`); + await tx.rollback(); + } + }); }); diff --git a/modules/invoiceOut/front/descriptor-menu/index.html b/modules/invoiceOut/front/descriptor-menu/index.html index 267aa0b15..435db3612 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.html +++ b/modules/invoiceOut/front/descriptor-menu/index.html @@ -227,7 +227,7 @@ vn-one vn-id="siiTypeInvoiceOut" data="siiTypeInvoiceOuts" - show-field="code" + show-field="description" value-field="id" fields="['id','code','description']" required="true" diff --git a/modules/invoiceOut/front/index/manual/index.html b/modules/invoiceOut/front/index/manual/index.html index c3362a319..5872911e4 100644 --- a/modules/invoiceOut/front/index/manual/index.html +++ b/modules/invoiceOut/front/index/manual/index.html @@ -6,6 +6,7 @@ auto-load="true" url="InvoiceOutSerials" data="invoiceOutSerials" + where="{code: {neq: 'R'}}" order="code"> { diff --git a/modules/ticket/back/methods/ticket/invoiceTickets.js b/modules/ticket/back/methods/ticket/invoiceTickets.js index 212f6556a..f1793773b 100644 --- a/modules/ticket/back/methods/ticket/invoiceTickets.js +++ b/modules/ticket/back/methods/ticket/invoiceTickets.js @@ -47,10 +47,10 @@ module.exports = function(Self) { let invoicesIds = []; try { const tickets = await models.Ticket.find({ + fields: ['id', 'clientFk', 'companyFk', 'addressFk'], where: { id: {inq: ticketsIds} - }, - fields: ['id', 'clientFk', 'companyFk'] + } }, myOptions); const [firstTicket] = tickets; @@ -65,18 +65,17 @@ module.exports = function(Self) { fields: ['id', 'hasToInvoiceByAddress'] }, myOptions); + let ticketsByAddress = {[firstTicket.addressFk]: ticketsIds}; if (client.hasToInvoiceByAddress) { - const query = ` - SELECT DISTINCT addressFk - FROM ticket t - WHERE id IN (?)`; - const result = await Self.rawSql(query, [ticketsIds], myOptions); - - const addressIds = result.map(address => address.addressFk); - for (const address of addressIds) - await createInvoice(ctx, companyId, ticketsIds, address, invoicesIds, invoiceCorrection, myOptions); - } else - await createInvoice(ctx, companyId, ticketsIds, null, invoicesIds, invoiceCorrection, myOptions); + ticketsByAddress = tickets.reduce((group, ticket) => { + const {addressFk} = ticket; + group[addressFk] = group[addressFk] ?? []; + group[addressFk].push(ticket.id); + return group; + }, {}); + } + for (const ticketIds of Object.values(ticketsByAddress)) + invoicesIds.push(await createInvoice(ctx, companyId, ticketIds, invoiceCorrection, myOptions)); if (tx) await tx.commit(); } catch (e) { @@ -91,7 +90,7 @@ module.exports = function(Self) { return invoicesIds; }; - async function createInvoice(ctx, companyId, ticketsIds, address, invoicesIds, invoiceCorrection, myOptions) { + async function createInvoice(ctx, companyId, ticketsIds, invoiceCorrection, myOptions) { const models = Self.app.models; await models.Ticket.rawSql(` CREATE OR REPLACE TEMPORARY TABLE tmp.ticketToInvoice @@ -100,12 +99,8 @@ module.exports = function(Self) { SELECT id FROM vn.ticket WHERE id IN (?) - ${address ? `AND addressFk = ${address}` : ''} `, [ticketsIds], myOptions); - - const invoiceId = - await models.Ticket.makeInvoice(ctx, 'R', companyId, Date.vnNew(), invoiceCorrection, myOptions); - invoicesIds.push(invoiceId); + return models.Ticket.makeInvoice(ctx, 'R', companyId, Date.vnNew(), invoiceCorrection, myOptions); } }; diff --git a/modules/ticket/back/methods/ticket/makeInvoice.js b/modules/ticket/back/methods/ticket/makeInvoice.js index fe7e527c8..32aa03f9d 100644 --- a/modules/ticket/back/methods/ticket/makeInvoice.js +++ b/modules/ticket/back/methods/ticket/makeInvoice.js @@ -106,7 +106,7 @@ module.exports = function(Self) { ); } - if (resultInvoice.id) // serial != 'R' && + if (resultInvoice.id) await Self.rawSql('CALL invoiceOutBooking(?)', [resultInvoice.id], myOptions); if (tx) await tx.commit(); From c755b1e6fa7f948b78d9de47e6fad5c43f14a198 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 15 Dec 2023 08:50:22 +0100 Subject: [PATCH 167/207] refs #5914 fix: correct sql version --- db/changes/{235201 => 235001}/00-getTaxBases.sql | 0 db/changes/{235201 => 235001}/01-newHasAnyPositiveBase.sql | 0 db/changes/{235201 => 235001}/01-refactorHasAnyNegativeBase.sql | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename db/changes/{235201 => 235001}/00-getTaxBases.sql (100%) rename db/changes/{235201 => 235001}/01-newHasAnyPositiveBase.sql (100%) rename db/changes/{235201 => 235001}/01-refactorHasAnyNegativeBase.sql (100%) diff --git a/db/changes/235201/00-getTaxBases.sql b/db/changes/235001/00-getTaxBases.sql similarity index 100% rename from db/changes/235201/00-getTaxBases.sql rename to db/changes/235001/00-getTaxBases.sql diff --git a/db/changes/235201/01-newHasAnyPositiveBase.sql b/db/changes/235001/01-newHasAnyPositiveBase.sql similarity index 100% rename from db/changes/235201/01-newHasAnyPositiveBase.sql rename to db/changes/235001/01-newHasAnyPositiveBase.sql diff --git a/db/changes/235201/01-refactorHasAnyNegativeBase.sql b/db/changes/235001/01-refactorHasAnyNegativeBase.sql similarity index 100% rename from db/changes/235201/01-refactorHasAnyNegativeBase.sql rename to db/changes/235001/01-refactorHasAnyNegativeBase.sql From 59f2e3d0e62c16c1822210bb7a71730bd3625025 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 15 Dec 2023 08:54:41 +0100 Subject: [PATCH 168/207] refs #5914 fix: remove unnecessary --- db/dump/structure.sql | 30 ------------------------------ loopback/locale/es.json | 3 +-- 2 files changed, 1 insertion(+), 32 deletions(-) diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 4e1695185..1db4252f4 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -26391,36 +26391,6 @@ CREATE TABLE `cplusCorrectingType` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; --- --- Table structure for table `cplusInvoiceType472` --- - -DROP TABLE IF EXISTS `cplusInvoiceType472`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cplusInvoiceType472` ( - `id` int(10) unsigned NOT NULL, - `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='(*18) TIPO FACTURA (Asientos)SOPORTADO – DEDUCIBLE (472)'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `siiTypeInvoiceOut` --- - -DROP TABLE IF EXISTS `siiTypeInvoiceOut`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `siiTypeInvoiceOut` ( - `id` int(10) unsigned NOT NULL, - `code` varchar(2) NOT NULL, - `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `code_UNIQUE` (`code`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tipo de Factura Emitidas en el suministro de inmediato'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Table structure for table `cplusRectificationType` -- diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 0c2ad3238..3a1cdfe99 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -334,6 +334,5 @@ "No tickets to invoice": "No hay tickets para facturar", "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", "Base negativa para los tickets: 39": "Base negativa para los tickets: 39", - "Base negativa para los tickets: 41": "Base negativa para los tickets: 41", - "keepPrice": "keepPrice" + "Base negativa para los tickets: 41": "Base negativa para los tickets: 41" } From 356fe6869635c241b897e8531b202aebe46b563c Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 15 Dec 2023 08:57:09 +0100 Subject: [PATCH 169/207] refs #5914 fix: remove unnecessary translation --- loopback/locale/es.json | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 3a1cdfe99..e137beb2d 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -332,7 +332,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", "No tickets to invoice": "No hay tickets para facturar", - "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", - "Base negativa para los tickets: 39": "Base negativa para los tickets: 39", - "Base negativa para los tickets: 41": "Base negativa para los tickets: 41" + "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}" } From c9af8cba816a04088347151447c833616371c306 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Fri, 15 Dec 2023 12:50:05 +0100 Subject: [PATCH 170/207] 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 171/207] 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 172/207] 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 173/207] 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 174/207] 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 175/207] 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 7777696cf75d7ce20c18bdc48f40ad251a0a5b6f Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 19 Dec 2023 13:58:08 +0100 Subject: [PATCH 176/207] refs #6589 fix(worker_absences): fix started hours --- modules/worker/back/methods/calendar/absences.js | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/worker/back/methods/calendar/absences.js b/modules/worker/back/methods/calendar/absences.js index 8420ed770..8a5d18987 100644 --- a/modules/worker/back/methods/calendar/absences.js +++ b/modules/worker/back/methods/calendar/absences.js @@ -39,6 +39,7 @@ module.exports = Self => { started.setFullYear(year); started.setMonth(0); started.setDate(1); + started.setHours(0, 0, 0, 0); const ended = Date.vnNew(); ended.setFullYear(year); From 516a3760a183fc42d5ea42fa3a6b7a90f8154a41 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 20 Dec 2023 07:27:13 +0100 Subject: [PATCH 177/207] 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 178/207] 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 179/207] 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 180/207] 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 542b09073e627bd4cc442c2a98979e370cdedf54 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 20 Dec 2023 14:02:05 +0100 Subject: [PATCH 181/207] changes moved: refs #6274 --- db/changes/{235001 => 235201}/00-timecontrol.sql | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename db/changes/{235001 => 235201}/00-timecontrol.sql (100%) diff --git a/db/changes/235001/00-timecontrol.sql b/db/changes/235201/00-timecontrol.sql similarity index 100% rename from db/changes/235001/00-timecontrol.sql rename to db/changes/235201/00-timecontrol.sql From 7b0c5fe0a00b5b8ce3410c8e69736e7615afe2d5 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 21 Dec 2023 08:33:50 +0100 Subject: [PATCH 182/207] 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 183/207] 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 f384616d693ae5c3121effb1baa815e4388c9865 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 21 Dec 2023 08:57:46 +0100 Subject: [PATCH 184/207] move changes: refs #6274 --- db/changes/{235001 => 240201}/00-updateCourtesyTime.sql | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename db/changes/{235001 => 240201}/00-updateCourtesyTime.sql (100%) diff --git a/db/changes/235001/00-updateCourtesyTime.sql b/db/changes/240201/00-updateCourtesyTime.sql similarity index 100% rename from db/changes/235001/00-updateCourtesyTime.sql rename to db/changes/240201/00-updateCourtesyTime.sql From 0f20f95dc581f9454f84f8f944812735083a411b Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 21 Dec 2023 10:08:17 +0100 Subject: [PATCH 185/207] refactor: refs #6433 Deleted isPreviousPrepared* columns in model --- modules/shelving/back/models/sector.json | 8 -------- 1 file changed, 8 deletions(-) diff --git a/modules/shelving/back/models/sector.json b/modules/shelving/back/models/sector.json index 47d66bd8d..5ff67491b 100644 --- a/modules/shelving/back/models/sector.json +++ b/modules/shelving/back/models/sector.json @@ -20,18 +20,10 @@ "type": "number", "required": true }, - "isPreviousPreparedByPacking": { - "type": "boolean", - "required": true - }, "code": { "type": "string", "required": false }, - "isPreviousPrepared": { - "type": "boolean", - "required": true - }, "isPackagingArea": { "type": "boolean", "required": true From dc661f298bfe6c8f4f858bbee0097472435c7379 Mon Sep 17 00:00:00 2001 From: JAVIER SEGARRA MARTINEZ Date: Thu, 21 Dec 2023 09:10:18 +0000 Subject: [PATCH 186/207] 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 187/207] 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 0998b5bf2cfb59d4864cc24f8d6b1aceab9f2495 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 21 Dec 2023 13:58:33 +0100 Subject: [PATCH 188/207] add locale and refactor: refs #6274 --- loopback/locale/es.json | 5 +++-- .../worker/back/methods/worker-time-control/clockIn.js | 6 +++--- modules/worker/back/methods/worker-time-control/login.js | 9 ++++----- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index a8134909e..185212d51 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}}" -} + "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", + "Incorrect pin.": "Pin incorrecto." +} \ No newline at end of file diff --git a/modules/worker/back/methods/worker-time-control/clockIn.js b/modules/worker/back/methods/worker-time-control/clockIn.js index 2e2441cc2..44e0c547a 100644 --- a/modules/worker/back/methods/worker-time-control/clockIn.js +++ b/modules/worker/back/methods/worker-time-control/clockIn.js @@ -36,9 +36,9 @@ module.exports = Self => { Object.assign(myOptions, options); const query = 'CALL vn.workerTimeControl_clockIn(?, ?, ?)'; - const [response] = await Self.rawSql(query, [workerFk, timed, direction], myOptions); - if (response[0] && response[0].error) - throw new UserError(response[0].error); + const [[response]] = await Self.rawSql(query, [workerFk, timed, direction], myOptions); + if (response && response.error) + throw new UserError(response.error); return response; }; diff --git a/modules/worker/back/methods/worker-time-control/login.js b/modules/worker/back/methods/worker-time-control/login.js index 894b5ba17..b2a17b4e4 100644 --- a/modules/worker/back/methods/worker-time-control/login.js +++ b/modules/worker/back/methods/worker-time-control/login.js @@ -8,7 +8,7 @@ module.exports = Self => { { arg: 'pin', type: 'string', - required: true, + required: true }, ], returns: { @@ -27,9 +27,8 @@ module.exports = Self => { Object.assign(myOptions, options); const query = `CALL vn.workerTimeControl_login(?)`; - const user = await Self.rawSql(query, [pin], myOptions); - - if (!user) throw new UserError('Indique el pin.'); - return user[0][0]; + const [[user]] = await Self.rawSql(query, [pin], myOptions); + if (!user) throw new UserError('Incorrect pin.'); + return user; }; }; From 27a369bef4aa176fc4d43c5efb2a7f20239995ec Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 21 Dec 2023 18:34:22 +0100 Subject: [PATCH 189/207] refactor(ticketSms): refs #6259 merge ticksms to clientsms --- db/changes/235201/00-ticketSmsToClientSms.sql | 25 +++++++++++++++++ db/dump/fixtures.sql | 14 ++++++++++ modules/client/back/model-config.json | 3 -- modules/client/back/models/client-sms.json | 5 ++++ modules/client/back/models/ticket-sms.json | 28 ------------------- modules/ticket/back/methods/ticket/sendSms.js | 4 ++- .../back/methods/ticket/specs/sendSms.spec.js | 4 +-- 7 files changed, 49 insertions(+), 34 deletions(-) create mode 100644 db/changes/235201/00-ticketSmsToClientSms.sql delete mode 100644 modules/client/back/models/ticket-sms.json diff --git a/db/changes/235201/00-ticketSmsToClientSms.sql b/db/changes/235201/00-ticketSmsToClientSms.sql new file mode 100644 index 000000000..f2aa73863 --- /dev/null +++ b/db/changes/235201/00-ticketSmsToClientSms.sql @@ -0,0 +1,25 @@ +ALTER TABLE `vn`.`clientSms` ADD `ticketFk` int(11) NULL; +ALTER TABLE `vn`.`clientSms` ADD CONSTRAINT `clientSms_FK_2` FOREIGN KEY (`ticketFk`) REFERENCES `vn`.`ticket`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; + +INSERT INTO`vn`.`clientSms` (`clientFk`, `smsFk`, `ticketFk`) + SELECT `t`.`clientFk`, `s`.`smsFk`, `s`.`ticketFk` + FROM `vn`.`clientSms` `s` + JOIN `vn`.`ticket` `t` ON `t`.`id` = `s`.`ticketFk`; + +RENAME TABLE `vn`.`ticketSms` TO `vn`.`ticketSms__`; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`clientSms_beforeInsert` + BEFORE INSERT ON `clientSms` + FOR EACH ROW +BEGIN + DECLARE vTicketOwner INT; + + SELECT clientFk INTO vTicketOwner + FROM ticket + WHERE id = NEW.ticketFk; + + IF NOT NEW.clientFk = vTicketOwner THEN + CALL util.throw('Unable to send an SMS ticket to a client who is not the owner'); + END IF; +END$$ \ No newline at end of file diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 8997e40b1..7ea766d61 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -3009,3 +3009,17 @@ INSERT INTO `vn`.`invoiceCorrectionType` (`id`, `description`) (1, 'Error in VAT calculation'), (2, 'Error in sales details'), (3, 'Error in customer data'); + +INSERT INTO `vn`.`sms` (`id`, `senderFk`, `sender`, `destination`, `message`, `statusCode`, `status`, `created`) + VALUES (1, 66, '111111111', '0001111111111', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 0, 'OK', util.VN_CURDATE()), + (2, 66, '222222222', '0002222222222', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 0, 'PENDING', util.VN_CURDATE()), + (3, 66, '333333333', '0003333333333', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 0, 'ERROR', util.VN_CURDATE()), + (4, 66, '444444444', '0004444444444', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 0, 'OK', util.VN_CURDATE()); + +INSERT INTO `vn`.`clientSms` (`id`, `clientFk`, `smsFk`, `ticketFk`) + VALUES(1, 1103, 1, NULL), + (2, 1103, 2, NULL), + (3, 1103, 3, 32), + (4, 1103, 4, 32), + (13, 1101, 1, NULL), + (14, 1101, 4, 27); \ No newline at end of file diff --git a/modules/client/back/model-config.json b/modules/client/back/model-config.json index a21407732..fc1254dd8 100644 --- a/modules/client/back/model-config.json +++ b/modules/client/back/model-config.json @@ -113,9 +113,6 @@ "SageTransactionType": { "dataSource": "vn" }, - "TicketSms": { - "dataSource": "vn" - }, "TpvError": { "dataSource": "vn" }, diff --git a/modules/client/back/models/client-sms.json b/modules/client/back/models/client-sms.json index b2244ebbb..df1b58737 100644 --- a/modules/client/back/models/client-sms.json +++ b/modules/client/back/models/client-sms.json @@ -21,6 +21,11 @@ "type": "belongsTo", "model": "Sms", "foreignKey": "smsFk" + }, + "ticket": { + "type": "belongsTo", + "model": "Ticket", + "foreignKey": "ticketFk" } } } diff --git a/modules/client/back/models/ticket-sms.json b/modules/client/back/models/ticket-sms.json deleted file mode 100644 index 03f592f51..000000000 --- a/modules/client/back/models/ticket-sms.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "TicketSms", - "base": "VnModel", - "options": { - "mysql": { - "table": "ticketSms" - } - }, - "properties": { - "smsFk": { - "type": "number", - "id": true, - "description": "Identifier" - } - }, - "relations": { - "ticket": { - "type": "belongsTo", - "model": "Ticket", - "foreignKey": "ticketFk" - }, - "sms": { - "type": "belongsTo", - "model": "Sms", - "foreignKey": "smsFk" - } - } -} diff --git a/modules/ticket/back/methods/ticket/sendSms.js b/modules/ticket/back/methods/ticket/sendSms.js index ffc95c6b4..36e52fe3d 100644 --- a/modules/ticket/back/methods/ticket/sendSms.js +++ b/modules/ticket/back/methods/ticket/sendSms.js @@ -33,7 +33,9 @@ module.exports = Self => { Self.sendSms = async(ctx, id, destination, message) => { const models = Self.app.models; const sms = await models.Sms.send(ctx, destination, message); - await models.TicketSms.create({ + const {clientFk} = await models.Ticket.findById(id); + await models.ClientSms.create({ + clientFk, ticketFk: id, smsFk: sms.id }); diff --git a/modules/ticket/back/methods/ticket/specs/sendSms.spec.js b/modules/ticket/back/methods/ticket/specs/sendSms.spec.js index 3f93198d1..43507ec56 100644 --- a/modules/ticket/back/methods/ticket/specs/sendSms.spec.js +++ b/modules/ticket/back/methods/ticket/specs/sendSms.spec.js @@ -17,9 +17,9 @@ describe('ticket sendSms()', () => { const filter = { ticketFk: id }; - const ticketSms = await models.TicketSms.findOne(filter, options); + const clientSms = await models.ClientSms.findOne(filter, options); - expect(ticketSms.ticketFk).toEqual(id); + expect(clientSms.ticketFk).toEqual(id); await tx.rollback(); } catch (e) { From 86db5a931d8b047fb55ca0c2139599737deb74b5 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 22 Dec 2023 10:44:21 +0100 Subject: [PATCH 190/207] arrange test suites: refs #6274 --- .../worker-time-control/specs/clockIn.spec.js | 553 +++++++++++++++++ .../worker-time-control/specs/login.spec.js | 2 +- .../specs/timeEntry.spec.js | 578 +----------------- 3 files changed, 555 insertions(+), 578 deletions(-) diff --git a/modules/worker/back/methods/worker-time-control/specs/clockIn.spec.js b/modules/worker/back/methods/worker-time-control/specs/clockIn.spec.js index 970fd2fe2..9cd3ed1c0 100644 --- a/modules/worker/back/methods/worker-time-control/specs/clockIn.spec.js +++ b/modules/worker/back/methods/worker-time-control/specs/clockIn.spec.js @@ -1,8 +1,29 @@ const models = require('vn-loopback/server/server').models; +const LoopBackContext = require('loopback-context'); describe('workerTimeControl clockIn()', () => { const workerId = 9; + const salesBossId = 19; + const hankPymId = 1107; + const jessicaJonesId = 1110; + const HHRRId = 37; + const teamBossId = 13; + const monday = 1; + const tuesday = 2; + const thursday = 4; + const friday = 5; + const sunday = 7; const inTime = '2001-01-01T00:00:00.000Z'; + const activeCtx = { + accessToken: {userId: 50}, + }; + const ctx = {req: activeCtx}; + + beforeAll(() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + }); it('should correctly clock in', async() => { const tx = await models.WorkerTimeControl.beginTransaction({}); @@ -24,5 +45,537 @@ describe('workerTimeControl clockIn()', () => { throw e; } }); + + describe('as Role errors', () => { + it('should add if the current user is team boss and the target user is himself', async() => { + activeCtx.accessToken.userId = teamBossId; + const workerId = teamBossId; + + const tx = await models.WorkerTimeControl.beginTransaction({}); + try { + const options = {transaction: tx}; + + const todayAtOne = Date.vnNew(); + todayAtOne.setHours(1, 0, 0, 0); + + ctx.args = {timed: todayAtOne, direction: 'in'}; + const createdTimeEntry = await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + expect(createdTimeEntry.id).toBeDefined(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should delete the created time entry for the team boss as himself', async() => { + activeCtx.accessToken.userId = teamBossId; + const workerId = teamBossId; + + const tx = await models.WorkerTimeControl.beginTransaction({}); + try { + const options = {transaction: tx}; + + const todayAtOne = Date.vnNew(); + todayAtOne.setHours(1, 0, 0, 0); + + ctx.args = {timed: todayAtOne, direction: 'in'}; + const createdTimeEntry = await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + expect(createdTimeEntry.id).toBeDefined(); + + await models.WorkerTimeControl.deleteTimeEntry(ctx, createdTimeEntry.id, options); + + const deletedTimeEntry = await models.WorkerTimeControl.findById(createdTimeEntry.id, null, options); + + expect(deletedTimeEntry).toBeNull(); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should edit the created time entry for the team boss as HHRR', async() => { + activeCtx.accessToken.userId = HHRRId; + const workerId = teamBossId; + + const tx = await models.WorkerTimeControl.beginTransaction({}); + try { + const options = {transaction: tx}; + + const todayAtOne = Date.vnNew(); + todayAtOne.setHours(1, 0, 0, 0); + + ctx.args = {timed: todayAtOne, direction: 'in'}; + const createdTimeEntry = await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + expect(createdTimeEntry.id).toBeDefined(); + + ctx.args = {direction: 'out'}; + const updatedTimeEntry = await models.WorkerTimeControl.updateTimeEntry( + ctx, createdTimeEntry.id, options + ); + + expect(updatedTimeEntry.direction).toEqual('out'); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + }); + + describe('as saleBoss editor', () => { + let workerId; + beforeEach(() => { + activeCtx.accessToken.userId = salesBossId; + workerId = hankPymId; + }); + + it('should fail to add a time entry if the target user has an absence that day', async() => { + const date = Date.vnNew(); + date.setHours(8, 0, 0); + date.setDate(date.getDate() - 16); + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + try { + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toBe(`No está permitido trabajar`); + }); + + it('should fail to add a time entry for a worker without an existing contract', async() => { + const date = Date.vnNew(); + date.setFullYear(date.getFullYear() - 2); + + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + try { + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toBe(`No hay un contrato en vigor`); + }); + + it('should fail to add a time entry for a worker without an existing contract and exceeding time', async() => { + let date = Date.vnNew(); + date.setDate(date.getDate() - 2); + let error; + + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + date.setHours(0, 0, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + try { + date.setHours(20, 0, 1); + ctx.args = {timed: date, direction: 'out'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toBe(`Superado el tiempo máximo entre entrada y salida`); + }); + + describe('direction errors', () => { + let date = Date.vnNew(); + date.setDate(date.getDate() - 1); + let error; + it('should throw an error when trying "in" direction twice', async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + date.setHours(8, 0, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + try { + date.setHours(10, 0, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toBe(`Dirección incorrecta`); + }); + + it('should throw an error when trying "in" direction after insert "in" and "middle"', async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + date.setHours(8, 0, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + date.setHours(9, 0, 0); + ctx.args = {timed: date, direction: 'middle'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + try { + date.setHours(10, 0, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toBe(`Dirección incorrecta`); + }); + + it('Should throw an error when trying "out" before closing a "middle" couple', async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + date.setHours(8, 0, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + date.setHours(9, 0, 0); + ctx.args = {timed: date, direction: 'middle'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + try { + date.setHours(10, 0, 0); + ctx.args = {timed: date, direction: 'out'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toBe(`Dirección incorrecta`); + }); + + it('should throw an error when trying "middle" after "out"', async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + date.setHours(8, 0, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + date.setHours(9, 0, 0); + ctx.args = {timed: date, direction: 'out'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + try { + date.setHours(10, 0, 0); + ctx.args = {timed: date, direction: 'middle'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toBe(`Dirección incorrecta`); + }); + + it('should throw an error when trying "out" direction twice', async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + date.setHours(8, 0, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + date.setHours(9, 0, 0); + ctx.args = {timed: date, direction: 'out'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + try { + date.setHours(10, 0, 0); + ctx.args = {timed: date, direction: 'out'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toBe(`Dirección incorrecta`); + }); + }); + + describe('12h rest', () => { + activeCtx.accessToken.userId = salesBossId; + const workerId = hankPymId; + it('should throw an error when the 12h rest is not fulfilled yet', async() => { + let date = Date.vnNew(); + date.setDate(date.getDate() - 2); + date = weekDay(date, monday); + let error; + + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + date.setHours(8, 0, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + date.setHours(16, 0, 0); + ctx.args = {timed: date, direction: 'out'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + try { + date = weekDay(date, tuesday); + date.setHours(4, 0, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toBe(`Descanso diario`); + }); + + it('should not fail as the 12h rest is fulfilled', async() => { + let date = Date.vnNew(); + date.setDate(date.getDate() - 2); + date = weekDay(date, monday); + let error; + + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + date.setHours(8, 0, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + date.setHours(16, 0, 0); + ctx.args = {timed: date, direction: 'out'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + try { + date = weekDay(date, tuesday); + date.setHours(4, 1, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).not.toBeDefined; + }); + }); + + describe('for 3500kg drivers with enforced 9h rest', () => { + activeCtx.accessToken.userId = salesBossId; + const workerId = jessicaJonesId; + it('should throw an error when the 9h enforced rest is not fulfilled', async() => { + let date = Date.vnNew(); + date.setDate(date.getDate() - 2); + date = weekDay(date, monday); + let error; + + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + date.setHours(8, 0, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + date.setHours(16, 0, 0); + ctx.args = {timed: date, direction: 'out'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + try { + date = weekDay(date, tuesday); + date.setHours(1, 0, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toBe(`Descanso diario`); + }); + + it('should not fail when the 9h enforced rest is fulfilled', async() => { + let date = Date.vnNew(); + date.setDate(date.getDate() - 2); + date = weekDay(date, monday); + let error; + + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + date.setHours(8, 0, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + date.setHours(16, 0, 0); + ctx.args = {timed: date, direction: 'out'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + try { + date = weekDay(date, tuesday); + date.setHours(1, 1, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).not.toBeDefined; + }); + }); + + describe('for 72h weekly rest', () => { + + it('should throw an error when work 11 consecutive days', async() => { + let date = Date.vnNew(); + date.setMonth(date.getMonth() - 1); + date.setDate(1); + let error; + + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + await populateWeek(date, monday, sunday, ctx, workerId, options); + date = nextWeek(date); + await populateWeek(date, monday, thursday, ctx, workerId, options); + try { + date = weekDay(date, friday); + date.setHours(10, 0, 1); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toBe(`Descanso semanal`); + }); + + it('should throw an error when the 72h weekly rest is not fulfilled', async() => { + + let date = Date.vnNew(); + date.setMonth(date.getMonth() - 1); + date.setDate(1); + let error; + + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + await populateWeek(date, monday, sunday, ctx, workerId, options); + date = nextWeek(date); + await populateWeek(date, monday, thursday, ctx, workerId, options); + + try { + date = weekDay(date, sunday); + date.setHours(17, 59, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toBe(`Descanso semanal`); + }); + + it('should throw an error when the 72h weekly rest is fulfilled', async() => { + + let date = Date.vnNew(); + date.setMonth(date.getMonth() - 1); + date.setDate(1); + let error; + + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + await populateWeek(date, monday, sunday, ctx, workerId, options); + date = nextWeek(date); + await populateWeek(date, monday, thursday, ctx, workerId, options); + + try { + date = weekDay(date, sunday); + date.setHours(18, 00, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).not.toBeDefined; + }); + }); + }); }); +function weekDay(date, dayToSet) { + const currentDay = date.getDay(); + const distance = dayToSet - currentDay; + + date.setDate(date.getDate() + distance); + return date; +} + +function nextWeek(date) { + const sunday = 7; + const currentDay = date.getDay(); + let newDate = date; + if (currentDay != 0) + newDate = weekDay(date, sunday); + + newDate.setDate(newDate.getDate() + 1); + return newDate; +} + +async function populateWeek(date, dayStart, dayEnd, ctx, workerId, options) { + const dateStart = new Date(weekDay(date, dayStart)); + const dateEnd = new Date(dateStart); + dateEnd.setDate(dateStart.getDate() + dayEnd); + + for (let i = dayStart; i <= dayEnd; i++) { + dateStart.setHours(10, 0, 0); + ctx.args = {timed: dateStart, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + dateStart.setHours(18, 0, 0); + ctx.args = {timed: dateStart, direction: 'out'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + dateStart.setDate(dateStart.getDate() + 1); + } +} diff --git a/modules/worker/back/methods/worker-time-control/specs/login.spec.js b/modules/worker/back/methods/worker-time-control/specs/login.spec.js index 88596f297..392d9a66b 100644 --- a/modules/worker/back/methods/worker-time-control/specs/login.spec.js +++ b/modules/worker/back/methods/worker-time-control/specs/login.spec.js @@ -13,7 +13,7 @@ describe('workerTimeControl login()', () => { await models.WorkerTimeControl.login(); } catch (error) { expect(error).toBeInstanceOf(UserError); - expect(error.message).toBe('Indique el pin.'); + expect(error.message).toBe('Incorrect pin.'); } }); }); diff --git a/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js b/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js index 42ec6290a..92c01792f 100644 --- a/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js +++ b/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js @@ -3,18 +3,10 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('workerTimeControl add/delete timeEntry()', () => { - const HHRRId = 37; - const teamBossId = 13; const employeeId = 1; - const salesPersonId = 1106; const salesBossId = 19; const hankPymId = 1107; - const jessicaJonesId = 1110; const monday = 1; - const tuesday = 2; - const thursday = 4; - const friday = 5; - const sunday = 7; const activeCtx = { accessToken: {userId: 50}, }; @@ -61,560 +53,11 @@ describe('workerTimeControl add/delete timeEntry()', () => { expect(error.statusCode).toBe(400); expect(error.message).toBe(`You don't have enough privileges`); }); - - it('should add if the current user is team boss and the target user is himself', async() => { - activeCtx.accessToken.userId = teamBossId; - const workerId = teamBossId; - - const tx = await models.WorkerTimeControl.beginTransaction({}); - try { - const options = {transaction: tx}; - - const todayAtOne = Date.vnNew(); - todayAtOne.setHours(1, 0, 0, 0); - - ctx.args = {timed: todayAtOne, direction: 'in'}; - const [createdTimeEntry] = await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - expect(createdTimeEntry.id).toBeDefined(); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); - - it('should try but fail to delete his own time entry', async() => { - activeCtx.accessToken.userId = salesBossId; - const workerId = salesBossId; - - let error; - const tx = await models.WorkerTimeControl.beginTransaction({}); - try { - const options = {transaction: tx}; - - const todayAtOne = Date.vnNew(); - todayAtOne.setHours(1, 0, 0, 0); - - ctx.args = {timed: todayAtOne, direction: 'in'}; - const [createdTimeEntry] = await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - activeCtx.accessToken.userId = salesPersonId; - await models.WorkerTimeControl.deleteTimeEntry(ctx, createdTimeEntry.id, options); - - await tx.rollback(); - } catch (e) { - error = e; - await tx.rollback(); - } - - expect(error).toBeDefined(); - expect(error.statusCode).toBe(400); - expect(error.message).toBe(`You don't have enough privileges`); - }); - - it('should delete the created time entry for the team boss as himself', async() => { - activeCtx.accessToken.userId = teamBossId; - const workerId = teamBossId; - - const tx = await models.WorkerTimeControl.beginTransaction({}); - try { - const options = {transaction: tx}; - - const todayAtOne = Date.vnNew(); - todayAtOne.setHours(1, 0, 0, 0); - - ctx.args = {timed: todayAtOne, direction: 'in'}; - const [createdTimeEntry] = await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - expect(createdTimeEntry.id).toBeDefined(); - - await models.WorkerTimeControl.deleteTimeEntry(ctx, createdTimeEntry.id, options); - - const deletedTimeEntry = await models.WorkerTimeControl.findById(createdTimeEntry.id, null, options); - - expect(deletedTimeEntry).toBeNull(); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); - - it('should delete the created time entry for the team boss as HHRR', async() => { - activeCtx.accessToken.userId = HHRRId; - const workerId = teamBossId; - - const tx = await models.WorkerTimeControl.beginTransaction({}); - try { - const options = {transaction: tx}; - - const todayAtOne = Date.vnNew(); - todayAtOne.setHours(1, 0, 0, 0); - - ctx.args = {timed: todayAtOne, direction: 'in'}; - const [createdTimeEntry] = await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - expect(createdTimeEntry.id).toBeDefined(); - - await models.WorkerTimeControl.deleteTimeEntry(ctx, createdTimeEntry.id, options); - - const deletedTimeEntry = await models.WorkerTimeControl.findById(createdTimeEntry.id, null, options); - - expect(deletedTimeEntry).toBeNull(); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); - - it('should edit the created time entry for the team boss as HHRR', async() => { - activeCtx.accessToken.userId = HHRRId; - const workerId = teamBossId; - - const tx = await models.WorkerTimeControl.beginTransaction({}); - try { - const options = {transaction: tx}; - - const todayAtOne = Date.vnNew(); - todayAtOne.setHours(1, 0, 0, 0); - - ctx.args = {timed: todayAtOne, direction: 'in'}; - const [createdTimeEntry] = await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - expect(createdTimeEntry.id).toBeDefined(); - - ctx.args = {direction: 'out'}; - const updatedTimeEntry = await models.WorkerTimeControl.updateTimeEntry(ctx, createdTimeEntry.id, options); - - expect(updatedTimeEntry.direction).toEqual('out'); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); }); describe('WorkerTimeControl_clockIn calls', () => { - let workerId; - beforeEach(() => { - activeCtx.accessToken.userId = salesBossId; - workerId = hankPymId; - }); - it('should fail to add a time entry if the target user has an absence that day', async() => { - const date = Date.vnNew(); - date.setHours(8, 0, 0); - date.setDate(date.getDate() - 16); - const tx = await models.WorkerTimeControl.beginTransaction({}); - const options = {transaction: tx}; - try { - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + beforeEach(() => activeCtx.accessToken.userId = salesBossId); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error.message).toBe(`No está permitido trabajar`); - }); - - it('should fail to add a time entry for a worker without an existing contract', async() => { - const date = Date.vnNew(); - date.setFullYear(date.getFullYear() - 2); - - const tx = await models.WorkerTimeControl.beginTransaction({}); - const options = {transaction: tx}; - try { - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error.message).toBe(`No hay un contrato en vigor`); - }); - - it('should fail to add a time entry for a worker without an existing contract', async() => { - let date = Date.vnNew(); - date.setDate(date.getDate() - 2); - let error; - - const tx = await models.WorkerTimeControl.beginTransaction({}); - const options = {transaction: tx}; - date.setHours(0, 0, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - try { - date.setHours(20,0, 1); - ctx.args = {timed: date, direction: 'out'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error.message).toBe(`Superado el tiempo máximo entre entrada y salida`); - }); - - describe('direction errors', () => { - let date = Date.vnNew(); - date.setDate(date.getDate() - 1); - let error; - it('should throw an error when trying "in" direction twice', async() => { - const tx = await models.WorkerTimeControl.beginTransaction({}); - const options = {transaction: tx}; - - date.setHours(8, 0, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - try { - date.setHours(10, 0, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error.message).toBe(`Dirección incorrecta`); - }); - - it('should throw an error when trying "in" direction after insert "in" and "middle"', async() => { - const tx = await models.WorkerTimeControl.beginTransaction({}); - const options = {transaction: tx}; - - date.setHours(8, 0, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - date.setHours(9, 0, 0); - ctx.args = {timed: date, direction: 'middle'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - try { - date.setHours(10, 0, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error.message).toBe(`Dirección incorrecta`); - }); - - it('Should throw an error when trying "out" before closing a "middle" couple', async() => { - const tx = await models.WorkerTimeControl.beginTransaction({}); - const options = {transaction: tx}; - - date.setHours(8, 0, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - date.setHours(9, 0, 0); - ctx.args = {timed: date, direction: 'middle'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - try { - date.setHours(10, 0, 0); - ctx.args = {timed: date, direction: 'out'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error.message).toBe(`Dirección incorrecta`); - }); - - it('should throw an error when trying "middle" after "out"', async() => { - const tx = await models.WorkerTimeControl.beginTransaction({}); - const options = {transaction: tx}; - - date.setHours(8, 0, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - date.setHours(9, 0, 0); - ctx.args = {timed: date, direction: 'out'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - try { - date.setHours(10, 0, 0); - ctx.args = {timed: date, direction: 'middle'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error.message).toBe(`Dirección incorrecta`); - }); - - it('should throw an error when trying "out" direction twice', async() => { - const tx = await models.WorkerTimeControl.beginTransaction({}); - const options = {transaction: tx}; - - date.setHours(8, 0, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - date.setHours(9, 0, 0); - ctx.args = {timed: date, direction: 'out'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - try { - date.setHours(10, 0, 0); - ctx.args = {timed: date, direction: 'out'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error.message).toBe(`Dirección incorrecta`); - }); - }); - - describe('12h rest', () => { - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; - it('should throw an error when the 12h rest is not fulfilled yet', async() => { - - let date = Date.vnNew(); - date.setDate(date.getDate() - 2); - date = weekDay(date, monday); - let error; - - const tx = await models.WorkerTimeControl.beginTransaction({}); - const options = {transaction: tx}; - - date.setHours(8, 0, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - date.setHours(16, 0, 0); - ctx.args = {timed: date, direction: 'out'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - try { - date = weekDay(date, tuesday); - date.setHours(4, 0, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error.message).toBe(`Descanso diario`); - }); - - it('should not fail as the 12h rest is fulfilled', async() => { - let date = Date.vnNew(); - date.setDate(date.getDate() - 2); - date = weekDay(date, monday); - let error; - - const tx = await models.WorkerTimeControl.beginTransaction({}); - const options = {transaction: tx}; - - date.setHours(8, 0, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - date.setHours(16, 0, 0); - ctx.args = {timed: date, direction: 'out'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - try { - date = weekDay(date, tuesday); - date.setHours(4, 1, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error).not.toBeDefined; - }); - }); - - describe('for 3500kg drivers with enforced 9h rest', () => { - activeCtx.accessToken.userId = salesBossId; - const workerId = jessicaJonesId; - it('should throw an error when the 9h enforced rest is not fulfilled', async() => { - - let date = Date.vnNew(); - date.setDate(date.getDate() - 2); - date = weekDay(date, monday); - let error; - - const tx = await models.WorkerTimeControl.beginTransaction({}); - const options = {transaction: tx}; - - date.setHours(8, 0, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - date.setHours(16, 0, 0); - ctx.args = {timed: date, direction: 'out'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - try { - date = weekDay(date, tuesday); - date.setHours(1, 0, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error.message).toBe(`Descanso diario`); - }); - - it('should not fail when the 9h enforced rest is fulfilled', async() => { - - let date = Date.vnNew(); - date.setDate(date.getDate() - 2); - date = weekDay(date, monday); - let error; - - const tx = await models.WorkerTimeControl.beginTransaction({}); - const options = {transaction: tx}; - - date.setHours(8, 0, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - date.setHours(16, 0, 0); - ctx.args = {timed: date, direction: 'out'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - try { - date = weekDay(date, tuesday); - date.setHours(1, 1, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error).not.toBeDefined; - }); - }); - - describe('for 72h weekly rest', () => { - - it('should throw an error when work 11 consecutive days', async() => { - let date = Date.vnNew(); - date.setMonth(date.getMonth() - 1); - date.setDate(1); - let error; - - const tx = await models.WorkerTimeControl.beginTransaction({}); - const options = {transaction: tx}; - - await populateWeek(date, monday, sunday, ctx, workerId, options); - date = nextWeek(date); - await populateWeek(date, monday, thursday, ctx, workerId, options); - try { - date = weekDay(date, friday); - date.setHours(10, 0, 1); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error.message).toBe(`Descanso semanal`); - }); - - it('should throw an error when the 72h weekly rest is not fulfilled', async() => { - - let date = Date.vnNew(); - date.setMonth(date.getMonth() - 1); - date.setDate(1); - let error; - - const tx = await models.WorkerTimeControl.beginTransaction({}); - const options = {transaction: tx}; - - await populateWeek(date, monday, sunday, ctx, workerId, options); - date = nextWeek(date); - await populateWeek(date, monday, thursday, ctx, workerId, options); - - try { - date = weekDay(date, sunday); - date.setHours(17, 59, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error.message).toBe(`Descanso semanal`); - }); - - it('should throw an error when the 72h weekly rest is fulfilled', async() => { - - let date = Date.vnNew(); - date.setMonth(date.getMonth() - 1); - date.setDate(1); - let error; - - const tx = await models.WorkerTimeControl.beginTransaction({}); - const options = {transaction: tx}; - - await populateWeek(date, monday, sunday, ctx, workerId, options); - date = nextWeek(date); - await populateWeek(date, monday, thursday, ctx, workerId, options); - - try { - date = weekDay(date, sunday); - date.setHours(18, 00, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error).not.toBeDefined; - }); - }); - describe('WorkerTimeControl_calculate calls', () => { let dated = Date.vnNew(); dated.setDate(dated.getDate() - 7); @@ -836,25 +279,6 @@ function weekDay(date, dayToSet) { return date; } -function nextWeek(date) { - const sunday = 7; - const currentDay = date.getDay(); - let newDate = date; - if (currentDay != 0) - newDate = weekDay(date, sunday); - - newDate.setDate(newDate.getDate() + 1); - return newDate; -} - -function lastWeek(date) { - const monday = 1; - newDate = weekDay(date, monday); - - newDate.setDate(newDate.getDate() - 1); - return newDate; -} - async function populateWeek(date, dayStart, dayEnd, ctx, workerId, options) { const dateStart = new Date(weekDay(date, dayStart)); const dateEnd = new Date(dateStart); From 2e1715a968fdfac0977952d3939cfe1b3f34190a Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 22 Dec 2023 15:19:45 +0100 Subject: [PATCH 191/207] refactor renewToken & replace ACL: refs #6274 --- back/methods/vn-user/renew-token.js | 41 ++++++++----------- .../methods/vn-user/specs/renew-token.spec.js | 1 - back/models/vn-user.json | 27 ++++++------ db/changes/240201/00-timecontrol.sql | 7 +++- 4 files changed, 37 insertions(+), 39 deletions(-) diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index 194747949..d00085d8a 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -1,14 +1,5 @@ -const UserError = require('vn-loopback/util/user-error'); const {models} = require('vn-loopback/server/server'); -const handlePromiseLogout = (Self, {id}, courtesyTime) => { - 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', @@ -28,14 +19,26 @@ module.exports = Self => { const {accessToken: token} = ctx.req; // Check if current token is valid - const isValid = await validateToken(token); - if (isValid) + + const {renewPeriod, courtesyTime} = await models.AccessTokenConfig.findOne({ + fields: ['renewPeriod', 'courtesyTime'] + }); + const now = Date.now(); + const differenceMilliseconds = now - token.created; + const differenceSeconds = Math.floor(differenceMilliseconds / 1000); + const isNotExceeded = differenceSeconds < renewPeriod - courtesyTime; + if (isNotExceeded) return token; - const {courtesyTime} = await models.AccessTokenConfig.findOne({fields: ['courtesyTime']}); - // Schedule to remove current token - handlePromiseLogout(Self, token, courtesyTime); + setTimeout(async() => { + try { + await Self.logout(token.id); + } catch (err) { + // eslint-disable-next-line no-console + console.error(err); + } + }, courtesyTime * 1000); // Create new accessToken const user = await Self.findById(token.userId); @@ -43,14 +46,4 @@ 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/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); diff --git a/back/models/vn-user.json b/back/models/vn-user.json index 86ffac2bb..d0687098d 100644 --- a/back/models/vn-user.json +++ b/back/models/vn-user.json @@ -95,27 +95,30 @@ "principalType": "ROLE", "principalId": "$everyone", "permission": "ALLOW" - }, - { - "property": "recoverPassword", - "accessType": "EXECUTE", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" - }, - { - "property": "validateAuth", + }, { + "property": "recoverPassword", "accessType": "EXECUTE", "principalType": "ROLE", "principalId": "$everyone", "permission": "ALLOW" - }, - { + }, { + "property": "validateAuth", + "accessType": "EXECUTE", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }, { "property": "privileges", "accessType": "*", "principalType": "ROLE", "principalId": "$authenticated", "permission": "ALLOW" + }, { + "property": "renewToken", + "accessType": "WRITE", + "principalType": "ROLE", + "principalId": "$authenticated", + "permission": "ALLOW" } ], "scopes": { diff --git a/db/changes/240201/00-timecontrol.sql b/db/changes/240201/00-timecontrol.sql index 0d3bd59b2..c3ddf5d96 100644 --- a/db/changes/240201/00-timecontrol.sql +++ b/db/changes/240201/00-timecontrol.sql @@ -1,3 +1,7 @@ +DELETE FROM `salix`.`ACL` + WHERE model = 'VnUser' + AND property = 'renewToken'; + INSERT INTO `account`.`role` (name, description) VALUES ('timeControl','Tablet para fichar'); @@ -8,7 +12,6 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp VALUES ('WorkerTimeControl', 'login', 'READ', 'ALLOW', 'ROLE', 'timeControl'), ('WorkerTimeControl', 'getClockIn', 'READ', 'ALLOW', 'ROLE', 'timeControl'), - ('WorkerTimeControl', 'clockIn', 'WRITE', 'ALLOW', 'ROLE', 'timeControl'), - ('VnUser', 'renewToken', 'WRITE', 'ALLOW', 'ROLE', 'timeControl'); + ('WorkerTimeControl', 'clockIn', 'WRITE', 'ALLOW', 'ROLE', 'timeControl'); CALL `account`.`role_sync`(); From 5a1c4ddea02f52c6e836246b70c1a5d0d459e082 Mon Sep 17 00:00:00 2001 From: pablone Date: Tue, 26 Dec 2023 08:20:13 +0100 Subject: [PATCH 192/207] refactor(ticketSms): refs #6259 ticketSmsToClientSms --- .../00-ticketSmsToClientSms.sql | 16 ---------------- .../back/methods/ticket/specs/sendSms.spec.js | 8 ++++---- 2 files changed, 4 insertions(+), 20 deletions(-) rename db/changes/{240001 => 240201}/00-ticketSmsToClientSms.sql (52%) diff --git a/db/changes/240001/00-ticketSmsToClientSms.sql b/db/changes/240201/00-ticketSmsToClientSms.sql similarity index 52% rename from db/changes/240001/00-ticketSmsToClientSms.sql rename to db/changes/240201/00-ticketSmsToClientSms.sql index f2aa73863..cd3cf7dd3 100644 --- a/db/changes/240001/00-ticketSmsToClientSms.sql +++ b/db/changes/240201/00-ticketSmsToClientSms.sql @@ -7,19 +7,3 @@ INSERT INTO`vn`.`clientSms` (`clientFk`, `smsFk`, `ticketFk`) JOIN `vn`.`ticket` `t` ON `t`.`id` = `s`.`ticketFk`; RENAME TABLE `vn`.`ticketSms` TO `vn`.`ticketSms__`; - -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`clientSms_beforeInsert` - BEFORE INSERT ON `clientSms` - FOR EACH ROW -BEGIN - DECLARE vTicketOwner INT; - - SELECT clientFk INTO vTicketOwner - FROM ticket - WHERE id = NEW.ticketFk; - - IF NOT NEW.clientFk = vTicketOwner THEN - CALL util.throw('Unable to send an SMS ticket to a client who is not the owner'); - END IF; -END$$ \ No newline at end of file diff --git a/modules/ticket/back/methods/ticket/specs/sendSms.spec.js b/modules/ticket/back/methods/ticket/specs/sendSms.spec.js index 43507ec56..afc1ada54 100644 --- a/modules/ticket/back/methods/ticket/specs/sendSms.spec.js +++ b/modules/ticket/back/methods/ticket/specs/sendSms.spec.js @@ -14,10 +14,10 @@ describe('ticket sendSms()', () => { await models.Ticket.sendSms(ctx, id, destination, message, options); - const filter = { - ticketFk: id - }; - const clientSms = await models.ClientSms.findOne(filter, options); + const clientSms = await models.ClientSms.findOne( + {where: {ticketFk: id}}, + options + ); expect(clientSms.ticketFk).toEqual(id); From 1b8461034e12fce15f4918e517f9cbe7ff40a896 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 29 Dec 2023 12:40:48 +0100 Subject: [PATCH 193/207] using hasAnyNegative: refs #6515 --- .../back/methods/invoiceOut/createManualInvoice.js | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js index 18e6903d6..043dfbead 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js +++ b/modules/invoiceOut/back/methods/invoiceOut/createManualInvoice.js @@ -85,7 +85,7 @@ module.exports = Self => { throw new UserError(`A ticket with an amount of zero can't be invoiced`); // Validates ticket nagative base - const hasNegativeBase = await getNegativeBase(ticketId, myOptions); + const hasNegativeBase = await getNegativeBase(maxShipped, clientId, companyId, myOptions); if (hasNegativeBase && company.code == 'VNL') throw new UserError(`A ticket with a negative base can't be invoiced`); } else { @@ -162,10 +162,13 @@ module.exports = Self => { return result.invoiceable; } - async function getNegativeBase(ticketId, options) { + async function getNegativeBase(maxShipped, clientId, companyId, options) { const models = Self.app.models; - const query = 'SELECT vn.hasSomeNegativeBase(?) AS base'; - const [result] = await models.InvoiceOut.rawSql(query, [ticketId], options); + await models.InvoiceOut.rawSql('CALL invoiceOut_exportationFromClient(?,?,?)', + [maxShipped, clientId, companyId], options + ); + const query = 'SELECT vn.hasAnyNegativeBase() AS base'; + const [result] = await models.InvoiceOut.rawSql(query, [], options); return result.base; } From 15ec91ec790fbe18191262127a20b402ce824d70 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 29 Dec 2023 14:05:01 +0100 Subject: [PATCH 194/207] 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 195/207] 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 196/207] 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 801037da64bf3c02d8017ba29e2dc7cf698448b6 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 2 Jan 2024 08:47:12 +0100 Subject: [PATCH 197/207] fix changes: refs #6274 --- db/changes/{240201 => 234601}/00-updateCourtesyTime.sql | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename db/changes/{240201 => 234601}/00-updateCourtesyTime.sql (100%) diff --git a/db/changes/240201/00-updateCourtesyTime.sql b/db/changes/234601/00-updateCourtesyTime.sql similarity index 100% rename from db/changes/240201/00-updateCourtesyTime.sql rename to db/changes/234601/00-updateCourtesyTime.sql From 763af7da2d17c14ec49d34f4455b6a2de95f111a Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 2 Jan 2024 08:58:41 +0100 Subject: [PATCH 198/207] fix test: refs #6274 --- .../worker/back/methods/worker-time-control/specs/login.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/worker/back/methods/worker-time-control/specs/login.spec.js b/modules/worker/back/methods/worker-time-control/specs/login.spec.js index 392d9a66b..8e992de96 100644 --- a/modules/worker/back/methods/worker-time-control/specs/login.spec.js +++ b/modules/worker/back/methods/worker-time-control/specs/login.spec.js @@ -3,7 +3,7 @@ const models = require('vn-loopback/server/server').models; describe('workerTimeControl login()', () => { it('should correctly login', async() => { - const response = await models.WorkerTimeControl.login(9, {}); + const response = await models.WorkerTimeControl.login(9); expect(response.name).toBe('developer'); }); From 6b8a4a512bc58067c2efd00b141e8a45a0d99e8c Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 2 Jan 2024 10:42:50 +0100 Subject: [PATCH 199/207] 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', From 1e3a7e5f9113aac0beb95b052c2b8be745934995 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 2 Jan 2024 13:17:10 +0100 Subject: [PATCH 200/207] refs #5914 refactor: invoiceTickets --- ...00-fixInvoiceCorrectionConstraintsName.sql | 7 +++++ .../{235001 => 240001}/00-getTaxBases.sql | 0 .../01-newHasAnyPositiveBase.sql | 2 +- .../01-refactorHasAnyNegativeBase.sql | 2 +- .../back/models/invoice-correction.json | 27 +++++++++++++++++++ .../back/methods/ticket/canBeInvoiced.js | 7 ----- .../back/methods/ticket/invoiceTickets.js | 19 +++++++------ .../ticket/back/methods/ticket/makeInvoice.js | 3 +-- .../ticket/specs/canBeInvoiced.spec.js | 20 +++----------- 9 files changed, 50 insertions(+), 37 deletions(-) create mode 100644 db/changes/240001/00-fixInvoiceCorrectionConstraintsName.sql rename db/changes/{235001 => 240001}/00-getTaxBases.sql (100%) rename db/changes/{235001 => 240001}/01-newHasAnyPositiveBase.sql (91%) rename db/changes/{235001 => 240001}/01-refactorHasAnyNegativeBase.sql (91%) diff --git a/db/changes/240001/00-fixInvoiceCorrectionConstraintsName.sql b/db/changes/240001/00-fixInvoiceCorrectionConstraintsName.sql new file mode 100644 index 000000000..426afea90 --- /dev/null +++ b/db/changes/240001/00-fixInvoiceCorrectionConstraintsName.sql @@ -0,0 +1,7 @@ +ALTER TABLE `vn`.`invoiceCorrection` DROP FOREIGN KEY `cplusInvoiceTyoeFk`; +ALTER TABLE `vn`.`invoiceCorrection` DROP FOREIGN KEY `invoiceCorrectionType_Fk33`; +ALTER TABLE `vn`.`invoiceCorrection` DROP FOREIGN KEY `invoiceCorrection_ibfk_1`; + +ALTER TABLE `vn`.`invoiceCorrection` ADD CONSTRAINT `siiTypeInvoiceOut_FK` FOREIGN KEY (`siiTypeInvoiceOutFk`) REFERENCES `vn`.`siiTypeInvoiceOut`(id) ON UPDATE CASCADE; +ALTER TABLE `vn`.`invoiceCorrection` ADD CONSTRAINT `invoiceCorrectionType_FK` FOREIGN KEY (`invoiceCorrectionTypeFk`) REFERENCES `vn`.`invoiceCorrectionType`(id) ON UPDATE CASCADE; +ALTER TABLE `vn`.`invoiceCorrection` ADD CONSTRAINT `cplusRectificationType_FK` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `vn`.`cplusRectificationType`(id) ON UPDATE CASCADE; diff --git a/db/changes/235001/00-getTaxBases.sql b/db/changes/240001/00-getTaxBases.sql similarity index 100% rename from db/changes/235001/00-getTaxBases.sql rename to db/changes/240001/00-getTaxBases.sql diff --git a/db/changes/235001/01-newHasAnyPositiveBase.sql b/db/changes/240001/01-newHasAnyPositiveBase.sql similarity index 91% rename from db/changes/235001/01-newHasAnyPositiveBase.sql rename to db/changes/240001/01-newHasAnyPositiveBase.sql index c9e7e8e05..70fd51bcc 100644 --- a/db/changes/235001/01-newHasAnyPositiveBase.sql +++ b/db/changes/240001/01-newHasAnyPositiveBase.sql @@ -14,7 +14,7 @@ BEGIN CALL getTaxBases(); - SELECT positive > 0 INTO hasAnyPositiveBase + SELECT positive INTO hasAnyPositiveBase FROM tmp.taxBases; DROP TEMPORARY TABLE diff --git a/db/changes/235001/01-refactorHasAnyNegativeBase.sql b/db/changes/240001/01-refactorHasAnyNegativeBase.sql similarity index 91% rename from db/changes/235001/01-refactorHasAnyNegativeBase.sql rename to db/changes/240001/01-refactorHasAnyNegativeBase.sql index 65822fc95..f851ee6b9 100644 --- a/db/changes/235001/01-refactorHasAnyNegativeBase.sql +++ b/db/changes/240001/01-refactorHasAnyNegativeBase.sql @@ -14,7 +14,7 @@ BEGIN CALL getTaxBases(); - SELECT negative > 0 INTO hasAnyNegativeBase + SELECT negative INTO hasAnyNegativeBase FROM tmp.taxBases; DROP TEMPORARY TABLE diff --git a/modules/invoiceOut/back/models/invoice-correction.json b/modules/invoiceOut/back/models/invoice-correction.json index 5924c9232..58f6f63b7 100644 --- a/modules/invoiceOut/back/models/invoice-correction.json +++ b/modules/invoiceOut/back/models/invoice-correction.json @@ -26,6 +26,33 @@ "invoiceCorrectionTypeFk": { "type": "number", "required": true + }, + "relations": { + "correcting": { + "type": "belongsTo", + "model": "InvoiceOut", + "foreignKey": "correctingFk" + }, + "corrected": { + "type": "belongsTo", + "model": "InvoiceOut", + "foreignKey": "correctedFk" + }, + "cplusRectificationType": { + "type": "belongsTo", + "model": "cplusRectificationType", + "foreignKey": "cplusRectificationTypeFk" + }, + "siiTypeInvoiceOut": { + "type": "belongsTo", + "model": "siiTypeInvoiceOut", + "foreignKey": "siiTypeInvoiceOutFk" + }, + "invoiceCorrectionType": { + "type": "belongsTo", + "model": "invoiceCorrectionType", + "foreignKey": "invoiceCorrectionTypeFk" + } } } } diff --git a/modules/ticket/back/methods/ticket/canBeInvoiced.js b/modules/ticket/back/methods/ticket/canBeInvoiced.js index 75d13a508..855a864c2 100644 --- a/modules/ticket/back/methods/ticket/canBeInvoiced.js +++ b/modules/ticket/back/methods/ticket/canBeInvoiced.js @@ -17,11 +17,6 @@ module.exports = function(Self) { type: 'boolean' } ], - returns: { - arg: 'data', - type: 'boolean', - root: true - }, http: { path: `/canBeInvoiced`, verb: 'get' @@ -63,7 +58,5 @@ module.exports = function(Self) { if (ticketsIds.length == 1 && priceZero) throw new UserError(`A ticket with an amount of zero can't be invoiced`); }); - - return true; }; }; diff --git a/modules/ticket/back/methods/ticket/invoiceTickets.js b/modules/ticket/back/methods/ticket/invoiceTickets.js index f1793773b..57f623289 100644 --- a/modules/ticket/back/methods/ticket/invoiceTickets.js +++ b/modules/ticket/back/methods/ticket/invoiceTickets.js @@ -61,20 +61,19 @@ module.exports = function(Self) { if (!isSameClient) throw new UserError(`You can't invoice tickets from multiple clients`); - const client = await models.Client.findById(clientId, { - fields: ['id', 'hasToInvoiceByAddress'] + const {hasToInvoiceByAddress} = await models.Client.findById(clientId, { + fields: ['hasToInvoiceByAddress'] }, myOptions); - let ticketsByAddress = {[firstTicket.addressFk]: ticketsIds}; - if (client.hasToInvoiceByAddress) { - ticketsByAddress = tickets.reduce((group, ticket) => { - const {addressFk} = ticket; + let ticketsByAddress = hasToInvoiceByAddress + ? Object.values(tickets.reduce((group, {id, addressFk}) => { group[addressFk] = group[addressFk] ?? []; - group[addressFk].push(ticket.id); + group[addressFk].push(id); return group; - }, {}); - } - for (const ticketIds of Object.values(ticketsByAddress)) + }, {})) + : [[ticketsIds]]; + + for (const ticketIds of ticketsByAddress) invoicesIds.push(await createInvoice(ctx, companyId, ticketIds, invoiceCorrection, myOptions)); if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/ticket/makeInvoice.js b/modules/ticket/back/methods/ticket/makeInvoice.js index 32aa03f9d..83222a4ee 100644 --- a/modules/ticket/back/methods/ticket/makeInvoice.js +++ b/modules/ticket/back/methods/ticket/makeInvoice.js @@ -106,8 +106,7 @@ module.exports = function(Self) { ); } - if (resultInvoice.id) - await Self.rawSql('CALL invoiceOutBooking(?)', [resultInvoice.id], myOptions); + await Self.rawSql('CALL invoiceOutBooking(?)', [resultInvoice.id], myOptions); if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/ticket/specs/canBeInvoiced.spec.js b/modules/ticket/back/methods/ticket/specs/canBeInvoiced.spec.js index e443ed6d3..1509b87df 100644 --- a/modules/ticket/back/methods/ticket/specs/canBeInvoiced.spec.js +++ b/modules/ticket/back/methods/ticket/specs/canBeInvoiced.spec.js @@ -27,10 +27,7 @@ describe('ticket canBeInvoiced()', () => { WHERE id IN (?) `, [ticketId], options); - const canBeInvoiced = await models.Ticket.canBeInvoiced(ctx, [ticketId], false, options); - - expect(canBeInvoiced).toEqual(false); - + await models.Ticket.canBeInvoiced(ctx, [ticketId], false, options); await tx.rollback(); } catch (e) { error = e; @@ -59,10 +56,7 @@ describe('ticket canBeInvoiced()', () => { WHERE id IN (?) `, [ticketId], options); - const canBeInvoiced = await models.Ticket.canBeInvoiced(ctx, [ticketId], false, options); - - expect(canBeInvoiced).toEqual(false); - + await models.Ticket.canBeInvoiced(ctx, [ticketId], false, options); await tx.rollback(); } catch (e) { error = e; @@ -95,10 +89,7 @@ describe('ticket canBeInvoiced()', () => { WHERE id IN (?) `, [ticketId], options); - const canBeInvoiced = await models.Ticket.canBeInvoiced(ctx, [ticketId], false, options); - - expect(canBeInvoiced).toEqual(false); - + await models.Ticket.canBeInvoiced(ctx, [ticketId], false, options); await tx.rollback(); } catch (e) { error = e; @@ -123,10 +114,7 @@ describe('ticket canBeInvoiced()', () => { WHERE id IN (?) `, [ticketId], options); - const canBeInvoiced = await models.Ticket.canBeInvoiced(ctx, [ticketId], false, options); - - expect(canBeInvoiced).toEqual(true); - + await models.Ticket.canBeInvoiced(ctx, [ticketId], false, options); await tx.rollback(); } catch (e) { await tx.rollback(); From c116bc56c3e23d52cff1ba6cda4eb396cd0aeaad Mon Sep 17 00:00:00 2001 From: pablone Date: Tue, 2 Jan 2024 19:37:51 +0100 Subject: [PATCH 201/207] refactor(clientSms): refs #6259 redirect to lilium --- modules/client/front/sms/index.html | 42 ++--------------------------- modules/client/front/sms/index.js | 28 ++++--------------- 2 files changed, 7 insertions(+), 63 deletions(-) diff --git a/modules/client/front/sms/index.html b/modules/client/front/sms/index.html index e2bc0785e..7fb3b870e 100644 --- a/modules/client/front/sms/index.html +++ b/modules/client/front/sms/index.html @@ -1,40 +1,2 @@ - - - - - - - - Sender - Destination - Message - Status - Created - - - - - - - {{::clientSms.sms.sender.name}} - - - {{::clientSms.sms.destination}} - {{::clientSms.sms.message}} - {{::clientSms.sms.status}} - {{::clientSms.sms.created | date:'dd/MM/yyyy HH:mm'}} - - - - - - - + + diff --git a/modules/client/front/sms/index.js b/modules/client/front/sms/index.js index 6ad64282e..8fa130248 100644 --- a/modules/client/front/sms/index.js +++ b/modules/client/front/sms/index.js @@ -1,32 +1,14 @@ import ngModule from '../module'; import Section from 'salix/components/section'; -export default class Controller extends Section { +class Controller extends Section { constructor($element, $) { super($element, $); + } - this.filter = { - fields: ['id', 'smsFk'], - include: { - relation: 'sms', - scope: { - fields: [ - 'senderFk', - 'sender', - 'destination', - 'message', - 'statusCode', - 'status', - 'created'], - include: { - relation: 'sender', - scope: { - fields: ['name'] - } - } - } - } - }; + async $onInit() { + this.$state.go('client.card.summary', {id: this.$params.id}); + window.location.href = await this.vnApp.getUrl(`Customer/${this.$params.id}/sms`); } } From 5dc49d226ad4450b130ff47231702593a69ddc00 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 3 Jan 2024 10:13:56 +0100 Subject: [PATCH 202/207] refs #6274 fix locale --- loopback/locale/en.json | 3 ++- loopback/locale/es.json | 7 +++--- .../back/methods/worker-time-control/login.js | 7 +++--- .../worker-time-control/specs/login.spec.js | 24 +++++++++++++++---- 4 files changed, 28 insertions(+), 13 deletions(-) diff --git a/loopback/locale/en.json b/loopback/locale/en.json index c5e8d4fcf..508c17344 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -200,5 +200,6 @@ "Try again": "Try again", "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}}" + "It was not able to remove the next expeditions:": "It was not able to remove the next expeditions: {{expeditions}}", + "Incorrect pin": "Incorrect pin." } diff --git a/loopback/locale/es.json b/loopback/locale/es.json index fc209a9cd..e2b90983b 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -330,9 +330,8 @@ "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", - "Incorrect pin.": "Pin incorrecto.", + "This user does not have an assigned tablet": "Este usuario no tiene tablet asignada", + "Incorrect pin": "Pin incorrecto.", "You already have the mailAlias": "Ya tienes este alias de correo", "The alias cant be modified": "Este alias de correo no puede ser modificado" -} - +} \ No newline at end of file diff --git a/modules/worker/back/methods/worker-time-control/login.js b/modules/worker/back/methods/worker-time-control/login.js index b2a17b4e4..9aa4bd145 100644 --- a/modules/worker/back/methods/worker-time-control/login.js +++ b/modules/worker/back/methods/worker-time-control/login.js @@ -1,7 +1,7 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.remoteMethod('login', { + Self.remoteMethodCtx('login', { description: 'Consult the user\'s information and the buttons that must be activated after logging in', accessType: 'READ', accepts: [ @@ -21,14 +21,15 @@ module.exports = Self => { } }); - Self.login = async(pin, options) => { + Self.login = async(ctx, pin, options) => { const myOptions = {}; + const $t = ctx.req.__; if (typeof options == 'object') Object.assign(myOptions, options); const query = `CALL vn.workerTimeControl_login(?)`; const [[user]] = await Self.rawSql(query, [pin], myOptions); - if (!user) throw new UserError('Incorrect pin.'); + if (!user) throw new UserError($t('Incorrect pin')); return user; }; }; diff --git a/modules/worker/back/methods/worker-time-control/specs/login.spec.js b/modules/worker/back/methods/worker-time-control/specs/login.spec.js index 8e992de96..d9f2dbb39 100644 --- a/modules/worker/back/methods/worker-time-control/specs/login.spec.js +++ b/modules/worker/back/methods/worker-time-control/specs/login.spec.js @@ -1,20 +1,34 @@ -const UserError = require('vn-loopback/util/user-error'); const models = require('vn-loopback/server/server').models; +const LoopBackContext = require('loopback-context'); +const UserError = require('vn-loopback/util/user-error'); describe('workerTimeControl login()', () => { + let ctx; + beforeAll(async() => { + ctx = { + accessToken: {userId: 9}, + req: { + headers: {origin: 'http://localhost'}, + __: key => key + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: ctx + }); + }); + it('should correctly login', async() => { - const response = await models.WorkerTimeControl.login(9); + const response = await models.WorkerTimeControl.login(ctx, 9); expect(response.name).toBe('developer'); }); it('should throw UserError if pin is not provided', async() => { try { - await models.WorkerTimeControl.login(); + await models.WorkerTimeControl.login(ctx); } catch (error) { expect(error).toBeInstanceOf(UserError); - expect(error.message).toBe('Incorrect pin.'); + expect(error.message).toBe('Incorrect pin'); } }); }); - From f73a447391b7541f41e3be2ccc05327c1254578e Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 3 Jan 2024 11:57:49 +0100 Subject: [PATCH 203/207] refs #6398 Hotfix 1/2 --- modules/ticket/back/models/ticket-tracking.json | 3 --- modules/ticket/front/tracking/index/index.html | 6 +++--- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/modules/ticket/back/models/ticket-tracking.json b/modules/ticket/back/models/ticket-tracking.json index 4b5a4d473..ac0eb9a69 100644 --- a/modules/ticket/back/models/ticket-tracking.json +++ b/modules/ticket/back/models/ticket-tracking.json @@ -20,9 +20,6 @@ }, "stateFk": { "type": "number" - }, - "userFk": { - "type": "number" } }, "relations": { diff --git a/modules/ticket/front/tracking/index/index.html b/modules/ticket/front/tracking/index/index.html index 12c4778c9..10ee6d848 100644 --- a/modules/ticket/front/tracking/index/index.html +++ b/modules/ticket/front/tracking/index/index.html @@ -23,9 +23,9 @@ {{::tracking.state.name}} - {{::tracking.worker.user.name || 'System' | translate}} + ng-class="{'link': tracking.user.id}" + ng-click="workerDescriptor.show($event, tracking.user.id)"> + {{::tracking.user.name || 'System' | translate}} {{::tracking.created | date:'dd/MM/yyyy HH:mm'}} From ba26237998a1bf2143c0b095963cd48aa1bffb28 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 3 Jan 2024 12:19:28 +0100 Subject: [PATCH 204/207] refs #5914 refactor: getTaxBases --- db/changes/240001/00-getTaxBases.sql | 10 ++++---- .../240001/01-newHasAnyPositiveBase.sql | 6 +++-- .../240001/01-refactorHasAnyNegativeBase.sql | 7 ++++-- .../front/descriptor-menu/locale/es.yml | 1 + .../back/methods/ticket/invoiceTickets.js | 2 +- .../ticket/specs/canBeInvoiced.spec.js | 25 +++++++++++++++++++ 6 files changed, 41 insertions(+), 10 deletions(-) diff --git a/db/changes/240001/00-getTaxBases.sql b/db/changes/240001/00-getTaxBases.sql index fa43c32f7..8bd1b745a 100644 --- a/db/changes/240001/00-getTaxBases.sql +++ b/db/changes/240001/00-getTaxBases.sql @@ -2,8 +2,8 @@ DELIMITER $$ $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`getTaxBases`() BEGIN - -/* Calcula y devuelve en número de bases imponibles postivas y negativas +/** +* Calcula y devuelve en número de bases imponibles postivas y negativas * Requiere la tabla temporal tmp.ticketToInvoice(id) * * returns tmp.taxBases @@ -21,10 +21,10 @@ BEGIN CREATE TEMPORARY TABLE tmp.taxBases ENGINE = MEMORY SELECT - SUM(CASE WHEN taxableBase > 0 THEN 1 ELSE 0 END) as positive, - SUM(CASE WHEN taxableBase < 0 THEN 1 ELSE 0 END) as negative + SUM(taxableBase > 0) as positive, + SUM(taxableBase < 0) as negative FROM( - SELECT SUM(taxableBase) as taxableBase + SELECT SUM(taxableBase) taxableBase FROM tmp.ticketTax GROUP BY pgcFk ) t; diff --git a/db/changes/240001/01-newHasAnyPositiveBase.sql b/db/changes/240001/01-newHasAnyPositiveBase.sql index 70fd51bcc..c4edfaed0 100644 --- a/db/changes/240001/01-newHasAnyPositiveBase.sql +++ b/db/changes/240001/01-newHasAnyPositiveBase.sql @@ -4,7 +4,8 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`hasAnyPositiveBase`( DETERMINISTIC BEGIN -/* Calcula si existe alguna base imponible positiva +/** +* Calcula si existe alguna base imponible positiva * Requiere la tabla temporal tmp.ticketToInvoice(id) para getTaxBases() * * returns BOOLEAN @@ -15,7 +16,8 @@ BEGIN CALL getTaxBases(); SELECT positive INTO hasAnyPositiveBase - FROM tmp.taxBases; + FROM tmp.taxBases + LIMIT 1; DROP TEMPORARY TABLE tmp.ticketTax, diff --git a/db/changes/240001/01-refactorHasAnyNegativeBase.sql b/db/changes/240001/01-refactorHasAnyNegativeBase.sql index f851ee6b9..a3eb2d9c7 100644 --- a/db/changes/240001/01-refactorHasAnyNegativeBase.sql +++ b/db/changes/240001/01-refactorHasAnyNegativeBase.sql @@ -4,7 +4,8 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`hasAnyNegativeBase`( DETERMINISTIC BEGIN -/* Calcula si existe alguna base imponible negativa +/** +* Calcula si existe alguna base imponible negativa * Requiere la tabla temporal tmp.ticketToInvoice(id) para getTaxBases() * * returns BOOLEAN @@ -15,7 +16,8 @@ BEGIN CALL getTaxBases(); SELECT negative INTO hasAnyNegativeBase - FROM tmp.taxBases; + FROM tmp.taxBases + LIMIT 1; DROP TEMPORARY TABLE tmp.ticketTax, @@ -27,3 +29,4 @@ BEGIN END$$ DELIMITER ; + diff --git a/modules/invoiceOut/front/descriptor-menu/locale/es.yml b/modules/invoiceOut/front/descriptor-menu/locale/es.yml index 9456646af..bf89b2ba0 100644 --- a/modules/invoiceOut/front/descriptor-menu/locale/es.yml +++ b/modules/invoiceOut/front/descriptor-menu/locale/es.yml @@ -23,3 +23,4 @@ The following refund tickets have been created: "Se han creado los siguientes ti Refund...: Abono... Transfer invoice to...: Transferir factura a... Rectificative type: Tipo rectificativa +Invoice trasfered!: ¡Factura transferida! diff --git a/modules/ticket/back/methods/ticket/invoiceTickets.js b/modules/ticket/back/methods/ticket/invoiceTickets.js index 57f623289..06429836e 100644 --- a/modules/ticket/back/methods/ticket/invoiceTickets.js +++ b/modules/ticket/back/methods/ticket/invoiceTickets.js @@ -71,7 +71,7 @@ module.exports = function(Self) { group[addressFk].push(id); return group; }, {})) - : [[ticketsIds]]; + : [ticketsIds]; for (const ticketIds of ticketsByAddress) invoicesIds.push(await createInvoice(ctx, companyId, ticketIds, invoiceCorrection, myOptions)); diff --git a/modules/ticket/back/methods/ticket/specs/canBeInvoiced.spec.js b/modules/ticket/back/methods/ticket/specs/canBeInvoiced.spec.js index 1509b87df..78973e040 100644 --- a/modules/ticket/back/methods/ticket/specs/canBeInvoiced.spec.js +++ b/modules/ticket/back/methods/ticket/specs/canBeInvoiced.spec.js @@ -121,4 +121,29 @@ describe('ticket canBeInvoiced()', () => { throw e; } }); + + it('should return falsy for a ticket has positiveBase', async() => { + const tx = await models.Ticket.beginTransaction({}); + + try { + const options = {transaction: tx}; + + await models.Ticket.rawSql(` + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketToInvoice + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT id + FROM vn.ticket + WHERE id IN (?) + `, [ticketId], options); + + await models.Ticket.canBeInvoiced(ctx, [ticketId], true, options); + await tx.rollback(); + } catch (e) { + error = e; + await tx.rollback(); + } + + expect(error.message).toEqual(`hasAnyPositiveBase`); + }); }); From 227afbe39dfa3255f177a6d6736e1a4267bbe249 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 3 Jan 2024 14:54:01 +0100 Subject: [PATCH 205/207] refs #5914 fix(invoiceOut_descriptorMenu): transalation --- modules/invoiceOut/front/descriptor-menu/index.js | 2 +- modules/invoiceOut/front/descriptor-menu/locale/es.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/invoiceOut/front/descriptor-menu/index.js b/modules/invoiceOut/front/descriptor-menu/index.js index aee323e39..2c28599e7 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.js +++ b/modules/invoiceOut/front/descriptor-menu/index.js @@ -137,7 +137,7 @@ class Controller extends Section { }; this.$http.post(`InvoiceOuts/transferInvoice`, params).then(res => { const invoiceId = res.data; - this.vnApp.showSuccess(this.$t('Invoice trasfered!')); + this.vnApp.showSuccess(this.$t('Transferred invoice')); this.$state.go('invoiceOut.card.summary', {id: invoiceId}); }); } diff --git a/modules/invoiceOut/front/descriptor-menu/locale/es.yml b/modules/invoiceOut/front/descriptor-menu/locale/es.yml index bf89b2ba0..aaeefd9cc 100644 --- a/modules/invoiceOut/front/descriptor-menu/locale/es.yml +++ b/modules/invoiceOut/front/descriptor-menu/locale/es.yml @@ -23,4 +23,4 @@ The following refund tickets have been created: "Se han creado los siguientes ti Refund...: Abono... Transfer invoice to...: Transferir factura a... Rectificative type: Tipo rectificativa -Invoice trasfered!: ¡Factura transferida! +Transferred invoice: Factura transferida From 2a65ad6b31d3055e6d13e345c5e86811ddf32ab9 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 4 Jan 2024 08:22:01 +0100 Subject: [PATCH 206/207] refs #6635 build: new version --- CHANGELOG.md | 7 +++++++ db/changes/240401/.gitkeep | 0 package-lock.json | 4 ++-- package.json | 2 +- 4 files changed, 10 insertions(+), 3 deletions(-) create mode 100644 db/changes/240401/.gitkeep diff --git a/CHANGELOG.md b/CHANGELOG.md index 1907f46bd..69e93a309 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,13 @@ 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). +## [2404.01] - 2024-01-25 + +### Added +### Changed +### Fixed + + ## [2402.01] - 2024-01-11 ### Added diff --git a/db/changes/240401/.gitkeep b/db/changes/240401/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/package-lock.json b/package-lock.json index 012fb50e7..36e11dc8f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "salix-back", - "version": "24.02.01", + "version": "24.04.01", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "salix-back", - "version": "24.02.01", + "version": "24.04.01", "license": "GPL-3.0", "dependencies": { "axios": "^1.2.2", diff --git a/package.json b/package.json index ab3d99e19..f13c44162 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "24.02.01", + "version": "24.04.01", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", From c72311860bbdf54186ca4962ff2d0f905c324281 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 8 Jan 2024 09:06:22 +0100 Subject: [PATCH 207/207] refs #647 remove e2e --- .../vn/ticket_componentMakeUpdate.spec.js | 123 ------------------ e2e/paths/03-worker/04_time_control.spec.js | 57 -------- .../05-ticket/01-sale/02_edit_sale.spec.js | 11 -- e2e/paths/05-ticket/11_diary.spec.js | 31 ----- e2e/paths/06-claim/02_detail.spec.js | 114 ---------------- .../10-travel/02_basic_data_and_log.spec.js | 13 -- front/core/components/treeview/index.spec.js | 12 -- .../methods/boxing/specs/getVideo.spec.js | 40 ------ 8 files changed, 401 deletions(-) delete mode 100644 db/tests/vn/ticket_componentMakeUpdate.spec.js delete mode 100644 e2e/paths/05-ticket/11_diary.spec.js delete mode 100644 e2e/paths/06-claim/02_detail.spec.js delete mode 100644 modules/ticket/back/methods/boxing/specs/getVideo.spec.js diff --git a/db/tests/vn/ticket_componentMakeUpdate.spec.js b/db/tests/vn/ticket_componentMakeUpdate.spec.js deleted file mode 100644 index a059f1060..000000000 --- a/db/tests/vn/ticket_componentMakeUpdate.spec.js +++ /dev/null @@ -1,123 +0,0 @@ -const app = require('vn-loopback/server/server'); -const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; - -// 2277 solucionar problema al testear procedimiento con start transaction / rollback -xdescribe('ticket_componentMakeUpdate()', () => { - it('should recalculate the ticket components without make modifications', async() => { - let stmts = []; - let stmt; - - let params = { - ticketId: 11, - clientId: 1102, - agencyModeId: 2, - addressId: 122, - zoneId: 3, - warehouseId: 1, - companyId: 442, - isDeleted: 0, - hasToBeUnrouted: 0, - componentOption: 1 - }; - - stmts.push('START TRANSACTION'); - - stmt = new ParameterizedSQL('SELECT * FROM vn.ticket WHERE id = ?', [ - params.ticketId - ]); - stmts.push(stmt); - - let originalTicketIndex = stmts.push(stmt) - 1; - - stmt = new ParameterizedSQL('CALL vn.ticket_componentMakeUpdate(?, ?, ?, ?, ?, ?, ?, DATE_ADD(CURDATE(), INTERVAL +1 DAY), DATE_ADD(CURDATE(), INTERVAL +1 DAY), ?, ?, ?)', [ - params.ticketId, - params.clientId, - params.agencyModeId, - params.addressId, - params.zoneId, - params.warehouseId, - params.companyId, - params.isDeleted, - params.hasToBeUnrouted, - params.componentOption - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('SELECT * FROM vn.ticket WHERE id = ?', [ - params.ticketId - ]); - stmts.push(stmt); - - let updatedTicketIndex = stmts.push(stmt) - 1; - - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await app.models.Ticket.rawStmt(sql); - - let originalTicketData = result[originalTicketIndex]; - let updatedTicketData = result[updatedTicketIndex]; - - expect(originalTicketData[0].isDeleted).toEqual(updatedTicketData[0].isDeleted); - expect(originalTicketData[0].routeFk).toEqual(updatedTicketData[0].routeFk); - }); - - it('should delete and unroute a ticket and recalculate the components', async() => { - let stmts = []; - let stmt; - - let params = { - ticketId: 11, - clientId: 1102, - agencyModeId: 2, - addressId: 122, - zoneId: 3, - warehouseId: 1, - companyId: 442, - isDeleted: 1, - hasToBeUnrouted: 1, - componentOption: 1 - }; - - stmts.push('START TRANSACTION'); - - stmt = new ParameterizedSQL('SELECT * FROM vn.ticket WHERE id = ?', [ - params.ticketId - ]); - stmts.push(stmt); - - let originalTicketIndex = stmts.push(stmt) - 1; - - stmt = new ParameterizedSQL('CALL vn.ticket_componentMakeUpdate(?, ?, ?, ?, ?, ?, ?, DATE_ADD(CURDATE(), INTERVAL +1 DAY), DATE_ADD(CURDATE(), INTERVAL +1 DAY), ?, ?, ?)', [ - params.ticketId, - params.clientId, - params.agencyModeId, - params.addressId, - params.zoneId, - params.warehouseId, - params.companyId, - params.isDeleted, - params.hasToBeUnrouted, - params.componentOption - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('SELECT * FROM vn.ticket WHERE id = ?', [ - params.ticketId - ]); - stmts.push(stmt); - - let updatedTicketIndex = stmts.push(stmt) - 1; - - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await app.models.Ticket.rawStmt(sql); - - let originalTicketData = result[originalTicketIndex]; - let updatedTicketData = result[updatedTicketIndex]; - - expect(originalTicketData[0].isDeleted).not.toEqual(updatedTicketData[0].isDeleted); - expect(originalTicketData[0].routeFk).not.toEqual(updatedTicketData[0].routeFk); - }); -}); diff --git a/e2e/paths/03-worker/04_time_control.spec.js b/e2e/paths/03-worker/04_time_control.spec.js index 5f64aa6ce..c6589d2e3 100644 --- a/e2e/paths/03-worker/04_time_control.spec.js +++ b/e2e/paths/03-worker/04_time_control.spec.js @@ -56,63 +56,6 @@ describe('Worker time control path', () => { expect(result).toContain(month); }); - it(`should return error when insert 'out' of first entry`, async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - await page.waitToClick(selectors.workerTimeControl.mondayAddTimeButton); - await page.pickTime(selectors.workerTimeControl.dialogTimeInput, eightAm); - await page.autocompleteSearch(selectors.workerTimeControl.dialogTimeDirection, 'out'); - await page.respondToDialog('accept'); - const message = await page.waitForSnackbar(); - - expect(message.text).toBeDefined(); - }); - - it(`should insert 'in' monday`, async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - await page.waitToClick(selectors.workerTimeControl.mondayAddTimeButton); - await page.pickTime(selectors.workerTimeControl.dialogTimeInput, eightAm); - await page.autocompleteSearch(selectors.workerTimeControl.dialogTimeDirection, 'in'); - await page.respondToDialog('accept'); - const result = await page.waitToGetProperty(selectors.workerTimeControl.firstEntryOfMonday, 'innerText'); - - expect(result).toEqual(eightAm); - }); - - it(`should insert 'out' monday`, async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - await page.waitToClick(selectors.workerTimeControl.mondayAddTimeButton); - await page.pickTime(selectors.workerTimeControl.dialogTimeInput, fourPm); - await page.autocompleteSearch(selectors.workerTimeControl.dialogTimeDirection, 'out'); - await page.respondToDialog('accept'); - const result = await page.waitToGetProperty(selectors.workerTimeControl.secondEntryOfMonday, 'innerText'); - - expect(result).toEqual(fourPm); - }); - - it(`should check Hank Pym worked 8:20 hours`, async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - await page.waitForTextInElement(selectors.workerTimeControl.mondayWorkedHours, '08:20 h.'); - await page.waitForTextInElement(selectors.workerTimeControl.weekWorkedHours, '08:20 h.'); - }); - - it('should remove first entry of monday', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - await page.waitForTextInElement(selectors.workerTimeControl.firstEntryOfMonday, eightAm); - await page.waitForTextInElement(selectors.workerTimeControl.secondEntryOfMonday, fourPm); - await page.waitToClick(selectors.workerTimeControl.firstEntryOfMondayDelete); - await page.respondToDialog('accept'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Entry removed'); - }); - - it(`should be the 'out' the first entry of monday`, async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - const result = await page.waitToGetProperty(selectors.workerTimeControl.firstEntryOfMonday, 'innerText'); - - expect(result).toEqual(fourPm); - }); - it('should change week of month', async() => { await page.click(selectors.workerTimeControl.thrirdWeekDay); const result = await page.getProperty(selectors.workerTimeControl.mondayWorkedHours, 'innerText'); diff --git a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js index 5e82306cc..b74f81253 100644 --- a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js +++ b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js @@ -188,17 +188,6 @@ describe('Ticket Edit sale path', () => { expect(result).toContain('22.50'); }); - it('should check in the history that logs has been added', async() => { - pending('https://redmine.verdnatura.es/issues/5455'); - await page.reload({waitUntil: ['networkidle0', 'domcontentloaded']}); - await page.waitToClick(selectors.ticketSales.firstSaleHistoryButton); - await page.waitForSelector(selectors.ticketSales.firstSaleHistory); - const result = await page.countElement(selectors.ticketSales.firstSaleHistory); - - expect(result).toBeGreaterThan(0); - await page.waitToClick(selectors.ticketSales.closeHistory); - }); - it('should recalculate price of sales', async() => { await page.waitToClick(selectors.ticketSales.firstSaleCheckbox); await page.waitToClick(selectors.ticketSales.secondSaleCheckbox); diff --git a/e2e/paths/05-ticket/11_diary.spec.js b/e2e/paths/05-ticket/11_diary.spec.js deleted file mode 100644 index e4c63855a..000000000 --- a/e2e/paths/05-ticket/11_diary.spec.js +++ /dev/null @@ -1,31 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -// #2221 Local MySQL8 crashes when rest method Items/getBalance is called -xdescribe('Ticket diary path', () => { - let page; - - beforeAll(async() => { - page = (await getBrowser()).page; - await page.loginAndModule('employee', 'ticket'); - }); - - afterAll(async() => { - await page.browser().close(); - }); - - it(`should navigate to item diary from ticket sale and check the lines`, async() => { - await page.accessToSearchResult('1'); - await page.waitToClick(selectors.ticketSummary.firstSaleItemId); - await page.waitToClick(selectors.ticketSummary.popoverDiaryButton); - await page.waitForState('item.card.diary'); - - const secondIdClass = await page.getClassName(selectors.itemDiary.secondTicketId); - const fourthBalanceClass = await page.getClassName(selectors.itemDiary.fourthBalance); - const firstBalanceClass = await page.getClassName(selectors.itemDiary.firstBalance); - - expect(secondIdClass).toContain('message'); - expect(fourthBalanceClass).toContain('message'); - expect(firstBalanceClass).toContain('balance'); - }); -}); diff --git a/e2e/paths/06-claim/02_detail.spec.js b/e2e/paths/06-claim/02_detail.spec.js deleted file mode 100644 index eb4ac5d71..000000000 --- a/e2e/paths/06-claim/02_detail.spec.js +++ /dev/null @@ -1,114 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer.js'; - -// #1528 e2e claim/detail -xdescribe('Claim detail', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('salesPerson', 'claim'); - await page.accessToSearchResult('1'); - await page.accessToSection('claim.card.detail'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should add the first claimable item from ticket to the claim', async() => { - await page.waitToClick(selectors.claimDetail.addItemButton); - await page.waitToClick(selectors.claimDetail.firstClaimableSaleFromTicket); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should confirm the claim contains now two items', async() => { - const result = await page.countElement(selectors.claimDetail.claimDetailLine); - - expect(result).toEqual(2); - }); - - it('should edit de first item claimed quantity', async() => { - await page.clearInput(selectors.claimDetail.firstItemQuantityInput); // selector deleted, find new upon fixes - await page.write(selectors.claimDetail.firstItemQuantityInput, '4'); // selector deleted, find new upon fixes - await page.keyboard.press('Enter'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should confirm the first item quantity, and the claimed total were correctly edited', async() => { - const claimedQuantity = page - .waitToGetProperty(selectors.claimDetail.firstItemQuantityInput, 'value'); // selector deleted, find new upon fixes - - const totalClaimed = page - .waitToGetProperty(selectors.claimDetail.totalClaimed, 'innerText'); - - expect(claimedQuantity).toEqual('4'); - expect(totalClaimed).toContain('€47.62'); - }); - - it('should login as salesAssistant and navigate to the claim.detail section', async() => { - await page.loginAndModule('salesAssistant', 'claim'); - await page.accessToSearchResult('1'); - await page.accessToSection('claim.card.detail'); - let url = await page.expectURL('/detail'); // replace with waitForState - - expect(url).toBe(true); - }); - - it('should edit de second item claimed discount', async() => { - await page.waitToClick(selectors.claimDetail.secondItemDiscount); - await page.write(selectors.claimDetail.discount, '100'); - await page.keyboard.press('Enter'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should check the mana is the expected one', async() => { - await page.waitToClick(selectors.claimDetail.secondItemDiscount); - const result = await page.waitToGetProperty(selectors.claimDetail.discoutPopoverMana, 'innerText'); - - expect(result).toContain('MANÁ: €106'); - }); - - it('should delete the second item from the claim', async() => { - await page.waitToClick(selectors.claimDetail.secondItemDeleteButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should confirm the claim contains now one item', async() => { - const result = await page.countElement(selectors.claimDetail.claimDetailLine); - - expect(result).toEqual(1); - }); - - it('should add the deleted ticket from to the claim', async() => { - await page.waitToClick(selectors.claimDetail.addItemButton); - await page.waitToClick(selectors.claimDetail.firstClaimableSaleFromTicket); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it(`should have been redirected to the next section in claims`, async() => { - let url = await page.expectURL('development'); // replace with waitForState - - expect(url).toBe(true); - }); - - it('should navigate back to claim.detail to confirm the claim contains now two items', async() => { - await page.accessToSection('claim.card.detail'); - await page.waitForSelector(selectors.claimDetail.claimDetailLine); - const result = await page.countElement(selectors.claimDetail.claimDetailLine); - - expect(result).toEqual(2); - }); -}); diff --git a/e2e/paths/10-travel/02_basic_data_and_log.spec.js b/e2e/paths/10-travel/02_basic_data_and_log.spec.js index 0079e8023..e6c601d7d 100644 --- a/e2e/paths/10-travel/02_basic_data_and_log.spec.js +++ b/e2e/paths/10-travel/02_basic_data_and_log.spec.js @@ -105,17 +105,4 @@ describe('Travel basic data path', () => { it(`should check the received checkbox was saved even tho it doesn't make sense`, async() => { await page.waitForClassPresent(selectors.travelBasicData.received, 'checked'); }); - - it('should navigate to the travel logs', async() => { - pending('https://redmine.verdnatura.es/issues/5455'); - await page.accessToSection('travel.card.log'); - await page.waitForState('travel.card.log'); - }); - - it('should check the 1st log contains details from the changes made', async() => { - pending('https://redmine.verdnatura.es/issues/5455'); - const result = await page.waitToGetProperty(selectors.travelLog.firstLogFirstTD, 'innerText'); - - expect(result).toContain('new reference!'); - }); }); diff --git a/front/core/components/treeview/index.spec.js b/front/core/components/treeview/index.spec.js index 9277f3ee4..1979d517f 100644 --- a/front/core/components/treeview/index.spec.js +++ b/front/core/components/treeview/index.spec.js @@ -33,18 +33,6 @@ describe('Component vnTreeview', () => { $element.remove(); }); - // See how to test DOM element in Jest - xdescribe('undrop()', () => { - it(`should reset all drop events and properties`, () => { - controller.dropping = angular.element(``); - jest.spyOn(controller.dropping.classList, 'remove'); - - controller.undrop(); - - expect(controller.dropping).toBeNull(); - }); - }); - describe('dragOver()', () => { it(`should set the dragClientY property`, () => { const event = new Event('dragover'); diff --git a/modules/ticket/back/methods/boxing/specs/getVideo.spec.js b/modules/ticket/back/methods/boxing/specs/getVideo.spec.js deleted file mode 100644 index 8e8cdc5b9..000000000 --- a/modules/ticket/back/methods/boxing/specs/getVideo.spec.js +++ /dev/null @@ -1,40 +0,0 @@ -const models = require('vn-loopback/server/server').models; -const https = require('https'); - -xdescribe('boxing getVideo()', () => { - it('should return data', async() => { - const tx = await models.PackingSiteConfig.beginTransaction({}); - - try { - const options = {transaction: tx}; - - const id = 1; - const video = 'video.mp4'; - - const response = { - pipe: () => {}, - on: () => {}, - end: () => {}, - }; - - const req = { - headers: 'apiHeader', - data: { - pipe: () => {}, - on: () => {}, - } - }; - - spyOn(https, 'request').and.returnValue(response); - - const result = await models.Boxing.getVideo(id, video, req, null, options); - - expect(result[0]).toEqual(response.data.videos[0].filename); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); -});