From 639d5963a3517463d0364ec73276583b42cb00b5 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 17 Jul 2023 13:50:07 +0200 Subject: [PATCH 01/47] refs #6028 get_routes --- db/changes/233001/00-getRoutesByWorker.sql | 24 ++++++++++ db/export-data.sh | 1 + .../client/specs/getRoutesByWorker.spec.js | 19 ++++++++ .../back/methods/route/getDeliveryPoint.js | 2 +- .../back/methods/route/getRoutesByWorker.js | 48 +++++++++++++++++++ .../route/back/methods/route/guessPriority.js | 4 +- .../route/back/methods/route/insertTicket.js | 2 +- modules/route/back/models/route.js | 1 + modules/route/front/tickets/index.js | 2 +- 9 files changed, 98 insertions(+), 5 deletions(-) create mode 100644 db/changes/233001/00-getRoutesByWorker.sql create mode 100644 modules/client/back/methods/client/specs/getRoutesByWorker.spec.js create mode 100644 modules/route/back/methods/route/getRoutesByWorker.js diff --git a/db/changes/233001/00-getRoutesByWorker.sql b/db/changes/233001/00-getRoutesByWorker.sql new file mode 100644 index 000000000..aa612d48e --- /dev/null +++ b/db/changes/233001/00-getRoutesByWorker.sql @@ -0,0 +1,24 @@ +DELETE FROM `salix`.`ACL` + WHERE + model = 'Route' + AND property = '*' + AND accessType = 'READ'; + +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) + VALUES + ('Route', 'find', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'findById', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'findOne', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'getRoutesByWorker', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'canViewAllRoute', 'READ', 'ALLOW', 'ROLE', 'deliveryBoss'), + ('Route', 'filter', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'getSuggestedTickets', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'getTickets', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'guessPriority', 'WRITE', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'insertTicket', 'WRITE', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'getDeliveryPoint', 'READ', 'ALLOW', 'ROLE', 'deliveryBoss'), + ('Route', 'summary', 'READ', 'ALLOW', 'ROLE', 'employee'); + + +INSERT INTO salix.AccessToken (id, ttl, scopes, created, userId, outdated) VALUES('1z0GILWTs8huKrJGp7Fj0PvHaGA8Gg9DTNhm6nn6AfhkNJygeVUHMZKOGfMPp0xO', 1209600, NULL, '2023-07-17 13:34:10', 56, '2023-07-31 13:34:10'); +INSERT INTO salix.AccessToken (id, ttl, scopes, created, userId, outdated) VALUES('1z0GILWTs8huKrJGp7Fj0PvHaGA8Gg9DTNhm6nn6AfhkNJygeVUHMZKOGfMPp0xP', 1209600, NULL, '2023-07-17 13:34:10', 57, '2023-07-31 13:34:10'); diff --git a/db/export-data.sh b/db/export-data.sh index 1df4db030..914564093 100755 --- a/db/export-data.sh +++ b/db/export-data.sh @@ -69,6 +69,7 @@ TABLES=( volumeConfig workCenter companyI18n + silexACL ) dump_tables ${TABLES[@]} diff --git a/modules/client/back/methods/client/specs/getRoutesByWorker.spec.js b/modules/client/back/methods/client/specs/getRoutesByWorker.spec.js new file mode 100644 index 000000000..b43fe49d2 --- /dev/null +++ b/modules/client/back/methods/client/specs/getRoutesByWorker.spec.js @@ -0,0 +1,19 @@ +const {models} = require('vn-loopback/server/server'); + +describe('getRoutesByWorker', () => { + fit('should return the routes of the worker can view all routes', async() => { + const deliveryBossId = 57; + const ctx = {req: {accessToken: {userId: deliveryBossId}}}; + const result = await models.Route.getRoutesByWorker(ctx); + + expect(result.length).toEqual(7); + }); + + fit('should return the routes of the worker can not view all routes', async() => { + const deliveryId = 56; + const ctx = {req: {accessToken: {userId: deliveryId}}}; + const result = await models.Route.getRoutesByWorker(ctx); + + expect(result.length).toEqual(5); + }); +}); diff --git a/modules/route/back/methods/route/getDeliveryPoint.js b/modules/route/back/methods/route/getDeliveryPoint.js index e5a50805a..3359f666e 100644 --- a/modules/route/back/methods/route/getDeliveryPoint.js +++ b/modules/route/back/methods/route/getDeliveryPoint.js @@ -1,7 +1,7 @@ module.exports = Self => { Self.remoteMethod('getDeliveryPoint', { description: 'get the deliveryPoint address', - accessType: 'WRITE', + accessType: 'READ', accepts: { arg: 'vehicleId', type: 'number', diff --git a/modules/route/back/methods/route/getRoutesByWorker.js b/modules/route/back/methods/route/getRoutesByWorker.js new file mode 100644 index 000000000..0a6f59816 --- /dev/null +++ b/modules/route/back/methods/route/getRoutesByWorker.js @@ -0,0 +1,48 @@ +module.exports = Self => { + Self.remoteMethodCtx('getRoutesByWorker', { + description: 'Return the routes by worker', + accessType: 'READ', + returns: { + type: 'object', + root: true + }, + http: { + path: `/get-routes-by-worker`, + verb: 'GET' + } + }); + + Self.getRoutesByWorker = async(ctx, options) => { + const userId = ctx.req.accessToken.userId; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const canViewAll = await Self.app.models.ACL.checkAccessAcl(ctx, 'Route', 'canViewAllRoute', 'READ'); + const condition = canViewAll ? `ay.warehouseFK = uc.warehouseFk` : `r.workerFk = ${userId}`; + + return Self.rawSql(` + SELECT concat(w.firstName , ' ', w.lastName) driver, + r.id, + Date_format(r.time, '%H:%i') hour, + r.created, + r.m3, + v.numberPlate, + a.name, + r.kmStart, + r.kmEnd, + r.started, + r.finished + FROM vn.route r + JOIN vn.vehicle v ON r.vehicleFk = v.id + JOIN vn.agencyMode a ON r.agencyModeFk = a.id + JOIN vn.agency ay ON a.agencyFk = ay.id + JOIN vn.worker w ON r.workerFk = w.id + LEFT JOIN vn.userConfig uc ON uc.userFk = ? + WHERE (r.created = util.VN_CURDATE() OR r.created = TIMESTAMPADD(day, 1, util.VN_CURDATE())) + AND ${condition} + ORDER BY r.created ASC, r.time ASC, a.name ASC + `, [userId], myOptions); + }; +}; diff --git a/modules/route/back/methods/route/guessPriority.js b/modules/route/back/methods/route/guessPriority.js index c6b2a9b74..749075388 100644 --- a/modules/route/back/methods/route/guessPriority.js +++ b/modules/route/back/methods/route/guessPriority.js @@ -1,7 +1,7 @@ module.exports = Self => { Self.remoteMethodCtx('guessPriority', { description: 'Changes automatically the priority of the tickets in a route', - accessType: 'READ', + accessType: 'WRITE', accepts: [{ arg: 'id', type: 'number', @@ -15,7 +15,7 @@ module.exports = Self => { }, http: { path: `/:id/guessPriority`, - verb: 'GET' + verb: 'PATCH' } }); diff --git a/modules/route/back/methods/route/insertTicket.js b/modules/route/back/methods/route/insertTicket.js index f78e1cb83..4ac8bad1a 100644 --- a/modules/route/back/methods/route/insertTicket.js +++ b/modules/route/back/methods/route/insertTicket.js @@ -3,7 +3,7 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethod('insertTicket', { description: 'Check if the ticket can be insert into the route and insert it', - accessType: 'READ', + accessType: 'WRITE', accepts: [{ arg: 'routeId', type: 'number', diff --git a/modules/route/back/models/route.js b/modules/route/back/models/route.js index 883f4597e..fe88f2e08 100644 --- a/modules/route/back/models/route.js +++ b/modules/route/back/models/route.js @@ -14,6 +14,7 @@ module.exports = Self => { require('../methods/route/driverRouteEmail')(Self); require('../methods/route/sendSms')(Self); require('../methods/route/downloadZip')(Self); + require('../methods/route/getRoutesByWorker')(Self); Self.validate('kmStart', validateDistance, { message: 'Distance must be lesser than 1000' diff --git a/modules/route/front/tickets/index.js b/modules/route/front/tickets/index.js index 8789708ac..a1b97005e 100644 --- a/modules/route/front/tickets/index.js +++ b/modules/route/front/tickets/index.js @@ -120,7 +120,7 @@ class Controller extends Section { guessPriority() { let query = `Routes/${this.$params.id}/guessPriority/`; - this.$http.get(query).then(() => { + this.$http.patch(query).then(() => { this.vnApp.showSuccess(this.$t('Order changed')); this.$.model.refresh(); }); From f3e43686a3db0f7a1e43434fd8e3396f5436b657 Mon Sep 17 00:00:00 2001 From: vicent Date: Thu, 24 Aug 2023 14:59:28 +0200 Subject: [PATCH 02/47] 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 03/47] 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 04/47] 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 05/47] 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 9f92bc4b4c5e72bc63385605a115f6d464416dac Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 10 Nov 2023 11:43:42 +0100 Subject: [PATCH 06/47] 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 07/47] 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 0a2fd9cf5de1915d897d4a5871f74f74ff988019 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Mon, 20 Nov 2023 18:39:37 +0100 Subject: [PATCH 08/47] 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 09/47] 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 707173d6184c9f7dbe663d69e3dd2e2fb4042c79 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 22 Nov 2023 07:04:33 +0100 Subject: [PATCH 10/47] refs #5890 fix: getTickets --- back/methods/collection/getTickets.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js index f04822697..cfd404beb 100644 --- a/back/methods/collection/getTickets.js +++ b/back/methods/collection/getTickets.js @@ -74,8 +74,8 @@ module.exports = Self => { LEFT JOIN parking p ON p.id = sh.parkingFk LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk LEFT JOIN origin o ON o.id = i.originFk - WHERE tc.collectionFk = ? - GROUP BY ish.id, p.code, p2.code + WHERE tc.collectionFk = ? AND iss.quantity IS NOT NULL + GROUP BY s.id, ish.id, p.code, p2.code ORDER BY pickingOrder;`, [id], myOptions); if (print) From a27bb53089eb6913b2ffbd14dc6c296be1ac6dee Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 22 Nov 2023 08:57:45 +0100 Subject: [PATCH 11/47] refs #5835 getTotals fixed --- .../back/methods/invoice-in/getTotals.js | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/modules/invoiceIn/back/methods/invoice-in/getTotals.js b/modules/invoiceIn/back/methods/invoice-in/getTotals.js index f35c10617..4c45284d5 100644 --- a/modules/invoiceIn/back/methods/invoice-in/getTotals.js +++ b/modules/invoiceIn/back/methods/invoice-in/getTotals.js @@ -29,15 +29,18 @@ module.exports = Self => { SELECT iit.*, SUM(iidd.amount) totalDueDay FROM vn.invoiceIn ii - LEFT JOIN (SELECT SUM(iit.taxableBase) totalTaxableBase, - CAST(SUM(iit.taxableBase * (1 + (ti.PorcentajeIva / 100))) AS DECIMAL(10,2)) totalVat + LEFT JOIN ( + SELECT SUM(iit.taxableBase) totalTaxableBase, + CAST( + SUM(COALESCE(iit.taxableBase * (1 + (ti.PorcentajeIva / 100)), iit.taxableBase)) + AS DECIMAL(10, 2) + ) totalVat FROM vn.invoiceInTax iit LEFT JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk - WHERE iit.invoiceInFk = ?) iit ON TRUE + WHERE iit.invoiceInFk = ? + ) iit ON TRUE LEFT JOIN vn.invoiceInDueDay iidd ON iidd.invoiceInFk = ii.id - WHERE - ii.id = ?`, [id, id]); - + WHERE ii.id = ?`, [id, id]); return result; }; }; From e856de0cfd8681f05b1639d003074545f38f9f39 Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 22 Nov 2023 15:54:38 +0100 Subject: [PATCH 12/47] feat: refs #6028 test --- .../00-getRoutesByWorker.sql | 4 -- .../client/specs/getRoutesByWorker.spec.js | 19 ------ modules/route/back/methods/route/filter.js | 6 +- .../route/back/methods/route/getByWorker.js | 66 +++++++++++++++++++ .../back/methods/route/getRoutesByWorker.js | 48 -------------- .../methods/route/specs/getByWorker.spec.js | 39 +++++++++++ modules/route/back/models/route.js | 2 +- 7 files changed, 110 insertions(+), 74 deletions(-) rename db/changes/{233001 => 234801}/00-getRoutesByWorker.sql (71%) delete mode 100644 modules/client/back/methods/client/specs/getRoutesByWorker.spec.js create mode 100644 modules/route/back/methods/route/getByWorker.js delete mode 100644 modules/route/back/methods/route/getRoutesByWorker.js create mode 100644 modules/route/back/methods/route/specs/getByWorker.spec.js diff --git a/db/changes/233001/00-getRoutesByWorker.sql b/db/changes/234801/00-getRoutesByWorker.sql similarity index 71% rename from db/changes/233001/00-getRoutesByWorker.sql rename to db/changes/234801/00-getRoutesByWorker.sql index aa612d48e..bdc4a246e 100644 --- a/db/changes/233001/00-getRoutesByWorker.sql +++ b/db/changes/234801/00-getRoutesByWorker.sql @@ -18,7 +18,3 @@ INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `pri ('Route', 'insertTicket', 'WRITE', 'ALLOW', 'ROLE', 'employee'), ('Route', 'getDeliveryPoint', 'READ', 'ALLOW', 'ROLE', 'deliveryBoss'), ('Route', 'summary', 'READ', 'ALLOW', 'ROLE', 'employee'); - - -INSERT INTO salix.AccessToken (id, ttl, scopes, created, userId, outdated) VALUES('1z0GILWTs8huKrJGp7Fj0PvHaGA8Gg9DTNhm6nn6AfhkNJygeVUHMZKOGfMPp0xO', 1209600, NULL, '2023-07-17 13:34:10', 56, '2023-07-31 13:34:10'); -INSERT INTO salix.AccessToken (id, ttl, scopes, created, userId, outdated) VALUES('1z0GILWTs8huKrJGp7Fj0PvHaGA8Gg9DTNhm6nn6AfhkNJygeVUHMZKOGfMPp0xP', 1209600, NULL, '2023-07-17 13:34:10', 57, '2023-07-31 13:34:10'); diff --git a/modules/client/back/methods/client/specs/getRoutesByWorker.spec.js b/modules/client/back/methods/client/specs/getRoutesByWorker.spec.js deleted file mode 100644 index b43fe49d2..000000000 --- a/modules/client/back/methods/client/specs/getRoutesByWorker.spec.js +++ /dev/null @@ -1,19 +0,0 @@ -const {models} = require('vn-loopback/server/server'); - -describe('getRoutesByWorker', () => { - fit('should return the routes of the worker can view all routes', async() => { - const deliveryBossId = 57; - const ctx = {req: {accessToken: {userId: deliveryBossId}}}; - const result = await models.Route.getRoutesByWorker(ctx); - - expect(result.length).toEqual(7); - }); - - fit('should return the routes of the worker can not view all routes', async() => { - const deliveryId = 56; - const ctx = {req: {accessToken: {userId: deliveryId}}}; - const result = await models.Route.getRoutesByWorker(ctx); - - expect(result.length).toEqual(5); - }); -}); diff --git a/modules/route/back/methods/route/filter.js b/modules/route/back/methods/route/filter.js index fc35e979f..afefa77d1 100644 --- a/modules/route/back/methods/route/filter.js +++ b/modules/route/back/methods/route/filter.js @@ -105,7 +105,7 @@ module.exports = Self => { } }); - filter = mergeFilters(ctx.args.filter, {where}); + filter = mergeFilters(filter, {where}); let stmts = []; let stmt; @@ -129,9 +129,11 @@ module.exports = Self => { r.description, am.name agencyName, u.name AS workerUserName, - v.numberPlate AS vehiclePlateNumber + v.numberPlate AS vehiclePlateNumber, + Date_format(r.time, '%H:%i') hour 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` diff --git a/modules/route/back/methods/route/getByWorker.js b/modules/route/back/methods/route/getByWorker.js new file mode 100644 index 000000000..2f8a286e6 --- /dev/null +++ b/modules/route/back/methods/route/getByWorker.js @@ -0,0 +1,66 @@ +const mergeFilters = require('vn-loopback/util/filter').mergeFilters; + +module.exports = Self => { + Self.remoteMethodCtx('getByWorker', { + description: 'Return the routes by worker', + accessType: 'READ', + returns: { + type: ['object'], + root: true + }, + http: { + path: `/getByWorker`, + verb: 'GET' + } + }); + + Self.getByWorker = async ctx => { + const models = Self.app.models; + const userId = ctx.req.accessToken.userId; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const canViewAll = await models.ACL.checkAccessAcl(ctx, 'Route', 'canViewAllRoute', 'READ'); + let filterGrant = {}; + console.log(userId); + console.log(canViewAll); + if (canViewAll) { + const userConfig = await models.UserConfig.getUserConfig(ctx, myOptions); + filterGrant = { + where: {'a.warehouseFk': userConfig.warehouseFk} + }; + } else { + filterGrant = { + where: {'r.workerFk': userId} + }; + } + + const currentDate = Date.vnNew(); + currentDate.setHours(0, 0, 0, 0); + const nextDay = Date.vnNew(); + nextDay.setDate(currentDate.getDate() + 1); + + const filter = { + where: { + and: [ + { + or: [ + {'r.created': currentDate}, + {'r.created': nextDay} + ] + } + ] + }, + order: [ + 'r.created ASC', + 'r.time ASC', + 'am.name ASC' + ] + }; + + const result = await Self.filter(ctx, mergeFilters(filter, filterGrant)); + return result; + }; +}; diff --git a/modules/route/back/methods/route/getRoutesByWorker.js b/modules/route/back/methods/route/getRoutesByWorker.js deleted file mode 100644 index 0a6f59816..000000000 --- a/modules/route/back/methods/route/getRoutesByWorker.js +++ /dev/null @@ -1,48 +0,0 @@ -module.exports = Self => { - Self.remoteMethodCtx('getRoutesByWorker', { - description: 'Return the routes by worker', - accessType: 'READ', - returns: { - type: 'object', - root: true - }, - http: { - path: `/get-routes-by-worker`, - verb: 'GET' - } - }); - - Self.getRoutesByWorker = async(ctx, options) => { - const userId = ctx.req.accessToken.userId; - const myOptions = {}; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - const canViewAll = await Self.app.models.ACL.checkAccessAcl(ctx, 'Route', 'canViewAllRoute', 'READ'); - const condition = canViewAll ? `ay.warehouseFK = uc.warehouseFk` : `r.workerFk = ${userId}`; - - return Self.rawSql(` - SELECT concat(w.firstName , ' ', w.lastName) driver, - r.id, - Date_format(r.time, '%H:%i') hour, - r.created, - r.m3, - v.numberPlate, - a.name, - r.kmStart, - r.kmEnd, - r.started, - r.finished - FROM vn.route r - JOIN vn.vehicle v ON r.vehicleFk = v.id - JOIN vn.agencyMode a ON r.agencyModeFk = a.id - JOIN vn.agency ay ON a.agencyFk = ay.id - JOIN vn.worker w ON r.workerFk = w.id - LEFT JOIN vn.userConfig uc ON uc.userFk = ? - WHERE (r.created = util.VN_CURDATE() OR r.created = TIMESTAMPADD(day, 1, util.VN_CURDATE())) - AND ${condition} - ORDER BY r.created ASC, r.time ASC, a.name ASC - `, [userId], myOptions); - }; -}; diff --git a/modules/route/back/methods/route/specs/getByWorker.spec.js b/modules/route/back/methods/route/specs/getByWorker.spec.js new file mode 100644 index 000000000..52b8d6d87 --- /dev/null +++ b/modules/route/back/methods/route/specs/getByWorker.spec.js @@ -0,0 +1,39 @@ +const app = require('vn-loopback/server/server'); +const LoopBackContext = require('loopback-context'); + +fdescribe('route getByWorker()', () => { + const userId = 56; + const activeCtx = { + accessToken: {userId: userId}, + http: { + req: { + headers: {origin: 'http://localhost'} + } + } + }; + const ctx = {req: activeCtx}; + + beforeAll(() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + }); + + it('should return routes assigned to the worker', async() => { + const result = await app.models.Route.getByWorker(ctx); + + // Aquí se verifica que el resultado contiene rutas asignadas al usuario + console.log(result); + + expect(result.every(route => route.workerFk === userId)).toBe(true); + }); + + it('should return all routes if user has canViewAllRoute permission', async() => { + // Simular que el usuario tiene permiso para ver todas las rutas + spyOn(app.models.ACL, 'checkAccessAcl').and.returnValue(Promise.resolve(true)); + + const result = await app.models.Route.getByWorker(ctx); + + expect(result.some(route => route.workerFk != userId)).toBe(true); + }); +}); diff --git a/modules/route/back/models/route.js b/modules/route/back/models/route.js index 073c601fe..cbdd75679 100644 --- a/modules/route/back/models/route.js +++ b/modules/route/back/models/route.js @@ -14,10 +14,10 @@ module.exports = Self => { require('../methods/route/driverRouteEmail')(Self); require('../methods/route/sendSms')(Self); require('../methods/route/downloadZip')(Self); - require('../methods/route/getRoutesByWorker')(Self); require('../methods/route/cmr')(Self); require('../methods/route/getExternalCmrs')(Self); require('../methods/route/downloadCmrsZip')(Self); + require('../methods/route/getByWorker')(Self); Self.validate('kmStart', validateDistance, { message: 'Distance must be lesser than 1000' From 6b07ee4eb1913294468af4e4202c9d768c1ff716 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 22 Nov 2023 18:35:14 +0100 Subject: [PATCH 13/47] 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 f4fabb9fff0f95506c289834adbef3e6af58e713 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 23 Nov 2023 08:26:14 +0100 Subject: [PATCH 14/47] refs #6491 refactor(order_filter): optimized --- CHANGELOG.md | 1 + modules/order/back/methods/order/filter.js | 3 +++ 2 files changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 08a62f044..1f16511b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - (Ticket -> Adelantar) Permite mover lineas sin generar negativos - (Ticket -> Adelantar) Permite modificar la fecha de los tickets +- (Trabajadores -> Notificaciones) Nueva sección (lilium) ### Changed ### Fixed diff --git a/modules/order/back/methods/order/filter.js b/modules/order/back/methods/order/filter.js index 97fca5c10..592ed11e6 100644 --- a/modules/order/back/methods/order/filter.js +++ b/modules/order/back/methods/order/filter.js @@ -139,6 +139,8 @@ module.exports = Self => { filter = mergeFilters(filter, {where}); const stmts = []; let stmt; + stmts.push(`SET @_optimizer_search_depth = @@optimizer_search_depth`); + stmts.push(`SET SESSION optimizer_search_depth = 0`); stmt = new ParameterizedSQL(` CREATE OR REPLACE TEMPORARY TABLE tmp.filter @@ -195,6 +197,7 @@ module.exports = Self => { stmt.merge(`GROUP BY id`); stmt.merge(conn.makePagination(filter)); stmts.push(stmt); + stmts.push(`SET SESSION optimizer_search_depth = @_optimizer_search_depth`); stmt = new ParameterizedSQL(`SELECT * FROM tmp.filter`); stmt.merge(conn.makeOrderBy(filter.order)); From 217aa1ac770ffb1e3e13cc76188cf800671af8bc Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 23 Nov 2023 08:35:08 +0100 Subject: [PATCH 15/47] refs #6491 deploy(2350) init version --- CHANGELOG.md | 7 +++++++ db/{changes => .archive}/233001/.gitkeep | 0 db/{changes => .archive}/233001/00-aclSaleTracking.sql | 0 db/{changes => .archive}/233001/00-clientSms.sql | 0 db/{changes => .archive}/233001/00-company.sql | 0 db/{changes => .archive}/233001/00-fixACLVehicle.sql | 0 db/{changes => .archive}/233001/00-itemRecycle.sql | 0 .../233001/00-itemShelving_inventory.sql | 0 db/{changes => .archive}/233001/00-noUniqueSocialName.sql | 0 db/{changes => .archive}/233001/00-roadmap.sql | 0 db/{changes => .archive}/233001/00-roadmapACL.sql | 0 db/{changes => .archive}/233001/00-ticketWeight.sql | 0 db/{changes => .archive}/233201/.gitkeep | 0 .../233201/00-acl_viaexpressConfig.sql | 0 db/{changes => .archive}/233201/00-transferClient.sql | 0 db/{changes => .archive}/233201/00-updatePrice.sql | 0 db/{changes => .archive}/233201/00-viaexpress.sql | 0 db/{changes => .archive}/233201/00-workerDocuware.sql | 0 db/{changes => .archive}/233202/00-client_create_upper.sql | 0 db/{changes => .archive}/233202/00-ticketSmsACL.sql | 0 db/{changes => .archive}/233401/00-setDeleted_acl.sql | 0 db/{changes => .archive}/233601/.gitkeep | 0 db/{changes => .archive}/233601/00-aclWorker.sql | 0 db/{changes => .archive}/233601/00-addExpeditionState.sql | 0 db/{changes => .archive}/233601/00-department.sql | 0 db/{changes => .archive}/233601/00-saleGroupDetail.sql | 0 db/{changes => .archive}/233801/.gitkeep | 0 db/{changes => .archive}/233801/00-firstScript.sql | 0 db/{changes => .archive}/233801/01-deviceLog_acl.sql | 0 db/{changes => .archive}/233802/.gitkeep | 0 .../233802/00-collectionGetTicketsACL.sql | 0 db/changes/235001/.gitkeep | 0 package-lock.json | 4 ++-- package.json | 2 +- 34 files changed, 10 insertions(+), 3 deletions(-) rename db/{changes => .archive}/233001/.gitkeep (100%) rename db/{changes => .archive}/233001/00-aclSaleTracking.sql (100%) rename db/{changes => .archive}/233001/00-clientSms.sql (100%) rename db/{changes => .archive}/233001/00-company.sql (100%) rename db/{changes => .archive}/233001/00-fixACLVehicle.sql (100%) rename db/{changes => .archive}/233001/00-itemRecycle.sql (100%) rename db/{changes => .archive}/233001/00-itemShelving_inventory.sql (100%) rename db/{changes => .archive}/233001/00-noUniqueSocialName.sql (100%) rename db/{changes => .archive}/233001/00-roadmap.sql (100%) rename db/{changes => .archive}/233001/00-roadmapACL.sql (100%) rename db/{changes => .archive}/233001/00-ticketWeight.sql (100%) rename db/{changes => .archive}/233201/.gitkeep (100%) rename db/{changes => .archive}/233201/00-acl_viaexpressConfig.sql (100%) rename db/{changes => .archive}/233201/00-transferClient.sql (100%) rename db/{changes => .archive}/233201/00-updatePrice.sql (100%) rename db/{changes => .archive}/233201/00-viaexpress.sql (100%) rename db/{changes => .archive}/233201/00-workerDocuware.sql (100%) rename db/{changes => .archive}/233202/00-client_create_upper.sql (100%) rename db/{changes => .archive}/233202/00-ticketSmsACL.sql (100%) rename db/{changes => .archive}/233401/00-setDeleted_acl.sql (100%) rename db/{changes => .archive}/233601/.gitkeep (100%) rename db/{changes => .archive}/233601/00-aclWorker.sql (100%) rename db/{changes => .archive}/233601/00-addExpeditionState.sql (100%) rename db/{changes => .archive}/233601/00-department.sql (100%) rename db/{changes => .archive}/233601/00-saleGroupDetail.sql (100%) rename db/{changes => .archive}/233801/.gitkeep (100%) rename db/{changes => .archive}/233801/00-firstScript.sql (100%) rename db/{changes => .archive}/233801/01-deviceLog_acl.sql (100%) rename db/{changes => .archive}/233802/.gitkeep (100%) rename db/{changes => .archive}/233802/00-collectionGetTicketsACL.sql (100%) create mode 100644 db/changes/235001/.gitkeep diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f16511b6..d8d040fd6 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). +## [2350.01] - 2023-12-14 + +### Added +### Changed +### Fixed + + ## [2348.01] - 2023-11-30 ### Added diff --git a/db/changes/233001/.gitkeep b/db/.archive/233001/.gitkeep similarity index 100% rename from db/changes/233001/.gitkeep rename to db/.archive/233001/.gitkeep diff --git a/db/changes/233001/00-aclSaleTracking.sql b/db/.archive/233001/00-aclSaleTracking.sql similarity index 100% rename from db/changes/233001/00-aclSaleTracking.sql rename to db/.archive/233001/00-aclSaleTracking.sql diff --git a/db/changes/233001/00-clientSms.sql b/db/.archive/233001/00-clientSms.sql similarity index 100% rename from db/changes/233001/00-clientSms.sql rename to db/.archive/233001/00-clientSms.sql diff --git a/db/changes/233001/00-company.sql b/db/.archive/233001/00-company.sql similarity index 100% rename from db/changes/233001/00-company.sql rename to db/.archive/233001/00-company.sql diff --git a/db/changes/233001/00-fixACLVehicle.sql b/db/.archive/233001/00-fixACLVehicle.sql similarity index 100% rename from db/changes/233001/00-fixACLVehicle.sql rename to db/.archive/233001/00-fixACLVehicle.sql diff --git a/db/changes/233001/00-itemRecycle.sql b/db/.archive/233001/00-itemRecycle.sql similarity index 100% rename from db/changes/233001/00-itemRecycle.sql rename to db/.archive/233001/00-itemRecycle.sql diff --git a/db/changes/233001/00-itemShelving_inventory.sql b/db/.archive/233001/00-itemShelving_inventory.sql similarity index 100% rename from db/changes/233001/00-itemShelving_inventory.sql rename to db/.archive/233001/00-itemShelving_inventory.sql diff --git a/db/changes/233001/00-noUniqueSocialName.sql b/db/.archive/233001/00-noUniqueSocialName.sql similarity index 100% rename from db/changes/233001/00-noUniqueSocialName.sql rename to db/.archive/233001/00-noUniqueSocialName.sql diff --git a/db/changes/233001/00-roadmap.sql b/db/.archive/233001/00-roadmap.sql similarity index 100% rename from db/changes/233001/00-roadmap.sql rename to db/.archive/233001/00-roadmap.sql diff --git a/db/changes/233001/00-roadmapACL.sql b/db/.archive/233001/00-roadmapACL.sql similarity index 100% rename from db/changes/233001/00-roadmapACL.sql rename to db/.archive/233001/00-roadmapACL.sql diff --git a/db/changes/233001/00-ticketWeight.sql b/db/.archive/233001/00-ticketWeight.sql similarity index 100% rename from db/changes/233001/00-ticketWeight.sql rename to db/.archive/233001/00-ticketWeight.sql diff --git a/db/changes/233201/.gitkeep b/db/.archive/233201/.gitkeep similarity index 100% rename from db/changes/233201/.gitkeep rename to db/.archive/233201/.gitkeep diff --git a/db/changes/233201/00-acl_viaexpressConfig.sql b/db/.archive/233201/00-acl_viaexpressConfig.sql similarity index 100% rename from db/changes/233201/00-acl_viaexpressConfig.sql rename to db/.archive/233201/00-acl_viaexpressConfig.sql diff --git a/db/changes/233201/00-transferClient.sql b/db/.archive/233201/00-transferClient.sql similarity index 100% rename from db/changes/233201/00-transferClient.sql rename to db/.archive/233201/00-transferClient.sql diff --git a/db/changes/233201/00-updatePrice.sql b/db/.archive/233201/00-updatePrice.sql similarity index 100% rename from db/changes/233201/00-updatePrice.sql rename to db/.archive/233201/00-updatePrice.sql diff --git a/db/changes/233201/00-viaexpress.sql b/db/.archive/233201/00-viaexpress.sql similarity index 100% rename from db/changes/233201/00-viaexpress.sql rename to db/.archive/233201/00-viaexpress.sql diff --git a/db/changes/233201/00-workerDocuware.sql b/db/.archive/233201/00-workerDocuware.sql similarity index 100% rename from db/changes/233201/00-workerDocuware.sql rename to db/.archive/233201/00-workerDocuware.sql diff --git a/db/changes/233202/00-client_create_upper.sql b/db/.archive/233202/00-client_create_upper.sql similarity index 100% rename from db/changes/233202/00-client_create_upper.sql rename to db/.archive/233202/00-client_create_upper.sql diff --git a/db/changes/233202/00-ticketSmsACL.sql b/db/.archive/233202/00-ticketSmsACL.sql similarity index 100% rename from db/changes/233202/00-ticketSmsACL.sql rename to db/.archive/233202/00-ticketSmsACL.sql diff --git a/db/changes/233401/00-setDeleted_acl.sql b/db/.archive/233401/00-setDeleted_acl.sql similarity index 100% rename from db/changes/233401/00-setDeleted_acl.sql rename to db/.archive/233401/00-setDeleted_acl.sql diff --git a/db/changes/233601/.gitkeep b/db/.archive/233601/.gitkeep similarity index 100% rename from db/changes/233601/.gitkeep rename to db/.archive/233601/.gitkeep diff --git a/db/changes/233601/00-aclWorker.sql b/db/.archive/233601/00-aclWorker.sql similarity index 100% rename from db/changes/233601/00-aclWorker.sql rename to db/.archive/233601/00-aclWorker.sql diff --git a/db/changes/233601/00-addExpeditionState.sql b/db/.archive/233601/00-addExpeditionState.sql similarity index 100% rename from db/changes/233601/00-addExpeditionState.sql rename to db/.archive/233601/00-addExpeditionState.sql diff --git a/db/changes/233601/00-department.sql b/db/.archive/233601/00-department.sql similarity index 100% rename from db/changes/233601/00-department.sql rename to db/.archive/233601/00-department.sql diff --git a/db/changes/233601/00-saleGroupDetail.sql b/db/.archive/233601/00-saleGroupDetail.sql similarity index 100% rename from db/changes/233601/00-saleGroupDetail.sql rename to db/.archive/233601/00-saleGroupDetail.sql diff --git a/db/changes/233801/.gitkeep b/db/.archive/233801/.gitkeep similarity index 100% rename from db/changes/233801/.gitkeep rename to db/.archive/233801/.gitkeep diff --git a/db/changes/233801/00-firstScript.sql b/db/.archive/233801/00-firstScript.sql similarity index 100% rename from db/changes/233801/00-firstScript.sql rename to db/.archive/233801/00-firstScript.sql diff --git a/db/changes/233801/01-deviceLog_acl.sql b/db/.archive/233801/01-deviceLog_acl.sql similarity index 100% rename from db/changes/233801/01-deviceLog_acl.sql rename to db/.archive/233801/01-deviceLog_acl.sql diff --git a/db/changes/233802/.gitkeep b/db/.archive/233802/.gitkeep similarity index 100% rename from db/changes/233802/.gitkeep rename to db/.archive/233802/.gitkeep diff --git a/db/changes/233802/00-collectionGetTicketsACL.sql b/db/.archive/233802/00-collectionGetTicketsACL.sql similarity index 100% rename from db/changes/233802/00-collectionGetTicketsACL.sql rename to db/.archive/233802/00-collectionGetTicketsACL.sql diff --git a/db/changes/235001/.gitkeep b/db/changes/235001/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/package-lock.json b/package-lock.json index b66279ae3..78ef93987 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "salix-back", - "version": "23.48.01", + "version": "23.50.01", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "salix-back", - "version": "23.48.01", + "version": "23.50.01", "license": "GPL-3.0", "dependencies": { "axios": "^1.2.2", diff --git a/package.json b/package.json index 04fcb008b..586c963dd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "23.48.01", + "version": "23.50.01", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", From f44424dbcfe92bc3bb5b5f3e42467ef8acfb6d2c Mon Sep 17 00:00:00 2001 From: jgallego Date: Thu, 23 Nov 2023 09:44:47 +0100 Subject: [PATCH 16/47] test: refs #6028 test --- back/methods/collection/newCollection.js | 133 ------------------ .../collection/spec/newCollection.spec.js | 12 -- back/models/collection.js | 1 - .../00-getRoutesByWorker.sql | 6 + .../route/back/methods/route/getByWorker.js | 3 +- .../methods/route/specs/getByWorker.spec.js | 5 +- 6 files changed, 8 insertions(+), 152 deletions(-) delete mode 100644 back/methods/collection/newCollection.js delete mode 100644 back/methods/collection/spec/newCollection.spec.js rename db/changes/{234801 => 235001}/00-getRoutesByWorker.sql (71%) diff --git a/back/methods/collection/newCollection.js b/back/methods/collection/newCollection.js deleted file mode 100644 index 2be9f8b0e..000000000 --- a/back/methods/collection/newCollection.js +++ /dev/null @@ -1,133 +0,0 @@ -module.exports = Self => { - Self.remoteMethodCtx('newCollection', { - description: 'Make a new collection of tickets', - accessType: 'WRITE', - accepts: [{ - arg: 'collectionFk', - type: 'Number', - required: false, - description: 'The collection id' - }, { - arg: 'sectorFk', - type: 'Number', - required: true, - description: 'The sector of worker' - }, { - arg: 'vWagons', - type: 'Number', - required: true, - description: 'The number of wagons' - }], - returns: { - type: 'Object', - root: true - }, - http: { - path: `/newCollection`, - verb: 'POST' - } - }); - - Self.newCollection = async(ctx, collectionFk, sectorFk, vWagons) => { - let query = ''; - const userId = ctx.req.accessToken.userId; - - if (!collectionFk) { - query = `CALL vn.collectionTrain_newBeta(?,?,?)`; - const [result] = await Self.rawSql(query, [sectorFk, vWagons, userId], {userId}); - if (result.length == 0) - throw new Error(`No collections for today`); - - collectionFk = result[0].vCollectionFk; - } - - query = `CALL vn.collectionTicket_get(?)`; - const [tickets] = await Self.rawSql(query, [collectionFk], {userId}); - - query = `CALL vn.collectionSale_get(?)`; - const [sales] = await Self.rawSql(query, [collectionFk], {userId}); - - query = `CALL vn.collectionPlacement_get(?)`; - const [placements] = await Self.rawSql(query, [collectionFk], {userId}); - - query = `CALL vn.collectionSticker_print(?,?)`; - await Self.rawSql(query, [collectionFk, sectorFk], {userId}); - - return makeCollection(tickets, sales, placements, collectionFk); - }; - - /** - * Returns a collection json - * @param {*} tickets - Request tickets - * @param {*} sales - Request sales - * @param {*} placements - Request placements - * @param {*} collectionFk - Request placements - * @return {Object} Collection JSON - */ - async function makeCollection(tickets, sales, placements, collectionFk) { - let collection = []; - - for (let i = 0; i < tickets.length; i++) { - let ticket = {}; - ticket['ticketFk'] = tickets[i]['ticketFk']; - ticket['level'] = tickets[i]['level']; - ticket['agencyName'] = tickets[i]['agencyName']; - ticket['warehouseFk'] = tickets[i]['warehouseFk']; - ticket['salesPersonFk'] = tickets[i]['salesPersonFk']; - - let ticketSales = []; - - for (let x = 0; x < sales.length; x++) { - if (sales[x]['ticketFk'] == ticket['ticketFk']) { - let sale = {}; - sale['collectionFk'] = collectionFk; - sale['ticketFk'] = sales[x]['ticketFk']; - sale['saleFk'] = sales[x]['saleFk']; - sale['itemFk'] = sales[x]['itemFk']; - sale['quantity'] = sales[x]['quantity']; - if (sales[x]['quantityPicked'] != null) - sale['quantityPicked'] = sales[x]['quantityPicked']; - else - sale['quantityPicked'] = 0; - sale['longName'] = sales[x]['longName']; - sale['size'] = sales[x]['size']; - sale['color'] = sales[x]['color']; - sale['discount'] = sales[x]['discount']; - sale['price'] = sales[x]['price']; - sale['stems'] = sales[x]['stems']; - sale['category'] = sales[x]['category']; - sale['origin'] = sales[x]['origin']; - sale['clientFk'] = sales[x]['clientFk']; - sale['productor'] = sales[x]['productor']; - sale['reserved'] = sales[x]['reserved']; - sale['isPreviousPrepared'] = sales[x]['isPreviousPrepared']; - sale['isPrepared'] = sales[x]['isPrepared']; - sale['isControlled'] = sales[x]['isControlled']; - - let salePlacements = []; - - for (let z = 0; z < placements.length; z++) { - if (placements[z]['saleFk'] == sale['saleFk']) { - let placement = {}; - placement['saleFk'] = placements[z]['saleFk']; - placement['itemFk'] = placements[z]['itemFk']; - placement['placement'] = placements[z]['placement']; - placement['shelving'] = placements[z]['shelving']; - placement['created'] = placements[z]['created']; - placement['visible'] = placements[z]['visible']; - placement['order'] = placements[z]['order']; - placement['grouping'] = placements[z]['grouping']; - salePlacements.push(placement); - } - } - sale['placements'] = salePlacements; - ticketSales.push(sale); - } - } - ticket['sales'] = ticketSales; - collection.push(ticket); - } - - return collection; - } -}; diff --git a/back/methods/collection/spec/newCollection.spec.js b/back/methods/collection/spec/newCollection.spec.js deleted file mode 100644 index e729594d1..000000000 --- a/back/methods/collection/spec/newCollection.spec.js +++ /dev/null @@ -1,12 +0,0 @@ -const {models} = require('vn-loopback/server/server'); - -describe('newCollection()', () => { - it('should return a new collection', async() => { - pending('#3400 analizar que hacer con rutas de back collection'); - let ctx = {req: {accessToken: {userId: 1106}}}; - let response = await models.Collection.newCollection(ctx, 1, 1, 1); - - expect(response.length).toBeGreaterThan(0); - expect(response[0].ticketFk).toEqual(2); - }); -}); diff --git a/back/models/collection.js b/back/models/collection.js index bfa906af6..1c10d49fa 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -1,6 +1,5 @@ module.exports = Self => { require('../methods/collection/getCollection')(Self); - require('../methods/collection/newCollection')(Self); require('../methods/collection/getSectors')(Self); require('../methods/collection/setSaleQuantity')(Self); require('../methods/collection/previousLabel')(Self); diff --git a/db/changes/234801/00-getRoutesByWorker.sql b/db/changes/235001/00-getRoutesByWorker.sql similarity index 71% rename from db/changes/234801/00-getRoutesByWorker.sql rename to db/changes/235001/00-getRoutesByWorker.sql index bdc4a246e..00d6e658a 100644 --- a/db/changes/234801/00-getRoutesByWorker.sql +++ b/db/changes/235001/00-getRoutesByWorker.sql @@ -11,7 +11,13 @@ INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `pri ('Route', 'findOne', 'READ', 'ALLOW', 'ROLE', 'employee'), ('Route', 'getRoutesByWorker', 'READ', 'ALLOW', 'ROLE', 'employee'), ('Route', 'canViewAllRoute', 'READ', 'ALLOW', 'ROLE', 'deliveryBoss'), + ('Route', 'cmr', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'downloadCmrsZip', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'downloadZip', 'READ', 'ALLOW', 'ROLE', 'employee'), ('Route', 'filter', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'getByWorker', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'getDeliveryPoint', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'getExternalCmrs', 'READ', 'ALLOW', 'ROLE', 'employee'), ('Route', 'getSuggestedTickets', 'READ', 'ALLOW', 'ROLE', 'employee'), ('Route', 'getTickets', 'READ', 'ALLOW', 'ROLE', 'employee'), ('Route', 'guessPriority', 'WRITE', 'ALLOW', 'ROLE', 'employee'), diff --git a/modules/route/back/methods/route/getByWorker.js b/modules/route/back/methods/route/getByWorker.js index 2f8a286e6..7e70cb1f1 100644 --- a/modules/route/back/methods/route/getByWorker.js +++ b/modules/route/back/methods/route/getByWorker.js @@ -24,8 +24,7 @@ module.exports = Self => { const canViewAll = await models.ACL.checkAccessAcl(ctx, 'Route', 'canViewAllRoute', 'READ'); let filterGrant = {}; - console.log(userId); - console.log(canViewAll); + if (canViewAll) { const userConfig = await models.UserConfig.getUserConfig(ctx, myOptions); filterGrant = { diff --git a/modules/route/back/methods/route/specs/getByWorker.spec.js b/modules/route/back/methods/route/specs/getByWorker.spec.js index 52b8d6d87..f3103509a 100644 --- a/modules/route/back/methods/route/specs/getByWorker.spec.js +++ b/modules/route/back/methods/route/specs/getByWorker.spec.js @@ -1,7 +1,7 @@ const app = require('vn-loopback/server/server'); const LoopBackContext = require('loopback-context'); -fdescribe('route getByWorker()', () => { +describe('route getByWorker()', () => { const userId = 56; const activeCtx = { accessToken: {userId: userId}, @@ -22,9 +22,6 @@ fdescribe('route getByWorker()', () => { it('should return routes assigned to the worker', async() => { const result = await app.models.Route.getByWorker(ctx); - // Aquí se verifica que el resultado contiene rutas asignadas al usuario - console.log(result); - expect(result.every(route => route.workerFk === userId)).toBe(true); }); From 900dffbbba344b62662e7fa8ce388d0d9006a20e Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 23 Nov 2023 10:26:28 +0100 Subject: [PATCH 17/47] 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 18/47] 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 19/47] 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 5b145a57e6991bf07c54c4f1126834028c592cc9 Mon Sep 17 00:00:00 2001 From: jgallego Date: Thu, 23 Nov 2023 11:29:53 +0100 Subject: [PATCH 20/47] error: refs 6028 test front quitado --- modules/route/front/tickets/index.spec.js | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/modules/route/front/tickets/index.spec.js b/modules/route/front/tickets/index.spec.js index 2c73048bd..fef4b8331 100644 --- a/modules/route/front/tickets/index.spec.js +++ b/modules/route/front/tickets/index.spec.js @@ -209,22 +209,6 @@ describe('Route', () => { }); }); - describe('guessPriority()', () => { - it('should perform a GET query then call both refresh and showSuccess methods', () => { - jest.spyOn(controller.$.model, 'refresh'); - jest.spyOn(controller.vnApp, 'showSuccess'); - controller.$params = {id: 99}; - - const url = `Routes/${controller.$params.id}/guessPriority/`; - $httpBackend.expectGET(url).respond('ok'); - controller.guessPriority(); - $httpBackend.flush(); - - expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Order changed'); - expect(controller.$.model.refresh).toHaveBeenCalledWith(); - }); - }); - describe('onDrop()', () => { it('should call the insert method when dragging a ticket number', () => { jest.spyOn(controller, 'insert'); From 6b2c1e09de32381e265b4838e01e25c09442f77a Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 23 Nov 2023 11:31:00 +0100 Subject: [PATCH 21/47] refs #5835 refactor --- modules/invoiceIn/back/methods/invoice-in/getTotals.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/invoiceIn/back/methods/invoice-in/getTotals.js b/modules/invoiceIn/back/methods/invoice-in/getTotals.js index 4c45284d5..7bef9f7e9 100644 --- a/modules/invoiceIn/back/methods/invoice-in/getTotals.js +++ b/modules/invoiceIn/back/methods/invoice-in/getTotals.js @@ -32,7 +32,7 @@ module.exports = Self => { LEFT JOIN ( SELECT SUM(iit.taxableBase) totalTaxableBase, CAST( - SUM(COALESCE(iit.taxableBase * (1 + (ti.PorcentajeIva / 100)), iit.taxableBase)) + SUM(IFNULL(iit.taxableBase * (1 + (ti.PorcentajeIva / 100)), iit.taxableBase)) AS DECIMAL(10, 2) ) totalVat FROM vn.invoiceInTax iit From 4735307f5d439d25ac3d4a476a01a77399613c80 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 23 Nov 2023 11:49:00 +0100 Subject: [PATCH 22/47] refs #5890: fix(Collection/getTickets): accepts iss.quantity nulls --- back/methods/collection/getTickets.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js index cfd404beb..50117b954 100644 --- a/back/methods/collection/getTickets.js +++ b/back/methods/collection/getTickets.js @@ -49,7 +49,7 @@ module.exports = Self => { ish.packing, ish.grouping, s.isAdded, - s.originalQuantity, + s.originalQuantity, s.quantity saleQuantity, iss.quantity reservedQuantity, SUM(iss.quantity) OVER (PARTITION BY s.id ORDER BY ish.id) accumulatedQuantity, @@ -74,7 +74,7 @@ module.exports = Self => { LEFT JOIN parking p ON p.id = sh.parkingFk LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk LEFT JOIN origin o ON o.id = i.originFk - WHERE tc.collectionFk = ? AND iss.quantity IS NOT NULL + WHERE tc.collectionFk = ? GROUP BY s.id, ish.id, p.code, p2.code ORDER BY pickingOrder;`, [id], myOptions); @@ -105,7 +105,7 @@ module.exports = Self => { LEFT JOIN vn.buy c ON c.itemFk = s.itemFk LEFT JOIN vn.entry e ON e.id = c.entryFk LEFT JOIN vn.travel tr ON tr.id = e.travelFk - WHERE s.ticketFk = ? + WHERE s.ticketFk = ? AND tr.landed >= util.VN_CURDATE() - INTERVAL 1 YEAR`, [ticketId], myOptions); ticket.sales = []; From eeef279483a5adc30d3ad3e31197d1f0e0141c5f Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 23 Nov 2023 13:34:29 +0100 Subject: [PATCH 23/47] 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 24/47] 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 25/47] 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 5d18c211a0c9159a39e4f4d02c18d899f4d1b689 Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 24 Nov 2023 08:40:06 +0100 Subject: [PATCH 26/47] 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 27/47] 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 28/47] 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 29/47] 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 aefff68c2903d94f1470b11d76781635fcad1b8c Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 27 Nov 2023 09:51:56 +0100 Subject: [PATCH 30/47] 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 37555cbb63290c523e2d237d5d058890d59cb751 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 27 Nov 2023 15:10:00 +0100 Subject: [PATCH 31/47] 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 2fa56cce4b0a554b63e12bea0112e047700acbc8 Mon Sep 17 00:00:00 2001 From: jgallego Date: Tue, 28 Nov 2023 09:22:00 +0100 Subject: [PATCH 32/47] 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 33/47] 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 34/47] 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 2e22984e77de749f76d93f36821350160c3ad138 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 29 Nov 2023 09:13:54 +0100 Subject: [PATCH 35/47] 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 48b82b02cad3501d599c4ef688942de5f0ecf807 Mon Sep 17 00:00:00 2001 From: JAVIER SEGARRA MARTINEZ Date: Wed, 29 Nov 2023 19:32:10 +0000 Subject: [PATCH 36/47] 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 37/47] 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 38/47] 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 39/47] 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 40/47] 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 138d11b7b0cb72c3b0d91fa553eaf32cfba5b8de Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 30 Nov 2023 08:10:32 +0100 Subject: [PATCH 41/47] 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 42/47] 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 43/47] 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 44/47] 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 45/47] 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 46/47] 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 ab69dcd4fe5c182f71713de516ff12c40a29a792 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 30 Nov 2023 12:32:41 +0100 Subject: [PATCH 47/47] 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';