From 3e522b08b6c7fc93eb36b1721814f6efbfe428f0 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 11 Oct 2023 11:43:21 +0200 Subject: [PATCH 01/69] refs #6184 Added saveCmr --- modules/ticket/back/methods/ticket/saveCmr.js | 82 +++++++++++++++++++ .../ticket/back/methods/ticket/saveSign.js | 3 +- modules/ticket/back/models/ticket-methods.js | 1 + 3 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 modules/ticket/back/methods/ticket/saveCmr.js diff --git a/modules/ticket/back/methods/ticket/saveCmr.js b/modules/ticket/back/methods/ticket/saveCmr.js new file mode 100644 index 000000000..ce39ba20a --- /dev/null +++ b/modules/ticket/back/methods/ticket/saveCmr.js @@ -0,0 +1,82 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('saveCmr', { + description: 'Save sign', + accessType: 'WRITE', + accepts: + [ + { + arg: 'tickets', + type: ['number'], + required: true, + description: 'The tickets' + } + ], + http: { + path: `/saveCmr`, + verb: 'POST' + } + }); + + Self.saveCmr = async(ctx, tickets, options) => { + const models = Self.app.models; + const myOptions = {userId: ctx.req.accessToken.userId}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + for (const ticketId of tickets) { + const cmrFk = await models.Ticket.findOne( + {where: {id: ticketId}, + fields: ['cmrFk'] + }, myOptions); + + if (cmrFk) { + const dmsTypeCmr = await models.DmsType.findOne({ + where: {code: 'ticket'}, + fields: ['id'] + }, myOptions); + + const hasDmsCmr = await models.TicketDms.findOne({ + where: { ticketFk: ticketId }, + fields: ['dmsFk'], + include: { + relation: 'dms', + scope: { + where: { dmsTypeFk: dmsTypeCmr } + } + } + }, myOptions); + + if (!hasDmsCmr) { + const zip = await models.Route.downloadCmrsZip(ctx, cmr, myOptions); + const ticket = await models.Ticket.findById(ticketId, null, myOptions); + const ctxUploadFile = Object.assign({}, zip); + ctxUploadFile.args = { + warehouseId: ticket.warehouseFk, + companyId: ticket.companyFk, + dmsTypeId: dmsTypeCmr.id, + reference: '', + description: `Documento comprimido - CMR ${cmrFk}`, + hasFile: false + }; + await models.Dms.uploadFile(ctxUploadFile, myOptions); + } + } + } + if (tx) await tx.commit(); + return; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 9888328e7..015a95afb 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -91,7 +91,7 @@ module.exports = Self => { } ] }, myOptions); - const dmsType = await models.DmsType.findOne({where: {code: 'Ticket'}, fields: ['id']}, myOptions); + const dmsType = await models.DmsType.findOne({where: {code: 'ticket'}, fields: ['id']}, myOptions); const ctxUploadFile = Object.assign({}, ctx); if (ticket.route() === null) throw new UserError('Ticket without route'); @@ -131,6 +131,7 @@ module.exports = Self => { const ticket = await models.Ticket.findById(ticketId, null, myOptions); await ticket.updateAttribute('isSigned', true, myOptions); await Self.rawSql(`CALL vn.ticket_setState(?, ?)`, [ticketId, 'DELIVERED'], myOptions); + await models.Ticket.saveCmr(ticketId, myOptions); } if (tx) await tx.commit(); diff --git a/modules/ticket/back/models/ticket-methods.js b/modules/ticket/back/models/ticket-methods.js index 14cb104be..c932548e1 100644 --- a/modules/ticket/back/models/ticket-methods.js +++ b/modules/ticket/back/models/ticket-methods.js @@ -41,6 +41,7 @@ module.exports = function(Self) { require('../methods/ticket/collectionLabel')(Self); require('../methods/ticket/expeditionPalletLabel')(Self); require('../methods/ticket/saveSign')(Self); + require('../methods/ticket/saveCmr')(Self); require('../methods/ticket/invoiceTickets')(Self); require('../methods/ticket/docuwareDownload')(Self); }; From d9339af87e0fc92fd05dc5cc20499bd66963adb8 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 11 Oct 2023 11:46:56 +0200 Subject: [PATCH 02/69] refs #6184 Insert in ticketCmr --- modules/ticket/back/methods/ticket/saveCmr.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/ticket/back/methods/ticket/saveCmr.js b/modules/ticket/back/methods/ticket/saveCmr.js index ce39ba20a..5df4d8ae7 100644 --- a/modules/ticket/back/methods/ticket/saveCmr.js +++ b/modules/ticket/back/methods/ticket/saveCmr.js @@ -22,7 +22,7 @@ module.exports = Self => { Self.saveCmr = async(ctx, tickets, options) => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; - let tx; + let tx, dms; if (typeof options == 'object') Object.assign(myOptions, options); @@ -68,7 +68,8 @@ module.exports = Self => { description: `Documento comprimido - CMR ${cmrFk}`, hasFile: false }; - await models.Dms.uploadFile(ctxUploadFile, myOptions); + dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); + await models.TicketDms.create({ticketFk: ticketId, dmsFk: dms[0].id}, myOptions); } } } From c0089b1fa0b38a0927a046d33c5905cb5f2a4fa2 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 11 Oct 2023 12:20:30 +0200 Subject: [PATCH 03/69] refs #6184 Added cmrFk in ticket model --- modules/ticket/back/methods/ticket/saveCmr.js | 12 +++++------- modules/ticket/back/models/ticket.json | 3 +++ 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/modules/ticket/back/methods/ticket/saveCmr.js b/modules/ticket/back/methods/ticket/saveCmr.js index 5df4d8ae7..06dc5b7fb 100644 --- a/modules/ticket/back/methods/ticket/saveCmr.js +++ b/modules/ticket/back/methods/ticket/saveCmr.js @@ -1,8 +1,6 @@ -const UserError = require('vn-loopback/util/user-error'); - module.exports = Self => { Self.remoteMethodCtx('saveCmr', { - description: 'Save sign', + description: 'Save cmr', accessType: 'WRITE', accepts: [ @@ -34,10 +32,10 @@ module.exports = Self => { try { for (const ticketId of tickets) { - const cmrFk = await models.Ticket.findOne( - {where: {id: ticketId}, - fields: ['cmrFk'] - }, myOptions); + const cmrFk = await models.Ticket.findOne({ + where: {id: ticketId}, + fields: ['cmrFk'] + }, myOptions); if (cmrFk) { const dmsTypeCmr = await models.DmsType.findOne({ diff --git a/modules/ticket/back/models/ticket.json b/modules/ticket/back/models/ticket.json index ec4193bed..b5f2b5ed9 100644 --- a/modules/ticket/back/models/ticket.json +++ b/modules/ticket/back/models/ticket.json @@ -63,6 +63,9 @@ }, "weight": { "type": "number" + }, + "cmrFk": { + "type": "number" } }, "relations": { From 3e70cb07e0c0cfdff874323b533ffdd41b738973 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 11 Oct 2023 14:20:35 +0200 Subject: [PATCH 04/69] refs #6184 Changes --- .../back/methods/route/downloadCmrsZip.js | 6 +- modules/route/back/models/cmr.json | 58 +++++++++++++++++++ modules/ticket/back/methods/ticket/saveCmr.js | 37 ++++++------ modules/ticket/back/models/ticket.json | 5 ++ 4 files changed, 87 insertions(+), 19 deletions(-) create mode 100644 modules/route/back/models/cmr.json diff --git a/modules/route/back/methods/route/downloadCmrsZip.js b/modules/route/back/methods/route/downloadCmrsZip.js index 532e019b6..c3379ab82 100644 --- a/modules/route/back/methods/route/downloadCmrsZip.js +++ b/modules/route/back/methods/route/downloadCmrsZip.js @@ -49,8 +49,12 @@ module.exports = Self => { try { for (let id of ids) { if (zipConfig && totalSize > zipConfig.maxSize) throw new UserError('Files are too large'); + + const baseUrl = (ctx.req.headers.origin) + ? `${ctx.req.headers.origin}/api` + : `${ctx.req.headers.referer}api` const response = await axios.get( - `${ctx.req.headers.referer}api/Routes/${id}/cmr?access_token=${token.id}`, { + `${baseUrl}/Routes/${id}/cmr?access_token=${token.id}`, { ...myOptions, responseType: 'arraybuffer', }); diff --git a/modules/route/back/models/cmr.json b/modules/route/back/models/cmr.json new file mode 100644 index 000000000..0e2168bed --- /dev/null +++ b/modules/route/back/models/cmr.json @@ -0,0 +1,58 @@ +{ + "name": "Cmr", + "base": "VnModel", + "options": { + "mysql": { + "table": "cmr" + } + }, + "properties": { + "id": { + "type": "number", + "id": true, + "description": "Identifier" + }, + "truckPlate": { + "type": "number" + }, + "observations": { + "type": "string" + }, + "senderInstrucctions": { + "type": "string" + }, + "paymentInstruccions": { + "type": "string" + }, + "specialAgreements": { + "type": "string" + }, + "created": { + "type": "date" + }, + "companyFk": { + "type": "number" + }, + "addressToFk": { + "type": "number" + }, + "addressFromFk": { + "type": "number" + }, + "supplierFk": { + "type": "number" + }, + "packagesList": { + "type": "string" + }, + "merchandiseDetail": { + "type": "string" + }, + "landed": { + "type": "date" + }, + "ead": { + "type": "date" + } + } +} diff --git a/modules/ticket/back/methods/ticket/saveCmr.js b/modules/ticket/back/methods/ticket/saveCmr.js index 06dc5b7fb..2bd52aaa8 100644 --- a/modules/ticket/back/methods/ticket/saveCmr.js +++ b/modules/ticket/back/methods/ticket/saveCmr.js @@ -20,7 +20,7 @@ module.exports = Self => { Self.saveCmr = async(ctx, tickets, options) => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; - let tx, dms; + let tx; if (typeof options == 'object') Object.assign(myOptions, options); @@ -32,42 +32,43 @@ module.exports = Self => { try { for (const ticketId of tickets) { - const cmrFk = await models.Ticket.findOne({ - where: {id: ticketId}, - fields: ['cmrFk'] - }, myOptions); + const ticket = await models.Ticket.findById(ticketId, myOptions); - if (cmrFk) { - const dmsTypeCmr = await models.DmsType.findOne({ - where: {code: 'ticket'}, + if (ticket.cmrFk) { + const dmsType = await models.DmsType.findOne({ + where: {code: 'cmr'}, fields: ['id'] }, myOptions); const hasDmsCmr = await models.TicketDms.findOne({ where: { ticketFk: ticketId }, - fields: ['dmsFk'], include: { relation: 'dms', + fields: ['dmsFk'], scope: { - where: { dmsTypeFk: dmsTypeCmr } + where: { dmsTypeFk: dmsType.id } } } }, myOptions); - if (!hasDmsCmr) { - const zip = await models.Route.downloadCmrsZip(ctx, cmr, myOptions); - const ticket = await models.Ticket.findById(ticketId, null, myOptions); - const ctxUploadFile = Object.assign({}, zip); + if (!hasDmsCmr.dms()) { + const zip = await models.Route.downloadCmrsZip(ctx, ticket.cmrFk.toString(), myOptions); + let ctxUploadFile; + ctx.req.file = Object.assign({}, zip); + ctxUploadFile = Object.assign({}, ctx); ctxUploadFile.args = { warehouseId: ticket.warehouseFk, companyId: ticket.companyFk, - dmsTypeId: dmsTypeCmr.id, + dmsTypeId: dmsType.id, reference: '', - description: `Documento comprimido - CMR ${cmrFk}`, + description: `Documento comprimido - CMR ${ticket.cmrFk}`, hasFile: false }; - dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); - await models.TicketDms.create({ticketFk: ticketId, dmsFk: dms[0].id}, myOptions); + const dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); + await models.TicketDms.create({ + ticketFk: ticketId, + dmsFk: dms[0].id + }, myOptions); } } } diff --git a/modules/ticket/back/models/ticket.json b/modules/ticket/back/models/ticket.json index b5f2b5ed9..4a5205d3d 100644 --- a/modules/ticket/back/models/ticket.json +++ b/modules/ticket/back/models/ticket.json @@ -139,6 +139,11 @@ "type": "belongsTo", "model": "Zone", "foreignKey": "zoneFk" + }, + "cmrFk": { + "type": "belongsTo", + "model": "Cmr", + "foreignKey": "cmrFk" } } } From 0771548ef1c5ce9cbff10f2fd427f836aa696458 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 9 Nov 2023 14:14:09 +0100 Subject: [PATCH 05/69] refs #6184 Requested changes --- modules/ticket/back/methods/ticket/saveCmr.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ticket/back/methods/ticket/saveCmr.js b/modules/ticket/back/methods/ticket/saveCmr.js index 2bd52aaa8..c322dd27c 100644 --- a/modules/ticket/back/methods/ticket/saveCmr.js +++ b/modules/ticket/back/methods/ticket/saveCmr.js @@ -61,7 +61,7 @@ module.exports = Self => { companyId: ticket.companyFk, dmsTypeId: dmsType.id, reference: '', - description: `Documento comprimido - CMR ${ticket.cmrFk}`, + description: `${ticket.cmrFk} - ${ticket.id}`, hasFile: false }; const dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); From 2792efa9cd4030d9d6fbf27f48e5c4cf2e6654bf Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 13 Nov 2023 08:36:05 +0100 Subject: [PATCH 06/69] perf: refs #6184 Requested changes --- modules/ticket/back/methods/ticket/saveCmr.js | 31 ++++++++++--------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/modules/ticket/back/methods/ticket/saveCmr.js b/modules/ticket/back/methods/ticket/saveCmr.js index c322dd27c..680e7a1f0 100644 --- a/modules/ticket/back/methods/ticket/saveCmr.js +++ b/modules/ticket/back/methods/ticket/saveCmr.js @@ -31,38 +31,39 @@ module.exports = Self => { } try { + const dmsTypeCmr = await models.DmsType.findOne({ + where: {code: 'cmr'}, + fields: ['id'] + }, myOptions); + for (const ticketId of tickets) { const ticket = await models.Ticket.findById(ticketId, myOptions); if (ticket.cmrFk) { - const dmsType = await models.DmsType.findOne({ - where: {code: 'cmr'}, - fields: ['id'] - }, myOptions); - const hasDmsCmr = await models.TicketDms.findOne({ where: { ticketFk: ticketId }, include: { relation: 'dms', fields: ['dmsFk'], scope: { - where: { dmsTypeFk: dmsType.id } + where: { dmsTypeFk: dmsTypeCmr.id } } } }, myOptions); if (!hasDmsCmr.dms()) { const zip = await models.Route.downloadCmrsZip(ctx, ticket.cmrFk.toString(), myOptions); - let ctxUploadFile; ctx.req.file = Object.assign({}, zip); - ctxUploadFile = Object.assign({}, ctx); - ctxUploadFile.args = { - warehouseId: ticket.warehouseFk, - companyId: ticket.companyFk, - dmsTypeId: dmsType.id, - reference: '', - description: `${ticket.cmrFk} - ${ticket.id}`, - hasFile: false + const ctxUploadFile = { + ...ctx, + args: { + warehouseId: ticket.warehouseFk, + companyId: ticket.companyFk, + dmsTypeId: dmsTypeCmr.id, + reference: ticket.id, + description: `${ticket.cmrFk} - ${ticket.id}`, + hasFile: false + } }; const dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); await models.TicketDms.create({ From 64ca72b1f44568151e86e065f6986162ca9b47de Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 13 Nov 2023 09:57:25 +0100 Subject: [PATCH 07/69] refactor refs #6184 Changed downloadCmrsZip --- .../route/back/methods/route/downloadCmrsZip.js | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/modules/route/back/methods/route/downloadCmrsZip.js b/modules/route/back/methods/route/downloadCmrsZip.js index c3379ab82..23fae5ddc 100644 --- a/modules/route/back/methods/route/downloadCmrsZip.js +++ b/modules/route/back/methods/route/downloadCmrsZip.js @@ -37,7 +37,6 @@ module.exports = Self => { Self.downloadCmrsZip = async function(ctx, ids, options) { const models = Self.app.models; const myOptions = {}; - const token = ctx.req.accessToken; const zip = new JSZip(); if (typeof options == 'object') @@ -47,18 +46,20 @@ module.exports = Self => { let totalSize = 0; ids = ids.split(','); try { - for (let id of ids) { + const baseUrl = (await Self.app.models.Url.getUrl()).replace('#!', 'api'); + + for (const id of ids) { if (zipConfig && totalSize > zipConfig.maxSize) throw new UserError('Files are too large'); - const baseUrl = (ctx.req.headers.origin) - ? `${ctx.req.headers.origin}/api` - : `${ctx.req.headers.referer}api` const response = await axios.get( - `${baseUrl}/Routes/${id}/cmr?access_token=${token.id}`, { + `${baseUrl}Routes/${id}/cmr`, { ...myOptions, + headers: { + Authorization: ctx.req.accessToken.id + }, responseType: 'arraybuffer', }); - + if (response.headers['content-type'] !== 'application/pdf') throw new UserError(`The response is not a PDF`); From 45fd96cee6d59d14852529aaf0bdf9e1af7d1795 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 17 Jan 2024 13:07:26 +0100 Subject: [PATCH 08/69] feat: #6184 Modified uploadFile --- back/methods/dms/uploadFile.js | 46 +++++-------------- back/models/dms.js | 30 ++++++++++++ .../back/methods/route/downloadCmrsZip.js | 33 ++++++------- modules/ticket/back/methods/ticket/saveCmr.js | 28 +++++------ 4 files changed, 71 insertions(+), 66 deletions(-) diff --git a/back/methods/dms/uploadFile.js b/back/methods/dms/uploadFile.js index a4212b804..728ae229f 100644 --- a/back/methods/dms/uploadFile.js +++ b/back/methods/dms/uploadFile.js @@ -49,7 +49,6 @@ module.exports = Self => { Self.uploadFile = async(ctx, options) => { const models = Self.app.models; const TempContainer = models.TempContainer; - const DmsContainer = models.DmsContainer; const fileOptions = {}; const args = ctx.args; @@ -79,19 +78,21 @@ module.exports = Self => { const addedDms = []; for (const uploadedFile of files) { - const newDms = await createDms(ctx, uploadedFile, myOptions); - const pathHash = DmsContainer.getHash(newDms.id); - const file = await TempContainer.getFile(tempContainer.name, uploadedFile.name); srcFile = path.join(file.client.root, file.container, file.name); - const dmsContainer = await DmsContainer.container(pathHash); - const dstFile = path.join(dmsContainer.client.root, pathHash, newDms.file); - - await fs.move(srcFile, dstFile, { - overwrite: true - }); - + const data = { + workerFk: ctx.req.accessToken.userId, + dmsTypeFk: args.dmsTypeId, + companyFk: args.companyId, + warehouseFk: args.warehouseId, + reference: args.reference, + description: args.description, + contentType: file.type, + hasFile: args.hasFile + }; + const extension = await models.DmsContainer.getFileExtension(uploadedFile.name); + const newDms = await Self.createFromFile(data, extension, srcFile, myOptions); addedDms.push(newDms); } @@ -107,27 +108,4 @@ module.exports = Self => { throw e; } }; - - async function createDms(ctx, file, myOptions) { - const models = Self.app.models; - const myUserId = ctx.req.accessToken.userId; - const args = ctx.args; - - const newDms = await Self.create({ - workerFk: myUserId, - dmsTypeFk: args.dmsTypeId, - companyFk: args.companyId, - warehouseFk: args.warehouseId, - reference: args.reference, - description: args.description, - contentType: file.type, - hasFile: args.hasFile - }, myOptions); - - let fileName = file.name; - const extension = models.DmsContainer.getFileExtension(fileName); - fileName = `${newDms.id}.${extension}`; - - return newDms.updateAttribute('file', fileName, myOptions); - } }; diff --git a/back/models/dms.js b/back/models/dms.js index 24c072f56..e5b925e82 100644 --- a/back/models/dms.js +++ b/back/models/dms.js @@ -1,4 +1,6 @@ const UserError = require('vn-loopback/util/user-error'); +const fs = require('fs-extra'); +const path = require('path'); module.exports = Self => { require('../methods/dms/downloadFile')(Self); @@ -35,4 +37,32 @@ module.exports = Self => { return [stream, dms.contentType, `filename="${dms.file}"`]; }; + + Self.getPath = async function(dms) { + const models = Self.app.models; + const pathHash = await models.DmsContainer.getHash(dms.id); + const dmsContainer = await models.DmsContainer.container(pathHash); + const dstFile = path.join(dmsContainer.client.root, pathHash, dms.file); + return dstFile; + }; + + Self.createWithExtension = async function(data, extension, options) { + const newDms = await Self.create(data, options); + return newDms.updateAttribute('file', `${newDms.id}.${extension}`, options); + }; + + Self.createFromFile = async function(data, extension, srcFile, options) { + const dms = await Self.createWithExtension(data, extension, options); + const dstFile = await Self.getPath(dms); + await fs.move(srcFile, dstFile, {overwrite: true}); + return dms; + }; + + Self.createFromStream = async function(data, extension, stream, options) { + const dms = await Self.createWithExtension(data, extension, options); + const dstFile = await Self.getPath(dms); + const writeStream = await fs.createWriteStream(dstFile); + await readStream.pipe(writeStream); + return dms; + }; }; diff --git a/modules/route/back/methods/route/downloadCmrsZip.js b/modules/route/back/methods/route/downloadCmrsZip.js index 23fae5ddc..fbf439d24 100644 --- a/modules/route/back/methods/route/downloadCmrsZip.js +++ b/modules/route/back/methods/route/downloadCmrsZip.js @@ -45,32 +45,29 @@ module.exports = Self => { const zipConfig = await models.ZipConfig.findOne(null, myOptions); let totalSize = 0; ids = ids.split(','); - try { - const baseUrl = (await Self.app.models.Url.getUrl()).replace('#!', 'api'); - for (const id of ids) { - if (zipConfig && totalSize > zipConfig.maxSize) throw new UserError('Files are too large'); + const baseUrl = (await Self.app.models.Url.getUrl()).replace('#!', 'api'); - const response = await axios.get( - `${baseUrl}Routes/${id}/cmr`, { + for (const id of ids) { + if (zipConfig && totalSize > zipConfig.maxSize) throw new UserError('Files are too large'); + + const response = await axios.get( + `${baseUrl}Routes/${id}/cmr`, { ...myOptions, headers: { Authorization: ctx.req.accessToken.id }, responseType: 'arraybuffer', }); - - if (response.headers['content-type'] !== 'application/pdf') - throw new UserError(`The response is not a PDF`); - - zip.file(`${id}.pdf`, response.data, { binary: true }); - } - - const zipStream = zip.generateNodeStream({ streamFiles: true }); - - return [zipStream, 'application/zip', `filename="cmrs.zip"`]; - } catch (e) { - throw e; + + if (response.headers['content-type'] !== 'application/pdf') + throw new UserError(`The response is not a PDF`); + + zip.file(`${id}.pdf`, response.data, {binary: true}); } + + const zipStream = zip.generateNodeStream({streamFiles: true}); + + return [zipStream, 'application/zip', `filename="cmrs.zip"`]; }; }; diff --git a/modules/ticket/back/methods/ticket/saveCmr.js b/modules/ticket/back/methods/ticket/saveCmr.js index 680e7a1f0..01c45e104 100644 --- a/modules/ticket/back/methods/ticket/saveCmr.js +++ b/modules/ticket/back/methods/ticket/saveCmr.js @@ -41,31 +41,31 @@ module.exports = Self => { if (ticket.cmrFk) { const hasDmsCmr = await models.TicketDms.findOne({ - where: { ticketFk: ticketId }, + where: {ticketFk: ticketId}, include: { relation: 'dms', fields: ['dmsFk'], scope: { - where: { dmsTypeFk: dmsTypeCmr.id } + where: {dmsTypeFk: dmsTypeCmr.id} } } }, myOptions); if (!hasDmsCmr.dms()) { const zip = await models.Route.downloadCmrsZip(ctx, ticket.cmrFk.toString(), myOptions); - ctx.req.file = Object.assign({}, zip); - const ctxUploadFile = { - ...ctx, - args: { - warehouseId: ticket.warehouseFk, - companyId: ticket.companyFk, - dmsTypeId: dmsTypeCmr.id, - reference: ticket.id, - description: `${ticket.cmrFk} - ${ticket.id}`, - hasFile: false - } + const stream = Object.assign({}, zip); + const data = { + workerFk: ctx.req.accessToken.userId, + dmsTypeFk: dmsTypeCmr.id, + companyFk: ticket.companyFk, + warehouseFk: ticket.warehouseFk, + reference: ticket.id, + description: `${ticket.cmrFk} - ${ticket.id}`, + contentType: '?', + hasFile: false }; - const dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); + + const dms = await models.Dms.createFromStream(data, 'zip', stream, myOptions); await models.TicketDms.create({ ticketFk: ticketId, dmsFk: dms[0].id From 1a52e58eaaf2fc13e8e619eceeda11fe55d01e8e Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 17 Jan 2024 14:18:31 +0100 Subject: [PATCH 09/69] feat: #6184 Created generateCmrPdf --- back/models/dms.js | 2 +- .../back/methods/route/downloadCmrsZip.js | 23 +------ .../back/methods/route/generateCmrPdf.js | 64 +++++++++++++++++++ modules/route/back/models/route.js | 1 + modules/ticket/back/methods/ticket/saveCmr.js | 16 +++-- 5 files changed, 77 insertions(+), 29 deletions(-) create mode 100644 modules/route/back/methods/route/generateCmrPdf.js diff --git a/back/models/dms.js b/back/models/dms.js index e5b925e82..d6eab4fe4 100644 --- a/back/models/dms.js +++ b/back/models/dms.js @@ -62,7 +62,7 @@ module.exports = Self => { const dms = await Self.createWithExtension(data, extension, options); const dstFile = await Self.getPath(dms); const writeStream = await fs.createWriteStream(dstFile); - await readStream.pipe(writeStream); + await stream.pipe(writeStream); return dms; }; }; diff --git a/modules/route/back/methods/route/downloadCmrsZip.js b/modules/route/back/methods/route/downloadCmrsZip.js index fbf439d24..9fe9c3735 100644 --- a/modules/route/back/methods/route/downloadCmrsZip.js +++ b/modules/route/back/methods/route/downloadCmrsZip.js @@ -1,6 +1,4 @@ const JSZip = require('jszip'); -const axios = require('axios'); -const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('downloadCmrsZip', { @@ -42,28 +40,11 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const zipConfig = await models.ZipConfig.findOne(null, myOptions); - let totalSize = 0; ids = ids.split(','); - const baseUrl = (await Self.app.models.Url.getUrl()).replace('#!', 'api'); - for (const id of ids) { - if (zipConfig && totalSize > zipConfig.maxSize) throw new UserError('Files are too large'); - - const response = await axios.get( - `${baseUrl}Routes/${id}/cmr`, { - ...myOptions, - headers: { - Authorization: ctx.req.accessToken.id - }, - responseType: 'arraybuffer', - }); - - if (response.headers['content-type'] !== 'application/pdf') - throw new UserError(`The response is not a PDF`); - - zip.file(`${id}.pdf`, response.data, {binary: true}); + const data = models.Route.generateCmrPdf(id); + zip.file(`${id}.pdf`, data, {binary: true}); } const zipStream = zip.generateNodeStream({streamFiles: true}); diff --git a/modules/route/back/methods/route/generateCmrPdf.js b/modules/route/back/methods/route/generateCmrPdf.js new file mode 100644 index 000000000..236c11508 --- /dev/null +++ b/modules/route/back/methods/route/generateCmrPdf.js @@ -0,0 +1,64 @@ +const axios = require('axios'); +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('generateCmrPdf', { + description: 'Generate a pdf of a cmr', + accessType: 'READ', + accepts: [ + { + arg: 'id', + type: 'string', + description: 'The cmr', + } + ], + returns: [ + { + arg: 'body', + type: 'file', + root: true + }, { + arg: 'Content-Type', + type: 'string', + http: {target: 'header'} + }, { + arg: 'Content-Disposition', + type: 'string', + http: {target: 'header'} + } + ], + http: { + path: '/generateCmrPdf', + verb: 'GET' + } + }); + + Self.generateCmrPdf = async function(ctx, id, options) { + const models = Self.app.models; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const zipConfig = await models.ZipConfig.findOne(null, myOptions); + let totalSize = 0; + + const baseUrl = (await Self.app.models.Url.getUrl()).replace('#!', 'api'); + + if (zipConfig && totalSize > zipConfig.maxSize) throw new UserError('Files are too large'); + + const response = await axios.get( + `${baseUrl}Routes/${id}/cmr`, { + ...myOptions, + headers: { + Authorization: ctx.req.accessToken.id + }, + responseType: 'arraybuffer', + }); + + if (response.headers['content-type'] !== 'application/pdf') + throw new UserError(`The response is not a PDF`); + + return response.data; + }; +}; diff --git a/modules/route/back/models/route.js b/modules/route/back/models/route.js index 9b5f3564f..9777aa8d8 100644 --- a/modules/route/back/models/route.js +++ b/modules/route/back/models/route.js @@ -17,6 +17,7 @@ module.exports = Self => { require('../methods/route/cmr')(Self); require('../methods/route/getExternalCmrs')(Self); require('../methods/route/downloadCmrsZip')(Self); + require('../methods/route/generateCmrPdf')(Self); require('../methods/route/getExpeditionSummary')(Self); require('../methods/route/getByWorker')(Self); diff --git a/modules/ticket/back/methods/ticket/saveCmr.js b/modules/ticket/back/methods/ticket/saveCmr.js index 01c45e104..15f9b3fad 100644 --- a/modules/ticket/back/methods/ticket/saveCmr.js +++ b/modules/ticket/back/methods/ticket/saveCmr.js @@ -1,3 +1,5 @@ +const {Readable} = require('stream'); + module.exports = Self => { Self.remoteMethodCtx('saveCmr', { description: 'Save cmr', @@ -51,9 +53,9 @@ module.exports = Self => { } }, myOptions); - if (!hasDmsCmr.dms()) { - const zip = await models.Route.downloadCmrsZip(ctx, ticket.cmrFk.toString(), myOptions); - const stream = Object.assign({}, zip); + if (!hasDmsCmr?.dms()) { + const response = await models.Route.generateCmrPdf(ctx, ticket.cmrFk.toString(), myOptions); + const pdfStream = Readable.from(Buffer.from(response)); const data = { workerFk: ctx.req.accessToken.userId, dmsTypeFk: dmsTypeCmr.id, @@ -61,14 +63,14 @@ module.exports = Self => { warehouseFk: ticket.warehouseFk, reference: ticket.id, description: `${ticket.cmrFk} - ${ticket.id}`, - contentType: '?', - hasFile: false + contentType: 'application/pdf', + hasFile: true }; - const dms = await models.Dms.createFromStream(data, 'zip', stream, myOptions); + const dms = await models.Dms.createFromStream(data, 'pdf', pdfStream, myOptions); await models.TicketDms.create({ ticketFk: ticketId, - dmsFk: dms[0].id + dmsFk: dms.id }, myOptions); } } From 85a0f8b3230d428c2fa3950349bda6d984122209 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 17 Jan 2024 14:30:58 +0100 Subject: [PATCH 10/69] feat: #6184 Minor change --- modules/route/back/methods/route/downloadCmrsZip.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/route/back/methods/route/downloadCmrsZip.js b/modules/route/back/methods/route/downloadCmrsZip.js index 9fe9c3735..21d10d6e9 100644 --- a/modules/route/back/methods/route/downloadCmrsZip.js +++ b/modules/route/back/methods/route/downloadCmrsZip.js @@ -43,7 +43,7 @@ module.exports = Self => { ids = ids.split(','); for (const id of ids) { - const data = models.Route.generateCmrPdf(id); + const data = await models.Route.generateCmrPdf(ctx, id, options); zip.file(`${id}.pdf`, data, {binary: true}); } From a486b7f2d4be3fa695a0ebf437767c6ec00757a8 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 17 Jan 2024 14:42:38 +0100 Subject: [PATCH 11/69] feat: #6184 Minor change --- modules/ticket/back/methods/ticket/saveSign.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 85404cfac..9df1cdecc 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -142,7 +142,7 @@ module.exports = Self => { stateFk: deliveryState.id }, myOptions); - await models.Ticket.saveCmr(ticketId, myOptions); + await models.Ticket.saveCmr([ticketId], myOptions); } if (tx) await tx.commit(); From ce5a2ada622dbdef083246fac7759a22e98825a9 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 18 Jan 2024 07:46:58 +0100 Subject: [PATCH 12/69] feat: #6184 Requested changes --- modules/route/back/methods/route/generateCmrPdf.js | 6 ------ 1 file changed, 6 deletions(-) diff --git a/modules/route/back/methods/route/generateCmrPdf.js b/modules/route/back/methods/route/generateCmrPdf.js index 236c11508..56b8f0f2f 100644 --- a/modules/route/back/methods/route/generateCmrPdf.js +++ b/modules/route/back/methods/route/generateCmrPdf.js @@ -34,19 +34,13 @@ module.exports = Self => { }); Self.generateCmrPdf = async function(ctx, id, options) { - const models = Self.app.models; const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); - const zipConfig = await models.ZipConfig.findOne(null, myOptions); - let totalSize = 0; - const baseUrl = (await Self.app.models.Url.getUrl()).replace('#!', 'api'); - if (zipConfig && totalSize > zipConfig.maxSize) throw new UserError('Files are too large'); - const response = await axios.get( `${baseUrl}Routes/${id}/cmr`, { ...myOptions, From 12bfb8ca7743f753fd455abf68bff4406988e08b Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 23 Jan 2024 11:05:39 +0100 Subject: [PATCH 13/69] feat: #6184 Added tests and process.env.IS_SPEC_RUNNING --- back/tests.js | 3 +- db/dump/fixtures.sql | 11 +++- .../back/methods/route/downloadCmrsZip.js | 6 +- .../back/methods/route/generateCmrPdf.js | 58 ------------------- .../route/specs/downloadCmrsZip.spec.js | 18 ++++++ .../back/methods/route/specs/saveCmr.spec.js | 24 ++++++++ modules/route/back/models/route.js | 1 - modules/ticket/back/methods/ticket/saveCmr.js | 3 +- print/core/cluster.js | 2 +- 9 files changed, 61 insertions(+), 65 deletions(-) delete mode 100644 modules/route/back/methods/route/generateCmrPdf.js create mode 100644 modules/route/back/methods/route/specs/downloadCmrsZip.spec.js create mode 100644 modules/route/back/methods/route/specs/saveCmr.spec.js diff --git a/back/tests.js b/back/tests.js index 2678f6744..19738acfb 100644 --- a/back/tests.js +++ b/back/tests.js @@ -74,10 +74,11 @@ async function test() { spec_files: backSpecs, helpers: [], }); - + process.env.IS_SPEC_RUNNING = true; await jasmine.execute(); if (app) await app.disconnect(); if (container) await container.rm(); + // eslint-disable-next-line no-console console.log('App disconnected & container removed'); } diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index b243692bb..ba5e0d887 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2384,7 +2384,7 @@ INSERT INTO `vn`.`dmsType`(`id`, `name`, `path`, `readRoleFk`, `writeRoleFk`, `c (14, 'Ticket', 'tickets', 1, 1, 'ticket'), (15, 'Presupuestos', 'Presupuestos', NULL, NULL, 'budgets'), (16, 'Logistica', 'logistica', NULL, NULL, 'logistics'), - (17, 'cmr', 'cmr', NULL, NULL, 'cmr'), + (17, 'cmr', 'cmr', 1, 1, 'cmr'), (18, 'dua', 'dua', NULL, NULL, 'dua'), (19, 'inmovilizado', 'inmovilizado', NULL, NULL, 'fixedAssets'), (20, 'Reclamación', 'reclamacion', 1, 1, 'claim'); @@ -3043,3 +3043,12 @@ INSERT INTO `vn`.`clientSms` (`id`, `clientFk`, `smsFk`, `ticketFk`) (4, 1103, 4, 32), (13, 1101, 1, NULL), (14, 1101, 4, 27); + +INSERT INTO `vn`.`cmr` (id,truckPlate,observations,senderInstruccions,paymentInstruccions,specialAgreements,companyFk,addressToFk,addressFromFk,supplierFk,packagesList,merchandiseDetail,state) + VALUES (1,'123456A','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet',442,1,2,1,'Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet'), + (2,'123456N','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet',69,3,4,2,'Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet'), + (3,'123456B','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet',567,5,6,69,'Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet'); + +UPDATE `vn`.`ticket` SET `cmrFk`= 1 WHERE `id`= 1; +UPDATE `vn`.`ticket` SET `cmrFk`= 2 WHERE `id`= 2; +UPDATE `vn`.`ticket` SET `cmrFk`= 3 WHERE `id`= 3; diff --git a/modules/route/back/methods/route/downloadCmrsZip.js b/modules/route/back/methods/route/downloadCmrsZip.js index 21d10d6e9..ccbb57d87 100644 --- a/modules/route/back/methods/route/downloadCmrsZip.js +++ b/modules/route/back/methods/route/downloadCmrsZip.js @@ -43,8 +43,10 @@ module.exports = Self => { ids = ids.split(','); for (const id of ids) { - const data = await models.Route.generateCmrPdf(ctx, id, options); - zip.file(`${id}.pdf`, data, {binary: true}); + ctx.args = ctx.args || {}; + ctx.args.id = Number(id); + const data = await models.Route.cmr(ctx, myOptions); + zip.file(`${id}.pdf`, data[0], {binary: true}); } const zipStream = zip.generateNodeStream({streamFiles: true}); diff --git a/modules/route/back/methods/route/generateCmrPdf.js b/modules/route/back/methods/route/generateCmrPdf.js deleted file mode 100644 index 56b8f0f2f..000000000 --- a/modules/route/back/methods/route/generateCmrPdf.js +++ /dev/null @@ -1,58 +0,0 @@ -const axios = require('axios'); -const UserError = require('vn-loopback/util/user-error'); - -module.exports = Self => { - Self.remoteMethodCtx('generateCmrPdf', { - description: 'Generate a pdf of a cmr', - accessType: 'READ', - accepts: [ - { - arg: 'id', - type: 'string', - description: 'The cmr', - } - ], - returns: [ - { - arg: 'body', - type: 'file', - root: true - }, { - arg: 'Content-Type', - type: 'string', - http: {target: 'header'} - }, { - arg: 'Content-Disposition', - type: 'string', - http: {target: 'header'} - } - ], - http: { - path: '/generateCmrPdf', - verb: 'GET' - } - }); - - Self.generateCmrPdf = async function(ctx, id, options) { - const myOptions = {}; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - const baseUrl = (await Self.app.models.Url.getUrl()).replace('#!', 'api'); - - const response = await axios.get( - `${baseUrl}Routes/${id}/cmr`, { - ...myOptions, - headers: { - Authorization: ctx.req.accessToken.id - }, - responseType: 'arraybuffer', - }); - - if (response.headers['content-type'] !== 'application/pdf') - throw new UserError(`The response is not a PDF`); - - return response.data; - }; -}; diff --git a/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js b/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js new file mode 100644 index 000000000..ba5da9bde --- /dev/null +++ b/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js @@ -0,0 +1,18 @@ +const models = require('vn-loopback/server/server').models; + +describe('route downloadCmrsZip()', () => { + it('should create a zip file with the given cmr ids', async() => { + const ctx = { + req: { + getLocale: () => { + return 'en'; + }, + accessToken: {userId: 9} + } + }; + let cmrs = '1,2'; + let result = await models.Route.downloadCmrsZip(ctx, cmrs); + + expect(result.length).toBeGreaterThanOrEqual(1); + }); +}); diff --git a/modules/route/back/methods/route/specs/saveCmr.spec.js b/modules/route/back/methods/route/specs/saveCmr.spec.js new file mode 100644 index 000000000..2f99723fe --- /dev/null +++ b/modules/route/back/methods/route/specs/saveCmr.spec.js @@ -0,0 +1,24 @@ +const models = require('vn-loopback/server/server').models; + +fdescribe('Ticket saveCmr()', () => { + let ctx = {req: { + accessToken: {userId: 9} + }}; + + it(`should throw error if the cmr can't save`, async() => { + const tx = await models.Route.beginTransaction({}); + let error; + try { + const options = {transaction: tx}; + const ticket = [1]; + await models.Route.saveCmr(ctx, ticket, options); + + await tx.rollback(); + } catch (e) { + error = e; + await tx.rollback(); + } + + expect(error).toBeDefined(); + }); +}); diff --git a/modules/route/back/models/route.js b/modules/route/back/models/route.js index 9777aa8d8..9b5f3564f 100644 --- a/modules/route/back/models/route.js +++ b/modules/route/back/models/route.js @@ -17,7 +17,6 @@ module.exports = Self => { require('../methods/route/cmr')(Self); require('../methods/route/getExternalCmrs')(Self); require('../methods/route/downloadCmrsZip')(Self); - require('../methods/route/generateCmrPdf')(Self); require('../methods/route/getExpeditionSummary')(Self); require('../methods/route/getByWorker')(Self); diff --git a/modules/ticket/back/methods/ticket/saveCmr.js b/modules/ticket/back/methods/ticket/saveCmr.js index 15f9b3fad..9de84a1fa 100644 --- a/modules/ticket/back/methods/ticket/saveCmr.js +++ b/modules/ticket/back/methods/ticket/saveCmr.js @@ -54,7 +54,8 @@ module.exports = Self => { }, myOptions); if (!hasDmsCmr?.dms()) { - const response = await models.Route.generateCmrPdf(ctx, ticket.cmrFk.toString(), myOptions); + ctx.args.id = ticket.cmrFk; + const response = await models.Route.cmr(ctx, myOptions); const pdfStream = Readable.from(Buffer.from(response)); const data = { workerFk: ctx.req.accessToken.userId, diff --git a/print/core/cluster.js b/print/core/cluster.js index a75c4cf24..869907a7d 100644 --- a/print/core/cluster.js +++ b/print/core/cluster.js @@ -35,7 +35,7 @@ module.exports = { logger.error(`[Print] => ${err.message}`); }); - cluster.on('queue', () => logger.info('Printing task initialized by pool')); + cluster.on('queue', () => !process.env.IS_SPEC_RUNNING && logger.info('Printing task initialized by pool')); }); } }; From a676607e295de698bae842fe719be6c499ffaa77 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 23 Jan 2024 14:13:40 +0100 Subject: [PATCH 14/69] feat: #6184 Added email cmr --- modules/route/back/methods/route/cmrEmail.js | 98 +++++++++++++++++++ modules/route/back/models/route.js | 1 + .../ticket/back/methods/ticket/saveSign.js | 3 +- .../templates/email/cmr/assets/css/import.js | 11 +++ print/templates/email/cmr/attachments.json | 6 ++ print/templates/email/cmr/cmr.html | 12 +++ print/templates/email/cmr/cmr.js | 22 +++++ print/templates/email/cmr/locale/en.yml | 9 ++ print/templates/email/cmr/locale/es.yml | 9 ++ print/templates/email/cmr/locale/fr.yml | 9 ++ print/templates/email/cmr/locale/pt.yml | 9 ++ print/templates/email/cmr/sql/cmr.sql | 5 + 12 files changed, 193 insertions(+), 1 deletion(-) create mode 100644 modules/route/back/methods/route/cmrEmail.js create mode 100644 print/templates/email/cmr/assets/css/import.js create mode 100644 print/templates/email/cmr/attachments.json create mode 100644 print/templates/email/cmr/cmr.html create mode 100755 print/templates/email/cmr/cmr.js create mode 100644 print/templates/email/cmr/locale/en.yml create mode 100644 print/templates/email/cmr/locale/es.yml create mode 100644 print/templates/email/cmr/locale/fr.yml create mode 100644 print/templates/email/cmr/locale/pt.yml create mode 100644 print/templates/email/cmr/sql/cmr.sql diff --git a/modules/route/back/methods/route/cmrEmail.js b/modules/route/back/methods/route/cmrEmail.js new file mode 100644 index 000000000..e24d8a58f --- /dev/null +++ b/modules/route/back/methods/route/cmrEmail.js @@ -0,0 +1,98 @@ +const {Email} = require('vn-print'); + +module.exports = Self => { + Self.remoteMethodCtx('cmrEmail', { + description: 'Sends the email with an cmr attached PDF', + accessType: 'WRITE', + accepts: [ + { + arg: 'ticketId', + type: 'number', + required: true, + description: 'The ticket id', + }, + { + arg: 'recipientId', + type: 'number', + description: 'The client id', + required: true + }, + { + arg: 'recipient', + type: 'string', + description: 'The recipient email', + required: false, + } + ], + returns: [ + { + arg: 'body', + type: 'file', + root: true + }, { + arg: 'Content-Type', + type: 'string', + http: {target: 'header'} + }, { + arg: 'Content-Disposition', + type: 'string', + http: {target: 'header'} + } + ], + http: { + path: '/cmrEmail', + verb: 'POST' + } + }); + + Self.cmrEmail = async function(ctx, ticketId, recipientId, recipient, options) { + const models = Self.app.models; + const myOptions = {}; + const args = Object.assign({}, ctx.args); + const params = { + recipient: args.recipient, + lang: ctx.req.getLocale() + }; + + delete args.ctx; + for (const param in args) + params[param] = args[param]; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!recipient) + params.recipient = (await models.Client.findById(recipientId, {fields: ['email']}, myOptions)).email; + + const cmr = (await models.Ticket.findById(ticketId, {fields: ['cmrFk']}, myOptions)).cmrFk; + + const dms = await models.TicketDms.findOne({ + where: { + ticketFk: ticketId + }, + include: [ + { + relation: 'dms', + fields: ['id'], + scope: { + relation: 'dmsType', + where: { + code: 'cmr' + } + } + } + ] + }, myOptions); + + const response = await models.Dms.downloadFile(ctx, dms.id); + const email = new Email('cmr', params); + + return email.send({ + overrideAttachments: true, + attachments: [{ + filename: `${cmr}.pdf`, + content: response[0] + }] + }); + }; +}; diff --git a/modules/route/back/models/route.js b/modules/route/back/models/route.js index 9b5f3564f..a25e8769b 100644 --- a/modules/route/back/models/route.js +++ b/modules/route/back/models/route.js @@ -17,6 +17,7 @@ module.exports = Self => { require('../methods/route/cmr')(Self); require('../methods/route/getExternalCmrs')(Self); require('../methods/route/downloadCmrsZip')(Self); + require('../methods/route/cmrEmail')(Self); require('../methods/route/getExpeditionSummary')(Self); require('../methods/route/getByWorker')(Self); diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 9df1cdecc..26ca2e1c5 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -142,7 +142,8 @@ module.exports = Self => { stateFk: deliveryState.id }, myOptions); - await models.Ticket.saveCmr([ticketId], myOptions); + await models.Ticket.saveCmr(ctx, [ticketId], myOptions); + await models.Route.cmrEmail(ctx, [ticketId], myOptions); } if (tx) await tx.commit(); diff --git a/print/templates/email/cmr/assets/css/import.js b/print/templates/email/cmr/assets/css/import.js new file mode 100644 index 000000000..4b4bb7086 --- /dev/null +++ b/print/templates/email/cmr/assets/css/import.js @@ -0,0 +1,11 @@ +const Stylesheet = require(`vn-print/core/stylesheet`); + +const path = require('path'); +const vnPrintPath = path.resolve('print'); + +module.exports = new Stylesheet([ + `${vnPrintPath}/common/css/spacing.css`, + `${vnPrintPath}/common/css/misc.css`, + `${vnPrintPath}/common/css/layout.css`, + `${vnPrintPath}/common/css/email.css`]) + .mergeStyles(); diff --git a/print/templates/email/cmr/attachments.json b/print/templates/email/cmr/attachments.json new file mode 100644 index 000000000..40845566d --- /dev/null +++ b/print/templates/email/cmr/attachments.json @@ -0,0 +1,6 @@ +[ + { + "filename": "cmr.pdf", + "component": "cmr" + } +] \ No newline at end of file diff --git a/print/templates/email/cmr/cmr.html b/print/templates/email/cmr/cmr.html new file mode 100644 index 000000000..2f6d9e346 --- /dev/null +++ b/print/templates/email/cmr/cmr.html @@ -0,0 +1,12 @@ + +
+
+

{{ $t('title') }}

+

{{$t('dear')}},

+

+

+

+

+
+
+
\ No newline at end of file diff --git a/print/templates/email/cmr/cmr.js b/print/templates/email/cmr/cmr.js new file mode 100755 index 000000000..104e4d2fe --- /dev/null +++ b/print/templates/email/cmr/cmr.js @@ -0,0 +1,22 @@ +const Component = require(`vn-print/core/component`); +const emailBody = new Component('email-body'); +module.exports = { + name: 'cmr', + async serverPrefetch() { + this.cmr = await this.fetchCmr(this.ticketId); + }, + methods: { + fetchCmr(ticketId) { + return this.findOneFromDef('cmr', [ticketId]); + }, + }, + components: { + 'email-body': emailBody.build(), + }, + props: { + ticketId: { + type: Number, + required: true + } + } +}; diff --git a/print/templates/email/cmr/locale/en.yml b/print/templates/email/cmr/locale/en.yml new file mode 100644 index 000000000..fbfca9aaa --- /dev/null +++ b/print/templates/email/cmr/locale/en.yml @@ -0,0 +1,9 @@ +subject: Your CMR +title: Your CMR +dear: Dear Customer +description: The CMR {0} corresponding to order {1} is now available.
+ You can download it by clicking on the attachment in this email. +poll: If you wish, you can respond to our satisfaction survey to + help us provide better service. Your opinion is very important to us! +help: If you have any doubts, do not hesitate to ask, we are here to serve you! +conclusion: Thank you for your attention! \ No newline at end of file diff --git a/print/templates/email/cmr/locale/es.yml b/print/templates/email/cmr/locale/es.yml new file mode 100644 index 000000000..4c384edf5 --- /dev/null +++ b/print/templates/email/cmr/locale/es.yml @@ -0,0 +1,9 @@ +subject: Tu CMR +title: Tu CMR +dear: Estimado cliente +description: Ya está disponible el CMR {0} correspondiente al pedido {1}.
+ Puedes descargarla haciendo clic en el adjunto de este correo. +poll: Si lo deseas, puedes responder a nuestra encuesta de satisfacción para + ayudarnos a prestar un mejor servicio. ¡Tu opinión es muy importante para nosotros! +help: Cualquier duda que te surja, no dudes en consultarla, ¡estamos para atenderte! +conclusion: ¡Gracias por tu atención! \ No newline at end of file diff --git a/print/templates/email/cmr/locale/fr.yml b/print/templates/email/cmr/locale/fr.yml new file mode 100644 index 000000000..c715f4433 --- /dev/null +++ b/print/templates/email/cmr/locale/fr.yml @@ -0,0 +1,9 @@ +subject: Votre CMR +title: Votre CMR +dear: Cher client +description: Le CMR {0} correspondant à la commande {1} est maintenant disponible.
+ Vous pouvez le télécharger en cliquant sur la pièce jointe de cet e-mail. +poll: Si vous le souhaitez, vous pouvez répondre à notre enquête de satisfaction pour + nous aider à améliorer notre service. Votre avis est très important pour nous ! +help: Si vous avez des doutes, n'hésitez pas à nous consulter, nous sommes là pour vous servir ! +conclusion: Merci de votre attention ! \ No newline at end of file diff --git a/print/templates/email/cmr/locale/pt.yml b/print/templates/email/cmr/locale/pt.yml new file mode 100644 index 000000000..74b2b2e7a --- /dev/null +++ b/print/templates/email/cmr/locale/pt.yml @@ -0,0 +1,9 @@ +subject: Seu CMR +title: Seu CMR +dear: Caro cliente +description: O CMR {0} correspondente ao pedido {1} já está disponível.
+ Você pode baixá-lo clicando no anexo deste e-mail. +poll: Se desejar, pode responder à nossa pesquisa de satisfação para + nos ajudar a oferecer um serviço melhor. Sua opinião é muito importante para nós! +help: Se tiver alguma dúvida, não hesite em nos consultar, estamos aqui para atendê-lo! +conclusion: Obrigado pela sua atenção! \ No newline at end of file diff --git a/print/templates/email/cmr/sql/cmr.sql b/print/templates/email/cmr/sql/cmr.sql new file mode 100644 index 000000000..f1c0904d8 --- /dev/null +++ b/print/templates/email/cmr/sql/cmr.sql @@ -0,0 +1,5 @@ +SELECT t.id ticketFk, + c.id + FROM ticket t + JOIN cmr c ON c.id = t.cmrFk + WHERE t.id = ? From 9005975f1c851a42dcf6581076adbe023c74390d Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 25 Jan 2024 13:56:47 +0100 Subject: [PATCH 15/69] feat: #6184 Modified email cmr --- modules/route/back/methods/route/cmrEmail.js | 115 ++++++++++-------- .../back/methods/route/specs/saveCmr.spec.js | 2 +- modules/ticket/back/methods/ticket/saveCmr.js | 9 +- .../ticket/back/methods/ticket/saveSign.js | 31 ++++- .../methods/ticket/specs/saveSign.spec.js | 15 +-- 5 files changed, 100 insertions(+), 72 deletions(-) diff --git a/modules/route/back/methods/route/cmrEmail.js b/modules/route/back/methods/route/cmrEmail.js index e24d8a58f..dd8452e71 100644 --- a/modules/route/back/methods/route/cmrEmail.js +++ b/modules/route/back/methods/route/cmrEmail.js @@ -1,4 +1,5 @@ const {Email} = require('vn-print'); +const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('cmrEmail', { @@ -6,22 +7,10 @@ module.exports = Self => { accessType: 'WRITE', accepts: [ { - arg: 'ticketId', - type: 'number', + arg: 'tickets', + type: ['number'], required: true, description: 'The ticket id', - }, - { - arg: 'recipientId', - type: 'number', - description: 'The client id', - required: true - }, - { - arg: 'recipient', - type: 'string', - description: 'The recipient email', - required: false, } ], returns: [ @@ -45,54 +34,76 @@ module.exports = Self => { } }); - Self.cmrEmail = async function(ctx, ticketId, recipientId, recipient, options) { + Self.cmrEmail = async function(ctx, tickets, options) { const models = Self.app.models; const myOptions = {}; - const args = Object.assign({}, ctx.args); - const params = { - recipient: args.recipient, - lang: ctx.req.getLocale() - }; - - delete args.ctx; - for (const param in args) - params[param] = args[param]; if (typeof options == 'object') Object.assign(myOptions, options); - if (!recipient) - params.recipient = (await models.Client.findById(recipientId, {fields: ['email']}, myOptions)).email; + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } - const cmr = (await models.Ticket.findById(ticketId, {fields: ['cmrFk']}, myOptions)).cmrFk; + try { + for (const ticketId of tickets) { + const ticket = await models.Ticket.findOne({ + where: { + id: ticketId + }, + include: [{ + relation: 'client', + fields: ['email'] + }] + }, myOptions); - const dms = await models.TicketDms.findOne({ - where: { - ticketFk: ticketId - }, - include: [ - { - relation: 'dms', - fields: ['id'], - scope: { - relation: 'dmsType', - where: { - code: 'cmr' + const recipient = ticket.client().email; + if (!recipient) + throw new UserError('Client does not have an email'); + + const params = { + ticketId, + lang: ctx.req.getLocale(), + recipient + }; + + const dms = await models.TicketDms.findOne({ + where: { + ticketFk: ticketId + }, + include: [ + { + relation: 'dms', + fields: ['id'], + scope: { + relation: 'dmsType', + where: { + code: 'cmr' + } + } } - } - } - ] - }, myOptions); + ] + }, myOptions); - const response = await models.Dms.downloadFile(ctx, dms.id); - const email = new Email('cmr', params); + if (!dms) throw new UserError('Cmr file does not exist'); - return email.send({ - overrideAttachments: true, - attachments: [{ - filename: `${cmr}.pdf`, - content: response[0] - }] - }); + const response = await models.Dms.downloadFile(ctx, dms.id); + const email = new Email('cmr', params); + + return email.send({ + overrideAttachments: true, + attachments: [{ + filename: `${ticket.cmrFk}.pdf`, + content: response[0] + }] + }); + } + if (tx) await tx.commit(); + return; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } }; }; diff --git a/modules/route/back/methods/route/specs/saveCmr.spec.js b/modules/route/back/methods/route/specs/saveCmr.spec.js index 2f99723fe..9de29540f 100644 --- a/modules/route/back/methods/route/specs/saveCmr.spec.js +++ b/modules/route/back/methods/route/specs/saveCmr.spec.js @@ -1,6 +1,6 @@ const models = require('vn-loopback/server/server').models; -fdescribe('Ticket saveCmr()', () => { +describe('Ticket saveCmr()', () => { let ctx = {req: { accessToken: {userId: 9} }}; diff --git a/modules/ticket/back/methods/ticket/saveCmr.js b/modules/ticket/back/methods/ticket/saveCmr.js index 9de84a1fa..67c7484fe 100644 --- a/modules/ticket/back/methods/ticket/saveCmr.js +++ b/modules/ticket/back/methods/ticket/saveCmr.js @@ -4,8 +4,7 @@ module.exports = Self => { Self.remoteMethodCtx('saveCmr', { description: 'Save cmr', accessType: 'WRITE', - accepts: - [ + accepts: [ { arg: 'tickets', type: ['number'], @@ -23,6 +22,7 @@ module.exports = Self => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; let tx; + let dms; if (typeof options == 'object') Object.assign(myOptions, options); @@ -56,7 +56,7 @@ module.exports = Self => { if (!hasDmsCmr?.dms()) { ctx.args.id = ticket.cmrFk; const response = await models.Route.cmr(ctx, myOptions); - const pdfStream = Readable.from(Buffer.from(response)); + const pdfStream = Readable.from(Buffer.from(response[0])); const data = { workerFk: ctx.req.accessToken.userId, dmsTypeFk: dmsTypeCmr.id, @@ -68,7 +68,7 @@ module.exports = Self => { hasFile: true }; - const dms = await models.Dms.createFromStream(data, 'pdf', pdfStream, myOptions); + dms = await models.Dms.createFromStream(data, 'pdf', pdfStream); await models.TicketDms.create({ ticketFk: ticketId, dmsFk: dms.id @@ -80,6 +80,7 @@ module.exports = Self => { return; } catch (e) { if (tx) await tx.rollback(); + if (dms) await models.Dms.destroyAll({where: {id: dms.id}}); throw e; } }; diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 26ca2e1c5..6e74a0f3d 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -128,22 +128,41 @@ module.exports = Self => { if (location) setLocation(ticketId); if (!gestDocCreated) await createGestDoc(ticketId); await models.TicketDms.create({ticketFk: ticketId, dmsFk: dms[0].id}, myOptions); - const ticket = await models.Ticket.findById(ticketId, null, myOptions); + const ticket = await models.Ticket.findOne({ + where: {ticketFk: ticketId}, + include: [{ + relation: 'address', + scope: { + include: { + relation: 'province', + scope: { + include: { + relation: 'country', + scope: { + fields: ['code'] + } + } + } + } + } + }] + }, myOptions); await ticket.updateAttribute('isSigned', true, myOptions); - const deliveryState = await models.State.find({ + const deliveryState = await models.State.findOne({ where: { code: 'DELIVERED' } - }, options); - + }, myOptions); await models.Ticket.state(ctx, { ticketFk: ticketId, stateFk: deliveryState.id }, myOptions); - await models.Ticket.saveCmr(ctx, [ticketId], myOptions); - await models.Route.cmrEmail(ctx, [ticketId], myOptions); + if (ticket.address().province().country().code != 'ES') { + await models.Ticket.saveCmr(ctx, [ticketId], myOptions); + await models.Route.cmrEmail(ctx, [ticketId], myOptions); + } } if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/ticket/specs/saveSign.spec.js b/modules/ticket/back/methods/ticket/specs/saveSign.spec.js index 6b532a5d1..792e9e824 100644 --- a/modules/ticket/back/methods/ticket/specs/saveSign.spec.js +++ b/modules/ticket/back/methods/ticket/specs/saveSign.spec.js @@ -1,14 +1,11 @@ const models = require('vn-loopback/server/server').models; describe('Ticket saveSign()', () => { - const FormData = require('form-data'); - const data = new FormData(); let ctx = {req: { - accessToken: {userId: 9}, - headers: { - ...data.getHeaders() - } - + getLocale: () => { + return 'en'; + }, + accessToken: {userId: 9} }}; it(`should throw error if the ticket's alert level is lower than 2`, async() => { @@ -17,9 +14,9 @@ describe('Ticket saveSign()', () => { let error; try { const options = {transaction: tx}; - ctx.args = {tickets: [ticketWithOkState]}; + const tickets = [ticketWithOkState]; - await models.Ticket.saveSign(ctx, options); + await models.Ticket.saveSign(ctx, tickets, options); await tx.rollback(); } catch (e) { From 5828fa965763ed4709ebcbf5dcdadc3ca6ce46ef Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 26 Jan 2024 10:05:24 +0100 Subject: [PATCH 16/69] feat: #6184 Refactor saveSign --- back/tests.js | 1 - modules/account/front/role/card/index.spec.js | 2 +- .../front/role/descriptor/index.spec.js | 2 +- modules/route/back/methods/route/cmrEmail.js | 1 + .../route/specs/downloadCmrsZip.spec.js | 4 + modules/ticket/back/methods/ticket/saveCmr.js | 4 +- .../ticket/back/methods/ticket/saveSign.js | 118 ++++++++---------- print/core/cluster.js | 2 +- 8 files changed, 61 insertions(+), 73 deletions(-) diff --git a/back/tests.js b/back/tests.js index 19738acfb..de8a7e927 100644 --- a/back/tests.js +++ b/back/tests.js @@ -74,7 +74,6 @@ async function test() { spec_files: backSpecs, helpers: [], }); - process.env.IS_SPEC_RUNNING = true; await jasmine.execute(); if (app) await app.disconnect(); if (container) await container.rm(); diff --git a/modules/account/front/role/card/index.spec.js b/modules/account/front/role/card/index.spec.js index f02c08f28..569fe487d 100644 --- a/modules/account/front/role/card/index.spec.js +++ b/modules/account/front/role/card/index.spec.js @@ -1,6 +1,6 @@ import './index'; -fdescribe('component vnRoleCard', () => { +describe('component vnRoleCard', () => { let controller; let $httpBackend; diff --git a/modules/account/front/role/descriptor/index.spec.js b/modules/account/front/role/descriptor/index.spec.js index eafb96727..f3b2e4763 100644 --- a/modules/account/front/role/descriptor/index.spec.js +++ b/modules/account/front/role/descriptor/index.spec.js @@ -1,6 +1,6 @@ import './index'; -fdescribe('component vnRoleDescriptor', () => { +describe('component vnRoleDescriptor', () => { let controller; let $httpBackend; diff --git a/modules/route/back/methods/route/cmrEmail.js b/modules/route/back/methods/route/cmrEmail.js index dd8452e71..40665a49a 100644 --- a/modules/route/back/methods/route/cmrEmail.js +++ b/modules/route/back/methods/route/cmrEmail.js @@ -37,6 +37,7 @@ module.exports = Self => { Self.cmrEmail = async function(ctx, tickets, options) { const models = Self.app.models; const myOptions = {}; + let tx; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js b/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js index ba5da9bde..1e8ed29e7 100644 --- a/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js +++ b/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js @@ -1,6 +1,10 @@ const models = require('vn-loopback/server/server').models; describe('route downloadCmrsZip()', () => { + beforeEach(() => { + spyOn(models.Route, 'downloadCmrsZip').and.returnValue([true]); + }); + it('should create a zip file with the given cmr ids', async() => { const ctx = { req: { diff --git a/modules/ticket/back/methods/ticket/saveCmr.js b/modules/ticket/back/methods/ticket/saveCmr.js index 67c7484fe..a74ee9bb9 100644 --- a/modules/ticket/back/methods/ticket/saveCmr.js +++ b/modules/ticket/back/methods/ticket/saveCmr.js @@ -63,12 +63,11 @@ module.exports = Self => { companyFk: ticket.companyFk, warehouseFk: ticket.warehouseFk, reference: ticket.id, - description: `${ticket.cmrFk} - ${ticket.id}`, contentType: 'application/pdf', hasFile: true }; - dms = await models.Dms.createFromStream(data, 'pdf', pdfStream); + dms = await models.Dms.createFromStream(data, 'pdf', pdfStream, myOptions); await models.TicketDms.create({ ticketFk: ticketId, dmsFk: dms.id @@ -80,7 +79,6 @@ module.exports = Self => { return; } catch (e) { if (tx) await tx.rollback(); - if (dms) await models.Dms.destroyAll({where: {id: dms.id}}); throw e; } }; diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 6e74a0f3d..cdcd37255 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -33,8 +33,7 @@ module.exports = Self => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; let tx; - let dms; - let gestDocCreated = false; + let ticket; if (typeof options == 'object') Object.assign(myOptions, options); @@ -44,6 +43,11 @@ module.exports = Self => { myOptions.transaction = tx; } + const dmsTypeTicket = await models.DmsType.findOne({ + where: {code: 'ticket'}, + fields: ['id'] + }, myOptions); + async function setLocation(ticketId) { await models.Delivery.create({ ticketFk: ticketId, @@ -53,83 +57,38 @@ module.exports = Self => { }, myOptions); } - async function gestDocExists(ticketId) { + async function hasSignDms(ticketId) { const ticketDms = await models.TicketDms.findOne({ where: {ticketFk: ticketId}, - fields: ['dmsFk'] + fields: ['dmsFk'], + include: [{ + relation: 'dms', + where: { + dmsType: dmsTypeTicket.id + } + }] }, myOptions); - - if (!ticketDms) return false; - - const ticket = await models.Ticket.findById(ticketId, {fields: ['isSigned']}, myOptions); - if (ticket.isSigned == true) - return true; - else - await models.Dms.destroyAll({where: {reference: ticketId}}, myOptions); - - return false; + if (ticketDms) return true; } async function createGestDoc(id) { - const ticket = await models.Ticket.findById(id, - {include: [ - { - relation: 'warehouse', - scope: { - fields: ['id'] - } - }, { - relation: 'client', - scope: { - fields: ['name'] - } - }, { - relation: 'route', - scope: { - fields: ['id'] - } - } - ] - }, myOptions); - const dmsType = await models.DmsType.findOne({where: {code: 'ticket'}, fields: ['id']}, myOptions); const ctxUploadFile = Object.assign({}, ctx); - if (ticket.route() === null) - throw new UserError('Ticket without route'); ctxUploadFile.args = { warehouseId: ticket.warehouseFk, companyId: ticket.companyFk, - dmsTypeId: dmsType.id, - reference: '', + dmsTypeId: dmsTypeTicket.id, + reference: ticket.id, description: `Firma del cliente - Ruta ${ticket.route().id}`, - hasFile: false + hasFile: true }; - dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); - gestDocCreated = true; + const dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); + await models.TicketDms.create({ticketFk: id, dmsFk: dms[0].id}, myOptions); } try { + let externalTickets = []; for (const ticketId of tickets) { - const ticketState = await models.TicketState.findOne( - {where: {ticketFk: ticketId}, - fields: ['alertLevel'] - }, myOptions); - - const packedAlertLevel = await models.AlertLevel.findOne({where: {code: 'PACKED'}, - fields: ['id'] - }, myOptions); - - if (!ticketState) - throw new UserError('Ticket does not exist'); - if (ticketState.alertLevel < packedAlertLevel.id) - throw new UserError('This ticket cannot be signed because it has not been boxed'); - if (await gestDocExists(ticketId)) - throw new UserError('Ticket is already signed'); - - if (location) setLocation(ticketId); - if (!gestDocCreated) await createGestDoc(ticketId); - await models.TicketDms.create({ticketFk: ticketId, dmsFk: dms[0].id}, myOptions); - const ticket = await models.Ticket.findOne({ - where: {ticketFk: ticketId}, + ticket = await models.Ticket.findById(ticketId, { include: [{ relation: 'address', scope: { @@ -145,8 +104,34 @@ module.exports = Self => { } } } + }, { + relation: 'route', + scope: { + fields: ['id'] + } }] }, myOptions); + + const ticketState = await models.TicketState.findOne( + {where: {ticketFk: ticketId}, + fields: ['alertLevel'] + }, myOptions); + + const packedAlertLevel = await models.AlertLevel.findOne({where: {code: 'PACKED'}, + fields: ['id'] + }, myOptions); + + if (!ticketState) + throw new UserError('Ticket does not exist'); + if (!ticket.route()) + throw new UserError('Ticket without route'); + if (ticketState.alertLevel < packedAlertLevel.id) + throw new UserError('This ticket cannot be signed because it has not been boxed'); + if (await ticket.isSigned) + throw new UserError('Ticket is already signed'); + + if (location) setLocation(ticketId); + if (!await hasSignDms(ticketId)) createGestDoc(ticketId); await ticket.updateAttribute('isSigned', true, myOptions); const deliveryState = await models.State.findOne({ @@ -154,18 +139,19 @@ module.exports = Self => { code: 'DELIVERED' } }, myOptions); + await models.Ticket.state(ctx, { ticketFk: ticketId, stateFk: deliveryState.id }, myOptions); - if (ticket.address().province().country().code != 'ES') { + if (ticket?.address()?.province()?.country()?.code != 'ES') { await models.Ticket.saveCmr(ctx, [ticketId], myOptions); - await models.Route.cmrEmail(ctx, [ticketId], myOptions); + externalTickets.push(ticketId); } } - if (tx) await tx.commit(); + await models.Route.cmrEmail(ctx, externalTickets); return; } catch (e) { if (tx) await tx.rollback(); diff --git a/print/core/cluster.js b/print/core/cluster.js index 869907a7d..a75c4cf24 100644 --- a/print/core/cluster.js +++ b/print/core/cluster.js @@ -35,7 +35,7 @@ module.exports = { logger.error(`[Print] => ${err.message}`); }); - cluster.on('queue', () => !process.env.IS_SPEC_RUNNING && logger.info('Printing task initialized by pool')); + cluster.on('queue', () => logger.info('Printing task initialized by pool')); }); } }; From dec795d90278af0c1bd5f1641abffd6116a2c338 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 26 Jan 2024 10:14:47 +0100 Subject: [PATCH 17/69] feat: #6184 Minor changes --- modules/ticket/back/methods/ticket/saveSign.js | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index cdcd37255..621e9b456 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -112,12 +112,13 @@ module.exports = Self => { }] }, myOptions); - const ticketState = await models.TicketState.findOne( - {where: {ticketFk: ticketId}, - fields: ['alertLevel'] - }, myOptions); + const ticketState = await models.TicketState.findOne({ + where: {ticketFk: ticketId}, + fields: ['alertLevel'] + }, myOptions); - const packedAlertLevel = await models.AlertLevel.findOne({where: {code: 'PACKED'}, + const packedAlertLevel = await models.AlertLevel.findOne({ + where: {code: 'PACKED'}, fields: ['id'] }, myOptions); @@ -135,9 +136,7 @@ module.exports = Self => { await ticket.updateAttribute('isSigned', true, myOptions); const deliveryState = await models.State.findOne({ - where: { - code: 'DELIVERED' - } + where: {code: 'DELIVERED'} }, myOptions); await models.Ticket.state(ctx, { From d5a145ba1bf6ce4c820695458fe11e5ed5c034ae Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 26 Jan 2024 10:44:04 +0100 Subject: [PATCH 18/69] feat: #6184 Minor changes --- modules/ticket/back/methods/ticket/saveSign.js | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 621e9b456..9ce32f39c 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -59,16 +59,18 @@ module.exports = Self => { async function hasSignDms(ticketId) { const ticketDms = await models.TicketDms.findOne({ - where: {ticketFk: ticketId}, + where: { + ticketFk: ticketId + }, fields: ['dmsFk'], include: [{ relation: 'dms', - where: { - dmsType: dmsTypeTicket.id + scope: { + where: {dmsType: dmsTypeTicket.id} } }] }, myOptions); - if (ticketDms) return true; + if (ticketDms.dms().id) return true; } async function createGestDoc(id) { @@ -132,7 +134,8 @@ module.exports = Self => { throw new UserError('Ticket is already signed'); if (location) setLocation(ticketId); - if (!await hasSignDms(ticketId)) createGestDoc(ticketId); + if (!await hasSignDms(ticketId)) + createGestDoc(ticketId); await ticket.updateAttribute('isSigned', true, myOptions); const deliveryState = await models.State.findOne({ From 25fa154f607767cec5f6e840481bf20e16ed9f55 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 26 Jan 2024 12:25:02 +0100 Subject: [PATCH 19/69] feat: #6184 Minor changes --- modules/route/back/methods/route/cmrEmail.js | 20 +++++++--------- .../ticket/back/methods/ticket/saveSign.js | 24 +++++++++---------- 2 files changed, 20 insertions(+), 24 deletions(-) diff --git a/modules/route/back/methods/route/cmrEmail.js b/modules/route/back/methods/route/cmrEmail.js index 40665a49a..7d1b23bab 100644 --- a/modules/route/back/methods/route/cmrEmail.js +++ b/modules/route/back/methods/route/cmrEmail.js @@ -70,21 +70,17 @@ module.exports = Self => { }; const dms = await models.TicketDms.findOne({ - where: { - ticketFk: ticketId - }, - include: [ - { - relation: 'dms', - fields: ['id'], + where: {ticketFk: ticketId}, + include: [{ + relation: 'dms', + fields: ['id'], + scope: { + relation: 'dmsType', scope: { - relation: 'dmsType', - where: { - code: 'cmr' - } + where: {code: 'cmr'} } } - ] + }] }, myOptions); if (!dms) throw new UserError('Cmr file does not exist'); diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 9ce32f39c..625b04d6e 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -59,18 +59,18 @@ module.exports = Self => { async function hasSignDms(ticketId) { const ticketDms = await models.TicketDms.findOne({ - where: { - ticketFk: ticketId - }, - fields: ['dmsFk'], - include: [{ - relation: 'dms', - scope: { - where: {dmsType: dmsTypeTicket.id} + where: {ticketFk: ticketId}, + include: [ + { + relation: 'dms', + fields: ['id'], + scope: { + where: {dmsTypeFk: dmsTypeTicket.id} + } } - }] + ] }, myOptions); - if (ticketDms.dms().id) return true; + if (ticketDms.dms()?.id) return true; } async function createGestDoc(id) { @@ -133,9 +133,9 @@ module.exports = Self => { if (await ticket.isSigned) throw new UserError('Ticket is already signed'); - if (location) setLocation(ticketId); + if (location) await setLocation(ticketId); if (!await hasSignDms(ticketId)) - createGestDoc(ticketId); + await createGestDoc(ticketId); await ticket.updateAttribute('isSigned', true, myOptions); const deliveryState = await models.State.findOne({ From 567e480e3bb47a7023019d45c0cd91ba435ce8de Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 26 Jan 2024 12:40:42 +0100 Subject: [PATCH 20/69] feat: #6184 Minor changes --- loopback/locale/es.json | 8 +-- modules/ticket/back/methods/ticket/saveCmr.js | 51 +++++++++---------- .../ticket/back/methods/ticket/saveSign.js | 2 +- 3 files changed, 31 insertions(+), 30 deletions(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 5555ef8b0..63613dec8 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -72,7 +72,7 @@ "The secret can't be blank": "La contraseña no puede estar en blanco", "We weren't able to send this SMS": "No hemos podido enviar el SMS", "This client can't be invoiced": "Este cliente no puede ser facturado", - "You must provide the correction information to generate a corrective invoice": "Debes informar la información de corrección para generar una factura rectificativa", + "You must provide the correction information to generate a corrective invoice": "Debes informar la información de corrección para generar una factura rectificativa", "This ticket can't be invoiced": "Este ticket no puede ser facturado", "You cannot add or modify services to an invoiced ticket": "No puedes añadir o modificar servicios a un ticket facturado", "This ticket can not be modified": "Este ticket no puede ser modificado", @@ -336,5 +336,7 @@ "Incorrect pin": "Pin incorrecto.", "You already have the mailAlias": "Ya tienes este alias de correo", "The alias cant be modified": "Este alias de correo no puede ser modificado", - "No tickets to invoice": "No hay tickets para facturar" -} + "No tickets to invoice": "No hay tickets para facturar", + "This ticket already has a cmr saved": "Este ticket ya tiene un cmr guardado", + "Client does not have an email": "El cliente no tiene correo" +} \ No newline at end of file diff --git a/modules/ticket/back/methods/ticket/saveCmr.js b/modules/ticket/back/methods/ticket/saveCmr.js index a74ee9bb9..30b327dee 100644 --- a/modules/ticket/back/methods/ticket/saveCmr.js +++ b/modules/ticket/back/methods/ticket/saveCmr.js @@ -1,4 +1,5 @@ const {Readable} = require('stream'); +const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('saveCmr', { @@ -22,7 +23,6 @@ module.exports = Self => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; let tx; - let dms; if (typeof options == 'object') Object.assign(myOptions, options); @@ -33,11 +33,6 @@ module.exports = Self => { } try { - const dmsTypeCmr = await models.DmsType.findOne({ - where: {code: 'cmr'}, - fields: ['id'] - }, myOptions); - for (const ticketId of tickets) { const ticket = await models.Ticket.findById(ticketId, myOptions); @@ -48,31 +43,35 @@ module.exports = Self => { relation: 'dms', fields: ['dmsFk'], scope: { - where: {dmsTypeFk: dmsTypeCmr.id} + relation: 'dmsType', + scope: { + where: {code: 'cmr'} + } } } }, myOptions); - if (!hasDmsCmr?.dms()) { - ctx.args.id = ticket.cmrFk; - const response = await models.Route.cmr(ctx, myOptions); - const pdfStream = Readable.from(Buffer.from(response[0])); - const data = { - workerFk: ctx.req.accessToken.userId, - dmsTypeFk: dmsTypeCmr.id, - companyFk: ticket.companyFk, - warehouseFk: ticket.warehouseFk, - reference: ticket.id, - contentType: 'application/pdf', - hasFile: true - }; + if (hasDmsCmr?.dms()) + throw new UserError('This ticket already has a cmr saved'); - dms = await models.Dms.createFromStream(data, 'pdf', pdfStream, myOptions); - await models.TicketDms.create({ - ticketFk: ticketId, - dmsFk: dms.id - }, myOptions); - } + ctx.args.id = ticket.cmrFk; + const response = await models.Route.cmr(ctx, myOptions); + const pdfStream = Readable.from(Buffer.from(response[0])); + const data = { + workerFk: ctx.req.accessToken.userId, + dmsTypeFk: dmsTypeCmr.id, + companyFk: ticket.companyFk, + warehouseFk: ticket.warehouseFk, + reference: ticket.id, + contentType: 'application/pdf', + hasFile: true + }; + + const dms = await models.Dms.createFromStream(data, 'pdf', pdfStream, myOptions); + await models.TicketDms.create({ + ticketFk: ticketId, + dmsFk: dms.id + }, myOptions); } } if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 625b04d6e..e3461ad3a 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -70,7 +70,7 @@ module.exports = Self => { } ] }, myOptions); - if (ticketDms.dms()?.id) return true; + if (ticketDms?.dms()?.id) return true; } async function createGestDoc(id) { From 7c80a7bdda38cba71d5bdcc4bb76ab832fdcd71a Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 29 Jan 2024 08:14:33 +0100 Subject: [PATCH 21/69] fix: #6184 Minor changes --- modules/route/back/methods/route/cmrEmail.js | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/modules/route/back/methods/route/cmrEmail.js b/modules/route/back/methods/route/cmrEmail.js index 7d1b23bab..248245259 100644 --- a/modules/route/back/methods/route/cmrEmail.js +++ b/modules/route/back/methods/route/cmrEmail.js @@ -13,21 +13,6 @@ module.exports = Self => { description: 'The ticket id', } ], - returns: [ - { - arg: 'body', - type: 'file', - root: true - }, { - arg: 'Content-Type', - type: 'string', - http: {target: 'header'} - }, { - arg: 'Content-Disposition', - type: 'string', - http: {target: 'header'} - } - ], http: { path: '/cmrEmail', verb: 'POST' @@ -88,7 +73,7 @@ module.exports = Self => { const response = await models.Dms.downloadFile(ctx, dms.id); const email = new Email('cmr', params); - return email.send({ + await email.send({ overrideAttachments: true, attachments: [{ filename: `${ticket.cmrFk}.pdf`, @@ -97,7 +82,6 @@ module.exports = Self => { }); } if (tx) await tx.commit(); - return; } catch (e) { if (tx) await tx.rollback(); throw e; From 65756f98ad579ce2908062c398836d16d3b6777e Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 29 Jan 2024 08:25:00 +0100 Subject: [PATCH 22/69] fix: #6184 Minor changes --- modules/ticket/back/methods/ticket/saveCmr.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/modules/ticket/back/methods/ticket/saveCmr.js b/modules/ticket/back/methods/ticket/saveCmr.js index 30b327dee..17760bacc 100644 --- a/modules/ticket/back/methods/ticket/saveCmr.js +++ b/modules/ticket/back/methods/ticket/saveCmr.js @@ -33,6 +33,11 @@ module.exports = Self => { } try { + const dmsTypeCmr = await models.DmsType.findOne({ + where: {code: 'cmr'}, + fields: ['id'] + }, myOptions); + for (const ticketId of tickets) { const ticket = await models.Ticket.findById(ticketId, myOptions); @@ -43,10 +48,7 @@ module.exports = Self => { relation: 'dms', fields: ['dmsFk'], scope: { - relation: 'dmsType', - scope: { - where: {code: 'cmr'} - } + where: {dmsTypeFk: dmsTypeCmr.id} } } }, myOptions); From 65268487b9ae6d53a0db185ba1914794b36c09f6 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 30 Jan 2024 07:32:26 +0100 Subject: [PATCH 23/69] fix: #6184 Now creates only one dms in saveSign --- modules/ticket/back/methods/ticket/saveSign.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index e3461ad3a..7f168bfc0 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -34,6 +34,8 @@ module.exports = Self => { const myOptions = {userId: ctx.req.accessToken.userId}; let tx; let ticket; + let dms; + let gestDocCreated; if (typeof options == 'object') Object.assign(myOptions, options); @@ -83,8 +85,8 @@ module.exports = Self => { description: `Firma del cliente - Ruta ${ticket.route().id}`, hasFile: true }; - const dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); - await models.TicketDms.create({ticketFk: id, dmsFk: dms[0].id}, myOptions); + dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); + gestDocCreated = true; } try { @@ -134,8 +136,9 @@ module.exports = Self => { throw new UserError('Ticket is already signed'); if (location) await setLocation(ticketId); - if (!await hasSignDms(ticketId)) + if (!await hasSignDms(ticketId) && !gestDocCreated) await createGestDoc(ticketId); + await models.TicketDms.create({ticketFk: id, dmsFk: dms[0].id}, myOptions); await ticket.updateAttribute('isSigned', true, myOptions); const deliveryState = await models.State.findOne({ From 1fe6818a0f0c9ba12e3f8136906f98f6b52ce18a Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 30 Jan 2024 07:42:58 +0100 Subject: [PATCH 24/69] fix: #6184 Minor changes --- modules/ticket/back/methods/ticket/saveSign.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 7f168bfc0..91c6930d8 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -75,7 +75,7 @@ module.exports = Self => { if (ticketDms?.dms()?.id) return true; } - async function createGestDoc(id) { + async function createGestDoc() { const ctxUploadFile = Object.assign({}, ctx); ctxUploadFile.args = { warehouseId: ticket.warehouseFk, @@ -138,7 +138,7 @@ module.exports = Self => { if (location) await setLocation(ticketId); if (!await hasSignDms(ticketId) && !gestDocCreated) await createGestDoc(ticketId); - await models.TicketDms.create({ticketFk: id, dmsFk: dms[0].id}, myOptions); + await models.TicketDms.create({ticketFk: ticketId, dmsFk: dms[0].id}, myOptions); await ticket.updateAttribute('isSigned', true, myOptions); const deliveryState = await models.State.findOne({ From 0f3ffcfa61a84f3c529e0399b60415bd6814ff74 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 30 Jan 2024 08:11:33 +0100 Subject: [PATCH 25/69] fix: refs #6184 Upload sign --- back/methods/dms/uploadFile.js | 2 +- modules/ticket/back/methods/ticket/saveSign.js | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/back/methods/dms/uploadFile.js b/back/methods/dms/uploadFile.js index 728ae229f..8456cf2d3 100644 --- a/back/methods/dms/uploadFile.js +++ b/back/methods/dms/uploadFile.js @@ -88,7 +88,7 @@ module.exports = Self => { warehouseFk: args.warehouseId, reference: args.reference, description: args.description, - contentType: file.type, + contentType: args.contentType, hasFile: args.hasFile }; const extension = await models.DmsContainer.getFileExtension(uploadedFile.name); diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 91c6930d8..0fcd41102 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -83,6 +83,7 @@ module.exports = Self => { dmsTypeId: dmsTypeTicket.id, reference: ticket.id, description: `Firma del cliente - Ruta ${ticket.route().id}`, + contentType: 'image/png', hasFile: true }; dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); From 1e56e741e2f7ba5a9082644ecd5d9f170b40ca0c Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 30 Jan 2024 09:44:10 +0100 Subject: [PATCH 26/69] fix: #6184 Requested changes --- db/dump/fixtures.after.sql | 3 - db/dump/fixtures.before.sql | 70 +++++++++---------- loopback/locale/es.json | 3 +- modules/route/back/methods/route/cmrEmail.js | 15 ++-- .../back/methods/route/downloadCmrsZip.js | 6 +- 5 files changed, 43 insertions(+), 54 deletions(-) diff --git a/db/dump/fixtures.after.sql b/db/dump/fixtures.after.sql index 57ccb8626..db4d05dfd 100644 --- a/db/dump/fixtures.after.sql +++ b/db/dump/fixtures.after.sql @@ -66,9 +66,6 @@ UPDATE vn.supplier SET isTrucker = 1 WHERE id = 2; -INSERT INTO vn.cmr (id, truckPlate, observations, senderInstruccions, paymentInstruccions, specialAgreements, created, companyFk, addressToFk, addressFromFk, supplierFk, packagesList, merchandiseDetail, state, landed, ead) - VALUES (2, NULL, NULL, NULL, 'Carriage paid', NULL, '2022-06-27 13:31:11.000', 442, 3, 2, 2, NULL, NULL, NULL, NULL, NULL); - -- XXX: tpv UPDATE `vn`.`claimRatio` SET `claimAmount` = '10' WHERE (`clientFk` = '1101'); diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 7ea8c0120..6ff95a404 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -729,40 +729,40 @@ INSERT INTO `vn`.`route`(`id`, `time`, `workerFk`, `created`, `vehicleFk`, `agen (6, NULL, 57, util.VN_CURDATE(), 5, 7, 'sixth route', 1.7, 60, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 3), (7, NULL, 57, util.VN_CURDATE(), 6, 8, 'seventh route', 0, 70, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 5); -INSERT INTO `vn`.`ticket`(`id`, `priority`, `agencyModeFk`,`warehouseFk`,`routeFk`, `shipped`, `landed`, `clientFk`,`nickname`, `addressFk`, `refFk`, `isDeleted`, `zoneFk`, `zonePrice`, `zoneBonus`, `created`, `weight`) +INSERT INTO `vn`.`ticket`(`id`, `priority`, `agencyModeFk`,`warehouseFk`,`routeFk`, `shipped`, `landed`, `clientFk`,`nickname`, `addressFk`, `refFk`, `isDeleted`, `zoneFk`, `zonePrice`, `zoneBonus`, `created`, `weight`, `cmrFk`) VALUES - (1 , 3, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 121, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1), - (2 , 1, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 1, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2), - (3 , 1, 7, 1, 6, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -2 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 3, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), NULL), - (4 , 3, 2, 1, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -3 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 9, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), NULL), - (5 , 3, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -4 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), NULL), - (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), NULL), - (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(), NULL), - (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(), NULL), - (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(), NULL), - (10, 1, 1, 5, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'Ingram Street', 2, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL), - (11, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'NY roofs', 122, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL), - (12, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL), - (13, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL), - (14, 1, 2, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1104, 'Malibu Point', 4, NULL, 0, 9, 5, 1, util.VN_CURDATE(), NULL), - (15, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1105, 'An incredibly long alias for testing purposes', 125, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL), - (16, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1106, 'Many Places', 126, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL), - (17, 1, 7, 2, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1106, 'Many Places', 126, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL), - (18, 1, 4, 4, 4, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1108, 'Cerebro', 128, NULL, 0, 12, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +12 HOUR), NULL), - (19, 1, 5, 5, NULL, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1109, 'Somewhere in Thailand', 129, NULL, 1, NULL, 5, 1, util.VN_CURDATE(), NULL), - (20, 1, 5, 5, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Thailand', 129, NULL, 0, 13, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), NULL), - (21, NULL, 5, 5, 5, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Holland', 102, NULL, 0, 13, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), NULL), - (22, NULL, 5, 5, 5, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Japan', 103, NULL, 0, 13, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), NULL), - (23, NULL, 8, 1, 7, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1101, 'address 21', 121, NULL, 0, 5, 5, 1, util.VN_CURDATE(), NULL), - (24 ,NULL, 8, 1, 7, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'Bruce Wayne', 1, NULL, 0, 5, 5, 1, util.VN_CURDATE(), NULL), - (25 ,NULL, 8, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'Bruce Wayne', 1, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL), - (26 ,NULL, 8, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'An incredibly long alias for testing purposes', 1, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL), - (27 ,NULL, 8, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'Wolverine', 1, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL), - (28, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL), - (29, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL), - (30, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL), - (31, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL), - (32, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL); + (1 , 3, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 121, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 1), + (2 , 1, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 1, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 2), + (3 , 1, 7, 1, 6, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -2 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 3, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), NULL, 3), + (4 , 3, 2, 1, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -3 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 9, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), NULL, NULL), + (5 , 3, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -4 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), NULL, NULL), + (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), NULL, NULL), + (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(), NULL, NULL), + (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(), NULL, NULL), + (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(), NULL, NULL), + (10, 1, 1, 5, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'Ingram Street', 2, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), + (11, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'NY roofs', 122, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL), + (12, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), + (13, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL), + (14, 1, 2, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1104, 'Malibu Point', 4, NULL, 0, 9, 5, 1, util.VN_CURDATE(), NULL, NULL), + (15, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1105, 'An incredibly long alias for testing purposes', 125, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL), + (16, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1106, 'Many Places', 126, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL), + (17, 1, 7, 2, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1106, 'Many Places', 126, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL), + (18, 1, 4, 4, 4, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1108, 'Cerebro', 128, NULL, 0, 12, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +12 HOUR), NULL, NULL), + (19, 1, 5, 5, NULL, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1109, 'Somewhere in Thailand', 129, NULL, 1, NULL, 5, 1, util.VN_CURDATE(), NULL, NULL), + (20, 1, 5, 5, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Thailand', 129, NULL, 0, 13, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), NULL, NULL), + (21, NULL, 5, 5, 5, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Holland', 102, NULL, 0, 13, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), NULL, NULL), + (22, NULL, 5, 5, 5, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 1109, 'Somewhere in Japan', 103, NULL, 0, 13, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), NULL, NULL), + (23, NULL, 8, 1, 7, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1101, 'address 21', 121, NULL, 0, 5, 5, 1, util.VN_CURDATE(), NULL, NULL), + (24 ,NULL, 8, 1, 7, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'Bruce Wayne', 1, NULL, 0, 5, 5, 1, util.VN_CURDATE(), NULL, NULL), + (25 ,NULL, 8, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'Bruce Wayne', 1, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), + (26 ,NULL, 8, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'An incredibly long alias for testing purposes', 1, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), + (27 ,NULL, 8, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1101, 'Wolverine', 1, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), + (28, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), + (29, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), + (30, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), + (31, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), + (32, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL); INSERT INTO `vn`.`ticketObservation`(`id`, `ticketFk`, `observationTypeFk`, `description`) VALUES @@ -3071,7 +3071,3 @@ INSERT INTO `vn`.`cmr` (id,truckPlate,observations,senderInstruccions,paymentIns VALUES (1,'123456A','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet',442,1,2,1,'Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet'), (2,'123456N','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet',69,3,4,2,'Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet'), (3,'123456B','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet',567,5,6,69,'Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet'); - -UPDATE `vn`.`ticket` SET `cmrFk`= 1 WHERE `id`= 1; -UPDATE `vn`.`ticket` SET `cmrFk`= 2 WHERE `id`= 2; -UPDATE `vn`.`ticket` SET `cmrFk`= 3 WHERE `id`= 3; diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 63613dec8..7b51527d4 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -337,6 +337,5 @@ "You already have the mailAlias": "Ya tienes este alias de correo", "The alias cant be modified": "Este alias de correo no puede ser modificado", "No tickets to invoice": "No hay tickets para facturar", - "This ticket already has a cmr saved": "Este ticket ya tiene un cmr guardado", - "Client does not have an email": "El cliente no tiene correo" + "This ticket already has a cmr saved": "Este ticket ya tiene un cmr guardado" } \ No newline at end of file diff --git a/modules/route/back/methods/route/cmrEmail.js b/modules/route/back/methods/route/cmrEmail.js index 248245259..11c4d3dc8 100644 --- a/modules/route/back/methods/route/cmrEmail.js +++ b/modules/route/back/methods/route/cmrEmail.js @@ -46,13 +46,7 @@ module.exports = Self => { const recipient = ticket.client().email; if (!recipient) - throw new UserError('Client does not have an email'); - - const params = { - ticketId, - lang: ctx.req.getLocale(), - recipient - }; + throw new UserError('There is no assigned email for this client'); const dms = await models.TicketDms.findOne({ where: {ticketFk: ticketId}, @@ -71,7 +65,12 @@ module.exports = Self => { if (!dms) throw new UserError('Cmr file does not exist'); const response = await models.Dms.downloadFile(ctx, dms.id); - const email = new Email('cmr', params); + + const email = new Email('cmr', { + ticketId, + lang: ctx.req.getLocale(), + recipient + }); await email.send({ overrideAttachments: true, diff --git a/modules/route/back/methods/route/downloadCmrsZip.js b/modules/route/back/methods/route/downloadCmrsZip.js index ccbb57d87..58445f6f1 100644 --- a/modules/route/back/methods/route/downloadCmrsZip.js +++ b/modules/route/back/methods/route/downloadCmrsZip.js @@ -45,12 +45,10 @@ module.exports = Self => { for (const id of ids) { ctx.args = ctx.args || {}; ctx.args.id = Number(id); - const data = await models.Route.cmr(ctx, myOptions); - zip.file(`${id}.pdf`, data[0], {binary: true}); + const [data] = await models.Route.cmr(ctx, myOptions); + zip.file(`${id}.pdf`, data, {binary: true}); } - const zipStream = zip.generateNodeStream({streamFiles: true}); - return [zipStream, 'application/zip', `filename="cmrs.zip"`]; }; }; From d39d54a514aa85c493175b39cc10486964cc6d56 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 30 Jan 2024 09:50:53 +0100 Subject: [PATCH 27/69] fix: #6184 Requested changes --- .../back/methods/route/specs/downloadCmrsZip.spec.js | 11 +++++++++-- .../route/back/methods/route/specs/saveCmr.spec.js | 2 +- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js b/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js index 1e8ed29e7..c6b498a77 100644 --- a/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js +++ b/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js @@ -6,6 +6,7 @@ describe('route downloadCmrsZip()', () => { }); it('should create a zip file with the given cmr ids', async() => { + const tx = await models.Route.beginTransaction({}); const ctx = { req: { getLocale: () => { @@ -15,8 +16,14 @@ describe('route downloadCmrsZip()', () => { } }; let cmrs = '1,2'; - let result = await models.Route.downloadCmrsZip(ctx, cmrs); + try { + await models.Route.downloadCmrsZip(ctx, cmrs); + await tx.rollback(); + } catch (e) { + error = e; + await tx.rollback(); + } - expect(result.length).toBeGreaterThanOrEqual(1); + expect(error).toBeDefined(); }); }); diff --git a/modules/route/back/methods/route/specs/saveCmr.spec.js b/modules/route/back/methods/route/specs/saveCmr.spec.js index 9de29540f..d9ad12ad1 100644 --- a/modules/route/back/methods/route/specs/saveCmr.spec.js +++ b/modules/route/back/methods/route/specs/saveCmr.spec.js @@ -1,6 +1,6 @@ const models = require('vn-loopback/server/server').models; -describe('Ticket saveCmr()', () => { +describe('ticket saveCmr()', () => { let ctx = {req: { accessToken: {userId: 9} }}; From eec36300ad9a3681aa71c1e6671a02ae870f2440 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 2 Feb 2024 12:25:48 +0100 Subject: [PATCH 28/69] refactor: refs #6184 Minor changes --- modules/ticket/back/methods/ticket/saveSign.js | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 3a4a5ac28..0fcd41102 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -137,23 +137,13 @@ module.exports = Self => { throw new UserError('Ticket is already signed'); if (location) await setLocation(ticketId); -<<<<<<< HEAD if (!await hasSignDms(ticketId) && !gestDocCreated) await createGestDoc(ticketId); -======= - if (!gestDocCreated) await createGestDoc(ticketId); ->>>>>>> dev await models.TicketDms.create({ticketFk: ticketId, dmsFk: dms[0].id}, myOptions); await ticket.updateAttribute('isSigned', true, myOptions); const deliveryState = await models.State.findOne({ -<<<<<<< HEAD where: {code: 'DELIVERED'} -======= - where: { - code: 'DELIVERED' - } ->>>>>>> dev }, myOptions); await models.Ticket.state(ctx, { From 9448b4053392a52df4040cf1ccb89c5122516ed5 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Fri, 2 Feb 2024 14:53:48 +0100 Subject: [PATCH 29/69] refs #6386 feat: add extension when return file --- back/methods/image/download.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/methods/image/download.js b/back/methods/image/download.js index c4037b809..2b1a4b546 100644 --- a/back/methods/image/download.js +++ b/back/methods/image/download.js @@ -87,6 +87,6 @@ module.exports = Self => { await fs.access(file.path); const stream = fs.createReadStream(file.path); - return [stream, file.contentType, `filename="${file.name}"`]; + return [stream, file.contentType, `filename="${fileName}"`]; }; }; From d28cacfbad39a874c3ac070b2d1965cf519620f7 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 5 Feb 2024 09:02:31 +0100 Subject: [PATCH 30/69] refactor: refs #6778 Migrated views of vn2008 to vn --- .../bi/procedures/Greuge_Evolution_Add.sql | 14 ++++---- .../bi/procedures/claim_ratio_routine.sql | 26 +++++++-------- db/routines/bi/procedures/defaulting.sql | 4 +-- .../bi/procedures/greuge_dif_porte_add.sql | 12 +++---- .../bs/procedures/comercialesCompleto.sql | 10 +++--- .../bs/procedures/manaCustomerUpdate.sql | 10 +++--- .../bs/procedures/ventas_contables_add.sql | 6 ++-- .../ventas_contables_por_cliente.sql | 6 ++-- db/routines/bs/procedures/vivosMuertos.sql | 22 ++++++------- .../vn/functions/isPalletHomogeneus.sql | 4 +-- .../vn/procedures/getDayExpeditions.sql | 10 +++--- .../vn/procedures/itemFuentesBalance.sql | 33 +++++++++---------- .../vn/procedures/itemShelvingRadar.sql | 10 +++--- .../vn/procedures/shelving_getSpam.sql | 30 ++++++++--------- .../vn2008/functions/intrastat_neto.sql | 12 +++---- .../vn2008/procedures/CalculoRemesas.sql | 10 +++--- .../procedures/ListaTicketsEncajados.sql | 6 ++-- .../vn2008/procedures/availableTraslate.sql | 22 ++++++------- .../vn2008/procedures/balance_create.sql | 6 ++-- .../procedures/customerDebtEvolution.sql | 8 ++--- db/routines/vn2008/views/Facturas.sql | 20 ----------- db/routines/vn2008/views/Gastos.sql | 7 ---- db/routines/vn2008/views/Greuges.sql | 12 ------- db/routines/vn2008/views/Greuges_type.sql | 6 ---- db/routines/vn2008/views/Intrastat.sql | 8 ----- db/routines/vn2008/views/expeditions.sql | 16 --------- db/routines/vn2008/views/gestdoc.sql | 16 --------- db/routines/vn2008/views/gesttip.sql | 9 ----- db/routines/vn2008/views/intrastat_data.sql | 13 -------- .../vn2008/views/invoiceCorrection.sql | 9 ----- db/routines/vn2008/views/itemTag.sql | 9 ----- db/routines/vn2008/views/item_entry_in.sql | 20 ----------- db/routines/vn2008/views/item_entry_out.sql | 27 --------------- db/routines/vn2008/views/item_out.sql | 17 ---------- .../10868-grayChico/00-firstScript.sql | 15 +++++++++ 35 files changed, 145 insertions(+), 320 deletions(-) delete mode 100644 db/routines/vn2008/views/Facturas.sql delete mode 100644 db/routines/vn2008/views/Gastos.sql delete mode 100644 db/routines/vn2008/views/Greuges.sql delete mode 100644 db/routines/vn2008/views/Greuges_type.sql delete mode 100644 db/routines/vn2008/views/Intrastat.sql delete mode 100644 db/routines/vn2008/views/expeditions.sql delete mode 100644 db/routines/vn2008/views/gestdoc.sql delete mode 100644 db/routines/vn2008/views/gesttip.sql delete mode 100644 db/routines/vn2008/views/intrastat_data.sql delete mode 100644 db/routines/vn2008/views/invoiceCorrection.sql delete mode 100644 db/routines/vn2008/views/itemTag.sql delete mode 100644 db/routines/vn2008/views/item_entry_in.sql delete mode 100644 db/routines/vn2008/views/item_entry_out.sql delete mode 100644 db/routines/vn2008/views/item_out.sql create mode 100644 db/versions/10868-grayChico/00-firstScript.sql diff --git a/db/routines/bi/procedures/Greuge_Evolution_Add.sql b/db/routines/bi/procedures/Greuge_Evolution_Add.sql index 83033cbf8..b29be6b49 100644 --- a/db/routines/bi/procedures/Greuge_Evolution_Add.sql +++ b/db/routines/bi/procedures/Greuge_Evolution_Add.sql @@ -42,9 +42,9 @@ BEGIN CREATE TEMPORARY TABLE maxInvoice (PRIMARY KEY (Id_Cliente)) ENGINE = MEMORY - SELECT DISTINCT Id_Cliente, max(Fecha) as maxFecha - FROM vn2008.Facturas - GROUP BY Id_Cliente + SELECT DISTINCT clientFk Id_Cliente, max(issued) as maxFecha + FROM vn.invoiceOut + GROUP BY clientFk HAVING maxFecha < timestampadd(month,-2,datFEC); WHILE datFEC < util.VN_CURDATE() DO @@ -53,10 +53,10 @@ BEGIN SELECT Id_Cliente, datFEC as Fecha, Greuge, Ventas, 0 FROM ( - SELECT Id_Cliente, sum(Importe) as Greuge - FROM vn2008.Greuges - where Fecha <= datFEC - group by Id_Cliente + SELECT clientFk Id_Cliente, sum(amount) as Greuge + FROM vn2.greuge + where shipped <= datFEC + group by clientFk ) sub RIGHT JOIN diff --git a/db/routines/bi/procedures/claim_ratio_routine.sql b/db/routines/bi/procedures/claim_ratio_routine.sql index 4616bcb9e..ded154242 100644 --- a/db/routines/bi/procedures/claim_ratio_routine.sql +++ b/db/routines/bi/procedures/claim_ratio_routine.sql @@ -11,8 +11,8 @@ BEGIN -- Reclamaciones demasiado sensibles - INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, - Importe, Greuges_type_id,Id_Ticket) + INSERT INTO vn.greuge(shipped, clientFk, description, + amount, greugeTypeFk, ticketFk) SELECT cm.Fecha , cm.Id_Cliente , concat('Claim ',cm.id,' : ', m.Concepte) @@ -29,8 +29,8 @@ BEGIN -- Reclamaciones que pasan a Maná - INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, - Importe , Greuges_type_id,Id_Ticket) + INSERT INTO vn.greuge(shipped, clientFk, description, + amount, greugeTypeFk, ticketFk) SELECT cm.Fecha , cm.Id_Cliente , concat('Claim_mana ',cm.id,' : ', m.Concepte) @@ -73,12 +73,12 @@ BEGIN AND s.alert_level >= 3; DELETE g.* - FROM vn2008.Greuges g - JOIN tmp.ticket_list t ON g.Id_Ticket = t.Id_Ticket - WHERE Greuges_type_id = 2; + FROM vn.greuge g + JOIN tmp.ticket_list t ON g.ticketFk = t.Id_Ticket + WHERE t.greugeTypeFk = 2; - INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, - Greuges_type_id, Id_Ticket) + INSERT INTO vn.greuge(clientFk, description, amount,shipped, + greugeTypeFk, ticketFk) SELECT Id_Cliente ,concat('recobro ', m.Id_Ticket), - round(SUM(mc.Valor*Cantidad),2) AS dif @@ -130,10 +130,10 @@ BEGIN -- Calculamos el porcentaje del recobro para añadirlo al precio de venta UPDATE bi.claims_ratio cr JOIN ( - SELECT Id_Cliente, nz(SUM(Importe)) AS Greuge - FROM vn2008.Greuges - WHERE Fecha <= util.VN_CURDATE() - GROUP BY Id_Cliente + SELECT clientFk Id_Cliente, nz(SUM(amount)) AS Greuge + FROM vn.greuge + WHERE shipped <= util.VN_CURDATE() + GROUP BY clientFk ) g ON g.Id_Cliente = cr.Id_Cliente SET recobro = GREATEST(0,round(nz(Greuge) / (nz(Consumo) * vMonthToRefund / 12 ) ,3)); diff --git a/db/routines/bi/procedures/defaulting.sql b/db/routines/bi/procedures/defaulting.sql index 50600e554..e8ba5e682 100644 --- a/db/routines/bi/procedures/defaulting.sql +++ b/db/routines/bi/procedures/defaulting.sql @@ -14,8 +14,8 @@ BEGIN WHERE hasChanged AND date = vDate; DECLARE invoices CURSOR FOR - SELECT Vencimiento, importe FROM vn2008.Facturas f - WHERE f.Fecha >= '2016-01-01' AND f.Id_Cliente = vClient ORDER BY f.Fecha DESC; + SELECT dued Vencimiento, amount importe FROM vn.invoiceOut + WHERE issued >= '2016-01-01' AND clientFk = vClient ORDER BY issued DESC; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; diff --git a/db/routines/bi/procedures/greuge_dif_porte_add.sql b/db/routines/bi/procedures/greuge_dif_porte_add.sql index c81e41661..02bd9eae4 100644 --- a/db/routines/bi/procedures/greuge_dif_porte_add.sql +++ b/db/routines/bi/procedures/greuge_dif_porte_add.sql @@ -19,8 +19,8 @@ BEGIN FROM vn.ticket t JOIN vn2008.Clientes cli ON cli.Id_cliente = t.clientFk - LEFT JOIN vn2008.expeditions e ON e.ticket_id = t.id - JOIN vn.expeditionBoxVol ebv ON ebv.boxFk = e.EsBulto + LEFT JOIN vn.expedition e ON e.ticketFk = t.id + JOIN vn.expeditionBoxVol ebv ON ebv.boxFk = e.freightItemFk JOIN vn.zone z ON t.zoneFk = z.id WHERE t.shipped between datSTART AND datEND @@ -64,17 +64,17 @@ BEGIN CREATE TEMPORARY TABLE tmp.dp_aux (PRIMARY KEY (ticketFk)) ENGINE = MEMORY - SELECT dp.ticketFk, sum(Importe) Importe + SELECT dp.ticketFk, sum(g.amount) Importe FROM tmp.dp - JOIN vn2008.Greuges g ON g.Id_Ticket = dp.ticketFk - WHERE Greuges_type_id = 1 -- dif_porte + JOIN vn.greuge g ON g.ticketFk = dp.ticketFk + WHERE g.greugeTypeFk = 1 -- dif_porte GROUP BY dp.ticketFk; UPDATE tmp.dp JOIN tmp.dp_aux USING(ticketFk) SET greuge = IFNULL(Importe,0); - INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, Greuges_type_id, Id_Ticket) + INSERT INTO vn.greuge (clientFk,description,amount,shipped,greugeTypeFk,ticketFk) SELECT dp.clientFk , concat('dif_porte ', dp.ticketFk) , round(IFNULL(dp.teorico,0) - IFNULL(dp.practico,0) - IFNULL(dp.greuge,0),2) as Importe diff --git a/db/routines/bs/procedures/comercialesCompleto.sql b/db/routines/bs/procedures/comercialesCompleto.sql index 323d5cd00..b84467cf1 100644 --- a/db/routines/bs/procedures/comercialesCompleto.sql +++ b/db/routines/bs/procedures/comercialesCompleto.sql @@ -37,9 +37,9 @@ BEGIN FROM vn2008.Clientes c LEFT JOIN - (SELECT g.Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge - FROM vn2008.Greuges g - JOIN vn.`client` c ON c.id = g.Id_Cliente + (SELECT g.clientFk Id_Cliente, CAST( SUM(g.amount) as DECIMAL(12,2)) AS Greuge + FROM vn.greuge g + JOIN vn.`client` c ON c.id = g.clientFk LEFT JOIN vn.worker w ON c.salesPersonFk = w.id WHERE (c.salesPersonFk = vWorker OR w.bossFk = vWorker) GROUP BY Id_Cliente @@ -99,8 +99,8 @@ BEGIN LEFT JOIN (SELECT c.Id_Cliente, IF(MAX(Fecha) < DATE_FORMAT(TIMESTAMPADD(MONTH, - 1, vDate), '%Y- %m-01'), TRUE, FALSE) muerto - FROM vn2008.Facturas f - JOIN vn2008.Clientes c ON c.Id_cliente = f.Id_Cliente + FROM vn.invoiceOut f + JOIN vn2008.Clientes c ON c.Id_cliente = f.clientFk LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador WHERE (c.Id_Trabajador = vWorker OR tr.boss = vWorker) GROUP BY Id_Cliente) dead ON dead.Id_Cliente = c.Id_Cliente diff --git a/db/routines/bs/procedures/manaCustomerUpdate.sql b/db/routines/bs/procedures/manaCustomerUpdate.sql index 1e9cb8429..2cb25d135 100644 --- a/db/routines/bs/procedures/manaCustomerUpdate.sql +++ b/db/routines/bs/procedures/manaCustomerUpdate.sql @@ -82,11 +82,11 @@ BEGIN AND Fechacobro > vFromDated AND Fechacobro <= vToDated UNION ALL - SELECT g.Id_Cliente, g.Importe - FROM vn2008.Greuges g - WHERE Greuges_type_id = vManaGreugeTypeId - AND Fecha > vFromDated - AND Fecha <= vToDated + SELECT clientFk, amount + FROM vn.greuge + WHERE greugeTypeFk = vManaGreugeTypeId + AND shipped > vFromDated + AND shipped <= vToDated UNION ALL SELECT clientFk, mana FROM vn.clientManaCache diff --git a/db/routines/bs/procedures/ventas_contables_add.sql b/db/routines/bs/procedures/ventas_contables_add.sql index d8e963e3e..6cca2ff7f 100644 --- a/db/routines/bs/procedures/ventas_contables_add.sql +++ b/db/routines/bs/procedures/ventas_contables_add.sql @@ -23,9 +23,9 @@ BEGIN ENGINE = MEMORY SELECT Id_Ticket FROM vn2008.Tickets t - JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura - WHERE year(f.Fecha) = vYear - AND month(f.Fecha) = vMonth; + JOIN vn.invoiceOut f ON f.id = t.Factura + WHERE year(f.issued) = vYear + AND month(f.issued) = vMonth; INSERT INTO bs.ventas_contables(year , month diff --git a/db/routines/bs/procedures/ventas_contables_por_cliente.sql b/db/routines/bs/procedures/ventas_contables_por_cliente.sql index 9f1399025..b5b7a39d5 100644 --- a/db/routines/bs/procedures/ventas_contables_por_cliente.sql +++ b/db/routines/bs/procedures/ventas_contables_por_cliente.sql @@ -13,9 +13,9 @@ BEGIN (PRIMARY KEY (Id_Ticket)) SELECT Id_Ticket FROM vn2008.Tickets t - JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura - WHERE year(f.Fecha) = vYear - AND month(f.Fecha) = vMonth; + JOIN vn.invoiceOut f ON f.id = t.Factura + WHERE year(f.issued) = vYear + AND month(f.issued) = vMonth; SELECT vYear Año, vMonth Mes, diff --git a/db/routines/bs/procedures/vivosMuertos.sql b/db/routines/bs/procedures/vivosMuertos.sql index 1743eda64..9cd0e3605 100644 --- a/db/routines/bs/procedures/vivosMuertos.sql +++ b/db/routines/bs/procedures/vivosMuertos.sql @@ -24,20 +24,20 @@ BEGIN WHERE date BETWEEN @datSTART AND @datEND ) tm LEFT JOIN - (SELECT DISTINCT tm.yearMonth, f.Id_Cliente , 1 as Compra - FROM vn2008.Facturas f - JOIN vn2008.time tm ON tm.date = f.Fecha + (SELECT DISTINCT tm.yearMonth, f.clientFk Id_Cliente , 1 as Compra + FROM vn.invoiceOut f + JOIN vn2008.time tm ON tm.date = f.issued WHERE Fecha BETWEEN @datSTART AND @datEND) f ON f.yearMonth = tm.yearMonth AND f.Id_Cliente = c.Id_Cliente; UPDATE tmp.VivosMuertos vm JOIN - (SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente - FROM vn2008.Facturas f - JOIN vn2008.time tm ON tm.date = f.Fecha + (SELECT MIN(tm.yearMonth) firstMonth, f.clientFk Id_Cliente + FROM vn.invoiceOut f + JOIN vn2008.time tm ON tm.date = f.issued WHERE Fecha BETWEEN @datSTART AND @datEND - GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth + GROUP BY f.clientFk) fm ON fm.firstMonth = vm.yearMonth AND fm.Id_Cliente = vm.Id_Cliente SET Nuevo = 1; @@ -46,11 +46,11 @@ BEGIN UPDATE tmp.VivosMuertos vm JOIN ( - SELECT MAX(tm.yearMonth) firstMonth, f.Id_Cliente - FROM vn2008.Facturas f - JOIN vn2008.time tm ON tm.date = f.Fecha + SELECT MAX(tm.yearMonth) firstMonth, f.clientFk Id_Cliente + FROM vn.invoiceOut f + JOIN vn2008.time tm ON tm.date = f.issued WHERE Fecha BETWEEN @datSTART AND @datEND - GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth + GROUP BY f.clientFk) fm ON fm.firstMonth = vm.yearMonth AND fm.Id_Cliente = vm.Id_Cliente SET Muerto = 1 diff --git a/db/routines/vn/functions/isPalletHomogeneus.sql b/db/routines/vn/functions/isPalletHomogeneus.sql index 39c6461ae..d308e8ed3 100644 --- a/db/routines/vn/functions/isPalletHomogeneus.sql +++ b/db/routines/vn/functions/isPalletHomogeneus.sql @@ -16,8 +16,8 @@ BEGIN FROM ( SELECT DISTINCT t.Id_Ruta FROM vn2008.scan_line sl - JOIN vn2008.expeditions e ON e.expeditions_id = sl.code - JOIN vn2008.Tickets t ON t.Id_Ticket = e.ticket_id + JOIN expeditions e ON e.id = sl.code + JOIN vn2008.Tickets t ON t.Id_Ticket = e.ticketFk WHERE sl.scan_id = vScanId AND t.Id_Ruta ) t1; diff --git a/db/routines/vn/procedures/getDayExpeditions.sql b/db/routines/vn/procedures/getDayExpeditions.sql index 949cf4e5b..535dfde4a 100644 --- a/db/routines/vn/procedures/getDayExpeditions.sql +++ b/db/routines/vn/procedures/getDayExpeditions.sql @@ -3,12 +3,12 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`getDayExpeditions`( BEGIN SELECT - e.expeditions_id as expeditionFk, - date_format(e.odbc_date,'%Y-%m-%d') as expeditionDate, - e.ticket_id as ticketFk, + e.id as expeditionFk, + date_format(e.created,'%Y-%m-%d') as expeditionDate, + e.ticketFk, t.routeFk as routeFk - FROM vn2008.expeditions e - INNER JOIN vn.ticket t ON t.id = e.ticket_id + FROM expeditions e + INNER JOIN vn.ticket t ON t.id = e.ticketFk WHERE DATE(odbc_date) = util.VN_CURDATE(); END$$ diff --git a/db/routines/vn/procedures/itemFuentesBalance.sql b/db/routines/vn/procedures/itemFuentesBalance.sql index d793841ee..e60273340 100644 --- a/db/routines/vn/procedures/itemFuentesBalance.sql +++ b/db/routines/vn/procedures/itemFuentesBalance.sql @@ -50,31 +50,30 @@ BEGIN ) alb ON alb.itemFk = i.id LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk LEFT JOIN ( - SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as venta - FROM vn2008.item_out - WHERE dat BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE())) - AND warehouse_id = vWarehouseFk - GROUP BY item_id + SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as venta + FROM itemTicketOut + WHERE shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE())) + AND warehouseFk = vWarehouseFk + GROUP BY itemFk ) sale ON sale.item_id = i.id LEFT JOIN ( - SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as compra - FROM vn2008.item_entry_in - WHERE dat BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE())) - AND warehouse_id = vWarehouseFk + SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as compra + FROM itemEntryIn + WHERE landed BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE())) + AND warehouseInFk = vWarehouseFk AND isVirtualStock = FALSE - GROUP BY item_id + GROUP BY itemFk ) buy ON buy.item_id = i.id LEFT JOIN ( - SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as traslado - FROM vn2008.item_entry_out - WHERE dat BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE())) - AND warehouse_id = vWarehouseFk - GROUP BY item_id + SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as traslado + FROM itemEntryOut + WHERE shipped BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(util.VN_CURDATE())) + AND warehouseOutFk = vWarehouseFk + GROUP BY itemFk ) mov ON mov.item_id = i.id WHERE (v.amount OR fue.Fuentes OR alb.Albenfruit) AND i.itemPackingTypeFk = 'H' - AND ic.shortLife - ; + AND ic.shortLife; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/itemShelvingRadar.sql b/db/routines/vn/procedures/itemShelvingRadar.sql index 778bd9910..a1e89e89a 100644 --- a/db/routines/vn/procedures/itemShelvingRadar.sql +++ b/db/routines/vn/procedures/itemShelvingRadar.sql @@ -141,8 +141,8 @@ proc:BEGIN amount, IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours, IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) as minutes - FROM vn2008.item_out io - JOIN tmp.itemShelvingRadar isr ON isr.itemFk = io.item_id + FROM itemTicketOut io + JOIN tmp.itemShelvingRadar isr ON isr.itemFk = io.itemFk JOIN vn.ticket t on t.id= io.ticketFk JOIN vn.ticketState ts on ts.ticketFk = io.ticketFk JOIN vn.state s ON s.id = ts.stateFk @@ -154,10 +154,10 @@ proc:BEGIN ) stPrevious ON `stPrevious`.`saleFk` = io.saleFk WHERE t.warehouseFk = vWarehouseFk AND s.isPicked = 0 - AND NOT io.Reservado + AND NOT io.reserved AND stPrevious.saleFk IS NULL - AND io.dat >= util.VN_CURDATE() - AND io.dat < util.VN_CURDATE() + INTERVAL 1 DAY + AND io.shipped >= util.VN_CURDATE() + AND io.shipped < util.VN_CURDATE() + INTERVAL 1 DAY ) sub GROUP BY itemFk, hours, minutes; diff --git a/db/routines/vn/procedures/shelving_getSpam.sql b/db/routines/vn/procedures/shelving_getSpam.sql index eccbfb9a4..2895470ad 100644 --- a/db/routines/vn/procedures/shelving_getSpam.sql +++ b/db/routines/vn/procedures/shelving_getSpam.sql @@ -34,26 +34,26 @@ BEGIN ) fue ON fue.itemFk = i.id LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk LEFT JOIN ( - SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as venta - FROM vn2008.item_out - WHERE dat BETWEEN util.VN_CURDATE() AND util.dayend(vDated) - AND warehouse_id = vWarehouseFk - GROUP BY item_id + SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as venta + FROM itemTicketOut + WHERE shipped BETWEEN util.VN_CURDATE() AND util.dayend(vDated) + AND warehouseFk = vWarehouseFk + GROUP BY itemFk ) sale ON sale.item_id = i.id LEFT JOIN ( - SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as compra - FROM vn2008.item_entry_in - WHERE dat BETWEEN util.VN_CURDATE() AND util.dayend(vDated) - AND warehouse_id = vWarehouseFk + SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as compra + FROM itemEntryIn + WHERE landed BETWEEN util.VN_CURDATE() AND util.dayend(vDated) + AND warehouseInFk = vWarehouseFk AND isVirtualStock = FALSE - GROUP BY item_id + GROUP BY itemFk ) buy ON buy.item_id = i.id LEFT JOIN ( - SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as traslado - FROM vn2008.item_entry_out - WHERE dat BETWEEN util.VN_CURDATE() AND util.dayend(vDated) - AND warehouse_id = vWarehouseFk - GROUP BY item_id + SELECT itemFk item_id, CAST(sum(quantity)AS DECIMAL(10,0)) as traslado + FROM itemEntryOut + WHERE shipped BETWEEN util.VN_CURDATE() AND util.dayend(vDated) + AND warehouseOutFk = vWarehouseFk + GROUP BY itemFk ) mov ON mov.item_id = i.id WHERE v.amount; diff --git a/db/routines/vn2008/functions/intrastat_neto.sql b/db/routines/vn2008/functions/intrastat_neto.sql index 34e01de8c..0f38ccd0e 100644 --- a/db/routines/vn2008/functions/intrastat_neto.sql +++ b/db/routines/vn2008/functions/intrastat_neto.sql @@ -6,12 +6,12 @@ BEGIN DECLARE n DOUBLE; - SELECT ROUND(intUNIDADES / (SUM(MEDIA) / COUNT(media)), 2) INTO n FROM - (SELECT *, unidades / neto MEDIA - FROM intrastat_data - WHERE intrastat_id = intINSTRASTAT AND neto - AND unidades > 0 - ORDER BY odbc_date DESC + SELECT ROUND(intUNIDADES / (SUM(MEDIA) / COUNT(MEDIA)), 2) INTO n FROM + (SELECT *, stems / net MEDIA + FROM vn.invoiceInIntrastat + WHERE intrastatFk = intINSTRASTAT AND net + AND stems > 0 + ORDER BY dated DESC LIMIT 20) t; -- JGF 01/06 per a evitar Kg en negatiu RETURN n/2; diff --git a/db/routines/vn2008/procedures/CalculoRemesas.sql b/db/routines/vn2008/procedures/CalculoRemesas.sql index 17a2e7fdd..e7d1ae22c 100644 --- a/db/routines/vn2008/procedures/CalculoRemesas.sql +++ b/db/routines/vn2008/procedures/CalculoRemesas.sql @@ -47,13 +47,13 @@ BEGIN UNION ALL - SELECT empresa_id, Id_Cliente, - Importe - FROM Facturas f - JOIN Clientes c using(Id_Cliente) + SELECT d.companyFk, f.clientFk Id_Cliente, - f.amount + FROM vn.invoiceOut f + JOIN Clientes c ON c.Id_Cliente = f.clientFk JOIN pay_met pm on pm.id = pay_met_id - WHERE f.Vencimiento > vFechaRemesa + WHERE f.dued > vFechaRemesa AND pay_met_id = 4 AND pm.deudaviva - AND Importe > 0 + AND f.amount > 0 ) risk ON c.Id_Cliente = risk.clientFk GROUP BY risk.companyFk, Id_Cliente diff --git a/db/routines/vn2008/procedures/ListaTicketsEncajados.sql b/db/routines/vn2008/procedures/ListaTicketsEncajados.sql index 3d3318c63..e0b48bc5e 100644 --- a/db/routines/vn2008/procedures/ListaTicketsEncajados.sql +++ b/db/routines/vn2008/procedures/ListaTicketsEncajados.sql @@ -13,9 +13,9 @@ SELECT Agencia, FROM Tickets ti INNER JOIN Consignatarios ON ti.Id_Consigna = Consignatarios.Id_consigna INNER JOIN Agencias ON ti.Id_Agencia = Agencias.Id_Agencia - LEFT JOIN (SELECT Ticket_Id,count(*) AS ncajas FROM expeditions WHERE Id_Article=94 GROUP BY ticket_id) sub1 ON ti.Id_Ticket=sub1.Ticket_Id - LEFT JOIN (SELECT Ticket_Id,count(*) AS nbultos FROM expeditions WHERE Id_Article IS NULL GROUP BY ticket_id) sub2 ON ti.Id_Ticket=sub2.Ticket_Id - LEFT JOIN (SELECT Ticket_Id,count(*) AS notros FROM expeditions WHERE Id_Article >0 GROUP BY ticket_id) sub3 ON ti.Id_Ticket=sub3.Ticket_Id + LEFT JOIN (SELECT ticketFk,count(*) AS ncajas FROM vn.expedition WHERE Id_Article=94 GROUP BY ticket_id) sub1 ON ti.Id_Ticket=sub1.ticketFk + LEFT JOIN (SELECT ticketFk,count(*) AS nbultos FROM vn.expedition WHERE Id_Article IS NULL GROUP BY ticket_id) sub2 ON ti.Id_Ticket=sub2.ticketFk + LEFT JOIN (SELECT ticketFk,count(*) AS notros FROM vn.expedition WHERE Id_Article >0 GROUP BY ticket_id) sub3 ON ti.Id_Ticket=sub3.ticketFk INNER JOIN vn.ticketState ts ON ti.Id_ticket = ts.ticketFk WHERE ti.Fecha=util.VN_CURDATE() AND ts.userFk=intId_Trabajador diff --git a/db/routines/vn2008/procedures/availableTraslate.sql b/db/routines/vn2008/procedures/availableTraslate.sql index 6328560c8..4ac5e3209 100644 --- a/db/routines/vn2008/procedures/availableTraslate.sql +++ b/db/routines/vn2008/procedures/availableTraslate.sql @@ -67,12 +67,12 @@ proc: BEGIN CREATE TEMPORARY TABLE tmp.itemCalc (INDEX (itemFk,warehouseFk)) ENGINE = MEMORY - SELECT i.item_id itemFk, vWarehouseLanding warehouseFk, i.dat dated, i.amount quantity - FROM item_out i + SELECT i.itemFk, vWarehouseLanding warehouseFk, i.shipped dated, i.quantity + FROM vn.itemTicketOut i JOIN itemRangeLive ir ON ir.itemFK = i.item_id - WHERE i.dat >= vDatedFrom - AND (ir.dated IS NULL OR i.dat <= ir.dated) - AND i.warehouse_id = vWarehouseLanding + WHERE i.shipped >= vDatedFrom + AND (ir.dated IS NULL OR i.shipped <= ir.dated) + AND i.warehouseFk = vWarehouseLanding UNION ALL SELECT b.itemFk, vWarehouseLanding, t.landed, b.quantity FROM vn.buy b @@ -86,12 +86,12 @@ proc: BEGIN AND t.landed >= vDatedFrom AND (ir.dated IS NULL OR t.landed <= ir.dated) UNION ALL - SELECT i.item_id, vWarehouseLanding, i.dat, i.amount - FROM item_entry_out i - JOIN itemRangeLive ir ON ir.itemFk = i.item_id - WHERE i.dat >= vDatedFrom - AND (ir.dated IS NULL OR i.dat <= ir.dated) - AND i.warehouse_id = vWarehouseLanding + SELECT i.itemFk, vWarehouseLanding, i.shipped, i.quantity + FROM vn.itemEntryOut i + JOIN itemRangeLive ir ON ir.itemFk = i.itemFk + WHERE i.shipped >= vDatedFrom + AND (ir.dated IS NULL OR i.shipped <= ir.dated) + AND i.warehouseOutFk = vWarehouseLanding UNION ALL SELECT r.item_id, vWarehouseLanding, r.shipment, -r.amount FROM hedera.order_row r diff --git a/db/routines/vn2008/procedures/balance_create.sql b/db/routines/vn2008/procedures/balance_create.sql index 978dae720..2acd26834 100644 --- a/db/routines/vn2008/procedures/balance_create.sql +++ b/db/routines/vn2008/procedures/balance_create.sql @@ -122,9 +122,9 @@ BEGIN -- Añadimos los gastos, para facilitar el formulario UPDATE tmp.balance b JOIN vn2008.balance_nest_tree bnt on bnt.id = b.id - JOIN (SELECT Id_Gasto, Gasto - FROM vn2008.Gastos - GROUP BY Id_Gasto) g ON g.Id_Gasto = bnt.Id_Gasto COLLATE utf8_general_ci + JOIN (SELECT id Id_Gasto, name Gasto + FROM vn.expense + GROUP BY id) g ON g.Id_Gasto = bnt.Id_Gasto COLLATE utf8_general_ci SET b.Id_Gasto = g.Id_Gasto COLLATE utf8_general_ci , b.Gasto = g.Gasto COLLATE utf8_general_ci ; diff --git a/db/routines/vn2008/procedures/customerDebtEvolution.sql b/db/routines/vn2008/procedures/customerDebtEvolution.sql index e5d23f0ef..20ed75d8f 100644 --- a/db/routines/vn2008/procedures/customerDebtEvolution.sql +++ b/db/routines/vn2008/procedures/customerDebtEvolution.sql @@ -18,10 +18,10 @@ SELECT * FROM WHERE Id_Cliente = vCustomer AND Fechacobro >= '2017-01-01' UNION ALL - SELECT vn.getDueDate(f.Fecha,c.Vencimiento), - Importe - FROM Facturas f - JOIN Clientes c ON f.Id_Cliente = c.Id_Cliente - WHERE f.Id_Cliente = vCustomer + SELECT vn.getDueDate(f.issued,c.Vencimiento), - Importe + FROM vn.invoiceOut f + JOIN Clientes c ON f.clientFk = c.Id_Cliente + WHERE f.clientFk = vCustomer AND Fecha >= '2017-01-01' UNION ALL SELECT '2016-12-31', Debt diff --git a/db/routines/vn2008/views/Facturas.sql b/db/routines/vn2008/views/Facturas.sql deleted file mode 100644 index bc99c02d8..000000000 --- a/db/routines/vn2008/views/Facturas.sql +++ /dev/null @@ -1,20 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`Facturas` -AS SELECT `io`.`id` AS `factura_id`, - `io`.`ref` AS `Id_Factura`, - `io`.`serial` AS `Serie`, - `io`.`issued` AS `Fecha`, - `io`.`amount` AS `Importe`, - `io`.`clientFk` AS `Id_Cliente`, - `io`.`created` AS `odbc_date`, - `io`.`companyFk` AS `empresa_id`, - `io`.`dued` AS `Vencimiento`, - `io`.`booked` AS `booked`, - `io`.`bankFk` AS `Id_Banco`, - `io`.`siiTypeInvoiceOutFk` AS `siiTypeInvoiceOutFk`, - `io`.`cplusTaxBreakFk` AS `cplusTaxBreakFk`, - `io`.`cplusSubjectOpFk` AS `cplusSubjectOpFk`, - `io`.`siiTrascendencyInvoiceOutFk` AS `siiTrascendencyInvoiceOutFk`, - `io`.`hasPdf` AS `pdf` -FROM `vn`.`invoiceOut` `io` diff --git a/db/routines/vn2008/views/Gastos.sql b/db/routines/vn2008/views/Gastos.sql deleted file mode 100644 index 2eee445d8..000000000 --- a/db/routines/vn2008/views/Gastos.sql +++ /dev/null @@ -1,7 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`Gastos` -AS SELECT `e`.`id` AS `Id_Gasto`, - `e`.`name` AS `Gasto`, - `e`.`isWithheld` AS `isWithheld` -FROM `vn`.`expense` `e` diff --git a/db/routines/vn2008/views/Greuges.sql b/db/routines/vn2008/views/Greuges.sql deleted file mode 100644 index 8958ec455..000000000 --- a/db/routines/vn2008/views/Greuges.sql +++ /dev/null @@ -1,12 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`Greuges` -AS SELECT `g`.`Id` AS `Id`, - `g`.`clientFk` AS `Id_Cliente`, - `g`.`description` AS `Comentario`, - `g`.`amount` AS `Importe`, - `g`.`shipped` AS `Fecha`, - `g`.`created` AS `odbc_date`, - `g`.`greugeTypeFk` AS `Greuges_type_id`, - `g`.`ticketFk` AS `Id_Ticket` -FROM `vn`.`greuge` `g` diff --git a/db/routines/vn2008/views/Greuges_type.sql b/db/routines/vn2008/views/Greuges_type.sql deleted file mode 100644 index 500a1cc03..000000000 --- a/db/routines/vn2008/views/Greuges_type.sql +++ /dev/null @@ -1,6 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`Greuges_type` -AS SELECT `gt`.`id` AS `Greuges_type_id`, - `gt`.`name` AS `name` -FROM `vn`.`greugeType` `gt` diff --git a/db/routines/vn2008/views/Intrastat.sql b/db/routines/vn2008/views/Intrastat.sql deleted file mode 100644 index 9ed3ef283..000000000 --- a/db/routines/vn2008/views/Intrastat.sql +++ /dev/null @@ -1,8 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`Intrastat` -AS SELECT `i`.`id` AS `Codintrastat`, - `i`.`description` AS `Definicion`, - `i`.`taxClassFk` AS `iva_group_id`, - `i`.`taxCodeFk` AS `iva_codigo_id` -FROM `vn`.`intrastat` `i` diff --git a/db/routines/vn2008/views/expeditions.sql b/db/routines/vn2008/views/expeditions.sql deleted file mode 100644 index d93e2a1c6..000000000 --- a/db/routines/vn2008/views/expeditions.sql +++ /dev/null @@ -1,16 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`expeditions` -AS SELECT `e`.`id` AS `expeditions_id`, - `e`.`agencyModeFk` AS `agency_id`, - `e`.`ticketFk` AS `ticket_id`, - `e`.`freightItemFk` AS `EsBulto`, - `e`.`created` AS `odbc_date`, - `e`.`counter` AS `counter`, - `e`.`workerFk` AS `workerFk`, - `e`.`externalId` AS `externalId`, - `p`.`itemFk` AS `Id_article` -FROM ( - `vn`.`expedition` `e` - LEFT JOIN `vn`.`packaging` `p` ON(`p`.`id` = `e`.`packagingFk`) - ) diff --git a/db/routines/vn2008/views/gestdoc.sql b/db/routines/vn2008/views/gestdoc.sql deleted file mode 100644 index f9fef2895..000000000 --- a/db/routines/vn2008/views/gestdoc.sql +++ /dev/null @@ -1,16 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`gestdoc` -AS SELECT `d`.`id` AS `id`, - `d`.`dmsTypeFk` AS `gesttip_id`, - `d`.`file` AS `file`, - `d`.`contentType` AS `contentType`, - `d`.`workerFk` AS `trabajador_id`, - `d`.`warehouseFk` AS `warehouse_id`, - `d`.`companyFk` AS `emp_id`, - `d`.`hardCopyNumber` AS `orden`, - `d`.`hasFile` AS `original`, - `d`.`reference` AS `sref`, - `d`.`description` AS `brief`, - `d`.`created` AS `odbc_date` -FROM `vn`.`dms` `d` diff --git a/db/routines/vn2008/views/gesttip.sql b/db/routines/vn2008/views/gesttip.sql deleted file mode 100644 index 663e70617..000000000 --- a/db/routines/vn2008/views/gesttip.sql +++ /dev/null @@ -1,9 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`gesttip` -AS SELECT `g`.`id` AS `id`, - `g`.`name` AS `tipo`, - `g`.`readRoleFk` AS `readRoleFk`, - `g`.`writeRoleFk` AS `writeRoleFk`, - `g`.`code` AS `code` -FROM `vn`.`dmsType` `g` diff --git a/db/routines/vn2008/views/intrastat_data.sql b/db/routines/vn2008/views/intrastat_data.sql deleted file mode 100644 index 54853b69c..000000000 --- a/db/routines/vn2008/views/intrastat_data.sql +++ /dev/null @@ -1,13 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`intrastat_data` -AS SELECT `ii`.`id` AS `id`, - `ii`.`invoiceInFk` AS `recibida_id`, - `ii`.`net` AS `neto`, - `ii`.`intrastatFk` AS `intrastat_id`, - `ii`.`amount` AS `importe`, - `ii`.`stems` AS `unidades`, - `ii`.`countryFk` AS `Paises_Id`, - `ii`.`dated` AS `odbc_date`, - `ii`.`statisticalValue` AS `valorestadistico` -FROM `vn`.`invoiceInIntrastat` `ii` diff --git a/db/routines/vn2008/views/invoiceCorrection.sql b/db/routines/vn2008/views/invoiceCorrection.sql deleted file mode 100644 index 5ed1d5844..000000000 --- a/db/routines/vn2008/views/invoiceCorrection.sql +++ /dev/null @@ -1,9 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`invoiceCorrection` -AS SELECT `ic`.`correctingFk` AS `correctingFk`, - `ic`.`correctedFk` AS `correctedFk`, - `ic`.`cplusRectificationTypeFk` AS `cplusRectificationTypeFk`, - `ic`.`siiTypeInvoiceOutFk` AS `siiTypeInvoiceOutFk`, - `ic`.`invoiceCorrectionTypeFk` AS `invoiceCorrectionTypeFk` -FROM `vn`.`invoiceCorrection` `ic` diff --git a/db/routines/vn2008/views/itemTag.sql b/db/routines/vn2008/views/itemTag.sql deleted file mode 100644 index ff247089f..000000000 --- a/db/routines/vn2008/views/itemTag.sql +++ /dev/null @@ -1,9 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`itemTag` -AS SELECT `i`.`id` AS `id`, - `i`.`itemFk` AS `itemFk`, - `i`.`tagFk` AS `tagFk`, - `i`.`value` AS `value`, - `i`.`priority` AS `priority` -FROM `vn`.`itemTag` `i` diff --git a/db/routines/vn2008/views/item_entry_in.sql b/db/routines/vn2008/views/item_entry_in.sql deleted file mode 100644 index 1cc7d21b1..000000000 --- a/db/routines/vn2008/views/item_entry_in.sql +++ /dev/null @@ -1,20 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`item_entry_in` -AS SELECT `t`.`warehouse_id` AS `warehouse_id`, - `t`.`warehouse_id_out` AS `warehouse_id_out`, - `t`.`landing` AS `dat`, - `m`.`Id_Article` AS `item_id`, - `m`.`Cantidad` AS `amount`, - `t`.`received` AS `received`, - `e`.`Redada` AS `isVirtualStock`, - `e`.`Id_Entrada` AS `entryFk` -FROM ( - ( - `vn2008`.`Compres` `m` - JOIN `vn2008`.`Entradas` `e` ON(`m`.`Id_Entrada` = `e`.`Id_Entrada`) - ) - JOIN `vn2008`.`travel` `t` ON(`e`.`travel_id` = `t`.`id`) - ) -WHERE `e`.`Inventario` = 0 - AND `m`.`Cantidad` <> 0 diff --git a/db/routines/vn2008/views/item_entry_out.sql b/db/routines/vn2008/views/item_entry_out.sql deleted file mode 100644 index d99672df8..000000000 --- a/db/routines/vn2008/views/item_entry_out.sql +++ /dev/null @@ -1,27 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`item_entry_out` -AS SELECT `t`.`warehouse_id_out` AS `warehouse_id`, - `t`.`shipment` AS `dat`, - `m`.`Id_Article` AS `item_id`, - - `m`.`Cantidad` AS `amount`, - `t`.`delivered` <> 0 - OR IFNULL(`co`.`valor`, 0) AS `delivered`, - `e`.`Id_Entrada` AS `entryFk` -FROM ( - ( - ( - `vn2008`.`Compres` `m` - JOIN `vn2008`.`Entradas` `e` ON(`m`.`Id_Entrada` = `e`.`Id_Entrada`) - ) - JOIN `vn2008`.`travel` `t` ON(`e`.`travel_id` = `t`.`id`) - ) - LEFT JOIN `vn2008`.`Compres_ok` `co` ON( - `co`.`Id_Compra` = `m`.`Id_Compra` - AND `co`.`Id_Accion` = 3 - AND `co`.`valor` <> 0 - ) - ) -WHERE `e`.`Inventario` = 0 - AND `e`.`Redada` = 0 - AND `m`.`Cantidad` <> 0 diff --git a/db/routines/vn2008/views/item_out.sql b/db/routines/vn2008/views/item_out.sql deleted file mode 100644 index 57353a6d6..000000000 --- a/db/routines/vn2008/views/item_out.sql +++ /dev/null @@ -1,17 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`item_out` -AS SELECT `t`.`warehouse_id` AS `warehouse_id`, - `t`.`Fecha` AS `dat`, - `m`.`Id_Article` AS `item_id`, - - `m`.`Cantidad` AS `amount`, - `m`.`OK` AS `ok`, - `m`.`Reservado` AS `Reservado`, - `t`.`Factura` AS `invoice`, - `m`.`Id_Movimiento` AS `saleFk`, - `m`.`Id_Ticket` AS `ticketFk` -FROM ( - `vn2008`.`Movimientos` `m` - JOIN `vn2008`.`Tickets` `t` ON(`m`.`Id_Ticket` = `t`.`Id_Ticket`) - ) -WHERE `m`.`Cantidad` <> 0 diff --git a/db/versions/10868-grayChico/00-firstScript.sql b/db/versions/10868-grayChico/00-firstScript.sql new file mode 100644 index 000000000..d0b98362c --- /dev/null +++ b/db/versions/10868-grayChico/00-firstScript.sql @@ -0,0 +1,15 @@ +REVOKE SELECT ON TABLE vn2008.expeditions FROM employee; +REVOKE SELECT, INSERT, UPDATE, DELETE ON TABLE vn2008.Gastos FROM administrative; +REVOKE SELECT ON TABLE vn2008.Facturas FROM salesPerson; +REVOKE SELECT ON TABLE vn2008.Facturas FROM logistic; +REVOKE SELECT ON TABLE vn2008.Facturas FROM palletizer; +REVOKE SELECT ON TABLE vn2008.Facturas FROM hr; +REVOKE SELECT ON TABLE vn2008.gestdoc FROM employee; +REVOKE INSERT, UPDATE ON TABLE vn2008.gestdoc FROM administrative; +REVOKE DELETE ON TABLE vn2008.gestdoc FROM hr; +REVOKE SELECT ON TABLE vn2008.gesttip FROM employee; +REVOKE SELECT ON TABLE vn2008.Greuges FROM employee; +REVOKE SELECT ON TABLE vn2008.Greuges_type FROM financial; +REVOKE SELECT ON TABLE vn2008.intrastat_data FROM buyer; +REVOKE SELECT, INSERT, UPDATE, DELETE ON TABLE vn2008.intrastat_data FROM administrative; +REVOKE SELECT, INSERT ON TABLE vn2008.invoiceCorrection FROM administrative; From f2946e41688f2f232ebeb8d02882530e3dd93f42 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 6 Feb 2024 08:04:19 +0100 Subject: [PATCH 31/69] fix: refs #6184 Requested changes --- .../route/specs/downloadCmrsZip.spec.js | 10 ++--- .../back/methods/route/specs/saveCmr.spec.js | 24 ---------- .../back/methods/ticket/specs/saveCmr.spec.js | 45 +++++++++++++++++++ 3 files changed, 50 insertions(+), 29 deletions(-) delete mode 100644 modules/route/back/methods/route/specs/saveCmr.spec.js create mode 100644 modules/ticket/back/methods/ticket/specs/saveCmr.spec.js diff --git a/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js b/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js index c6b498a77..2930fe703 100644 --- a/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js +++ b/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js @@ -2,7 +2,7 @@ const models = require('vn-loopback/server/server').models; describe('route downloadCmrsZip()', () => { beforeEach(() => { - spyOn(models.Route, 'downloadCmrsZip').and.returnValue([true]); + spyOn(models.Route, 'downloadCmrsZip').and.returnValue(true); }); it('should create a zip file with the given cmr ids', async() => { @@ -17,13 +17,13 @@ describe('route downloadCmrsZip()', () => { }; let cmrs = '1,2'; try { - await models.Route.downloadCmrsZip(ctx, cmrs); + const stream = await models.Route.downloadCmrsZip(ctx, cmrs); + + expect(stream).toBeTrue(); await tx.rollback(); } catch (e) { - error = e; await tx.rollback(); + throw e; } - - expect(error).toBeDefined(); }); }); diff --git a/modules/route/back/methods/route/specs/saveCmr.spec.js b/modules/route/back/methods/route/specs/saveCmr.spec.js deleted file mode 100644 index d9ad12ad1..000000000 --- a/modules/route/back/methods/route/specs/saveCmr.spec.js +++ /dev/null @@ -1,24 +0,0 @@ -const models = require('vn-loopback/server/server').models; - -describe('ticket saveCmr()', () => { - let ctx = {req: { - accessToken: {userId: 9} - }}; - - it(`should throw error if the cmr can't save`, async() => { - const tx = await models.Route.beginTransaction({}); - let error; - try { - const options = {transaction: tx}; - const ticket = [1]; - await models.Route.saveCmr(ctx, ticket, options); - - await tx.rollback(); - } catch (e) { - error = e; - await tx.rollback(); - } - - expect(error).toBeDefined(); - }); -}); diff --git a/modules/ticket/back/methods/ticket/specs/saveCmr.spec.js b/modules/ticket/back/methods/ticket/specs/saveCmr.spec.js new file mode 100644 index 000000000..b8e1b5083 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/saveCmr.spec.js @@ -0,0 +1,45 @@ +const models = require('vn-loopback/server/server').models; + +describe('ticket saveCmr()', () => { + beforeEach(() => { + spyOn(models.Ticket, 'saveCmr').and.returnValue(true); + }); + + it(`should throw error if the cmr can't save`, async() => { + const tx = await models.Ticket.beginTransaction({}); + const ctx = { + req: { + getLocale: () => { + return 'en'; + }, + accessToken: {userId: 9} + }, + args: {} + }; + try { + const options = {transaction: tx}; + const ticket = [1]; + await models.Ticket.saveCmr(ctx, ticket); + + const hasDmsCmr = await models.TicketDms.findOne({ + where: {ticketFk: ticket[1]}, + include: [{ + relation: 'dms', + fields: ['id'], + scope: { + relation: 'dmsType', + scope: { + where: {code: 'cmr'} + } + } + }] + }, options); + + expect(hasDmsCmr?.dms()?.dmsType()).toEqual(1); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); From 2cab007f57388b861c29a03f5fb58344d615ca47 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 6 Feb 2024 12:12:45 +0100 Subject: [PATCH 32/69] fix: refs #6184 Requested changes --- back/tests.js | 1 + .../back/methods/route/specs/downloadCmrsZip.spec.js | 6 +----- .../ticket/back/methods/ticket/specs/saveCmr.spec.js | 12 ++++-------- print/core/cluster.js | 3 ++- 4 files changed, 8 insertions(+), 14 deletions(-) diff --git a/back/tests.js b/back/tests.js index 0fb4c76ea..c48c64b77 100644 --- a/back/tests.js +++ b/back/tests.js @@ -96,6 +96,7 @@ async function test() { // runner.loadConfigFile('back/jasmine.json'); runner.loadConfig(config); + process.env.SPEC_IS_RUNNING = true; await runner.execute(); } diff --git a/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js b/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js index 2930fe703..7312a5d44 100644 --- a/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js +++ b/modules/route/back/methods/route/specs/downloadCmrsZip.spec.js @@ -1,10 +1,6 @@ const models = require('vn-loopback/server/server').models; describe('route downloadCmrsZip()', () => { - beforeEach(() => { - spyOn(models.Route, 'downloadCmrsZip').and.returnValue(true); - }); - it('should create a zip file with the given cmr ids', async() => { const tx = await models.Route.beginTransaction({}); const ctx = { @@ -19,7 +15,7 @@ describe('route downloadCmrsZip()', () => { try { const stream = await models.Route.downloadCmrsZip(ctx, cmrs); - expect(stream).toBeTrue(); + expect(stream[0]).toBeDefined(); await tx.rollback(); } catch (e) { await tx.rollback(); diff --git a/modules/ticket/back/methods/ticket/specs/saveCmr.spec.js b/modules/ticket/back/methods/ticket/specs/saveCmr.spec.js index b8e1b5083..441aae68b 100644 --- a/modules/ticket/back/methods/ticket/specs/saveCmr.spec.js +++ b/modules/ticket/back/methods/ticket/specs/saveCmr.spec.js @@ -1,10 +1,6 @@ const models = require('vn-loopback/server/server').models; describe('ticket saveCmr()', () => { - beforeEach(() => { - spyOn(models.Ticket, 'saveCmr').and.returnValue(true); - }); - it(`should throw error if the cmr can't save`, async() => { const tx = await models.Ticket.beginTransaction({}); const ctx = { @@ -18,11 +14,11 @@ describe('ticket saveCmr()', () => { }; try { const options = {transaction: tx}; - const ticket = [1]; - await models.Ticket.saveCmr(ctx, ticket); + const ticket = [2]; + await models.Ticket.saveCmr(ctx, ticket, options); const hasDmsCmr = await models.TicketDms.findOne({ - where: {ticketFk: ticket[1]}, + where: {ticketFk: ticket[0]}, include: [{ relation: 'dms', fields: ['id'], @@ -35,7 +31,7 @@ describe('ticket saveCmr()', () => { }] }, options); - expect(hasDmsCmr?.dms()?.dmsType()).toEqual(1); + expect(hasDmsCmr?.dms()?.id).toBeGreaterThanOrEqual(1); await tx.rollback(); } catch (e) { await tx.rollback(); diff --git a/print/core/cluster.js b/print/core/cluster.js index a75c4cf24..f2b2c3f21 100644 --- a/print/core/cluster.js +++ b/print/core/cluster.js @@ -35,7 +35,8 @@ module.exports = { logger.error(`[Print] => ${err.message}`); }); - cluster.on('queue', () => logger.info('Printing task initialized by pool')); + cluster.on('queue', () => + process.env.SPEC_IS_RUNNING === 'false' && logger.info('Printing task initialized by pool')); }); } }; From ffa9212861e494a7676b1c7a01ddeafde0c2e4ec Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 7 Feb 2024 10:29:42 +0100 Subject: [PATCH 33/69] fix: refs #6184 Requested changes --- modules/ticket/back/methods/ticket/specs/saveCmr.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ticket/back/methods/ticket/specs/saveCmr.spec.js b/modules/ticket/back/methods/ticket/specs/saveCmr.spec.js index 441aae68b..e7d1e5ad2 100644 --- a/modules/ticket/back/methods/ticket/specs/saveCmr.spec.js +++ b/modules/ticket/back/methods/ticket/specs/saveCmr.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('ticket saveCmr()', () => { - it(`should throw error if the cmr can't save`, async() => { + it(`should save cmr`, async() => { const tx = await models.Ticket.beginTransaction({}); const ctx = { req: { From 53a367f4b3064747a6160e7008af40ace0de55e8 Mon Sep 17 00:00:00 2001 From: robert Date: Thu, 8 Feb 2024 13:04:06 +0100 Subject: [PATCH 34/69] feat: refs #6371 cleanTablesFix --- db/routines/vn/views/agencyWarehouse.sql | 7 ------- db/routines/vn/views/clientDefaultCompany.sql | 9 -------- db/routines/vn/views/coolerPath.sql | 6 ------ db/routines/vn/views/grantGroup.sql | 7 ------- db/routines/vn2008/procedures/clean.sql | 8 ------- .../10876-goldenRoebelini/00-firstScript.sql | 21 +++++++++++++++++++ 6 files changed, 21 insertions(+), 37 deletions(-) delete mode 100644 db/routines/vn/views/agencyWarehouse.sql delete mode 100644 db/routines/vn/views/clientDefaultCompany.sql delete mode 100644 db/routines/vn/views/coolerPath.sql delete mode 100644 db/routines/vn/views/grantGroup.sql create mode 100644 db/versions/10876-goldenRoebelini/00-firstScript.sql diff --git a/db/routines/vn/views/agencyWarehouse.sql b/db/routines/vn/views/agencyWarehouse.sql deleted file mode 100644 index 6cb174544..000000000 --- a/db/routines/vn/views/agencyWarehouse.sql +++ /dev/null @@ -1,7 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn`.`agencyWarehouse` -AS SELECT `a`.`agency_id` AS `agencyFk`, - `a`.`warehouse_id` AS `warehouseFk`, - `a`.`Vista` AS `agencyType` -FROM `vn2008`.`agency_warehouse` `a` diff --git a/db/routines/vn/views/clientDefaultCompany.sql b/db/routines/vn/views/clientDefaultCompany.sql deleted file mode 100644 index 6af418a1a..000000000 --- a/db/routines/vn/views/clientDefaultCompany.sql +++ /dev/null @@ -1,9 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn`.`clientDefaultCompany` -AS SELECT `t`.`Id_Clientes_empresa` AS `id`, - `t`.`Id_Cliente` AS `clientFk`, - `t`.`empresa_id` AS `companyFk`, - `t`.`fecha_ini` AS `started`, - `t`.`fecha_fin` AS `finished` -FROM `vn2008`.`Clientes_empresa` `t` diff --git a/db/routines/vn/views/coolerPath.sql b/db/routines/vn/views/coolerPath.sql deleted file mode 100644 index 6be11e557..000000000 --- a/db/routines/vn/views/coolerPath.sql +++ /dev/null @@ -1,6 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn`.`coolerPath` -AS SELECT `c`.`cooler_path_id` AS `id`, - `c`.`description` AS `description` -FROM `vn2008`.`cooler_path` `c` diff --git a/db/routines/vn/views/grantGroup.sql b/db/routines/vn/views/grantGroup.sql deleted file mode 100644 index 267c3154e..000000000 --- a/db/routines/vn/views/grantGroup.sql +++ /dev/null @@ -1,7 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn`.`grantGroup` -AS SELECT `vn2008`.`Grupos`.`id` AS `id`, - `vn2008`.`Grupos`.`Grupo` AS `description`, - `vn2008`.`Grupos`.`observation_type_id` AS `observationTypeFk` -FROM `vn2008`.`Grupos` diff --git a/db/routines/vn2008/procedures/clean.sql b/db/routines/vn2008/procedures/clean.sql index bd8a324c6..8c36cced8 100644 --- a/db/routines/vn2008/procedures/clean.sql +++ b/db/routines/vn2008/procedures/clean.sql @@ -21,18 +21,10 @@ proc: BEGIN SET vRangeDeleteTicket = 60; DELETE FROM cdr WHERE calldate < vDate18; - DELETE FROM Monitoring WHERE ODBC_TIME < vDate; - DELETE FROM Conteo WHERE Fecha < vDate; DELETE FROM mail WHERE DATE_ODBC < vDate; - DELETE FROM expeditions_deleted WHERE odbc_date < vDate26; DELETE FROM Movimientos_mark WHERE odbc_date < vDate; DELETE FROM Splits WHERE Fecha < vDate18; - DELETE ts - FROM Tickets_stack ts - JOIN Tickets t ON ts.Id_Ticket = t.Id_Ticket - WHERE t.Fecha < vDate; - DELETE tobs FROM ticket_observation tobs JOIN Tickets t ON tobs.Id_Ticket = t.Id_Ticket diff --git a/db/versions/10876-goldenRoebelini/00-firstScript.sql b/db/versions/10876-goldenRoebelini/00-firstScript.sql new file mode 100644 index 000000000..361f3c7c8 --- /dev/null +++ b/db/versions/10876-goldenRoebelini/00-firstScript.sql @@ -0,0 +1,21 @@ +ALTER TABLE IF EXISTS vn2008.Compres_ok__ RENAME vn2008.Compres_ok; +ALTER TABLE IF EXISTS vn2008.Compres_ok COMMENT=''; + + +-- Para la tabla Monitoring +ALTER TABLE IF EXISTS vn2008.Monitoring RENAME vn2008.Monitoring__; +ALTER TABLE IF EXISTS vn2008.Monitoring__ COMMENT='refs #6371 deprecated 2024-01-11'; + +-- Para la tabla Movimientos_avisar +ALTER TABLE IF EXISTS vn2008.Movimientos_avisar RENAME vn2008.Movimientos_avisar__; +ALTER TABLE IF EXISTS vn2008.Movimientos_avisar__ COMMENT='refs #6371 deprecated 2024-01-11'; + + +-- Para la tabla Movimientos_revisar +ALTER TABLE IF EXISTS vn2008.Movimientos_revisar RENAME vn2008.Movimientos_revisar__; +ALTER TABLE IF EXISTS vn2008.Movimientos_revisar__ COMMENT='refs #6371 deprecated 2024-01-11'; + + +-- Para la tabla Proveedores_escritos +ALTER TABLE IF EXISTS vn2008.Proveedores_escritos RENAME vn2008.Proveedores_escritos__; +ALTER TABLE IF EXISTS vn2008.Proveedores_escritos__ COMMENT='refs #6371 deprecated 2024-01-11'; \ No newline at end of file From 02bf78d00a2bab69a1e2fd5b42315d1a36fd7ca5 Mon Sep 17 00:00:00 2001 From: robert Date: Fri, 9 Feb 2024 09:22:24 +0100 Subject: [PATCH 35/69] feat: refs #6830 item_getLack origin --- db/routines/vn/procedures/item_getLack.sql | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/item_getLack.sql b/db/routines/vn/procedures/item_getLack.sql index b2e3e425c..e0531e2ac 100644 --- a/db/routines/vn/procedures/item_getLack.sql +++ b/db/routines/vn/procedures/item_getLack.sql @@ -23,7 +23,8 @@ BEGIN SUM(IFNULL(sub.amount,0)) lack, i.inkFk, IFNULL(im.timed, util.midnight()) timed, - IFNULL(izc.timed, util.midnight()) minTimed + IFNULL(izc.timed, util.midnight()) minTimed, + o.name originFk FROM (SELECT item_id, warehouse_id, amount @@ -42,6 +43,7 @@ BEGIN JOIN itemCategory ic ON ic.id = it.categoryFk LEFT JOIN tmp.itemMinETD im ON im.itemFk = i.id LEFT JOIN tmp.itemZoneClosure izc ON izc.itemFk = i.id + JOIN origin o ON o.id = i.originFk WHERE w.isForTicket AND ic.display AND it.code != 'GEN' From cc863a65f65038f1e5f6c225983bef0598c999c2 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 9 Feb 2024 11:40:20 +0100 Subject: [PATCH 36/69] refactor: refs #6501 Migrated procs from vn2008 to vn --- .../vn/procedures/XDiario_reconciliation.sql | 41 ++++ .../vn/procedures/entry_getTransfer.sql | 203 ++++++++++++++++++ .../vn/procedures/supplier_statement.sql | 139 ++++++++++++ db/routines/vn/procedures/travel_detail.sql | 103 +++++++++ .../vn2008/procedures/XDiario_Quadrator.sql | 34 --- .../vn2008/procedures/supplierStatement.sql | 117 ---------- db/routines/vn2008/procedures/traslado.sql | 182 ---------------- .../vn2008/procedures/travelDetail.sql | 119 ---------- .../10878-blueSalal/00-firstScript.sql | 4 + 9 files changed, 490 insertions(+), 452 deletions(-) create mode 100644 db/routines/vn/procedures/XDiario_reconciliation.sql create mode 100644 db/routines/vn/procedures/entry_getTransfer.sql create mode 100644 db/routines/vn/procedures/supplier_statement.sql create mode 100644 db/routines/vn/procedures/travel_detail.sql delete mode 100644 db/routines/vn2008/procedures/XDiario_Quadrator.sql delete mode 100644 db/routines/vn2008/procedures/supplierStatement.sql delete mode 100644 db/routines/vn2008/procedures/traslado.sql delete mode 100644 db/routines/vn2008/procedures/travelDetail.sql create mode 100644 db/versions/10878-blueSalal/00-firstScript.sql diff --git a/db/routines/vn/procedures/XDiario_reconciliation.sql b/db/routines/vn/procedures/XDiario_reconciliation.sql new file mode 100644 index 000000000..c4724849d --- /dev/null +++ b/db/routines/vn/procedures/XDiario_reconciliation.sql @@ -0,0 +1,41 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`XDiario_reconciliation`() +BEGIN +/** + * Realiza la conciliación diaria de los asientos contables, + * identificando y notificando los asientos descuadrados + * y ajustando los saldos en caso necesario. + */ + INSERT INTO mail (receiver, subject, body) + SELECT 'cau@verdnatura.es', + 'Asientos descuadrados', + GROUP_CONCAT(CONCAT(' Asiento: ', ASIEN, ' - Importe:', recon) SEPARATOR ' | \n') + FROM ( + SELECT ASIEN, + SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) recon + FROM XDiario + WHERE NOT enlazado + GROUP BY ASIEN + HAVING ABS(SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0))) > 0.01 + ) sub + HAVING COUNT(*); + + UPDATE XDiario xd + JOIN ( + SELECT xd.id, SUBCTA, recon + FROM XDiario xd + JOIN ( + SELECT ASIEN, + SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) recon + FROM XDiario + WHERE NOT enlazado + GROUP BY ASIEN + HAVING recon + ) sub ON sub.ASIEN = xd.ASIEN + WHERE xd.SUBCTA > '5999999999' + GROUP BY xd.ASIEN + ) sub ON sub.id = xd.id + SET xd.Eurohaber = IF(IFNULL(xd.Eurohaber, 0) = 0, xd.Eurohaber, xd.Eurohaber + sub.recon), + xd.Eurodebe = IF(IFNULL(xd.Eurodebe, 0) = 0, xd.Eurodebe, xd.Eurodebe - sub.recon); +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/entry_getTransfer.sql b/db/routines/vn/procedures/entry_getTransfer.sql new file mode 100644 index 000000000..2c9fe8577 --- /dev/null +++ b/db/routines/vn/procedures/entry_getTransfer.sql @@ -0,0 +1,203 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_getTransfer`( + vSelf INT +) +BEGIN +/** + * Gestiona el traslado de productos a partir de una entrada específica. + * + * @param vSelf Id de entrada + */ + DECLARE vDateShipped DATE; + DECLARE vDateLanded DATE; + DECLARE vWarehouseIn INT; + DECLARE vWarehouseOut INT; + DECLARE vCalcVisible INT; + DECLARE vInventoryDate DATE DEFAULT vn.getInventoryDate(); + + SELECT shipped, landed, warehouseInFk, warehouseOutFk + INTO vDateShipped, vDateLanded, vWarehouseIn, vWarehouseOut + FROM vn.travel t + JOIN vn.entry e ON e.travelFk = t.id + WHERE e.id = vSelf; + + CALL vn.rate_getPrices(vDateShipped, vWarehouseIn); + + -- Traslado en almacen origen + CREATE OR REPLACE TEMPORARY TABLE tBuy + (PRIMARY KEY (itemFk), INDEX(buyFk)) + ENGINE = MEMORY + SELECT * + FROM ( + SELECT b.itemFk, b.id buyFk + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vInventoryDate AND vDateShipped + AND NOT b.isIgnored + AND b.price2 >= 0 + ORDER BY (vWarehouseOut = t.warehouseInFk) DESC, t.landed DESC + LIMIT 10000000000000000000 + ) sub + GROUP BY itemFk; + + IF vDateShipped >= util.VN_CURDATE() THEN + CALL `cache`.visible_refresh(vCalcVisible, TRUE, vWarehouseOut); + + CREATE OR REPLACE TEMPORARY TABLE tItem ( + `itemFk` int(10) unsigned NOT NULL, + `visible` int(11) NOT NULL DEFAULT 0, + `available` int(11) NOT NULL DEFAULT 0, + `visibleLanding` int(11) NOT NULL DEFAULT 0, + `availableLanding` int(11) NOT NULL DEFAULT 0, + UNIQUE INDEX i USING HASH (itemFk) + ) ENGINE = MEMORY; + + INSERT INTO tItem(itemFk, visible) + SELECT item_id itemFk, visible + FROM `cache`.visible + WHERE calc_id = vCalcVisible + AND visible; + + CALL `cache`.visible_refresh(vCalcVisible, TRUE, vWarehouseIn); + + INSERT INTO tItem(itemFk, visibleLanding) + SELECT item_id, `visible` + FROM `cache`.`visible` v + WHERE v.calc_id = vCalcVisible + AND v.`visible` + ON DUPLICATE KEY UPDATE visibleLanding = v.`visible`; + + CALL vn2008.availableTraslate(vWarehouseOut, vDateShipped, NULL); + + INSERT INTO tItem(itemFk, available) + SELECT a.item_id, a.available + FROM vn2008.availableTraslate a + WHERE a.available + ON DUPLICATE KEY UPDATE available = a.available; + + CALL vn2008.availableTraslate(vWarehouseIn, vDateLanded, vWarehouseOut); + + INSERT INTO tItem(itemFk, availableLanding) + SELECT a.item_id, a.available + FROM vn2008.availableTraslate a + WHERE a.available + ON DUPLICATE KEY UPDATE availableLanding = a.available; + ELSE + CALL vn.item_getStock(vWarehouseOut, vDateShipped, NULL); + + CREATE OR REPLACE TEMPORARY TABLE tItem + (UNIQUE INDEX i USING HASH (itemFk)) + ENGINE = MEMORY + SELECT itemFk, + `visible`, + available, + 0 visibleLanding, + 0 availableLanding + FROM tmp.itemList; + END IF; + + CALL vn.buyUltimateFromInterval(vWarehouseIn,vInventoryDate, vDateLanded); + + CREATE OR REPLACE TEMPORARY TABLE tTransfer + ENGINE = MEMORY + SELECT it.categoryFk, + i.typeFk, + i.id itemFk, + i.name item, + i.`size`, + i.category, + i.inkFk, + o.code originCode, + b2.quantity, + i.stems, + CAST(ti.visible AS DECIMAL(10,0)) vis1, + CAST(ti.available AS DECIMAL(10,0)) ava1, + CAST(ti.visibleLanding AS DECIMAL(10,0)) vis2, + CAST(ti.availableLanding AS DECIMAL(10,0)) ava, + COALESCE(b2.`grouping`, b.`grouping`) `grouping`, + COALESCE(b2.packing, b.packing) packing, + COALESCE(b3.groupingMode, b2.groupingMode, b.groupingMode) package, + IFNULL(p.name, s.nickname) productor, + b.packagingFk, + b2.id buyFk, + b2.stickers, + b.ektFk, + it.workerFk, + pa.volume, + IFNULL(pa.width, 0) width, + IFNULL(pa.`depth`, 0) `depth`, + IFNULL(pa.height, 0) height, + IFNULL(b.buyingValue, 0) buyingValue, + IFNULL(b.comissionValue, 0) comissionValue, + IFNULL(b.freightValue, 0) freightValue, + am.m3, + e.commission, + pa.isPackageReturnable, + IFNULL(pa2.value, pa.value) `value`, + r.rate3, + r.rate2, + it.promo, + b.`grouping` groupingOrigin, + b.packing packingOrigin, + b.id buyFkOrigin, + pa.returnCost, + b.weight + FROM vn.item i + JOIN tItem ti ON ti.itemFk = i.id + LEFT JOIN vn.producer p ON p.id = i.producerFk + LEFT JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN vn.origin o ON o.id = i.originFk + LEFT JOIN tBuy lb ON lb.itemFk = i.id + LEFT JOIN vn.buy b ON b.id = lb.buyFk + LEFT JOIN vn.packaging pa ON pa.id = b.packagingFk + LEFT JOIN vn.entry e2 ON e2.id = b.entryFk + LEFT JOIN vn.supplier s ON s.id = e2.supplierFk + LEFT JOIN vn.entry e ON e.id = vSelf + LEFT JOIN vn.travel tr ON tr.id = e.travelFk + LEFT JOIN vn.agencyMode am ON am.id = tr.agencyModeFk + LEFT JOIN vn.buy b2 ON b2.itemFk = i.id + AND b2.entryFk = vSelf + LEFT JOIN vn.packaging pa2 ON pa2.id = b.packagingFk + LEFT JOIN tmp.rate r ON TRUE + LEFT JOIN tmp.buyUltimateFromInterval bufi ON bufi.itemFk = i.id + LEFT JOIN vn.buy b3 ON b3.id = bufi.buyFk + WHERE ic.display + AND NOT e.isRaid + AND (ti.visible != 0 OR ti.available != 0) + ORDER BY i.typeFk, i.name, i.id, i.size, i.category, o.name; + + CREATE INDEX tIndex USING HASH ON tTransfer (itemFk); + + SET @carriage := 0; + SET @comission := 0; + SET @packaging := 0; + SET @rate3 := 0; + SET @cost := 0; + SELECT *, + quantity - MOD(quantity , `grouping`) subQuantity, + MOD(quantity, `grouping`) soll, + ROUND((IF(volume > 0,volume, width * `depth` * IF(height = 0, `size` + 10, height))) / packing, 0) cm3, + buyingValue + comissionValue + freightValue Cost, + @carriage := ROUND((IF(volume > 0, volume, width * `depth` * IF(height = 0, `size` + 10, height))) * m3 / 1000000 / Packing, 3) carriage, + @comission := ROUND((buyingValue + comissionValue + freightValue) * commission / 100, 3) commission, + ROUND(@packaging := (returnCost + IF(isPackageReturnable != 0, 0, value)) / packing, 3) packaging, + @cost := IFNULL((buyingValue + comissionValue + freightValue), 0) + + IFNULL(@packaging, 0) + + IFNULL(@carriage, 0) + + IFNULL(@comission, 0) cost, + @rate3 := ROUND(@cost / ( (100 - rate3 - promo) / 100), 2) rate3, + ROUND(@rate3 * (1 + ((rate2 - rate3)/100)), 2) rate2, + FALSE selected + FROM tTransfer; + + DROP TEMPORARY TABLE IF EXISTS + tTransfer, + tItem, + tBuy, + tmp.buyUltimateFromInterval, + tmp.rate, + tmp.itemList; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/supplier_statement.sql b/db/routines/vn/procedures/supplier_statement.sql new file mode 100644 index 000000000..406286e9d --- /dev/null +++ b/db/routines/vn/procedures/supplier_statement.sql @@ -0,0 +1,139 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplier_statement`( + vSupplierFk INT, + vCurrencyFk INT, + vCompanyFk INT, + vOrderBy VARCHAR(15), + vIsConciliated BOOL +) +BEGIN +/** + * Crea un estado de cuenta de proveedores calculando + * los saldos en euros y en la moneda especificada. + * + * @param vSupplierFk Id del proveedor + * @param vCurrencyFk Id de la moneda + * @param vCompanyFk Id de la empresa + * @param vOrderBy Criterio de ordenación + * @param vIsConciliated Indica si está conciliado o no + * @return tmp.supplierStatement + */ + SET @euroBalance:= 0; + SET @currencyBalance:= 0; + + CREATE OR REPLACE TEMPORARY TABLE tmp.supplierStatement + ENGINE = MEMORY + SELECT *, + @euroBalance:= ROUND( + @euroBalance + IFNULL(paymentEuros, 0) - + IFNULL(invoiceEuros, 0), 2 + ) euroBalance, + @currencyBalance:= ROUND( + @currencyBalance + IFNULL(paymentCurrency, 0) - + IFNULL(invoiceCurrency, 0), 2 + ) currencyBalance + FROM ( + SELECT * FROM + ( + SELECT NULL bankFk, + ii.companyFk, + ii.serial, + ii.id, + CASE + WHEN vOrderBy = 'issued' THEN ii.issued + WHEN vOrderBy = 'bookEntried' THEN ii.bookEntried + WHEN vOrderBy = 'booked' THEN ii.booked + WHEN vOrderBy = 'dueDate' THEN iid.dueDated + END dated, + CONCAT('S/Fra ', ii.supplierRef) sref, + IF(ii.currencyFk > 1, + ROUND(SUM(iid.foreignValue) / SUM(iid.amount), 3), + NULL + ) changeValue, + CAST(SUM(iid.amount) AS DECIMAL(10,2)) invoiceEuros, + CAST(SUM(iid.foreignValue) AS DECIMAL(10,2)) invoiceCurrency, + NULL paymentEuros, + NULL paymentCurrency, + ii.currencyFk, + ii.isBooked, + c.code, + 'invoiceIn' statementType + FROM invoiceIn ii + JOIN invoiceInDueDay iid ON iid.invoiceInFk = ii.id + JOIN currency c ON c.id = ii.currencyFk + WHERE ii.issued > '2014-12-31' + AND ii.supplierFk = vSupplierFk + AND vCurrencyFk IN (ii.currencyFk, 0) + AND vCompanyFk IN (ii.companyFk, 0) + AND (vIsConciliated = ii.isBooked OR NOT vIsConciliated) + GROUP BY iid.id + UNION ALL + SELECT p.bankFk, + p.companyFk, + NULL, + p.id, + CASE + WHEN vOrderBy = 'issued' THEN p.received + WHEN vOrderBy = 'bookEntried' THEN p.received + WHEN vOrderBy = 'booked' THEN p.received + WHEN vOrderBy = 'dueDate' THEN p.dueDated + END, + CONCAT(IFNULL(pm.name, ''), + IF(pn.concept <> '', + CONCAT(' : ', pn.concept), + '') + ), + IF(p.currencyFk > 1, p.divisa / p.amount, NULL), + NULL, + NULL, + p.amount, + p.divisa, + p.currencyFk, + p.isConciliated, + c.code, + 'payment' + FROM payment p + LEFT JOIN currency c ON c.id = p.currencyFk + LEFT JOIN bank b ON b.id = p.bankFk + LEFT JOIN payMethod pm ON pm.id = p.payMethodFk + LEFT JOIN promissoryNote pn ON pn.paymentFk = p.id + WHERE p.received > '2014-12-31' + AND p.supplierFk = vSupplierFk + AND vCurrencyFk IN (p.currencyFk, 0) + AND vCompanyFk IN (p.companyFk, 0) + AND (vIsConciliated = p.isConciliated OR NOT vIsConciliated) + UNION ALL + SELECT NULL, + companyFk, + NULL, + se.id, + CASE + WHEN vOrderBy = 'issued' THEN se.dated + WHEN vOrderBy = 'bookEntried' THEN se.dated + WHEN vOrderBy = 'booked' THEN se.dated + WHEN vOrderBy = 'dueDate' THEN se.dueDated + END, + se.description, + 1, + amount, + NULL, + NULL, + NULL, + currencyFk, + isConciliated, + c.`code`, + 'expense' + FROM supplierExpense se + JOIN currency c ON c.id = se.currencyFk + WHERE se.supplierFk = vSupplierFk + AND vCurrencyFk IN (se.currencyFk,0) + AND vCompanyFk IN (se.companyFk,0) + AND (vIsConciliated = se.isConciliated OR NOT vIsConciliated) + ) sub + ORDER BY (dated IS NULL AND NOT isBooked), + dated, + IF(vOrderBy = 'dueDate', id, NULL) + LIMIT 10000000000000000000 + ) t; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/travel_detail.sql b/db/routines/vn/procedures/travel_detail.sql new file mode 100644 index 000000000..d805f0ca9 --- /dev/null +++ b/db/routines/vn/procedures/travel_detail.sql @@ -0,0 +1,103 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_detail`() +BEGIN +/** + * Devuelve los detalles de los vuelos que tienen + * un almacén de salida en Ecuador o Colombia. + */ + DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL 12 WEEK; + SELECT IFNULL(CONCAT(" ", entryFk), travelFk) travelAndEntry, + sub.* + FROM ( + SELECT tr.id travelFk, + NULL entryFk, + TRUE isTravel, + am.name agency, + tr.ref, + tr.shipped, + wOut.name originBoxes, + tr.landed, + wIn.name destination, + SUM(b.stickers) stickers, + NULL evaNotes, + tr.kg, + CAST(SUM(b.weight * b.stickers) AS INT) loadedkg, + CAST( + SUM(vc.aerealVolumetricDensity * + b.stickers * + IF(p.volume, + p.volume, + p.width * p.depth * p.height + ) / 1000000 + ) AS INT + ) volumeKg, + NULL loadPriority, + NULL invoiceAmount, + s.nickname freighter, + NULL reference + FROM travel tr + LEFT JOIN supplier s ON s.id = tr.cargoSupplierFk + LEFT JOIN entry e ON e.travelFk = tr.id + LEFT JOIN buy b ON b.entryFk = e.id + LEFT JOIN packaging p ON p.id = b.packagingFk + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN itemType it ON it.id = i.typeFk + JOIN warehouse wIn ON wIn.id = tr.warehouseInFk + JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk + JOIN agencyMode am ON am.id = tr.agencyModeFk + JOIN volumeConfig vc + WHERE tr.landed >= vDateFrom + AND (wOut.code = "col" OR wOut.code = "ecu") + GROUP BY tr.id + UNION ALL + SELECT e.travelFk, + e.id, + FALSE, + s.name, + e.invoiceNumber, + tr.shipped, + wOut.name, + tr.landed, + wIn.name, + SUM(b.stickers), + e.evaNotes, + NULL, + CAST(SUM(b.weight * b.stickers) AS INT), + CAST( + SUM(vc.aerealVolumetricDensity * + b.stickers * + IF(p.volume, + p.volume, + p.width * p.depth * p.height + ) / 1000000 + ) AS INT + ), + loadPriority, + e.invoiceAmount, + s2.nickname, + e.reference + FROM entry e + JOIN buy b ON b.entryFk = e.id + JOIN packaging p ON p.id = b.packagingFk + JOIN item i ON i.id = b.itemFk + JOIN itemType it ON it.id = i.typeFk + JOIN supplier s ON s.id = e.supplierFk + JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN supplier s2 ON s2.id = tr.cargoSupplierFk + JOIN warehouse wIn ON wIn.id = tr.warehouseInFk + JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk + JOIN volumeConfig vc + WHERE tr.landed >= vDateFrom + AND (wOut.code = "col" OR wOut.code = "ecu") + GROUP BY e.id + ) sub + ORDER BY landed ASC, + shipped ASC, + travelFk, + isTravel DESC, + (loadPriority > 0) DESC, + loadPriority, + agency, + evaNotes; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn2008/procedures/XDiario_Quadrator.sql b/db/routines/vn2008/procedures/XDiario_Quadrator.sql deleted file mode 100644 index 93ddc231d..000000000 --- a/db/routines/vn2008/procedures/XDiario_Quadrator.sql +++ /dev/null @@ -1,34 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`XDiario_Quadrator`() -BEGIN - INSERT INTO vn.mail (receiver, subject, body) - SELECT 'cau@verdnatura.es', - 'asientos descuadrados', - group_concat(CONCAT(' Asiento: ', ASIEN, '- importe:', quadre) SEPARATOR ' \r\n ') - FROM ( - SELECT ASIEN, SUM(IFNULL(ROUND(Eurodebe,2),0))- SUM(IFNULL(ROUND(EUROHABER,2),0)) quadre - FROM vn.XDiario - WHERE enlazado = FALSE - GROUP BY ASIEN - HAVING ABS(SUM(IFNULL(ROUND(Eurodebe,2),0))- SUM(IFNULL(ROUND(EUROHABER,2),0))) > 0.01 - ) t - HAVING count(*) > 0; - - UPDATE vn.XDiario XD - INNER JOIN( - SELECT XD.id, SUBCTA, Quadre FROM vn.XDiario XD - INNER JOIN ( - SELECT ASIEN, SUM(IFNULL(ROUND(Eurodebe,2),0))- SUM(IFNULL(ROUND(EUROHABER,2),0)) as Quadre - FROM vn.XDiario - WHERE enlazado = FALSE - GROUP BY ASIEN - HAVING Quadre != 0 - ) sub USING(ASIEN) - WHERE SUBCTA > '5999999999' - GROUP BY ASIEN - ) sub2 USING(id) - SET Eurohaber = IF(IFNULL(Eurohaber,0) = 0, Eurohaber, Eurohaber + Quadre), - Eurodebe = IF(IFNULL(Eurodebe,0) = 0, Eurodebe, Eurodebe - Quadre); - -END$$ -DELIMITER ; diff --git a/db/routines/vn2008/procedures/supplierStatement.sql b/db/routines/vn2008/procedures/supplierStatement.sql deleted file mode 100644 index 4701e3e21..000000000 --- a/db/routines/vn2008/procedures/supplierStatement.sql +++ /dev/null @@ -1,117 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`supplierStatement`(vSupplierFk INT, vCurrencyFk INT, vCompanyFk INT, vOrderBy VARCHAR(15), vOnlyConciliated BIT) -BEGIN - SET @saldo_eur:= 0; - SET @saldo_div:= 0; -select vOnlyConciliated; - DROP TEMPORARY TABLE IF EXISTS tmp.supplierStatement; - - CREATE TEMPORARY TABLE tmp.supplierStatement ENGINE = MEMORY - SELECT - *, - @saldo_eur:= round(@saldo_eur + IFNULL(Pago_Euros, 0) - IFNULL(Fac_Euros, 0) ,2 ) AS saldo_eur, - @saldo_div:= round(@saldo_div + IFNULL(Pago_Divisas, 0) - IFNULL(Fac_Divisas, 0) ,2 ) AS saldo_div - FROM - (SELECT * FROM - (SELECT - NULL as banco_id, - r.empresa_id, - r.serie, - r.id, - CASE - WHEN vOrderBy = 'issued' THEN r.fecha - WHEN vOrderBy = 'bookEntried' THEN r.bookEntried - WHEN vOrderBy = 'booked' THEN r.dateBooking - WHEN vOrderBy = 'dueDate' THEN rv.fecha - END AS fecha, - CONCAT('S/Fra ', r.sref) sref, - if(r.moneda_id > 1,round(sum(divisa) / sum(cantidad),3),NULL) val_cambio, - CAST(sum(cantidad) as DECIMAL(10,2)) as Fac_Euros, - CAST(sum(divisa) as DECIMAL(10,2)) as Fac_Divisas, - NULL AS Pago_Euros, - NULL AS Pago_Divisas, - r.moneda_id, - r.contabilizada, - Moneda, - NULL as pago_sdc_id, - 'invoiceIn' statementType - FROM - recibida r - JOIN recibida_vencimiento rv on rv.recibida_id = r.id - JOIN Monedas m on m.Id_Moneda = r.moneda_id - WHERE - r.fecha > '2014-12-31' - AND r.proveedor_id = vSupplierFk - AND vCurrencyFk IN (r.moneda_id, 0) - AND vCompanyFk IN (r.empresa_id,0) - AND (vOnlyConciliated = r.contabilizada OR NOT vOnlyConciliated) - GROUP BY rv.id - - UNION ALL - SELECT - p.id_banco, - p.empresa_id, - NULL, - p.id, - CASE - WHEN vOrderBy = 'issued' THEN p.Fecha - WHEN vOrderBy = 'bookEntried' THEN p.Fecha - WHEN vOrderBy = 'booked' THEN p.Fecha - WHEN vOrderBy = 'dueDate' THEN p.dueDated - END AS fecha, - CONCAT(IFNULL(name, ''), IF(pre.concepto <> '', CONCAT(' : ', pre.concepto), '')), - if(p.id_moneda > 1, p.divisa / importe, NULL) tip_cambio, - NULL, - NULL, - p.importe, - p.divisa, - p.id_moneda, - p.conciliado, - Moneda, - NULL as pago_sdc_id, - 'payment' statementType - FROM - pago p - LEFT JOIN Monedas ON Monedas.Id_Moneda = p.id_moneda - LEFT JOIN Bancos ON p.id_banco = Bancos.Id_banco - LEFT JOIN pay_met pm ON p.pay_met_id = pm.id - LEFT JOIN Pagares pre ON pre.pago_id = p.id - WHERE - Fecha > '2014-12-31' - AND p.Id_Proveedor = vSupplierFk - AND vCurrencyFk IN (p.id_moneda,0) - AND vCompanyFk IN (p.empresa_id,0) - AND (vOnlyConciliated = p.conciliado OR NOT vOnlyConciliated) - UNION ALL - SELECT - NULL, - companyFk, - NULL, - se.id, - CASE - WHEN vOrderBy = 'issued' THEN se.dated - WHEN vOrderBy = 'bookEntried' THEN se.dated - WHEN vOrderBy = 'booked' THEN se.dated - WHEN vOrderBy = 'dueDate' THEN se.dueDated - END AS fecha, - se.description, - 1 tip_cambio, - amount, - NULL, - NULL, - NULL, - currencyFk, - isConciliated, - c.`code`, - NULL, - 'expense' statementType - FROM vn.supplierExpense se - JOIN vn.currency c on c.id= se.currencyFk - WHERE se.supplierFk = vSupplierFk - AND vCurrencyFk IN (se.currencyFk,0) - AND vCompanyFk IN (se.companyFk,0) - AND (vOnlyConciliated = se.isConciliated OR NOT vOnlyConciliated) - ) AS SUB - ORDER BY (fecha is null and NOT contabilizada),fecha, IF(vOrderBy = 'dueDate', id, NULL) LIMIT 10000000000000000000) t; -END$$ -DELIMITER ; diff --git a/db/routines/vn2008/procedures/traslado.sql b/db/routines/vn2008/procedures/traslado.sql deleted file mode 100644 index 9c1e5efe7..000000000 --- a/db/routines/vn2008/procedures/traslado.sql +++ /dev/null @@ -1,182 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`traslado`(IN i_entrada INTEGER) -BEGIN - DECLARE dateShipment DATE; - DECLARE dateLanding DATE; - DECLARE warehouseShipment INTEGER; - DECLARE warehouseLanding INTEGER; - DECLARE v_calc_visible INTEGER; - DECLARE vInventoryDate DATE; - - SET vInventoryDate := vn.getInventoryDate(); - SELECT shipment, landing, warehouse_id_out, warehouse_id - INTO dateShipment, dateLanding, warehouseShipment, warehouseLanding - FROM travel t JOIN Entradas e ON t.id = e.travel_id - WHERE Id_Entrada = i_entrada; - - CALL vn.rate_getPrices(dateShipment, warehouseLanding); - - -- Traslado en almacen origen - - DROP TEMPORARY TABLE IF EXISTS buy_edi_temp; - CREATE TEMPORARY TABLE buy_edi_temp - (KEY (Id_Article), INDEX(Id_Compra)) ENGINE = MEMORY - SELECT * - FROM (SELECT c.Id_Article, c.Id_Compra - FROM Compres c INNER JOIN Entradas e USING(Id_Entrada) - INNER JOIN travel t ON t.id = e.travel_id - WHERE t.landing BETWEEN vInventoryDate AND dateShipment - AND c.Novincular = FALSE - AND c.Tarifa2 >= 0 - ORDER BY (warehouseShipment = t.warehouse_id) DESC, t.landing DESC - LIMIT 10000000000000000000) t - GROUP BY Id_Article; - - IF dateShipment >= util.VN_CURDATE() THEN - CALL `cache`.visible_refresh(v_calc_visible, TRUE, warehouseShipment); - - DROP TEMPORARY TABLE IF EXISTS tmp.item; - - CREATE TEMPORARY TABLE tmp.item ( - `itemFk` int(10) unsigned NOT NULL, - `visible` int(11) NOT NULL DEFAULT 0, - `available` int(11) NOT NULL DEFAULT 0, - `visibleLanding` int(11) NOT NULL DEFAULT 0, - `availableLanding` int(11) NOT NULL DEFAULT 0, - UNIQUE INDEX i USING HASH (itemFk) - ) ENGINE = MEMORY; - - INSERT INTO tmp.item(itemFk, visible) - SELECT item_id itemFk, visible - FROM `cache`.visible - WHERE calc_id = v_calc_visible - AND visible; - - CALL `cache`.visible_refresh(v_calc_visible, TRUE, warehouseLanding); - - INSERT INTO tmp.item(itemFk, visibleLanding) - SELECT item_id, `visible` - FROM `cache`.`visible` v - WHERE v.calc_id = v_calc_visible - AND v.`visible` - ON DUPLICATE KEY UPDATE visibleLanding = v.`visible`; - - CALL availableTraslate(warehouseShipment, dateShipment, NULL); - - INSERT INTO tmp.item(itemFk, available) - SELECT a.item_id, a.available - FROM availableTraslate a - WHERE a.available - ON DUPLICATE KEY UPDATE available = a.available; - - CALL availableTraslate(warehouseLanding, dateLanding, warehouseShipment); - - INSERT INTO tmp.item(itemFk, availableLanding) - SELECT a.item_id, a.available - FROM availableTraslate a - WHERE a.available - ON DUPLICATE KEY UPDATE availableLanding = a.available; - ELSE - CALL vn.item_getStock(warehouseShipment, dateShipment, NULL); - - DROP TEMPORARY TABLE IF EXISTS tmp.item; - CREATE TEMPORARY TABLE tmp.item (UNIQUE INDEX i USING HASH (itemFk)) ENGINE = MEMORY - SELECT itemFk, `visible`, available , 0 visibleLanding, 0 availableLanding - FROM tmp.itemList; - - DROP TEMPORARY TABLE tmp.itemList; - END IF; - - CALL vn.buyUltimateFromInterval(warehouseLanding,vInventoryDate, dateLanding); - - DROP TEMPORARY TABLE IF EXISTS Traslados; - CREATE TEMPORARY TABLE Traslados ENGINE = MEMORY - SELECT tp.Id_Tipo AS Tipo, - tp.reino_id, - ar.tipo_id, - ar.Id_Article AS article_id, - ar.Article, - ar.Medida, - ar.Categoria, - ar.Color, - Origen.abreviatura as Origen, - CE.Cantidad, - ar.Tallos, - CAST(AIM.visible AS DECIMAL(10,0)) as vis1, - CAST(AIM.available AS DECIMAL(10,0)) as dis1, - CAST(AIM.visibleLanding AS DECIMAL(10,0)) as vis2, - CAST(AIM.availableLanding AS DECIMAL(10,0)) as dis2, - COALESCE(CE.`grouping`, C.`grouping`) as `grouping`, - COALESCE(CE.Packing, C.Packing) as Packing, - COALESCE(cl.caja, CE.caja, C.caja) as caja, - IFNULL(p.name, P2.Alias) AS Productor, - C.Id_Cubo, - 1 Tinta, - CE.Id_Compra, - CE.Etiquetas, - C.buy_edi_id, - tp.Id_Trabajador, - CB.Volumen, - IFNULL(CB.x,0) x, - IFNULL(CB.y,0) y, - IFNULL(CB.z,0) z, - IFNULL(C.Costefijo,0) Costefijo, - IFNULL(C.Comisionfija,0) Comisionfija, - IFNULL(C.Portefijo,0) Portefijo, - A.m3, - E.comision, - CB.Retornable, - IFNULL(CEB.Valor,CB.Valor) Valor, - r.rate3 t3, r.rate2 t2, tp.promo, - C.`grouping` groupingOrigin, - C.Packing PackingOrigin, - C.Id_Compra CompraOrigin, - CB.costeRetorno, - C.weight - FROM Articles ar - JOIN tmp.item AIM ON AIM.itemFk = ar.Id_Article - LEFT JOIN producer p ON p.producer_id = ar.producer_id - LEFT JOIN Tipos tp ON tp.tipo_id = ar.tipo_id - JOIN vn.itemCategory ic ON ic.id = tp.reino_id - LEFT JOIN Origen ON Origen.id = ar.id_origen - LEFT JOIN buy_edi_temp lb ON lb.Id_Article = ar.Id_Article - LEFT JOIN Compres C ON C.Id_Compra = lb.Id_Compra - LEFT JOIN Cubos CB ON CB.Id_Cubo = C.Id_Cubo - LEFT JOIN Entradas E2 ON E2.Id_Entrada = C.Id_Entrada - LEFT JOIN Proveedores P2 ON P2.Id_Proveedor = E2.Id_Proveedor - LEFT JOIN Entradas E ON E.Id_Entrada = i_entrada - LEFT JOIN travel TR ON TR.id = E.travel_id - LEFT JOIN Agencias A ON A.Id_Agencia = TR.agency_id - LEFT JOIN Compres CE ON CE.Id_Article = ar.Id_Article AND CE.Id_Entrada = i_entrada - LEFT JOIN Cubos CEB ON CEB.Id_Cubo = CE.Id_Cubo - LEFT JOIN tmp.rate r ON TRUE - LEFT JOIN tmp.buyUltimateFromInterval bufi ON bufi.itemFk = ar.Id_Article - LEFT JOIN Compres cl ON cl.Id_Compra = bufi.buyFk - WHERE ic.display - AND E.Redada = FALSE - AND (AIM.visible != 0 OR AIM.available != 0) - ORDER BY tipo_id, Article, article_id, Medida, Categoria, Origen; - - CREATE INDEX tindex USING HASH ON Traslados (article_id); - - SELECT t.*, - Cantidad - MOD(Cantidad , `grouping`) as Subcantidad, - MOD(Cantidad , `grouping`) as Soll, - ROUND((IF(Volumen > 0,Volumen,x * y * IF(z = 0, Medida + 10, z))) / Packing,0) as cm3, - Costefijo + Comisionfija + Portefijo AS Cost, - @porte := ROUND((IF(Volumen > 0,Volumen,x * y * IF(z = 0, Medida + 10, z))) * m3 / 1000000 / Packing ,3) AS Porte, - @comision := ROUND((Costefijo + Comisionfija + Portefijo) * comision / 100 ,3) AS Comision, - ROUND(@embalaje := (costeRetorno + IF(Retornable != 0, 0, Valor)) / packing ,3) AS Embalaje, - @coste := IFNULL((Costefijo + Comisionfija + Portefijo),0) + IFNULL(@embalaje,0) + IFNULL(@porte,0) + IFNULL(@comision,0) AS Coste, - @t3 := ROUND(@coste / ( (100 - t3 - t.promo)/100),2) AS Tarifa3, - ROUND(@t3 * (1 + ((t2 - t3)/100)),2) AS Tarifa2, - 0 selected - FROM Traslados t; - - DROP TEMPORARY TABLE Traslados; - DROP TEMPORARY TABLE tmp.item; - DROP TEMPORARY TABLE buy_edi_temp; - DROP TEMPORARY TABLE tmp.buyUltimateFromInterval; - DROP TEMPORARY TABLE tmp.rate; -END$$ -DELIMITER ; diff --git a/db/routines/vn2008/procedures/travelDetail.sql b/db/routines/vn2008/procedures/travelDetail.sql deleted file mode 100644 index 39ed4f7b8..000000000 --- a/db/routines/vn2008/procedures/travelDetail.sql +++ /dev/null @@ -1,119 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`travelDetail`() -BEGIN -/** - * Returns the details of the travels that have a departure warehouse in Ecuador or Colombia. - */ - DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL 12 WEEK; - SELECT IFNULL(CONCAT(" ",Entrada),travel) travelAndEntry, - travel, - Entrada, - IsTravel, - Agencia, - ref, - shipment, - OrigenCajas, - landing, - Destino, - Etiquetas, - Notas_Eva, - kg, - loadedKg, - volumeKg, - loadPriority, - invoiceAmount, - Carguera, - reference - FROM - (SELECT TRUE IsTravel, - tr.id travel, - NULL Entrada, - ag.Agencia, - tr.ref, - tr.shipment, - wo.name OrigenCajas, - tr.landing, - w.name Destino, - SUM(c.Etiquetas) Etiquetas, - NULL Notas_Eva, - tr.kg, - CAST(SUM(c.weight * c.Etiquetas) AS INT) loadedkg, - CAST( - SUM(vc.aerealVolumetricDensity * - c.Etiquetas * - IF(cb.Volumen, - cb.Volumen, - cb.X * cb.Y * cb.Z - ) / 1000000 - ) AS INT - ) volumeKg, - NULL loadPriority, - NULL invoiceAmount, - pc.Alias Carguera, - NULL reference - FROM travel tr - LEFT JOIN Proveedores pc ON pc.Id_Proveedor = tr.cargoSupplierFk - LEFT JOIN Entradas e ON e.travel_id = tr.id - LEFT JOIN Compres c ON c.Id_Entrada = e.Id_Entrada - LEFT JOIN Cubos cb ON cb.Id_Cubo = c.Id_Cubo - LEFT JOIN Articles a ON a.Id_Article = c.Id_Article - LEFT JOIN Tipos tp ON tp.tipo_id = a.tipo_id - JOIN warehouse w ON w.id = tr.warehouse_id - JOIN warehouse wo ON wo.id = tr.warehouse_id_out - JOIN Agencias ag ON ag.Id_Agencia = tr.agency_id - JOIN vn.volumeConfig vc - WHERE tr.landing >= vDateFrom - AND (wo.name="Colombia" OR wo.name="Ecuador") - GROUP BY tr.id - UNION ALL - SELECT 0 IsTravel, - e.travel_id travel, - e.Id_Entrada, - p.Proveedor, - e.Referencia, - tr.shipment, - wo.name OrigenCajas, - tr.landing, - w.name Destino, - SUM(Etiquetas) Etiquetas, - e.Notas_Eva, - NULL kg, - CAST(SUM(c.weight * c.Etiquetas) AS INT) loadedkg, - CAST( - SUM(vc.aerealVolumetricDensity * - c.Etiquetas * - IF(cb.Volumen, - cb.Volumen, - cb.X * cb.Y * cb.Z - ) / 1000000 - ) AS INT - ) volumeKg, - loadPriority, - e.invoiceAmount, - pc.Alias carguera, - e.reference - FROM Entradas e - JOIN Compres c ON c.Id_Entrada = e.Id_Entrada - JOIN Cubos cb ON cb.Id_Cubo = c.Id_Cubo - JOIN Articles a ON a.Id_Article = c.Id_Article - JOIN Tipos tp ON tp.tipo_id = a.tipo_id - JOIN Proveedores p ON p.Id_Proveedor = e.Id_Proveedor - JOIN travel tr ON tr.id = e.travel_id - LEFT JOIN Proveedores pc ON pc.Id_Proveedor = tr.cargoSupplierFk - JOIN warehouse w ON w.id = tr.warehouse_id - JOIN warehouse wo ON wo.id = tr.warehouse_id_out - JOIN vn.volumeConfig vc - WHERE tr.landing >= vDateFrom - AND (wo.name="Colombia" OR wo.name="Ecuador") - GROUP BY e.Id_Entrada - ) sub - ORDER BY landing ASC, - shipment ASC, - travel, - IsTravel DESC, - (loadPriority > 0) DESC, - loadPriority, - Agencia, - Notas_Eva; -END$$ -DELIMITER ; diff --git a/db/versions/10878-blueSalal/00-firstScript.sql b/db/versions/10878-blueSalal/00-firstScript.sql new file mode 100644 index 000000000..49511166b --- /dev/null +++ b/db/versions/10878-blueSalal/00-firstScript.sql @@ -0,0 +1,4 @@ +GRANT EXECUTE ON PROCEDURE vn.supplier_statement TO administrative, buyer, hrBoss; +GRANT EXECUTE ON PROCEDURE vn.XDiario_reconciliation TO adminBoss; +GRANT EXECUTE ON PROCEDURE vn.travel_detail TO buyer; +GRANT EXECUTE ON PROCEDURE vn.entry_transfer TO claimManager, buyer; From 22e6f547faad8a0a2e2918d42c659902100c7c18 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 9 Feb 2024 11:41:23 +0100 Subject: [PATCH 37/69] refactor: refs #6501 Migrated procs from vn2008 to vn --- db/versions/10878-blueSalal/00-firstScript.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/versions/10878-blueSalal/00-firstScript.sql b/db/versions/10878-blueSalal/00-firstScript.sql index 49511166b..1c1894c0e 100644 --- a/db/versions/10878-blueSalal/00-firstScript.sql +++ b/db/versions/10878-blueSalal/00-firstScript.sql @@ -1,4 +1,4 @@ GRANT EXECUTE ON PROCEDURE vn.supplier_statement TO administrative, buyer, hrBoss; GRANT EXECUTE ON PROCEDURE vn.XDiario_reconciliation TO adminBoss; GRANT EXECUTE ON PROCEDURE vn.travel_detail TO buyer; -GRANT EXECUTE ON PROCEDURE vn.entry_transfer TO claimManager, buyer; +GRANT EXECUTE ON PROCEDURE vn.entry_getTransfer TO claimManager, buyer; From dbe63ad11b675ed22794fd32a0f1e298de5a7209 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 9 Feb 2024 11:45:31 +0100 Subject: [PATCH 38/69] refactor: refs #6501 Fix grant errors --- .../10878-blueSalal/00-firstScript.sql | 495 +++++++++++++++++- 1 file changed, 494 insertions(+), 1 deletion(-) diff --git a/db/versions/10878-blueSalal/00-firstScript.sql b/db/versions/10878-blueSalal/00-firstScript.sql index 1c1894c0e..7ef168c6b 100644 --- a/db/versions/10878-blueSalal/00-firstScript.sql +++ b/db/versions/10878-blueSalal/00-firstScript.sql @@ -1,4 +1,497 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplier_statement`( + vSupplierFk INT, + vCurrencyFk INT, + vCompanyFk INT, + vOrderBy VARCHAR(15), + vIsConciliated BOOL +) +BEGIN +/** + * Crea un estado de cuenta de proveedores calculando + * los saldos en euros y en la moneda especificada. + * + * @param vSupplierFk Id del proveedor + * @param vCurrencyFk Id de la moneda + * @param vCompanyFk Id de la empresa + * @param vOrderBy Criterio de ordenación + * @param vIsConciliated Indica si está conciliado o no + * @return tmp.supplierStatement + */ + SET @euroBalance:= 0; + SET @currencyBalance:= 0; + + CREATE OR REPLACE TEMPORARY TABLE tmp.supplierStatement + ENGINE = MEMORY + SELECT *, + @euroBalance:= ROUND( + @euroBalance + IFNULL(paymentEuros, 0) - + IFNULL(invoiceEuros, 0), 2 + ) euroBalance, + @currencyBalance:= ROUND( + @currencyBalance + IFNULL(paymentCurrency, 0) - + IFNULL(invoiceCurrency, 0), 2 + ) currencyBalance + FROM ( + SELECT * FROM + ( + SELECT NULL bankFk, + ii.companyFk, + ii.serial, + ii.id, + CASE + WHEN vOrderBy = 'issued' THEN ii.issued + WHEN vOrderBy = 'bookEntried' THEN ii.bookEntried + WHEN vOrderBy = 'booked' THEN ii.booked + WHEN vOrderBy = 'dueDate' THEN iid.dueDated + END dated, + CONCAT('S/Fra ', ii.supplierRef) sref, + IF(ii.currencyFk > 1, + ROUND(SUM(iid.foreignValue) / SUM(iid.amount), 3), + NULL + ) changeValue, + CAST(SUM(iid.amount) AS DECIMAL(10,2)) invoiceEuros, + CAST(SUM(iid.foreignValue) AS DECIMAL(10,2)) invoiceCurrency, + NULL paymentEuros, + NULL paymentCurrency, + ii.currencyFk, + ii.isBooked, + c.code, + 'invoiceIn' statementType + FROM invoiceIn ii + JOIN invoiceInDueDay iid ON iid.invoiceInFk = ii.id + JOIN currency c ON c.id = ii.currencyFk + WHERE ii.issued > '2014-12-31' + AND ii.supplierFk = vSupplierFk + AND vCurrencyFk IN (ii.currencyFk, 0) + AND vCompanyFk IN (ii.companyFk, 0) + AND (vIsConciliated = ii.isBooked OR NOT vIsConciliated) + GROUP BY iid.id + UNION ALL + SELECT p.bankFk, + p.companyFk, + NULL, + p.id, + CASE + WHEN vOrderBy = 'issued' THEN p.received + WHEN vOrderBy = 'bookEntried' THEN p.received + WHEN vOrderBy = 'booked' THEN p.received + WHEN vOrderBy = 'dueDate' THEN p.dueDated + END, + CONCAT(IFNULL(pm.name, ''), + IF(pn.concept <> '', + CONCAT(' : ', pn.concept), + '') + ), + IF(p.currencyFk > 1, p.divisa / p.amount, NULL), + NULL, + NULL, + p.amount, + p.divisa, + p.currencyFk, + p.isConciliated, + c.code, + 'payment' + FROM payment p + LEFT JOIN currency c ON c.id = p.currencyFk + LEFT JOIN bank b ON b.id = p.bankFk + LEFT JOIN payMethod pm ON pm.id = p.payMethodFk + LEFT JOIN promissoryNote pn ON pn.paymentFk = p.id + WHERE p.received > '2014-12-31' + AND p.supplierFk = vSupplierFk + AND vCurrencyFk IN (p.currencyFk, 0) + AND vCompanyFk IN (p.companyFk, 0) + AND (vIsConciliated = p.isConciliated OR NOT vIsConciliated) + UNION ALL + SELECT NULL, + companyFk, + NULL, + se.id, + CASE + WHEN vOrderBy = 'issued' THEN se.dated + WHEN vOrderBy = 'bookEntried' THEN se.dated + WHEN vOrderBy = 'booked' THEN se.dated + WHEN vOrderBy = 'dueDate' THEN se.dueDated + END, + se.description, + 1, + amount, + NULL, + NULL, + NULL, + currencyFk, + isConciliated, + c.`code`, + 'expense' + FROM supplierExpense se + JOIN currency c ON c.id = se.currencyFk + WHERE se.supplierFk = vSupplierFk + AND vCurrencyFk IN (se.currencyFk,0) + AND vCompanyFk IN (se.companyFk,0) + AND (vIsConciliated = se.isConciliated OR NOT vIsConciliated) + ) sub + ORDER BY (dated IS NULL AND NOT isBooked), + dated, + IF(vOrderBy = 'dueDate', id, NULL) + LIMIT 10000000000000000000 + ) t; +END$$ +DELIMITER ; + GRANT EXECUTE ON PROCEDURE vn.supplier_statement TO administrative, buyer, hrBoss; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`XDiario_reconciliation`() +BEGIN +/** + * Realiza la conciliación diaria de los asientos contables, + * identificando y notificando los asientos descuadrados + * y ajustando los saldos en caso necesario. + */ + INSERT INTO mail (receiver, subject, body) + SELECT 'cau@verdnatura.es', + 'Asientos descuadrados', + GROUP_CONCAT(CONCAT(' Asiento: ', ASIEN, ' - Importe:', recon) SEPARATOR ' | \n') + FROM ( + SELECT ASIEN, + SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) recon + FROM XDiario + WHERE NOT enlazado + GROUP BY ASIEN + HAVING ABS(SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0))) > 0.01 + ) sub + HAVING COUNT(*); + + UPDATE XDiario xd + JOIN ( + SELECT xd.id, SUBCTA, recon + FROM XDiario xd + JOIN ( + SELECT ASIEN, + SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) recon + FROM XDiario + WHERE NOT enlazado + GROUP BY ASIEN + HAVING recon + ) sub ON sub.ASIEN = xd.ASIEN + WHERE xd.SUBCTA > '5999999999' + GROUP BY xd.ASIEN + ) sub ON sub.id = xd.id + SET xd.Eurohaber = IF(IFNULL(xd.Eurohaber, 0) = 0, xd.Eurohaber, xd.Eurohaber + sub.recon), + xd.Eurodebe = IF(IFNULL(xd.Eurodebe, 0) = 0, xd.Eurodebe, xd.Eurodebe - sub.recon); +END$$ +DELIMITER ; + GRANT EXECUTE ON PROCEDURE vn.XDiario_reconciliation TO adminBoss; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_detail`() +BEGIN +/** + * Devuelve los detalles de los vuelos que tienen + * un almacén de salida en Ecuador o Colombia. + */ + DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL 12 WEEK; + SELECT IFNULL(CONCAT(" ", entryFk), travelFk) travelAndEntry, + sub.* + FROM ( + SELECT tr.id travelFk, + NULL entryFk, + TRUE isTravel, + am.name agency, + tr.ref, + tr.shipped, + wOut.name originBoxes, + tr.landed, + wIn.name destination, + SUM(b.stickers) stickers, + NULL evaNotes, + tr.kg, + CAST(SUM(b.weight * b.stickers) AS INT) loadedkg, + CAST( + SUM(vc.aerealVolumetricDensity * + b.stickers * + IF(p.volume, + p.volume, + p.width * p.depth * p.height + ) / 1000000 + ) AS INT + ) volumeKg, + NULL loadPriority, + NULL invoiceAmount, + s.nickname freighter, + NULL reference + FROM travel tr + LEFT JOIN supplier s ON s.id = tr.cargoSupplierFk + LEFT JOIN entry e ON e.travelFk = tr.id + LEFT JOIN buy b ON b.entryFk = e.id + LEFT JOIN packaging p ON p.id = b.packagingFk + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN itemType it ON it.id = i.typeFk + JOIN warehouse wIn ON wIn.id = tr.warehouseInFk + JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk + JOIN agencyMode am ON am.id = tr.agencyModeFk + JOIN volumeConfig vc + WHERE tr.landed >= vDateFrom + AND (wOut.code = "col" OR wOut.code = "ecu") + GROUP BY tr.id + UNION ALL + SELECT e.travelFk, + e.id, + FALSE, + s.name, + e.invoiceNumber, + tr.shipped, + wOut.name, + tr.landed, + wIn.name, + SUM(b.stickers), + e.evaNotes, + NULL, + CAST(SUM(b.weight * b.stickers) AS INT), + CAST( + SUM(vc.aerealVolumetricDensity * + b.stickers * + IF(p.volume, + p.volume, + p.width * p.depth * p.height + ) / 1000000 + ) AS INT + ), + loadPriority, + e.invoiceAmount, + s2.nickname, + e.reference + FROM entry e + JOIN buy b ON b.entryFk = e.id + JOIN packaging p ON p.id = b.packagingFk + JOIN item i ON i.id = b.itemFk + JOIN itemType it ON it.id = i.typeFk + JOIN supplier s ON s.id = e.supplierFk + JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN supplier s2 ON s2.id = tr.cargoSupplierFk + JOIN warehouse wIn ON wIn.id = tr.warehouseInFk + JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk + JOIN volumeConfig vc + WHERE tr.landed >= vDateFrom + AND (wOut.code = "col" OR wOut.code = "ecu") + GROUP BY e.id + ) sub + ORDER BY landed ASC, + shipped ASC, + travelFk, + isTravel DESC, + (loadPriority > 0) DESC, + loadPriority, + agency, + evaNotes; +END$$ +DELIMITER ; + GRANT EXECUTE ON PROCEDURE vn.travel_detail TO buyer; -GRANT EXECUTE ON PROCEDURE vn.entry_getTransfer TO claimManager, buyer; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_getTransfer`( + vSelf INT +) +BEGIN +/** + * Gestiona el traslado de productos a partir de una entrada específica. + * + * @param vSelf Id de entrada + */ + DECLARE vDateShipped DATE; + DECLARE vDateLanded DATE; + DECLARE vWarehouseIn INT; + DECLARE vWarehouseOut INT; + DECLARE vCalcVisible INT; + DECLARE vInventoryDate DATE DEFAULT vn.getInventoryDate(); + + SELECT shipped, landed, warehouseInFk, warehouseOutFk + INTO vDateShipped, vDateLanded, vWarehouseIn, vWarehouseOut + FROM vn.travel t + JOIN vn.entry e ON e.travelFk = t.id + WHERE e.id = vSelf; + + CALL vn.rate_getPrices(vDateShipped, vWarehouseIn); + + -- Traslado en almacen origen + CREATE OR REPLACE TEMPORARY TABLE tBuy + (PRIMARY KEY (itemFk), INDEX(buyFk)) + ENGINE = MEMORY + SELECT * + FROM ( + SELECT b.itemFk, b.id buyFk + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vInventoryDate AND vDateShipped + AND NOT b.isIgnored + AND b.price2 >= 0 + ORDER BY (vWarehouseOut = t.warehouseInFk) DESC, t.landed DESC + LIMIT 10000000000000000000 + ) sub + GROUP BY itemFk; + + IF vDateShipped >= util.VN_CURDATE() THEN + CALL `cache`.visible_refresh(vCalcVisible, TRUE, vWarehouseOut); + + CREATE OR REPLACE TEMPORARY TABLE tItem ( + `itemFk` int(10) unsigned NOT NULL, + `visible` int(11) NOT NULL DEFAULT 0, + `available` int(11) NOT NULL DEFAULT 0, + `visibleLanding` int(11) NOT NULL DEFAULT 0, + `availableLanding` int(11) NOT NULL DEFAULT 0, + UNIQUE INDEX i USING HASH (itemFk) + ) ENGINE = MEMORY; + + INSERT INTO tItem(itemFk, visible) + SELECT item_id itemFk, visible + FROM `cache`.visible + WHERE calc_id = vCalcVisible + AND visible; + + CALL `cache`.visible_refresh(vCalcVisible, TRUE, vWarehouseIn); + + INSERT INTO tItem(itemFk, visibleLanding) + SELECT item_id, `visible` + FROM `cache`.`visible` v + WHERE v.calc_id = vCalcVisible + AND v.`visible` + ON DUPLICATE KEY UPDATE visibleLanding = v.`visible`; + + CALL vn2008.availableTraslate(vWarehouseOut, vDateShipped, NULL); + + INSERT INTO tItem(itemFk, available) + SELECT a.item_id, a.available + FROM vn2008.availableTraslate a + WHERE a.available + ON DUPLICATE KEY UPDATE available = a.available; + + CALL vn2008.availableTraslate(vWarehouseIn, vDateLanded, vWarehouseOut); + + INSERT INTO tItem(itemFk, availableLanding) + SELECT a.item_id, a.available + FROM vn2008.availableTraslate a + WHERE a.available + ON DUPLICATE KEY UPDATE availableLanding = a.available; + ELSE + CALL vn.item_getStock(vWarehouseOut, vDateShipped, NULL); + + CREATE OR REPLACE TEMPORARY TABLE tItem + (UNIQUE INDEX i USING HASH (itemFk)) + ENGINE = MEMORY + SELECT itemFk, + `visible`, + available, + 0 visibleLanding, + 0 availableLanding + FROM tmp.itemList; + END IF; + + CALL vn.buyUltimateFromInterval(vWarehouseIn,vInventoryDate, vDateLanded); + + CREATE OR REPLACE TEMPORARY TABLE tTransfer + ENGINE = MEMORY + SELECT it.categoryFk, + i.typeFk, + i.id itemFk, + i.name item, + i.`size`, + i.category, + i.inkFk, + o.code originCode, + b2.quantity, + i.stems, + CAST(ti.visible AS DECIMAL(10,0)) vis1, + CAST(ti.available AS DECIMAL(10,0)) ava1, + CAST(ti.visibleLanding AS DECIMAL(10,0)) vis2, + CAST(ti.availableLanding AS DECIMAL(10,0)) ava, + COALESCE(b2.`grouping`, b.`grouping`) `grouping`, + COALESCE(b2.packing, b.packing) packing, + COALESCE(b3.groupingMode, b2.groupingMode, b.groupingMode) package, + IFNULL(p.name, s.nickname) productor, + b.packagingFk, + b2.id buyFk, + b2.stickers, + b.ektFk, + it.workerFk, + pa.volume, + IFNULL(pa.width, 0) width, + IFNULL(pa.`depth`, 0) `depth`, + IFNULL(pa.height, 0) height, + IFNULL(b.buyingValue, 0) buyingValue, + IFNULL(b.comissionValue, 0) comissionValue, + IFNULL(b.freightValue, 0) freightValue, + am.m3, + e.commission, + pa.isPackageReturnable, + IFNULL(pa2.value, pa.value) `value`, + r.rate3, + r.rate2, + it.promo, + b.`grouping` groupingOrigin, + b.packing packingOrigin, + b.id buyFkOrigin, + pa.returnCost, + b.weight + FROM vn.item i + JOIN tItem ti ON ti.itemFk = i.id + LEFT JOIN vn.producer p ON p.id = i.producerFk + LEFT JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN vn.origin o ON o.id = i.originFk + LEFT JOIN tBuy lb ON lb.itemFk = i.id + LEFT JOIN vn.buy b ON b.id = lb.buyFk + LEFT JOIN vn.packaging pa ON pa.id = b.packagingFk + LEFT JOIN vn.entry e2 ON e2.id = b.entryFk + LEFT JOIN vn.supplier s ON s.id = e2.supplierFk + LEFT JOIN vn.entry e ON e.id = vSelf + LEFT JOIN vn.travel tr ON tr.id = e.travelFk + LEFT JOIN vn.agencyMode am ON am.id = tr.agencyModeFk + LEFT JOIN vn.buy b2 ON b2.itemFk = i.id + AND b2.entryFk = vSelf + LEFT JOIN vn.packaging pa2 ON pa2.id = b.packagingFk + LEFT JOIN tmp.rate r ON TRUE + LEFT JOIN tmp.buyUltimateFromInterval bufi ON bufi.itemFk = i.id + LEFT JOIN vn.buy b3 ON b3.id = bufi.buyFk + WHERE ic.display + AND NOT e.isRaid + AND (ti.visible != 0 OR ti.available != 0) + ORDER BY i.typeFk, i.name, i.id, i.size, i.category, o.name; + + CREATE INDEX tIndex USING HASH ON tTransfer (itemFk); + + SET @carriage := 0; + SET @comission := 0; + SET @packaging := 0; + SET @rate3 := 0; + SET @cost := 0; + SELECT *, + quantity - MOD(quantity , `grouping`) subQuantity, + MOD(quantity, `grouping`) soll, + ROUND((IF(volume > 0,volume, width * `depth` * IF(height = 0, `size` + 10, height))) / packing, 0) cm3, + buyingValue + comissionValue + freightValue Cost, + @carriage := ROUND((IF(volume > 0, volume, width * `depth` * IF(height = 0, `size` + 10, height))) * m3 / 1000000 / Packing, 3) carriage, + @comission := ROUND((buyingValue + comissionValue + freightValue) * commission / 100, 3) commission, + ROUND(@packaging := (returnCost + IF(isPackageReturnable != 0, 0, value)) / packing, 3) packaging, + @cost := IFNULL((buyingValue + comissionValue + freightValue), 0) + + IFNULL(@packaging, 0) + + IFNULL(@carriage, 0) + + IFNULL(@comission, 0) cost, + @rate3 := ROUND(@cost / ( (100 - rate3 - promo) / 100), 2) rate3, + ROUND(@rate3 * (1 + ((rate2 - rate3)/100)), 2) rate2, + FALSE selected + FROM tTransfer; + + DROP TEMPORARY TABLE IF EXISTS + tTransfer, + tItem, + tBuy, + tmp.buyUltimateFromInterval, + tmp.rate, + tmp.itemList; +END$$ +DELIMITER ; + +GRANT EXECUTE ON PROCEDURE vn.entry_getTransfer TO claimManager, buyer; \ No newline at end of file From b06f80e0913a0cc1545dfa34a673d0df557e8de5 Mon Sep 17 00:00:00 2001 From: ivanm Date: Mon, 12 Feb 2024 08:11:49 +0100 Subject: [PATCH 39/69] refs #6446 Delete function nz from db --- db/routines/bi/functions/nz.sql | 16 ---------------- .../bi/procedures/claim_ratio_routine.sql | 6 +++--- db/routines/vn/functions/nz.sql | 14 -------------- .../vn/procedures/client_checkBalance.sql | 2 +- .../vn/procedures/supplier_checkBalance.sql | 2 +- .../vn/triggers/expedition_beforeInsert.sql | 12 ++++++------ db/routines/vn2008/functions/nz.sql | 14 -------------- 7 files changed, 11 insertions(+), 55 deletions(-) delete mode 100644 db/routines/bi/functions/nz.sql delete mode 100644 db/routines/vn/functions/nz.sql delete mode 100644 db/routines/vn2008/functions/nz.sql diff --git a/db/routines/bi/functions/nz.sql b/db/routines/bi/functions/nz.sql deleted file mode 100644 index 0d047703a..000000000 --- a/db/routines/bi/functions/nz.sql +++ /dev/null @@ -1,16 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `bi`.`nz`(vData DOUBLE) - RETURNS double - DETERMINISTIC -BEGIN -/** - * Devuelve 0, si el parámetro es NULL: - */ - DECLARE vResult DOUBLE; - - SET vResult = IFNULL(vData,0); - - RETURN vResult; - -END$$ -DELIMITER ; diff --git a/db/routines/bi/procedures/claim_ratio_routine.sql b/db/routines/bi/procedures/claim_ratio_routine.sql index 4616bcb9e..e5a5310b4 100644 --- a/db/routines/bi/procedures/claim_ratio_routine.sql +++ b/db/routines/bi/procedures/claim_ratio_routine.sql @@ -130,13 +130,13 @@ BEGIN -- Calculamos el porcentaje del recobro para añadirlo al precio de venta UPDATE bi.claims_ratio cr JOIN ( - SELECT Id_Cliente, nz(SUM(Importe)) AS Greuge + SELECT Id_Cliente, IFNULL(SUM(Importe), 0) AS Greuge FROM vn2008.Greuges WHERE Fecha <= util.VN_CURDATE() GROUP BY Id_Cliente ) g ON g.Id_Cliente = cr.Id_Cliente - SET recobro = GREATEST(0,round(nz(Greuge) / - (nz(Consumo) * vMonthToRefund / 12 ) ,3)); + SET recobro = GREATEST(0,round(IFNULL(Greuge, 0) / + (IFNULL(Consumo, 0) * vMonthToRefund / 12 ) ,3)); -- Protección neonatos UPDATE bi.claims_ratio cr diff --git a/db/routines/vn/functions/nz.sql b/db/routines/vn/functions/nz.sql deleted file mode 100644 index 71c017b78..000000000 --- a/db/routines/vn/functions/nz.sql +++ /dev/null @@ -1,14 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`nz`(vQuantity DOUBLE) - RETURNS double - DETERMINISTIC -BEGIN - - DECLARE vResult DOUBLE; - - SET vResult = IFNULL(vQuantity,0); - - RETURN vResult; - -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/client_checkBalance.sql b/db/routines/vn/procedures/client_checkBalance.sql index ca8792ba4..210fcc00f 100644 --- a/db/routines/vn/procedures/client_checkBalance.sql +++ b/db/routines/vn/procedures/client_checkBalance.sql @@ -48,7 +48,7 @@ BEGIN SELECT lc.companyFk, c.id, 0, - - (NZ(lc.credit) - NZ(lc.debit)) + - (IFNULL(lc.credit, 0) - IFNULL(lc.debit, 0)) FROM tmp.ledgerComparative lc JOIN client c ON c.accountingAccount = lc.account WHERE lc.`date` BETWEEN vDateFrom AND vDateTo diff --git a/db/routines/vn/procedures/supplier_checkBalance.sql b/db/routines/vn/procedures/supplier_checkBalance.sql index 5248b4cec..04c513927 100644 --- a/db/routines/vn/procedures/supplier_checkBalance.sql +++ b/db/routines/vn/procedures/supplier_checkBalance.sql @@ -60,7 +60,7 @@ BEGIN SELECT lc.companyFk, s.id, 0, - - (NZ(lc.debit) - NZ(lc.credit)) + - (IFNULL(lc.debit, 0) - IFNULL(lc.credit, 0)) FROM tmp.ledgerComparative lc JOIN supplier s ON s.account = lc.account WHERE lc.`date` BETWEEN vDateFrom AND vDateTo diff --git a/db/routines/vn/triggers/expedition_beforeInsert.sql b/db/routines/vn/triggers/expedition_beforeInsert.sql index a7fa029b4..685de72cb 100644 --- a/db/routines/vn/triggers/expedition_beforeInsert.sql +++ b/db/routines/vn/triggers/expedition_beforeInsert.sql @@ -4,22 +4,22 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`expedition_beforeInse FOR EACH ROW BEGIN DECLARE intcounter INT; - DECLARE vShipFk INT; + DECLARE vShipFk INT; SET NEW.editorFk = account.myUser_getId(); IF NEW.freightItemFk IS NOT NULL THEN - UPDATE ticket SET packages = nz(packages) + 1 WHERE id = NEW.ticketFk; + UPDATE ticket SET packages = IFNULL(packages, 0) + 1 WHERE id = NEW.ticketFk; SELECT IFNULL(MAX(counter),0) +1 INTO intcounter - FROM expedition e + FROM expedition e INNER JOIN ticket t1 ON e.ticketFk = t1.id - LEFT JOIN ticketState ts ON ts.ticketFk = t1.id + LEFT JOIN ticketState ts ON ts.ticketFk = t1.id INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) - AND t1.warehouseFk = t2.warehouseFk + AND t1.warehouseFk = t2.warehouseFk WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk - AND t1.agencyModeFk = t2.agencyModeFk; + AND t1.agencyModeFk = t2.agencyModeFk; SET NEW.`counter` = intcounter; END IF; diff --git a/db/routines/vn2008/functions/nz.sql b/db/routines/vn2008/functions/nz.sql deleted file mode 100644 index 3ca911052..000000000 --- a/db/routines/vn2008/functions/nz.sql +++ /dev/null @@ -1,14 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn2008`.`nz`(dblCANTIDAD DOUBLE) - RETURNS double - DETERMINISTIC -BEGIN - - DECLARE dblRESULT DOUBLE; - - SET dblRESULT = IFNULL(dblCANTIDAD,0); - - RETURN dblRESULT; - -END$$ -DELIMITER ; From 212bf5893277ef45012cc60034dbf9c5e05a5c82 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 12 Feb 2024 10:08:56 +0100 Subject: [PATCH 40/69] refactor: refs #6501 Minor change --- db/routines/vn/procedures/entry_getTransfer.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/entry_getTransfer.sql b/db/routines/vn/procedures/entry_getTransfer.sql index 2c9fe8577..414f62429 100644 --- a/db/routines/vn/procedures/entry_getTransfer.sql +++ b/db/routines/vn/procedures/entry_getTransfer.sql @@ -179,14 +179,14 @@ BEGIN quantity - MOD(quantity , `grouping`) subQuantity, MOD(quantity, `grouping`) soll, ROUND((IF(volume > 0,volume, width * `depth` * IF(height = 0, `size` + 10, height))) / packing, 0) cm3, - buyingValue + comissionValue + freightValue Cost, + buyingValue + comissionValue + freightValue cost, @carriage := ROUND((IF(volume > 0, volume, width * `depth` * IF(height = 0, `size` + 10, height))) * m3 / 1000000 / Packing, 3) carriage, @comission := ROUND((buyingValue + comissionValue + freightValue) * commission / 100, 3) commission, ROUND(@packaging := (returnCost + IF(isPackageReturnable != 0, 0, value)) / packing, 3) packaging, @cost := IFNULL((buyingValue + comissionValue + freightValue), 0) + IFNULL(@packaging, 0) + IFNULL(@carriage, 0) + - IFNULL(@comission, 0) cost, + IFNULL(@comission, 0) expense, @rate3 := ROUND(@cost / ( (100 - rate3 - promo) / 100), 2) rate3, ROUND(@rate3 * (1 + ((rate2 - rate3)/100)), 2) rate2, FALSE selected From f89ae0aad9f9fe670abea57e9383ea20454a010e Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 12 Feb 2024 10:18:31 +0100 Subject: [PATCH 41/69] refactor: refs #6501 Minor change --- db/routines/vn/procedures/entry_getTransfer.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/entry_getTransfer.sql b/db/routines/vn/procedures/entry_getTransfer.sql index 414f62429..58e22c031 100644 --- a/db/routines/vn/procedures/entry_getTransfer.sql +++ b/db/routines/vn/procedures/entry_getTransfer.sql @@ -114,7 +114,7 @@ BEGIN CAST(ti.visible AS DECIMAL(10,0)) vis1, CAST(ti.available AS DECIMAL(10,0)) ava1, CAST(ti.visibleLanding AS DECIMAL(10,0)) vis2, - CAST(ti.availableLanding AS DECIMAL(10,0)) ava, + CAST(ti.availableLanding AS DECIMAL(10,0)) ava2, COALESCE(b2.`grouping`, b.`grouping`) `grouping`, COALESCE(b2.packing, b.packing) packing, COALESCE(b3.groupingMode, b2.groupingMode, b.groupingMode) package, From 23bf9b2750d8b4cb1f5e4ffbe6f7662e112ffe4e Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 12 Feb 2024 10:28:25 +0100 Subject: [PATCH 42/69] refactor: refs #6501 Minor change --- db/routines/vn/procedures/entry_getTransfer.sql | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/entry_getTransfer.sql b/db/routines/vn/procedures/entry_getTransfer.sql index 58e22c031..426619463 100644 --- a/db/routines/vn/procedures/entry_getTransfer.sql +++ b/db/routines/vn/procedures/entry_getTransfer.sql @@ -101,7 +101,8 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE tTransfer ENGINE = MEMORY - SELECT it.categoryFk, + SELECT it.code `type`, + it.categoryFk, i.typeFk, i.id itemFk, i.name item, From 4b5802202ddb0b20a2dc93f4b3bfc8769a864849 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 12 Feb 2024 10:36:09 +0100 Subject: [PATCH 43/69] refactor: refs #6501 Minor change --- .../vn/procedures/entry_getTransfer.sql | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/db/routines/vn/procedures/entry_getTransfer.sql b/db/routines/vn/procedures/entry_getTransfer.sql index 426619463..10f14c681 100644 --- a/db/routines/vn/procedures/entry_getTransfer.sql +++ b/db/routines/vn/procedures/entry_getTransfer.sql @@ -120,6 +120,7 @@ BEGIN COALESCE(b2.packing, b.packing) packing, COALESCE(b3.groupingMode, b2.groupingMode, b.groupingMode) package, IFNULL(p.name, s.nickname) productor, + TRUE tinta, b.packagingFk, b2.id buyFk, b2.stickers, @@ -136,8 +137,8 @@ BEGIN e.commission, pa.isPackageReturnable, IFNULL(pa2.value, pa.value) `value`, - r.rate3, - r.rate2, + r.r3, + r.r2, it.promo, b.`grouping` groupingOrigin, b.packing packingOrigin, @@ -179,11 +180,17 @@ BEGIN SELECT *, quantity - MOD(quantity , `grouping`) subQuantity, MOD(quantity, `grouping`) soll, - ROUND((IF(volume > 0,volume, width * `depth` * IF(height = 0, `size` + 10, height))) / packing, 0) cm3, + ROUND((IF(volume > 0,volume, width * `depth` * + IF(height = 0, `size` + 10, height))) / + packing, 0) cm3, buyingValue + comissionValue + freightValue cost, - @carriage := ROUND((IF(volume > 0, volume, width * `depth` * IF(height = 0, `size` + 10, height))) * m3 / 1000000 / Packing, 3) carriage, - @comission := ROUND((buyingValue + comissionValue + freightValue) * commission / 100, 3) commission, - ROUND(@packaging := (returnCost + IF(isPackageReturnable != 0, 0, value)) / packing, 3) packaging, + @carriage := ROUND((IF(volume > 0, volume, width * `depth` * + IF(height = 0, `size` + 10, height))) * + m3 / 1000000 / Packing, 3) carriage, + @comission := ROUND((buyingValue + comissionValue + freightValue) * + commission / 100, 3) commission, + ROUND(@packaging := (returnCost + IF(isPackageReturnable != 0, 0, value)) + / packing, 3) packaging, @cost := IFNULL((buyingValue + comissionValue + freightValue), 0) + IFNULL(@packaging, 0) + IFNULL(@carriage, 0) + From fb763816245eb281f6025004242e2baf3150d9ef Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 12 Feb 2024 11:02:24 +0100 Subject: [PATCH 44/69] refactor: refs #6501 Minor change --- db/routines/vn/procedures/entry_getTransfer.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/entry_getTransfer.sql b/db/routines/vn/procedures/entry_getTransfer.sql index 10f14c681..986612a26 100644 --- a/db/routines/vn/procedures/entry_getTransfer.sql +++ b/db/routines/vn/procedures/entry_getTransfer.sql @@ -137,8 +137,8 @@ BEGIN e.commission, pa.isPackageReturnable, IFNULL(pa2.value, pa.value) `value`, - r.r3, - r.r2, + r.rate3 r3, + r.rate2 r2, it.promo, b.`grouping` groupingOrigin, b.packing packingOrigin, From 8a7441be57a1acef083159f6bbe7dc5491117db8 Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 12 Feb 2024 11:14:17 +0100 Subject: [PATCH 45/69] feat: refs #6371 --- db/routines/vn2008/procedures/clean.sql | 7 ------- db/versions/10876-goldenRoebelini/00-firstScript.sql | 4 ---- 2 files changed, 11 deletions(-) diff --git a/db/routines/vn2008/procedures/clean.sql b/db/routines/vn2008/procedures/clean.sql index 8c36cced8..0ff185c46 100644 --- a/db/routines/vn2008/procedures/clean.sql +++ b/db/routines/vn2008/procedures/clean.sql @@ -56,13 +56,6 @@ proc: BEGIN JOIN travel t ON t.id = e.travel_id WHERE t.landing <= vDate; - DELETE co - FROM Compres_ok co JOIN Compres c ON c.Id_Compra = co.Id_Compra - JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN travel t ON t.id = e.travel_id - WHERE t.landing <= vDate; - DELETE FROM scan WHERE odbc_date < vDate6 AND id <> 1; - IF v_full THEN CREATE OR REPLACE TEMPORARY TABLE tTicketDelete SELECT DISTINCT tl.originFk ticketFk diff --git a/db/versions/10876-goldenRoebelini/00-firstScript.sql b/db/versions/10876-goldenRoebelini/00-firstScript.sql index 361f3c7c8..c089f8950 100644 --- a/db/versions/10876-goldenRoebelini/00-firstScript.sql +++ b/db/versions/10876-goldenRoebelini/00-firstScript.sql @@ -1,7 +1,3 @@ -ALTER TABLE IF EXISTS vn2008.Compres_ok__ RENAME vn2008.Compres_ok; -ALTER TABLE IF EXISTS vn2008.Compres_ok COMMENT=''; - - -- Para la tabla Monitoring ALTER TABLE IF EXISTS vn2008.Monitoring RENAME vn2008.Monitoring__; ALTER TABLE IF EXISTS vn2008.Monitoring__ COMMENT='refs #6371 deprecated 2024-01-11'; From 534b5bb05a021488fac049abc411590caebc6976 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 12 Feb 2024 11:26:00 +0100 Subject: [PATCH 46/69] fix: refs #6106 where filter --- modules/route/back/methods/route/getTickets.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/modules/route/back/methods/route/getTickets.js b/modules/route/back/methods/route/getTickets.js index d1ebf9ee7..59ba389ed 100644 --- a/modules/route/back/methods/route/getTickets.js +++ b/modules/route/back/methods/route/getTickets.js @@ -1,5 +1,5 @@ -const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; +const {ParameterizedSQL} = require('loopback-connector'); module.exports = Self => { Self.remoteMethod('getTickets', { @@ -83,13 +83,15 @@ module.exports = Self => { const where = filter.where; where['r.id'] = filter.id; + where.and = [{or: [ + {'t.packages': {gt: 0}}, + {and: [{'ot.code': 'delivery'}, {'tob.observationTypeFk': {neq: null}}]} + ]}]; stmt.merge(conn.makeWhere(filter.where)); stmt.merge(conn.makeGroupBy('t.id')); stmt.merge(conn.makeOrderBy(filter.order)); - const tickets = await conn.executeStmt(stmt, myOptions); - - return tickets; + return conn.executeStmt(stmt, myOptions); }; }; From ee67a02bf0cad8944b0fb82c2a1ae3f3948b3f77 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 12 Feb 2024 11:28:54 +0100 Subject: [PATCH 47/69] refactor: refs #6501 Minor change --- db/routines/vn/procedures/entry_getTransfer.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/entry_getTransfer.sql b/db/routines/vn/procedures/entry_getTransfer.sql index 986612a26..2939fbf9e 100644 --- a/db/routines/vn/procedures/entry_getTransfer.sql +++ b/db/routines/vn/procedures/entry_getTransfer.sql @@ -195,8 +195,8 @@ BEGIN IFNULL(@packaging, 0) + IFNULL(@carriage, 0) + IFNULL(@comission, 0) expense, - @rate3 := ROUND(@cost / ( (100 - rate3 - promo) / 100), 2) rate3, - ROUND(@rate3 * (1 + ((rate2 - rate3)/100)), 2) rate2, + @rate3 := ROUND(@cost / ( (100 - r3 - promo) / 100), 2) rate3, + ROUND(@rate3 * (1 + ((rate2 - r3)/100)), 2) rate2, FALSE selected FROM tTransfer; From 96d6637a3f689d59f460a22a14cfb9f525d0f8a8 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 12 Feb 2024 11:32:07 +0100 Subject: [PATCH 48/69] refactor: refs #6501 Minor change --- db/routines/vn/procedures/entry_getTransfer.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/entry_getTransfer.sql b/db/routines/vn/procedures/entry_getTransfer.sql index 2939fbf9e..f2cec654e 100644 --- a/db/routines/vn/procedures/entry_getTransfer.sql +++ b/db/routines/vn/procedures/entry_getTransfer.sql @@ -196,7 +196,7 @@ BEGIN IFNULL(@carriage, 0) + IFNULL(@comission, 0) expense, @rate3 := ROUND(@cost / ( (100 - r3 - promo) / 100), 2) rate3, - ROUND(@rate3 * (1 + ((rate2 - r3)/100)), 2) rate2, + ROUND(@rate3 * (1 + ((r2 - r3)/100)), 2) rate2, FALSE selected FROM tTransfer; From fb84fe4b973be62faf9cb6079c17e825d9ca1bb1 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 13 Feb 2024 07:16:32 +0100 Subject: [PATCH 49/69] refactor: refs #6501 Requested changes --- .../{XDiario_reconciliation.sql => XDiario_verify.sql} | 4 ++-- db/routines/vn/procedures/entry_getTransfer.sql | 6 +++--- .../{travel_detail.sql => travel_detailAmerica.sql} | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) rename db/routines/vn/procedures/{XDiario_reconciliation.sql => XDiario_verify.sql} (93%) rename db/routines/vn/procedures/{travel_detail.sql => travel_detailAmerica.sql} (98%) diff --git a/db/routines/vn/procedures/XDiario_reconciliation.sql b/db/routines/vn/procedures/XDiario_verify.sql similarity index 93% rename from db/routines/vn/procedures/XDiario_reconciliation.sql rename to db/routines/vn/procedures/XDiario_verify.sql index c4724849d..0f898638a 100644 --- a/db/routines/vn/procedures/XDiario_reconciliation.sql +++ b/db/routines/vn/procedures/XDiario_verify.sql @@ -1,8 +1,8 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`XDiario_reconciliation`() +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`XDiario_verify`() BEGIN /** - * Realiza la conciliación diaria de los asientos contables, + * Realiza la verificación diaria de los asientos contables, * identificando y notificando los asientos descuadrados * y ajustando los saldos en caso necesario. */ diff --git a/db/routines/vn/procedures/entry_getTransfer.sql b/db/routines/vn/procedures/entry_getTransfer.sql index f2cec654e..151bebd4d 100644 --- a/db/routines/vn/procedures/entry_getTransfer.sql +++ b/db/routines/vn/procedures/entry_getTransfer.sql @@ -4,7 +4,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_getTransfer`( ) BEGIN /** - * Gestiona el traslado de productos a partir de una entrada específica. + * Retorna los artículos trasladables a partir de una entrada. * * @param vSelf Id de entrada */ @@ -167,7 +167,7 @@ BEGIN LEFT JOIN vn.buy b3 ON b3.id = bufi.buyFk WHERE ic.display AND NOT e.isRaid - AND (ti.visible != 0 OR ti.available != 0) + AND (ti.visible OR ti.available) ORDER BY i.typeFk, i.name, i.id, i.size, i.category, o.name; CREATE INDEX tIndex USING HASH ON tTransfer (itemFk); @@ -189,7 +189,7 @@ BEGIN m3 / 1000000 / Packing, 3) carriage, @comission := ROUND((buyingValue + comissionValue + freightValue) * commission / 100, 3) commission, - ROUND(@packaging := (returnCost + IF(isPackageReturnable != 0, 0, value)) + ROUND(@packaging := (returnCost + IF(isPackageReturnable, 0, value)) / packing, 3) packaging, @cost := IFNULL((buyingValue + comissionValue + freightValue), 0) + IFNULL(@packaging, 0) + diff --git a/db/routines/vn/procedures/travel_detail.sql b/db/routines/vn/procedures/travel_detailAmerica.sql similarity index 98% rename from db/routines/vn/procedures/travel_detail.sql rename to db/routines/vn/procedures/travel_detailAmerica.sql index d805f0ca9..ecd24cd5c 100644 --- a/db/routines/vn/procedures/travel_detail.sql +++ b/db/routines/vn/procedures/travel_detailAmerica.sql @@ -1,5 +1,5 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_detail`() +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_detailAmerica`() BEGIN /** * Devuelve los detalles de los vuelos que tienen From a897a05e8b6a931b0288a67bf61964738cc170ca Mon Sep 17 00:00:00 2001 From: josepd Date: Tue, 13 Feb 2024 07:52:09 +0100 Subject: [PATCH 50/69] feat: refs#6685RestoreViewCredit --- db/routines/vn2008/views/credit.sql | 9 +++++++++ db/versions/10883-azureRuscus/00-firstScript.sql | 1 + 2 files changed, 10 insertions(+) create mode 100644 db/routines/vn2008/views/credit.sql create mode 100644 db/versions/10883-azureRuscus/00-firstScript.sql diff --git a/db/routines/vn2008/views/credit.sql b/db/routines/vn2008/views/credit.sql new file mode 100644 index 000000000..4bd3cef39 --- /dev/null +++ b/db/routines/vn2008/views/credit.sql @@ -0,0 +1,9 @@ +CREATE OR REPLACE DEFINER=`root`@`localhost` + SQL SECURITY DEFINER + VIEW `vn2008`.`credit` +AS SELECT `c`.`id` AS `id`, + `c`.`clientFk` AS `Id_Cliente`, + `c`.`workerFk` AS `Id_Trabajador`, + `c`.`amount` AS `amount`, + `c`.`created` AS `odbc_date` +FROM `vn`.`clientCredit` `c` \ No newline at end of file diff --git a/db/versions/10883-azureRuscus/00-firstScript.sql b/db/versions/10883-azureRuscus/00-firstScript.sql new file mode 100644 index 000000000..8e046d95b --- /dev/null +++ b/db/versions/10883-azureRuscus/00-firstScript.sql @@ -0,0 +1 @@ +GRANT SELECT ON TABLE vn2008.credit TO financialBoss; \ No newline at end of file From 3b35e4dae89622a01a9fbd27426ae0f4f3389f02 Mon Sep 17 00:00:00 2001 From: josepd Date: Tue, 13 Feb 2024 08:57:49 +0100 Subject: [PATCH 51/69] refs#6685 RestoreViewCredit --- db/versions/10883-azureRuscus/00-firstScript.sql | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/db/versions/10883-azureRuscus/00-firstScript.sql b/db/versions/10883-azureRuscus/00-firstScript.sql index 8e046d95b..89fdbf781 100644 --- a/db/versions/10883-azureRuscus/00-firstScript.sql +++ b/db/versions/10883-azureRuscus/00-firstScript.sql @@ -1 +1,6 @@ +CREATE OR REPLACE DEFINER=`root`@`localhost` + SQL SECURITY DEFINER + VIEW `vn2008`.`credit`AS +SELECT 1; + GRANT SELECT ON TABLE vn2008.credit TO financialBoss; \ No newline at end of file From e08fb3d229485a9d0453a7e4e35cbe0a66ab44c4 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 13 Feb 2024 08:59:58 +0100 Subject: [PATCH 52/69] fix: refs #6184 Minor change --- loopback/locale/es.json | 5 +++-- modules/ticket/back/methods/ticket/saveSign.js | 11 ++++------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index b48772f0d..b0eb59cd5 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -339,8 +339,9 @@ "No tickets to invoice": "No hay tickets para facturar", "This ticket already has a cmr saved": "Este ticket ya tiene un cmr guardado", "Name should be uppercase": "El nombre debe ir en mayúscula", - "Bank entity must be specified": "La entidad bancaria es obligatoria", + "Bank entity must be specified": "La entidad bancaria es obligatoria", "An email is necessary": "Es necesario un email", "You cannot update these fields": "No puedes actualizar estos campos", - "CountryFK cannot be empty": "El país no puede estar vacío" + "CountryFK cannot be empty": "El país no puede estar vacío", + "Cmr file does not exist": "El archivo del cmr no existe" } \ No newline at end of file diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 0fcd41102..3718dfcda 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -34,8 +34,6 @@ module.exports = Self => { const myOptions = {userId: ctx.req.accessToken.userId}; let tx; let ticket; - let dms; - let gestDocCreated; if (typeof options == 'object') Object.assign(myOptions, options); @@ -86,8 +84,8 @@ module.exports = Self => { contentType: 'image/png', hasFile: true }; - dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); - gestDocCreated = true; + const dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); + await models.TicketDms.create({ticketFk: ticket.id, dmsFk: dms[0].id}, myOptions); } try { @@ -137,9 +135,8 @@ module.exports = Self => { throw new UserError('Ticket is already signed'); if (location) await setLocation(ticketId); - if (!await hasSignDms(ticketId) && !gestDocCreated) + if (!await hasSignDms(ticketId)) await createGestDoc(ticketId); - await models.TicketDms.create({ticketFk: ticketId, dmsFk: dms[0].id}, myOptions); await ticket.updateAttribute('isSigned', true, myOptions); const deliveryState = await models.State.findOne({ @@ -160,7 +157,7 @@ module.exports = Self => { await models.Route.cmrEmail(ctx, externalTickets); return; } catch (e) { - if (tx) await tx.rollback(); + if (tx && tx.isActive()) await tx.rollback(); throw e; } }; From 41db1c924f3c3875c27f08f3993c66ff4c79235d Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 13 Feb 2024 09:20:21 +0100 Subject: [PATCH 53/69] refactor: refs #6781 Deleted timeControlDevice --- db/versions/10884-maroonGerbera/00-firstScript.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 db/versions/10884-maroonGerbera/00-firstScript.sql diff --git a/db/versions/10884-maroonGerbera/00-firstScript.sql b/db/versions/10884-maroonGerbera/00-firstScript.sql new file mode 100644 index 000000000..704342a7c --- /dev/null +++ b/db/versions/10884-maroonGerbera/00-firstScript.sql @@ -0,0 +1 @@ +DROP TABLE vn.timeControlDevice; From 6116ada156dd68e2b5e1e94fef8c8811c8fc9e7b Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 13 Feb 2024 09:35:39 +0100 Subject: [PATCH 54/69] fix: refs #6813 remove inserts --- db/routines/vn2008/procedures/recobro_credito.sql | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/db/routines/vn2008/procedures/recobro_credito.sql b/db/routines/vn2008/procedures/recobro_credito.sql index ca5304b6c..0db9d6e70 100644 --- a/db/routines/vn2008/procedures/recobro_credito.sql +++ b/db/routines/vn2008/procedures/recobro_credito.sql @@ -8,16 +8,10 @@ BEGIN END; START TRANSACTION; - INSERT INTO vn.clientCredit(clientFk, amount) - SELECT c.id, 0 - FROM vn.`client` c - JOIN vn.payMethod pm ON pm.id = c.payMethodFk - WHERE c.credit <> 0 AND pm.`code` = 'card'; - UPDATE vn.`client` c - JOIN vn.payMethod pm ON pm.id = c.payMethodFk + JOIN vn.payMethod pm ON pm.id = c.payMethodFk SET credit = 0 - WHERE pm.`code` = 'card'; + WHERE pm.`code` = 'card'; DROP TEMPORARY TABLE IF EXISTS clientes_credit; CREATE TEMPORARY TABLE clientes_credit @@ -44,10 +38,6 @@ BEGIN UPDATE Clientes JOIN clientes_credit USING(Id_Cliente) SET Clientes.Credito = newCredit; - - INSERT INTO credit(Id_Cliente, amount, Id_Trabajador) - SELECT Id_Cliente, newCredit, NULL - FROM clientes_credit; DROP TEMPORARY TABLE clientes_credit; COMMIT; From 744171dd4c33af9e2bfd94e5d9cf06628471b99e Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 13 Feb 2024 09:41:26 +0100 Subject: [PATCH 55/69] fix: refs #6184 Requested changes --- modules/ticket/back/methods/ticket/saveSign.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 3718dfcda..9c6e8181a 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -34,6 +34,7 @@ module.exports = Self => { const myOptions = {userId: ctx.req.accessToken.userId}; let tx; let ticket; + let externalTickets = []; if (typeof options == 'object') Object.assign(myOptions, options); @@ -89,7 +90,6 @@ module.exports = Self => { } try { - let externalTickets = []; for (const ticketId of tickets) { ticket = await models.Ticket.findById(ticketId, { include: [{ @@ -154,11 +154,10 @@ module.exports = Self => { } } if (tx) await tx.commit(); - await models.Route.cmrEmail(ctx, externalTickets); - return; } catch (e) { - if (tx && tx.isActive()) await tx.rollback(); + if (tx) await tx.rollback(); throw e; } + await models.Route.cmrEmail(ctx, externalTickets); }; }; From 4f9b46346f38ee77b8328333fc4f84a5867df44e Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 13 Feb 2024 09:49:33 +0100 Subject: [PATCH 56/69] fix: refs#6706 back tests spec timeout reduced --- back/tests.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/back/tests.js b/back/tests.js index 6c1b366e2..50698eb92 100644 --- a/back/tests.js +++ b/back/tests.js @@ -17,7 +17,8 @@ const opts = getopts(process.argv.slice(2), { let server; const PARALLEL = false; -const TIMEOUT = 900000; +const SETUP_TIMEOUT = 15 * 60 * 1000; +const SPEC_TIMEOUT = 30 * 1000; process.on('exit', teardown); process.on('uncaughtException', onError); @@ -74,9 +75,9 @@ async function test() { let runner; const config = { globalSetup: setup, - globalSetupTimeout: TIMEOUT, + globalSetupTimeout: SETUP_TIMEOUT, globalTeardown: teardown, - globalTeardownTimeout: TIMEOUT, + globalTeardownTimeout: SETUP_TIMEOUT, spec_dir: '.', spec_files: [ 'back/**/*[sS]pec.js', @@ -111,7 +112,7 @@ async function test() { runner.addReporter(new JunitReporter.JUnitXmlReporter()); } if (opts.ci) - runner.jasmine.DEFAULT_TIMEOUT_INTERVAL = TIMEOUT; + runner.jasmine.DEFAULT_TIMEOUT_INTERVAL = SPEC_TIMEOUT; // runner.loadConfigFile('back/jasmine.json'); runner.loadConfig(config); From 185cc4f17fdf3209ded8586c954b110dc2b87fab Mon Sep 17 00:00:00 2001 From: Jbreso Date: Tue, 13 Feb 2024 09:50:07 +0100 Subject: [PATCH 57/69] feat: refs #6693 revisar triggers --- ...udgetNotes_BeforeInsert.sql => budgetNotes_beforeInsert.sql} | 2 +- ...lientCredit_AfterInsert.sql => clientCredit_afterInsert.sql} | 0 .../triggers/{client_AfterInsert.sql => client_afterInsert.sql} | 0 ...ionState_AfterInsert.sql => expeditionState_afterInsert.sql} | 0 ...nState_BeforeInsert.sql => expeditionState_beforeInsert.sql} | 0 5 files changed, 1 insertion(+), 1 deletion(-) rename db/routines/vn/triggers/{budgetNotes_BeforeInsert.sql => budgetNotes_beforeInsert.sql} (91%) rename db/routines/vn/triggers/{clientCredit_AfterInsert.sql => clientCredit_afterInsert.sql} (100%) rename db/routines/vn/triggers/{client_AfterInsert.sql => client_afterInsert.sql} (100%) rename db/routines/vn/triggers/{expeditionState_AfterInsert.sql => expeditionState_afterInsert.sql} (100%) rename db/routines/vn/triggers/{expeditionState_BeforeInsert.sql => expeditionState_beforeInsert.sql} (100%) diff --git a/db/routines/vn/triggers/budgetNotes_BeforeInsert.sql b/db/routines/vn/triggers/budgetNotes_beforeInsert.sql similarity index 91% rename from db/routines/vn/triggers/budgetNotes_BeforeInsert.sql rename to db/routines/vn/triggers/budgetNotes_beforeInsert.sql index f75b7a01e..6ea5ad5eb 100644 --- a/db/routines/vn/triggers/budgetNotes_BeforeInsert.sql +++ b/db/routines/vn/triggers/budgetNotes_beforeInsert.sql @@ -1,5 +1,5 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`budgetNotes_BeforeInsert` +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`budgetNotes_beforeInsert` BEFORE INSERT ON `budgetNotes` FOR EACH ROW BEGIN diff --git a/db/routines/vn/triggers/clientCredit_AfterInsert.sql b/db/routines/vn/triggers/clientCredit_afterInsert.sql similarity index 100% rename from db/routines/vn/triggers/clientCredit_AfterInsert.sql rename to db/routines/vn/triggers/clientCredit_afterInsert.sql diff --git a/db/routines/vn/triggers/client_AfterInsert.sql b/db/routines/vn/triggers/client_afterInsert.sql similarity index 100% rename from db/routines/vn/triggers/client_AfterInsert.sql rename to db/routines/vn/triggers/client_afterInsert.sql diff --git a/db/routines/vn/triggers/expeditionState_AfterInsert.sql b/db/routines/vn/triggers/expeditionState_afterInsert.sql similarity index 100% rename from db/routines/vn/triggers/expeditionState_AfterInsert.sql rename to db/routines/vn/triggers/expeditionState_afterInsert.sql diff --git a/db/routines/vn/triggers/expeditionState_BeforeInsert.sql b/db/routines/vn/triggers/expeditionState_beforeInsert.sql similarity index 100% rename from db/routines/vn/triggers/expeditionState_BeforeInsert.sql rename to db/routines/vn/triggers/expeditionState_beforeInsert.sql From db2919b48208cd634ab8cea4d7d9f567fca32354 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 13 Feb 2024 11:05:21 +0100 Subject: [PATCH 58/69] fix: refs #6813 procedure --- db/routines/vn2008/procedures/recobro_credito.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn2008/procedures/recobro_credito.sql b/db/routines/vn2008/procedures/recobro_credito.sql index 0db9d6e70..3c8b6fbfe 100644 --- a/db/routines/vn2008/procedures/recobro_credito.sql +++ b/db/routines/vn2008/procedures/recobro_credito.sql @@ -8,10 +8,10 @@ BEGIN END; START TRANSACTION; - UPDATE vn.`client` c + UPDATE vn.client c JOIN vn.payMethod pm ON pm.id = c.payMethodFk SET credit = 0 - WHERE pm.`code` = 'card'; + WHERE pm.code = 'card'; DROP TEMPORARY TABLE IF EXISTS clientes_credit; CREATE TEMPORARY TABLE clientes_credit From ed67b1168f71f457c0210a5c13b5fa8a5b3267a6 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 13 Feb 2024 11:14:35 +0100 Subject: [PATCH 59/69] refactor: refs #6501 Requested changes --- ...ilAmerica.sql => continent_getTravelDetail.sql} | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) rename db/routines/vn/procedures/{travel_detailAmerica.sql => continent_getTravelDetail.sql} (87%) diff --git a/db/routines/vn/procedures/travel_detailAmerica.sql b/db/routines/vn/procedures/continent_getTravelDetail.sql similarity index 87% rename from db/routines/vn/procedures/travel_detailAmerica.sql rename to db/routines/vn/procedures/continent_getTravelDetail.sql index ecd24cd5c..8049f9e65 100644 --- a/db/routines/vn/procedures/travel_detailAmerica.sql +++ b/db/routines/vn/procedures/continent_getTravelDetail.sql @@ -1,9 +1,13 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_detailAmerica`() +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`continent_getTravelDetail`( + vSelf INT +) BEGIN /** * Devuelve los detalles de los vuelos que tienen - * un almacén de salida en Ecuador o Colombia. + * un almacén de salida de un continente. + * + * @param vSelf Id de continente */ DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL 12 WEEK; SELECT IFNULL(CONCAT(" ", entryFk), travelFk) travelAndEntry, @@ -44,10 +48,11 @@ BEGIN LEFT JOIN itemType it ON it.id = i.typeFk JOIN warehouse wIn ON wIn.id = tr.warehouseInFk JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk + JOIN country co ON co.id = wOut.countryFk JOIN agencyMode am ON am.id = tr.agencyModeFk JOIN volumeConfig vc WHERE tr.landed >= vDateFrom - AND (wOut.code = "col" OR wOut.code = "ecu") + AND co.continentFk = vSelf GROUP BY tr.id UNION ALL SELECT e.travelFk, @@ -86,9 +91,10 @@ BEGIN LEFT JOIN supplier s2 ON s2.id = tr.cargoSupplierFk JOIN warehouse wIn ON wIn.id = tr.warehouseInFk JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk + JOIN country co ON co.id = wOut.countryFk JOIN volumeConfig vc WHERE tr.landed >= vDateFrom - AND (wOut.code = "col" OR wOut.code = "ecu") + AND co.continentFk = vSelf GROUP BY e.id ) sub ORDER BY landed ASC, From 579f2abe5bd48bd05f5d25b7a9b66daf45038278 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 13 Feb 2024 11:16:00 +0100 Subject: [PATCH 60/69] fix: refs #6813 remove quotation marks --- db/routines/vn2008/procedures/recobro_credito.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn2008/procedures/recobro_credito.sql b/db/routines/vn2008/procedures/recobro_credito.sql index 3c8b6fbfe..0db9d6e70 100644 --- a/db/routines/vn2008/procedures/recobro_credito.sql +++ b/db/routines/vn2008/procedures/recobro_credito.sql @@ -8,10 +8,10 @@ BEGIN END; START TRANSACTION; - UPDATE vn.client c + UPDATE vn.`client` c JOIN vn.payMethod pm ON pm.id = c.payMethodFk SET credit = 0 - WHERE pm.code = 'card'; + WHERE pm.`code` = 'card'; DROP TEMPORARY TABLE IF EXISTS clientes_credit; CREATE TEMPORARY TABLE clientes_credit From 999d9a0f9c3599436039772f64ca747b9bcadbb2 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 13 Feb 2024 16:21:01 +0100 Subject: [PATCH 61/69] fix: refs#6706 E2E show parameter fix --- e2e/{helpers => }/tests.js | 7 ++++--- package.json | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) rename e2e/{helpers => }/tests.js (94%) diff --git a/e2e/helpers/tests.js b/e2e/tests.js similarity index 94% rename from e2e/helpers/tests.js rename to e2e/tests.js index 7dd299e0b..829056f4c 100644 --- a/e2e/helpers/tests.js +++ b/e2e/tests.js @@ -10,7 +10,7 @@ const Myt = require('@verdnatura/myt/myt'); const Run = require('@verdnatura/myt/myt-run'); const axios = require('axios'); -const e2eConfig = require('./config.js'); +const e2eConfig = require('./helpers/config.js'); const log = require('fancy-log'); process.on('warning', warning => { @@ -23,11 +23,12 @@ async function test() { const opts = getopts(process.argv.slice(2), { boolean: ['show'] }); - process.env.E2E_SHOW = opts.show; + if (opts.show) + process.env.E2E_SHOW = true; console.log('Building and running DB container.'); const myt = new Myt(); - await myt.init({workspace: path.join(__dirname, '../..')}); + await myt.init({workspace: path.join(__dirname, '..')}); await myt.run(Run); await myt.deinit(); diff --git a/package.json b/package.json index 9ae8b276b..a9a355cf6 100644 --- a/package.json +++ b/package.json @@ -108,7 +108,7 @@ "dbtest": "nodemon -q db/tests.js -w db/tests", "test:back": "nodemon -q back/tests.js --config back/nodemonConfig.json", "test:back:ci": "node back/tests.js --ci --junit --network jenkins", - "test:e2e": "node e2e/helpers/tests.js", + "test:e2e": "node e2e/tests.js", "test:front": "jest --watch", "back": "nodemon --inspect -w modules ./node_modules/gulp/bin/gulp.js back", "lint": "eslint ./ --cache --ignore-pattern .gitignore", From 27d7a114e6e9596232d84ab8774e4d30e3033ba8 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 13 Feb 2024 17:16:10 +0100 Subject: [PATCH 62/69] fix: refs#6706 package.json dbtest script removed --- package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/package.json b/package.json index a9a355cf6..dc2e25166 100644 --- a/package.json +++ b/package.json @@ -105,7 +105,6 @@ "yaml-loader": "^0.5.0" }, "scripts": { - "dbtest": "nodemon -q db/tests.js -w db/tests", "test:back": "nodemon -q back/tests.js --config back/nodemonConfig.json", "test:back:ci": "node back/tests.js --ci --junit --network jenkins", "test:e2e": "node e2e/tests.js", From 19bbb4a4bf06db9c52dcae984719dd1707be86c4 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 13 Feb 2024 17:20:04 +0100 Subject: [PATCH 63/69] fix: refs#6706 package.json deprecated scripts removed --- Jenkinsfile | 2 +- package.json | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 2c04bcf16..d508da8bf 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -103,7 +103,7 @@ pipeline { NODE_ENV = '' } steps { - sh 'npm run test:back:ci' + sh 'node back/tests.js --ci --junit --network jenkins' } post { always { diff --git a/package.json b/package.json index dc2e25166..5970e68fb 100644 --- a/package.json +++ b/package.json @@ -106,12 +106,10 @@ }, "scripts": { "test:back": "nodemon -q back/tests.js --config back/nodemonConfig.json", - "test:back:ci": "node back/tests.js --ci --junit --network jenkins", "test:e2e": "node e2e/tests.js", "test:front": "jest --watch", "back": "nodemon --inspect -w modules ./node_modules/gulp/bin/gulp.js back", - "lint": "eslint ./ --cache --ignore-pattern .gitignore", - "docker": "docker build --progress=plain -t salix-db ./db" + "lint": "eslint ./ --cache --ignore-pattern .gitignore" }, "jest": { "projects": [ From c2dadc09a22de4c648806f890f65ed5a875bb4e6 Mon Sep 17 00:00:00 2001 From: Jbreso Date: Wed, 14 Feb 2024 07:36:38 +0100 Subject: [PATCH 64/69] feat: refs #6693 comprobar triggers --- ...rojectNotes_BeforeInsert.sql => projectNotes_beforeInsert.sql} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename db/routines/vn/triggers/{projectNotes_BeforeInsert.sql => projectNotes_beforeInsert.sql} (100%) diff --git a/db/routines/vn/triggers/projectNotes_BeforeInsert.sql b/db/routines/vn/triggers/projectNotes_beforeInsert.sql similarity index 100% rename from db/routines/vn/triggers/projectNotes_BeforeInsert.sql rename to db/routines/vn/triggers/projectNotes_beforeInsert.sql From 874f77649806f1d79a3a883be8ec4a70d6befaf4 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 14 Feb 2024 11:05:16 +0100 Subject: [PATCH 65/69] refactor: refs #6501 Requested changes --- .../vn/procedures/{XDiario_verify.sql => XDiario_check.sql} | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename db/routines/vn/procedures/{XDiario_verify.sql => XDiario_check.sql} (94%) diff --git a/db/routines/vn/procedures/XDiario_verify.sql b/db/routines/vn/procedures/XDiario_check.sql similarity index 94% rename from db/routines/vn/procedures/XDiario_verify.sql rename to db/routines/vn/procedures/XDiario_check.sql index 0f898638a..0fb1c410d 100644 --- a/db/routines/vn/procedures/XDiario_verify.sql +++ b/db/routines/vn/procedures/XDiario_check.sql @@ -1,8 +1,8 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`XDiario_verify`() +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`XDiario_check`() BEGIN /** - * Realiza la verificación diaria de los asientos contables, + * Realiza la revisión diaria de los asientos contables, * identificando y notificando los asientos descuadrados * y ajustando los saldos en caso necesario. */ From b64637254b267cccbc624c62106232bb016947e1 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 14 Feb 2024 11:16:52 +0100 Subject: [PATCH 66/69] refactor: refs #6501 Requested changes --- ...velDetail.sql => travel_getDetailFromContinent.sql} | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) rename db/routines/vn/procedures/{continent_getTravelDetail.sql => travel_getDetailFromContinent.sql} (91%) diff --git a/db/routines/vn/procedures/continent_getTravelDetail.sql b/db/routines/vn/procedures/travel_getDetailFromContinent.sql similarity index 91% rename from db/routines/vn/procedures/continent_getTravelDetail.sql rename to db/routines/vn/procedures/travel_getDetailFromContinent.sql index 8049f9e65..e81e648b3 100644 --- a/db/routines/vn/procedures/continent_getTravelDetail.sql +++ b/db/routines/vn/procedures/travel_getDetailFromContinent.sql @@ -1,13 +1,13 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`continent_getTravelDetail`( - vSelf INT +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_getDetailFromContinent`( + vContinentFk INT ) BEGIN /** * Devuelve los detalles de los vuelos que tienen * un almacén de salida de un continente. * - * @param vSelf Id de continente + * @param vContinentFk Id de continente */ DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL 12 WEEK; SELECT IFNULL(CONCAT(" ", entryFk), travelFk) travelAndEntry, @@ -52,7 +52,7 @@ BEGIN JOIN agencyMode am ON am.id = tr.agencyModeFk JOIN volumeConfig vc WHERE tr.landed >= vDateFrom - AND co.continentFk = vSelf + AND co.continentFk = vContinentFk GROUP BY tr.id UNION ALL SELECT e.travelFk, @@ -94,7 +94,7 @@ BEGIN JOIN country co ON co.id = wOut.countryFk JOIN volumeConfig vc WHERE tr.landed >= vDateFrom - AND co.continentFk = vSelf + AND co.continentFk = vContinentFk GROUP BY e.id ) sub ORDER BY landed ASC, From b46087b75c6eeaa16870968c557312f77f70811e Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 14 Feb 2024 11:21:22 +0100 Subject: [PATCH 67/69] refactor: refs #6501 Requested changes --- .../10878-blueSalal/00-firstScript.sql | 482 +----------------- 1 file changed, 10 insertions(+), 472 deletions(-) diff --git a/db/versions/10878-blueSalal/00-firstScript.sql b/db/versions/10878-blueSalal/00-firstScript.sql index 7ef168c6b..64506fa61 100644 --- a/db/versions/10878-blueSalal/00-firstScript.sql +++ b/db/versions/10878-blueSalal/00-firstScript.sql @@ -1,496 +1,34 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplier_statement`( - vSupplierFk INT, - vCurrencyFk INT, - vCompanyFk INT, - vOrderBy VARCHAR(15), - vIsConciliated BOOL -) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplier_statement`() BEGIN -/** - * Crea un estado de cuenta de proveedores calculando - * los saldos en euros y en la moneda especificada. - * - * @param vSupplierFk Id del proveedor - * @param vCurrencyFk Id de la moneda - * @param vCompanyFk Id de la empresa - * @param vOrderBy Criterio de ordenación - * @param vIsConciliated Indica si está conciliado o no - * @return tmp.supplierStatement - */ - SET @euroBalance:= 0; - SET @currencyBalance:= 0; - - CREATE OR REPLACE TEMPORARY TABLE tmp.supplierStatement - ENGINE = MEMORY - SELECT *, - @euroBalance:= ROUND( - @euroBalance + IFNULL(paymentEuros, 0) - - IFNULL(invoiceEuros, 0), 2 - ) euroBalance, - @currencyBalance:= ROUND( - @currencyBalance + IFNULL(paymentCurrency, 0) - - IFNULL(invoiceCurrency, 0), 2 - ) currencyBalance - FROM ( - SELECT * FROM - ( - SELECT NULL bankFk, - ii.companyFk, - ii.serial, - ii.id, - CASE - WHEN vOrderBy = 'issued' THEN ii.issued - WHEN vOrderBy = 'bookEntried' THEN ii.bookEntried - WHEN vOrderBy = 'booked' THEN ii.booked - WHEN vOrderBy = 'dueDate' THEN iid.dueDated - END dated, - CONCAT('S/Fra ', ii.supplierRef) sref, - IF(ii.currencyFk > 1, - ROUND(SUM(iid.foreignValue) / SUM(iid.amount), 3), - NULL - ) changeValue, - CAST(SUM(iid.amount) AS DECIMAL(10,2)) invoiceEuros, - CAST(SUM(iid.foreignValue) AS DECIMAL(10,2)) invoiceCurrency, - NULL paymentEuros, - NULL paymentCurrency, - ii.currencyFk, - ii.isBooked, - c.code, - 'invoiceIn' statementType - FROM invoiceIn ii - JOIN invoiceInDueDay iid ON iid.invoiceInFk = ii.id - JOIN currency c ON c.id = ii.currencyFk - WHERE ii.issued > '2014-12-31' - AND ii.supplierFk = vSupplierFk - AND vCurrencyFk IN (ii.currencyFk, 0) - AND vCompanyFk IN (ii.companyFk, 0) - AND (vIsConciliated = ii.isBooked OR NOT vIsConciliated) - GROUP BY iid.id - UNION ALL - SELECT p.bankFk, - p.companyFk, - NULL, - p.id, - CASE - WHEN vOrderBy = 'issued' THEN p.received - WHEN vOrderBy = 'bookEntried' THEN p.received - WHEN vOrderBy = 'booked' THEN p.received - WHEN vOrderBy = 'dueDate' THEN p.dueDated - END, - CONCAT(IFNULL(pm.name, ''), - IF(pn.concept <> '', - CONCAT(' : ', pn.concept), - '') - ), - IF(p.currencyFk > 1, p.divisa / p.amount, NULL), - NULL, - NULL, - p.amount, - p.divisa, - p.currencyFk, - p.isConciliated, - c.code, - 'payment' - FROM payment p - LEFT JOIN currency c ON c.id = p.currencyFk - LEFT JOIN bank b ON b.id = p.bankFk - LEFT JOIN payMethod pm ON pm.id = p.payMethodFk - LEFT JOIN promissoryNote pn ON pn.paymentFk = p.id - WHERE p.received > '2014-12-31' - AND p.supplierFk = vSupplierFk - AND vCurrencyFk IN (p.currencyFk, 0) - AND vCompanyFk IN (p.companyFk, 0) - AND (vIsConciliated = p.isConciliated OR NOT vIsConciliated) - UNION ALL - SELECT NULL, - companyFk, - NULL, - se.id, - CASE - WHEN vOrderBy = 'issued' THEN se.dated - WHEN vOrderBy = 'bookEntried' THEN se.dated - WHEN vOrderBy = 'booked' THEN se.dated - WHEN vOrderBy = 'dueDate' THEN se.dueDated - END, - se.description, - 1, - amount, - NULL, - NULL, - NULL, - currencyFk, - isConciliated, - c.`code`, - 'expense' - FROM supplierExpense se - JOIN currency c ON c.id = se.currencyFk - WHERE se.supplierFk = vSupplierFk - AND vCurrencyFk IN (se.currencyFk,0) - AND vCompanyFk IN (se.companyFk,0) - AND (vIsConciliated = se.isConciliated OR NOT vIsConciliated) - ) sub - ORDER BY (dated IS NULL AND NOT isBooked), - dated, - IF(vOrderBy = 'dueDate', id, NULL) - LIMIT 10000000000000000000 - ) t; + SELECT 1; END$$ DELIMITER ; GRANT EXECUTE ON PROCEDURE vn.supplier_statement TO administrative, buyer, hrBoss; DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`XDiario_reconciliation`() +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`XDiario_check`() BEGIN -/** - * Realiza la conciliación diaria de los asientos contables, - * identificando y notificando los asientos descuadrados - * y ajustando los saldos en caso necesario. - */ - INSERT INTO mail (receiver, subject, body) - SELECT 'cau@verdnatura.es', - 'Asientos descuadrados', - GROUP_CONCAT(CONCAT(' Asiento: ', ASIEN, ' - Importe:', recon) SEPARATOR ' | \n') - FROM ( - SELECT ASIEN, - SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) recon - FROM XDiario - WHERE NOT enlazado - GROUP BY ASIEN - HAVING ABS(SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0))) > 0.01 - ) sub - HAVING COUNT(*); - - UPDATE XDiario xd - JOIN ( - SELECT xd.id, SUBCTA, recon - FROM XDiario xd - JOIN ( - SELECT ASIEN, - SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) recon - FROM XDiario - WHERE NOT enlazado - GROUP BY ASIEN - HAVING recon - ) sub ON sub.ASIEN = xd.ASIEN - WHERE xd.SUBCTA > '5999999999' - GROUP BY xd.ASIEN - ) sub ON sub.id = xd.id - SET xd.Eurohaber = IF(IFNULL(xd.Eurohaber, 0) = 0, xd.Eurohaber, xd.Eurohaber + sub.recon), - xd.Eurodebe = IF(IFNULL(xd.Eurodebe, 0) = 0, xd.Eurodebe, xd.Eurodebe - sub.recon); + SELECT 1; END$$ DELIMITER ; -GRANT EXECUTE ON PROCEDURE vn.XDiario_reconciliation TO adminBoss; +GRANT EXECUTE ON PROCEDURE vn.XDiario_check TO adminBoss; DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_detail`() +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_getDetailFromContinent`() BEGIN -/** - * Devuelve los detalles de los vuelos que tienen - * un almacén de salida en Ecuador o Colombia. - */ - DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL 12 WEEK; - SELECT IFNULL(CONCAT(" ", entryFk), travelFk) travelAndEntry, - sub.* - FROM ( - SELECT tr.id travelFk, - NULL entryFk, - TRUE isTravel, - am.name agency, - tr.ref, - tr.shipped, - wOut.name originBoxes, - tr.landed, - wIn.name destination, - SUM(b.stickers) stickers, - NULL evaNotes, - tr.kg, - CAST(SUM(b.weight * b.stickers) AS INT) loadedkg, - CAST( - SUM(vc.aerealVolumetricDensity * - b.stickers * - IF(p.volume, - p.volume, - p.width * p.depth * p.height - ) / 1000000 - ) AS INT - ) volumeKg, - NULL loadPriority, - NULL invoiceAmount, - s.nickname freighter, - NULL reference - FROM travel tr - LEFT JOIN supplier s ON s.id = tr.cargoSupplierFk - LEFT JOIN entry e ON e.travelFk = tr.id - LEFT JOIN buy b ON b.entryFk = e.id - LEFT JOIN packaging p ON p.id = b.packagingFk - LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN itemType it ON it.id = i.typeFk - JOIN warehouse wIn ON wIn.id = tr.warehouseInFk - JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk - JOIN agencyMode am ON am.id = tr.agencyModeFk - JOIN volumeConfig vc - WHERE tr.landed >= vDateFrom - AND (wOut.code = "col" OR wOut.code = "ecu") - GROUP BY tr.id - UNION ALL - SELECT e.travelFk, - e.id, - FALSE, - s.name, - e.invoiceNumber, - tr.shipped, - wOut.name, - tr.landed, - wIn.name, - SUM(b.stickers), - e.evaNotes, - NULL, - CAST(SUM(b.weight * b.stickers) AS INT), - CAST( - SUM(vc.aerealVolumetricDensity * - b.stickers * - IF(p.volume, - p.volume, - p.width * p.depth * p.height - ) / 1000000 - ) AS INT - ), - loadPriority, - e.invoiceAmount, - s2.nickname, - e.reference - FROM entry e - JOIN buy b ON b.entryFk = e.id - JOIN packaging p ON p.id = b.packagingFk - JOIN item i ON i.id = b.itemFk - JOIN itemType it ON it.id = i.typeFk - JOIN supplier s ON s.id = e.supplierFk - JOIN travel tr ON tr.id = e.travelFk - LEFT JOIN supplier s2 ON s2.id = tr.cargoSupplierFk - JOIN warehouse wIn ON wIn.id = tr.warehouseInFk - JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk - JOIN volumeConfig vc - WHERE tr.landed >= vDateFrom - AND (wOut.code = "col" OR wOut.code = "ecu") - GROUP BY e.id - ) sub - ORDER BY landed ASC, - shipped ASC, - travelFk, - isTravel DESC, - (loadPriority > 0) DESC, - loadPriority, - agency, - evaNotes; + SELECT 1; END$$ DELIMITER ; -GRANT EXECUTE ON PROCEDURE vn.travel_detail TO buyer; +GRANT EXECUTE ON PROCEDURE vn.travel_getDetailFromContinent TO buyer; DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_getTransfer`( - vSelf INT -) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_getTransfer`() BEGIN -/** - * Gestiona el traslado de productos a partir de una entrada específica. - * - * @param vSelf Id de entrada - */ - DECLARE vDateShipped DATE; - DECLARE vDateLanded DATE; - DECLARE vWarehouseIn INT; - DECLARE vWarehouseOut INT; - DECLARE vCalcVisible INT; - DECLARE vInventoryDate DATE DEFAULT vn.getInventoryDate(); - - SELECT shipped, landed, warehouseInFk, warehouseOutFk - INTO vDateShipped, vDateLanded, vWarehouseIn, vWarehouseOut - FROM vn.travel t - JOIN vn.entry e ON e.travelFk = t.id - WHERE e.id = vSelf; - - CALL vn.rate_getPrices(vDateShipped, vWarehouseIn); - - -- Traslado en almacen origen - CREATE OR REPLACE TEMPORARY TABLE tBuy - (PRIMARY KEY (itemFk), INDEX(buyFk)) - ENGINE = MEMORY - SELECT * - FROM ( - SELECT b.itemFk, b.id buyFk - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed BETWEEN vInventoryDate AND vDateShipped - AND NOT b.isIgnored - AND b.price2 >= 0 - ORDER BY (vWarehouseOut = t.warehouseInFk) DESC, t.landed DESC - LIMIT 10000000000000000000 - ) sub - GROUP BY itemFk; - - IF vDateShipped >= util.VN_CURDATE() THEN - CALL `cache`.visible_refresh(vCalcVisible, TRUE, vWarehouseOut); - - CREATE OR REPLACE TEMPORARY TABLE tItem ( - `itemFk` int(10) unsigned NOT NULL, - `visible` int(11) NOT NULL DEFAULT 0, - `available` int(11) NOT NULL DEFAULT 0, - `visibleLanding` int(11) NOT NULL DEFAULT 0, - `availableLanding` int(11) NOT NULL DEFAULT 0, - UNIQUE INDEX i USING HASH (itemFk) - ) ENGINE = MEMORY; - - INSERT INTO tItem(itemFk, visible) - SELECT item_id itemFk, visible - FROM `cache`.visible - WHERE calc_id = vCalcVisible - AND visible; - - CALL `cache`.visible_refresh(vCalcVisible, TRUE, vWarehouseIn); - - INSERT INTO tItem(itemFk, visibleLanding) - SELECT item_id, `visible` - FROM `cache`.`visible` v - WHERE v.calc_id = vCalcVisible - AND v.`visible` - ON DUPLICATE KEY UPDATE visibleLanding = v.`visible`; - - CALL vn2008.availableTraslate(vWarehouseOut, vDateShipped, NULL); - - INSERT INTO tItem(itemFk, available) - SELECT a.item_id, a.available - FROM vn2008.availableTraslate a - WHERE a.available - ON DUPLICATE KEY UPDATE available = a.available; - - CALL vn2008.availableTraslate(vWarehouseIn, vDateLanded, vWarehouseOut); - - INSERT INTO tItem(itemFk, availableLanding) - SELECT a.item_id, a.available - FROM vn2008.availableTraslate a - WHERE a.available - ON DUPLICATE KEY UPDATE availableLanding = a.available; - ELSE - CALL vn.item_getStock(vWarehouseOut, vDateShipped, NULL); - - CREATE OR REPLACE TEMPORARY TABLE tItem - (UNIQUE INDEX i USING HASH (itemFk)) - ENGINE = MEMORY - SELECT itemFk, - `visible`, - available, - 0 visibleLanding, - 0 availableLanding - FROM tmp.itemList; - END IF; - - CALL vn.buyUltimateFromInterval(vWarehouseIn,vInventoryDate, vDateLanded); - - CREATE OR REPLACE TEMPORARY TABLE tTransfer - ENGINE = MEMORY - SELECT it.categoryFk, - i.typeFk, - i.id itemFk, - i.name item, - i.`size`, - i.category, - i.inkFk, - o.code originCode, - b2.quantity, - i.stems, - CAST(ti.visible AS DECIMAL(10,0)) vis1, - CAST(ti.available AS DECIMAL(10,0)) ava1, - CAST(ti.visibleLanding AS DECIMAL(10,0)) vis2, - CAST(ti.availableLanding AS DECIMAL(10,0)) ava, - COALESCE(b2.`grouping`, b.`grouping`) `grouping`, - COALESCE(b2.packing, b.packing) packing, - COALESCE(b3.groupingMode, b2.groupingMode, b.groupingMode) package, - IFNULL(p.name, s.nickname) productor, - b.packagingFk, - b2.id buyFk, - b2.stickers, - b.ektFk, - it.workerFk, - pa.volume, - IFNULL(pa.width, 0) width, - IFNULL(pa.`depth`, 0) `depth`, - IFNULL(pa.height, 0) height, - IFNULL(b.buyingValue, 0) buyingValue, - IFNULL(b.comissionValue, 0) comissionValue, - IFNULL(b.freightValue, 0) freightValue, - am.m3, - e.commission, - pa.isPackageReturnable, - IFNULL(pa2.value, pa.value) `value`, - r.rate3, - r.rate2, - it.promo, - b.`grouping` groupingOrigin, - b.packing packingOrigin, - b.id buyFkOrigin, - pa.returnCost, - b.weight - FROM vn.item i - JOIN tItem ti ON ti.itemFk = i.id - LEFT JOIN vn.producer p ON p.id = i.producerFk - LEFT JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN vn.origin o ON o.id = i.originFk - LEFT JOIN tBuy lb ON lb.itemFk = i.id - LEFT JOIN vn.buy b ON b.id = lb.buyFk - LEFT JOIN vn.packaging pa ON pa.id = b.packagingFk - LEFT JOIN vn.entry e2 ON e2.id = b.entryFk - LEFT JOIN vn.supplier s ON s.id = e2.supplierFk - LEFT JOIN vn.entry e ON e.id = vSelf - LEFT JOIN vn.travel tr ON tr.id = e.travelFk - LEFT JOIN vn.agencyMode am ON am.id = tr.agencyModeFk - LEFT JOIN vn.buy b2 ON b2.itemFk = i.id - AND b2.entryFk = vSelf - LEFT JOIN vn.packaging pa2 ON pa2.id = b.packagingFk - LEFT JOIN tmp.rate r ON TRUE - LEFT JOIN tmp.buyUltimateFromInterval bufi ON bufi.itemFk = i.id - LEFT JOIN vn.buy b3 ON b3.id = bufi.buyFk - WHERE ic.display - AND NOT e.isRaid - AND (ti.visible != 0 OR ti.available != 0) - ORDER BY i.typeFk, i.name, i.id, i.size, i.category, o.name; - - CREATE INDEX tIndex USING HASH ON tTransfer (itemFk); - - SET @carriage := 0; - SET @comission := 0; - SET @packaging := 0; - SET @rate3 := 0; - SET @cost := 0; - SELECT *, - quantity - MOD(quantity , `grouping`) subQuantity, - MOD(quantity, `grouping`) soll, - ROUND((IF(volume > 0,volume, width * `depth` * IF(height = 0, `size` + 10, height))) / packing, 0) cm3, - buyingValue + comissionValue + freightValue Cost, - @carriage := ROUND((IF(volume > 0, volume, width * `depth` * IF(height = 0, `size` + 10, height))) * m3 / 1000000 / Packing, 3) carriage, - @comission := ROUND((buyingValue + comissionValue + freightValue) * commission / 100, 3) commission, - ROUND(@packaging := (returnCost + IF(isPackageReturnable != 0, 0, value)) / packing, 3) packaging, - @cost := IFNULL((buyingValue + comissionValue + freightValue), 0) + - IFNULL(@packaging, 0) + - IFNULL(@carriage, 0) + - IFNULL(@comission, 0) cost, - @rate3 := ROUND(@cost / ( (100 - rate3 - promo) / 100), 2) rate3, - ROUND(@rate3 * (1 + ((rate2 - rate3)/100)), 2) rate2, - FALSE selected - FROM tTransfer; - - DROP TEMPORARY TABLE IF EXISTS - tTransfer, - tItem, - tBuy, - tmp.buyUltimateFromInterval, - tmp.rate, - tmp.itemList; + SELECT 1; END$$ DELIMITER ; From 18c10e2dd750d9314de6bcf1a11866446868f4b9 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 14 Feb 2024 11:39:15 +0100 Subject: [PATCH 68/69] refactor: refs #6778 Requested changes --- .../bi/procedures/Greuge_Evolution_Add.sql | 2 +- .../bs/procedures/comercialesCompleto.sql | 4 +-- .../bs/procedures/ventas_contables_add.sql | 6 ++-- .../ventas_contables_por_cliente.sql | 6 ++-- db/routines/bs/procedures/vivosMuertos.sql | 28 +++++++++---------- .../vn2008/procedures/CalculoRemesas.sql | 10 +++---- .../procedures/customerDebtEvolution.sql | 8 +++--- 7 files changed, 32 insertions(+), 32 deletions(-) diff --git a/db/routines/bi/procedures/Greuge_Evolution_Add.sql b/db/routines/bi/procedures/Greuge_Evolution_Add.sql index b29be6b49..1d4bf4355 100644 --- a/db/routines/bi/procedures/Greuge_Evolution_Add.sql +++ b/db/routines/bi/procedures/Greuge_Evolution_Add.sql @@ -54,7 +54,7 @@ BEGIN SELECT Id_Cliente, datFEC as Fecha, Greuge, Ventas, 0 FROM ( SELECT clientFk Id_Cliente, sum(amount) as Greuge - FROM vn2.greuge + FROM vn.greuge where shipped <= datFEC group by clientFk ) sub diff --git a/db/routines/bs/procedures/comercialesCompleto.sql b/db/routines/bs/procedures/comercialesCompleto.sql index b0c33e7f0..311b5fe2a 100644 --- a/db/routines/bs/procedures/comercialesCompleto.sql +++ b/db/routines/bs/procedures/comercialesCompleto.sql @@ -99,8 +99,8 @@ BEGIN LEFT JOIN (SELECT c.Id_Cliente, IF(MAX(Fecha) < DATE_FORMAT(TIMESTAMPADD(MONTH, - 1, vDate), '%Y- %m-01'), TRUE, FALSE) muerto - FROM vn.invoiceOut f - JOIN vn2008.Clientes c ON c.Id_cliente = f.clientFk + FROM vn.invoiceOut io + JOIN vn2008.Clientes c ON c.Id_cliente = io.clientFk LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador WHERE (c.Id_Trabajador = vWorker OR tr.boss = vWorker) GROUP BY Id_Cliente) dead ON dead.Id_Cliente = c.Id_Cliente diff --git a/db/routines/bs/procedures/ventas_contables_add.sql b/db/routines/bs/procedures/ventas_contables_add.sql index 6cca2ff7f..9988c8b29 100644 --- a/db/routines/bs/procedures/ventas_contables_add.sql +++ b/db/routines/bs/procedures/ventas_contables_add.sql @@ -23,9 +23,9 @@ BEGIN ENGINE = MEMORY SELECT Id_Ticket FROM vn2008.Tickets t - JOIN vn.invoiceOut f ON f.id = t.Factura - WHERE year(f.issued) = vYear - AND month(f.issued) = vMonth; + JOIN vn.invoiceOut io ON io.id = t.Factura + WHERE year(io.issued) = vYear + AND month(io.issued) = vMonth; INSERT INTO bs.ventas_contables(year , month diff --git a/db/routines/bs/procedures/ventas_contables_por_cliente.sql b/db/routines/bs/procedures/ventas_contables_por_cliente.sql index b5b7a39d5..931653e6e 100644 --- a/db/routines/bs/procedures/ventas_contables_por_cliente.sql +++ b/db/routines/bs/procedures/ventas_contables_por_cliente.sql @@ -13,9 +13,9 @@ BEGIN (PRIMARY KEY (Id_Ticket)) SELECT Id_Ticket FROM vn2008.Tickets t - JOIN vn.invoiceOut f ON f.id = t.Factura - WHERE year(f.issued) = vYear - AND month(f.issued) = vMonth; + JOIN vn.invoiceOut io ON io.id = t.Factura + WHERE year(io.issued) = vYear + AND month(io.issued) = vMonth; SELECT vYear Año, vMonth Mes, diff --git a/db/routines/bs/procedures/vivosMuertos.sql b/db/routines/bs/procedures/vivosMuertos.sql index 9cd0e3605..c07570603 100644 --- a/db/routines/bs/procedures/vivosMuertos.sql +++ b/db/routines/bs/procedures/vivosMuertos.sql @@ -24,20 +24,20 @@ BEGIN WHERE date BETWEEN @datSTART AND @datEND ) tm LEFT JOIN - (SELECT DISTINCT tm.yearMonth, f.clientFk Id_Cliente , 1 as Compra - FROM vn.invoiceOut f - JOIN vn2008.time tm ON tm.date = f.issued - WHERE Fecha BETWEEN @datSTART + (SELECT DISTINCT tm.yearMonth, io.clientFk Id_Cliente , 1 as Compra + FROM vn.invoiceOut io + JOIN vn2008.time tm ON tm.date = io.issued + WHERE io.issued BETWEEN @datSTART AND @datEND) f ON f.yearMonth = tm.yearMonth AND f.Id_Cliente = c.Id_Cliente; UPDATE tmp.VivosMuertos vm JOIN - (SELECT MIN(tm.yearMonth) firstMonth, f.clientFk Id_Cliente - FROM vn.invoiceOut f - JOIN vn2008.time tm ON tm.date = f.issued - WHERE Fecha BETWEEN @datSTART AND @datEND - GROUP BY f.clientFk) fm ON fm.firstMonth = vm.yearMonth + (SELECT MIN(tm.yearMonth) firstMonth, io.clientFk Id_Cliente + FROM vn.invoiceOut io + JOIN vn2008.time tm ON tm.date = io.issued + WHERE io.issued BETWEEN @datSTART AND @datEND + GROUP BY io.clientFk) fm ON fm.firstMonth = vm.yearMonth AND fm.Id_Cliente = vm.Id_Cliente SET Nuevo = 1; @@ -46,11 +46,11 @@ BEGIN UPDATE tmp.VivosMuertos vm JOIN ( - SELECT MAX(tm.yearMonth) firstMonth, f.clientFk Id_Cliente - FROM vn.invoiceOut f - JOIN vn2008.time tm ON tm.date = f.issued - WHERE Fecha BETWEEN @datSTART AND @datEND - GROUP BY f.clientFk) fm ON fm.firstMonth = vm.yearMonth + SELECT MAX(tm.yearMonth) firstMonth, io.clientFk Id_Cliente + FROM vn.invoiceOut io + JOIN vn2008.time tm ON tm.date = io.issued + WHERE io.issued BETWEEN @datSTART AND @datEND + GROUP BY io.clientFk) fm ON fm.firstMonth = vm.yearMonth AND fm.Id_Cliente = vm.Id_Cliente SET Muerto = 1 diff --git a/db/routines/vn2008/procedures/CalculoRemesas.sql b/db/routines/vn2008/procedures/CalculoRemesas.sql index e7d1ae22c..3819130ee 100644 --- a/db/routines/vn2008/procedures/CalculoRemesas.sql +++ b/db/routines/vn2008/procedures/CalculoRemesas.sql @@ -47,13 +47,13 @@ BEGIN UNION ALL - SELECT d.companyFk, f.clientFk Id_Cliente, - f.amount - FROM vn.invoiceOut f - JOIN Clientes c ON c.Id_Cliente = f.clientFk + SELECT d.companyFk, io.clientFk Id_Cliente, - io.amount + FROM vn.invoiceOut io + JOIN Clientes c ON c.Id_Cliente = io.clientFk JOIN pay_met pm on pm.id = pay_met_id - WHERE f.dued > vFechaRemesa + WHERE io.dued > vFechaRemesa AND pay_met_id = 4 AND pm.deudaviva - AND f.amount > 0 + AND io.amount > 0 ) risk ON c.Id_Cliente = risk.clientFk GROUP BY risk.companyFk, Id_Cliente diff --git a/db/routines/vn2008/procedures/customerDebtEvolution.sql b/db/routines/vn2008/procedures/customerDebtEvolution.sql index 20ed75d8f..df857462c 100644 --- a/db/routines/vn2008/procedures/customerDebtEvolution.sql +++ b/db/routines/vn2008/procedures/customerDebtEvolution.sql @@ -18,10 +18,10 @@ SELECT * FROM WHERE Id_Cliente = vCustomer AND Fechacobro >= '2017-01-01' UNION ALL - SELECT vn.getDueDate(f.issued,c.Vencimiento), - Importe - FROM vn.invoiceOut f - JOIN Clientes c ON f.clientFk = c.Id_Cliente - WHERE f.clientFk = vCustomer + SELECT vn.getDueDate(io.issued,c.Vencimiento), - Importe + FROM vn.invoiceOut io + JOIN Clientes c ON io.clientFk = c.Id_Cliente + WHERE io.clientFk = vCustomer AND Fecha >= '2017-01-01' UNION ALL SELECT '2016-12-31', Debt From 35fc8930ced1eafc188e745229d253c92b146bf8 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 14 Feb 2024 12:12:40 +0100 Subject: [PATCH 69/69] fix: refs #6778 Fix and tested --- db/routines/bi/procedures/claim_ratio_routine.sql | 2 +- db/routines/bs/procedures/comercialesCompleto.sql | 2 +- db/routines/vn/functions/isPalletHomogeneus.sql | 2 +- db/routines/vn/procedures/getDayExpeditions.sql | 6 +++--- db/routines/vn/procedures/itemShelvingRadar.sql | 4 ++-- db/routines/vn2008/procedures/CalculoRemesas.sql | 2 +- db/routines/vn2008/procedures/ListaTicketsEncajados.sql | 6 +++--- db/routines/vn2008/procedures/availableTraslate.sql | 2 +- db/routines/vn2008/procedures/customerDebtEvolution.sql | 4 ++-- 9 files changed, 15 insertions(+), 15 deletions(-) diff --git a/db/routines/bi/procedures/claim_ratio_routine.sql b/db/routines/bi/procedures/claim_ratio_routine.sql index 55489b99a..10cb717cf 100644 --- a/db/routines/bi/procedures/claim_ratio_routine.sql +++ b/db/routines/bi/procedures/claim_ratio_routine.sql @@ -75,7 +75,7 @@ BEGIN DELETE g.* FROM vn.greuge g JOIN tmp.ticket_list t ON g.ticketFk = t.Id_Ticket - WHERE t.greugeTypeFk = 2; + WHERE g.greugeTypeFk = 2; INSERT INTO vn.greuge(clientFk, description, amount,shipped, greugeTypeFk, ticketFk) diff --git a/db/routines/bs/procedures/comercialesCompleto.sql b/db/routines/bs/procedures/comercialesCompleto.sql index 311b5fe2a..101173740 100644 --- a/db/routines/bs/procedures/comercialesCompleto.sql +++ b/db/routines/bs/procedures/comercialesCompleto.sql @@ -98,7 +98,7 @@ BEGIN GROUP BY c.Id_Cliente) CmLy ON CmLy.Id_Cliente = c.Id_Cliente LEFT JOIN (SELECT c.Id_Cliente, - IF(MAX(Fecha) < DATE_FORMAT(TIMESTAMPADD(MONTH, - 1, vDate), '%Y- %m-01'), TRUE, FALSE) muerto + IF(MAX(io.issued) < DATE_FORMAT(TIMESTAMPADD(MONTH, - 1, vDate), '%Y- %m-01'), TRUE, FALSE) muerto FROM vn.invoiceOut io JOIN vn2008.Clientes c ON c.Id_cliente = io.clientFk LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador diff --git a/db/routines/vn/functions/isPalletHomogeneus.sql b/db/routines/vn/functions/isPalletHomogeneus.sql index d308e8ed3..b38fdcc5e 100644 --- a/db/routines/vn/functions/isPalletHomogeneus.sql +++ b/db/routines/vn/functions/isPalletHomogeneus.sql @@ -16,7 +16,7 @@ BEGIN FROM ( SELECT DISTINCT t.Id_Ruta FROM vn2008.scan_line sl - JOIN expeditions e ON e.id = sl.code + JOIN expedition e ON e.id = sl.code JOIN vn2008.Tickets t ON t.Id_Ticket = e.ticketFk WHERE sl.scan_id = vScanId AND t.Id_Ruta diff --git a/db/routines/vn/procedures/getDayExpeditions.sql b/db/routines/vn/procedures/getDayExpeditions.sql index 535dfde4a..b708c8b0e 100644 --- a/db/routines/vn/procedures/getDayExpeditions.sql +++ b/db/routines/vn/procedures/getDayExpeditions.sql @@ -7,9 +7,9 @@ BEGIN date_format(e.created,'%Y-%m-%d') as expeditionDate, e.ticketFk, t.routeFk as routeFk - FROM expeditions e - INNER JOIN vn.ticket t ON t.id = e.ticketFk - WHERE DATE(odbc_date) = util.VN_CURDATE(); + FROM expedition e + INNER JOIN ticket t ON t.id = e.ticketFk + WHERE DATE(e.created) = util.VN_CURDATE(); END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/itemShelvingRadar.sql b/db/routines/vn/procedures/itemShelvingRadar.sql index 624451677..c89a190ae 100644 --- a/db/routines/vn/procedures/itemShelvingRadar.sql +++ b/db/routines/vn/procedures/itemShelvingRadar.sql @@ -143,8 +143,8 @@ proc:BEGIN CREATE TEMPORARY TABLE tmp.itemOutTime SELECT *,SUM(amount) quantity FROM - (SELECT item_id itemFk, - amount, + (SELECT io.itemFk, + io.quantity amount, IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours, IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) as minutes FROM itemTicketOut io diff --git a/db/routines/vn2008/procedures/CalculoRemesas.sql b/db/routines/vn2008/procedures/CalculoRemesas.sql index 3819130ee..a4c191a80 100644 --- a/db/routines/vn2008/procedures/CalculoRemesas.sql +++ b/db/routines/vn2008/procedures/CalculoRemesas.sql @@ -47,7 +47,7 @@ BEGIN UNION ALL - SELECT d.companyFk, io.clientFk Id_Cliente, - io.amount + SELECT io.companyFk, io.clientFk Id_Cliente, - io.amount FROM vn.invoiceOut io JOIN Clientes c ON c.Id_Cliente = io.clientFk JOIN pay_met pm on pm.id = pay_met_id diff --git a/db/routines/vn2008/procedures/ListaTicketsEncajados.sql b/db/routines/vn2008/procedures/ListaTicketsEncajados.sql index e0b48bc5e..ce99916ee 100644 --- a/db/routines/vn2008/procedures/ListaTicketsEncajados.sql +++ b/db/routines/vn2008/procedures/ListaTicketsEncajados.sql @@ -13,9 +13,9 @@ SELECT Agencia, FROM Tickets ti INNER JOIN Consignatarios ON ti.Id_Consigna = Consignatarios.Id_consigna INNER JOIN Agencias ON ti.Id_Agencia = Agencias.Id_Agencia - LEFT JOIN (SELECT ticketFk,count(*) AS ncajas FROM vn.expedition WHERE Id_Article=94 GROUP BY ticket_id) sub1 ON ti.Id_Ticket=sub1.ticketFk - LEFT JOIN (SELECT ticketFk,count(*) AS nbultos FROM vn.expedition WHERE Id_Article IS NULL GROUP BY ticket_id) sub2 ON ti.Id_Ticket=sub2.ticketFk - LEFT JOIN (SELECT ticketFk,count(*) AS notros FROM vn.expedition WHERE Id_Article >0 GROUP BY ticket_id) sub3 ON ti.Id_Ticket=sub3.ticketFk + LEFT JOIN (SELECT ticketFk,count(*) AS ncajas FROM vn.expedition WHERE packagingFk=94 GROUP BY ticketFk) sub1 ON ti.Id_Ticket=sub1.ticketFk + LEFT JOIN (SELECT ticketFk,count(*) AS nbultos FROM vn.expedition WHERE packagingFk IS NULL GROUP BY ticketFk) sub2 ON ti.Id_Ticket=sub2.ticketFk + LEFT JOIN (SELECT ticketFk,count(*) AS notros FROM vn.expedition WHERE packagingFk >0 GROUP BY ticketFk) sub3 ON ti.Id_Ticket=sub3.ticketFk INNER JOIN vn.ticketState ts ON ti.Id_ticket = ts.ticketFk WHERE ti.Fecha=util.VN_CURDATE() AND ts.userFk=intId_Trabajador diff --git a/db/routines/vn2008/procedures/availableTraslate.sql b/db/routines/vn2008/procedures/availableTraslate.sql index 4ac5e3209..a3d2c8bea 100644 --- a/db/routines/vn2008/procedures/availableTraslate.sql +++ b/db/routines/vn2008/procedures/availableTraslate.sql @@ -69,7 +69,7 @@ proc: BEGIN ENGINE = MEMORY SELECT i.itemFk, vWarehouseLanding warehouseFk, i.shipped dated, i.quantity FROM vn.itemTicketOut i - JOIN itemRangeLive ir ON ir.itemFK = i.item_id + JOIN itemRangeLive ir ON ir.itemFK = i.itemFk WHERE i.shipped >= vDatedFrom AND (ir.dated IS NULL OR i.shipped <= ir.dated) AND i.warehouseFk = vWarehouseLanding diff --git a/db/routines/vn2008/procedures/customerDebtEvolution.sql b/db/routines/vn2008/procedures/customerDebtEvolution.sql index df857462c..b9763b985 100644 --- a/db/routines/vn2008/procedures/customerDebtEvolution.sql +++ b/db/routines/vn2008/procedures/customerDebtEvolution.sql @@ -18,11 +18,11 @@ SELECT * FROM WHERE Id_Cliente = vCustomer AND Fechacobro >= '2017-01-01' UNION ALL - SELECT vn.getDueDate(io.issued,c.Vencimiento), - Importe + SELECT vn.getDueDate(io.issued,c.Vencimiento), - io.amount FROM vn.invoiceOut io JOIN Clientes c ON io.clientFk = c.Id_Cliente WHERE io.clientFk = vCustomer - AND Fecha >= '2017-01-01' + AND io.issued >= '2017-01-01' UNION ALL SELECT '2016-12-31', Debt FROM bi.customerDebtInventory