From e32a29fc093e0617ffbe8b696667b1c0d7d40dda Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Sun, 25 Jun 2023 19:08:13 +0200 Subject: [PATCH 01/19] refs #5900 Remove duplicated logs --- .../back/methods/client/confirmTransaction.js | 24 --------- modules/client/back/methods/client/sendSms.js | 27 +--------- .../back/methods/client/specs/sendSms.spec.js | 5 +- .../methods/route/specs/updateVolume.spec.js | 12 ----- .../route/back/methods/route/updateVolume.js | 15 ------ .../back/methods/ticket-request/confirm.js | 16 ------ .../back/methods/ticket/componentUpdate.js | 10 ---- modules/ticket/back/methods/ticket/merge.js | 15 +----- modules/ticket/back/methods/ticket/sendSms.js | 54 +++---------------- .../back/methods/ticket/specs/merge.spec.js | 2 - .../back/methods/ticket/specs/sendSms.spec.js | 11 ++-- .../back/methods/ticket/transferSales.js | 49 ----------------- modules/ticket/back/models/ticket.js | 26 --------- .../back/methods/travel/cloneWithEntries.js | 14 ----- .../back/methods/travel/deleteThermograph.js | 16 ------ .../updateWorkerTimeControlMail.js | 21 -------- 16 files changed, 12 insertions(+), 305 deletions(-) diff --git a/modules/client/back/methods/client/confirmTransaction.js b/modules/client/back/methods/client/confirmTransaction.js index fcb33c4ca..17c50e7db 100644 --- a/modules/client/back/methods/client/confirmTransaction.js +++ b/modules/client/back/methods/client/confirmTransaction.js @@ -19,9 +19,6 @@ module.exports = Self => { }); Self.confirmTransaction = async(ctx, id, options) => { - const models = Self.app.models; - const userId = ctx.req.accessToken.userId; - let tx; const myOptions = {userId: ctx.req.accessToken.userId}; @@ -34,29 +31,8 @@ module.exports = Self => { } try { - const oldTpvTransaction = await models.TpvTransaction.findById(id, null, myOptions); - const confirm = await Self.rawSql('CALL hedera.tpvTransaction_confirmById(?)', [id], myOptions); - - const tpvTransaction = await models.TpvTransaction.findById(id, null, myOptions); - - const oldInstance = {status: oldTpvTransaction.status}; - const newInstance = {status: tpvTransaction.status}; - - const logRecord = { - originFk: tpvTransaction.clientFk, - userFk: userId, - action: 'update', - changedModel: 'TpvTransaction', - changedModelId: id, - oldInstance: oldInstance, - newInstance: newInstance - }; - - await models.ClientLog.create(logRecord, myOptions); - if (tx) await tx.commit(); - return confirm; } catch (e) { if (tx) await tx.rollback(); diff --git a/modules/client/back/methods/client/sendSms.js b/modules/client/back/methods/client/sendSms.js index 9d6a12416..83b7c8d6e 100644 --- a/modules/client/back/methods/client/sendSms.js +++ b/modules/client/back/methods/client/sendSms.js @@ -30,34 +30,9 @@ module.exports = Self => { } }); - Self.sendSms = async(ctx, id, destination, message, options) => { + Self.sendSms = async(ctx, id, destination, message) => { const models = Self.app.models; - const myOptions = {}; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - const userId = ctx.req.accessToken.userId; - const sms = await models.Sms.send(ctx, destination, message); - const logRecord = { - originFk: id, - userFk: userId, - action: 'insert', - changedModel: 'sms', - newInstance: { - destinationFk: id, - destination: destination, - message: message, - statusCode: sms.statusCode, - status: sms.status - } - }; - - const clientLog = await models.ClientLog.create(logRecord, myOptions); - - sms.logId = clientLog.id; - return sms; }; }; diff --git a/modules/client/back/methods/client/specs/sendSms.spec.js b/modules/client/back/methods/client/specs/sendSms.spec.js index 47e788184..df680c55f 100644 --- a/modules/client/back/methods/client/specs/sendSms.spec.js +++ b/modules/client/back/methods/client/specs/sendSms.spec.js @@ -13,10 +13,7 @@ describe('client sendSms()', () => { const sms = await models.Client.sendSms(ctx, id, destination, message, options); - const createdLog = await models.ClientLog.findById(sms.logId, null, options); - const json = JSON.parse(JSON.stringify(createdLog.newInstance)); - - expect(json.message).toEqual(message); + expect(sms).toBeDefined(); await tx.rollback(); } catch (e) { diff --git a/modules/route/back/methods/route/specs/updateVolume.spec.js b/modules/route/back/methods/route/specs/updateVolume.spec.js index fdcc1a6ec..a28dc4627 100644 --- a/modules/route/back/methods/route/specs/updateVolume.spec.js +++ b/modules/route/back/methods/route/specs/updateVolume.spec.js @@ -31,18 +31,6 @@ describe('route updateVolume()', () => { const updatedRoute = await app.models.Route.findById(routeId, null, options); expect(updatedRoute.m3).not.toEqual(route.m3); - - const logs = await app.models.RouteLog.find({ - fields: ['id', 'newInstance'] - }, options); - - const m3Log = logs.filter(log => { - if (log.newInstance) - return log.newInstance.m3 === updatedRoute.m3; - }); - - expect(m3Log.length).toEqual(1); - await tx.rollback(); } catch (e) { await tx.rollback(); diff --git a/modules/route/back/methods/route/updateVolume.js b/modules/route/back/methods/route/updateVolume.js index cdced3882..388364cff 100644 --- a/modules/route/back/methods/route/updateVolume.js +++ b/modules/route/back/methods/route/updateVolume.js @@ -35,24 +35,9 @@ module.exports = Self => { } try { - const originalRoute = await models.Route.findById(id, null, myOptions); - await Self.rawSql(`CALL vn.routeUpdateM3(?)`, [id], myOptions); - const updatedRoute = await models.Route.findById(id, null, myOptions); - - await models.RouteLog.create({ - originFk: id, - userFk: userId, - action: 'update', - changedModel: 'Route', - changedModelId: id, - oldInstance: {m3: originalRoute.m3}, - newInstance: {m3: updatedRoute.m3} - }, myOptions); - if (tx) await tx.commit(); - return updatedRoute; } catch (e) { if (tx) await tx.rollback(); diff --git a/modules/ticket/back/methods/ticket-request/confirm.js b/modules/ticket/back/methods/ticket-request/confirm.js index 2061ca355..9cd7f4d68 100644 --- a/modules/ticket/back/methods/ticket-request/confirm.js +++ b/modules/ticket/back/methods/ticket-request/confirm.js @@ -97,22 +97,6 @@ module.exports = Self => { }); await models.Chat.sendCheckingPresence(ctx, requesterId, message, myOptions); - const logRecord = { - originFk: sale.ticketFk, - userFk: userId, - action: 'update', - changedModel: 'ticketRequest', - newInstance: { - destinationFk: sale.ticketFk, - quantity: sale.quantity, - concept: sale.concept, - itemId: sale.itemFk, - ticketId: sale.ticketFk, - } - }; - - await Self.app.models.TicketLog.create(logRecord, myOptions); - if (tx) await tx.commit(); return sale; diff --git a/modules/ticket/back/methods/ticket/componentUpdate.js b/modules/ticket/back/methods/ticket/componentUpdate.js index a8b631d7c..48aee36d4 100644 --- a/modules/ticket/back/methods/ticket/componentUpdate.js +++ b/modules/ticket/back/methods/ticket/componentUpdate.js @@ -242,16 +242,6 @@ module.exports = Self => { const oldProperties = await loggable.translateValues(Self, changes.old); const newProperties = await loggable.translateValues(Self, changes.new); - await models.TicketLog.create({ - originFk: args.id, - userFk: userId, - action: 'update', - changedModel: 'Ticket', - changedModelId: args.id, - oldInstance: oldProperties, - newInstance: newProperties - }, myOptions); - const salesPersonId = originalTicket.client().salesPersonFk; if (salesPersonId) { const origin = ctx.req.headers.origin; diff --git a/modules/ticket/back/methods/ticket/merge.js b/modules/ticket/back/methods/ticket/merge.js index 9a6f859f7..3c0da077f 100644 --- a/modules/ticket/back/methods/ticket/merge.js +++ b/modules/ticket/back/methods/ticket/merge.js @@ -52,22 +52,9 @@ module.exports = Self => { }); if (!ticket.originId || !ticket.destinationId) continue; - const ticketDestinationLogRecord = { - originFk: ticket.destinationId, - userFk: ctx.req.accessToken.userId, - action: 'update', - changedModel: 'Ticket', - changedModelId: ticket.destinationId, - changedModelValue: ticket.destinationId, - oldInstance: {}, - newInstance: {mergedTicket: ticket.originId} - }; - await models.Sale.updateAll({ticketFk: ticket.originId}, {ticketFk: ticket.destinationId}, myOptions); - if (await models.Ticket.setDeleted(ctx, ticket.originId, myOptions)) { - await models.TicketLog.create(ticketDestinationLogRecord, myOptions); + if (await models.Ticket.setDeleted(ctx, ticket.originId, myOptions)) await models.Chat.sendCheckingPresence(ctx, ticket.workerFk, message); - } } if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/ticket/sendSms.js b/modules/ticket/back/methods/ticket/sendSms.js index 2336ae859..ffc95c6b4 100644 --- a/modules/ticket/back/methods/ticket/sendSms.js +++ b/modules/ticket/back/methods/ticket/sendSms.js @@ -30,54 +30,12 @@ module.exports = Self => { } }); - Self.sendSms = async(ctx, id, destination, message, options) => { + Self.sendSms = async(ctx, id, destination, message) => { const models = Self.app.models; - const myOptions = {}; - let tx; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } - - const userId = ctx.req.accessToken.userId; - - try { - const sms = await models.Sms.send(ctx, destination, message); - - const newTicketSms = { - ticketFk: id, - smsFk: sms.id - }; - await models.TicketSms.create(newTicketSms); - - const logRecord = { - originFk: id, - userFk: userId, - action: 'insert', - changedModel: 'sms', - newInstance: { - destinationFk: id, - destination: destination, - message: message, - statusCode: sms.statusCode, - status: sms.status - } - }; - - const ticketLog = await models.TicketLog.create(logRecord, myOptions); - - sms.logId = ticketLog.id; - - if (tx) await tx.commit(); - - return sms; - } catch (e) { - if (tx) await tx.rollback(); - throw e; - } + const sms = await models.Sms.send(ctx, destination, message); + await models.TicketSms.create({ + ticketFk: id, + smsFk: sms.id + }); }; }; diff --git a/modules/ticket/back/methods/ticket/specs/merge.spec.js b/modules/ticket/back/methods/ticket/specs/merge.spec.js index 3254e58a8..3be6b8bac 100644 --- a/modules/ticket/back/methods/ticket/specs/merge.spec.js +++ b/modules/ticket/back/methods/ticket/specs/merge.spec.js @@ -43,12 +43,10 @@ describe('ticket merge()', () => { await models.Ticket.merge(ctx, [tickets], options); - const createdTicketLog = await models.TicketLog.find({where: {originFk: tickets.destinationId}}, options); const deletedTicket = await models.Ticket.findOne({where: {id: tickets.originId}}, options); const salesTicketFuture = await models.Sale.find({where: {ticketFk: tickets.destinationId}}, options); const chatNotificationAfterMerge = await models.Chat.find(null, options); - expect(createdTicketLog.length).toEqual(1); expect(deletedTicket.isDeleted).toEqual(true); expect(salesTicketFuture.length).toEqual(2); expect(chatNotificationBeforeMerge.length).toEqual(chatNotificationAfterMerge.length - 2); diff --git a/modules/ticket/back/methods/ticket/specs/sendSms.spec.js b/modules/ticket/back/methods/ticket/specs/sendSms.spec.js index f94b8be2a..3f93198d1 100644 --- a/modules/ticket/back/methods/ticket/specs/sendSms.spec.js +++ b/modules/ticket/back/methods/ticket/specs/sendSms.spec.js @@ -12,19 +12,14 @@ describe('ticket sendSms()', () => { const destination = 222222222; const message = 'this is the message created in a test'; - const sms = await models.Ticket.sendSms(ctx, id, destination, message, options); - - const createdLog = await models.TicketLog.findById(sms.logId, null, options); + await models.Ticket.sendSms(ctx, id, destination, message, options); const filter = { - ticketFk: createdLog.originFk + ticketFk: id }; const ticketSms = await models.TicketSms.findOne(filter, options); - const json = JSON.parse(JSON.stringify(createdLog.newInstance)); - - expect(json.message).toEqual(message); - expect(ticketSms.ticketFk).toEqual(createdLog.originFk); + expect(ticketSms.ticketFk).toEqual(id); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/ticket/transferSales.js b/modules/ticket/back/methods/ticket/transferSales.js index 01ada49d0..0eee50d5f 100644 --- a/modules/ticket/back/methods/ticket/transferSales.js +++ b/modules/ticket/back/methods/ticket/transferSales.js @@ -84,13 +84,6 @@ module.exports = Self => { for (const sale of sales) { const originalSale = map.get(sale.id); - const originalSaleData = { // <-- Loopback modifies original instance on save - itemFk: originalSale.itemFk, - quantity: originalSale.quantity, - concept: originalSale.concept, - ticketFk: originalSale.ticketFk - }; - if (sale.quantity == originalSale.quantity) { query = `UPDATE sale SET ticketFk = ? @@ -100,48 +93,6 @@ module.exports = Self => { await transferPartialSale( ticketId, originalSale, sale, myOptions); } - - // Log to original ticket - await models.TicketLog.create({ - originFk: id, - userFk: userId, - action: 'update', - changedModel: 'Sale', - changedModelId: sale.id, - oldInstance: { - item: originalSaleData.itemFk, - quantity: originalSaleData.quantity, - concept: originalSaleData.concept, - ticket: originalSaleData.ticketFk - }, - newInstance: { - item: sale.itemFk, - quantity: sale.quantity, - concept: sale.concept, - ticket: ticketId - } - }, myOptions); - - // Log to destination ticket - await models.TicketLog.create({ - originFk: ticketId, - userFk: userId, - action: 'update', - changedModel: 'Sale', - changedModelId: sale.id, - oldInstance: { - item: originalSaleData.itemFk, - quantity: originalSaleData.quantity, - concept: originalSaleData.concept, - ticket: originalSaleData.ticketFk - }, - newInstance: { - item: sale.itemFk, - quantity: sale.quantity, - concept: sale.concept, - ticket: ticketId - } - }, myOptions); } const isTicketEmpty = await models.Ticket.isEmpty(id, myOptions); diff --git a/modules/ticket/back/models/ticket.js b/modules/ticket/back/models/ticket.js index c05130552..ea068ef8a 100644 --- a/modules/ticket/back/models/ticket.js +++ b/modules/ticket/back/models/ticket.js @@ -1,30 +1,4 @@ - -const LoopBackContext = require('loopback-context'); - module.exports = Self => { // Methods require('./ticket-methods')(Self); - - Self.observe('before save', async function(ctx) { - const loopBackContext = LoopBackContext.getCurrentContext(); - const httpCtx = loopBackContext.active; - - if (ctx.isNewInstance) return; - - let changes = ctx.data || ctx.instance; - - if (changes.routeFk === null && ctx.currentInstance.routeFk != null) { - let instance = JSON.parse(JSON.stringify(ctx.currentInstance)); - let userId = httpCtx.accessToken.userId; - let logRecord = { - originFk: ctx.currentInstance.routeFk, - userFk: userId, - action: 'delete', - changedModel: 'Route', - oldInstance: {ticket: instance.id}, - newInstance: null - }; - await Self.app.models.RouteLog.create(logRecord); - } - }); }; diff --git a/modules/travel/back/methods/travel/cloneWithEntries.js b/modules/travel/back/methods/travel/cloneWithEntries.js index e5b6b1580..45ebef283 100644 --- a/modules/travel/back/methods/travel/cloneWithEntries.js +++ b/modules/travel/back/methods/travel/cloneWithEntries.js @@ -25,9 +25,7 @@ module.exports = Self => { }); Self.cloneWithEntries = async(ctx, id) => { - const userId = ctx.req.accessToken.userId; const conn = Self.dataSource.connector; - const models = Self.app.models; const travel = await Self.findById(id, { fields: [ 'id', @@ -81,18 +79,6 @@ module.exports = Self => { ] }); - const oldProperties = await loggable.translateValues(Self, travel); - const newProperties = await loggable.translateValues(Self, newTravel); - await models.TravelLog.create({ - originFk: newTravel.id, - userFk: userId, - action: 'insert', - changedModel: 'Travel', - changedModelId: newTravel.id, - oldInstance: oldProperties, - newInstance: newProperties - }); - return newTravel.id; }; }; diff --git a/modules/travel/back/methods/travel/deleteThermograph.js b/modules/travel/back/methods/travel/deleteThermograph.js index d22fc8b29..254dc45aa 100644 --- a/modules/travel/back/methods/travel/deleteThermograph.js +++ b/modules/travel/back/methods/travel/deleteThermograph.js @@ -30,24 +30,8 @@ module.exports = Self => { SET travelFk = NULL, dmsFk = NULL WHERE id = ?`, [id], {userId}); - const oldInstance = { - travelFk: travelThermograph.travelFk, - dmsFk: travelThermograph.dmsFk - }; - - await models.TravelLog.create({ - originFk: travelThermograph.travelFk, - userFk: userId, - action: 'delete', - changedModel: 'TravelThermograph', - changedModelId: id, - oldInstance: oldInstance, - newInstance: {} - }); - travelThermograph.travelFk = null; travelThermograph.dmsFk = null; - return travelThermograph; }; }; diff --git a/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js b/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js index 6f794511f..6fe30de91 100644 --- a/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js +++ b/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js @@ -40,7 +40,6 @@ module.exports = Self => { Self.updateWorkerTimeControlMail = async(ctx, options) => { const models = Self.app.models; const args = ctx.args; - const userId = ctx.req.accessToken.userId; const myOptions = {}; @@ -57,9 +56,6 @@ module.exports = Self => { if (!workerTimeControlMail) throw new UserError(`There aren't records for this week`); - const oldState = workerTimeControlMail.state; - const oldReason = workerTimeControlMail.reason; - await workerTimeControlMail.updateAttributes({ state: args.state, reason: args.reason || null @@ -70,22 +66,5 @@ module.exports = Self => { sendedCounter: workerTimeControlMail.sendedCounter + 1 }, myOptions); } - - const logRecord = { - originFk: args.workerId, - userFk: userId, - action: 'update', - changedModel: 'WorkerTimeControlMail', - oldInstance: { - state: oldState, - reason: oldReason - }, - newInstance: { - state: args.state, - reason: args.reason - } - }; - - return models.WorkerLog.create(logRecord, myOptions); }; }; From cc5021a75f093eb830611d448f3adae4f2264036 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 26 Jun 2023 09:40:55 +0200 Subject: [PATCH 02/19] refs #5684 Removed xxxLog.create and dependences --- loopback/locale/es.json | 1 - .../back/methods/claim/claimPickupEmail.js | 8 ---- .../back/methods/client/confirmTransaction.js | 21 ---------- .../back/methods/client/updateFiscalData.js | 13 ------ modules/client/back/models/client.js | 15 ------- .../route/back/methods/route/guessPriority.js | 11 ----- .../route/back/methods/route/updateVolume.js | 15 +------ .../back/methods/ticket/componentUpdate.js | 10 ----- modules/ticket/back/methods/ticket/merge.js | 15 +------ .../back/methods/ticket/transferSales.js | 42 ------------------- .../back/methods/travel/cloneWithEntries.js | 12 ------ .../back/methods/travel/deleteThermograph.js | 15 ------- 12 files changed, 2 insertions(+), 176 deletions(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 138fa7100..ed036331f 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -177,7 +177,6 @@ "You can not select this payment method without a registered bankery account": "No se puede utilizar este método de pago si no has registrado una cuenta bancaria", "Action not allowed on the test environment": "Esta acción no está permitida en el entorno de pruebas", "The selected ticket is not suitable for this route": "El ticket seleccionado no es apto para esta ruta", - "Sorts whole route": "Reordena ruta entera", "New ticket request has been created with price": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}* y un precio de *{{price}} €*", "New ticket request has been created": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}*", "Swift / BIC cannot be empty": "Swift / BIC no puede estar vacío", diff --git a/modules/claim/back/methods/claim/claimPickupEmail.js b/modules/claim/back/methods/claim/claimPickupEmail.js index c688d6ded..1fd8eb99e 100644 --- a/modules/claim/back/methods/claim/claimPickupEmail.js +++ b/modules/claim/back/methods/claim/claimPickupEmail.js @@ -77,14 +77,6 @@ module.exports = Self => { if (salesPersonId) await models.Chat.sendCheckingPresence(ctx, salesPersonId, message); - await models.ClaimLog.create({ - originFk: args.id, - userFk: userId, - action: 'insert', - description: 'Claim-pickup-order sent', - changedModel: 'Mail' - }); - const email = new Email('claim-pickup-order', params); return email.send(); diff --git a/modules/client/back/methods/client/confirmTransaction.js b/modules/client/back/methods/client/confirmTransaction.js index fcb33c4ca..c694326a4 100644 --- a/modules/client/back/methods/client/confirmTransaction.js +++ b/modules/client/back/methods/client/confirmTransaction.js @@ -34,29 +34,8 @@ module.exports = Self => { } try { - const oldTpvTransaction = await models.TpvTransaction.findById(id, null, myOptions); - const confirm = await Self.rawSql('CALL hedera.tpvTransaction_confirmById(?)', [id], myOptions); - - const tpvTransaction = await models.TpvTransaction.findById(id, null, myOptions); - - const oldInstance = {status: oldTpvTransaction.status}; - const newInstance = {status: tpvTransaction.status}; - - const logRecord = { - originFk: tpvTransaction.clientFk, - userFk: userId, - action: 'update', - changedModel: 'TpvTransaction', - changedModelId: id, - oldInstance: oldInstance, - newInstance: newInstance - }; - - await models.ClientLog.create(logRecord, myOptions); - if (tx) await tx.commit(); - return confirm; } catch (e) { if (tx) await tx.rollback(); diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js index 697c567a3..5fd886c32 100644 --- a/modules/client/back/methods/client/updateFiscalData.js +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -144,20 +144,7 @@ module.exports = Self => { if (taxDataChecked && !hasSageData) throw new UserError(`You need to fill sage information before you check verified data`); - if (args.despiteOfClient) { - const logRecord = { - originFk: clientId, - userFk: userId, - action: 'update', - changedModel: 'Client', - changedModelId: clientId, - description: $t(`Client checked as validated despite of duplication`, { - clientId: args.despiteOfClient - }) - }; - await models.ClientLog.create(logRecord, myOptions); - } // Remove unwanted properties delete args.ctx; delete args.id; diff --git a/modules/client/back/models/client.js b/modules/client/back/models/client.js index 7b577fa98..51157e15d 100644 --- a/modules/client/back/models/client.js +++ b/modules/client/back/models/client.js @@ -479,21 +479,6 @@ module.exports = Self => { hasChanges = oldData.name != changes.name || oldData.active != changes.active; if (!hasChanges) return; - - const isClient = await Self.app.models.Client.count({id: oldData.id}); - if (isClient) { - const loopBackContext = LoopBackContext.getCurrentContext(); - const userId = loopBackContext.active.accessToken.userId; - const logRecord = { - originFk: oldData.id, - userFk: userId, - action: 'update', - changedModel: 'VnUser', - oldInstance: {name: oldData.name, active: oldData.active}, - newInstance: {name: changes.name, active: changes.active} - }; - await Self.app.models.ClientLog.create(logRecord); - } } }); }); diff --git a/modules/route/back/methods/route/guessPriority.js b/modules/route/back/methods/route/guessPriority.js index 67b68aa89..c6b2a9b74 100644 --- a/modules/route/back/methods/route/guessPriority.js +++ b/modules/route/back/methods/route/guessPriority.js @@ -21,7 +21,6 @@ module.exports = Self => { Self.guessPriority = async(ctx, id) => { const userId = ctx.req.accessToken.userId; - const $t = ctx.req.__; // $translate const query = `CALL vn.routeGuessPriority(?)`; const tx = await Self.beginTransaction({}); @@ -30,16 +29,6 @@ module.exports = Self => { const priority = await Self.rawSql(query, [id], options); - let logRecord = { - originFk: id, - userFk: userId, - action: 'update', - changedModel: 'Route', - description: $t('Sorts whole route') - }; - - await Self.app.models.RouteLog.create(logRecord, options); - await tx.commit(); return priority; } catch (e) { diff --git a/modules/route/back/methods/route/updateVolume.js b/modules/route/back/methods/route/updateVolume.js index cdced3882..7884dc953 100644 --- a/modules/route/back/methods/route/updateVolume.js +++ b/modules/route/back/methods/route/updateVolume.js @@ -35,24 +35,11 @@ module.exports = Self => { } try { - const originalRoute = await models.Route.findById(id, null, myOptions); - await Self.rawSql(`CALL vn.routeUpdateM3(?)`, [id], myOptions); const updatedRoute = await models.Route.findById(id, null, myOptions); - - await models.RouteLog.create({ - originFk: id, - userFk: userId, - action: 'update', - changedModel: 'Route', - changedModelId: id, - oldInstance: {m3: originalRoute.m3}, - newInstance: {m3: updatedRoute.m3} - }, myOptions); - + if (tx) await tx.commit(); - return updatedRoute; } catch (e) { if (tx) await tx.rollback(); diff --git a/modules/ticket/back/methods/ticket/componentUpdate.js b/modules/ticket/back/methods/ticket/componentUpdate.js index a8b631d7c..48aee36d4 100644 --- a/modules/ticket/back/methods/ticket/componentUpdate.js +++ b/modules/ticket/back/methods/ticket/componentUpdate.js @@ -242,16 +242,6 @@ module.exports = Self => { const oldProperties = await loggable.translateValues(Self, changes.old); const newProperties = await loggable.translateValues(Self, changes.new); - await models.TicketLog.create({ - originFk: args.id, - userFk: userId, - action: 'update', - changedModel: 'Ticket', - changedModelId: args.id, - oldInstance: oldProperties, - newInstance: newProperties - }, myOptions); - const salesPersonId = originalTicket.client().salesPersonFk; if (salesPersonId) { const origin = ctx.req.headers.origin; diff --git a/modules/ticket/back/methods/ticket/merge.js b/modules/ticket/back/methods/ticket/merge.js index 9a6f859f7..3c0da077f 100644 --- a/modules/ticket/back/methods/ticket/merge.js +++ b/modules/ticket/back/methods/ticket/merge.js @@ -52,22 +52,9 @@ module.exports = Self => { }); if (!ticket.originId || !ticket.destinationId) continue; - const ticketDestinationLogRecord = { - originFk: ticket.destinationId, - userFk: ctx.req.accessToken.userId, - action: 'update', - changedModel: 'Ticket', - changedModelId: ticket.destinationId, - changedModelValue: ticket.destinationId, - oldInstance: {}, - newInstance: {mergedTicket: ticket.originId} - }; - await models.Sale.updateAll({ticketFk: ticket.originId}, {ticketFk: ticket.destinationId}, myOptions); - if (await models.Ticket.setDeleted(ctx, ticket.originId, myOptions)) { - await models.TicketLog.create(ticketDestinationLogRecord, myOptions); + if (await models.Ticket.setDeleted(ctx, ticket.originId, myOptions)) await models.Chat.sendCheckingPresence(ctx, ticket.workerFk, message); - } } if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/ticket/transferSales.js b/modules/ticket/back/methods/ticket/transferSales.js index 01ada49d0..6fb9b4678 100644 --- a/modules/ticket/back/methods/ticket/transferSales.js +++ b/modules/ticket/back/methods/ticket/transferSales.js @@ -100,48 +100,6 @@ module.exports = Self => { await transferPartialSale( ticketId, originalSale, sale, myOptions); } - - // Log to original ticket - await models.TicketLog.create({ - originFk: id, - userFk: userId, - action: 'update', - changedModel: 'Sale', - changedModelId: sale.id, - oldInstance: { - item: originalSaleData.itemFk, - quantity: originalSaleData.quantity, - concept: originalSaleData.concept, - ticket: originalSaleData.ticketFk - }, - newInstance: { - item: sale.itemFk, - quantity: sale.quantity, - concept: sale.concept, - ticket: ticketId - } - }, myOptions); - - // Log to destination ticket - await models.TicketLog.create({ - originFk: ticketId, - userFk: userId, - action: 'update', - changedModel: 'Sale', - changedModelId: sale.id, - oldInstance: { - item: originalSaleData.itemFk, - quantity: originalSaleData.quantity, - concept: originalSaleData.concept, - ticket: originalSaleData.ticketFk - }, - newInstance: { - item: sale.itemFk, - quantity: sale.quantity, - concept: sale.concept, - ticket: ticketId - } - }, myOptions); } const isTicketEmpty = await models.Ticket.isEmpty(id, myOptions); diff --git a/modules/travel/back/methods/travel/cloneWithEntries.js b/modules/travel/back/methods/travel/cloneWithEntries.js index e5b6b1580..1337d35e5 100644 --- a/modules/travel/back/methods/travel/cloneWithEntries.js +++ b/modules/travel/back/methods/travel/cloneWithEntries.js @@ -81,18 +81,6 @@ module.exports = Self => { ] }); - const oldProperties = await loggable.translateValues(Self, travel); - const newProperties = await loggable.translateValues(Self, newTravel); - await models.TravelLog.create({ - originFk: newTravel.id, - userFk: userId, - action: 'insert', - changedModel: 'Travel', - changedModelId: newTravel.id, - oldInstance: oldProperties, - newInstance: newProperties - }); - return newTravel.id; }; }; diff --git a/modules/travel/back/methods/travel/deleteThermograph.js b/modules/travel/back/methods/travel/deleteThermograph.js index d22fc8b29..39f748eef 100644 --- a/modules/travel/back/methods/travel/deleteThermograph.js +++ b/modules/travel/back/methods/travel/deleteThermograph.js @@ -30,21 +30,6 @@ module.exports = Self => { SET travelFk = NULL, dmsFk = NULL WHERE id = ?`, [id], {userId}); - const oldInstance = { - travelFk: travelThermograph.travelFk, - dmsFk: travelThermograph.dmsFk - }; - - await models.TravelLog.create({ - originFk: travelThermograph.travelFk, - userFk: userId, - action: 'delete', - changedModel: 'TravelThermograph', - changedModelId: id, - oldInstance: oldInstance, - newInstance: {} - }); - travelThermograph.travelFk = null; travelThermograph.dmsFk = null; From 88e845b511c860b86131da6616ea8bb78b05c41b Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 26 Jun 2023 10:49:09 +0200 Subject: [PATCH 03/19] change applyFilters --- modules/travel/front/search-panel/index.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/modules/travel/front/search-panel/index.js b/modules/travel/front/search-panel/index.js index 9cf417da1..089953127 100644 --- a/modules/travel/front/search-panel/index.js +++ b/modules/travel/front/search-panel/index.js @@ -37,6 +37,16 @@ class Controller extends SearchPanel { } applyFilters(param) { + if (typeof this.filter.scopeDays === 'number') { + const shippedFrom = Date.vnNew(); + shippedFrom.setHours(0, 0, 0, 0); + + const shippedTo = new Date(shippedFrom.getTime()); + shippedTo.setDate(shippedTo.getDate() + this.filter.scopeDays); + shippedTo.setHours(23, 59, 59, 999); + Object.assign(this.filter, {shippedFrom, shippedTo}); + } + this.model.applyFilter({}, this.filter) .then(() => { if (param && this.model._orgData.length === 1) From de62dd9ffdd7be7c13305b6f6df7562a2b7d476e Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 26 Jun 2023 12:32:08 +0200 Subject: [PATCH 04/19] refs # e2e fix --- e2e/paths/10-travel/03_descriptor.spec.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/e2e/paths/10-travel/03_descriptor.spec.js b/e2e/paths/10-travel/03_descriptor.spec.js index 3752400c6..4723cc4a3 100644 --- a/e2e/paths/10-travel/03_descriptor.spec.js +++ b/e2e/paths/10-travel/03_descriptor.spec.js @@ -9,7 +9,7 @@ describe('Travel descriptor path', () => { browser = await getBrowser(); page = browser.page; await page.loginAndModule('buyer', 'travel'); - await page.write(selectors.travelIndex.generalSearchFilter, '1'); + await page.write(selectors.travelIndex.generalSearchFilter, '3'); await page.keyboard.press('Enter'); await page.waitForState('travel.card.summary'); }); @@ -23,7 +23,7 @@ describe('Travel descriptor path', () => { await page.waitForState('travel.index'); const result = await page.countElement(selectors.travelIndex.anySearchResult); - expect(result).toBeGreaterThanOrEqual(7); + expect(result).toBeGreaterThanOrEqual(1); }); it('should navigate to the first search result', async() => { From 46ffd8d95af931bd0d5d2e42bacaaad192db4a25 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 27 Jun 2023 08:07:54 +0200 Subject: [PATCH 05/19] refs #5554 console.log --- back/methods/vn-user/renew-token.js | 2 ++ front/salix/components/layout/index.js | 1 + 2 files changed, 3 insertions(+) diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index 41470dfea..fb99992bf 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -27,6 +27,8 @@ module.exports = Self => { const accessTokenConfig = await models.AccessTokenConfig.findOne({fields: ['renewPeriod']}); + console.log(userId, created, now, differenceMilliseconds, differenceSeconds, accessTokenConfig.renewPeriod, differenceSeconds <= accessTokenConfig.renewPeriod); + if (differenceSeconds <= accessTokenConfig.renewPeriod) throw new UserError(`The renew period has not been exceeded`); diff --git a/front/salix/components/layout/index.js b/front/salix/components/layout/index.js index dc2313f4f..008d31ab2 100644 --- a/front/salix/components/layout/index.js +++ b/front/salix/components/layout/index.js @@ -49,6 +49,7 @@ export class Layout extends Component { const differenceMilliseconds = now - new Date(this.vnToken.created); const differenceSeconds = Math.floor(differenceMilliseconds / 1000); + console.log(this.vnToken.created, now, differenceMilliseconds, differenceSeconds, this.renewPeriod, differenceSeconds > this.renewPeriod); if (differenceSeconds > this.renewPeriod) { this.$http.post('VnUsers/renewToken') .then(json => { From 1cf5ff9a62114f3c3d269b867c13faa37a6a1d23 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 27 Jun 2023 08:24:31 +0200 Subject: [PATCH 06/19] refs #5554 new Date() --- back/methods/vn-user/renew-token.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index fb99992bf..ee50d06d4 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -22,7 +22,7 @@ module.exports = Self => { const tokenId = ctx.req.accessToken.id; const now = new Date(); - const differenceMilliseconds = now - created; + const differenceMilliseconds = now - new Date(created); const differenceSeconds = Math.floor(differenceMilliseconds / 1000); const accessTokenConfig = await models.AccessTokenConfig.findOne({fields: ['renewPeriod']}); From 8e5a6dbab3087b1e8028dee180d3a5712cb43318 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 27 Jun 2023 11:44:23 +0200 Subject: [PATCH 07/19] fix warn --- modules/travel/front/summary/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/travel/front/summary/index.html b/modules/travel/front/summary/index.html index 5d38ed08f..d9dbb0f90 100644 --- a/modules/travel/front/summary/index.html +++ b/modules/travel/front/summary/index.html @@ -92,7 +92,7 @@ {{entry.supplierName}} - {{entry.ref}} + {{entry.reference}} {{entry.hb}} {{entry.freightValue | currency: 'EUR': 2}} {{entry.packageValue | currency: 'EUR': 2}} From f8a972c2f2219a2dcb1aaa8aa84170981253aa0e Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 27 Jun 2023 14:48:22 +0200 Subject: [PATCH 08/19] refs #5094 fix translation --- modules/ticket/front/index/index.html | 2 +- modules/ticket/front/index/locale/es.yml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/ticket/front/index/index.html b/modules/ticket/front/index/index.html index d6e230ebe..59b8e8953 100644 --- a/modules/ticket/front/index/index.html +++ b/modules/ticket/front/index/index.html @@ -156,7 +156,7 @@ icon="install_mobile" ng-show="$ctrl.totalChecked > 0" ng-click="$ctrl.sendDocuware()" - vn-tooltip="Set as delivered and open delivery note(s)" + vn-tooltip="Set as delivered and send delivery note(s) to the tablet" tooltip-position="left"> Date: Wed, 28 Jun 2023 09:09:36 +0200 Subject: [PATCH 09/19] refs #5900 User avatar with sticky position --- front/salix/components/log/index.html | 4 +++- front/salix/components/log/index.js | 10 +++++----- front/salix/components/log/style.scss | 22 ++++++++++++++++------ 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/front/salix/components/log/index.html b/front/salix/components/log/index.html index 16342783d..6a1367e28 100644 --- a/front/salix/components/log/index.html +++ b/front/salix/components/log/index.html @@ -24,7 +24,8 @@
- + @@ -33,6 +34,7 @@ ng-src="/api/Images/user/160x160/{{::userLog.userFk}}/download?access_token={{::$ctrl.vnToken.token}}"> +
diff --git a/front/salix/components/log/index.js b/front/salix/components/log/index.js index 3df367cae..176815eef 100644 --- a/front/salix/components/log/index.js +++ b/front/salix/components/log/index.js @@ -115,23 +115,21 @@ export default class Controller extends Section { // User const userChanged = originChanged - || log.userFk != prevLog.userFk - || nLogs >= 5; + || log.userFk != prevLog.userFk; if (userChanged) { originLog.logs.push(userLog = { user: log.user, userFk: log.userFk, logs: [] }); - nLogs = 0; } - nLogs++; // Model const modelChanged = userChanged || log.changedModel != prevLog.changedModel - || log.changedModelId != prevLog.changedModelId; + || log.changedModelId != prevLog.changedModelId + || nLogs >= 6; if (modelChanged) { userLog.logs.push(modelLog = { model: log.changedModel, @@ -140,7 +138,9 @@ export default class Controller extends Section { showValue: log.changedModelValue, logs: [] }); + nLogs = 0; } + nLogs++; modelLog.logs.push(log); diff --git a/front/salix/components/log/style.scss b/front/salix/components/log/style.scss index d729d09a3..1da55332e 100644 --- a/front/salix/components/log/style.scss +++ b/front/salix/components/log/style.scss @@ -44,11 +44,21 @@ vn-log { right: -4px; z-index: 1; } - & > vn-avatar { - cursor: pointer; + & > .user-avatar { + background-color: $color-bg; + padding: $spacing-sm 0; + margin-top: -$spacing-sm; + position: relative; // Compatibility with old browsers + position: sticky; + top: 72px; - &.system { - background-color: $color-main !important; + & > vn-avatar { + cursor: pointer; + display: block; + + &.system { + background-color: $color-main !important; + } } } & > .line { @@ -57,8 +67,8 @@ vn-log { width: 2px; left: 18px; z-index: -1; - top: 44px; - bottom: -2px; + top: 0; + bottom: -$spacing-sm; } } &:last-child > .timeline > .line { From 12481b5f3d61447d3da0464b5583779ac94e8155 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Wed, 28 Jun 2023 16:07:24 +0200 Subject: [PATCH 10/19] refs #5900 CSS fix --- front/salix/components/log/style.scss | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/front/salix/components/log/style.scss b/front/salix/components/log/style.scss index 1da55332e..07e3dc5b7 100644 --- a/front/salix/components/log/style.scss +++ b/front/salix/components/log/style.scss @@ -50,7 +50,7 @@ vn-log { margin-top: -$spacing-sm; position: relative; // Compatibility with old browsers position: sticky; - top: 72px; + top: 64px; & > vn-avatar { cursor: pointer; From d200a1a6950a9a458afcb46a19c78d3972ab14b9 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Wed, 28 Jun 2023 16:08:12 +0200 Subject: [PATCH 11/19] refs #5900 CSS fixes --- front/salix/components/log/style.scss | 1 - 1 file changed, 1 deletion(-) diff --git a/front/salix/components/log/style.scss b/front/salix/components/log/style.scss index 07e3dc5b7..09a762db3 100644 --- a/front/salix/components/log/style.scss +++ b/front/salix/components/log/style.scss @@ -48,7 +48,6 @@ vn-log { background-color: $color-bg; padding: $spacing-sm 0; margin-top: -$spacing-sm; - position: relative; // Compatibility with old browsers position: sticky; top: 64px; From 840a88bdc10860cf3354469178b16e7f1abacbaa Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 29 Jun 2023 07:14:45 +0200 Subject: [PATCH 12/19] refs #5833 remove console.logs --- back/methods/vn-user/renew-token.js | 2 -- front/salix/components/layout/index.js | 5 ++++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index ee50d06d4..0642f1d6e 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -27,8 +27,6 @@ module.exports = Self => { const accessTokenConfig = await models.AccessTokenConfig.findOne({fields: ['renewPeriod']}); - console.log(userId, created, now, differenceMilliseconds, differenceSeconds, accessTokenConfig.renewPeriod, differenceSeconds <= accessTokenConfig.renewPeriod); - if (differenceSeconds <= accessTokenConfig.renewPeriod) throw new UserError(`The renew period has not been exceeded`); diff --git a/front/salix/components/layout/index.js b/front/salix/components/layout/index.js index 008d31ab2..449fd8d58 100644 --- a/front/salix/components/layout/index.js +++ b/front/salix/components/layout/index.js @@ -49,7 +49,6 @@ export class Layout extends Component { const differenceMilliseconds = now - new Date(this.vnToken.created); const differenceSeconds = Math.floor(differenceMilliseconds / 1000); - console.log(this.vnToken.created, now, differenceMilliseconds, differenceSeconds, this.renewPeriod, differenceSeconds > this.renewPeriod); if (differenceSeconds > this.renewPeriod) { this.$http.post('VnUsers/renewToken') .then(json => { @@ -59,6 +58,10 @@ export class Layout extends Component { this.vnToken.set(json.data.token, json.data.created, remember); } + }) + .catch(err => { + if (err.status != 400) + throw err; }); } } From 1d993c74e5a67e86a2e42cc5b02ff276c2cab070 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Thu, 29 Jun 2023 10:39:07 +0200 Subject: [PATCH 13/19] refs #5590 fix total invoiceOut --- db/dump/fixtures.sql | 32 ++++++-- db/dump/structure.sql | 74 +++++++++++++------ modules/ticket/back/methods/sale/refund.js | 2 +- .../ticket/back/methods/sale/updatePrice.js | 2 +- modules/ticket/back/methods/ticket/addSale.js | 2 +- .../back/methods/ticket/updateDiscount.js | 2 +- 6 files changed, 81 insertions(+), 33 deletions(-) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index c4338a555..cce9864e1 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -699,12 +699,12 @@ INSERT INTO `vn`.`route`(`id`, `time`, `workerFk`, `created`, `vehicleFk`, `agen INSERT INTO `vn`.`ticket`(`id`, `priority`, `agencyModeFk`,`warehouseFk`,`routeFk`, `shipped`, `landed`, `clientFk`,`nickname`, `addressFk`, `refFk`, `isDeleted`, `zoneFk`, `zonePrice`, `zoneBonus`, `created`) VALUES - (1 , 3, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 121, 'T1111111', 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), - (2 , 1, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, 'T1111111', 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), - (3 , 1, 7, 1, 6, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -2 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, 'T2222222', 0, 3, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH)), - (4 , 3, 2, 1, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -3 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, 'T3333333', 0, 9, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH)), - (5 , 3, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -4 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, 'T4444444', 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH)), - (6 , 1, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Mountain Drive Gotham', 1, 'A1111111', 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), + (1 , 3, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 121, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), + (2 , 1, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), + (3 , 1, 7, 1, 6, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -2 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 3, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH)), + (4 , 3, 2, 1, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -3 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 9, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH)), + (5 , 3, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -4 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH)), + (6 , 1, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Mountain Drive Gotham', 1, NULL, 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), (7 , NULL, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1101, 'Mountain Drive Gotham', 1, NULL, 0, 3, 5, 1, util.VN_CURDATE()), (8 , NULL, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1101, 'Bat cave', 121, NULL, 0, 3, 5, 1, util.VN_CURDATE()), (9 , NULL, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1104, 'Stark tower', 124, NULL, 0, 3, 5, 1, util.VN_CURDATE()), @@ -2572,6 +2572,26 @@ INSERT INTO `vn`.`ticketRecalc`(`ticketFk`) CALL `vn`.`ticket_doRecalc`(); +UPDATE `vn`.`ticket` + SET refFk = 'T1111111' + WHERE id IN (1,2); + +UPDATE `vn`.`ticket` + SET refFk = 'T2222222' + WHERE id = 3; + +UPDATE `vn`.`ticket` + SET refFk = 'T3333333' + WHERE id = 4; + +UPDATE `vn`.`ticket` + SET refFk = 'T4444444' + WHERE id = 5; + +UPDATE `vn`.`ticket` + SET refFk = 'A1111111' + WHERE id = 6; + INSERT INTO `vn`.`zoneAgencyMode`(`id`, `agencyModeFk`, `zoneFk`) VALUES (1, 1, 1), diff --git a/db/dump/structure.sql b/db/dump/structure.sql index b07e88fde..8edc5ab9e 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -12605,7 +12605,7 @@ BEGIN FROM myTicket t WHERE shipped BETWEEN TIMESTAMP(vFrom) AND TIMESTAMP(vTo, '23:59:59'); - CALL vn.ticketGetTotal; + CALL vn.ticketGetTotal(NULL); SELECT v.id, IFNULL(v.landed, v.shipped) landed, v.shipped, v.companyFk, v.nickname, @@ -47167,7 +47167,7 @@ BEGIN ENGINE = MEMORY SELECT vTicketId ticketFk; - CALL ticketGetTotal; + CALL ticketGetTotal(NULL); SELECT total INTO vTotal FROM tmp.ticketTotal; @@ -58494,6 +58494,13 @@ BEGIN DECLARE vIsCEESerial BOOL DEFAULT FALSE; DECLARE vIsCorrectInvoiceDate BOOL; DECLARE vMaxShipped DATE; + DECLARE vDone BOOL; + DECLARE vTicketFk INT; + DECLARE vCursor CURSOR FOR + SELECT id + FROM ticketToInvoice; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; SET vInvoiceDate = IFNULL(vInvoiceDate, util.VN_CURDATE()); @@ -58579,6 +58586,20 @@ BEGIN FROM invoiceOut WHERE id = vNewInvoiceId; + OPEN vCursor; + l: LOOP + SET vDone = FALSE; + FETCH vCursor INTO vTicketFk; + + IF vDone THEN + LEAVE l; + END IF; + + CALL ticket_recalc(vTicketFk, vTaxArea); + + END LOOP; + CLOSE vCursor; + UPDATE ticket t JOIN tmp.ticketToInvoice ti ON ti.id = t.id SET t.refFk = vNewRef; @@ -58594,10 +58615,6 @@ BEGIN INSERT INTO ticketTracking(stateFk,ticketFk,workerFk) SELECT * FROM tmp.updateInter; - INSERT INTO ticketLog (action, userFk, originFk, description) - SELECT 'UPDATE', account.myUser_getId(), ti.id, CONCAT('Crea factura ', vNewRef) - FROM tmp.ticketToInvoice ti; - CALL invoiceExpenceMake(vNewInvoiceId); CALL invoiceTaxMake(vNewInvoiceId,vTaxArea); @@ -69870,7 +69887,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketGetTotal`() +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketGetTotal`(vTaxArea VARCHAR(25)) BEGIN /** * Calcula el total con IVA para un conjunto de tickets. @@ -69878,7 +69895,7 @@ BEGIN * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular * @return tmp.ticketTotal Total para cada ticket */ - CALL ticket_getTax(NULL); + CALL ticket_getTax(vTaxArea); DROP TEMPORARY TABLE IF EXISTS tmp.ticketTotal; CREATE TEMPORARY TABLE tmp.ticketTotal @@ -70029,7 +70046,7 @@ BEGIN AND clientFk = vClientFk AND shipped > '2001-01-01'; - CALL vn.ticketGetTotal; + CALL vn.ticketGetTotal(NULL); SELECT c.id, c.name as Cliente, @@ -71878,7 +71895,7 @@ proc: BEGIN LEAVE myLoop; END IF; - CALL ticket_recalc(vTicketFk); + CALL ticket_recalc(vTicketFk, NULL); END LOOP; CLOSE cCur; @@ -72333,15 +72350,15 @@ BEGIN JOIN ticket t ON t.id = tmpTicket.ticketFk; CALL addressTaxArea (); - - IF vTaxArea > '' THEN + + IF vTaxArea IS NOT NULL THEN UPDATE tmp.addressTaxArea SET areaFk = vTaxArea; END IF; + /* Solo se calcula la base imponible (taxableBase) y el impuesto se calculará posteriormente * No se debería cambiar el sistema por problemas con los decimales */ - DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; CREATE TEMPORARY TABLE tmp.ticketTax (PRIMARY KEY (ticketFk, code, rate)) @@ -72349,7 +72366,7 @@ BEGIN SELECT * FROM ( SELECT tmpTicket.ticketFk, bp.pgcFk, - SUM(s.quantity * s.price * (100 - s.discount)/100 ) AS taxableBase, + SUM(s.quantity * s.price * (100 - s.discount)/100 ) taxableBase, pgc.rate, tc.code, bp.priority @@ -72369,7 +72386,7 @@ BEGIN JOIN pgc ON pgc.code = bp.pgcFk JOIN taxClass tc ON tc.id = bp.taxClassFk GROUP BY tmpTicket.ticketFk, pgc.code, pgc.rate - HAVING taxableBase != 0) t3 + HAVING taxableBase <> 0) t3 ORDER BY priority; DROP TEMPORARY TABLE IF EXISTS tmp.ticketServiceTax; @@ -72378,7 +72395,7 @@ BEGIN ENGINE = MEMORY SELECT tt.ticketFk, pgc.code pgcFk, - SUM(ts.quantity * ts.price) AS taxableBase, + SUM(ts.quantity * ts.price) taxableBase, pgc.rate, tc.code FROM tmp.ticket tt @@ -72394,7 +72411,7 @@ BEGIN JOIN pgc ON pgc.code = bp.pgcFk JOIN taxClass tc ON tc.id = bp.taxClassFk GROUP BY tt.ticketFk, pgc.code - HAVING taxableBase != 0; + HAVING taxableBase <> 0; INSERT INTO tmp.ticketTax (ticketFk, pgcFk, taxableBase, rate, code) SELECT ts.ticketFk, ts.pgcFk, ts.taxableBase, ts.rate, ts.code @@ -72405,8 +72422,8 @@ BEGIN CREATE TEMPORARY TABLE tmp.ticketAmount (INDEX (ticketFk)) ENGINE = MEMORY - SELECT ticketFk, - taxableBase, + SELECT ticketFk, + taxableBase, SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax, code FROM tmp.ticketTax @@ -72725,20 +72742,31 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_recalc`(vTicketId INT) -BEGIN +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_recalc`(vSelf INT, vTaxArea VARCHAR(25)) +proc:BEGIN /** * Calcula y guarda el total con/sin IVA en un ticket. * * @param vTicketId Identificador del ticket */ + DECLARE hasInvoice BOOL; + + SELECT COUNT(*) INTO hasInvoice + FROM ticket + WHERE id = vSelf + AND refFk IS NOT NULL; + + IF hasInvoice THEN + LEAVE proc; + END IF; + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; CREATE TEMPORARY TABLE tmp.ticket ENGINE = MEMORY - SELECT vTicketId ticketFk; + SELECT vSelf ticketFk; - CALL ticketGetTotal; + CALL ticketGetTotal(vTaxArea); UPDATE ticket t JOIN tmp.ticketTotal tt ON tt.ticketFk = t.id diff --git a/modules/ticket/back/methods/sale/refund.js b/modules/ticket/back/methods/sale/refund.js index 7abcedd90..a8191610a 100644 --- a/modules/ticket/back/methods/sale/refund.js +++ b/modules/ticket/back/methods/sale/refund.js @@ -106,7 +106,7 @@ module.exports = Self => { } } - const query = `CALL vn.ticket_recalc(?)`; + const query = `CALL vn.ticket_recalc(?, NULL)`; await Self.rawSql(query, [refundTicket.id], myOptions); if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/sale/updatePrice.js b/modules/ticket/back/methods/sale/updatePrice.js index 649395da6..62e4ebd42 100644 --- a/modules/ticket/back/methods/sale/updatePrice.js +++ b/modules/ticket/back/methods/sale/updatePrice.js @@ -96,7 +96,7 @@ module.exports = Self => { await sale.updateAttributes({price: newPrice}, myOptions); await Self.rawSql('CALL vn.manaSpellersRequery(?)', [userId], myOptions); - await Self.rawSql('CALL vn.ticket_recalc(?)', [sale.ticketFk], myOptions); + await Self.rawSql('CALL vn.ticket_recalc(?, NULL)', [sale.ticketFk], myOptions); const salesPerson = sale.ticket().client().salesPersonUser(); if (salesPerson) { diff --git a/modules/ticket/back/methods/ticket/addSale.js b/modules/ticket/back/methods/ticket/addSale.js index 85b0510ae..2cd02a8a4 100644 --- a/modules/ticket/back/methods/ticket/addSale.js +++ b/modules/ticket/back/methods/ticket/addSale.js @@ -85,7 +85,7 @@ module.exports = Self => { }, myOptions); await Self.rawSql('CALL vn.sale_calculateComponent(?, NULL)', [newSale.id], myOptions); - await Self.rawSql('CALL vn.ticket_recalc(?)', [id], myOptions); + await Self.rawSql('CALL vn.ticket_recalc(?, NULL)', [id], myOptions); const sale = await models.Sale.findById(newSale.id, { include: { diff --git a/modules/ticket/back/methods/ticket/updateDiscount.js b/modules/ticket/back/methods/ticket/updateDiscount.js index 6feeafa1a..e092ee4ed 100644 --- a/modules/ticket/back/methods/ticket/updateDiscount.js +++ b/modules/ticket/back/methods/ticket/updateDiscount.js @@ -147,7 +147,7 @@ module.exports = Self => { await Promise.all(promises); await Self.rawSql('CALL vn.manaSpellersRequery(?)', [userId], myOptions); - await Self.rawSql('CALL vn.ticket_recalc(?)', [id], myOptions); + await Self.rawSql('CALL vn.ticket_recalc(?, NULL)', [id], myOptions); const ticket = await models.Ticket.findById(id, { include: { From 3bd890c3436d6a9367d9e80f8677efa74331a7f2 Mon Sep 17 00:00:00 2001 From: vicent Date: Thu, 29 Jun 2023 12:11:16 +0200 Subject: [PATCH 14/19] refs #5554 fix: solo llama al back cuando se tiene q renovar --- back/methods/vn-user/renew-token.js | 19 ++- back/methods/vn-user/signIn.js | 2 +- back/models/access-token-config.json | 4 + db/changes/232601/00-salix.sql | 5 +- front/core/services/auth.js | 7 +- front/core/services/interceptor.js | 12 +- front/core/services/token.js | 127 ++++++++++++++++---- front/salix/components/layout/index.html | 4 +- front/salix/components/layout/index.js | 41 +------ front/salix/components/layout/index.spec.js | 45 ------- front/salix/routes.js | 3 +- 11 files changed, 138 insertions(+), 131 deletions(-) diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index 0642f1d6e..9850267d6 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -17,23 +17,22 @@ module.exports = Self => { Self.renewToken = async function(ctx) { const models = Self.app.models; - const userId = ctx.req.accessToken.userId; - const created = ctx.req.accessToken.created; - const tokenId = ctx.req.accessToken.id; + const token = ctx.req.accessToken; const now = new Date(); - const differenceMilliseconds = now - new Date(created); + const differenceMilliseconds = now - token.created; const differenceSeconds = Math.floor(differenceMilliseconds / 1000); - const accessTokenConfig = await models.AccessTokenConfig.findOne({fields: ['renewPeriod']}); + const fields = ['renewPeriod', 'courtesyTime']; + const accessTokenConfig = await models.AccessTokenConfig.findOne({fields}); - if (differenceSeconds <= accessTokenConfig.renewPeriod) - throw new UserError(`The renew period has not been exceeded`); + if (differenceSeconds < accessTokenConfig.renewPeriod - accessTokenConfig.courtesyTime) + throw new UserError(`The renew period has not been exceeded`, 'periodNotExceeded'); - await Self.logout(tokenId); - const user = await Self.findById(userId); + await Self.logout(token.id); + const user = await Self.findById(token.userId); const accessToken = await user.createAccessToken(); - return {token: accessToken.id, created: accessToken.created}; + return {id: accessToken.id, ttl: accessToken.ttl}; }; }; diff --git a/back/methods/vn-user/signIn.js b/back/methods/vn-user/signIn.js index c98f1da54..e52d68df5 100644 --- a/back/methods/vn-user/signIn.js +++ b/back/methods/vn-user/signIn.js @@ -76,6 +76,6 @@ module.exports = Self => { let loginInfo = Object.assign({password}, userInfo); token = await Self.login(loginInfo, 'user'); - return {token: token.id, created: token.created}; + return {token: token.id, ttl: token.ttl}; }; }; diff --git a/back/models/access-token-config.json b/back/models/access-token-config.json index 6d90a0f4d..d5838a158 100644 --- a/back/models/access-token-config.json +++ b/back/models/access-token-config.json @@ -16,6 +16,10 @@ "type": "number", "required": true }, + "courtesyTime": { + "type": "number", + "required": true + }, "renewInterval": { "type": "number", "required": true diff --git a/db/changes/232601/00-salix.sql b/db/changes/232601/00-salix.sql index dc1ed69be..44366abce 100644 --- a/db/changes/232601/00-salix.sql +++ b/db/changes/232601/00-salix.sql @@ -1,10 +1,11 @@ CREATE TABLE `salix`.`accessTokenConfig` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `renewPeriod` int(10) unsigned DEFAULT NULL, + `courtesyTime` int(10) unsigned DEFAULT NULL, `renewInterval` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; -INSERT IGNORE INTO `salix`.`accessTokenConfig` (`id`, `renewPeriod`, `renewInterval`) +INSERT IGNORE INTO `salix`.`accessTokenConfig` (`id`, `renewPeriod`, `courtesyTime`, `renewInterval`) VALUES - (1, 21600, 300); + (1, 21600, 5, 300); diff --git a/front/core/services/auth.js b/front/core/services/auth.js index ef6c07637..92ff4b061 100644 --- a/front/core/services/auth.js +++ b/front/core/services/auth.js @@ -59,12 +59,13 @@ export default class Auth { password: password || undefined }; + const now = new Date(); return this.$http.post('VnUsers/signIn', params) - .then(json => this.onLoginOk(json, remember)); + .then(json => this.onLoginOk(json, now, remember)); } - onLoginOk(json, remember) { - this.vnToken.set(json.data.token, json.data.created, remember); + onLoginOk(json, now, remember) { + this.vnToken.set(json.data.token, now, json.data.ttl, remember); return this.loadAcls().then(() => { let continueHash = this.$state.params.continue; diff --git a/front/core/services/interceptor.js b/front/core/services/interceptor.js index 3f3d9912b..1c7b1a460 100644 --- a/front/core/services/interceptor.js +++ b/front/core/services/interceptor.js @@ -1,11 +1,15 @@ import ngModule from '../module'; import HttpError from 'core/lib/http-error'; -interceptor.$inject = ['$q', 'vnApp', 'vnToken', '$translate']; -function interceptor($q, vnApp, vnToken, $translate) { +interceptor.$inject = ['$q', 'vnApp', '$translate']; +function interceptor($q, vnApp, $translate) { let apiPath = 'api/'; + let token; return { + setToken(newToken) { + token = newToken; + }, setApiPath(path) { apiPath = path; }, @@ -14,8 +18,8 @@ function interceptor($q, vnApp, vnToken, $translate) { if (config.url.charAt(0) !== '/' && apiPath) config.url = `${apiPath}${config.url}`; - if (vnToken.token) - config.headers.Authorization = vnToken.token; + if (token) + config.headers.Authorization = token; if ($translate.use()) config.headers['Accept-Language'] = $translate.use(); if (config.filter) { diff --git a/front/core/services/token.js b/front/core/services/token.js index c1bb5a173..d0e0b7ced 100644 --- a/front/core/services/token.js +++ b/front/core/services/token.js @@ -6,37 +6,114 @@ import ngModule from '../module'; * @property {String} token The current login token or %null */ export default class Token { - constructor() { - try { - this.token = sessionStorage.getItem('vnToken'); - this.created = sessionStorage.getItem('vnTokenCreated'); - if (!this.token) { - this.token = localStorage.getItem('vnToken'); - this.created = localStorage.getItem('vnTokenCreated'); - } - } catch (e) {} - } - set(token, created, remember) { - this.unset(); - try { - if (remember) { - localStorage.setItem('vnToken', token); - localStorage.setItem('vnTokenCreated', created); - } else { - sessionStorage.setItem('vnToken', token); - sessionStorage.setItem('vnTokenCreated', created); - } - } catch (e) {} + constructor(vnInterceptor, $http, $rootScope) { + Object.assign(this, { + vnInterceptor, + $http, + $rootScope + }); - this.token = token; - this.created = created; + try { + this.getStorage(sessionStorage); + this.remember = true; + + if (!this.token) { + this.getStorage(localStorage); + this.remember = false; + } + } catch (e) {} } + + set(token, created, ttl, remember) { + this.unset(); + + Object.assign(this, { + token, + created, + ttl, + remember + }); + this.vnInterceptor.setToken(token); + + try { + if (remember) + this.setStorage(localStorage, token, created, ttl); + else + this.setStorage(sessionStorage, token, created, ttl); + } catch (e) {} + } + unset() { - localStorage.removeItem('vnToken'); - sessionStorage.removeItem('vnToken'); this.token = null; this.created = null; + this.ttl = null; + this.remember = null; + this.vnInterceptor.setToken(null); + + this.removeStorage(localStorage); + this.removeStorage(sessionStorage); + } + + getStorage(storage) { + this.token = storage.getItem('vnToken'); + this.created = storage.getItem('vnTokenCreated'); + this.renewPeriod = storage.getItem('vnTokenRenewPeriod'); + } + + setStorage(storage, token, created, ttl) { + storage.setItem('vnToken', token); + storage.setItem('vnTokenCreated', created); + storage.setItem('vnTokenTtl', ttl); + } + + removeStorage(storage) { + storage.removeItem('vnToken'); + storage.removeItem('vnTokenCreated'); + storage.removeItem('vnTokenTtl'); + } + + fetchConfig() { + const filter = {fields: ['renewInterval', 'renewPeriod']}; + this.$http.get('AccessTokenConfigs/findOne', {filter}).then(res => { + const data = res.data; + if (!data) return; + this.renewPeriod = data.renewPeriod; + this.stopRenewer(); + this.inservalId = setInterval(() => this.checkValidity(), data.renewInterval * 1000); + this.checkValidity(); + }); + } + + checkValidity() { + if (this.checking) return; + this.checking = true; + const renewPeriod = Math.min(this.ttl, this.renewPeriod) * 1000; + const maxDate = this.created.getTime() + renewPeriod; + const now = new Date(); + + if (now.getTime() <= maxDate) { + this.checking = false; + return; + } + + this.$http.post('VnUsers/renewToken') + .then(res => { + const token = res.data; + this.set(token.id, now, token.ttl, this.remember); + }) + .catch(res => { + if (res.data?.error?.code !== 'periodNotExceeded') + throw res; + }) + .finally(() => { + this.checking = false; + }); + } + + stopRenewer() { + clearInterval(this.inservalId); } } +Token.$inject = ['vnInterceptor', '$http', '$rootScope']; ngModule.service('vnToken', Token); diff --git a/front/salix/components/layout/index.html b/front/salix/components/layout/index.html index 5a525ef77..972defaa1 100644 --- a/front/salix/components/layout/index.html +++ b/front/salix/components/layout/index.html @@ -42,7 +42,7 @@